label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: public void test3() throws FileNotFoundException, IOException { Decoder decoder1 = new MP3Decoder(new FileInputStream("/home/marc/tmp/test1.mp3")); Decoder decoder2 = new OggDecoder(new FileInputStream("/home/marc/tmp/test1.ogg")); FileOutputStream out = new FileOutputStream("/home/marc/tmp/test.pipe"); IOUtils.copy(decoder1, out); IOUtils.copy(decoder2, out); } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: public void execute(HttpResponse response) throws HttpException, IOException { StringBuffer content = new StringBuffer(); NodeSet allNodes = membershipRegistry.listAllMembers(); for (Node node : allNodes) { content.append(node.getId().toString()); content.append(SystemUtils.LINE_SEPARATOR); } StringEntity body = new StringEntity(content.toString()); body.setContentType(PLAIN_TEXT_RESPONSE_CONTENT_TYPE); response.setEntity(body); } Code Sample 2: private String readWebpage() { BufferedReader in = null; StringBuffer sb = new StringBuffer(); try { URI uri = new URI("file:///www.vogella.de"); IProxyService proxyService = getProxyService(); IProxyData[] proxyDataForHost = proxyService.select(uri); for (IProxyData data : proxyDataForHost) { if (data.getHost() != null) { System.setProperty("http.proxySet", "true"); System.setProperty("http.proxyHost", data.getHost()); } if (data.getHost() != null) { System.setProperty("http.proxyPort", String.valueOf(data.getPort())); } } proxyService = null; URL url; url = uri.toURL(); in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { sb.append(inputLine + "\n"); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } return sb.toString(); }
00
Code Sample 1: public String getRssFeedUrl(boolean searchWeb) { String rssFeedUrl = null; if (entity.getNewsFeedUrl() != null & !entity.getUrl().equals("")) { return entity.getNewsFeedUrl(); } else if (entity.getUrl() == null || entity.getUrl().equals("")) { return entity.getNewsFeedUrl(); } else if (searchWeb) { HttpURLConnection con = null; InputStream is = null; try { URL url = new URL(entity.getUrl()); con = (HttpURLConnection) url.openConnection(); con.connect(); is = con.getInputStream(); InputStreamReader sr = new InputStreamReader(is); BufferedReader br = new BufferedReader(sr); String ln; StringBuffer sb = new StringBuffer(); while ((ln = br.readLine()) != null) { sb.append(ln + "\n"); } rssFeedUrl = extractRssFeedUrl(sb.toString()); } catch (Exception e) { log.error(e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { log.error(e); } } if (con != null) { con.disconnect(); } } } return rssFeedUrl; } Code Sample 2: public void elimina(Pedido pe) throws errorSQL, errorConexionBD { System.out.println("GestorPedido.elimina()"); int id = pe.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM pedido WHERE id=" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorPedido.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorPedido.elimina(): " + e); } }
00
Code Sample 1: protected static JXStatusBar getStatusBar(final JXPanel jxPanel, final JTabbedPane mainTabbedPane) { JXStatusBar statusBar = new JXStatusBar(); try { ClassLoader cl = Thread.currentThread().getContextClassLoader(); Enumeration<URL> urls = cl.getResources("META-INF/MANIFEST.MF"); String substanceVer = null; String substanceBuildStamp = null; while (urls.hasMoreElements()) { InputStream is = urls.nextElement().openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); while (true) { String line = br.readLine(); if (line == null) break; int firstColonIndex = line.indexOf(":"); if (firstColonIndex < 0) continue; String name = line.substring(0, firstColonIndex).trim(); String val = line.substring(firstColonIndex + 1).trim(); if (name.compareTo("Substance-Version") == 0) substanceVer = val; if (name.compareTo("Substance-BuildStamp") == 0) substanceBuildStamp = val; } try { br.close(); } catch (IOException ioe) { } } if (substanceVer != null) { JLabel statusLabel = new JLabel(substanceVer + " [built on " + substanceBuildStamp + "]"); JXStatusBar.Constraint cStatusLabel = new JXStatusBar.Constraint(); cStatusLabel.setFixedWidth(300); statusBar.add(statusLabel, cStatusLabel); } } catch (IOException ioe) { } JXStatusBar.Constraint c2 = new JXStatusBar.Constraint(JXStatusBar.Constraint.ResizeBehavior.FILL); final JLabel tabLabel = new JLabel(""); statusBar.add(tabLabel, c2); mainTabbedPane.getModel().addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { int selectedIndex = mainTabbedPane.getSelectedIndex(); if (selectedIndex < 0) tabLabel.setText("No selected tab"); else tabLabel.setText("Tab " + mainTabbedPane.getTitleAt(selectedIndex) + " selected"); } }); JPanel fontSizePanel = FontSizePanel.getPanel(); JXStatusBar.Constraint fontSizePanelConstraints = new JXStatusBar.Constraint(); fontSizePanelConstraints.setFixedWidth(270); statusBar.add(fontSizePanel, fontSizePanelConstraints); JPanel alphaPanel = new JPanel(new FlowLayout(FlowLayout.LEADING, 0, 0)); final JLabel alphaLabel = new JLabel("100%"); final JSlider alphaSlider = new JSlider(0, 100, 100); alphaSlider.setFocusable(false); alphaSlider.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { int currValue = alphaSlider.getValue(); alphaLabel.setText(currValue + "%"); jxPanel.setAlpha(currValue / 100.0f); } }); alphaSlider.setToolTipText("Changes the global opacity. Is not Substance-specific"); alphaSlider.setPreferredSize(new Dimension(120, alphaSlider.getPreferredSize().height)); alphaPanel.add(alphaLabel); alphaPanel.add(alphaSlider); JXStatusBar.Constraint alphaPanelConstraints = new JXStatusBar.Constraint(); alphaPanelConstraints.setFixedWidth(160); statusBar.add(alphaPanel, alphaPanelConstraints); return statusBar; } Code Sample 2: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
00
Code Sample 1: public In(String s) { try { File file = new File(s); if (file.exists()) { scanner = new Scanner(file, charsetName); scanner.useLocale(usLocale); return; } URL url = getClass().getResource(s); if (url == null) { url = new URL(s); } URLConnection site = url.openConnection(); InputStream is = site.getInputStream(); scanner = new Scanner(is, charsetName); scanner.useLocale(usLocale); } catch (IOException ioe) { System.err.println("Could not open " + s); } } Code Sample 2: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = random.nextLong(); } sbValueBeforeMD5.append(sid); 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) { } }
11
Code Sample 1: public void print(PrintWriter out) { out.println("<?xml version=\"1.0\"?>\n" + "<?xml-stylesheet type=\"text/xsl\" href=\"http://www.urbigene.com/foaf/foaf2html.xsl\" ?>\n" + "<rdf:RDF \n" + "xml:lang=\"en\" \n" + "xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" \n" + "xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\" \n" + "xmlns=\"http://xmlns.com/foaf/0.1/\" \n" + "xmlns:foaf=\"http://xmlns.com/foaf/0.1/\" \n" + "xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n"); out.println("<!-- generated with SciFoaf http://www.urbigene.com/foaf -->"); if (this.mainAuthor == null && this.authors.getAuthorCount() > 0) { this.mainAuthor = this.authors.getAuthorAt(0); } if (this.mainAuthor != null) { out.println("<foaf:PersonalProfileDocument rdf:about=\"\">\n" + "\t<foaf:primaryTopic rdf:nodeID=\"" + this.mainAuthor.getID() + "\"/>\n" + "\t<foaf:maker rdf:resource=\"mailto:[email protected]\"/>\n" + "\t<dc:title>FOAF for " + XMLUtilities.escape(this.mainAuthor.getName()) + "</dc:title>\n" + "\t<dc:description>\n" + "\tFriend-of-a-Friend description for " + XMLUtilities.escape(this.mainAuthor.getName()) + "\n" + "\t</dc:description>\n" + "</foaf:PersonalProfileDocument>\n\n"); } for (int i = 0; i < this.laboratories.size(); ++i) { Laboratory lab = this.laboratories.getLabAt(i); out.println("<foaf:Group rdf:ID=\"laboratory_ID" + i + "\" >"); out.println("\t<foaf:name>" + XMLUtilities.escape(lab.toString()) + "</foaf:name>"); for (int j = 0; j < lab.getAuthorCount(); ++j) { out.println("\t<foaf:member rdf:resource=\"#" + lab.getAuthorAt(j).getID() + "\" />"); } out.println("</foaf:Group>\n\n"); } for (int i = 0; i < this.authors.size(); ++i) { Author author = authors.getAuthorAt(i); out.println("<foaf:Person rdf:ID=\"" + xmlName(author.getID()) + "\" >"); out.println("\t<foaf:name>" + xmlName(author.getName()) + "</foaf:name>"); out.println("\t<foaf:title>Dr</foaf:title>"); out.println("\t<foaf:family_name>" + xmlName(author.getLastName()) + "</foaf:family_name>"); if (author.getForeName() != null && author.getForeName().length() > 2) { out.println("\t<foaf:firstName>" + xmlName(author.getForeName()) + "</foaf:firstName>"); } String prop = author.getProperty("foaf:mbox"); if (prop != null) { String tokens[] = prop.split("[\t ]+"); for (int j = 0; j < tokens.length; ++j) { if (tokens[j].trim().length() == 0) continue; if (tokens[j].equals("mailto:")) continue; if (!tokens[j].startsWith("mailto:")) tokens[j] = "mailto:" + tokens[j]; try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(tokens[j].getBytes()); byte[] digest = md.digest(); out.print("\t<foaf:mbox_sha1sum>"); for (int k = 0; k < digest.length; k++) { String hex = Integer.toHexString(digest[k]); if (hex.length() == 1) hex = "0" + hex; hex = hex.substring(hex.length() - 2); out.print(hex); } out.println("</foaf:mbox_sha1sum>"); } catch (Exception err) { out.println("\t<foaf:mbox rdf:resource=\"" + tokens[j] + "\" />"); } } } prop = author.getProperty("foaf:nick"); if (prop != null) { String tokens[] = prop.split("[\t ]+"); for (int j = 0; j < tokens.length; ++j) { if (tokens[j].trim().length() == 0) continue; out.println("\t<foaf:surname>" + XMLUtilities.escape(tokens[j]) + "</foaf:surname>"); } } prop = author.getProperty("foaf:homepage"); if (prop != null) { String tokens[] = prop.split("[\t ]+"); for (int j = 0; j < tokens.length; ++j) { if (!tokens[j].trim().startsWith("http://")) continue; if (tokens[j].trim().equals("http://")) continue; out.println("\t<foaf:homepage rdf:resource=\"" + XMLUtilities.escape(tokens[j].trim()) + "\"/>"); } } out.println("\t<foaf:publications rdf:resource=\"http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?db=pubmed&amp;cmd=Search&amp;itool=pubmed_Abstract&amp;term=" + author.getTerm() + "\"/>"); prop = author.getProperty("foaf:img"); if (prop != null) { String tokens[] = prop.split("[\t ]+"); for (int j = 0; j < tokens.length; ++j) { if (!tokens[j].trim().startsWith("http://")) continue; if (tokens[j].trim().equals("http://")) continue; out.println("\t<foaf:depiction rdf:resource=\"" + XMLUtilities.escape(tokens[j].trim()) + "\"/>"); } } AuthorList knows = this.whoknowwho.getKnown(author); for (int j = 0; j < knows.size(); ++j) { out.println("\t<foaf:knows rdf:resource=\"#" + xmlName(knows.getAuthorAt(j).getID()) + "\" />"); } Paper publications[] = this.papers.getAuthorPublications(author).toArray(); if (!(publications.length == 0)) { HashSet meshes = new HashSet(); for (int j = 0; j < publications.length; ++j) { meshes.addAll(publications[j].meshTerms); } for (Iterator itermesh = meshes.iterator(); itermesh.hasNext(); ) { MeshTerm meshterm = (MeshTerm) itermesh.next(); out.println("\t<foaf:interest>\n" + "\t\t<rdf:Description rdf:about=\"" + meshterm.getURL() + "\">\n" + "\t\t\t<dc:title>" + XMLUtilities.escape(meshterm.toString()) + "</dc:title>\n" + "\t\t</rdf:Description>\n" + "\t</foaf:interest>"); } } out.println("</foaf:Person>\n\n"); } Paper paperarray[] = this.papers.toArray(); for (int i = 0; i < paperarray.length; ++i) { out.println("<foaf:Document rdf:about=\"http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?cmd=Retrieve&amp;db=pubmed&amp;dopt=Abstract&amp;list_uids=" + paperarray[i].getPMID() + "\">"); out.println("<dc:title>" + XMLUtilities.escape(paperarray[i].getTitle()) + "</dc:title>"); for (Iterator iter = paperarray[i].authors.iterator(); iter.hasNext(); ) { Author author = (Author) iter.next(); out.println("<dc:author rdf:resource=\"#" + XMLUtilities.escape(author.getID()) + "\"/>"); } out.println("</foaf:Document>"); } out.println("</rdf:RDF>"); } Code Sample 2: public String md5sum(String toCompute) throws Exception { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(toCompute.getBytes()); java.math.BigInteger hash = new java.math.BigInteger(1, md.digest()); return hash.toString(16); }
00
Code Sample 1: public GPSTrace loadGPSTrace(long reportID) { try { URL url = new URL(SERVER_URL + XML_PATH + "gps.xml"); System.out.println(url); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.parse(url.openStream()); Element customerElement = document.getDocumentElement(); NodeList gps = customerElement.getElementsByTagName("gps"); trace = getGPSTrace(gps); } catch (SAXException sxe) { Exception x = sxe; if (sxe.getException() != null) x = sxe.getException(); x.printStackTrace(); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } return trace; } Code Sample 2: @SuppressWarnings("unchecked") @Override public synchronized void drop(DropTargetDropEvent arg0) { Helper.log().debug("Dropped"); Transferable t = arg0.getTransferable(); try { arg0.acceptDrop(arg0.getDropAction()); List<File> filelist = (List<File>) t.getTransferData(t.getTransferDataFlavors()[0]); for (File file : filelist) { Helper.log().debug(file.getAbsolutePath()); if (file.getName().toLowerCase().contains(".lnk")) { Helper.log().debug(file.getName() + " is a link"); File target = new File(rp.getRoot().getFullPath() + "/" + file.getName()); Helper.log().debug("I have opened the mayor at " + target.getAbsolutePath()); FileOutputStream fo = new FileOutputStream(target); FileInputStream fi = new FileInputStream(file); int i = 0; while (fi.available() > 0) { fo.write(fi.read()); System.out.print("."); i++; } Helper.log().debug(i + " bytes have been written to " + target.getAbsolutePath()); fo.close(); fi.close(); } } rp.redraw(); } catch (Throwable tr) { tr.printStackTrace(); } Helper.log().debug(arg0.getSource().toString()); }
11
Code Sample 1: 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)"); } Code Sample 2: private void generateArchetype(final IProject project, final IDataModel model, final IProgressMonitor monitor, final boolean offline) throws CoreException, InterruptedException, IOException { if (getArchetypeArtifactId(model) != null) { final Properties properties = new Properties(); properties.put("archetypeArtifactId", getArchetypeArtifactId(model)); properties.put("archetypeGroupId", getArchetypeGroupId(model)); properties.put("archetypeVersion", getArchetypeVersion(model)); String artifact = (String) model.getProperty(IMavenFacetInstallDataModelProperties.PROJECT_ARTIFACT_ID); if (artifact == null || artifact.trim().length() == 0) { artifact = project.getName(); } properties.put("artifactId", artifact); String group = (String) model.getProperty(IMavenFacetInstallDataModelProperties.PROJECT_GROUP_ID); if (group == null || group.trim().length() == 0) { group = project.getName(); } properties.put("groupId", group); properties.put("version", model.getProperty(IMavenFacetInstallDataModelProperties.PROJECT_VERSION)); final StringBuffer sb = new StringBuffer(System.getProperty("user.home")).append(File.separator); sb.append(".m2").append(File.separator).append("repository"); final String local = sb.toString(); Logger.getLog().debug("Local Maven2 repository :: " + local); properties.put("localRepository", local); if (!offline) { final String sbRepos = getRepositories(); properties.put("remoteRepositories", sbRepos); } final ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager(); final ILaunchConfigurationType launchConfigurationType = launchManager.getLaunchConfigurationType(LAUNCH_CONFIGURATION_TYPE_ID); final ILaunchConfigurationWorkingCopy workingCopy = launchConfigurationType.newInstance(null, "Creating project using Apache Maven archetype"); File archetypePomDirectory = getDefaultArchetypePomDirectory(); try { String dfPom = getPomFile(group, artifact); ByteArrayInputStream bais = new ByteArrayInputStream(dfPom.getBytes()); File f = new File(archetypePomDirectory, "pom.xml"); OutputStream fous = null; try { fous = new FileOutputStream(f); IOUtils.copy(bais, fous); } finally { try { if (fous != null) { fous.close(); } if (bais != null) { bais.close(); } } catch (IOException e) { } } if (SiteManager.isHttpProxyEnable()) { addProxySettings(properties); } workingCopy.setAttribute(ATTR_POM_DIR, archetypePomDirectory.getAbsolutePath()); workingCopy.setAttribute(ATTR_PROPERTIES, convertPropertiesToList(properties)); String goalName = "archetype:create"; if (offline) { goalName = new StringBuffer(goalName).append(" -o").toString(); } goalName = updateGoal(goalName); workingCopy.setAttribute(ATTR_GOALS, goalName); final long timeout = org.maven.ide.eclipse.ext.Maven2Plugin.getTimeout(); TimeoutLaunchConfiguration.launchWithTimeout(monitor, workingCopy, project, timeout); monitor.setTaskName("Moving to workspace"); FileUtils.copyDirectoryStructure(new File(archetypePomDirectory, project.getName()), ArchetypePOMHelper.getProjectDirectory(project)); monitor.worked(1); performMavenInstall(monitor, project, offline); project.refreshLocal(2, monitor); } catch (final IOException ioe) { Logger.log(Logger.ERROR, "I/O exception. One probably solution is absence " + "of mvn2 archetypes or not the correct version, " + "in your local repository. Please, check existence " + "of this archetype."); Logger.getLog().error("I/O Exception arised creating mvn2 archetype", ioe); throw ioe; } finally { FileUtils.deleteDirectory(archetypePomDirectory); Logger.log(Logger.INFO, "Invoked removing of archetype POM directory"); } } monitor.worked(1); }
11
Code Sample 1: public String getDigest(String s) throws Exception { MessageDigest md = MessageDigest.getInstance(hashName); md.update(s.getBytes()); byte[] dig = md.digest(); return Base16.toHexString(dig); } Code Sample 2: public static String generate(String presentity, String eventPackage) { if (presentity == null || eventPackage == null) { return null; } String date = Long.toString(System.currentTimeMillis()); try { MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.update(presentity.getBytes()); md.update(eventPackage.getBytes()); md.update(date.getBytes()); byte[] digest = md.digest(); return toHexString(digest); } catch (NoSuchAlgorithmException e) { return null; } }
00
Code Sample 1: public static String encodePassword(String password) { try { MessageDigest messageDiegest = MessageDigest.getInstance("SHA-1"); messageDiegest.update(password.getBytes("UTF-8")); return Base64.encodeToString(messageDiegest.digest(), false); } catch (NoSuchAlgorithmException e) { log.error("Exception while encoding password"); throw new Error(e); } catch (UnsupportedEncodingException e) { log.error("Exception while encoding password"); throw new Error(e); } } Code Sample 2: public void setInternalReferences() { for (int i = 0; i < REFSPECS.length; i++) { REFSPECS[i].setTypeRefs(conn); } String sql, sql2; try { String[][] params2 = { { "PACKAGE", "name" }, { "CLASSTYPE", "qualifiedname" }, { "MEMBER", "qualifiedname" }, { "EXECMEMBER", "fullyqualifiedname" } }; for (int i = 0; i < params2.length; i++) { log.traceln("\tProcessing seetag " + params2[i][0] + " references.."); sql = "select r.sourcedoc_id, " + params2[i][0] + ".id, " + params2[i][0] + "." + params2[i][1] + " from REFERENCE r, " + params2[i][0] + " where r.refdoc_name = " + params2[i][0] + "." + params2[i][1] + " and r.refdoc_id is null"; Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery(sql); sql2 = "update REFERENCE set refdoc_id=? where sourcedoc_id=? and refdoc_name=?"; PreparedStatement pstmt = conn.prepareStatement(sql2); while (rset.next()) { pstmt.clearParameters(); pstmt.setInt(1, rset.getInt(2)); pstmt.setInt(2, rset.getInt(1)); pstmt.setString(3, rset.getString(3)); pstmt.executeUpdate(); } pstmt.close(); rset.close(); stmt.close(); conn.commit(); } } catch (SQLException ex) { log.error("Internal Reference Update Failed!"); DBUtils.logSQLException(ex); log.error("Rolling back.."); try { conn.rollback(); } catch (SQLException inner_ex) { log.error("rollback failed!"); } } }
11
Code Sample 1: public static String digestString(String data, String algorithm) { String result = null; if (data != null) { try { MessageDigest _md = MessageDigest.getInstance(algorithm); _md.update(data.getBytes()); byte[] _digest = _md.digest(); String _ds; _ds = toHexString(_digest, 0, _digest.length); result = _ds; } catch (NoSuchAlgorithmException e) { result = null; } } return result; } Code Sample 2: public static byte[] SHA1byte(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; }
11
Code Sample 1: public void adjustPadding(File file, int paddingSize, long audioStart) throws FileNotFoundException, IOException { logger.finer("Need to move audio file to accomodate tag"); FileChannel fcIn = null; FileChannel fcOut; ByteBuffer paddingBuffer = ByteBuffer.wrap(new byte[paddingSize]); File paddedFile; try { paddedFile = File.createTempFile(Utils.getMinBaseFilenameAllowedForTempFile(file), ".new", file.getParentFile()); logger.finest("Created temp file:" + paddedFile.getName() + " for " + file.getName()); } catch (IOException ioe) { logger.log(Level.SEVERE, ioe.getMessage(), ioe); if (ioe.getMessage().equals(FileSystemMessage.ACCESS_IS_DENIED.getMsg())) { logger.severe(ErrorMessage.GENERAL_WRITE_FAILED_TO_CREATE_TEMPORARY_FILE_IN_FOLDER.getMsg(file.getName(), file.getParentFile().getPath())); throw new UnableToCreateFileException(ErrorMessage.GENERAL_WRITE_FAILED_TO_CREATE_TEMPORARY_FILE_IN_FOLDER.getMsg(file.getName(), file.getParentFile().getPath())); } else { logger.severe(ErrorMessage.GENERAL_WRITE_FAILED_TO_CREATE_TEMPORARY_FILE_IN_FOLDER.getMsg(file.getName(), file.getParentFile().getPath())); throw new UnableToCreateFileException(ErrorMessage.GENERAL_WRITE_FAILED_TO_CREATE_TEMPORARY_FILE_IN_FOLDER.getMsg(file.getName(), file.getParentFile().getPath())); } } try { fcOut = new FileOutputStream(paddedFile).getChannel(); } catch (FileNotFoundException ioe) { logger.log(Level.SEVERE, ioe.getMessage(), ioe); logger.severe(ErrorMessage.GENERAL_WRITE_FAILED_TO_MODIFY_TEMPORARY_FILE_IN_FOLDER.getMsg(file.getName(), file.getParentFile().getPath())); throw new UnableToModifyFileException(ErrorMessage.GENERAL_WRITE_FAILED_TO_MODIFY_TEMPORARY_FILE_IN_FOLDER.getMsg(file.getName(), file.getParentFile().getPath())); } try { fcIn = new FileInputStream(file).getChannel(); long written = fcOut.write(paddingBuffer); logger.finer("Copying:" + (file.length() - audioStart) + "bytes"); long audiolength = file.length() - audioStart; if (audiolength <= MAXIMUM_WRITABLE_CHUNK_SIZE) { long written2 = fcIn.transferTo(audioStart, audiolength, fcOut); logger.finer("Written padding:" + written + " Data:" + written2); if (written2 != audiolength) { throw new RuntimeException(ErrorMessage.MP3_UNABLE_TO_ADJUST_PADDING.getMsg(audiolength, written2)); } } else { long noOfChunks = audiolength / MAXIMUM_WRITABLE_CHUNK_SIZE; long lastChunkSize = audiolength % MAXIMUM_WRITABLE_CHUNK_SIZE; long written2 = 0; for (int i = 0; i < noOfChunks; i++) { written2 += fcIn.transferTo(audioStart + (i * MAXIMUM_WRITABLE_CHUNK_SIZE), MAXIMUM_WRITABLE_CHUNK_SIZE, fcOut); } written2 += fcIn.transferTo(audioStart + (noOfChunks * MAXIMUM_WRITABLE_CHUNK_SIZE), lastChunkSize, fcOut); logger.finer("Written padding:" + written + " Data:" + written2); if (written2 != audiolength) { throw new RuntimeException(ErrorMessage.MP3_UNABLE_TO_ADJUST_PADDING.getMsg(audiolength, written2)); } } long lastModified = file.lastModified(); if (fcIn != null) { if (fcIn.isOpen()) { fcIn.close(); } } if (fcOut != null) { if (fcOut.isOpen()) { fcOut.close(); } } replaceFile(file, paddedFile); paddedFile.setLastModified(lastModified); } finally { try { if (fcIn != null) { if (fcIn.isOpen()) { fcIn.close(); } } if (fcOut != null) { if (fcOut.isOpen()) { fcOut.close(); } } } catch (Exception e) { logger.log(Level.WARNING, "Problem closing channels and locks:" + e.getMessage(), e); } } } Code Sample 2: public void process(String src, String dest) { try { KanjiDAO kanjiDAO = KanjiDAOFactory.getDAO(); MorphologicalAnalyzer mecab = MorphologicalAnalyzer.getInstance(); if (mecab.isActive()) { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(src), "UTF8")); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dest), "UTF8")); String line; bw.write("// // // \r\n$title=\r\n$singer=\r\n$id=\r\n\r\n + _______ // 0 0 0 0 0 0 0\r\n\r\n"); while ((line = br.readLine()) != null) { System.out.println(line); String segment[] = line.split("//"); String japanese = null; String english = null; if (segment.length > 1) english = segment[1].trim(); if (segment.length > 0) japanese = segment[0].trim().replaceAll(" ", "_"); boolean first = true; if (japanese != null) { ArrayList<ExtractedWord> wordList = mecab.extractWord(japanese); Iterator<ExtractedWord> iter = wordList.iterator(); while (iter.hasNext()) { ExtractedWord word = iter.next(); if (first) { first = false; bw.write("*"); } else bw.write(" "); if (word.isParticle) bw.write("- "); else bw.write("+ "); if (!word.original.equals(word.reading)) { System.out.println("--> " + JapaneseString.toRomaji(word.original) + " / " + JapaneseString.toRomaji(word.reading)); KReading[] kr = ReadingAnalyzer.analyzeReadingStub(word.original, word.reading, kanjiDAO); if (kr != null) { for (int i = 0; i < kr.length; i++) { if (i > 0) bw.write(" "); bw.write(kr[i].kanji); if (kr[i].type != KReading.KANA) { bw.write("|"); bw.write(kr[i].reading); } } } else { bw.write(word.original); bw.write("|"); bw.write(word.reading); } } else { bw.write(word.original); } bw.write(" // \r\n"); } if (english != null) { bw.write(english); bw.write("\r\n"); } bw.write("\r\n"); } } br.close(); bw.close(); } else { System.out.println("Mecab couldn't be initialized"); } } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: @Override public Class<?> loadClass(final String name) throws ClassNotFoundException { final String baseName = StringUtils.substringBefore(name, "$"); if (baseName.startsWith("java") && !whitelist.contains(baseName) && !additionalWhitelist.contains(baseName)) { throw new NoClassDefFoundError(name + " is a restricted class for GAE"); } if (!name.startsWith("com.gargoylesoftware")) { return super.loadClass(name); } super.loadClass(name); final InputStream is = getResourceAsStream(name.replaceAll("\\.", "/") + ".class"); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { IOUtils.copy(is, bos); final byte[] bytes = bos.toByteArray(); return defineClass(name, bytes, 0, bytes.length); } catch (final IOException e) { throw new RuntimeException(e); } } Code Sample 2: private void copyDirContent(String fromDir, String toDir) throws Exception { String fs = System.getProperty("file.separator"); File[] files = new File(fromDir).listFiles(); if (files == null) { throw new FileNotFoundException("Sourcepath: " + fromDir + " not found!"); } for (int i = 0; i < files.length; i++) { File dir = new File(toDir); dir.mkdirs(); if (files[i].isFile()) { try { FileChannel srcChannel = new FileInputStream(files[i]).getChannel(); FileChannel dstChannel = new FileOutputStream(toDir + fs + files[i].getName()).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (Exception e) { Logger.ERROR("Error during file copy: " + e.getMessage()); throw e; } } } }
11
Code Sample 1: private boolean readRemoteFile() { InputStream inputstream; Concept concept = new Concept(); try { inputstream = url.openStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputstream); BufferedReader bufferedreader = new BufferedReader(inputStreamReader); String s4; while ((s4 = bufferedreader.readLine()) != null && s4.length() > 0) { if (!parseLine(s4, concept)) { return false; } } } catch (MalformedURLException e) { logger.fatal("malformed URL, trying to read local file"); return readLocalFile(); } catch (IOException e1) { logger.fatal("Error reading URL file, trying to read local file"); return readLocalFile(); } catch (Exception x) { logger.fatal("Failed to readRemoteFile " + x.getMessage() + ", trying to read local file"); return readLocalFile(); } return true; } Code Sample 2: @Test public void GetBingSearchResult() throws UnsupportedEncodingException { String query = "Scanner Java example"; String request = "http://api.bing.net/xml.aspx?AppId=731DD1E61BE6DE4601A3008DC7A0EB379149EC29" + "&Version=2.2&Market=en-US&Query=" + URLEncoder.encode(query, "UTF-8") + "&Sources=web+spell&Web.Count=50"; try { URL url = new URL(request); System.out.println("Host : " + url.getHost()); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; String finalContents = ""; while ((inputLine = reader.readLine()) != null) { finalContents += "\n" + inputLine; } Document doc = Jsoup.parse(finalContents); Elements eles = doc.getElementsByTag("web:Url"); for (Element ele : eles) { System.out.println(ele.text()); } } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: private static boolean hasPackageInfo(URL url) { if (url == null) return false; BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = br.readLine()) != null) { if (line.startsWith("Specification-Title: ") || line.startsWith("Specification-Version: ") || line.startsWith("Specification-Vendor: ") || line.startsWith("Implementation-Title: ") || line.startsWith("Implementation-Version: ") || line.startsWith("Implementation-Vendor: ")) return true; } } catch (IOException ioe) { } finally { if (br != null) try { br.close(); } catch (IOException e) { } } return false; } Code Sample 2: public String getMD5Str(String str) { MessageDigest messageDigest = null; String mdStr = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(str.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } mdStr = md5StrBuff.toString(); return mdStr; }
00
Code Sample 1: public void close() throws IOException { output.flush(); output.close(); FTPClient client = new FTPClient(); if (server == null) { throw new IOException("FTP_SERVER property is missing"); } else { if (port != null) { client.connect(server, Integer.parseInt(port)); } else { client.connect(server); } } if (username != null) { logger.debug("log in as specified user"); client.login(username, password); } else { logger.debug("log in as anonymous"); client.login("anonymous", this.getClass().getName()); } if (binaery) { logger.debug("use binaery mode"); client.setFileType(FTP.BINARY_FILE_TYPE); } else { logger.debug("use ascii mode"); client.setFileType(FTP.ASCII_FILE_TYPE); } client.enterLocalPassiveMode(); logger.debug("store file on server: " + tempFile + " under name: " + file); InputStream stream = new FileInputStream(tempFile); String dir = file.substring(0, file.lastIndexOf("/")) + "/"; String split[] = dir.split("/"); String last = ""; logger.debug("creating dir: " + dir); for (int i = 0; i < split.length; i++) { last = last + "/" + split[i]; logger.debug(last + " --> " + client.makeDirectory(last)); } logger.debug("storing file: " + file); client.deleteFile(file); client.storeFile(file, stream); client.disconnect(); tempFile.delete(); try { FTPSource source = new FTPSource(); source.configure(properties); source.setIdentifier(file); if (source.exist()) { logger.debug("done"); } else { throw new IOException("can't find file I just wrote, something went wrong!"); } } catch (ConfigurationException e) { throw new IOException(e.getMessage()); } } 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); } }
11
Code Sample 1: private void copy(File fin, File fout) throws IOException { FileOutputStream out = new FileOutputStream(fout); FileInputStream in = new FileInputStream(fin); byte[] buf = new byte[2048]; int read = in.read(buf); while (read > 0) { out.write(buf, 0, read); read = in.read(buf); } in.close(); out.close(); } Code Sample 2: public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
00
Code Sample 1: public static void readFile(FOUserAgent ua, String uri, Writer output, String encoding) throws IOException { InputStream in = getURLInputStream(ua, uri); try { StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, encoding); } finally { IOUtils.closeQuietly(in); } } Code Sample 2: private void parseXmlFile() throws IOException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder db = dbf.newDocumentBuilder(); if (file != null) { dom = db.parse(file); } else { dom = db.parse(url.openStream()); } } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (SAXException se) { se.printStackTrace(); } }
00
Code Sample 1: public static final String md5(final String s) { try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte messageDigest[] = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { String h = Integer.toHexString(0xFF & messageDigest[i]); while (h.length() < 2) { h = "0" + h; } hexString.append(h); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; } Code Sample 2: public static void main(String[] args) { String inFile = "test_data/blobs.png"; String outFile = "ReadWriteTest.png"; itkImageFileReaderUC2_Pointer reader = itkImageFileReaderUC2.itkImageFileReaderUC2_New(); itkImageFileWriterUC2_Pointer writer = itkImageFileWriterUC2.itkImageFileWriterUC2_New(); reader.SetFileName(inFile); writer.SetFileName(outFile); writer.SetInput(reader.GetOutput()); writer.Update(); }
00
Code Sample 1: private static URL downloadFile(URL url, File destFile) throws Exception { try { URLConnection urlConnection = url.openConnection(); File tmpFile = null; try { tmpFile = File.createTempFile("remoteLib_", null); InputStream in = null; FileOutputStream out = null; try { in = urlConnection.getInputStream(); out = new FileOutputStream(tmpFile); IOUtils.copy(in, out); } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } } FileUtils.copyFile(tmpFile, destFile); } finally { if (tmpFile != null) { tmpFile.delete(); } } URL localURL = destFile.toURI().toURL(); return localURL; } catch (Exception ex) { throw new RuntimeException("Could not download URL: " + url, ex); } } Code Sample 2: private void readFromStorableInput(String filename) { try { URL url = new URL(getCodeBase(), filename); InputStream stream = url.openStream(); StorableInput input = new StorableInput(stream); fDrawing.release(); fDrawing = (Drawing) input.readStorable(); view().setDrawing(fDrawing); } catch (IOException e) { initDrawing(); showStatus("Error:" + e); } }
11
Code Sample 1: private String getPage(String urlString) throws Exception { if (pageBuffer.containsKey(urlString)) return pageBuffer.get(urlString); URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); BufferedReader in = null; StringBuilder page = new StringBuilder(); try { in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = in.readLine()) != null) { page.append(line); page.append("\n"); } } catch (IOException ioe) { logger.warn("Failed to read web page"); } finally { if (in != null) { in.close(); } } return page.toString(); } 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; }
00
Code Sample 1: private static String fetchUrl(String url, boolean keepLineEnds) throws IOException, MalformedURLException { URLConnection destConnection = (new URL(url)).openConnection(); BufferedReader br; String inputLine; StringBuffer doc = new StringBuffer(); String contentEncoding; destConnection.setRequestProperty("Accept-Encoding", "gzip"); if (proxyAuth != null) destConnection.setRequestProperty("Proxy-Authorization", proxyAuth); destConnection.connect(); contentEncoding = destConnection.getContentEncoding(); if ((contentEncoding != null) && contentEncoding.equals("gzip")) { br = new BufferedReader(new InputStreamReader(new GZIPInputStream(destConnection.getInputStream()))); } else { br = new BufferedReader(new InputStreamReader(destConnection.getInputStream())); } while ((inputLine = br.readLine()) != null) { if (keepLineEnds) doc.append(inputLine + "\n"); else doc.append(inputLine); } br.close(); return doc.toString(); } Code Sample 2: private void openConnection() throws IOException { connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "text/xml"); }
11
Code Sample 1: public void delete(String user) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); stmt.executeUpdate("delete from Principals where PrincipalId = '" + user + "'"); stmt.executeUpdate("delete from Roles where PrincipalId = '" + user + "'"); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } } Code Sample 2: protected String doIt() throws java.lang.Exception { StringBuffer sql = null; int no = 0; String clientCheck = " AND AD_Client_ID=" + m_AD_Client_ID; String[] strFields = new String[] { "Value", "Name", "Description", "DocumentNote", "Help", "UPC", "SKU", "Classification", "ProductType", "Discontinued", "DiscontinuedBy", "ImageURL", "DescriptionURL" }; for (int i = 0; i < strFields.length; i++) { sql = new StringBuffer("UPDATE I_PRODUCT i " + "SET ").append(strFields[i]).append(" = (SELECT ").append(strFields[i]).append(" FROM M_Product p" + " WHERE i.M_Product_ID=p.M_Product_ID AND i.AD_Client_ID=p.AD_Client_ID) " + "WHERE M_Product_ID IS NOT NULL" + " AND EXISTS (SELECT * FROM M_Product p WHERE " + strFields[i] + " IS NOT NULL AND p.M_Product_ID = i.M_Product_ID AND i.AD_Client_ID=p.AD_Client_ID)" + " AND I_IsImported='N'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - " + strFields[i] + " - default from existing Product=" + no); } } String[] numFields = new String[] { "C_UOM_ID", "M_Product_Category_ID", "Volume", "Weight", "ShelfWidth", "ShelfHeight", "ShelfDepth", "UnitsPerPallet", "M_Product_Family_ID" }; for (int i = 0; i < numFields.length; i++) { sql = new StringBuffer("UPDATE I_PRODUCT i " + "SET ").append(numFields[i]).append(" = (SELECT ").append(numFields[i]).append(" FROM M_Product p" + " WHERE i.M_Product_ID=p.M_Product_ID AND i.AD_Client_ID=p.AD_Client_ID) " + "WHERE M_Product_ID IS NOT NULL" + " AND EXISTS (SELECT * FROM M_Product p WHERE " + numFields[i] + " IS NOT NULL AND p.M_Product_ID = i.M_Product_ID AND i.AD_Client_ID=p.AD_Client_ID)" + " AND I_IsImported='N'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - " + numFields[i] + " default from existing Product=" + no); } } String[] strFieldsPO = new String[] { "UPC", "PriceEffective", "VendorProductNo", "VendorCategory", "Manufacturer", "Discontinued", "DiscontinuedBy" }; for (int i = 0; i < strFieldsPO.length; i++) { sql = new StringBuffer("UPDATE I_PRODUCT i " + "SET ").append(strFieldsPO[i]).append(" = (SELECT ").append(strFieldsPO[i]).append(" FROM M_Product_PO p" + " WHERE i.M_Product_ID=p.M_Product_ID AND i.C_BPartner_ID=p.C_BPartner_ID AND i.AD_Client_ID=p.AD_Client_ID) " + "WHERE M_Product_ID IS NOT NULL AND C_BPartner_ID IS NOT NULL" + " AND EXISTS (SELECT * FROM M_Product_PO p WHERE " + strFieldsPO[i] + " IS NOT NULL AND p.M_Product_ID = i.M_Product_ID AND i.AD_Client_ID=p.AD_Client_ID)" + " AND I_IsImported='N'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - " + strFieldsPO[i] + " default from existing Product PO=" + no); } } String[] numFieldsPO = new String[] { "C_UOM_ID", "C_Currency_ID", "RoyaltyAmt", "Order_Min", "Order_Pack", "CostPerOrder", "DeliveryTime_Promised" }; for (int i = 0; i < numFieldsPO.length; i++) { sql = new StringBuffer("UPDATE I_PRODUCT i " + "SET ").append(numFieldsPO[i]).append(" = (SELECT ").append(numFieldsPO[i]).append(" FROM M_Product_PO p" + " WHERE i.M_Product_ID=p.M_Product_ID AND i.C_BPartner_ID=p.C_BPartner_ID AND i.AD_Client_ID=p.AD_Client_ID) " + "WHERE M_Product_ID IS NOT NULL AND C_BPartner_ID IS NOT NULL" + " AND EXISTS (SELECT * FROM M_Product_PO p WHERE " + numFieldsPO[i] + " IS NOT NULL AND p.M_Product_ID = i.M_Product_ID AND i.AD_Client_ID=p.AD_Client_ID)" + " AND I_IsImported='N'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - " + numFieldsPO[i] + " default from existing Product PO=" + no); } } numFieldsPO = new String[] { "PriceList", "PricePO" }; for (int i = 0; i < numFieldsPO.length; i++) { sql = new StringBuffer("UPDATE I_PRODUCT i " + "SET ").append(numFieldsPO[i]).append(" = (SELECT ").append(numFieldsPO[i]).append(" FROM M_Product_PO p" + " WHERE i.M_Product_ID=p.M_Product_ID AND i.C_BPartner_ID=p.C_BPartner_ID AND i.AD_Client_ID=p.AD_Client_ID) " + "WHERE M_Product_ID IS NOT NULL AND C_BPartner_ID IS NOT NULL" + " AND (").append(numFieldsPO[i]).append(" IS NULL OR ").append(numFieldsPO[i]).append("=0)" + " AND I_IsImported='N'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - " + numFieldsPO[i] + " default from existing Product PO=" + no); } } sql = new StringBuffer("UPDATE I_Product i " + "SET X12DE355 = " + "(SELECT X12DE355 FROM C_UOM u WHERE u.IsDefault='Y' AND u.AD_Client_ID IN (0,i.AD_Client_ID) AND ROWNUM=1) " + "WHERE X12DE355 IS NULL AND C_UOM_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); log.fine("doIt - Set UOM Default=" + no); sql = new StringBuffer("UPDATE I_Product i " + "SET C_UOM_ID = (SELECT C_UOM_ID FROM C_UOM u WHERE u.X12DE355=i.X12DE355 AND u.AD_Client_ID IN (0,i.AD_Client_ID)) " + "WHERE C_UOM_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); log.info("doIt - Set UOM=" + no); sql = new StringBuffer("UPDATE I_Product " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid UOM, ' " + "WHERE C_UOM_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - Invalid UOM=" + no); } sql = new StringBuffer("UPDATE I_Product " + "SET ProductCategory_Value=(SELECT Value FROM M_Product_Category" + " WHERE IsDefault='Y' AND AD_Client_ID=").append(m_AD_Client_ID).append(" AND ROWNUM=1) " + "WHERE ProductCategory_Value IS NULL AND M_Product_Category_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); log.fine("doIt - Set Category Default=" + no); sql = new StringBuffer("UPDATE I_Product i " + "SET M_Product_Category_ID=(SELECT M_Product_Category_ID FROM M_Product_Category c" + " WHERE i.ProductCategory_Value=c.Value AND i.AD_Client_ID=c.AD_Client_ID) " + "WHERE M_Product_Category_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); log.info("doIt - Set Category=" + no); sql = new StringBuffer("UPDATE I_Product " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid ProdCategorty,' " + "WHERE M_Product_Category_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - Invalid Category=" + no); } sql = new StringBuffer("UPDATE I_Product i " + "SET ISO_Code=(SELECT ISO_Code FROM C_Currency c" + " INNER JOIN C_AcctSchema a ON (a.C_Currency_ID=c.C_Currency_ID)" + " INNER JOIN AD_ClientInfo fo ON (a.C_AcctSchema_ID=fo.C_AcctSchema1_ID)" + " WHERE fo.AD_Client_ID=i.AD_Client_ID) " + "WHERE C_Currency_ID IS NULL AND ISO_Code IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); log.fine("doIt - Set Currency Default=" + no); sql = new StringBuffer("UPDATE I_Product i " + "SET C_Currency_ID=(SELECT C_Currency_ID FROM C_Currency c" + " WHERE i.ISO_Code=c.ISO_Code AND c.AD_Client_ID IN (0,i.AD_Client_ID)) " + "WHERE C_Currency_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); log.info("doIt- Set Currency=" + no); sql = new StringBuffer("UPDATE I_Product " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Currency,' " + "WHERE C_Currency_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - Invalid Currency=" + no); } sql = new StringBuffer("UPDATE I_Product " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid ProductType,' " + "WHERE ProductType NOT IN ('I','S')" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - Invalid ProductType=" + no); } sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Value not unique,' " + "WHERE I_IsImported<>'Y'" + " AND Value IN (SELECT Value FROM I_Product pr WHERE i.AD_Client_ID=pr.AD_Client_ID GROUP BY Value HAVING COUNT(*) > 1)").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.warning("doIt - Not Unique Value=" + no); } sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=UPC not unique,' " + "WHERE I_IsImported<>'Y'" + " AND UPC IN (SELECT UPC FROM I_Product pr WHERE i.AD_Client_ID=pr.AD_Client_ID GROUP BY UPC HAVING COUNT(*) > 1)").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.warning("doIt - Not Unique UPC=" + no); } sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=No Mandatory Value,' " + "WHERE Value IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.warning("doIt - No Mandatory Value=" + no); } sql = new StringBuffer("UPDATE I_Product " + "SET VendorProductNo=Value " + "WHERE C_BPartner_ID IS NOT NULL AND VendorProductNo IS NULL" + " AND I_IsImported='N'").append(clientCheck); no = DB.executeUpdate(sql.toString()); log.info("doIt - VendorProductNo Set to Value=" + no); sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=VendorProductNo not unique,' " + "WHERE I_IsImported<>'Y'" + " AND C_BPartner_ID IS NOT NULL" + " AND (C_BPartner_ID, VendorProductNo) IN " + " (SELECT C_BPartner_ID, VendorProductNo FROM I_Product pr WHERE i.AD_Client_ID=pr.AD_Client_ID GROUP BY C_BPartner_ID, VendorProductNo HAVING COUNT(*) > 1)").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.warning("doIt - Not Unique VendorProductNo=" + no); } int C_TaxCategory_ID = 0; try { PreparedStatement pstmt = DB.prepareStatement("SELECT C_TaxCategory_ID FROM C_TaxCategory WHERE IsDefault='Y'" + clientCheck); ResultSet rs = pstmt.executeQuery(); if (rs.next()) { C_TaxCategory_ID = rs.getInt(1); } rs.close(); pstmt.close(); } catch (SQLException e) { throw new Exception("doIt - TaxCategory", e); } log.fine("doIt - C_TaxCategory_ID=" + C_TaxCategory_ID); int noInsert = 0; int noUpdate = 0; int noInsertPO = 0; int noUpdatePO = 0; log.fine("doIt - start inserting/updating ..."); sql = new StringBuffer("SELECT I_Product_ID, M_Product_ID, C_BPartner_ID " + "FROM I_Product WHERE I_IsImported='N'").append(clientCheck); Connection conn = DB.createConnection(false, Connection.TRANSACTION_READ_COMMITTED); try { PreparedStatement pstmt_insertProduct = conn.prepareStatement("INSERT INTO M_Product (M_Product_ID," + "AD_Client_ID,AD_Org_ID,IsActive,Created,CreatedBy,Updated,UpdatedBy," + "Value,Name,Description,DocumentNote,Help," + "UPC,SKU,C_UOM_ID,IsSummary,M_Product_Category_ID,C_TaxCategory_ID," + "ProductType,ImageURL,DescriptionURL,M_Product_Family_ID) " + "SELECT ?," + "AD_Client_ID,AD_Org_ID,'Y',CURRENT_TIMESTAMP,CreatedBy,CURRENT_TIMESTAMP,UpdatedBy," + "Value,Name,Description,DocumentNote,Help," + "UPC,SKU,C_UOM_ID,'N',M_Product_Category_ID," + C_TaxCategory_ID + "," + "ProductType,ImageURL,DescriptionURL,M_Product_Category_ID " + "FROM I_Product " + "WHERE I_Product_ID=?"); PreparedStatement pstmt_updateProduct = conn.prepareStatement("UPDATE M_PRODUCT " + "SET Value=aux.value" + ",Name=aux.Name" + ",Description=aux.Description" + ",DocumentNote=aux.DocumentNote" + ",Help=aux.Help" + ",UPC=aux.UPC" + ",SKU=aux.SKU" + ",C_UOM_ID=aux.C_UOM_ID" + ",M_Product_Category_ID=aux.M_Product_Category_ID" + ",Classification=aux.Classification" + ",ProductType=aux.ProductType" + ",Volume=aux.Volume" + ",Weight=aux.Weight" + ",ShelfWidth=aux.ShelfWidth" + ",ShelfHeight=aux.ShelfHeight" + ",ShelfDepth=aux.ShelfDepth" + ",UnitsPerPallet=aux.UnitsPerPallet" + ",Discontinued=aux.Discontinued" + ",DiscontinuedBy=aux.DiscontinuedBy" + ",Updated=current_timestamp" + ",UpdatedBy=aux.UpdatedBy" + " from (SELECT Value,Name,Description,DocumentNote,Help,UPC,SKU,C_UOM_ID,M_Product_Category_ID,Classification,ProductType,Volume,Weight,ShelfWidth,ShelfHeight,ShelfDepth,UnitsPerPallet,Discontinued,DiscontinuedBy,UpdatedBy FROM I_Product WHERE I_Product_ID=?) as aux" + " WHERE M_Product_ID=?"); PreparedStatement pstmt_updateProductPO = conn.prepareStatement("UPDATE M_Product_PO " + "SET IsCurrentVendor='Y'" + ",C_UOM_ID=aux1.C_UOM_ID" + ",C_Currency_ID=aux1.C_Currency_ID" + ",UPC=aux1.UPC" + ",PriceList=aux1.PriceList" + ",PricePO=aux1.PricePO" + ",RoyaltyAmt=aux1.RoyaltyAmt" + ",PriceEffective=aux1.PriceEffective" + ",VendorProductNo=aux1.VendorProductNo" + ",VendorCategory=aux1.VendorCategory" + ",Manufacturer=aux1.Manufacturer" + ",Discontinued=aux1.Discontinued" + ",DiscontinuedBy=aux1.DiscontinuedBy" + ",Order_Min=aux1.Order_Min" + ",Order_Pack=aux1.Order_Pack" + ",CostPerOrder=aux1.CostPerOrder" + ",DeliveryTime_Promised=aux1.DeliveryTime_Promised" + ",Updated=current_timestamp" + ",UpdatedBy=aux1.UpdatedBy" + " from (SELECT 'Y',C_UOM_ID,C_Currency_ID,UPC,PriceList,PricePO,RoyaltyAmt,PriceEffective,VendorProductNo,VendorCategory,Manufacturer,Discontinued,DiscontinuedBy,Order_Min,Order_Pack,CostPerOrder,DeliveryTime_Promised,UpdatedBy FROM I_Product WHERE I_Product_ID=?) as aux1" + " WHERE M_Product_ID=? AND C_BPartner_ID=?"); PreparedStatement pstmt_insertProductPO = conn.prepareStatement("INSERT INTO M_Product_PO (M_Product_ID,C_BPartner_ID, " + "AD_Client_ID,AD_Org_ID,IsActive,Created,CreatedBy,Updated,UpdatedBy," + "IsCurrentVendor,C_UOM_ID,C_Currency_ID,UPC," + "PriceList,PricePO,RoyaltyAmt,PriceEffective," + "VendorProductNo,VendorCategory,Manufacturer," + "Discontinued,DiscontinuedBy,Order_Min,Order_Pack," + "CostPerOrder,DeliveryTime_Promised) " + "SELECT ?,?, " + "AD_Client_ID,AD_Org_ID,'Y',d,CreatedBy,CURRENT_TIMESTAMP,UpdatedBy," + "'Y',C_UOM_ID,C_Currency_ID,UPC," + "PriceList,PricePO,RoyaltyAmt,PriceEffective," + "VendorProductNo,VendorCategory,Manufacturer," + "Discontinued,DiscontinuedBy,Order_Min,Order_Pack," + "CostPerOrder,DeliveryTime_Promised " + "FROM I_Product " + "WHERE I_Product_ID=?"); PreparedStatement pstmt_setImported = conn.prepareStatement("UPDATE I_Product SET I_IsImported='Y', M_Product_ID=?, " + "Updated=CURRENT_TIMESTAMP, Processed='Y' WHERE I_Product_ID=?"); PreparedStatement pstmt = DB.prepareStatement(sql.toString()); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { int I_Product_ID = rs.getInt(1); int M_Product_ID = rs.getInt(2); int C_BPartner_ID = rs.getInt(3); boolean newProduct = M_Product_ID == 0; log.fine("I_Product_ID=" + I_Product_ID + ", M_Product_ID=" + M_Product_ID + ", C_BPartner_ID=" + C_BPartner_ID); if (newProduct) { M_Product_ID = DB.getNextID(m_AD_Client_ID, "M_Product", null); pstmt_insertProduct.setInt(1, M_Product_ID); pstmt_insertProduct.setInt(2, I_Product_ID); try { no = pstmt_insertProduct.executeUpdate(); log.finer("Insert Product = " + no); noInsert++; } catch (SQLException ex) { log.warning("Insert Product - " + ex.toString()); sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append(DB.TO_STRING("Insert Product: " + ex.toString())).append("WHERE I_Product_ID=").append(I_Product_ID); DB.executeUpdate(sql.toString()); continue; } } else { pstmt_updateProduct.setInt(1, I_Product_ID); pstmt_updateProduct.setInt(2, M_Product_ID); try { no = pstmt_updateProduct.executeUpdate(); log.finer("Update Product = " + no); noUpdate++; } catch (SQLException ex) { log.warning("Update Product - " + ex.toString()); sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append(DB.TO_STRING("Update Product: " + ex.toString())).append("WHERE I_Product_ID=").append(I_Product_ID); DB.executeUpdate(sql.toString()); continue; } } if (C_BPartner_ID != 0) { no = 0; if (!newProduct) { pstmt_updateProductPO.setInt(1, I_Product_ID); pstmt_updateProductPO.setInt(2, M_Product_ID); pstmt_updateProductPO.setInt(3, C_BPartner_ID); try { no = pstmt_updateProductPO.executeUpdate(); log.finer("Update Product_PO = " + no); noUpdatePO++; } catch (SQLException ex) { log.warning("Update Product_PO - " + ex.toString()); noUpdate--; conn.rollback(); sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append(DB.TO_STRING("Update Product_PO: " + ex.toString())).append("WHERE I_Product_ID=").append(I_Product_ID); DB.executeUpdate(sql.toString()); continue; } } if (no == 0) { pstmt_insertProductPO.setInt(1, M_Product_ID); pstmt_insertProductPO.setInt(2, C_BPartner_ID); pstmt_insertProductPO.setInt(3, I_Product_ID); try { no = pstmt_insertProductPO.executeUpdate(); log.finer("Insert Product_PO = " + no); noInsertPO++; } catch (SQLException ex) { log.warning("Insert Product_PO - " + ex.toString()); noInsert--; conn.rollback(); sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append(DB.TO_STRING("Insert Product_PO: " + ex.toString())).append("WHERE I_Product_ID=").append(I_Product_ID); DB.executeUpdate(sql.toString()); continue; } } } pstmt_setImported.setInt(1, M_Product_ID); pstmt_setImported.setInt(2, I_Product_ID); no = pstmt_setImported.executeUpdate(); conn.commit(); } rs.close(); pstmt.close(); pstmt_insertProduct.close(); pstmt_updateProduct.close(); pstmt_insertProductPO.close(); pstmt_updateProductPO.close(); pstmt_setImported.close(); conn.close(); conn = null; } catch (SQLException e) { try { if (conn != null) { conn.close(); } conn = null; } catch (SQLException ex) { } log.log(Level.SEVERE, "doIt", e); throw new Exception("doIt", e); } finally { if (conn != null) { conn.close(); } conn = null; } sql = new StringBuffer("UPDATE I_Product " + "SET I_IsImported='N', Updated=CURRENT_TIMESTAMP " + "WHERE I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); StringBuffer infoReturn = new StringBuffer(""); infoReturn.append("<tr><td>@Errors@</td><td>").append(no).append("</td></tr>"); infoReturn.append("<tr><td>@M_Product_ID@: @Inserted@</td><td>").append(noInsert).append("</td></tr>"); infoReturn.append("<tr><td>@M_Product_ID@: @Updated@</td><td>").append(noUpdate).append("</td></tr>"); infoReturn.append("<tr><td>@M_Product_ID@ @Purchase@: @Inserted@</td><td>").append(noInsertPO).append("</td></tr>"); infoReturn.append("<tr><td>@M_Product_ID@ @Purchase@: @Updated@</td><td>").append(noUpdatePO).append("</td></tr>"); return infoReturn.toString(); }
00
Code Sample 1: public static void main(String[] args) { FTPClient client = new FTPClient(); try { File l_file = new File("C:/temp/testLoribel.html"); String l_url = "http://www.loribel.com/index.html"; GB_HttpTools.loadUrlToFile(l_url, l_file, ENCODING.ISO_8859_1); System.out.println("Try to connect..."); client.connect("ftp://ftp.phpnet.org"); System.out.println("Connected to server"); System.out.println("Try to connect..."); boolean b = client.login("fff", "ddd"); System.out.println("Login: " + b); String[] l_names = client.listNames(); GB_DebugTools.debugArray(GB_FtpDemo2.class, "names", l_names); b = client.makeDirectory("test02/toto"); System.out.println("Mkdir: " + b); String l_remote = "test02/test.xml"; InputStream l_local = new StringInputStream("Test111111111111111"); b = client.storeFile(l_remote, l_local); System.out.println("Copy file: " + b); } catch (Exception ex) { ex.printStackTrace(); } } Code Sample 2: public static String encodeByMd5(String str) { try { if (str == null) { str = ""; } MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(str.getBytes("utf-8")); byte[] b = md5.digest(); int i; StringBuffer buff = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) { i += 256; } if (i < 16) { buff.append("0"); } buff.append(Integer.toHexString(i)); } return buff.toString(); } catch (Exception e) { return str; } }
00
Code Sample 1: public static String encrypt(String value) { MessageDigest messageDigest; byte[] raw = null; try { messageDigest = MessageDigest.getInstance("SHA"); messageDigest.update(((String) value).getBytes("UTF-8")); raw = messageDigest.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return (new BASE64Encoder()).encode(raw); } Code Sample 2: public void moveMessage(DBMimeMessage oSrcMsg) throws MessagingException { if (DebugFile.trace) { DebugFile.writeln("Begin DBFolder.moveMessage()"); DebugFile.incIdent(); } JDCConnection oConn = null; PreparedStatement oStmt = null; ResultSet oRSet = null; BigDecimal oPg = null; BigDecimal oPos = null; int iLen = 0; try { oConn = ((DBStore) getStore()).getConnection(); oStmt = oConn.prepareStatement("SELECT " + DB.pg_message + "," + DB.nu_position + "," + DB.len_mimemsg + " FROM " + DB.k_mime_msgs + " WHERE " + DB.gu_mimemsg + "=?"); oStmt.setString(1, oSrcMsg.getMessageGuid()); oRSet = oStmt.executeQuery(); if (oRSet.next()) { oPg = oRSet.getBigDecimal(1); oPos = oRSet.getBigDecimal(2); iLen = oRSet.getInt(3); } oRSet.close(); oRSet = null; oStmt.close(); oStmt = null; oConn.setAutoCommit(false); oStmt = oConn.prepareStatement("UPDATE " + DB.k_categories + " SET " + DB.len_size + "=" + DB.len_size + "-" + String.valueOf(iLen) + " WHERE " + DB.gu_category + "=?"); oStmt.setString(1, ((DBFolder) (oSrcMsg.getFolder())).getCategory().getString(DB.gu_category)); oStmt.executeUpdate(); oStmt.close(); oStmt = null; oStmt = oConn.prepareStatement("UPDATE " + DB.k_categories + " SET " + DB.len_size + "=" + DB.len_size + "+" + String.valueOf(iLen) + " WHERE " + DB.gu_category + "=?"); oStmt.setString(1, getCategory().getString(DB.gu_category)); oStmt.executeUpdate(); oStmt.close(); oStmt = null; oConn.commit(); } catch (SQLException sqle) { if (null != oRSet) { try { oRSet.close(); } catch (Exception ignore) { } } if (null != oStmt) { try { oStmt.close(); } catch (Exception ignore) { } } if (null != oConn) { try { oConn.rollback(); } catch (Exception ignore) { } } throw new MessagingException(sqle.getMessage(), sqle); } if (null == oPg) throw new MessagingException("Source message not found"); if (null == oPos) throw new MessagingException("Source message position is not valid"); DBFolder oSrcFldr = (DBFolder) oSrcMsg.getFolder(); MboxFile oMboxSrc = null, oMboxThis = null; try { oMboxSrc = new MboxFile(oSrcFldr.getFile(), MboxFile.READ_WRITE); oMboxThis = new MboxFile(oSrcFldr.getFile(), MboxFile.READ_WRITE); oMboxThis.appendMessage(oMboxSrc, oPos.longValue(), iLen); oMboxThis.close(); oMboxThis = null; oMboxSrc.purge(new int[] { oPg.intValue() }); oMboxSrc.close(); oMboxSrc = null; } catch (Exception e) { if (oMboxThis != null) { try { oMboxThis.close(); } catch (Exception ignore) { } } if (oMboxSrc != null) { try { oMboxSrc.close(); } catch (Exception ignore) { } } throw new MessagingException(e.getMessage(), e); } try { oConn = ((DBStore) getStore()).getConnection(); BigDecimal dNext = getNextMessage(); String sCatGuid = getCategory().getString(DB.gu_category); oStmt = oConn.prepareStatement("UPDATE " + DB.k_mime_msgs + " SET " + DB.gu_category + "=?," + DB.pg_message + "=? WHERE " + DB.gu_mimemsg + "=?"); oStmt.setString(1, sCatGuid); oStmt.setBigDecimal(2, dNext); oStmt.setString(3, oSrcMsg.getMessageGuid()); oStmt.executeUpdate(); oStmt.close(); oStmt = null; oConn.commit(); } catch (SQLException sqle) { if (null != oStmt) { try { oStmt.close(); } catch (Exception ignore) { } } if (null != oConn) { try { oConn.rollback(); } catch (Exception ignore) { } } throw new MessagingException(sqle.getMessage(), sqle); } if (DebugFile.trace) { DebugFile.decIdent(); DebugFile.writeln("End DBFolder.moveMessage()"); } }
00
Code Sample 1: public int update(BusinessObject o) throws DAOException { int update = 0; Item item = (Item) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("UPDATE_ITEM")); pst.setString(1, item.getDescription()); pst.setDouble(2, item.getUnit_price()); pst.setInt(3, item.getQuantity()); pst.setDouble(4, item.getVat()); pst.setInt(5, item.getIdProject()); if (item.getIdBill() == 0) pst.setNull(6, java.sql.Types.INTEGER); else pst.setInt(6, item.getIdBill()); pst.setInt(7, item.getIdCurrency()); pst.setInt(8, item.getId()); System.out.println("item => " + item.getDescription() + " " + item.getUnit_price() + " " + item.getQuantity() + " " + item.getVat() + " " + item.getIdProject() + " " + item.getIdBill() + " " + item.getIdCurrency() + " " + item.getId()); update = pst.executeUpdate(); if (update <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (update > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return update; } Code Sample 2: protected void setOuterIP() { try { URL url = new URL("http://elm-ve.sf.net/ipCheck/ipCheck.cgi"); InputStreamReader isr = new InputStreamReader(url.openStream()); BufferedReader br = new BufferedReader(isr); String ip = br.readLine(); ip = ip.trim(); bridgeOutIPTF.setText(ip); } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: public static void main(String[] args) throws IOException { System.setProperty("java.protocol.xfile", "com.luzan.common.nfs"); if (args.length < 1) usage(); final String cmd = args[0]; if ("delete".equalsIgnoreCase(cmd)) { final String path = getParameter(args, 1); XFile xfile = new XFile(path); if (!xfile.exists()) { System.out.print("File doean't exist.\n"); System.exit(1); } xfile.delete(); } else if ("copy".equalsIgnoreCase(cmd)) { final String pathFrom = getParameter(args, 1); final String pathTo = getParameter(args, 2); final XFile xfileFrom = new XFile(pathFrom); final XFile xfileTo = new XFile(pathTo); if (!xfileFrom.exists()) { System.out.print("File doesn't exist.\n"); System.exit(1); } final String mime = getParameter(args, 3, null); final XFileInputStream in = new XFileInputStream(xfileFrom); final XFileOutputStream xout = new XFileOutputStream(xfileTo); if (!StringUtils.isEmpty(mime)) { final com.luzan.common.nfs.s3.XFileExtensionAccessor xfa = ((com.luzan.common.nfs.s3.XFileExtensionAccessor) xfileTo.getExtensionAccessor()); if (xfa != null) { xfa.setMimeType(mime); xfa.setContentLength(xfileFrom.length()); } } IOUtils.copy(in, xout); xout.flush(); xout.close(); in.close(); } } Code Sample 2: private Source getStylesheetSource(String stylesheetResource) throws ApplicationContextException { if (LOG.isDebugEnabled()) { LOG.debug("Loading XSLT stylesheet from " + stylesheetResource); } try { URL url = this.getClass().getClassLoader().getResource(stylesheetResource); String urlPath = url.toString(); String systemId = urlPath.substring(0, urlPath.lastIndexOf('/') + 1); return new StreamSource(url.openStream(), systemId); } catch (IOException e) { throw new RuntimeException("Can't load XSLT stylesheet from " + stylesheetResource, e); } }
11
Code Sample 1: public static void copyfile(String src, String dst) throws IOException { dst = new File(dst).getAbsolutePath(); new File(new File(dst).getParent()).mkdirs(); FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } Code Sample 2: public void write(OutputStream out, String className, InputStream classDefStream) throws IOException { ByteArrayOutputStream a = new ByteArrayOutputStream(); IOUtils.copy(classDefStream, a); a.close(); DataOutputStream da = new DataOutputStream(out); da.writeUTF(className); da.writeUTF(new String(base64.cipher(a.toByteArray()))); }
00
Code Sample 1: public static void main(String[] args) { FileInputStream fr = null; FileOutputStream fw = null; BufferedInputStream br = null; BufferedOutputStream bw = null; try { fr = new FileInputStream("D:/5.xls"); fw = new FileOutputStream("c:/Dxw.java"); br = new BufferedInputStream(fr); bw = new BufferedOutputStream(fw); int read = br.read(); while (read != -1) { bw.write(read); read = br.read(); } } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (bw != null) { try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } } } Code Sample 2: public static String ReadURLString(String str) throws IOException { try { URL url = new URL(str); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader in = new BufferedReader(isr); String inputLine; String line = ""; int i = 0; while ((inputLine = in.readLine()) != null) { line += inputLine + "\n"; } is.close(); isr.close(); in.close(); return line; } catch (Exception e) { e.printStackTrace(); } return ""; }
11
Code Sample 1: public int addCollectionInstruction() throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { String sql = "insert into Instructions (Type, Operator) " + "values (1, 0)"; conn = fido.util.FidoDataSource.getConnection(); stmt = conn.createStatement(); stmt.executeUpdate(sql); return getCurrentId(stmt); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } } Code Sample 2: public void createTableIfNotExisting(Connection conn) throws SQLException { String sql = "select * from " + tableName; PreparedStatement ps = null; try { ps = conn.prepareStatement(sql); ps.executeQuery(); } catch (SQLException sqle) { ps.close(); sql = "create table " + tableName + " ( tableName varchar(255) not null primary key, " + " lastId numeric(18) not null)"; ps = conn.prepareStatement(sql); ps.executeUpdate(); } finally { ps.close(); try { if (!conn.getAutoCommit()) conn.commit(); } catch (Exception e) { conn.rollback(); } } }
00
Code Sample 1: public static String MD5_hex(String p) { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); md.update(p.getBytes()); BigInteger hash = new BigInteger(1, md.digest()); String ret = hash.toString(16); return ret; } catch (NoSuchAlgorithmException e) { logger.error("can not create confirmation key", e); throw new TechException(e); } } Code Sample 2: public void login() { loginsuccessful = false; try { cookies = new StringBuilder(); HttpParams params = new BasicHttpParams(); params.setParameter("http.useragent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6"); DefaultHttpClient httpclient = new DefaultHttpClient(params); NULogger.getLogger().info("Trying to log in to crocko.com"); HttpPost httppost = new HttpPost("https://www.crocko.com/accounts/login"); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("login", getUsername())); formparams.add(new BasicNameValuePair("password", getPassword())); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); httppost.setEntity(entity); HttpResponse httpresponse = httpclient.execute(httppost); NULogger.getLogger().info("Getting cookies........"); NULogger.getLogger().info(EntityUtils.toString(httpresponse.getEntity())); Iterator<Cookie> it = httpclient.getCookieStore().getCookies().iterator(); Cookie escookie = null; while (it.hasNext()) { escookie = it.next(); cookies.append(escookie.getName()).append("=").append(escookie.getValue()).append(";"); if (escookie.getName().equals("PHPSESSID")) { sessionid = escookie.getValue(); NULogger.getLogger().info(sessionid); } } if (cookies.toString().contains("logacc")) { NULogger.getLogger().info(cookies.toString()); loginsuccessful = true; username = getUsername(); password = getPassword(); NULogger.getLogger().info("Crocko login successful :)"); } if (!loginsuccessful) { NULogger.getLogger().info("Crocko.com Login failed :("); loginsuccessful = false; username = ""; password = ""; JOptionPane.showMessageDialog(NeembuuUploader.getInstance(), "<html><b>" + HOSTNAME + "</b> " + TranslationProvider.get("neembuuuploader.accounts.loginerror") + "</html>", HOSTNAME, JOptionPane.WARNING_MESSAGE); AccountsManager.getInstance().setVisible(true); } httpclient.getConnectionManager().shutdown(); } catch (Exception e) { NULogger.getLogger().log(Level.SEVERE, "{0}: {1}", new Object[] { getClass().getName(), e.toString() }); System.err.println(e); } }
11
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
11
Code Sample 1: @Override public void run() { long timeout = 10 * 1000L; long start = (new Date()).getTime(); try { InputStream is = socket.getInputStream(); boolean available = false; while (!available && !socket.isClosed()) { try { if (is.available() != 0) { available = true; } else { Thread.sleep(100); } } catch (Exception e) { LOG.error("Error checking socket", e); } long curr = (new Date()).getTime(); if ((curr - start) >= timeout) { break; } } if (socket.isClosed()) { } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(is, baos); baos.flush(); baos.close(); data = baos.toByteArray(); } String msg = FtpResponse.ReadComplete.asString() + ClientCommand.SP + "Read Complete" + ClientCommand.CRLF; List<String> list = new ArrayList<String>(); list.add(msg); ClientResponse response = new ClientResponse(list); ftpClient.notifyListeners(response); } catch (Exception e) { LOG.error("Error reading server response", e); } } Code Sample 2: public void copy(File s, File t) throws IOException { FileChannel in = (new FileInputStream(s)).getChannel(); FileChannel out = (new FileOutputStream(t)).getChannel(); in.transferTo(0, s.length(), out); in.close(); out.close(); }
11
Code Sample 1: @SuppressWarnings("unchecked") protected void processTransformAction(HttpServletRequest request, HttpServletResponse response, String action) throws Exception { File transformationFile = null; String tr = request.getParameter(Definitions.REQUEST_PARAMNAME_XSLT); if (StringUtils.isNotBlank(tr)) { transformationFile = new File(xslBase, tr); if (!transformationFile.isFile()) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Parameter \"" + Definitions.REQUEST_PARAMNAME_XSLT + "\" " + "with value \"" + tr + "\" refers to non existing file"); return; } } StreamResult result; ByteArrayOutputStream baos = null; if (isDevelopmentMode) { baos = new ByteArrayOutputStream(); if (StringUtils.equals(action, "get")) { result = new StreamResult(new Base64.OutputStream(baos, Base64.DECODE)); } else { result = new StreamResult(baos); } } else { if (StringUtils.equals(action, "get")) { result = new StreamResult(new Base64.OutputStream(response.getOutputStream(), Base64.DECODE)); } else { result = new StreamResult(response.getOutputStream()); } } HashMap<String, Object> params = new HashMap<String, Object>(); params.putAll(request.getParameterMap()); params.put("{" + Definitions.CONFIGURATION_NAMESPACE + "}configuration", configuration); params.put("{" + Definitions.REQUEST_NAMESPACE + "}request", request); params.put("{" + Definitions.RESPONSE_NAMESPACE + "}response", response); params.put("{" + Definitions.SESSION_NAMESPACE + "}session", request.getSession()); params.put("{" + Definitions.INFOFUZE_NAMESPACE + "}development-mode", new Boolean(Config.getInstance().isDevelopmentMode())); Transformer transformer = new Transformer(); transformer.setTransformationFile(transformationFile); transformer.setParams(params); transformer.setTransformMode(TransformMode.NORMAL); transformer.setConfiguration(configuration); transformer.setErrorListener(new TransformationErrorListener(response)); transformer.setLogInfo(false); String method = transformer.getOutputProperties().getProperty(OutputKeys.METHOD, "xml"); String contentType; if (method.endsWith("html")) { contentType = Definitions.MIMETYPE_HTML; } else if (method.equals("xml")) { contentType = Definitions.MIMETYPE_XML; } else { contentType = Definitions.MIMETYPE_TEXTPLAIN; } String encoding = transformer.getOutputProperties().getProperty(OutputKeys.ENCODING, "UTF-8"); response.setContentType(contentType + ";charset=" + encoding); DataSourceIf dataSource = new NullSource(); transformer.transform((Source) dataSource, result); if (isDevelopmentMode) { IOUtils.copy(new ByteArrayInputStream(baos.toByteArray()), response.getOutputStream()); } } Code Sample 2: private void sendBinaryFile(File file) throws IOException, CVSException { BufferedInputStream in = null; try { in = new BufferedInputStream(new FileInputStream(file)); if (m_bCompressFiles) { GZIPOutputStream gzipOut = null; InputStream gzipIn = null; File gzipFile = null; try { gzipFile = File.createTempFile("javacvs", "tmp"); gzipOut = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(gzipFile))); int b; while ((b = in.read()) != -1) gzipOut.write((byte) b); gzipOut.close(); long gzipLength = gzipFile.length(); sendLine("z" + Long.toString(gzipLength)); gzipIn = new BufferedInputStream(new FileInputStream(gzipFile)); for (long i = 0; i < gzipLength; i++) { b = gzipIn.read(); if (b == -1) throw new EOFException(); m_Out.write((byte) b); } } finally { if (gzipOut != null) gzipOut.close(); if (gzipIn != null) gzipIn.close(); if (gzipFile != null) gzipFile.delete(); } } else { long nLength = file.length(); sendLine(Long.toString(nLength)); for (long i = 0; i < nLength; i++) { int b = in.read(); if (b == -1) throw new EOFException(); m_Out.write((byte) b); } } } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } }
11
Code Sample 1: protected static URL[] createUrls(URL jarUrls[]) { ArrayList<URL> additionalUrls = new ArrayList<URL>(Arrays.asList(jarUrls)); for (URL ju : jarUrls) { try { JarFile jar = new JarFile(ju.getFile()); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry j = entries.nextElement(); if (j.isDirectory()) continue; if (j.getName().startsWith("lib/") && j.getName().endsWith(".jar")) { URL url = new URL("jar:" + ju.getProtocol() + ":" + ju.getFile() + "!/" + j.getName()); InputStream is = url.openStream(); File tmpFile = File.createTempFile("SCDeploy", ".jar"); FileOutputStream fos = new FileOutputStream(tmpFile); IOUtils.copy(is, fos); is.close(); fos.close(); additionalUrls.add(new URL("file://" + tmpFile.getAbsolutePath())); } } } catch (IOException e) { } } return additionalUrls.toArray(new URL[] {}); } Code Sample 2: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } }
00
Code Sample 1: protected Source resolveRepositoryURI(String path) throws TransformerException { Source resolvedSource = null; try { if (path != null) { URL url = new URL(path); InputStream in = url.openStream(); if (in != null) { resolvedSource = new StreamSource(in); } } else { throw new TransformerException("Resource does not exist. \"" + path + "\" is not accessible."); } } catch (MalformedURLException mfue) { throw new TransformerException("Error accessing resource using servlet context: " + path, mfue); } catch (IOException ioe) { throw new TransformerException("Unable to access resource at: " + path, ioe); } return resolvedSource; } Code Sample 2: int responseTomcat(InetAddress dest, int port, String request, boolean methodPost, StringBuffer response, int timeout) { int methodGetMaxSize = 250; int methodPostMaxSize = 32000; if (request == null || response == null) return -1; String fullRequest; if (methodPost) { String resource; String queryStr; int qIdx = request.indexOf('?'); if (qIdx == -1) { resource = request; queryStr = ""; } else { resource = request.substring(0, qIdx); queryStr = request.substring(qIdx + 1); } fullRequest = "POST " + resource + " HTTP/1.1\nHost: " + dest.getHostName() + ":" + (new Integer(port)).toString() + "\n\n" + queryStr; } else { fullRequest = "GET " + request + " HTTP/1.1\nHost: " + dest.getHostName() + ":" + (new Integer(port)).toString() + "\n\n"; } if (methodPost && fullRequest.length() > methodPostMaxSize) { response.setLength(0); response.append("Complete POST request longer than maximum of " + methodPostMaxSize); return -5; } else if ((!methodPost) && fullRequest.length() > methodGetMaxSize) { response.setLength(0); response.append("Complete GET request longer than maximum of " + methodGetMaxSize); return -6; } String inputLine = ""; request = "http://" + dest.getHostName() + ":" + (new Integer(port).toString()) + request; try { URL urlAddress = new URL(request); URLConnection urlC = urlAddress.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(urlC.getInputStream())); while ((inputLine = in.readLine()) != null) { response = response.append(inputLine).append("\n"); } } catch (MalformedURLException e) { return -4; } catch (IOException e) { return -3; } return 200; }
00
Code Sample 1: public static String encryptePassword(String md5key, String passwordAccount, String encryptedPassword, int passwdenc) throws UnsupportedEncodingException, NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance(Constants.ALGORITHM); switch(passwdenc) { case 1: md.update((md5key + encryptedPassword).getBytes("8859_1")); break; case 2: md.update((encryptedPassword + md5key).getBytes("8859_1")); break; default: return null; } return new String(md.digest()); } Code Sample 2: private static Bitmap loadFromUrl(String url, String portId) { Bitmap bitmap = null; final HttpGet get = new HttpGet(url); HttpEntity entity = null; try { final HttpResponse response = ServiceProxy.getInstance(portId).execute(get); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { entity = response.getEntity(); try { InputStream in = entity.getContent(); bitmap = BitmapFactory.decodeStream(in); } catch (IOException e) { Log.error(e); } } } catch (IOException e) { Log.error(e); } finally { if (entity != null) { try { entity.consumeContent(); } catch (IOException e) { Log.error(e); } } } return bitmap; }
11
Code Sample 1: public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext context = getServletContext(); String forw = null; try { int maxUploadSize = 50000000; MultipartRequest multi = new MultipartRequest(request, ".", maxUploadSize); String descrizione = multi.getParameter("text"); File myFile = multi.getFile("uploadfile"); String filePath = multi.getOriginalFileName("uploadfile"); String path = "C:\\files\\"; try { FileInputStream inStream = new FileInputStream(myFile); FileOutputStream outStream = new FileOutputStream(path + myFile.getName()); while (inStream.available() > 0) { outStream.write(inStream.read()); } inStream.close(); outStream.close(); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } forw = "../sendDoc.jsp"; request.setAttribute("contentType", context.getMimeType(path + myFile.getName())); request.setAttribute("text", descrizione); request.setAttribute("path", path + myFile.getName()); request.setAttribute("size", Long.toString(myFile.length()) + " Bytes"); RequestDispatcher rd = request.getRequestDispatcher(forw); rd.forward(request, response); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: private String createCSVFile(String fileName) throws FileNotFoundException, IOException { String csvFile = fileName + ".csv"; BufferedReader buf = new BufferedReader(new FileReader(fileName)); BufferedWriter out = new BufferedWriter(new FileWriter(csvFile)); String line; while ((line = buf.readLine()) != null) out.write(line + "\n"); buf.close(); out.close(); return csvFile; } Code Sample 2: public static void copyFile(File src, File dst) throws ResourceNotFoundException, ParseErrorException, Exception { if (src.getAbsolutePath().endsWith(".vm")) { copyVMFile(src, dst.getAbsolutePath().substring(0, dst.getAbsolutePath().lastIndexOf(".vm"))); } else { FileInputStream fIn; FileOutputStream fOut; FileChannel fIChan, fOChan; long fSize; MappedByteBuffer mBuf; fIn = new FileInputStream(src); fOut = new FileOutputStream(dst); fIChan = fIn.getChannel(); fOChan = fOut.getChannel(); fSize = fIChan.size(); mBuf = fIChan.map(FileChannel.MapMode.READ_ONLY, 0, fSize); fOChan.write(mBuf); fIChan.close(); fIn.close(); fOChan.close(); fOut.close(); } }
00
Code Sample 1: public void testGet() throws Exception { HttpGet request = new HttpGet(baseUri + "/test"); HttpResponse response = client.execute(request); assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals("test", TestUtil.getResponseAsString(response)); } Code Sample 2: protected static String getInitialUUID() { if (myRand == null) { myRand = new Random(); } long rand = myRand.nextLong(); String sid; try { sid = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { sid = Thread.currentThread().getName(); } StringBuffer sb = new StringBuffer(); sb.append(sid); sb.append(":"); sb.append(Long.toString(rand)); MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new OMException(e); } md5.update(sb.toString().getBytes()); byte[] array = md5.digest(); StringBuffer sb2 = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; sb2.append(Integer.toHexString(b)); } int begin = myRand.nextInt(); if (begin < 0) begin = begin * -1; begin = begin % 8; return sb2.toString().substring(begin, begin + 18).toUpperCase(); }
11
Code Sample 1: public static void main(String[] args) throws MalformedURLException, IOException { InputStream in = null; try { in = new URL("hdfs://localhost:8020/user/leeing/maxtemp/sample.txt").openStream(); IOUtils.copyBytes(in, System.out, 8192, false); } finally { IOUtils.closeStream(in); System.out.println("\nend."); } } Code Sample 2: public static void copyFile(final File fromFile, File toFile) throws IOException { try { if (!fromFile.exists()) { throw new IOException("FileCopy: " + "no such source file: " + fromFile.getAbsoluteFile()); } if (!fromFile.isFile()) { throw new IOException("FileCopy: " + "can't copy directory: " + fromFile.getAbsoluteFile()); } if (!fromFile.canRead()) { throw new IOException("FileCopy: " + "source file is unreadable: " + fromFile.getAbsoluteFile()); } if (toFile.isDirectory()) { toFile = new File(toFile, fromFile.getName()); } if (toFile.exists() && !toFile.canWrite()) { throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFile.getAbsoluteFile()); } final FileChannel inChannel = new FileInputStream(fromFile).getChannel(); final FileChannel outChannel = new FileOutputStream(toFile).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (final IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } catch (final IOException e) { if (LOGGER.isErrorEnabled()) { LOGGER.error("CopyFile went wrong!", e); } } }
11
Code Sample 1: private final void copyTargetFileToSourceFile(File sourceFile, File targetFile) throws MJProcessorException { if (!targetFile.exists()) { targetFile.getParentFile().mkdirs(); try { if (!targetFile.exists()) { targetFile.createNewFile(); } } catch (IOException e) { throw new MJProcessorException(e.getMessage(), e); } } FileChannel in = null, out = null; try { in = new FileInputStream(sourceFile).getChannel(); out = new FileOutputStream(targetFile).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } catch (IOException e) { log.error(e); } finally { if (in != null) try { in.close(); } catch (IOException e) { log.error(e); } if (out != null) try { out.close(); } catch (IOException e) { log.error(e); } } } Code Sample 2: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: public final void provisionGSLAM() { try { UUID[] slaUUID = new UUID[] { new UUID("AG-1") }; SLA[] slas = sslamContext.getSLARegistry().getIQuery().getSLA(slaUUID); for (SLA s : slas) { Party[] parties = s.getParties(); System.out.println("SLA Info :::" + s.getUuid().toString()); for (Party p : parties) { System.out.println("Printing gslam_epr value for Party" + p.getId() + "--" + p.getAgreementRole()); System.out.println(parties[0].getPropertyValue(new STND("gslam_epr"))); } } sslamContext.getSLARegistry().getIRegister().register(slas[0], slaUUID, SLAState.OBSERVED); String xmlFile2Send = System.getenv("SLASOI_HOME") + System.getProperty("file.separator") + "Integration" + System.getProperty("file.separator") + "soap" + System.getProperty("file.separator") + "provision.xml"; String soapAction = ""; URL url; url = new URL(syntaxConverterNegotiationWSURL); URLConnection connection = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) connection; FileInputStream fin = new FileInputStream(xmlFile2Send); ByteArrayOutputStream bout = new ByteArrayOutputStream(); SOAPClient4XG.copy(fin, bout); fin.close(); byte[] b = bout.toByteArray(); httpConn.setRequestProperty("Content-Length", String.valueOf(b.length)); httpConn.setRequestProperty("Content-Type", "application/soap+xml; charset=UTF-8"); httpConn.setRequestProperty("SOAPAction", soapAction); httpConn.setRequestMethod("POST"); httpConn.setDoOutput(true); httpConn.setDoInput(true); OutputStream out = httpConn.getOutputStream(); out.write(b); out.close(); InputStreamReader isr = new InputStreamReader(httpConn.getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance(); javax.xml.parsers.DocumentBuilder db; db = factory.newDocumentBuilder(); org.xml.sax.InputSource inStream = new org.xml.sax.InputSource(); inStream.setCharacterStream(new java.io.StringReader(response.toString())); System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" + "####################################################" + "#################################################\n" + "####################################################" + "#################################################\n" + "Component Name: GSLAM\n" + "Interface Name: negotiate/coordinage\n" + "Operation Name: Provision\n" + "Input:Type " + "void" + "\n" + "####################################################" + "#################################################\n" + "####################################################" + "#################################################\n" + "######################################## RESPONSE" + "############################################\n\n"); System.out.println(response.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (RegistrationFailureException e) { e.printStackTrace(); } catch (SLAManagerContextException e) { e.printStackTrace(); } catch (InvalidUUIDException e) { e.printStackTrace(); } } Code Sample 2: public void setTypeRefs(Connection conn) { log.traceln("\tProcessing " + table + " references.."); try { String query = " select distinct c.id, c.qualifiedname from " + table + ", CLASSTYPE c " + " where " + table + "." + reffield + " is null and " + table + "." + classnamefield + " = c.qualifiedname"; PreparedStatement pstmt = conn.prepareStatement(query); long start = new Date().getTime(); ResultSet rset = pstmt.executeQuery(); long queryTime = new Date().getTime() - start; log.debug("query time: " + queryTime + " ms"); String update = "update " + table + " set " + reffield + "=? where " + classnamefield + "=? and " + reffield + " is null"; PreparedStatement pstmt2 = conn.prepareStatement(update); int n = 0; start = new Date().getTime(); while (rset.next()) { n++; pstmt2.setInt(1, rset.getInt(1)); pstmt2.setString(2, rset.getString(2)); pstmt2.executeUpdate(); } queryTime = new Date().getTime() - start; log.debug("total update time: " + queryTime + " ms"); log.debug("number of times through loop: " + n); if (n > 0) log.debug("avg update time: " + (queryTime / n) + " ms"); pstmt2.close(); rset.close(); pstmt.close(); conn.commit(); log.verbose("Updated (committed) " + table + " references"); } catch (SQLException ex) { log.error("Internal Reference Update Failed!"); DBUtils.logSQLException(ex); log.error("Rolling back.."); try { conn.rollback(); } catch (SQLException inner_ex) { log.error("rollback failed!"); } } }
00
Code Sample 1: public static boolean delete(String url, int ip, int port) { try { HttpURLConnection request = (HttpURLConnection) new URL(url).openConnection(); request.setRequestMethod("DELETE"); request.setRequestProperty(GameRecord.GAME_IP_HEADER, String.valueOf(ip)); request.setRequestProperty(GameRecord.GAME_PORT_HEADER, String.valueOf(port)); request.connect(); return request.getResponseCode() == HttpURLConnection.HTTP_OK; } catch (IOException e) { e.printStackTrace(); } return false; } Code Sample 2: 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) { } } } }
11
Code Sample 1: public static void main(String[] args) throws IOException { FileChannel fc = new FileOutputStream("src/com/aaron/nio/data.txt").getChannel(); fc.write(ByteBuffer.wrap("dfsdf ".getBytes())); fc.close(); fc = new RandomAccessFile("src/com/aaron/nio/data.txt", "rw").getChannel(); fc.position(fc.size()); fc.write(ByteBuffer.wrap("中文的 ".getBytes())); fc.close(); fc = new FileInputStream("src/com/aaron/nio/data.txt").getChannel(); ByteBuffer buff = ByteBuffer.allocate(1024); fc.read(buff); buff.flip(); while (buff.hasRemaining()) { System.out.print(buff.getChar()); } fc.close(); } Code Sample 2: public void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; Closer c = new Closer(); try { source = c.register(new FileInputStream(sourceFile).getChannel()); destination = c.register(new FileOutputStream(destFile).getChannel()); destination.transferFrom(source, 0, source.size()); } catch (IOException e) { c.doNotThrow(); throw e; } finally { c.closeAll(); } }
11
Code Sample 1: private void sendBinaryFile(File file) throws IOException, CVSException { BufferedInputStream in = null; try { in = new BufferedInputStream(new FileInputStream(file)); if (m_bCompressFiles) { GZIPOutputStream gzipOut = null; InputStream gzipIn = null; File gzipFile = null; try { gzipFile = File.createTempFile("javacvs", "tmp"); gzipOut = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(gzipFile))); int b; while ((b = in.read()) != -1) gzipOut.write((byte) b); gzipOut.close(); long gzipLength = gzipFile.length(); sendLine("z" + Long.toString(gzipLength)); gzipIn = new BufferedInputStream(new FileInputStream(gzipFile)); for (long i = 0; i < gzipLength; i++) { b = gzipIn.read(); if (b == -1) throw new EOFException(); m_Out.write((byte) b); } } finally { if (gzipOut != null) gzipOut.close(); if (gzipIn != null) gzipIn.close(); if (gzipFile != null) gzipFile.delete(); } } else { long nLength = file.length(); sendLine(Long.toString(nLength)); for (long i = 0; i < nLength; i++) { int b = in.read(); if (b == -1) throw new EOFException(); m_Out.write((byte) b); } } } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } } Code Sample 2: private String copyAndHash(InputStream input, File into) throws IOException { MessageDigest digest = createMessageDigest(); DigestInputStream dis = new DigestInputStream(input, digest); IOException ex; FileOutputStream fos = null; try { fos = new FileOutputStream(into); IOUtils.copyLarge(dis, fos); byte[] hash = digest.digest(); Formatter formatter = new Formatter(); for (byte b : hash) { formatter.format("%02x", b); } return formatter.toString(); } catch (IOException e) { ex = e; } finally { IOUtils.closeQuietly(dis); IOUtils.closeQuietly(fos); } if (logger.isWarnEnabled()) logger.warn("Couldn't retrieve data from input!", ex); deleteTempFile(into); throw ex; }
11
Code Sample 1: public static String getMd5Password(final String password) { String response = null; try { final MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(password.getBytes()); final byte[] md5Byte = algorithm.digest(); final StringBuffer buffer = new StringBuffer(); for (final byte b : md5Byte) { if ((b <= 15) && (b >= 0)) { buffer.append("0"); } buffer.append(Integer.toHexString(0xFF & b)); } response = buffer.toString(); } catch (final NoSuchAlgorithmException e) { ProjektUtil.LOG.error("No digester MD5 found in classpath!", e); } return response; } Code Sample 2: public String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance(SHA1); md.update(text.getBytes(CHAR_SET), 0, text.length()); byte[] mdbytes = md.digest(); return byteToHex(mdbytes); }
00
Code Sample 1: protected static final void copyFile(String from, String to) throws SeleniumException { try { java.io.File fileFrom = new File(from); java.io.File fileTo = new File(to); FileReader in = new FileReader(fileFrom); FileWriter out = new FileWriter(fileTo); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception e) { throw new SeleniumException("Failed to copy new file : " + from + " to : " + to, e); } } Code Sample 2: public void submitReport() { String subject = m_Subject.getText(); String description = m_Description.getText(); String email = m_Email.getText(); if (subject.length() == 0) { Util.flashComponent(m_Subject, Color.RED); return; } if (description.length() == 0) { Util.flashComponent(m_Description, Color.RED); return; } DynamicLocalisation loc = m_MainFrame.getLocalisation(); if (email.length() == 0 || email.indexOf("@") == -1 || email.indexOf(".") == -1 || email.startsWith("@")) { email = "[email protected]"; } try { String data = URLEncoder.encode("mode", "UTF-8") + "=" + URLEncoder.encode("manual", "UTF-8"); data += "&" + URLEncoder.encode("from", "UTF-8") + "=" + URLEncoder.encode(email, "UTF-8"); data += "&" + URLEncoder.encode("subject", "UTF-8") + "=" + URLEncoder.encode(subject, "UTF-8"); data += "&" + URLEncoder.encode("body", "UTF-8") + "=" + URLEncoder.encode(description, "UTF-8"); data += "&" + URLEncoder.encode("jvm", "UTF-8") + "=" + URLEncoder.encode(System.getProperty("java.version"), "UTF-8"); data += "&" + URLEncoder.encode("ocdsver", "UTF-8") + "=" + URLEncoder.encode(Constants.OPENCDS_VERSION, "UTF-8"); data += "&" + URLEncoder.encode("os", "UTF-8") + "=" + URLEncoder.encode(Constants.OS_NAME + " " + System.getProperty("os.version") + " " + System.getProperty("os.arch"), "UTF-8"); URL url = new URL(Constants.BUGREPORT_SCRIPT); 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) { System.out.println(line); } wr.close(); rd.close(); JOptionPane.showMessageDialog(this, loc.getMessage("ReportBug.SentMessage")); } catch (Exception e) { Logger.getInstance().logException(e); } dispose(); }
11
Code Sample 1: public synchronized String encrypt(final String pPassword) throws NoSuchAlgorithmException, UnsupportedEncodingException { final MessageDigest md = MessageDigest.getInstance("SHA"); md.update(pPassword.getBytes("UTF-8")); final byte raw[] = md.digest(); return BASE64Encoder.encodeBuffer(raw); } Code Sample 2: private String getRandomGUID(final boolean secure) { MessageDigest md5 = null; final StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } try { final long time = System.currentTimeMillis(); final long rand; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(id); sbValueBeforeMD5.append(SEMI_COLON); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(SEMI_COLON); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); final byte[] array = md5.digest(); final StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { final int bufferIndex = array[j] & SHIFT_SPACE; if (ZERO_TEST > bufferIndex) sb.append(CHAR_ZERO); sb.append(Integer.toHexString(bufferIndex)); } return sb.toString(); } catch (Exception e) { throw new RuntimeException(e); } }
00
Code Sample 1: public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { URL url = new URL("http://pubsubhubbub.appspot.com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream()); out.write("hub.mode=publish&hub.url=" + req.getParameter("url")); out.flush(); out.close(); conn.getResponseCode(); try { resp.sendRedirect(req.getParameter("from")); } catch (Exception e) { } } Code Sample 2: public static void copieFichier(File fichier1, File fichier2) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(fichier1).getChannel(); out = new FileOutputStream(fichier2).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } }
00
Code Sample 1: @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(); } } Code Sample 2: protected void setRankOrder() { this.rankOrder = new int[values.length]; for (int i = 0; i < rankOrder.length; i++) { rankOrder[i] = i; assert (!Double.isNaN(values[i])); } for (int i = rankOrder.length - 1; i >= 0; i--) { boolean swapped = false; for (int j = 0; j < i; j++) if (values[rankOrder[j]] < values[rankOrder[j + 1]]) { int r = rankOrder[j]; rankOrder[j] = rankOrder[j + 1]; rankOrder[j + 1] = r; } } }
00
Code Sample 1: public boolean login(String strUrl, String loginName, String loginPwd) throws ApplicationException { String starter = "-----------------------------"; String returnChar = "\r\n"; String lineEnd = "--"; String urlString = strUrl; String input = null; List txtList = new ArrayList(); List fileList = new ArrayList(); String targetFile = null; String actionStatus = null; StringBuffer returnMessage = new StringBuffer(); List head = new ArrayList(); final String boundary = String.valueOf(System.currentTimeMillis()); URL url = null; URLConnection conn = null; BufferedReader br = null; DataOutputStream dos = null; boolean isLogin = false; txtList.add(new HtmlFormText("loginName", loginName)); txtList.add(new HtmlFormText("loginPwd", loginPwd)); txtList.add(new HtmlFormText("navMode", "I")); txtList.add(new HtmlFormText("action", "login")); try { url = new URL(urlString); conn = url.openConnection(); ((HttpURLConnection) conn).setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestProperty("Content-Type", "multipart/form-data, boundary=" + "---------------------------" + boundary); if (input != null) { String auth = "Basic " + new sun.misc.BASE64Encoder().encode(input.getBytes()); conn.setRequestProperty("Authorization", auth); } dos = new DataOutputStream(conn.getOutputStream()); dos.write((starter + boundary + returnChar).getBytes()); for (int i = 0; i < txtList.size(); i++) { HtmlFormText htmltext = (HtmlFormText) txtList.get(i); dos.write(htmltext.getTranslated()); if (i + 1 < txtList.size()) { dos.write((starter + boundary + returnChar).getBytes()); } else if (fileList.size() > 0) { dos.write((starter + boundary + returnChar).getBytes()); } } dos.write((starter + boundary + "--" + returnChar).getBytes()); dos.flush(); br = new BufferedReader(new InputStreamReader(conn.getInputStream())); String cookieVal = conn.getHeaderField(HEADER_SETCOOKIE); if (cookieVal != null) { cookie = cookieVal.substring(0, cookieVal.indexOf(";")); } String tempstr; int line = 0; while (null != ((tempstr = br.readLine()))) { if (!tempstr.equals("")) { if ("window.location.replace(\"/Home.do\");".indexOf(returnMessage.append(formatLine(tempstr)).toString()) != -1) { isLogin = true; break; } line++; } } txtList.clear(); fileList.clear(); } catch (Exception e) { log.error(e, e); throw new ApplicationException(FormErrorConstant.DB_APP_BASE_URL_ERROR); } finally { try { dos.close(); } catch (Exception e) { } try { br.close(); } catch (Exception e) { } } return isLogin; } Code Sample 2: public static URL getIconURLForUser(String id) { try { URL url = new URL("http://profiles.yahoo.com/" + id); BufferedReader r = new BufferedReader(new InputStreamReader(url.openStream())); String input = null; while ((input = r.readLine()) != null) { if (input.indexOf("<a href=\"") < 0) continue; if (input.indexOf("<img src=\"") < 0) continue; if (input.indexOf("<a href=\"") > input.indexOf("<img src=\"")) continue; String href = input.substring(input.indexOf("<a href=\"") + 9); String src = input.substring(input.indexOf("<img src=\"") + 10); if (href.indexOf("\"") < 0) continue; if (src.indexOf("\"") < 0) continue; href = href.substring(0, href.indexOf("\"")); src = src.substring(0, src.indexOf("\"")); if (href.equals(src)) { return new URL(href); } } } catch (IOException e) { } URL toReturn = null; try { toReturn = new URL("http://us.i1.yimg.com/us.yimg.com/i/ppl/no_photo.gif"); } catch (MalformedURLException e) { Debug.assrt(false); } return toReturn; }
11
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: private InputStream getManifestAsResource() { ClassLoader cl = getClass().getClassLoader(); try { Enumeration manifests = cl != null ? cl.getResources(Constants.OSGI_BUNDLE_MANIFEST) : ClassLoader.getSystemResources(Constants.OSGI_BUNDLE_MANIFEST); while (manifests.hasMoreElements()) { URL url = (URL) manifests.nextElement(); try { Headers headers = Headers.parseManifest(url.openStream()); if ("true".equals(headers.get(Constants.ECLIPSE_SYSTEMBUNDLE))) return url.openStream(); } catch (BundleException e) { } } } catch (IOException e) { } return null; } Code Sample 2: private static URL handleRedirectUrl(URL url) { try { URLConnection cn = url.openConnection(); Utils.setHeader(cn); if (!(cn instanceof HttpURLConnection)) { return url; } HttpURLConnection hcn = (HttpURLConnection) cn; hcn.setInstanceFollowRedirects(false); int resCode = hcn.getResponseCode(); if (resCode == 200) { System.out.println("URL: " + url); return url; } String location = hcn.getHeaderField("Location"); hcn.disconnect(); return handleRedirectUrl(new URL(location.replace(" ", "%20"))); } catch (IOException e) { e.printStackTrace(); } return url; }
11
Code Sample 1: public File addFile(File file, String suffix) throws IOException { if (file.exists() && file.isFile()) { File nf = File.createTempFile(prefix, "." + suffix, workdir); nf.delete(); if (!file.renameTo(nf)) { IOUtils.copy(file, nf); } synchronized (fileList) { fileList.add(nf); } if (log.isDebugEnabled()) { log.debug("Add file [" + file.getPath() + "] -> [" + nf.getPath() + "]"); } return nf; } return file; } Code Sample 2: public void updateDb(int scriptNumber) throws SQLException, IOException { String pathName = updatesPackage.replace(".", "/"); InputStream in = getClass().getClassLoader().getResourceAsStream(pathName + "/" + scriptNumber + ".sql"); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); String script = out.toString("UTF-8"); String[] statements = script.split(";"); for (String statement : statements) { getJdbcTemplate().execute(statement); } }
00
Code Sample 1: private static void loadCommandList() { final URL url; try { url = IOUtils.getResource(null, PYTHON_MENU_FILE); } catch (final FileNotFoundException ex) { log.error("File '" + PYTHON_MENU_FILE + "': " + ex.getMessage()); return; } final List<String> cmdList = new ArrayList<String>(); try { final InputStream inputStream = url.openStream(); try { final Reader reader = new InputStreamReader(inputStream, IOUtils.MAP_ENCODING); try { final BufferedReader bufferedReader = new BufferedReader(reader); try { while (true) { final String inputLine = bufferedReader.readLine(); if (inputLine == null) { break; } final String line = inputLine.trim(); if (line.length() > 0 && !line.startsWith("#")) { final int k = line.indexOf('('); if (k > 0) { cmdList.add(line.substring(0, k) + "()"); } else { log.error("Parse error in " + url + ":"); log.error(" \"" + line + "\" missing '()'"); cmdList.add(line + "()"); } } } Collections.sort(cmdList, String.CASE_INSENSITIVE_ORDER); if (!cmdList.isEmpty()) { menuEntries = cmdList.toArray(new String[cmdList.size()]); } } finally { bufferedReader.close(); } } finally { reader.close(); } } finally { inputStream.close(); } } catch (final FileNotFoundException ex) { log.error("File '" + url + "' not found: " + ex.getMessage()); } catch (final EOFException ignored) { } catch (final UnsupportedEncodingException ex) { log.error("Cannot decode file '" + url + "': " + ex.getMessage()); } catch (final IOException ex) { log.error("Cannot read file '" + url + "': " + ex.getMessage()); } } Code Sample 2: public void copyTo(String newname) throws IOException { FileChannel srcChannel = new FileInputStream(dosname).getChannel(); FileChannel dstChannel = new FileOutputStream(newname).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
00
Code Sample 1: public ByteArrayOutputStream download(final String contentUuid) throws WebServiceClientException { try { URL url = new URL(getPath("/download/" + contentUuid)); URLConnection connection = url.openConnection(); InputStream inputStream = connection.getInputStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); int c; while ((c = inputStream.read()) != -1) { outputStream.write(c); } inputStream.close(); return outputStream; } catch (Exception ex) { throw new WebServiceClientException("Could not download content from web service.", ex); } } Code Sample 2: private void generateDocFile(String srcFileName, String s, String destFileName) { try { ZipFile docxFile = new ZipFile(new File(srcFileName)); ZipEntry documentXML = docxFile.getEntry("word/document.xml"); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); InputStream documentXMLIS1 = docxFile.getInputStream(documentXML); Document doc = dbf.newDocumentBuilder().parse(documentXMLIS1); Transformer t = TransformerFactory.newInstance().newTransformer(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); t.transform(new DOMSource(doc), new StreamResult(baos)); ZipOutputStream docxOutFile = new ZipOutputStream(new FileOutputStream(destFileName)); Enumeration<ZipEntry> entriesIter = (Enumeration<ZipEntry>) docxFile.entries(); while (entriesIter.hasMoreElements()) { ZipEntry entry = entriesIter.nextElement(); if (entry.getName().equals("word/document.xml")) { docxOutFile.putNextEntry(new ZipEntry(entry.getName())); byte[] datas = s.getBytes("UTF-8"); docxOutFile.write(datas, 0, datas.length); docxOutFile.closeEntry(); } else if (entry.getName().equals("word/media/image1.png")) { InputStream incoming = new FileInputStream("c:/aaa.jpg"); byte[] data = new byte[incoming.available()]; int readCount = incoming.read(data, 0, data.length); docxOutFile.putNextEntry(new ZipEntry(entry.getName())); docxOutFile.write(data, 0, readCount); docxOutFile.closeEntry(); } else { InputStream incoming = docxFile.getInputStream(entry); byte[] data = new byte[incoming.available()]; int readCount = incoming.read(data, 0, data.length); docxOutFile.putNextEntry(new ZipEntry(entry.getName())); docxOutFile.write(data, 0, readCount); docxOutFile.closeEntry(); } } docxOutFile.close(); } catch (Exception e) { } }
11
Code Sample 1: private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } } Code Sample 2: public void write(File file) throws Exception { if (isInMemory()) { FileOutputStream fout = null; try { fout = new FileOutputStream(file); fout.write(get()); } finally { if (fout != null) { fout.close(); } } } else { File outputFile = getStoreLocation(); if (outputFile != null) { size = outputFile.length(); if (!outputFile.renameTo(file)) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(outputFile)); out = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(in, out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } } } else { throw new FileUploadException("Cannot write uploaded file to disk!"); } } }
11
Code Sample 1: public static String md5(String word) { MessageDigest alg = null; try { alg = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(ServletUtils.class.getName()).log(Level.SEVERE, null, ex); } alg.reset(); alg.update(word.getBytes()); byte[] digest = alg.digest(); StringBuilder hashedWord = new StringBuilder(); String hx; for (int i = 0; i < digest.length; i++) { hx = Integer.toHexString(0xFF & digest[i]); if (hx.length() == 1) { hx = "0" + hx; } hashedWord.append(hx); } return hashedWord.toString(); } Code Sample 2: public boolean WriteFile(java.io.Serializable inObj, String fileName) throws Exception { FileOutputStream out; try { SecretKey skey = null; AlgorithmParameterSpec aps; out = new FileOutputStream(fileName); cipher = Cipher.getInstance(algorithm); KeySpec kspec = new PBEKeySpec(filePasswd.toCharArray()); SecretKeyFactory skf = SecretKeyFactory.getInstance(algorithm); skey = skf.generateSecret(kspec); MessageDigest md = MessageDigest.getInstance(res.getString("MD5")); md.update(filePasswd.getBytes()); byte[] digest = md.digest(); System.arraycopy(digest, 0, salt, 0, 8); aps = new PBEParameterSpec(salt, iterations); out.write(salt); ObjectOutputStream s = new ObjectOutputStream(out); cipher.init(Cipher.ENCRYPT_MODE, skey, aps); SealedObject so = new SealedObject(inObj, cipher); s.writeObject(so); s.flush(); out.close(); } catch (Exception e) { Log.out("fileName=" + fileName); Log.out("algorithm=" + algorithm); Log.out(e); throw e; } return true; }
11
Code Sample 1: public static void generateCode(File flowFile, String packagePath, File destDir, File scriptRootFolder) throws IOException { InputStream javaSrcIn = generateCode(flowFile, packagePath, scriptRootFolder); File outputFolder = new File(destDir, packagePath.replace('.', File.separatorChar)); String fileName = flowFile.getName(); fileName = fileName.substring(0, fileName.lastIndexOf(".") + 1) + Consts.FILE_EXTENSION_GROOVY; File outputFile = new File(outputFolder, fileName); OutputStream javaSrcOut = new FileOutputStream(outputFile); IOUtils.copyBufferedStream(javaSrcIn, javaSrcOut); javaSrcIn.close(); javaSrcOut.close(); } Code Sample 2: private void copyfile(File srcFile, File dstDir) throws FileNotFoundException, IOException { if (srcFile.isDirectory()) { File newDestDir = new File(dstDir, srcFile.getName()); newDestDir.mkdir(); String fileNameList[] = srcFile.list(); for (int i = 0; i < fileNameList.length; i++) { File newSouceFile = new File(srcFile, fileNameList[i]); copyfile(newSouceFile, newDestDir); } } else { File newDestFile = new File(dstDir, srcFile.getName()); FileInputStream in = new FileInputStream(srcFile); FileOutputStream out = new FileOutputStream(newDestFile); FileChannel inChannel = in.getChannel(); FileChannel outChannel = out.getChannel(); long i; Logger.log("copyFile before- copiedSize = " + copiedSize); for (i = 0; i < srcFile.length() - BLOCK_LENGTH; i += BLOCK_LENGTH) { synchronized (this) { inChannel.transferTo(i, BLOCK_LENGTH, outChannel); copiedSize += BLOCK_LENGTH; } } synchronized (this) { inChannel.transferTo(i, srcFile.length() - i, outChannel); copiedSize += srcFile.length() - i; } Logger.log("copyFile after copy- copiedSize = " + copiedSize + "srcFile.length = " + srcFile.length() + "diff = " + (copiedSize - srcFile.length())); in.close(); out.close(); outChannel = null; Logger.log("File copied."); } }
00
Code Sample 1: public static void copyURLToFile(URL source, File destination) throws IOException { InputStream input = source.openStream(); try { FileOutputStream output = openOutputStream(destination); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } } Code Sample 2: public boolean downloadNextTLE() { boolean success = true; if (!downloadINI) { errorText = "startTLEDownload() must be ran before downloadNextTLE() can begin"; return false; } if (!this.hasMoreToDownload()) { errorText = "There are no more TLEs to download"; return false; } int i = currentTLEindex; try { URL url = new URL(rootWeb + fileNames[i]); URLConnection c = url.openConnection(); InputStreamReader isr = new InputStreamReader(c.getInputStream()); BufferedReader br = new BufferedReader(isr); File outFile = new File(localPath + fileNames[i]); BufferedWriter writer = new BufferedWriter(new FileWriter(outFile)); String currentLine = ""; while ((currentLine = br.readLine()) != null) { writer.write(currentLine); writer.newLine(); } br.close(); writer.close(); } catch (Exception e) { System.out.println("Error Reading/Writing TLE - " + fileNames[i] + "\n" + e.toString()); success = false; errorText = e.toString(); return false; } currentTLEindex++; return success; }
00
Code Sample 1: @Test public void test_baseMaterialsForTypeID_NonExistingID() throws Exception { URL url = new URL(baseUrl + "/baseMaterialsForTypeID/1234567890"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); assertThat(connection.getResponseCode(), equalTo(400)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/xml"); assertThat(connection.getResponseCode(), equalTo(400)); } Code Sample 2: public RecordIterator(URL fileUrl, ModelDataFile modelDataFile) throws DataFileException { this.modelDataFile = modelDataFile; InputStream urlStream = null; try { urlStream = fileUrl.openStream(); } catch (IOException e) { throw new DataFileException("Error open URL: " + fileUrl.toString(), e); } this.setupStream(urlStream, fileUrl.toString()); }
00
Code Sample 1: private String calculateHash(String s) { if (s == null) { return null; } MessageDigest messageDigest; try { messageDigest = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { logger.error("Could not find a message digest algorithm."); return null; } messageDigest.update(s.getBytes()); byte[] hash = messageDigest.digest(); StringBuilder sb = new StringBuilder(); for (byte b : hash) { sb.append(String.format("%02x", b)); } return sb.toString(); } Code Sample 2: private boolean performModuleInstallation(Model m) { String seldir = directoryHandler.getSelectedDirectory(); if (seldir == null) { MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK); box.setText("Cannot install"); box.setMessage("A target directory must be selected."); box.open(); return false; } String sjar = pathText.getText(); File fjar = new File(sjar); if (!fjar.exists()) { MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK); box.setText("Cannot install"); box.setMessage("A non-existing jar file has been selected."); box.open(); return false; } int count = 0; try { URLClassLoader loader = new URLClassLoader(new URL[] { fjar.toURI().toURL() }); JarInputStream jis = new JarInputStream(new FileInputStream(fjar)); JarEntry entry = jis.getNextJarEntry(); while (entry != null) { String name = entry.getName(); if (name.endsWith(".class")) { name = name.substring(0, name.length() - 6); name = name.replace('/', '.'); Class<?> cls = loader.loadClass(name); if (IAlgorithm.class.isAssignableFrom(cls) && !cls.isInterface() && (cls.getModifiers() & Modifier.ABSTRACT) == 0) { if (!testAlgorithm(cls, m)) return false; count++; } } entry = jis.getNextJarEntry(); } } catch (Exception e1) { Application.logexcept("Could not load classes from jar file.", e1); return false; } if (count == 0) { MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK); box.setText("Cannot install"); box.setMessage("There don't seem to be any algorithms in the specified module."); box.open(); return false; } try { FileChannel ic = new FileInputStream(sjar).getChannel(); FileChannel oc = new FileOutputStream(seldir + File.separator + fjar.getName()).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); } catch (Exception e) { Application.logexcept("Could not install module", e); return false; } result = new Object(); return true; }
00
Code Sample 1: protected static Certificate[] getCurrentCertificates() throws Exception { Certificate[] certificate = AppletLoader.class.getProtectionDomain().getCodeSource().getCertificates(); if (certificate == null) { URL location = AppletLoader.class.getProtectionDomain().getCodeSource().getLocation(); JarURLConnection jurl = (JarURLConnection) (new URL("jar:" + location.toString() + "!/org/lwjgl/util/applet/AppletLoader.class").openConnection()); jurl.setDefaultUseCaches(true); certificate = jurl.getCertificates(); } return certificate; } Code Sample 2: private static void fileUpload() throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(postURL); file = new File("h:\\Rock Lee.jpg"); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); ContentBody cbFile = new FileBody(file); mpEntity.addPart("file", cbFile); httppost.setEntity(mpEntity); System.out.println("executing request " + httppost.getRequestLine()); System.out.println("Now uploading your file into bayfiles.com"); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println(response.getStatusLine()); if (resEntity != null) { uploadresponse = EntityUtils.toString(resEntity); } System.out.println("Upload response : " + uploadresponse); downloadlink = parseResponse(uploadresponse, "\"downloadUrl\":\"", "\""); downloadlink = downloadlink.replaceAll("\\\\", ""); deletelink = parseResponse(uploadresponse, "\"deleteUrl\":\"", "\""); deletelink = deletelink.replaceAll("\\\\", ""); System.out.println("Download link : " + downloadlink); System.out.println("Delete link : " + deletelink); }
11
Code Sample 1: protected void copyFile(File from, File to) throws IOException { to.getParentFile().mkdirs(); InputStream in = new FileInputStream(from); try { OutputStream out = new FileOutputStream(to); try { byte[] buf = new byte[1024]; int readLength; while ((readLength = in.read(buf)) > 0) { out.write(buf, 0, readLength); } } finally { out.close(); } } finally { in.close(); } } Code Sample 2: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: public static void fileCopy(File src, File dest) throws IOException { IOException xforward = null; 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(); final int MB32 = 32 * 1024 * 1024; long size = fcin.size(); long position = 0; while (position < size) { position += fcin.transferTo(position, MB32, fcout); } } catch (IOException xio) { xforward = xio; } finally { if (fis != null) try { fis.close(); fis = null; } catch (IOException xio) { } if (fos != null) try { fos.close(); fos = null; } catch (IOException xio) { } if (fcin != null && fcin.isOpen()) try { fcin.close(); fcin = null; } catch (IOException xio) { } if (fcout != null && fcout.isOpen()) try { fcout.close(); fcout = null; } catch (IOException xio) { } } if (xforward != null) { throw xforward; } } Code Sample 2: public void copyFile(File in, File out) throws Exception { FileChannel ic = new FileInputStream(in).getChannel(); FileChannel oc = new FileOutputStream(out).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); }
11
Code Sample 1: public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new SoundFilter()); int returnVal = fc.showDialog(AdministracionResorces.this, Messages.getString("gui.AdministracionResorces.17")); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + "/" + rutaDatos + "sonidos/" + file.getName(); String rutaRelativa = rutaDatos + "sonidos/" + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); imagen.setSonidoURL(rutaRelativa); System.out.println(rutaGlobal + " " + rutaRelativa); buttonSonido.setIcon(new ImageIcon(getClass().getResource("/es/unizar/cps/tecnoDiscap/data/icons/view_sidetreeOK.png"))); gui.getAudio().reproduceAudio(imagen); } catch (IOException ex) { ex.printStackTrace(); } } else { } } Code Sample 2: protected void copyFile(File sourceFile, File destFile) { FileChannel in = null; FileChannel out = null; try { if (!verifyOrCreateParentPath(destFile.getParentFile())) { throw new IOException("Parent directory path " + destFile.getAbsolutePath() + " did not exist and could not be created"); } if (destFile.exists() || destFile.createNewFile()) { in = new FileInputStream(sourceFile).getChannel(); out = new FileOutputStream(destFile).getChannel(); in.transferTo(0, in.size(), out); } else { throw new IOException("Couldn't create file for " + destFile.getAbsolutePath()); } } catch (IOException ioe) { if (destFile.exists() && destFile.length() < sourceFile.length()) { destFile.delete(); } ioe.printStackTrace(); } finally { try { in.close(); } catch (Throwable t) { } try { out.close(); } catch (Throwable t) { } destFile.setLastModified(sourceFile.lastModified()); } }
11
Code Sample 1: private static List retrieveQuotes(Report report, Symbol symbol, String suffix, TradingDate startDate, TradingDate endDate) throws ImportExportException { List quotes = new ArrayList(); String URLString = constructURL(symbol, suffix, startDate, endDate); EODQuoteFilter filter = new YahooEODQuoteFilter(symbol); PreferencesManager.ProxyPreferences proxyPreferences = PreferencesManager.getProxySettings(); try { URL url = new URL(URLString); InputStreamReader input = new InputStreamReader(url.openStream()); BufferedReader bufferedInput = new BufferedReader(input); String line = bufferedInput.readLine(); while (line != null) { line = bufferedInput.readLine(); if (line != null) { try { EODQuote quote = filter.toEODQuote(line); quotes.add(quote); verify(report, quote); } catch (QuoteFormatException e) { report.addError(Locale.getString("YAHOO_DISPLAY_URL") + ":" + symbol + ":" + Locale.getString("ERROR") + ": " + e.getMessage()); } } } bufferedInput.close(); } catch (BindException e) { throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); } catch (ConnectException e) { throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); } catch (UnknownHostException e) { throw new ImportExportException(Locale.getString("UNKNOWN_HOST_ERROR", e.getMessage())); } catch (NoRouteToHostException e) { throw new ImportExportException(Locale.getString("DESTINATION_UNREACHABLE_ERROR", e.getMessage())); } catch (MalformedURLException e) { throw new ImportExportException(Locale.getString("INVALID_PROXY_ERROR", proxyPreferences.host, proxyPreferences.port)); } catch (FileNotFoundException e) { } catch (IOException e) { throw new ImportExportException(Locale.getString("ERROR_DOWNLOADING_QUOTES")); } return quotes; } Code Sample 2: public static Set<Province> getProvincias(String pURL) { Set<Province> result = new HashSet<Province>(); String iniProv = "<prov>"; String finProv = "</prov>"; String iniNomProv = "<np>"; String finNomProv = "</np>"; String iniCodigo = "<cpine>"; String finCodigo = "</cpine>"; int ini, fin; try { URL url = new URL(pURL); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String str; Province provincia; while ((str = br.readLine()) != null) { if (str.contains(iniProv)) { provincia = new Province(); while ((str = br.readLine()) != null && !str.contains(finProv)) { if (str.contains(iniNomProv)) { ini = str.indexOf(iniNomProv) + iniNomProv.length(); fin = str.indexOf(finNomProv); provincia.setDescription(str.substring(ini, fin)); } if (str.contains(iniCodigo)) { ini = str.indexOf(iniCodigo) + iniCodigo.length(); fin = str.indexOf(finCodigo); provincia.setCodeProvince(Integer.parseInt(str.substring(ini, fin))); } } result.add(provincia); } } br.close(); } catch (Exception e) { System.err.println(e); } return result; }
11
Code Sample 1: public static String getMD5(String input) { String res = ""; try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(input.getBytes("ISO8859_1")); byte[] md5 = algorithm.digest(); String tmp = ""; for (int i = 0; i < md5.length; i++) { tmp = (Integer.toHexString(0xFF & md5[i])); if (tmp.length() == 1) { res += "0" + tmp; } else { res += tmp; } } } catch (Exception ex) { } return res; } Code Sample 2: public static synchronized String encrypt(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(text.getBytes("UTF-8")); byte raw[] = md.digest(); return new Base64(-1).encodeToString(raw); }
00
Code Sample 1: static ConversionMap create(String file) { ConversionMap out = new ConversionMap(); URL url = ConversionMap.class.getResource("data/" + file); try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = in.readLine(); while (line != null) { if (line.length() > 0) { String[] arr = line.split("\t"); try { double value = Double.parseDouble(arr[1]); out.put(translate(lowercase(arr[0].getBytes())), value); out.defaultValue += value; out.length = arr[0].length(); } catch (NumberFormatException e) { throw new RuntimeException("Something is wrong with in conversion file: " + e); } } line = in.readLine(); } in.close(); out.defaultValue /= Math.pow(4, out.length); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Their was an error while reading the conversion map: " + e); } return out; } Code Sample 2: @SuppressWarnings("deprecation") private void loadClassFilesFromJar() { IPackageFragmentRoot packageFragmentRoot = (IPackageFragmentRoot) getJavaElement(); File jarFile = packageFragmentRoot.getResource().getLocation().toFile(); try { URL url = jarFile.toURL(); URLConnection u = url.openConnection(); ZipInputStream inputStream = new ZipInputStream(u.getInputStream()); ZipEntry entry = inputStream.getNextEntry(); while (null != entry) { if (entry.getName().endsWith(".class")) { ClassParser parser = new ClassParser(inputStream, entry.getName()); Repository.addClass(parser.parse()); } entry = inputStream.getNextEntry(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: public JSONObject getTargetGraph(HttpSession session, JSONObject json) throws JSONException { StringBuffer out = new StringBuffer(); Graph tgt = null; MappingManager manager = (MappingManager) session.getAttribute(RuncibleConstants.MAPPING_MANAGER.key()); try { tgt = manager.getTargetGraph(); if (tgt != null) { FlexGraphViewFactory factory = new FlexGraphViewFactory(); factory.setColorScheme(ColorSchemes.ORANGES); factory.visit(tgt); GraphView view = factory.getGraphView(); GraphViewRenderer renderer = new FlexGraphViewRenderer(); renderer.setGraphView(view); InputStream xmlStream = renderer.renderGraphView(); StringWriter writer = new StringWriter(); IOUtils.copy(xmlStream, writer); writer.close(); System.out.println(writer.toString()); out.append(writer.toString()); } else { out.append("No target graph loaded."); } } catch (Exception e) { return JSONUtils.SimpleJSONError("Cannot load target graph: " + e.getMessage()); } return JSONUtils.SimpleJSONResponse(out.toString()); } Code Sample 2: public void testAddingEntries() throws Exception { DiskCache c = new DiskCache(); { c.setRoot(rootFolder.getAbsolutePath()); c.setHtmlExtension("htm"); c.setPropertiesExtension("txt"); assertEquals("htm", c.getHtmlExtension()); assertEquals("txt", c.getPropertiesExtension()); assertEquals(rootFolder.getAbsolutePath(), c.getRoot()); } String key1 = "cat1/key1"; String key2 = "cat1/key2"; try { try { { c.removeCacheEntry(key1, null); CacheItem i = c.getOrCreateCacheEntry(key1); assertNull(i.getEncoding()); assertEquals(-1L, i.getLastModified()); assertEquals(-1, i.getTranslationCount()); assertFalse(i.isCached()); assertNull(i.getHeaders()); i.setLastModified(300005L); i.setTranslationCount(10); i.setEncoding("ISO-8859-7"); i.setHeader(new ResponseHeaderImpl("Test2", new String[] { "Value3", "Value4" })); i.setHeader(new ResponseHeaderImpl("Test1", new String[] { "Value1", "Value2" })); byte[] greekTextBytes = new byte[] { -57, -20, -27, -15, -34, -13, -23, -31, 32, -48, -17, -21, -23, -12, -23, -22, -34, 32, -59, -10, -25, -20, -27, -15, -33, -28, -31, 32, -60, -23, -31, -19, -35, -20, -27, -12, -31, -23, 32, -22, -31, -24, -25, -20, -27, -15, -23, -19, -36, 32, -60, -39, -47, -59, -63, -51, 32, -13, -12, -17, 32, -28, -33, -22, -12, -11, -17, 32, -13, -11, -29, -22, -17, -23, -19, -7, -19, -23, -2, -19, 32, -12, -25, -14, 32, -56, -27, -13, -13, -31, -21, -17, -19, -33, -22, -25, -14 }; String greekText = new String(greekTextBytes, "ISO-8859-7"); { InputStream input = new ByteArrayInputStream(greekTextBytes); try { i.setContentAsStream(input); } finally { input.close(); } } assertEquals("ISO-8859-7", i.getEncoding()); assertEquals(300005L, i.getLastModified()); assertEquals(10, i.getTranslationCount()); assertFalse(i.isCached()); i.updateAfterAllContentUpdated(null, null); { assertEquals(3, i.getHeaders().size()); int ii = 0; for (ResponseHeader h : i.getHeaders()) { ii++; if (ii == 1) { assertEquals("Content-Length", h.getName()); assertEquals("[97]", Arrays.toString(h.getValues())); } else if (ii == 2) { assertEquals("Test1", h.getName()); assertEquals("[Value1, Value2]", Arrays.toString(h.getValues())); } else if (ii == 3) { assertEquals("Test2", h.getName()); assertEquals("[Value3, Value4]", Arrays.toString(h.getValues())); } } } c.storeInCache(key1, i); assertEquals("ISO-8859-7", i.getEncoding()); assertEquals(300005L, i.getLastModified()); assertEquals(10, i.getTranslationCount()); assertTrue(i.isCached()); { InputStream input = i.getContentAsStream(); StringWriter w = new StringWriter(); IOUtils.copy(input, w, "ISO-8859-7"); IOUtils.closeQuietly(input); IOUtils.closeQuietly(w); assertEquals(greekText, w.toString()); } } { c.removeCacheEntry(key2, null); CacheItem i = c.getOrCreateCacheEntry(key2); assertNull(i.getEncoding()); assertEquals(-1L, i.getLastModified()); assertEquals(-1, i.getTranslationCount()); assertFalse(i.isCached()); assertNull(i.getHeaders()); i.setLastModified(350000L); i.setTranslationCount(11); i.setEncoding("ISO-8859-1"); i.setHeader(new ResponseHeaderImpl("Test3", new String[] { "Value3", "Value4" })); i.setHeader(new ResponseHeaderImpl("Test4", new String[] { "Value1" })); String englishText = "Hello this is another example"; { InputStream input = new ByteArrayInputStream(englishText.getBytes("ISO-8859-1")); try { i.setContentAsStream(input); } finally { input.close(); } } assertEquals("ISO-8859-1", i.getEncoding()); assertEquals(350000L, i.getLastModified()); assertEquals(11, i.getTranslationCount()); assertFalse(i.isCached()); i.updateAfterAllContentUpdated(null, null); { assertEquals(3, i.getHeaders().size()); int ii = 0; for (ResponseHeader h : i.getHeaders()) { ii++; if (ii == 1) { assertEquals("Content-Length", h.getName()); assertEquals("[29]", Arrays.toString(h.getValues())); } else if (ii == 2) { assertEquals("Test3", h.getName()); assertEquals("[Value3, Value4]", Arrays.toString(h.getValues())); } else if (ii == 3) { assertEquals("Test4", h.getName()); assertEquals("[Value1]", Arrays.toString(h.getValues())); } } } c.storeInCache(key2, i); assertEquals("ISO-8859-1", i.getEncoding()); assertEquals(350000L, i.getLastModified()); assertEquals(11, i.getTranslationCount()); assertTrue(i.isCached()); { InputStream input = i.getContentAsStream(); StringWriter w = new StringWriter(); IOUtils.copy(input, w, "ISO-8859-1"); IOUtils.closeQuietly(input); IOUtils.closeQuietly(w); assertEquals(englishText, w.toString()); } } { CacheItem i = c.getOrCreateCacheEntry(key1); assertEquals("ISO-8859-7", i.getEncoding()); assertEquals(300005L, i.getLastModified()); assertEquals(10, i.getTranslationCount()); assertTrue(i.isCached()); { assertEquals(3, i.getHeaders().size()); int ii = 0; for (ResponseHeader h : i.getHeaders()) { ii++; if (ii == 1) { assertEquals("Content-Length", h.getName()); assertEquals("[97]", Arrays.toString(h.getValues())); } else if (ii == 2) { assertEquals("Test1", h.getName()); assertEquals("[Value1, Value2]", Arrays.toString(h.getValues())); } else if (ii == 3) { assertEquals("Test2", h.getName()); assertEquals("[Value3, Value4]", Arrays.toString(h.getValues())); } } } byte[] greekTextBytes = new byte[] { -57, -20, -27, -15, -34, -13, -23, -31, 32, -48, -17, -21, -23, -12, -23, -22, -34, 32, -59, -10, -25, -20, -27, -15, -33, -28, -31, 32, -60, -23, -31, -19, -35, -20, -27, -12, -31, -23, 32, -22, -31, -24, -25, -20, -27, -15, -23, -19, -36, 32, -60, -39, -47, -59, -63, -51, 32, -13, -12, -17, 32, -28, -33, -22, -12, -11, -17, 32, -13, -11, -29, -22, -17, -23, -19, -7, -19, -23, -2, -19, 32, -12, -25, -14, 32, -56, -27, -13, -13, -31, -21, -17, -19, -33, -22, -25, -14 }; String greekText = new String(greekTextBytes, "ISO-8859-7"); { InputStream input = i.getContentAsStream(); StringWriter w = new StringWriter(); IOUtils.copy(input, w, "ISO-8859-7"); IOUtils.closeQuietly(input); IOUtils.closeQuietly(w); assertEquals(greekText, w.toString()); } } { c.removeCacheEntry(key1, null); CacheItem i = c.getOrCreateCacheEntry(key1); assertNull(i.getEncoding()); assertEquals(-1L, i.getLastModified()); assertEquals(-1, i.getTranslationCount()); assertFalse(i.isCached()); assertNull(i.getHeaders()); } } finally { c.removeCacheEntry(key1, null); } } finally { c.removeCacheEntry(key2, null); } }
00
Code Sample 1: private void getDownloadLink() throws Exception { status = UploadStatus.GETTINGLINK; NULogger.getLogger().info("Now Getting Download link..."); HttpClient client = new DefaultHttpClient(); HttpGet h = new HttpGet(uploadresponse); h.setHeader("Referer", postURL); if (zShareAccount.loginsuccessful) { h.setHeader("Cookie", zShareAccount.getSidcookie() + ";" + zShareAccount.getMysessioncookie()); } else { h.setHeader("Cookie", sidcookie + ";" + mysessioncookie); } HttpResponse res = client.execute(h); HttpEntity entity = res.getEntity(); linkpage = EntityUtils.toString(entity); linkpage = linkpage.replaceAll("\n", ""); downloadlink = CommonUploaderTasks.parseResponse(linkpage, "value=\"", "\""); deletelink = CommonUploaderTasks.parseResponse(linkpage, "delete.html?", "\""); deletelink = "http://www.zshare.net/delete.html?" + deletelink; downURL = downloadlink; delURL = deletelink; NULogger.getLogger().log(Level.INFO, "Download link : {0}", downloadlink); NULogger.getLogger().log(Level.INFO, "Delete Link : {0}", deletelink); uploadFinished(); } Code Sample 2: public static void main(String[] args) { String u = "http://portal.acm.org/results.cfm?query=%28Author%3A%22" + "Boehm%2C+Barry" + "%22%29&srt=score%20dsc&short=0&source_disp=&since_month=&since_year=&before_month=&before_year=&coll=ACM&dl=ACM&termshow=matchboolean&range_query=&CFID=22704101&CFTOKEN=37827144&start=1"; URL url = null; AcmSearchresultPageParser_2008Apr cb = new AcmSearchresultPageParser_2008Apr(); try { url = new URL(u); HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.setUseCaches(false); InputStream is = uc.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); ParserDelegator pd = new ParserDelegator(); pd.parse(br, cb, true); br.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("all doc num= " + cb.getAllDocNum()); for (int i = 0; i < cb.getEachResultStartposisions().size(); i++) { HashMap<String, Integer> m = cb.getEachResultStartposisions().get(i); System.out.println(i + "pos= " + m); } }
00
Code Sample 1: public static boolean update(Funcionario objFuncionario) { int result = 0; Connection c = DBConnection.getConnection(); PreparedStatement pst = null; if (c == null) { return false; } try { c.setAutoCommit(false); final String sql = "update funcionario " + " set nome = ? , cpf = ? , telefone = ? , email = ?, senha = ?, login = ?, id_cargo = ?" + " where id_funcionario = ?"; pst = c.prepareStatement(sql); pst.setString(1, objFuncionario.getNome()); pst.setString(2, objFuncionario.getCpf()); pst.setString(3, objFuncionario.getTelefone()); pst.setString(4, objFuncionario.getEmail()); pst.setString(5, objFuncionario.getSenha()); pst.setString(6, objFuncionario.getLogin()); pst.setLong(7, (objFuncionario.getCargo()).getCodigo()); pst.setLong(8, objFuncionario.getCodigo()); result = pst.executeUpdate(); c.commit(); } catch (SQLException e) { try { c.rollback(); } catch (SQLException e1) { System.out.println("[FuncionarioDAO.update] Erro ao atualizar -> " + e1.getMessage()); } System.out.println("[FuncionarioDAO.update] Erro ao atualizar -> " + e.getMessage()); } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } if (result > 0) { return true; } else { return false; } } Code Sample 2: public String encripta(String senha) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(senha.getBytes()); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(digest.digest()); } catch (NoSuchAlgorithmException ns) { ns.printStackTrace(); return senha; } }
00
Code Sample 1: public static long getLastModified(URL url) throws IOException { if ("file".equals(url.getProtocol())) { String externalForm = url.toExternalForm(); File file = new File(externalForm.substring(5)); return file.lastModified(); } else { URLConnection connection = url.openConnection(); long modified = connection.getLastModified(); try { InputStream is = connection.getInputStream(); if (is != null) is.close(); } catch (UnknownServiceException use) { } catch (IOException ioe) { } return modified; } } Code Sample 2: @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (doAuth(request, response)) { Connection conn = null; try { int UID = icsm.getIntChatSession(request).getUID(); conn = getJDBCConnection(icsm.getHeavyDatabaseConnectionPool(), request, response, HttpServletResponse.SC_SERVICE_UNAVAILABLE); if (conn == null) return; ResultSet rs = IntChatDatabaseOperations.executeQuery(conn, "SELECT id FROM ic_messagetypes WHERE templatename='" + IntChatConstants.MessageTemplates.IC_FILES + "' LIMIT 1"); if (rs.next()) { int fileTypeID = rs.getInt("id"); String recipients = request.getHeader(IntChatConstants.HEADER_FILERECIPIENTS); rs.getStatement().close(); rs = null; if (recipients != null) { HashMap<String, String> hm = Tools.parseMultiparamLine(request.getHeader("Content-Disposition")); String fileName = URLDecoder.decode(hm.get("filename"), IntChatServerDefaults.ENCODING); long fileLength = (request.getHeader("Content-Length") != null ? Long.parseLong(request.getHeader("Content-Length")) : -1); fileLength = (request.getHeader(IntChatConstants.HEADER_FILELENGTH) != null ? Long.parseLong(request.getHeader(IntChatConstants.HEADER_FILELENGTH)) : fileLength); long maxFileSize = RuntimeParameters.getIntValue(ParameterNames.MAX_FILE_SIZE) * 1048576; if (maxFileSize > 0 && fileLength > maxFileSize) { request.getInputStream().close(); response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE); return; } long now = System.currentTimeMillis(); long nextid = ic_messages_id_seq.nextval(); IntChatServletInputStream in = new IntChatServletInputStream(request); IntChatMessage icm = null; conn.setAutoCommit(false); try { PreparedStatement ps = conn.prepareStatement("INSERT INTO ic_messages (id, tid, mhead, mbody, mdate, sid) VALUES (?, ?, ?, ?, ?, ?)"); ps.setLong(1, nextid); ps.setInt(2, fileTypeID); ps.setString(3, fileName); ps.setString(4, Long.toString(fileLength)); ps.setLong(5, now); ps.setInt(6, UID); ps.executeUpdate(); ps.close(); if (!insertBLOB(conn, in, fileLength, nextid, maxFileSize)) { conn.rollback(); return; } icm = new IntChatMessage(false, fileTypeID, null, null); String[] id = recipients.split(","); int id1; for (int i = 0; i < id.length; i++) { id1 = Integer.parseInt(id[i].trim()); IntChatDatabaseOperations.executeUpdate(conn, "INSERT INTO ic_recipients (mid, rid) VALUES ('" + nextid + "', '" + id1 + "')"); icm.addTo(id1); } conn.commit(); } catch (Exception e) { conn.rollback(); throw e; } finally { conn.setAutoCommit(true); } if (icm != null) { icm.setID(nextid); icm.setDate(new Timestamp(now - TimeZone.getDefault().getOffset(now))); icm.setFrom(UID); icm.setHeadText(fileName); icm.setBodyText(Long.toString(fileLength)); icsm.onClientSentMessage(icm); } response.setStatus(HttpServletResponse.SC_OK); } else { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } } else { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } if (rs != null) { rs.getStatement().close(); rs = null; } } catch (RetryRequest rr) { throw rr; } catch (Exception e) { Tools.makeErrorResponse(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e); } finally { try { if (conn != null) icsm.getHeavyDatabaseConnectionPool().releaseConnection(conn); } catch (Exception e) { } } } }
11
Code Sample 1: public static void process(PricesType prices, Long id_site, DatabaseAdapter dbDyn) throws PriceException { PreparedStatement ps = null; String sql_ = null; PriceListItemType debugItem = null; try { if (log.isDebugEnabled()) { log.debug("dbDyn - " + dbDyn); if (dbDyn != null) log.debug("dbDyn.conn - " + dbDyn.getConnection()); } dbDyn.getConnection().setAutoCommit(false); if (dbDyn.getFamaly() != DatabaseManager.MYSQL_FAMALY) { sql_ = "delete from WM_PRICE_IMPORT_TABLE where shop_code in " + "( select shop_code from WM_PRICE_SHOP_LIST where ID_SITE=? )"; ps = dbDyn.prepareStatement(sql_); RsetTools.setLong(ps, 1, id_site); ps.executeUpdate(); ps.close(); ps = null; } else { String sqlCheck = ""; boolean isFound = false; WmPriceShopListListType shops = GetWmPriceShopListWithIdSiteList.getInstance(dbDyn, id_site).item; boolean isFirst = true; for (int i = 0; i < shops.getWmPriceShopListCount(); i++) { WmPriceShopListItemType shop = shops.getWmPriceShopList(i); isFound = true; if (isFirst) isFirst = false; else sqlCheck += ","; sqlCheck += ("'" + shop.getCodeShop() + "'"); } if (isFound) { sql_ = "delete from WM_PRICE_IMPORT_TABLE where shop_code in ( " + sqlCheck + " )"; if (log.isDebugEnabled()) log.debug("sql " + sql_); ps = dbDyn.prepareStatement(sql_); ps.executeUpdate(); ps.close(); ps = null; } } if (log.isDebugEnabled()) log.debug("Start unmarshalling data"); if (prices == null) throw new PriceException("������ ������� ����� �������. ��� ������ #10.03"); int batchLoop = 0; int count = 0; sql_ = "insert into WM_PRICE_IMPORT_TABLE " + "(is_group, id, id_main, name, price, currency, is_to_load, shop_code, ID_UPLOAD_PRICE) " + "values (?,?,?,?,?,?,?,?,?)"; Long id_upload_session = null; for (int j = 0; j < prices.getPriceListCount(); j++) { PriceListType price = prices.getPriceList(j); if (log.isDebugEnabled()) { log.debug("shopCode " + price.getShopCode()); log.debug("Size vector: " + price.getItemCount()); } for (int i = 0; (i < price.getItemCount()) && (count < 5000); i++, count++) { if (ps == null) ps = dbDyn.prepareStatement(sql_); PriceListItemType item = price.getItem(i); debugItem = item; ps.setInt(1, Boolean.TRUE.equals(item.getIsGroup()) ? 1 : 0); RsetTools.setLong(ps, 2, item.getItemID()); RsetTools.setLong(ps, 3, item.getParentID()); ps.setString(4, item.getNameItem()); RsetTools.setDouble(ps, 5, item.getPrice()); ps.setString(6, item.getCurr()); ps.setString(7, item.getIsLoad().toString()); ps.setString(8, price.getShopCode().toUpperCase()); RsetTools.setLong(ps, 9, id_upload_session); if (dbDyn.getIsBatchUpdate()) { ps.addBatch(); if (++batchLoop >= 200) { int[] updateCounts = ps.executeBatch(); ps.close(); ps = null; batchLoop = 0; } } else ps.executeUpdate(); } } if (dbDyn.getIsBatchUpdate()) { if (ps != null) { int[] updateCounts = ps.executeBatch(); ps.close(); ps = null; } } ImportPriceProcess.process(dbDyn, id_site); dbDyn.commit(); } catch (Exception e) { if (debugItem != null) { log.error("debugItem.getIsGroup() " + (Boolean.TRUE.equals(debugItem.getIsGroup()) ? 1 : 0)); log.error("debugItem.getItemID() " + debugItem.getItemID()); log.error("debugItem.getParentID() " + debugItem.getParentID()); log.error("debugItem.getNameItem() " + debugItem.getNameItem()); log.error("debugItem.getPrice() " + debugItem.getPrice()); log.error("debugItem.getCurr() " + debugItem.getCurr()); log.error("debugItem.getIsLoad().toString() " + debugItem.getIsLoad().toString()); } else log.error("debugItem is null"); log.error("sql:\n" + sql_); final String es = "error process import price-list"; log.error(es, e); try { dbDyn.rollback(); } catch (Exception e11) { } throw new PriceException(es, e); } finally { DatabaseManager.close(ps); ps = null; } } Code Sample 2: public int subclass(int objectId, String description) throws FidoDatabaseException, ObjectNotFoundException { try { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { String sql = "insert into Objects (Description) " + "values ('" + description + "')"; conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); if (contains(stmt, objectId) == false) throw new ObjectNotFoundException(objectId); stmt.executeUpdate(sql); int id; sql = "select currval('objects_objectid_seq')"; rs = stmt.executeQuery(sql); if (rs.next() == false) throw new SQLException("No rows returned from select currval() query"); else id = rs.getInt(1); ObjectLinkTable objectLinkList = new ObjectLinkTable(); objectLinkList.linkObjects(stmt, id, "isa", objectId); conn.commit(); return id; } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } }
00
Code Sample 1: private boolean parse(Type type, URL url, boolean checkDict) throws Exception { boolean ok = true; Exception ee = null; Element rootElement = null; try { InputStream in = url.openStream(); if (type.equals(Type.XOM)) { new Builder().build(in); } else if (type.equals(Type.CML)) { rootElement = new CMLBuilder().build(in).getRootElement(); } in.close(); } catch (Exception e) { ee = e; } if (ee != null) { logger.severe("failed to cmlParse: " + url + "\n..... because: [" + ee + "] [" + ee.getMessage() + "] in [" + url + "]"); ok = false; } if (ok && checkDict) { ok = checkDict(rootElement); } return ok; } Code Sample 2: public void fetchKey() throws IOException { String strurl = MessageFormat.format(keyurl, new Object[] { username, secret, login, session }); StringBuffer result = new StringBuffer(); BufferedReader reader = null; URL url = null; try { url = new URL(strurl); reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; while ((line = reader.readLine()) != null) { result.append(line); } } finally { try { if (reader != null) reader.close(); } catch (Exception e) { } } Pattern p = Pattern.compile("<key>(.*)</key>"); Matcher m = p.matcher(result.toString()); if (m.matches()) { this.key = m.group(1); } }
00
Code Sample 1: public static void copyFile(File from, File to) throws FileNotFoundException, IOException { requireFile(from); requireFile(to); if (to.isDirectory()) { to = new File(to, getFileName(from)); } FileChannel sourceChannel = new FileInputStream(from).getChannel(); FileChannel destinationChannel = new FileOutputStream(to).getChannel(); destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); destinationChannel.close(); } Code Sample 2: public static int[] sort(int[] v) { int i; int l = v.length; int[] index = new int[l]; for (i = 0; i < l; i++) index[i] = i; int tmp; boolean change = true; while (change) { change = false; for (i = 0; i < l - 1; i++) { if (v[index[i]] > v[index[i + 1]]) { tmp = index[i]; index[i] = index[i + 1]; index[i + 1] = tmp; change = true; } } } return index; }
00
Code Sample 1: public FlatFileFrame() { super("Specify Your Flat File Data"); try { Class transferAgentClass = this.getStorageTransferAgentClass(); if (transferAgentClass == null) { throw new RuntimeException("Transfer agent class can not be null."); } Class[] parameterTypes = new Class[] { RepositoryStorage.class }; Constructor constr = transferAgentClass.getConstructor(parameterTypes); Object[] actualValues = new Object[] { this }; this.transferAgent = (RepositoryStorageTransferAgent) constr.newInstance(actualValues); } catch (Exception err) { throw new RuntimeException("Unable to instantiate transfer agent.", err); } this.fmtlistener = new FormatTableModelListener(); this.map = new HashMap(); this.NoCallbackChangeMode = false; this.setSize(new Dimension(1000, 400)); this.setLayout(new GridLayout(1, 1)); this.Config = new FlatFileToolsConfig(); this.Config.initialize(); this.connectionHandler = new RepositoryConnectionHandler(this.Config); this.Connection = (FlatFileStorageConnectivity) this.connectionHandler.getConnection("default"); this.Prefs = new FlatFileToolsPrefs(); this.Prefs.initialize(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); String formatted_date = formatter.format(new Date()); this.createdOnText = new JTextField(formatted_date); this.createdByText = new JTextField(this.Prefs.getConfigValue("createdby")); this.reposListeners = new Vector(); this.removeFormatButton = new JButton("Remove"); this.previewPanel = new DataSetPanel(new DataSet()); this.previewPanel.setEditable(false); this.chooser = new JFileChooser(); this.chooser.setMultiSelectionEnabled(true); this.enabledRadio = new JRadioButton("Enabled:"); this.enabledRadio.setSelected(true); this.editPrefsButton = new JButton("Preferences..."); this.editPrefsButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { System.out.println("Making visible"); prefsEditor.setVisible(true); } }); this.commentTextArea = new JTextArea(20, 8); this.commentTextArea.setText("No comment."); this.commentTextArea.setToolTipText("A detailed (possibly formatted) description including guidance to future developers of this set."); this.iconServer = new IconServer(); this.iconServer.setConfigFile(this.Prefs.getConfigValue("default", "iconmapfile")); this.nicknameText = new IconifiedDomainNameTextField(new FlatFileFindNameDialog(Config, iconServer), this.iconServer); this.nicknameText.setPreferredSize(new Dimension(200, 25)); this.nicknameText.setText(this.Prefs.getConfigValue("default", "domainname") + "."); this.nicknameText.setNameTextToolTipText("Right click to search the database."); this.uploadButton = new JButton("Upload"); this.uploadButton.setToolTipText("Uploads current state to repository."); this.uploadButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { System.out.println("Trying to upload flat file spec..."); try { String expname = getNickname(); int split = expname.lastIndexOf('.'); String domain = ""; String name = ""; String usersdomain = Prefs.getConfigValue("default", "domainname"); if (split > 0) { domain = expname.substring(0, split); name = expname.substring(split + 1, expname.length()); } else { name = expname; } name = name.trim(); if (name.equals("")) { JOptionPane.showMessageDialog(null, "Cowardly refusing to upload with an empty flat file name..."); return; } if (!domain.equals(usersdomain)) { int s = JOptionPane.showConfirmDialog(null, "If you are not the original author, you may wish to switch the current domain name " + domain + " to \nyour domain name " + usersdomain + ". Would you like to do this?\n (If you'll be using this domain often, you may want to set it in your preferences.)", "Potential WWW name-space clash!", JOptionPane.YES_NO_CANCEL_OPTION); if (s == JOptionPane.YES_OPTION) { setNickname(usersdomain + "." + name); executeTransfer(); } if (s == JOptionPane.NO_OPTION) { executeTransfer(); } } else { executeTransfer(); } } catch (Exception err) { throw new RuntimeException("Problem uploading storage.", err); } } }); this.repositoryView = new JButton("default"); this.repositoryView.addActionListener(new ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { repositoryEditor.setCurrentRepository(repositoryView.getText()); repositoryEditor.setVisible(true); } }); this.prefsEditor = new PrefsConfigFrame(this.Prefs); this.prefsEditor.setVisible(false); this.prefsEditor.addCloseListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { prefsEditor.setVisible(false); } }); this.prefsEditor.addSelectListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { prefsEditor.setVisible(false); } }); this.repositoryEditor = new ReposConfigFrame(this.Config); this.repositoryEditor.setVisible(false); this.repositoryEditor.addSelectListener(new SelectListener()); this.repositoryEditor.addCloseListener(new CloseListener()); this.addSources = new JButton("Source from file..."); this.preview = new JButton("Preview"); this.leastcolumn = new JSpinner(); this.columns2show = new JSpinner(); this.leastrow = new JSpinner(); this.rows2show = new JSpinner(); int rowCount = 10; JLabel sourceLabel = new JLabel("File Source"); this.flatfilesource = new JTextField(); this.flatfilesource.setPreferredSize(new Dimension(200, 25)); this.flatfilesource.setMinimumSize(new Dimension(200, 25)); this.flatfilesource.setMaximumSize(new Dimension(200, 25)); this.isURLButton = new JRadioButton("URL"); Box scrollBox = Box.createVerticalBox(); Box srcBox = Box.createHorizontalBox(); srcBox.add(this.addSources); srcBox.add(sourceLabel); srcBox.add(this.flatfilesource); srcBox.add(this.isURLButton); srcBox.add(this.preview); scrollBox.add(srcBox); Box detailsPanel = Box.createVerticalBox(); Box detailsBox = Box.createVerticalBox(); JLabel label; Box jointBox; jointBox = Box.createHorizontalBox(); label = new JLabel("Pre-Header Lines:"); this.preheaderlines = new JSpinner(); jointBox.add(label); jointBox.add(this.preheaderlines); detailsBox.add(jointBox); this.preheaderlines.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent ev) { int selectedRow = fileselector.getSelectedRow(); if (selectedRow >= 0) { String fn = (String) sourcemodel.getValueAt(selectedRow, 0); if (fn != null) { updateDetailsFor(fn); } } } }); jointBox = Box.createHorizontalBox(); label = new JLabel("Has Header Line:"); this.hasHeaderLineBox = new JCheckBox(); jointBox.add(label); jointBox.add(this.hasHeaderLineBox); detailsBox.add(jointBox); this.hasHeaderLineBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { int selectedRow = fileselector.getSelectedRow(); if (selectedRow >= 0) { String fn = (String) sourcemodel.getValueAt(selectedRow, 0); if (fn != null) { fn = fn.trim(); if ((fn != null) && (fn.length() > 0)) { updateDetailsFor(fn); } } } } }); jointBox = Box.createHorizontalBox(); label = new JLabel("Post-Header Lines:"); this.postheaderlines = new JSpinner(); jointBox.add(label); jointBox.add(this.postheaderlines); detailsBox.add(jointBox); this.postheaderlines.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent ev) { int selectedRow = fileselector.getSelectedRow(); if (selectedRow >= 0) { String fn = (String) sourcemodel.getValueAt(selectedRow, 0); if (fn != null) { fn = fn.trim(); if ((fn != null) && (fn.length() > 0)) { updateDetailsFor(fn); } } } } }); jointBox = Box.createHorizontalBox(); label = new JLabel("Format:"); jointBox.add(label); this.singleFormatText = new JTextField("%s"); jointBox.add(this.singleFormatText); jointBox.add(new JLabel("Repeat")); this.repeatFormatNumber = new JSpinner(); this.repeatFormatNumber.setValue(new Integer(1)); jointBox.add(this.repeatFormatNumber); this.addFormatButton = new JButton("Add"); jointBox.add(this.addFormatButton); this.removeFormatButton = new JButton("Remove"); jointBox.add(this.removeFormatButton); detailsBox.add(jointBox); jointBox = Box.createHorizontalBox(); label = new JLabel("Column Format:"); this.formatmodel = new FormatTableModel(); this.formatTable = new JTable(this.formatmodel); this.formatmodel.addTableModelListener(this.fmtlistener); JTable hdrTable = this.formatTable.getTableHeader().getTable(); this.formatTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); JScrollPane fsp = new JScrollPane(this.formatTable); fsp.setPreferredSize(new Dimension(200, 100)); jointBox.add(label); jointBox.add(fsp); detailsBox.add(jointBox); jointBox = Box.createHorizontalBox(); label = new JLabel("Field Delimiter:"); this.fieldDelimiter = new JTextField("\\t"); this.fieldDelimiter.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { int selectedRow = fileselector.getSelectedRow(); if (selectedRow >= 0) { String fn = (String) sourcemodel.getValueAt(selectedRow, 0); if (fn != null) { fn = fn.trim(); if ((fn != null) && (fn.length() > 0)) { updateDetailsFor(fn); } } } } }); jointBox.add(label); jointBox.add(this.fieldDelimiter); this.inferButton = new JButton("Infer"); this.inferButton.setEnabled(false); jointBox.add(this.inferButton); detailsBox.add(jointBox); jointBox = Box.createHorizontalBox(); label = new JLabel("Record Delimiter:"); this.recordDelimiter = new JTextField("\\n"); this.recordDelimiter.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { int selectedRow = fileselector.getSelectedRow(); if (selectedRow >= 0) { String fn = (String) sourcemodel.getValueAt(selectedRow, 0); if (fn != null) { fn = fn.trim(); if ((fn != null) && (fn.length() > 0)) { updateDetailsFor(fn); } } } } }); jointBox.add(label); jointBox.add(this.recordDelimiter); detailsBox.add(jointBox); detailsBox.add(Box.createVerticalGlue()); detailsBox.add(Box.createVerticalGlue()); detailsPanel.add(srcBox); detailsPanel.add(detailsBox); detailsPanel.add(previewPanel); this.addFormatButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { String fmt2rep = singleFormatText.getText(); Integer rep = (Integer) repeatFormatNumber.getValue(); Vector fmtparts = formatmodel.getFormatParts(); int selectedCol = formatTable.getSelectedColumn(); if (selectedCol < 0) { selectedCol = formatTable.getColumnCount() - 1; } for (int r = 1; r <= rep.intValue(); r++) { fmtparts.insertElementAt(fmt2rep, selectedCol); } formatmodel.setFormatParts(fmtparts); updateFormatTable(); int selectedRow = fileselector.getSelectedRow(); if ((selectedRow < sourcemodel.getRowCount()) && (selectedRow >= 0)) { String fn = (String) sourcemodel.getValueAt(selectedRow, 0); fn = fn.trim(); if (fn != null) { fn = fn.trim(); if ((fn != null) && (fn.length() > 0)) { updateDetailsFor(fn); } } } } }); this.removeFormatButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { int selectedCol = formatTable.getSelectedColumn(); if (selectedCol < 0) { return; } Vector parts = formatmodel.getFormatParts(); if (parts.size() == 1) { throw new RuntimeException("At least one format column is required."); } parts.removeElementAt(selectedCol); formatmodel.setFormatParts(parts); updateFormatTable(); int selectedRow = fileselector.getSelectedRow(); if ((selectedRow < sourcemodel.getRowCount()) && (selectedRow >= 0)) { String fn = (String) sourcemodel.getValueAt(selectedRow, 0); fn = fn.trim(); if (fn != null) { fn = fn.trim(); if ((fn != null) && (fn.length() > 0)) { updateDetailsFor(fn); } } } System.out.println("The new Column count after remove is " + formatmodel.getColumnCount()); } }); this.inferButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { int row = fileselector.getSelectedRow(); int col = 0; String filename = (String) sourcemodel.getValueAt(0, 0); Boolean isURL = (Boolean) sourcemodel.getValueAt(0, 1); BufferedReader br = null; File file = null; DataInputStream in = null; if (isURL.booleanValue()) { try { URL url2goto = new URL(filename); in = new DataInputStream(url2goto.openStream()); System.out.println("READY TO READ FROM URL:" + url2goto); } catch (Exception err) { throw new RuntimeException("Problem constructing URI for " + filename + ".", err); } } else { file = new File(filename); if (!file.exists()) { throw new RuntimeException("The file named '" + filename + "' does not exist."); } FileInputStream fstream = null; try { fstream = new FileInputStream(filename); in = new DataInputStream(fstream); } catch (Exception err) { throw new RuntimeException("Problem creating FileInputStream for " + filename + ".", err); } } br = new BufferedReader(new InputStreamReader(in)); JTable hdrTable = formatTable.getTableHeader().getTable(); try { String strLine; int line = 0; int ignorePreHdrLines = ((Integer) preheaderlines.getValue()).intValue(); int ignorePostHdrLines = ((Integer) postheaderlines.getValue()).intValue(); int numhdr = 0; boolean hasHeaderLine = false; if (hasHeaderLineBox.isSelected()) { hasHeaderLine = true; } if (hasHeaderLine) { numhdr = 1; } String FD = fieldDelimiter.getText(); while ((strLine = br.readLine()) != null) { if (line <= (ignorePreHdrLines + numhdr + ignorePostHdrLines)) { System.out.println(strLine); } else { String[] putative_cols = strLine.split(FD); System.out.println("The number of potential columns is " + putative_cols.length); String FMT = ""; while (formatTable.getColumnCount() > putative_cols.length) { TableColumn tcol = formatTable.getColumnModel().getColumn(0); formatTable.removeColumn(tcol); } for (int i = 0; i < putative_cols.length; i++) { String fmt = ""; try { Double dummy = new Double(putative_cols[i]); fmt = "%f"; } catch (Exception err) { fmt = "%s"; } FMT = FMT + fmt; formatTable.setValueAt(fmt, 0, i); } System.out.println("The potential format is " + FMT); formatmodel.setFormat(FMT); break; } line++; } in.close(); } catch (Exception err) { throw new RuntimeException("Problem reading single line from file.", err); } for (int j = 0; j < formatTable.getColumnCount(); j++) { hdrTable.getColumnModel().getColumn(j).setHeaderValue("" + (j + 1)); } formatTable.repaint(); } }); Box topbox = Box.createHorizontalBox(); topbox.add(detailsPanel); Box mainbox = Box.createVerticalBox(); Box setBox = Box.createHorizontalBox(); setBox.add(this.editPrefsButton); jointBox = Box.createHorizontalBox(); label = new JLabel("Created On:"); jointBox.add(label); this.createdOnText.setPreferredSize(new Dimension(50, 25)); jointBox.add(this.createdOnText); setBox.add(jointBox); jointBox = Box.createHorizontalBox(); label = new JLabel("Created By:"); jointBox.add(label); this.createdByText.setPreferredSize(new Dimension(50, 25)); jointBox.add(this.createdByText); setBox.add(jointBox); setBox.add(this.uploadButton); setBox.add(this.repositoryView); setBox.add(this.nicknameText); setBox.add(this.enabledRadio); mainbox.add(setBox); jointBox = Box.createHorizontalBox(); label = new JLabel("Comment:"); jointBox.add(label); jointBox.add(new JScrollPane(this.commentTextArea)); mainbox.add(jointBox); mainbox.add(topbox); mainbox.add(previewPanel); this.add(mainbox); this.addSources.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { int option = chooser.showOpenDialog(null); File[] files = null; if (option == JFileChooser.APPROVE_OPTION) { files = chooser.getSelectedFiles(); if (files.length > 10) { ((DefaultTableModel) sourcemodel).setRowCount(files.length); } else { ((DefaultTableModel) sourcemodel).setRowCount(10); } for (int i = 0; i < files.length; i++) { sourcemodel.setValueAt(files[i].getAbsolutePath(), i, 0); } } if (anyNonEmptySources()) { allowFormatParsing(true); } else { allowFormatParsing(false); } } }); this.preview.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { FlatFileDOM[] filespecs = new FlatFileDOM[map.size()]; int k = 0; for (int j = 0; j < sourcemodel.getRowCount(); j++) { String fn = (String) sourcemodel.getValueAt(j, 0); if (map.containsKey(fn)) { filespecs[k] = (FlatFileDOM) map.get(fn); k++; } } Vector hdrs = null; Vector types = null; for (int j = 0; j < filespecs.length; j++) { DataSetReader rdr = new DataSetReader(filespecs[j]); int rc = rdr.determineRowCount(); filespecs[j].setRowCount(rc); if (j == 0) { hdrs = rdr.getHeaders(); types = rdr.getTypes(); } System.out.println("The number of rows is=" + rc); } System.out.println("Creating flatfileset"); FlatFileSet dataset = new FlatFileSet(filespecs); System.out.println("Finished sorting!!!"); for (int j = 0; j < hdrs.size(); j++) { dataset.addColumn((String) hdrs.get(j), (Class) types.get(j)); } System.out.println("Number of headers is=" + hdrs.size()); System.out.println("The dataset rc is " + dataset.getRowCount()); System.out.println("The dataset cc is " + dataset.getColumnCount()); previewPanel.setDataSet(dataset); previewPanel.setVerticalScrollIntermittant(true); previewPanel.setHorizontalScrollIntermittant(true); previewPanel.setEditable(false); if (anyNonEmptySources()) { allowFormatParsing(true); } else { allowFormatParsing(false); } } }); allowFormatParsing(false); this.formatTable.repaint(); } Code Sample 2: private Reader getReader(String uri, Query query) throws SourceException { if (OntoramaConfig.DEBUG) { System.out.println("uri = " + uri); } InputStreamReader reader = null; try { System.out.println("class UrlSource, uri = " + uri); URL url = new URL(uri); URLConnection connection = url.openConnection(); reader = new InputStreamReader(connection.getInputStream()); } catch (MalformedURLException urlExc) { throw new SourceException("Url " + uri + " specified for this ontology source is not well formed, error: " + urlExc.getMessage()); } catch (IOException ioExc) { throw new SourceException("Couldn't read input data source for " + uri + ", error: " + ioExc.getMessage()); } return reader; }
11
Code Sample 1: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public static void decompressGZIP(File gzip, File to, long skip) throws IOException { GZIPInputStream gis = null; BufferedOutputStream bos = null; try { bos = new BufferedOutputStream(new FileOutputStream(to)); FileInputStream fis = new FileInputStream(gzip); fis.skip(skip); gis = new GZIPInputStream(fis); final byte[] buffer = new byte[IO_BUFFER]; int read = -1; while ((read = gis.read(buffer)) != -1) { bos.write(buffer, 0, read); } } finally { try { gis.close(); } catch (Exception nope) { } try { bos.flush(); } catch (Exception nope) { } try { bos.close(); } catch (Exception nope) { } } }
00
Code Sample 1: public static String getMD5Hash(String hashthis) throws NoSuchAlgorithmException { byte[] key = "PATIENTISAUTHENTICATION".getBytes(); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(hashthis.getBytes()); return new String(HashUtility.base64Encode(md5.digest(key))); } Code Sample 2: public <E extends Exception> void doWithConnection(String httpAddress, ICallableWithParameter<Void, URLConnection, E> toDo) throws E, ConnectionException { URLConnection connection; try { URL url = new URL(httpAddress); connection = url.openConnection(); } catch (MalformedURLException e) { throw new ConnectionException("Connecting to " + httpAddress + " got", e); } catch (IOException e) { throw new ConnectionException("Connecting to " + httpAddress + " got", e); } authenticationHandler.doWithProxyAuthentication(connection, toDo); }
11
Code Sample 1: public static String generateNonce(boolean is32) { Random random = new Random(); String result = String.valueOf(random.nextInt(9876599) + 123400); if (is32) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(result.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } result = buf.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } return result; } Code Sample 2: public void createVendorSignature() { byte b; try { _vendorMessageDigest = MessageDigest.getInstance("MD5"); _vendorSig = Signature.getInstance("MD5/RSA/PKCS#1"); _vendorSig.initSign((PrivateKey) _vendorPrivateKey); _vendorMessageDigest.update(getBankString().getBytes()); _vendorMessageDigestBytes = _vendorMessageDigest.digest(); _vendorSig.update(_vendorMessageDigestBytes); _vendorSignatureBytes = _vendorSig.sign(); } catch (Exception e) { } ; }
11
Code Sample 1: public static void readFile(FOUserAgent ua, String uri, Writer output, String encoding) throws IOException { InputStream in = getURLInputStream(ua, uri); try { StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, encoding); } finally { IOUtils.closeQuietly(in); } } Code Sample 2: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } out.setLastModified(in.lastModified()); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
00
Code Sample 1: public static String getDigest(String seed, String code) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(seed.getBytes("UTF-8")); byte[] passwordMD5Byte = md.digest(code.getBytes("UTF-8")); StringBuffer sb = new StringBuffer(); for (int i = 0; i < passwordMD5Byte.length; i++) sb.append(Integer.toHexString(passwordMD5Byte[i] & 0XFF)); return sb.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); log.error(e); return null; } catch (UnsupportedEncodingException e) { e.printStackTrace(); log.error(e); return null; } } Code Sample 2: public static boolean predictDataSet(String completePath, String Type, String predictionOutputFileName, String CFDataFolderName) { try { if (Type.equalsIgnoreCase("Qualifying")) { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CompleteQualifyingDataInByteFormat.txt"); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); TShortObjectHashMap qualMap = new TShortObjectHashMap(17770, 1); ByteBuffer qualmappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); while (qualmappedfile.hasRemaining()) { short movie = qualmappedfile.getShort(); int customer = qualmappedfile.getInt(); if (qualMap.containsKey(movie)) { TIntArrayList arr = (TIntArrayList) qualMap.get(movie); arr.add(customer); qualMap.put(movie, arr); } else { TIntArrayList arr = new TIntArrayList(); arr.add(customer); qualMap.put(movie, arr); } } System.out.println("Populated qualifying hashmap"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionOutputFileName); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf; TShortObjectHashMap movieDiffStats; double finalPrediction; short[] movies = qualMap.keys(); Arrays.sort(movies); for (int i = 0; i < movies.length; i++) { short movieToProcess = movies[i]; movieDiffStats = loadMovieDiffStats(completePath, movieToProcess, CFDataFolderName); TIntArrayList customersToProcess = (TIntArrayList) qualMap.get(movieToProcess); for (int j = 0; j < customersToProcess.size(); j++) { int customerToProcess = customersToProcess.getQuick(j); finalPrediction = predictPearsonWeightedSlopeOneRating(knn, movieToProcess, customerToProcess, movieDiffStats); if (finalPrediction == finalPrediction) { if (finalPrediction < 1.0) finalPrediction = 1.0; else if (finalPrediction > 5.0) finalPrediction = 5.0; } else finalPrediction = movieAverages.get(movieToProcess); buf = ByteBuffer.allocate(10); buf.putShort(movieToProcess); buf.putInt(customerToProcess); buf.putFloat(new Double(finalPrediction).floatValue()); buf.flip(); outC.write(buf); } } outC.close(); return true; } else if (Type.equalsIgnoreCase("Probe")) { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CompleteProbeDataInByteFormat.txt"); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); TShortObjectHashMap probeMap = new TShortObjectHashMap(17770, 1); ByteBuffer probemappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); while (probemappedfile.hasRemaining()) { short movie = probemappedfile.getShort(); int customer = probemappedfile.getInt(); byte rating = probemappedfile.get(); if (probeMap.containsKey(movie)) { TIntByteHashMap actualRatings = (TIntByteHashMap) probeMap.get(movie); actualRatings.put(customer, rating); probeMap.put(movie, actualRatings); } else { TIntByteHashMap actualRatings = new TIntByteHashMap(); actualRatings.put(customer, rating); probeMap.put(movie, actualRatings); } } System.out.println("Populated probe hashmap"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionOutputFileName); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf; double finalPrediction; TShortObjectHashMap movieDiffStats; short[] movies = probeMap.keys(); Arrays.sort(movies); for (int i = 0; i < movies.length; i++) { short movieToProcess = movies[i]; movieDiffStats = loadMovieDiffStats(completePath, movieToProcess, CFDataFolderName); TIntByteHashMap custRatingsToProcess = (TIntByteHashMap) probeMap.get(movieToProcess); TIntArrayList customersToProcess = new TIntArrayList(custRatingsToProcess.keys()); for (int j = 0; j < customersToProcess.size(); j++) { int customerToProcess = customersToProcess.getQuick(j); byte rating = custRatingsToProcess.get(customerToProcess); finalPrediction = predictPearsonWeightedSlopeOneRating(knn, movieToProcess, customerToProcess, movieDiffStats); if (finalPrediction == finalPrediction) { if (finalPrediction < 1.0) finalPrediction = 1.0; else if (finalPrediction > 5.0) finalPrediction = 5.0; } else { finalPrediction = movieAverages.get(movieToProcess); System.out.println("NaN Prediction"); } buf = ByteBuffer.allocate(11); buf.putShort(movieToProcess); buf.putInt(customerToProcess); buf.put(rating); buf.putFloat(new Double(finalPrediction).floatValue()); buf.flip(); outC.write(buf); } } outC.close(); return true; } else return false; } catch (Exception e) { e.printStackTrace(); return false; } }
00
Code Sample 1: public void copy(File s, File t) throws IOException { FileChannel in = (new FileInputStream(s)).getChannel(); FileChannel out = (new FileOutputStream(t)).getChannel(); in.transferTo(0, s.length(), out); in.close(); out.close(); } 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: private Image retrievePdsImage(double lat, double lon) { imageDone = false; try { StringBuffer urlBuff = new StringBuffer(psdUrl + psdCgi + "?"); urlBuff.append("DATA_SET_NAME=" + dataSet); urlBuff.append("&VERSION=" + version); urlBuff.append("&PIXEL_TYPE=" + pixelType); urlBuff.append("&PROJECTION=" + projection); urlBuff.append("&STRETCH=" + stretch); urlBuff.append("&GRIDLINE_FREQUENCY=" + gridlineFrequency); urlBuff.append("&SCALE=" + URLEncoder.encode(scale)); urlBuff.append("&RESOLUTION=" + resolution); urlBuff.append("&LATBOX=" + latbox); urlBuff.append("&LONBOX=" + lonbox); urlBuff.append("&BANDS_SELECTED=" + bandsSelected); urlBuff.append("&LAT=" + lat); urlBuff.append("&LON=" + lon); URL url = new URL(urlBuff.toString()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String result = null; String line; String imageSrc; int count = 0; while ((line = in.readLine()) != null) { if (count == 6) result = line; count++; } int startIndex = result.indexOf("<TH COLSPAN=2 ROWSPAN=2><IMG SRC = \"") + 36; int endIndex = result.indexOf("\"", startIndex); imageSrc = result.substring(startIndex, endIndex); URL imageUrl = new URL(imageSrc); return (Toolkit.getDefaultToolkit().getImage(imageUrl)); } catch (MalformedURLException e) { } catch (IOException e) { } return null; } Code Sample 2: private Metadata readMetadataIndexFileFromNetwork(String mediaMetadataURI) throws IOException { Metadata tempMetadata = new Metadata(); URL url = new URL(mediaMetadataURI); BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream())); String tempLine = null; while ((tempLine = input.readLine()) != null) { Property tempProperty = PropertyList.splitStringIntoKeyAndValue(tempLine); if (tempProperty != null) { tempMetadata.addIfNotNull(tempProperty.getKey(), tempProperty.getValue()); } } input.close(); return tempMetadata; }
00
Code Sample 1: public static BufferedReader openForReading(String name, URI base, ClassLoader classLoader) throws IOException { if ((name == null) || name.trim().equals("")) { return null; } if (name.trim().equals("System.in")) { if (STD_IN == null) { STD_IN = new BufferedReader(new InputStreamReader(System.in)); } return STD_IN; } URL url = nameToURL(name, base, classLoader); if (url == null) { throw new IOException("Could not convert \"" + name + "\" with base \"" + base + "\" to a URL."); } InputStreamReader inputStreamReader = null; try { inputStreamReader = new InputStreamReader(url.openStream()); } catch (IOException ex) { try { URL possibleJarURL = ClassUtilities.jarURLEntryResource(url.toString()); if (possibleJarURL != null) { inputStreamReader = new InputStreamReader(possibleJarURL.openStream()); } return new BufferedReader(inputStreamReader); } catch (Exception ex2) { try { if (inputStreamReader != null) { inputStreamReader.close(); } } catch (IOException ex3) { } IOException ioException = new IOException("Failed to open \"" + url + "\"."); ioException.initCause(ex); throw ioException; } } return new BufferedReader(inputStreamReader); } Code Sample 2: private void getGUID(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 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 static void printResource(OutputStream os, String resourceName) throws IOException { InputStream is = null; try { is = ResourceLoader.loadResource(resourceName); if (is == null) { throw new IOException("Given resource not found!"); } IOUtils.copy(is, os); } finally { IOUtils.closeQuietly(is); } }
11
Code Sample 1: private static String getDocumentAt(String urlString) { StringBuffer html_text = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) html_text.append(line + "\n"); reader.close(); } catch (MalformedURLException e) { System.out.println("����URL: " + urlString); } catch (IOException e) { e.printStackTrace(); } return html_text.toString(); } Code Sample 2: public ArrayList parseFile(File newfile) throws IOException { String s; String firstName; String header; String name = null; Integer PVLoggerID = new Integer(0); String[] tokens; int nvalues = 0; double num1, num2, num3; double xoffset = 1.0; double xdelta = 1.0; double yoffset = 1.0; double ydelta = 1.0; double zoffset = 1.0; double zdelta = 1.0; boolean readfit = false; boolean readraw = false; boolean zerodata = false; boolean baddata = false; boolean harpdata = false; ArrayList fitparams = new ArrayList(); ArrayList xraw = new ArrayList(); ArrayList yraw = new ArrayList(); ArrayList zraw = new ArrayList(); ArrayList sraw = new ArrayList(); ArrayList sxraw = new ArrayList(); ArrayList syraw = new ArrayList(); ArrayList szraw = new ArrayList(); URL url = newfile.toURI().toURL(); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); while ((s = br.readLine()) != null) { tokens = s.split("\\s+"); nvalues = tokens.length; firstName = (String) tokens[0]; if (((String) tokens[0]).length() == 0) { readraw = false; readfit = false; continue; } if ((nvalues == 4) && (!firstName.startsWith("---"))) { if ((Double.parseDouble(tokens[1]) == 0.) && (Double.parseDouble(tokens[2]) == 0.) && (Double.parseDouble(tokens[3]) == 0.)) { zerodata = true; } else { zerodata = false; } if (tokens[1].equals("NaN") || tokens[2].equals("NaN") || tokens[3].equals("NaN")) { baddata = true; } else { baddata = false; } } if (firstName.startsWith("start")) { header = s; } if (firstName.indexOf("WS") > 0) { if (name != null) { dumpData(name, fitparams, sraw, sxraw, syraw, szraw, yraw, zraw, xraw); } name = tokens[0]; readraw = false; readfit = false; zerodata = false; baddata = false; harpdata = false; fitparams.clear(); xraw.clear(); yraw.clear(); zraw.clear(); sraw.clear(); sxraw.clear(); syraw.clear(); szraw.clear(); } if (firstName.startsWith("Area")) ; if (firstName.startsWith("Ampl")) ; if (firstName.startsWith("Mean")) ; if (firstName.startsWith("Sigma")) { fitparams.add(new Double(Double.parseDouble(tokens[3]))); fitparams.add(new Double(Double.parseDouble(tokens[1]))); fitparams.add(new Double(Double.parseDouble(tokens[5]))); } if (firstName.startsWith("Offset")) ; if (firstName.startsWith("Slope")) ; if ((firstName.equals("Position")) && (((String) tokens[2]).equals("Raw"))) { readraw = true; continue; } if ((firstName.equals("Position")) && (((String) tokens[2]).equals("Fit"))) { readfit = true; continue; } if ((firstName.contains("Harp"))) { xraw.clear(); yraw.clear(); zraw.clear(); sraw.clear(); sxraw.clear(); syraw.clear(); szraw.clear(); harpdata = true; readraw = true; name = tokens[0]; continue; } if (firstName.startsWith("---")) continue; if (harpdata == true) { if (((String) tokens[0]).length() != 0) { if (firstName.startsWith("PVLogger")) { try { PVLoggerID = new Integer(Integer.parseInt(tokens[2])); } catch (NumberFormatException e) { } } else { sxraw.add(new Double(Double.parseDouble(tokens[0]))); xraw.add(new Double(Double.parseDouble(tokens[1]))); syraw.add(new Double(Double.parseDouble(tokens[2]))); yraw.add(new Double(Double.parseDouble(tokens[3]))); szraw.add(new Double(Double.parseDouble(tokens[4]))); zraw.add(new Double(Double.parseDouble(tokens[5]))); } } continue; } if (readraw && (!zerodata) && (!baddata)) { sraw.add(new Double(Double.parseDouble(tokens[0]) / Math.sqrt(2.0))); sxraw.add(new Double(Double.parseDouble(tokens[0]) / Math.sqrt(2.0))); syraw.add(new Double(Double.parseDouble(tokens[0]) / Math.sqrt(2.0))); szraw.add(new Double(Double.parseDouble(tokens[0]))); yraw.add(new Double(Double.parseDouble(tokens[1]))); zraw.add(new Double(Double.parseDouble(tokens[2]))); xraw.add(new Double(Double.parseDouble(tokens[3]))); } if (firstName.startsWith("PVLogger")) { try { PVLoggerID = new Integer(Integer.parseInt(tokens[2])); } catch (NumberFormatException e) { } } } dumpData(name, fitparams, sraw, sxraw, syraw, szraw, yraw, zraw, xraw); wiredata.add((Integer) PVLoggerID); return wiredata; }
00
Code Sample 1: protected static boolean copyFile(File src, File dest) { try { if (!dest.exists()) { dest.createNewFile(); } FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest); byte[] temp = new byte[1024 * 8]; int readSize = 0; do { readSize = fis.read(temp); fos.write(temp, 0, readSize); } while (readSize == temp.length); temp = null; fis.close(); fos.flush(); fos.close(); } catch (Exception e) { return false; } return true; } Code Sample 2: private boolean authenticate(String reply) { String user = reply.substring(0, reply.indexOf(" ")); String resp = reply.substring(reply.indexOf(" ") + 1); if (!module.users.contains(user)) { error = "so such user " + user; return false; } try { LineNumberReader secrets = new LineNumberReader(new FileReader(module.secretsFile)); String line; while ((line = secrets.readLine()) != null) { if (line.startsWith(user + ":")) { MessageDigest md4 = MessageDigest.getInstance("BrokenMD4"); md4.update(new byte[4]); md4.update(line.substring(line.indexOf(":") + 1).getBytes("US-ASCII")); md4.update(challenge.getBytes("US-ASCII")); String hash = Util.base64(md4.digest()); if (hash.equals(resp)) { secrets.close(); return true; } } } secrets.close(); } catch (Exception e) { logger.fatal(e.toString()); error = "server configuration error"; return false; } error = "authentication failure for module " + module.name; return false; }
00
Code Sample 1: private static void copyObjects(File[] source, String target) { for (int i = 0; i < source.length; i++) { try { File inputFile = source[i]; File outputFile = new File(target + source[i].getName()); 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 ex) { Logger.error(ex.getClass() + " " + ex.getMessage()); for (int j = 0; j < ex.getStackTrace().length; j++) Logger.error(" " + ex.getStackTrace()[j].toString()); ex.printStackTrace(); } } } Code Sample 2: public String parse() { try { URL url = new URL(mUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; boolean flag1 = false; while ((line = reader.readLine()) != null) { line = line.trim(); if (!flag1 && line.contains("</center>")) flag1 = true; if (flag1 && line.contains("<br><center>")) break; if (flag1) { mText.append(line); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return mText.toString(); }
00
Code Sample 1: private static String getRegistrationClasses() { CentralRegistrationClass c = new CentralRegistrationClass(); String name = c.getClass().getCanonicalName().replace('.', '/').concat(".class"); try { Enumeration<URL> urlEnum = c.getClass().getClassLoader().getResources("META-INF/MANIFEST.MF"); while (urlEnum.hasMoreElements()) { URL url = urlEnum.nextElement(); String file = url.getFile(); JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); Manifest mf = jarConnection.getManifest(); Attributes attrs = (Attributes) mf.getAttributes(name); if (attrs != null) { String classes = attrs.getValue("RegistrationClasses"); return classes; } } } catch (IOException ex) { ex.printStackTrace(); } return ""; } Code Sample 2: public static String executePost(String urlStr, String content) { StringBuffer result = new StringBuffer(); try { Authentication.doIt(); URL url = new URL(urlStr); System.out.println("Host: " + url.getHost()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); System.out.println("got connection "); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); connection.setRequestProperty("Content-Length", "" + content.length()); connection.setRequestProperty("SOAPAction", "\"http://niki-bt.act.cmis.csiro.org/SMSService/SendText\""); connection.setRequestMethod("POST"); PrintWriter out = new PrintWriter(connection.getOutputStream()); out.print(content); out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { result.append(inputLine); } in.close(); out.close(); connection.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } String msg = result.toString(); if (msg != null) { int beginCut = msg.indexOf('>'); int endCut = msg.lastIndexOf('<'); if (beginCut != -1 && endCut != -1) { return msg.substring(beginCut + 1, endCut); } } return null; }
00
Code Sample 1: private File unzipArchive(File zipArchive, File outDir, String nameInZipArchive) throws IOException { File mainFile = null; ZipEntry entry = null; ZipInputStream zis = new ZipInputStream(new FileInputStream((zipArchive))); FileOutputStream fos = null; byte buffer[] = new byte[4096]; int bytesRead; while ((entry = zis.getNextEntry()) != null) { File outFile = new File(outDir, entry.getName()); if (entry.getName().equals(nameInZipArchive)) mainFile = outFile; fos = new FileOutputStream(outFile); while ((bytesRead = zis.read(buffer)) != -1) fos.write(buffer, 0, bytesRead); fos.close(); } zis.close(); return mainFile; } Code Sample 2: 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 = MessageLocalizer.getMessage("SCHEMA_CREATED_BY_OBJECT") + " [" + objectControlller + "] " + MessageLocalizer.getMessage("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) { } } } }
11
Code Sample 1: public static void copyFile(File oldFile, File newFile) throws Exception { newFile.getParentFile().mkdirs(); newFile.createNewFile(); FileChannel srcChannel = new FileInputStream(oldFile).getChannel(); FileChannel dstChannel = new FileOutputStream(newFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } Code Sample 2: public static void createModelZip(String filename, String tempdir, boolean overwrite) throws Exception { FileTools.checkOutput(filename, overwrite); BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream(filename); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); int BUFFER = 2048; byte data[] = new byte[BUFFER]; File f = new File(tempdir); for (File fs : f.listFiles()) { FileInputStream fi = new FileInputStream(fs.getAbsolutePath()); origin = new BufferedInputStream(fi, BUFFER); ZipEntry entry = new ZipEntry(fs.getName()); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) out.write(data, 0, count); out.closeEntry(); origin.close(); } out.close(); }
00
Code Sample 1: @Override protected String doInBackground(Location... params) { if (params == null || params.length == 0 || params[0] == null) { return null; } Location location = params[0]; String address = ""; String cachedAddress = DataService.GetInstance(mContext).getAddressFormLocationCache(location.getLatitude(), location.getLongitude()); if (!TextUtils.isEmpty(cachedAddress)) { address = cachedAddress; } else { StringBuilder jsonText = new StringBuilder(); HttpClient client = new DefaultHttpClient(); String url = String.format(GoogleMapAPITemplate, location.getLatitude(), location.getLongitude()); HttpGet httpGet = new HttpGet(url); try { HttpResponse response = client.execute(httpGet); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) { jsonText.append(line); } JSONObject result = new JSONObject(jsonText.toString()); String status = result.getString(GoogleMapStatusSchema.status); if (GoogleMapStatusCodes.OK.equals(status)) { JSONArray addresses = result.getJSONArray(GoogleMapStatusSchema.results); if (addresses.length() > 0) { address = addresses.getJSONObject(0).getString(GoogleMapStatusSchema.formatted_address); if (!TextUtils.isEmpty(currentBestLocationAddress)) { DataService.GetInstance(mContext).updateAddressToLocationCache(location.getLatitude(), location.getLongitude(), currentBestLocationAddress); } } } } else { Log.e("Error", "Failed to get address via google map API."); } } catch (ClientProtocolException e) { e.printStackTrace(); Toast.makeText(mContext, "Failed to get location.", Toast.LENGTH_SHORT).show(); } catch (IOException e) { Toast.makeText(mContext, "Failed to get location.", Toast.LENGTH_SHORT).show(); } catch (JSONException e) { Toast.makeText(mContext, "Failed to get location.", Toast.LENGTH_SHORT).show(); } } return address; } Code Sample 2: public static String loadWebsiteHtmlCode(String url, String useragent) { HttpClient httpClient = new DefaultHttpClient(); HttpGet getMethod = new HttpGet(url); String htmlCode = ""; if (useragent != null) { getMethod.setHeader("user-agent", useragent); } try { HttpResponse resp = httpClient.execute(getMethod); int statusCode = resp.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { logger.debug("Method failed!" + statusCode); } htmlCode = EntityUtils.toString(resp.getEntity()); } catch (Exception e) { logger.debug("Fatal protocol violation: " + e.getMessage()); logger.trace(e); } return htmlCode; }
00
Code Sample 1: public static void copy(final File src, final File dst) throws IOException, IllegalArgumentException { long fileSize = src.length(); final FileInputStream fis = new FileInputStream(src); final FileOutputStream fos = new FileOutputStream(dst); final FileChannel in = fis.getChannel(), out = fos.getChannel(); try { long offs = 0, doneCnt = 0; final long copyCnt = Math.min(65536, fileSize); do { doneCnt = in.transferTo(offs, copyCnt, out); offs += doneCnt; fileSize -= doneCnt; } while (fileSize > 0); } finally { try { in.close(); } catch (final IOException e) { } try { out.close(); } catch (final IOException e) { } try { fis.close(); } catch (final IOException e) { } try { fos.close(); } catch (final IOException e) { } src.delete(); } } Code Sample 2: private void loadConfig(ServletContext ctx, String configFileName) { Digester digester = new Digester(); digester.push(this); digester.addFactoryCreate("pagespy/server", new AbstractObjectCreationFactory() { public Object createObject(Attributes attrs) { String className = attrs.getValue("className"); try { return Class.forName(className).newInstance(); } catch (Exception e) { throw new ClassCastException("Error al instanciar " + className); } } }); digester.addSetProperty("pagespy/server/param", "name", "value"); digester.addSetNext("pagespy/server", "setServer", PageSpyServer.class.getName()); digester.addCallMethod("pagespy/ignored-patterns", "setIgnorePattern", 1); digester.addCallParam("pagespy/ignored-patterns", 0); digester.addFactoryCreate("pagespy/property-setters/setter", new AbstractObjectCreationFactory() { public Object createObject(Attributes attrs) { String className = attrs.getValue("className"); try { return Class.forName(className).newInstance(); } catch (Exception e) { throw new ClassCastException("Error al instanciar " + className); } } }); digester.addSetNext("pagespy/property-setters/setter", "addPropertySetter", PagePropertySetter.class.getName()); digester.addFactoryCreate("pagespy/page-replacers/replacer", new AbstractObjectCreationFactory() { public Object createObject(Attributes attrs) { String className = attrs.getValue("className"); try { return Class.forName(className).newInstance(); } catch (Exception e) { throw new ClassCastException("Error al instanciar " + className); } } }); digester.addSetNext("pagespy/page-replacers/replacer", "addPageReplacer", PageReplacer.class.getName()); digester.addFactoryCreate("pagespy/properties-panel", new AbstractObjectCreationFactory() { public Object createObject(Attributes attrs) { String className = attrs.getValue("className"); try { return Class.forName(className).newInstance(); } catch (Exception e) { throw new ClassCastException("Error al instanciar " + className); } } }); digester.addSetNext("pagespy/properties-panel", "setPropertiesPanel", PagePanel.class.getName()); try { this.getLogger().info("Initializing " + configFileName); URL url = ctx.getResource(configFileName); if (url == null) { url = this.getClass().getResource(configFileName); } digester.parse(url.openStream()); } catch (Exception e) { this.getLogger().error("Error parsing configuration file.", e); throw new RuntimeException(e); } }
11
Code Sample 1: public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { PrintWriter writer = null; InputStream is = null; FileOutputStream fos = null; try { writer = response.getWriter(); } catch (IOException ex) { log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } String filename = request.getHeader("X-File-Name"); try { is = request.getInputStream(); fos = new FileOutputStream(new File(realPath + filename)); IOUtils.copy(is, fos); response.setStatus(response.SC_OK); writer.print("{success: true}"); } catch (FileNotFoundException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); } Code Sample 2: private void writeFile(FileInputStream inFile, FileOutputStream outFile) throws IOException { byte[] buf = new byte[2048]; int read; while ((read = inFile.read(buf)) > 0 && !stopped) outFile.write(buf, 0, read); inFile.close(); }
00
Code Sample 1: public static void BubbleSortDouble2(double[] num) { int last_exchange; int right_border = num.length - 1; do { last_exchange = 0; for (int j = 0; j < num.length - 1; j++) { if (num[j] > num[j + 1]) { double temp = num[j]; num[j] = num[j + 1]; num[j + 1] = temp; last_exchange = j; } } right_border = last_exchange; } while (right_border > 0); } Code Sample 2: public void write(File file) throws Exception { if (medooFile != null) { if (!medooFile.renameTo(file)) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(medooFile)); out = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(in, out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } } } else { throw new FileUploadException("Cannot write uploaded file to disk!"); } }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public static void notify(String msg) throws Exception { String url = "http://api.clickatell.com/http/sendmsg?"; url = add(url, "user", user); url = add(url, "password", password); url = add(url, "api_id", apiId); url = add(url, "to", to); url = add(url, "text", msg); URL u = new URL(url); URLConnection c = u.openConnection(); InputStream is = c.getInputStream(); IOUtils.copy(is, System.out); IOUtils.closeQuietly(is); }
00
Code Sample 1: private ShaderProgram loadShaderProgram() { ShaderProgram sp = null; String vertexProgram = null; String fragmentProgram = null; Shader[] shaders = new Shader[2]; try { ClassLoader cl = this.getClass().getClassLoader(); URL url = cl.getResource("Shaders/simple.vert"); System.out.println("url " + url); InputStream inputSteam = cl.getResourceAsStream("Shaders/simple.vert"); Reader reader = null; if (inputSteam != null) { reader = new InputStreamReader(inputSteam); } else { File file = new File("lib"); URL url2 = new URL("jar:file:" + file.getAbsolutePath() + "/j3d-vrml97-i3mainz.jar!/Shaders/simple.vert"); InputStream inputSteam2 = url2.openStream(); reader = new InputStreamReader(inputSteam2); } char[] buffer = new char[10000]; int len = reader.read(buffer); vertexProgram = new String(buffer); vertexProgram = vertexProgram.substring(0, len); } catch (Exception e) { System.err.println("could'nt load simple.vert"); e.printStackTrace(); } try { ClassLoader cl = this.getClass().getClassLoader(); URL url = cl.getResource("Shaders/simple.frag"); System.out.println("url " + url); InputStream inputSteam = cl.getResourceAsStream("Shaders/simple.frag"); Reader reader = null; if (inputSteam != null) { reader = new InputStreamReader(inputSteam); } else { File file = new File("lib"); URL url2 = new URL("jar:file:" + file.getAbsolutePath() + "/j3d-vrml97-i3mainz.jar!/Shaders/simple.frag"); InputStream inputSteam2 = url2.openStream(); reader = new InputStreamReader(inputSteam2); } char[] buffer = new char[10000]; int len = reader.read(buffer); fragmentProgram = new String(buffer); fragmentProgram = fragmentProgram.substring(0, len); } catch (Exception e) { System.err.println("could'nt load simple.frag"); e.printStackTrace(); } if (vertexProgram != null && fragmentProgram != null) { shaders[0] = new SourceCodeShader(Shader.SHADING_LANGUAGE_GLSL, Shader.SHADER_TYPE_VERTEX, vertexProgram); shaders[1] = new SourceCodeShader(Shader.SHADING_LANGUAGE_GLSL, Shader.SHADER_TYPE_FRAGMENT, fragmentProgram); sp = new GLSLShaderProgram(); sp.setShaders(shaders); } return sp; } Code Sample 2: public GGProvinces getListProvinces() throws IllegalStateException, GGException, Exception { List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("method", "gg.photos.geo.getListProvinces")); qparams.add(new BasicNameValuePair("key", this.key)); String url = REST_URL + "?" + URLEncodedUtils.format(qparams, "UTF-8"); URI uri = new URI(url); HttpGet httpget = new HttpGet(uri); HttpResponse response = httpClient.execute(httpget); int status = response.getStatusLine().getStatusCode(); errorCheck(response, status); InputStream content = response.getEntity().getContent(); GGProvinces provinces = JAXB.unmarshal(content, GGProvinces.class); return provinces; }