label
class label 2
classes | source_code
stringlengths 398
72.9k
|
---|---|
11
| Code Sample 1:
public synchronized String encrypt(String plaintext) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); md.update(plaintext.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { log().error("failed to encrypt the password.", e); throw new RuntimeException("failed to encrypt the password.", e); } catch (UnsupportedEncodingException e) { log().error("failed to encrypt the password.", e); throw new RuntimeException("failed to encrypt the password.", e); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
Code Sample 2:
public boolean verifySignature() { try { byte[] data = readFile(name + ".tmp1.bin"); if (data == null) return false; if (data[data.length - 0x104] != 'N' || data[data.length - 0x103] != 'G' || data[data.length - 0x102] != 'I' || data[data.length - 0x101] != 'S') return false; byte[] signature = new byte[0x100]; byte[] module = new byte[data.length - 0x104]; System.arraycopy(data, data.length - 0x100, signature, 0, 0x100); System.arraycopy(data, 0, module, 0, data.length - 0x104); BigIntegerEx power = new BigIntegerEx(BigIntegerEx.LITTLE_ENDIAN, new byte[] { 0x01, 0x00, 0x01, 0x00 }); BigIntegerEx mod = new BigIntegerEx(BigIntegerEx.LITTLE_ENDIAN, new byte[] { (byte) 0x6B, (byte) 0xCE, (byte) 0xF5, (byte) 0x2D, (byte) 0x2A, (byte) 0x7D, (byte) 0x7A, (byte) 0x67, (byte) 0x21, (byte) 0x21, (byte) 0x84, (byte) 0xC9, (byte) 0xBC, (byte) 0x25, (byte) 0xC7, (byte) 0xBC, (byte) 0xDF, (byte) 0x3D, (byte) 0x8F, (byte) 0xD9, (byte) 0x47, (byte) 0xBC, (byte) 0x45, (byte) 0x48, (byte) 0x8B, (byte) 0x22, (byte) 0x85, (byte) 0x3B, (byte) 0xC5, (byte) 0xC1, (byte) 0xF4, (byte) 0xF5, (byte) 0x3C, (byte) 0x0C, (byte) 0x49, (byte) 0xBB, (byte) 0x56, (byte) 0xE0, (byte) 0x3D, (byte) 0xBC, (byte) 0xA2, (byte) 0xD2, (byte) 0x35, (byte) 0xC1, (byte) 0xF0, (byte) 0x74, (byte) 0x2E, (byte) 0x15, (byte) 0x5A, (byte) 0x06, (byte) 0x8A, (byte) 0x68, (byte) 0x01, (byte) 0x9E, (byte) 0x60, (byte) 0x17, (byte) 0x70, (byte) 0x8B, (byte) 0xBD, (byte) 0xF8, (byte) 0xD5, (byte) 0xF9, (byte) 0x3A, (byte) 0xD3, (byte) 0x25, (byte) 0xB2, (byte) 0x66, (byte) 0x92, (byte) 0xBA, (byte) 0x43, (byte) 0x8A, (byte) 0x81, (byte) 0x52, (byte) 0x0F, (byte) 0x64, (byte) 0x98, (byte) 0xFF, (byte) 0x60, (byte) 0x37, (byte) 0xAF, (byte) 0xB4, (byte) 0x11, (byte) 0x8C, (byte) 0xF9, (byte) 0x2E, (byte) 0xC5, (byte) 0xEE, (byte) 0xCA, (byte) 0xB4, (byte) 0x41, (byte) 0x60, (byte) 0x3C, (byte) 0x7D, (byte) 0x02, (byte) 0xAF, (byte) 0xA1, (byte) 0x2B, (byte) 0x9B, (byte) 0x22, (byte) 0x4B, (byte) 0x3B, (byte) 0xFC, (byte) 0xD2, (byte) 0x5D, (byte) 0x73, (byte) 0xE9, (byte) 0x29, (byte) 0x34, (byte) 0x91, (byte) 0x85, (byte) 0x93, (byte) 0x4C, (byte) 0xBE, (byte) 0xBE, (byte) 0x73, (byte) 0xA9, (byte) 0xD2, (byte) 0x3B, (byte) 0x27, (byte) 0x7A, (byte) 0x47, (byte) 0x76, (byte) 0xEC, (byte) 0xB0, (byte) 0x28, (byte) 0xC9, (byte) 0xC1, (byte) 0xDA, (byte) 0xEE, (byte) 0xAA, (byte) 0xB3, (byte) 0x96, (byte) 0x9C, (byte) 0x1E, (byte) 0xF5, (byte) 0x6B, (byte) 0xF6, (byte) 0x64, (byte) 0xD8, (byte) 0x94, (byte) 0x2E, (byte) 0xF1, (byte) 0xF7, (byte) 0x14, (byte) 0x5F, (byte) 0xA0, (byte) 0xF1, (byte) 0xA3, (byte) 0xB9, (byte) 0xB1, (byte) 0xAA, (byte) 0x58, (byte) 0x97, (byte) 0xDC, (byte) 0x09, (byte) 0x17, (byte) 0x0C, (byte) 0x04, (byte) 0xD3, (byte) 0x8E, (byte) 0x02, (byte) 0x2C, (byte) 0x83, (byte) 0x8A, (byte) 0xD6, (byte) 0xAF, (byte) 0x7C, (byte) 0xFE, (byte) 0x83, (byte) 0x33, (byte) 0xC6, (byte) 0xA8, (byte) 0xC3, (byte) 0x84, (byte) 0xEF, (byte) 0x29, (byte) 0x06, (byte) 0xA9, (byte) 0xB7, (byte) 0x2D, (byte) 0x06, (byte) 0x0B, (byte) 0x0D, (byte) 0x6F, (byte) 0x70, (byte) 0x9E, (byte) 0x34, (byte) 0xA6, (byte) 0xC7, (byte) 0x31, (byte) 0xBE, (byte) 0x56, (byte) 0xDE, (byte) 0xDD, (byte) 0x02, (byte) 0x92, (byte) 0xF8, (byte) 0xA0, (byte) 0x58, (byte) 0x0B, (byte) 0xFC, (byte) 0xFA, (byte) 0xBA, (byte) 0x49, (byte) 0xB4, (byte) 0x48, (byte) 0xDB, (byte) 0xEC, (byte) 0x25, (byte) 0xF3, (byte) 0x18, (byte) 0x8F, (byte) 0x2D, (byte) 0xB3, (byte) 0xC0, (byte) 0xB8, (byte) 0xDD, (byte) 0xBC, (byte) 0xD6, (byte) 0xAA, (byte) 0xA6, (byte) 0xDB, (byte) 0x6F, (byte) 0x7D, (byte) 0x7D, (byte) 0x25, (byte) 0xA6, (byte) 0xCD, (byte) 0x39, (byte) 0x6D, (byte) 0xDA, (byte) 0x76, (byte) 0x0C, (byte) 0x79, (byte) 0xBF, (byte) 0x48, (byte) 0x25, (byte) 0xFC, (byte) 0x2D, (byte) 0xC5, (byte) 0xFA, (byte) 0x53, (byte) 0x9B, (byte) 0x4D, (byte) 0x60, (byte) 0xF4, (byte) 0xEF, (byte) 0xC7, (byte) 0xEA, (byte) 0xAC, (byte) 0xA1, (byte) 0x7B, (byte) 0x03, (byte) 0xF4, (byte) 0xAF, (byte) 0xC7 }); byte[] result = new BigIntegerEx(BigIntegerEx.LITTLE_ENDIAN, signature).modPow(power, mod).toByteArray(); byte[] digest; byte[] properResult = new byte[0x100]; for (int i = 0; i < properResult.length; i++) properResult[i] = (byte) 0xBB; MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(module); md.update("MAIEV.MOD".getBytes()); digest = md.digest(); System.arraycopy(digest, 0, properResult, 0, digest.length); for (int i = 0; i < result.length; i++) if (result[i] != properResult[i]) return false; return true; } catch (Exception e) { System.out.println("Failed to verify signature: " + e.toString()); } return false; } |
11
| Code Sample 1:
public void writeTo(OutputStream out) throws IOException { if (!closed) { throw new IOException("Stream not closed"); } if (isInMemory()) { memoryOutputStream.writeTo(out); } else { FileInputStream fis = new FileInputStream(outputFile); try { IOUtils.copy(fis, out); } finally { IOUtils.closeQuietly(fis); } } }
Code Sample 2:
public static void copy(FileInputStream from, FileOutputStream to) throws IOException { FileChannel fromChannel = from.getChannel(); FileChannel toChannel = to.getChannel(); copy(fromChannel, toChannel); fromChannel.close(); toChannel.close(); } |
00
| Code Sample 1:
public String getIpAddress() { try { URL url = new URL("http://checkip.dyndns.org"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String linha; String rtn = ""; while ((linha = in.readLine()) != null) rtn += linha; ; in.close(); return filtraRetorno(rtn); } catch (IOException ex) { Logger.getLogger(ExternalIp.class.getName()).log(Level.SEVERE, null, ex); return "ERRO."; } }
Code Sample 2:
public boolean getFile(String pRemoteDirectory, String pLocalDirectory, String pFileName) throws IOException { FTPClient fc = new FTPClient(); fc.connect(getRemoteHost()); fc.login(getUserName(), getPassword()); fc.changeWorkingDirectory(pRemoteDirectory); String workingDirectory = fc.printWorkingDirectory(); FileOutputStream fos = null; logInfo("Connected to remote host=" + getRemoteHost() + "; userName=" + getUserName() + "; " + "; remoteDirectory=" + pRemoteDirectory + "; localDirectory=" + pLocalDirectory + "; workingDirectory=" + workingDirectory); try { fos = new FileOutputStream(pLocalDirectory + "/" + pFileName); boolean retrieved = fc.retrieveFile(pFileName, fos); if (true == retrieved) { logInfo("Successfully retrieved file: " + pFileName); } else { logError("Could not retrieve file: " + pFileName); } return retrieved; } finally { if (null != fos) { fos.flush(); fos.close(); } } } |
11
| Code Sample 1:
public Document retrieveDefinition(String uri) throws IOException, UnvalidResponseException { if (!isADbPediaURI(uri)) throw new IllegalArgumentException("Not a DbPedia Resource URI"); String rawDataUri = fromResourceToRawDataUri(uri); URL url = new URL(rawDataUri); URLConnection conn = url.openConnection(); logger.debug(".conn open"); conn.setDoOutput(true); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); logger.debug(".resp obtained"); StringBuffer responseBuffer = new StringBuffer(); String line; while ((line = rd.readLine()) != null) { responseBuffer.append(line); responseBuffer.append(NEWLINE); } rd.close(); logger.debug(".done"); try { return documentParser.parse(responseBuffer.toString()); } catch (SAXException e) { throw new UnvalidResponseException("Incorrect XML document", e); } }
Code Sample 2:
public static Collection<Class<? extends Page>> loadPages() throws IOException { ClassLoader ldr = Thread.currentThread().getContextClassLoader(); Collection<Class<? extends Page>> pages = new ArrayList<Class<? extends Page>>(); Enumeration<URL> e = ldr.getResources("META-INF/services/" + Page.class.getName()); while (e.hasMoreElements()) { URL url = e.nextElement(); InputStream is = url.openStream(); ; try { BufferedReader r = new BufferedReader(new InputStreamReader(is, "UTF-8")); while (true) { String line = r.readLine(); if (line == null) break; int comment = line.indexOf('#'); if (comment >= 0) line = line.substring(0, comment); String name = line.trim(); if (name.length() == 0) continue; Class<?> clz = Class.forName(name, true, ldr); Class<? extends Page> impl = clz.asSubclass(Page.class); pages.add(impl); } } catch (Exception ex) { System.out.println(ex); } finally { try { is.close(); } catch (Exception ex) { } } } return pages; } |
11
| Code Sample 1:
public static void main(String[] args) { File container = new File(ArchiveFeature.class.getProtectionDomain().getCodeSource().getLocation().toURI()); if (container == null) { throw new RuntimeException("this use-case isn't being invoked from the executable jar"); } JarFile jarFile = new JarFile(container); String artifactName = PROJECT_DIST_ARCHIVE + ".tar.gz"; File artifactFile = new File(".", artifactName); ZipEntry artifactEntry = jarFile.getEntry(artifactName); InputStream source = jarFile.getInputStream(artifactEntry); try { FileOutputStream dest = new FileOutputStream(artifactFile); try { IOUtils.copy(source, dest); } finally { IOUtils.closeQuietly(dest); } } finally { IOUtils.closeQuietly(source); } Project project = new Project(); project.setName("project"); project.init(); Target target = new Target(); target.setName("target"); project.addTarget(target); project.addBuildListener(new Log4jListener()); Untar untar = new Untar(); untar.setTaskName("untar"); untar.setSrc(artifactFile); untar.setDest(new File(".")); Untar.UntarCompressionMethod method = new Untar.UntarCompressionMethod(); method.setValue("gzip"); untar.setCompression(method); untar.setProject(project); untar.setOwningTarget(target); target.addTask(untar); untar.execute(); }
Code Sample 2:
private void copyFile(File in, File out) throws Exception { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } |
00
| Code Sample 1:
public void deploy(final File extension) { log.info("Deploying new extension from {}", extension.getPath()); RequestContextHolder.setRequestContext(new RequestContext(SZoneConfig.getDefaultZoneName(), SZoneConfig.getAdminUserName(SZoneConfig.getDefaultZoneName()), new BaseSessionContext())); RequestContextHolder.getRequestContext().resolve(); JarInputStream warIn; try { warIn = new JarInputStream(new FileInputStream(extension), true); } catch (IOException e) { log.warn("Unable to open extension WAR at " + extension.getPath(), e); return; } SAXReader reader = new SAXReader(false); reader.setIncludeExternalDTDDeclarations(false); String extensionPrefix = extension.getName().substring(0, extension.getName().lastIndexOf(".")); File extensionDir = new File(extensionBaseDir, extensionPrefix); extensionDir.mkdirs(); File extensionWebDir = new File(this.extensionWebDir, extensionPrefix); extensionWebDir.mkdirs(); try { for (JarEntry entry = warIn.getNextJarEntry(); entry != null; entry = warIn.getNextJarEntry()) { File inflated = new File(entry.getName().startsWith(infPrefix) ? extensionDir : extensionWebDir, entry.getName()); if (entry.isDirectory()) { log.debug("Creating directory at {}", inflated.getPath()); inflated.mkdirs(); continue; } inflated.getParentFile().mkdirs(); FileOutputStream entryOut = new FileOutputStream(inflated); if (!entry.getName().endsWith(configurationFileExtension)) { log.debug("Inflating file resource to {}", inflated.getPath()); IOUtils.copy(warIn, entryOut); entryOut.close(); continue; } try { final Document document = reader.read(new TeeInputStream(new CloseShieldInputStream(warIn), entryOut, true)); Attribute schema = document.getRootElement().attribute(schemaAttribute); if (schema == null || StringUtils.isBlank(schema.getText())) { log.debug("Inflating XML with unrecognized schema to {}", inflated.getPath()); continue; } if (schema.getText().contains(definitionsSchemaNamespace)) { log.debug("Inflating and registering definition from {}", inflated.getPath()); document.getRootElement().add(new AbstractAttribute() { private static final long serialVersionUID = -7880537136055718310L; public QName getQName() { return new QName(extensionAttr, document.getRootElement().getNamespace()); } public String getValue() { return extension.getName().substring(0, extension.getName().lastIndexOf(".")); } }); definitionModule.addDefinition(document, true); continue; } if (schema.getText().contains(templateSchemaNamespace)) { log.debug("Inflating and registering template from {}", inflated.getPath()); templateService.addTemplate(document, true, zoneModule.getDefaultZone()); continue; } } catch (DocumentException e) { log.warn("Malformed XML file in extension war at " + extension.getPath(), e); return; } } } catch (IOException e) { log.warn("Malformed extension war at " + extension.getPath(), e); return; } finally { try { warIn.close(); } catch (IOException e) { log.warn("Unable to close extension war at " + extension.getPath(), e); return; } RequestContextHolder.clear(); } log.info("Extension deployed successfully from {}", extension.getPath()); }
Code Sample 2:
private InputStream getInputStream() throws URISyntaxException, MalformedURLException, IOException { InputStream inStream = null; try { URL url = new URI(wsdlFile).toURL(); URLConnection connection = url.openConnection(); connection.connect(); inStream = connection.getInputStream(); } catch (IllegalArgumentException ex) { inStream = new FileInputStream(wsdlFile); } return inStream; } |
11
| Code Sample 1:
private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } }
Code Sample 2:
void run(String[] args) { InputStream istream = System.in; System.out.println("TradeMaximizer " + version); String filename = parseArgs(args, false); if (filename != null) { System.out.println("Input from: " + filename); try { if (filename.startsWith("http:") || filename.startsWith("ftp:")) { URL url = new URL(filename); istream = url.openStream(); } else istream = new FileInputStream(filename); } catch (IOException ex) { fatalError(ex.toString()); } } List<String[]> wantLists = readWantLists(istream); if (wantLists == null) return; if (options.size() > 0) { System.out.print("Options:"); for (String option : options) System.out.print(" " + option); System.out.println(); } System.out.println(); try { MessageDigest digest = MessageDigest.getInstance("MD5"); for (String[] wset : wantLists) { for (String w : wset) { digest.update((byte) ' '); digest.update(w.getBytes()); } digest.update((byte) '\n'); } System.out.println("Input Checksum: " + toHexString(digest.digest())); } catch (NoSuchAlgorithmException ex) { } parseArgs(args, true); if (iterations > 1 && seed == -1) { seed = System.currentTimeMillis(); System.out.println("No explicit SEED, using " + seed); } if (!(metric instanceof MetricSumSquares) && priorityScheme != NO_PRIORITIES) System.out.println("Warning: using priorities with the non-default metric is normally worthless"); buildGraph(wantLists); if (showMissing && officialNames != null && officialNames.size() > 0) { for (String name : usedNames) officialNames.remove(name); List<String> missing = new ArrayList<String>(officialNames); Collections.sort(missing); for (String name : missing) { System.out.println("**** Missing want list for official name " + name); } System.out.println(); } if (showErrors && errors.size() > 0) { Collections.sort(errors); System.out.println("ERRORS:"); for (String error : errors) System.out.println(error); System.out.println(); } long startTime = System.currentTimeMillis(); graph.removeImpossibleEdges(); List<List<Graph.Vertex>> bestCycles = graph.findCycles(); int bestMetric = metric.calculate(bestCycles); if (iterations > 1) { System.out.println(metric); graph.saveMatches(); for (int i = 0; i < iterations - 1; i++) { graph.shuffle(); List<List<Graph.Vertex>> cycles = graph.findCycles(); int newMetric = metric.calculate(cycles); if (newMetric < bestMetric) { bestMetric = newMetric; bestCycles = cycles; graph.saveMatches(); System.out.println(metric); } else if (verbose) System.out.println("# " + metric); } System.out.println(); graph.restoreMatches(); } long stopTime = System.currentTimeMillis(); displayMatches(bestCycles); if (showElapsedTime) System.out.println("Elapsed time = " + (stopTime - startTime) + "ms"); } |
11
| Code Sample 1:
@Override protected FTPClient ftpConnect() throws SocketException, IOException, NoSuchAlgorithmException { FilePathItem fpi = getFilePathItem(); FTPClient f = new FTPSClient(); f.connect(fpi.getHost()); f.login(fpi.getUsername(), fpi.getPassword()); return f; }
Code Sample 2:
private boolean initConnection() { try { if (ftp == null) { ftp = new FTPClient(); serverIP = getServer(); userName = getUserName(); password = getPassword(); } ftp.connect(serverIP); ftp.login(userName, password); return true; } catch (SocketException a_excp) { throw new RuntimeException(a_excp); } catch (IOException a_excp) { throw new RuntimeException(a_excp); } catch (Throwable a_th) { throw new RuntimeException(a_th); } } |
00
| Code Sample 1:
public void testCreateNewXMLFile() throws InvalidNodeTypeDefException, ParseException, Exception { JCRNodeSource emptySource = loadTestSource(); assertEquals(false, emptySource.exists()); OutputStream sourceOut = emptySource.getOutputStream(); assertNotNull(sourceOut); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } InputStream contentIn2 = getClass().getResourceAsStream(CONTENT2_FILE); sourceOut = emptySource.getOutputStream(); try { IOUtils.copy(contentIn2, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn2.close(); } InputStream expected = getClass().getResourceAsStream(CONTENT2_FILE); JCRNodeSource persistentSource = loadTestSource(); assertEquals(true, persistentSource.exists()); InputStream actual = persistentSource.getInputStream(); try { assertTrue(isXmlEqual(expected, actual)); } finally { expected.close(); actual.close(); } JCRNodeSource tmpSrc = (JCRNodeSource) resolveSource(BASE_URL + "users/alexander.saar"); persistentSource.delete(); tmpSrc.delete(); }
Code Sample 2:
public static ArrayList search(String query) throws Exception { ArrayList list = new ArrayList(); String url = "http://hypem.com/playlist/search/" + query + "/xml/1/list.xspf"; HttpURLConnection conn = (HttpURLConnection) (new URL(url)).openConnection(); conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"); XmlNode node = XmlLoader.load(conn.getInputStream()); XmlNode tracks[] = node.getFirstChild("trackList").getChild("track"); for (int i = 0; i < tracks.length; i++) { String location = decrypt(tracks[i].getFirstChild("location").getText()); String annotation = tracks[i].getFirstChild("annotation").getText().replaceAll("[\r\n]", ""); list.add(location); System.out.print("found in Hypem: "); System.out.print(annotation); System.out.print(", "); System.out.println(location); } return list; } |
11
| Code Sample 1:
public static void request() { try { URL url = new URL("http://www.nseindia.com/marketinfo/companyinfo/companysearch.jsp?cons=ghcl§ion=7"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { System.out.println(line); } rd.close(); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
private static void loadListFromRecouces(String category, URL url, DataSetArray<DataSetList> list, final StatusLineManager slm) { i = 0; try { if (url == null) return; InputStream in = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF8")); String strLine; while ((strLine = br.readLine()) != null) { strLine = strLine.trim(); i++; if (slm != null) { Display.getDefault().syncExec(new Runnable() { public void run() { slm.setMessage(_("Importing country code " + i)); } }); } if (!strLine.isEmpty() && !strLine.startsWith("#")) { String parts[] = strLine.split("=", 2); if (parts.length == 2) { String key = parts[0].trim(); String value = parts[1].trim(); key = DataUtils.replaceAllAccentedChars(key).toUpperCase(); DataSetList newListEntry = new DataSetList(category, key, value); list.addNewDataSetIfNew(newListEntry); } } } in.close(); } catch (IOException e) { Logger.logError(e, "Error loading " + url.getFile()); } } |
00
| Code Sample 1:
protected IRunnableWithProgress getProjectCreationRunnable() { return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { int remainingWorkUnits = 10; monitor.beginTask("New Modulo Project Creation", remainingWorkUnits); IWorkspace ws = ResourcesPlugin.getWorkspace(); newProject = fMainPage.getProjectHandle(); IProjectDescription description = ws.newProjectDescription(newProject.getName()); String[] natures = { JavaCore.NATURE_ID, ModuloLauncherPlugin.NATURE_ID }; description.setNatureIds(natures); ICommand command = description.newCommand(); command.setBuilderName(JavaCore.BUILDER_ID); ICommand[] commands = { command }; description.setBuildSpec(commands); IJavaProject jproject = JavaCore.create(newProject); ModuloProject modProj = new ModuloProject(); modProj.setJavaProject(jproject); try { newProject.create(description, new SubProgressMonitor(monitor, 1)); newProject.open(new SubProgressMonitor(monitor, 1)); IFolder srcFolder = newProject.getFolder("src"); IFolder javaFolder = srcFolder.getFolder("java"); IFolder buildFolder = newProject.getFolder("build"); IFolder classesFolder = buildFolder.getFolder("classes"); modProj.createFolder(srcFolder); modProj.createFolder(javaFolder); modProj.createFolder(buildFolder); modProj.createFolder(classesFolder); IPath buildPath = newProject.getFolder("build/classes").getFullPath(); jproject.setOutputLocation(buildPath, new SubProgressMonitor(monitor, 1)); IClasspathEntry[] entries = new IClasspathEntry[] { JavaCore.newSourceEntry(newProject.getFolder("src/java").getFullPath()), JavaCore.newContainerEntry(new Path(JavaRuntime.JRE_CONTAINER)), JavaCore.newContainerEntry(new Path(ModuloClasspathContainer.CONTAINER_ID)) }; jproject.setRawClasspath(entries, new SubProgressMonitor(monitor, 1)); ModuleDefinition definition = new ModuleDefinition(); definition.setId(fModuloPage.getPackageName()); definition.setVersion(new VersionNumber(1, 0, 0)); definition.setMetaName(fModuloPage.getModuleName()); definition.setMetaDescription("The " + fModuloPage.getModuleName() + " Module."); definition.setModuleClassName(fModuloPage.getPackageName() + "." + fModuloPage.getModuleClassName()); if (fModuloPage.isConfigSelectioned()) definition.setConfigurationClassName(fModuloPage.getPackageName() + "." + fModuloPage.getConfigClassName()); if (fModuloPage.isStatSelectioned()) definition.setStatisticsClassName(fModuloPage.getPackageName() + "." + fModuloPage.getStatClassName()); modProj.setDefinition(definition); modProj.createPackage(); modProj.createModuleXML(); modProj.createMainClass(); if (fModuloPage.isConfigSelectioned()) modProj.createConfigClass(); if (fModuloPage.isStatSelectioned()) modProj.createStatClass(); modProj.createModuleProperties(); modProj.createMessagesProperties(); IFolder binFolder = newProject.getFolder("bin"); binFolder.delete(true, new SubProgressMonitor(monitor, 1)); } catch (CoreException e) { e.printStackTrace(); } finally { monitor.done(); } } }; }
Code Sample 2:
byte[] makeIDPFXORMask() { if (idpfMask == null) { try { MessageDigest sha = MessageDigest.getInstance("SHA-1"); String temp = strip(getPrimaryIdentifier()); sha.update(temp.getBytes("UTF-8"), 0, temp.length()); idpfMask = sha.digest(); } catch (NoSuchAlgorithmException e) { System.err.println("No such Algorithm (really, did I misspell SHA-1?"); System.err.println(e.toString()); return null; } catch (IOException e) { System.err.println("IO Exception. check out mask.write..."); System.err.println(e.toString()); return null; } } return idpfMask; } |
00
| Code Sample 1:
private Document getDocument(URL url) throws SAXException, IOException { InputStream is; try { is = url.openStream(); } catch (IOException io) { System.out.println("parameter error : The specified reading data is mistaken."); System.out.println(" Request URL is " + sourceUri); throw new IOException("\t" + io.toString()); } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = null; try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException pce) { System.out.println("error : The error of DocumentBuilder instance generation"); throw new RuntimeException(pce.toString()); } Document doc; try { doc = builder.parse(is); } catch (Exception e) { System.out.println("error : parse of reading data went wrong."); System.out.println(" Request URL is " + sourceUri); throw new RuntimeException(e.toString()); } return doc; }
Code Sample 2:
private static PointGeomReader[] loadResourceList(final String resourceName, ClassLoader loader) { if (loader == null) loader = ClassLoader.getSystemClassLoader(); final FastSet<PointGeomReader> result = FastSet.newInstance(); try { final Enumeration<URL> resources = loader.getResources(resourceName); if (resources != null) { while (resources.hasMoreElements()) { final URL url = resources.nextElement(); final Properties mapping; InputStream urlIn = null; try { urlIn = url.openStream(); mapping = new Properties(); mapping.load(urlIn); } catch (IOException ioe) { continue; } finally { if (urlIn != null) try { urlIn.close(); } catch (Exception ignore) { } } for (Enumeration keys = mapping.propertyNames(); keys.hasMoreElements(); ) { final String format = (String) keys.nextElement(); final String implClassName = mapping.getProperty(format); result.add(loadResource(implClassName, loader)); } } } } catch (IOException ignore) { } PointGeomReader[] resultArr = result.toArray(new PointGeomReader[result.size()]); Arrays.sort(resultArr, FastComparator.DEFAULT); FastSet.recycle(result); return resultArr; } |
00
| Code Sample 1:
@Override public void write(OutputStream output) throws IOException, WebApplicationException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final GZIPOutputStream gzipOs = new GZIPOutputStream(baos); IOUtils.copy(is, gzipOs); baos.close(); gzipOs.close(); output.write(baos.toByteArray()); }
Code Sample 2:
protected InputStream callApiGet(String apiUrl, int expected) { try { URL url = new URL(apiUrl); HttpURLConnection request = (HttpURLConnection) url.openConnection(); if (ApplicationConstants.CONNECT_TIMEOUT > -1) { request.setConnectTimeout(ApplicationConstants.CONNECT_TIMEOUT); } if (ApplicationConstants.READ_TIMEOUT > -1) { request.setReadTimeout(ApplicationConstants.READ_TIMEOUT); } for (String headerName : requestHeaders.keySet()) { request.setRequestProperty(headerName, requestHeaders.get(headerName)); } request.connect(); if (request.getResponseCode() != expected) { throw new BingMapsException(convertStreamToString(request.getErrorStream())); } else { return getWrappedInputStream(request.getInputStream(), GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding())); } } catch (IOException e) { throw new BingMapsException(e); } } |
11
| Code Sample 1:
public static void copyFile(File in, File out) { int len; byte[] buffer = new byte[1024]; try { FileInputStream fin = new FileInputStream(in); FileOutputStream fout = new FileOutputStream(out); while ((len = fin.read(buffer)) >= 0) fout.write(buffer, 0, len); fin.close(); fout.close(); } catch (IOException ex) { } }
Code Sample 2:
public static int save(File inputFile, File outputFile) throws IOException { InputStream in = null; OutputStream out = null; try { in = new FileInputStream(inputFile); outputFile.getParentFile().mkdirs(); out = new FileOutputStream(outputFile); } catch (Exception e) { e.getMessage(); } try { return IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); try { if (out != null) { out.close(); } } catch (IOException ioe) { ioe.getMessage(); } try { if (in != null) { in.close(); } } catch (IOException ioe) { ioe.getMessage(); } } } |
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 boolean copyFile(File outFile, File inFile) { InputStream inStream = null; OutputStream outStream = null; try { if (outFile.createNewFile()) { inStream = new FileInputStream(inFile); outStream = new FileOutputStream(outFile); byte[] buffer = new byte[1024]; int length; while ((length = inStream.read(buffer)) > 0) outStream.write(buffer, 0, length); inStream.close(); outStream.close(); } else return false; } catch (IOException iox) { iox.printStackTrace(); return false; } return true; } |
11
| Code Sample 1:
public static void copyWithClose(InputStream is, OutputStream os) throws IOException { try { IOUtils.copy(is, os); } catch (IOException ioe) { try { if (os != null) os.close(); } catch (Exception e) { } try { if (is != null) is.close(); } catch (Exception e) { } } }
Code Sample 2:
public void testStorageString() throws Exception { TranslationResponseInMemory r = new TranslationResponseInMemory(2048, "UTF-8"); r.addText("This is an example"); r.addText(" and another one."); assertEquals("This is an example and another one.", r.getText()); InputStream input = r.getInputStream(); StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer, "UTF-8"); } finally { input.close(); writer.close(); } assertEquals("This is an example and another one.", writer.toString()); try { r.getOutputStream(); fail("Once addText() is used the text is stored as a String and you cannot use getOutputStream anymore"); } catch (IOException e) { } try { r.getWriter(); fail("Once addText() is used the text is stored as a String and you cannot use getOutputStream anymore"); } catch (IOException e) { } r.setEndState(ResponseStateOk.getInstance()); assertTrue(r.hasEnded()); } |
11
| Code Sample 1:
@Override public String toString() { if (byteArrayOutputStream == null) return "<Unparsed binary data: Content-Type=" + getHeader("Content-Type") + " >"; String charsetName = getCharsetName(); if (charsetName == null) charsetName = "ISO-8859-1"; try { if (unzip) { GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray())); ByteArrayOutputStream unzippedResult = new ByteArrayOutputStream(); IOUtils.copy(gzipInputStream, unzippedResult); return unzippedResult.toString(charsetName); } else { return byteArrayOutputStream.toString(charsetName); } } catch (UnsupportedEncodingException e) { throw new OutputException(e); } catch (IOException e) { throw new OutputException(e); } }
Code Sample 2:
protected boolean writeFile(Interest outstandingInterest) throws IOException { File fileToWrite = ccnNameToFilePath(outstandingInterest.name()); Log.info("CCNFileProxy: extracted request for file: " + fileToWrite.getAbsolutePath() + " exists? ", fileToWrite.exists()); if (!fileToWrite.exists()) { Log.warning("File {0} does not exist. Ignoring request.", fileToWrite.getAbsoluteFile()); return false; } FileInputStream fis = null; try { fis = new FileInputStream(fileToWrite); } catch (FileNotFoundException fnf) { Log.warning("Unexpected: file we expected to exist doesn't exist: {0}!", fileToWrite.getAbsolutePath()); return false; } CCNTime modificationTime = new CCNTime(fileToWrite.lastModified()); ContentName versionedName = VersioningProfile.addVersion(new ContentName(_prefix, outstandingInterest.name().postfix(_prefix).components()), modificationTime); CCNFileOutputStream ccnout = new CCNFileOutputStream(versionedName, _handle); ccnout.addOutstandingInterest(outstandingInterest); byte[] buffer = new byte[BUF_SIZE]; int read = fis.read(buffer); while (read >= 0) { ccnout.write(buffer, 0, read); read = fis.read(buffer); } fis.close(); ccnout.close(); return true; } |
11
| Code Sample 1:
public static boolean writeFileByBinary(InputStream pIs, File pFile, boolean pAppend) { boolean flag = false; try { FileOutputStream fos = new FileOutputStream(pFile, pAppend); IOUtils.copy(pIs, fos); fos.flush(); fos.close(); pIs.close(); flag = true; } catch (Exception e) { LOG.error("将字节流写入�?" + pFile.getName() + "出现异常�?", e); } return flag; }
Code Sample 2:
public static void copyFile(String sIn, String sOut) throws IOException { File fIn = new File(sIn); File fOut = new File(sOut); FileChannel fcIn = new FileInputStream(fIn).getChannel(); FileChannel fcOut = new FileOutputStream(fOut).getChannel(); try { fcIn.transferTo(0, fcIn.size(), fcOut); } catch (IOException e) { throw e; } finally { if (fcIn != null) fcIn.close(); if (fcOut != null) fcOut.close(); } fOut.setReadable(fIn.canRead()); fOut.setWritable(fIn.canWrite()); fOut.setExecutable(fIn.canExecute()); } |
00
| Code Sample 1:
protected URLConnection openConnection(URL url) throws IOException { if (url == null) return null; if (!url.getProtocol().equals("nntp")) return null; if (m_connection != null) { if (m_connection.getURL().getHost().equals(url.getHost()) && (m_connection.getURL().getPort() == url.getPort()) && (m_connection.getURL().getUserInfo().equals(url.getUserInfo()))) { return m_connection; } } m_connection = new NNTPConnection(url); return m_connection; }
Code Sample 2:
public static String md5(String text) { MessageDigest msgDigest = null; try { msgDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("System doesn't support MD5 algorithm."); } try { msgDigest.update(text.getBytes("utf-8")); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("System doesn't support your EncodingException."); } byte[] bytes = msgDigest.digest(); String md5Str = new String(encodeHex(bytes)); return md5Str; } |
11
| Code Sample 1:
private static String webService(String strUrl) { StringBuffer buffer = new StringBuffer(); try { URL url = new URL(strUrl); InputStream input = url.openStream(); String sCurrentLine = ""; InputStreamReader read = new InputStreamReader(input, "utf-8"); BufferedReader l_reader = new java.io.BufferedReader(read); while ((sCurrentLine = l_reader.readLine()) != null) { buffer.append(sCurrentLine); } return buffer.toString(); } catch (Exception e) { e.printStackTrace(); return null; } }
Code Sample 2:
private static List lookupForImplementations(final Class clazz, final ClassLoader loader, final String[] defaultImplementations, final boolean onlyFirst, final boolean returnInstances) throws ClassNotFoundException { if (clazz == null) { throw new IllegalArgumentException("Argument 'clazz' cannot be null!"); } ClassLoader classLoader = loader; if (classLoader == null) { classLoader = clazz.getClassLoader(); } String interfaceName = clazz.getName(); ArrayList tmp = new ArrayList(); ArrayList toRemove = new ArrayList(); String className = System.getProperty(interfaceName); if (className != null && className.trim().length() > 0) { tmp.add(className.trim()); } Enumeration en = null; try { en = classLoader.getResources("META-INF/services/" + clazz.getName()); } catch (IOException e) { e.printStackTrace(); } while (en != null && en.hasMoreElements()) { URL url = (URL) en.nextElement(); InputStream is = null; try { is = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); String line; do { line = reader.readLine(); boolean remove = false; if (line != null) { if (line.startsWith("#-")) { remove = true; line = line.substring(2); } int pos = line.indexOf('#'); if (pos >= 0) { line = line.substring(0, pos); } line = line.trim(); if (line.length() > 0) { if (remove) { toRemove.add(line); } else { tmp.add(line); } } } } while (line != null); } catch (IOException e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } } if (defaultImplementations != null) { for (int i = 0; i < defaultImplementations.length; i++) { tmp.add(defaultImplementations[i].trim()); } } if (!clazz.isInterface()) { int m = clazz.getModifiers(); if (!Modifier.isAbstract(m) && Modifier.isPublic(m) && !Modifier.isStatic(m)) { tmp.add(interfaceName); } } tmp.removeAll(toRemove); ArrayList res = new ArrayList(); for (Iterator it = tmp.iterator(); it.hasNext(); ) { className = (String) it.next(); try { Class c = Class.forName(className, false, classLoader); if (c != null) { if (clazz.isAssignableFrom(c)) { if (returnInstances) { Object o = null; try { o = c.newInstance(); } catch (Throwable e) { e.printStackTrace(); } if (o != null) { res.add(o); if (onlyFirst) { return res; } } } else { res.add(c); if (onlyFirst) { return res; } } } else { logger.warning("MetaInfLookup: Class '" + className + "' is not a subclass of class : " + interfaceName); } } } catch (ClassNotFoundException e) { logger.log(Level.WARNING, "Cannot create implementation of interface: " + interfaceName, e); } } if (res.size() == 0) { throw new ClassNotFoundException("Cannot find any implemnetation of class " + interfaceName); } return res; } |
11
| Code Sample 1:
public static void generate(final InputStream input, String format, Point dimension, IPath outputLocation) throws CoreException { MultiStatus status = new MultiStatus(GraphVizActivator.ID, 0, "Errors occurred while running Graphviz", null); File dotInput = null, dotOutput = outputLocation.toFile(); ByteArrayOutputStream dotContents = new ByteArrayOutputStream(); try { dotInput = File.createTempFile(TMP_FILE_PREFIX, DOT_EXTENSION); FileOutputStream tmpDotOutputStream = null; try { IOUtils.copy(input, dotContents); tmpDotOutputStream = new FileOutputStream(dotInput); IOUtils.copy(new ByteArrayInputStream(dotContents.toByteArray()), tmpDotOutputStream); } finally { IOUtils.closeQuietly(tmpDotOutputStream); } IStatus result = runDot(format, dimension, dotInput, dotOutput); if (dotOutput.isFile()) { if (!result.isOK() && Platform.inDebugMode()) LogUtils.log(status); return; } } catch (IOException e) { status.add(new Status(IStatus.ERROR, GraphVizActivator.ID, "", e)); } finally { dotInput.delete(); IOUtils.closeQuietly(input); } throw new CoreException(status); }
Code Sample 2:
public static void fileCopy(String from_name, String to_name) throws IOException { File fromFile = new File(from_name); File toFile = new File(to_name); if (fromFile.equals(toFile)) abort("cannot copy on itself: " + from_name); if (!fromFile.exists()) abort("no such currentSourcepartName file: " + from_name); if (!fromFile.isFile()) abort("can't copy directory: " + from_name); if (!fromFile.canRead()) abort("currentSourcepartName file is unreadable: " + from_name); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) abort("destination file is unwriteable: " + to_name); } else { String parent = toFile.getParent(); if (parent == null) abort("destination directory doesn't exist: " + parent); File dir = new File(parent); if (!dir.exists()) abort("destination directory doesn't exist: " + parent); if (dir.isFile()) abort("destination is not a directory: " + parent); if (!dir.canWrite()) abort("destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } |
00
| Code Sample 1:
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String limitsSet = ""; String synstatus = SystemFilesLoader.getInstance().getNewgenlibProperties().getProperty("SYNDETICS", "OFF"); String synncode = SystemFilesLoader.getInstance().getNewgenlibProperties().getProperty("SYNDETICS_CLIENT_CODE", ""); try { if (request.getSession().getAttribute("searchLimits") != null) { System.out.println("searchLimits set"); limitsSet = "SET"; java.util.Hashtable htLimits = new java.util.Hashtable(); htLimits = (java.util.Hashtable) request.getSession().getAttribute("searchLimits"); } else { limitsSet = "UNSET"; System.out.println("searchLimits not set"); } java.util.Properties prop = System.getProperties(); prop.load(new FileInputStream(ejb.bprocess.util.NewGenLibRoot.getRoot() + java.io.File.separator + "SystemFiles" + java.io.File.separator + "ENV_VAR.txt")); System.out.println("SEARCH MODE IS " + searchmode + " FILE PATH " + ejb.bprocess.util.NewGenLibRoot.getRoot() + java.io.File.separator + "SystemFiles" + java.io.File.separator + "ENV_VAR.txt"); } catch (Exception e) { } javax.servlet.http.HttpSession session = request.getSession(); String forward = "searchView"; int link = 0, singleLink = 0; java.util.Vector vecThisPage = new java.util.Vector(); aportal.form.cataloguing.SearchViewForm svF = (aportal.form.cataloguing.SearchViewForm) form; svF.setSyndeticsStatus(synstatus); svF.setSyndeticsClientCode(synncode); opacHm = (ejb.bprocess.opac.xcql.OPACUtilitiesHome) ejb.bprocess.util.HomeFactory.getInstance().getRemoteHome("OPACUtilities"); ejb.bprocess.opac.xcql.OPACUtilities opacUt = opacHm.create(); System.out.println("CLASS NO " + request.getParameter("ClassNo") + " ClassNoForwarded " + session.getAttribute("ClassNoForwarded")); if (svF.getExportRec() == null || !(svF.getExportRec().equals("export"))) { if (request.getParameter("CatId") != null && request.getParameter("OwnerId") != null && request.getParameter("relation") != null && !(session.getAttribute("HostItemDisplay") != null && session.getAttribute("HostItemDisplay").toString().equals("false"))) { home = (ejb.bprocess.opac.xcql.SearchSRUWCatalogueHome) ejb.bprocess.util.HomeFactory.getInstance().getRemoteHome("SearchSRUWCatalogue"); ejb.bprocess.opac.xcql.SearchSRUWCatalogue searchCat = home.create(); String catId1 = request.getParameter("CatId"); String ownId1 = request.getParameter("OwnerId"); System.out.println("*********************CatId1: " + catId1); svF.setCatalogueRecordId(catId1); svF.setOwnerLibraryId(ownId1); String rel = request.getParameter("relation"); java.util.Vector vecL = searchCat.getRelatedCatalogueRecords(null, catId1, ownId1, rel); request.setAttribute("LuceneVector", vecL); session.setAttribute("searchVec", vecL); singleLink = 1; session.setAttribute("HostItemDisplay", "false"); link = 1; forward = "searchRes"; vecThisPage.addElement(catId1); vecThisPage.addElement(ownId1); } else if (link == 0 || singleLink == 1) { System.out.println("LINK AND SINGLE LINK " + link + " single " + singleLink); if ((request.getParameter("ClassNo") != null) && session.getAttribute("ClassNoForwarded") == null) { System.out.println("action called for class no."); String classificNo = request.getParameter("ClassNo"); System.out.println("TITLE WORDS "); home = (ejb.bprocess.opac.xcql.SearchSRUWCatalogueHome) ejb.bprocess.util.HomeFactory.getInstance().getRemoteHome("SearchSRUWCatalogue"); ejb.bprocess.opac.xcql.SearchSRUWCatalogue searchCat = home.create(); String rawSearchText = (new beans.miscellaneous.RequestStringProcessor()).processString("*" + classificNo + "*"); System.out.println("raw search Text" + rawSearchText); String searchText = "classificationNumber=" + rawSearchText; System.out.println("search text is " + searchText); String xmlRes = (new org.z3950.zing.cql.CQLParser()).parse(searchText).toXCQL(0); java.util.Hashtable hs = new java.util.Hashtable(); java.util.Vector v1 = new java.util.Vector(); if (session.getAttribute("searchLimits") != null) { hs = (java.util.Hashtable) session.getAttribute("searchLimits"); } Vector vec = new Vector(); String solrQuery = Utility.getInstance().simplifiedSolrQuery(classificNo, "classificationNumber"); if (limitsSet.equalsIgnoreCase("SET")) { String limitsQuery = limitsSolrQuery(hs); solrQuery += limitsQuery; } solrQuery += " & "; Vector newRetvec = searchCat.processSolrQuery(1, 25, solrQuery, "245_Tag", "asc"); Hashtable ht = (Hashtable) newRetvec.get(0); String totrec = (String) ht.get("HITS"); session.setAttribute("TOTALREC", Integer.parseInt(totrec)); v1 = (Vector) ht.get("RESULTS"); hs.put("Query", solrQuery); if (v1.size() > 0) { hs.put("searchText", rawSearchText); hs.put("noOfRecords", 25); hs.put("browseType", "Classification Number"); session.setAttribute("searchEntry", hs); session.setAttribute("searchVec", v1); forward = "searchRes"; } else { forward = "home"; } } else { System.out.println("ELSE CALLED "); String record = request.getParameter("record"); String recNo = request.getParameter("recNo"); Integer catId = 0, ownerId = 0; String title = ""; if (request.getParameter("CatId") != null && request.getParameter("OwnerId") != null) { catId = new Integer(request.getParameter("CatId")).intValue(); ownerId = new Integer(request.getParameter("OwnerId")).intValue(); System.out.println("catId is +++=" + catId); System.out.println("OwnerId is +++=" + ownerId); title = request.getParameter("title"); svF.setCatalogueRecordId(request.getParameter("CatId")); svF.setOwnerLibraryId(request.getParameter("OwnerId")); } System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%VVVVVVVVVVVVVVVVVVVVVV"); ArrayList alOtherBooks = ((ejb.bprocess.opac.SearchCatalogue) ejb.bprocess.util.HomeFactory.getInstance().getHome("SearchCatalogue")).getOtherBooksInTheRack(null, catId.toString(), ownerId.toString(), ownerId.toString()); System.out.println("alOtherBooks size is " + alOtherBooks.size()); Vector vOtherBooks = new Vector(); Session catrecsession = DBConnector.getInstance().getSession(); utility = ejb.bprocess.util.Utility.getInstance(catrecsession); for (int i = 0; i < alOtherBooks.size(); i++) { String[] scData = (String[]) (alOtherBooks.get(i)); String catalogueId = scData[0]; String ownerLibId = scData[1]; System.out.println("catId is +++=" + catalogueId); System.out.println("OwnerId is +++=" + ownerLibId); String xmlWholeRecord = ""; String titleD = ""; String titleV = ""; String authorV = ""; String isbnNumber = ""; if (catalogueId != null && ownerLibId != null) { try { System.out.println("***************************** 0"); Hashtable htDetails = utility.getCatalogueRecord(new Integer(catalogueId), new Integer(ownerLibId)); System.out.println("***************************** 1"); if (htDetails != null && !htDetails.isEmpty()) { System.out.println("htDetails" + htDetails.toString()); titleV = utility.getTestedString(htDetails.get("Title")); authorV = utility.getTestedString(htDetails.get("Author")); isbnNumber = utility.getTestedString(htDetails.get("ISBN")); String[] str1 = titleV.split("/"); if (str1.length > 0) { titleD = str1[0]; if (titleD.length() > 45) { titleD = titleD.substring(0, 45) + "..."; } } String[] str = new String[5]; str[0] = titleD; str[1] = authorV; str[2] = isbnNumber; str[3] = catalogueId; str[4] = ownerLibId; vOtherBooks.add(str); System.out.println("Other Books size is " + vOtherBooks.size()); } } catch (Exception e) { e.printStackTrace(); } } } System.out.println("Other Books vector is *************************** \n "); for (int i = 0; i < vOtherBooks.size(); i++) { String[] str = (String[]) vOtherBooks.get(i); System.out.println("title :" + str[0].toString()); System.out.println("author :" + str[1].toString()); System.out.println("isbn :" + str[2].toString()); System.out.println("catID :" + str[3].toString()); System.out.println("ownerLibId :" + str[4].toString()); } System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"); request.setAttribute("fisheyedata", vOtherBooks); catrecsession.close(); session.setAttribute("SingleViewExport", vecThisPage); if (session.getAttribute("OnlySingleRec") != null && session.getAttribute("OnlySingleRec").toString().equals("true")) { java.util.Vector v1 = new java.util.Vector(); System.out.println("SEARCH MODE " + searchmode); if (searchmode.equalsIgnoreCase("a")) { System.out.println("SEARCHMODE IN SEARCH VIEW ACTION (IF) " + searchmode); v1 = (java.util.Vector) request.getAttribute("LuceneVector"); System.out.println("VECTOR V1 " + v1); } else { System.out.println("SEARCHMODE IN SEARCH VIEW ACTION (ELSE)" + searchmode); v1 = (java.util.Vector) session.getAttribute("searchVec"); } Object[] obj = (Object[]) v1.elementAt(0); String str[] = (String[]) obj[0]; java.util.Hashtable h = new java.util.Hashtable(); String tit = ""; h = (java.util.Hashtable) obj[1]; System.out.println("HASH TABLE in view action " + h); catId = new Integer(str[0]).intValue(); ownerId = new Integer(str[1]).intValue(); title = h.get("TITLE").toString(); svF.setAttachmentsAndUrl(""); if ((h.get("ATTACHMENTS") != null && h.get("ATTACHMENTS").equals("AVAILABLE"))) { svF.setAttachmentsAndUrl("available"); } record = "full"; recNo = "1"; session.removeAttribute("OnlySingleRec"); } if (session.getAttribute("HostItemDisplay") != null && session.getAttribute("HostItemDisplay").equals("false")) { session.removeAttribute("HostItemDisplay"); } session.setAttribute("Title", title); java.util.Hashtable hash1 = opacUt.getDetailsForSingleCatalogueRecord(catId, ownerId); vecThisPage.addElement(String.valueOf(catId)); vecThisPage.addElement(String.valueOf(ownerId)); svF.setAttachmentsAndUrl(""); if (hash1.get("ATTACHMENTS") != null && hash1.get("ATTACHMENTS").toString().equals("AVAILABLE")) { svF.setAttachmentsAndUrl("available"); } svF.setRecordNo(recNo); session.setAttribute("record", record); java.util.Vector vecCO = (java.util.Vector) session.getAttribute("CatAndOwner"); svF.setCatCur(catId); svF.setOwnerCur(ownerId); svF.setPrevExists("no"); svF.setNextExists("no"); if (vecCO != null) { for (int j = 0; j < vecCO.size(); j = j + 4) { int c = new Integer(vecCO.elementAt(j).toString()).intValue(); int o = new Integer(vecCO.elementAt(j + 1).toString()).intValue(); if (c == catId && o == ownerId) { if (j != 0) { int catPrev = new Integer(vecCO.elementAt(j - 4).toString()).intValue(); int ownerPrev = new Integer(vecCO.elementAt(j - 3).toString()).intValue(); svF.setCatPrev(catPrev); svF.setOwnerPrev(ownerPrev); svF.setTitlePrev(vecCO.elementAt(j - 2).toString()); svF.setRecPrev(vecCO.elementAt(j - 1).toString()); svF.setPrevExists("yes"); } if (j < vecCO.size() - 4) { int catNext = new Integer(vecCO.elementAt(j + 4).toString()).intValue(); int ownerNext = new Integer(vecCO.elementAt(j + 5).toString()).intValue(); svF.setCatNext(catNext); svF.setOwnerNext(ownerNext); svF.setTitleNext(vecCO.elementAt(j + 6).toString()); svF.setRecNext(vecCO.elementAt(j + 7).toString()); svF.setNextExists("yes"); } } } } String str[] = (String[]) hash1.get("Biblo_Mat"); int bib_id = new Integer(str[0]).intValue(); int mat_id = new Integer(str[1]).intValue(); aportal.view.RecordView rv = new aportal.view.DesignFactory().getCorView(bib_id, mat_id, record); String type = ""; if (bib_id == 3 && mat_id == 1) { type = "Book"; } else if (bib_id == 4 && mat_id == 1) { type = "Serial"; } else if (bib_id == 1 && mat_id == 1) { type = "Book Chapter"; } else if (bib_id == 2 && mat_id == 1) { type = "Serial Article"; } else { type = ejb.bprocess.util.TypeDefinition.getInstance().getTypeDefinition(String.valueOf(bib_id), String.valueOf(mat_id)); } java.util.Hashtable hMono = (java.util.Hashtable) hash1.get("MonoGraphRecords"); java.util.Hashtable h4 = rv.getView(hash1); h4.put("Type", type); Hashtable ht = (Hashtable) h4.get("NoLink"); if (ht != null && ht.get("URLS_856") != null) { Vector urls856 = (Vector) ht.get("URLS_856"); if (urls856.size() > 0) { Hashtable linksAndText = new Hashtable(); Hashtable url856 = new Hashtable(); for (int i = 0; i < urls856.size(); i += 2) { url856.put(urls856.elementAt(i), urls856.elementAt(i + 1)); } linksAndText.put("URL", url856); h4.put("URLS_856", linksAndText); } } try { String sessionid = request.getSession().getId(); ejb.bprocess.holdings.HoldingsStatement holdingsStatement = ((ejb.bprocess.holdings.HoldingsStatementHome) ejb.bprocess.util.HomeFactory.getInstance().getRemoteHome("HoldingsStatement")).create(); java.util.Vector vecLib = new java.util.Vector(); vecLib.addElement("1"); if (session.getAttribute("Libraries") != null) { vecLib = (java.util.Vector) session.getAttribute("Libraries"); } String libIds = ""; for (int p = 0; p < vecLib.size(); p++) { if (p != 0) { libIds += ","; } String libName = vecLib.elementAt(p).toString(); Session session1 = DBConnector.getInstance().getSession(); libIds += ejb.bprocess.util.Utility.getInstance(session1).getLibraryId(libName); session1.close(); } request.setAttribute("catRecId", String.valueOf(catId)); request.setAttribute("ownLibId", String.valueOf(ownerId)); request.setAttribute("libIds", String.valueOf(libIds)); Hashtable onerecordattach = new Hashtable(); JSONObject jsonCatOwnId = new JSONObject().put("Id", catId).put("LibId", ownerId); ejb.bprocess.opac.SearchCatalogue searchCatAttach = ((ejb.bprocess.opac.SearchCatalogueHome) ejb.bprocess.util.HomeFactory.getInstance().getRemoteHome("SearchCatalogue")).create(); String strAttach = searchCatAttach.getAttachmentDetails(jsonCatOwnId.toString()); if (!strAttach.equals("")) { JSONObject jsonAttach = new JSONObject(strAttach); if (jsonAttach != null) { if (!jsonAttach.isNull("BookCover")) { ArrayList albookcover = new ArrayList(); JSONArray jsonarr = (JSONArray) jsonAttach.get("BookCover"); if (jsonarr != null) { for (int j = 0; j < jsonarr.length(); j++) { albookcover.add(jsonarr.getString(j)); } onerecordattach.put("BookCover", albookcover); } } if (!jsonAttach.isNull("TOC")) { ArrayList alTOC = new ArrayList(); JSONArray jsonarr = (JSONArray) jsonAttach.get("TOC"); if (jsonarr != null) { for (int j = 0; j < jsonarr.length(); j++) { alTOC.add(jsonarr.getString(j)); } onerecordattach.put("TOC", alTOC); } } if (!jsonAttach.isNull("Preview")) { ArrayList alPreview = new ArrayList(); JSONArray jsonarr = (JSONArray) jsonAttach.get("Preview"); if (jsonarr != null) { for (int j = 0; j < jsonarr.length(); j++) { alPreview.add(jsonarr.getString(j)); } onerecordattach.put("Preview", alPreview); } } if (!jsonAttach.isNull("FullView")) { ArrayList alFullView = new ArrayList(); JSONArray jsonarr = (JSONArray) jsonAttach.get("FullView"); if (jsonarr != null) { for (int j = 0; j < jsonarr.length(); j++) { alFullView.add(jsonarr.getString(j)); } onerecordattach.put("FullView", alFullView); } } if (!jsonAttach.isNull("Attachment")) { ArrayList alAttachment = new ArrayList(); JSONArray jsonarr = (JSONArray) jsonAttach.get("Attachment"); if (jsonarr != null) { for (int j = 0; j < jsonarr.length(); j++) { alAttachment.add(jsonarr.getString(j)); } onerecordattach.put("Attachment", alAttachment); } } if (onerecordattach != null && !onerecordattach.isEmpty()) { h4.put("dAttachment", onerecordattach); } } } svF.setHashSing(h4); System.out.println("hash tabel values*************************"); Enumeration enumx = h4.keys(); while (enumx.hasMoreElements()) { String key = enumx.nextElement().toString(); System.out.println("Key: " + key + "-----value: " + h4.get(key)); } System.out.println("********************************************"); } catch (Exception e) { e.printStackTrace(); } } } } else if (svF.getExportRec() != null && svF.getExportRec().equals("export")) { svF.setExportRec(null); vecThisPage = (java.util.Vector) session.getAttribute("SingleViewExport"); String format = svF.getSf(); if (format.equals("marc")) { String marc = opacUt.getDetailsForMultiRecordViewMARC(vecThisPage); svF.setDisplayFormat(marc); session.setAttribute("RecordDisplay", marc); forward = "RecordFormat"; } else if (format.equals("marcXml")) { String marcXML = opacUt.getDetailsForMultiRecordViewMARCXML(vecThisPage); svF.setDisplayFormat(marcXML); response.setContentType("text/xml"); session.setAttribute("RecordDisplay", marcXML); forward = "RecordFormat"; } else if (format.equals("mods")) { String mods = opacUt.getDetailsForMultiRecordViewMODS(vecThisPage); svF.setDisplayFormat(mods); session.setAttribute("RecordDisplay", mods); forward = "RecordFormat"; } else if (format.equals("dc")) { String dc = opacUt.getDetailsForMultiRecordViewDublinCore(vecThisPage); svF.setDisplayFormat(dc); session.setAttribute("RecordDisplay", dc); forward = "RecordFormat"; } else if (format.equals("agris")) { String agr = opacUt.getDetailsForMultiRecordViewAgris(vecThisPage); svF.setDisplayFormat(agr); session.setAttribute("RecordDisplay", agr); forward = "RecordFormat"; } else if (format.equals("text")) { java.util.Vector vecTextDis = new java.util.Vector(); for (int i2 = 0; i2 < vecThisPage.size(); i2 = i2 + 2) { java.util.Hashtable hash1 = opacUt.getDetailsForSingleCatalogueRecord(new Integer(vecThisPage.elementAt(i2).toString()).intValue(), new Integer(vecThisPage.elementAt(i2 + 1).toString()).intValue()); aportal.view.ISBDView fullView = new aportal.view.ISBDView(); java.util.Hashtable hashCit = fullView.getView(hash1); vecTextDis.addElement(hashCit); forward = "RecordFormatText"; } session.setAttribute("RecordTextDisplay", vecTextDis); if (svF.getPs() != null && svF.getPs().equals("email")) { boolean flag = false; if (svF.getEmail() != null && !(svF.getEmail().equals(""))) { String emailId = svF.getEmail(); try { String sessionid = request.getSession().getId(); java.net.URL url = new java.net.URL("http://localhost:" + request.getServerPort() + "/newgenlibctxt/jsp/aportal/cataloguing/RecordDisplayText.jsp;jsessionid=" + sessionid); java.net.URLConnection urlCon = url.openConnection(); java.io.InputStream is = urlCon.getInputStream(); String htmlContent = ""; java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(is)); String line = ""; while ((line = br.readLine()) != null) { htmlContent = htmlContent + line; } String[] emailids = { emailId }; int status = SendEmail.getInstance().sendMail(emailids, "OPAC results", htmlContent, "html"); if (status == 0) flag = true; else flag = false; } catch (Exception exp) { exp.printStackTrace(); } } String mailMessage = "The selected records have been successfully mailed to " + svF.getEmail(); if (flag == false) { mailMessage = "<h4><p>The selected records could not be mailed to " + svF.getEmail() + " These might be the possible reasons.</p></h4>" + "<h5><ol> <li>The email id entered is not a valid one</font></li>" + "<li>The email id domain might not be in the list of allowed recipient hosts</li>" + "<li>There might a error in connectivity to the mail server</li></ol></h5>" + "<h4><p>Please contact the Network Administrator </p></h4>"; } session.setAttribute("MailStatus", mailMessage); forward = "SendEmail"; } } } String version = ejb.bprocess.util.StaticValues.getInstance().getVersion(); if (version != null && !version.equals("")) { svF.setVersion(version); } if (session.getAttribute("ClassNoForwarded") != null) { session.removeAttribute("ClassNoForwarded"); } return mapping.findForward(forward); }
Code Sample 2:
public static String uploadArticleMedia(String localPath, String articleImageName, String year, String month, String day, DataStore db, HttpSession session) { CofaxToolsUser user = (CofaxToolsUser) session.getAttribute("user"); if (!localPath.endsWith(File.separator)) { localPath += File.separator; } FTPClient ftp = new FTPClient(); String liveFTPLogin = (String) user.workingPubConfigElementsHash.get("LIVEFTPLOGIN"); String liveFTPPassword = (String) user.workingPubConfigElementsHash.get("LIVEFTPPASSWORD"); String liveImagesServer = (String) user.workingPubConfigElementsHash.get("LIVEFTPSERVER"); String liveImagesFolder = (String) user.workingPubConfigElementsHash.get("LIVEIMAGESFOLDER"); if (!liveImagesFolder.endsWith("/")) { liveImagesFolder = liveImagesFolder + "/"; } String liveImagesYearFolder = ""; String liveImagesMonthFolder = ""; String fileLocation = ""; fileLocation += "/" + year + "/" + month + "/" + day; liveImagesYearFolder = liveImagesFolder + year; liveImagesMonthFolder = (liveImagesYearFolder + "/" + month); liveImagesFolder = (liveImagesMonthFolder + "/" + day); CofaxToolsUtil.log("CofaxToolsFTP: liveImagesServer: " + liveImagesServer); CofaxToolsUtil.log("CofaxToolsFTP: liveImagesFolder: " + liveImagesFolder); boolean stored = false; ArrayList servers = splitServers(liveImagesServer); for (int count = 0; count < servers.size(); count++) { String server = (String) servers.get(count); try { int reply; ftp.connect(server); CofaxToolsUtil.log("CofaxToolsFTP: uploadArticleMedia connecting to server : " + server); CofaxToolsUtil.log("CofaxToolsFTP: uploadArticleMedia results: " + ftp.getReplyString()); CofaxToolsUtil.log(ftp.getReplyString()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return ("CofaxToolsFTP uploadArticleMedia ERROR: FTP server refused connection."); } else { ftp.login(liveFTPLogin, liveFTPPassword); } try { ftp.setFileType(FTP.IMAGE_FILE_TYPE); InputStream input; CofaxToolsUtil.log("CofaxToolsFTP: opening file stream: " + localPath + articleImageName); input = new FileInputStream(localPath + articleImageName); CofaxToolsUtil.log("CofaxToolsFTP: attempting to change working directory to: " + liveImagesFolder); boolean changed = ftp.changeWorkingDirectory(liveImagesFolder); CofaxToolsUtil.log("CofaxToolsFTP: uploadArticleMedia results: " + changed); if (changed == false) { CofaxToolsUtil.log("CofaxToolsFTP: uploadArticleMedia attempting to create directory :" + liveImagesFolder); boolean newDirYear = ftp.makeDirectory(liveImagesYearFolder); boolean newDirMonth = ftp.makeDirectory(liveImagesMonthFolder); boolean newDir = ftp.makeDirectory(liveImagesFolder); CofaxToolsUtil.log("CofaxToolsFTP: uploadArticleMedia results: YearDir: " + newDirYear + " MonthDir: " + newDirMonth + " finalDir: " + newDir); changed = ftp.changeWorkingDirectory(liveImagesFolder); } if (changed) { CofaxToolsUtil.log("CofaxToolsFTP: storing " + articleImageName + " to " + liveImagesFolder); stored = ftp.storeFile(articleImageName, input); } else { CofaxToolsUtil.log("CofaxToolsFTP: failed changing: " + liveImagesFolder); } if (stored) { CofaxToolsUtil.log("CofaxToolsFTP: Successfully ftped file."); } else { CofaxToolsUtil.log("CofaxToolsFTP: Failed ftping file."); } input.close(); ftp.logout(); ftp.disconnect(); } catch (org.apache.commons.net.io.CopyStreamException e) { CofaxToolsUtil.log("CofaxToolsFTP: Failed ftping file." + e.toString()); CofaxToolsUtil.log("CofaxToolsFTP: " + e.getIOException().toString()); return ("Cannot upload file " + liveImagesFolder + "/" + articleImageName); } catch (IOException e) { CofaxToolsUtil.log("CofaxToolsFTP: Failed ftping file." + e.toString()); return ("Cannot upload file " + liveImagesFolder + "/" + articleImageName); } catch (Exception e) { CofaxToolsUtil.log("CofaxToolsFTP: Failed ftping file." + e.toString()); return ("Cannot upload file " + liveImagesFolder + "/" + articleImageName); } } catch (IOException e) { return ("Could not connect to server: " + e); } } return (""); } |
00
| Code Sample 1:
private boolean enregistreToi() { PrintWriter lEcrivain; String laDest = "./img_types/" + sonImage; if (!new File("./img_types").exists()) { new File("./img_types").mkdirs(); } try { FileChannel leFicSource = new FileInputStream(sonFichier).getChannel(); FileChannel leFicDest = new FileOutputStream(laDest).getChannel(); leFicSource.transferTo(0, leFicSource.size(), leFicDest); leFicSource.close(); leFicDest.close(); lEcrivain = new PrintWriter(new FileWriter(new File("bundll/types.jay"), true)); lEcrivain.println(sonNom); lEcrivain.println(sonImage); if (sonOptionRadio1.isSelected()) { lEcrivain.println("0:?"); } if (sonOptionRadio2.isSelected()) { lEcrivain.println("1:" + JOptionPane.showInputDialog(null, "Vous avez choisis de rendre ce terrain difficile � franchir.\nVeuillez en indiquer la raison.", "Demande de pr�cision", JOptionPane.INFORMATION_MESSAGE)); } if (sonOptionRadio3.isSelected()) { lEcrivain.println("2:?"); } lEcrivain.close(); return true; } catch (Exception lException) { return false; } }
Code Sample 2:
public byte[] getEncoded(X509Certificate checkCert, X509Certificate rootCert, String url) { try { if (checkCert == null || rootCert == null) return null; if (url == null) { url = PdfPKCS7.getOCSPURL(checkCert); } if (url == null) return null; OCSPReq request = generateOCSPRequest(rootCert, checkCert.getSerialNumber()); byte[] array = request.getEncoded(); URL urlt = new URL(url); HttpURLConnection con = (HttpURLConnection) urlt.openConnection(); con.setRequestProperty("Content-Type", "application/ocsp-request"); con.setRequestProperty("Accept", "application/ocsp-response"); con.setDoOutput(true); OutputStream out = con.getOutputStream(); DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(out)); dataOut.write(array); dataOut.flush(); dataOut.close(); if (con.getResponseCode() / 100 != 2) { throw new IOException(MessageLocalization.getComposedMessage("invalid.http.response.1", con.getResponseCode())); } InputStream in = (InputStream) con.getContent(); OCSPResp ocspResponse = new OCSPResp(RandomAccessFileOrArray.InputStreamToArray(in)); if (ocspResponse.getStatus() != 0) throw new IOException(MessageLocalization.getComposedMessage("invalid.status.1", ocspResponse.getStatus())); BasicOCSPResp basicResponse = (BasicOCSPResp) ocspResponse.getResponseObject(); if (basicResponse != null) { SingleResp[] responses = basicResponse.getResponses(); if (responses.length == 1) { SingleResp resp = responses[0]; Object status = resp.getCertStatus(); if (status == CertificateStatus.GOOD) { return basicResponse.getEncoded(); } else if (status instanceof org.bouncycastle.ocsp.RevokedStatus) { throw new IOException(MessageLocalization.getComposedMessage("ocsp.status.is.revoked")); } else { throw new IOException(MessageLocalization.getComposedMessage("ocsp.status.is.unknown")); } } } } catch (Exception ex) { if (LOGGER.isLogging(Level.ERROR)) LOGGER.error("OcspClientBouncyCastle", ex); } return null; } |
11
| Code Sample 1:
public static void downloadJars(IProject project, String repositoryUrl, String jarDirectory, String[] jars) { try { File tmpFile = null; for (String jar : jars) { try { tmpFile = File.createTempFile("tmpPlugin_", ".zip"); URL url = new URL(repositoryUrl + jarDirectory + jar); String destFilename = new File(url.getFile()).getName(); File destFile = new File(project.getLocation().append("lib").append(jarDirectory).toFile(), destFilename); InputStream inputStream = null; FileOutputStream outputStream = null; try { URLConnection urlConnection = url.openConnection(); inputStream = urlConnection.getInputStream(); outputStream = new FileOutputStream(tmpFile); IOUtils.copy(inputStream, outputStream); } finally { if (outputStream != null) { outputStream.close(); } if (inputStream != null) { inputStream.close(); } } FileUtils.copyFile(tmpFile, destFile); } finally { if (tmpFile != null) { tmpFile.delete(); } } } } catch (Exception ex) { ex.printStackTrace(); } }
Code Sample 2:
private void copia(FileInputStream input, FileOutputStream output) throws ErrorException { if (input == null || output == null) { throw new ErrorException("Param null"); } FileChannel inChannel = input.getChannel(); FileChannel outChannel = output.getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); inChannel.close(); outChannel.close(); } catch (IOException e) { throw new ErrorException("Casino nella copia del file"); } } |
11
| Code Sample 1:
@Override public void process(HttpServletRequest request, HttpServletResponse response) throws Exception { String userAgentGroup = processUserAgent(request); final LiwenxRequest lRequest = new LiwenxRequestImpl(request, response, messageSource, userAgentGroup); Locator loc = router.route(lRequest); if (loc instanceof RedirectLocator) { response.sendRedirect(((RedirectLocator) loc).getPage()); } else { ((AbstractLiwenxRequest) lRequest).setRequestedLocator(loc); try { LiwenxResponse resp = processPage(lRequest, lRequest.getRequestedLocator(), maxRedirections); processHeaders(resp, response); processCookies(resp, response); if (resp instanceof ExternalRedirectionResponse) { response.sendRedirect(((ExternalRedirectionResponse) resp).getRedirectTo()); } else if (resp instanceof BinaryResponse) { BinaryResponse bResp = (BinaryResponse) resp; response.setContentType(bResp.getMimeType().toString()); IOUtils.copy(bResp.getInputStream(), response.getOutputStream()); } else if (resp instanceof XmlResponse) { final Element root = ((XmlResponse) resp).getXml(); Document doc = root.getDocument(); if (doc == null) { doc = new Document(root); } final Locator l = lRequest.getCurrentLocator(); final Device device = l.getDevice(); response.setContentType(calculateContentType(device)); response.setCharacterEncoding(encoding); if (device == Device.HTML) { view.processView(doc, l.getLocale(), userAgentGroup, response.getWriter()); } else { Serializer s = new Serializer(response.getOutputStream(), encoding); s.write(doc); } } } catch (PageNotFoundException e) { response.sendError(HttpServletResponse.SC_NOT_FOUND); } catch (TooManyRedirectionsException e) { throw e; } catch (Exception e) { throw e; } } }
Code Sample 2:
public static void main(String[] args) throws IOException { long start = System.currentTimeMillis(); FileResourceManager frm = CommonsTransactionContext.configure(new File("C:/tmp")); try { frm.start(); } catch (ResourceManagerSystemException e) { throw new RuntimeException(e); } FileInputStream is = new FileInputStream("C:/Alfresco/WCM_Eval_Guide2.0.pdf"); CommonsTransactionOutputStream os = new CommonsTransactionOutputStream(new Ownerr()); IOUtils.copy(is, os); IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); try { frm.stop(FileResourceManager.SHUTDOWN_MODE_NORMAL); } catch (ResourceManagerSystemException e) { throw new RuntimeException(e); } System.out.println(System.currentTimeMillis() - start); } |
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 DataFileType[] getDataFiles(Collection<ContentToSend> contentsToSend) { DataFileType[] files = new DataFileType[contentsToSend.size()]; int fileIndex = 0; for (ContentToSend contentToSend : contentsToSend) { DataFileType dataFile = DataFileType.Factory.newInstance(); dataFile.setFilename(contentToSend.getFileName()); dataFile.setId("D" + fileIndex); dataFile.setMimeType(contentToSend.getMimeType()); dataFile.setContentType(DataFileType.ContentType.EMBEDDED_BASE_64); final StringWriter stringWriter = new StringWriter(); final OutputStream encodeStream = Base64.newEncoder(stringWriter, 0, null); final InputStream is = contentToSend.getInputStream(); try { long sizeCopied = IOUtils.copyLarge(is, encodeStream); dataFile.setSize(BigDecimal.valueOf(sizeCopied)); } catch (IOException e) { throw new RuntimeException("Failed to get input to the file to be sent", e); } finally { IOUtils.closeQuietly(encodeStream); IOUtils.closeQuietly(is); } dataFile.setStringValue(stringWriter.toString()); files[fileIndex++] = dataFile; } return files; } |
00
| Code Sample 1:
private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } }
Code Sample 2:
public synchronized boolean copyTmpDataFile(String fpath) throws IOException { if (tmpDataOutput != null) tmpDataOutput.close(); tmpDataOutput = null; if (tmpDataFile == null) return false; File nfp = new File(fpath); if (nfp.exists()) nfp.delete(); FileInputStream src = new FileInputStream(tmpDataFile); FileOutputStream dst = new FileOutputStream(nfp); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = src.read(buffer)) != -1) dst.write(buffer, 0, bytesRead); src.close(); dst.close(); return true; } |
11
| 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:
protected void assignListeners() { groupsList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent event) { refreshInfo(); } }); saveButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { JFileChooser fileDialog = new JFileChooser("."); fileDialog.setFileFilter(ReaderData.mkExtensionFileFilter(".grp", "Group Files")); int outcome = fileDialog.showSaveDialog((Frame) null); if (outcome == JFileChooser.APPROVE_OPTION) { assert (fileDialog.getCurrentDirectory() != null); assert (fileDialog.getSelectedFile() != null); String fileName = fileDialog.getCurrentDirectory().toString() + File.separator + fileDialog.getSelectedFile().getName(); try { PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileName))); ReaderWriterGroup.write(out, writer); System.err.println("Wrote groups informations to output '" + fileName + "'."); out.close(); } catch (IOException e) { System.err.println("error while writing (GroupManager.saveClt):"); e.printStackTrace(); } } else if (outcome == JFileChooser.CANCEL_OPTION) { } } }); loadButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { JFileChooser fileDialog = new JFileChooser("."); fileDialog.setFileFilter(ReaderData.mkExtensionFileFilter(".grp", "Group Files")); int outcome = fileDialog.showOpenDialog((Frame) null); if (outcome == JFileChooser.APPROVE_OPTION) { assert (fileDialog.getCurrentDirectory() != null); assert (fileDialog.getSelectedFile() != null); String fileName = fileDialog.getCurrentDirectory().toString() + File.separator + fileDialog.getSelectedFile().getName(); BufferedReader fileReader = null; try { fileReader = new BufferedReader(new FileReader(fileName)); ReaderWriterGroup.read(fileReader, writer); fileReader.close(); } catch (Exception e) { System.err.println("Exception while reading from file '" + fileName + "'."); System.err.println(e); } } else if (outcome == JFileChooser.CANCEL_OPTION) { } } }); ItemListener propItemListener = new ItemListener() { @Override public void itemStateChanged(ItemEvent event) { int[] indices = groupsList.getSelectedIndices(); for (int index : indices) { Group group = getGroupFromListIndex(index); if (group != null) { if (event.getSource() instanceof JComboBox) { JComboBox eventSource = (JComboBox) event.getSource(); if (eventSource == colorComboBox) { Color color = colorComboBox.getSelectedColor(); assert (color != null); group.setColor(color); shapeComboBox.setColor(color); } else if (eventSource == shapeComboBox) { Shape shape = shapeComboBox.getSelectedShape(); assert (shape != null); group.setShape(shape); } } else if (event.getSource() instanceof JCheckBox) { JCheckBox eventSource = (JCheckBox) event.getSource(); if (eventSource == showGroupCheckBox) { group.visible = showGroupCheckBox.isSelected(); } else if (eventSource == showGraphicInfoCheckBox) { group.info = showGraphicInfoCheckBox.isSelected(); } } } } graph.notifyAboutGroupsChange(null); } }; colorComboBox.addItemListener(propItemListener); shapeComboBox.addItemListener(propItemListener); showGroupCheckBox.addItemListener(propItemListener); showGraphicInfoCheckBox.addItemListener(propItemListener); showGroupfreeNodesCheckBox.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent event) { graph.getGroup(0).visible = showGroupfreeNodesCheckBox.isSelected(); graph.notifyAboutGroupsChange(null); } }); ActionListener propActionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent event) { JButton botton = (JButton) event.getSource(); Group group = getGroupFromListIndex(groupsList.getSelectedIndex()); if (group != null) { for (GraphVertex graphVertex : group) { if (botton == showLabelsButton) { graphVertex.setShowName(NameVisibility.Priority.GROUPS, true); } else if (botton == hideLabelsButton) { graphVertex.setShowName(NameVisibility.Priority.GROUPS, false); } } graph.notifyAboutGroupsChange(null); } } }; showLabelsButton.addActionListener(propActionListener); hideLabelsButton.addActionListener(propActionListener); newButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { String newGroupName = JOptionPane.showInputDialog(null, "Enter a name", "Name of the new group", JOptionPane.QUESTION_MESSAGE); if (newGroupName != null) { if (graph.getGroup(newGroupName) == null) { graph.addGroup(new Group(newGroupName, graph)); } } } }); editButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { Group group = getGroupFromListIndex(groupsList.getSelectedIndex()); if (group != null) { DialogEditGroup dialog = new DialogEditGroup(graph, group); dialog.setModal(true); dialog.setVisible(true); } } }); deleteButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { int index = groupsList.getSelectedIndex(); if (index > 0 && index < graph.getNumberOfGroups() - 1) { graph.removeGroup(index); } } }); upButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { int index = groupsList.getSelectedIndex(); if (index < graph.getNumberOfGroups() - 1) { graph.moveGroupUp(index); groupsList.setSelectedIndex(index - 1); } } }); downButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { int index = groupsList.getSelectedIndex(); if (index < graph.getNumberOfGroups() - 1) { graph.moveGroupDown(index); groupsList.setSelectedIndex(index + 1); } } }); } |
11
| Code Sample 1:
public void setTableBraille(String tableBraille, boolean sys) { fiConf.setProperty(OptNames.fi_braille_table, tableBraille); fiConf.setProperty(OptNames.fi_is_sys_braille_table, Boolean.toString(sys)); FileChannel in = null; FileChannel out = null; try { String fichTable; if (!(tableBraille.endsWith(".ent"))) { tableBraille = tableBraille + ".ent"; } if (sys) { fichTable = ConfigNat.getInstallFolder() + "xsl/tablesBraille/" + tableBraille; } else { fichTable = ConfigNat.getUserBrailleTableFolder() + tableBraille; } in = new FileInputStream(fichTable).getChannel(); out = new FileOutputStream(getUserBrailleTableFolder() + "Brltab.ent").getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
static void copy(String scr, String dest) throws IOException { InputStream in = null; OutputStream out = null; try { in = new FileInputStream(scr); out = new FileOutputStream(dest); byte[] buf = new byte[1024]; int n; while ((n = in.read(buf)) >= 0) out.write(buf, 0, n); } finally { closeIgnoringException(in); closeIgnoringException(out); } } |
11
| Code Sample 1:
private void prepareQueryResultData(ZipEntryRef zer, String nodeDir, String reportDir, Set<ZipEntryRef> statusZers) throws Exception { String jobDir = nodeDir + File.separator + "job_" + zer.getUri(); if (!WorkDirectory.isWorkingDirectoryValid(jobDir)) { throw new Exception("Cannot acces to " + jobDir); } File f = new File(jobDir + File.separator + "result.xml"); if (!f.exists() || !f.isFile() || !f.canRead()) { throw new Exception("Cannot acces to result file " + f.getAbsolutePath()); } String fcopyName = reportDir + File.separator + zer.getName() + ".xml"; BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fcopyName)); IOUtils.copy(bis, bos); bis.close(); bos.close(); zer.setUri(fcopyName); f = new File(jobDir + File.separator + "status.xml"); if (!f.exists() || !f.isFile() || !f.canRead()) { throw new Exception("Cannot acces to status file " + f.getAbsolutePath()); } fcopyName = reportDir + File.separator + zer.getName() + "_status.xml"; bis = new BufferedInputStream(new FileInputStream(f)); bos = new BufferedOutputStream(new FileOutputStream(fcopyName)); IOUtils.copy(bis, bos); bis.close(); bos.close(); statusZers.add(new ZipEntryRef(ZipEntryRef.SINGLE_FILE, zer.getName(), fcopyName, ZipEntryRef.WITH_REL)); }
Code Sample 2:
@Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String fileName = request.getParameter("tegsoftFileName"); if (fileName.startsWith("Tegsoft_BACKUP_")) { fileName = fileName.substring("Tegsoft_BACKUP_".length()); String targetFileName = "/home/customer/" + fileName; response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); FileInputStream is = new FileInputStream(targetFileName); IOUtils.copy(is, response.getOutputStream()); is.close(); return; } if (fileName.equals("Tegsoft_ASTMODULES")) { String targetFileName = tobeHome + "/setup/Tegsoft_ASTMODULES.tgz"; response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); FileInputStream is = new FileInputStream(targetFileName); IOUtils.copy(is, response.getOutputStream()); is.close(); return; } if (fileName.equals("Tegsoft_ASTSBIN")) { String targetFileName = tobeHome + "/setup/Tegsoft_ASTSBIN.tgz"; response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); FileInputStream is = new FileInputStream(targetFileName); IOUtils.copy(is, response.getOutputStream()); is.close(); return; } if (!fileName.startsWith("Tegsoft_")) { return; } if (!fileName.endsWith(".zip")) { return; } if (fileName.indexOf("_") < 0) { return; } fileName = fileName.substring(fileName.indexOf("_") + 1); if (fileName.indexOf("_") < 0) { return; } String fileType = fileName.substring(0, fileName.indexOf("_")); String destinationFileName = tobeHome + "/setup/Tegsoft_" + fileName; if (!new File(destinationFileName).exists()) { if ("FORMS".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/forms", tobeHome + "/setup/Tegsoft_" + fileName); } else if ("IMAGES".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/image", tobeHome + "/setup/Tegsoft_" + fileName); } else if ("VIDEOS".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/videos", tobeHome + "/setup/Tegsoft_" + fileName); } else if ("TEGSOFTJARS".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/WEB-INF/lib/", tobeHome + "/setup/Tegsoft_" + fileName, "Tegsoft", "jar"); } else if ("TOBEJARS".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/WEB-INF/lib/", tobeHome + "/setup/Tegsoft_" + fileName, "Tobe", "jar"); } else if ("ALLJARS".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/WEB-INF/lib/", tobeHome + "/setup/Tegsoft_" + fileName); } else if ("DB".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/sql", tobeHome + "/setup/Tegsoft_" + fileName); } else if ("CONFIGSERVICE".equals(fileType)) { FileUtil.createZipPackage("/tegsoft/src/java/TegsoftTelecom/configFiles/init.d/", tobeHome + "/setup/Tegsoft_" + fileName, "tegsoft", null); } else if ("CONFIGSCRIPTS".equals(fileType)) { FileUtil.createZipPackage("/tegsoft/src/java/TegsoftTelecom/configFiles/root/", tobeHome + "/setup/Tegsoft_" + fileName, "tegsoft", null); } else if ("CONFIGFOP".equals(fileType)) { FileUtil.createZipPackage("/tegsoft/src/java/TegsoftTelecom/configFiles/fop/", tobeHome + "/setup/Tegsoft_" + fileName); } else if ("CONFIGASTERISK".equals(fileType)) { FileUtil.createZipPackage("/tegsoft/src/java/TegsoftTelecom/configFiles/asterisk/", tobeHome + "/setup/Tegsoft_" + fileName); } } response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); FileInputStream is = new FileInputStream(destinationFileName); IOUtils.copy(is, response.getOutputStream()); is.close(); } catch (Exception ex) { ex.printStackTrace(); } } |
00
| Code Sample 1:
public String generateMappackMD5(File mapPackFile) throws IOException, NoSuchAlgorithmException { ZipFile zip = new ZipFile(mapPackFile); try { Enumeration<? extends ZipEntry> entries = zip.entries(); MessageDigest md5Total = MessageDigest.getInstance("MD5"); MessageDigest md5 = MessageDigest.getInstance("MD5"); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) continue; String name = entry.getName(); if (name.toUpperCase().startsWith("META-INF")) continue; md5.reset(); InputStream in = zip.getInputStream(entry); byte[] data = Utilities.getInputBytes(in); in.close(); byte[] digest = md5.digest(data); log.trace("Hashsum " + Hex.encodeHexString(digest) + " includes \"" + name + "\""); md5Total.update(digest); md5Total.update(name.getBytes()); } String md5sum = Hex.encodeHexString(md5Total.digest()); log.trace("md5sum of " + mapPackFile.getName() + ": " + md5sum); return md5sum; } finally { zip.close(); } }
Code Sample 2:
public void sorter() { String inputLine1, inputLine2; String epiNames[] = new String[1000]; String epiEpisodes[] = new String[1000]; int lineCounter = 0; try { String pluginDir = pluginInterface.getPluginDirectoryName(); String eplist_file = pluginDir + System.getProperty("file.separator") + "EpisodeList.txt"; File episodeList = new File(eplist_file); if (!episodeList.isFile()) { episodeList.createNewFile(); } final BufferedReader in = new BufferedReader(new FileReader(episodeList)); while ((inputLine1 = in.readLine()) != null) { if ((inputLine2 = in.readLine()) != null) { epiNames[lineCounter] = inputLine1; epiEpisodes[lineCounter] = inputLine2; lineCounter++; } } in.close(); int epiLength = epiNames.length; for (int i = 0; i < (lineCounter); i++) { for (int j = 0; j < (lineCounter - 1); j++) { if (epiNames[j].compareToIgnoreCase(epiNames[j + 1]) > 0) { String temp = epiNames[j]; epiNames[j] = epiNames[j + 1]; epiNames[j + 1] = temp; String temp2 = epiEpisodes[j]; epiEpisodes[j] = epiEpisodes[j + 1]; epiEpisodes[j + 1] = temp2; } } } File episodeList2 = new File(eplist_file); BufferedWriter bufWriter = new BufferedWriter(new FileWriter(episodeList2)); for (int i = 0; i <= lineCounter; i++) { if (epiNames[i] == null) { break; } bufWriter.write(epiNames[i] + "\n"); bufWriter.write(epiEpisodes[i] + "\n"); } bufWriter.close(); } catch (IOException e) { e.printStackTrace(); } } |
11
| Code Sample 1:
public static void copyFile(File in, File out) { int len; byte[] buffer = new byte[1024]; try { FileInputStream fin = new FileInputStream(in); FileOutputStream fout = new FileOutputStream(out); while ((len = fin.read(buffer)) >= 0) fout.write(buffer, 0, len); fin.close(); fout.close(); } catch (IOException ex) { } }
Code Sample 2:
public void copy(final File source, final File target) throws FileSystemException { LogHelper.logMethod(log, toObjectString(), "copy(), source = " + source + ", target = " + target); FileChannel sourceChannel = null; FileChannel targetChannel = null; try { sourceChannel = new FileInputStream(source).getChannel(); targetChannel = new FileOutputStream(target).getChannel(); sourceChannel.transferTo(0L, sourceChannel.size(), targetChannel); log.info("Copied " + source + " to " + target); } catch (FileNotFoundException e) { throw new FileSystemException("Unexpected FileNotFoundException while copying a file", e); } catch (IOException e) { throw new FileSystemException("Unexpected IOException while copying a file", e); } finally { if (sourceChannel != null) { try { sourceChannel.close(); } catch (IOException e) { log.error("IOException during source channel close after copy", e); } } if (targetChannel != null) { try { targetChannel.close(); } catch (IOException e) { log.error("IOException during target channel close after copy", e); } } } } |
11
| Code Sample 1:
public boolean copyDirectoryTree(File srcPath, File dstPath) { try { if (srcPath.isDirectory()) { if (!dstPath.exists()) dstPath.mkdir(); String files[] = srcPath.list(); for (int i = 0; i < files.length; i++) copyDirectoryTree(new File(srcPath, files[i]), new File(dstPath, files[i])); } else { if (!srcPath.exists()) { errMsgLog += "copyDirectoryTree I/O error from '" + srcPath + "' does not exist.\n"; lastErrMsgLog = errMsgLog; return (false); } else { InputStream in = new FileInputStream(srcPath); OutputStream out = new FileOutputStream(dstPath); byte[] buf = new byte[10240]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); } } return (true); } catch (Exception e) { errMsgLog += "copyDirectoryTree I/O error from '" + srcPath.getName() + "' to '" + dstPath.getName() + "\n " + e + "\n"; lastErrMsgLog = errMsgLog; return (false); } }
Code Sample 2:
public boolean restore(File directory) { log.debug("restore file from directory " + directory.getAbsolutePath()); try { if (!directory.exists()) return false; String[] operationFileNames = directory.list(); if (operationFileNames.length < 6) { log.error("Only " + operationFileNames.length + " files found in directory " + directory.getAbsolutePath()); return false; } int fileCount = 0; for (int i = 0; i < operationFileNames.length; i++) { if (!operationFileNames[i].toUpperCase().endsWith(".XML")) continue; log.debug("found file: " + operationFileNames[i]); fileCount++; File filein = new File(directory.getAbsolutePath() + File.separator + operationFileNames[i]); File fileout = new File(operationsDirectory + File.separator + operationFileNames[i]); FileReader in = new FileReader(filein); FileWriter out = new FileWriter(fileout); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } if (fileCount < 6) return false; return true; } catch (Exception e) { log.error("Exception while restoring operations files, may not be complete: " + e); return false; } } |
11
| Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.addHeader("Cache-Control", "max-age=" + Constants.HTTP_CACHE_SECONDS); String uuid = req.getRequestURI().substring(req.getRequestURI().indexOf(Constants.SERVLET_FULL_PREFIX) + Constants.SERVLET_FULL_PREFIX.length() + 1); boolean notScale = ClientUtils.toBoolean(req.getParameter(Constants.URL_PARAM_NOT_SCALE)); ServletOutputStream os = resp.getOutputStream(); if (uuid != null && !"".equals(uuid)) { try { String mimetype = fedoraAccess.getMimeTypeForStream(uuid, FedoraUtils.IMG_FULL_STREAM); if (mimetype == null) { mimetype = "image/jpeg"; } ImageMimeType loadFromMimeType = ImageMimeType.loadFromMimeType(mimetype); if (loadFromMimeType == ImageMimeType.JPEG || loadFromMimeType == ImageMimeType.PNG) { StringBuffer sb = new StringBuffer(); sb.append(config.getFedoraHost()).append("/objects/").append(uuid).append("/datastreams/IMG_FULL/content"); InputStream is = RESTHelper.get(sb.toString(), config.getFedoraLogin(), config.getFedoraPassword(), false); if (is == null) { return; } try { IOUtils.copyStreams(is, os); } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Unable to open full image.", e); } finally { os.flush(); if (is != null) { try { is.close(); } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Unable to close stream.", e); } finally { is = null; } } } } else { Image rawImg = KrameriusImageSupport.readImage(uuid, FedoraUtils.IMG_FULL_STREAM, this.fedoraAccess, 0, loadFromMimeType); BufferedImage scaled = null; if (!notScale) { scaled = KrameriusImageSupport.getSmallerImage(rawImg, 1250, 1000); } else { scaled = KrameriusImageSupport.getSmallerImage(rawImg, 2500, 2000); } KrameriusImageSupport.writeImageToStream(scaled, "JPG", os); resp.setContentType(ImageMimeType.JPEG.getValue()); resp.setStatus(HttpURLConnection.HTTP_OK); } } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Unable to open full image.", e); } catch (XPathExpressionException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Unable to create XPath expression.", e); } finally { os.flush(); } } } |
00
| Code Sample 1:
public static void parseRDFXML(String url, StatementHandler handler) throws IOException { ARP parser = new ARP(); parser.getHandlers().setStatementHandler(handler); URLConnection conn = new URL(url).openConnection(); String encoding = conn.getContentEncoding(); InputStream in = null; try { in = conn.getInputStream(); if (encoding == null) parser.load(in, url); else parser.load(new InputStreamReader(in, encoding), url); in.close(); } catch (org.xml.sax.SAXException e) { throw new OntopiaRuntimeException(e); } finally { if (in != null) in.close(); } }
Code Sample 2:
public void checkFilesAndCopyValid(String filename) { downloadResults(); loadResults(); File tmpFolderF = new File(tmpFolder); deleteFileFromTMPFolder(tmpFolderF); ZipReader zr = new ZipReader(); zr.UnzipFile(filename); try { LogManager.getInstance().log("Ov��uji odevzdan� soubory a kop�ruji validovan�:"); LogManager.getInstance().log(""); JAXBElement<?> element = ElementJAXB.getJAXBElement(); Ppa1VysledkyCviceniType pvct = (Ppa1VysledkyCviceniType) element.getValue(); File zipFolder = new File(tmpFolder).listFiles()[0].listFiles()[0].listFiles()[0]; File[] zipFolderList = zipFolder.listFiles(); for (File studentDirectory : zipFolderList) { if (studentDirectory.isDirectory()) { String osobniCisloZeSlozky = studentDirectory.getName().split("-")[0]; LogManager.getInstance().changeLog("Prov��ov�n� soubor� studenta s ��slem: " + osobniCisloZeSlozky); List<StudentType> students = (List<StudentType>) pvct.getStudent(); for (StudentType student : students) { if (student.getOsobniCislo().equals(osobniCisloZeSlozky)) { int pzp = student.getDomaciUlohy().getPosledniZpracovanyPokus().getCislo().intValue(); DomaciUlohyType dut = student.getDomaciUlohy(); ChybneOdevzdaneType chot = dut.getChybneOdevzdane(); ObjectFactory of = new ObjectFactory(); File[] pokusyDirectories = studentDirectory.listFiles(); NodeList souboryNL = result.getElementsByTagName("soubor"); int start = souboryNL.getLength() - 1; boolean samostatnaPrace = false; for (int i = (pokusyDirectories.length - 1); i >= 0; i--) { if ((pokusyDirectories[i].isDirectory()) && (pzp < Integer.parseInt(pokusyDirectories[i].getName().split("_")[1].trim()))) { File testedFile = pokusyDirectories[i].listFiles()[0]; if ((testedFile.exists()) && (testedFile.isFile())) { String[] partsOfFilename = testedFile.getName().split("_"); String osobniCisloZeSouboru = "", priponaSouboru = ""; String[] posledniCastSouboru = null; if (partsOfFilename.length == 4) { posledniCastSouboru = partsOfFilename[3].split("[.]"); osobniCisloZeSouboru = posledniCastSouboru[0]; if (posledniCastSouboru.length <= 1) priponaSouboru = ""; else priponaSouboru = posledniCastSouboru[1]; } String samostatnaPraceNazev = Konfigurace.getInstance().getSamostatnaPraceNazev(); List<SouborType> lst = chot.getSoubor(); if (testedFile.getName().startsWith(samostatnaPraceNazev)) { samostatnaPrace = true; } else { samostatnaPrace = false; if (partsOfFilename.length != 4) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("�patn� struktura jm�na souboru."); lst.add(st); continue; } else if (!testedFile.getName().startsWith("Ppa1_cv")) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("�patn� za��tek jm�na souboru."); lst.add(st); continue; } else if (!priponaSouboru.equals("java")) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("�patn� p��pona souboru."); lst.add(st); continue; } else if (!osobniCisloZeSouboru.equals(osobniCisloZeSlozky)) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("Nesouhlas� osobn� ��sla."); lst.add(st); continue; } else if (partsOfFilename[3].split("[.]").length > 2) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("V�ce p��pon souboru."); lst.add(st); continue; } else { long cisloCviceni, cisloUlohy; try { if (partsOfFilename[1].length() == 4) { String cisloS = partsOfFilename[1].substring(2); long cisloL = Long.parseLong(cisloS); cisloCviceni = cisloL; } else { throw new NumberFormatException(); } } catch (NumberFormatException e) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("Chyb� (nebo je chybn�) ��slo cvi�en�"); lst.add(st); continue; } try { if (partsOfFilename[2].length() > 0) { String cisloS = partsOfFilename[2]; long cisloL = Long.parseLong(cisloS); cisloUlohy = cisloL; } else { throw new NumberFormatException(); } } catch (NumberFormatException e) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("Chyb� (nebo je chybn�) ��slo �lohy"); lst.add(st); continue; } CislaUloh ci = new CislaUloh(); List<long[]> cviceni = ci.getSeznamCviceni(); boolean nalezenoCv = false, nalezenaUl = false; for (long[] c : cviceni) { if (c[0] == cisloCviceni) { for (int j = 1; j < c.length; j++) { if (c[j] == cisloUlohy) { nalezenaUl = true; break; } } nalezenoCv = true; break; } } if (!nalezenoCv) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("Neplatn� ��slo cvi�en�"); lst.add(st); continue; } if (!nalezenaUl) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("Neplatn� ��slo �lohy"); lst.add(st); continue; } } } } Calendar dateFromZipFile = null; File zipFile = new File(filename); if (zipFile.exists()) { String[] s = zipFile.getName().split("_"); if (s.length >= 3) { String[] date = s[1].split("-"), time = s[2].split("-"); dateFromZipFile = new GregorianCalendar(); dateFromZipFile.set(Integer.parseInt(date[0]), Integer.parseInt(date[1]) - 1, Integer.parseInt(date[2]), Integer.parseInt(time[0]), Integer.parseInt(time[1]), 0); } } boolean shodaJmenaSouboru = false; String vysledekValidaceSouboru = ""; for (int j = start; j >= 0; j--) { NodeList vlastnostiSouboruNL = souboryNL.item(j).getChildNodes(); for (int k = 0; k < vlastnostiSouboruNL.getLength(); k++) { if (vlastnostiSouboruNL.item(k).getNodeName().equals("cas")) { String[] obsahElementuCas = vlastnostiSouboruNL.item(k).getTextContent().split(" "); String[] datumZElementu = obsahElementuCas[0].split("-"), casZElementu = obsahElementuCas[1].split("-"); Calendar datumACasZElementu = new GregorianCalendar(); datumACasZElementu.set(Integer.parseInt(datumZElementu[0]), Integer.parseInt(datumZElementu[1]) - 1, Integer.parseInt(datumZElementu[2]), Integer.parseInt(casZElementu[0]), Integer.parseInt(casZElementu[1]), Integer.parseInt(casZElementu[2])); if ((dateFromZipFile != null) && (datumACasZElementu.compareTo(dateFromZipFile) > 0)) { shodaJmenaSouboru = false; break; } } if (vlastnostiSouboruNL.item(k).getNodeName().equals("nazev")) { shodaJmenaSouboru = vlastnostiSouboruNL.item(k).getTextContent().equals(testedFile.getName()); } if (vlastnostiSouboruNL.item(k).getNodeName().equals("vysledek")) { vysledekValidaceSouboru = vlastnostiSouboruNL.item(k).getTextContent(); } } if (shodaJmenaSouboru) { start = --j; break; } } if (shodaJmenaSouboru && !samostatnaPrace) { boolean odevzdanoVcas = false; String cisloCviceniS = testedFile.getName().split("_")[1].substring(2); int cisloCviceniI = Integer.parseInt(cisloCviceniS); String cisloUlohyS = testedFile.getName().split("_")[2]; int cisloUlohyI = Integer.parseInt(cisloUlohyS); List<CviceniType> lct = student.getDomaciUlohy().getCviceni(); for (CviceniType ct : lct) { if (ct.getCislo().intValue() == cisloCviceniI) { MezniTerminOdevzdaniVcasType mtovt = ct.getMezniTerminOdevzdaniVcas(); Calendar mtovGC = new GregorianCalendar(); mtovGC.set(mtovt.getDatum().getYear(), mtovt.getDatum().getMonth() - 1, mtovt.getDatum().getDay(), 23, 59, 59); Calendar fileTimeStamp = new GregorianCalendar(); fileTimeStamp.setTimeInMillis(testedFile.lastModified()); String[] datumSouboru = String.format("%tF", fileTimeStamp).split("-"); String[] casSouboru = String.format("%tT", fileTimeStamp).split(":"); XMLGregorianCalendar xmlGCDate = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(Integer.parseInt(datumSouboru[0]), Integer.parseInt(datumSouboru[1]), Integer.parseInt(datumSouboru[2]), DatatypeConstants.FIELD_UNDEFINED); XMLGregorianCalendar xmlGCTime = DatatypeFactory.newInstance().newXMLGregorianCalendarTime(Integer.parseInt(casSouboru[0]), Integer.parseInt(casSouboru[1]), Integer.parseInt(casSouboru[2]), DatatypeConstants.FIELD_UNDEFINED); if (fileTimeStamp.compareTo(mtovGC) <= 0) odevzdanoVcas = true; else odevzdanoVcas = false; List<UlohaType> lut = ct.getUloha(); for (UlohaType ut : lut) { if (ut.getCislo().intValue() == cisloUlohyI) { List<OdevzdanoType> lot = ut.getOdevzdano(); OdevzdanoType ot = of.createOdevzdanoType(); ot.setDatum(xmlGCDate); ot.setCas(xmlGCTime); OdevzdanoVcasType ovt = of.createOdevzdanoVcasType(); ovt.setVysledek(odevzdanoVcas); ValidatorType vt = of.createValidatorType(); vt.setVysledek(vysledekValidaceSouboru.equals("true")); ot.setOdevzdanoVcas(ovt); ot.setValidator(vt); lot.add(ot); if (vt.isVysledek()) { String test = String.format("%s%s%02d", validovane, File.separator, ct.getCislo().intValue()); if (!(new File(test).exists())) { LogManager.getInstance().log("Nebyla provedena p��prava soubor�. Chyb� slo�ka " + test.substring(Ppa1Cviceni.USER_DIR.length()) + "."); return; } else { copyValidFile(testedFile, ct.getCislo().intValue()); } } break; } } break; } } } else if (shodaJmenaSouboru && samostatnaPrace) { String[] partsOfFilename = testedFile.getName().split("_"); String[] partsOfLastPartOfFilename = partsOfFilename[partsOfFilename.length - 1].split("[.]"); String osobniCisloZeSouboru = partsOfLastPartOfFilename[0]; String priponaZeSouboru = partsOfLastPartOfFilename[partsOfLastPartOfFilename.length - 1]; if ((partsOfLastPartOfFilename.length == 2) && (priponaZeSouboru.equals("java"))) { if (student.getOsobniCislo().equals(osobniCisloZeSouboru)) { Calendar fileTimeStamp = new GregorianCalendar(); fileTimeStamp.setTimeInMillis(testedFile.lastModified()); String[] datumSouboru = String.format("%tF", fileTimeStamp).split("-"); String[] casSouboru = String.format("%tT", fileTimeStamp).split(":"); XMLGregorianCalendar xmlGCDate = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(Integer.parseInt(datumSouboru[0]), Integer.parseInt(datumSouboru[1]), Integer.parseInt(datumSouboru[2]), DatatypeConstants.FIELD_UNDEFINED); XMLGregorianCalendar xmlGCTime = DatatypeFactory.newInstance().newXMLGregorianCalendarTime(Integer.parseInt(casSouboru[0]), Integer.parseInt(casSouboru[1]), Integer.parseInt(casSouboru[2]), DatatypeConstants.FIELD_UNDEFINED); List<UlozenoType> lut = student.getSamostatnaPrace().getUlozeno(); if (lut.isEmpty()) { File samostatnaPraceNewFile = new File(sp + File.separator + testedFile.getName()); if (samostatnaPraceNewFile.exists()) { samostatnaPraceNewFile.delete(); samostatnaPraceNewFile.createNewFile(); } String EOL = "" + (char) 0x0D + (char) 0x0A; FileReader fr = new FileReader(testedFile); BufferedReader br = new BufferedReader(fr); FileWriter fw = new FileWriter(samostatnaPraceNewFile); String line; while ((line = br.readLine()) != null) fw.write(line + EOL); br.close(); fw.close(); samostatnaPraceNewFile.setLastModified(testedFile.lastModified()); } UlozenoType ut = of.createUlozenoType(); ut.setDatum(xmlGCDate); ut.setCas(xmlGCTime); lut.add(0, ut); } } } } } PosledniZpracovanyPokusType pzpt = new PosledniZpracovanyPokusType(); String[] slozkaPoslednihoPokusu = pokusyDirectories[pokusyDirectories.length - 1].getName().split("_"); int cisloPokusu = Integer.parseInt(slozkaPoslednihoPokusu[slozkaPoslednihoPokusu.length - 1].trim()); pzpt.setCislo(new BigInteger(String.valueOf(cisloPokusu))); student.getDomaciUlohy().setPosledniZpracovanyPokus(pzpt); break; } } } } ElementJAXB.setJAXBElement(element); LogManager.getInstance().log("Ov��ov�n� a kop�rov�n� odevzdan�ch soubor� dokon�eno."); } catch (FileNotFoundException e) { e.printStackTrace(); LogManager.getInstance().log("Nastala chyba p�i ov��ov�n� a kop�rov�n�."); } catch (DatatypeConfigurationException e) { e.printStackTrace(); LogManager.getInstance().log("Nastala chyba p�i ov��ov�n� a kop�rov�n�."); } catch (IOException e) { e.printStackTrace(); LogManager.getInstance().log("Nastala chyba p�i ov��ov�n� a kop�rov�n�."); } LogManager.getInstance().log("Maz�n� rozbalen�ch soubor� ..."); deleteFileFromTMPFolder(tmpFolderF); LogManager.getInstance().changeLog("Maz�n� rozbalen�ch soubor� ... OK"); } |
11
| Code Sample 1:
private static File createTempWebXml(Class portletClass, File portletDir, String appName, String portletName) throws IOException, FileNotFoundException { File pathToWebInf = new File(portletDir, "WEB-INF"); File tempWebXml = File.createTempFile("web", ".xml", pathToWebInf); tempWebXml.deleteOnExit(); OutputStream webOutputStream = new FileOutputStream(tempWebXml); PortletUnitWebXmlStream streamSource = WEB_XML_STREAM_FACTORY; IOUtils.copy(streamSource.createStream(portletClass, appName, portletName), webOutputStream); webOutputStream.close(); return tempWebXml; }
Code Sample 2:
public void createZip(String baseDir, String objFileName) throws Exception { logger.info("createZip: [ " + baseDir + "] [" + objFileName + "]"); baseDir = baseDir + "/" + timesmpt; File folderObject = new File(baseDir); if (folderObject.exists()) { List<?> fileList = getSubFiles(new File(baseDir)); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(objFileName)); ZipEntry ze = null; byte[] buf = new byte[1024]; int readLen = 0; for (int i = 0; i < fileList.size(); i++) { File f = (File) fileList.get(i); ze = new ZipEntry(getAbsFileName(baseDir, f)); ze.setSize(f.length()); ze.setTime(f.lastModified()); zos.putNextEntry(ze); InputStream is = new BufferedInputStream(new FileInputStream(f)); while ((readLen = is.read(buf, 0, 1024)) != -1) { zos.write(buf, 0, readLen); } is.close(); } zos.close(); } else { throw new Exception("this folder isnot exist!"); } } |
11
| Code Sample 1:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
Code Sample 2:
public static void upper() throws Exception { File input = new File("dateiname"); PostMethod post = new PostMethod("url"); post.setRequestBody(new FileInputStream(input)); if (input.length() < Integer.MAX_VALUE) post.setRequestContentLength((int) input.length()); else post.setRequestContentLength(EntityEnclosingMethod.CONTENT_LENGTH_CHUNKED); post.setRequestHeader("Content-type", "text/xml; charset=ISO-8859�1"); HttpClient httpclient = new HttpClient(); httpclient.executeMethod(post); post.releaseConnection(); URL url = new URL("https://www.amazon.de/"); URLConnection conn = url.openConnection(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { System.out.println(line); } rd.close(); } |
11
| Code Sample 1:
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()); } }
Code Sample 2:
public boolean downloadFile(String sourceFilename, String targetFilename) throws RQLException { checkFtpClient(); InputStream in = null; try { in = ftpClient.retrieveFileStream(sourceFilename); if (in == null) { return false; } FileOutputStream target = new FileOutputStream(targetFilename); IOUtils.copy(in, target); in.close(); target.close(); return ftpClient.completePendingCommand(); } catch (IOException ex) { throw new RQLException("Download of file with name " + sourceFilename + " via FTP from server " + server + " failed.", ex); } } |
00
| Code Sample 1:
private void FindAvail() throws ParserConfigurationException, SQLException { Savepoint sp1; String availsql = "select xmlquery('$c/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]' "; availsql += "passing hp_administrator.availability.AVAIL as \"c\") "; availsql += " from hp_administrator.availability "; availsql += " where date = '" + booking_details.getDate() + "' and train_no like '" + booking_details.getTrain_no() + "'"; System.out.println(availsql); String availxml = ""; String seatxml = ""; String navailstr = ""; String nspavailstr = ""; String currentcoachstr = ""; String srctillstr = "", srcavailstr = "", srcmaxstr = ""; Integer srctill, srcavail, srcmax; Integer navailcoach; Integer nspavailcoach, seatstart, seatcnt, alloccnt; String routesrcstr = "", routedeststr = ""; PreparedStatement pstseat; Statement stavail, stavailupd, stseatupd, stseat; ResultSet rsavail, rsseat; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document docavail, docseattmp, docseatfin, docseat; Element rootavail, rootseat; Node n; try { stavail = conn.createStatement(); sp1 = conn.setSavepoint(); rsavail = stavail.executeQuery(availsql); if (rsavail.next()) availxml = rsavail.getString(1); System.out.println(availxml); StringBuffer StringBuffer1 = new StringBuffer(availxml); ByteArrayInputStream Bis1 = new ByteArrayInputStream(StringBuffer1.toString().getBytes("UTF-16")); docavail = db.parse(Bis1); StringWriter sw; OutputFormat formatter; formatter = new OutputFormat(); formatter.setPreserveSpace(true); formatter.setEncoding("UTF-8"); formatter.setOmitXMLDeclaration(true); XMLSerializer serializer; rootavail = docavail.getDocumentElement(); NodeList coachlist = rootavail.getElementsByTagName("coach"); Element currentcoach, minseat; Element routesrc, routedest, nextstn, dest, user, agent; NodeList nl, nl1; number_of_tickets_rem = booking_details.getNoOfPersons(); int tickpos = 0; firsttime = true; boolean enterloop; for (int i = 0; i < coachlist.getLength(); i++) { currentcoach = (Element) coachlist.item(i); currentcoachstr = currentcoach.getAttribute("number"); String coachmaxstr = currentcoach.getAttribute("coachmax"); Integer coachmax = Integer.parseInt(coachmaxstr.trim()); routesrc = (Element) currentcoach.getFirstChild(); routedest = (Element) currentcoach.getLastChild(); routedest = (Element) routedest.getPreviousSibling().getPreviousSibling().getPreviousSibling(); routesrcstr = routesrc.getNodeName(); routedeststr = routedest.getNodeName(); String seatsql = "select xmlquery('$c/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]' "; seatsql += " passing hp_administrator.book_tickets.SEAT as \"c\") from hp_administrator.book_tickets "; seatsql += " where date = '" + booking_details.getDate() + "' and train_no like '" + booking_details.getTrain_no() + "' "; System.out.println("route :" + sourcenws); System.out.println("route :" + destnnws); System.out.println("route src :" + routesrcstr); System.out.println("route dest :" + routedeststr); System.out.println(seatsql); stseat = conn.createStatement(); rsseat = stseat.executeQuery(seatsql); if (rsseat.next()) seatxml = rsseat.getString(1); StringBuffer StringBuffer2 = new StringBuffer(seatxml); ByteArrayInputStream Bis2 = new ByteArrayInputStream(StringBuffer2.toString().getBytes("UTF-16")); docseat = db.parse(Bis2); rootseat = docseat.getDocumentElement(); enterloop = false; if (routesrcstr.equals(sourcenws) && routedeststr.equals(destnnws)) { System.out.println("case 1"); navailstr = routesrc.getTextContent(); navailcoach = Integer.parseInt(navailstr.trim()); if (useragent) nspavailstr = routesrc.getAttribute("agent"); else nspavailstr = routesrc.getAttribute("user"); nspavailcoach = Integer.parseInt(nspavailstr.trim()); srctillstr = routesrc.getAttribute(sourcenws + "TILL"); srctill = Integer.parseInt(srctillstr.trim()); srcmaxstr = routesrc.getAttribute(sourcenws); srcmax = Integer.parseInt(srcmaxstr.trim()); srcavailstr = routesrc.getTextContent(); srcavail = Integer.parseInt(srcavailstr.trim()); seatstart = coachmax - srctill + 1; seatcnt = srcmax; alloccnt = srcmax - srcavail; seatstart += alloccnt; seatcnt -= alloccnt; Element seat, stn; NodeList nl3 = rootseat.getElementsByTagName("seat"); seat = (Element) nl3.item(0); if (booking_details.getNoOfPersons() <= navailcoach && booking_details.getNoOfPersons() <= nspavailcoach) { coach.clear(); booking_details.coachlist.clear(); booking_details.seatlist.clear(); seatno.clear(); for (tickpos = 0; tickpos < booking_details.getNoOfPersons(); tickpos++) { coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } } number_of_tickets_rem = 0; navailcoach -= booking_details.getNoOfPersons(); nspavailcoach -= booking_details.getNoOfPersons(); if (!firsttime) conn.rollback(sp1); String availupdstr = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupdstr += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + navailcoach + "\""; availupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); int updvar = stavailupd.executeUpdate(availupdstr); if (updvar > 0) System.out.println("upda avail success"); sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(seatupdstr); stseatupd = conn.createStatement(); updvar = stseatupd.executeUpdate(seatupdstr); if (updvar > 0) System.out.println("upda seat success"); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupdstr = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupdstr += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + "/@" + sp + " with \"" + nspavailcoach + "\""; availupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupdstr); stavailupd = conn.createStatement(); updvar = stavailupd.executeUpdate(availupdstr); if (updvar > 0) System.out.println("upda" + sp + " success"); break; } while (navailcoach > 0 && nspavailcoach > 0 && number_of_tickets_rem > 0) { if (firsttime) { sp1 = conn.setSavepoint(); firsttime = false; } enterloop = true; coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); tickpos++; number_of_tickets_rem--; navailcoach--; nspavailcoach--; while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } String availupdstr = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupdstr += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + navailcoach + "\""; availupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupdstr); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupdstr = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupdstr += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + sp + "\"]/" + sourcenws + "/@" + sp + " with \"" + nspavailcoach + "\""; availupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupdstr); } if (enterloop) { sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stseatupd = conn.createStatement(); stseatupd.executeUpdate(seatupdstr); } } else if (routesrcstr.equals(sourcenws) && !routedeststr.equals(destnnws)) { System.out.println("case 2"); String excesssrcstr = routesrc.getTextContent(); System.out.println(excesssrcstr); Integer excesssrc = Integer.parseInt(excesssrcstr.trim()); NodeList nl2 = currentcoach.getElementsByTagName(destnnws); Element e2 = (Element) nl2.item(0); String desttillstr = e2.getAttribute(destnnws + "TILL"); System.out.println(desttillstr); Integer desttillcnt = Integer.parseInt(desttillstr.trim()); srcmaxstr = routesrc.getAttribute(sourcenws); System.out.println(srcmaxstr); srcmax = Integer.parseInt(srcmaxstr.trim()); String spexcesssrcstr = "", spdesttillstr = ""; if (useragent) { spexcesssrcstr = routesrc.getAttribute("agent"); spdesttillstr = e2.getAttribute("agenttill"); } else { spexcesssrcstr = routesrc.getAttribute("user"); spdesttillstr = e2.getAttribute("usertill"); } System.out.println(spdesttillstr); System.out.println(spexcesssrcstr); Integer spdesttillcnt = Integer.parseInt(spdesttillstr.trim()); Integer spexcesssrc = Integer.parseInt(spexcesssrcstr.trim()); Element seat, stn; if (booking_details.getNoOfPersons() <= desttillcnt && booking_details.getNoOfPersons() <= spdesttillcnt) { seatstart = coachmax - desttillcnt + 1; seatcnt = desttillcnt; NodeList nl3 = rootseat.getElementsByTagName("seat"); seat = (Element) nl3.item(0); coach.clear(); seatno.clear(); booking_details.coachlist.clear(); booking_details.seatlist.clear(); for (tickpos = 0; tickpos < booking_details.getNoOfPersons(); tickpos++) { coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } } number_of_tickets_rem = 0; desttillcnt -= booking_details.getNoOfPersons(); spdesttillcnt -= booking_details.getNoOfPersons(); if (!firsttime) conn.rollback(sp1); String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + destnnws + "TILL" + " with \"" + desttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupd); stavailupd = conn.createStatement(); int upst = stavailupd.executeUpdate(availupd); if (upst > 0) System.out.println("update avail success"); sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(seatupdstr); stseatupd = conn.createStatement(); upst = stseatupd.executeUpdate(seatupdstr); if (upst > 0) System.out.println("update seat success"); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + sp + "till" + " with \"" + spdesttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupd); stavailupd = conn.createStatement(); upst = stavailupd.executeUpdate(availupd); if (upst > 0) System.out.println("update " + sp + " success"); break; } else if (booking_details.getNoOfPersons() > spdesttillcnt && spdesttillcnt > 0 && booking_details.getNoOfPersons() <= spdesttillcnt + spexcesssrc) { int diff = 0; if (booking_details.getNoOfPersons() > spdesttillcnt) diff = booking_details.getNoOfPersons() - spdesttillcnt; tickpos = 0; boolean initflg = true; seatstart = coachmax - desttillcnt + 1; seatcnt = desttillcnt; NodeList nl3 = rootseat.getElementsByTagName("seat"); seat = (Element) nl3.item(0); coach.clear(); seatno.clear(); booking_details.coachlist.clear(); booking_details.seatlist.clear(); for (tickpos = 0; tickpos < booking_details.getNoOfPersons(); tickpos++) { coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } if (spdesttillcnt != 0) { desttillcnt--; spdesttillcnt--; } System.out.println("desttillcnt=" + desttillcnt + " spdes = " + desttillcnt + "initflg =" + initflg); if (spdesttillcnt == 0 && initflg == true) { alloccnt = srcmax - excesssrc; seatstart = 1 + alloccnt; initflg = false; seat = (Element) seat.getParentNode().getFirstChild(); } } excesssrc -= diff; spexcesssrc -= diff; number_of_tickets_rem = 0; if (!firsttime) conn.rollback(sp1); String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + destnnws + "TILL" + " with \"" + desttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupd); stavailupd = conn.createStatement(); int upst = stavailupd.executeUpdate(availupd); if (upst > 0) System.out.println("update avail success"); availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + excesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupd); stavailupd = conn.createStatement(); upst = stavailupd.executeUpdate(availupd); if (upst > 0) System.out.println("update avail success"); sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(seatupdstr); stseatupd = conn.createStatement(); upst = stseatupd.executeUpdate(seatupdstr); if (upst > 0) System.out.println("update seat success"); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + sp + "till" + " with \"" + spdesttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupd); stavailupd = conn.createStatement(); upst = stavailupd.executeUpdate(availupd); if (upst > 0) System.out.println("update " + sp + " success"); availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + "/@" + sp + " with \"" + spexcesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupd); stavailupd = conn.createStatement(); upst = stavailupd.executeUpdate(availupd); if (upst > 0) System.out.println("update " + sp + " success"); break; } else if (booking_details.getNoOfPersons() > spdesttillcnt && spdesttillcnt == 0 && booking_details.getNoOfPersons() <= spexcesssrc) { alloccnt = srcmax - excesssrc; seatstart = 1 + alloccnt; tickpos = 0; boolean initflg = true; NodeList nl3 = rootseat.getElementsByTagName("seat"); seat = (Element) nl3.item(0); coach.clear(); seatno.clear(); booking_details.coachlist.clear(); booking_details.seatlist.clear(); for (tickpos = 0; tickpos < booking_details.getNoOfPersons(); tickpos++) { coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } System.out.println("desttillcnt=" + desttillcnt + " spdes = " + desttillcnt + "initflg =" + initflg); } excesssrc -= booking_details.getNoOfPersons(); spexcesssrc -= booking_details.getNoOfPersons(); ; number_of_tickets_rem = 0; if (!firsttime) conn.rollback(sp1); String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + excesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupd); stavailupd = conn.createStatement(); int upst = stavailupd.executeUpdate(availupd); if (upst > 0) System.out.println("update avail success"); sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(seatupdstr); stseatupd = conn.createStatement(); upst = stseatupd.executeUpdate(seatupdstr); if (upst > 0) System.out.println("update seat success"); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + "/@" + sp + " with \"" + spexcesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupd); stavailupd = conn.createStatement(); upst = stavailupd.executeUpdate(availupd); if (upst > 0) System.out.println("update " + sp + " success"); break; } NodeList nl3 = rootseat.getElementsByTagName("seat"); seat = (Element) nl3.item(0); seatstart = 1; String sp = ""; if (useragent) sp = "agent"; else sp = "user"; while (spexcesssrc + spdesttillcnt > 0 && number_of_tickets_rem > 0) { if (firsttime) { sp1 = conn.setSavepoint(); firsttime = false; } enterloop = true; if (spdesttillcnt > 0) { seatstart = coachmax - desttillcnt + 1; desttillcnt--; spdesttillcnt--; String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + destnnws + "TILL" + " with \"" + desttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + sp + "till" + " with \"" + spdesttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); } else if (spdesttillcnt == 0) { alloccnt = srcmax - excesssrc; seatstart = 1 + alloccnt; excesssrc--; spexcesssrc--; String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + excesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + "/@" + sp + " with \"" + spexcesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); } while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); tickpos++; number_of_tickets_rem--; } if (enterloop) { sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stseatupd = conn.createStatement(); stseatupd.executeUpdate(seatupdstr); } } else if (!routesrcstr.equals(sourcenws) && routedeststr.equals(destnnws)) { System.out.println("case 3"); NodeList nl2 = currentcoach.getElementsByTagName(sourcenws); Element e2 = (Element) nl2.item(0); navailstr = e2.getTextContent(); System.out.println(navailstr); navailcoach = Integer.parseInt(navailstr.trim()); if (useragent) nspavailstr = e2.getAttribute("agent"); else nspavailstr = e2.getAttribute("user"); System.out.println(nspavailstr); nspavailcoach = Integer.parseInt(nspavailstr.trim()); srctillstr = e2.getAttribute(sourcenws + "TILL"); System.out.println(srctillstr); srctill = Integer.parseInt(srctillstr.trim()); srcmaxstr = e2.getAttribute(sourcenws); System.out.println(srcmaxstr); srcmax = Integer.parseInt(srcmaxstr.trim()); seatstart = coachmax - srctill + 1; seatcnt = srcmax; alloccnt = srcmax - navailcoach; seatstart += alloccnt; seatcnt -= alloccnt; Element seat, stn; NodeList nl3 = rootseat.getElementsByTagName("seat"); seat = (Element) nl3.item(0); if (booking_details.getNoOfPersons() <= navailcoach && booking_details.getNoOfPersons() <= nspavailcoach) { coach.clear(); seatno.clear(); booking_details.coachlist.clear(); booking_details.seatlist.clear(); for (tickpos = 0; tickpos < booking_details.getNoOfPersons(); tickpos++) { coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } } number_of_tickets_rem = 0; navailcoach -= booking_details.getNoOfPersons(); nspavailcoach -= booking_details.getNoOfPersons(); String availupdstr = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupdstr += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + navailcoach + "\""; availupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupdstr); sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stseatupd = conn.createStatement(); stseatupd.executeUpdate(seatupdstr); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupdstr = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupdstr += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + "/@" + sp + " with \"" + nspavailcoach + "\""; availupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupdstr); break; } while (navailcoach > 0 && nspavailcoach > 0 && number_of_tickets_rem > 0) { if (firsttime) { sp1 = conn.setSavepoint(); firsttime = false; } enterloop = true; coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); tickpos++; number_of_tickets_rem--; navailcoach--; nspavailcoach--; while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } String availupdstr = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupdstr += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + navailcoach + "\""; availupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupdstr); stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupdstr); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupdstr = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupdstr += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + "/@" + sp + " with \"" + nspavailcoach + "\""; availupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupdstr); stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupdstr); } if (enterloop) { sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println("!@#------->" + seatupdstr); stseatupd = conn.createStatement(); } } else if (!routesrcstr.equals(sourcenws) && !routedeststr.equals(destnnws)) { System.out.println("case 4"); srcmaxstr = routesrc.getAttribute(sourcenws); System.out.println(srcmaxstr); srcmax = Integer.parseInt(srcmaxstr.trim()); Element seat, stn; NodeList nl2 = currentcoach.getElementsByTagName(sourcenws); Element e2 = (Element) nl2.item(0); navailstr = e2.getTextContent(); Integer excesssrc = Integer.parseInt(navailstr.trim()); nl2 = currentcoach.getElementsByTagName(destnnws); e2 = (Element) nl2.item(0); navailstr = e2.getAttribute(destnnws + "TILL"); Integer desttillcnt = Integer.parseInt(navailstr.trim()); String spexcesssrcstr = "", spdesttillstr = ""; if (useragent) { spexcesssrcstr = routesrc.getAttribute("agent"); spdesttillstr = e2.getAttribute("agenttill"); } else { spexcesssrcstr = routesrc.getAttribute("user"); spdesttillstr = e2.getAttribute("usertill"); } Integer spdesttillcnt = Integer.parseInt(spdesttillstr.trim()); Integer spexcesssrc = Integer.parseInt(spexcesssrcstr.trim()); NodeList nl3 = rootseat.getElementsByTagName("seat"); seat = (Element) nl3.item(0); boolean initflg = true; if (booking_details.getNoOfPersons() <= spdesttillcnt) { seatstart = coachmax - desttillcnt + 1; seatcnt = desttillcnt; coach.clear(); seatno.clear(); booking_details.coachlist.clear(); booking_details.seatlist.clear(); for (tickpos = 0; tickpos < booking_details.getNoOfPersons(); tickpos++) { coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } } number_of_tickets_rem = 0; desttillcnt -= booking_details.getNoOfPersons(); spdesttillcnt -= booking_details.getNoOfPersons(); if (!firsttime) conn.rollback(sp1); String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + destnnws + "TILL" + " with \"" + desttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stseatupd = conn.createStatement(); stseatupd.executeUpdate(seatupdstr); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + sp + "till" + " with \"" + spdesttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); break; } else if (booking_details.getNoOfPersons() > spdesttillcnt && spdesttillcnt > 0 && booking_details.getNoOfPersons() <= spdesttillcnt + spexcesssrc) { int diff = 0; if (booking_details.getNoOfPersons() > spdesttillcnt) diff = booking_details.getNoOfPersons() - spdesttillcnt; seatstart = coachmax - desttillcnt + 1; seatcnt = desttillcnt; coach.clear(); seatno.clear(); booking_details.coachlist.clear(); booking_details.seatlist.clear(); for (tickpos = 0; tickpos < booking_details.getNoOfPersons(); tickpos++) { coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } if (spdesttillcnt != 0) { desttillcnt--; spdesttillcnt--; } if (spdesttillcnt == 0 && initflg == true) { alloccnt = srcmax - excesssrc; seatstart = 1 + alloccnt; initflg = false; } } excesssrc -= diff; spexcesssrc -= diff; number_of_tickets_rem = 0; if (!firsttime) conn.rollback(sp1); String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + destnnws + "TILL" + " with \"" + desttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + excesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stseatupd = conn.createStatement(); stseatupd.executeUpdate(seatupdstr); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + sp + "till" + " with \"" + spdesttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + "/@" + sp + " with \"" + spexcesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); break; } else if (spdesttillcnt == 0 && booking_details.getNoOfPersons() <= spexcesssrc) { alloccnt = srcmax - excesssrc; seatstart = 1 + alloccnt; coach.clear(); seatno.clear(); booking_details.coachlist.clear(); booking_details.seatlist.clear(); for (tickpos = 0; tickpos < booking_details.getNoOfPersons(); tickpos++) { coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } } excesssrc -= booking_details.getNoOfPersons(); spexcesssrc -= booking_details.getNoOfPersons(); number_of_tickets_rem = 0; if (!firsttime) conn.rollback(sp1); String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + excesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stseatupd = conn.createStatement(); stseatupd.executeUpdate(seatupdstr); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + "/@" + sp + " with \"" + spexcesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); break; } seatstart = 1; String sp = ""; if (useragent) sp = "agent"; else sp = "user"; while (spexcesssrc + spdesttillcnt > 0 && number_of_tickets_rem > 0) { if (firsttime) { sp1 = conn.setSavepoint(); firsttime = false; } enterloop = true; if (spdesttillcnt > 0) { seatstart = coachmax - desttillcnt + 1; desttillcnt--; spdesttillcnt--; String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + destnnws + "TILL" + " with \"" + desttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + sp + "till" + " with \"" + spdesttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); } else if (spdesttillcnt == 0) { alloccnt = srcmax - excesssrc; seatstart = 1 + alloccnt; excesssrc--; spexcesssrc--; String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + "/@" + sp + " with \"" + excesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + spexcesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); } while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); tickpos++; number_of_tickets_rem--; } if (enterloop) { sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stseatupd = conn.createStatement(); stseatupd.executeUpdate(seatupdstr); } } } availfin = true; } catch (SQLException e) { conn.rollback(); e.printStackTrace(); } catch (UnsupportedEncodingException e) { conn.rollback(); e.printStackTrace(); } catch (SAXException e) { conn.rollback(); e.printStackTrace(); } catch (IOException e) { conn.rollback(); e.printStackTrace(); } }
Code Sample 2:
static String getMD5Hash(String str) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] b = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < b.length; i++) { int v = (int) b[i]; v = v < 0 ? 0x100 + v : v; String cc = Integer.toHexString(v); if (cc.length() == 1) sb.append('0'); sb.append(cc); } return sb.toString(); } |
11
| Code Sample 1:
public void setContentMD5() { MessageDigest messagedigest = null; try { messagedigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); contentMD5 = null; } messagedigest.update(content.getBytes()); byte digest[] = messagedigest.digest(); String chk = ""; for (int i = 0; i < digest.length; i++) { String s = Integer.toHexString(digest[i] & 0xFF); chk += ((s.length() == 1) ? "0" + s : s); } contentMD5 = chk; }
Code Sample 2:
private String hashMD5(String strToHash) throws Exception { try { byte[] bHash = new byte[strToHash.length() * 2]; MessageDigest md = MessageDigest.getInstance("MD5"); md.update(strToHash.getBytes("UTF-16LE")); bHash = md.digest(); StringBuffer hexString = new StringBuffer(); for (byte element : bHash) { String strTemp = Integer.toHexString(element); hexString.append(strTemp.replaceAll("f", "")); } return hexString.toString(); } catch (NoSuchAlgorithmException duu) { throw new Exception("NoSuchAlgorithmException: " + duu.getMessage()); } } |
11
| Code Sample 1:
public synchronized void write() throws IOException { ZipOutputStream jar = new ZipOutputStream(new FileOutputStream(jarPath)); int index = className.lastIndexOf('.'); String packageName = className.substring(0, index); String clazz = className.substring(index + 1); String directory = packageName.replace('.', '/'); ZipEntry dummyClass = new ZipEntry(directory + "/" + clazz + ".class"); jar.putNextEntry(dummyClass); ClassGen classgen = new ClassGen(getClassName(), "java.lang.Object", "<generated>", Constants.ACC_PUBLIC | Constants.ACC_SUPER, null); byte[] bytes = classgen.getJavaClass().getBytes(); jar.write(bytes); jar.closeEntry(); ZipEntry synthFile = new ZipEntry(directory + "/synth.xml"); jar.putNextEntry(synthFile); Comment comment = new Comment("Generated by SynthBuilder from L2FProd.com"); Element root = new Element("synth"); root.addAttribute(new Attribute("version", "1")); root.appendChild(comment); Element defaultStyle = new Element("style"); defaultStyle.addAttribute(new Attribute("id", "default")); Element defaultFont = new Element("font"); defaultFont.addAttribute(new Attribute("name", "SansSerif")); defaultFont.addAttribute(new Attribute("size", "12")); defaultStyle.appendChild(defaultFont); Element defaultState = new Element("state"); defaultStyle.appendChild(defaultState); root.appendChild(defaultStyle); Element bind = new Element("bind"); bind.addAttribute(new Attribute("style", "default")); bind.addAttribute(new Attribute("type", "region")); bind.addAttribute(new Attribute("key", ".*")); root.appendChild(bind); doc = new Document(root); imagesToCopy = new HashMap(); ComponentStyle[] styles = config.getStyles(); for (ComponentStyle element : styles) { write(element); } Serializer writer = new Serializer(jar); writer.setIndent(2); writer.write(doc); writer.flush(); jar.closeEntry(); for (Iterator iter = imagesToCopy.keySet().iterator(); iter.hasNext(); ) { String element = (String) iter.next(); File pathToImage = (File) imagesToCopy.get(element); ZipEntry image = new ZipEntry(directory + "/" + element); jar.putNextEntry(image); FileInputStream input = new FileInputStream(pathToImage); int read = -1; while ((read = input.read()) != -1) { jar.write(read); } input.close(); jar.flush(); jar.closeEntry(); } jar.flush(); jar.close(); }
Code Sample 2:
public static void compress(final File zip, final Map<InputStream, String> entries, final IProgressMonitor monitor) throws IOException { if (zip == null || entries == null || CollectionUtils.isEmpty(entries.keySet())) throw new IllegalArgumentException("One ore more parameters are empty!"); if (zip.exists()) zip.delete(); else if (!zip.getParentFile().exists()) zip.getParentFile().mkdirs(); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zip))); out.setLevel(Deflater.BEST_COMPRESSION); try { for (InputStream inputStream : entries.keySet()) { ZipEntry zipEntry = new ZipEntry(skipBeginningSlash(entries.get(inputStream))); out.putNextEntry(zipEntry); IOUtils.copy(inputStream, out); out.closeEntry(); inputStream.close(); if (monitor != null) monitor.worked(1); } } finally { IOUtils.closeQuietly(out); } } |
00
| Code Sample 1:
public void setRemoteConfig(String s) { try { HashMap<String, String> map = new HashMap<String, String>(); URL url = new URL(s); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; while ((line = in.readLine()) != null) { if (line.startsWith("#")) continue; String[] split = line.split("="); if (split.length >= 2) { map.put(split[0], split[1]); } } MethodAndFieldSetter.setMethodsAndFields(this, map); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
@Override public String encode(String password) { String hash = null; MessageDigest m; try { m = MessageDigest.getInstance("MD5"); m.update(password.getBytes(), 0, password.length()); hash = String.format("%1$032X", new BigInteger(1, m.digest())); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return hash; } |
11
| Code Sample 1:
public static final boolean copy(File source, File target, boolean overwrite) { if (!overwrite && target.exists()) { LOGGER.error("Target file exist and it not permitted to overwrite it !"); return false; } FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(target).getChannel(); in.transferTo(0, in.size(), out); } catch (FileNotFoundException e) { LOGGER.error(e.getLocalizedMessage()); if (LOGGER.isDebugEnabled()) e.printStackTrace(); return false; } catch (IOException e) { LOGGER.error(e.getLocalizedMessage()); if (LOGGER.isDebugEnabled()) e.printStackTrace(); return false; } finally { try { in.close(); } catch (Exception e) { } try { out.close(); } catch (Exception e) { } } return true; }
Code Sample 2:
@Test public void testTransactWriteAndRead() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile file = new RFile("testreadwritetrans.txt"); RFileOutputStream out = new RFileOutputStream(file, WriteMode.TRANSACTED, false, 1); out.write("test".getBytes("utf-8")); out.close(); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[4]; int readCount = in.read(buffer); in.close(); assertEquals(4, readCount); String resultRead = new String(buffer, "utf-8"); assertEquals("test", resultRead); } finally { server.stop(); } } |
11
| Code Sample 1:
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (req.getParameter("i") != null) { String img = req.getParameter("i"); if (img == null) { resp.sendError(404, "Image was null"); return; } File f = null; if (img.startsWith("file")) { try { f = new File(new URI(img)); } catch (URISyntaxException e) { resp.sendError(500, e.getMessage()); return; } } else { f = new File(img); } if (f.exists()) { f = f.getCanonicalFile(); if (f.getName().endsWith(".jpg") || f.getName().endsWith(".png")) { resp.setContentType("image/png"); FileInputStream fis = null; OutputStream os = resp.getOutputStream(); try { fis = new FileInputStream(f); IOUtils.copy(fis, os); } finally { os.flush(); if (fis != null) fis.close(); } } } return; } String mediaUrl = "/media" + req.getPathInfo(); String parts[] = mediaUrl.split("/"); mediaHandler.handleRequest(parts, req, resp); }
Code Sample 2:
public static void main(String[] args) { String WTKdir = null; String sourceFile = null; String instrFile = null; String outFile = null; String jadFile = null; Manifest mnf; if (args.length == 0) { usage(); return; } int i = 0; while (i < args.length && args[i].startsWith("-")) { if (("-WTK".equals(args[i])) && (i < args.length - 1)) { i++; WTKdir = args[i]; } else if (("-source".equals(args[i])) && (i < args.length - 1)) { i++; sourceFile = args[i]; } else if (("-instr".equals(args[i])) && (i < args.length - 1)) { i++; instrFile = args[i]; } else if (("-o".equals(args[i])) && (i < args.length - 1)) { i++; outFile = args[i]; } else if (("-jad".equals(args[i])) && (i < args.length - 1)) { i++; jadFile = args[i]; } else { System.out.println("Error: Unrecognized option: " + args[i]); System.exit(0); } i++; } if (WTKdir == null || sourceFile == null || instrFile == null) { System.out.println("Error: Missing parameter!!!"); usage(); return; } if (outFile == null) outFile = sourceFile; FileInputStream fisJar; try { fisJar = new FileInputStream(sourceFile); } catch (FileNotFoundException e1) { System.out.println("Cannot find source jar file: " + sourceFile); e1.printStackTrace(); return; } FileOutputStream fosJar; File aux = null; try { aux = File.createTempFile("predef", "aux"); fosJar = new FileOutputStream(aux); } catch (IOException e1) { System.out.println("Cannot find temporary jar file: " + aux); e1.printStackTrace(); return; } JarFile instrJar = null; Enumeration en = null; File tempDir = null; try { instrJar = new JarFile(instrFile); en = instrJar.entries(); tempDir = File.createTempFile("jbtp", ""); tempDir.delete(); System.out.println("Create directory: " + tempDir.mkdirs()); tempDir.deleteOnExit(); } catch (IOException e) { System.out.println("Cannot open instrumented file: " + instrFile); e.printStackTrace(); return; } String[] wtklib = new java.io.File(WTKdir + File.separator + "lib").list(new OnlyJar()); String preverifyCmd = WTKdir + File.separator + "bin" + File.separator + "preverify -classpath " + WTKdir + File.separator + "lib" + File.separator + CLDC_JAR + File.pathSeparator + WTKdir + File.separator + "lib" + File.separator + MIDP_JAR + File.pathSeparator + WTKdir + File.separator + "lib" + File.separator + WMA_JAR + File.pathSeparator + instrFile; for (int k = 0; k < wtklib.length; k++) { preverifyCmd += File.pathSeparator + WTKdir + File.separator + "lib" + wtklib[k]; } preverifyCmd += " " + "-d " + tempDir.getAbsolutePath() + " "; while (en.hasMoreElements()) { JarEntry je = (JarEntry) en.nextElement(); String jeName = je.getName(); if (jeName.endsWith(".class")) jeName = jeName.substring(0, jeName.length() - 6); preverifyCmd += jeName + " "; } try { Process p = Runtime.getRuntime().exec(preverifyCmd); if (p.waitFor() != 0) { BufferedReader in = new BufferedReader(new InputStreamReader(p.getErrorStream())); System.out.println("Error calling the preverify command."); while (in.ready()) { System.out.print("" + in.readLine()); } System.out.println(); in.close(); return; } } catch (Exception e) { System.out.println("Cannot execute preverify command"); e.printStackTrace(); return; } File[] listOfFiles = computeFiles(tempDir); System.out.println("-------------------------------\n" + "Files to insert: "); String[] strFiles = new String[listOfFiles.length]; int l = tempDir.toString().length() + 1; for (int j = 0; j < listOfFiles.length; j++) { strFiles[j] = listOfFiles[j].toString().substring(l); strFiles[j] = strFiles[j].replace(File.separatorChar, '/'); System.out.println(strFiles[j]); } System.out.println("-------------------------------"); try { JarInputStream jis = new JarInputStream(fisJar); mnf = jis.getManifest(); JarOutputStream jos = new JarOutputStream(fosJar, mnf); nextJar: for (JarEntry je = jis.getNextJarEntry(); je != null; je = jis.getNextJarEntry()) { String s = je.getName(); for (int k = 0; k < strFiles.length; k++) { if (strFiles[k].equals(s)) continue nextJar; } jos.putNextEntry(je); byte[] b = new byte[512]; for (int k = jis.read(b, 0, 512); k >= 0; k = jis.read(b, 0, 512)) { jos.write(b, 0, k); } } jis.close(); for (int j = 0; j < strFiles.length; j++) { FileInputStream fis = new FileInputStream(listOfFiles[j]); JarEntry je = new JarEntry(strFiles[j]); jos.putNextEntry(je); byte[] b = new byte[512]; while (fis.available() > 0) { int k = fis.read(b, 0, 512); jos.write(b, 0, k); } fis.close(); } jos.close(); fisJar.close(); fosJar.close(); } catch (IOException e) { System.out.println("Cannot read/write jar file."); e.printStackTrace(); return; } try { FileOutputStream fos = new FileOutputStream(outFile); FileInputStream fis = new FileInputStream(aux); byte[] b = new byte[512]; while (fis.available() > 0) { int k = fis.read(b, 0, 512); fos.write(b, 0, k); } fis.close(); fos.close(); } catch (IOException e) { System.out.println("Cannot write output jar file: " + outFile); e.printStackTrace(); } Iterator it; Attributes atr; atr = mnf.getMainAttributes(); it = atr.keySet().iterator(); if (jadFile != null) { FileOutputStream fos; try { File outJarFile = new File(outFile); fos = new FileOutputStream(jadFile); PrintStream psjad = new PrintStream(fos); while (it.hasNext()) { Object ats = it.next(); psjad.println(ats + ": " + atr.get(ats)); } psjad.println("MIDlet-Jar-URL: " + outFile); psjad.println("MIDlet-Jar-Size: " + outJarFile.length()); fos.close(); } catch (IOException eio) { System.out.println("Cannot create jad file."); eio.printStackTrace(); } } } |
11
| Code Sample 1:
public static String getHash(String uri) throws NoSuchAlgorithmException { MessageDigest mDigest = MessageDigest.getInstance("MD5"); mDigest.update(uri.getBytes()); byte d[] = mDigest.digest(); StringBuffer hash = new StringBuffer(); for (int i = 0; i < d.length; i++) { hash.append(Integer.toHexString(0xFF & d[i])); } return hash.toString(); }
Code Sample 2:
public synchronized String getEncryptedPassword(String plaintext, String algorithm) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = null; md = MessageDigest.getInstance(algorithm); md.update(plaintext.getBytes("UTF-8")); return bytesToHexString(md.digest()); } |
11
| Code Sample 1:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
Code Sample 2:
private void fillTemplate(String resource, OutputStream outputStream, Map<String, String> replacements) throws IOException { URL url = Tools.getResource(resource); if (url == null) { throw new IOException("could not find resource"); } BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, Charset.forName("UTF-8"))); String line = null; do { line = reader.readLine(); if (line != null) { for (String key : replacements.keySet()) { String value = replacements.get(key); if (key != null) { line = line.replace(key, value); } } writer.write(line); writer.newLine(); } } while (line != null); reader.close(); writer.close(); } |
11
| Code Sample 1:
public static void copyFromTo(String src, String des) { staticprintln("Copying:\"" + src + "\"\nto:\"" + des + "\""); try { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(des).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { } }
Code Sample 2:
public void setBckImg(String newPath) { try { File inputFile = new File(getPath()); File outputFile = new File(newPath); if (!inputFile.getCanonicalPath().equals(outputFile.getCanonicalPath())) { FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = null; try { out = new FileOutputStream(outputFile); } catch (FileNotFoundException ex1) { ex1.printStackTrace(); JOptionPane.showMessageDialog(null, ex1.getMessage().substring(0, Math.min(ex1.getMessage().length(), drawPanel.MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "Set Bck Img", JOptionPane.ERROR_MESSAGE); } int c; if (out != null) { while ((c = in.read()) != -1) out.write(c); out.close(); } in.close(); } } catch (Exception ex) { ex.printStackTrace(); LogHandler.log(ex.getMessage(), Level.INFO, "LOG_MSG", isLoggingEnabled()); JOptionPane.showMessageDialog(null, ex.getMessage().substring(0, Math.min(ex.getMessage().length(), drawPanel.MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "Set Bck Img", JOptionPane.ERROR_MESSAGE); } setPath(newPath); bckImg = new ImageIcon(getPath()); } |
11
| Code Sample 1:
public void echo(HttpRequest request, HttpResponse response) throws IOException { InputStream in = request.getInputStream(); if ("gzip".equals(request.getField("Content-Encoding"))) { in = new GZIPInputStream(in); } IOUtils.copy(in, response.getOutputStream()); }
Code Sample 2:
public void patchFile(final File classFile) { if (!classFile.exists()) { myErrors.add(new FormErrorInfo(null, "Class to bind does not exist: " + myRootContainer.getClassToBind())); return; } FileInputStream fis; try { byte[] patchedData; fis = new FileInputStream(classFile); try { patchedData = patchClass(fis); if (patchedData == null) { return; } } finally { fis.close(); } FileOutputStream fos = new FileOutputStream(classFile); try { fos.write(patchedData); } finally { fos.close(); } } catch (IOException e) { myErrors.add(new FormErrorInfo(null, "Cannot read or write class file " + classFile.getPath() + ": " + e.toString())); } } |
00
| Code Sample 1:
protected URLConnection openConnection(URL url) throws IOException { if (bundleEntry != null) return (new BundleURLConnection(url, bundleEntry)); String bidString = url.getHost(); if (bidString == null) { throw new IOException(NLS.bind(AdaptorMsg.URL_NO_BUNDLE_ID, url.toExternalForm())); } AbstractBundle bundle = null; long bundleID; try { bundleID = Long.parseLong(bidString); } catch (NumberFormatException nfe) { throw new MalformedURLException(NLS.bind(AdaptorMsg.URL_INVALID_BUNDLE_ID, bidString)); } bundle = (AbstractBundle) context.getBundle(bundleID); if (!url.getAuthority().equals(SECURITY_AUTHORIZED)) { checkAdminPermission(bundle); } if (bundle == null) { throw new IOException(NLS.bind(AdaptorMsg.URL_NO_BUNDLE_FOUND, url.toExternalForm())); } return (new BundleURLConnection(url, findBundleEntry(url, bundle))); }
Code Sample 2:
public InputStream loadDriver(String id) throws IOException { Hashtable drivers = loadDriverDB(); DriverInfo di = (DriverInfo) drivers.get(id); InputStream stream = null; if (di == null) { log.warn("No id" + id); throw new IOException("No driver id '" + id + "'"); } try { String strURL = di.url; if (strURL.indexOf(":") == -1) { strURL = jarbase + strURL; } URL url = new URL(strURL); stream = url.openStream(); } catch (MalformedURLException e) { log.error("bad URL for in " + di, e); throw new IOException("Bad driver URL " + e); } catch (IOException e) { log.error("can't connect to URL in " + di, e); throw e; } return stream; } |
11
| Code Sample 1:
public static boolean copyFile(final File src, final File dest, long extent, final boolean overwrite) throws FileNotFoundException, IOException { boolean result = false; if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Copying file " + src + " to " + dest + " extent " + extent + " exists " + dest.exists()); } if (dest.exists()) { if (overwrite) { dest.delete(); LOGGER.finer(dest.getAbsolutePath() + " removed before copy."); } else { return result; } } FileInputStream fis = null; FileOutputStream fos = null; FileChannel fcin = null; FileChannel fcout = null; try { fis = new FileInputStream(src); fos = new FileOutputStream(dest); fcin = fis.getChannel(); fcout = fos.getChannel(); if (extent < 0) { extent = fcin.size(); } long trans = fcin.transferTo(0, extent, fcout); if (trans < extent) { result = false; } result = true; } catch (IOException e) { String message = "Copying " + src.getAbsolutePath() + " to " + dest.getAbsolutePath() + " with extent " + extent + " got IOE: " + e.getMessage(); if (e.getMessage().equals("Invalid argument")) { LOGGER.severe("Failed copy, trying workaround: " + message); workaroundCopyFile(src, dest); } else { IOException newE = new IOException(message); newE.setStackTrace(e.getStackTrace()); throw newE; } } finally { if (fcin != null) { fcin.close(); } if (fcout != null) { fcout.close(); } if (fis != null) { fis.close(); } if (fos != null) { fos.close(); } } return result; }
Code Sample 2:
@Test @Ignore public void testToJson() throws IOException { JsonSerializer js = new StreamingJsonSerializer(new ObjectMapper()); BulkOperation op = js.createBulkOperation(createTestData(10000), false); IOUtils.copy(op.getData(), System.out); } |
00
| Code Sample 1:
@Override public final boolean save() throws RecordException, RecordValidationException, RecordValidationSyntax { if (frozen) { throw new RecordException("The object is frozen."); } boolean toReturn = false; Class<? extends Record> actualClass = this.getClass(); HashMap<String, Integer> columns = getColumns(TableNameResolver.getTableName(actualClass)); Connection conn = ConnectionManager.getConnection(); LoggableStatement pStat = null; try { if (exists()) { doValidations(true); StatementBuilder builder = new StatementBuilder("update " + TableNameResolver.getTableName(actualClass) + " set"); String updates = ""; for (String key : columns.keySet()) { if (!key.equals("id")) { Field f = null; try { f = FieldHandler.findField(actualClass, key); } catch (FieldOrMethodNotFoundException e) { throw new RecordException("Database column name >" + key + "< not found in class " + actualClass.getCanonicalName()); } updates += key + " = :" + key + ", "; builder.set(key, FieldHandler.getValue(f, this)); } } builder.append(updates.substring(0, updates.length() - 2)); builder.append("where id = :id"); builder.set(":id", FieldHandler.getValue(FieldHandler.findField(actualClass, "id"), this)); pStat = builder.getPreparedStatement(conn); log.log(pStat.getQueryString()); int i = pStat.executeUpdate(); toReturn = i == 1; } else { doValidations(false); StatementBuilder builder = new StatementBuilder("insert into " + TableNameResolver.getTableName(actualClass) + " "); String names = ""; String values = ""; for (String key : columns.keySet()) { Field f = null; try { f = FieldHandler.findField(actualClass, key); } catch (FieldOrMethodNotFoundException e) { throw new RecordException("Database column name >" + key + "< not found in class " + actualClass.getCanonicalName()); } if (key.equals("id") && (Integer) FieldHandler.getValue(f, this) == 0) { continue; } names += key + ", "; values += ":" + key + ", "; builder.set(key, f.get(this)); } names = names.substring(0, names.length() - 2); values = values.substring(0, values.length() - 2); builder.append("(" + names + ")"); builder.append("values"); builder.append("(" + values + ")"); pStat = builder.getPreparedStatement(conn); log.log(pStat.getQueryString()); int i = pStat.executeUpdate(); toReturn = i == 1; } if (childList != null) { if (childObjects == null) { childObjects = new HashMap<Class<? extends Record>, Record>(); } for (Class<? extends Record> c : childList.keySet()) { if (childObjects.get(c) != null) { childObjects.get(c).save(); } } } if (childrenList != null) { if (childrenObjects == null) { childrenObjects = new HashMap<Class<? extends Record>, List<? extends Record>>(); } for (Class<? extends Record> c : childrenList.keySet()) { if (childrenObjects.get(c) != null) { for (Record r : childrenObjects.get(c)) { r.save(); } } } } if (relatedList != null) { if (childrenObjects == null) { childrenObjects = new HashMap<Class<? extends Record>, List<? extends Record>>(); } for (Class<? extends Record> c : relatedList.keySet()) { if (childrenObjects.get(c) != null) { for (Record r : childrenObjects.get(c)) { r.save(); } } } } return toReturn; } catch (Exception e) { if (e instanceof RecordValidationException) { throw (RecordValidationException) e; } if (e instanceof RecordValidationSyntax) { throw (RecordValidationSyntax) e; } try { conn.rollback(); } catch (SQLException e1) { throw new RecordException("Error executing rollback"); } throw new RecordException(e); } finally { try { if (pStat != null) { pStat.close(); } conn.commit(); conn.close(); } catch (SQLException e) { throw new RecordException("Error closing connection"); } } }
Code Sample 2:
public static String get(String u, String usr, String pwd) { String response = ""; logger.debug("Attempting to call: " + u); logger.debug("Creating Authenticator: usr=" + usr + ", pwd=" + pwd); Authenticator.setDefault(new CustomAuthenticator(usr, pwd)); try { URL url = new URL(u); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer sb = new StringBuffer(0); String str; while ((str = in.readLine()) != null) { sb.append(str); } in.close(); logger.debug("Response: " + sb.toString()); response = sb.toString(); } catch (MalformedURLException e) { logger.error(e); logger.trace(e, e); } catch (IOException e) { logger.error(e); logger.trace(e, e); } return response; } |
00
| Code Sample 1:
public String getHashedPhoneId(Context aContext) { if (hashedPhoneId == null) { final String androidId = BuildInfo.getAndroidID(aContext); if (androidId == null) { hashedPhoneId = "EMULATOR"; } else { try { final MessageDigest messageDigest = MessageDigest.getInstance("SHA"); messageDigest.update(androidId.getBytes()); messageDigest.update(aContext.getPackageName().getBytes()); final StringBuilder stringBuilder = new StringBuilder(); for (byte b : messageDigest.digest()) { stringBuilder.append(String.format("%02X", b)); } hashedPhoneId = stringBuilder.toString(); } catch (Exception e) { Log.e(LoggingExceptionHandler.class.getName(), "Unable to get phone id", e); hashedPhoneId = "Not Available"; } } } return hashedPhoneId; }
Code Sample 2:
private String getResourceAsString(final String name) throws IOException { final InputStream is = JiBXTestCase.class.getResourceAsStream(name); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copyAndClose(is, baos); return baos.toString(); } |
11
| Code Sample 1:
public static String encrypt(String text) throws NoSuchAlgorithmException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; try { md.update(text.getBytes("iso-8859-1"), 0, text.length()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } md5hash = md.digest(); return convertToHex(md5hash); }
Code Sample 2:
private byte[] _generate() throws NoSuchAlgorithmException { if (host == null) { try { seed = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { seed = "localhost/127.0.0.1"; } catch (SecurityException e) { seed = "localhost/127.0.0.1"; } host = seed; } else { seed = host; } seed = seed + new Date().toString(); seed = seed + Long.toString(rnd.nextLong()); md = MessageDigest.getInstance(algorithm); md.update(seed.getBytes()); return md.digest(); } |
00
| 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) { } } catch (FileNotFoundException e) { } }
Code Sample 2:
public static void main(String args[]) { int i, j, l; short NUMNUMBERS = 256; short numbers[] = new short[NUMNUMBERS]; Darjeeling.print("START"); for (l = 0; l < 100; l++) { for (i = 0; i < NUMNUMBERS; i++) numbers[i] = (short) (NUMNUMBERS - 1 - i); for (i = 0; i < NUMNUMBERS; i++) { for (j = 0; j < NUMNUMBERS - i - 1; j++) if (numbers[j] > numbers[j + 1]) { short temp = numbers[j]; numbers[j] = numbers[j + 1]; numbers[j + 1] = temp; } } } Darjeeling.print("END"); } |
00
| Code Sample 1:
public String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
Code Sample 2:
public int executeUpdate(String query, QueryParameter params) throws DAOException { PreparedStatement ps = null; Query queryObj = getModel().getQuery(query); if (conditionalQueries != null && conditionalQueries.containsKey(query)) { queryObj = (Query) conditionalQueries.get(query); } String sql = queryObj.getStatement(params.getVariables()); logger.debug(sql); try { if (con == null || con.isClosed()) { con = DataSource.getInstance().getConnection(getModel().getDataSource()); } ps = con.prepareStatement(sql); setParameters(ps, queryObj, params); return ps.executeUpdate(); } catch (SQLException e) { logger.error("DataBase Error :", e); if (transactionMode) rollback(); transactionMode = false; throw new DAOException("Unexpected Error Query (" + query + ")", "error.DAO.database", e.getMessage()); } catch (Exception ex) { logger.error("Error :", ex); if (transactionMode) rollback(); transactionMode = false; throw new DAOException("Unexpected Error Query (" + query + ")", "error.DAO.database", ex.getMessage()); } finally { try { if (!transactionMode) con.commit(); if (ps != null) ps.close(); if (!transactionMode && con != null) con.close(); } catch (SQLException e) { throw new DAOException("Unexpected Error Query (" + query + ")", "error.DAO.database", e.getMessage()); } } } |
00
| Code Sample 1:
public DatabaseDefinitionFactory(final DBIf db, final String adapter) throws IOException { _db = db; LOG.debug("Loading adapter: " + adapter); final URL url = getClass().getClassLoader().getResource("adapter/" + adapter + ".properties"); _props = new Properties(); _props.load(url.openStream()); if (adapter.equals("mysql")) { _modifier = new MySQLModifier(this); } else if (adapter.equals("postgresql")) { _modifier = new PostgresModifier(this); } else if (adapter.equals("hypersonic")) { _modifier = new HSQLModifier(this); } else if (adapter.equals("oracle")) { _modifier = new OracleModifier(this); } else if (adapter.equals("mssql")) { _modifier = new MSSQLModifier(this); } else { _modifier = null; } }
Code Sample 2:
public static String getMD5(String _pwd) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(_pwd.getBytes()); return toHexadecimal(new String(md.digest()).getBytes()); } catch (NoSuchAlgorithmException x) { x.printStackTrace(); return ""; } } |
11
| Code Sample 1:
public static void addClasses(URL url) { BufferedReader reader = null; String line; ClassLoader cl = Thread.currentThread().getContextClassLoader(); try { reader = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = reader.readLine()) != null) { line = line.trim(); if ((line.length() == 0) || line.startsWith(";")) { continue; } try { classes.add(Class.forName(line, true, cl)); } catch (Throwable t) { } } } catch (Throwable t) { } finally { if (reader != null) { try { reader.close(); } catch (Throwable t) { } } } }
Code Sample 2:
private void innerJob(String inFrom, String inTo, String line, Map<String, Match> result) throws UnsupportedEncodingException, IOException { String subline = line.substring(line.indexOf(inTo) + inTo.length()); String tempStr = subline.substring(subline.indexOf(inFrom) + inFrom.length(), subline.indexOf(inTo)); String inURL = "http://goal.2010worldcup.163.com/data/match/general/" + tempStr.substring(tempStr.indexOf("/") + 1) + ".xml"; URL url = new URL(inURL); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); String inLine = null; String scoreFrom = "score=\""; String homeTo = "\" side=\"Home"; String awayTo = "\" side=\"Away"; String goalInclud = "Stat"; String playerFrom = "playerId=\""; String playerTo = "\" position="; String timeFrom = "time=\""; String timeTo = "\" period"; String teamFinish = "</Team>"; boolean homeStart = false; boolean awayStart = false; while ((inLine = reader.readLine()) != null) { if (inLine.indexOf(teamFinish) != -1) { homeStart = false; awayStart = false; } if (inLine.indexOf(homeTo) != -1) { result.get(key).setHomeScore(inLine.substring(inLine.indexOf(scoreFrom) + scoreFrom.length(), inLine.indexOf(homeTo))); homeStart = true; } if (homeStart && inLine.indexOf(goalInclud) != -1) { MatchEvent me = new MatchEvent(); me.setPlayerName(getPlayerName(inLine.substring(inLine.indexOf(playerFrom) + playerFrom.length(), inLine.indexOf(playerTo)))); me.setTime(inLine.substring(inLine.indexOf(timeFrom) + timeFrom.length(), inLine.indexOf(timeTo))); result.get(key).getHomeEvents().add(me); } if (inLine.indexOf(awayTo) != -1) { result.get(key).setAwayScore(inLine.substring(inLine.indexOf(scoreFrom) + scoreFrom.length(), inLine.indexOf(awayTo))); awayStart = true; } if (awayStart && inLine.indexOf(goalInclud) != -1) { MatchEvent me = new MatchEvent(); me.setPlayerName(getPlayerName(inLine.substring(inLine.indexOf(playerFrom) + playerFrom.length(), inLine.indexOf(playerTo)))); me.setTime(inLine.substring(inLine.indexOf(timeFrom) + timeFrom.length(), inLine.indexOf(timeTo))); result.get(key).getAwayEvents().add(me); } } reader.close(); } |
00
| Code Sample 1:
private void downloadFiles() throws SocketException, IOException { HashSet<String> files_set = new HashSet<String>(); boolean hasWildcarts = false; FTPClient client = new FTPClient(); for (String file : downloadFiles) { files_set.add(file); if (file.contains(WILDCARD_WORD) || file.contains(WILDCARD_DIGIT)) hasWildcarts = true; } client.connect(source.getHost()); client.login(username, password); FTPFile[] files = client.listFiles(source.getPath()); if (!hasWildcarts) { for (FTPFile file : files) { String filename = file.getName(); if (files_set.contains(filename)) { long file_size = file.getSize() / 1024; Calendar cal = file.getTimestamp(); URL source_file = new File(source + file.getName()).toURI().toURL(); DownloadQueue.add(new Download(projectName, parser.getParserID(), source_file, file_size, cal, target + file.getName())); } } } else { for (FTPFile file : files) { String filename = file.getName(); boolean match = false; for (String db_filename : downloadFiles) { db_filename = db_filename.replaceAll("\\" + WILDCARD_WORD, WILDCARD_WORD_PATTERN); db_filename = db_filename.replaceAll("\\" + WILDCARD_DIGIT, WILDCARD_DIGIT_PATTERN); Pattern p = Pattern.compile(db_filename); Matcher m = p.matcher(filename); match = m.matches(); } if (match) { long file_size = file.getSize() / 1024; Calendar cal = file.getTimestamp(); URL source_file = new File(source + file.getName()).toURI().toURL(); DownloadQueue.add(new Download(projectName, parser.getParserID(), source_file, file_size, cal, target + file.getName())); } } } }
Code Sample 2:
private File downloadPDB(String pdbId) { File tempFile = new File(path + "/" + pdbId + ".pdb.gz"); File pdbHome = new File(path); if (!pdbHome.canWrite()) { System.err.println("can not write to " + pdbHome); return null; } String ftp = String.format("ftp://ftp.ebi.ac.uk/pub/databases/msd/pdb_uncompressed/pdb%s.ent", pdbId.toLowerCase()); System.out.println("Fetching " + ftp); try { URL url = new URL(ftp); InputStream conn = url.openStream(); System.out.println("writing to " + tempFile); FileOutputStream outPut = new FileOutputStream(tempFile); GZIPOutputStream gzOutPut = new GZIPOutputStream(outPut); PrintWriter pw = new PrintWriter(gzOutPut); BufferedReader fileBuffer = new BufferedReader(new InputStreamReader(conn)); String line; while ((line = fileBuffer.readLine()) != null) { pw.println(line); } pw.flush(); pw.close(); outPut.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); return null; } return tempFile; } |
00
| Code Sample 1:
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(); }
Code Sample 2:
public void login() { if (email.isEmpty() || pass.isEmpty()) { NotifyUtil.warn("Acount Data", "You need to specify and account e-mail and password.", false); return; } final ProgressHandle handle = ProgressHandleFactory.createHandle("Connecting to Facebook ..."); final Runnable task = new Runnable() { @Override public void run() { handle.start(); handle.switchToIndeterminate(); FacebookJsonRestClient client = new FacebookJsonRestClient(API_KEY, SECRET); client.setIsDesktop(true); HttpURLConnection connection; List<String> cookies; try { String token = client.auth_createToken(); String post_url = "http://www.facebook.com/login.php"; String get_url = "http://www.facebook.com/login.php" + "?api_key=" + API_KEY + "&v=1.0" + "&auth_token=" + token; HttpURLConnection.setFollowRedirects(true); connection = (HttpURLConnection) new URL(get_url).openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401"); connection.setRequestProperty("Host", "www.facebook.com"); connection.setRequestProperty("Accept-Charset", "UFT-8"); connection.connect(); cookies = connection.getHeaderFields().get("Set-Cookie"); connection = (HttpURLConnection) new URL(post_url).openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401"); connection.setRequestProperty("Host", "www.facebook.com"); connection.setRequestProperty("Accept-Charset", "UFT-8"); if (cookies != null) { for (String cookie : cookies) { connection.addRequestProperty("Cookie", cookie.split(";", 2)[0]); } } String params = "api_key=" + API_KEY + "&auth_token=" + token + "&email=" + URLEncoder.encode(email, "UTF-8") + "&pass=" + URLEncoder.encode(pass, "UTF-8") + "&v=1.0"; connection.setRequestProperty("Content-Length", Integer.toString(params.length())); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setDoOutput(true); connection.connect(); connection.getOutputStream().write(params.toString().getBytes("UTF-8")); connection.getOutputStream().close(); cookies = connection.getHeaderFields().get("Set-Cookie"); if (cookies == null) { ActionListener listener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String url = "http://www.chartsy.org/facebook/"; DesktopUtil.browseAndWarn(url, null); } }; NotifyUtil.show("Application Permission", "You need to grant permission first.", MessageType.WARNING, listener, false); connection.disconnect(); loggedIn = false; } else { sessionKey = client.auth_getSession(token); sessionSecret = client.getSessionSecret(); loggedIn = true; } connection.disconnect(); handle.finish(); } catch (FacebookException fex) { handle.finish(); NotifyUtil.error("Login Error", fex.getMessage(), fex, false); } catch (IOException ioex) { handle.finish(); NotifyUtil.error("Login Error", ioex.getMessage(), ioex, false); } } }; WindowManager.getDefault().invokeWhenUIReady(task); } |
00
| Code Sample 1:
public Image getURLImage(String url) { if (!images.containsKey(url)) { try { URL img = new URL(url); images.put(url, new Image(null, img.openStream())); } catch (Exception e) { throw new RuntimeException(e.getMessage() + ": " + url); } } imageTimes.put(url, System.currentTimeMillis()); return images.get(url); }
Code Sample 2:
private void preprocessObjects(GeoObject[] objects) throws IOException { System.out.println("objects.length " + objects.length); for (int i = 0; i < objects.length; i++) { String fileName = objects[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("i: " + " world filename " + tmp); File worldFile = new File(tmp); if (worldFile.exists()) { BufferedReader worldFileReader = new BufferedReader(new InputStreamReader(new FileInputStream(worldFile))); if (staticDebugOn) debug("b4nextline: "); line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); if (line != null) { line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); tokenizer = new StringTokenizer(line, " \n\t\r\"", false); objects[i].setLon(Double.valueOf(tokenizer.nextToken()).doubleValue()); line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); tokenizer = new StringTokenizer(line, " \n\t\r\"", false); objects[i].setLat(Double.valueOf(tokenizer.nextToken()).doubleValue()); } } File file = new File(objects[i].getPath()); if (file.exists()) { System.out.println("object src file found "); 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); objects[i].setPath(tmp); file = new File(fileName); if (file.exists()) { 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(); } } } } |
00
| Code Sample 1:
@Override protected IStatus runCancelableRunnable(IProgressMonitor monitor) { IStatus returnValue = Status.OK_STATUS; monitor.beginTask(NLS.bind(Messages.SaveFileOnDiskHandler_SavingFiles, open), informationUnitsFromExecutionEvent.size()); for (InformationUnit informationUnit : informationUnitsFromExecutionEvent) { if (!monitor.isCanceled()) { monitor.setTaskName(NLS.bind(Messages.SaveFileOnDiskHandler_Saving, informationUnit.getLabel())); InformationStructureRead read = InformationStructureRead.newSession(informationUnit); read.getValueByNodeId(Activator.FILENAME); IFile binaryReferenceFile = InformationUtil.getBinaryReferenceFile(informationUnit); FileWriter writer = null; try { if (binaryReferenceFile != null) { File file = new File(open, (String) read.getValueByNodeId(Activator.FILENAME)); InputStream contents = binaryReferenceFile.getContents(); writer = new FileWriter(file); IOUtils.copy(contents, writer); monitor.worked(1); } } catch (Exception e) { returnValue = StatusCreator.newStatus(NLS.bind(Messages.SaveFileOnDiskHandler_ErrorSaving, informationUnit.getLabel(), e)); break; } finally { if (writer != null) { try { writer.flush(); writer.close(); } catch (IOException e) { } } } } } return returnValue; }
Code Sample 2:
@Override public Object getImage(String key) { if (key.indexOf("exhibition/") != -1) { InputStream inputStream = null; try { URL url = new URL(getBaseURL() + "icons/" + key + ".png"); inputStream = url.openStream(); return url; } catch (Exception e) { } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { ExceptionHandlingService.INSTANCE.handleException(e); } } } } return super.getImage(key); } |
00
| Code Sample 1:
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; } } } }
Code Sample 2:
protected int sendData(String submitName, String submitValue) throws HttpException, IOException, SAXException { PostMethod postMethod = null; try { postMethod = new PostMethod(getDocumentBase().toString()); postMethod.getParams().setCookiePolicy(org.apache.commons.httpclient.cookie.CookiePolicy.IGNORE_COOKIES); postMethod.addRequestHeader("Cookie", getWikiPrefix() + "_session=" + getSession() + "; " + getWikiPrefix() + "UserID=" + getUserId() + "; " + getWikiPrefix() + "UserName=" + getUserName() + "; "); List<Part> parts = new ArrayList<Part>(); for (String s : new String[] { "wpSection", "wpEdittime", "wpScrolltop", "wpStarttime", "wpEditToken" }) { parts.add(new StringPart(s, StringEscapeUtils.unescapeJava(getNonNullParameter(s)))); } parts.add(new StringPart("action", "edit")); parts.add(new StringPart("wpTextbox1", getArticleContent())); parts.add(new StringPart("wpSummary", getSummary())); parts.add(new StringPart("wpAutoSummary", Digest.MD5.isImplemented() ? Digest.MD5.encrypt(getSummary()) : "")); parts.add(new StringPart(submitName, submitValue)); MultipartRequestEntity requestEntity = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), postMethod.getParams()); postMethod.setRequestEntity(requestEntity); int status = getHttpClient().executeMethod(postMethod); IOUtils.copyTo(postMethod.getResponseBodyAsStream(), System.err); return status; } catch (HttpException err) { throw err; } catch (IOException err) { throw err; } finally { if (postMethod != null) postMethod.releaseConnection(); } } |
11
| Code Sample 1:
private static void copyFile(File source, File destination) throws IOException, SecurityException { if (!destination.exists()) destination.createNewFile(); FileChannel sourceChannel = null; FileChannel destinationChannel = null; try { sourceChannel = new FileInputStream(source).getChannel(); destinationChannel = new FileOutputStream(destination).getChannel(); long count = 0; long size = sourceChannel.size(); while ((count += destinationChannel.transferFrom(sourceChannel, 0, size - count)) < size) ; } finally { if (sourceChannel != null) sourceChannel.close(); if (destinationChannel != null) destinationChannel.close(); } }
Code Sample 2:
static void copy(String src, String dest) throws IOException { File ifp = new File(src); File ofp = new File(dest); if (ifp.exists() == false) { throw new IOException("file '" + src + "' does not exist"); } FileInputStream fis = new FileInputStream(ifp); FileOutputStream fos = new FileOutputStream(ofp); byte[] b = new byte[1024]; while (fis.read(b) > 0) fos.write(b); fis.close(); fos.close(); } |
00
| Code Sample 1:
public int process(ProcessorContext context) throws InterruptedException, ProcessorException { logger.info("JAISaveTask:process"); final RenderedOp im = (RenderedOp) context.get("RenderedOp"); final String path = "s3://s3.amazonaws.com/rssfetch/" + (new Guid()); final PNGEncodeParam.RGB encPar = new PNGEncodeParam.RGB(); encPar.setTransparentRGB(new int[] { 0, 0, 0 }); File tmpFile = null; try { tmpFile = File.createTempFile("thmb", ".png"); OutputStream out = new FileOutputStream(tmpFile); final ParameterBlock pb = (new ParameterBlock()).addSource(im).add(out).add("png").add(encPar); JAI.create("encode", pb, null); out.flush(); out.close(); FileInputStream in = new FileInputStream(tmpFile); final XFile xfile = new XFile(path); final XFileOutputStream xout = new XFileOutputStream(xfile); final com.luzan.common.nfs.s3.XFileExtensionAccessor xfa = ((com.luzan.common.nfs.s3.XFileExtensionAccessor) xfile.getExtensionAccessor()); if (xfa != null) { xfa.setMimeType("image/png"); xfa.setContentLength(tmpFile.length()); } IOUtils.copy(in, xout); xout.flush(); xout.close(); in.close(); context.put("outputPath", path); } catch (IOException e) { logger.error(e); throw new ProcessorException(e); } catch (Throwable e) { logger.error(e); throw new ProcessorException(e); } finally { if (tmpFile != null && tmpFile.exists()) { tmpFile.delete(); } } return TaskState.STATE_MO_START + TaskState.STATE_ENCODE; }
Code Sample 2:
public static String getMd5Hash(String text) { StringBuffer result = new StringBuffer(32); try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(text.getBytes()); Formatter f = new Formatter(result); byte[] digest = md5.digest(); for (int i = 0; i < digest.length; i++) { f.format("%02x", new Object[] { new Byte(digest[i]) }); } } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } return result.toString(); } |
11
| Code Sample 1:
@SuppressWarnings("unchecked") public ArrayList<GmailContact> getAllContacts() throws GmailException { String query = properties.getString("export_page"); query = query.replace("[RANDOM_INT]", "" + random.nextInt()); int statusCode = -1; GetMethod get = new GetMethod(query); if (log.isInfoEnabled()) log.info("getting all contacts ..."); try { statusCode = client.executeMethod(get); if (statusCode != 200) throw new GmailException("In contacts export page: Status code expected: 200 -> Status code returned: " + statusCode); } catch (HttpException e) { throw new GmailException("HttpException in contacts export page:" + e.getMessage()); } catch (IOException e) { throw new GmailException("IOException in contacts export page:" + e.getMessage()); } finally { get.releaseConnection(); } if (log.isTraceEnabled()) log.trace("accessing contacts export page successful..."); String query_post = properties.getString("outlook_export_page"); PostMethod post = new PostMethod(query_post); post.addRequestHeader("Accept-Encoding", "gzip,deflate"); post.addRequestHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.8"); NameValuePair[] data = { new NameValuePair("at", getCookie("GMAIL_AT")), new NameValuePair("ecf", "o"), new NameValuePair("ac", "Export Contacts") }; post.setRequestBody(data); if (log.isTraceEnabled()) log.trace("getting contacts csv file..."); try { statusCode = client.executeMethod(post); if (statusCode != 200) throw new GmailException("In csv file post: Status code expected: 200 -> Status code returned: " + statusCode); if (log.isTraceEnabled()) log.trace("Gmail: csv charset: " + post.getResponseCharSet()); GMAIL_OUTPUT_CHARSET = post.getResponseCharSet(); InputStreamReader isr = new InputStreamReader(new GZIPInputStream(post.getResponseBodyAsStream()), post.getResponseCharSet()); CSVReader reader = new CSVReader(isr); List csvEntries = reader.readAll(); reader.close(); ArrayList<GmailContact> contacts = new ArrayList<GmailContact>(); MessageDigest m = MessageDigest.getInstance("MD5"); if (log.isTraceEnabled()) log.trace("creating Gmail contacts..."); for (int i = 1; i < csvEntries.size(); i++) { GmailContact contact = new GmailContact(); String[] value = (String[]) csvEntries.get(i); for (int j = 0; j < value.length; j++) { switch(j) { case 0: contact.setName(value[j]); break; case 1: contact.setEmail(value[j]); if (contact.getName() == null) contact.setIdName(value[j]); else contact.setIdName(contact.getName() + value[j]); break; case 2: contact.setNotes(value[j]); break; case 3: contact.setEmail2(value[j]); break; case 4: contact.setEmail3(value[j]); break; case 5: contact.setMobilePhone(value[j]); break; case 6: contact.setPager(value[j]); break; case 7: contact.setCompany(value[j]); break; case 8: contact.setJobTitle(value[j]); break; case 9: contact.setHomePhone(value[j]); break; case 10: contact.setHomePhone2(value[j]); break; case 11: contact.setHomeFax(value[j]); break; case 12: contact.setHomeAddress(value[j]); break; case 13: contact.setBusinessPhone(value[j]); break; case 14: contact.setBusinessPhone2(value[j]); break; case 15: contact.setBusinessFax(value[j]); break; case 16: contact.setBusinessAddress(value[j]); break; case 17: contact.setOtherPhone(value[j]); break; case 18: contact.setOtherFax(value[j]); break; case 19: contact.setOtherAddress(value[j]); break; } } m.update(contact.toString().getBytes()); if (log.isTraceEnabled()) log.trace("setting Md5 Hash..."); contact.setMd5Hash(new BigInteger(m.digest()).toString()); contacts.add(contact); } if (log.isTraceEnabled()) log.trace("Mapping contacts uid..."); Collections.sort(contacts); ArrayList<GmailContact> idList = getAllContactsID(); for (int i = 0; i < idList.size(); i++) { contacts.get(i).setId(idList.get(i).getId()); } if (log.isInfoEnabled()) log.info("getting all contacts info successful..."); return contacts; } catch (HttpException e) { throw new GmailException("HttpException in csv file post:" + e.getMessage()); } catch (IOException e) { throw new GmailException("IOException in csv file post:" + e.getMessage()); } catch (NoSuchAlgorithmException e) { throw new GmailException("No such md5 algorithm " + e.getMessage()); } finally { post.releaseConnection(); } }
Code Sample 2:
public static URL getAuthenticationURL(String apiKey, String permission, String sharedSecret) throws Exception { String apiSig = sharedSecret + "api_key" + apiKey + "perms" + permission; MessageDigest m = MessageDigest.getInstance("MD5"); m.update(apiSig.getBytes(), 0, apiSig.length()); apiSig = new BigInteger(1, m.digest()).toString(16); StringBuffer buffer = new StringBuffer(); buffer.append("http://flickr.com/services/auth/?"); buffer.append("api_key=" + apiKey); buffer.append("&").append("perms=").append(permission); buffer.append("&").append("api_sig=").append(apiSig); return new URL(buffer.toString()); } |
00
| Code Sample 1:
public String contactService(String service, StringBuffer xmlRequest) throws Exception { Logger.debug(UPSConnections.class, "UPS CONNECTIONS ***** Started " + service + " " + new Date().toString() + " *****"); HttpURLConnection connection; URL url; String response = ""; try { Logger.debug(UPSConnections.class, "connect to " + protocol + "://" + hostname + "/" + URLPrefix + "/" + service); if (protocol.equalsIgnoreCase("https")) { java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); System.getProperties().put("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol"); url = new URL(protocol + "://" + hostname + "/" + URLPrefix + "/" + service); connection = (HttpsURLConnection) url.openConnection(); } else { url = new URL(protocol + "://" + hostname + "/" + URLPrefix + "/" + service); connection = (HttpURLConnection) url.openConnection(); } Logger.debug(UPSConnections.class, "Establishing connection with " + url.toString()); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); OutputStream out = connection.getOutputStream(); StringBuffer request = new StringBuffer(); request.append(accessXMLRequest()); request.append(xmlRequest); out.write((request.toString()).getBytes()); Logger.debug(UPSConnections.class, "Transmission sent to " + url.toString() + ":\n" + xmlRequest); out.close(); try { response = readURLConnection(connection); } catch (Exception e) { Logger.debug(UPSConnections.class, "Error in reading URL Connection" + e.getMessage()); throw e; } Logger.debug(UPSConnections.class, "Response = " + response); } catch (Exception e1) { Logger.info(UPSConnections.class, "Error sending data to server" + e1.toString()); Logger.debug(UPSConnections.class, "Error sending data to server" + e1.toString()); } finally { Logger.info(UPSConnections.class, "****** Transmission Finished " + service + " " + new Date().toString() + " *********"); Logger.debug(UPSConnections.class, "****** Transmission Finished " + service + " " + new Date().toString() + " *********"); } return response; }
Code Sample 2:
private void handleNodeUp(long eventID, long nodeID, String eventTime) { Category log = ThreadCategory.getInstance(OutageWriter.class); if (eventID == -1 || nodeID == -1) { log.warn(EventConstants.NODE_UP_EVENT_UEI + " ignored - info incomplete - eventid/nodeid: " + eventID + "/" + nodeID); return; } Connection dbConn = null; try { dbConn = DatabaseConnectionFactory.getInstance().getConnection(); int count = 0; if (openOutageExists(dbConn, nodeID)) { try { dbConn.setAutoCommit(false); } catch (SQLException sqle) { log.error("Unable to change database AutoCommit to FALSE", sqle); return; } PreparedStatement outageUpdater = dbConn.prepareStatement(OutageConstants.DB_UPDATE_OUTAGES_FOR_NODE); outageUpdater.setLong(1, eventID); outageUpdater.setTimestamp(2, convertEventTimeIntoTimestamp(eventTime)); outageUpdater.setLong(3, nodeID); count = outageUpdater.executeUpdate(); outageUpdater.close(); } else { log.warn("\'" + EventConstants.NODE_UP_EVENT_UEI + "\' for " + nodeID + " no open record."); } try { dbConn.commit(); if (log.isDebugEnabled()) log.debug("nodeUp closed " + count + " outages for nodeid " + nodeID + " in DB"); } catch (SQLException se) { log.warn("Rolling back transaction, nodeUp could not be recorded for nodeId: " + nodeID, se); try { dbConn.rollback(); } catch (SQLException sqle) { log.warn("SQL exception during rollback, reason", sqle); } } } catch (SQLException se) { log.warn("SQL exception while handling \'nodeRegainedService\'", se); } finally { try { if (dbConn != null) dbConn.close(); } catch (SQLException e) { log.warn("Exception closing JDBC connection", e); } } } |
11
| Code Sample 1:
final void saveProject(Project project, final File file) { if (projectsList.contains(project)) { if (project.isDirty() || !file.getParentFile().equals(workspaceDirectory)) { try { if (!file.exists()) { if (!file.createNewFile()) throw new IOException("cannot create file " + file.getAbsolutePath()); } File tmpFile = File.createTempFile("JFPSM", ".tmp"); ZipOutputStream zoStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(file))); zoStream.setMethod(ZipOutputStream.DEFLATED); ZipEntry projectXMLEntry = new ZipEntry("project.xml"); projectXMLEntry.setMethod(ZipEntry.DEFLATED); zoStream.putNextEntry(projectXMLEntry); CustomXMLEncoder encoder = new CustomXMLEncoder(new BufferedOutputStream(new FileOutputStream(tmpFile))); encoder.writeObject(project); encoder.close(); int bytesIn; byte[] readBuffer = new byte[1024]; FileInputStream fis = new FileInputStream(tmpFile); while ((bytesIn = fis.read(readBuffer)) != -1) zoStream.write(readBuffer, 0, bytesIn); fis.close(); ZipEntry entry; String floorDirectory; for (FloorSet floorSet : project.getLevelSet().getFloorSetsList()) for (Floor floor : floorSet.getFloorsList()) { floorDirectory = "levelset/" + floorSet.getName() + "/" + floor.getName() + "/"; for (MapType type : MapType.values()) { entry = new ZipEntry(floorDirectory + type.getFilename()); entry.setMethod(ZipEntry.DEFLATED); zoStream.putNextEntry(entry); ImageIO.write(floor.getMap(type).getImage(), "png", zoStream); } } final String tileDirectory = "tileset/"; for (Tile tile : project.getTileSet().getTilesList()) for (int textureIndex = 0; textureIndex < tile.getMaxTextureCount(); textureIndex++) if (tile.getTexture(textureIndex) != null) { entry = new ZipEntry(tileDirectory + tile.getName() + textureIndex + ".png"); entry.setMethod(ZipEntry.DEFLATED); zoStream.putNextEntry(entry); ImageIO.write(tile.getTexture(textureIndex), "png", zoStream); } zoStream.close(); tmpFile.delete(); } catch (IOException ioe) { throw new RuntimeException("The project " + project.getName() + " cannot be saved!", ioe); } } } else throw new IllegalArgumentException("The project " + project.getName() + " is not handled by this project set!"); }
Code Sample 2:
public static void resourceToFile(final String resource, final String filePath) throws IOException { log.debug("Classloader is " + IOCopyUtils.class.getClassLoader()); InputStream in = IOCopyUtils.class.getResourceAsStream(resource); if (in == null) { log.warn("Resource not '" + resource + "' found. Try to prefix with '/'"); in = IOCopyUtils.class.getResourceAsStream("/" + resource); } if (in == null) { throw new IOException("Resource not '" + resource + "' found."); } final File file = new File(filePath); final OutputStream out = FileUtils.openOutputStream(file); final int bytes = IOUtils.copy(in, out); IOUtils.closeQuietly(out); IOUtils.closeQuietly(in); log.debug("Copied resource '" + resource + "' to file " + filePath + " (" + bytes + " bytes)"); } |
00
| Code Sample 1:
public void addUser(String name, String unit, String organizeName, int userId, int orgId, String email) { Connection connection = null; PreparedStatement ps = null; DBOperation dbo = factory.createDBOperation(POOL_NAME); try { connection = dbo.getConnection(); ps = connection.prepareStatement(INSERT_USER); ps.setInt(1, AddrslistMainDao.getNewID()); ps.setInt(2, -100); ps.setString(3, name.substring(0, 1)); ps.setString(4, name.substring(1)); ps.setString(5, unit); ps.setString(6, organizeName); ps.setString(7, ""); ps.setString(8, email); ps.setString(9, ""); ps.setString(10, ""); ps.setString(11, ""); ps.setString(12, ""); ps.setString(13, ""); ps.setString(14, ""); ps.setString(15, ""); ps.setString(16, ""); ps.setString(17, ""); ps.setString(18, ""); ps.setInt(19, userId); ps.setInt(20, orgId); ps.executeUpdate(); connection.commit(); } catch (Exception e) { e.printStackTrace(); try { connection.rollback(); } catch (SQLException e1) { } } finally { try { ps.close(); connection.close(); dbo.close(); } catch (Exception e) { } } }
Code Sample 2:
private static void getFileFtp(String user, String password, String host, int port, String fileName, String location) throws Exception { Log.info("\nretrieve " + fileName + NEW_LINE); FTPClient client = new FTPClient(); client.connect(host, port); int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new Exception("FTP fail to connect"); } if (!client.login(user, password)) { throw new Exception("FTP fail to login"); } try { File locationFile = new File(location); File dest = new File(locationFile, fileName); if (dest.exists()) { dest.delete(); } else { locationFile.mkdirs(); } boolean status = client.changeWorkingDirectory("/"); Log.info("chdir-status:" + status + NEW_LINE); client.setFileTransferMode(FTPClient.BINARY_FILE_TYPE); client.setFileType(FTPClient.BINARY_FILE_TYPE); client.enterLocalActiveMode(); InputStream in = client.retrieveFileStream(fileName); if (in == null) { Log.error("Input stream is null\n"); throw new Exception("Fail to retrieve file " + fileName); } Thread.sleep(3000); saveInputStreamToFile(in, new File(location, fileName)); } finally { client.disconnect(); } } |
11
| Code Sample 1:
public static boolean copyFile(String sourceFileName, String destFileName) { if (sourceFileName == null || destFileName == null) return false; if (sourceFileName.equals(destFileName)) return false; try { java.io.FileInputStream in = new java.io.FileInputStream(sourceFileName); java.io.FileOutputStream out = new java.io.FileOutputStream(destFileName); try { byte[] buf = new byte[31000]; int read = in.read(buf); while (read > -1) { out.write(buf, 0, read); read = in.read(buf); } } finally { in.close(); out.close(); } } catch (Exception e) { System.out.println(e.toString()); return false; } return true; }
Code Sample 2:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } |
00
| Code Sample 1:
public static void 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 String useService(HashMap<String, String> input) { String output = ""; if (input.size() < 1) { return ""; } String data = ""; try { for (String key : input.keySet()) { data += "&" + URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(input.get(key), "UTF-8"); } data = data.substring(1); URL url = new URL(serviceUrl); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { output += line; } wr.close(); rd.close(); } catch (Exception e) { e.printStackTrace(); } return output; } |
11
| Code Sample 1:
public static void doIt(String action) { int f = -1; Statement s = null; Connection connection = null; try { init(); log.info("<<< Looking up UserTransaction >>>"); UserTransaction usertransaction = (UserTransaction) context.lookup("java:comp/UserTransaction"); log.info("<<< beginning the transaction >>>"); usertransaction.begin(); log.info("<<< Connecting to xadatasource >>>"); connection = xadatasource.getConnection(); log.info("<<< Connected >>>"); s = connection.createStatement(); s.executeUpdate("update testdata set foo=foo + 1 where id=1"); if ((action != null) && action.equals("commit")) { log.info("<<< committing the transaction >>>"); usertransaction.commit(); } else { log.info("<<< rolling back the transaction >>>"); usertransaction.rollback(); } log.info("<<< transaction complete >>>"); } catch (Exception e) { log.error("doIt", e); } finally { try { s.close(); connection.close(); } catch (Exception x) { log.error("problem closing statement/connection", x); } } }
Code Sample 2:
public void criarTopicoQuestao(Questao q, Integer idTopico) throws SQLException { PreparedStatement stmt = null; String sql = "INSERT INTO questao_topico (id_questao, id_disciplina, id_topico) VALUES (?,?,?)"; try { stmt = conexao.prepareStatement(sql); stmt.setInt(1, q.getIdQuestao()); stmt.setInt(2, q.getDisciplina().getIdDisciplina()); stmt.setInt(3, idTopico); stmt.executeUpdate(); conexao.commit(); } catch (SQLException e) { conexao.rollback(); throw e; } } |
11
| Code Sample 1:
public void postProcess() throws StopWriterVisitorException { dxfWriter.postProcess(); try { FileChannel fcinDxf = new FileInputStream(fTemp).getChannel(); FileChannel fcoutDxf = new FileOutputStream(m_Fich).getChannel(); DriverUtilities.copy(fcinDxf, fcoutDxf); fTemp.delete(); } catch (FileNotFoundException e) { throw new StopWriterVisitorException(getName(), e); } catch (IOException e) { throw new StopWriterVisitorException(getName(), e); } }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } |
00
| Code Sample 1:
private void setInlineXML(Entry entry, DatastreamXMLMetadata ds) throws UnsupportedEncodingException, StreamIOException { String content; if (m_obj.hasContentModel(Models.SERVICE_DEPLOYMENT_3_0) && (ds.DatastreamID.equals("SERVICE-PROFILE") || ds.DatastreamID.equals("WSDL"))) { content = DOTranslationUtility.normalizeInlineXML(new String(ds.xmlContent, m_encoding), m_transContext); } else { content = new String(ds.xmlContent, m_encoding); } if (m_format.equals(ATOM_ZIP1_1)) { String name = ds.DSVersionID + ".xml"; try { m_zout.putNextEntry(new ZipEntry(name)); InputStream is = new ByteArrayInputStream(content.getBytes(m_encoding)); IOUtils.copy(is, m_zout); m_zout.closeEntry(); is.close(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } IRI iri = new IRI(name); entry.setSummary(ds.DSVersionID); entry.setContent(iri, ds.DSMIME); } else { entry.setContent(content, ds.DSMIME); } }
Code Sample 2:
public static String md5(String texto) { String resultado; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(texto.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); resultado = hash.toString(16); if (resultado.length() < 32) { char chars[] = new char[32 - resultado.length()]; Arrays.fill(chars, '0'); resultado = new String(chars) + resultado; } } catch (NoSuchAlgorithmException e) { resultado = e.toString(); } return resultado; } |
00
| Code Sample 1:
public static void copyFile(String fromFilePath, String toFilePath, boolean overwrite) throws IOException { File fromFile = new File(fromFilePath); File toFile = new File(toFilePath); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFilePath); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFilePath); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFilePath); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!overwrite) { throw new IOException(toFilePath + " already exists!"); } if (!toFile.canWrite()) { throw new IOException("FileCopy: destination file is unwriteable: " + toFilePath); } String parent = toFile.getParent(); if (parent == null) { parent = System.getProperty("user.dir"); } File dir = new File(parent); if (!dir.exists()) { throw new IOException("FileCopy: destination directory doesn't exist: " + parent); } if (dir.isFile()) { throw new IOException("FileCopy: destination is not a directory: " + parent); } if (!dir.canWrite()) { throw new IOException("FileCopy: destination directory is unwriteable: " + parent); } } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { long lastModified = fromFile.lastModified(); toFile.setLastModified(lastModified); if (from != null) { try { from.close(); } catch (IOException e) { } } if (to != null) { try { to.close(); } catch (IOException e) { } } } }
Code Sample 2:
public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt.executeUpdate(sql); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } } |
00
| Code Sample 1:
public static byte[] loadURLToBuffer(URL url, int maxLength) throws IOException { byte[] buf = new byte[maxLength]; byte[] data = null; int iCount = 0; BufferedInputStream in = new BufferedInputStream(url.openStream(), 20480); iCount = in.read(buf, 0, buf.length); if (iCount != -1) { data = new byte[iCount]; System.arraycopy(buf, 0, data, 0, iCount); } in.close(); return data; }
Code Sample 2:
private void handleInterfaceReparented(String ipAddr, Parms eventParms) { Category log = ThreadCategory.getInstance(OutageWriter.class); if (log.isDebugEnabled()) log.debug("interfaceReparented event received..."); if (ipAddr == null || eventParms == null) { log.warn(EventConstants.INTERFACE_REPARENTED_EVENT_UEI + " ignored - info incomplete - ip/parms: " + ipAddr + "/" + eventParms); return; } long oldNodeId = -1; long newNodeId = -1; String parmName = null; Value parmValue = null; String parmContent = null; Enumeration parmEnum = eventParms.enumerateParm(); while (parmEnum.hasMoreElements()) { Parm parm = (Parm) parmEnum.nextElement(); parmName = parm.getParmName(); parmValue = parm.getValue(); if (parmValue == null) continue; else parmContent = parmValue.getContent(); if (parmName.equals(EventConstants.PARM_OLD_NODEID)) { try { oldNodeId = Integer.valueOf(parmContent).intValue(); } catch (NumberFormatException nfe) { log.warn("Parameter " + EventConstants.PARM_OLD_NODEID + " cannot be non-numeric"); oldNodeId = -1; } } else if (parmName.equals(EventConstants.PARM_NEW_NODEID)) { try { newNodeId = Integer.valueOf(parmContent).intValue(); } catch (NumberFormatException nfe) { log.warn("Parameter " + EventConstants.PARM_NEW_NODEID + " cannot be non-numeric"); newNodeId = -1; } } } if (newNodeId == -1 || oldNodeId == -1) { log.warn("Unable to process 'interfaceReparented' event, invalid event parm."); return; } Connection dbConn = null; try { dbConn = DatabaseConnectionFactory.getInstance().getConnection(); try { dbConn.setAutoCommit(false); } catch (SQLException sqle) { log.error("Unable to change database AutoCommit to FALSE", sqle); return; } PreparedStatement reparentOutagesStmt = dbConn.prepareStatement(OutageConstants.DB_REPARENT_OUTAGES); reparentOutagesStmt.setLong(1, newNodeId); reparentOutagesStmt.setLong(2, oldNodeId); reparentOutagesStmt.setString(3, ipAddr); int count = reparentOutagesStmt.executeUpdate(); try { dbConn.commit(); if (log.isDebugEnabled()) log.debug("Reparented " + count + " outages - ip: " + ipAddr + " reparented from " + oldNodeId + " to " + newNodeId); } catch (SQLException se) { log.warn("Rolling back transaction, reparent outages failed for newNodeId/ipAddr: " + newNodeId + "/" + ipAddr); try { dbConn.rollback(); } catch (SQLException sqle) { log.warn("SQL exception during rollback, reason", sqle); } } reparentOutagesStmt.close(); } catch (SQLException se) { log.warn("SQL exception while handling \'interfaceReparented\'", se); } finally { try { if (dbConn != null) dbConn.close(); } catch (SQLException e) { log.warn("Exception closing JDBC connection", e); } } } |
11
| Code Sample 1:
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { String pathInfo = httpServletRequest.getPathInfo(); log.info("PathInfo: " + pathInfo); if (pathInfo == null || pathInfo.equals("") || pathInfo.equals("/")) { httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); return; } String fileName = pathInfo.charAt(0) == '/' ? pathInfo.substring(1) : pathInfo; log.info("FileName: " + fileName); Connection con = null; PreparedStatement ps = null; ResultSet rs = null; try { con = getDataSource().getConnection(); ps = con.prepareStatement("select file, size from files where name=?"); ps.setString(1, fileName); rs = ps.executeQuery(); if (rs.next()) { httpServletResponse.setContentType(getServletContext().getMimeType(fileName)); httpServletResponse.setContentLength(rs.getInt("size")); OutputStream os = httpServletResponse.getOutputStream(); org.apache.commons.io.IOUtils.copy(rs.getBinaryStream("file"), os); os.flush(); } else { httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } catch (SQLException e) { throw new ServletException(e); } finally { if (rs != null) try { rs.close(); } catch (SQLException e) { } if (ps != null) try { ps.close(); } catch (SQLException e) { } if (con != null) try { con.close(); } catch (SQLException e) { } } }
Code Sample 2:
void shutdown(final boolean unexpected) { if (unexpected) { log.warn("S H U T D O W N --- received unexpected shutdown request."); } else { log.info("S H U T D O W N --- start regular shutdown."); } if (this.uncaughtException != null) { log.warn("Shutdown probably caused by the following Exception.", this.uncaughtException); } log.error("check if we need the controler listener infrastructure"); if (this.dumpDataAtEnd) { new PopulationWriter(this.population, this.network).write(this.controlerIO.getOutputFilename(FILENAME_POPULATION)); new NetworkWriter(this.network).write(this.controlerIO.getOutputFilename(FILENAME_NETWORK)); new ConfigWriter(this.config).write(this.controlerIO.getOutputFilename(FILENAME_CONFIG)); if (!unexpected && this.getConfig().vspExperimental().isWritingOutputEvents()) { File toFile = new File(this.controlerIO.getOutputFilename("output_events.xml.gz")); File fromFile = new File(this.controlerIO.getIterationFilename(this.getLastIteration(), "events.xml.gz")); IOUtils.copyFile(fromFile, toFile); } } if (unexpected) { log.info("S H U T D O W N --- unexpected shutdown request completed."); } else { log.info("S H U T D O W N --- regular shutdown completed."); } try { Runtime.getRuntime().removeShutdownHook(this.shutdownHook); } catch (IllegalStateException e) { log.info("Cannot remove shutdown hook. " + e.getMessage()); } this.shutdownHook = null; this.collectLogMessagesAppender = null; IOUtils.closeOutputDirLogging(); } |
11
| Code Sample 1:
public static void main(String[] args) { if (args.length == 0) { System.out.println("Specify name of the file, just one entry per line"); System.exit(0); } File inFile = new File(args[0]); BufferedReader myBR = null; File outFile = new File(args[0] + ".xml"); BufferedWriter myBW = null; try { myBR = new BufferedReader(new FileReader(inFile)); myBW = new BufferedWriter(new FileWriter(outFile)); } catch (Exception ex) { System.out.println("IN: " + inFile.getAbsolutePath()); System.out.println("OUT: " + outFile.getAbsolutePath()); ex.printStackTrace(); System.exit(0); } try { String readLine; while ((readLine = myBR.readLine()) != null) { myBW.write("<dbColumn name=\"" + readLine + "\" display=\"" + readLine + "\" panel=\"CENTER\" >"); myBW.write("\n"); myBW.write("<dbType name=\"text\" maxVal=\"10\" defaultVal=\"\" sizeX=\"5\"/>"); myBW.write("\n"); myBW.write("</dbColumn>"); myBW.write("\n"); } myBW.close(); myBR.close(); } catch (Exception ex) { ex.printStackTrace(); System.exit(0); } System.out.println("OUT: " + outFile.getAbsolutePath()); System.out.println("erzeugt"); }
Code Sample 2:
public static File writeInternalFile(Context cx, URL url, String dir, String filename) { FileOutputStream fos = null; File fi = null; try { fi = newInternalFile(cx, dir, filename); fos = FileUtils.openOutputStream(fi); int length = IOUtils.copy(url.openStream(), fos); log(length + " bytes copyed."); } catch (IOException e) { AIOUtils.log("", e); } finally { try { fos.close(); } catch (IOException e) { AIOUtils.log("", e); } } return fi; } |
00
| Code Sample 1:
protected String readFileUsingHttp(String fileUrlName) { String response = ""; try { URL url = new URL(fileUrlName); URLConnection connection = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) connection; httpConn.setRequestProperty("Content-Type", "text/html"); httpConn.setRequestProperty("Content-Length", "0"); httpConn.setRequestMethod("GET"); httpConn.setDoOutput(true); httpConn.setDoInput(true); httpConn.setAllowUserInteraction(false); InputStreamReader isr = new InputStreamReader(httpConn.getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine = ""; while ((inputLine = in.readLine()) != null) { response += inputLine + "\n"; } if (response.endsWith("\n")) { response = response.substring(0, response.length() - 1); } in.close(); } catch (Exception x) { x.printStackTrace(); } return response; }
Code Sample 2:
public static void copyFile(final File sourceFile, final File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileInputStream inStream = null; FileOutputStream outStream = null; FileChannel source = null; FileChannel destination = null; try { source = (inStream = new FileInputStream(sourceFile)).getChannel(); destination = (outStream = new FileOutputStream(destFile)).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { closeIO(source); closeIO(inStream); closeIO(destination); closeIO(outStream); } } |
00
| Code Sample 1:
private void writeToFile(Body b, File mime4jFile) throws FileNotFoundException, IOException { if (b instanceof TextBody) { String charset = CharsetUtil.toJavaCharset(b.getParent().getCharset()); if (charset == null) { charset = "ISO8859-1"; } OutputStream out = new FileOutputStream(mime4jFile); IOUtils.copy(((TextBody) b).getReader(), out, charset); } else { OutputStream out = new FileOutputStream(mime4jFile); IOUtils.copy(((BinaryBody) b).getInputStream(), out); } }
Code Sample 2:
public File getAppHome() { if (appHome == null) { if (System.getProperty("app.home") != null) { appHome = new File(System.getProperty("app.home")); } if (appHome == null) { URL url = Main.class.getClassLoader().getResource("com/hs/mail/container/Main.class"); if (url != null) { try { JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); url = jarConnection.getJarFileURL(); URI baseURI = new URI(url.toString()).resolve(".."); appHome = new File(baseURI).getCanonicalFile(); System.setProperty("app.home", appHome.getAbsolutePath()); } catch (Exception ignored) { } } } if (appHome == null) { appHome = new File("../."); System.setProperty("app.home", appHome.getAbsolutePath()); } } return appHome; } |
11
| Code Sample 1:
private Datastream addManagedDatastreamVersion(Entry entry) throws StreamIOException, ObjectIntegrityException { Datastream ds = new DatastreamManagedContent(); setDSCommonProperties(ds, entry); ds.DSLocationType = "INTERNAL_ID"; ds.DSMIME = getDSMimeType(entry); IRI contentLocation = entry.getContentSrc(); if (contentLocation != null) { if (m_obj.isNew()) { ValidationUtility.validateURL(contentLocation.toString(), ds.DSControlGrp); } if (m_format.equals(ATOM_ZIP1_1)) { if (!contentLocation.isAbsolute() && !contentLocation.isPathAbsolute()) { File f = getContentSrcAsFile(contentLocation); contentLocation = new IRI(DatastreamManagedContent.TEMP_SCHEME + f.getAbsolutePath()); } } ds.DSLocation = contentLocation.toString(); ds.DSLocation = (DOTranslationUtility.normalizeDSLocationURLs(m_obj.getPid(), ds, m_transContext)).DSLocation; return ds; } try { File temp = File.createTempFile("binary-datastream", null); OutputStream out = new FileOutputStream(temp); if (MimeTypeHelper.isText(ds.DSMIME) || MimeTypeHelper.isXml(ds.DSMIME)) { IOUtils.copy(new StringReader(entry.getContent()), out, m_encoding); } else { IOUtils.copy(entry.getContentStream(), out); } ds.DSLocation = DatastreamManagedContent.TEMP_SCHEME + temp.getAbsolutePath(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } return ds; }
Code Sample 2:
private void sendFile(File file, HttpExchange response) throws IOException { response.getResponseHeaders().add(FileUploadBase.CONTENT_LENGTH, Long.toString(file.length())); InputStream inputStream = null; try { inputStream = new FileInputStream(file); IOUtils.copy(inputStream, response.getResponseBody()); } catch (Exception exception) { throw new IOException("error sending file", exception); } finally { IOUtils.closeQuietly(inputStream); } } |
00
| Code Sample 1:
public void init() { System.out.println("Init applet..."); int port = Integer.parseInt(getParameter("port")); int useUDP = Integer.parseInt(getParameter("udp")); boolean bUseUDP = false; if (useUDP > 0) bUseUDP = true; m_strWorld = getParameter("world"); m_strHost = this.getCodeBase().getHost(); try { new EnvironmentMap(getParameter("vrwmap")); } catch (Throwable t) { System.out.println(t.getMessage()); } URL urlExperiment = null; InputStream expStream = null; try { String strPathExperiment = getParameter("experiment"); if (strPathExperiment.length() > 0) { urlExperiment = new URL(getCodeBase(), strPathExperiment); expStream = urlExperiment.openStream(); } } catch (java.net.MalformedURLException e) { System.out.println("Couldn't open url experiment: badly specified URL " + e.getMessage()); } catch (Throwable t) { System.out.println("Couldn't open url experiment: " + t.getMessage()); } try { System.out.println("Creating client, logging to " + m_strWorld); m_VRWClient = new VRWClient(m_strHost, port, true, bUseUDP); m_VRWClient.setInApplet(true); m_VRWClient.login(m_strWorld); } catch (java.io.IOException e) { System.out.println("IOException creating the VRWClient"); } try { jsobj = JSObject.getWindow(this); } catch (Throwable t) { System.out.println("Exception getting Java Script Interface: " + t.getMessage()); } refApplet = this; m_frmVRWConsole = new VRWConsoleFrame(); m_frmVRWConsole.setTitle("VRW Client Console"); m_frmVRWConsole.pack(); m_frmVRWConsole.setSize(Math.max(300, m_frmVRWConsole.getSize().width), Math.max(200, m_frmVRWConsole.getSize().height)); if (expStream != null) { System.out.println("Passing experiment stream to VRWConsoleFrame"); m_frmVRWConsole.loadExperiment(expStream); } m_frmVRWConsole.setVisible(true); }
Code Sample 2:
public File createWindow(String pdfUrl) { URL url; InputStream is; try { int fileLength = 0; String str; if (pdfUrl.startsWith("jar:/")) { str = "file.pdf"; is = this.getClass().getResourceAsStream(pdfUrl.substring(4)); } else { url = new URL(pdfUrl); is = url.openStream(); str = url.getPath().substring(url.getPath().lastIndexOf('/') + 1); fileLength = url.openConnection().getContentLength(); } final String filename = str; tempURLFile = File.createTempFile(filename.substring(0, filename.lastIndexOf('.')), filename.substring(filename.lastIndexOf('.')), new File(ObjectStore.temp_dir)); FileOutputStream fos = new FileOutputStream(tempURLFile); if (visible) { download.setLocation((coords.x - (download.getWidth() / 2)), (coords.y - (download.getHeight() / 2))); download.setVisible(true); } if (visible) { pb.setMinimum(0); pb.setMaximum(fileLength); String message = Messages.getMessage("PageLayoutViewMenu.DownloadWindowMessage"); message = message.replaceAll("FILENAME", filename); downloadFile.setText(message); Font f = turnOff.getFont(); turnOff.setFont(new Font(f.getName(), f.getStyle(), 8)); turnOff.setAlignmentY(JLabel.RIGHT_ALIGNMENT); turnOff.setText(Messages.getMessage("PageLayoutViewMenu.DownloadWindowTurnOff")); } byte[] buffer = new byte[4096]; int read; int current = 0; String rate = "kb"; int mod = 1000; if (fileLength > 1000000) { rate = "mb"; mod = 1000000; } if (visible) { progress = Messages.getMessage("PageLayoutViewMenu.DownloadWindowProgress"); if (fileLength < 1000000) progress = progress.replaceAll("DVALUE", (fileLength / mod) + " " + rate); else { String fraction = String.valueOf(((fileLength % mod) / 10000)); if (((fileLength % mod) / 10000) < 10) fraction = "0" + fraction; progress = progress.replaceAll("DVALUE", (fileLength / mod) + "." + fraction + " " + rate); } } while ((read = is.read(buffer)) != -1) { current = current + read; downloadCount = downloadCount + read; if (visible) { if (fileLength < 1000000) downloadMessage.setText(progress.replaceAll("DSOME", (current / mod) + " " + rate)); else { String fraction = String.valueOf(((current % mod) / 10000)); if (((current % mod) / 10000) < 10) fraction = "0" + fraction; downloadMessage.setText(progress.replaceAll("DSOME", (current / mod) + "." + fraction + " " + rate)); } pb.setValue(current); download.repaint(); } fos.write(buffer, 0, read); } fos.flush(); is.close(); fos.close(); if (visible) downloadMessage.setText("Download of " + filename + " is complete."); } catch (Exception e) { LogWriter.writeLog("[PDF] Exception " + e + " opening URL " + pdfUrl); e.printStackTrace(); } if (visible) download.setVisible(false); return tempURLFile; } |
11
| Code Sample 1:
public void copyContent(long mailId1, long mailId2) throws Exception { File file1 = new File(this.getMailDir(mailId1) + "/"); File file2 = new File(this.getMailDir(mailId2) + "/"); this.recursiveDir(file2); if (file1.isDirectory()) { File[] files = file1.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i].isFile()) { File file2s = new File(file2.getAbsolutePath() + "/" + files[i].getName()); if (!file2s.exists()) { file2s.createNewFile(); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file2s)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(files[i])); int read; while ((read = in.read()) != -1) { out.write(read); } out.flush(); if (in != null) { try { in.close(); } catch (IOException ex1) { ex1.printStackTrace(); } } if (out != null) { try { out.close(); } catch (IOException ex) { ex.printStackTrace(); } } } } } } } }
Code Sample 2:
public static 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, NULL_OUTPUT_STREAM); } finally { IOUtils.close(in); } return checksum; } |
00
| Code Sample 1:
private void setManagedContent(Entry entry, Datastream vds) throws StreamIOException { if (m_transContext == DOTranslationUtility.SERIALIZE_EXPORT_ARCHIVE && !m_format.equals(ATOM_ZIP1_1)) { String mimeType = vds.DSMIME; if (MimeTypeHelper.isText(mimeType) || MimeTypeHelper.isXml(mimeType)) { try { entry.setContent(IOUtils.toString(vds.getContentStream(), m_encoding), mimeType); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } } else { entry.setContent(vds.getContentStream(), mimeType); } } else { String dsLocation; IRI iri; if (m_format.equals(ATOM_ZIP1_1) && m_transContext != DOTranslationUtility.AS_IS) { dsLocation = vds.DSVersionID + "." + MimeTypeUtils.fileExtensionForMIMEType(vds.DSMIME); try { m_zout.putNextEntry(new ZipEntry(dsLocation)); InputStream is = vds.getContentStream(); IOUtils.copy(is, m_zout); is.close(); m_zout.closeEntry(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } } else { dsLocation = StreamUtility.enc(DOTranslationUtility.normalizeDSLocationURLs(m_obj.getPid(), vds, m_transContext).DSLocation); } iri = new IRI(dsLocation); entry.setSummary(vds.DSVersionID); entry.setContent(iri, vds.DSMIME); } }
Code Sample 2:
public String getWeather(String cityName, String fileAddr) { try { URL url = new URL("http://www.google.com/ig/api?hl=zh_cn&weather=" + cityName); InputStream inputstream = url.openStream(); String s, str; BufferedReader in = new BufferedReader(new InputStreamReader(inputstream)); StringBuffer stringbuffer = new StringBuffer(); Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileAddr), "utf-8")); while ((s = in.readLine()) != null) { stringbuffer.append(s); } str = new String(stringbuffer); out.write(str); out.close(); in.close(); } catch (IOException e) { e.printStackTrace(); } File file = new File(fileAddr); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); String str = null; try { DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(file); NodeList nodelist1 = (NodeList) doc.getElementsByTagName("forecast_conditions"); NodeList nodelist2 = nodelist1.item(0).getChildNodes(); str = nodelist2.item(4).getAttributes().item(0).getNodeValue() + ",temperature:" + nodelist2.item(1).getAttributes().item(0).getNodeValue() + "℃-" + nodelist2.item(2).getAttributes().item(0).getNodeValue() + "℃"; } catch (Exception e) { e.printStackTrace(); } return str; } |
11
| Code Sample 1:
private void copyFile(String fileName, String messageID, boolean isError) { try { File inputFile = new File(fileName); File outputFile = null; if (isError) { outputFile = new File(provider.getErrorDataLocation(folderName) + messageID + ".xml"); } else { outputFile = new File(provider.getDataProcessedLocation(folderName) + messageID + ".xml"); } FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception e) { } }
Code Sample 2:
private static void compressZip(String source, String dest) throws Exception { File baseFolder = new File(source); if (baseFolder.exists()) { if (baseFolder.isDirectory()) { List<File> fileList = getSubFiles(new File(source)); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(dest)); zos.setEncoding("GBK"); ZipEntry entry = null; byte[] buf = new byte[2048]; int readLen = 0; for (int i = 0; i < fileList.size(); i++) { File file = fileList.get(i); if (file.isDirectory()) { entry = new ZipEntry(getAbsFileName(source, file) + "/"); } else { entry = new ZipEntry(getAbsFileName(source, file)); } entry.setSize(file.length()); entry.setTime(file.lastModified()); zos.putNextEntry(entry); if (file.isFile()) { InputStream in = new BufferedInputStream(new FileInputStream(file)); while ((readLen = in.read(buf, 0, 1024)) != -1) { zos.write(buf, 0, readLen); } in.close(); } } zos.close(); } else { throw new Exception("Can not do this operation!."); } } else { baseFolder.mkdirs(); compressZip(source, dest); } } |
11
| Code Sample 1:
public static String md5(String text, String charset) { MessageDigest msgDigest = null; try { msgDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("System doesn't support MD5 algorithm."); } msgDigest.update(text.getBytes()); byte[] bytes = msgDigest.digest(); byte tb; char low; char high; char tmpChar; String md5Str = new String(); for (int i = 0; i < bytes.length; i++) { tb = bytes[i]; tmpChar = (char) ((tb >>> 4) & 0x000f); if (tmpChar >= 10) { high = (char) (('a' + tmpChar) - 10); } else { high = (char) ('0' + tmpChar); } md5Str += high; tmpChar = (char) (tb & 0x000f); if (tmpChar >= 10) { low = (char) (('a' + tmpChar) - 10); } else { low = (char) ('0' + tmpChar); } md5Str += low; } return md5Str; }
Code Sample 2:
private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } |
11
| Code Sample 1:
public static void main(String[] args) throws Exception { String infile = "C:\\copy.sql"; String outfile = "C:\\copy.txt"; FileInputStream fin = new FileInputStream(infile); FileOutputStream fout = new FileOutputStream(outfile); FileChannel fcin = fin.getChannel(); FileChannel fcout = fout.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (true) { buffer.clear(); int r = fcin.read(buffer); if (r == -1) { break; } buffer.flip(); fcout.write(buffer); } }
Code Sample 2:
public void init(File file) { InputStream is = null; ByteArrayOutputStream os = null; try { is = new FileInputStream(file); os = new ByteArrayOutputStream(); IOUtils.copy(is, os); } catch (Throwable e) { throw new VisualizerEngineException("Unexcpected exception while reading MDF file", e); } if (simulationEngine != null) simulationEngine.stopSimulation(); simulationEngine = new TrafficAsynchSimulationEngine(); simulationEngine.init(MDFReader.read(os.toByteArray())); simulationEngineThread = null; } |
11
| Code Sample 1:
private void copy(File from, File to) { if (from.isDirectory()) { File[] files = from.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { File newTo = new File(to.getPath() + File.separator + files[i].getName()); newTo.mkdirs(); copy(files[i], newTo); } else { copy(files[i], to); } } } else { try { to = new File(to.getPath() + File.separator + from.getName()); to.createNewFile(); FileChannel src = new FileInputStream(from).getChannel(); FileChannel dest = new FileOutputStream(to).getChannel(); dest.transferFrom(src, 0, src.size()); dest.close(); src.close(); } catch (FileNotFoundException e) { errorLog(e.toString()); e.printStackTrace(); } catch (IOException e) { errorLog(e.toString()); e.printStackTrace(); } } }
Code Sample 2:
private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base: </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()); } |
00
| Code Sample 1:
public String tranportRemoteUnitToLocalTempFile(String urlStr) throws UnitTransportException { InputStream input = null; BufferedOutputStream bos = null; File tempUnit = null; try { URL url = null; int total = 0; try { url = new URL(urlStr); input = url.openStream(); URLConnection urlConnection; urlConnection = url.openConnection(); total = urlConnection.getContentLength(); } catch (IOException e) { throw new UnitTransportException(String.format("Can't get remote file [%s].", urlStr), e); } String unitName = urlStr.substring(urlStr.lastIndexOf('/') + 1); tempUnit = null; try { if (StringUtils.isNotEmpty(unitName)) tempUnit = new File(CommonUtil.getTempDir(), unitName); else tempUnit = File.createTempFile(CommonUtil.getTempDir(), "tempUnit"); File parent = tempUnit.getParentFile(); FileUtils.forceMkdir(parent); if (!tempUnit.exists()) FileUtils.touch(tempUnit); bos = new BufferedOutputStream(new FileOutputStream(tempUnit)); } catch (FileNotFoundException e) { throw new UnitTransportException(String.format("Can't find temp file [%s].", tempUnit.getAbsolutePath()), e); } catch (IOException e) { throw new UnitTransportException(String.format("Can't create temp file [%s].", tempUnit.getAbsolutePath()), e); } catch (DeployToolException e) { throw new UnitTransportException(String.format("Error when create temp file [%s].", tempUnit), e); } logger.info(String.format("Use [%s] for http unit [%s].", tempUnit.getAbsoluteFile(), urlStr)); int size = -1; try { size = IOUtils.copy(input, bos); bos.flush(); } catch (IOException e) { logger.info(String.format("Error when download [%s] to [%s].", urlStr, tempUnit)); } if (size != total) throw new UnitTransportException(String.format("The file size is not right when download http unit [%s]", urlStr)); } finally { if (input != null) IOUtils.closeQuietly(input); if (bos != null) IOUtils.closeQuietly(bos); } logger.info(String.format("Download unit to [%s].", tempUnit.getAbsolutePath())); return tempUnit.getAbsolutePath(); }
Code Sample 2:
public static final String crypt(String password, String salt) throws NoSuchAlgorithmException { String magic = "$1$"; byte finalState[]; MessageDigest ctx, ctx1; long l; if (salt.startsWith(magic)) { salt = salt.substring(magic.length()); } if (salt.indexOf('$') != -1) { salt = salt.substring(0, salt.indexOf('$')); } if (salt.length() > 8) { salt = salt.substring(0, 8); } ctx = MessageDigest.getInstance("MD5"); ctx.update(password.getBytes()); ctx.update(magic.getBytes()); ctx.update(salt.getBytes()); ctx1 = MessageDigest.getInstance("MD5"); ctx1.update(password.getBytes()); ctx1.update(salt.getBytes()); ctx1.update(password.getBytes()); finalState = ctx1.digest(); for (int pl = password.length(); pl > 0; pl -= 16) { for (int i = 0; i < (pl > 16 ? 16 : pl); i++) ctx.update(finalState[i]); } clearbits(finalState); for (int i = password.length(); i != 0; i >>>= 1) { if ((i & 1) != 0) { ctx.update(finalState[0]); } else { ctx.update(password.getBytes()[0]); } } finalState = ctx.digest(); for (int i = 0; i < 1000; i++) { ctx1 = MessageDigest.getInstance("MD5"); if ((i & 1) != 0) { ctx1.update(password.getBytes()); } else { for (int c = 0; c < 16; c++) ctx1.update(finalState[c]); } if ((i % 3) != 0) { ctx1.update(salt.getBytes()); } if ((i % 7) != 0) { ctx1.update(password.getBytes()); } if ((i & 1) != 0) { for (int c = 0; c < 16; c++) ctx1.update(finalState[c]); } else { ctx1.update(password.getBytes()); } finalState = ctx1.digest(); } StringBuffer result = new StringBuffer(); result.append(magic); result.append(salt); result.append("$"); l = (bytes2u(finalState[0]) << 16) | (bytes2u(finalState[6]) << 8) | bytes2u(finalState[12]); result.append(to64(l, 4)); l = (bytes2u(finalState[1]) << 16) | (bytes2u(finalState[7]) << 8) | bytes2u(finalState[13]); result.append(to64(l, 4)); l = (bytes2u(finalState[2]) << 16) | (bytes2u(finalState[8]) << 8) | bytes2u(finalState[14]); result.append(to64(l, 4)); l = (bytes2u(finalState[3]) << 16) | (bytes2u(finalState[9]) << 8) | bytes2u(finalState[15]); result.append(to64(l, 4)); l = (bytes2u(finalState[4]) << 16) | (bytes2u(finalState[10]) << 8) | bytes2u(finalState[5]); result.append(to64(l, 4)); l = bytes2u(finalState[11]); result.append(to64(l, 2)); clearbits(finalState); return result.toString(); } |
00
| Code Sample 1:
public static String getHashedPassword(String password) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(password.getBytes()); BigInteger hashedInt = new BigInteger(1, digest.digest()); return String.format("%1$032X", hashedInt); } catch (NoSuchAlgorithmException nsae) { System.err.println(nsae.getMessage()); } return ""; }
Code Sample 2:
@Override List<String> HttpGet(URL url) throws IOException { List<String> responseList = new ArrayList<String>(); Logger.getInstance().logInfo("HTTP GET: " + url, null, getGatewayId()); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setConnectTimeout(20000); con.setAllowUserInteraction(false); responseList.add(con.getResponseCode() + " " + con.getResponseMessage()); InputStream inputStream = con.getErrorStream(); if (inputStream == null) inputStream = con.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); String inputLine; while ((inputLine = in.readLine()) != null) responseList.add(inputLine); in.close(); return responseList; } |
11
| Code Sample 1:
private void parseTemplate(File templateFile, Map dataMap) throws ContainerException { Debug.log("Parsing template : " + templateFile.getAbsolutePath(), module); Reader reader = null; try { reader = new InputStreamReader(new FileInputStream(templateFile)); } catch (FileNotFoundException e) { throw new ContainerException(e); } String targetDirectoryName = args.length > 1 ? args[1] : null; if (targetDirectoryName == null) { targetDirectoryName = target; } String targetDirectory = ofbizHome + targetDirectoryName + args[0]; File targetDir = new File(targetDirectory); if (!targetDir.exists()) { boolean created = targetDir.mkdirs(); if (!created) { throw new ContainerException("Unable to create target directory - " + targetDirectory); } } if (!targetDirectory.endsWith("/")) { targetDirectory = targetDirectory + "/"; } Writer writer = null; try { writer = new FileWriter(targetDirectory + templateFile.getName()); } catch (IOException e) { throw new ContainerException(e); } try { FreeMarkerWorker.renderTemplate(templateFile.getAbsolutePath(), reader, dataMap, writer); } catch (Exception e) { throw new ContainerException(e); } try { writer.flush(); writer.close(); } catch (IOException e) { throw new ContainerException(e); } }
Code Sample 2:
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { Session session = HibernateUtil.getInstance().getSession(); response.setBufferSize(65536); ServletOutputStream outStream = response.getOutputStream(); File file = null; FileData fileData = null; try { String fileParameter = request.getParameter("file"); String disposition = request.getParameter("disposition"); if (fileParameter == null || fileParameter.equals("")) { String pi = request.getPathInfo(); int lastSlashIndex = pi.lastIndexOf("/") + 1; fileParameter = pi.substring(lastSlashIndex, pi.indexOf("_", pi.lastIndexOf("/"))); } if (fileParameter == null || fileParameter.equals("")) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.flushBuffer(); Logger.log("file parameter not specified"); return; } if (disposition == null || disposition.equals("")) { String pi = request.getPathInfo(); String filename = pi.substring(pi.lastIndexOf("/") + 1); int underscoreIndex = filename.indexOf("_") + 1; disposition = filename.substring(underscoreIndex, filename.indexOf("_", underscoreIndex)); } file = (File) session.load(File.class, new Long(fileParameter)); Logger.log("Content requested=" + file.getName() + ":" + fileParameter + " Referral: " + request.getParameter("referer")); long ifModifiedSince = request.getDateHeader("If-Modified-Since"); long fileDate = file.getLastModifiedDate() - (file.getLastModifiedDate() % 1000); if (fileDate <= ifModifiedSince) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); if ("attachment".equals(disposition)) { response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); } else { response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\""); } response.setContentType(file.getContentType()); response.setHeader("Content-Description", file.getName()); response.setDateHeader("Last-Modified", file.getLastModifiedDate()); response.setDateHeader("Expires", System.currentTimeMillis() + 31536000000L); response.setContentLength((int) file.getSize()); response.flushBuffer(); Logger.log("Conditional GET: " + file.getName()); return; } User authUser = baseService.getAuthenticatedUser(session, request, response); if (!SecurityHelper.doesUserHavePermission(session, authUser, file, Permission.PERM.READ)) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "Forbidden"); response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.flushBuffer(); Logger.log("Forbidden content requested: " + fileParameter); return; } String contentType = file.getContentType(); response.setContentType(contentType); if ("attachment".equals(disposition)) { response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); } else { response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\""); } String name = file.getName(); response.setHeader("Content-Description", name); response.setDateHeader("Last-Modified", file.getLastModifiedDate()); response.setDateHeader("Expires", System.currentTimeMillis() + 31536000000L); response.setContentLength((int) file.getSize()); java.io.File possibleDataFile = new java.io.File(BaseSystem.getTempDir() + file.getNameOnDisk()); if (possibleDataFile.exists()) { Logger.log("File exists in " + BaseSystem.getTempDir() + " pulling " + possibleDataFile.getName()); FileInputStream fileInputStream = new FileInputStream(possibleDataFile); try { IOUtils.copy(fileInputStream, outStream); } finally { try { fileInputStream.close(); } catch (Throwable t) { } } } else { List<FileData> fileDataList = HibernateUtil.getInstance().executeQuery(session, "from " + FileData.class.getSimpleName() + " where permissibleObject.id = " + file.getId()); if (fileDataList.size() == 0) { response.sendError(HttpServletResponse.SC_NOT_FOUND); response.setStatus(HttpServletResponse.SC_NOT_FOUND); Logger.log("Requested content not found: " + fileParameter); response.flushBuffer(); return; } fileData = (FileData) fileDataList.get(0); FileOutputStream fileOutputStream = null; try { java.io.File tmpDir = new java.io.File(BaseSystem.getTempDir()); tmpDir.mkdirs(); fileOutputStream = new FileOutputStream(possibleDataFile); IOUtils.write(fileData.getData(), fileOutputStream); } catch (Throwable t) { Logger.log(t); } finally { try { fileOutputStream.close(); } catch (Throwable t) { } } IOUtils.write(fileData.getData(), outStream); } } catch (Throwable t) { Logger.log(t); try { response.sendError(HttpServletResponse.SC_NOT_FOUND); response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.flushBuffer(); } catch (Throwable tt) { } try { response.reset(); response.resetBuffer(); } catch (Throwable tt) { } } finally { file = null; fileData = null; try { outStream.flush(); } catch (Throwable t) { } try { outStream.close(); } catch (Throwable t) { } try { session.close(); } catch (Throwable t) { } } } |
00
| Code Sample 1:
private void getViolationsReportByProductOfferIdYearMonthDay() throws IOException { String xmlFile9Send = System.getenv("SLASOI_HOME") + System.getProperty("file.separator") + "Integration" + System.getProperty("file.separator") + "soap" + System.getProperty("file.separator") + "getViolationsReportByProductOfferIdYearMonthDay.xml"; URL url9; url9 = new URL(bmReportingWSUrl); URLConnection connection9 = url9.openConnection(); HttpURLConnection httpConn9 = (HttpURLConnection) connection9; FileInputStream fin9 = new FileInputStream(xmlFile9Send); ByteArrayOutputStream bout9 = new ByteArrayOutputStream(); SOAPClient4XG.copy(fin9, bout9); fin9.close(); byte[] b9 = bout9.toByteArray(); httpConn9.setRequestProperty("Content-Length", String.valueOf(b9.length)); httpConn9.setRequestProperty("Content-Type", "application/soap+xml; charset=UTF-8"); httpConn9.setRequestProperty("SOAPAction", soapAction); httpConn9.setRequestMethod("POST"); httpConn9.setDoOutput(true); httpConn9.setDoInput(true); OutputStream out9 = httpConn9.getOutputStream(); out9.write(b9); out9.close(); InputStreamReader isr9 = new InputStreamReader(httpConn9.getInputStream()); BufferedReader in9 = new BufferedReader(isr9); String inputLine9; StringBuffer response9 = new StringBuffer(); while ((inputLine9 = in9.readLine()) != null) { response9.append(inputLine9); } in9.close(); System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" + "####################################################" + "#################################################\n" + "####################################################" + "#################################################\n" + "Component Name: Business Manager\n" + "Interface Name: getReport\n" + "Operation Name: " + "getViolationsReportByProductOfferIdYearMonthDay\n" + "Input" + "ProductOfferID-1\n" + "PartyID-1\n" + "\n" + "####################################################" + "#################################################\n" + "####################################################" + "#################################################\n" + "######################################## RESPONSE" + "############################################\n\n"); System.out.println("--------------------------------"); System.out.println("Response\n" + response9.toString()); }
Code Sample 2:
public void readFully(String urlS) throws Exception { URL url = new URL(urlS); URLConnection conn = url.openConnection(); InputStream is = conn.getInputStream(); byte[] data = new byte[10240]; int b = is.read(data); while (b > 0) { size += b; b = is.read(data); } is.close(); } |
00
| Code Sample 1:
private void analyseCorpus(final IStatusDisplayer fStatus) { final String sDistrosFile = "Distros.tmp"; final String sSymbolsFile = "Symbols.tmp"; Chunker = new EntropyChunker(); int Levels = 2; sgOverallGraph = new SymbolicGraph(1, Levels); siIndex = new SemanticIndex(sgOverallGraph); try { siIndex.MeaningExtractor = new LocalWordNetMeaningExtractor(); } catch (IOException ioe) { siIndex.MeaningExtractor = null; } try { DocumentSet dsSet = new DocumentSet(FilePathEdt.getText(), 1.0); dsSet.createSets(true, (double) 100 / 100); int iCurCnt, iTotal; String sFile = ""; Iterator iIter = dsSet.getTrainingSet().iterator(); iTotal = dsSet.getTrainingSet().size(); if (iTotal == 0) { appendToLog("No input documents.\n"); appendToLog("======DONE=====\n"); return; } appendToLog("Training chunker..."); Chunker.train(dsSet.toFilenameSet(DocumentSet.FROM_WHOLE_SET)); appendToLog("Setting delimiters..."); setDelimiters(Chunker.getDelimiters()); iCurCnt = 0; cdDoc = new DistributionDocument[Levels]; for (int iCnt = 0; iCnt < Levels; iCnt++) cdDoc[iCnt] = new DistributionDocument(1, MinLevel + iCnt); fStatus.setVisible(true); ThreadList t = new ThreadList(Runtime.getRuntime().availableProcessors() + 1); appendToLog("(Pass 1/3) Loading files..." + sFile); TreeSet tsOverallSymbols = new TreeSet(); while (iIter.hasNext()) { sFile = ((CategorizedFileEntry) iIter.next()).getFileName(); fStatus.setStatus("(Pass 1/3) Loading file..." + sFile, (double) iCurCnt / iTotal); final DistributionDocument[] cdDocArg = cdDoc; final String sFileArg = sFile; for (int iCnt = 0; iCnt < cdDoc.length; iCnt++) { final int iCntArg = iCnt; while (!t.addThreadFor(new Runnable() { public void run() { if (!RightToLeftText) cdDocArg[iCntArg].loadDataStringFromFile(sFileArg, false); else { cdDocArg[iCntArg].setDataString(utils.reverseString(utils.loadFileToString(sFileArg)), iCntArg, false); } } })) Thread.yield(); } try { t.waitUntilCompletion(); } catch (InterruptedException ex) { ex.printStackTrace(System.err); appendToLog("Interrupted..."); sgOverallGraph.removeNotificationListener(); return; } sgOverallGraph.setDataString(((new StringBuffer().append((char) StreamTokenizer.TT_EOF))).toString()); sgOverallGraph.loadFromFile(sFile); fStatus.setStatus("Loaded file..." + sFile, (double) ++iCurCnt / iTotal); Thread.yield(); } Set sSymbols = null; File fPreviousSymbols = new File(sSymbolsFile); boolean bSymbolsLoadedOK = false; if (fPreviousSymbols.exists()) { System.err.println("ATTENTION: Using previous symbols..."); try { FileInputStream fis = new FileInputStream(fPreviousSymbols); ObjectInputStream ois = new ObjectInputStream(fis); sSymbols = (Set) ois.readObject(); ois.close(); bSymbolsLoadedOK = true; } catch (FileNotFoundException ex) { ex.printStackTrace(System.err); } catch (IOException ex) { ex.printStackTrace(System.err); } catch (ClassNotFoundException ex) { ex.printStackTrace(System.err); } } if (!bSymbolsLoadedOK) sSymbols = getSymbolsByProbabilities(sgOverallGraph.getDataString(), fStatus); int iMinSymbolSize = Integer.MAX_VALUE; int iMaxSymbolSize = Integer.MIN_VALUE; Iterator iSymbol = sSymbols.iterator(); while (iSymbol.hasNext()) { String sCurSymbol = (String) iSymbol.next(); if (iMaxSymbolSize < sCurSymbol.length()) iMaxSymbolSize = sCurSymbol.length(); if (iMinSymbolSize > sCurSymbol.length()) iMinSymbolSize = sCurSymbol.length(); } try { FileOutputStream fos = new FileOutputStream(sSymbolsFile); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(sSymbols); oos.close(); } catch (FileNotFoundException ex) { ex.printStackTrace(System.err); } catch (IOException ex) { ex.printStackTrace(System.err); } appendToLog("(Pass 2/3) Determining symbol distros per n-gram size..."); iIter = dsSet.getTrainingSet().iterator(); iTotal = dsSet.getTrainingSet().size(); if (iTotal == 0) { appendToLog("No input documents.\n"); appendToLog("======DONE=====\n"); return; } iCurCnt = 0; Distribution dSymbolsPerSize = new Distribution(); Distribution dNonSymbolsPerSize = new Distribution(); Distribution dSymbolSizes = new Distribution(); File fPreviousRun = new File(sDistrosFile); boolean bDistrosLoadedOK = false; if (fPreviousRun.exists()) { System.err.println("ATTENTION: Using previous distros..."); try { FileInputStream fis = new FileInputStream(fPreviousRun); ObjectInputStream ois = new ObjectInputStream(fis); dSymbolsPerSize = (Distribution) ois.readObject(); dNonSymbolsPerSize = (Distribution) ois.readObject(); dSymbolSizes = (Distribution) ois.readObject(); ois.close(); bDistrosLoadedOK = true; } catch (FileNotFoundException ex) { ex.printStackTrace(System.err); } catch (IOException ex) { ex.printStackTrace(System.err); dSymbolsPerSize = new Distribution(); dNonSymbolsPerSize = new Distribution(); dSymbolSizes = new Distribution(); } catch (ClassNotFoundException ex) { ex.printStackTrace(System.err); dSymbolsPerSize = new Distribution(); dNonSymbolsPerSize = new Distribution(); dSymbolSizes = new Distribution(); } } if (!bDistrosLoadedOK) while (iIter.hasNext()) { fStatus.setStatus("(Pass 2/3) Parsing file..." + sFile, (double) iCurCnt++ / iTotal); sFile = ((CategorizedFileEntry) iIter.next()).getFileName(); String sDataString = ""; try { ByteArrayOutputStream bsOut = new ByteArrayOutputStream(); FileInputStream fiIn = new FileInputStream(sFile); int iData = 0; while ((iData = fiIn.read()) > -1) bsOut.write(iData); sDataString = bsOut.toString(); } catch (IOException ioe) { ioe.printStackTrace(System.err); } final Distribution dSymbolsPerSizeArg = dSymbolsPerSize; final Distribution dNonSymbolsPerSizeArg = dNonSymbolsPerSize; final Distribution dSymbolSizesArg = dSymbolSizes; final String sDataStringArg = sDataString; final Set sSymbolsArg = sSymbols; for (int iSymbolSize = iMinSymbolSize; iSymbolSize <= iMaxSymbolSize; iSymbolSize++) { final int iSymbolSizeArg = iSymbolSize; while (!t.addThreadFor(new Runnable() { public void run() { NGramDocument ndCur = new NGramDocument(iSymbolSizeArg, iSymbolSizeArg, 1, iSymbolSizeArg, iSymbolSizeArg); ndCur.setDataString(sDataStringArg); int iSymbolCnt = 0; int iNonSymbolCnt = 0; Iterator iExtracted = ndCur.getDocumentGraph().getGraphLevel(0).getVertexSet().iterator(); while (iExtracted.hasNext()) { String sCur = ((Vertex) iExtracted.next()).toString(); if (sSymbolsArg.contains(sCur)) { iSymbolCnt++; synchronized (dSymbolSizesArg) { dSymbolSizesArg.setValue(sCur.length(), dSymbolSizesArg.getValue(sCur.length()) + 1.0); } } else iNonSymbolCnt++; } synchronized (dSymbolsPerSizeArg) { dSymbolsPerSizeArg.setValue(iSymbolSizeArg, dSymbolsPerSizeArg.getValue(iSymbolSizeArg) + iSymbolCnt); } synchronized (dNonSymbolsPerSizeArg) { dNonSymbolsPerSizeArg.setValue(iSymbolSizeArg, dNonSymbolsPerSizeArg.getValue(iSymbolSizeArg) + iNonSymbolCnt); } } })) Thread.yield(); } } if (!bDistrosLoadedOK) try { t.waitUntilCompletion(); try { FileOutputStream fos = new FileOutputStream(sDistrosFile); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(dSymbolsPerSize); oos.writeObject(dNonSymbolsPerSize); oos.writeObject(dSymbolSizes); oos.close(); } catch (FileNotFoundException ex) { ex.printStackTrace(System.err); } catch (IOException ex) { ex.printStackTrace(System.err); } } catch (InterruptedException ex) { appendToLog("Interrupted..."); sgOverallGraph.removeNotificationListener(); return; } appendToLog("\n(Pass 3/3) Determining optimal n-gram range...\n"); NGramSizeEstimator nseEstimator = new NGramSizeEstimator(dSymbolsPerSize, dNonSymbolsPerSize); IntegerPair p = nseEstimator.getOptimalRange(); appendToLog("\nProposed n-gram sizes:" + p.first() + "," + p.second()); fStatus.setStatus("Determining optimal distance...", 0.0); DistanceEstimator de = new DistanceEstimator(dSymbolsPerSize, dNonSymbolsPerSize, nseEstimator); int iBestDist = de.getOptimalDistance(1, nseEstimator.getMaxRank() * 2, p.first(), p.second()); fStatus.setStatus("Determining optimal distance...", 1.0); appendToLog("\nOptimal distance:" + iBestDist); appendToLog("======DONE=====\n"); } finally { sgOverallGraph.removeNotificationListener(); } }
Code Sample 2:
private byte[] loadResourceFromCodeBase(String name) { byte[] bytecode; InputStream is = null; logger.debug("LoadResourceFromCodeBase()++"); try { URL url = new URL(this._codeBase, name); int content_length = -1; URLConnection connection = url.openConnection(); connection.setRequestProperty("user-agent", "Aglets/1.1"); connection.setRequestProperty("agent-system", "aglets"); connection.setRequestProperty("agent-language", "java"); connection.setDoInput(true); connection.setUseCaches(false); connection.connect(); is = connection.getInputStream(); content_length = connection.getContentLength(); if (content_length < 0) { content_length = is.available(); } if (content_length == 0) { return null; } bytecode = new byte[content_length]; int offset = 0; while (content_length > 0) { int read = is.read(bytecode, offset, content_length); offset += read; content_length -= read; } is.close(); } catch (IOException ex) { logger.error("Error loading [" + name + "] resource from [" + this._codeBase + "]", ex); bytecode = null; } finally { if (is != null) { try { is.close(); } catch (Exception ex) { logger.error("Error closing.", ex); } } } logger.debug("LoadResourceFromCodeBase()--"); return bytecode; } |
00
| Code Sample 1:
public static byte[] SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return sha1hash; }
Code Sample 2:
private void download(String address, String localFileName, String host, int porta) { InputStream in = null; URLConnection conn = null; OutputStream out = null; System.out.println("Update.download() BAIXANDO " + address); try { URL url = new URL(address); out = new BufferedOutputStream(new FileOutputStream(localFileName)); if (host != "" && host != null) { Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, porta)); conn = url.openConnection(proxy); } else { conn = url.openConnection(); } in = conn.getInputStream(); byte[] buffer = new byte[1024]; int numRead; long numWritten = 0; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); numWritten += numRead; } System.out.println(localFileName + "\t" + numWritten); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException ioe) { } } } |
00
| Code Sample 1:
public byte[] md5(String clearText) { MessageDigest md; byte[] digest; try { md = MessageDigest.getInstance("MD5"); md.update(clearText.getBytes()); digest = md.digest(); } catch (NoSuchAlgorithmException e) { throw new UnsupportedOperationException(e.toString()); } return digest; }
Code Sample 2:
@Override public KeySelectorResult select(KeyInfo keyInfo, Purpose purpose, AlgorithmMethod method, XMLCryptoContext context) throws KeySelectorException { try { return super.select(keyInfo, purpose, method, context); } catch (KeySelectorException e) { LOG.debug("no key found via ds:KeyInfo key selector"); } LOG.debug("signature resource name: " + this.signatureResourceName); String signatureSegment = this.signatureResourceName.substring(0, this.signatureResourceName.lastIndexOf("/")); LOG.debug("signature segment: " + signatureSegment); String signatureBase = this.signatureResourceName.substring(this.signatureResourceName.lastIndexOf("/") + 1); LOG.debug("signature base: " + signatureBase); String signatureRelationshipResourceName = signatureSegment + "/_rels/" + signatureBase + ".rels"; LOG.debug("signature relationship resource name: " + signatureRelationshipResourceName); ZipArchiveInputStream zipInputStream; try { zipInputStream = new ZipArchiveInputStream(this.opcUrl.openStream(), "UTF8", true, true); } catch (IOException e) { throw new KeySelectorException(e); } ZipArchiveEntry zipEntry; try { while (null != (zipEntry = zipInputStream.getNextZipEntry())) { if (signatureRelationshipResourceName.equals(zipEntry.getName())) { break; } } } catch (IOException e) { throw new KeySelectorException(e); } if (null == zipEntry) { LOG.warn("relationship part not present: " + signatureRelationshipResourceName); throw new KeySelectorException("no key found"); } LOG.debug("signature relationship part found"); JAXBElement<CTRelationships> signatureRelationshipsElement; try { signatureRelationshipsElement = (JAXBElement<CTRelationships>) this.relationshipsUnmarshaller.unmarshal(zipInputStream); } catch (JAXBException e) { throw new KeySelectorException(e); } CTRelationships signatureRelationships = signatureRelationshipsElement.getValue(); List<CTRelationship> signatureRelationshipList = signatureRelationships.getRelationship(); List<String> certificateResourceNames = new LinkedList<String>(); for (CTRelationship signatureRelationship : signatureRelationshipList) { if (DIGITAL_SIGNATURE_CERTIFICATE_REL_TYPE.equals(signatureRelationship.getType())) { String certificateResourceName = signatureRelationship.getTarget().substring(1); certificateResourceNames.add(certificateResourceName); } } X509Certificate endEntityCertificate = null; for (String certificateResourceName : certificateResourceNames) { try { zipInputStream = new ZipArchiveInputStream(this.opcUrl.openStream(), "UTF8", true, true); } catch (IOException e) { throw new KeySelectorException(e); } try { while (null != (zipEntry = zipInputStream.getNextZipEntry())) { if (certificateResourceName.equals(zipEntry.getName())) { break; } } } catch (IOException e) { throw new KeySelectorException(e); } if (null == zipEntry) { LOG.warn("certificate part not present: " + certificateResourceName); continue; } X509Certificate certificate; try { certificate = (X509Certificate) this.certificateFactory.generateCertificate(zipInputStream); } catch (CertificateException e) { throw new KeySelectorException(e); } LOG.debug("certificate subject: " + certificate.getSubjectX500Principal()); if (-1 != certificate.getBasicConstraints()) { LOG.debug("skipping CA certificate"); continue; } if (null != endEntityCertificate) { throw new KeySelectorException("two possible end entity certificates"); } endEntityCertificate = certificate; } if (null == endEntityCertificate) { throw new KeySelectorException("no key found"); } this.certificate = endEntityCertificate; return this; } |
00
| Code Sample 1:
protected void readLockssConfigFile(URL url, List<String> peers) { PrintWriter out = null; try { out = new PrintWriter(new OutputStreamWriter(System.out, "utf8"), true); out.println("unicode-output-ready"); } catch (UnsupportedEncodingException ex) { System.out.println(ex.toString()); return; } XMLInputFactory xmlif = XMLInputFactory.newInstance(); xmlif.setProperty("javax.xml.stream.isCoalescing", java.lang.Boolean.TRUE); xmlif.setProperty("javax.xml.stream.isNamespaceAware", java.lang.Boolean.TRUE); XMLStreamReader xmlr = null; BufferedInputStream stream = null; long starttime = System.currentTimeMillis(); out.println("Starting to parse the remote config xml[" + url + "]"); int elementCount = 0; int topPropertyCounter = 0; int propertyTagLevel = 0; try { stream = new BufferedInputStream(url.openStream()); xmlr = xmlif.createXMLStreamReader(stream, "utf8"); int eventType = xmlr.getEventType(); String curElement = ""; String targetTagName = "property"; String peerListAttrName = "id.initialV3PeerList"; boolean sentinel = false; boolean valueline = false; while (xmlr.hasNext()) { eventType = xmlr.next(); switch(eventType) { case XMLEvent.START_ELEMENT: curElement = xmlr.getLocalName(); if (curElement.equals("property")) { topPropertyCounter++; propertyTagLevel++; int count = xmlr.getAttributeCount(); if (count > 0) { for (int i = 0; i < count; i++) { if (xmlr.getAttributeValue(i).equals(peerListAttrName)) { sentinel = true; out.println("!!!!!! hit the" + peerListAttrName); out.println("attr=" + xmlr.getAttributeName(i)); out.println("vl=" + xmlr.getAttributeValue(i)); out.println(">>>>>>>>>>>>>> start :property tag (" + topPropertyCounter + ") >>>>>>>>>>>>>>"); out.println(">>>>>>>>>>>>>> property tag level (" + propertyTagLevel + ") >>>>>>>>>>>>>>"); out.print(xmlr.getAttributeName(i).toString()); out.print("="); out.print("\""); out.print(xmlr.getAttributeValue(i)); out.println(""); } } } } if (sentinel && curElement.equals("value")) { valueline = true; String ipAd = xmlr.getElementText(); peers.add(ipAd); } break; case XMLEvent.CHARACTERS: break; case XMLEvent.ATTRIBUTE: if (curElement.equals(targetTagName)) { } break; case XMLEvent.END_ELEMENT: if (xmlr.getLocalName().equals("property")) { if (sentinel) { out.println("========= end of the target property element"); sentinel = false; valueline = false; } elementCount++; propertyTagLevel--; } else { } break; case XMLEvent.END_DOCUMENT: } } } catch (MalformedURLException ue) { } catch (IOException ex) { } catch (XMLStreamException ex) { } finally { if (xmlr != null) { try { xmlr.close(); } catch (XMLStreamException ex) { } } if (stream != null) { try { stream.close(); } catch (IOException ex) { } } } }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } |
00
| Code Sample 1:
public static void loadFile(final URL url, final StringBuffer buffer) throws IOException { InputStream in = null; BufferedReader dis = null; try { in = url.openStream(); dis = new BufferedReader(new InputStreamReader(in)); int i; while ((i = dis.read()) != -1) { buffer.append((char) i); } } finally { closeStream(in); closeReader(dis); } }
Code Sample 2:
public byte[] getCoded(String name, String pass) { byte[] digest = null; if (pass != null && 0 < pass.length()) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(name.getBytes()); md.update(pass.getBytes()); digest = md.digest(); } catch (Exception e) { e.printStackTrace(); digest = null; } } return digest; } |
00
| Code Sample 1:
private void execute(File file) throws IOException { if (file == null) throw new RuntimeException("undefined file"); if (!file.exists()) throw new RuntimeException("file not found :" + file); if (!file.isFile()) throw new RuntimeException("not a file :" + file); String login = cfg.getProperty(GC_USERNAME); String password = null; if (cfg.containsKey(GC_PASSWORD)) { password = cfg.getProperty(GC_PASSWORD); } else { password = new String(Base64.decode(cfg.getProperty(GC_PASSWORD64))); } PostMethod post = null; try { HttpClient client = new HttpClient(); post = new PostMethod("https://" + projectName + ".googlecode.com/files"); post.addRequestHeader("User-Agent", getClass().getName()); post.addRequestHeader("Authorization", "Basic " + Base64.encode(login + ":" + password)); List<Part> parts = new ArrayList<Part>(); String s = this.summary; if (StringUtils.isBlank(s)) { s = file.getName() + " (" + TimeUtils.toYYYYMMDD() + ")"; } parts.add(new StringPart("summary", s)); for (String lbl : this.labels) { if (StringUtils.isBlank(lbl)) continue; parts.add(new StringPart("label", lbl.trim())); } parts.add(new FilePart("filename", file)); MultipartRequestEntity requestEntity = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams()); post.setRequestEntity(requestEntity); int status = client.executeMethod(post); if (status != 201) { throw new IOException("http status !=201 : " + post.getResponseBodyAsString()); } else { IOUtils.copyTo(post.getResponseBodyAsStream(), new NullOutputStream()); } } finally { if (post != null) post.releaseConnection(); } }
Code Sample 2:
private Element makeRequest(String link) { try { URL url = new URL(link); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.connect(); InputStream in = conn.getInputStream(); DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.parse(in); Element element = document.getDocumentElement(); element.normalize(); if (checkRootTag(element)) { return element; } else { return null; } } catch (IOException e) { e.printStackTrace(); return null; } catch (ParserConfigurationException e) { e.printStackTrace(); return null; } catch (SAXException e) { e.printStackTrace(); return null; } } |
00
| Code Sample 1:
public void registerSchema(String newSchemaName, String objectControlller, long boui, String expression, String schema) throws SQLException { Connection cndef = null; PreparedStatement pstm = null; try { cndef = this.getRepositoryConnection(p_ctx.getApplication(), "default", 2); String friendlyName = "Schema created by object [" + objectControlller + "] with boui [" + boui + "]"; pstm = cndef.prepareStatement("DELETE FROM NGTDIC WHERE TABLENAME=? and objecttype='S'"); pstm.setString(1, newSchemaName); pstm.executeUpdate(); pstm.close(); pstm = cndef.prepareStatement("INSERT INTO NGTDIC (\"SCHEMA\",OBJECTNAME,OBJECTTYPE,TABLENAME, " + "FRIENDLYNAME, EXPRESSION) VALUES (" + "?,?,?,?,?,?)"); pstm.setString(1, schema); pstm.setString(2, newSchemaName); pstm.setString(3, "S"); pstm.setString(4, newSchemaName); pstm.setString(5, friendlyName); pstm.setString(6, expression); pstm.executeUpdate(); pstm.close(); cndef.commit(); } catch (Exception e) { cndef.rollback(); e.printStackTrace(); throw new SQLException(e.getMessage()); } finally { if (pstm != null) { try { pstm.close(); } catch (Exception e) { } } } }
Code Sample 2:
public static synchronized String getMD5_Base64(final String input) { if (isInited == false) { isInited = true; try { digest = MessageDigest.getInstance("MD5"); } catch (Exception ex) { logger.error("Cannot get MessageDigest. Application may fail to run correctly.", ex); } } if (digest == null) { return input; } try { digest.update(input.getBytes("UTF-8")); } catch (java.io.UnsupportedEncodingException ex) { logger.error("Assertion: This should never occur."); } byte[] rawData = digest.digest(); byte[] encoded = Base64.encode(rawData); String retValue = new String(encoded); return retValue; } |
00
| Code Sample 1:
private static InputStream connect(final String url) throws IOException { InputStream in = null; try { final URLConnection conn = new URL(url).openConnection(); conn.setConnectTimeout(YahooGeocoding.connectTimeOut); conn.setReadTimeout(YahooGeocoding.readTimeOut); conn.setRequestProperty("User-Agent", YahooGeocoding.USER_AGENT); in = conn.getInputStream(); return in; } catch (final IOException e) { Util.d("problems connecting to geonames url " + url + "Exception:" + e); } return in; }
Code Sample 2:
private String getMD5(String data) { try { MessageDigest md5Algorithm = MessageDigest.getInstance("MD5"); md5Algorithm.update(data.getBytes(), 0, data.length()); byte[] digest = md5Algorithm.digest(); StringBuffer hexString = new StringBuffer(); String hexDigit = null; for (int i = 0; i < digest.length; i++) { hexDigit = Integer.toHexString(0xFF & digest[i]); if (hexDigit.length() < 2) { hexDigit = "0" + hexDigit; } hexString.append(hexDigit); } return hexString.toString(); } catch (NoSuchAlgorithmException ne) { return data; } } |
11
| Code Sample 1:
private void createScript(File scriptsLocation, String relativePath, String scriptContent) { Writer fileWriter = null; try { File scriptFile = new File(scriptsLocation.getAbsolutePath() + "/" + relativePath); scriptFile.getParentFile().mkdirs(); fileWriter = new FileWriter(scriptFile); IOUtils.copy(new StringReader(scriptContent), fileWriter); } catch (IOException e) { throw new UnitilsException(e); } finally { IOUtils.closeQuietly(fileWriter); } }
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(); } |
Subsets and Splits