id
int32
0
901k
id1
int32
74
23.7M
id2
int32
74
23.7M
func1
stringlengths
234
68.5k
func2
stringlengths
234
68.5k
label
bool
2 classes
500
9,096,612
1,605,515
public void include(String href) throws ProteuException { try { if (href.toLowerCase().startsWith("http://")) { java.net.URLConnection urlConn = (new java.net.URL(href)).openConnection(); Download.sendInputStream(this, urlConn.getInputStream()); } else { requestHead.set("JCN_URL_INCLUDE", href); Url.build(this); } } catch (ProteuException pe) { throw pe; } catch (Throwable t) { logger.error("Include", t); throw new ProteuException(t.getMessage(), t); } }
public void createZip(String baseDir, String objFileName) throws Exception { logger.info("createZip: [ " + baseDir + "] [" + objFileName + "]"); baseDir = baseDir + "/" + timesmpt; File folderObject = new File(baseDir); if (folderObject.exists()) { List<?> fileList = getSubFiles(new File(baseDir)); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(objFileName)); ZipEntry ze = null; byte[] buf = new byte[1024]; int readLen = 0; for (int i = 0; i < fileList.size(); i++) { File f = (File) fileList.get(i); ze = new ZipEntry(getAbsFileName(baseDir, f)); ze.setSize(f.length()); ze.setTime(f.lastModified()); zos.putNextEntry(ze); InputStream is = new BufferedInputStream(new FileInputStream(f)); while ((readLen = is.read(buf, 0, 1024)) != -1) { zos.write(buf, 0, readLen); } is.close(); } zos.close(); } else { throw new Exception("this folder isnot exist!"); } }
false
501
11,723,383
8,452,131
private void getImage(String filename) throws MalformedURLException, IOException, SAXException, FileNotFoundException { String url = Constants.STRATEGICDOMINATION_URL + "/images/gameimages/" + filename; WebRequest req = new GetMethodWebRequest(url); SiteResponse response = getSiteResponse(req); File file = new File("etc/images/" + filename); FileOutputStream outputStream = new FileOutputStream(file); IOUtils.copy(response.getInputStream(), outputStream); }
public void put(String path, File fileToPut) throws IOException { FTPClient ftp = new FTPClient(); try { int reply; ftp.connect(this.endpointURL, this.endpointPort); log.debug("Ftp put reply: " + ftp.getReplyString()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); throw new IOException("Ftp put server refused connection."); } if (!ftp.login("anonymous", "")) { ftp.logout(); throw new IOException("FTP: server wrong passwd"); } ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); InputStream input = new FileInputStream(fileToPut); if (ftp.storeFile(path, input) != true) { ftp.logout(); input.close(); throw new IOException("FTP put exception"); } input.close(); ftp.logout(); } catch (Exception e) { log.error("Ftp client exception: " + e.getMessage(), e); throw new IOException(e.getMessage()); } }
false
502
18,464,490
6,322,440
@Override public void actionPerformed(ActionEvent e) { if (copiedFiles_ != null) { File[] tmpFiles = new File[copiedFiles_.length]; File tmpDir = new File(Settings.getPropertyString(ConstantKeys.project_dir), "tmp/"); tmpDir.mkdirs(); for (int i = copiedFiles_.length - 1; i >= 0; i--) { Frame f = FrameManager.getInstance().getFrameAtIndex(i); try { File in = f.getFile(); File out = new File(tmpDir, f.getFile().getName()); FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); tmpFiles[i] = out; } catch (IOException e1) { e1.printStackTrace(); } } try { FrameManager.getInstance().insertFrames(getTable().getSelectedRow(), FrameManager.INSERT_TYPE.MOVE, tmpFiles); } catch (IOException e1) { e1.printStackTrace(); } } }
public static void copyFile(final File fromFile, File toFile) throws IOException { try { if (!fromFile.exists()) { throw new IOException("FileCopy: " + "no such source file: " + fromFile.getAbsoluteFile()); } if (!fromFile.isFile()) { throw new IOException("FileCopy: " + "can't copy directory: " + fromFile.getAbsoluteFile()); } if (!fromFile.canRead()) { throw new IOException("FileCopy: " + "source file is unreadable: " + fromFile.getAbsoluteFile()); } if (toFile.isDirectory()) { toFile = new File(toFile, fromFile.getName()); } if (toFile.exists() && !toFile.canWrite()) { throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFile.getAbsoluteFile()); } final FileChannel inChannel = new FileInputStream(fromFile).getChannel(); final FileChannel outChannel = new FileOutputStream(toFile).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (final IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } catch (final IOException e) { if (LOGGER.isErrorEnabled()) { LOGGER.error("CopyFile went wrong!", e); } } }
true
503
20,112,083
11,701,818
@Override public void connect() throws IOException { URL url = getLocator().getURL(); if (url.getProtocol().equals("file")) { final String newUrlStr = URLUtils.createAbsoluteFileUrl(url.toExternalForm()); if (newUrlStr != null) { if (!newUrlStr.toString().equals(url.toExternalForm())) { logger.warning("Changing file URL to absolute for URL.openConnection, from " + url.toExternalForm() + " to " + newUrlStr); url = new URL(newUrlStr); } } } conn = url.openConnection(); if (!url.getProtocol().equals("ftp") && conn.getURL().getProtocol().equals("ftp")) { logger.warning("URL.openConnection() morphed " + url + " to " + conn.getURL()); throw new IOException("URL.openConnection() returned an FTP connection for a non-ftp url: " + url); } if (conn instanceof HttpURLConnection) { final HttpURLConnection huc = (HttpURLConnection) conn; huc.connect(); final int code = huc.getResponseCode(); if (!(code >= 200 && code < 300)) { huc.disconnect(); throw new IOException("HTTP response code: " + code); } logger.finer("URL: " + url); logger.finer("Response code: " + code); logger.finer("Full content type: " + conn.getContentType()); boolean contentTypeSet = false; if (stripTrailer(conn.getContentType()).equals("text/plain")) { final String ext = PathUtils.extractExtension(url.getPath()); if (ext != null) { final String result = MimeManager.getMimeType(ext); if (result != null) { contentTypeStr = ContentDescriptor.mimeTypeToPackageName(result); contentTypeSet = true; logger.fine("Received content type " + conn.getContentType() + "; overriding based on extension, to: " + result); } } } if (!contentTypeSet) contentTypeStr = ContentDescriptor.mimeTypeToPackageName(stripTrailer(conn.getContentType())); } else { conn.connect(); contentTypeStr = ContentDescriptor.mimeTypeToPackageName(conn.getContentType()); } contentType = new ContentDescriptor(contentTypeStr); sources = new URLSourceStream[1]; sources[0] = new URLSourceStream(); connected = true; }
private static void copyFile(File source, File destination) throws IOException, SecurityException { if (!destination.exists()) destination.createNewFile(); FileChannel sourceChannel = null; FileChannel destinationChannel = null; try { sourceChannel = new FileInputStream(source).getChannel(); destinationChannel = new FileOutputStream(destination).getChannel(); long count = 0; long size = sourceChannel.size(); while ((count += destinationChannel.transferFrom(sourceChannel, 0, size - count)) < size) ; } finally { if (sourceChannel != null) sourceChannel.close(); if (destinationChannel != null) destinationChannel.close(); } }
false
504
16,588,230
23,484,507
public static void main(String[] args) throws IOException { MSPack pack = new MSPack(new FileInputStream(args[0])); String[] files = pack.getFileNames(); for (int i = 0; i < files.length; i++) System.out.println(i + ": " + files[i] + ": " + pack.getLengths()[i]); System.out.println("Writing " + files[files.length - 1]); InputStream is = pack.getInputStream(files.length - 1); OutputStream os = new FileOutputStream(files[files.length - 1]); int n; byte[] buf = new byte[4096]; while ((n = is.read(buf)) != -1) os.write(buf, 0, n); os.close(); is.close(); }
public static void copy(File fromFile, File toFile) throws IOException { if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFile.getName()); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFile.getName()); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFile.getName()); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); 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) { ; } } }
true
505
19,045,087
12,800,568
public static void copyfile(String src, String dst) throws IOException { dst = new File(dst).getAbsolutePath(); new File(new File(dst).getParent()).mkdirs(); FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
public void exportFile() { String expfolder = PropertyHandler.getInstance().getProperty(PropertyHandler.KINDLE_EXPORT_FOLDER_KEY); File out = new File(expfolder + File.separator + previewInfo.getTitle() + ".prc"); File f = new File(absPath); try { FileOutputStream fout = new FileOutputStream(out); FileInputStream fin = new FileInputStream(f); int read = 0; byte[] buffer = new byte[1024 * 1024]; while ((read = fin.read(buffer)) > 0) { fout.write(buffer, 0, read); } fin.close(); fout.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
true
506
552,314
13,368,519
public void refreshFileItem(YahooInfo legroup) throws Exception { String lapage = new String(""); String ledir = new String(""); Pattern pat; Matcher mat; Pattern pat2; Matcher mat2; int data; URL myurl = new URL("http://groups.yahoo.com/mygroups"); URLConnection conn; URI myuri = new URI("http://groups.yahoo.com/mygroups"); YahooInfo yi; clearItem(legroup); for (int i = 0; i < UrlList.size(); i++) { if (UrlList.get(i).getGroup().equals(legroup.getGroup()) && UrlList.get(i).getDir().startsWith(legroup.getDir())) { if (UrlList.get(i).isGroup()) { System.out.print(UrlList.get(i).getGroup() + " : "); myuri = new URI(UrlList.get(i).getUrl()); myurl = new URL(UrlList.get(i).getUrl()); conn = myurl.openConnection(); conn.connect(); System.out.println(conn.getHeaderField(0).toString()); if (!Pattern.matches("HTTP/... 2.. .*", conn.getHeaderField(0).toString())) { System.out.println(conn.getHeaderField(0).toString()); return; } InputStream in = conn.getInputStream(); lapage = ""; for (data = in.read(); data != -1; data = in.read()) lapage += (char) data; pat = Pattern.compile("<li> <a href=\"(.+?)\".*?>Files</a></li>"); mat = pat.matcher(lapage); if (mat.find()) { yi = new YahooInfo(UrlList.get(i).getGroup(), "/", "", myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL().toString()); UrlList.add(yi); } } if (UrlList.get(i).isDir()) { System.out.println(UrlList.get(i).getGroup() + UrlList.get(i).getDir()); myuri = new URI(UrlList.get(i).getUrl()); myurl = new URL(UrlList.get(i).getUrl()); do { myurl = new URL(myurl.toString()); conn = myurl.openConnection(); conn.connect(); if (!Pattern.matches("HTTP/... 2.. .*", conn.getHeaderField(0).toString())) { System.out.println(conn.getHeaderField(0).toString()); return; } System.out.print("p"); InputStream in = conn.getInputStream(); lapage = ""; for (data = in.read(); data != -1; data = in.read()) lapage += (char) data; pat = Pattern.compile("<span class=\"title\">\n<a href=\"(.+?/)\">(.+?)</a>"); mat = pat.matcher(lapage); while (mat.find()) { ledir = new String(UrlList.get(i).getDir()); pat2 = Pattern.compile("([A-Za-z0-9]+)"); mat2 = pat2.matcher(mat.group(2)); while (mat2.find()) { ledir += mat2.group(1); } ledir += "/"; yi = new YahooInfo(UrlList.get(i).getGroup(), ledir, "", myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL().toString()); UrlList.add(yi); } pat = Pattern.compile("<span class=\"title\">\n<a href=\"(.+?yahoofs.+?)\".*?>(.+?)</a>"); mat = pat.matcher(lapage); while (mat.find()) { yi = new YahooInfo(UrlList.get(i).getGroup(), UrlList.get(i).getDir(), mat.group(2), myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL().toString()); UrlList.add(yi); } System.out.println(""); pat = Pattern.compile("<a href=\"(.+?)\">Next"); mat = pat.matcher(lapage); myurl = null; if (mat.find()) { myurl = myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL(); } } while (myurl != null); } } } }
public void sendTemplate(String filename, TemplateValues values) throws IOException { Checker.checkEmpty(filename, "filename"); Checker.checkNull(values, "values"); URL url = _getFile(filename); boolean writeSpaces = Context.getRootContext().getRunMode() == RUN_MODE.DEV ? true : false; Template t = new Template(url.openStream(), writeSpaces); try { t.write(getWriter(), values); } catch (ErrorListException ele) { Context.getRootContext().getLogger().error(ele); } }
false
507
11,988,852
22,998,999
public static final void parse(String infile, String outfile) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(infile)); DataOutputStream output = new DataOutputStream(new FileOutputStream(outfile)); int w = Integer.parseInt(reader.readLine()); int h = Integer.parseInt(reader.readLine()); output.writeByte(w); output.writeByte(h); int lineCount = 2; try { do { for (int i = 0; i < h; i++) { lineCount++; String line = reader.readLine(); if (line == null) { throw new RuntimeException("Unexpected end of file at line " + lineCount); } for (int j = 0; j < w; j++) { char c = line.charAt(j); System.out.print(c); output.writeByte(c); } System.out.println(""); } lineCount++; output.writeShort(Short.parseShort(reader.readLine())); } while (reader.readLine() != null); } finally { reader.close(); output.close(); } }
public static void concatFiles(List<File> sourceFiles, File destFile) throws IOException { FileOutputStream outFile = new FileOutputStream(destFile); FileChannel outChannel = outFile.getChannel(); for (File f : sourceFiles) { FileInputStream fis = new FileInputStream(f); FileChannel channel = fis.getChannel(); channel.transferTo(0, channel.size(), outChannel); channel.close(); fis.close(); } outChannel.close(); }
true
508
12,721,185
3,904,948
public static int fileUpload(long lngFileSize, InputStream inputStream, String strFilePath, String strFileName) throws IOException { String SEPARATOR = System.getProperty("file.separator"); if (lngFileSize > (10 * 1024 * 1024)) { return -1; } InputStream is = null; FileOutputStream fos = null; try { File dir = new File(strFilePath); if (!dir.exists()) dir.mkdirs(); is = inputStream; fos = new FileOutputStream(new File(strFilePath + SEPARATOR + strFileName)); IOUtils.copy(is, fos); } catch (Exception ex) { return -2; } finally { try { fos.close(); is.close(); } catch (Exception ex2) { } } return 0; }
public ManageUsers() { if (System.getProperty("user.home") != null) { dataFile = new File(System.getProperty("user.home") + File.separator + "MyRx" + File.separator + "MyRx.dat"); File dataFileDir = new File(System.getProperty("user.home") + File.separator + "MyRx"); dataFileDir.mkdirs(); } else { dataFile = new File("MyRx.dat"); } try { dataFile.createNewFile(); } catch (IOException e1) { logger.error(e1); JOptionPane.showMessageDialog(Menu.getMainMenu(), e1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } File oldDataFile = new File("MyRx.dat"); if (oldDataFile.exists()) { FileChannel src = null, dst = null; try { src = new FileInputStream(oldDataFile.getAbsolutePath()).getChannel(); dst = new FileOutputStream(dataFile.getAbsolutePath()).getChannel(); dst.transferFrom(src, 0, src.size()); if (!oldDataFile.delete()) { oldDataFile.deleteOnExit(); } } catch (FileNotFoundException e) { logger.error(e); JOptionPane.showMessageDialog(Menu.getMainMenu(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } catch (IOException e) { logger.error(e); JOptionPane.showMessageDialog(Menu.getMainMenu(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } finally { try { src.close(); dst.close(); } catch (IOException e) { logger.error(e); } } } }
true
509
16,199,085
10,816,494
@Override public byte[] read(String path) throws PersistenceException { path = fmtPath(path); try { S3Object fileObj = s3Service.getObject(bucketObj, path); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(fileObj.getDataInputStream(), out); return out.toByteArray(); } catch (Exception e) { throw new PersistenceException("fail to read s3 file - " + path, e); } }
@Override public void sendData(String serverUrl, String fileName, String type, InputStream is) throws IOException { ClientSession clientSession = null; try { if (logger.isDebugEnabled()) { logger.debug("Connecting to " + serverUrl); } clientSession = (ClientSession) Connector.open(serverUrl); HeaderSet hsConnectReply = clientSession.connect(clientSession.createHeaderSet()); if (hsConnectReply.getResponseCode() != ResponseCodes.OBEX_HTTP_OK) { throw new IOException("Connect Error " + hsConnectReply.getResponseCode()); } HeaderSet hsOperation = clientSession.createHeaderSet(); hsOperation.setHeader(HeaderSet.NAME, fileName); if (type != null) { hsOperation.setHeader(HeaderSet.TYPE, type); } hsOperation.setHeader(HeaderSet.LENGTH, new Long(is.available())); Operation po = clientSession.put(hsOperation); OutputStream os = po.openOutputStream(); IOUtils.copy(is, os); os.flush(); os.close(); if (logger.isDebugEnabled()) { logger.debug("put responseCode " + po.getResponseCode()); } po.close(); HeaderSet hsDisconnect = clientSession.disconnect(null); if (logger.isDebugEnabled()) { logger.debug("disconnect responseCode " + hsDisconnect.getResponseCode()); } if (hsDisconnect.getResponseCode() != ResponseCodes.OBEX_HTTP_OK) { throw new IOException("Send Error " + hsConnectReply.getResponseCode()); } } finally { if (clientSession != null) { try { clientSession.close(); } catch (IOException ignore) { if (logger.isDebugEnabled()) { logger.debug("IOException during clientSession.close()", ignore); } } } clientSession = null; } }
true
510
4,162,691
20,239,270
private static String getData(String myurl) throws Exception { URL url = new URL(myurl); uc = (HttpURLConnection) url.openConnection(); if (login) { uc.setRequestProperty("Cookie", usercookie + ";" + pwdcookie); } br = new BufferedReader(new InputStreamReader(uc.getInputStream())); String temp = "", k = ""; while ((temp = br.readLine()) != null) { k += temp; } br.close(); return k; }
public static void nioJoinFiles(FileLib.FileValidator validator, File target, File[] sources) { boolean big_files = false; for (int i = 0; i < sources.length; i++) { if (sources[i].length() > Integer.MAX_VALUE) { big_files = true; break; } } if (big_files) { joinFiles(validator, target, sources); } else { System.out.println(i18n.getString("jdk14_comment")); FileOutputStream fos = null; try { fos = new FileOutputStream(target); FileChannel fco = fos.getChannel(); FileInputStream fis = null; for (int i = 0; i < sources.length; i++) { fis = new FileInputStream(sources[i]); FileChannel fci = fis.getChannel(); java.nio.MappedByteBuffer map; try { map = fci.map(FileChannel.MapMode.READ_ONLY, 0, (int) sources[i].length()); fco.write(map); fci.close(); } catch (IOException ioe) { JOptionPane.showMessageDialog(null, ioe, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); try { fis.close(); fos.close(); } catch (IOException e) { } } finally { fis.close(); } } fco.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, e, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); } finally { try { if (fos != null) fos.close(); } catch (IOException e) { } } } }
false
511
5,090,669
5,040,724
private static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
public Document parse(Document document) { CSSCompilerBuilder compilerBuilder = new CSSCompilerBuilder(); StyleSheetCompilerFactory compilerFactory = getStyleSheetCompilerFactory(); compilerBuilder.setStyleSheetCompilerFactory(compilerFactory); CSSCompiler cssCompiler = compilerBuilder.getCSSCompiler(); CompiledStyleSheet defaultCompiledStyleSheet; try { URL url = getClass().getResource("/com/volantis/mcs/runtime/default.css"); InputStream stream = url.openStream(); defaultCompiledStyleSheet = cssCompiler.compile(new InputStreamReader(stream), null); } catch (IOException e) { throw new ExtendedRuntimeException(e); } StylingFactory stylingFactory = StylingFactory.getDefaultInstance(); StylingEngine stylingEngine = stylingFactory.createStylingEngine(new InlineStyleSheetCompilerFactory(StylingFunctions.getResolver())); stylingEngine.pushStyleSheet(defaultCompiledStyleSheet); DocumentStyler styler = new DocumentStyler(stylingEngine, XDIMESchemata.CDM_NAMESPACE); styler.style(document); DOMWalker walker = new DOMWalker(new WalkingDOMVisitorStub() { public void visit(Element element) { if (element.getStyles() == null) { throw new IllegalArgumentException("element " + element.getName() + " has no styles"); } } }); walker.walk(document); DOMTransformer transformer = new DeferredInheritTransformer(); document = transformer.transform(null, document); return document; }
false
512
7,356,945
15,497,380
public void run() { try { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Checking for updates at " + checkUrl); } URL url = new URL(checkUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuffer content = new StringBuffer(); String s = reader.readLine(); while (s != null) { content.append(s); s = reader.readLine(); } LOGGER.info("update-available", content.toString()); } else if (LOGGER.isDebugEnabled()) { LOGGER.debug("No update available (Response code " + connection.getResponseCode() + ")"); } } catch (Throwable e) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Update check failed", e); } } }
public static String generateSig(Map<String, String> params, String secret) { SortedSet<String> keys = new TreeSet<String>(params.keySet()); keys.remove(FacebookParam.SIGNATURE.toString()); String str = ""; for (String key : keys) { str += key + "=" + params.get(key); } str += secret; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes("UTF-8")); StringBuilder result = new StringBuilder(); for (byte b : md.digest()) { result.append(Integer.toHexString((b & 0xf0) >>> 4)); result.append(Integer.toHexString(b & 0x0f)); } return result.toString(); } catch (Exception e) { throw new RuntimeException(e); } }
false
513
16,034,464
11,113,074
public void generate(String rootDir, RootModel root) throws Exception { IOUtils.copyStream(HTMLGenerator.class.getResourceAsStream("stylesheet.css"), new FileOutputStream(new File(rootDir, "stylesheet.css"))); Velocity.init(); VelocityContext context = new VelocityContext(); context.put("model", root); context.put("util", new VelocityUtils()); context.put("msg", messages); processTemplate("index.html", new File(rootDir, "index.html"), context); processTemplate("list.html", new File(rootDir, "list.html"), context); processTemplate("summary.html", new File(rootDir, "summary.html"), context); File imageDir = new File(rootDir, "images"); imageDir.mkdir(); IOUtils.copyStream(HTMLGenerator.class.getResourceAsStream("primarykey.gif"), new FileOutputStream(new File(imageDir, "primarykey.gif"))); File tableDir = new File(rootDir, "tables"); tableDir.mkdir(); for (TableModel table : root.getTables()) { context.put("table", table); processTemplate("table.html", new File(tableDir, table.getTableName() + ".html"), context); } }
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()); } }
true
514
18,675,737
20,009,109
private void post(String title, Document content, Set<String> tags) throws HttpException, IOException, TransformerException { PostMethod method = null; try { method = new PostMethod("http://www.blogger.com/feeds/" + this.blogId + "/posts/default"); method.addRequestHeader("GData-Version", String.valueOf(GDataVersion)); method.addRequestHeader("Authorization", "GoogleLogin auth=" + this.AuthToken); Document dom = this.domBuilder.newDocument(); Element entry = dom.createElementNS(Atom.NS, "entry"); dom.appendChild(entry); entry.setAttribute("xmlns", Atom.NS); Element titleNode = dom.createElementNS(Atom.NS, "title"); entry.appendChild(titleNode); titleNode.setAttribute("type", "text"); titleNode.appendChild(dom.createTextNode(title)); Element contentNode = dom.createElementNS(Atom.NS, "content"); entry.appendChild(contentNode); contentNode.setAttribute("type", "xhtml"); contentNode.appendChild(dom.importNode(content.getDocumentElement(), true)); for (String tag : tags) { Element category = dom.createElementNS(Atom.NS, "category"); category.setAttribute("scheme", "http://www.blogger.com/atom/ns#"); category.setAttribute("term", tag); entry.appendChild(category); } StringWriter out = new StringWriter(); this.xml2ascii.transform(new DOMSource(dom), new StreamResult(out)); method.setRequestEntity(new StringRequestEntity(out.toString(), "application/atom+xml", "UTF-8")); int status = getHttpClient().executeMethod(method); if (status == 201) { IOUtils.copyTo(method.getResponseBodyAsStream(), System.out); } else { throw new HttpException("post returned http-code=" + status + " expected 201 (CREATE)"); } } catch (TransformerException err) { throw err; } catch (HttpException err) { throw err; } catch (IOException err) { throw err; } finally { if (method != null) method.releaseConnection(); } }
public static void concatFiles(final String as_base_file_name) throws IOException, FileNotFoundException { new File(as_base_file_name).createNewFile(); final OutputStream lo_out = new FileOutputStream(as_base_file_name, true); int ln_part = 1, ln_readed = -1; final byte[] lh_buffer = new byte[32768]; File lo_file = new File(as_base_file_name + "part1"); while (lo_file.exists() && lo_file.isFile()) { final InputStream lo_input = new FileInputStream(lo_file); while ((ln_readed = lo_input.read(lh_buffer)) != -1) { lo_out.write(lh_buffer, 0, ln_readed); } ln_part++; lo_file = new File(as_base_file_name + "part" + ln_part); } lo_out.flush(); lo_out.close(); }
true
515
12,238,227
941,896
public void doActionxxx() { try { System.out.println("app: ggc"); String server_name = "http://192.168.4.3:8080/"; server_name = server_name.trim(); if (server_name.length() == 0) { server_name = "http://www.atech-software.com/"; } else { if (!server_name.startsWith("http://")) server_name = "http://" + server_name; if (!server_name.endsWith("/")) server_name = server_name + "/"; } URL url = new URL(server_name + "ATechUpdateGetFile?" + "" + "file_id=1" + "&" + "version_requested=1"); InputStream is = url.openStream(); RandomAccessFile raf = new RandomAccessFile("/home/andy/test.jpg", "rw"); ArrayList<Integer> list = new ArrayList<Integer>(); float size = 671200; long current_size = 0; System.out.println("File size: " + is.available()); byte[] array = new byte[1024]; while (is.available() > 0) { if (is.available() < 1024) { array = new byte[is.available()]; } is.read(array); raf.write(array); current_size += array.length; System.out.println("Progress: " + ((current_size / size) * 100)); } System.out.println("Size Arr: " + list.size()); CheckSumUtility csu = new CheckSumUtility(); System.out.println("Checksum: " + csu.getChecksumValue("/home/andy/test.jpg")); } catch (Exception ex) { ex.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(); } }
false
516
20,082,006
11,149,084
public static void copyFile(File src, File dst) throws IOException { FileChannel sourceChannel = new FileInputStream(src).getChannel(); FileChannel destinationChannel = new FileOutputStream(dst).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
private void deleteProject(String uid, String home, HttpServletRequest request, HttpServletResponse response) throws Exception { String project = request.getParameter("project"); String line; response.setContentType("text/html"); PrintWriter out = response.getWriter(); htmlHeader(out, "Project Status", ""); try { synchronized (Class.forName("com.sun.gep.SunTCP")) { Vector list = new Vector(); String directory = home; Runtime.getRuntime().exec("/usr/bin/rm -rf " + directory + project); FilePermission perm = new FilePermission(directory + SUNTCP_LIST, "read,write,execute"); File listfile = new File(directory + SUNTCP_LIST); BufferedReader read = new BufferedReader(new FileReader(listfile)); while ((line = read.readLine()) != null) { if (!((new StringTokenizer(line, "\t")).nextToken().equals(project))) { list.addElement(line); } } read.close(); if (list.size() > 0) { PrintWriter write = new PrintWriter(new BufferedWriter(new FileWriter(listfile))); for (int i = 0; i < list.size(); i++) { write.println((String) list.get(i)); } write.close(); } else { listfile.delete(); } out.println("The project was successfully deleted."); } } catch (Exception e) { out.println("Error accessing this project."); } out.println("<center><form><input type=button value=Continue onClick=\"opener.location.reload(); window.close()\"></form></center>"); htmlFooter(out); }
true
517
8,372,919
16,544,386
private String MD5(String s) { Log.d("MD5", "Hashing '" + s + "'"); String hash = ""; try { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(s.getBytes(), 0, s.length()); hash = new BigInteger(1, m.digest()).toString(16); Log.d("MD5", "Hash: " + hash); } catch (Exception e) { Log.e("MD5", e.getMessage()); } return hash; }
public static String getEncodedHex(String text) { MessageDigest md = null; String encodedString = null; try { md = MessageDigest.getInstance("MD5"); md.update(text.getBytes()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } Hex hex = new Hex(); encodedString = new String(hex.encode(md.digest())); md.reset(); return encodedString; }
true
518
17,994,731
12,568,442
public static String encrypt(String txt) throws Exception { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(txt.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
public static String MD5(String text) { byte[] md5hash = new byte[32]; try { MessageDigest md; md = MessageDigest.getInstance("MD5"); md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); } catch (Exception e) { e.printStackTrace(); } return convertToHex(md5hash); }
true
519
17,270,255
16,157,869
@SuppressWarnings("static-access") public void run() { valuesRow = new String[this.getMaxCounter()]; for (int i = 0; i < this.getMaxCounter(); i++) { InputStream is = null; try { String surl = "http://download.finance.yahoo.com/d/quotes.csv?s=^GDAXI&f=sl1d1t1c1ohgv&e=.csv"; URL url = new URL(surl); is = url.openStream(); BufferedReader dis = new BufferedReader(new InputStreamReader(is)); String s = dis.readLine(); System.out.println(s); valuesRow[i] = s; is.close(); } catch (MalformedURLException mue) { System.out.println("Ouch - a MalformedURLException happened."); mue.printStackTrace(); System.exit(1); } catch (IOException ioe) { System.out.println("Oops- an IOException happened."); ioe.printStackTrace(); System.exit(1); } try { Thread.currentThread().sleep(this.getTsleep()); } catch (InterruptedException e) { } } System.out.println("valuesRow.length=" + valuesRow.length); }
public void insertStringInFile(String file, String textToInsert, long fromByte, long toByte) throws Exception { String tmpFile = file + ".tmp"; BufferedInputStream in = null; BufferedOutputStream out = null; long byteCount = 0; try { in = new BufferedInputStream(new FileInputStream(new File(file))); out = new BufferedOutputStream(new FileOutputStream(tmpFile)); long size = fromByte; byte[] buf = null; if (size == 0) { } else { buf = new byte[(int) size]; int length = -1; if ((length = in.read(buf)) != -1) { out.write(buf, 0, length); byteCount = byteCount + length; } else { String msg = "Failed to read the first '" + size + "' bytes of file '" + file + "'. This might be a programming error."; this.logger.warning(msg); throw new Exception(msg); } } buf = textToInsert.getBytes(); int length = buf.length; out.write(buf, 0, length); byteCount = byteCount + length; long skipLength = toByte - fromByte; long skippedBytes = in.skip(skipLength); if (skippedBytes == -1) { } else { buf = new byte[4096]; length = -1; while ((length = in.read(buf)) != -1) { out.write(buf, 0, length); byteCount = byteCount + length; } } in.close(); in = null; out.close(); out = null; File fileToDelete = new File(file); boolean wasDeleted = fileToDelete.delete(); if (!wasDeleted) { String msg = "Failed to delete the original file '" + file + "' to replace it with the modified file after text insertion."; this.logger.warning(msg); throw new Exception(msg); } File fileToRename = new File(tmpFile); boolean wasRenamed = fileToRename.renameTo(fileToDelete); if (!wasRenamed) { String msg = "Failed to rename tmp file '" + tmpFile + "' to the name of the original file '" + file + "'"; this.logger.warning(msg); throw new Exception(msg); } } catch (Exception e) { this.logger.log(Level.WARNING, "Failed to read/write file '" + file + "'.", e); throw e; } finally { if (in != null) { try { in.close(); } catch (IOException e) { this.logger.log(Level.FINEST, "Ignoring error closing input file '" + file + "'.", e); } } if (out != null) { try { out.close(); } catch (IOException e) { this.logger.log(Level.FINEST, "Ignoring error closing output file '" + tmpFile + "'.", e); } } } }
false
520
17,212,288
228,925
private void copyFile(File source, File destination) throws IOException { FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream(source); fileOutputStream = new FileOutputStream(destination); int bufferLength = 1024; byte[] buffer = new byte[bufferLength]; int readCount = 0; while ((readCount = fileInputStream.read(buffer)) != -1) { fileOutputStream.write(buffer, 0, readCount); } } finally { if (fileInputStream != null) { fileInputStream.close(); } if (fileOutputStream != null) { fileOutputStream.close(); } } }
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!"); }
true
521
100,791
21,361,961
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(); } }
private void transform(CommandLine commandLine) throws IOException { Reader reader; if (commandLine.hasOption('i')) { reader = createFileReader(commandLine.getOptionValue('i')); } else { reader = createStandardInputReader(); } Writer writer; if (commandLine.hasOption('o')) { writer = createFileWriter(commandLine.getOptionValue('o')); } else { writer = createStandardOutputWriter(); } String mapRule = commandLine.getOptionValue("m"); try { SrxTransformer transformer = new SrxAnyTransformer(); Map<String, Object> parameterMap = new HashMap<String, Object>(); if (mapRule != null) { parameterMap.put(Srx1Transformer.MAP_RULE_NAME, mapRule); } transformer.transform(reader, writer, parameterMap); } finally { cleanupReader(reader); cleanupWriter(writer); } }
true
522
9,543,284
23,050,895
public static final void copyFile(String srcFilename, String dstFilename) throws IOException { FileInputStream fis = null; FileOutputStream fos = null; FileChannel ifc = null; FileChannel ofc = null; Util.copyBuffer.clear(); try { fis = new FileInputStream(srcFilename); ifc = fis.getChannel(); fos = new FileOutputStream(dstFilename); ofc = fos.getChannel(); int sz = (int) ifc.size(); int n = 0; while (n < sz) { if (ifc.read(Util.copyBuffer) < 0) { break; } Util.copyBuffer.flip(); n += ofc.write(Util.copyBuffer); Util.copyBuffer.compact(); } } finally { try { if (ifc != null) { ifc.close(); } else if (fis != null) { fis.close(); } } catch (IOException exc) { } try { if (ofc != null) { ofc.close(); } else if (fos != null) { fos.close(); } } catch (IOException exc) { } } }
protected void saveResponse(final WebResponse response, final WebRequest request) throws IOException { counter_++; final String extension = chooseExtension(response.getContentType()); final File f = createFile(request.getUrl(), extension); final InputStream input = response.getContentAsStream(); final OutputStream output = new FileOutputStream(f); try { IOUtils.copy(response.getContentAsStream(), output); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } final URL url = response.getWebRequest().getUrl(); LOG.info("Created file " + f.getAbsolutePath() + " for response " + counter_ + ": " + url); final StringBuilder buffer = new StringBuilder(); buffer.append("tab[tab.length] = {code: " + response.getStatusCode() + ", "); buffer.append("fileName: '" + f.getName() + "', "); buffer.append("contentType: '" + response.getContentType() + "', "); buffer.append("method: '" + request.getHttpMethod().name() + "', "); if (request.getHttpMethod() == HttpMethod.POST && request.getEncodingType() == FormEncodingType.URL_ENCODED) { buffer.append("postParameters: " + nameValueListToJsMap(request.getRequestParameters()) + ", "); } buffer.append("url: '" + escapeJSString(url.toString()) + "', "); buffer.append("loadTime: " + response.getLoadTime() + ", "); final byte[] bytes = IOUtils.toByteArray(response.getContentAsStream()); buffer.append("responseSize: " + ((bytes == null) ? 0 : bytes.length) + ", "); buffer.append("responseHeaders: " + nameValueListToJsMap(response.getResponseHeaders())); buffer.append("};\n"); appendToJSFile(buffer.toString()); }
true
523
21,374,041
17,671,343
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 unzip(String zipFileName, String outputDirectory) throws Exception { ZipInputStream in = new ZipInputStream(new FileInputStream(zipFileName)); ZipEntry z; while ((z = in.getNextEntry()) != null) { System.out.println("unziping " + z.getName()); if (z.isDirectory()) { String name = z.getName(); name = name.substring(0, name.length() - 1); File f = new File(outputDirectory + File.separator + name); f.mkdir(); System.out.println("mkdir " + outputDirectory + File.separator + name); } else { File f = new File(outputDirectory + File.separator + z.getName()); f.createNewFile(); FileOutputStream out = new FileOutputStream(f); int b; while ((b = in.read()) != -1) out.write(b); out.close(); } } in.close(); }
true
524
7,631,411
22,808,166
public static final byte[] getHttpStream(final String uri) { URL url; try { url = new URL(uri); } catch (Exception e) { return null; } InputStream is = null; try { is = url.openStream(); } catch (Exception e) { return null; } ByteArrayOutputStream os = new ByteArrayOutputStream(); byte[] arrayByte = null; try { arrayByte = new byte[4096]; int read; while ((read = is.read(arrayByte)) >= 0) { os.write(arrayByte, 0, read); } arrayByte = os.toByteArray(); } catch (IOException e) { return null; } finally { try { if (os != null) { os.close(); os = null; } if (is != null) { is.close(); is = null; } } catch (IOException e) { } } return arrayByte; }
protected void init() throws MXQueryException { String add = getStringValueOrEmpty(subIters[0]); if (add == null) { currentToken = BooleanToken.FALSE_TOKEN; return; } URI uri; if (!TypeLexicalConstraints.isValidURI(add)) throw new DynamicException(ErrorCodes.F0017_INVALID_ARGUMENT_TO_FN_DOC, "Invalid URI given to fn:doc-available", loc); try { if (TypeLexicalConstraints.isAbsoluteURI(add)) { uri = new URI(add); } else { uri = new URI(IOLib.convertToAndroid(add)); } } catch (URISyntaxException se) { throw new DynamicException(ErrorCodes.F0017_INVALID_ARGUMENT_TO_FN_DOC, "Invalid URI given to fn:doc-available", loc); } if (add.startsWith("http://")) { URL url; try { url = uri.toURL(); } catch (MalformedURLException e) { throw new DynamicException(ErrorCodes.F0017_INVALID_ARGUMENT_TO_FN_DOC, "Invalid URI given to fn:doc-available", loc); } try { InputStream in = url.openStream(); in.close(); } catch (IOException e) { currentToken = BooleanToken.FALSE_TOKEN; return; } currentToken = BooleanToken.TRUE_TOKEN; } else { try { BufferedReader in = new BufferedReader(new InputStreamReader(MXQuery.getContext().openFileInput(uri.toString()))); currentToken = BooleanToken.TRUE_TOKEN; } catch (FileNotFoundException e) { currentToken = BooleanToken.FALSE_TOKEN; } catch (IOException e) { currentToken = BooleanToken.FALSE_TOKEN; } } }
false
525
1,639,107
5,644,911
public void copy(File source, File destination) { try { FileInputStream fileInputStream = new FileInputStream(source); FileOutputStream fileOutputStream = new FileOutputStream(destination); FileChannel inputChannel = fileInputStream.getChannel(); FileChannel outputChannel = fileOutputStream.getChannel(); transfer(inputChannel, outputChannel, source.length(), false); fileInputStream.close(); fileOutputStream.close(); destination.setLastModified(source.lastModified()); } catch (Exception e) { e.printStackTrace(); } }
private static long writeVMDKFile(String absoluteFile, String urlString) throws Exception { URL urlCon = new URL(urlString); HttpsURLConnection conn = (HttpsURLConnection) urlCon.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setAllowUserInteraction(true); List cookies = (List) headers.get("Set-cookie"); cookieValue = (String) cookies.get(0); StringTokenizer tokenizer = new StringTokenizer(cookieValue, ";"); cookieValue = tokenizer.nextToken(); String path = "$" + tokenizer.nextToken(); String cookie = "$Version=\"1\"; " + cookieValue + "; " + path; Map map = new HashMap(); map.put("Cookie", Collections.singletonList(cookie)); ((BindingProvider) vimPort).getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, map); conn.setRequestProperty("Cookie", cookie); conn.setRequestProperty("Content-Type", "application/octet-stream"); conn.setRequestProperty("Expect", "100-continue"); conn.setRequestMethod("GET"); conn.setRequestProperty("Content-Length", "1024"); InputStream in = conn.getInputStream(); String localpath = localPath + "/" + absoluteFile; OutputStream out = new FileOutputStream(new File(localpath)); byte[] buf = new byte[102400]; int len = 0; long written = 0; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); written = written + len; } System.out.println(" Exported File " + absoluteFile + " : " + written); in.close(); out.close(); return written; }
false
526
282,874
9,492,898
public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt.executeUpdate(sql); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } }
public static Object getInputStream(String name, boolean showMsg, URL appletDocumentBase, String appletProxy) { String errorMessage = null; int iurlPrefix; for (iurlPrefix = urlPrefixes.length; --iurlPrefix >= 0; ) if (name.startsWith(urlPrefixes[iurlPrefix])) break; boolean isURL = (iurlPrefix >= 0); boolean isApplet = (appletDocumentBase != null); InputStream in = null; int length; try { if (isApplet || isURL) { if (isApplet && isURL && appletProxy != null) name = appletProxy + "?url=" + URLEncoder.encode(name, "utf-8"); URL url = (isApplet ? new URL(appletDocumentBase, name) : new URL(name)); name = url.toString(); if (showMsg) Logger.info("FileManager opening " + url.toString()); URLConnection conn = url.openConnection(); length = conn.getContentLength(); in = conn.getInputStream(); } else { if (showMsg) Logger.info("FileManager opening " + name); File file = new File(name); length = (int) file.length(); in = new FileInputStream(file); } return new MonitorInputStream(in, length); } catch (Exception e) { try { if (in != null) in.close(); } catch (IOException e1) { } errorMessage = "" + e; } return errorMessage; }
false
527
3,386,551
9,542,520
public static String convertStringToMD5(String toEnc) { try { MessageDigest mdEnc = MessageDigest.getInstance("MD5"); mdEnc.update(toEnc.getBytes(), 0, toEnc.length()); return new BigInteger(1, mdEnc.digest()).toString(16); } catch (Exception e) { return null; } }
@SuppressWarnings("static-access") public void run() { while (true) { try { thisThread.sleep(10000); } catch (InterruptedException e) { System.out.print("no connection"); } ++i; umat.flush(); umat = null; try { base = getDocumentBase(); username = getParameter("username"); } catch (Exception e) { } String userdat = "data/" + username + "_l.cod"; URL url = null; try { url = new URL(base, userdat); } catch (MalformedURLException e1) { } InputStream in = null; try { in = url.openStream(); } catch (IOException e1) { } BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(in)); } catch (Exception r) { } try { String line = reader.readLine(); StringTokenizer tokenizer = new StringTokenizer(line, " "); int dim = Integer.parseInt(tokenizer.nextToken().trim().toLowerCase()); this.topol = tokenizer.nextToken().trim().toLowerCase(); xunit = Integer.parseInt(tokenizer.nextToken().trim().toLowerCase()); yunit = Integer.parseInt(tokenizer.nextToken().trim().toLowerCase()); @SuppressWarnings("unused") String neigh = tokenizer.nextToken().trim().toLowerCase(); String label = null; labels = new String[xunit][yunit]; for (int e = 0; e < yunit; e++) { for (int r = 0; r < xunit; r++) { line = reader.readLine(); StringTokenizer tokenizer2 = new StringTokenizer(line, " "); for (int w = 0; w < dim; w++) { if (tokenizer2.countTokens() > 0) tokenizer2.nextToken(); } while (tokenizer2.countTokens() > 0) { label = tokenizer2.nextToken() + " "; } if (label == null) { labels[r][e] = "none"; } else { labels[r][e] = label; } label = null; } } reader.close(); if (topol.equals("hexa")) { xposit = new int[xunit][yunit]; yposit = new int[xunit][yunit]; double divisor1 = xunit; double divisor2 = yunit; for (int p = 0; p < xunit; p++) { for (int q = 0; q < yunit; q++) { if (q % 2 == 0) { double nenner = (p * width); xposit[p][q] = (int) Math.round(nenner / divisor1); } if (q % 2 != 0) { double nenner = (width * 0.5) + (p * width); xposit[p][q] = (int) Math.round(nenner / divisor1); } yposit[p][q] = (int) Math.round(((height * 0.5) + q * height) / divisor2); } } } if (topol.equals("rect")) { xposit = new int[xunit][yunit]; yposit = new int[xunit][yunit]; double divisor1 = xunit; double divisor2 = yunit; for (int p = 0; p < xunit; p++) { for (int q = 0; q < yunit; q++) { double nenner = (width * 0.5) + (p * width); xposit[p][q] = (int) Math.round((nenner / divisor1)); yposit[p][q] = (int) Math.round(((height * 0.5) + q * height) / divisor2); } } } } catch (IOException o) { } String userpng = "images/" + username + ".png"; mt.removeImage(umat); umat = getImage(base, userpng); mt.addImage(umat, 0); try { mt.waitForID(0); } catch (InterruptedException i) { showStatus("Interrupted"); } repaint(); } }
false
528
6,850,521
17,577,733
@SuppressWarnings({ "ProhibitedExceptionDeclared" }) public int run(@NotNull final List<String> args) throws Exception { int returnCode = 0; if (args.size() == 0) { log(Level.SEVERE, "noarguments"); returnCode++; } final byte[] buf = new byte[BUF_SIZE]; for (final String arg : args) { try { final URL url = new URL(arg); final URLConnection con = url.openConnection(); final InputStream in = con.getInputStream(); try { final String location = con.getHeaderField("Content-Location"); final String outputFilename = new File((location != null ? new URL(url, location) : url).getFile()).getName(); log(Level.INFO, "writing", arg, outputFilename); final OutputStream out = new FileOutputStream(outputFilename); try { for (int bytesRead; (bytesRead = in.read(buf)) != -1; ) { out.write(buf, 0, bytesRead); } } finally { out.close(); } } finally { in.close(); } } catch (final IOException e) { log(Level.WARNING, "cannotopen", arg, e); returnCode++; } } return returnCode; }
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 AttributeCategories (CategoryName) values ('color')"); stmt.executeUpdate("insert into Attributes (AttributeName, Category) values ('blue', 'color')"); stmt.executeUpdate("insert into Attributes (AttributeName, Category) values ('red', 'color')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (100, 'ball')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (101, 'blue ball')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (102, 'red ball')"); stmt.executeQuery("select setval('objects_objectid_seq', 1000)"); 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 (102, 'instance', 100)"); stmt.executeUpdate("insert into ObjectAttributes (ObjectId, AttributeName) values (101, 'blue')"); stmt.executeUpdate("insert into ObjectAttributes (ObjectId, AttributeName) values (102, 'red')"); stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('LEFT-WALL', '1', 'AV+ | ADJ+', 1)"); stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('the', '1', 'D+', 1)"); stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('red', '1', 'ADJ- | ADJ+', 1)"); stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('blue', '1', 'ADJ- | ADJ+', 1)"); stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('ball', '1', '[@ADJ-] & [D-] & DO-', 100)"); stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('throw', '1', 'AV- & DO+', 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 GrammarLinks (LinkName, LinkType) values ('ADJ', 11)"); stmt.executeUpdate("insert into Articles (ArticleName, Dereference) values ('the', 1)"); stmt.executeUpdate("insert into FrameSlots (SlotName) values ('object')"); stmt.executeUpdate("insert into QuestionWords (QuestionWord, Type) values ('which', 7)"); stmt.executeUpdate("insert into Verbs (VerbName, Type, SubjectSlot, IndirectObjectSlot, PredicateNounSlot) values ('throw', 1, '', '', 'object')"); stmt.executeQuery("select setval('instructions_instructionid_seq', 1)"); stmt.executeUpdate("insert into Instructions (Type, ExecuteString, FrameSlot, Operator, LinkName, ObjectId, AttributeName) " + "values (3, '', null, 0, null, null, null)"); stmt.executeQuery("select setval('transactions_transactionid_seq', 1)"); stmt.executeUpdate("insert into Transactions (InstructionId, Description) values (2, 'throw')"); stmt.executeQuery("select setval('verbtransactions_verbid_seq', 1)"); stmt.executeUpdate("insert into VerbTransactions (VerbString, MoodType, TransactionId) values ('throw', 1, 2)"); stmt.executeUpdate("insert into VerbConstraints (VerbId, FrameSlot, ObjectId) values (2, 'object', 1)"); stmt.executeUpdate("update SystemProperties set value = 'Tutorial 3 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(); } }
false
529
3,734,993
5,623,479
private void fetchAlignment() throws IOException { String urlString = BASE_URL + ALN_URL + DATASET_URL + "&family=" + mFamily; URL url = new URL(urlString); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); processAlignment(in); }
public static String getHash(String text) { String ret = null; try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(text.getBytes()); ret = getHex(md.digest()); } catch (NoSuchAlgorithmException e) { log.error(e); throw new OopsException(e, "Hash Error."); } return ret; }
false
530
924,033
18,096,549
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 void copyFile(File src, File dest, boolean notifyUserOnError) { if (src.exists()) { try { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(src)); byte[] read = new byte[128]; int len = 128; while ((len = in.read(read)) > 0) out.write(read, 0, len); out.flush(); out.close(); in.close(); } catch (IOException e) { String message = "Error while copying " + src.getAbsolutePath() + " to " + dest.getAbsolutePath() + " : " + e.getMessage(); if (notifyUserOnError) { Log.getInstance(SystemUtils.class).warnWithUserNotification(message); } else { Log.getInstance(SystemUtils.class).warn(message); } } } else { String message = "Unable to copy file: source does not exists: " + src.getAbsolutePath(); if (notifyUserOnError) { Log.getInstance(SystemUtils.class).warnWithUserNotification(message); } else { Log.getInstance(SystemUtils.class).warn(message); } } }
true
531
137,780
692,680
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!"); }
private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } }
true
532
22,900,247
3,402,511
public static void copyDirectory(File sourceDirectory, File targetDirectory) throws IOException { File[] sourceFiles = sourceDirectory.listFiles(FILE_FILTER); File[] sourceDirectories = sourceDirectory.listFiles(DIRECTORY_FILTER); targetDirectory.mkdirs(); if (sourceFiles != null && sourceFiles.length > 0) { for (int i = 0; i < sourceFiles.length; i++) { File sourceFile = sourceFiles[i]; FileInputStream fis = new FileInputStream(sourceFile); FileOutputStream fos = new FileOutputStream(targetDirectory + File.separator + sourceFile.getName()); FileChannel fcin = fis.getChannel(); FileChannel fcout = fos.getChannel(); ByteBuffer buf = ByteBuffer.allocateDirect(8192); long size = fcin.size(); long n = 0; while (n < size) { buf.clear(); if (fcin.read(buf) < 0) { break; } buf.flip(); n += fcout.write(buf); } fcin.close(); fcout.close(); fis.close(); fos.close(); } } if (sourceDirectories != null && sourceDirectories.length > 0) { for (int i = 0; i < sourceDirectories.length; i++) { File directory = sourceDirectories[i]; File newTargetDirectory = new File(targetDirectory, directory.getName()); copyDirectory(directory, newTargetDirectory); } } }
private static FileEntry writeEntry(Zip64File zip64File, FileEntry targetPath, File toWrite, boolean compress) { InputStream in = null; EntryOutputStream out = null; processAndCreateFolderEntries(zip64File, parseTargetPath(targetPath.getName(), toWrite), compress); try { if (!compress) { out = zip64File.openEntryOutputStream(targetPath.getName(), FileEntry.iMETHOD_STORED, getFileDate(toWrite)); } else { out = zip64File.openEntryOutputStream(targetPath.getName(), FileEntry.iMETHOD_DEFLATED, getFileDate(toWrite)); } if (!targetPath.isDirectory()) { in = new FileInputStream(toWrite); IOUtils.copyLarge(in, out); in.close(); } out.flush(); out.close(); if (targetPath.isDirectory()) { log.info("[createZip] Written folder entry to zip: " + targetPath.getName()); } else { log.info("[createZip] Written file entry to zip: " + targetPath.getName()); } } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (ZipException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } return targetPath; }
true
533
13,356,869
19,660,598
public void createZip(File zipFileName, Vector<File> selected) { try { byte[] buffer = new byte[4096]; ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFileName), 8096)); out.setLevel(Deflater.BEST_COMPRESSION); out.setMethod(ZipOutputStream.DEFLATED); for (int i = 0; i < selected.size(); i++) { FileInputStream in = new FileInputStream(selected.get(i)); String file = selected.get(i).getPath(); if (file.indexOf("\\") != -1) file = file.substring(file.lastIndexOf(Options.fs) + 1, file.length()); ZipEntry ze = new ZipEntry(file); out.putNextEntry(ze); int len; while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len); out.closeEntry(); in.close(); selected.get(i).delete(); } out.close(); } catch (IllegalArgumentException iae) { iae.printStackTrace(); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } }
private static void replaceEntityMappings(File signserverearpath, File entityMappingXML) throws ZipException, IOException { ZipInputStream earFile = new ZipInputStream(new FileInputStream(signserverearpath)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream tempZip = new ZipOutputStream(baos); ZipEntry next = earFile.getNextEntry(); while (next != null) { ByteArrayOutputStream content = new ByteArrayOutputStream(); byte[] data = new byte[30000]; int numberread; while ((numberread = earFile.read(data)) != -1) { content.write(data, 0, numberread); } if (next.getName().equals("signserver-ejb.jar")) { content = replaceEntityMappings(content, entityMappingXML); next = new ZipEntry("signserver-ejb.jar"); } tempZip.putNextEntry(next); tempZip.write(content.toByteArray()); next = earFile.getNextEntry(); } earFile.close(); tempZip.close(); FileOutputStream fos = new FileOutputStream(signserverearpath); fos.write(baos.toByteArray()); fos.close(); }
true
534
10,426,070
6,814,855
public static long copy(File src, long amount, File dst) { final int BUFFER_SIZE = 1024; long amountToRead = amount; InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(src)); out = new BufferedOutputStream(new FileOutputStream(dst)); byte[] buf = new byte[BUFFER_SIZE]; while (amountToRead > 0) { int read = in.read(buf, 0, (int) Math.min(BUFFER_SIZE, amountToRead)); if (read == -1) break; amountToRead -= read; out.write(buf, 0, read); } } catch (IOException e) { } finally { close(in); flush(out); close(out); } return amount - amountToRead; }
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; }
true
535
12,985,350
14,293,059
public static String encryptPassword(String password) { String hash = null; try { MessageDigest md = null; md = MessageDigest.getInstance("SHA"); md.update(password.getBytes("UTF-8")); byte raw[] = md.digest(); hash = Base64.encode(raw, false); } catch (Exception e) { } return hash; }
public static final String crypt(final String password, String salt, final String magic) { if (password == null) throw new IllegalArgumentException("Null password!"); if (salt == null) throw new IllegalArgumentException("Null salt!"); if (magic == null) throw new IllegalArgumentException("Null salt!"); byte finalState[]; long l; MessageDigest ctx, ctx1; try { ctx = MessageDigest.getInstance("md5"); ctx1 = MessageDigest.getInstance("md5"); } catch (final NoSuchAlgorithmException ex) { System.err.println(ex); return null; } if (salt.startsWith(magic)) { salt = salt.substring(magic.length()); } if (salt.indexOf('$') != -1) { salt = salt.substring(0, salt.indexOf('$')); } if (salt.length() > 8) { salt = salt.substring(0, 8); } ctx.update(password.getBytes()); ctx.update(magic.getBytes()); ctx.update(salt.getBytes()); ctx1.update(password.getBytes()); ctx1.update(salt.getBytes()); ctx1.update(password.getBytes()); finalState = ctx1.digest(); for (int pl = password.length(); pl > 0; pl -= 16) { ctx.update(finalState, 0, pl > 16 ? 16 : pl); } clearbits(finalState); for (int i = password.length(); i != 0; i >>>= 1) { if ((i & 1) != 0) { ctx.update(finalState, 0, 1); } else { ctx.update(password.getBytes(), 0, 1); } } finalState = ctx.digest(); for (int i = 0; i < 1000; i++) { try { ctx1 = MessageDigest.getInstance("md5"); } catch (final NoSuchAlgorithmException e0) { return null; } if ((i & 1) != 0) { ctx1.update(password.getBytes()); } else { ctx1.update(finalState, 0, 16); } if ((i % 3) != 0) { ctx1.update(salt.getBytes()); } if ((i % 7) != 0) { ctx1.update(password.getBytes()); } if ((i & 1) != 0) { ctx1.update(finalState, 0, 16); } else { ctx1.update(password.getBytes()); } finalState = ctx1.digest(); } final StringBuffer result = new StringBuffer(); result.append(magic); result.append(salt); result.append("$"); l = (bytes2u(finalState[0]) << 16) | (bytes2u(finalState[6]) << 8) | bytes2u(finalState[12]); result.append(to64(l, 4)); l = (bytes2u(finalState[1]) << 16) | (bytes2u(finalState[7]) << 8) | bytes2u(finalState[13]); result.append(to64(l, 4)); l = (bytes2u(finalState[2]) << 16) | (bytes2u(finalState[8]) << 8) | bytes2u(finalState[14]); result.append(to64(l, 4)); l = (bytes2u(finalState[3]) << 16) | (bytes2u(finalState[9]) << 8) | bytes2u(finalState[15]); result.append(to64(l, 4)); l = (bytes2u(finalState[4]) << 16) | (bytes2u(finalState[10]) << 8) | bytes2u(finalState[5]); result.append(to64(l, 4)); l = bytes2u(finalState[11]); result.append(to64(l, 2)); clearbits(finalState); return result.toString(); }
true
536
13,376,846
13,536,658
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; }
private String protectMarkup(String content, String markupRegex, String replaceSource, String replaceTarget) { Matcher matcher = Pattern.compile(markupRegex, Pattern.MULTILINE | Pattern.DOTALL).matcher(content); StringBuffer result = new StringBuffer(); while (matcher.find()) { String protectedMarkup = matcher.group(); protectedMarkup = protectedMarkup.replaceAll(replaceSource, replaceTarget); try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.reset(); digest.update(protectedMarkup.getBytes("UTF-8")); String hash = bytesToHash(digest.digest()); matcher.appendReplacement(result, hash); c_protectionMap.put(hash, protectedMarkup); m_hashList.add(hash); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } matcher.appendTail(result); return result.toString(); }
true
537
7,177,879
17,226,920
public SM2Client(String umn, String authorizationID, String protocol, String serverName, Map props, CallbackHandler handler) { super(SM2_MECHANISM + "-" + umn, authorizationID, protocol, serverName, props, handler); this.umn = umn; complete = false; state = 0; if (sha == null) try { sha = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException x) { cat.error("SM2Client()", x); throw new RuntimeException(String.valueOf(x)); } sha.update(String.valueOf(umn).getBytes()); sha.update(String.valueOf(authorizationID).getBytes()); sha.update(String.valueOf(protocol).getBytes()); sha.update(String.valueOf(serverName).getBytes()); sha.update(String.valueOf(properties).getBytes()); sha.update(String.valueOf(Thread.currentThread().getName()).getBytes()); uid = new BigInteger(1, sha.digest()).toString(26); Ec = null; }
public void setUrl(URL url) throws PDFException, PDFSecurityException, IOException { InputStream in = null; try { URLConnection urlConnection = url.openConnection(); in = urlConnection.getInputStream(); String pathOrURL = url.toString(); setInputStream(in, pathOrURL); } finally { if (in != null) { in.close(); } } }
false
538
13,028,546
18,318,816
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; }
public static void invokeMvnArtifact(final IProject project, final IModuleExtension moduleExtension, final String location) throws CoreException, InterruptedException, IOException { final Properties properties = new Properties(); properties.put("archetypeGroupId", "org.nexopenframework.plugins"); properties.put("archetypeArtifactId", "openfrwk-archetype-webmodule"); final String version = org.maven.ide.eclipse.ext.Maven2Plugin.getArchetypeVersion(); properties.put("archetypeVersion", version); properties.put("artifactId", moduleExtension.getArtifact()); properties.put("groupId", moduleExtension.getGroup()); properties.put("version", moduleExtension.getVersion()); final ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager(); final ILaunchConfigurationType launchConfigurationType = launchManager.getLaunchConfigurationType(LAUNCH_CONFIGURATION_TYPE_ID); final ILaunchConfigurationWorkingCopy workingCopy = launchConfigurationType.newInstance(null, "Creating WEB module using Apache Maven archetype"); File archetypePomDirectory = getDefaultArchetypePomDirectory(); try { final String dfPom = getPomFile(moduleExtension.getGroup(), moduleExtension.getArtifact()); final ByteArrayInputStream bais = new ByteArrayInputStream(dfPom.getBytes()); final File f = new File(archetypePomDirectory, "pom.xml"); OutputStream fous = null; try { fous = new FileOutputStream(f); IOUtils.copy(bais, fous); } finally { try { if (fous != null) { fous.close(); } if (bais != null) { bais.close(); } } catch (final IOException e) { } } String goalName = "archetype:create"; boolean offline = false; try { final Class clazz = Thread.currentThread().getContextClassLoader().loadClass("org.maven.ide.eclipse.Maven2Plugin"); final Maven2Plugin plugin = (Maven2Plugin) clazz.getMethod("getDefault", new Class[0]).invoke(null, new Object[0]); offline = plugin.getPreferenceStore().getBoolean("eclipse.m2.offline"); } catch (final ClassNotFoundException e) { Logger.logException("No class [org.maven.ide.eclipse.ext.Maven2Plugin] in classpath", e); } catch (final NoSuchMethodException e) { Logger.logException("No method getDefault", e); } catch (final Throwable e) { Logger.logException(e); } if (offline) { goalName = new StringBuffer(goalName).append(" -o").toString(); } if (!offline) { final IPreferenceStore ps = Maven2Plugin.getDefault().getPreferenceStore(); final String repositories = ps.getString(Maven2PreferenceConstants.P_M2_REPOSITORIES); final String[] repos = repositories.split(org.maven.ide.eclipse.ext.Maven2Plugin.REPO_SEPARATOR); final StringBuffer sbRepos = new StringBuffer(); for (int k = 0; k < repos.length; k++) { sbRepos.append(repos[k]); if (k != repos.length - 1) { sbRepos.append(","); } } properties.put("remoteRepositories", sbRepos.toString()); } workingCopy.setAttribute(ATTR_GOALS, goalName); workingCopy.setAttribute(ATTR_POM_DIR, archetypePomDirectory.getAbsolutePath()); workingCopy.setAttribute(ATTR_PROPERTIES, convertPropertiesToList(properties)); final long timeout = org.maven.ide.eclipse.ext.Maven2Plugin.getTimeout(); TimeoutLaunchConfiguration.launchWithTimeout(new NullProgressMonitor(), workingCopy, project, timeout); FileUtils.copyDirectoryStructure(new File(archetypePomDirectory, project.getName()), new File(location)); FileUtils.deleteDirectory(new File(location + "/src")); FileUtils.forceDelete(new File(location, "pom.xml")); project.refreshLocal(IResource.DEPTH_INFINITE, null); } finally { FileUtils.deleteDirectory(archetypePomDirectory); Logger.log(Logger.INFO, "Invoked removing of archetype POM directory"); } }
true
539
9,958,260
14,717,089
public String doAdd(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { UploadFileForm vo = (UploadFileForm) form; FormFile file = vo.getFile(); String inforId = request.getParameter("inforId"); System.out.println("inforId=" + inforId); if (file != null) { String realpath = getServlet().getServletContext().getRealPath("/"); realpath = realpath.replaceAll("\\\\", "/"); String rootFilePath = getServlet().getServletContext().getRealPath(request.getContextPath()); rootFilePath = (new StringBuilder(String.valueOf(rootFilePath))).append(UploadFileOne.strPath).toString(); String strAppend = (new StringBuilder(String.valueOf(UUIDGenerator.nextHex()))).append(UploadFileOne.getFileType(file)).toString(); if (file.getFileSize() != 0) { file.getInputStream(); String name = file.getFileName(); String fullPath = realpath + "attach/" + strAppend + name; t_attach attach = new t_attach(); attach.setAttach_fullname(fullPath); attach.setAttach_name(name); attach.setInfor_id(Integer.parseInt(inforId)); attach.setInsert_day(new Date()); attach.setUpdate_day(new Date()); t_attach_EditMap attachEdit = new t_attach_EditMap(); attachEdit.add(attach); File sysfile = new File(fullPath); if (!sysfile.exists()) { sysfile.createNewFile(); } java.io.OutputStream out = new FileOutputStream(sysfile); org.apache.commons.io.IOUtils.copy(file.getInputStream(), out); out.close(); System.out.println("file name is :" + name); } } request.setAttribute("operating-status", "�����ɹ�! ��ӭ����ʹ�á�"); System.out.println("in the end...."); return "aftersave"; }
public static boolean copyFileCover(String srcFileName, String descFileName, boolean coverlay) { File srcFile = new File(srcFileName); if (!srcFile.exists()) { System.out.println("�����ļ�ʧ�ܣ�Դ�ļ�" + srcFileName + "������!"); return false; } else if (!srcFile.isFile()) { System.out.println("�����ļ�ʧ�ܣ�" + srcFileName + "����һ���ļ�!"); return false; } File descFile = new File(descFileName); if (descFile.exists()) { if (coverlay) { System.out.println("Ŀ���ļ��Ѵ��ڣ�׼��ɾ��!"); if (!FileOperateUtils.delFile(descFileName)) { System.out.println("ɾ��Ŀ���ļ�" + descFileName + "ʧ��!"); return false; } } else { System.out.println("�����ļ�ʧ�ܣ�Ŀ���ļ�" + descFileName + "�Ѵ���!"); return false; } } else { if (!descFile.getParentFile().exists()) { System.out.println("Ŀ���ļ����ڵ�Ŀ¼�����ڣ�����Ŀ¼!"); if (!descFile.getParentFile().mkdirs()) { System.out.println("����Ŀ���ļ����ڵ�Ŀ¼ʧ��!"); return false; } } } int readByte = 0; InputStream ins = null; OutputStream outs = null; try { ins = new FileInputStream(srcFile); outs = new FileOutputStream(descFile); byte[] buf = new byte[1024]; while ((readByte = ins.read(buf)) != -1) { outs.write(buf, 0, readByte); } System.out.println("���Ƶ����ļ�" + srcFileName + "��" + descFileName + "�ɹ�!"); return true; } catch (Exception e) { System.out.println("�����ļ�ʧ�ܣ�" + e.getMessage()); return false; } finally { if (outs != null) { try { outs.close(); } catch (IOException oute) { oute.printStackTrace(); } } if (ins != null) { try { ins.close(); } catch (IOException ine) { ine.printStackTrace(); } } } }
true
540
19,657,516
7,507,773
private static Map loadHandlerList(final String resourceName, ClassLoader loader) { if (loader == null) loader = ClassLoader.getSystemClassLoader(); final Map result = new HashMap(); try { final Enumeration resources = loader.getResources(resourceName); if (resources != null) { while (resources.hasMoreElements()) { final URL url = (URL) resources.nextElement(); final Properties mapping; InputStream urlIn = null; try { urlIn = url.openStream(); mapping = new Properties(); mapping.load(urlIn); } catch (IOException ioe) { continue; } finally { if (urlIn != null) try { urlIn.close(); } catch (Exception ignore) { } } for (Enumeration keys = mapping.propertyNames(); keys.hasMoreElements(); ) { final String protocol = (String) keys.nextElement(); final String implClassName = mapping.getProperty(protocol); final Object currentImpl = result.get(protocol); if (currentImpl != null) { if (implClassName.equals(currentImpl.getClass().getName())) continue; else throw new IllegalStateException("duplicate " + "protocol handler class [" + implClassName + "] for protocol " + protocol); } result.put(protocol, loadURLStreamHandler(implClassName, loader)); } } } } catch (IOException ignore) { } return result; }
public boolean restore(File directory) { log.debug("restore file from directory " + directory.getAbsolutePath()); try { if (!directory.exists()) return false; String[] operationFileNames = directory.list(); if (operationFileNames.length < 6) { log.error("Only " + operationFileNames.length + " files found in directory " + directory.getAbsolutePath()); return false; } int fileCount = 0; for (int i = 0; i < operationFileNames.length; i++) { if (!operationFileNames[i].toUpperCase().endsWith(".XML")) continue; log.debug("found file: " + operationFileNames[i]); fileCount++; File filein = new File(directory.getAbsolutePath() + File.separator + operationFileNames[i]); File fileout = new File(operationsDirectory + File.separator + operationFileNames[i]); FileReader in = new FileReader(filein); FileWriter out = new FileWriter(fileout); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } if (fileCount < 6) return false; return true; } catch (Exception e) { log.error("Exception while restoring operations files, may not be complete: " + e); return false; } }
false
541
18,374,477
21,262,909
public void insertUser(final User user) throws IOException { try { Connection conn = null; boolean autoCommit = false; try { conn = pool.getConnection(); autoCommit = conn.getAutoCommit(); conn.setAutoCommit(false); final PreparedStatement insertUser = conn.prepareStatement("insert into users (userId, mainRoleId) values (?,?)"); log.finest("userId= " + user.getUserId()); insertUser.setString(1, user.getUserId()); log.finest("mainRole= " + user.getMainRole().getId()); insertUser.setInt(2, user.getMainRole().getId()); insertUser.executeUpdate(); final PreparedStatement insertRoles = conn.prepareStatement("insert into userRoles (userId, roleId) values (?,?)"); for (final Role role : user.getRoles()) { insertRoles.setString(1, user.getUserId()); insertRoles.setInt(2, role.getId()); insertRoles.executeUpdate(); } conn.commit(); } catch (Throwable t) { if (conn != null) conn.rollback(); log.log(Level.SEVERE, t.toString(), t); throw new SQLException(t.toString()); } finally { if (conn != null) { conn.setAutoCommit(autoCommit); conn.close(); } } } catch (final SQLException sqle) { log.log(Level.SEVERE, sqle.toString(), sqle); throw new IOException(sqle.toString()); } }
public static void find(String pckgname, Class<?> tosubclass) { String name = new String(pckgname); if (!name.startsWith("/")) { name = "/" + name; } name = name.replace('.', '/'); URL url = tosubclass.getResource(name); System.out.println(name + "->" + url); if (url == null) return; File directory = new File(url.getFile()); if (directory.exists()) { String[] files = directory.list(); for (int i = 0; i < files.length; i++) { if (files[i].endsWith(".class")) { String classname = files[i].substring(0, files[i].length() - 6); try { Object o = Class.forName(pckgname + "." + classname).newInstance(); if (tosubclass.isInstance(o)) { System.out.println(classname); } } catch (ClassNotFoundException cnfex) { System.err.println(cnfex); } catch (InstantiationException iex) { } catch (IllegalAccessException iaex) { } } } } else { try { JarURLConnection conn = (JarURLConnection) url.openConnection(); String starts = conn.getEntryName(); JarFile jfile = conn.getJarFile(); Enumeration<JarEntry> e = jfile.entries(); while (e.hasMoreElements()) { ZipEntry entry = e.nextElement(); String entryname = entry.getName(); if (entryname.startsWith(starts) && (entryname.lastIndexOf('/') <= starts.length()) && entryname.endsWith(".class")) { String classname = entryname.substring(0, entryname.length() - 6); if (classname.startsWith("/")) classname = classname.substring(1); classname = classname.replace('/', '.'); try { Object o = Class.forName(classname).newInstance(); if (tosubclass.isInstance(o)) { System.out.println(classname.substring(classname.lastIndexOf('.') + 1)); } } catch (ClassNotFoundException cnfex) { System.err.println(cnfex); } catch (InstantiationException iex) { } catch (IllegalAccessException iaex) { } } } } catch (IOException ioex) { System.err.println(ioex); } } }
false
542
4,505,945
23,099,329
private BinaryDocument documentFor(String code, String type, int diagramIndex) { code = code.replaceAll("\n", "").replaceAll("\t", "").trim().replaceAll(" ", "%20"); StringBuilder builder = new StringBuilder("http://yuml.me/diagram/"); builder.append(type).append("/"); builder.append(code); URL url; try { url = new URL(builder.toString()); String name = "uml" + diagramIndex + ".png"; diagramIndex++; BinaryDocument pic = new BinaryDocument(name, "image/png"); IOUtils.copy(url.openStream(), pic.getContent().getOutputStream()); return pic; } catch (MalformedURLException e) { throw ManagedIOException.manage(e); } catch (IOException e) { throw ManagedIOException.manage(e); } }
@Override public void close() throws IOException { super.close(); byte[] signatureData = toByteArray(); ZipOutputStream zipOutputStream = new ZipOutputStream(this.targetOutputStream); ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(this.originalZipFile)); ZipEntry zipEntry; while (null != (zipEntry = zipInputStream.getNextEntry())) { if (!zipEntry.getName().equals(ASiCUtil.SIGNATURE_FILE)) { ZipEntry newZipEntry = new ZipEntry(zipEntry.getName()); zipOutputStream.putNextEntry(newZipEntry); LOG.debug("copying " + zipEntry.getName()); IOUtils.copy(zipInputStream, zipOutputStream); } } zipInputStream.close(); zipEntry = new ZipEntry(ASiCUtil.SIGNATURE_FILE); LOG.debug("writing " + zipEntry.getName()); zipOutputStream.putNextEntry(zipEntry); IOUtils.write(signatureData, zipOutputStream); zipOutputStream.close(); }
true
543
22,135,201
21,781,575
public void testCodingFromFileSmaller() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); WritableByteChannel channel = newChannel(baos); HttpParams params = new BasicHttpParams(); SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 16); File tmpFile = File.createTempFile("testFile", "txt"); FileOutputStream fout = new FileOutputStream(tmpFile); OutputStreamWriter wrtout = new OutputStreamWriter(fout); wrtout.write("stuff;"); wrtout.write("more stuff;"); wrtout.flush(); wrtout.close(); FileChannel fchannel = new FileInputStream(tmpFile).getChannel(); encoder.transfer(fchannel, 0, 20); String s = baos.toString("US-ASCII"); assertTrue(encoder.isCompleted()); assertEquals("stuff;more stuff", s); tmpFile.delete(); }
private String loadSchemas() { StringWriter writer = new StringWriter(); try { IOUtils.copy(CoreOdfValidator.class.getResourceAsStream("schema_list.properties"), writer); } catch (IOException e) { e.printStackTrace(); } return writer.toString(); }
true
544
5,951,609
1,953,115
public void testCryptHash() { Log.v("Test", "[*] testCryptHash()"); String testStr = "Hash me"; byte messageDigest[]; MessageDigest digest = null; try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(testStr.getBytes()); messageDigest = digest.digest(); digest.digest(testStr.getBytes()); digest = java.security.MessageDigest.getInstance("SHA1"); digest.update(testStr.getBytes()); messageDigest = digest.digest(); digest = null; digest = java.security.MessageDigest.getInstance("SHA1"); digest.update(imei.getBytes()); messageDigest = digest.digest(); hashedImei = this.toHex(messageDigest); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } }
protected int doWork() { SAMFileReader reader = new SAMFileReader(IoUtil.openFileForReading(INPUT)); reader.getFileHeader().setSortOrder(SORT_ORDER); SAMFileWriter writer = new SAMFileWriterFactory().makeSAMOrBAMWriter(reader.getFileHeader(), false, OUTPUT); Iterator<SAMRecord> iterator = reader.iterator(); while (iterator.hasNext()) writer.addAlignment(iterator.next()); reader.close(); writer.close(); return 0; }
false
545
13,299,925
15,333,826
public void run() { try { FileChannel in = (new FileInputStream(file)).getChannel(); FileChannel out = (new FileOutputStream(updaterFile)).getChannel(); in.transferTo(0, file.length(), out); updater.setProgress(50); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } startUpdater(); }
public synchronized String encrypt(String password) { try { MessageDigest md = null; md = MessageDigest.getInstance("SHA-1"); md.update(password.getBytes("UTF-8")); byte raw[] = md.digest(); byte[] hash = (new Base64()).encode(raw); return new String(hash); } catch (NoSuchAlgorithmException e) { System.out.println("Algorithm SHA-1 is not supported"); return null; } catch (UnsupportedEncodingException e) { System.out.println("UTF-8 encoding is not supported"); return null; } }
false
546
658,771
13,275,192
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(); }
public static void main(String[] args) throws Exception { BufferedImage image = ImageIO.read(BitmapFont.class.getResource("Candara-38-Bold.png")); URL url = BitmapFontData.class.getResource("Candara-38-Bold.fnt"); BitmapFontData bitmapFontData = new BitmapFontData(url.openStream(), true); BitmapFont font = new BitmapFont(bitmapFontData, true); font.drawMultiLine("Hello world\nthis is a\ntest!!!", 100, 100); VertexData vertexData = font.createVertexData(); Display.setDisplayMode(new DisplayMode(640, 480)); Display.create(); RenderPass renderPass = new RenderPass(); renderPass.setClearMask(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); renderPass.setClearColor(new Color4f(0.3f, 0.4f, 0.5f, 1f)); renderPass.setView(View.createOrtho(0, 640, 0, 480, -1000, 1000)); ByteBuffer[][] pixels = { { TextureLoader.getImageData(image) } }; Texture texture = new Texture(TextureType.TEXTURE_2D, 4, image.getWidth(), image.getHeight(), 0, Format.BGRA, pixels, false, false); Shape shape = new Shape(vertexData); shape.getState().setUnit(0, new Unit(texture)); shape.getState().setBlendEnabled(true); shape.getState().setBlendSrcFunc(BlendSrcFunc.SRC_ALPHA); shape.getState().setBlendDstFunc(BlendDstFunc.ONE_MINUS_SRC_ALPHA); renderPass.getRootNode().addShape(shape); Renderer renderer = new Renderer(new SceneGraph(renderPass)); while (!Display.isCloseRequested()) { renderer.render(); Display.update(); } Display.destroy(); }
false
547
16,588,230
7,553,634
public static void main(String[] args) throws IOException { MSPack pack = new MSPack(new FileInputStream(args[0])); String[] files = pack.getFileNames(); for (int i = 0; i < files.length; i++) System.out.println(i + ": " + files[i] + ": " + pack.getLengths()[i]); System.out.println("Writing " + files[files.length - 1]); InputStream is = pack.getInputStream(files.length - 1); OutputStream os = new FileOutputStream(files[files.length - 1]); int n; byte[] buf = new byte[4096]; while ((n = is.read(buf)) != -1) os.write(buf, 0, n); os.close(); is.close(); }
public static String calcolaMd5(String messaggio) { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } md.reset(); md.update(messaggio.getBytes()); byte[] impronta = md.digest(); return new String(impronta); }
false
548
793,386
16,236,980
public void bubbleSort(int[] arr) { BasicProcessor.getInstance().getStartBlock(); BasicProcessor.getInstance().getVarDeclaration(); boolean swapped = true; BasicProcessor.getInstance().getVarDeclaration(); int j = 0; BasicProcessor.getInstance().getVarDeclaration(); int tmp; { BasicProcessor.getInstance().getWhileStatement(); while (swapped) { BasicProcessor.getInstance().getStartBlock(); swapped = false; j++; { BasicProcessor.getInstance().getForStatement(); for (int i = 0; i < arr.length - j; i++) { BasicProcessor.getInstance().getStartBlock(); { BasicProcessor.getInstance().getIfStatement(); if (arr[i] > arr[i + 1]) { BasicProcessor.getInstance().getStartBlock(); tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; swapped = true; BasicProcessor.getInstance().getEndBlock(); } } BasicProcessor.getInstance().getEndBlock(); } } BasicProcessor.getInstance().getEndBlock(); } } BasicProcessor.getInstance().getEndBlock(); }
public void loadProperties() { try { java.util.Properties props = new java.util.Properties(); java.net.URL url = ClassLoader.getSystemResource("env.properties"); props.load(url.openStream()); this.proxyCertificatePath = props.getProperty("proxy.certificate.path"); this.dummyFileDirName = props.getProperty("delete.dummyFileDirName"); this.idleTimeTestDelay = new Integer(props.getProperty("idleTimeTestDelaySeconds")); if (props.getProperty("gridftp.timeoutMilliSecs") != null) { this.gridftpTimeoutMilliSecs = new Integer(props.getProperty("gridftp.timeoutMilliSecs").trim()); } this.assertContentInWriteTests = new Boolean(props.getProperty("assertContentInWriteTests")); this.gridftpHost1 = props.getProperty("gridftp.host1"); this.gridftpPort1 = new Integer(props.getProperty("gridftp.port1")); this.gridftpHost2 = props.getProperty("gridftp.host2"); this.gridftpPort2 = new Integer(props.getProperty("gridftp.port2")); this.srbGsiHost = props.getProperty("srb.gsi.host"); this.srbGsiPort = new Integer(props.getProperty("srb.gsi.port")); this.srbGsiPortMin = new Integer(props.getProperty("srb.gsi.port.min")); this.srbGsiPortMax = new Integer(props.getProperty("srb.gsi.port.max")); this.srbGsiDefaultResource = props.getProperty("srb.gsi.defaultResource"); this.srbEncryptHost = props.getProperty("srb.encrypt.host"); this.srbEncryptPort = new Integer(props.getProperty("srb.encrypt.port")); this.srbEncryptPortMin = new Integer(props.getProperty("srb.encrypt.port.min")); this.srbEncryptPortMax = new Integer(props.getProperty("srb.encrypt.port.max")); this.srbEncryptDefaultResource = props.getProperty("srb.encrypt.defaultResource"); this.srbEncryptHomeDirectory = props.getProperty("srb.encrypt.homeDirectory"); this.srbEncryptMcatZone = props.getProperty("srb.encrypt.mcatZone"); this.srbEncryptMdasDomainName = props.getProperty("srb.encrypt.mdasDomainName"); this.srbEncryptUsername = props.getProperty("srb.encrypt.username"); this.srbEncryptPassword = props.getProperty("srb.encrypt.password"); this.sftpHost = props.getProperty("sftp.host"); this.sftpPort = new Integer(props.getProperty("sftp.port")); this.sftpPath = props.getProperty("sftp.path"); this.sftpUsername = props.getProperty("sftp.username"); this.sftpPassword = props.getProperty("sftp.password"); if (props.getProperty("sftp.timeoutMilliSecs") != null) { this.sftpTimeoutMilliSecs = new Integer(props.getProperty("sftp.timeoutMilliSecs").trim()); } irodsEncryptHost = props.getProperty("irods.encrypt.host"); irodsEncryptPort = new Integer(props.getProperty("irods.encrypt.port")); irodsEncryptResource = props.getProperty("irods.encrypt.defaultResource"); irodsEncryptHomeDirectory = props.getProperty("irods.encrypt.homeDirectory"); irodsEncryptZone = props.getProperty("irods.encrypt.zone"); irodsEncryptUsername = props.getProperty("irods.encrypt.username"); irodsEncryptPassword = props.getProperty("irods.encrypt.password"); irodsGsiHost = props.getProperty("irods.gsi.host"); irodsGsiPort = new Integer(props.getProperty("irods.gsi.port")); irodsGsiZone = props.getProperty("irods.gsi.zone"); srbQueryTimeout = new Integer(props.getProperty("srb.query.timeout")); this.ftpUri = props.getProperty("ftp.uri"); this.httpUri = props.getProperty("http.uri"); this.httpProxy = props.getProperty("http.proxy"); this.httpPort = new Integer(props.getProperty("http.port")); this.fileUri = props.getProperty("file.uri"); java.net.URI tempUri = new java.net.URI(this.fileUri); File f = new File(tempUri); if (!f.exists()) { String temp = System.getProperty("java.io.tmpdir"); System.out.println("Cannot list [" + fileUri + "] listing java.io.tmpdir instead [" + temp + "]"); this.fileUri = temp; } useSrbGsiInFsCopyTest = new Boolean(props.getProperty("srb.gsi.use.in.fs.copy.test")); useSrbEncryptInFsCopyTest = new Boolean(props.getProperty("srb.encrypt.use.in.fs.copy.test")); useGridftpHost1InFsCopyTest = new Boolean(props.getProperty("gridftp.host1.use.in.fs.copy.test")); useGridftpHost2InFsCopyTest = new Boolean(props.getProperty("gridftp.host2.use.in.fs.copy.test")); useSftpInFsCopyTest = new Boolean(props.getProperty("sftp.use.in.fs.copy.test")); useLocalFileInFsCopyTest = new Boolean(props.getProperty("file.use.in.fs.copy.test")); useIrodsGsiCopyTest = new Boolean(props.getProperty("irods.gsi.use.in.fs.copy.test")); useIrodsEncryptCopyTest = new Boolean(props.getProperty("irods.encrypt.use.in.fs.copy.test")); assertNotNull(this.proxyCertificatePath); assertNotNull(this.dummyFileDirName); assertNotNull(this.idleTimeTestDelay); assertNotNull(this.ftpUri); assertNotNull(this.httpUri); } catch (Exception ex) { Logger.getLogger(AbstractTestClass.class.getName()).log(Level.SEVERE, null, ex); fail("Unable to locate and load 'testsettings.properties' file in source " + ex); } }
false
549
14,058,237
22,525,884
public boolean renameTo(File dest) throws IOException { if (dest == null) { throw new NullPointerException("dest"); } if (!file.renameTo(dest)) { FileInputStream inputStream = new FileInputStream(file); FileOutputStream outputStream = new FileOutputStream(dest); FileChannel in = inputStream.getChannel(); FileChannel out = outputStream.getChannel(); long destsize = in.transferTo(0, size, out); in.close(); out.close(); if (destsize == size) { file.delete(); file = dest; isRenamed = true; return true; } else { dest.delete(); return false; } } file = dest; isRenamed = true; return true; }
public String generateKey(String className, String methodName, String text, String meaning) { if (text == null) { return null; } MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Error initializing MD5", e); } try { md5.update(text.getBytes("UTF-8")); if (meaning != null) { md5.update(meaning.getBytes("UTF-8")); } } catch (UnsupportedEncodingException e) { throw new RuntimeException("UTF-8 unsupported", e); } return StringUtils.toHexString(md5.digest()); }
false
550
3,210,076
5,266,380
private void readHomePage(ITestThread testThread) throws IOException { if (null == testThread) { throw new IllegalArgumentException("Test thread may not be null."); } final InputStream urlIn = new URL(testUrl).openStream(); final int availableBytes = urlIn.available(); if (0 == availableBytes) { throw new IllegalStateException("Zero bytes on target host."); } in = new BufferedReader(new InputStreamReader(urlIn)); String line; while (null != in && null != (line = in.readLine())) { page.append(line); page.append('\n'); if (0 != lineDelay) { OS.sleep(lineDelay); } if (testThread.isActionStopped()) { break; } } }
public WordEntry[] getVariants(String word) throws MatchPackException { String upperWord = word.toUpperCase(); if (variantsDictionary == null) { try { long start = System.currentTimeMillis(); URL url = this.getClass().getResource("varlex.dic"); ObjectInputStream si = new ObjectInputStream(url.openStream()); variantsDictionary = (Map) si.readObject(); long end = System.currentTimeMillis(); System.out.println("loaded " + (end - start) + "ms"); si.close(); } catch (Exception e) { throw new MatchPackException("cannot load: varlex.dic " + e.getMessage()); } } List l = (List) variantsDictionary.get(upperWord); if (l == null) { return new WordEntry[0]; } return (WordEntry[]) l.toArray(new WordEntry[0]); }
false
551
21,150,258
1,427,758
private String convert(InputStream input, String encoding) throws Exception { Process p = Runtime.getRuntime().exec("tidy -q -f /dev/null -wrap 0 --output-xml yes --doctype omit --force-output true --new-empty-tags " + emptyTags + " --quote-nbsp no -utf8"); Thread t = new CopyThread(input, p.getOutputStream()); t.start(); ByteArrayOutputStream output = new ByteArrayOutputStream(); IOUtils.copy(p.getInputStream(), output); p.waitFor(); t.join(); return output.toString(); }
private static void ensureJavaScriptHostBytes(TreeLogger logger) throws UnableToCompleteException { if (javaScriptHostBytes != null) { return; } String className = JavaScriptHost.class.getName(); try { String path = className.replace('.', '/') + ".class"; ClassLoader cl = Thread.currentThread().getContextClassLoader(); URL url = cl.getResource(path); if (url != null) { javaScriptHostBytes = getClassBytesFromStream(url.openStream()); } else { logger.log(TreeLogger.ERROR, "Could not find required bootstrap class '" + className + "' in the classpath", null); throw new UnableToCompleteException(); } } catch (IOException e) { logger.log(TreeLogger.ERROR, "Error reading class bytes for " + className, e); throw new UnableToCompleteException(); } }
false
552
23,494,305
13,433,127
private static void copy(File src, File dst) { try { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { e.printStackTrace(); } }
public void save(File selectedFile) throws IOException { if (storeEntriesInFiles) { boolean moved = false; for (int i = 0; i < tempFiles.size(); i++) { File newFile = new File(selectedFile.getAbsolutePath() + "_" + Integer.toString(i) + ".zettmp"); moved = tempFiles.get(i).renameTo(newFile); if (!moved) { BufferedReader read = new BufferedReader(new FileReader(tempFiles.get(i))); PrintWriter write = new PrintWriter(newFile); String s; while ((s = read.readLine()) != null) write.print(s); read.close(); write.flush(); write.close(); tempFiles.get(i).delete(); } tempFiles.set(i, newFile); } } GZIPOutputStream output = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(selectedFile))); XStream xml_convert = new XStream(); xml_convert.setMode(XStream.ID_REFERENCES); xml_convert.toXML(this, output); output.flush(); output.close(); }
true
553
6,245,929
18,878,916
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { URL url = new URL("http://pubsubhubbub.appspot.com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream()); out.write("hub.mode=publish&hub.url=" + req.getParameter("url")); out.flush(); out.close(); conn.getResponseCode(); try { resp.sendRedirect(req.getParameter("from")); } catch (Exception e) { } }
public String getContents(String fileUri) throws IOException { StringBuffer contents = new StringBuffer(); if (fileUri != null && !fileUri.equals("")) { BufferedReader input = null; try { LOG.info("Reading:" + fileUri); URL url = getClass().getClassLoader().getResource(fileUri); if (url != null) { InputStream stream = url.openStream(); input = new BufferedReader(new InputStreamReader(stream)); appendInputToContents(input, contents); } else { LOG.error("Unable to locate file:" + fileUri + " in directory " + new File(".").getAbsolutePath()); } } finally { if (input != null) { input.close(); } } } return contents.toString(); }
false
554
8,024,082
5,596,825
public static void main(String[] args) throws Exception { FileChannel fc = new FileOutputStream("data.txt").getChannel(); fc.write(ByteBuffer.wrap("Some text ".getBytes())); fc.close(); fc = new RandomAccessFile("data.txt", "rw").getChannel(); fc.position(fc.size()); fc.write(ByteBuffer.wrap("Some more".getBytes())); fc.close(); fc = new FileInputStream("data.txt").getChannel(); ByteBuffer buff = ByteBuffer.allocate(BSIZE); fc.read(buff); buff.flip(); while (buff.hasRemaining()) System.out.print((char) buff.get()); }
public ZIPSignatureService(InputStream documentInputStream, SignatureFacet signatureFacet, OutputStream documentOutputStream, RevocationDataService revocationDataService, TimeStampService timeStampService, String role, IdentityDTO identity, byte[] photo, DigestAlgo signatureDigestAlgo) throws IOException { super(signatureDigestAlgo); this.temporaryDataStorage = new HttpSessionTemporaryDataStorage(); this.documentOutputStream = documentOutputStream; this.tmpFile = File.createTempFile("eid-dss-", ".zip"); FileOutputStream fileOutputStream; fileOutputStream = new FileOutputStream(this.tmpFile); IOUtils.copy(documentInputStream, fileOutputStream); addSignatureFacet(new ZIPSignatureFacet(this.tmpFile, signatureDigestAlgo)); XAdESSignatureFacet xadesSignatureFacet = new XAdESSignatureFacet(getSignatureDigestAlgorithm()); xadesSignatureFacet.setRole(role); addSignatureFacet(xadesSignatureFacet); addSignatureFacet(new KeyInfoSignatureFacet(true, false, false)); addSignatureFacet(new XAdESXLSignatureFacet(timeStampService, revocationDataService, getSignatureDigestAlgorithm())); addSignatureFacet(signatureFacet); if (null != identity) { IdentitySignatureFacet identitySignatureFacet = new IdentitySignatureFacet(identity, photo, getSignatureDigestAlgorithm()); addSignatureFacet(identitySignatureFacet); } }
true
555
12,138,255
6,853,666
public static void loadPoFile(URL url) { states state = states.IDLE; String msgCtxt = ""; String msgId = ""; String msgStr = ""; try { if (url == null) return; InputStream in = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF8")); String strLine; while ((strLine = br.readLine()) != null) { if (strLine.startsWith("msgctxt")) { if (state != states.MSGCTXT) msgCtxt = ""; state = states.MSGCTXT; strLine = strLine.substring(7).trim(); } if (strLine.startsWith("msgid")) { if (state != states.MSGID) msgId = ""; state = states.MSGID; strLine = strLine.substring(5).trim(); } if (strLine.startsWith("msgstr")) { if (state != states.MSGSTR) msgStr = ""; state = states.MSGSTR; strLine = strLine.substring(6).trim(); } if (!strLine.startsWith("\"")) { state = states.IDLE; msgCtxt = ""; msgId = ""; msgStr = ""; } else { if (state == states.MSGCTXT) { msgCtxt += format(strLine); } if (state == states.MSGID) { if (msgId.isEmpty()) { if (!msgCtxt.isEmpty()) { msgId = msgCtxt + "|"; msgCtxt = ""; } } msgId += format(strLine); } if (state == states.MSGSTR) { msgCtxt = ""; msgStr += format(strLine); if (!msgId.isEmpty()) messages.setProperty(msgId, msgStr); } } } in.close(); } catch (IOException e) { Logger.logError(e, "Error loading message.po."); } }
public static void sendPostRequest() { String data = "text=Eschirichia coli"; try { URL url = new URL("http://taxonfinder.ubio.org/analyze?"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(data); writer.flush(); StringBuffer answer = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = reader.readLine()) != null) { answer.append(line); } writer.close(); reader.close(); System.out.println(answer.toString()); } catch (MalformedURLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } }
true
556
8,372,919
10,893,111
private String MD5(String s) { Log.d("MD5", "Hashing '" + s + "'"); String hash = ""; try { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(s.getBytes(), 0, s.length()); hash = new BigInteger(1, m.digest()).toString(16); Log.d("MD5", "Hash: " + hash); } catch (Exception e) { Log.e("MD5", e.getMessage()); } return hash; }
public static void copyFile(File in, File out) throws IOException { try { FileReader inf = new FileReader(in); OutputStreamWriter outf = new OutputStreamWriter(new FileOutputStream(out), "UTF-8"); int c; while ((c = inf.read()) != -1) outf.write(c); inf.close(); outf.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
false
557
6,788,258
16,891,145
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); } }
public static byte[] expandPasswordToKeySSHCom(String password, int keyLen) { try { if (password == null) { password = ""; } MessageDigest md5 = MessageDigest.getInstance("MD5"); int digLen = md5.getDigestLength(); byte[] buf = new byte[((keyLen + digLen) / digLen) * digLen]; int cnt = 0; while (cnt < keyLen) { md5.update(password.getBytes()); if (cnt > 0) { md5.update(buf, 0, cnt); } md5.digest(buf, cnt, digLen); cnt += digLen; } byte[] key = new byte[keyLen]; System.arraycopy(buf, 0, key, 0, keyLen); return key; } catch (Exception e) { throw new Error("Error in SSH2KeyPairFile.expandPasswordToKeySSHCom: " + e); } }
true
558
8,612,648
2,575,374
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 static void copy(File in, File out) throws Exception { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
true
559
3,054,600
2,433,175
private void generateArchetype(final IProject project, final IDataModel model, final IProgressMonitor monitor, final boolean offline) throws CoreException, InterruptedException, IOException { if (getArchetypeArtifactId(model) != null) { final Properties properties = new Properties(); properties.put("archetypeArtifactId", getArchetypeArtifactId(model)); properties.put("archetypeGroupId", getArchetypeGroupId(model)); properties.put("archetypeVersion", getArchetypeVersion(model)); String artifact = (String) model.getProperty(IMavenFacetInstallDataModelProperties.PROJECT_ARTIFACT_ID); if (artifact == null || artifact.trim().length() == 0) { artifact = project.getName(); } properties.put("artifactId", artifact); String group = (String) model.getProperty(IMavenFacetInstallDataModelProperties.PROJECT_GROUP_ID); if (group == null || group.trim().length() == 0) { group = project.getName(); } properties.put("groupId", group); properties.put("version", model.getProperty(IMavenFacetInstallDataModelProperties.PROJECT_VERSION)); final StringBuffer sb = new StringBuffer(System.getProperty("user.home")).append(File.separator); sb.append(".m2").append(File.separator).append("repository"); final String local = sb.toString(); Logger.getLog().debug("Local Maven2 repository :: " + local); properties.put("localRepository", local); if (!offline) { final String sbRepos = getRepositories(); properties.put("remoteRepositories", sbRepos); } final ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager(); final ILaunchConfigurationType launchConfigurationType = launchManager.getLaunchConfigurationType(LAUNCH_CONFIGURATION_TYPE_ID); final ILaunchConfigurationWorkingCopy workingCopy = launchConfigurationType.newInstance(null, "Creating project using Apache Maven archetype"); File archetypePomDirectory = getDefaultArchetypePomDirectory(); try { String dfPom = getPomFile(group, artifact); ByteArrayInputStream bais = new ByteArrayInputStream(dfPom.getBytes()); File f = new File(archetypePomDirectory, "pom.xml"); OutputStream fous = null; try { fous = new FileOutputStream(f); IOUtils.copy(bais, fous); } finally { try { if (fous != null) { fous.close(); } if (bais != null) { bais.close(); } } catch (IOException e) { } } if (SiteManager.isHttpProxyEnable()) { addProxySettings(properties); } workingCopy.setAttribute(ATTR_POM_DIR, archetypePomDirectory.getAbsolutePath()); workingCopy.setAttribute(ATTR_PROPERTIES, convertPropertiesToList(properties)); String goalName = "archetype:create"; if (offline) { goalName = new StringBuffer(goalName).append(" -o").toString(); } goalName = updateGoal(goalName); workingCopy.setAttribute(ATTR_GOALS, goalName); final long timeout = org.maven.ide.eclipse.ext.Maven2Plugin.getTimeout(); TimeoutLaunchConfiguration.launchWithTimeout(monitor, workingCopy, project, timeout); monitor.setTaskName("Moving to workspace"); FileUtils.copyDirectoryStructure(new File(archetypePomDirectory, project.getName()), ArchetypePOMHelper.getProjectDirectory(project)); monitor.worked(1); performMavenInstall(monitor, project, offline); project.refreshLocal(2, monitor); } catch (final IOException ioe) { Logger.log(Logger.ERROR, "I/O exception. One probably solution is absence " + "of mvn2 archetypes or not the correct version, " + "in your local repository. Please, check existence " + "of this archetype."); Logger.getLog().error("I/O Exception arised creating mvn2 archetype", ioe); throw ioe; } finally { FileUtils.deleteDirectory(archetypePomDirectory); Logger.log(Logger.INFO, "Invoked removing of archetype POM directory"); } } monitor.worked(1); }
private void copyFile(File orig, File dest) { byte[] buffer = new byte[1024]; try { FileInputStream fis = new FileInputStream(orig); FileOutputStream fos = new FileOutputStream(dest, true); int readBytes = 0; do { readBytes = fis.read(buffer); if (readBytes > 0) fos.write(buffer, 0, readBytes); } while (readBytes > 0); fos.close(); fis.close(); } catch (Exception e) { e.printStackTrace(); } }
true
560
23,179,136
18,510,279
private void doLogin(String password) throws LoginFailedException, IncorrectPasswordException { final long mgr = Constants.MANAGER; Data data, response; try { response = sendAndWait(new Request(mgr)).get(0); MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("MD5 hash not supported."); } byte[] challenge = response.getBytes(); md.update(challenge); md.update(password.getBytes(Data.STRING_ENCODING)); try { data = Data.valueOf(md.digest()); response = sendAndWait(new Request(mgr).add(0, data)).get(0); } catch (ExecutionException ex) { throw new IncorrectPasswordException(); } setLoginMessage(response.getString()); response = sendAndWait(new Request(mgr).add(0, getLoginData())).get(0); ID = response.getWord(); registerSettings(); } catch (InterruptedException ex) { throw new LoginFailedException(ex); } catch (ExecutionException ex) { throw new LoginFailedException(ex); } catch (IOException ex) { throw new LoginFailedException(ex); } }
public void login() { loginsuccessful = false; try { cookies = new StringBuilder(); HttpParams params = new BasicHttpParams(); params.setParameter("http.useragent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6"); DefaultHttpClient httpclient = new DefaultHttpClient(params); NULogger.getLogger().info("Trying to log in to crocko.com"); HttpPost httppost = new HttpPost("https://www.crocko.com/accounts/login"); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("login", getUsername())); formparams.add(new BasicNameValuePair("password", getPassword())); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); httppost.setEntity(entity); HttpResponse httpresponse = httpclient.execute(httppost); NULogger.getLogger().info("Getting cookies........"); NULogger.getLogger().info(EntityUtils.toString(httpresponse.getEntity())); Iterator<Cookie> it = httpclient.getCookieStore().getCookies().iterator(); Cookie escookie = null; while (it.hasNext()) { escookie = it.next(); cookies.append(escookie.getName()).append("=").append(escookie.getValue()).append(";"); if (escookie.getName().equals("PHPSESSID")) { sessionid = escookie.getValue(); NULogger.getLogger().info(sessionid); } } if (cookies.toString().contains("logacc")) { NULogger.getLogger().info(cookies.toString()); loginsuccessful = true; username = getUsername(); password = getPassword(); NULogger.getLogger().info("Crocko login successful :)"); } if (!loginsuccessful) { NULogger.getLogger().info("Crocko.com Login failed :("); loginsuccessful = false; username = ""; password = ""; JOptionPane.showMessageDialog(NeembuuUploader.getInstance(), "<html><b>" + HOSTNAME + "</b> " + TranslationProvider.get("neembuuuploader.accounts.loginerror") + "</html>", HOSTNAME, JOptionPane.WARNING_MESSAGE); AccountsManager.getInstance().setVisible(true); } httpclient.getConnectionManager().shutdown(); } catch (Exception e) { NULogger.getLogger().log(Level.SEVERE, "{0}: {1}", new Object[] { getClass().getName(), e.toString() }); System.err.println(e); } }
false
561
9,510,815
3,726,610
public static void copy(File source, File target) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(target).getChannel(); ByteBuffer buffer = ByteBuffer.allocateDirect(BUFFER); while (in.read(buffer) != -1) { buffer.flip(); while (buffer.hasRemaining()) { out.write(buffer); } buffer.clear(); } } catch (IOException ex) { throw new RuntimeException(ex); } finally { close(in); close(out); } }
private static void processFile(StreamDriver driver, String sourceName) throws Exception { String destName = sourceName + ".xml"; File dest = new File(destName); if (dest.exists()) { throw new IllegalArgumentException("File '" + destName + "' already exists!"); } FileChannel sourceChannel = new FileInputStream(sourceName).getChannel(); try { MappedByteBuffer sourceByteBuffer = sourceChannel.map(FileChannel.MapMode.READ_ONLY, 0, sourceChannel.size()); CharsetDecoder decoder = Charset.forName("ISO-8859-15").newDecoder(); CharBuffer sourceBuffer = decoder.decode(sourceByteBuffer); driver.generateXmlDocument(sourceBuffer, new FileOutputStream(dest)); } finally { sourceChannel.close(); } }
true
562
20,052,285
5,375,381
private void copyFile(String path) { try { File srcfile = new File(srcdir, path); File destfile = new File(destdir, path); File parent = destfile.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } FileInputStream fis = new FileInputStream(srcfile); FileOutputStream fos = new FileOutputStream(destfile); int bytes_read = 0; byte buffer[] = new byte[512]; while ((bytes_read = fis.read(buffer)) != -1) { fos.write(buffer, 0, bytes_read); } fis.close(); fos.close(); } catch (IOException e) { throw new BuildException("Error while copying file " + path); } }
public TempFileBinaryBody(InputStream is) throws IOException { TempPath tempPath = TempStorage.getInstance().getRootTempPath(); tempFile = tempPath.createTempFile("attachment", ".bin"); OutputStream out = tempFile.getOutputStream(); IOUtils.copy(is, out); out.close(); }
true
563
5,004,897
3,352,341
private boolean passwordMatches(String user, String plainPassword, String scrambledPassword) { MessageDigest md; byte[] temp_digest, pass_digest; byte[] hex_digest = new byte[35]; byte[] scrambled = scrambledPassword.getBytes(); try { md = MessageDigest.getInstance("MD5"); md.update(plainPassword.getBytes("US-ASCII")); md.update(user.getBytes("US-ASCII")); temp_digest = md.digest(); Utils.bytesToHex(temp_digest, hex_digest, 0); md.update(hex_digest, 0, 32); md.update(salt.getBytes()); pass_digest = md.digest(); Utils.bytesToHex(pass_digest, hex_digest, 3); hex_digest[0] = (byte) 'm'; hex_digest[1] = (byte) 'd'; hex_digest[2] = (byte) '5'; for (int i = 0; i < hex_digest.length; i++) { if (scrambled[i] != hex_digest[i]) { return false; } } } catch (Exception e) { logger.error(e); } return true; }
public void processSaveCompany(Company companyBean, AuthSession authSession) { if (authSession == null) { return; } DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); String sql = "UPDATE WM_LIST_COMPANY " + "SET " + " full_name = ?, " + " short_name = ?, " + " address = ?, " + " telefon_buh = ?, " + " telefon_chief = ?, " + " chief = ?, " + " buh = ?, " + " fax = ?, " + " email = ?, " + " icq = ?, " + " short_client_info = ?, " + " url = ?, " + " short_info = ? " + "WHERE ID_FIRM = ? and ID_FIRM in "; switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: String idList = authSession.getGrantedCompanyId(); sql += " (" + idList + ") "; break; default: sql += "(select z1.ID_FIRM from v$_read_list_firm z1 where z1.user_login = ?)"; break; } ps = dbDyn.prepareStatement(sql); int num = 1; ps.setString(num++, companyBean.getName()); ps.setString(num++, companyBean.getShortName()); ps.setString(num++, companyBean.getAddress()); ps.setString(num++, ""); ps.setString(num++, ""); ps.setString(num++, companyBean.getCeo()); ps.setString(num++, companyBean.getCfo()); ps.setString(num++, ""); ps.setString(num++, ""); RsetTools.setLong(ps, num++, null); ps.setString(num++, ""); ps.setString(num++, companyBean.getWebsite()); ps.setString(num++, companyBean.getInfo()); RsetTools.setLong(ps, num++, companyBean.getId()); switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: break; default: ps.setString(num++, authSession.getUserLogin()); break; } int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of updated record - " + i1); dbDyn.commit(); } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error save company"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } }
false
564
12,979,701
20,849,254
@Override public List<SheetFullName> importSheets(INetxiliaSystem workbookProcessor, WorkbookId workbookName, URL url, IProcessingConsole console) throws ImportException { try { return importSheets(workbookProcessor, workbookName, url.openStream(), console); } catch (Exception e) { throw new ImportException(url, "Cannot open workbook:" + e, e); } }
public static AudioInputStream getWavFromURL(String urlstr) { URL url; AudioInputStream ais = null; try { url = new URL(urlstr); URLConnection c = url.openConnection(); c.connect(); InputStream stream = c.getInputStream(); ais = new AudioInputStream(stream, playFormat, AudioSystem.NOT_SPECIFIED); LOG.debug("[getWavFromURL]Getting audio from URL: {}", url); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ais; }
false
565
13,234,957
14,782,656
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 Long statusSWGCraftTime() { long current = System.currentTimeMillis() / 1000L; if (current < (previousStatusCheck + SWGCraft.STATUS_CHECK_DELAY)) return previousStatusTime; URL url = null; try { synchronized (previousStatusTime) { if (current >= previousStatusCheck + SWGCraft.STATUS_CHECK_DELAY) { url = SWGCraft.getStatusTextURL(); String statusTime = ZReader.read(url.openStream()); previousStatusTime = Long.valueOf(statusTime); previousStatusCheck = current; } return previousStatusTime; } } catch (UnknownHostException e) { SWGCraft.showUnknownHostDialog(url, e); } catch (Throwable e) { SWGAide.printDebug("cmgr", 1, "SWGResourceManager:statusSWGCraftTime:", e.toString()); } return Long.valueOf(0); }
false
566
15,088,608
23,429,413
public synchronized String encrypt(String plaintext) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException noSuchAlgorithmException) { noSuchAlgorithmException.printStackTrace(); } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException unsupportedEncodingException) { unsupportedEncodingException.printStackTrace(); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
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()); }
true
567
16,549,992
20,325,581
public static String hash(String string, String algorithm, String encoding) throws UnsupportedEncodingException { try { MessageDigest digest = MessageDigest.getInstance(algorithm); digest.update(string.getBytes(encoding)); byte[] encodedPassword = digest.digest(); return new BigInteger(1, encodedPassword).toString(16); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } }
public static byte[] generateHash(String strPassword, byte[] salt) { try { MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.update(strPassword.getBytes(CHAR_ENCODING)); md.update(salt); return md.digest(); } catch (Exception e) { e.printStackTrace(); } return null; }
true
568
3,673,682
4,048,013
private void DrawModel(Graphics offg, int obj_num, boolean object, float h, float s, int vt_num, int fc_num) { int px[] = new int[3]; int py[] = new int[3]; int count = 0; int tmp[] = new int[fc_num]; double tmp_depth[] = new double[fc_num]; rotate(vt_num); offg.setColor(Color.black); for (int i = 0; i < fc_num; i++) { double a1 = fc[i].vt1.x - fc[i].vt0.x; double a2 = fc[i].vt1.y - fc[i].vt0.y; double a3 = fc[i].vt1.z - fc[i].vt0.z; double b1 = fc[i].vt2.x - fc[i].vt1.x; double b2 = fc[i].vt2.y - fc[i].vt1.y; double b3 = fc[i].vt2.z - fc[i].vt1.z; fc[i].nx = a2 * b3 - a3 * b2; fc[i].ny = a3 * b1 - a1 * b3; fc[i].nz = a1 * b2 - a2 * b1; if (fc[i].nz < 0) { fc[i].nx = a2 * b3 - a3 * b2; fc[i].ny = a3 * b1 - a1 * b3; tmp[count] = i; tmp_depth[count] = fc[i].getDepth(); count++; } } int lim = count - 1; do { int m = 0; for (int n = 0; n <= lim - 1; n++) { if (tmp_depth[n] < tmp_depth[n + 1]) { double t = tmp_depth[n]; tmp_depth[n] = tmp_depth[n + 1]; tmp_depth[n + 1] = t; int ti = tmp[n]; tmp[n] = tmp[n + 1]; tmp[n + 1] = ti; m = n; } } lim = m; } while (lim != 0); for (int m = 0; m < count; m++) { int i = tmp[m]; double l = Math.sqrt(fc[i].nx * fc[i].nx + fc[i].ny * fc[i].ny + fc[i].nz * fc[i].nz); test(offg, i, l, h, s); px[0] = (int) (fc[i].vt0.x * m_Scale + centerp.x); py[0] = (int) (-fc[i].vt0.y * m_Scale + centerp.y); px[1] = (int) (fc[i].vt1.x * m_Scale + centerp.x); py[1] = (int) (-fc[i].vt1.y * m_Scale + centerp.y); px[2] = (int) (fc[i].vt2.x * m_Scale + centerp.x); py[2] = (int) (-fc[i].vt2.y * m_Scale + centerp.y); offg.fillPolygon(px, py, 3); } if (labelFlag && object) { offg.setFont(Fonts.FONT_REAL); offg.drawString(d_con.getPointerData().getRealObjName(obj_num), (int) ((fc[0].vt0.x + 10) * m_Scale + centerp.x), (int) (-(fc[0].vt0.y + 10) * m_Scale + centerp.y)); } }
public InputStream getParameterAsInputStream(String key) throws UndefinedParameterError, IOException { String urlString = getParameter(key); if (urlString == null) return null; try { URL url = new URL(urlString); InputStream stream = url.openStream(); return stream; } catch (MalformedURLException e) { File file = getParameterAsFile(key); if (file != null) { return new FileInputStream(file); } else { return null; } } }
false
569
8,071,138
14,555,517
public void sendContent(OutputStream out, Range range, Map map, String string) throws IOException, NotAuthorizedException, BadRequestException { System.out.println("sendContent " + file); RFileInputStream in = new RFileInputStream(file); try { IOUtils.copyLarge(in, out); } finally { in.close(); } }
@Override @RemoteMethod public boolean encrypt(int idAnexo) { try { Anexo anexo = anexoService.selectById(idAnexo); aes.init(Cipher.ENCRYPT_MODE, aeskeySpec); FileInputStream fis = new FileInputStream(config.baseDir + "/arquivos_upload_direto/" + anexo.getAnexoCaminho()); CipherOutputStream cos = new CipherOutputStream(new FileOutputStream(config.baseDir + "/arquivos_upload_direto/encrypt/" + anexo.getAnexoCaminho()), aes); IOUtils.copy(fis, cos); cos.close(); fis.close(); } catch (Exception e) { e.printStackTrace(); return false; } return true; }
true
570
16,568,044
7,713,594
public void setContentAsStream(final InputStream input) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); try { IOUtils.copy(input, output); } finally { output.close(); } this.content = output.toByteArray(); }
private static void copyFile(File source, File dest, boolean visibleFilesOnly) throws IOException { if (visibleFilesOnly && isHiddenOrDotFile(source)) { return; } if (dest.exists()) { System.err.println("Destination File Already Exists: " + dest); } FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }
true
571
7,321,949
16,958,918
private boolean saveLOBDataToFileSystem() { if ("".equals(m_attachmentPathRoot)) { log.severe("no attachmentPath defined"); return false; } if (m_items == null || m_items.size() == 0) { setBinaryData(null); return true; } final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { final DocumentBuilder builder = factory.newDocumentBuilder(); final Document document = builder.newDocument(); final Element root = document.createElement("attachments"); document.appendChild(root); document.setXmlStandalone(true); for (int i = 0; i < m_items.size(); i++) { log.fine(m_items.get(i).toString()); File entryFile = m_items.get(i).getFile(); final String path = entryFile.getAbsolutePath(); log.fine(path + " - " + m_attachmentPathRoot); if (!path.startsWith(m_attachmentPathRoot)) { log.fine("move file: " + path); FileChannel in = null; FileChannel out = null; try { final File destFolder = new File(m_attachmentPathRoot + File.separator + getAttachmentPathSnippet()); if (!destFolder.exists()) { if (!destFolder.mkdirs()) { log.warning("unable to create folder: " + destFolder.getPath()); } } final File destFile = new File(m_attachmentPathRoot + File.separator + getAttachmentPathSnippet() + File.separator + entryFile.getName()); in = new FileInputStream(entryFile).getChannel(); out = new FileOutputStream(destFile).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); if (entryFile.exists()) { if (!entryFile.delete()) { entryFile.deleteOnExit(); } } entryFile = destFile; } catch (IOException e) { e.printStackTrace(); log.severe("unable to copy file " + entryFile.getAbsolutePath() + " to " + m_attachmentPathRoot + File.separator + getAttachmentPathSnippet() + File.separator + entryFile.getName()); } finally { if (in != null && in.isOpen()) { in.close(); } if (out != null && out.isOpen()) { out.close(); } } } final Element entry = document.createElement("entry"); entry.setAttribute("name", getEntryName(i)); String filePathToStore = entryFile.getAbsolutePath(); filePathToStore = filePathToStore.replaceFirst(m_attachmentPathRoot.replaceAll("\\\\", "\\\\\\\\"), ATTACHMENT_FOLDER_PLACEHOLDER); log.fine(filePathToStore); entry.setAttribute("file", filePathToStore); root.appendChild(entry); } final Source source = new DOMSource(document); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final Result result = new StreamResult(bos); final Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.transform(source, result); final byte[] xmlData = bos.toByteArray(); log.fine(bos.toString()); setBinaryData(xmlData); return true; } catch (Exception e) { log.log(Level.SEVERE, "saveLOBData", e); } setBinaryData(null); return false; }
public static boolean copyFile(final String src, final String dest) { if (fileExists(src)) { try { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); return true; } catch (IOException e) { Logger.getAnonymousLogger().severe(e.getLocalizedMessage()); } } return false; }
true
572
8,693,826
16,388,707
private String readJsonString() { StringBuilder builder = new StringBuilder(); HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(SERVER_URL); try { HttpResponse response = client.execute(httpGet); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } } else { Log.e(TAG, "Failed to download file"); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return builder.toString(); }
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; }
false
573
16,123,665
2,092,752
public static void bubbleSort(Drawable[] list) { boolean swapped; do { swapped = false; for (int i = 0; i < list.length - 1; ++i) { if (list[i].getSortValue() > list[i + 1].getSortValue()) { Drawable temp = list[i]; list[i] = list[i + 1]; list[i + 1] = temp; swapped = true; } } } while (swapped); }
public void save() { final JFileChooser fc = new JFileChooser(); fc.setFileFilter(new FileFilter() { public String getDescription() { return "PDF File"; } public boolean accept(File f) { return f.isDirectory() || f.getName().toLowerCase().endsWith(".pdf"); } }); if (fc.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) { return; } File targetFile = fc.getSelectedFile(); if (!targetFile.getName().toLowerCase().endsWith(".pdf")) { targetFile = new File(targetFile.getParentFile(), targetFile.getName() + ".pdf"); } if (targetFile.exists()) { if (JOptionPane.showConfirmDialog(this, "Do you want to overwrite the file?") != JOptionPane.YES_OPTION) { return; } } try { final InputStream is = new FileInputStream(filename); try { final OutputStream os = new FileOutputStream(targetFile); try { final byte[] buffer = new byte[32768]; for (int read; (read = is.read(buffer)) != -1; ) { os.write(buffer, 0, read); } } finally { os.close(); } } finally { is.close(); } } catch (IOException e) { e.printStackTrace(); } }
false
574
253,661
15,507,613
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(); } }
@Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); int i; String dicomURL = request.getParameter("datasetURL"); String contentType = request.getParameter("contentType"); String studyUID = request.getParameter("studyUID"); String seriesUID = request.getParameter("seriesUID"); String objectUID = request.getParameter("objectUID"); dicomURL += "&contentType=" + contentType + "&studyUID=" + studyUID + "&seriesUID=" + seriesUID + "&objectUID=" + objectUID + "&transferSyntax=1.2.840.10008.1.2.1"; dicomURL = dicomURL.replace("+", "%2B"); InputStream is = null; DataInputStream dis = null; try { URL url = new URL(dicomURL); is = url.openStream(); dis = new DataInputStream(is); for (i = 0; i < dicomData.length; i++) dicomData[i] = dis.readUnsignedByte(); String windowCenter = getElementValue("00281050"); String windowWidth = getElementValue("00281051"); request.getSession(true).setAttribute(WINDOW_CENTER_PARAM, windowCenter == null ? null : windowCenter.trim()); request.getSession(true).setAttribute(WINDOW_WIDTH_PARAM, windowWidth == null ? null : windowWidth.trim()); dis.skipBytes(50000000); is.close(); dis.close(); out.println("Success"); out.close(); } catch (Exception e) { log.error("Unable to read and send the DICOM dataset page", e); } }
false
575
4,114,529
10,432,257
@Override public void save(File folder) { actInstance = instance; this.setProperty(EsomMapper.PROPERTY_INSTANCE, String.valueOf(actInstance)); log.debug("instance: " + this.getProperty(EsomMapper.PROPERTY_INSTANCE)); if (this.getProperty(EsomMapper.PROPERTY_LRN_RADIO_SELECTED) == EsomMapper.RADIO_LOAD_SELECTED) { File src = new File(this.getProperty(EsomMapper.PROPERTY_LRN_FILE)); if (src.getParent() != folder.getPath()) { log.debug("saving lrn file in save folder " + folder.getPath()); File dst = new File(folder.getAbsolutePath() + File.separator + src.getName() + String.valueOf(actInstance)); try { FileReader fr = new FileReader(src); BufferedReader br = new BufferedReader(fr); dst.createNewFile(); FileWriter fw = new FileWriter(dst); BufferedWriter bw = new BufferedWriter(fw); int i = 0; while ((i = br.read()) != -1) bw.write(i); bw.flush(); bw.close(); br.close(); fr.close(); } catch (FileNotFoundException e) { log.error("Error while opening lrn sourcefile! Saving wasn't possible!!!"); e.printStackTrace(); } catch (IOException e) { log.error("Error while creating lrn destfile! Creating wasn't possible!!!"); e.printStackTrace(); } this.setProperty(EsomMapper.PROPERTY_LRN_FILE, dst.getName()); log.debug("done saving lrn file"); } } if (this.getProperty(EsomMapper.PROPERTY_WTS_RADIO_SELECTED) == EsomMapper.RADIO_LOAD_SELECTED) { File src = new File(this.getProperty(EsomMapper.PROPERTY_WTS_FILE)); if (src.getParent() != folder.getPath()) { log.debug("saving wts file in save folder " + folder.getPath()); File dst = new File(folder.getAbsolutePath() + File.separator + src.getName() + String.valueOf(actInstance)); try { FileReader fr = new FileReader(src); BufferedReader br = new BufferedReader(fr); dst.createNewFile(); FileWriter fw = new FileWriter(dst); BufferedWriter bw = new BufferedWriter(fw); int i = 0; while ((i = br.read()) != -1) bw.write(i); bw.flush(); bw.close(); br.close(); fr.close(); } catch (FileNotFoundException e) { log.error("Error while opening wts sourcefile! Saving wasn't possible!!!"); e.printStackTrace(); } catch (IOException e) { log.error("Error while creating wts destfile! Creating wasn't possible!!!"); e.printStackTrace(); } this.setProperty(EsomMapper.PROPERTY_WTS_FILE, dst.getName()); log.debug("done saving wts file"); } } if (this.getProperty(EsomMapper.PROPERTY_LRN_RADIO_SELECTED) == EsomMapper.RADIO_SELECT_FROM_DATANAV_SELECTED) { this.setProperty(EsomMapper.PROPERTY_LRN_FILE, "EsomMapper" + this.actInstance + ".lrn"); File dst = new File(folder + File.separator + this.getProperty(EsomMapper.PROPERTY_LRN_FILE)); try { FileWriter fw = new FileWriter(dst); BufferedWriter bw = new BufferedWriter(fw); bw.write("# EsomMapper LRN save file\n"); bw.write("% " + this.inputVectors.getNumRows() + "\n"); bw.write("% " + this.inputVectors.getNumCols() + "\n"); bw.write("% 9"); for (IColumn col : this.inputVectors.getColumns()) { if (col.getType() == IClusterNumber.class) bw.write("\t2"); else if (col.getType() == String.class) bw.write("\t8"); else bw.write("\t1"); } bw.write("\n% Key"); for (IColumn col : this.inputVectors.getColumns()) { bw.write("\t" + col.getLabel()); } bw.write("\n"); int keyIterator = 0; for (Vector<Object> row : this.inputVectors.getGrid()) { bw.write(this.inputVectors.getKey(keyIterator++).toString()); for (Object point : row) bw.write("\t" + point.toString()); bw.write("\n"); } bw.flush(); fw.flush(); bw.close(); fw.close(); } catch (IOException e) { e.printStackTrace(); } this.setProperty(EsomMapper.PROPERTY_LRN_RADIO_SELECTED, EsomMapper.RADIO_LOAD_SELECTED); } if (this.getProperty(EsomMapper.PROPERTY_WTS_RADIO_SELECTED) == EsomMapper.RADIO_SELECT_FROM_DATANAV_SELECTED) { this.setProperty(EsomMapper.PROPERTY_WTS_FILE, "EsomMapper" + this.actInstance + ".wts"); MyRetina tempRetina = new MyRetina(this.outputRetina.getNumRows(), this.outputRetina.getNumCols(), this.outputRetina.getDim(), this.outputRetina.getDistanceFunction(), this.outputRetina.isToroid()); for (int row = 0; row < this.outputRetina.getNumRows(); row++) { for (int col = 0; col < this.outputRetina.getNumCols(); col++) { for (int dim = 0; dim < this.outputRetina.getDim(); dim++) { tempRetina.setNeuron(row, col, dim, this.outputRetina.getPointasDoubleArray(row, col)[dim]); } } } EsomIO.writeWTSFile(folder + File.separator + this.getProperty(EsomMapper.PROPERTY_WTS_FILE), tempRetina); this.setProperty(EsomMapper.PROPERTY_WTS_RADIO_SELECTED, EsomMapper.RADIO_LOAD_SELECTED); } EsomMapper.instance++; }
private void createImageArchive() throws Exception { imageArchive = new File(resoutFolder, "images.CrAr"); DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(imageArchive))); out.writeInt(toNativeEndian(imageFiles.size())); for (int i = 0; i < imageFiles.size(); i++) { File f = imageFiles.get(i); out.writeLong(toNativeEndian(f.length())); out.writeLong(toNativeEndian(new File(resFolder, f.getName().substring(0, f.getName().length() - 5)).length())); } for (int i = 0; i < imageFiles.size(); i++) { BufferedInputStream in = new BufferedInputStream(new FileInputStream(imageFiles.get(i))); int read; while ((read = in.read()) != -1) { out.write(read); } in.close(); } out.close(); }
true
576
20,239,268
8,883,153
public static File[] splitFile(FileValidator validator, File source, long target_length, File todir, String prefix) { if (target_length == 0) return null; if (todir == null) { todir = new File(System.getProperty("java.io.tmpdir")); } if (prefix == null || prefix.equals("")) { prefix = source.getName(); } Vector result = new Vector(); FileOutputStream fos = null; FileInputStream fis = null; try { fis = new FileInputStream(source); byte[] bytes = new byte[CACHE_SIZE]; long current_target_size = 0; int current_target_nb = 1; int nbread = -1; try { File f = new File(todir, prefix + i18n.getString("targetname_suffix") + current_target_nb); if (!validator.verifyFile(f)) return null; result.add(f); fos = new FileOutputStream(f); while ((nbread = fis.read(bytes)) > -1) { if ((current_target_size + nbread) > target_length) { int limit = (int) (target_length - current_target_size); fos.write(bytes, 0, limit); fos.close(); current_target_nb++; current_target_size = 0; f = new File(todir, prefix + "_" + current_target_nb); if (!validator.verifyFile(f)) return null; result.add(f); fos = new FileOutputStream(f); fos.write(bytes, limit, nbread - limit); current_target_size += nbread - limit; } else { fos.write(bytes, 0, nbread); current_target_size += nbread; } } } catch (IOException ioe) { JOptionPane.showMessageDialog(null, ioe, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); } finally { try { if (fos != null) fos.close(); } catch (IOException e) { } try { if (fis != null) fis.close(); } catch (IOException e) { } } } catch (Exception e) { JOptionPane.showMessageDialog(null, e, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); } finally { try { if (fos != null) fos.close(); } catch (IOException e) { } } File[] fresult = null; if (result.size() > 0) { fresult = new File[result.size()]; fresult = (File[]) result.toArray(fresult); } return fresult; }
protected int getResponseCode(String address) throws Exception { URL url = new URL(address); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setUseCaches(false); try { con.connect(); return con.getResponseCode(); } finally { con.disconnect(); } }
false
577
2,711,585
649,639
public static void _save(PortletRequest req, PortletResponse res, PortletConfig config, ActionForm form) throws Exception { try { String filePath = getUserManagerConfigPath() + "user_manager_config.properties"; String tmpFilePath = UtilMethods.getTemporaryDirPath() + "user_manager_config_properties.tmp"; File from = new java.io.File(tmpFilePath); from.createNewFile(); File to = new java.io.File(filePath); to.createNewFile(); FileChannel srcChannel = new FileInputStream(from).getChannel(); FileChannel dstChannel = new FileOutputStream(to).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (NonWritableChannelException we) { } catch (IOException e) { Logger.error(UserManagerPropertiesFactory.class, "Property File save Failed " + e, e); } SessionMessages.add(req, "message", "message.usermanager.display.save"); }
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(); } }
true
578
14,244,843
20,926,398
private void encryptChkFile(ProjectMember member, File chkFile) throws Exception { final java.io.FileReader reader = new java.io.FileReader(chkFile); final File encryptedChkFile = new File(member.createOutputFileName(outputPath, "chk")); FileOutputStream outfile = null; ObjectOutputStream outstream = null; Utilities.discardBooleanResult(encryptedChkFile.getParentFile().mkdirs()); outfile = new FileOutputStream(encryptedChkFile); outstream = new ObjectOutputStream(outfile); outstream.writeObject(new Format().parse(reader)); reader.close(); outfile.close(); outstream.close(); }
public static Cursor load(URL url, String descriptor) { if (url == null) { log.log(Level.WARNING, "Trying to load a cursor with a null url."); return null; } String cursorFile = url.getFile(); BufferedReader reader = null; int lineNumber = 0; try { DirectoryTextureLoader loader; URL cursorUrl; if (cursorFile.endsWith(cursorDescriptorFile)) { cursorUrl = url; Cursor cached = cursorCache.get(url); if (cached != null) return cached; reader = new BufferedReader(new InputStreamReader(url.openStream())); loader = new DirectoryTextureLoader(url, false); } else if (cursorFile.endsWith(cursorArchiveFile)) { loader = new DirectoryTextureLoader(url, true); if (descriptor == null) descriptor = defaultDescriptorFile; cursorUrl = loader.makeUrl(descriptor); Cursor cached = cursorCache.get(url); if (cached != null) return cached; ZipInputStream zis = new ZipInputStream(url.openStream()); ZipEntry entry; boolean found = false; while ((entry = zis.getNextEntry()) != null) { if (descriptor.equals(entry.getName())) { found = true; break; } } if (!found) { throw new IOException("Descriptor file \"" + descriptor + "\" was not found."); } reader = new BufferedReader(new InputStreamReader(zis)); } else { log.log(Level.WARNING, "Invalid cursor fileName \"{0}\".", cursorFile); return null; } Cursor cursor = new Cursor(); cursor.url = cursorUrl; List<Integer> delays = new ArrayList<Integer>(); List<String> frameFileNames = new ArrayList<String>(); Map<String, Texture> textureCache = new HashMap<String, Texture>(); String line; while ((line = reader.readLine()) != null) { lineNumber++; int commentIndex = line.indexOf(commentString); if (commentIndex != -1) { line = line.substring(0, commentIndex); } StringTokenizer tokens = new StringTokenizer(line, delims); if (!tokens.hasMoreTokens()) continue; String prefix = tokens.nextToken(); if (prefix.equals(hotSpotXPrefix)) { cursor.hotSpotOffset.x = Integer.valueOf(tokens.nextToken()); } else if (prefix.equals(hotSpotYPrefix)) { cursor.hotSpotOffset.y = Integer.valueOf(tokens.nextToken()); } else if (prefix.equals(timePrefix)) { delays.add(Integer.valueOf(tokens.nextToken())); if (tokens.nextToken().equals(imagePrefix)) { String file = tokens.nextToken(""); file = file.substring(file.indexOf('=') + 1); file.trim(); frameFileNames.add(file); if (textureCache.get(file) == null) { textureCache.put(file, loader.loadTexture(file)); } } else { throw new NoSuchElementException(); } } } cursor.frameFileNames = frameFileNames.toArray(new String[0]); cursor.textureCache = textureCache; cursor.delays = new int[delays.size()]; cursor.images = new Image[frameFileNames.size()]; cursor.textures = new Texture[frameFileNames.size()]; for (int i = 0; i < cursor.frameFileNames.length; i++) { cursor.textures[i] = textureCache.get(cursor.frameFileNames[i]); cursor.images[i] = cursor.textures[i].getImage(); cursor.delays[i] = delays.get(i); } if (delays.size() == 1) cursor.delays = null; if (cursor.images.length == 0) { log.log(Level.WARNING, "The cursor has no animation frames."); return null; } cursor.width = cursor.images[0].getWidth(); cursor.height = cursor.images[0].getHeight(); cursorCache.put(cursor.url, cursor); return cursor; } catch (MalformedURLException mue) { log.log(Level.WARNING, "Unable to load cursor.", mue); } catch (IOException ioe) { log.log(Level.WARNING, "Unable to load cursor.", ioe); } catch (NumberFormatException nfe) { log.log(Level.WARNING, "Numerical error while parsing the " + "file \"{0}\" at line {1}", new Object[] { url, lineNumber }); } catch (IndexOutOfBoundsException ioobe) { log.log(Level.WARNING, "Error, \"=\" expected in the file \"{0}\" at line {1}", new Object[] { url, lineNumber }); } catch (NoSuchElementException nsee) { log.log(Level.WARNING, "Error while parsing the file \"{0}\" at line {1}", new Object[] { url, lineNumber }); } finally { if (reader != null) { try { reader.close(); } catch (IOException ioe) { log.log(Level.SEVERE, "Unable to close the steam.", ioe); } } } return null; }
false
579
519,787
20,684,330
public InputStream unZip(URL url) throws Exception { ZipInputStream zipped = new ZipInputStream(url.openStream()); System.out.println("unzipping: " + url.getFile()); ZipEntry zip = zipped.getNextEntry(); byte[] b = new byte[4096]; ByteArrayOutputStream bOut = new ByteArrayOutputStream(); for (int iRead = zipped.read(b); iRead != -1; iRead = zipped.read(b)) { bOut.write(b, 0, iRead); } zipped.close(); ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); return (InputStream) bIn; }
public String downloadToSdCard(String localFileName, String suffixFromHeader, String extension) { InputStream in = null; FileOutputStream fos = null; String absolutePath = null; try { Log.i(TAG, "Opening URL: " + url); StreamAndHeader inAndHeader = HTTPUtils.openWithHeader(url, suffixFromHeader); if (inAndHeader == null || inAndHeader.mStream == null) { return null; } in = inAndHeader.mStream; String sdcardpath = android.os.Environment.getExternalStorageDirectory().getAbsolutePath(); String headerValue = suffixFromHeader == null || inAndHeader.mHeaderValue == null ? "" : inAndHeader.mHeaderValue; headerValue = headerValue.replaceAll("[-:]*\\s*", ""); String filename = sdcardpath + "/" + localFileName + headerValue + (extension == null ? "" : extension); mSize = in.available(); Log.i(TAG, "Downloading " + filename + ", size: " + mSize); fos = new FileOutputStream(new File(filename)); int buffersize = 1024; byte[] buffer = new byte[buffersize]; int readsize = buffersize; mCount = 0; while (readsize != -1) { readsize = in.read(buffer, 0, buffersize); if (readsize > 0) { Log.i(TAG, "Read " + readsize + " bytes..."); fos.write(buffer, 0, readsize); mCount += readsize; } } fos.flush(); fos.close(); FileInputStream controlIn = new FileInputStream(filename); mSavedSize = controlIn.available(); Log.v(TAG, "saved size: " + mSavedSize); mAbsolutePath = filename; done(); } catch (Exception e) { Log.e(TAG, "LoadingWorker.run", e); } finally { HTTPUtils.close(in); } return mAbsolutePath; }
false
580
5,942,289
15,599,609
private byte[] digestPassword(byte[] salt, String password) throws AuthenticationException { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(salt); md.update(password.getBytes("UTF8")); return md.digest(); } catch (Exception e) { throw new AuthenticationException(MESSAGE_CONFIGURATION_ERROR_KEY, e); } }
private void addAuditDatastream() throws ObjectIntegrityException, StreamIOException { if (m_obj.getAuditRecords().size() == 0) { return; } String dsId = m_pid.toURI() + "/AUDIT"; String dsvId = dsId + "/" + DateUtility.convertDateToString(m_obj.getCreateDate()); Entry dsEntry = m_feed.addEntry(); dsEntry.setId(dsId); dsEntry.setTitle("AUDIT"); dsEntry.setUpdated(m_obj.getCreateDate()); dsEntry.addCategory(MODEL.STATE.uri, "A", null); dsEntry.addCategory(MODEL.CONTROL_GROUP.uri, "X", null); dsEntry.addCategory(MODEL.VERSIONABLE.uri, "false", null); dsEntry.addLink(dsvId, Link.REL_ALTERNATE); Entry dsvEntry = m_feed.addEntry(); dsvEntry.setId(dsvId); dsvEntry.setTitle("AUDIT.0"); dsvEntry.setUpdated(m_obj.getCreateDate()); ThreadHelper.addInReplyTo(dsvEntry, m_pid.toURI() + "/AUDIT"); dsvEntry.addCategory(MODEL.FORMAT_URI.uri, AUDIT1_0.uri, null); dsvEntry.addCategory(MODEL.LABEL.uri, "Audit Trail for this object", null); if (m_format.equals(ATOM_ZIP1_1)) { String name = "AUDIT.0.xml"; try { m_zout.putNextEntry(new ZipEntry(name)); Reader r = new StringReader(DOTranslationUtility.getAuditTrail(m_obj)); IOUtils.copy(r, m_zout, m_encoding); m_zout.closeEntry(); r.close(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } IRI iri = new IRI(name); dsvEntry.setSummary("AUDIT.0"); dsvEntry.setContent(iri, "text/xml"); } else { dsvEntry.setContent(DOTranslationUtility.getAuditTrail(m_obj), "text/xml"); } }
false
581
13,680,335
21,947,196
private String fetchCompareContent() throws IOException { URL url = new URL(compareTo); StringWriter sw = new StringWriter(); IOUtils.copy(url.openStream(), sw); return sw.getBuffer().toString(); }
public synchronized String encrypt(final String pPassword) throws NoSuchAlgorithmException, UnsupportedEncodingException { final MessageDigest md = MessageDigest.getInstance("SHA"); md.update(pPassword.getBytes("UTF-8")); final byte raw[] = md.digest(); return BASE64Encoder.encodeBuffer(raw); }
false
582
691,247
15,940,692
private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
@Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String fileName = request.getParameter("tegsoftFileName"); if (fileName.startsWith("Tegsoft_BACKUP_")) { fileName = fileName.substring("Tegsoft_BACKUP_".length()); String targetFileName = "/home/customer/" + fileName; response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); FileInputStream is = new FileInputStream(targetFileName); IOUtils.copy(is, response.getOutputStream()); is.close(); return; } if (fileName.equals("Tegsoft_ASTMODULES")) { String targetFileName = tobeHome + "/setup/Tegsoft_ASTMODULES.tgz"; response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); FileInputStream is = new FileInputStream(targetFileName); IOUtils.copy(is, response.getOutputStream()); is.close(); return; } if (fileName.equals("Tegsoft_ASTSBIN")) { String targetFileName = tobeHome + "/setup/Tegsoft_ASTSBIN.tgz"; response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); FileInputStream is = new FileInputStream(targetFileName); IOUtils.copy(is, response.getOutputStream()); is.close(); return; } if (!fileName.startsWith("Tegsoft_")) { return; } if (!fileName.endsWith(".zip")) { return; } if (fileName.indexOf("_") < 0) { return; } fileName = fileName.substring(fileName.indexOf("_") + 1); if (fileName.indexOf("_") < 0) { return; } String fileType = fileName.substring(0, fileName.indexOf("_")); String destinationFileName = tobeHome + "/setup/Tegsoft_" + fileName; if (!new File(destinationFileName).exists()) { if ("FORMS".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/forms", tobeHome + "/setup/Tegsoft_" + fileName); } else if ("IMAGES".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/image", tobeHome + "/setup/Tegsoft_" + fileName); } else if ("VIDEOS".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/videos", tobeHome + "/setup/Tegsoft_" + fileName); } else if ("TEGSOFTJARS".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/WEB-INF/lib/", tobeHome + "/setup/Tegsoft_" + fileName, "Tegsoft", "jar"); } else if ("TOBEJARS".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/WEB-INF/lib/", tobeHome + "/setup/Tegsoft_" + fileName, "Tobe", "jar"); } else if ("ALLJARS".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/WEB-INF/lib/", tobeHome + "/setup/Tegsoft_" + fileName); } else if ("DB".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/sql", tobeHome + "/setup/Tegsoft_" + fileName); } else if ("CONFIGSERVICE".equals(fileType)) { FileUtil.createZipPackage("/tegsoft/src/java/TegsoftTelecom/configFiles/init.d/", tobeHome + "/setup/Tegsoft_" + fileName, "tegsoft", null); } else if ("CONFIGSCRIPTS".equals(fileType)) { FileUtil.createZipPackage("/tegsoft/src/java/TegsoftTelecom/configFiles/root/", tobeHome + "/setup/Tegsoft_" + fileName, "tegsoft", null); } else if ("CONFIGFOP".equals(fileType)) { FileUtil.createZipPackage("/tegsoft/src/java/TegsoftTelecom/configFiles/fop/", tobeHome + "/setup/Tegsoft_" + fileName); } else if ("CONFIGASTERISK".equals(fileType)) { FileUtil.createZipPackage("/tegsoft/src/java/TegsoftTelecom/configFiles/asterisk/", tobeHome + "/setup/Tegsoft_" + fileName); } } response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); FileInputStream is = new FileInputStream(destinationFileName); IOUtils.copy(is, response.getOutputStream()); is.close(); } catch (Exception ex) { ex.printStackTrace(); } }
true
583
3,229,361
21,273,055
public void copyFile(String source_name, String dest_name) throws IOException { File source_file = new File(source_name); File destination_file = new File(dest_name); FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException(QZ.PHRASES.getPhrase("25") + " " + source_name); if (!source_file.canRead()) throw new FileCopyException(QZ.PHRASES.getPhrase("26") + " " + QZ.PHRASES.getPhrase("27") + ": " + source_name); if (destination_file.exists()) { if (destination_file.isFile()) { DataInputStream in = new DataInputStream(System.in); String response; if (!destination_file.canWrite()) throw new FileCopyException(QZ.PHRASES.getPhrase("28") + " " + QZ.PHRASES.getPhrase("29") + ": " + dest_name); System.out.print(QZ.PHRASES.getPhrase("19") + dest_name + QZ.PHRASES.getPhrase("30") + ": "); System.out.flush(); response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new FileCopyException(QZ.PHRASES.getPhrase("31")); } else throw new FileCopyException(QZ.PHRASES.getPhrase("28") + " " + QZ.PHRASES.getPhrase("32") + ": " + dest_name); } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException(QZ.PHRASES.getPhrase("28") + " " + QZ.PHRASES.getPhrase("33") + ": " + dest_name); if (!parentdir.canWrite()) throw new FileCopyException(QZ.PHRASES.getPhrase("28") + " " + QZ.PHRASES.getPhrase("34") + ": " + dest_name); } source = new FileInputStream(source_file); destination = new FileOutputStream(destination_file); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } finally { if (source != null) try { source.close(); } catch (IOException e) { ; } if (destination != null) try { destination.close(); } catch (IOException e) { ; } } }
public RobotList<Resource> sort_incr_Resource(RobotList<Resource> list, String field) { int length = list.size(); Index_value[] resource_dist = new Index_value[length]; if (field.equals("") || field.equals("location")) { Location cur_loc = this.getLocation(); for (int i = 0; i < length; i++) { resource_dist[i] = new Index_value(i, distance(cur_loc, list.get(i).location)); } } else if (field.equals("energy")) { for (int i = 0; i < length; i++) { resource_dist[i] = new Index_value(i, list.get(i).energy); } } else if (field.equals("ammostash")) { for (int i = 0; i < length; i++) { resource_dist[i] = new Index_value(i, list.get(i).ammostash); } } else if (field.equals("speed")) { for (int i = 0; i < length; i++) { resource_dist[i] = new Index_value(i, list.get(i).speed); } } else if (field.equals("health")) { for (int i = 0; i < length; i++) { resource_dist[i] = new Index_value(i, list.get(i).health); } } else { say("impossible to sort list - nothing modified"); return list; } boolean permut; do { permut = false; for (int i = 0; i < length - 1; i++) { if (resource_dist[i].value > resource_dist[i + 1].value) { Index_value a = resource_dist[i]; resource_dist[i] = resource_dist[i + 1]; resource_dist[i + 1] = a; permut = true; } } } while (permut); RobotList<Resource> new_resource_list = new RobotList<Resource>(Resource.class); for (int i = 0; i < length; i++) { new_resource_list.addLast(list.get(resource_dist[i].index)); } return new_resource_list; }
false
584
17,456,737
21,907,869
public File addFile(File file, String suffix) throws IOException { if (file.exists() && file.isFile()) { File nf = File.createTempFile(prefix, "." + suffix, workdir); nf.delete(); if (!file.renameTo(nf)) { IOUtils.copy(file, nf); } synchronized (fileList) { fileList.add(nf); } if (log.isDebugEnabled()) { log.debug("Add file [" + file.getPath() + "] -> [" + nf.getPath() + "]"); } return nf; } return file; }
public static void copy(String source, String destination) { FileReader in = null; FileWriter out = null; try { File inputFile = new File(source); File outputFile = new File(destination); in = new FileReader(inputFile); out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) try { in.close(); } catch (IOException e) { e.printStackTrace(); } if (out != null) try { out.close(); } catch (IOException e) { e.printStackTrace(); } } }
true
585
12,863,885
21,515,430
private static String md5(String input) { String res = ""; try { MessageDigest cript = MessageDigest.getInstance("MD5"); cript.reset(); cript.update(input.getBytes()); byte[] md5 = cript.digest(); String tmp = ""; for (int i = 0; i < md5.length; i++) { tmp = (Integer.toHexString(0xFF & md5[i])); if (tmp.length() == 1) { res += "0" + tmp; } else { res += tmp; } } } catch (NoSuchAlgorithmException ex) { Log4k.error(pdfPrinter.class.getName(), ex.getMessage()); } return res; }
protected synchronized void doLogin(long timeout, String eventMask) throws IOException, AuthenticationFailedException, TimeoutException { ChallengeAction challengeAction; ManagerResponse challengeResponse; String challenge; String key; LoginAction loginAction; ManagerResponse loginResponse; if (socket == null) { connect(); } synchronized (protocolIdentifier) { if (protocolIdentifier.value == null) { try { protocolIdentifier.wait(timeout); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } if (protocolIdentifier.value == null) { disconnect(); if (reader != null && reader.getTerminationException() != null) { throw reader.getTerminationException(); } else { throw new TimeoutException("Timeout waiting for protocol identifier"); } } } challengeAction = new ChallengeAction("MD5"); try { challengeResponse = sendAction(challengeAction); } catch (Exception e) { disconnect(); throw new AuthenticationFailedException("Unable to send challenge action", e); } if (challengeResponse instanceof ChallengeResponse) { challenge = ((ChallengeResponse) challengeResponse).getChallenge(); } else { disconnect(); throw new AuthenticationFailedException("Unable to get challenge from Asterisk. ChallengeAction returned: " + challengeResponse.getMessage()); } try { MessageDigest md; md = MessageDigest.getInstance("MD5"); if (challenge != null) { md.update(challenge.getBytes()); } if (password != null) { md.update(password.getBytes()); } key = ManagerUtil.toHexString(md.digest()); } catch (NoSuchAlgorithmException ex) { disconnect(); throw new AuthenticationFailedException("Unable to create login key using MD5 Message Digest", ex); } loginAction = new LoginAction(username, "MD5", key, eventMask); try { loginResponse = sendAction(loginAction); } catch (Exception e) { disconnect(); throw new AuthenticationFailedException("Unable to send login action", e); } if (loginResponse instanceof ManagerError) { disconnect(); throw new AuthenticationFailedException(loginResponse.getMessage()); } state = CONNECTED; logger.info("Successfully logged in"); version = determineVersion(); writer.setTargetVersion(version); logger.info("Determined Asterisk version: " + version); ConnectEvent connectEvent = new ConnectEvent(this); connectEvent.setProtocolIdentifier(getProtocolIdentifier()); connectEvent.setDateReceived(DateUtil.getDate()); fireEvent(connectEvent); }
true
586
1,811,750
15,971,793
public void testHttpPostsWithExpectContinue() throws Exception { int reqNo = 20; Random rnd = new Random(); List testData = new ArrayList(reqNo); for (int i = 0; i < reqNo; i++) { int size = rnd.nextInt(5000); byte[] data = new byte[size]; rnd.nextBytes(data); testData.add(data); } this.server.registerHandler("*", new HttpRequestHandler() { public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (request instanceof HttpEntityEnclosingRequest) { HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] data = EntityUtils.toByteArray(incoming); ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(true); response.setEntity(outgoing); } else { StringEntity outgoing = new StringEntity("No content"); response.setEntity(outgoing); } } }); this.server.start(); this.client.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); HttpHost host = new HttpHost("localhost", this.server.getPort()); try { for (int r = 0; r < reqNo; r++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, this.client.getParams()); } BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/"); byte[] data = (byte[]) testData.get(r); ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(true); post.setEntity(outgoing); HttpResponse response = this.client.execute(post, host, conn); byte[] received = EntityUtils.toByteArray(response.getEntity()); byte[] expected = (byte[]) testData.get(r); assertEquals(expected.length, received.length); for (int i = 0; i < expected.length; i++) { assertEquals(expected[i], received[i]); } if (!this.client.keepAlive(response)) { conn.close(); } } HttpConnectionMetrics cm = conn.getMetrics(); assertEquals(reqNo, cm.getRequestCount()); assertEquals(reqNo, cm.getResponseCount()); } finally { conn.close(); this.server.shutdown(); } }
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { jButton1.setEnabled(false); for (int i = 0; i < max; i++) { Card crd = WLP.getSelectedCard(WLP.jTable1.getSelectedRows()[i]); String s, s2; s = ""; s2 = ""; try { URL url = new URL("http://www.m-w.com/dictionary/" + crd.getWord()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { s = s + str; } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } Pattern pattern = Pattern.compile("popWin\\('/cgi-bin/(.+?)'", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher = pattern.matcher(s); if (matcher.find()) { String newurl = "http://m-w.com/cgi-bin/" + matcher.group(1); try { URL url2 = new URL(newurl); BufferedReader in2 = new BufferedReader(new InputStreamReader(url2.openStream())); String str; while ((str = in2.readLine()) != null) { s2 = s2 + str; } in2.close(); } catch (MalformedURLException e) { } catch (IOException e) { } Pattern pattern2 = Pattern.compile("<A HREF=\"http://(.+?)\">Click here to listen with your default audio player", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher2 = pattern2.matcher(s2); if (matcher2.find()) { getWave("http://" + matcher2.group(1), crd.getWord()); } int val = jProgressBar1.getValue(); val++; jProgressBar1.setValue(val); this.paintAll(this.getGraphics()); } } jButton1.setEnabled(true); }
false
587
5,162,892
10,093,209
public void testRelativeRedirect2() throws Exception { int port = this.localServer.getServicePort(); String host = this.localServer.getServiceHostName(); this.localServer.register("*", new RelativeRedirectService2()); DefaultHttpClient client = new DefaultHttpClient(); HttpContext context = new BasicHttpContext(); client.getParams().setBooleanParameter(ClientPNames.REJECT_RELATIVE_REDIRECT, false); HttpGet httpget = new HttpGet("/test/oldlocation"); HttpResponse response = client.execute(getServerHttp(), httpget, context); HttpEntity e = response.getEntity(); if (e != null) { e.consumeContent(); } HttpRequest reqWrapper = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); assertEquals("/test/relativelocation", reqWrapper.getRequestLine().getUri()); assertEquals(host, targetHost.getHostName()); assertEquals(port, targetHost.getPort()); }
@Override public InitResult init(String name) { this.urlString = name; URL url; URLConnection con; try { url = new URL(urlString); con = url.openConnection(); int size = con.getContentLength(); char[] characters = new char[size]; BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); in.read(characters); in.close(); return new InitResult(0, size, characters); } catch (Exception e) { throw new ParserException(e); } }
false
588
11,818,436
6,535,232
public void zip_compressFiles() throws Exception { FileInputStream in = null; File f1 = new File("C:\\WINDOWS\\regedit.exe"); File f2 = new File("C:\\WINDOWS\\win.ini"); File file = new File("C:\\" + NTUtil.class.getName() + ".zip"); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file)); out.putNextEntry(new ZipEntry("regedit.exe")); in = new FileInputStream(f1); while (in.available() > 0) { out.write(in.read()); } in.close(); out.closeEntry(); out.putNextEntry(new ZipEntry("win.ini")); in = new FileInputStream(f2); while (in.available() > 0) { out.write(in.read()); } in.close(); out.closeEntry(); out.close(); }
public String encodePassword(String password, byte[] salt) throws Exception { if (salt == null) { salt = new byte[12]; secureRandom.nextBytes(salt); } MessageDigest md = MessageDigest.getInstance("MD5"); md.update(salt); md.update(password.getBytes("UTF8")); byte[] digest = md.digest(); byte[] storedPassword = new byte[digest.length + 12]; System.arraycopy(salt, 0, storedPassword, 0, 12); System.arraycopy(digest, 0, storedPassword, 12, digest.length); return new String(Base64.encode(storedPassword)); }
false
589
19,748,972
18,840,586
public String sendSMS(String host, String port, String username, String password, String from, String to, String text, String uhd, String charset, String coding, String validity, String deferred, String dlrmask, String dlrurl, String pid, String mclass, String mwi) throws SMSPushRequestException, Exception { StringBuffer res = new StringBuffer(); if (!Utils.checkNonEmptyStringAttribute(coding) || coding.equals("0")) text = Utils.convertTextForGSMEncodingURLEncoded(text); else if (coding.equals("1")) text = Utils.convertTextForUTFEncodingURLEncoded(text, "UTF-8"); else text = Utils.convertTextForUTFEncodingURLEncoded(text, "UCS-2"); String directives = "username=" + username; directives += "&password=" + password; directives += "&from=" + URLEncoder.encode(from, "UTF-8"); directives += "&to=" + to; directives += "&text=" + text; if (Utils.checkNonEmptyStringAttribute(uhd)) directives += "&uhd=" + uhd; if (Utils.checkNonEmptyStringAttribute(charset)) directives += "&charset=" + charset; if (Utils.checkNonEmptyStringAttribute(coding)) directives += "&coding=" + coding; if (Utils.checkNonEmptyStringAttribute(validity)) directives += "&validity=" + validity; if (Utils.checkNonEmptyStringAttribute(deferred)) directives += "&deferred=" + deferred; if (Utils.checkNonEmptyStringAttribute(dlrmask)) directives += "&dlrmask=" + dlrmask; if (Utils.checkNonEmptyStringAttribute(dlrurl)) directives += "&dlrurl=" + dlrurl; if (Utils.checkNonEmptyStringAttribute(pid)) directives += "&pid=" + pid; if (Utils.checkNonEmptyStringAttribute(mclass)) directives += "&mclass=" + mclass; if (Utils.checkNonEmptyStringAttribute(mwi)) directives += "&mwi=" + mwi; URL url = new URL("http://" + host + ":" + port + "/cgi-bin/sendsms?" + directives); URLConnection conn = url.openConnection(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String response; while ((response = rd.readLine()) != null) res.append(response); rd.close(); String resultCode = res.substring(0, res.indexOf(":")); if (!resultCode.equals(SMS_PUSH_RESPONSE_SUCCESS_CODE)) throw new SMSPushRequestException(resultCode); return res.toString(); }
public static String encodeString(String encodeType, String str) { if (encodeType.equals("md5of16")) { MD5 m = new MD5(); return m.getMD5ofStr16(str); } else if (encodeType.equals("md5of32")) { MD5 m = new MD5(); return m.getMD5ofStr(str); } else { try { MessageDigest gv = MessageDigest.getInstance(encodeType); gv.update(str.getBytes()); return new BASE64Encoder().encode(gv.digest()); } catch (java.security.NoSuchAlgorithmException e) { logger.error("BASE64加密失败", e); return null; } } }
false
590
2,210,894
332,635
protected int doExecuteInsert(PreparedStatement statement, Table data) throws SQLException { ResultSet rs = null; int result = -1; try { lastError = null; result = statement.executeUpdate(); if (!isAutoCommit()) connection.commit(); rs = statement.getGeneratedKeys(); while (rs.next()) { FieldUtils.setValue(data, data.key, rs.getObject(1)); } } catch (SQLException ex) { if (!isAutoCommit()) { lastError = ex; connection.rollback(); LogUtils.log(Level.SEVERE, "Transaction is being rollback. Error: " + ex.toString()); } else { throw ex; } } finally { if (statement != null) statement.close(); if (rs != null) rs.close(); } return result; }
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!"); }
false
591
2,964,000
13,422,847
private void addConfigurationResource(final String fileName, final boolean ensureLoaded) { try { final ClassLoader cl = this.getClass().getClassLoader(); final Properties p = new Properties(); final URL url = cl.getResource(fileName); if (url == null) { throw new NakedObjectRuntimeException("Failed to load configuration resource: " + fileName); } p.load(url.openStream()); configuration.add(p); } catch (Exception e) { if (ensureLoaded) { throw new NakedObjectRuntimeException(e); } LOG.debug("Resource: " + fileName + " not found, but not needed"); } }
private void createTree(DefaultMutableTreeNode top) throws MalformedURLException, ParserConfigurationException, SAXException, IOException { InputStream stream; URL url = new URL(SHIPS_URL + view.getBaseurl()); try { stream = url.openStream(); } catch (Exception e) { stream = getClass().getResourceAsStream("ships.xml"); } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document doc = parser.parse(stream); NodeList races = doc.getElementsByTagName("race"); for (int i = 0; i < races.getLength(); i++) { Element race = (Element) races.item(i); top.add(buildRaceTree(race)); } top.setUserObject("Ships"); view.getShipTree().repaint(); view.getShipTree().expandRow(0); }
false
592
6,622,146
14,636,645
public Object[] bubblesort(Object[] tosort) { Boolean sorting; int upperlimit = tosort.length - 1; do { sorting = false; for (int s0 = 0; s0 < upperlimit; s0++) { if (tosort[s0].toString().compareTo(tosort[s0 + 1].toString()) < 0) { } else if (tosort[s0].toString().compareTo(tosort[s0 + 1].toString()) == 0) { Object[] tosortnew = new Object[tosort.length - 1]; for (int tmp = 0; tmp < s0; tmp++) { tosortnew[tmp] = tosort[tmp]; } for (int tmp = s0; tmp < tosortnew.length; tmp++) { tosortnew[tmp] = tosort[tmp + 1]; } tosort = tosortnew; upperlimit = upperlimit - 1; s0 = s0 - 1; } else if (tosort[s0].toString().compareTo(tosort[s0 + 1].toString()) > 0) { String swap = (String) tosort[s0]; tosort[s0] = tosort[s0 + 1]; tosort[s0 + 1] = swap; sorting = true; } } upperlimit = upperlimit - 1; } while (sorting); return tosort; }
private static void loadQueryProcessorFactories() { qpFactoryMap = new HashMap<String, QueryProcessorFactoryIF>(); Enumeration<URL> resources = null; try { resources = QueryUtils.class.getClassLoader().getResources(RESOURCE_STRING); } catch (IOException e) { log.error("Error while trying to look for " + "QueryProcessorFactoryIF implementations.", e); } while (resources != null && resources.hasMoreElements()) { URL url = resources.nextElement(); InputStream is = null; try { is = url.openStream(); } catch (IOException e) { log.warn("Error opening stream to QueryProcessorFactoryIF service description.", e); } if (is != null) { BufferedReader rdr = new BufferedReader(new InputStreamReader(is)); String line; try { while ((line = rdr.readLine()) != null) { try { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Class<?> c = Class.forName(line, true, classLoader); if (QueryProcessorFactoryIF.class.isAssignableFrom(c)) { QueryProcessorFactoryIF factory = (QueryProcessorFactoryIF) c.newInstance(); qpFactoryMap.put(factory.getQueryLanguage().toUpperCase(), factory); } else { log.warn("Wrong entry for QueryProcessorFactoryIF service " + "description, '" + line + "' is not implementing the " + "correct interface."); } } catch (Exception e) { log.warn("Could not create an instance for " + "QueryProcessorFactoryIF service '" + line + "'."); } } } catch (IOException e) { log.warn("Could not read from QueryProcessorFactoryIF " + "service descriptor.", e); } } } if (!qpFactoryMap.containsKey(DEFAULT_LANGUAGE)) { qpFactoryMap.put(DEFAULT_LANGUAGE, new TologQueryProcessorFactory()); } }
false
593
23,677,114
17,891,162
public static void copyFile1(File srcFile, File destFile) throws IOException { if(!destFile.exists()) { destFile.createNewFile(); } FileInputStream fis = new FileInputStream(srcFile); FileOutputStream fos = new FileOutputStream(destFile); FileChannel source = fis.getChannel(); FileChannel destination = fos.getChannel(); destination.transferFrom(source, 0, source.size()); source.close(); destination.close(); fis.close(); fos.close(); }
public void testAllowClosingInputStreamTwice() throws IOException { OutputStream outputStream = fileSystem.createOutputStream(_("hello"), OutputMode.OVERWRITE); outputStream.write(new byte[] { 1, 2, 3 }); outputStream.close(); InputStream inputStream = fileSystem.createInputStream(_("hello")); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); IOUtils.copy(inputStream, buffer); inputStream.close(); inputStream.close(); }
true
594
3,452,556
17,097,179
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { Git git = Git.getCurrent(req.getSession()); GitComponentReader gitReader = git.getComponentReader("warpinjector"); String id = req.getParameter("id"); GitElement element = gitReader.getElement(id); String path = (String) element.getAttribute("targetdir"); File folder = new File(path); PrintWriter out = helper.getPrintWriter(resp); MessageBundle messageBundle = new MessageBundle("net.sf.warpcore.cms/servlets/InjectorServletMessages"); Locale locale = req.getLocale(); helper.header(out, messageBundle, locale); if (git.getUser() == null) { helper.notLoggedIn(out, messageBundle, locale); } else { try { MultiPartRequest request = new MultiPartRequest(req); FileInfo info = request.getFileInfo("userfile"); File file = info.getFile(); out.println("tempfile found: " + file.getPath() + "<br>"); String fileName = info.getFileName(); File target = new File(folder, fileName); out.println("copying tempfile to: " + target.getPath() + "<br>"); FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(target); byte buf[] = new byte[1024]; int n; while ((n = fis.read(buf)) > 0) fos.write(buf, 0, n); fis.close(); fos.close(); out.println("copy successful - deleting old tempfile<br>"); out.println("deletion result. " + file.delete() + "<p>"); out.println(messageBundle.getMessage("Done. The file {0} has been uploaded", new String[] { "'" + fileName + "'" }, locale)); out.println("<p><a href=\"" + req.getRequestURI() + "?id=" + req.getParameter("id") + "\">" + messageBundle.getMessage("Click here to import another file.", locale) + "</a>"); } catch (Exception ex) { out.println(messageBundle.getMessage("An error occured: {0}", new String[] { ex.getMessage() }, locale)); } } helper.footer(out); }
public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
true
595
14,377,058
8,597,004
public String process(URL url) throws IOException { String line, results = ""; InputStream is = url.openStream(); BufferedReader dis = new BufferedReader(new InputStreamReader(is)); while ((line = dis.readLine()) != null) { results += line + "\n"; } System.out.println(results); return results; }
public String getHtmlSource(String url) { StringBuffer codeBuffer = null; BufferedReader in = null; URLConnection uc = null; try { uc = new URL(url).openConnection(); uc.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)"); in = new BufferedReader(new InputStreamReader(uc.getInputStream(), "utf-8")); codeBuffer = new StringBuffer(); String tempCode = ""; while ((tempCode = in.readLine()) != null) { codeBuffer.append(tempCode).append("\n"); } in.close(); tempCode = null; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (null != in) in = null; if (null != uc) uc = null; } return codeBuffer.toString(); }
true
596
1,042,184
1,429,497
public static String scramble(String text) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(text.getBytes("UTF-8")); StringBuffer sb = new StringBuffer(); for (byte b : md.digest()) sb.append(Integer.toString(b & 0xFF, 16)); return sb.toString(); } catch (UnsupportedEncodingException e) { return null; } catch (NoSuchAlgorithmException e) { return null; } }
private Scanner getUrlScanner(String strUrl) { URL urlParticipants = null; Scanner scannerParticipants; try { urlParticipants = new URL(strUrl); URLConnection connParticipants; if (StringUtils.isBlank(this.configProxyIp)) { connParticipants = urlParticipants.openConnection(); } else { SocketAddress address = new InetSocketAddress(this.configProxyIp, this.configProxyPort); Proxy proxy = new Proxy(Proxy.Type.HTTP, address); connParticipants = urlParticipants.openConnection(proxy); } InputStream streamParticipant = connParticipants.getInputStream(); String charSet = StringUtils.substringAfterLast(connParticipants.getContentType(), "charset="); scannerParticipants = new Scanner(streamParticipant, charSet); } catch (MalformedURLException e) { throw new IcehorsetoolsRuntimeException(MessageFormat.format(Lang.get(this.getClass(), "MalformedURLException"), new Object[] { urlParticipants.toString() })); } catch (IOException e) { throw new IcehorsetoolsRuntimeException(MessageFormat.format(Lang.get(this.getClass(), "IOException"), new Object[] { urlParticipants.toString() })); } return scannerParticipants; }
false
597
21,868,018
17,857,284
public void process() throws Exception { String searchXML = FileUtils.readFileToString(new File(getSearchRequestRelativeFilePath())); Map<String, String> parametersMap = new HashMap<String, String>(); parametersMap.put("searchXML", searchXML); String proxyHost = null; int proxyPort = -1; String serverUserName = null; String serverUserPassword = null; FileOutputStream fos = null; if (getUseProxy()) { serverUserName = getServerUserName(); serverUserPassword = getServerUserPassword(); } if (getUseProxy()) { proxyHost = getProxyHost(); proxyPort = getProxyPort(); } try { InputStream responseInputStream = URLUtils.getHttpResponse(getSearchBaseURL(), serverUserName, serverUserPassword, URLUtils.HTTP_POST_METHOD, proxyHost, proxyPort, parametersMap, -1); fos = new FileOutputStream(getSearchResponseRelativeFilePath()); IOUtils.copyLarge(responseInputStream, fos); } finally { if (null != fos) { fos.flush(); fos.close(); } } }
public static void copyFile(File source, File destination) throws IOException { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
true
598
20,499,484
346,058
private static byte[] getLoginHashSHA(final char[] password, final int seed) throws GGException { try { final MessageDigest hash = MessageDigest.getInstance("SHA1"); hash.update(new String(password).getBytes()); hash.update(GGUtils.intToByte(seed)); return hash.digest(); } catch (final NoSuchAlgorithmException e) { LOG.error("SHA1 algorithm not usable", e); throw new GGException("SHA1 algorithm not usable!", e); } }
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!"); }
false
599
12,115,248
1,109,960
public void actionPerformed(ActionEvent evt) { try { File tempFile = new File("/tmp/controler.xml"); File f = new File("/tmp/controler-temp.xml"); BufferedInputStream copySource = new BufferedInputStream(new FileInputStream(tempFile)); BufferedOutputStream copyDestination = new BufferedOutputStream(new FileOutputStream(f)); int read = 0; while (read != -1) { read = copySource.read(buffer, 0, BUFFER_SIZE); if (read != -1) { copyDestination.write(buffer, 0, read); } } copyDestination.write(new String("</log>\n").getBytes()); copySource.close(); copyDestination.close(); XMLParser parser = new XMLParser("Controler"); parser.parse(f); f.delete(); } catch (IOException ex) { System.out.println("An error occured during the file copy!"); } }
public void run() { logger.info("downloading '" + url.toString() + "' to: " + dstFile.getAbsolutePath()); Preferences prefs = Preferences.userRoot().node("gvsig.downloader"); int timeout = prefs.getInt("timeout", 60000); DataOutputStream dos; try { DataInputStream is; OutputStreamWriter os = null; HttpURLConnection connection = null; if (url.getProtocol().equals("https")) { disableHttsValidation(); } connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(timeout); if (data != null) { connection.setRequestProperty("SOAPAction", "post"); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "text/xml; charset=UTF-8"); os = new OutputStreamWriter(connection.getOutputStream()); os.write(data); os.flush(); is = new DataInputStream(connection.getInputStream()); } else { is = new DataInputStream(url.openStream()); } dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dstFile))); byte[] buffer = new byte[1024 * 4]; long readed = 0; for (int i = is.read(buffer); !Utilities.getCanceled(groupID) && i > 0; i = is.read(buffer)) { dos.write(buffer, 0, i); readed += i; } if (os != null) { os.close(); } dos.close(); is.close(); is = null; dos = null; if (Utilities.getCanceled(groupID)) { logger.warning("[RemoteServices] '" + url + "' CANCELED."); dstFile.delete(); dstFile = null; } else { Utilities.addDownloadedURL(url, dstFile.getAbsolutePath()); } } catch (Exception e) { e.printStackTrace(); Utilities.downloadException = e; } }
false