label int64 0 1 | func1 stringlengths 173 53.1k | func2 stringlengths 173 53.1k | id int64 0 901k |
|---|---|---|---|
1 | public void save(File f, AudioFileFormat.Type t) throws IOException { if (t.getExtension().equals("raw")) { IOUtils.copy(makeInputStream(), new FileOutputStream(f)); } else { AudioSystem.write(makeStream(), t, f); } } | public static void decompress(File apps,File f) throws IOException{ String filename=f.getName(); filename=filename.substring(0,filename.length()-PACK_FILE_SUFFIX.length()); File dir=new File(apps,filename); if(!dir.exists()){ dir.mkdirs(); } if(dir.isDirectory()){ JarFile jar=new JarFile(f); Enumeration<JarEntry> files=jar.entries(); while(files.hasMoreElements()){ JarEntry je=files.nextElement(); if(je.isDirectory()){ File item=new File(dir,je.getName()); item.mkdirs(); }else{ File item=new File(dir,je.getName()); item.getParentFile().mkdirs(); InputStream input=jar.getInputStream(je); FileOutputStream out=new FileOutputStream(item); IOUtils.copy(input, out); input.close(); out.close(); } //System.out.println(je.isDirectory() + je.getName()); } } } | 13,600 |
1 | public static void streamCopyFile(File srcFile, File destFile) { try { FileInputStream fi = new FileInputStream(srcFile); FileOutputStream fo = new FileOutputStream(destFile); byte[] buf = new byte[1024]; int readLength = 0; while (readLength != -1) { readLength = fi.read(buf); if (readLength != -1) { fo.write(buf, 0, readLength); } } fo.close(); fi.close(); } catch (Exception e) { } } | 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); } } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } | 13,601 |
0 | public static void copyFileByNIO(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } | @SuppressWarnings("unused") private GraphicalViewer createGraphicalViewer(Composite parent) { GraphicalViewer viewer = new ScrollingGraphicalViewer(); viewer.createControl(parent); viewer.getControl().setBackground(parent.getBackground()); viewer.setRootEditPart(new ScalableFreeformRootEditPart()); viewer.setKeyHandler(new GraphicalViewerKeyHandler(viewer)); getEditDomain().addViewer(viewer); getSite().setSelectionProvider(viewer); viewer.setEditPartFactory(getEditPartFactory()); viewer.setContents(getContent()); return viewer; } | 13,602 |
1 | protected String getTextResponse(String address, boolean ignoreResponseCode) throws Exception { URL url = new URL(address); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setUseCaches(false); BufferedReader in = null; try { con.connect(); if (!ignoreResponseCode) { assertEquals(HttpURLConnection.HTTP_OK, con.getResponseCode()); } in = new BufferedReader(new InputStreamReader(con.getInputStream())); StringBuilder builder = new StringBuilder(); String inputLine = null; while ((inputLine = in.readLine()) != null) { builder.append(inputLine); } return builder.toString(); } finally { if (in != null) { in.close(); } con.disconnect(); } } | public static byte[] getbytes(String host, int port, String cmd) { String result = "GetHtmlFromServer no answer"; String tmp = ""; result = ""; try { tmp = "http://" + host + ":" + port + "/" + cmd; URL url = new URL(tmp); if (1 == 2) { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { result += str; } in.close(); return result.getBytes(); } else { HttpURLConnection c = (HttpURLConnection) url.openConnection(); c.setConnectTimeout(2 * 1000); c.setRequestMethod("GET"); c.connect(); int amt = c.getContentLength(); InputStream in = c.getInputStream(); MojasiWriter writer = new MojasiWriter(); byte[] buff = new byte[256]; while (writer.size() < amt) { int got = in.read(buff); if (got < 0) break; writer.pushBytes(buff, got); } in.close(); c.disconnect(); return writer.getBytes(); } } catch (MalformedURLException e) { System.err.println(tmp + " " + e); } catch (IOException e) { ; } return null; } | 13,603 |
1 | public static String sha1(String clearText, String seed) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update((seed + clearText).getBytes()); return convertToHex(md.digest()); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } | 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; } } | 13,604 |
1 | private boolean exportPKC(String keystoreLocation, String pw) { boolean created = false; KeyStore ks = null; try { ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(new BufferedInputStream(new FileInputStream(keystoreLocation)), pw.toCharArray()); } catch (Exception e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error reading keystore file when exporting PKC: " + e.getMessage()); } return false; } Certificate cert = null; try { cert = ks.getCertificate("saws"); } catch (KeyStoreException e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error reading certificate from keystore file when exporting PKC: " + e.getMessage()); } return false; } try { StringBuffer sb = new StringBuffer("-----BEGIN CERTIFICATE-----\n"); sb.append(new String(Base64.encode(cert.getEncoded()))); sb.append("\n-----END CERTIFICATE-----\n"); OutputStreamWriter wr = new OutputStreamWriter(new FileOutputStream("sawsSigningPKC.crt")); wr.write(new String(sb)); wr.flush(); wr.close(); created = true; } catch (Exception e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error exporting PKC file: " + e.getMessage()); } return false; } return created; } | public static void copyFileByNIO(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } | 13,605 |
0 | private ModelDefinition buildModel(String name) { ModelDefinition model = null; URL url = ResourceLocator.locateBinaryModel(name); InputStream is = null; if (url == null) { url = ResourceLocator.locateTextModel(name); try { is = url.openStream(); model = buildModelFromText(name, is); File file = ResourceLocator.replaceExtension(url, ResourceLocator.BINARY_MODEL_EXTENSION); BinaryExporter.getInstance().save(model, file); } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } } else { try { is = url.openStream(); model = (ModelDefinition) BinaryImporter.getInstance().load(is); } catch (IOException e) { e.printStackTrace(); } } return model; } | public URL grabCover(String artist, String title) { if (idf.jCheckBox3.isSelected()) { println("Searching cover for: " + artist); artist = artist.trim(); URL url = null; int searchnumber = 0; try { URL yahoo = new URL("http://www.gracenote.com/search/?query=" + artist.toLowerCase().replaceAll(" ", "+") + "&search_type=artist"); BufferedReader in = new BufferedReader(new InputStreamReader(yahoo.openStream())); println("" + yahoo); String inputLine; String line = ""; while ((inputLine = in.readLine()) != null) line += inputLine; boolean notfound = true; String cut = line; while (notfound) { String search = "<div class=\"album-name large\"><strong>Album:</strong> <a href=\""; if (line.indexOf(search) <= 0) { println("Artist was not found!"); in.close(); return null; } cut = cut.substring(cut.indexOf(search) + search.length()); String test = cut.substring(0, cut.indexOf("\"")); URL secondurl = new URL("http://www.gracenote.com" + test); println("" + secondurl); BufferedReader secin = new BufferedReader(new InputStreamReader(secondurl.openStream())); String secinputLine; String secline = ""; while ((secinputLine = secin.readLine()) != null) secline += secinputLine; if (!(secline.toUpperCase().indexOf(title.toUpperCase()) < 0 && idf.jCheckBox2.isSelected())) { String secsearch = "<div class=\"album-image\"><img src=\""; String seccut = secline.substring(secline.indexOf(secsearch) + secsearch.length()); seccut = seccut.substring(0, seccut.indexOf("\"")); url = new URL("http://www.gracenote.com" + seccut); if (url.toString().indexOf("covers/default") <= 0 && url.toString().indexOf("covers/") > 0) { notfound = false; } } secin.close(); } in.close(); println(url.toString()); } catch (Exception e) { println("error " + e + "\n"); e.printStackTrace(); } return url; } else { return null; } } | 13,606 |
0 | public static Map<VariableLengthInteger, ElementDescriptor> readDescriptors(URL url) throws IOException, XMLStreamException { if (url == null) { throw new IllegalArgumentException("url is null"); } InputStream stream = new BufferedInputStream(url.openStream()); try { return readDescriptors(stream); } finally { try { stream.close(); } catch (IOException ignored) { } } } | public long copyDirAllFilesToDirectoryRecursive(String baseDirStr, String destDirStr, boolean copyOutputsRtIDsDirs) throws Exception { long plussQuotaSize = 0; if (baseDirStr.endsWith(sep)) { baseDirStr = baseDirStr.substring(0, baseDirStr.length() - 1); } if (destDirStr.endsWith(sep)) { destDirStr = destDirStr.substring(0, destDirStr.length() - 1); } FileUtils.getInstance().createDirectory(destDirStr); BufferedInputStream in = null; BufferedOutputStream out = null; byte dataBuff[] = new byte[bufferSize]; File baseDir = new File(baseDirStr); baseDir.mkdirs(); if (!baseDir.exists()) { createDirectory(baseDirStr); } if ((baseDir.exists()) && (baseDir.isDirectory())) { String[] entryList = baseDir.list(); if (entryList.length > 0) { for (int pos = 0; pos < entryList.length; pos++) { String entryName = entryList[pos]; String oldPathFileName = baseDirStr + sep + entryName; File entryFile = new File(oldPathFileName); if (entryFile.isFile()) { String newPathFileName = destDirStr + sep + entryName; File newFile = new File(newPathFileName); if (newFile.exists()) { plussQuotaSize -= newFile.length(); newFile.delete(); } in = new BufferedInputStream(new FileInputStream(oldPathFileName), bufferSize); out = new BufferedOutputStream(new FileOutputStream(newPathFileName), bufferSize); int readLen; while ((readLen = in.read(dataBuff)) > 0) { out.write(dataBuff, 0, readLen); plussQuotaSize += readLen; } out.flush(); in.close(); out.close(); } if (entryFile.isDirectory()) { boolean enableCopyDir = false; if (copyOutputsRtIDsDirs) { enableCopyDir = true; } else { if (entryFile.getParentFile().getName().equals("outputs")) { enableCopyDir = false; } else { enableCopyDir = true; } } if (enableCopyDir) { plussQuotaSize += this.copyDirAllFilesToDirectoryRecursive(baseDirStr + sep + entryName, destDirStr + sep + entryName, copyOutputsRtIDsDirs); } } } } } else { throw new Exception("Base dir not exist ! baseDirStr = (" + baseDirStr + ")"); } return plussQuotaSize; } | 13,607 |
1 | public static void copyFile(File sourceFile, File destFile) throws IOException { FileChannel inputFileChannel = new FileInputStream(sourceFile).getChannel(); FileChannel outputFileChannel = new FileOutputStream(destFile).getChannel(); long offset = 0L; long length = inputFileChannel.size(); final long MAXTRANSFERBUFFERLENGTH = 1024 * 1024; try { for (; offset < length; ) { offset += inputFileChannel.transferTo(offset, MAXTRANSFERBUFFERLENGTH, outputFileChannel); inputFileChannel.position(offset); } } finally { try { outputFileChannel.close(); } catch (Exception ignore) { } try { inputFileChannel.close(); } catch (IOException ignore) { } } } | 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); System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: " + "existing file was not overwritten."); } 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) { ; } } } | 13,608 |
0 | public void imagesParserAssesmentItem(int file, int currentquestion, Resource resTemp) { NodeList nl = null; Node n = null; NamedNodeMap nnp = null; Node nsrc = null; URL url = null; String sFilename = ""; String sNewPath = ""; int index; String sOldPath = ""; try { if (file == 1) { nl = doc.getElementsByTagName("img"); } else { nl = doc_[currentquestion].getElementsByTagName("img"); } for (int i = 0; i < nl.getLength(); i++) { n = nl.item(i); nnp = n.getAttributes(); nsrc = nnp.getNamedItem("src"); String sTemp = nsrc.getTextContent(); url = new URL("file", "localhost", sTemp); sOldPath = url.getPath(); sOldPath = sOldPath.replace('/', File.separatorChar); int indexFirstSlash = sOldPath.indexOf(File.separatorChar); String sSourcePath = sOldPath.substring(indexFirstSlash + 1); index = sOldPath.lastIndexOf(File.separatorChar); sFilename = sOldPath.substring(index + 1); sNewPath = this.sTempLocation + sFilename; FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(sSourcePath).getChannel(); out = new FileOutputStream(sNewPath).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } if (file == 1) { sXml = sXml.replace(nsrc.getTextContent(), sFilename); } else { sXml_[currentquestion] = sXml_[currentquestion].replace(nsrc.getTextContent(), sFilename); } lsImages.add(sFilename); resTemp.addFile(sFilename); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } | public static String plainToMD(LoggerCollection loggerCol, String input) { byte[] byteHash = null; MessageDigest md = null; StringBuilder md4result = new StringBuilder(); try { md = MessageDigest.getInstance("MD4", new BouncyCastleProvider()); md.reset(); md.update(input.getBytes("UnicodeLittleUnmarked")); byteHash = md.digest(); for (int i = 0; i < byteHash.length; i++) { md4result.append(Integer.toHexString(0xFF & byteHash[i])); } } catch (UnsupportedEncodingException ex) { loggerCol.logException(CLASSDEBUG, "de.searchworkorange.lib.misc.hash.MD4Hash", Level.FATAL, ex); } catch (NoSuchAlgorithmException ex) { loggerCol.logException(CLASSDEBUG, "de.searchworkorange.lib.misc.hash.MD4Hash", Level.FATAL, ex); } return (md4result.toString()); } | 13,609 |
0 | static Properties readAllProps(Hashtable<?, ?> env) throws IOException { Properties props = new Properties(); if (env != null) { props = mergProps(props, env); } props = mergSysProps(props, System.getProperties()); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Enumeration<?> resources = classLoader.getResources(jndiProp); while (resources.hasMoreElements()) { URL url = (URL) resources.nextElement(); InputStream fis = url.openStream(); Properties resource = new Properties(); resource.load(fis); fis.close(); props = mergProps(props, resource); } return props; } | private void copyFile(URL from, File to) { try { InputStream is = from.openStream(); IOUtils.copy(is, new FileOutputStream(to)); } catch (IOException e) { e.printStackTrace(); } } | 13,610 |
1 | public void performOk(final IProject project, final TomcatPropertyPage page) { page.setPropertyValue("tomcat.jdbc.driver", c_drivers.getText()); page.setPropertyValue("tomcat.jdbc.url", url.getText()); page.setPropertyValue("tomcat.jdbc.user", username.getText()); page.setPropertyValue("tomcat.jdbc.password", password.getText()); File lib = new File(page.tomcatHome.getText(), "lib"); if (!lib.exists()) { lib = new File(new File(page.tomcatHome.getText(), "common"), "lib"); if (!lib.exists()) { Logger.log(Logger.ERROR, "Not properly location of Tomcat Home at :: " + lib); throw new IllegalStateException("Not properly location of Tomcat Home"); } } final File conf = new File(page.tomcatHome.getText(), "conf/Catalina/localhost"); if (!conf.exists()) { final boolean create = NexOpenUIActivator.getDefault().getTomcatConfProperty(); if (create) { if (Logger.getLog().isDebugEnabled()) { Logger.getLog().debug("Create directory " + conf); } try { conf.mkdirs(); } catch (final SecurityException se) { Logger.getLog().error("Retrieved a Security exception creating " + conf, se); Logger.log(Logger.ERROR, "Not created " + conf + " directory. Not enough privilegies. Message :: " + se.getMessage()); } } } String str_driverLibrary = LIBRARIES.get(c_drivers.getText()); if ("<mysql_driver>".equals(str_driverLibrary)) { str_driverLibrary = NexOpenUIActivator.getDefault().getMySQLDriver(); } final File driverLibrary = new File(lib, str_driverLibrary); if (!driverLibrary.exists()) { InputStream driver = null; FileOutputStream fos = null; try { driver = AppServerPropertyPage.toInputStream(new Path("jdbc/" + str_driverLibrary)); fos = new FileOutputStream(driverLibrary); IOUtils.copy(driver, fos); } catch (IOException e) { Logger.log(Logger.ERROR, "Could not copy the driver jar file to Tomcat", e); } finally { try { if (driver != null) { driver.close(); driver = null; } if (fos != null) { fos.flush(); fos.close(); fos = null; } } catch (IOException e) { } } } page.processTomcatCfg(c_drivers.getText(), url.getText(), username.getText(), password.getText()); } | public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { if (System.getProperty("os.name").toUpperCase().indexOf("WIN") != -1) { int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } } else { inChannel.transferTo(0, inChannel.size(), outChannel); } } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } | 13,611 |
1 | public static synchronized String encrypt(String plaintext) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = null; md = MessageDigest.getInstance("SHA"); md.update(plaintext.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } | protected String insertCommand(String command) throws ServletException { String digest; try { MessageDigest md = MessageDigest.getInstance(m_messagedigest_algorithm); md.update(command.getBytes()); byte bytes[] = new byte[20]; m_random.nextBytes(bytes); md.update(bytes); digest = bytesToHex(md.digest()); } catch (NoSuchAlgorithmException e) { throw new ServletException("NoSuchAlgorithmException while " + "attempting to generate graph ID: " + e); } String id = System.currentTimeMillis() + "-" + digest; m_map.put(id, command); return id; } | 13,612 |
0 | private void createHomeTab() { Tabpanel homeTab = new Tabpanel(); windowContainer.addWindow(homeTab, Msg.getMsg(EnvWeb.getCtx(), "Home").replaceAll("&", ""), false); Portallayout portalLayout = new Portallayout(); portalLayout.setWidth("100%"); portalLayout.setHeight("100%"); portalLayout.setStyle("position: absolute; overflow: auto"); homeTab.appendChild(portalLayout); Portalchildren portalchildren = null; int currentColumnNo = 0; String sql = "SELECT COUNT(DISTINCT COLUMNNO) " + "FROM PA_DASHBOARDCONTENT " + "WHERE (AD_CLIENT_ID=0 OR AD_CLIENT_ID=?) AND ISACTIVE='Y'"; int noOfCols = DB.getSQLValue(null, sql, EnvWeb.getCtx().getAD_Client_ID()); int width = noOfCols <= 0 ? 100 : 100 / noOfCols; sql = "SELECT x.*, m.AD_MENU_ID " + "FROM PA_DASHBOARDCONTENT x " + "LEFT OUTER JOIN AD_MENU m ON x.AD_WINDOW_ID=m.AD_WINDOW_ID " + "WHERE (x.AD_CLIENT_ID=0 OR x.AD_CLIENT_ID=?) AND x.ISACTIVE='Y' " + "AND x.zulfilepath not in (?, ?, ?) " + "ORDER BY x.COLUMNNO, x.AD_CLIENT_ID, x.LINE "; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, null); pstmt.setInt(1, EnvWeb.getCtx().getAD_Client_ID()); pstmt.setString(2, ACTIVITIES_PATH); pstmt.setString(3, FAVOURITES_PATH); pstmt.setString(4, VIEWS_PATH); rs = pstmt.executeQuery(); while (rs.next()) { int columnNo = rs.getInt("ColumnNo"); if (portalchildren == null || currentColumnNo != columnNo) { portalchildren = new Portalchildren(); portalLayout.appendChild(portalchildren); portalchildren.setWidth(width + "%"); portalchildren.setStyle("padding: 5px"); currentColumnNo = columnNo; } Panel panel = new Panel(); panel.setStyle("margin-bottom:10px"); panel.setTitle(rs.getString("Name")); String description = rs.getString("Description"); if (description != null) panel.setTooltiptext(description); String collapsible = rs.getString("IsCollapsible"); panel.setCollapsible(collapsible.equals("Y")); panel.setBorder("normal"); portalchildren.appendChild(panel); Panelchildren content = new Panelchildren(); panel.appendChild(content); boolean panelEmpty = true; String htmlContent = rs.getString("HTML"); if (htmlContent != null) { StringBuffer result = new StringBuffer("<html><head>"); URL url = getClass().getClassLoader().getResource("org/compiere/images/PAPanel.css"); InputStreamReader ins; try { ins = new InputStreamReader(url.openStream()); BufferedReader bufferedReader = new BufferedReader(ins); String cssLine; while ((cssLine = bufferedReader.readLine()) != null) result.append(cssLine + "\n"); } catch (IOException e1) { logger.log(Level.SEVERE, e1.getLocalizedMessage(), e1); } result.append("</head><body><div class=\"content\">\n"); result.append(stripHtml(htmlContent, false) + "<br>\n"); result.append("</div>\n</body>\n</html>\n</html>"); Html html = new Html(); html.setContent(result.toString()); content.appendChild(html); panelEmpty = false; } int AD_Window_ID = rs.getInt("AD_Window_ID"); if (AD_Window_ID > 0) { int AD_Menu_ID = rs.getInt("AD_Menu_ID"); ToolBarButton btn = new ToolBarButton(String.valueOf(AD_Menu_ID)); MMenu menu = new MMenu(EnvWeb.getCtx(), AD_Menu_ID, null); btn.setLabel(menu.getName()); btn.addEventListener(Events.ON_CLICK, this); content.appendChild(btn); panelEmpty = false; } int PA_Goal_ID = rs.getInt("PA_Goal_ID"); if (PA_Goal_ID > 0) { StringBuffer result = new StringBuffer("<html><head>"); URL url = getClass().getClassLoader().getResource("org/compiere/images/PAPanel.css"); InputStreamReader ins; try { ins = new InputStreamReader(url.openStream()); BufferedReader bufferedReader = new BufferedReader(ins); String cssLine; while ((cssLine = bufferedReader.readLine()) != null) result.append(cssLine + "\n"); } catch (IOException e1) { logger.log(Level.SEVERE, e1.getLocalizedMessage(), e1); } result.append("</head><body><div class=\"content\">\n"); result.append(renderGoals(PA_Goal_ID, content)); result.append("</div>\n</body>\n</html>\n</html>"); Html html = new Html(); html.setContent(result.toString()); content.appendChild(html); panelEmpty = false; } String url = rs.getString("ZulFilePath"); if (url != null) { try { Component component = Executions.createComponents(url, content, null); if (component != null) { if (component instanceof DashboardPanel) { DashboardPanel dashboardPanel = (DashboardPanel) component; if (!dashboardPanel.getChildren().isEmpty()) { content.appendChild(dashboardPanel); dashboardRunnable.add(dashboardPanel); panelEmpty = false; } } else { content.appendChild(component); panelEmpty = false; } } } catch (Exception e) { logger.log(Level.WARNING, "Failed to create components. zul=" + url, e); } } if (panelEmpty) panel.detach(); } } catch (Exception e) { logger.log(Level.WARNING, "Failed to create dashboard content", e); } finally { Util.closeCursor(pstmt, rs); } registerWindow(homeTab); if (!portalLayout.getDesktop().isServerPushEnabled()) portalLayout.getDesktop().enableServerPush(true); dashboardRunnable.refreshDashboard(); dashboardThread = new Thread(dashboardRunnable, "UpdateInfo"); dashboardThread.setDaemon(true); dashboardThread.start(); } | public void execute() throws BuildException { Project proj = getProject(); if (templateFile == null) throw new BuildException("Template file not set"); if (targetFile == null) throw new BuildException("Target file not set"); try { File template = new File(templateFile); File target = new File(targetFile); if (!template.exists()) throw new BuildException("Template file does not exist " + template.toString()); if (!template.canRead()) throw new BuildException("Cannot read template file: " + template.toString()); if (((!append) && (!overwrite)) && (!target.exists())) throw new BuildException("Target file already exists and append and overwrite are false " + target.toString()); if (VERBOSE) { System.out.println("ProcessTemplate: tmpl in " + template.toString()); System.out.println("ProcessTemplate: file out " + target.toString()); } BufferedReader reader = new BufferedReader(new FileReader(template)); BufferedWriter writer = new BufferedWriter(new FileWriter(targetFile, append)); parse(reader, writer); writer.flush(); writer.close(); } catch (Exception e) { if (VERBOSE) e.printStackTrace(); throw new BuildException(e); } } | 13,613 |
1 | public void jsFunction_extract(ScriptableFile outputFile) throws IOException, FileSystemException, ArchiveException { InputStream is = file.jsFunction_createInputStream(); OutputStream output = outputFile.jsFunction_createOutputStream(); BufferedInputStream buf = new BufferedInputStream(is); ArchiveInputStream input = ScriptableZipArchive.getFactory().createArchiveInputStream(buf); try { long count = 0; while (input.getNextEntry() != null) { if (count == offset) { IOUtils.copy(input, output); break; } count++; } } finally { input.close(); output.close(); is.close(); } } | public static void copyFile(final File in, final File out) throws IOException { final FileChannel inChannel = new FileInputStream(in).getChannel(); final FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (final IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } | 13,614 |
1 | public void criarQuestaoDiscursiva(QuestaoDiscursiva q) throws SQLException { PreparedStatement stmt = null; String sql = "INSERT INTO discursiva (id_questao,gabarito) VALUES (?,?)"; try { stmt = conexao.prepareStatement(sql); stmt.setInt(1, q.getIdQuestao()); stmt.setString(2, q.getGabarito()); stmt.executeUpdate(); conexao.commit(); } catch (SQLException e) { conexao.rollback(); throw e; } } | public void addStadium(Stadium stadium) throws StadiumException { Connection conn = ConnectionManager.getManager().getConnection(); if (findStadiumBy_N_C(stadium.getName(), stadium.getCity()) != -1) throw new StadiumException("Stadium already exists"); try { PreparedStatement stm = conn.prepareStatement(Statements.INSERT_STADIUM); conn.setAutoCommit(false); stm.setString(1, stadium.getName()); stm.setString(2, stadium.getCity()); stm.executeUpdate(); int id = getMaxId(); TribuneLogic logic = TribuneLogic.getInstance(); for (Tribune trib : stadium.getTribunes()) { int tribuneId = logic.addTribune(trib); if (tribuneId != -1) { stm = conn.prepareStatement(Statements.INSERT_STAD_TRIBUNE); stm.setInt(1, id); stm.setInt(2, tribuneId); stm.executeUpdate(); } } } catch (SQLException e) { try { conn.rollback(); conn.setAutoCommit(true); } catch (SQLException e1) { e1.printStackTrace(); } throw new StadiumException("Adding stadium failed", e); } try { conn.commit(); conn.setAutoCommit(true); } catch (SQLException e) { e.printStackTrace(); } } | 13,615 |
0 | private HashMap<String, GCVote> getVotes(ArrayList<String> waypoints, boolean blnSleepBeforeDownload) { if (blnSleepBeforeDownload) { try { Thread.sleep(PACKET_SLEEP_TIME); } catch (InterruptedException e) { e.printStackTrace(); } } final String strWaypoints = this.join(waypoints, ","); try { String strParameters = URLEncoder.encode("waypoints", "UTF-8") + "=" + URLEncoder.encode(strWaypoints, "UTF-8"); if (this.mstrUsername.length() > 0) { strParameters += "&" + URLEncoder.encode("userName", "UTF-8") + "=" + URLEncoder.encode(this.mstrUsername, "UTF-8"); if (this.mstrPassword.length() > 0) { strParameters += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(this.mstrPassword, "UTF-8"); } } final URL url = new URL(BASE_URL_GET_VOTE); URLConnection conn = url.openConnection(); conn.setDoOutput(true); final OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream()); osw.write(strParameters); osw.flush(); final SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); saxParserFactory.setValidating(false); saxParserFactory.setNamespaceAware(true); final SAXParser saxParser = saxParserFactory.newSAXParser(); final XMLReader xmlReader = saxParser.getXMLReader(); final GCVoteHandler gcVoteHandler = new GCVoteHandler(); xmlReader.setContentHandler(gcVoteHandler); xmlReader.parse(new InputSource(new InputStreamReader(conn.getInputStream()))); return gcVoteHandler.getVotes(); } catch (Exception e) { e.printStackTrace(); return null; } } | private void saveFile(Folder folder, Object key, InputStream stream) throws FileManagerException { File file = new File(folder, key.toString()); LOGGER.debug("Writing file: " + file.getAbsolutePath()); Writer writer = null; Writer encodedWriter = null; try { encodedWriter = new OutputStreamWriter(new FileOutputStream(file), getEncodeCharset()); IOUtils.copy(stream, encodedWriter, getDecodeCharset()); LOGGER.info("saveFile(), decode charset: " + getDecodeCharset() + ", encode charset: " + getEncodeCharset()); } catch (IOException e) { throw new FileManagerException("Unable to write to file: " + file.getAbsolutePath(), e); } finally { try { encodedWriter.close(); } catch (IOException e) { throw new FileManagerException("Unable to write to file: " + file.getAbsolutePath(), e); } } } | 13,616 |
1 | public static void main(String[] args) throws Exception { InputStream in = null; try { in = new URL(args[0]).openStream(); IOUtils.copyBytes(in, System.out, 4096, false); } finally { IOUtils.closeStream(in); } } | public static boolean copyFileChannel(final File _fileFrom, final File _fileTo, final boolean _append) { FileChannel srcChannel = null; FileChannel dstChannel = null; try { srcChannel = new FileInputStream(_fileFrom).getChannel(); dstChannel = new FileOutputStream(_fileTo, _append).getChannel(); if (_append) { dstChannel.transferFrom(srcChannel, dstChannel.size(), srcChannel.size()); } else { dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } srcChannel.close(); dstChannel.close(); } catch (final IOException e) { return false; } finally { try { if (srcChannel != null) { srcChannel.close(); } } catch (final IOException _evt) { FuLog.error(_evt); } try { if (dstChannel != null) { dstChannel.close(); } } catch (final IOException _evt) { FuLog.error(_evt); } } return true; } | 13,617 |
0 | public boolean saveNote(NoteData n) { String query; try { conn.setAutoCommit(false); Statement stmt = null; ResultSet rset = null; stmt = conn.createStatement(); query = "select * from notes where noteid = " + n.getID(); rset = stmt.executeQuery(query); if (rset.next()) { query = "UPDATE notes SET title = '" + escapeCharacters(n.getTitle()) + "', keywords = '" + escapeCharacters(n.getKeywords()) + "' WHERE noteid = " + n.getID(); try { stmt.executeUpdate(query); } catch (SQLException e) { e.printStackTrace(); conn.rollback(); conn.setAutoCommit(true); return false; } LinkedList<FieldData> fields = n.getFields(); ListIterator<FieldData> iter = fields.listIterator(0); FieldData f = null; PreparedStatement pstmt = conn.prepareStatement("UPDATE fielddata SET data = ? WHERE noteid = ? AND fieldid = ?"); try { while (iter.hasNext()) { f = iter.next(); if (f instanceof FieldDataImage) { System.out.println("field is an image."); pstmt.setBytes(1, ((FieldDataImage) f).getDataBytes()); } else { System.out.println("field is not an image"); pstmt.setString(1, f.getData()); } pstmt.setInt(2, n.getID()); pstmt.setInt(3, f.getID()); pstmt.execute(); } } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } query = "DELETE FROM links WHERE (note1id = " + n.getID() + " OR note2id = " + n.getID() + ")"; try { stmt.execute(query); } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } Vector<Link> associations = n.getAssociations(); ListIterator<Link> itr = associations.listIterator(); Link association = null; pstmt = conn.prepareStatement("INSERT INTO links (note1id, note2id) VALUES (?, ?)"); try { while (itr.hasNext()) { association = itr.next(); pstmt.setInt(1, n.getID()); pstmt.setInt(2, association.getID()); pstmt.execute(); } } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } } else { query = "INSERT INTO notes (templateid, title, keywords) VALUES (" + n.getTemplate().getID() + ", '" + escapeCharacters(n.getTitle()) + "', '" + escapeCharacters(n.getKeywords()) + "')"; try { stmt.executeUpdate(query); } catch (SQLException e) { e.printStackTrace(); conn.rollback(); conn.setAutoCommit(true); return false; } LinkedList<FieldData> fields = n.getFields(); ListIterator<FieldData> iter = fields.listIterator(0); FieldData f = null; n.setID(Integer.parseInt(executeMySQLGet("SELECT LAST_INSERT_ID()"))); PreparedStatement pstmt; try { pstmt = conn.prepareStatement("INSERT INTO fielddata (noteid, fieldid, data) VALUES (?,?,?)"); while (iter.hasNext()) { f = iter.next(); if (f instanceof FieldDataImage) { System.out.println("field is an image."); pstmt.setBytes(3, ((FieldDataImage) f).getDataBytes()); } else { System.out.println("field is not an image"); pstmt.setString(3, f.getData()); } pstmt.setInt(1, n.getID()); pstmt.setInt(2, f.getID()); pstmt.execute(); } } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } Vector<Link> assoc = n.getAssociations(); Iterator<Link> itr = assoc.listIterator(); Link l = null; pstmt = conn.prepareStatement("INSERT INTO links (note1id, note2id) VALUES (?,?)"); try { while (itr.hasNext()) { l = itr.next(); pstmt.setInt(1, n.getID()); pstmt.setInt(2, l.getID()); pstmt.execute(); } } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } } conn.commit(); conn.setAutoCommit(true); } catch (SQLException ex) { ex.printStackTrace(); return false; } return true; } | public static void main(String[] args) throws Exception { if (args.length < 2) { System.err.println("Usage: java SOAPClient4XG " + "http://soapURL soapEnvelopefile.xml" + " [SOAPAction]"); System.err.println("SOAPAction is optional."); System.exit(1); } String SOAPUrl = args[0]; String xmlFile2Send = args[1]; String SOAPAction = ""; if (args.length > 2) SOAPAction = args[2]; URL url = new URL(SOAPUrl); URLConnection connection = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) connection; FileInputStream fin = new FileInputStream(xmlFile2Send); ByteArrayOutputStream bout = new ByteArrayOutputStream(); copy(fin, bout); fin.close(); byte[] b = bout.toByteArray(); httpConn.setRequestProperty("Content-Length", String.valueOf(b.length)); httpConn.setRequestProperty("Content-Type", "text/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; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); } | 13,618 |
1 | public static void copyFile(String sIn, String sOut) throws IOException { File fIn = new File(sIn); File fOut = new File(sOut); FileChannel fcIn = new FileInputStream(fIn).getChannel(); FileChannel fcOut = new FileOutputStream(fOut).getChannel(); try { fcIn.transferTo(0, fcIn.size(), fcOut); } catch (IOException e) { throw e; } finally { if (fcIn != null) fcIn.close(); if (fcOut != null) fcOut.close(); } fOut.setReadable(fIn.canRead()); fOut.setWritable(fIn.canWrite()); fOut.setExecutable(fIn.canExecute()); } | @Test(dependsOnMethods = { "getSize" }) public void download() throws IOException { FileObject typica = fsManager.resolveFile("s3://" + bucketName + "/jonny.zip"); File localCache = File.createTempFile("vfs.", ".s3-test"); FileOutputStream out = new FileOutputStream(localCache); IOUtils.copy(typica.getContent().getInputStream(), out); Assert.assertEquals(localCache.length(), typica.getContent().getSize()); localCache.delete(); } | 13,619 |
0 | public final void run() { active = true; String s = findcachedir(); uid = getuid(s); try { File file = new File(s + "main_file_cache.dat"); if (file.exists() && file.length() > 0x3200000L) file.delete(); cache_dat = new RandomAccessFile(s + "main_file_cache.dat", "rw"); for (int j = 0; j < 5; j++) cache_idx[j] = new RandomAccessFile(s + "main_file_cache.idx" + j, "rw"); } catch (Exception exception) { exception.printStackTrace(); } for (int i = threadliveid; threadliveid == i; ) { if (socketreq != 0) { try { socket = new Socket(socketip, socketreq); } catch (Exception _ex) { socket = null; } socketreq = 0; } else if (threadreq != null) { Thread thread = new Thread(threadreq); thread.setDaemon(true); thread.start(); thread.setPriority(threadreqpri); threadreq = null; } else if (dnsreq != null) { try { dns = InetAddress.getByName(dnsreq).getHostName(); } catch (Exception _ex) { dns = "unknown"; } dnsreq = null; } else if (savereq != null) { if (savebuf != null) try { FileOutputStream fileoutputstream = new FileOutputStream(s + savereq); fileoutputstream.write(savebuf, 0, savelen); fileoutputstream.close(); } catch (Exception _ex) { } if (waveplay) { wave = s + savereq; waveplay = false; } if (midiplay) { midi = s + savereq; midiplay = false; } savereq = null; } else if (urlreq != null) { try { urlstream = new DataInputStream((new URL(mainapp.getCodeBase(), urlreq)).openStream()); } catch (Exception _ex) { urlstream = null; } urlreq = null; } try { Thread.sleep(50L); } catch (Exception _ex) { } } } | public static String harvestForUser(Node userNode, String alias, Boolean all) { FTPClient client = new FTPClient(); OutputStream outStream = null; Calendar filterCal = Calendar.getInstance(); filterCal.set(Calendar.DAY_OF_MONTH, filterCal.get(Calendar.DAY_OF_MONTH) - 1); Date aDayAgo = filterCal.getTime(); String outputRecord = ""; try { Session session = CustomSystemSession.create(r); client.connect(ftpHostname); client.login(ftpUsername, ftpPassword); FTPFile[] users = client.listFiles(); if (users != null) { for (FTPFile user : users) { String userName = user.getName(); if (alias.equals(userName)) { outputRecord += "Found account " + userName + ".\n"; client.changeWorkingDirectory("/" + userName + "/"); FTPFile[] experiments = client.listFiles(); if (experiments != null && userNode != null) { for (FTPFile experiment : experiments) { String experimentName = experiment.getName(); outputRecord += "Exploring " + userName + "/" + experimentName + ".\n"; client.changeWorkingDirectory("/" + userName + "/" + experimentName + "/"); FTPFile[] datasets = client.listFiles(); if (datasets != null) { for (FTPFile dataset : datasets) { String datasetName = dataset.getName(); outputRecord += "Exploring " + userName + "/" + experimentName + "/" + datasetName + ".\n"; client.changeWorkingDirectory("/" + userName + "/" + experimentName + "/" + datasetName + "/"); Date collectionDate = dataset.getTimestamp().getTime(); if (collectionDate.after(aDayAgo) || all) { FTPFile[] images = client.listFiles(); if (images != null) { for (FTPFile image : images) { outputRecord += processImage(userName, experimentName, datasetName, collectionDate, image, client, userNode, session); } } } } } } } } } } client.logout(); } catch (IOException ioe) { log.info("Error communicating with FTP server."); log.error("Error communicating with FTP server.", ioe); ioe.printStackTrace(); } catch (RepositoryException ioe) { log.info("Error communicating with repository."); log.error("Error communicating with repository.", ioe); ioe.printStackTrace(); } finally { IOUtils.closeQuietly(outStream); try { client.disconnect(); } catch (IOException e) { log.error("Problem disconnecting from FTP server", e); } } return outputRecord; } | 13,620 |
0 | @Override protected String doWget(final URL url, final boolean post, final boolean ignore, final String... post_data) throws Exception { String msg = ""; InputStream in = null; OutputStream out = null; String data = null; try { final URLConnection urlcon = url.openConnection(); if (post) { boolean key = false; for (final String s : post_data) { msg += URLEncoder.encode(s, "UTF-8"); if (key = !key) { msg += "="; } else { msg += "&"; } } urlcon.setDoOutput(true); out = urlcon.getOutputStream(); out.write(msg.getBytes()); } in = urlcon.getInputStream(); data = ignore ? null : ""; int len; final byte[] buffer = new byte[1023]; while ((len = in.read(buffer)) >= 0) { if (!ignore) { data += new String(buffer, 0, len); } } if (LogHelper.isLogLevelEnabled(LogLevel.DEBUG, DefaultCommunicationHelper.class)) { LogHelper.log(DefaultCommunicationHelper.class, LogLevel.DEBUG, "WGET= URL[" + url.toString() + "?" + msg + "] RETURN[" + data + "]"); } return data; } catch (final Exception ex) { LogHelper.log(DefaultCommunicationHelper.class, LogLevel.WARN, "An error occurred while submitting " + msg + " request to " + url.toString() + " with the following data: " + data, ex); throw ex; } finally { if (in != null) { try { in.close(); } catch (final Exception e) { LogHelper.log(DefaultCommunicationHelper.class, LogLevel.DEBUG, "An error occurred while closing an input stream", e); } } if (out != null) { try { out.close(); } catch (final Exception e) { LogHelper.log(DefaultCommunicationHelper.class, LogLevel.DEBUG, "An error occurred while closing an output stream", e); } } } } | private String sendToServer(String request) throws IOException { Log.d("test", "request body " + request); String result = null; maybeCreateHttpClient(); HttpPost post = new HttpPost(Config.APP_BASE_URI); post.addHeader("Content-Type", "text/vnd.aexp.json.req"); post.setEntity(new StringEntity(request)); HttpResponse resp = httpClient.execute(post); int status = resp.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_OK) throw new IOException("HTTP status: " + Integer.toString(status)); DataInputStream is = new DataInputStream(resp.getEntity().getContent()); result = is.readLine(); return result; } | 13,621 |
0 | private long getNextHighValue() throws Exception { Connection con = null; PreparedStatement psGetHighValue = null; PreparedStatement psUpdateHighValue = null; ResultSet rs = null; long high = -1L; int isolation = -1; DBOperation dbo = factory.createDBOperation(POOL_NAME); try { con = dbo.getConnection(); psGetHighValue = con.prepareStatement(strGetHighValue); psGetHighValue.setString(1, this.name); for (rs = psGetHighValue.executeQuery(); rs.next(); ) { high = rs.getLong("high"); } psUpdateHighValue = con.prepareStatement(strUpdateHighValue); psUpdateHighValue.setLong(1, high + 1L); psUpdateHighValue.setString(2, this.name); psUpdateHighValue.executeUpdate(); } catch (SQLException e) { if (con != null) { con.rollback(); } throw e; } finally { if (psUpdateHighValue != null) { psUpdateHighValue.close(); } close(dbo, psGetHighValue, rs); } return high; } | public static String crypt(String strPassword, String strSalt) { try { StringTokenizer st = new StringTokenizer(strSalt, "$"); st.nextToken(); byte[] abyPassword = strPassword.getBytes(); byte[] abySalt = st.nextToken().getBytes(); MessageDigest _md = MessageDigest.getInstance("MD5"); _md.update(abyPassword); _md.update(MAGIC.getBytes()); _md.update(abySalt); MessageDigest md2 = MessageDigest.getInstance("MD5"); md2.update(abyPassword); md2.update(abySalt); md2.update(abyPassword); byte[] abyFinal = md2.digest(); for (int n = abyPassword.length; n > 0; n -= 16) { _md.update(abyFinal, 0, n > 16 ? 16 : n); } abyFinal = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; for (int j = 0, i = abyPassword.length; i != 0; i >>>= 1) { if ((i & 1) == 1) _md.update(abyFinal, j, 1); else _md.update(abyPassword, j, 1); } StringBuffer sbPasswd = new StringBuffer(); sbPasswd.append(MAGIC); sbPasswd.append(new String(abySalt)); sbPasswd.append('$'); abyFinal = _md.digest(); for (int n = 0; n < 1000; n++) { MessageDigest md3 = MessageDigest.getInstance("MD5"); if ((n & 1) != 0) md3.update(abyPassword); else md3.update(abyFinal); if ((n % 3) != 0) md3.update(abySalt); if ((n % 7) != 0) md3.update(abyPassword); if ((n & 1) != 0) md3.update(abyFinal); else md3.update(abyPassword); abyFinal = md3.digest(); } int[] anFinal = new int[] { (abyFinal[0] & 0x7f) | (abyFinal[0] & 0x80), (abyFinal[1] & 0x7f) | (abyFinal[1] & 0x80), (abyFinal[2] & 0x7f) | (abyFinal[2] & 0x80), (abyFinal[3] & 0x7f) | (abyFinal[3] & 0x80), (abyFinal[4] & 0x7f) | (abyFinal[4] & 0x80), (abyFinal[5] & 0x7f) | (abyFinal[5] & 0x80), (abyFinal[6] & 0x7f) | (abyFinal[6] & 0x80), (abyFinal[7] & 0x7f) | (abyFinal[7] & 0x80), (abyFinal[8] & 0x7f) | (abyFinal[8] & 0x80), (abyFinal[9] & 0x7f) | (abyFinal[9] & 0x80), (abyFinal[10] & 0x7f) | (abyFinal[10] & 0x80), (abyFinal[11] & 0x7f) | (abyFinal[11] & 0x80), (abyFinal[12] & 0x7f) | (abyFinal[12] & 0x80), (abyFinal[13] & 0x7f) | (abyFinal[13] & 0x80), (abyFinal[14] & 0x7f) | (abyFinal[14] & 0x80), (abyFinal[15] & 0x7f) | (abyFinal[15] & 0x80) }; to64(sbPasswd, anFinal[0] << 16 | anFinal[6] << 8 | anFinal[12], 4); to64(sbPasswd, anFinal[1] << 16 | anFinal[7] << 8 | anFinal[13], 4); to64(sbPasswd, anFinal[2] << 16 | anFinal[8] << 8 | anFinal[14], 4); to64(sbPasswd, anFinal[3] << 16 | anFinal[9] << 8 | anFinal[15], 4); to64(sbPasswd, anFinal[4] << 16 | anFinal[10] << 8 | anFinal[5], 4); to64(sbPasswd, anFinal[11], 2); return sbPasswd.toString(); } catch (NoSuchAlgorithmException e) { return null; } } | 13,622 |
1 | static void copy(String src, String dest) throws IOException { File ifp = new File(src); File ofp = new File(dest); if (ifp.exists() == false) { throw new IOException("file '" + src + "' does not exist"); } FileInputStream fis = new FileInputStream(ifp); FileOutputStream fos = new FileOutputStream(ofp); byte[] b = new byte[1024]; while (fis.read(b) > 0) fos.write(b); fis.close(); fos.close(); } | private void writeFile(FileInputStream inFile, FileOutputStream outFile) throws IOException { byte[] buf = new byte[2048]; int read; while ((read = inFile.read(buf)) > 0) outFile.write(buf, 0, read); inFile.close(); } | 13,623 |
1 | private static void insertModuleInEar(File fromEar, File toEar, String moduleType, String moduleName, String contextRoot) throws Exception { ZipInputStream earFile = new ZipInputStream(new FileInputStream(fromEar)); FileOutputStream fos = new FileOutputStream(toEar); ZipOutputStream tempZip = new ZipOutputStream(fos); ZipEntry next = earFile.getNextEntry(); while (next != null) { ByteArrayOutputStream content = new ByteArrayOutputStream(); byte[] data = new byte[30000]; int numberread; while ((numberread = earFile.read(data)) != -1) { content.write(data, 0, numberread); } if (next.getName().equals("META-INF/application.xml")) { content = insertModule(earFile, next, content, moduleType, moduleName, contextRoot); next = new ZipEntry("META-INF/application.xml"); } tempZip.putNextEntry(next); tempZip.write(content.toByteArray()); next = earFile.getNextEntry(); } earFile.close(); tempZip.close(); fos.close(); } | protected void copy(File source, File destination) throws IOException { final FileChannel inChannel = new FileInputStream(source).getChannel(); final FileChannel outChannel = new FileOutputStream(destination).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } | 13,624 |
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); } } } | @Override public void handle(HttpExchange http) throws IOException { Headers reqHeaders = http.getRequestHeaders(); Headers respHeader = http.getResponseHeaders(); respHeader.add("Content-Type", "text/plain"); http.sendResponseHeaders(200, 0); PrintWriter console = new PrintWriter(System.err); PrintWriter web = new PrintWriter(http.getResponseBody()); PrintWriter out = new PrintWriter(new YWriter(web, console)); out.println("### " + new Date() + " ###"); out.println("Method: " + http.getRequestMethod()); out.println("Protocol: " + http.getProtocol()); out.println("RemoteAddress.HostName: " + http.getRemoteAddress().getHostName()); for (String key : reqHeaders.keySet()) { out.println("* \"" + key + "\""); for (String v : reqHeaders.get(key)) { out.println("\t" + v); } } InputStream in = http.getRequestBody(); if (in != null) { out.println(); IOUtils.copyTo(new InputStreamReader(in), out); in.close(); } out.flush(); out.close(); } | 13,625 |
0 | public String upload(String urlString, ByteArrayOutputStream dataStream) { HttpURLConnection conn = null; DataOutputStream dos = null; String exsistingFileName = "blah.png"; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; try { URL url = new URL(urlString); conn = (HttpURLConnection) url.openConnection(); conn.setInstanceFollowRedirects(false); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"aFile\";" + " filename=\"" + exsistingFileName + "\"" + lineEnd); dos.writeBytes(lineEnd); dos.write(dataStream.toByteArray()); dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); dos.flush(); dos.close(); return conn.getHeaderField("location"); } catch (MalformedURLException ex) { log.log(Level.INFO, "From ServletCom CLIENT REQUEST:" + ex); } catch (IOException ioe) { log.log(Level.INFO, "From ServletCom CLIENT REQUEST:" + ioe); } return null; } | public static byte[] encode(String origin, String algorithm) throws NoSuchAlgorithmException { String resultStr = null; resultStr = new String(origin); MessageDigest md = MessageDigest.getInstance(algorithm); md.update(resultStr.getBytes()); return md.digest(); } | 13,626 |
0 | protected ResourceBundle loadBundle(String prefix) { URL url = Thread.currentThread().getContextClassLoader().getResource(prefix + ".properties"); if (url != null) { try { return new PropertyResourceBundle(url.openStream()); } catch (IOException e) { throw ThrowableManagerRegistry.caught(e); } } return null; } | private String hash(String message) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e) { throw new AssertionError("Can't find the SHA1 algorithm in the java.security package"); } String saltString = String.valueOf(12345); md.update(saltString.getBytes()); md.update(message.getBytes()); byte[] digestBytes = md.digest(); StringBuffer digestSB = new StringBuffer(); for (int i = 0; i < digestBytes.length; i++) { int lowNibble = digestBytes[i] & 0x0f; int highNibble = (digestBytes[i] >> 4) & 0x0f; digestSB.append(Integer.toHexString(highNibble)); digestSB.append(Integer.toHexString(lowNibble)); } String digestStr = digestSB.toString().trim(); return digestStr; } | 13,627 |
0 | @SuppressWarnings("unchecked") private void appendAttachments(final Part part) throws MessagingException, IOException { if (part.isMimeType("message/*")) { JcrMessage jcrMessage = new JcrMessage(); Message attachedMessage = null; if (part.getContent() instanceof Message) { attachedMessage = (Message) part.getContent(); } else { attachedMessage = new MStorMessage(null, (InputStream) part.getContent()); } jcrMessage.setFlags(attachedMessage.getFlags()); jcrMessage.setHeaders(attachedMessage.getAllHeaders()); jcrMessage.setReceived(attachedMessage.getReceivedDate()); jcrMessage.setExpunged(attachedMessage.isExpunged()); jcrMessage.setMessage(attachedMessage); messages.add(jcrMessage); } else if (part.isMimeType("multipart/*")) { Multipart multi = (Multipart) part.getContent(); for (int i = 0; i < multi.getCount(); i++) { appendAttachments(multi.getBodyPart(i)); } } else if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition()) || StringUtils.isNotEmpty(part.getFileName())) { JcrFile attachment = new JcrFile(); String name = null; if (StringUtils.isNotEmpty(part.getFileName())) { name = part.getFileName(); for (JcrFile attach : attachments) { if (attach.getName().equals(name)) { return; } } } else { String[] contentId = part.getHeader("Content-Id"); if (contentId != null && contentId.length > 0) { name = contentId[0]; } else { name = "attachment"; } } int count = 0; for (JcrFile attach : attachments) { if (attach.getName().equals(name)) { count++; } } if (count > 0) { name += "_" + count; } attachment.setName(name); ByteArrayOutputStream pout = new ByteArrayOutputStream(); IOUtils.copy(part.getInputStream(), pout); attachment.setDataProvider(new JcrDataProviderImpl(TYPE.BYTES, pout.toByteArray())); attachment.setMimeType(part.getContentType()); attachment.setLastModified(java.util.Calendar.getInstance()); attachments.add(attachment); } } | private static Pair<URL, DTObject> loadRecruitersConf(URL url) throws ExternalConfigException, SyntaxException, IOException { Assert.notNullArg(url, "resourceName may not be null"); InputStream is = url.openStream(); try { Object value = ObjectParser.parse(is); if (!(value instanceof DTObject)) { throw new ExternalConfigException("The global value in " + url + " must be a DTObject"); } return new Pair<URL, DTObject>(url, (DTObject) value); } finally { is.close(); } } | 13,628 |
1 | public void testReaderWriterUC2() throws Exception { String inFile = "test_data/mri.png"; String outFile = "test_output/mri__smooth_testReaderWriter.png"; itkImageFileReaderUC2_Pointer reader = itkImageFileReaderUC2.itkImageFileReaderUC2_New(); itkImageFileWriterUC2_Pointer writer = itkImageFileWriterUC2.itkImageFileWriterUC2_New(); reader.SetFileName(inFile); writer.SetFileName(outFile); writer.SetInput(reader.GetOutput()); writer.Update(); } | public static void copyFile(File src, File dest) throws IOException { FileInputStream fIn; FileOutputStream fOut; FileChannel fIChan, fOChan; long fSize; MappedByteBuffer mBuf; fIn = new FileInputStream(src); fOut = new FileOutputStream(dest); 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(); } | 13,629 |
0 | public static void writeFullImageToStream(Image scaledImage, String javaFormat, OutputStream os) throws IOException { BufferedImage bufImage = new BufferedImage(scaledImage.getWidth(null), scaledImage.getHeight(null), BufferedImage.TYPE_BYTE_BINARY); Graphics gr = bufImage.getGraphics(); gr.drawImage(scaledImage, 0, 0, null); gr.dispose(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ImageIO.write(bufImage, javaFormat, bos); IOUtils.copyStreams(new ByteArrayInputStream(bos.toByteArray()), os); } | private String send(String method, String contentType, String urlStr, String body) throws MalformedURLException, IOException { HttpURLConnection postCon = (HttpURLConnection) new URL(getUrl(urlStr)).openConnection(); postCon.setRequestMethod(method); postCon.setDoOutput(true); postCon.setDoInput(true); if (cookie != null) { postCon.setRequestProperty("Cookie", cookie); if (contentType != null) { postCon.setRequestProperty("Content-type", contentType); } postCon.setRequestProperty("Content-Length", body == null ? "0" : Integer.toString(body.length())); } if (body != null) { OutputStream os = postCon.getOutputStream(); OutputStreamWriter out = new OutputStreamWriter(os); out.write(body); out.close(); } InputStream is = null; try { is = postCon.getInputStream(); } catch (IOException ioe) { is = postCon.getErrorStream(); } int resCode = postCon.getResponseCode(); if (resCode == 201 || resCode == 202) { String loc = postCon.getHeaderField("Location"); System.out.println("loc:" + loc); return loc; } StringBuffer sb = StreamUtil.readStream(is); return sb.toString(); } | 13,630 |
0 | private void load() throws SQLException { Connection conn = null; Statement stmt = null; try { conn = FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); ClearData.clearTables(stmt); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (100, 'Person')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (101, 'john')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (200, 'Dog')"); stmt.executeQuery("select setval('objects_objectid_seq', 1000)"); stmt.executeUpdate("insert into ClassLinkTypes (LinkName, LinkType) values ('hasa', 2)"); stmt.executeUpdate("insert into ObjectLinks (ObjectId, LinkName, LinkToObject) values (100, 'isa', 1)"); stmt.executeUpdate("insert into ObjectLinks (ObjectId, LinkName, LinkToObject) values (101, 'instance', 100)"); stmt.executeUpdate("insert into ObjectLinks (ObjectId, LinkName, LinkToObject) values (200, 'isa', 1)"); stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('LEFT-WALL', '1', 'AV+', 1)"); stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('john', '1', 'S+ | DO-', 1)"); stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('a', '1', 'D+', 1)"); stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('dog', '1', '[D-] & (S+ | DO-)', 200)"); stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('have', '1', 'S- & AV- & DO+', 1)"); stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values " + " ('English', 'third singular', 1, 'have', 'has', TRUE)"); stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('S', 1)"); stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('DO', 3)"); stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('AV', 7)"); stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('D', 10)"); stmt.executeUpdate("insert into Articles (ArticleName, Dereference) values ('a', 2)"); stmt.executeUpdate("insert into FrameSlots (SlotName) values ('actor')"); stmt.executeUpdate("insert into FrameSlots (SlotName) values ('object')"); stmt.executeUpdate("insert into Verbs (VerbName, Type, SubjectSlot, IndirectObjectSlot, PredicateNounSlot) values ('have', 1, 'actor', '', 'object')"); stmt.executeQuery("select setval('instructions_instructionid_seq', 1)"); stmt.executeUpdate("insert into Instructions (Type, ExecuteString, FrameSlot, Operator, LinkName, ObjectId, AttributeName) " + "values (3, 'link %actor hasa %object', null, 0, null, null, null)"); stmt.executeQuery("select setval('transactions_transactionid_seq', 1)"); stmt.executeUpdate("insert into Transactions (InstructionId, Description) values (2, 'have - link')"); stmt.executeQuery("select setval('verbtransactions_verbid_seq', 1)"); stmt.executeUpdate("insert into VerbTransactions (VerbString, MoodType, TransactionId) values ('have', 1, 2)"); stmt.executeUpdate("insert into VerbConstraints (VerbId, FrameSlot, ObjectId) values (2, 'actor', 1)"); stmt.executeUpdate("insert into VerbConstraints (VerbId, FrameSlot, ObjectId) values (2, 'object', 1)"); stmt.executeUpdate("insert into ProperNouns (Noun, SenseNumber, ObjectId) values ('john', 1, 101)"); stmt.executeUpdate("update SystemProperties set value = 'Tutorial 1 Data' where name = 'DB Data Version'"); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } | public static String encrypt32(String plainText) { String str = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } str = buf.toString(); System.out.println("result: " + buf.toString()); System.out.println("result: " + buf.toString().substring(8, 24)); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return str; } return str; } | 13,631 |
0 | private String getManifestVersion() { URL url = AceTree.class.getResource("/org/rhwlab/help/messages/manifest.html"); InputStream istream = null; String s = ""; try { istream = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(istream)); while (br.ready()) { s = br.readLine(); if (s.indexOf("Manifest-Version:") == 0) { s = s.substring(17); break; } System.out.println("read: " + s); } br.close(); } catch (Exception e) { e.printStackTrace(); } return "Version: " + s + C.NL; } | private void doUpdate(final boolean notifyOnChange) { if (!validServerUrl) { return; } boolean tempBuildClean = true; List failedBuilds = new ArrayList(); try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; while ((line = in.readLine()) != null) { Matcher matcher = ROW_PARSER_PATTERN.matcher(line); if (matcher.matches() && checkAllProjects) { String project = matcher.group(GROUP_PROJECT); String status = matcher.group(GROUP_STATUS); if (status.equals(MessageUtils.getString("ccOutput.status.failed"))) { tempBuildClean = false; failedBuilds.add(project); } } } } catch (IOException e) { serverReachable = false; if (notifyOnChange) { monitor.notifyServerUnreachable(MessageUtils.getString("error.readError", new String[] { url.toString() })); } return; } if (notifyOnChange && buildClean && !tempBuildClean) { monitor.notifyBuildFailure(MessageUtils.getString("message.buildFailed", new Object[] { failedBuilds.get(0) })); } if (notifyOnChange && !buildClean && tempBuildClean) { monitor.notifyBuildFixed(MessageUtils.getString("message.allBuildsClean")); } buildClean = tempBuildClean; monitor.setStatus(buildClean); serverReachable = true; } | 13,632 |
1 | private void update() { if (VERSION.contains("dev")) return; System.out.println(updateURL_s); try { URL updateURL = new URL(updateURL_s); InputStream uis = updateURL.openStream(); InputStreamReader uisr = new InputStreamReader(uis); BufferedReader ubr = new BufferedReader(uisr); String header = ubr.readLine(); if (header.equals("GENREMANUPDATEPAGE")) { String cver = ubr.readLine(); String cdl = ubr.readLine(); if (!cver.equals(VERSION)) { System.out.println("Update available!"); int i = JOptionPane.showConfirmDialog(this, Language.get("UPDATE_AVAILABLE_MSG").replaceAll("%o", VERSION).replaceAll("%c", cver), Language.get("UPDATE_AVAILABLE_TITLE"), JOptionPane.YES_NO_OPTION); if (i == 0) { URL url = new URL(cdl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); if (connection.getResponseCode() / 100 != 2) { throw new Exception("Server error! Response code: " + connection.getResponseCode()); } int contentLength = connection.getContentLength(); if (contentLength < 1) { throw new Exception("Invalid content length!"); } int size = contentLength; File tempfile = File.createTempFile("genreman_update", ".zip"); tempfile.deleteOnExit(); RandomAccessFile file = new RandomAccessFile(tempfile, "rw"); InputStream stream = connection.getInputStream(); int downloaded = 0; ProgressWindow pwin = new ProgressWindow(this, "Downloading"); pwin.setVisible(true); pwin.setProgress(0); pwin.setText("Connecting..."); while (downloaded < size) { byte buffer[]; if (size - downloaded > 1024) { buffer = new byte[1024]; } else { buffer = new byte[size - downloaded]; } int read = stream.read(buffer); if (read == -1) break; file.write(buffer, 0, read); downloaded += read; pwin.setProgress(downloaded / size); } file.close(); System.out.println("Downloaded file to " + tempfile.getAbsolutePath()); pwin.setVisible(false); pwin.dispose(); pwin = null; ZipInputStream zin = new ZipInputStream(new FileInputStream(tempfile)); ZipEntry entry; while ((entry = zin.getNextEntry()) != null) { File outf = new File(entry.getName()); System.out.println(outf.getAbsoluteFile()); if (outf.exists()) outf.delete(); OutputStream out = new FileOutputStream(outf); byte[] buf = new byte[1024]; int len; while ((len = zin.read(buf)) > 0) { out.write(buf, 0, len); } out.close(); } JOptionPane.showMessageDialog(this, Language.get("UPDATE_SUCCESS_MSG"), Language.get("UPDATE_SUCCESS_TITLE"), JOptionPane.INFORMATION_MESSAGE); setVisible(false); if (System.getProperty("os.name").indexOf("Windows") != -1) { Runtime.getRuntime().exec("iTunesGenreArtManager.exe"); } else { Runtime.getRuntime().exec("java -jar \"iTunes Genre Art Manager.app/Contents/Resources/Java/iTunes_Genre_Art_Manager.jar\""); } System.exit(0); } else { } } ubr.close(); uisr.close(); uis.close(); } else { while (ubr.ready()) { System.out.println(ubr.readLine()); } ubr.close(); uisr.close(); uis.close(); throw new Exception("Update page had invalid header: " + header); } } catch (Exception ex) { JOptionPane.showMessageDialog(this, Language.get("UPDATE_ERROR_MSG"), Language.get("UPDATE_ERROR_TITLE"), JOptionPane.ERROR_MESSAGE); ex.printStackTrace(); } } | @Test public void testWrite() { System.out.println("write"); final File[] files = { new File(sharePath) }; System.out.println("Creating hash..."); String initHash = MD5File.MD5Directory(files[0]); System.out.println("Hash: " + initHash); Share readShare = ShareUtility.createShare(files, "TestShare"); System.out.println("Creating shares..."); final ShareFolder[] readers = ShareUtility.cropShareToParts(readShare, PARTS); System.out.println("Reading and writing shares..."); done = 0; for (int i = 0; i < PARTS; i++) { final int j = i; new Thread() { public void run() { ShareFolder part = (ShareFolder) ObjectClone.clone(readers[j]); ShareFileReader reader = new ShareFileReader(readers[j], files[0]); ShareFileWriter writer = new ShareFileWriter(part, new File("Downloads/" + readers[j].getName())); long tot = 0; byte[] b = new byte[(int) (Math.random() * 10000)]; while (tot < readers[j].getSize()) { reader.read(b); byte[] bwrite = new byte[(int) (Math.random() * 10000) + b.length]; System.arraycopy(b, 0, bwrite, 0, b.length); writer.write(bwrite, b.length); tot += b.length; } done++; System.out.println((int) (done * 100.0 / PARTS) + "% Complete"); } }.start(); } while (done < PARTS) { Thread.yield(); } File resultFile = new File("Downloads/" + readShare.getName()); System.out.println("Creating hash of written share..."); String resultHash = MD5File.MD5Directory(resultFile); System.out.println("Init hash: " + initHash); System.out.println("Result hash: " + resultHash); assertEquals(initHash, resultHash); } | 13,633 |
0 | public static List<ServerInfo> getStartedServers() { List<ServerInfo> infos = new ArrayList<ServerInfo>(); try { StringBuilder request = new StringBuilder(); request.append(url).append("/").append(displayServlet); request.append("?ingame=1"); URL objUrl = new URL(request.toString()); URLConnection urlConnect = objUrl.openConnection(); InputStream in = urlConnect.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); while (reader.ready()) { String name = reader.readLine(); String ip = reader.readLine(); int port = Integer.valueOf(reader.readLine()); ServerInfo server = new ServerInfo(name, ip, port); server.nbPlayers = Integer.valueOf(reader.readLine()); infos.add(server); } in.close(); return infos; } catch (Exception e) { return infos; } } | public boolean validateZipFile(File zipFile) { String tempdir = Config.CONTEXT.getRealPath(getBackupTempFilePath()); try { deleteTempFiles(); File ftempDir = new File(tempdir); ftempDir.mkdirs(); File tempZip = new File(tempdir + File.separator + zipFile.getName()); tempZip.createNewFile(); FileChannel ic = new FileInputStream(zipFile).getChannel(); FileChannel oc = new FileOutputStream(tempZip).getChannel(); for (long i = 0; i <= ic.size(); i++) { ic.transferTo(0, 1000000, oc); i = i + 999999; } ic.close(); oc.close(); if (zipFile != null && zipFile.getName().toLowerCase().endsWith(".zip")) { ZipFile z = new ZipFile(zipFile); ZipUtil.extract(z, new File(Config.CONTEXT.getRealPath(backupTempFilePath))); } return true; } catch (Exception e) { Logger.error(this, "Error with file", e); return false; } } | 13,634 |
1 | public void run() { try { URL url = new URL("http://pokedev.org/time.php"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); StringTokenizer s = new StringTokenizer(in.readLine()); m_day = Integer.parseInt(s.nextToken()); m_hour = Integer.parseInt(s.nextToken()); m_minutes = Integer.parseInt(s.nextToken()); in.close(); } catch (Exception e) { System.out.println("ERROR: Cannot reach time server, reverting to local time"); Calendar cal = Calendar.getInstance(); m_hour = cal.get(Calendar.HOUR_OF_DAY); m_minutes = 0; m_day = 0; } while (m_isRunning) { m_minutes = m_minutes == 59 ? 0 : m_minutes + 1; if (m_minutes == 0) { if (m_hour == 23) { incrementDay(); m_hour = 0; } else { m_hour += 1; } } m_hour = m_hour == 23 ? 0 : m_hour + 1; if (System.currentTimeMillis() - m_lastWeatherUpdate >= 3600000) { generateWeather(); m_lastWeatherUpdate = System.currentTimeMillis(); } try { Thread.sleep(60000); } catch (Exception e) { } } System.out.println("INFO: Time Service stopped"); } | 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; } | 13,635 |
0 | private PropertiesLoader(String masterFileLocation, String extraFileLocation) throws IOException { List propertiesList = new ArrayList(); ClassLoader classLoader = this.getClass().getClassLoader(); try { InputStream is = classLoader.getResourceAsStream(masterFileLocation); Properties p = new Properties(); p.load(is); is.close(); propertiesList.add(p); } catch (IOException ioex) { IOException ex = new IOException("could not load ROME master plugins file [" + masterFileLocation + "], " + ioex.getMessage()); ex.setStackTrace(ioex.getStackTrace()); throw ex; } Enumeration urls = classLoader.getResources(extraFileLocation); while (urls.hasMoreElements()) { URL url = (URL) urls.nextElement(); Properties p = new Properties(); try { InputStream is = url.openStream(); p.load(is); is.close(); } catch (IOException ioex) { IOException ex = new IOException("could not load ROME extensions plugins file [" + url.toString() + "], " + ioex.getMessage()); ex.setStackTrace(ioex.getStackTrace()); throw ex; } propertiesList.add(p); } _properties = new Properties[propertiesList.size()]; propertiesList.toArray(_properties); } | public HttpEntity execute(final HttpRequestBase request) throws IOException, ClientProtocolException { final HttpResponse response = mClient.execute(request); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK | statusCode == HttpStatus.SC_CREATED) { return response.getEntity(); } return null; } | 13,636 |
0 | public static String getMD5(String password) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); byte[] digest = md.digest(); String out = ""; for (int i = 0; i < digest.length; i++) { out += digest[i]; } return out; } catch (NoSuchAlgorithmException e) { System.err.println("Manca l'MD5 (piuttosto strano)"); } return ""; } | private void connect() throws Exception { if (client != null) throw new IllegalStateException("Already connected."); try { _logger.debug("About to connect to ftp server " + server + " port " + port); client = new FTPClient(); client.connect(server, port); if (!FTPReply.isPositiveCompletion(client.getReplyCode())) { throw new Exception("Unable to connect to FTP server " + server + " port " + port + " got error [" + client.getReplyString() + "]"); } _logger.info("Connected to ftp server " + server + " port " + port); _logger.debug(client.getReplyString()); _logger.debug("FTP server is [" + client.getSystemName() + "]"); if (!client.login(username, password)) { throw new Exception("Invalid username / password combination for FTP server " + server + " port " + port); } _logger.debug("Log in successful."); if (passiveMode) { client.enterLocalPassiveMode(); _logger.debug("Passive mode selected."); } else { client.enterLocalActiveMode(); _logger.debug("Active mode selected."); } if (binaryMode) { client.setFileType(FTP.BINARY_FILE_TYPE); _logger.debug("BINARY mode selected."); } else { client.setFileType(FTP.ASCII_FILE_TYPE); _logger.debug("ASCII mode selected."); } if (client.changeWorkingDirectory(remoteRootDir)) { _logger.debug("Changed directory to " + remoteRootDir); } else { if (client.makeDirectory(remoteRootDir)) { _logger.debug("Created directory " + remoteRootDir); if (client.changeWorkingDirectory(remoteRootDir)) { _logger.debug("Changed directory to " + remoteRootDir); } else { throw new Exception("Cannot change directory to [" + remoteRootDir + "] on FTP server " + server + " port " + port); } } else { throw new Exception("Cannot create directory [" + remoteRootDir + "] on FTP server " + server + " port " + port); } } } catch (Exception e) { disconnect(); throw e; } } | 13,637 |
0 | public static String crypt(String password, String salt) { if (salt.startsWith(magic)) { salt = salt.substring(magic.length()); } int saltEnd = salt.indexOf('$'); if (saltEnd != -1) { salt = salt.substring(0, saltEnd); } if (salt.length() > 8) { salt = salt.substring(0, 8); } MessageDigest md5_1, md5_2; try { md5_1 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } md5_1.update(password.getBytes()); md5_1.update(magic.getBytes()); md5_1.update(salt.getBytes()); try { md5_2 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } md5_2.update(password.getBytes()); md5_2.update(salt.getBytes()); md5_2.update(password.getBytes()); byte[] md5_2_digest = md5_2.digest(); int md5Size = md5_2_digest.length; int pwLength = password.length(); for (int i = pwLength; i > 0; i -= md5Size) { md5_1.update(md5_2_digest, 0, i > md5Size ? md5Size : i); } md5_2.reset(); byte[] pwBytes = password.getBytes(); for (int i = pwLength; i > 0; i >>= 1) { if ((i & 1) == 1) { md5_1.update((byte) 0); } else { md5_1.update(pwBytes[0]); } } StringBuffer output = new StringBuffer(magic); output.append(salt); output.append("$"); byte[] md5_1_digest = md5_1.digest(); byte[] saltBytes = salt.getBytes(); for (int i = 0; i < 1000; i++) { md5_2.reset(); if ((i & 1) == 1) { md5_2.update(pwBytes); } else { md5_2.update(md5_1_digest); } if (i % 3 != 0) { md5_2.update(saltBytes); } if (i % 7 != 0) { md5_2.update(pwBytes); } if ((i & 1) != 0) { md5_2.update(md5_1_digest); } else { md5_2.update(pwBytes); } md5_1_digest = md5_2.digest(); } int value; value = ((md5_1_digest[0] & 0xff) << 16) | ((md5_1_digest[6] & 0xff) << 8) | (md5_1_digest[12] & 0xff); output.append(cryptTo64(value, 4)); value = ((md5_1_digest[1] & 0xff) << 16) | ((md5_1_digest[7] & 0xff) << 8) | (md5_1_digest[13] & 0xff); output.append(cryptTo64(value, 4)); value = ((md5_1_digest[2] & 0xff) << 16) | ((md5_1_digest[8] & 0xff) << 8) | (md5_1_digest[14] & 0xff); output.append(cryptTo64(value, 4)); value = ((md5_1_digest[3] & 0xff) << 16) | ((md5_1_digest[9] & 0xff) << 8) | (md5_1_digest[15] & 0xff); output.append(cryptTo64(value, 4)); value = ((md5_1_digest[4] & 0xff) << 16) | ((md5_1_digest[10] & 0xff) << 8) | (md5_1_digest[5] & 0xff); output.append(cryptTo64(value, 4)); value = md5_1_digest[11] & 0xff; output.append(cryptTo64(value, 2)); md5_1 = null; md5_2 = null; md5_1_digest = null; md5_2_digest = null; pwBytes = null; saltBytes = null; password = salt = null; return output.toString(); } | public boolean searchEntity(String login, String password, String searcheId, OutputStream os) throws SynchronizationException { HttpClient client = new SSLHttpClient(); try { StringBuilder builder = new StringBuilder(url).append("?" + CMD_PARAM + "=" + CMD_SEARCH).append("&" + LOGIN_PARAM + "=" + URLEncoder.encode(login, "UTF-8")).append("&" + PASSWD_PARAM + "=" + URLEncoder.encode(password, "UTF-8")).append("&" + SEARCH_PARAM + "=" + searcheId); HttpGet method = httpGetMethod(builder.toString()); HttpResponse response = client.execute(method); Header header = response.getFirstHeader(HEADER_NAME); if (header != null && HEADER_VALUE.equals(HEADER_VALUE)) { int code = response.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { long expectedLength = response.getEntity().getContentLength(); InputStream is = response.getEntity().getContent(); FileUtils.writeInFile(is, os, expectedLength); return true; } else { throw new SynchronizationException("Command 'search' : HTTP error code returned." + code, SynchronizationException.ERROR_SEARCH); } } else { throw new SynchronizationException("HTTP header is invalid", SynchronizationException.ERROR_SEARCH); } } catch (Exception e) { throw new SynchronizationException("Command 'search' -> ", e, SynchronizationException.ERROR_SEARCH); } } | 13,638 |
0 | private void loadImage(URL url) { ImageData imageData; Image artworkImage = null; InputStream artworkStream = null; try { artworkStream = new BufferedInputStream(url.openStream()); imageData = new ImageLoader().load(artworkStream)[0]; Image tmpImage = new Image(getDisplay(), imageData); artworkImage = ImageUtilities.scaleImageTo(tmpImage, 128, 128); tmpImage.dispose(); } catch (Exception e) { } finally { if (artworkStream != null) { try { artworkStream.close(); } catch (IOException e) { e.printStackTrace(); } } } loadImage(artworkImage, url); } | private void album(String albumTitle, String albumNbSong, URL url) { try { if (color == SWT.COLOR_WHITE) { color = SWT.COLOR_GRAY; } else { color = SWT.COLOR_WHITE; } url.openConnection(); InputStream is = url.openStream(); Image coverPicture = new Image(this.getDisplay(), is); Composite albumComposite = new Composite(main, SWT.NONE); albumComposite.setLayout(new FormLayout()); FormData data = new FormData(); data.left = new FormAttachment(0, 5); data.right = new FormAttachment(100, -5); if (prevCompo == null) { data.top = new FormAttachment(0, 0); } else { data.top = new FormAttachment(prevCompo, 0, SWT.BOTTOM); } albumComposite.setLayoutData(data); albumComposite.setBackground(Display.getDefault().getSystemColor(color)); Label cover = new Label(albumComposite, SWT.LEFT); cover.setText("cover"); cover.setImage(coverPicture); data = new FormData(75, 75); cover.setLayoutData(data); Label title = new Label(albumComposite, SWT.CENTER); title.setFont(new Font(this.getDisplay(), "Arial", 10, SWT.BOLD)); title.setText(albumTitle); data = new FormData(); data.bottom = new FormAttachment(50, -5); data.left = new FormAttachment(cover, 5); title.setBackground(Display.getDefault().getSystemColor(color)); title.setLayoutData(data); Label nbSong = new Label(albumComposite, SWT.LEFT | SWT.BOLD); nbSong.setFont(new Font(this.getDisplay(), "Arial", 8, SWT.ITALIC)); nbSong.setText("Release date : " + albumNbSong); data = new FormData(); data.top = new FormAttachment(50, 5); data.left = new FormAttachment(cover, 5); nbSong.setBackground(Display.getDefault().getSystemColor(color)); nbSong.setLayoutData(data); prevCompo = albumComposite; } catch (Exception e) { e.printStackTrace(); } } | 13,639 |
0 | public void init() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Throwable e) { } Container c = getContentPane(); c.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS)); String[] lines = getAppletInfo().split("\n"); for (int i = 0; i < lines.length; i++) { c.add(new JLabel(lines[i])); } new Worker() { public Object construct() { Object result; try { if (getParameter("data") != null && getParameter("data").length() > 0) { NanoXMLDOMInput domi = new NanoXMLDOMInput(new UMLFigureFactory(), new StringReader(getParameter("data"))); result = domi.readObject(0); } else if (getParameter("datafile") != null) { InputStream in = null; try { URL url = new URL(getDocumentBase(), getParameter("datafile")); in = url.openConnection().getInputStream(); NanoXMLDOMInput domi = new NanoXMLDOMInput(new UMLFigureFactory(), in); result = domi.readObject(0); } finally { if (in != null) in.close(); } } else { result = null; } } catch (Throwable t) { result = t; } return result; } public void finished(Object result) { Container c = getContentPane(); c.setLayout(new BorderLayout()); c.removeAll(); initComponents(); if (result != null) { if (result instanceof Drawing) { setDrawing((Drawing) result); } else if (result instanceof Throwable) { getDrawing().add(new TextFigure(result.toString())); ((Throwable) result).printStackTrace(); } } boolean isLiveConnect; try { Class.forName("netscape.javascript.JSObject"); isLiveConnect = true; } catch (Throwable t) { isLiveConnect = false; } loadButton.setEnabled(isLiveConnect && getParameter("dataread") != null); saveButton.setEnabled(isLiveConnect && getParameter("datawrite") != null); if (isLiveConnect) { String methodName = getParameter("dataread"); if (methodName.indexOf('(') > 0) { methodName = methodName.substring(0, methodName.indexOf('(') - 1); } JSObject win = JSObject.getWindow(UMLLiveConnectApplet.this); Object data = win.call(methodName, new Object[0]); if (data instanceof String) { setData((String) data); } } c.validate(); } }.start(); } | public String computeMD5(String string) throws ServiceException { try { MessageDigest digest = MessageDigest.getInstance("md5"); digest.reset(); digest.update(string.getBytes(Invoker.ENCODING)); return convertToHex(digest.digest()); } catch (NoSuchAlgorithmException exception) { String message = "Could not create properly the MD5 digest"; log.error(message, exception); throw new ServiceException(message, exception); } catch (UnsupportedEncodingException exception) { String message = "Could not encode properly the MD5 digest"; log.error(message, exception); throw new ServiceException(message, exception); } } | 13,640 |
0 | public void createIndex(File indexDir) throws SearchLibException, IOException { if (!indexDir.mkdir()) throw new SearchLibException("directory creation failed (" + indexDir + ")"); InputStream is = null; FileWriter target = null; for (String resource : resources) { String res = rootPath + '/' + resource; is = getClass().getResourceAsStream(res); if (is == null) is = getClass().getResourceAsStream("common" + '/' + resource); if (is == null) throw new SearchLibException("Unable to find resource " + res); try { File f = new File(indexDir, resource); if (f.getParentFile() != indexDir) f.getParentFile().mkdirs(); target = new FileWriter(f); IOUtils.copy(is, target); } finally { if (target != null) target.close(); if (is != null) is.close(); } } } | public String expandTemplate(String target) throws IOException, HttpException { connect(); try { HttpGet request = new HttpGet(contextPath + target); HttpResponse response = httpexecutor.execute(request, conn); TolvenLogger.info("Response: " + response.getStatusLine(), TemplateGen.class); disconnect(); return EntityUtils.toString(response.getEntity()); } finally { disconnect(); } } | 13,641 |
1 | private void parseTemplate(File templateFile, Map dataMap) throws ContainerException { Debug.log("Parsing template : " + templateFile.getAbsolutePath(), module); Reader reader = null; try { reader = new InputStreamReader(new FileInputStream(templateFile)); } catch (FileNotFoundException e) { throw new ContainerException(e); } String targetDirectoryName = args.length > 1 ? args[1] : null; if (targetDirectoryName == null) { targetDirectoryName = target; } String targetDirectory = ofbizHome + targetDirectoryName + args[0]; File targetDir = new File(targetDirectory); if (!targetDir.exists()) { boolean created = targetDir.mkdirs(); if (!created) { throw new ContainerException("Unable to create target directory - " + targetDirectory); } } if (!targetDirectory.endsWith("/")) { targetDirectory = targetDirectory + "/"; } Writer writer = null; try { writer = new FileWriter(targetDirectory + templateFile.getName()); } catch (IOException e) { throw new ContainerException(e); } try { FreeMarkerWorker.renderTemplate(templateFile.getAbsolutePath(), reader, dataMap, writer); } catch (Exception e) { throw new ContainerException(e); } try { writer.flush(); writer.close(); } catch (IOException e) { throw new ContainerException(e); } } | @Test public void testWriteAndRead() throws Exception { JCFS.configureLoopback(dir); RFile file = new RFile("testreadwrite.txt"); RFileOutputStream out = new RFileOutputStream(file); 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); } | 13,642 |
1 | private String getHash(String string) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } md5.reset(); md5.update(string.getBytes()); byte[] result = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < result.length; i++) { hexString.append(Integer.toHexString(0xFF & result[i])); } String str = hexString.toString(); return str; } | public static String encryptString(String str) { StringBuffer sb = new StringBuffer(); int i; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(str.getBytes()); byte[] md5Bytes = md5.digest(); for (i = 0; i < md5Bytes.length; i++) { sb.append(md5Bytes[i]); } } catch (Exception e) { } return sb.toString(); } | 13,643 |
0 | public void testSavepoint4() throws Exception { Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #savepoint4 (data int)"); stmt.close(); con.setAutoCommit(false); for (int i = 0; i < 3; i++) { System.out.println("iteration: " + i); PreparedStatement pstmt = con.prepareStatement("INSERT INTO #savepoint4 (data) VALUES (?)"); pstmt.setInt(1, 1); assertTrue(pstmt.executeUpdate() == 1); Savepoint savepoint = con.setSavepoint(); assertNotNull(savepoint); assertTrue(savepoint.getSavepointId() == 1); try { savepoint.getSavepointName(); assertTrue(false); } catch (SQLException e) { } pstmt.setInt(1, 2); assertTrue(pstmt.executeUpdate() == 1); pstmt.close(); pstmt = con.prepareStatement("SELECT SUM(data) FROM #savepoint4"); ResultSet rs = pstmt.executeQuery(); assertTrue(rs.next()); assertTrue(rs.getInt(1) == 3); assertTrue(!rs.next()); pstmt.close(); rs.close(); con.rollback(savepoint); pstmt = con.prepareStatement("SELECT SUM(data) FROM #savepoint4"); rs = pstmt.executeQuery(); assertTrue(rs.next()); assertTrue(rs.getInt(1) == 1); assertTrue(!rs.next()); pstmt.close(); rs.close(); con.rollback(); } con.setAutoCommit(true); } | public void run() { try { ThreadGroup transfers = new ThreadGroup("transfers"); URL url = new URL("jar:http://jopenrpg.sourceforge.net/files/dev/pythonlib.jar!/"); JarURLConnection juc = (JarURLConnection) url.openConnection(); File top = new File(System.getProperty("user.home"), "jopenrpg"); final JarFile jarfile = juc.getJarFile(); Enumeration enumer = jarfile.entries(); while (enumer.hasMoreElements()) { final JarEntry entry = (JarEntry) enumer.nextElement(); final File f = new File(top, entry.getName()); if (entry.isDirectory()) { f.mkdirs(); } else { if (!entry.getName().startsWith("META-INF")) new Thread(transfers, new Runnable() { public void run() { try { BufferedReader br = new BufferedReader(new InputStreamReader(jarfile.getInputStream(entry))); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f))); StringBuffer buf = new StringBuffer(); while (br.ready()) { buf.append(br.read()); } bw.write(buf.toString(), 0, buf.length()); bw.close(); br.close(); } catch (Exception ex) { System.out.println(ex); } } }).start(); } } while (transfers.activeCount() > 0) yield(); SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(ReferenceManager.getInstance().getMainFrame(), "Jython libraries installed."); } }); } catch (Exception ex) { ex.printStackTrace(); } } | 13,644 |
0 | public void copyFileToFileWithPaths(String sourcePath, String destinPath) throws Exception { BufferedInputStream in = null; BufferedOutputStream out = null; byte dataBuff[] = new byte[bufferSize]; File file1 = new File(sourcePath); if (file1.exists() && (file1.isFile())) { File file2 = new File(destinPath); if (file2.exists()) { file2.delete(); } FileUtils.getInstance().createDirectory(file2.getParent()); in = new BufferedInputStream(new FileInputStream(sourcePath), bufferSize); out = new BufferedOutputStream(new FileOutputStream(destinPath), bufferSize); int readLen; while ((readLen = in.read(dataBuff)) > 0) { out.write(dataBuff, 0, readLen); } out.flush(); in.close(); out.close(); } else { throw new Exception("Source file not exist ! sourcePath = (" + sourcePath + ")"); } } | private void initBanner() { for (int k = 0; k < 3; k++) { if (bannerImg == null) { int i = getRandomId(); imageURL = NbBundle.getMessage(BottomContent.class, "URL_BannerImageLink", Integer.toString(i)); bannerURL = NbBundle.getMessage(BottomContent.class, "URL_BannerLink", Integer.toString(i)); HttpContext context = new BasicHttpContext(); context.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpGet method = new HttpGet(imageURL); try { HttpResponse response = ProxyManager.httpClient.execute(method, context); HttpEntity entity = response.getEntity(); if (entity != null) { bannerImg = new ImageIcon(ImageIO.read(entity.getContent())); EntityUtils.consume(entity); } } catch (IOException ex) { bannerImg = null; } finally { method.abort(); } } else { break; } } if (bannerImg == null) { NotifyUtil.error("Banner Error", "Application could not get banner image. Please check your internet connection.", false); } } | 13,645 |
0 | 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(); } } | public boolean isPasswordCorrect(String attempt) { try { MessageDigest digest = MessageDigest.getInstance(attempt); digest.update(salt); digest.update(attempt.getBytes("UTF-8")); byte[] attemptHash = digest.digest(); return attemptHash.equals(hash); } catch (UnsupportedEncodingException ex) { Logger.getLogger(UserRecord.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (NoSuchAlgorithmException ex) { Logger.getLogger(UserRecord.class.getName()).log(Level.SEVERE, null, ex); return false; } } | 13,646 |
1 | public static String md5(String texto) { String resultado; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(texto.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); resultado = hash.toString(16); if (resultado.length() < 32) { char chars[] = new char[32 - resultado.length()]; Arrays.fill(chars, '0'); resultado = new String(chars) + resultado; } } catch (NoSuchAlgorithmException e) { resultado = e.toString(); } return resultado; } | private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } | 13,647 |
1 | public void jsFunction_addFile(ScriptableFile infile) throws IOException { if (!infile.jsFunction_exists()) throw new IllegalArgumentException("Cannot add a file that doesn't exists to an archive"); ZipArchiveEntry entry = new ZipArchiveEntry(infile.getName()); entry.setSize(infile.jsFunction_getSize()); out.putArchiveEntry(entry); try { InputStream inStream = infile.jsFunction_createInputStream(); IOUtils.copy(inStream, out); inStream.close(); } finally { out.closeArchiveEntry(); } } | 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(); } } | 13,648 |
1 | public static void main(String[] args) { String str = "vbnjm7pexhlmof3kapi_key76bbc056cf516a844af25a763b2b8426auth_tokenff8080812374bd3f0123b60363a5230acomment_text你frob118edb4cb78b439207c2329b76395f9fmethodyupoo.photos.comments.addphoto_idff80808123922c950123b6066c946a3f"; MessageDigest md = null; String s = new String("你"); try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } md.reset(); try { md.update(str.getBytes("UTF-8")); System.out.println(new BigInteger(1, md.digest()).toString(16)); System.out.println(new BigInteger(1, s.getBytes("UTF-8")).toString(16)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } | private void handleServerIntroduction(DataPacket serverPacket) { DataPacketIterator iter = serverPacket.getDataPacketIterator(); String version = iter.nextString(); int serverReportedUDPPort = iter.nextUByte2(); _authKey = iter.nextUByte4(); _introKey = iter.nextUByte4(); _clientKey = makeClientKey(_authKey, _introKey); String passwordKey = iter.nextString(); _logger.log(Level.INFO, "Connection to version " + version + " with udp port " + serverReportedUDPPort); DataPacket packet = null; if (initUDPSocketAndStartPacketReader(_tcpSocket.getInetAddress(), serverReportedUDPPort)) { ParameterBuilder builder = new ParameterBuilder(); builder.appendUByte2(_udpSocket.getLocalPort()); builder.appendString(_user); MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ignore) { } md5.update(_serverKey.getBytes()); md5.update(passwordKey.getBytes()); md5.update(_password.getBytes()); for (byte b : md5.digest()) { builder.appendByte(b); } packet = new DataPacketImpl(ClientCommandConstants.INTRODUCTION, builder.toParameter()); } else { packet = new DataPacketImpl(ClientCommandConstants.TCP_ONLY); } sendTCPPacket(packet); } | 13,649 |
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; } | public void run() { GZIPInputStream gzipInputStream = null; try { gzipInputStream = new GZIPInputStream(pipedInputStream); IOUtils.copy(gzipInputStream, outputStream); } catch (Throwable t) { ungzipThreadThrowableList.add(t); } finally { IOUtils.closeQuietly(gzipInputStream); IOUtils.closeQuietly(pipedInputStream); } } | 13,650 |
0 | 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(); } | public static void main(String args[]) throws IOException, TrimmerException, DataStoreException { Options options = new Options(); options.addOption(new CommandLineOptionBuilder("ace", "path to ace file").isRequired(true).build()); options.addOption(new CommandLineOptionBuilder("phd", "path to phd file").isRequired(true).build()); options.addOption(new CommandLineOptionBuilder("out", "path to new ace file").isRequired(true).build()); options.addOption(new CommandLineOptionBuilder("min_sanger", "min sanger end coveage default =" + DEFAULT_MIN_SANGER_END_CLONE_CVG).build()); options.addOption(new CommandLineOptionBuilder("min_biDriection", "min bi directional end coveage default =" + DEFAULT_MIN_BI_DIRECTIONAL_END_COVERAGE).build()); options.addOption(new CommandLineOptionBuilder("ignore_threshold", "min end coveage threshold to stop trying to trim default =" + DEFAULT_IGNORE_END_CVG_THRESHOLD).build()); CommandLine commandLine; PhdDataStore phdDataStore = null; AceContigDataStore datastore = null; try { commandLine = CommandLineUtils.parseCommandLine(options, args); int minSangerEndCloneCoverage = commandLine.hasOption("min_sanger") ? Integer.parseInt(commandLine.getOptionValue("min_sanger")) : DEFAULT_MIN_SANGER_END_CLONE_CVG; int minBiDirectionalEndCoverage = commandLine.hasOption("min_biDriection") ? Integer.parseInt(commandLine.getOptionValue("min_biDriection")) : DEFAULT_MIN_BI_DIRECTIONAL_END_COVERAGE; int ignoreThresholdEndCoverage = commandLine.hasOption("ignore_threshold") ? Integer.parseInt(commandLine.getOptionValue("ignore_threshold")) : DEFAULT_IGNORE_END_CVG_THRESHOLD; AceContigTrimmer trimmer = new NextGenClosureAceContigTrimmer(minSangerEndCloneCoverage, minBiDirectionalEndCoverage, ignoreThresholdEndCoverage); File aceFile = new File(commandLine.getOptionValue("ace")); File phdFile = new File(commandLine.getOptionValue("phd")); phdDataStore = new DefaultPhdFileDataStore(phdFile); datastore = new IndexedAceFileDataStore(aceFile); File tempFile = File.createTempFile("nextGenClosureAceTrimmer", ".ace"); tempFile.deleteOnExit(); OutputStream tempOut = new FileOutputStream(tempFile); int numberOfContigs = 0; int numberOfTotalReads = 0; for (AceContig contig : datastore) { AceContig trimmedAceContig = trimmer.trimContig(contig); if (trimmedAceContig != null) { numberOfContigs++; numberOfTotalReads += trimmedAceContig.getNumberOfReads(); AceFileWriter.writeAceFile(trimmedAceContig, phdDataStore, tempOut); } } IOUtil.closeAndIgnoreErrors(tempOut); OutputStream masterAceOut = new FileOutputStream(new File(commandLine.getOptionValue("out"))); masterAceOut.write(String.format("AS %d %d%n", numberOfContigs, numberOfTotalReads).getBytes()); InputStream tempInput = new FileInputStream(tempFile); IOUtils.copy(tempInput, masterAceOut); } catch (ParseException e) { System.err.println(e.getMessage()); printHelp(options); } finally { IOUtil.closeAndIgnoreErrors(phdDataStore, datastore); } } | 13,651 |
1 | private void handleFile(File file, HttpServletRequest request, HttpServletResponse response) throws Exception { String filename = file.getName(); long filesize = file.length(); String mimeType = getMimeType(filename); response.setContentType(mimeType); if (filesize > getDownloadThreshhold()) { response.setHeader("Content-Disposition", "attachment; filename=" + filename); } response.setContentLength((int) filesize); ServletOutputStream out = response.getOutputStream(); IOUtils.copy(new FileInputStream(file), out); out.flush(); } | 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; } | 13,652 |
1 | public static void verifierSiDerniereVersionDesPluginsMenus(ControleurDeMenu i) { if (i.getURLFichierInfoDerniereVersion() == null || i.getURLFichierInfoDerniereVersion() == "") { System.err.println("Evenements.java:verifierSiDerniereVersionDesPluginsMenus impossible:\n" + "pour le plugin chargeur de menu :" + i.getNomPlugin()); } if (i.getVersionPlugin() == 0) { System.err.println("version non renseignee pour :" + i.getNomPlugin() + " on continue sur le plugin suivant"); return; } URL url; try { url = new URL(i.getURLFichierInfoDerniereVersion()); } catch (MalformedURLException e1) { System.err.println("impossible d'ouvrir l'URL (url mal formee)" + i.getURLFichierInfoDerniereVersion() + "\n lors de la recuperation des informations de version sur " + i.getNomPlugin()); return; } InputStream is; try { is = url.openStream(); } catch (IOException e1) { System.err.println("impossible d'ouvrir l'URL (destination inaccessible)" + i.getURLFichierInfoDerniereVersion() + "\n lors de la recuperation des informations de version sur " + i.getNomPlugin()); return; } File destination; try { destination = File.createTempFile("SimplexeReseau" + compteurDeFichiersTemporaires, ".buf"); } catch (IOException e1) { System.err.println("impossible de creer le fichier temporaire\n lors de la recuperation des informations de version sur " + i.getNomPlugin()); return; } compteurDeFichiersTemporaires++; destination.deleteOnExit(); java.io.InputStream sourceFile = null; java.io.FileOutputStream destinationFile = null; try { destination.createNewFile(); } catch (IOException e) { System.err.println("impossible de creer un fichier temporaire\n lors de la recuperation des informations de version sur " + i.getNomPlugin()); return; } sourceFile = is; try { destinationFile = new FileOutputStream(destination); } catch (FileNotFoundException e) { System.err.println("impossible d'ouvrir le flux reseau\n lors de la recuperation des informations de version sur " + i.getNomPlugin()); return; } byte buffer[] = new byte[512 * 1024]; int nbLecture; try { while ((nbLecture = sourceFile.read(buffer)) != -1) { destinationFile.write(buffer, 0, nbLecture); } } catch (IOException e) { System.err.println("impossible d'ecrire dans le fichier temporaire\n lors de la recuperation des informations de version sur " + i.getNomPlugin()); return; } try { sourceFile.close(); destinationFile.close(); } catch (IOException e) { System.err.println("impossible de fermer le fichier temporaire ou le flux reseau\n lors de la recuperation des informations de version sur " + i.getNomPlugin()); return; } BufferedReader lecteurAvecBuffer = null; String ligne; try { lecteurAvecBuffer = new BufferedReader(new FileReader(destination)); } catch (FileNotFoundException e) { System.err.println("impossible d'ouvrir le fichier temporaire apres sa creation (contacter un developpeur)\n lors de la recuperation des informations de version sur " + i.getNomPlugin()); return; } try { boolean estLaDerniereVersion = true; String URLRecupererDerniereVersion = null; while ((ligne = lecteurAvecBuffer.readLine()) != null) { if (ligne.startsWith("version:")) { if (ligne.equals("version:" + i.getVersionPlugin())) { } else { System.err.println("la version pour " + i.getNomPlugin() + " est depassee (" + i.getVersionPlugin() + " alors que la " + ligne + "est disponible)"); estLaDerniereVersion = false; } } if (ligne.startsWith("url:")) { URLRecupererDerniereVersion = ligne.substring(4, ligne.length()); } } if (!estLaDerniereVersion && URLRecupererDerniereVersion != null) { TelechargerPluginEtCharger(i, URLRecupererDerniereVersion); } else { System.out.println("on est a la derniere version du plugin " + i.getNomPlugin()); } } catch (IOException e) { System.err.println("impossible de lire le fichier temporaire apres sa creation\n lors de la recuperation des informations de version sur " + i.getNomPlugin()); return; } try { lecteurAvecBuffer.close(); } catch (IOException e) { return; } } | public static TestResponse post(String urlString, byte[] data, String contentType, String accept) throws IOException { HttpURLConnection httpCon = null; byte[] result = null; byte[] errorResult = null; try { URL url = new URL(urlString); httpCon = (HttpURLConnection) url.openConnection(); httpCon.setDoOutput(true); httpCon.setRequestMethod("POST"); httpCon.setRequestProperty("Content-Type", contentType); httpCon.setRequestProperty("Accept", accept); if (data != null) { OutputStream output = httpCon.getOutputStream(); output.write(data); output.close(); } BufferedInputStream in = new BufferedInputStream(httpCon.getInputStream()); ByteArrayOutputStream os = new ByteArrayOutputStream(); int next = in.read(); while (next > -1) { os.write(next); next = in.read(); } os.flush(); result = os.toByteArray(); os.close(); } catch (IOException e) { e.printStackTrace(); } finally { InputStream errorStream = httpCon.getErrorStream(); if (errorStream != null) { BufferedInputStream errorIn = new BufferedInputStream(errorStream); ByteArrayOutputStream errorOs = new ByteArrayOutputStream(); int errorNext = errorIn.read(); while (errorNext > -1) { errorOs.write(errorNext); errorNext = errorIn.read(); } errorOs.flush(); errorResult = errorOs.toByteArray(); errorOs.close(); } return new TestResponse(httpCon.getResponseCode(), errorResult, result); } } | 13,653 |
1 | private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } | private static byte[] Md5f(String plainText) { byte[] ab = new byte[16]; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte b[] = md.digest(); ab = b; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ab; } | 13,654 |
0 | public static String encryptPass(String pass) { String passEncrypt; MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { } md5.update(pass.getBytes()); BigInteger dis = new BigInteger(1, md5.digest()); passEncrypt = dis.toString(16); return passEncrypt; } | public boolean getFiles(String pRemoteDirectory, String pLocalDirectory) throws IOException { final String methodSignature = "boolean getFiles(String,String): "; FTPClient fc = new FTPClient(); fc.connect(getRemoteHost()); fc.login(getUserName(), getPassword()); fc.changeWorkingDirectory(pRemoteDirectory); FTPFile[] files = fc.listFiles(); boolean retrieved = false; logInfo("Listing Files: "); int retrieveCount = 0; File tmpFile = null; for (int i = 0; i < files.length; i++) { tmpFile = new File(files[i].getName()); if (!tmpFile.isDirectory()) { FileOutputStream fos = new FileOutputStream(pLocalDirectory + "/" + files[i].getName()); retrieved = fc.retrieveFile(files[i].getName(), fos); if (false == retrieved) { logInfo("Unable to retrieve file: " + files[i].getName()); } else { logInfo("Successfully retrieved file: " + files[i].getName()); retrieveCount++; } if (null != fos) { fos.flush(); fos.close(); } } } logInfo("Retrieve count: " + retrieveCount); if (retrieveCount > 0) { return true; } return false; } | 13,655 |
1 | @Override protected void writeFile() { super.writeFile(); try { String tagListFilePath = file.toURI().toASCIIString(); tagListFilePath = tagListFilePath.substring(0, tagListFilePath.lastIndexOf(FileManager.GLIPS_VIEW_EXTENSION)) + FileManager.TAG_LIST_FILE_EXTENSION; File tagListFile = new File(new URI(tagListFilePath)); StringBuffer buffer = new StringBuffer(""); for (String tagName : tags) { buffer.append(tagName + "\n"); } ByteBuffer byteBuffer = ByteBuffer.wrap(buffer.toString().getBytes("UTF-8")); FileOutputStream out = new FileOutputStream(tagListFile); FileChannel channel = out.getChannel(); channel.write(byteBuffer); channel.close(); } catch (Exception ex) { } try { String parentPath = file.getParentFile().toURI().toASCIIString(); if (!parentPath.endsWith("/")) { parentPath += "/"; } File srcFile = null, destFile = null; byte[] tab = new byte[1000]; int nb = 0; InputStream in = null; OutputStream out = null; for (String destinationName : dataBaseFiles.keySet()) { srcFile = dataBaseFiles.get(destinationName); if (srcFile != null) { destFile = new File(new URI(parentPath + destinationName)); in = new BufferedInputStream(new FileInputStream(srcFile)); out = new BufferedOutputStream(new FileOutputStream(destFile)); while (in.available() > 0) { nb = in.read(tab); if (nb > 0) { out.write(tab, 0, nb); } } in.close(); out.flush(); out.close(); } } } catch (Exception ex) { ex.printStackTrace(); } } | private void writeInputStreamToFile(InputStream stream, File file) { try { FileOutputStream fOut = new FileOutputStream(file); IOUtils.copy(stream, fOut); fOut.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } | 13,656 |
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; } | 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(); } } | 13,657 |
1 | public static String encrypt(final String password, final String algorithm, final byte[] salt) { final StringBuffer buffer = new StringBuffer(); MessageDigest digest = null; int size = 0; if ("CRYPT".equalsIgnoreCase(algorithm)) { throw new InternalError("Not implemented"); } else if ("SHA".equalsIgnoreCase(algorithm) || "SSHA".equalsIgnoreCase(algorithm)) { size = 20; if (salt != null && salt.length > 0) { buffer.append("{SSHA}"); } else { buffer.append("{SHA}"); } try { digest = MessageDigest.getInstance("SHA-1"); } catch (final NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if ("MD5".equalsIgnoreCase(algorithm) || "SMD5".equalsIgnoreCase(algorithm)) { size = 16; if (salt != null && salt.length > 0) { buffer.append("{SMD5}"); } else { buffer.append("{MD5}"); } try { digest = MessageDigest.getInstance("MD5"); } catch (final NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } int outSize = size; digest.reset(); digest.update(password.getBytes()); if (salt != null && salt.length > 0) { digest.update(salt); outSize += salt.length; } final byte[] out = new byte[outSize]; System.arraycopy(digest.digest(), 0, out, 0, size); if (salt != null && salt.length > 0) { System.arraycopy(salt, 0, out, size, salt.length); } buffer.append(Base64.encode(out)); return buffer.toString(); } | public static String encrypt(String plainText) throws Exception { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new Exception(e.getMessage()); } try { md.update(plainText.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new Exception(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } | 13,658 |
0 | private MimeTypes() { try { final URL url = RES.getURL("types"); final InputStream is = url.openStream(); final BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = br.readLine(); while (line != null) { line = line.trim(); final int p = line.indexOf('#'); if (p >= 0) { line = line.substring(0, p).trim(); } if (line.length() > 0) { final StringTokenizer st = new StringTokenizer(line, " \t"); if (st.countTokens() > 1) { final String mime = st.nextToken(); while (st.hasMoreTokens()) { extnMap.put(st.nextToken(), mime); } } } line = br.readLine(); } br.close(); } catch (IOException e) { e.printStackTrace(); } canParse.add(TEXT_HTML); canParse.add(TEXT_CSS); } | public void addUser(String strUserName, String strPass, boolean isEncrypt) throws Exception { Connection con = null; PreparedStatement pstmt = null; try { con = DbForumFactory.getConnection(); con.setAutoCommit(false); int userID = DbSequenceManager.nextID(DbSequenceManager.USER); pstmt = con.prepareStatement(INSERT_USER); pstmt.setString(1, strUserName); if (isEncrypt) { pstmt.setString(2, SecurityUtil.md5ByHex(strPass)); } else { pstmt.setString(2, strPass); } pstmt.setString(3, ""); pstmt.setString(4, ""); pstmt.setString(5, ""); pstmt.setString(6, ""); pstmt.setString(7, ""); pstmt.setInt(8, userID); pstmt.executeUpdate(); pstmt.clearParameters(); pstmt = con.prepareStatement(INSERT_USERPROPS); pstmt.setString(1, ""); pstmt.setString(2, ""); pstmt.setString(3, ""); pstmt.setInt(4, 0); pstmt.setString(5, ""); pstmt.setInt(6, 0); pstmt.setInt(7, 0); pstmt.setString(8, ""); pstmt.setString(9, ""); pstmt.setString(10, ""); pstmt.setInt(11, 0); pstmt.setInt(12, 0); pstmt.setInt(13, 0); pstmt.setInt(14, 0); pstmt.setString(15, ""); pstmt.setString(16, ""); pstmt.setString(17, ""); pstmt.setString(18, ""); pstmt.setString(19, ""); pstmt.setString(20, ""); pstmt.setString(21, ""); pstmt.setString(22, ""); pstmt.setString(23, ""); pstmt.setInt(24, 0); pstmt.setInt(25, 0); pstmt.setInt(26, userID); pstmt.executeUpdate(); pstmt.clearParameters(); pstmt = con.prepareStatement(INSTER_USERGROUP); pstmt.setInt(1, 4); pstmt.setInt(2, userID); pstmt.setInt(3, 0); pstmt.executeUpdate(); con.commit(); } catch (Exception e) { try { con.rollback(); } catch (SQLException e1) { } log.error("insert user Error: " + e.toString()); } finally { DbForumFactory.closeDB(null, pstmt, null, con); } } | 13,659 |
0 | public void actionPerformed(ActionEvent e) { if (path.compareTo("") != 0) { imageName = (path.substring(path.lastIndexOf(File.separator) + 1, path.length())); String name = imageName.substring(0, imageName.lastIndexOf('.')); String extension = imageName.substring(imageName.lastIndexOf('.') + 1, imageName.length()); File imageFile = new File(path); directoryPath = "images" + File.separator + imageName.substring(0, 1).toUpperCase(); File directory = new File(directoryPath); directory.mkdirs(); imagePath = "." + File.separator + "images" + File.separator + imageName.substring(0, 1).toUpperCase() + File.separator + imageName; File newFile = new File(imagePath); if (myImagesBehaviour.equals(TLanguage.getString("TIGManageGalleryDialog.REPLACE_IMAGE"))) { Vector<Vector<String>> aux = TIGDataBase.imageSearchByName(name); if (aux.size() != 0) { int idImage = TIGDataBase.imageKeySearchName(name); TIGDataBase.deleteAsociatedOfImage(idImage); } } if (myImagesBehaviour.equals(TLanguage.getString("TIGManageGalleryDialog.ADD_IMAGE"))) { int i = 1; while (newFile.exists()) { imagePath = "." + File.separator + "images" + File.separator + imageName.substring(0, 1).toUpperCase() + File.separator + imageName.substring(0, imageName.lastIndexOf('.')) + "_" + i + imageName.substring(imageName.lastIndexOf('.'), imageName.length()); name = name + "_" + i; newFile = new File(imagePath); i++; } } imagePathThumb = (imagePath.substring(0, imagePath.lastIndexOf("."))).concat("_th.jpg"); imageName = name + "." + extension; try { FileChannel srcChannel = new FileInputStream(path).getChannel(); FileChannel dstChannel = new FileOutputStream(imagePath).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } TIGDataBase.insertDB(theConcepts, imageName, imageName.substring(0, imageName.lastIndexOf('.'))); image = null; if (imageFile != null) { if (TFileUtils.isJAIRequired(imageFile)) { RenderedOp src = JAI.create("fileload", imageFile.getAbsolutePath()); BufferedImage bufferedImage = src.getAsBufferedImage(); image = new ImageIcon(bufferedImage); } else { image = new ImageIcon(imageFile.getAbsolutePath()); } if (image.getImageLoadStatus() == MediaTracker.ERRORED) { int choosenOption = JOptionPane.NO_OPTION; choosenOption = JOptionPane.showConfirmDialog(null, TLanguage.getString("TIGInsertImageAction.MESSAGE"), TLanguage.getString("TIGInsertImageAction.NAME"), JOptionPane.CLOSED_OPTION, JOptionPane.ERROR_MESSAGE); } else { createThumbnail(); } } } } | public void init(String password) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes("UTF-8"), 0, password.length()); byte[] rawKey = md.digest(); skeySpec = new SecretKeySpec(rawKey, "AES"); ivSpec = new IvParameterSpec(rawKey); cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); } catch (UnsupportedEncodingException ex) { Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchPaddingException ex) { Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex); } } | 13,660 |
0 | public String MD5(String text) { try { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (Exception e) { System.out.println(e.toString()); } return null; } | 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!"); } | 13,661 |
0 | public static void replaceEntry(File file, String entryName, InputStream stream) throws PersistenceException { try { File temporaryFile = File.createTempFile("pmMDA_zargo", ".zargo"); temporaryFile.deleteOnExit(); FileInputStream inputStream = new FileInputStream(file); ZipInputStream input = new ZipInputStream(inputStream); ZipOutputStream output = new ZipOutputStream(new FileOutputStream(temporaryFile)); ZipEntry entry = input.getNextEntry(); while (entry != null) { ZipEntry zipEntry = new ZipEntry(entry); zipEntry.setCompressedSize(-1); output.putNextEntry(zipEntry); if (!entry.getName().equals(entryName)) { IOUtils.copy(input, output); } else { IOUtils.copy(stream, output); } input.closeEntry(); output.closeEntry(); entry = input.getNextEntry(); } input.close(); inputStream.close(); output.close(); System.gc(); boolean isSuccess = file.delete(); if (!isSuccess) { throw new PersistenceException(); } isSuccess = temporaryFile.renameTo(file); if (!isSuccess) { throw new PersistenceException(); } } catch (IOException e) { throw new PersistenceException(e); } } | public static String createHash(String seed) { MessageDigest md; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Can't happen!", e); } try { md.update(seed.getBytes(CHARSET)); md.update(String.valueOf(System.currentTimeMillis()).getBytes(CHARSET)); return toHexString(md.digest()); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Can't happen!", e); } } | 13,662 |
0 | private void copyOutResource(String dstPath, InputStream in) throws FileNotFoundException, IOException { FileOutputStream out = null; try { dstPath = this.outputDir + dstPath; File file = new File(dstPath); file.getParentFile().mkdirs(); out = new FileOutputStream(file); IOUtils.copy(in, out); } finally { if (out != null) { out.close(); } } } | 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) { } } | 13,663 |
1 | private void insertService(String table, int type) { Connection con = null; log.info(""); log.info("正在生成" + table + "的服务。。。。。。。"); try { con = DODataSource.getDefaultCon(); con.setAutoCommit(false); Statement stmt = con.createStatement(); Statement stmt2 = con.createStatement(); String serviceUid = UUIDHex.getInstance().generate(); DOBO bo = DOBO.getDOBOByName(StringUtil.getDotName(table)); List props = new ArrayList(); StringBuffer mainSql = null; String name = ""; String l10n = ""; String prefix = StringUtil.getDotName(table); Boolean isNew = null; switch(type) { case 1: name = prefix + ".insert"; l10n = name; props = bo.retrieveProperties(); mainSql = getInsertSql(props, table); isNew = Boolean.TRUE; break; case 2: name = prefix + ".update"; l10n = name; props = bo.retrieveProperties(); mainSql = this.getModiSql(props, table); isNew = Boolean.FALSE; break; case 3: DOBOProperty property = DOBOProperty.getDOBOPropertyByName(bo.getName(), "objuid"); System.out.println("BOBOBO::::::" + bo); System.out.println("Property::::::" + property); if (property == null) { return; } name = prefix + ".delete"; l10n = name; props.add(property); mainSql = new StringBuffer("delete from ").append(table).append(" where objuid = ?"); break; case 4: property = DOBOProperty.getDOBOPropertyByName(bo.getName(), "objuid"); if (property == null) { return; } name = prefix + ".browse"; l10n = name; props.add(property); mainSql = new StringBuffer("select * from ").append(table).append(" where objuid = ?"); break; case 5: name = prefix + ".list"; l10n = name; mainSql = new StringBuffer("select * from ").append(table); } this.setParaLinkBatch(props, stmt2, serviceUid, isNew); StringBuffer aSql = new StringBuffer("insert into DO_Service(objuid,l10n,name,bouid,mainSql) values(").append("'").append(serviceUid).append("','").append(l10n).append("','").append(name).append("','").append(this.getDOBOUid(table)).append("','").append(mainSql).append("')"); log.info("Servcice's Sql:" + aSql.toString()); stmt.executeUpdate(aSql.toString()); stmt2.executeBatch(); con.commit(); } catch (SQLException ex) { try { con.rollback(); } catch (SQLException ex2) { ex2.printStackTrace(); } ex.printStackTrace(); } finally { try { if (!con.isClosed()) { con.close(); } } catch (SQLException ex1) { ex1.printStackTrace(); } } } | @Override public void excluir(QuestaoMultiplaEscolha q) throws Exception { PreparedStatement stmt = null; String sql = "DELETE FROM questao WHERE id_questao=?"; try { stmt = conexao.prepareStatement(sql); stmt.setInt(1, q.getIdQuestao()); stmt.executeUpdate(); conexao.commit(); } catch (SQLException e) { conexao.rollback(); throw e; } } | 13,664 |
1 | public static int gunzipFile(File file_input, File dir_output) { GZIPInputStream gzip_in_stream; try { FileInputStream in = new FileInputStream(file_input); BufferedInputStream source = new BufferedInputStream(in); gzip_in_stream = new GZIPInputStream(source); } catch (IOException e) { return STATUS_IN_FAIL; } String file_input_name = file_input.getName(); String file_output_name = file_input_name.substring(0, file_input_name.length() - 3); File output_file = new File(dir_output, file_output_name); byte[] input_buffer = new byte[BUF_SIZE]; int len = 0; try { FileOutputStream out = new FileOutputStream(output_file); BufferedOutputStream destination = new BufferedOutputStream(out, BUF_SIZE); while ((len = gzip_in_stream.read(input_buffer, 0, BUF_SIZE)) != -1) destination.write(input_buffer, 0, len); destination.flush(); out.close(); } catch (IOException e) { return STATUS_GUNZIP_FAIL; } try { gzip_in_stream.close(); } catch (IOException e) { } return STATUS_OK; } | private static void createCompoundData(String dir, String type) { try { Set s = new HashSet(); File nouns = new File(dir + "index." + type); FileInputStream fis = new FileInputStream(nouns); InputStreamReader reader = new InputStreamReader(fis); StringBuffer sb = new StringBuffer(); int chr = reader.read(); while (chr >= 0) { if (chr == '\n' || chr == '\r') { String line = sb.toString(); if (line.length() > 0) { String[] spaceSplit = PerlHelp.split(line); for (int i = 0; i < spaceSplit.length; i++) { if (spaceSplit[i].indexOf('_') >= 0) { s.add(spaceSplit[i].replace('_', ' ')); } } } sb.setLength(0); } else { sb.append((char) chr); } chr = reader.read(); } System.out.println(type + " size=" + s.size()); File output = new File(dir + "compound." + type + "s.gz"); FileOutputStream fos = new FileOutputStream(output); GZIPOutputStream gzos = new GZIPOutputStream(new BufferedOutputStream(fos)); PrintWriter writer = new PrintWriter(gzos); writer.println("# This file was extracted from WordNet data, the following copyright notice"); writer.println("# from WordNet is attached."); writer.println("#"); writer.println("# This software and database is being provided to you, the LICENSEE, by "); writer.println("# Princeton University under the following license. By obtaining, using "); writer.println("# and/or copying this software and database, you agree that you have "); writer.println("# read, understood, and will comply with these terms and conditions.: "); writer.println("# "); writer.println("# Permission to use, copy, modify and distribute this software and "); writer.println("# database and its documentation for any purpose and without fee or "); writer.println("# royalty is hereby granted, provided that you agree to comply with "); writer.println("# the following copyright notice and statements, including the disclaimer, "); writer.println("# and that the same appear on ALL copies of the software, database and "); writer.println("# documentation, including modifications that you make for internal "); writer.println("# use or for distribution. "); writer.println("# "); writer.println("# WordNet 1.7 Copyright 2001 by Princeton University. All rights reserved. "); writer.println("# "); writer.println("# THIS SOFTWARE AND DATABASE IS PROVIDED \"AS IS\" AND PRINCETON "); writer.println("# UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR "); writer.println("# IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PRINCETON "); writer.println("# UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES OF MERCHANT- "); writer.println("# ABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE "); writer.println("# OF THE LICENSED SOFTWARE, DATABASE OR DOCUMENTATION WILL NOT "); writer.println("# INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR "); writer.println("# OTHER RIGHTS. "); writer.println("# "); writer.println("# The name of Princeton University or Princeton may not be used in"); writer.println("# advertising or publicity pertaining to distribution of the software"); writer.println("# and/or database. Title to copyright in this software, database and"); writer.println("# any associated documentation shall at all times remain with"); writer.println("# Princeton University and LICENSEE agrees to preserve same. "); for (Iterator i = s.iterator(); i.hasNext(); ) { String mwe = (String) i.next(); writer.println(mwe); } writer.close(); } catch (Exception e) { e.printStackTrace(); } } | 13,665 |
1 | public BufferedImage process(final InputStream is, DjatokaDecodeParam params) throws DjatokaException { if (isWindows) return processUsingTemp(is, params); ArrayList<Double> dims = null; if (params.getRegion() != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copyStream(is, baos); dims = getRegionMetadata(new ByteArrayInputStream(baos.toByteArray()), params); return process(new ByteArrayInputStream(baos.toByteArray()), dims, params); } else return process(is, dims, params); } | public void backupXML() { try { TimeStamp timeStamp = new TimeStamp(); String fnameIn = this.fnameXML(); String pathBackup = this.pathXML + "\\Backup\\"; String fnameOut = fnameIn.substring(fnameIn.indexOf(this.fname), fnameIn.length()); fnameOut = fnameOut.substring(0, fnameOut.indexOf("xml")); fnameOut = pathBackup + fnameOut + timeStamp.now("yyyyMMdd-kkmmss") + ".xml"; System.out.println("fnameIn: " + fnameIn); System.out.println("fnameOut: " + fnameOut); FileChannel in = new FileInputStream(fnameIn).getChannel(); FileChannel out = new FileOutputStream(fnameOut).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { central.inform("ORM.backupXML: " + e.toString()); } } | 13,666 |
0 | public void writeToStream(OutputStream out) throws IOException { InputStream result = null; if (tempFile != null) { InputStream input = new BufferedInputStream(new FileInputStream(tempFile)); IOUtils.copy(input, out); IOUtils.closeQuietly(input); } else if (tempBuffer != null) { out.write(tempBuffer); } } | public void run() { counter = 0; Log.debug("Fetching news"); Session session = botService.getSession(); if (session == null) { Log.warn("No current IRC session"); return; } final List<Channel> channels = session.getChannels(); if (channels.isEmpty()) { Log.warn("No channel for the current IRC session"); return; } if (StringUtils.isEmpty(feedURL)) { Log.warn("No feed provided"); return; } Log.debug("Creating feedListener"); FeedParserListener feedParserListener = new DefaultFeedParserListener() { public void onChannel(FeedParserState state, String title, String link, String description) throws FeedParserException { Log.debug("onChannel:" + title + "," + link + "," + description); } public void onItem(FeedParserState state, String title, String link, String description, String permalink) throws FeedParserException { if (counter >= MAX_FEEDS) { throw new FeedPollerCancelException("Maximum number of items reached"); } boolean canAnnounce = false; try { if (lastDigest == null) { MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.update(title.getBytes()); lastDigest = md.digest(); canAnnounce = true; } else { MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.update(title.getBytes()); byte[] currentDigest = md.digest(); if (!MessageDigest.isEqual(currentDigest, lastDigest)) { lastDigest = currentDigest; canAnnounce = true; } } if (canAnnounce) { String shortTitle = title; if (shortTitle.length() > TITLE_MAX_LEN) { shortTitle = shortTitle.substring(0, TITLE_MAX_LEN) + " ..."; } String shortLink = IOUtil.getTinyUrl(link); Log.debug("Link:" + shortLink); for (Channel channel : channels) { channel.say(String.format("%s, %s", shortTitle, shortLink)); } } } catch (Exception e) { throw new FeedParserException(e); } counter++; } public void onCreated(FeedParserState state, Date date) throws FeedParserException { } }; if (parser != null) { InputStream is = null; try { Log.debug("Reading feedURL"); is = new URL(feedURL).openStream(); parser.parse(feedParserListener, is, feedURL); Log.debug("Parsing done"); } catch (IOException ioe) { Log.error(ioe.getMessage(), ioe); } catch (FeedPollerCancelException fpce) { } catch (FeedParserException e) { for (Channel channel : channels) { channel.say(e.getMessage()); } } finally { IOUtil.closeQuietly(is); } } else { Log.warn("Wasn't able to create feed parser"); } } | 13,667 |
1 | public boolean copyTo(String targetFilePath) { try { FileInputStream srcFile = new FileInputStream(filePath); FileOutputStream target = new FileOutputStream(targetFilePath); byte[] buff = new byte[1024]; int readed = -1; while ((readed = srcFile.read(buff)) > 0) target.write(buff, 0, readed); srcFile.close(); target.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } } | 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(); } } } | 13,668 |
1 | public static void main(String[] args) throws Exception { TripleDES tdes = new TripleDES(); StreamBlockReader reader = new StreamBlockReader(new FileInputStream("D:\\testTDESENC.txt")); StreamBlockWriter writer = new StreamBlockWriter(new FileOutputStream("D:\\testTDESDEC.txt")); SingleKey key = new SingleKey(new Block(128), ""); key = new SingleKey(new Block("01011101110000101001100111001011101000001110111101001001101101101101100000011101100100110000101100001110000001111101001101001101"), ""); Mode mode = new ECBTripleDESMode(tdes); tdes.decrypt(reader, writer, key, mode); } | 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(); } } | 13,669 |
0 | private static AtomContainer askForMovieSettings() throws IOException, QTException { final InputStream inputStream = QuickTimeFormatGenerator.class.getResourceAsStream(REFERENCE_MOVIE_RESOURCE); final ByteArrayOutputStream byteArray = new ByteArrayOutputStream(1024 * 100); IOUtils.copy(inputStream, byteArray); final byte[] movieBytes = byteArray.toByteArray(); final QTHandle qtHandle = new QTHandle(movieBytes); final DataRef dataRef = new DataRef(qtHandle, StdQTConstants.kDataRefFileExtensionTag, ".mov"); final Movie movie = Movie.fromDataRef(dataRef, StdQTConstants.newMovieActive | StdQTConstants4.newMovieAsyncOK); final MovieExporter exporter = new MovieExporter(StdQTConstants.kQTFileTypeMovie); exporter.doUserDialog(movie, null, 0, movie.getDuration()); return exporter.getExportSettingsFromAtomContainer(); } | public static GoogleResponse getElevation(String lat, String lon) throws IOException { String url = "http://maps.google.com/maps/api/elevation/xml?locations="; url = url + String.valueOf(lat); url = url + ","; url = url + String.valueOf(lon); url = url + "&sensor=false"; BufferedReader in = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String line; GoogleResponse googleResponse = new GoogleResponse(); googleResponse.lat = Double.valueOf(lat); googleResponse.lon = Double.valueOf(lon); while ((line = in.readLine()) != null) { line = line.trim(); if (line.startsWith("<status>")) { line = line.replace("<status>", ""); line = line.replace("</status>", ""); googleResponse.status = line; if (!line.toLowerCase().equals("ok")) return googleResponse; } else if (line.startsWith("<elevation>")) { line = line.replace("<elevation>", ""); line = line.replace("</elevation>", ""); googleResponse.elevation = Double.valueOf(line); return googleResponse; } } return googleResponse; } | 13,670 |
0 | public static void main(String[] args) { int dizi[] = { 23, 78, 45, 8, 3, 32, 56, 39, 92, 28 }; boolean test = false; int kars = 0; int tas = 0; while (true) { for (int j = 0; j < dizi.length - 1; j++) { kars++; if (dizi[j] > dizi[j + 1]) { int temp = dizi[j]; dizi[j] = dizi[j + 1]; dizi[j + 1] = temp; test = true; tas++; } } if (!test) { break; } else { test = false; } } for (int i = 0; i < dizi.length; i++) { System.out.print(dizi[i] + " "); } for (int i = 0; i < 5; i++) { System.out.println("i" + i); } } | public static void test(String args[]) { int trace; int bytes_read = 0; int last_contentLenght = 0; try { BufferedReader reader; URL url; url = new URL(args[0]); URLConnection istream = url.openConnection(); last_contentLenght = istream.getContentLength(); reader = new BufferedReader(new InputStreamReader(istream.getInputStream())); System.out.println(url.toString()); String line; trace = t2pNewTrace(); while ((line = reader.readLine()) != null) { bytes_read = bytes_read + line.length() + 1; t2pProcessLine(trace, line); } t2pHandleEventPairs(trace); t2pSort(trace, 0); t2pExportTrace(trace, new String("pngtest2.png"), 1000, 700, (float) 0, (float) 33); t2pExportTrace(trace, new String("pngtest3.png"), 1000, 700, (float) 2.3, (float) 2.44); System.out.println("Press any key to contiune read from stream !!!"); System.out.println(t2pGetProcessName(trace, 0)); System.in.read(); istream = url.openConnection(); if (last_contentLenght != istream.getContentLength()) { istream = url.openConnection(); istream.setRequestProperty("Range", "bytes=" + Integer.toString(bytes_read) + "-"); System.out.println(Integer.toString(istream.getContentLength())); reader = new BufferedReader(new InputStreamReader(istream.getInputStream())); while ((line = reader.readLine()) != null) { System.out.println(line); t2pProcessLine(trace, line); } } else System.out.println("File not changed !"); t2pDeleteTrace(trace); } catch (MalformedURLException e) { System.out.println("MalformedURLException !!!"); } catch (IOException e) { System.out.println("File not found " + args[0]); } ; } | 13,671 |
1 | public static void copyFile(File source, File dest) { try { FileChannel in = new FileInputStream(source).getChannel(); if (!dest.getParentFile().exists()) dest.getParentFile().mkdirs(); FileChannel out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } | 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(); } } | 13,672 |
0 | public static void copyFile(String oldPathFile, String newPathFile) { try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPathFile); if (oldfile.exists()) { InputStream inStream = new FileInputStream(oldPathFile); FileOutputStream fs = new FileOutputStream(newPathFile); byte[] buffer = new byte[2048]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; fs.write(buffer, 0, byteread); } inStream.close(); } else { System.err.println(FileUtil.class.toString() + ":不存在file" + oldPathFile); } } catch (Exception e) { System.err.println(FileUtil.class.toString() + ":复制file" + oldPathFile + "到" + newPathFile + "出错!"); } } | public boolean searchEntity(String login, String password, String searcheId, OutputStream os) throws SynchronizationException { HttpClient client = new SSLHttpClient(); try { StringBuilder builder = new StringBuilder(url).append("?" + CMD_PARAM + "=" + CMD_SEARCH).append("&" + LOGIN_PARAM + "=" + URLEncoder.encode(login, "UTF-8")).append("&" + PASSWD_PARAM + "=" + URLEncoder.encode(password, "UTF-8")).append("&" + SEARCH_PARAM + "=" + searcheId); HttpGet method = httpGetMethod(builder.toString()); HttpResponse response = client.execute(method); Header header = response.getFirstHeader(HEADER_NAME); if (header != null && HEADER_VALUE.equals(HEADER_VALUE)) { int code = response.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { long expectedLength = response.getEntity().getContentLength(); InputStream is = response.getEntity().getContent(); FileUtils.writeInFile(is, os, expectedLength); return true; } else { throw new SynchronizationException("Command 'search' : HTTP error code returned." + code, SynchronizationException.ERROR_SEARCH); } } else { throw new SynchronizationException("HTTP header is invalid", SynchronizationException.ERROR_SEARCH); } } catch (Exception e) { throw new SynchronizationException("Command 'search' -> ", e, SynchronizationException.ERROR_SEARCH); } } | 13,673 |
0 | public void loginSendSpace() throws Exception { loginsuccessful = false; 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 sendspace"); HttpPost httppost = new HttpPost("http://www.sendspace.com/login.html"); httppost.setHeader("Cookie", sidcookie + ";" + ssuicookie); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("action", "login")); formparams.add(new BasicNameValuePair("submit", "login")); formparams.add(new BasicNameValuePair("target", "%252F")); formparams.add(new BasicNameValuePair("action_type", "login")); formparams.add(new BasicNameValuePair("remember", "1")); formparams.add(new BasicNameValuePair("username", 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........"); Iterator<Cookie> it = httpclient.getCookieStore().getCookies().iterator(); Cookie escookie = null; while (it.hasNext()) { escookie = it.next(); if (escookie.getName().equalsIgnoreCase("ssal")) { ssalcookie = escookie.getName() + "=" + escookie.getValue(); NULogger.getLogger().info(ssalcookie); loginsuccessful = true; } } if (loginsuccessful) { username = getUsername(); password = getPassword(); NULogger.getLogger().info("SendSpace login success :)"); } else { NULogger.getLogger().info("SendSpace 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); } } | @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("application/json"); resp.setCharacterEncoding("utf-8"); String format = req.getParameter("format"); EntityManager em = EMF.get().createEntityManager(); String uname = (req.getParameter("uname") == null) ? "" : req.getParameter("uname"); String passwd = (req.getParameter("passwd") == null) ? "" : req.getParameter("passwd"); String name = (req.getParameter("name") == null) ? "" : req.getParameter("name"); String email = (req.getParameter("email") == null) ? "" : req.getParameter("email"); if (uname == null || uname.equals("") || uname.length() < 4) { if (format != null && format.equals("xml")) resp.getWriter().print(Error.unameTooShort(uname).toXML(em)); else resp.getWriter().print(Error.unameTooShort(uname).toJSON(em)); resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } if (User.fromUserName(em, uname) != null) { if (format != null && format.equals("xml")) resp.getWriter().print(Error.userExists(uname).toXML(em)); else resp.getWriter().print(Error.userExists(uname).toJSON(em)); resp.setStatus(HttpServletResponse.SC_CONFLICT); em.close(); return; } if (passwd.equals("") || passwd.length() < 6) { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); if (format != null && format.equals("xml")) resp.getWriter().print(Error.passwdTooShort(uname).toXML(em)); else resp.getWriter().print(Error.passwdTooShort(uname).toJSON(em)); em.close(); return; } User u = new User(); u.setUsername(uname); u.setPasswd(passwd); u.setName(name); u.setEmail(email); u.setPaid(false); StringBuffer apikey = new StringBuffer(); try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); String api = System.nanoTime() + "" + System.identityHashCode(this) + "" + uname; algorithm.update(api.getBytes()); byte[] digest = algorithm.digest(); for (int i = 0; i < digest.length; i++) { apikey.append(Integer.toHexString(0xFF & digest[i])); } } catch (NoSuchAlgorithmException e) { resp.setStatus(500); if (format != null && format.equals("xml")) resp.getWriter().print(Error.unknownError().toXML(em)); else resp.getWriter().print(Error.unknownError().toJSON(em)); log.severe(e.toString()); em.close(); return; } u.setApiKey(apikey.toString()); EntityTransaction tx = em.getTransaction(); tx.begin(); try { em.persist(u); tx.commit(); } catch (Throwable t) { log.severe("Error adding user " + uname + " Reason:" + t.getMessage()); tx.rollback(); resp.setStatus(500); if (format != null && format.equals("xml")) resp.getWriter().print(Error.unknownError().toXML(em)); else resp.getWriter().print(Error.unknownError().toJSON(em)); return; } log.info("User " + u.getName() + " was created successfully"); resp.setStatus(HttpServletResponse.SC_CREATED); if (format != null && format.equals("xml")) resp.getWriter().print(u.toXML(em)); else resp.getWriter().print(u.toJSON(em)); em.close(); } | 13,674 |
0 | private static boolean isUrlResourceExists(final URL url) { try { InputStream is = url.openStream(); try { is.close(); } catch (IOException ioe) { } return true; } catch (IOException ioe) { return false; } } | protected void createFile(File sourceActionDirectory, File destinationActionDirectory, LinkedList<String> segments) throws DuplicateActionFileException { File currentSrcDir = sourceActionDirectory; File currentDestDir = destinationActionDirectory; String segment = ""; for (int i = 0; i < segments.size() - 1; i++) { segment = segments.get(i); currentSrcDir = new File(currentSrcDir, segment); currentDestDir = new File(currentDestDir, segment); } if (currentSrcDir != null && currentDestDir != null) { File srcFile = new File(currentSrcDir, segments.getLast()); if (srcFile.exists()) { File destFile = new File(currentDestDir, segments.getLast()); if (destFile.exists()) { throw new DuplicateActionFileException(srcFile.toURI().toASCIIString()); } try { FileChannel srcChannel = new FileInputStream(srcFile).getChannel(); FileChannel destChannel = new FileOutputStream(destFile).getChannel(); ByteBuffer buffer = ByteBuffer.allocate((int) srcChannel.size()); while (srcChannel.position() < srcChannel.size()) { srcChannel.read(buffer); } srcChannel.close(); buffer.rewind(); destChannel.write(buffer); destChannel.close(); } catch (Exception ex) { ex.printStackTrace(); } } } } | 13,675 |
1 | public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } | @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(); } } | 13,676 |
0 | public static List<PropertiesHolder> convertToPropertiesHolders(Collection<String> locations) { List<PropertiesHolder> propertiesHolders = new ArrayList<PropertiesHolder>(); for (String path : locations) { Locale locale = null; int startIndex = path.lastIndexOf('/'); if (startIndex < 0) { startIndex = 0; } int localeIndex = path.indexOf('_', startIndex); String localeString = null; if (localeIndex > 0) { localeString = path.substring(localeIndex + 1, path.lastIndexOf('.')); } if (org.apache.commons.lang.StringUtils.isBlank(localeString)) { locale = MessageProvider.DEFAULT_LOCALE; log.info("no locale could be guessed for properties: " + path); } else { locale = StringUtils.parseLocaleString(localeString); if (locale == null) { locale = Locale.getDefault(); log.info("no locale could be guessed for properties: " + path); } } try { Properties props = new Properties(); URL url = new URL(path); if (path.endsWith(".properties")) { props.load(url.openStream()); } else if (path.endsWith(".xml")) { props.loadFromXML(url.openStream()); } else if (path.endsWith(".xls")) { } else { log.warn("unknown filetype for properties: " + path); } String bundleName = props.getProperty("webwarp-modules-bundle-id"); if (org.apache.commons.lang.StringUtils.isEmpty(bundleName)) { log.warn("bundle name is empty for path: " + path + ". Provide a bundle entry 'webwarp-modules-bundle-id' to set one."); bundleName = MessageProvider.DEFAULT_BUNDLE_NAME; } propertiesHolders.add(new PropertiesHolder(props, bundleName, locale)); } catch (Exception e) { log.error("Error reading properties from : " + path, e); } } return propertiesHolders; } | protected void validate(long googcmId, long reservePrice, String description, String category, int days, String status, String title, byte[] imgBytes) throws PortalException, SystemException { if (Validator.isNull(description)) throw new AuctionDescriptionException(); else if (Validator.isNull(title)) throw new AuctionTitleException(); else if (Validator.isNull(category)) throw new CategoryIdException(); if (googcmId < 1000000000l | googcmId > 999999999999999l) throw new AuctionGoogCMIdException(); long imgMaxSize = 1048576l; if ((imgBytes == null) || (imgBytes.length > ((int) imgMaxSize))) throw new AuctionImageSizeException(); if (days != 3 & days != 7 & days != 10) throw new AuctionEndeDateException(); if ((reservePrice < 0) || (reservePrice > 10000)) throw new AuctionReservePriceException(); try { URL url = new URL("https://checkout.google.com/api/checkout/v2/checkoutForm/Merchant/" + googcmId); URLConnection conn = url.openConnection(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); boolean sellerExists = true; String line; while ((line = rd.readLine()) != null) { if (line.contains("" + googcmId)) { throw new AuctionGoogCMAccountException(); } } rd.close(); } catch (IOException e) { e.printStackTrace(); } } | 13,677 |
0 | protected String readFileUsingHttp(String fileUrlName) { String response = ""; try { URL url = new URL(fileUrlName); URLConnection connection = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) connection; httpConn.setRequestProperty("Content-Type", "text/html"); httpConn.setRequestProperty("Content-Length", "0"); httpConn.setRequestMethod("GET"); httpConn.setDoOutput(true); httpConn.setDoInput(true); httpConn.setAllowUserInteraction(false); InputStreamReader isr = new InputStreamReader(httpConn.getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine = ""; while ((inputLine = in.readLine()) != null) { response += inputLine + "\n"; } if (response.endsWith("\n")) { response = response.substring(0, response.length() - 1); } in.close(); } catch (Exception x) { x.printStackTrace(); } return response; } | private static File copyFileTo(File file, File directory) throws IOException { File newFile = new File(directory, file.getName()); FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(file); fos = new FileOutputStream(newFile); byte buff[] = new byte[1024]; int val; while ((val = fis.read(buff)) > 0) fos.write(buff, 0, val); } finally { if (fis != null) fis.close(); if (fos != null) fos.close(); } return newFile; } | 13,678 |
0 | public void execute() { File sourceFile = new File(oarfilePath); File destinationFile = new File(deploymentDirectory + File.separator + sourceFile.getName()); try { FileInputStream fis = new FileInputStream(sourceFile); FileOutputStream fos = new FileOutputStream(destinationFile); byte[] readArray = new byte[2048]; while (fis.read(readArray) != -1) { fos.write(readArray); } fis.close(); fos.flush(); fos.close(); } catch (IOException ioe) { logger.severe("failed to copy the file:" + ioe); } } | protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletConfig config = getServletConfig(); ServletContext context = config.getServletContext(); try { String driver = context.getInitParameter("driver"); Class.forName(driver); String dbURL = context.getInitParameter("db"); String username = context.getInitParameter("username"); String password = ""; connection = DriverManager.getConnection(dbURL, username, password); } catch (ClassNotFoundException e) { System.out.println("Database driver not found."); } catch (SQLException e) { System.out.println("Error opening the db connection: " + e.getMessage()); } String action = ""; String notice; String error = ""; HttpSession session = request.getSession(); session.setMaxInactiveInterval(300); if (request.getParameter("action") != null) { action = request.getParameter("action"); } else { notice = "Unknown action!"; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } if (action.equals("edit_events")) { String sql; String month_name = ""; int month; int year; Event event; if (request.getParameter("month") != null) { month = Integer.parseInt(request.getParameter("month")); String temp = request.getParameter("year_num"); year = Integer.parseInt(temp); int month_num = month - 1; event = new Event(year, month_num, 1); month_name = event.getMonthName(); year = event.getYearNumber(); if (month < 10) { sql = "SELECT * FROM event WHERE date LIKE '" + year + "-0" + month + "-%'"; } else { sql = "SELECT * FROM event WHERE date LIKE '" + year + "-" + month + "-%'"; } } else { event = new Event(); month_name = event.getMonthName(); month = event.getMonthNumber() + 1; year = event.getYearNumber(); sql = "SELECT * FROM event WHERE date LIKE '" + year + "-%" + month + "-%'"; } try { dbStatement = connection.createStatement(); dbResultSet = dbStatement.executeQuery(sql); request.setAttribute("resultset", dbResultSet); request.setAttribute("year", Integer.toString(year)); request.setAttribute("month", Integer.toString(month)); request.setAttribute("month_name", month_name); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/edit_events.jsp"); dispatcher.forward(request, response); return; } catch (SQLException e) { notice = "Error retrieving events from the database."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("edit_event")) { int id = Integer.parseInt(request.getParameter("id")); Event event = new Event(); event = event.getEvent(id); if (event != null) { request.setAttribute("event", event); request.setAttribute("id", Integer.toString(id)); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/add_event.jsp"); dispatcher.forward(request, response); return; } else { notice = "Error retrieving event from the database."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("save_event")) { String title = request.getParameter("title"); String description = request.getParameter("description"); String month = request.getParameter("month"); String day = request.getParameter("day"); String year = request.getParameter("year"); String start_time = ""; String end_time = ""; if (request.getParameter("all_day") == null) { String start_hour = request.getParameter("start_hour"); String start_minutes = request.getParameter("start_minutes"); String start_ampm = request.getParameter("start_ampm"); String end_hour = request.getParameter("end_hour"); String end_minutes = request.getParameter("end_minutes"); String end_ampm = request.getParameter("end_ampm"); if (Integer.parseInt(start_hour) < 10) { start_hour = "0" + start_hour; } if (Integer.parseInt(end_hour) < 10) { end_hour = "0" + end_hour; } start_time = start_hour + ":" + start_minutes + " " + start_ampm; end_time = end_hour + ":" + end_minutes + " " + end_ampm; } Event event = null; if (!start_time.equals("") && !end_time.equals("")) { event = new Event(title, description, month, day, year, start_time, end_time); } else { event = new Event(title, description, month, day, year); } if (event.saveEvent()) { notice = "Calendar event saved!"; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } else { notice = "Error saving calendar event."; request.setAttribute("notice", notice); request.setAttribute("event", event); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/add_event.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("update_event")) { String title = request.getParameter("title"); String description = request.getParameter("description"); String month = request.getParameter("month"); String day = request.getParameter("day"); String year = request.getParameter("year"); String start_time = ""; String end_time = ""; int id = Integer.parseInt(request.getParameter("id")); if (request.getParameter("all_day") == null) { String start_hour = request.getParameter("start_hour"); String start_minutes = request.getParameter("start_minutes"); String start_ampm = request.getParameter("start_ampm"); String end_hour = request.getParameter("end_hour"); String end_minutes = request.getParameter("end_minutes"); String end_ampm = request.getParameter("end_ampm"); if (Integer.parseInt(start_hour) < 10) { start_hour = "0" + start_hour; } if (Integer.parseInt(end_hour) < 10) { end_hour = "0" + end_hour; } start_time = start_hour + ":" + start_minutes + " " + start_ampm; end_time = end_hour + ":" + end_minutes + " " + end_ampm; } Event event = null; if (!start_time.equals("") && !end_time.equals("")) { event = new Event(title, description, month, day, year, start_time, end_time); } else { event = new Event(title, description, month, day, year); } if (event.updateEvent(id)) { notice = "Calendar event updated!"; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } else { notice = "Error updating calendar event."; request.setAttribute("notice", notice); request.setAttribute("event", event); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/add_event.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("delete_event")) { int id = Integer.parseInt(request.getParameter("id")); Event event = new Event(); if (event.deleteEvent(id)) { notice = "Calendar event successfully deleted."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_events"); dispatcher.forward(request, response); return; } else { notice = "Error deleting event from the database."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_events"); dispatcher.forward(request, response); return; } } else if (action.equals("edit_members")) { String sql = "SELECT * FROM person ORDER BY lname"; if (request.getParameter("member_type") != null) { String member_type = request.getParameter("member_type"); if (member_type.equals("all")) { sql = "SELECT * FROM person ORDER BY lname"; } else { sql = "SELECT * FROM person where member_type LIKE '" + member_type + "' ORDER BY lname"; } request.setAttribute("member_type", member_type); } try { dbStatement = connection.createStatement(); dbResultSet = dbStatement.executeQuery(sql); request.setAttribute("resultset", dbResultSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/edit_members.jsp"); dispatcher.forward(request, response); return; } catch (SQLException e) { notice = "Error retrieving members from the database."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("edit_person")) { int id = Integer.parseInt(request.getParameter("id")); String member_type = request.getParameter("member_type"); Person person = new Person(); person = person.getPerson(id); if (member_type.equals("student")) { Student student = person.getStudent(); request.setAttribute("student", student); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/edit_student.jsp"); dispatcher.forward(request, response); return; } else if (member_type.equals("alumni")) { Alumni alumni = person.getAlumni(); request.setAttribute("alumni", alumni); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/edit_alumni.jsp"); dispatcher.forward(request, response); return; } else if (member_type.equals("hospital")) { Hospital hospital = person.getHospital(id); request.setAttribute("hospital", hospital); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/edit_hospital.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("update_alumni")) { int person_id = Integer.parseInt(request.getParameter("person_id")); Person person = new Person(); person = person.getPerson(person_id); Alumni cur_alumni = person.getAlumni(); String fname = request.getParameter("fname"); String lname = request.getParameter("lname"); String address1 = request.getParameter("address1"); String address2 = request.getParameter("address2"); String city = request.getParameter("city"); String state = request.getParameter("state"); String zip = request.getParameter("zip"); String email = request.getParameter("email"); String company_name = request.getParameter("company_name"); String position = request.getParameter("position"); int mentor = 0; if (request.getParameter("mentor") != null) { mentor = 1; } String graduation_date = request.getParameter("graduation_year") + "-" + request.getParameter("graduation_month") + "-01"; String password = ""; if (request.getParameter("password") != null) { password = request.getParameter("password"); MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); md.update(password.getBytes("UTF-8")); } catch (Exception x) { notice = "Could not encrypt your password. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } password = (new BASE64Encoder()).encode(md.digest()); } else { password = cur_alumni.getPassword(); } int is_admin = 0; if (request.getParameter("is_admin") != null) { is_admin = 1; } Alumni new_alumni = new Alumni(fname, lname, address1, address2, city, state, zip, email, password, is_admin, company_name, position, graduation_date, mentor); if (!new_alumni.getEmail().equals(cur_alumni.getEmail())) { if (new_alumni.checkEmailIsRegistered()) { notice = "That email address is already registered!"; request.setAttribute("notice", notice); request.setAttribute("alumni", new_alumni); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } } if (!new_alumni.updateAlumni(person_id)) { session.setAttribute("alumni", new_alumni); notice = "There was an error saving your information. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } notice = "Member information successfully updated."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } else if (action.equals("update_hospital")) { int person_id = Integer.parseInt(request.getParameter("person_id")); Person person = new Person(); person = person.getPerson(person_id); Hospital cur_hospital = person.getHospital(person_id); String fname = request.getParameter("fname"); String lname = request.getParameter("lname"); String address1 = request.getParameter("address1"); String address2 = request.getParameter("address2"); String city = request.getParameter("city"); String state = request.getParameter("state"); String zip = request.getParameter("zip"); String email = request.getParameter("email"); String name = request.getParameter("name"); String phone = request.getParameter("phone"); String url = request.getParameter("url"); String password = ""; if (cur_hospital.getPassword() != null) { if (request.getParameter("password") != null && !request.getParameter("password").equals("")) { password = request.getParameter("password"); MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); md.update(password.getBytes("UTF-8")); } catch (Exception x) { notice = "Could not encrypt your password. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } password = (new BASE64Encoder()).encode(md.digest()); } else { password = cur_hospital.getPassword(); } } int is_admin = 0; if (request.getParameter("is_admin") != null) { is_admin = 1; } Hospital new_hospital = new Hospital(fname, lname, address1, address2, city, state, zip, email, password, is_admin, name, phone, url); if (!new_hospital.getEmail().equals(cur_hospital.getEmail())) { if (new_hospital.checkEmailIsRegistered()) { notice = "That email address is already registered!"; request.setAttribute("notice", notice); request.setAttribute("hospital", new_hospital); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } } if (!new_hospital.updateHospital(person_id)) { session.setAttribute("hospital", new_hospital); notice = "There was an error saving your information. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } notice = "Information successfully updated."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } else if (action.equals("update_student")) { int person_id = Integer.parseInt(request.getParameter("person_id")); Person person = new Person(); person = person.getPerson(person_id); Student cur_student = person.getStudent(); String fname = request.getParameter("fname"); String lname = request.getParameter("lname"); String address1 = request.getParameter("address1"); String address2 = request.getParameter("address2"); String city = request.getParameter("city"); String state = request.getParameter("state"); String zip = request.getParameter("zip"); String email = request.getParameter("email"); String start_date = request.getParameter("start_year") + "-" + request.getParameter("start_month") + "-01"; String graduation_date = ""; if (!request.getParameter("grad_year").equals("") && !request.getParameter("grad_month").equals("")) { graduation_date = request.getParameter("grad_year") + "-" + request.getParameter("grad_month") + "-01"; } String password = ""; if (request.getParameter("password") != null && !request.getParameter("password").equals("")) { password = request.getParameter("password"); MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); md.update(password.getBytes("UTF-8")); } catch (Exception x) { notice = "Could not encrypt your password. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } password = (new BASE64Encoder()).encode(md.digest()); } else { password = cur_student.getPassword(); } int is_admin = 0; if (request.getParameter("is_admin") != null) { is_admin = 1; } Student new_student = new Student(fname, lname, address1, address2, city, state, zip, email, password, is_admin, start_date, graduation_date); if (!new_student.getEmail().equals(cur_student.getEmail())) { if (new_student.checkEmailIsRegistered()) { notice = "That email address is already registered!"; request.setAttribute("notice", notice); request.setAttribute("student", new_student); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } } if (!new_student.updateStudent(person_id)) { notice = "There was an error saving your information. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } notice = "Information successfully updated."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } else if (action.equals("delete_person")) { int id = Integer.parseInt(request.getParameter("id")); String member_type = request.getParameter("member_type"); Person person = new Person(); person = person.getPerson(id); if (person.deletePerson(member_type)) { notice = person.getFname() + ' ' + person.getLname() + " successfully deleted from database."; request.setAttribute("notice", notice); person = null; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members&member_type=all"); dispatcher.forward(request, response); return; } } else if (action.equals("manage_pages")) { String sql = "SELECT * FROM pages WHERE parent_id=0 OR parent_id IN (SELECT id FROM pages WHERE title LIKE 'root')"; if (request.getParameter("id") != null) { int id = Integer.parseInt(request.getParameter("id")); sql = "SELECT * FROM pages WHERE parent_id=" + id; } try { dbStatement = connection.createStatement(); dbResultSet = dbStatement.executeQuery(sql); request.setAttribute("resultset", dbResultSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/edit_pages.jsp"); dispatcher.forward(request, response); return; } catch (SQLException e) { notice = "Error retrieving content pages from the database."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("add_page")) { String sql = "SELECT id, title FROM pages WHERE parent_id=0 OR parent_id IN (SELECT id FROM pages WHERE title LIKE 'root')"; try { dbStatement = connection.createStatement(); dbResultSet = dbStatement.executeQuery(sql); request.setAttribute("resultset", dbResultSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/add_page.jsp"); dispatcher.forward(request, response); return; } catch (SQLException e) { notice = "Error retrieving content pages from the database."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("save_page")) { String title = request.getParameter("title"); String content = request.getParameter("content"); Page page = null; if (request.getParameter("parent_id") != null) { int parent_id = Integer.parseInt(request.getParameter("parent_id")); page = new Page(title, content, parent_id); } else { page = new Page(title, content, 0); } if (page.savePage()) { notice = "Content page saved!"; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } else { notice = "There was an error saving the page."; request.setAttribute("page", page); request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/add_page.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("edit_page")) { String sql = "SELECT * FROM pages WHERE parent_id=0"; int id = Integer.parseInt(request.getParameter("id")); Page page = new Page(); page = page.getPage(id); try { dbStatement = connection.createStatement(); dbResultSet = dbStatement.executeQuery(sql); request.setAttribute("resultset", dbResultSet); } catch (SQLException e) { notice = "Error retrieving content pages from the database."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } if (page != null) { request.setAttribute("page", page); request.setAttribute("id", Integer.toString(id)); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/add_page.jsp"); dispatcher.forward(request, response); return; } else { notice = "Error retrieving content page from the database."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("update_page")) { int id = Integer.parseInt(request.getParameter("id")); String title = request.getParameter("title"); String content = request.getParameter("content"); int parent_id = 0; if (request.getParameter("parent_id") != null) { parent_id = Integer.parseInt(request.getParameter("parent_id")); } Page page = new Page(title, content, parent_id); if (page.updatePage(id)) { notice = "Content page was updated successfully."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } else { notice = "Error updating the content page."; request.setAttribute("notice", notice); request.setAttribute("page", page); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/add_page.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("delete_page")) { int id = Integer.parseInt(request.getParameter("id")); Page page = new Page(); if (page.deletePage(id)) { notice = "Content page (and sub pages) deleted successfully."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } else { notice = "Error deleting the content page(s)."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("list_residencies")) { Residency residency = new Residency(); dbResultSet = residency.getResidencies(); request.setAttribute("result", dbResultSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/list_residencies.jsp"); dispatcher.forward(request, response); return; } else if (action.equals("delete_residency")) { int job_id = Integer.parseInt(request.getParameter("id")); Residency residency = new Residency(); if (residency.deleteResidency(job_id)) { notice = "Residency has been successfully deleted."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=list_residencies"); dispatcher.forward(request, response); return; } else { notice = "Error deleting the residency."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("edit_residency")) { int job_id = Integer.parseInt(request.getParameter("id")); Residency residency = new Residency(); dbResultSet = residency.getResidency(job_id); if (dbResultSet != null) { try { int hId = dbResultSet.getInt("hospital_id"); String hName = residency.getHospitalName(hId); request.setAttribute("hName", hName); dbResultSet.beforeFirst(); } catch (SQLException e) { error = "There was an error retreiving the residency."; session.setAttribute("error", error); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/error.jsp"); dispatcher.forward(request, response); return; } request.setAttribute("result", dbResultSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/edit_residency.jsp"); dispatcher.forward(request, response); return; } else { notice = "There was an error in locating the residency you selected."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("new_residency")) { Residency residency = new Residency(); dbResultSet = residency.getHospitals(); request.setAttribute("result", dbResultSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/add_residency.jsp"); dispatcher.forward(request, response); return; } else if (action.equals("add_residency")) { Person person = (Person) session.getAttribute("person"); if (person.isAdmin()) { String hName = request.getParameter("hName"); String title = request.getParameter("title"); String description = request.getParameter("description"); String start_month = request.getParameter("startDateMonth"); String start_day = request.getParameter("startDateDay"); String start_year = request.getParameter("startDateYear"); String start_date = start_year + start_month + start_day; String end_month = request.getParameter("endDateMonth"); String end_day = request.getParameter("endDateDay"); String end_year = request.getParameter("endDateYear"); String end_date = end_year + end_month + end_day; String deadline_month = request.getParameter("deadlineDateMonth"); String deadline_day = request.getParameter("deadlineDateDay"); String deadline_year = request.getParameter("deadlineDateYear"); String deadline_date = deadline_year + deadline_month + deadline_day; int hId = Integer.parseInt(request.getParameter("hId")); Residency residency = new Residency(title, start_date, end_date, deadline_date, description, hId); if (residency.saveResidency()) { notice = "Residency has been successfully saved."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=list_residencies"); dispatcher.forward(request, response); return; } else { notice = "Error saving the residency."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } } RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } else if (action.equals("update_residency")) { Person person = (Person) session.getAttribute("person"); int job_id = Integer.parseInt(request.getParameter("job_id")); if (person.isAdmin()) { String hName = request.getParameter("hName"); String title = request.getParameter("title"); String description = request.getParameter("description"); String start_month = request.getParameter("startDateMonth"); String start_day = request.getParameter("startDateDay"); String start_year = request.getParameter("startDateYear"); String start_date = start_year + start_month + start_day; String end_month = request.getParameter("endDateMonth"); String end_day = request.getParameter("endDateDay"); String end_year = request.getParameter("endDateYear"); String end_date = end_year + end_month + end_day; String deadline_month = request.getParameter("deadlineDateMonth"); String deadline_day = request.getParameter("deadlineDateDay"); String deadline_year = request.getParameter("deadlineDateYear"); String deadline_date = deadline_year + deadline_month + deadline_day; int hId = Integer.parseInt(request.getParameter("hId")); Residency residency = new Residency(job_id, title, start_date, end_date, deadline_date, description); if (residency.updateResidency(job_id)) { notice = "Residency has been successfully saved."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=list_residencies"); dispatcher.forward(request, response); return; } else { notice = "Error saving the residency."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } } RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } else if (action.equals("add_hospital")) { Person person = (Person) session.getAttribute("person"); if (person.isAdmin()) { String name = request.getParameter("name"); String url = request.getParameter("url"); String address1 = request.getParameter("address1"); String address2 = request.getParameter("address2"); String city = request.getParameter("city"); String state = request.getParameter("state"); String zip = request.getParameter("zip"); String phone = request.getParameter("phone"); String lname = request.getParameter("name"); Hospital hospital = new Hospital(lname, address1, address2, city, state, zip, name, phone, url); if (!hospital.saveHospitalAdmin()) { notice = "There was an error saving your information. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=new_residency"); dispatcher.forward(request, response); return; } else { notice = "Unknown request. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("Get Admin News List")) { News news = new News(); if (news.getNewsList() != null) { dbResultSet = news.getNewsList(); request.setAttribute("result", dbResultSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/list.jsp"); dispatcher.forward(request, response); return; } else { notice = "Could not get news list."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("Get News List")) { News news = new News(); if (news.getNewsList() != null) { dbResultSet = news.getNewsList(); request.setAttribute("result", dbResultSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/news_list.jsp"); dispatcher.forward(request, response); return; } else { notice = "Could not get news list."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/gsu_fhce/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("detail")) { String id = request.getParameter("id"); News news = new News(); if (news.getNewsDetail(id) != null) { dbResultSet = news.getNewsDetail(id); request.setAttribute("result", dbResultSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/news_detail.jsp"); dispatcher.forward(request, response); return; } else { notice = "Could not get news detail."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("delete")) { int id = 0; id = Integer.parseInt(request.getParameter("id")); News news = new News(); if (news.deleteNews(id)) { notice = "News successfully deleted."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=Get Admin News List"); dispatcher.forward(request, response); return; } else { notice = "Error deleting the news."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=Get Admin News List"); dispatcher.forward(request, response); return; } } else if (action.equals("edit")) { int id = Integer.parseInt(request.getParameter("id")); News news = new News(); news = news.getNews(id); if (news != null) { request.setAttribute("news", news); request.setAttribute("id", Integer.toString(id)); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/news_update.jsp"); dispatcher.forward(request, response); return; } else { notice = "Error retrieving news from the database."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("Update News")) { String title = request.getParameter("title"); String date = (request.getParameter("year")) + (request.getParameter("month")) + (request.getParameter("day")); String content = request.getParameter("content"); int id = Integer.parseInt(request.getParameter("newsid")); News news = new News(title, date, content); if (news.updateNews(id)) { notice = "News successfully updated."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=Get Admin News List"); dispatcher.forward(request, response); return; } else { notice = "Could not update news."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=Get Admin News List"); dispatcher.forward(request, response); return; } } else if (action.equals("Add News")) { String id = ""; String title = request.getParameter("title"); String date = request.getParameter("year") + "-" + request.getParameter("month") + "-" + request.getParameter("day"); String content = request.getParameter("content"); News news = new News(title, date, content); if (news.addNews()) { notice = "News successfully added."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=Get Admin News List"); dispatcher.forward(request, response); return; } else { notice = "Could not add news."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("manage_mship")) { Mentor mentor = new Mentor(); dbResultSet = mentor.getMentorships(); if (dbResultSet != null) { request.setAttribute("result", dbResultSet); } else { notice = "There are no current mentorships."; request.setAttribute("notice", notice); } RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/list_mentorships.jsp"); dispatcher.forward(request, response); return; } else if (action.equals("delete_mship")) { int mentorship_id = Integer.parseInt(request.getParameter("id")); Mentor mentor = new Mentor(); if (mentor.delMentorship(mentorship_id)) { notice = "Mentorship successfully deleted."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=manage_mship"); dispatcher.forward(request, response); return; } else { notice = "Error deleting the mentorship."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=manage_mship"); dispatcher.forward(request, response); return; } } else if (action.equals("new_mship")) { Mentor mentor = new Mentor(); ResultSet alumnis = null; ResultSet students = null; alumnis = mentor.getAlumnis(); students = mentor.getStudents(); request.setAttribute("alumni_result", alumnis); request.setAttribute("student_result", students); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/create_mship.jsp"); dispatcher.forward(request, response); return; } else if (action.equals("create_mship")) { int student_id = Integer.parseInt(request.getParameter("student_id")); int alumni_id = Integer.parseInt(request.getParameter("alumni_id")); Mentor mentor = new Mentor(); if (mentor.addMentorship(student_id, alumni_id)) { notice = "Mentorship successfully created."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=manage_mship"); dispatcher.forward(request, response); return; } else { notice = "There was an error creating the mentorship."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/create_mship.jsp"); dispatcher.forward(request, response); return; } } } | 13,679 |
0 | @Override public DataTable generateDataTable(Query query, HttpServletRequest request) throws DataSourceException { String url = request.getParameter(URL_PARAM_NAME); if (StringUtils.isEmpty(url)) { log.error("url parameter not provided."); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url parameter not provided"); } Reader reader; try { reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); } catch (MalformedURLException e) { log.error("url is malformed: " + url); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url is malformed: " + url); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } DataTable dataTable = null; ULocale requestLocale = DataSourceHelper.getLocaleFromRequest(request); try { dataTable = CsvDataSourceHelper.read(reader, null, true, requestLocale); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } return dataTable; } | private BibtexDatabase parseBibtexDatabase(List<String> id, boolean abs) throws IOException { if (id.isEmpty()) { return null; } URL url; URLConnection conn; try { url = new URL(importUrl); conn = url.openConnection(); } catch (MalformedURLException e) { e.printStackTrace(); return null; } conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Referer", searchUrl); PrintWriter out = new PrintWriter(conn.getOutputStream()); String recordIds = ""; Iterator<String> iter = id.iterator(); while (iter.hasNext()) { recordIds += iter.next() + " "; } recordIds = recordIds.trim(); String citation = abs ? "citation-abstract" : "citation-only"; String content = "recordIds=" + recordIds.replaceAll(" ", "%20") + "&fromPageName=&citations-format=" + citation + "&download-format=download-bibtex"; System.out.println(content); out.write(content); out.flush(); out.close(); BufferedReader bufr = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); char[] buffer = new char[256]; while (true) { int bytesRead = bufr.read(buffer); if (bytesRead == -1) { break; } for (int i = 0; i < bytesRead; i++) { sb.append((char) buffer[i]); } } System.out.println(sb.toString()); ParserResult results = new BibtexParser(bufr).parse(); bufr.close(); return results.getDatabase(); } | 13,680 |
0 | 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(); } | public String plainStringToMD5(String input) { MessageDigest md = null; byte[] byteHash = null; StringBuffer resultString = new StringBuffer(); try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.exit(-1); } md.reset(); md.update(input.getBytes()); byteHash = md.digest(); for (int i = 0; i < byteHash.length; i++) { resultString.append(Integer.toHexString(0xFF & byteHash[i])); } return (resultString.toString()); } | 13,681 |
1 | private void copyFile(String fileName, String messageID, boolean isError) { try { File inputFile = new File(fileName); File outputFile = null; if (isError) { outputFile = new File(provider.getErrorDataLocation(folderName) + messageID + ".xml"); } else { outputFile = new File(provider.getDataProcessedLocation(folderName) + messageID + ".xml"); } FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception e) { } } | private void copyOutResource(String dstPath, InputStream in) throws FileNotFoundException, IOException { FileOutputStream out = null; try { dstPath = this.outputDir + dstPath; File file = new File(dstPath); file.getParentFile().mkdirs(); out = new FileOutputStream(file); IOUtils.copy(in, out); } finally { if (out != null) { out.close(); } } } | 13,682 |
1 | private static void setEnvEntry(File fromEAR, File toEAR, String ejbJarName, String envEntryName, String envEntryValue) throws Exception { ZipInputStream earFile = new ZipInputStream(new FileInputStream(fromEAR)); FileOutputStream fos = new FileOutputStream(toEAR); ZipOutputStream tempZip = new ZipOutputStream(fos); ZipEntry next = earFile.getNextEntry(); while (next != null) { ByteArrayOutputStream content = new ByteArrayOutputStream(); byte[] data = new byte[30000]; int numberread; while ((numberread = earFile.read(data)) != -1) { content.write(data, 0, numberread); } if (next.getName().equals(ejbJarName)) { content = editEJBJAR(next, content, envEntryName, envEntryValue); next = new ZipEntry(ejbJarName); } tempZip.putNextEntry(next); tempZip.write(content.toByteArray()); next = earFile.getNextEntry(); } earFile.close(); tempZip.close(); fos.close(); } | private void collectImageFile(@NotNull final Progress progress, @NotNull final File collectedDirectory) throws IOException { final File file = new File(collectedDirectory, ActionBuilderUtils.getString(ACTION_BUILDER, "configSource.image.name")); final FileOutputStream fos = new FileOutputStream(file); try { final FileChannel outChannel = fos.getChannel(); try { final int numOfFaceObjects = faceObjects.size(); progress.setLabel(ActionBuilderUtils.getString(ACTION_BUILDER, "archCollectImages"), numOfFaceObjects); final ByteBuffer byteBuffer = ByteBuffer.allocate(1024); final Charset charset = Charset.forName("ISO-8859-1"); int i = 0; for (final FaceObject faceObject : faceObjects) { final String face = faceObject.getFaceName(); final String path = archFaceProvider.getFilename(face); try { final FileInputStream fin = new FileInputStream(path); try { final FileChannel inChannel = fin.getChannel(); final long imageSize = inChannel.size(); byteBuffer.clear(); byteBuffer.put(("IMAGE " + (faceObjects.isIncludeFaceNumbers() ? i + " " : "") + imageSize + " " + face + "\n").getBytes(charset)); byteBuffer.flip(); outChannel.write(byteBuffer); inChannel.transferTo(0L, imageSize, outChannel); } finally { fin.close(); } } catch (final FileNotFoundException ignored) { ACTION_BUILDER.showMessageDialog(progress.getParentComponent(), "archCollectErrorFileNotFound", path); return; } catch (final IOException e) { ACTION_BUILDER.showMessageDialog(progress.getParentComponent(), "archCollectErrorIOException", path, e); return; } if (i++ % 100 == 0) { progress.setValue(i); } } progress.setValue(faceObjects.size()); } finally { outChannel.close(); } } finally { fos.close(); } } | 13,683 |
0 | private static <T> Collection<T> loadFromServices(Class<T> interf) throws Exception { ClassLoader classLoader = DSServiceLoader.class.getClassLoader(); Enumeration<URL> e = classLoader.getResources("META-INF/services/" + interf.getName()); Collection<T> services = new ArrayList<T>(); while (e.hasMoreElements()) { URL url = e.nextElement(); InputStream is = url.openStream(); try { BufferedReader r = new BufferedReader(new InputStreamReader(is, "UTF-8")); while (true) { String line = r.readLine(); if (line == null) { break; } int comment = line.indexOf('#'); if (comment >= 0) { line = line.substring(0, comment); } String name = line.trim(); if (name.length() == 0) { continue; } Class<?> clz = Class.forName(name, true, classLoader); Class<? extends T> impl = clz.asSubclass(interf); Constructor<? extends T> ctor = impl.getConstructor(); T svc = ctor.newInstance(); services.add(svc); } } finally { is.close(); } } return services; } | public void testPreparedStatement0009() throws Exception { Connection cx = getConnection(); dropTable("#t0009"); Statement stmt = cx.createStatement(); stmt.executeUpdate("create table #t0009 " + " (i integer not null, " + " s char(10) not null) "); cx.setAutoCommit(false); PreparedStatement pStmt = cx.prepareStatement("insert into #t0009 values (?, ?)"); int rowsToAdd = 8; final String theString = "abcdefghijklmnopqrstuvwxyz"; int count = 0; for (int i = 1; i <= rowsToAdd; i++) { pStmt.setInt(1, i); pStmt.setString(2, theString.substring(0, i)); count += pStmt.executeUpdate(); } assertTrue(count == rowsToAdd); cx.rollback(); stmt = cx.createStatement(); ResultSet rs = stmt.executeQuery("select s, i from #t0009"); assertNotNull(rs); count = 0; while (rs.next()) { count++; assertTrue(rs.getString(1).trim().length() == rs.getInt(2)); } assertTrue(count == 0); cx.commit(); rowsToAdd = 6; count = 0; for (int i = 1; i <= rowsToAdd; i++) { pStmt.setInt(1, i); pStmt.setString(2, theString.substring(0, i)); count += pStmt.executeUpdate(); } assertTrue(count == rowsToAdd); cx.commit(); rs = stmt.executeQuery("select s, i from #t0009"); count = 0; while (rs.next()) { count++; assertTrue(rs.getString(1).trim().length() == rs.getInt(2)); } assertTrue(count == rowsToAdd); cx.commit(); cx.setAutoCommit(true); } | 13,684 |
1 | private String unzip(TupleInput input) { boolean zipped = input.readBoolean(); if (!zipped) { return input.readString(); } int len = input.readInt(); try { byte array[] = new byte[len]; input.read(array); GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(array)); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copyTo(in, out); in.close(); out.close(); return new String(out.toByteArray()); } catch (IOException err) { throw new RuntimeException(err); } } | public void show(HttpServletRequest request, HttpServletResponse response, String pantalla, Atributos modelos) { URL url = getRecurso(pantalla); try { IOUtils.copy(url.openStream(), response.getOutputStream()); } catch (IOException e) { throw new RuntimeException(e); } } | 13,685 |
0 | public Result search(Object object) { if (object == null || !(object instanceof String)) { return null; } String query = (String) object; Result hitResult = new Result(); Set<Hit> hits = new HashSet<Hit>(8); try { query = URLEncoder.encode(query, "UTF-8"); URL url = new URL("http://ajax.googleapis.com/ajax/services/search/web?start=0&rsz=large&v=1.0&q=" + query); URLConnection connection = url.openConnection(); connection.addRequestProperty("Referer", HTTP_REFERER); String line; StringBuilder builder = new StringBuilder(); InputStream input = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); while ((line = reader.readLine()) != null) { builder.append(line); } input.close(); String response = builder.toString(); JSONObject json = new JSONObject(response); LOGGER.debug(json.getString("responseData")); int count = json.getJSONObject("responseData").getJSONObject("cursor").getInt("estimatedResultCount"); hitResult.setEstimatedCount(count); JSONArray ja = json.getJSONObject("responseData").getJSONArray("results"); for (int i = 0; i < ja.length(); i++) { JSONObject j = ja.getJSONObject(i); Hit hit = new Hit(); String result = j.getString("titleNoFormatting"); hit.setTitle(result == null || result.equals("") ? "${EMPTY}" : result); result = j.getString("url"); hit.setUrl(new URL(result)); hits.add(hit); } } catch (Exception e) { e.printStackTrace(); LOGGER.error("Something went wrong..." + e.getMessage()); } hitResult.setHits(hits); return hitResult; } | public static void copyFile(File source, File destination) { if (!source.exists()) { return; } if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) { destination.getParentFile().mkdirs(); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } | 13,686 |
1 | public static void main(String[] args) throws Exception { TripleDES tdes = new TripleDES(); StreamBlockReader reader = new StreamBlockReader(new FileInputStream("D:\\testTDESENC.txt")); StreamBlockWriter writer = new StreamBlockWriter(new FileOutputStream("D:\\testTDESDEC.txt")); SingleKey key = new SingleKey(new Block(128), ""); key = new SingleKey(new Block("01011101110000101001100111001011101000001110111101001001101101101101100000011101100100110000101100001110000001111101001101001101"), ""); Mode mode = new ECBTripleDESMode(tdes); tdes.decrypt(reader, writer, key, mode); } | private void output(HttpServletResponse resp, InputStream is, long length, String fileName) throws Exception { resp.reset(); String mimeType = "image/jpeg"; resp.setContentType(mimeType); resp.setContentLength((int) length); resp.setHeader("Content-Disposition", "inline; filename=\"" + fileName + "\""); resp.setHeader("Cache-Control", "must-revalidate"); ServletOutputStream sout = resp.getOutputStream(); IOUtils.copy(is, sout); sout.flush(); resp.flushBuffer(); } | 13,687 |
0 | protected BufferedImage handleGMUException() { if (params.uri.startsWith("http://mars.gmu.edu:8080")) try { URLConnection connection = new URL(params.uri).openConnection(); int index = params.uri.lastIndexOf("?"); params.uri = "<img class=\"itemthumb\" src=\""; BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String url = null; while ((url = reader.readLine()) != null) { index = url.indexOf(params.uri); if (index != -1) { url = "http://mars.gmu.edu:8080" + url.substring(index + 28); url = url.substring(0, url.indexOf("\" alt=\"")); break; } } if (url != null) { connection = new URL(url).openConnection(); return processNewUri(connection); } } catch (Exception e) { } return null; } | public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { if (System.getProperty("os.name").toUpperCase().indexOf("WIN") != -1) { int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } } else { inChannel.transferTo(0, inChannel.size(), outChannel); } } finally { if (inChannel != null) try { inChannel.close(); } catch (Exception e) { } ; if (outChannel != null) try { outChannel.close(); } catch (Exception e) { } ; } } | 13,688 |
1 | public static void copyDirs(File sourceDir, File destDir) throws IOException { if (!destDir.exists()) destDir.mkdirs(); for (File file : sourceDir.listFiles()) { if (file.isDirectory()) { copyDirs(file, new File(destDir, file.getName())); } else { FileChannel srcChannel = new FileInputStream(file).getChannel(); File out = new File(destDir, file.getName()); out.createNewFile(); FileChannel dstChannel = new FileOutputStream(out).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } } } | public void verRecordatorio() { try { cantidadArchivos = obtenerCantidad() + 1; boolean existe = false; String filenametxt = ""; String filenamezip = ""; String hora = ""; String lugar = ""; String actividad = ""; String linea = ""; int dia = 0; int mes = 0; int ano = 0; for (int i = 1; i < cantidadArchivos; i++) { filenamezip = "recordatorio" + i + ".zip"; filenametxt = "recordatorio" + i + ".txt"; BufferedOutputStream dest = null; BufferedInputStream is = null; ZipEntry entry; ZipFile zipfile = new ZipFile(filenamezip); Enumeration e = zipfile.entries(); while (e.hasMoreElements()) { entry = (ZipEntry) e.nextElement(); is = new BufferedInputStream(zipfile.getInputStream(entry)); int count; byte data[] = new byte[buffer]; FileOutputStream fos = new FileOutputStream(entry.getName()); dest = new BufferedOutputStream(fos, buffer); while ((count = is.read(data, 0, buffer)) != -1) dest.write(data, 0, count); dest.flush(); dest.close(); is.close(); } DataInputStream input = new DataInputStream(new FileInputStream(filenametxt)); dia = Integer.parseInt(input.readLine()); mes = Integer.parseInt(input.readLine()); ano = Integer.parseInt(input.readLine()); if (dia == Integer.parseInt(identificarDato(datoSeleccionado))) { existe = true; hora = input.readLine(); lugar = input.readLine(); while ((linea = input.readLine()) != null) actividad += linea + "\n"; verRecordatorioInterfaz(hora, lugar, actividad); hora = ""; lugar = ""; actividad = ""; } input.close(); } if (!existe) JOptionPane.showMessageDialog(null, "No existe un recordatorio guardado\n" + "para el " + identificarDato(datoSeleccionado) + " de " + meses[mesTemporal].toLowerCase() + " del a�o " + anoTemporal, "No existe", JOptionPane.INFORMATION_MESSAGE); table.clearSelection(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error en: " + e.toString(), "Error", JOptionPane.ERROR_MESSAGE); } } | 13,689 |
1 | private void getRandomGUID(boolean secure) throws NoSuchAlgorithmException { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); throw 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); } } | public static String hashURL(String url) { if (url == null) { throw new IllegalArgumentException("URL may not be null. "); } String result = null; try { MessageDigest md = MessageDigest.getInstance("SHA-1"); if (md != null) { md.reset(); md.update(url.getBytes()); BigInteger hash = new BigInteger(1, md.digest()); result = hash.toString(16); } md = null; } catch (NoSuchAlgorithmException ex) { result = null; } return result; } | 13,690 |
1 | public void write(PDDocument doc) throws COSVisitorException { document = doc; SecurityHandler securityHandler = document.getSecurityHandler(); if (securityHandler != null) { try { securityHandler.prepareDocumentForEncryption(document); this.willEncrypt = true; } catch (IOException e) { throw new COSVisitorException(e); } catch (CryptographyException e) { throw new COSVisitorException(e); } } else { this.willEncrypt = false; } COSDocument cosDoc = document.getDocument(); COSDictionary trailer = cosDoc.getTrailer(); COSArray idArray = (COSArray) trailer.getDictionaryObject("ID"); if (idArray == null) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(Long.toString(System.currentTimeMillis()).getBytes()); COSDictionary info = (COSDictionary) trailer.getDictionaryObject("Info"); if (info != null) { Iterator values = info.getValues().iterator(); while (values.hasNext()) { md.update(values.next().toString().getBytes()); } } idArray = new COSArray(); COSString id = new COSString(md.digest()); idArray.add(id); idArray.add(id); trailer.setItem("ID", idArray); } catch (NoSuchAlgorithmException e) { throw new COSVisitorException(e); } } cosDoc.accept(this); } | public static String stringToHash(String text) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); md.update(text.getBytes("iso-8859-1"), 0, text.length()); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("Should not happened: SHA-1 algorithm is missing."); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Should not happened: Could not encode text bytes '" + text + "' to iso-8859-1."); } return new String(Base64.encodeBase64(md.digest())); } | 13,691 |
0 | public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; } | private boolean downloadFile() { FTPClient ftp = new FTPClient(); try { int reply; ftp.connect(this.server); ResourcePool.LogMessage(this, ResourcePool.INFO_MESSAGE, "Connected to " + this.server); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "FTP server refused connection."); return false; } } catch (IOException e) { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { return false; } } ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "FTP Could not connect to server."); ResourcePool.LogException(e, this); return false; } try { if (!ftp.login(this.user, this.password)) { ftp.logout(); ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "FTP login failed."); return false; } ResourcePool.LogMessage(this, ResourcePool.INFO_MESSAGE, "Remote system is " + ftp.getSystemName()); if ((this.transferType != null) && (this.transferType.compareTo(FTPWorkerThread.ASCII) == 0)) { ftp.setFileType(FTP.ASCII_FILE_TYPE); } else { ftp.setFileType(FTP.BINARY_FILE_TYPE); } if ((this.passiveMode != null) && this.passiveMode.equalsIgnoreCase(FTPWorkerThread.FALSE)) { ftp.enterLocalActiveMode(); } else { ftp.enterLocalPassiveMode(); } } catch (FTPConnectionClosedException e) { ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "Server closed connection."); ResourcePool.LogException(e, this); return false; } catch (IOException e) { ResourcePool.LogException(e, this); return false; } OutputStream output; try { java.util.Date startDate = new java.util.Date(); output = new FileOutputStream(this.destFileName); ftp.retrieveFile(this.fileName, output); File f = new File(this.destFileName); if (f.exists() && (this.lastModifiedDate != null)) { f.setLastModified(this.lastModifiedDate.longValue()); } java.util.Date endDate = new java.util.Date(); this.downloadTime = endDate.getTime() - startDate.getTime(); double iDownLoadTime = ((this.downloadTime + 1) / 1000) + 1; ResourcePool.LogMessage(this, ResourcePool.INFO_MESSAGE, "Download Complete, Rate = " + (this.fileSize / (iDownLoadTime * 1024)) + " Kb/s, Seconds = " + iDownLoadTime); this.downloadTime = (this.downloadTime + 1) / 1000; if (ftp.isConnected()) { ftp.disconnect(); } } catch (FTPConnectionClosedException e) { ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, e.getMessage()); ResourcePool.LogException(e, this); return false; } catch (IOException e) { ResourcePool.LogException(e, this); return false; } return true; } | 13,692 |
0 | public TestReport runImpl() throws Exception { DefaultTestReport report = new DefaultTestReport(this); ParsedURL purl; try { purl = new ParsedURL(base); } catch (Exception e) { StringWriter trace = new StringWriter(); e.printStackTrace(new PrintWriter(trace)); report.setErrorCode(ERROR_CANNOT_PARSE_URL); report.setDescription(new TestReport.Entry[] { new TestReport.Entry(TestMessages.formatMessage(ENTRY_KEY_ERROR_DESCRIPTION, null), TestMessages.formatMessage(ERROR_CANNOT_PARSE_URL, new String[] { "null", base, trace.toString() })) }); report.setPassed(false); return report; } byte[] data = new byte[5]; int num = 0; try { InputStream is = purl.openStream(); num = is.read(data); } catch (IOException ioe) { ioe.printStackTrace(); } StringBuffer sb = new StringBuffer(); for (int i = 0; i < num; i++) { int val = ((int) data[i]) & 0xFF; if (val < 16) { sb.append("0"); } sb.append(Integer.toHexString(val) + " "); } String info = ("CT: " + purl.getContentType() + " CE: " + purl.getContentEncoding() + " DATA: " + sb + "URL: " + purl); if (ref.equals(info)) { report.setPassed(true); return report; } report.setErrorCode(ERROR_WRONG_RESULT); report.setDescription(new TestReport.Entry[] { new TestReport.Entry(TestMessages.formatMessage(ENTRY_KEY_ERROR_DESCRIPTION, null), TestMessages.formatMessage(ERROR_WRONG_RESULT, new String[] { info, ref })) }); report.setPassed(false); return report; } | private InputStream get(String url, long startOffset, long expectedLength) throws ClientProtocolException, IOException { url = normalizeUrl(url); Log.i(LOG_TAG, "Get " + url); mHttpGet = new HttpGet(url); int expectedStatusCode = HttpStatus.SC_OK; if (startOffset > 0) { String range = "bytes=" + startOffset + "-"; if (expectedLength >= 0) { range += expectedLength - 1; } Log.i(LOG_TAG, "requesting byte range " + range); mHttpGet.addHeader("Range", range); expectedStatusCode = HttpStatus.SC_PARTIAL_CONTENT; } HttpResponse response = mHttpClient.execute(mHttpGet); long bytesToSkip = 0; int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != expectedStatusCode) { if ((statusCode == HttpStatus.SC_OK) && (expectedStatusCode == HttpStatus.SC_PARTIAL_CONTENT)) { Log.i(LOG_TAG, "Byte range request ignored"); bytesToSkip = startOffset; } else { throw new IOException("Unexpected Http status code " + statusCode + " expected " + expectedStatusCode); } } HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); if (bytesToSkip > 0) { is.skip(bytesToSkip); } return is; } | 13,693 |
0 | public static synchronized int registerVote(String IDVotazione, byte[] T1, byte[] sbT2, byte[] envelope, Config config) { if (IDVotazione == null) { LOGGER.error("registerVote::IDV null"); return C_addVote_BOH; } if (T1 == null) { LOGGER.error("registerVote::T1 null"); return C_addVote_BOH; } if (envelope == null) { LOGGER.error("registerVote::envelope null"); return C_addVote_BOH; } LOGGER.info("registering vote started"); Connection conn = null; PreparedStatement stmt = null; boolean autoCommitPresent = true; int ANSWER = C_addVote_BOH; try { ByteArrayInputStream tmpXMLStream = new ByteArrayInputStream(envelope); SAXReader tmpXMLReader = new SAXReader(); Document doc = tmpXMLReader.read(tmpXMLStream); if (LOGGER.isTraceEnabled()) LOGGER.trace(doc.asXML()); String sT1 = new String(Base64.encodeBase64(T1), "utf-8"); String ssbT2 = new String(Base64.encodeBase64(sbT2), "utf-8"); String sEnvelope = new String(Base64.encodeBase64(envelope), "utf-8"); LOGGER.trace("loading jdbc driver ..."); Class.forName("com.mysql.jdbc.Driver"); LOGGER.trace("... loaded"); conn = DriverManager.getConnection(config.getSconn()); autoCommitPresent = conn.getAutoCommit(); conn.setAutoCommit(false); String query = "" + " INSERT INTO votes(IDVotazione, T1, signByT2 , envelope) " + " VALUES (? , ? , ? , ? ) "; stmt = conn.prepareStatement(query); stmt.setString(1, IDVotazione); stmt.setString(2, sT1); stmt.setString(3, ssbT2); stmt.setString(4, sEnvelope); stmt.executeUpdate(); stmt.close(); LOGGER.debug("vote saved for references, now start the parsing"); query = "" + " INSERT INTO risposte (IDVotazione, T1, IDquestion , myrisposta,freetext) " + " VALUES (? , ? , ? , ? ,?) "; stmt = conn.prepareStatement(query); Element question, itemsElem, rispostaElem; List<Element> rispList; String id, rispostaText, risposta, freeText, questionType; Iterator<Element> questionIterator = doc.selectNodes("/poll/manifest/question").iterator(); while (questionIterator.hasNext()) { question = (Element) questionIterator.next(); risposta = freeText = ""; id = question.attributeValue("id"); itemsElem = question.element("items"); questionType = itemsElem == null ? "" : itemsElem.attributeValue("type"); rispostaElem = question.element("myrisposta"); rispostaText = rispostaElem == null ? "" : rispostaElem.getText(); if (rispostaText.equals(Votazione.C_TAG_WHITE_XML)) { risposta = C_TAG_WHITE; } else if (rispostaText.equals(Votazione.C_TAG_NULL_XML)) { risposta = C_TAG_NULL; } else { if (!rispostaText.equals("") && LOGGER.isDebugEnabled()) LOGGER.warn("Risposta text should be empty!: " + rispostaText); risposta = C_TAG_BUG; if (questionType.equals("selection")) { Element rispItem = rispostaElem.element("item"); String tmpRisposta = rispItem.attributeValue("index"); if (tmpRisposta != null) { risposta = tmpRisposta; if (risposta.equals("0")) freeText = rispItem.getText(); } } else if (questionType.equals("borda")) { rispList = rispostaElem.elements("item"); if (rispList != null) { risposta = ""; String index, tokens; for (Element rispItem : rispList) { index = rispItem.attributeValue("index"); tokens = rispItem.attributeValue("tokens"); if (index.equals("0")) freeText = rispItem.getText(); if (risposta.length() > 0) risposta += ","; risposta += index + ":" + tokens; } } } else if (questionType.equals("ordering")) { rispList = rispostaElem.elements("item"); if (rispList != null) { risposta = ""; String index, order; for (Element rispItem : rispList) { index = rispItem.attributeValue("index"); order = rispItem.attributeValue("order"); if (index == null) { continue; } if (index.equals("0")) freeText = rispItem.getText(); if (risposta.length() > 0) risposta += ","; risposta += index + ":" + order; } } } else if (questionType.equals("multiple")) { rispList = rispostaElem.elements("item"); if (rispList != null) { risposta = ""; String index; for (Element rispItem : rispList) { index = rispItem.attributeValue("index"); if (index.equals("0")) freeText = rispItem.getText(); if (risposta.length() > 0) risposta += ","; risposta += index; } } } else if (questionType.equals("free")) { freeText = rispostaElem.element("item").getText(); risposta = ""; } } if (LOGGER.isTraceEnabled()) { LOGGER.trace("ID_QUESTION: " + id); LOGGER.trace("question type: " + questionType); LOGGER.trace("risposta: " + risposta); LOGGER.trace("freetext: " + freeText); } if (risposta.equals(C_TAG_BUG)) { LOGGER.error("Invalid answer"); LOGGER.error("T1: " + sT1); LOGGER.error("ID_QUESTION: " + id); LOGGER.error("question type: " + questionType); } stmt.setString(1, IDVotazione); stmt.setString(2, sT1); stmt.setString(3, id); stmt.setString(4, risposta); stmt.setString(5, freeText); stmt.addBatch(); } stmt.executeBatch(); stmt.close(); conn.commit(); ANSWER = C_addVote_OK; LOGGER.info("registering vote end successfully"); } catch (SQLException e) { try { conn.rollback(); } catch (Exception ex) { } if (e.getErrorCode() == 1062) { ANSWER = C_addVote_DUPLICATE; LOGGER.error("error while registering vote (duplication)"); } else { ANSWER = C_addVote_BOH; LOGGER.error("error while registering vote", e); } } catch (UnsupportedEncodingException e) { try { conn.rollback(); } catch (Exception ex) { } LOGGER.error("encoding error", e); ANSWER = C_addVote_BOH; } catch (DocumentException e) { LOGGER.error("DocumentException", e); ANSWER = C_addVote_BOH; } catch (ClassNotFoundException e) { try { conn.rollback(); } catch (Exception ex) { } LOGGER.error("error while registering vote", e); ANSWER = C_addVote_BOH; } catch (Exception e) { try { conn.rollback(); } catch (Exception ex) { } LOGGER.error("Unexpected exception while registering vote", e); ANSWER = C_addVote_BOH; } finally { try { conn.setAutoCommit(autoCommitPresent); conn.close(); } catch (Exception e) { } ; } return ANSWER; } | public static String mdFive(String string) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] array = new byte[32]; md.update(string.getBytes("iso-8859-1"), 0, string.length()); array = md.digest(); return convertToHex(array); } | 13,694 |
0 | 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; } | private String hashPassword(String password) { if (password != null && password.trim().length() > 0) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.trim().getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); return hash.toString(16); } catch (NoSuchAlgorithmException nsae) { } } return null; } | 13,695 |
0 | public void apop(String user, char[] secret) throws IOException, POP3Exception { if (timestamp == null) { throw new CommandNotSupportedException("No timestamp from server - APOP not possible"); } try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(timestamp.getBytes()); if (secret == null) secret = new char[0]; byte[] digest = md.digest(new String(secret).getBytes("ISO-8859-1")); mutex.lock(); sendCommand("APOP", new String[] { user, digestToString(digest) }); POP3Response response = readSingleLineResponse(); if (!response.isOK()) { throw new POP3Exception(response); } state = TRANSACTION; } catch (NoSuchAlgorithmException e) { throw new POP3Exception("Installed JRE doesn't support MD5 - APOP not possible"); } finally { mutex.release(); } } | static InputStream getFileAsStream(Class clazz, HandlerChain chain) { URL url = clazz.getResource(chain.file()); if (url == null) { url = Thread.currentThread().getContextClassLoader().getResource(chain.file()); } if (url == null) { String tmp = clazz.getPackage().getName(); tmp = tmp.replace('.', '/'); tmp += "/" + chain.file(); url = Thread.currentThread().getContextClassLoader().getResource(tmp); } if (url == null) { throw new UtilException("util.failed.to.find.handlerchain.file", clazz.getName(), chain.file()); } try { return url.openStream(); } catch (IOException e) { throw new UtilException("util.failed.to.parse.handlerchain.file", clazz.getName(), chain.file()); } } | 13,696 |
0 | private void updateUser(AddEditUserForm addform, HttpServletRequest request) throws Exception { Session hbsession = HibernateUtil.currentSession(); try { Transaction tx = hbsession.beginTransaction(); NvUsers user = (NvUsers) hbsession.load(NvUsers.class, addform.getLogin()); if (!addform.getPassword().equalsIgnoreCase("")) { MessageDigest md = (MessageDigest) MessageDigest.getInstance("MD5").clone(); md.update(addform.getPassword().getBytes("UTF-8")); byte[] pd = md.digest(); StringBuffer app = new StringBuffer(); for (int i = 0; i < pd.length; i++) { String s2 = Integer.toHexString(pd[i] & 0xFF); app.append((s2.length() == 1) ? "0" + s2 : s2); } user.setPassword(app.toString()); } ActionErrors errors = new ActionErrors(); HashMap cAttrs = addform.getCustomAttrs(); Query q1 = hbsession.createQuery("from org.nodevision.portal.hibernate.om.NvCustomAttrs as a"); Iterator attrs = q1.iterate(); HashMap attrInfos = new HashMap(); while (attrs.hasNext()) { NvCustomAttrs element = (NvCustomAttrs) attrs.next(); attrInfos.put(element.getAttrName(), element.getAttrType()); NvCustomValuesId id = new NvCustomValuesId(); id.setNvUsers(user); NvCustomValues value = new NvCustomValues(); id.setNvCustomAttrs(element); value.setId(id); if (element.getAttrType().equalsIgnoreCase("String")) { ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream serializer = new ObjectOutputStream(bout); serializer.writeObject(cAttrs.get(element.getAttrName()).toString()); value.setAttrValue(Hibernate.createBlob(bout.toByteArray())); } else if (element.getAttrType().equalsIgnoreCase("Boolean")) { Boolean valueBoolean = Boolean.FALSE; if (cAttrs.get(element.getAttrName()) != null) { valueBoolean = Boolean.TRUE; } ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream serializer = new ObjectOutputStream(bout); serializer.writeObject(valueBoolean); value.setAttrValue(Hibernate.createBlob(bout.toByteArray())); } else if (element.getAttrType().equalsIgnoreCase("Date")) { Date date = new Date(0); if (!cAttrs.get(element.getAttrName()).toString().equalsIgnoreCase("")) { String bdate = cAttrs.get(element.getAttrName()).toString(); SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy"); date = df.parse(bdate); } ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream serializer = new ObjectOutputStream(bout); serializer.writeObject(date); value.setAttrValue(Hibernate.createBlob(bout.toByteArray())); } hbsession.saveOrUpdate(value); hbsession.flush(); } String bdate = addform.getUser_bdate(); SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy"); Date parsedDate = df.parse(bdate); user.setTimezone(addform.getTimezone()); user.setLocale(addform.getLocale()); user.setBdate(new BigDecimal(parsedDate.getTime())); user.setGender(addform.getUser_gender()); user.setEmployer(addform.getEmployer()); user.setDepartment(addform.getDepartment()); user.setJobtitle(addform.getJobtitle()); user.setNamePrefix(addform.getName_prefix()); user.setNameGiven(addform.getName_given()); user.setNameFamily(addform.getName_famliy()); user.setNameMiddle(addform.getName_middle()); user.setNameSuffix(addform.getName_suffix()); user.setHomeName(addform.getHome_name()); user.setHomeStreet(addform.getHome_street()); user.setHomeStateprov(addform.getHome_stateprov()); user.setHomePostalcode(addform.getHome_postalcode().equalsIgnoreCase("") ? new Integer(0) : new Integer(addform.getHome_postalcode())); user.setHomeOrganization(addform.getHome_organization_name()); user.setHomeCountry(addform.getHome_country()); user.setHomeCity(addform.getHome_city()); user.setHomePhoneIntcode((addform.getHome_phone_intcode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_phone_intcode())); user.setHomePhoneLoccode((addform.getHome_phone_loccode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_phone_loccode())); user.setHomePhoneNumber((addform.getHome_phone_number().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_phone_number())); user.setHomePhoneExt((addform.getHome_phone_ext().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_phone_ext())); user.setHomePhoneComment(addform.getHome_phone_commment()); user.setHomeFaxIntcode((addform.getHome_fax_intcode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_fax_intcode())); user.setHomeFaxLoccode((addform.getHome_fax_loccode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_fax_loccode())); user.setHomeFaxNumber((addform.getHome_fax_number().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_fax_number())); user.setHomeFaxExt((addform.getHome_fax_ext().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_fax_ext())); user.setHomeFaxComment(addform.getHome_fax_commment()); user.setHomeMobileIntcode((addform.getHome_mobile_intcode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_mobile_intcode())); user.setHomeMobileLoccode((addform.getHome_mobile_loccode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_mobile_loccode())); user.setHomeMobileNumber((addform.getHome_mobile_number().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_mobile_number())); user.setHomeMobileExt((addform.getHome_mobile_ext().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_mobile_ext())); user.setHomeMobileComment(addform.getHome_mobile_commment()); user.setHomePagerIntcode((addform.getHome_pager_intcode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_pager_intcode())); user.setHomePagerLoccode((addform.getHome_pager_loccode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_pager_loccode())); user.setHomePagerNumber((addform.getHome_pager_number().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_pager_number())); user.setHomePagerExt((addform.getHome_pager_ext().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_pager_ext())); user.setHomePagerComment(addform.getHome_pager_commment()); user.setHomeUri(addform.getHome_uri()); user.setHomeEmail(addform.getHome_email()); user.setBusinessName(addform.getBusiness_name()); user.setBusinessStreet(addform.getBusiness_street()); user.setBusinessStateprov(addform.getBusiness_stateprov()); user.setBusinessPostalcode((addform.getBusiness_postalcode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_postalcode())); user.setBusinessOrganization(addform.getBusiness_organization_name()); user.setBusinessCountry(addform.getBusiness_country()); user.setBusinessCity(addform.getBusiness_city()); user.setBusinessPhoneIntcode((addform.getBusiness_phone_intcode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_phone_intcode())); user.setBusinessPhoneLoccode((addform.getBusiness_phone_loccode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_phone_loccode())); user.setBusinessPhoneNumber((addform.getBusiness_phone_number().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_phone_number())); user.setBusinessPhoneExt((addform.getBusiness_phone_ext().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_phone_ext())); user.setBusinessPhoneComment(addform.getBusiness_phone_commment()); user.setBusinessFaxIntcode((addform.getBusiness_fax_intcode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_fax_intcode())); user.setBusinessFaxLoccode((addform.getBusiness_fax_loccode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_fax_loccode())); user.setBusinessFaxNumber((addform.getBusiness_fax_number().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_fax_number())); user.setBusinessFaxExt((addform.getBusiness_fax_ext().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_fax_ext())); user.setBusinessFaxComment(addform.getBusiness_fax_commment()); user.setBusinessMobileIntcode((addform.getBusiness_mobile_intcode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_mobile_intcode())); user.setBusinessMobileLoccode((addform.getBusiness_mobile_loccode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_mobile_loccode())); user.setBusinessMobileNumber((addform.getBusiness_mobile_number().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_mobile_number())); user.setBusinessMobileExt((addform.getBusiness_mobile_ext().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_mobile_ext())); user.setBusinessMobileComment(addform.getBusiness_mobile_commment()); user.setBusinessPagerIntcode((addform.getBusiness_pager_intcode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_pager_intcode())); user.setBusinessPagerLoccode((addform.getBusiness_pager_loccode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_pager_loccode())); user.setBusinessPagerNumber((addform.getBusiness_pager_number().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_pager_number())); user.setBusinessPagerExt((addform.getBusiness_pager_ext().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_pager_ext())); user.setBusinessPagerComment(addform.getBusiness_pager_commment()); user.setBusinessUri(addform.getBusiness_uri()); user.setBusinessEmail(addform.getBusiness_email()); String hqlDelete = "delete org.nodevision.portal.hibernate.om.NvUserRoles where login = :login"; int deletedEntities = hbsession.createQuery(hqlDelete).setString("login", user.getLogin()).executeUpdate(); String[] selectedGroups = addform.getSelectedGroups(); Set newGroups = new HashSet(); for (int i = 0; i < selectedGroups.length; i++) { NvUserRolesId userroles = new NvUserRolesId(); userroles.setNvUsers(user); userroles.setNvRoles((NvRoles) hbsession.load(NvRoles.class, selectedGroups[i])); NvUserRoles newRole = new NvUserRoles(); newRole.setId(userroles); newGroups.add(newRole); } user.setSetOfNvUserRoles(newGroups); hbsession.update(user); hbsession.flush(); if (!hbsession.connection().getAutoCommit()) { tx.commit(); } } finally { HibernateUtil.closeSession(); } } | public static void main(String[] args) throws Exception { String codecClassname = args[0]; Class<?> codecClass = Class.forName(codecClassname); Configuration conf = new Configuration(); CompressionCodec codec = (CompressionCodec) ReflectionUtils.newInstance(codecClass, conf); CompressionOutputStream out = codec.createOutputStream(System.out); IOUtils.copyBytes(System.in, out, 4096, false); out.finish(); } | 13,697 |
0 | public static void connectServer() { if (ftpClient == null) { int reply; try { setArg(configFile); ftpClient = new FTPClient(); ftpClient.setDefaultPort(port); ftpClient.configure(getFtpConfig()); ftpClient.connect(ip); ftpClient.login(username, password); ftpClient.setDefaultPort(port); System.out.print(ftpClient.getReplyString()); reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); System.err.println("FTP server refused connection."); } } catch (Exception e) { System.err.println("��¼ftp��������" + ip + "��ʧ��"); e.printStackTrace(); } } } | public synchronized String encrypt(String plaintext) throws ServiceUnavailableException { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new ServiceUnavailableException(e.getMessage()); } try { md.reset(); md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new ServiceUnavailableException(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } | 13,698 |
0 | public String getHttpText() { URL url = null; try { url = new URL(getUrl()); } catch (MalformedURLException e) { log.error(e.getMessage()); } StringBuffer sb = new StringBuffer(); HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(getRequestMethod()); conn.setDoOutput(true); if (getRequestProperty() != null && "".equals(getRequestProperty())) { conn.setRequestProperty("Accept", getRequestProperty()); } PrintWriter out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), getCharset())); out.println(getParam()); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), getCharset())); String inputLine; int i = 1; while ((inputLine = in.readLine()) != null) { if (getStartLine() == 0 && getEndLine() == 0) { sb.append(inputLine).append("\n"); } else { if (getEndLine() > 0) { if (i >= getStartLine() && i <= getEndLine()) { sb.append(inputLine).append("\n"); } } else { if (i >= getStartLine()) { sb.append(inputLine).append("\n"); } } } i++; } in.close(); } catch (IOException e) { log.error(e.getMessage()); } finally { if (conn != null) { conn.disconnect(); } } return sb.toString(); } | public static synchronized String encrypt(String plaintext) throws Exception { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plaintext.getBytes("UTF-8")); byte raw[] = md.digest(); return (new BASE64Encoder()).encode(raw); } | 13,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.