label
class label 2
classes | source_code
stringlengths 398
72.9k
|
|---|---|
00
|
Code Sample 1:
private void createJarArchive(File archiveFile, List<File> filesToBeJared, File base) throws Exception { FileOutputStream stream = new FileOutputStream(archiveFile); JarOutputStream out = new JarOutputStream(stream); for (File tobeJared : filesToBeJared) { if (tobeJared == null || !tobeJared.exists() || tobeJared.isDirectory()) continue; String entryName = tobeJared.getAbsolutePath().substring(base.getAbsolutePath().length() + 1).replace("\\", "/"); JarEntry jarEntry = new JarEntry(entryName); jarEntry.setTime(tobeJared.lastModified()); out.putNextEntry(jarEntry); FileInputStream in = new FileInputStream(tobeJared); IOUtils.copy(in, out); IOUtils.closeQuietly(in); out.closeEntry(); } out.close(); stream.close(); System.out.println("Generated file: " + archiveFile); }
Code Sample 2:
public void PutFile(ClientConnector cc, Map<String, String> attributes) throws Exception { String destinationNode = attributes.get("dest_name"); String destinationUser = attributes.get("dest_user"); String destinationPassword = attributes.get("dest_password"); String destinationFile = attributes.get("dest_file"); String messageID = attributes.get("messageID"); String destinationFileType = attributes.get("dest_file_type"); Integer destinationPort = 21; String destinationPortString = attributes.get("dest_port"); if ((destinationPortString != null) && (destinationPortString.equals(""))) { try { destinationPort = Integer.parseInt(destinationPortString); } catch (Exception e) { destinationPort = 21; log.debug("Destination Port \"" + destinationPortString + "\" was not valid. Using Default (21)"); } } log.info("Starting FTP push of \"" + destinationFile + "\" to \"" + destinationNode); if ((destinationUser == null) || (destinationUser.equals(""))) { List userDBVal = axt.db.GeneralDAO.getNodeValue(destinationNode, "ftpUser"); if (userDBVal.size() < 1) { destinationUser = DEFAULTUSER; } else { destinationUser = (String) userDBVal.get(0); } } if ((destinationPassword == null) || (destinationPassword.equals(""))) { List passwordDBVal = axt.db.GeneralDAO.getNodeValue(destinationNode, "ftpPassword"); if (passwordDBVal.size() < 1) { destinationPassword = DEFAULTPASSWORD; } else { destinationPassword = (String) passwordDBVal.get(0); } } log.debug("Getting Stage File ID"); String stageFile = null; try { stageFile = STAGINGDIR + "/" + axt.db.GeneralDAO.getStageFile(messageID); } catch (Exception stageException) { throw new Exception("Failed to assign a staging file \"" + stageFile + "\" - ERROR: " + stageException); } InputStream in; try { in = new FileInputStream(stageFile); } catch (FileNotFoundException fileNFException) { throw new Exception("Failed to get the staging file \"" + stageFile + "\" - ERROR: " + fileNFException); } log.debug("Sending File"); FTPClient ftp = new FTPClient(); try { log.debug("Connecting"); ftp.connect(destinationNode, destinationPort); log.debug("Checking Status"); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); throw new Exception("Failed to connect to \"" + destinationNode + "\" as user \"" + destinationUser + "\" - ERROR: " + ftp.getReplyString()); } log.debug("Logging In"); if (!ftp.login(destinationUser, destinationPassword)) { ftp.disconnect(); throw new Exception("Failed to connect to \"" + destinationNode + "\" as user \"" + destinationUser + "\" - ERROR: Login Failed"); } } catch (SocketException socketException) { throw new Exception("Failed to connect to \"" + destinationNode + "\" as user \"" + destinationUser + "\" - ERROR: " + socketException); } catch (IOException ioe) { throw new Exception("Failed to connect to \"" + destinationNode + "\" as user \"" + destinationUser + "\" - ERROR: " + ioe); } log.debug("Performing Site Commands"); Iterator siteIterator = GeneralDAO.getNodeValue(destinationNode, "ftpSite").iterator(); while (siteIterator.hasNext()) { String siteCommand = null; try { siteCommand = (String) siteIterator.next(); ftp.site(siteCommand); } catch (IOException e) { throw new Exception("FTP \"site\" command \"" + siteCommand + "\" failed - ERROR: " + e); } } if (destinationFileType != null) { if (destinationFileType.equals("A")) { log.debug("Set File Type to ASCII"); ftp.setFileType(FTP.ASCII_FILE_TYPE); } else if (destinationFileType.equals("B")) { log.debug("Set File Type to BINARY"); ftp.setFileType(FTP.BINARY_FILE_TYPE); } else if (destinationFileType.equals("E")) { log.debug("Set File Type to EBCDIC"); ftp.setFileType(FTP.EBCDIC_FILE_TYPE); } } log.debug("Pushing File"); OutputStream out = null; try { out = ftp.storeFileStream(destinationFile); if (out == null) { throw new Exception("Failed send the file \"" + destinationFile + "\" to \"" + destinationNode + "\" - ERROR: " + ftp.getReplyString()); } } catch (IOException ioe2) { log.error("Failed to push the file \"" + destinationFile + "\" to \"" + destinationNode + "\" - ERROR: " + ioe2); } DESCrypt decrypter = null; try { decrypter = new DESCrypt(); } catch (Exception cryptInitError) { log.error("Failed to initialize the encrypt process - ERROR: " + cryptInitError); } try { decrypter.decrypt(in, out); } catch (Exception cryptError) { log.error("Send Error" + cryptError); } log.debug("Logging Out"); try { out.close(); ftp.logout(); in.close(); } catch (IOException ioe3) { log.error("Failed close connection to \"" + destinationNode + "\" - ERROR: " + ioe3); } return; }
|
11
|
Code Sample 1:
public static String getMD5(String password) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); byte[] digest = md.digest(); String out = ""; for (int i = 0; i < digest.length; i++) { out += digest[i]; } return out; } catch (NoSuchAlgorithmException e) { System.err.println("Manca l'MD5 (piuttosto strano)"); } return ""; }
Code Sample 2:
public static String hash(String plainTextPwd) { MessageDigest hashAlgo; try { hashAlgo = java.security.MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new QwickException(e); } hashAlgo.update(plainTextPwd.getBytes()); return new String(hashAlgo.digest()); }
|
11
|
Code Sample 1:
public static byte[] encrypt(String x) throws NoSuchAlgorithmException { MessageDigest d = null; d = MessageDigest.getInstance("SHA-1"); d.reset(); d.update(x.getBytes()); return d.digest(); }
Code Sample 2:
@Override public String encodePassword(String rawPass, Object salt) throws DataAccessException { try { MessageDigest digest = MessageDigest.getInstance(digestAlgorithm); digest.reset(); digest.update(((String) salt).getBytes("UTF-8")); return new String(digest.digest(rawPass.getBytes("UTF-8"))); } catch (Throwable e) { throw new DataAccessException("Error al codificar la contrase�a", e) { private static final long serialVersionUID = 3880106673612870103L; }; } }
|
00
|
Code Sample 1:
public String loadFileContent(final String _resourceURI) { final Lock readLock = this.fileLock.readLock(); final Lock writeLock = this.fileLock.writeLock(); boolean hasReadLock = false; boolean hasWriteLock = false; try { readLock.lock(); hasReadLock = true; if (!this.cachedResources.containsKey(_resourceURI)) { readLock.unlock(); hasReadLock = false; writeLock.lock(); hasWriteLock = true; if (!this.cachedResources.containsKey(_resourceURI)) { final InputStream resourceAsStream = this.getClass().getResourceAsStream(_resourceURI); final StringWriter writer = new StringWriter(); try { IOUtils.copy(resourceAsStream, writer); } catch (final IOException ex) { throw new IllegalStateException("Resource not read-able", ex); } final String loadedResource = writer.toString(); this.cachedResources.put(_resourceURI, loadedResource); } writeLock.unlock(); hasWriteLock = false; readLock.lock(); hasReadLock = true; } return this.cachedResources.get(_resourceURI); } finally { if (hasReadLock) { readLock.unlock(); } if (hasWriteLock) { writeLock.unlock(); } } }
Code Sample 2:
public static Document send(final String urlAddress) { Document responseMessage = null; try { URL url = new URL(urlAddress); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setAllowUserInteraction(false); int response = connection.getResponseCode(); if (response == HttpURLConnection.HTTP_OK) { String contentType = connection.getContentType(); if (contentType != null && contentType.startsWith("text/html")) { InputStream inputStream = connection.getInputStream(); responseMessage = XmlUtils.fromStream(inputStream); } else { responseMessage = XmlUtils.newDocument(); Element responseElement = XmlUtils.createElement(responseMessage, "rsp"); Element messageElement = XmlUtils.createElement(responseElement, "message"); messageElement.setTextContent(String.valueOf(connection.getResponseCode())); Element commentElement = XmlUtils.createElement(responseElement, "comment"); commentElement.setTextContent(contentType); } } else { responseMessage = XmlUtils.newDocument(); Element responseElement = XmlUtils.createElement(responseMessage, "rsp"); Element messageElement = XmlUtils.createElement(responseElement, "message"); messageElement.setTextContent(String.valueOf(connection.getResponseCode())); Element commentElement = XmlUtils.createElement(responseElement, "comment"); commentElement.setTextContent(connection.getResponseMessage()); } } catch (Exception e) { e.printStackTrace(); } return responseMessage; }
|
00
|
Code Sample 1:
ArrayList<String> remoteSampling(IntersectionFile[] intersectionFiles, double[][] points) { logger.info("begin REMOTE sampling, number of threads " + intersectConfig.getThreadCount() + ", number of layers=" + intersectionFiles.length + ", number of coordinates=" + points.length); ArrayList<String> output = null; try { long start = System.currentTimeMillis(); URL url = new URL(intersectConfig.getLayerIndexUrl() + "/intersect/batch"); URLConnection c = url.openConnection(); c.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(c.getOutputStream()); out.write("fids="); for (int i = 0; i < intersectionFiles.length; i++) { if (i > 0) { out.write(","); } out.write(intersectionFiles[i].getFieldId()); } out.write("&points="); for (int i = 0; i < points.length; i++) { if (i > 0) { out.write(","); } out.write(String.valueOf(points[i][0])); out.write(","); out.write(String.valueOf(points[i][1])); } out.close(); CSVReader csv = new CSVReader(new InputStreamReader(new GZIPInputStream(c.getInputStream()))); long mid = System.currentTimeMillis(); ArrayList<StringBuilder> tmpOutput = new ArrayList<StringBuilder>(); for (int i = 0; i < intersectionFiles.length; i++) { tmpOutput.add(new StringBuilder()); } String[] line; int row = 0; csv.readNext(); while ((line = csv.readNext()) != null) { for (int i = 2; i < line.length && i - 2 < tmpOutput.size(); i++) { if (row > 0) { tmpOutput.get(i - 2).append("\n"); } tmpOutput.get(i - 2).append(line[i]); } row++; } csv.close(); output = new ArrayList<String>(); for (int i = 0; i < tmpOutput.size(); i++) { output.add(tmpOutput.get(i).toString()); tmpOutput.set(i, null); } long end = System.currentTimeMillis(); logger.info("sample time for " + 5 + " layers and " + 3 + " coordinates: get response=" + (mid - start) + "ms, write response=" + (end - mid) + "ms"); } catch (Exception e) { e.printStackTrace(); } return output; }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
11
|
Code Sample 1:
@SmallTest public void testSha1() throws Exception { MessageDigest digest = MessageDigest.getInstance("SHA-1"); int numTests = mTestData.length; for (int i = 0; i < numTests; i++) { digest.update(mTestData[i].input.getBytes()); byte[] hash = digest.digest(); String encodedHash = encodeHex(hash); assertEquals(encodedHash, mTestData[i].result); } }
Code Sample 2:
public static String md5encrypt(String toEncrypt) { if (toEncrypt == null) { throw new IllegalArgumentException("null is not a valid password to encrypt"); } try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(toEncrypt.getBytes()); byte[] hash = md.digest(); return new String(dumpBytes(hash)); } catch (NoSuchAlgorithmException nsae) { return toEncrypt; } }
|
00
|
Code Sample 1:
public static String encrypt(String message) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(message.getBytes()); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(digest.digest()); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); return null; } }
Code Sample 2:
public static void copyFile(final File in, final File out) throws IOException { final FileChannel inChannel = new FileInputStream(in).getChannel(); final FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (final IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } }
|
00
|
Code Sample 1:
@Override public final boolean exists() { try { final URLConnection uc = this.url.openConnection(); uc.connect(); uc.getInputStream().close(); return true; } catch (final IOException e) { return false; } }
Code Sample 2:
public boolean backupFile(File oldFile, File newFile) { boolean isBkupFileOK = false; FileChannel sourceChannel = null; FileChannel targetChannel = null; try { sourceChannel = new FileInputStream(oldFile).getChannel(); targetChannel = new FileOutputStream(newFile).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); } catch (IOException e) { logger.log(Level.SEVERE, "IO exception occurred while copying config file", e); } finally { if ((newFile != null) && (newFile.exists()) && (newFile.length() > 0)) { isBkupFileOK = true; } try { if (sourceChannel != null) { sourceChannel.close(); } if (targetChannel != null) { targetChannel.close(); } } catch (IOException e) { logger.log(Level.INFO, "closing channels failed"); } } return isBkupFileOK; }
|
00
|
Code Sample 1:
public void doActionOn(TomcatProject prj) throws Exception { String path = TomcatLauncherPlugin.getDefault().getManagerAppUrl(); try { path += "/reload?path=" + prj.getWebPath(); URL url = new URL(path); Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { String user = TomcatLauncherPlugin.getDefault().getManagerAppUser(); String password = TomcatLauncherPlugin.getDefault().getManagerAppPassword(); return new PasswordAuthentication(user, password.toCharArray()); } }); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.getContent(); connection.disconnect(); Authenticator.setDefault(null); } catch (Exception e) { throw new Exception("The following url was used : \n" + path + "\n\nCheck manager app settings (username and password)\n\n"); } }
Code Sample 2:
public boolean loadResource(String resourcePath) { try { URL url = Thread.currentThread().getContextClassLoader().getResource(resourcePath); if (url == null) { logger.error("Cannot find the resource named: '" + resourcePath + "'. Failed to load the keyword list."); return false; } InputStreamReader isr = new InputStreamReader(url.openStream()); BufferedReader br = new BufferedReader(isr); String ligne = br.readLine(); while (ligne != null) { if (!contains(ligne.toUpperCase())) addLast(ligne.toUpperCase()); ligne = br.readLine(); } return true; } catch (IOException ioe) { logger.log(Level.ERROR, "Cannot load default SQL keywords file.", ioe); } return false; }
|
00
|
Code Sample 1:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String servletPath = req.getServletPath(); String requestURI = req.getRequestURI(); String resource = requestURI.substring(requestURI.indexOf(servletPath) + servletPath.length()); URL url = ClassResource.get(resourceDirectory + resource); try { File file = null; JarEntry jarEntry = null; JarFile jarFile = null; if (!url.toExternalForm().startsWith("jar:")) { file = new File(url.toURI()); } else { jarFile = ((JarURLConnection) url.openConnection()).getJarFile(); String[] jarURL = url.toExternalForm().split("!"); jarEntry = jarFile.getJarEntry(jarURL[1].substring(1)); } if (file != null && file.isDirectory()) { PrintWriter writer = resp.getWriter(); resp.setContentType("text/html"); DevelUtils.writePageBegin(writer); DevelUtils.writeTitleAndHeaderEnd(writer, "Makumba resources"); if (SourceViewServlet.redirected(req, resp, servletPath)) { return; } String relativeDirectory = file.getName(); if (file.getAbsolutePath().indexOf(resourceDirectory) != -1) { relativeDirectory = file.getAbsolutePath().substring(file.getAbsolutePath().indexOf(resourceDirectory)); } SourceViewServlet.printDirlistingHeader(writer, file.getCanonicalPath(), relativeDirectory); if (!(relativeDirectory.equals(resourceDirectory))) { writer.println("<b><a href=\"../\">../</a></b> (up one level)"); } SourceViewServlet.processDirectory(writer, file, null); String[] list = file.list(); Arrays.sort(list); for (int i = 0; i < list.length; i++) { String s = list[i]; File f = new File(file.getAbsolutePath() + File.separator + s); if (f.isFile()) { writer.println("<b><a href=\"" + s + "\">" + s + "</a></b>"); } } writer.println("</pre>"); DevelUtils.writePageEnd(writer); resp.setHeader("Last-Modified", dfLastModified.format(new Date())); return; } else if (jarEntry != null && jarEntry.isDirectory()) { Enumeration<JarEntry> entries = jarFile.entries(); ArrayList<String> files = new ArrayList<String>(); ArrayList<String> directories = new ArrayList<String>(); PrintWriter writer = resp.getWriter(); resp.setContentType("text/html"); DevelUtils.writePageBegin(writer); DevelUtils.writeTitleAndHeaderEnd(writer, "Makumba resources"); if (SourceViewServlet.redirected(req, resp, servletPath)) { return; } String relativeDirectory = jarEntry.getName(); SourceViewServlet.printDirlistingHeader(writer, url.toExternalForm(), relativeDirectory); if (!relativeDirectory.equals(resourceDirectory) && !relativeDirectory.equals(resourceDirectory + "/")) { writer.println("<b><a href=\"../\">../</a></b> (up one level)"); } while (entries.hasMoreElements()) { JarEntry entry = (JarEntry) entries.nextElement(); if (entry.getName().startsWith(relativeDirectory)) { String s = entry.getName().substring(relativeDirectory.length()); while (s.length() > 0 && s.startsWith("/")) { s = s.substring(1); } if (s.indexOf("/") == -1) { if (s.length() > 0) { files.add(s); } } else if (s.indexOf("/") == s.lastIndexOf("/") && s.endsWith("/")) { if (s.endsWith("/")) { s = s.substring(0, s.length() - 1); } if (s.length() > 0) { directories.add(s); } } } } for (String string : directories) { writer.println("<b><a href=\"" + string + "/\">" + string + "/</a></b>"); } for (String string : files) { writer.println("<b><a href=\"" + string + "\">" + string + "</a></b>"); } writer.println("</pre>"); DevelUtils.writePageEnd(writer); resp.setHeader("Last-Modified", dfLastModified.format(new Date())); return; } else { final Date lastModified; if (url.toExternalForm().startsWith("jar:")) { JarFile jf = ((JarURLConnection) url.openConnection()).getJarFile(); String[] jarURL = url.toExternalForm().split("!"); lastModified = new Date(jf.getJarEntry(jarURL[1].substring(1)).getTime()); } else { lastModified = new Date(new File(url.toURI()).lastModified()); } resp.setHeader("Last-Modified", dfLastModified.format(lastModified)); resp.setContentType(getContentType(url)); Object cachedResource = NamedResources.getStaticCache(makumbaResources).getResource(resource); ServletOutputStream outputStream = resp.getOutputStream(); if (isBinary(url)) { for (int i = 0; i < ((byte[]) cachedResource).length; i++) { outputStream.write(((byte[]) cachedResource)[i]); } } else { outputStream.print(cachedResource.toString()); } } } catch (URISyntaxException e) { e.printStackTrace(); } }
Code Sample 2:
public void run() { try { File inf = new File(dest); if (!inf.exists()) { inf.getParentFile().mkdirs(); } FileChannel in = new FileInputStream(src).getChannel(); FileChannel out = new FileOutputStream(dest).getChannel(); out.transferFrom(in, 0, in.size()); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); System.err.println("Error copying file \n" + src + "\n" + dest); } }
|
00
|
Code Sample 1:
public static void parse(URL url, ContentHandler handler) { InputStream input = null; try { input = url.openStream(); SAXParser parser = createSaxParser(); XMLReader reader = parser.getXMLReader(); reader.setContentHandler(handler); reader.parse(new InputSource(input)); } catch (SAXException e) { throw new XmlException("Could not parse xml", e); } catch (IOException e) { throw new XmlException("Could not parse xml", e); } finally { if (input != null) { try { input.close(); } catch (IOException e) { } } } }
Code Sample 2:
public static void extract(final File destDir, final ZipInfo zipInfo, final IProgressMonitor monitor) throws IOException { if (!destDir.exists()) destDir.mkdirs(); for (String key : zipInfo.getEntryKeys()) { ZipEntry entry = zipInfo.getEntry(key); InputStream in = zipInfo.getInputStream(entry); File entryDest = new File(destDir, entry.getName()); entryDest.getParentFile().mkdirs(); if (!entry.isDirectory()) { OutputStream out = new FileOutputStream(new File(destDir, entry.getName())); try { IOUtils.copy(in, out); out.flush(); if (monitor != null) monitor.worked(1); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } } if (monitor != null) monitor.done(); }
|
00
|
Code Sample 1:
private boolean verifyAppId(String appid) { try { String urlstr = "http://" + appid + ".appspot.com"; URL url = new URL(urlstr); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buf = new StringBuffer(); String line; while ((line = reader.readLine()) != null) { buf.append(line); } reader.close(); return buf.toString().contains("hyk-proxy"); } catch (Exception e) { } return false; }
Code Sample 2:
private static void copyFile(String srFile, String dtFile) { try { File f1 = new File(srFile); File f2 = new File(dtFile); InputStream in = new FileInputStream(f1); OutputStream out = new FileOutputStream(f2); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); } catch (FileNotFoundException ex) { System.out.println("Error copying " + srFile + " to " + dtFile); System.out.println(ex.getMessage() + " in the specified directory."); } catch (IOException e) { System.out.println(e.getMessage()); } }
|
00
|
Code Sample 1:
private HttpURLConnection connect() throws MalformedURLException, IOException { HttpURLConnection connection = null; if (repositoryLocation == null) { Utils.debug("RemoteRepository", "repository Location unspecified"); return null; } URL url = new URL(repositoryLocation); connection = (HttpURLConnection) url.openConnection(); return connection; }
Code Sample 2:
public static void copy(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws IOException { InputStream input = (InputStream) ((NativeJavaObject) args[0]).unwrap(); OutputStream output = (OutputStream) ((NativeJavaObject) args[1]).unwrap(); IOUtils.copy(input, output); }
|
11
|
Code Sample 1:
private Map<String, DomAttr> getAttributesFor(final BaseFrame frame) throws IOException { final Map<String, DomAttr> map = createAttributesCopyWithClonedAttribute(frame, "src"); final DomAttr srcAttr = map.get("src"); if (srcAttr == null) { return map; } final Page enclosedPage = frame.getEnclosedPage(); final String suffix = getFileExtension(enclosedPage); final File file = createFile(srcAttr.getValue(), "." + suffix); if (enclosedPage instanceof HtmlPage) { file.delete(); ((HtmlPage) enclosedPage).save(file); } else { final InputStream is = enclosedPage.getWebResponse().getContentAsStream(); final FileOutputStream fos = new FileOutputStream(file); IOUtils.copyLarge(is, fos); IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } srcAttr.setValue(file.getParentFile().getName() + FILE_SEPARATOR + file.getName()); return map; }
Code Sample 2:
public void visit(BosMember member) throws BosException { String relative = AddressingUtil.getRelativePath(member.getDataSourceUri(), baseUri); URL resultUrl; try { resultUrl = new URL(outputUrl, relative); File resultFile = new File(resultUrl.toURI()); resultFile.getParentFile().mkdirs(); log.info("Creating result file \"" + resultFile.getAbsolutePath() + "\"..."); IOUtils.copy(member.getInputStream(), new FileOutputStream(resultFile)); } catch (Exception e) { throw new BosException(e); } }
|
00
|
Code Sample 1:
public static String Sha1(String s) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] hash = new byte[40]; md.update(s.getBytes("iso-8859-1"), 0, s.length()); hash = md.digest(); return toHex(hash); } catch (Exception e) { e.printStackTrace(); return null; } }
Code Sample 2:
public static boolean isODF(URL url) throws IOException { InputStream resStream = ODFUtil.findDataInputStream(url.openStream(), ODFUtil.MIMETYPE_FILE); if (null == resStream) { LOG.debug("mimetype stream not found in ODF package"); return false; } String mimetypeContent = IOUtils.toString(resStream); return mimetypeContent.startsWith(ODFUtil.MIMETYPE_START); }
|
00
|
Code Sample 1:
public static String recoverPassword(String token) { try { token = encryptGeneral1(token); String data = URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode(token, "UTF-8"); URL url = new URL("https://mypasswords-server.appspot.com/recover_password"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder finalResult = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { finalResult.append(line); } wr.close(); rd.close(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(new InputSource(new StringReader(finalResult.toString()))); document.normalizeDocument(); Element root = document.getDocumentElement(); String password = root.getTextContent(); password = decryptGeneral1(password); return password; } catch (Exception e) { System.out.println(e.getMessage()); } return null; }
Code Sample 2:
public static void writeToFile(final File file, final InputStream in) throws IOException { IOUtils.createFile(file); FileOutputStream fos = null; try { fos = new FileOutputStream(file); IOUtils.copyStream(in, fos); } finally { IOUtils.closeIO(fos); } }
|
00
|
Code Sample 1:
public void testSnapPullWithMasterUrl() throws Exception { copyFile(new File(CONF_DIR + "solrconfig-slave1.xml"), new File(slave.getConfDir(), "solrconfig.xml")); slaveJetty.stop(); slaveJetty = createJetty(slave); slaveClient = createNewSolrServer(slaveJetty.getLocalPort()); for (int i = 0; i < 500; i++) index(masterClient, "id", i, "name", "name = " + i); masterClient.commit(); NamedList masterQueryRsp = query("*:*", masterClient); SolrDocumentList masterQueryResult = (SolrDocumentList) masterQueryRsp.get("response"); assertEquals(500, masterQueryResult.getNumFound()); String masterUrl = "http://localhost:" + slaveJetty.getLocalPort() + "/solr/replication?command=fetchindex&masterUrl="; masterUrl += "http://localhost:" + masterJetty.getLocalPort() + "/solr/replication"; URL url = new URL(masterUrl); InputStream stream = url.openStream(); try { stream.close(); } catch (IOException e) { } Thread.sleep(3000); NamedList slaveQueryRsp = query("*:*", slaveClient); SolrDocumentList slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response"); assertEquals(500, slaveQueryResult.getNumFound()); String cmp = TestDistributedSearch.compare(masterQueryResult, slaveQueryResult, 0, null); assertEquals(null, cmp); }
Code Sample 2:
public static String getMD5Str(String source) { String s = null; char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; try { java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); md.update(source.getBytes()); byte tmp[] = md.digest(); char str[] = new char[16 * 2]; int k = 0; for (int i = 0; i < 16; i++) { byte byte0 = tmp[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } s = new String(str); } catch (Exception e) { e.printStackTrace(); } return s; }
|
11
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
public ODFSignatureService(TimeStampServiceValidator timeStampServiceValidator, RevocationDataService revocationDataService, SignatureFacet signatureFacet, InputStream documentInputStream, OutputStream documentOutputStream, TimeStampService timeStampService, String role, IdentityDTO identity, byte[] photo, DigestAlgo digestAlgo) throws Exception { super(digestAlgo); this.temporaryDataStorage = new HttpSessionTemporaryDataStorage(); this.documentOutputStream = documentOutputStream; this.tmpFile = File.createTempFile("eid-dss-", ".odf"); FileOutputStream fileOutputStream; fileOutputStream = new FileOutputStream(this.tmpFile); IOUtils.copy(documentInputStream, fileOutputStream); addSignatureFacet(new XAdESXLSignatureFacet(timeStampService, revocationDataService, getSignatureDigestAlgorithm())); addSignatureFacet(signatureFacet); XAdESSignatureFacet xadesSignatureFacet = super.getXAdESSignatureFacet(); xadesSignatureFacet.setRole(role); if (null != identity) { IdentitySignatureFacet identitySignatureFacet = new IdentitySignatureFacet(identity, photo, getSignatureDigestAlgorithm()); addSignatureFacet(identitySignatureFacet); } }
|
11
|
Code Sample 1:
public void testCreateNewXMLFile() throws InvalidNodeTypeDefException, ParseException, Exception { JCRNodeSource emptySource = loadTestSource(); assertEquals(false, emptySource.exists()); OutputStream sourceOut = emptySource.getOutputStream(); assertNotNull(sourceOut); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } InputStream expected = getClass().getResourceAsStream(CONTENT_FILE); JCRNodeSource persistentSource = loadTestSource(); assertEquals(true, persistentSource.exists()); InputStream actual = persistentSource.getInputStream(); try { assertTrue(isXmlEqual(expected, actual)); } finally { expected.close(); actual.close(); } JCRNodeSource tmpSrc = (JCRNodeSource) resolveSource(BASE_URL + "users/alexander.saar"); persistentSource.delete(); tmpSrc.delete(); }
Code Sample 2:
private static void copy(File source, File dest) throws FileNotFoundException, IOException { FileInputStream input = new FileInputStream(source); FileOutputStream output = new FileOutputStream(dest); System.out.println("Copying " + source + " to " + dest); IOUtils.copy(input, output); output.close(); input.close(); dest.setLastModified(source.lastModified()); }
|
00
|
Code Sample 1:
public void setFlag(Flags.Flag oFlg, boolean bFlg) throws MessagingException { String sColunm; super.setFlag(oFlg, bFlg); if (oFlg.equals(Flags.Flag.ANSWERED)) sColunm = DB.bo_answered; else if (oFlg.equals(Flags.Flag.DELETED)) sColunm = DB.bo_deleted; else if (oFlg.equals(Flags.Flag.DRAFT)) sColunm = DB.bo_draft; else if (oFlg.equals(Flags.Flag.FLAGGED)) sColunm = DB.bo_flagged; else if (oFlg.equals(Flags.Flag.RECENT)) sColunm = DB.bo_recent; else if (oFlg.equals(Flags.Flag.SEEN)) sColunm = DB.bo_seen; else sColunm = null; if (null != sColunm && oFolder instanceof DBFolder) { JDCConnection oConn = null; PreparedStatement oUpdt = null; try { oConn = ((DBFolder) oFolder).getConnection(); String sSQL = "UPDATE " + DB.k_mime_msgs + " SET " + sColunm + "=" + (bFlg ? "1" : "0") + " WHERE " + DB.gu_mimemsg + "='" + getMessageGuid() + "'"; if (DebugFile.trace) DebugFile.writeln("Connection.prepareStatement(" + sSQL + ")"); oUpdt = oConn.prepareStatement(sSQL); oUpdt.executeUpdate(); oUpdt.close(); oUpdt = null; oConn.commit(); oConn = null; } catch (SQLException e) { if (null != oConn) { try { oConn.rollback(); } catch (Exception ignore) { } } if (null != oUpdt) { try { oUpdt.close(); } catch (Exception ignore) { } } if (DebugFile.trace) DebugFile.decIdent(); throw new MessagingException(e.getMessage(), e); } } }
Code Sample 2:
private void constructDialogContent(Composite parent) { SashForm splitter = new SashForm(parent, SWT.HORIZONTAL); splitter.setLayoutData(new GridData(GridData.FILL_BOTH)); Group fragmentsGroup = new Group(splitter, SWT.NONE); fragmentsGroup.setLayout(new GridLayout(1, false)); fragmentsGroup.setText("Result Fragments"); fragmentsTable = CheckboxTableViewer.newCheckList(fragmentsGroup, SWT.NONE); fragmentsTable.getTable().setLayoutData(new GridData(GridData.FILL_BOTH)); fragmentsTable.setContentProvider(new ArrayContentProvider()); fragmentsTable.setLabelProvider(new LabelProvider() { public Image getImage(Object element) { return JFaceResources.getImage(WsmoImageRegistry.INSTANCE_ICON); } public String getText(Object element) { if (element == null) { return ""; } if (element instanceof ProcessFragment) { ProcessFragment frag = (ProcessFragment) element; String label = (frag.getName() == null) ? " <no-fragment-name>" : frag.getName(); if (frag.getDescription() != null) { label += " [" + Utils.normalizeSpaces(frag.getDescription()) + ']'; } return label; } return element.toString(); } }); fragmentsTable.setInput(results.toArray()); final MenuManager menuMgr = new MenuManager(); menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager mgr) { if (false == GUIHelper.containsCursor(fragmentsTable.getTable())) { return; } if (false == fragmentsTable.getSelection().isEmpty()) { menuMgr.add(new Action("Edit Name") { public void run() { doEditName(); } }); menuMgr.add(new Action("Edit Description") { public void run() { doEditDescription(); } }); menuMgr.add(new Separator()); } menuMgr.add(new Action("Select All") { public void run() { fragmentsTable.setAllChecked(true); updateSelectionMonitor(); } }); menuMgr.add(new Separator()); menuMgr.add(new Action("Unselect All") { public void run() { fragmentsTable.setAllChecked(false); updateSelectionMonitor(); } }); } }); fragmentsTable.getTable().setMenu(menuMgr.createContextMenu(fragmentsTable.getTable())); fragmentsTable.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { updatePreviewPanel((IStructuredSelection) event.getSelection()); } }); new FragmentsToolTipProvider(this.fragmentsTable.getTable()); Group previewGroup = new Group(splitter, SWT.NONE); previewGroup.setLayout(new GridLayout(1, false)); previewGroup.setText("Fragment Preview"); createZoomToolbar(previewGroup); previewArea = new Composite(previewGroup, SWT.BORDER); previewArea.setLayoutData(new GridData(GridData.FILL_BOTH)); previewArea.setLayout(new GridLayout(1, false)); viewer = new ScrollingGraphicalViewer(); viewer.createControl(previewArea); ScalableFreeformRootEditPart rootEditPart = new ScalableFreeformRootEditPart(); viewer.setRootEditPart(rootEditPart); viewer.setEditPartFactory(new GraphicalPartFactory()); viewer.getControl().setBackground(ColorConstants.listBackground); viewer.getControl().setLayoutData(new GridData(GridData.FILL_BOTH)); ZoomManager zoomManager = rootEditPart.getZoomManager(); ArrayList<String> zoomContributions = new ArrayList<String>(); zoomContributions.add(ZoomManager.FIT_ALL); zoomContributions.add(ZoomManager.FIT_HEIGHT); zoomContributions.add(ZoomManager.FIT_WIDTH); zoomManager.setZoomLevelContributions(zoomContributions); zoomManager.setZoomLevels(new double[] { 0.25, 0.33, 0.5, 0.75, 1.0 }); zoomManager.setZoom(1.0); Composite businessGoalPanel = new Composite(previewGroup, SWT.NONE); businessGoalPanel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); businessGoalPanel.setLayout(new GridLayout(4, false)); Label lab = new Label(businessGoalPanel, SWT.NONE); lab.setText("Process goal:"); bpgIRI = new Text(businessGoalPanel, SWT.BORDER | SWT.READ_ONLY); bpgIRI.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); selectBpgButton = new Button(businessGoalPanel, SWT.NONE); selectBpgButton.setText("Select"); selectBpgButton.setEnabled(false); selectBpgButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent s) { doSelectProcessGoal(); } }); clearBpgButton = new Button(businessGoalPanel, SWT.NONE); clearBpgButton.setText("Clear"); clearBpgButton.setEnabled(false); clearBpgButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent s) { IStructuredSelection sel = (IStructuredSelection) fragmentsTable.getSelection(); if (sel.isEmpty() || false == sel.getFirstElement() instanceof ProcessFragment) { return; } ((ProcessFragment) sel.getFirstElement()).setBusinessProcessGoal(null); updatePreviewPanel(sel); } }); splitter.setWeights(new int[] { 1, 2 }); }
|
00
|
Code Sample 1:
private static String executeQueryWithXbird(String queryFile, String replace) throws XQueryException, IOException, URISyntaxException { URL url = DocumentTableTest.class.getResource(queryFile); URI uri = url.toURI(); String query = IOUtils.toString(url.openStream()); XQueryProcessor processor = new XQueryProcessor(); query = query.replace("fn:doc(\"auction.xml\")", replace); if (DEBUG_LIGHT) { System.err.println(query); } XQueryModule mod = processor.parse(query, uri); StringWriter res_sw = new StringWriter(); Serializer ser = new SAXSerializer(new SAXWriter(res_sw), res_sw); processor.execute(mod, ser); String result = res_sw.toString(); return result; }
Code Sample 2:
public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
|
00
|
Code Sample 1:
public static String CreateHash(String s) { String str = s.toString(); if (str == null || str.length() == 0) { throw new IllegalArgumentException("String cannot be null or empty"); } StringBuffer hexString = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] hash = md.digest(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) { hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); } else { hexString.append(Integer.toHexString(0xFF & hash[i])); } } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return (hexString.toString()); }
Code Sample 2:
public void deployDir(File srcDir, String destDir) { File[] dirFiles = srcDir.listFiles(); for (int k = 0; dirFiles != null && k < dirFiles.length; k++) { if (!dirFiles[k].getName().startsWith(".")) { if (dirFiles[k].isFile()) { File deployFile = new File(destDir + File.separator + dirFiles[k].getName()); if (dirFiles[k].lastModified() != deployFile.lastModified() || dirFiles[k].length() != deployFile.length()) { IOUtils.copy(dirFiles[k], deployFile); } } else if (dirFiles[k].isDirectory()) { String newDestDir = destDir + File.separator + dirFiles[k].getName(); deployDir(dirFiles[k], newDestDir); } } } }
|
11
|
Code Sample 1:
public static String getMD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
Code Sample 2:
public static String hashString(String pwd) { StringBuffer hex = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(pwd.getBytes()); byte[] d = md.digest(); String plaintxt; for (int i = 0; i < d.length; i++) { plaintxt = Integer.toHexString(0xFF & d[i]); if (plaintxt.length() < 2) { plaintxt = "0" + plaintxt; } hex.append(plaintxt); } } catch (NoSuchAlgorithmException nsae) { } return hex.toString(); }
|
00
|
Code Sample 1:
private void addAllSpecialPages(Environment env, ZipOutputStream zipout, int progressStart, int progressLength) throws Exception, IOException { ResourceBundle messages = ResourceBundle.getBundle("ApplicationResources", locale); String tpl; int count = 0; int numberOfSpecialPages = 7; progress = Math.min(progressStart + (int) ((double) count * (double) progressLength / numberOfSpecialPages), 99); count++; String cssContent = wb.readRaw(virtualWiki, "StyleSheet"); addZipEntry(zipout, "css/vqwiki.css", cssContent); progress = Math.min(progressStart + (int) ((double) count * (double) progressLength / numberOfSpecialPages), 99); count++; tpl = getTemplateFilledWithContent("search"); addTopicEntry(zipout, tpl, "WikiSearch", "WikiSearch.html"); progress = Math.min(progressStart + (int) ((double) count * (double) progressLength / numberOfSpecialPages), 99); count++; zipout.putNextEntry(new ZipEntry("applets/export2html-applet.jar")); IOUtils.copy(new FileInputStream(ctx.getRealPath("/WEB-INF/classes/export2html/export2html-applet.jar")), zipout); zipout.closeEntry(); zipout.flush(); try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); JarOutputStream indexjar = new JarOutputStream(bos); JarEntry jarEntry; File searchDir = new File(wb.getSearchEngine().getSearchIndexPath(virtualWiki)); String files[] = searchDir.list(); StringBuffer listOfAllFiles = new StringBuffer(); for (int i = 0; i < files.length; i++) { if (listOfAllFiles.length() > 0) { listOfAllFiles.append(","); } listOfAllFiles.append(files[i]); jarEntry = new JarEntry("lucene/index/" + files[i]); indexjar.putNextEntry(jarEntry); IOUtils.copy(new FileInputStream(new File(searchDir, files[i])), indexjar); indexjar.closeEntry(); } indexjar.flush(); indexjar.putNextEntry(new JarEntry("lucene/index.dir")); IOUtils.copy(new StringReader(listOfAllFiles.toString()), indexjar); indexjar.closeEntry(); indexjar.flush(); indexjar.close(); zipout.putNextEntry(new ZipEntry("applets/index.jar")); zipout.write(bos.toByteArray()); zipout.closeEntry(); zipout.flush(); bos.reset(); } catch (Exception e) { logger.log(Level.FINE, "Exception while adding lucene index: ", e); } progress = Math.min(progressStart + (int) ((double) count * (double) progressLength / numberOfSpecialPages), 99); count++; StringBuffer content = new StringBuffer(); content.append("<table><tr><th>" + messages.getString("common.date") + "</th><th>" + messages.getString("common.topic") + "</th><th>" + messages.getString("common.user") + "</th></tr>" + IOUtils.LINE_SEPARATOR); Collection all = null; try { Calendar cal = Calendar.getInstance(); ChangeLog cl = wb.getChangeLog(); int n = env.getIntSetting(Environment.PROPERTY_RECENT_CHANGES_DAYS); if (n == 0) { n = 5; } all = new ArrayList(); for (int i = 0; i < n; i++) { Collection col = cl.getChanges(virtualWiki, cal.getTime()); if (col != null) { all.addAll(col); } cal.add(Calendar.DATE, -1); } } catch (Exception e) { } DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale); for (Iterator iter = all.iterator(); iter.hasNext(); ) { Change change = (Change) iter.next(); content.append("<tr><td class=\"recent\">" + df.format(change.getTime()) + "</td><td class=\"recent\"><a href=\"" + safename(change.getTopic()) + ".html\">" + change.getTopic() + "</a></td><td class=\"recent\">" + change.getUser() + "</td></tr>"); } content.append("</table>" + IOUtils.LINE_SEPARATOR); tpl = getTemplateFilledWithContent(null); tpl = tpl.replaceAll("@@CONTENTS@@", content.toString()); addTopicEntry(zipout, tpl, "RecentChanges", "RecentChanges.html"); logger.fine("Done adding all special topics."); }
Code Sample 2:
private static String getUnsaltedHash(String algorithm, String input) throws NoSuchAlgorithmException { MessageDigest messageDigest = MessageDigest.getInstance(algorithm); messageDigest.reset(); messageDigest.update(input.getBytes(Main.DEFAULT_CHARSET)); byte[] digest = messageDigest.digest(); return String.format(Main.DEFAULT_LOCALE, "%0" + (digest.length << 1) + "x", new BigInteger(1, digest)); }
|
00
|
Code Sample 1:
@Override protected IProject createProject(String projectName, IProgressMonitor monitor) throws CoreException { monitor.beginTask(CheatSheetsPlugin.INSTANCE.getString("_UI_CreateJavaProject_message", new String[] { projectName }), 5); IProject project = super.createProject(projectName, new SubProgressMonitor(monitor, 1)); if (project != null) { IProjectDescription description = project.getDescription(); if (!description.hasNature(JavaCore.NATURE_ID)) { IJavaProject javaProject = JavaCore.create(project); if (javaProject != null) { String[] natures = description.getNatureIds(); String[] javaNatures = new String[natures.length + 1]; System.arraycopy(natures, 0, javaNatures, 0, natures.length); javaNatures[natures.length] = JavaCore.NATURE_ID; description.setNatureIds(javaNatures); project.setDescription(description, new SubProgressMonitor(monitor, 1)); IFolder sourceFolder = project.getFolder(SOURCE_FOLDER); if (!sourceFolder.exists()) { sourceFolder.create(true, true, new SubProgressMonitor(monitor, 1)); } javaProject.setOutputLocation(project.getFolder(OUTPUT_FOLDER).getFullPath(), new SubProgressMonitor(monitor, 1)); IClasspathEntry[] entries = new IClasspathEntry[] { JavaCore.newSourceEntry(sourceFolder.getFullPath()), JavaCore.newContainerEntry(new Path("org.eclipse.jdt.launching.JRE_CONTAINER")) }; javaProject.setRawClasspath(entries, new SubProgressMonitor(monitor, 1)); } } } monitor.done(); return project; }
Code Sample 2:
protected void copyFile(String inputFilePath, String outputFilePath) throws GenerationException { String from = getTemplateDir() + inputFilePath; try { logger.debug("Copying from " + from + " to " + outputFilePath); InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(from); if (inputStream == null) { throw new GenerationException("Source file not found: " + from); } FileOutputStream outputStream = new FileOutputStream(new File(outputFilePath)); IOUtils.copy(inputStream, outputStream); inputStream.close(); outputStream.close(); } catch (Exception e) { throw new GenerationException("Error while copying file: " + from, e); } }
|
00
|
Code Sample 1:
private void checkChartsyRegistration(String username, String password) { HttpPost post = new HttpPost(NbBundle.getMessage(RegisterPanel.class, "RegisterPanel.chartsyRegisterURL")); String message = ""; try { List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("username", username)); nvps.add(new BasicNameValuePair("password", password)); post.setEntity(new UrlEncodedFormEntity(nvps)); HttpResponse response = ProxyManager.httpClient.execute(post); HttpEntity entity = response.getEntity(); if (entity != null) { String[] lines = EntityUtils.toString(entity).split("\n"); if (lines[0].equals("OK")) { RegisterAction.preferences.putBoolean("registred", true); RegisterAction.preferences.put("name", lines[1]); RegisterAction.preferences.put("email", lines[2]); RegisterAction.preferences.put("date", String.valueOf(Calendar.getInstance().getTimeInMillis())); RegisterAction.preferences.put("username", username); RegisterAction.preferences.put("password", new String(passwordTxt.getPassword())); if (lines[1] != null && !lines[1].isEmpty()) { message = NbBundle.getMessage(RegisterPanel.class, "RegisterPanel.registerDone.withUsername.message", lines[1]); } else { message = NbBundle.getMessage(RegisterPanel.class, "RegisterPanel.registerDone.noUsername.message"); } } else { message = NbBundle.getMessage(RegisterPanel.class, "RegisterPanel.registerAuthError.message"); } EntityUtils.consume(entity); } } catch (Exception ex) { message = NbBundle.getMessage(RegisterPanel.class, "RegisterPanel.registerConnectionError.message"); } finally { post.abort(); } messageLbl.setText(message); messageLbl.setVisible(true); }
Code Sample 2:
public static void main(String[] args) throws Exception { String uri = args[0]; Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(URI.create(uri), conf); InputStream in = null; try { in = fs.open(new Path(uri)); IOUtils.copyBytes(in, System.out, 4096, false); } finally { IOUtils.closeStream(in); } }
|
00
|
Code Sample 1:
public static void translateTableAttributes(String baseDir, String tableName, NameSpaceDefinition nsDefinition) throws Exception { setVosiNS(baseDir, "table_att", nsDefinition); String filename = baseDir + "table_att.xsl"; Scanner s = new Scanner(new File(filename)); PrintWriter fw = new PrintWriter(new File(baseDir + tableName + "_att.xsl")); while (s.hasNextLine()) { fw.println(s.nextLine().replaceAll("TABLENAME", tableName)); } s.close(); fw.close(); applyStyle(baseDir + "tables.xml", baseDir + tableName + "_att.json", baseDir + tableName + "_att.xsl"); }
Code Sample 2:
public boolean update(int idTorneo, torneo torneoModificado) { int intResult = 0; String sql = "UPDATE torneo " + "SET nombreTorneo = ?, ciudad = ?, fechaInicio = ?, fechaFinal = ?, " + " organizador = ? " + " WHERE idTorneo = " + idTorneo; try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); populatePreparedStatement2(torneoModificado); intResult = ps.executeUpdate(); connection.commit(); } catch (SQLException ex) { ex.printStackTrace(); try { connection.rollback(); } catch (SQLException exe) { exe.printStackTrace(); } } finally { conexionBD.close(ps); conexionBD.close(connection); } return (intResult > 0); }
|
11
|
Code Sample 1:
public static String Sha1(String s) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] hash = new byte[40]; md.update(s.getBytes("iso-8859-1"), 0, s.length()); hash = md.digest(); return toHex(hash); } catch (Exception e) { e.printStackTrace(); return null; } }
Code Sample 2:
private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } }
|
11
|
Code Sample 1:
private void analyseCorpus(final IStatusDisplayer fStatus) { final String sDistrosFile = "Distros.tmp"; final String sSymbolsFile = "Symbols.tmp"; Chunker = new EntropyChunker(); int Levels = 2; sgOverallGraph = new SymbolicGraph(1, Levels); siIndex = new SemanticIndex(sgOverallGraph); try { siIndex.MeaningExtractor = new LocalWordNetMeaningExtractor(); } catch (IOException ioe) { siIndex.MeaningExtractor = null; } try { DocumentSet dsSet = new DocumentSet(FilePathEdt.getText(), 1.0); dsSet.createSets(true, (double) 100 / 100); int iCurCnt, iTotal; String sFile = ""; Iterator iIter = dsSet.getTrainingSet().iterator(); iTotal = dsSet.getTrainingSet().size(); if (iTotal == 0) { appendToLog("No input documents.\n"); appendToLog("======DONE=====\n"); return; } appendToLog("Training chunker..."); Chunker.train(dsSet.toFilenameSet(DocumentSet.FROM_WHOLE_SET)); appendToLog("Setting delimiters..."); setDelimiters(Chunker.getDelimiters()); iCurCnt = 0; cdDoc = new DistributionDocument[Levels]; for (int iCnt = 0; iCnt < Levels; iCnt++) cdDoc[iCnt] = new DistributionDocument(1, MinLevel + iCnt); fStatus.setVisible(true); ThreadList t = new ThreadList(Runtime.getRuntime().availableProcessors() + 1); appendToLog("(Pass 1/3) Loading files..." + sFile); TreeSet tsOverallSymbols = new TreeSet(); while (iIter.hasNext()) { sFile = ((CategorizedFileEntry) iIter.next()).getFileName(); fStatus.setStatus("(Pass 1/3) Loading file..." + sFile, (double) iCurCnt / iTotal); final DistributionDocument[] cdDocArg = cdDoc; final String sFileArg = sFile; for (int iCnt = 0; iCnt < cdDoc.length; iCnt++) { final int iCntArg = iCnt; while (!t.addThreadFor(new Runnable() { public void run() { if (!RightToLeftText) cdDocArg[iCntArg].loadDataStringFromFile(sFileArg, false); else { cdDocArg[iCntArg].setDataString(utils.reverseString(utils.loadFileToString(sFileArg)), iCntArg, false); } } })) Thread.yield(); } try { t.waitUntilCompletion(); } catch (InterruptedException ex) { ex.printStackTrace(System.err); appendToLog("Interrupted..."); sgOverallGraph.removeNotificationListener(); return; } sgOverallGraph.setDataString(((new StringBuffer().append((char) StreamTokenizer.TT_EOF))).toString()); sgOverallGraph.loadFromFile(sFile); fStatus.setStatus("Loaded file..." + sFile, (double) ++iCurCnt / iTotal); Thread.yield(); } Set sSymbols = null; File fPreviousSymbols = new File(sSymbolsFile); boolean bSymbolsLoadedOK = false; if (fPreviousSymbols.exists()) { System.err.println("ATTENTION: Using previous symbols..."); try { FileInputStream fis = new FileInputStream(fPreviousSymbols); ObjectInputStream ois = new ObjectInputStream(fis); sSymbols = (Set) ois.readObject(); ois.close(); bSymbolsLoadedOK = true; } catch (FileNotFoundException ex) { ex.printStackTrace(System.err); } catch (IOException ex) { ex.printStackTrace(System.err); } catch (ClassNotFoundException ex) { ex.printStackTrace(System.err); } } if (!bSymbolsLoadedOK) sSymbols = getSymbolsByProbabilities(sgOverallGraph.getDataString(), fStatus); int iMinSymbolSize = Integer.MAX_VALUE; int iMaxSymbolSize = Integer.MIN_VALUE; Iterator iSymbol = sSymbols.iterator(); while (iSymbol.hasNext()) { String sCurSymbol = (String) iSymbol.next(); if (iMaxSymbolSize < sCurSymbol.length()) iMaxSymbolSize = sCurSymbol.length(); if (iMinSymbolSize > sCurSymbol.length()) iMinSymbolSize = sCurSymbol.length(); } try { FileOutputStream fos = new FileOutputStream(sSymbolsFile); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(sSymbols); oos.close(); } catch (FileNotFoundException ex) { ex.printStackTrace(System.err); } catch (IOException ex) { ex.printStackTrace(System.err); } appendToLog("(Pass 2/3) Determining symbol distros per n-gram size..."); iIter = dsSet.getTrainingSet().iterator(); iTotal = dsSet.getTrainingSet().size(); if (iTotal == 0) { appendToLog("No input documents.\n"); appendToLog("======DONE=====\n"); return; } iCurCnt = 0; Distribution dSymbolsPerSize = new Distribution(); Distribution dNonSymbolsPerSize = new Distribution(); Distribution dSymbolSizes = new Distribution(); File fPreviousRun = new File(sDistrosFile); boolean bDistrosLoadedOK = false; if (fPreviousRun.exists()) { System.err.println("ATTENTION: Using previous distros..."); try { FileInputStream fis = new FileInputStream(fPreviousRun); ObjectInputStream ois = new ObjectInputStream(fis); dSymbolsPerSize = (Distribution) ois.readObject(); dNonSymbolsPerSize = (Distribution) ois.readObject(); dSymbolSizes = (Distribution) ois.readObject(); ois.close(); bDistrosLoadedOK = true; } catch (FileNotFoundException ex) { ex.printStackTrace(System.err); } catch (IOException ex) { ex.printStackTrace(System.err); dSymbolsPerSize = new Distribution(); dNonSymbolsPerSize = new Distribution(); dSymbolSizes = new Distribution(); } catch (ClassNotFoundException ex) { ex.printStackTrace(System.err); dSymbolsPerSize = new Distribution(); dNonSymbolsPerSize = new Distribution(); dSymbolSizes = new Distribution(); } } if (!bDistrosLoadedOK) while (iIter.hasNext()) { fStatus.setStatus("(Pass 2/3) Parsing file..." + sFile, (double) iCurCnt++ / iTotal); sFile = ((CategorizedFileEntry) iIter.next()).getFileName(); String sDataString = ""; try { ByteArrayOutputStream bsOut = new ByteArrayOutputStream(); FileInputStream fiIn = new FileInputStream(sFile); int iData = 0; while ((iData = fiIn.read()) > -1) bsOut.write(iData); sDataString = bsOut.toString(); } catch (IOException ioe) { ioe.printStackTrace(System.err); } final Distribution dSymbolsPerSizeArg = dSymbolsPerSize; final Distribution dNonSymbolsPerSizeArg = dNonSymbolsPerSize; final Distribution dSymbolSizesArg = dSymbolSizes; final String sDataStringArg = sDataString; final Set sSymbolsArg = sSymbols; for (int iSymbolSize = iMinSymbolSize; iSymbolSize <= iMaxSymbolSize; iSymbolSize++) { final int iSymbolSizeArg = iSymbolSize; while (!t.addThreadFor(new Runnable() { public void run() { NGramDocument ndCur = new NGramDocument(iSymbolSizeArg, iSymbolSizeArg, 1, iSymbolSizeArg, iSymbolSizeArg); ndCur.setDataString(sDataStringArg); int iSymbolCnt = 0; int iNonSymbolCnt = 0; Iterator iExtracted = ndCur.getDocumentGraph().getGraphLevel(0).getVertexSet().iterator(); while (iExtracted.hasNext()) { String sCur = ((Vertex) iExtracted.next()).toString(); if (sSymbolsArg.contains(sCur)) { iSymbolCnt++; synchronized (dSymbolSizesArg) { dSymbolSizesArg.setValue(sCur.length(), dSymbolSizesArg.getValue(sCur.length()) + 1.0); } } else iNonSymbolCnt++; } synchronized (dSymbolsPerSizeArg) { dSymbolsPerSizeArg.setValue(iSymbolSizeArg, dSymbolsPerSizeArg.getValue(iSymbolSizeArg) + iSymbolCnt); } synchronized (dNonSymbolsPerSizeArg) { dNonSymbolsPerSizeArg.setValue(iSymbolSizeArg, dNonSymbolsPerSizeArg.getValue(iSymbolSizeArg) + iNonSymbolCnt); } } })) Thread.yield(); } } if (!bDistrosLoadedOK) try { t.waitUntilCompletion(); try { FileOutputStream fos = new FileOutputStream(sDistrosFile); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(dSymbolsPerSize); oos.writeObject(dNonSymbolsPerSize); oos.writeObject(dSymbolSizes); oos.close(); } catch (FileNotFoundException ex) { ex.printStackTrace(System.err); } catch (IOException ex) { ex.printStackTrace(System.err); } } catch (InterruptedException ex) { appendToLog("Interrupted..."); sgOverallGraph.removeNotificationListener(); return; } appendToLog("\n(Pass 3/3) Determining optimal n-gram range...\n"); NGramSizeEstimator nseEstimator = new NGramSizeEstimator(dSymbolsPerSize, dNonSymbolsPerSize); IntegerPair p = nseEstimator.getOptimalRange(); appendToLog("\nProposed n-gram sizes:" + p.first() + "," + p.second()); fStatus.setStatus("Determining optimal distance...", 0.0); DistanceEstimator de = new DistanceEstimator(dSymbolsPerSize, dNonSymbolsPerSize, nseEstimator); int iBestDist = de.getOptimalDistance(1, nseEstimator.getMaxRank() * 2, p.first(), p.second()); fStatus.setStatus("Determining optimal distance...", 1.0); appendToLog("\nOptimal distance:" + iBestDist); appendToLog("======DONE=====\n"); } finally { sgOverallGraph.removeNotificationListener(); } }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
11
|
Code Sample 1:
public static String generateMD5(String clear) { byte hash[] = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(clear.getBytes()); hash = md5.digest(); } catch (NoSuchAlgorithmException e) { } if (hash != null) { StringBuffer hexString = new StringBuffer(); for (int i = 0; i < hash.length; i++) { String tmp = Integer.toHexString(0xFF & hash[i]); if (tmp.length() == 1) { tmp = "0" + tmp; } hexString.append(tmp); } return hexString.toString(); } else { return null; } }
Code Sample 2:
public synchronized String encrypt(String plaintext) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); md.update(plaintext.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { log().error("failed to encrypt the password.", e); throw new RuntimeException("failed to encrypt the password.", e); } catch (UnsupportedEncodingException e) { log().error("failed to encrypt the password.", e); throw new RuntimeException("failed to encrypt the password.", e); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
|
00
|
Code Sample 1:
private boolean parse(Type type, URL url, boolean checkDict) throws Exception { boolean ok = true; Exception ee = null; Element rootElement = null; try { InputStream in = url.openStream(); if (type.equals(Type.XOM)) { new Builder().build(in); } else if (type.equals(Type.CML)) { rootElement = new CMLBuilder().build(in).getRootElement(); } in.close(); } catch (Exception e) { ee = e; } if (ee != null) { logger.severe("failed to cmlParse: " + url + "\n..... because: [" + ee + "] [" + ee.getMessage() + "] in [" + url + "]"); ok = false; } if (ok && checkDict) { ok = checkDict(rootElement); } return ok; }
Code Sample 2:
public static final void zip(final ZipOutputStream out, final File f, String base) throws Exception { if (f.isDirectory()) { final File[] fl = f.listFiles(); base = base.length() == 0 ? "" : base + File.separator; for (final File element : fl) { zip(out, element, base + element.getName()); } } else { out.putNextEntry(new org.apache.tools.zip.ZipEntry(base)); final FileInputStream in = new FileInputStream(f); IOUtils.copyStream(in, out); in.close(); } Thread.sleep(10); }
|
00
|
Code Sample 1:
public InputStream getFileStream(String filePath) { if (this.inJar) { try { URL url = getClassResourceUrl(this.getClass(), filePath); if (url != null) { return url.openStream(); } } catch (IOException ioe) { Debug.signal(Debug.ERROR, this, ioe); } } else { try { return new FileInputStream(filePath); } catch (FileNotFoundException fe) { Debug.signal(Debug.ERROR, this, fe); } } return null; }
Code Sample 2:
public String elementsSearch() { int index = 0; for (int i1 = 0; i1 < 6; i1++) { for (int i2 = 0; i2 < 5; i2++) { if (index < 5) { if (initialMatrix[i1][i2] > 0) { finalMatrix[index] = initialMatrix[i1][i2]; index++; } } else break; } } int temp; for (int i = 0; i < finalMatrix.length; i++) { for (int j = 0; j < finalMatrix.length - 1; j++) { if (finalMatrix[j] < finalMatrix[j + 1]) { temp = finalMatrix[j]; finalMatrix[j] = finalMatrix[j + 1]; finalMatrix[j + 1] = temp; } } } String result = ""; for (int k : finalMatrix) result += k + " "; return result; }
|
00
|
Code Sample 1:
public static String md5(String value) { try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(value.getBytes()); return bytesToString(messageDigest.digest()); } catch (Exception ex) { Tools.logException(Tools.class, ex, value); } return value; }
Code Sample 2:
private static void exportConfigResource(ClassLoader classLoader, String resourceName, String targetFileName) throws Exception { InputStream is = classLoader.getResourceAsStream(resourceName); FileOutputStream fos = new FileOutputStream(targetFileName, false); IOUtils.copy(is, fos); fos.close(); is.close(); }
|
00
|
Code Sample 1:
public void readData() throws IOException { i = 0; j = 0; URL url = getClass().getResource("resources/Chrom_623_620.dat"); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); s = br.readLine(); StringTokenizer st = new StringTokenizer(s); s = br.readLine(); st = new StringTokenizer(s); chrom_x[i][j] = Double.parseDouble(st.nextToken()); temp_prev = chrom_x[i][j]; chrom_y[i][j] = Double.parseDouble(st.nextToken()); gridmin = chrom_x[i][j]; gridmax = chrom_x[i][j]; sext1[i][j] = Double.parseDouble(st.nextToken()); sext2[i][j] = Double.parseDouble(st.nextToken()); sext3[i][j] = Double.parseDouble(st.nextToken()); sext4[i][j] = Double.parseDouble(st.nextToken()); j++; while ((s = br.readLine()) != null) { st = new StringTokenizer(s); temp_new = Double.parseDouble(st.nextToken()); if (temp_new != temp_prev) { temp_prev = temp_new; i++; j = 0; } chrom_x[i][j] = temp_new; chrom_y[i][j] = Double.parseDouble(st.nextToken()); sext1[i][j] = Double.parseDouble(st.nextToken()); sext2[i][j] = Double.parseDouble(st.nextToken()); sext3[i][j] = Double.parseDouble(st.nextToken()); sext4[i][j] = Double.parseDouble(st.nextToken()); imax = i; jmax = j; j++; if (chrom_x[i][j] <= gridmin) gridmin = chrom_x[i][j]; if (chrom_x[i][j] >= gridmax) gridmax = chrom_x[i][j]; } }
Code Sample 2:
public static void uploadFile(String localPath, String hostname, String username, String password, String remotePath) { FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(hostname); int reply = ftpClient.getReplyCode(); boolean success = false; if (FTPReply.isPositiveCompletion(reply)) { success = ftpClient.login(username, password); if (!success) { Output.error("Failed to login with username/password " + username + "/" + password); return; } ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.ASCII_FILE_TYPE); } FileInputStream in = new FileInputStream(localPath); boolean result = ftpClient.storeFile(remotePath, in); if (!result) { Output.error("Logged in but failed to upload " + localPath + " to " + remotePath + "\nPerhaps one of the paths was wrong."); } in.close(); ftpClient.disconnect(); } catch (IOException ioe) { Output.error("Error ftp'ing using " + "\nlocalPath: " + localPath + "\nhostname: " + hostname + "\nusername: " + username + "\npassword: " + password + "\nremotePath: " + remotePath, ioe); } }
|
00
|
Code Sample 1:
public void updateComponent(int id, int quantity) throws SQLException { Connection connection = null; PreparedStatement ps = null; try { Class.forName("com.mysql.jdbc.Driver"); connection = (Connection) DriverManager.getConnection(this.jdbcURL); connection.setAutoCommit(false); String query = "UPDATE components SET quantity=quantity+? WHERE comp_id=?"; ps = connection.prepareStatement(query); ps.setInt(1, quantity); ps.setInt(2, id); ps.executeUpdate(); connection.commit(); } catch (Exception ex) { connection.rollback(); } finally { try { connection.close(); } catch (Exception ex) { } try { ps.close(); } catch (Exception ex) { } } }
Code Sample 2:
private InputStream callService(String text) { InputStream in = null; try { URL url = new URL(SERVLET_URL); URLConnection conn = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setRequestMethod("POST"); httpConn.setDoInput(true); httpConn.setDoOutput(true); httpConn.connect(); DataOutputStream dataStream = new DataOutputStream(conn.getOutputStream()); dataStream.writeBytes(text); dataStream.flush(); dataStream.close(); int responseCode = httpConn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { in = httpConn.getInputStream(); } } catch (Exception ex) { ex.printStackTrace(); } return in; }
|
00
|
Code Sample 1:
public void prepareWorkingDirectory() throws Exception { workingDirectory = tempDir + "/profile_" + System.nanoTime(); (new File(workingDirectory)).mkdir(); String monitorCallShellScript = "data/scripts/monitorcall.sh"; URL monitorCallShellScriptUrl = Thread.currentThread().getContextClassLoader().getResource(monitorCallShellScript); File inScriptFile = null; try { inScriptFile = new File(monitorCallShellScriptUrl.toURI()); } catch (URISyntaxException e) { throw e; } monitorShellScript = workingDirectory + "/monitorcall.sh"; File outScriptFile = new File(monitorShellScript); FileChannel inChannel = new FileInputStream(inScriptFile).getChannel(); FileChannel outChannel = new FileOutputStream(outScriptFile).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } try { LinuxCommandExecutor cmdExecutor = new LinuxCommandExecutor(); cmdExecutor.runCommand("chmod 777 " + monitorShellScript); } catch (Exception e) { throw e; } }
Code Sample 2:
public void testReleaseConnectionOnAbort() throws Exception { HttpParams mgrpar = defaultParams.copy(); ConnManagerParams.setMaxTotalConnections(mgrpar, 1); ThreadSafeClientConnManager mgr = createTSCCM(mgrpar, null); final HttpHost target = getServerHttp(); final HttpRoute route = new HttpRoute(target, null, false); final int rsplen = 8; final String uri = "/random/" + rsplen; HttpRequest request = new BasicHttpRequest("GET", uri, HttpVersion.HTTP_1_1); ManagedClientConnection conn = getConnection(mgr, route); conn.open(route, httpContext, defaultParams); HttpResponse response = Helper.execute(request, conn, target, httpExecutor, httpProcessor, defaultParams, httpContext); assertEquals("wrong status in first response", HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); try { getConnection(mgr, route, 100L, TimeUnit.MILLISECONDS); fail("ConnectionPoolTimeoutException should have been thrown"); } catch (ConnectionPoolTimeoutException e) { } assertTrue(conn instanceof AbstractClientConnAdapter); ((AbstractClientConnAdapter) conn).abortConnection(); conn = getConnection(mgr, route, 5L, TimeUnit.SECONDS); assertFalse("connection should have been closed", conn.isOpen()); mgr.releaseConnection(conn, -1, null); mgr.shutdown(); }
|
00
|
Code Sample 1:
public void apop(String user, char[] secret) throws IOException, POP3Exception { if (timestamp == null) { throw new CommandNotSupportedException("No timestamp from server - APOP not possible"); } try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(timestamp.getBytes()); if (secret == null) secret = new char[0]; byte[] digest = md.digest(new String(secret).getBytes("ISO-8859-1")); mutex.lock(); sendCommand("APOP", new String[] { user, digestToString(digest) }); POP3Response response = readSingleLineResponse(); if (!response.isOK()) { throw new POP3Exception(response); } state = TRANSACTION; } catch (NoSuchAlgorithmException e) { throw new POP3Exception("Installed JRE doesn't support MD5 - APOP not possible"); } finally { mutex.release(); } }
Code Sample 2:
public static void copyFileByNIO(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
|
11
|
Code Sample 1:
public Logging() throws Exception { File home = new File(System.getProperty("user.home"), ".jorgan"); if (!home.exists()) { home.mkdirs(); } File logging = new File(home, "logging.properties"); if (!logging.exists()) { InputStream input = getClass().getResourceAsStream("logging.properties"); OutputStream output = null; try { output = new FileOutputStream(logging); IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } } FileInputStream input = null; try { input = new FileInputStream(logging); LogManager.getLogManager().readConfiguration(input); } finally { IOUtils.closeQuietly(input); } }
Code Sample 2:
public void saveUploadFile(String toFileName, UploadFile uploadFile, SysConfig sysConfig) throws IOException { OutputStream bos = new FileOutputStream(toFileName); IOUtils.copy(uploadFile.getInputStream(), bos); if (sysConfig.isAttachImg(uploadFile.getFileName()) && sysConfig.getReduceAttachImg() == 1) { ImgUtil.reduceImg(toFileName, toFileName + Constant.IMG_SMALL_FILEPREFIX, sysConfig.getReduceAttachImgSize(), sysConfig.getReduceAttachImgSize(), 1); } }
|
11
|
Code Sample 1:
public static void main(String[] args) throws IOException { System.out.println("Start filtering zgps..."); final Config config = ConfigUtils.loadConfig(args[0]); final String CONFIG_MODULE = "GPSFilterZGPS"; File sourceFileSelectedStages = new File(config.findParam(CONFIG_MODULE, "sourceFileSelectedStages")); File sourceFileZGPS = new File(config.findParam(CONFIG_MODULE, "sourceFileZGPS")); File targetFile = new File(config.findParam(CONFIG_MODULE, "targetFile")); System.out.println("Start reading selected stages..."); FilterZGPSSelectedStages selectedStages = new FilterZGPSSelectedStages(); selectedStages.createSelectedStages(sourceFileSelectedStages); System.out.println("Done. " + selectedStages.getSelectedStages().size() + " stages were stored"); System.out.println("Start reading and writing zgps..."); try { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(sourceFileZGPS))); BufferedWriter out = new BufferedWriter(new FileWriter(targetFile)); out.write(in.readLine()); out.newLine(); String lineFromInputFile; while ((lineFromInputFile = in.readLine()) != null) { String[] entries = lineFromInputFile.split("\t"); if (selectedStages.containsStage(Integer.parseInt(entries[0]), Integer.parseInt(entries[1]), Integer.parseInt(entries[2]))) { out.write(lineFromInputFile); out.newLine(); out.flush(); } } in.close(); out.close(); } catch (FileNotFoundException e) { System.out.println("Could not find source file for selected stages."); e.printStackTrace(); } catch (IOException e) { System.out.println("IO Exception while reading or writing zgps."); e.printStackTrace(); } System.out.println("Done."); }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
00
|
Code Sample 1:
public final synchronized boolean isValidLicenseFile() throws LicenseNotSetupException { if (!isSetup()) { throw new LicenseNotSetupException(); } boolean returnValue = false; Properties properties = getLicenseFile(); logger.debug("isValidLicenseFile: License to validate:"); logger.debug(properties); StringBuffer validationStringBuffer = new StringBuffer(); validationStringBuffer.append(LICENSE_KEY_KEY + ":" + properties.getProperty(LICENSE_KEY_KEY) + ","); validationStringBuffer.append(LICENSE_FILE_STATUS_KEY + ":" + properties.getProperty(LICENSE_FILE_STATUS_KEY) + ","); validationStringBuffer.append(LICENSE_FILE_USERS_KEY + ":" + properties.getProperty(LICENSE_FILE_USERS_KEY) + ","); validationStringBuffer.append(LICENSE_FILE_MAC_KEY + ":" + properties.getProperty(LICENSE_FILE_MAC_KEY) + ","); validationStringBuffer.append(LICENSE_FILE_HOST_NAME_KEY + ":" + properties.getProperty(LICENSE_FILE_HOST_NAME_KEY) + ","); validationStringBuffer.append(LICENSE_FILE_OFFSET_KEY + ":" + properties.getProperty(LICENSE_FILE_OFFSET_KEY) + ","); validationStringBuffer.append(LICENSE_FILE_EXP_DATE_KEY + ":" + properties.getProperty(LICENSE_FILE_EXP_DATE_KEY) + ","); validationStringBuffer.append(LICENSE_EXPIRES_KEY + ":" + properties.getProperty(LICENSE_EXPIRES_KEY)); logger.debug("isValidLicenseFile: Validation String Buffer: " + validationStringBuffer.toString()); String validationKey = (String) properties.getProperty(LICENSE_FILE_SHA_KEY); try { MessageDigest messageDigest = MessageDigest.getInstance("SHA-1"); messageDigest.update(validationStringBuffer.toString().getBytes()); String newValidation = Base64.encode(messageDigest.digest()); if (newValidation.equals(validationKey)) { if (getMACAddress().equals(Settings.getInstance().getMACAddress())) { returnValue = true; } } } catch (Exception exception) { System.out.println("Exception in LicenseInstanceVO.isValidLicenseFile"); } return returnValue; }
Code Sample 2:
private void copyFiles(File oldFolder, File newFolder) { for (File fileToCopy : oldFolder.listFiles()) { File copiedFile = new File(newFolder.getAbsolutePath() + "\\" + fileToCopy.getName()); try { FileInputStream source = new FileInputStream(fileToCopy); FileOutputStream destination = new FileOutputStream(copiedFile); FileChannel sourceFileChannel = source.getChannel(); FileChannel destinationFileChannel = destination.getChannel(); long size = sourceFileChannel.size(); sourceFileChannel.transferTo(0, size, destinationFileChannel); source.close(); destination.close(); } catch (Exception exc) { exc.printStackTrace(); } } }
|
00
|
Code Sample 1:
public static long writeInputStreamToOutputStream(final InputStream in, final OutputStream out) { long size = 0; try { size = IOUtils.copyLarge(in, out); } catch (IOException e1) { e1.printStackTrace(); } return size; }
Code Sample 2:
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; }
|
11
|
Code Sample 1:
public static int copy(File src, int amount, File dst) { final int BUFFER_SIZE = 1024; int 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, Math.min(BUFFER_SIZE, amountToRead)); if (read == -1) break; amountToRead -= read; out.write(buf, 0, read); } } catch (IOException e) { } finally { if (in != null) try { in.close(); } catch (IOException e) { } if (out != null) { try { out.flush(); } catch (IOException e) { } try { out.close(); } catch (IOException e) { } } } return amount - amountToRead; }
Code Sample 2:
public static void copy(File from, File to, CopyMode mode) throws IOException { if (!from.exists()) { IllegalArgumentException e = new IllegalArgumentException("Source doesn't exist: " + from.getCanonicalFile()); log.throwing("Utils", "copy", e); throw e; } if (from.isFile()) { if (!to.canWrite()) { IllegalArgumentException e = new IllegalArgumentException("Cannot write to target location: " + to.getCanonicalFile()); log.throwing("Utils", "copy", e); throw e; } } if (to.exists()) { if ((mode.val & CopyMode.OverwriteFile.val) != CopyMode.OverwriteFile.val) { IllegalArgumentException e = new IllegalArgumentException("Target already exists: " + to.getCanonicalFile()); log.throwing("Utils", "copy", e); throw e; } if (to.isDirectory()) { if ((mode.val & CopyMode.OverwriteFolder.val) != CopyMode.OverwriteFolder.val) { IllegalArgumentException e = new IllegalArgumentException("Target is a folder: " + to.getCanonicalFile()); log.throwing("Utils", "copy", e); throw e; } else to.delete(); } } if (from.isFile()) { FileChannel in = new FileInputStream(from).getChannel(); FileLock inLock = in.lock(); FileChannel out = new FileOutputStream(to).getChannel(); FileLock outLock = out.lock(); try { in.transferTo(0, (int) in.size(), out); } finally { inLock.release(); outLock.release(); in.close(); out.close(); } } else { to.mkdirs(); File[] contents = to.listFiles(); for (File file : contents) { File newTo = new File(to.getCanonicalPath() + "/" + file.getName()); copy(file, newTo, mode); } } }
|
11
|
Code Sample 1:
public String readFile(String filename) throws UnsupportedEncodingException, FileNotFoundException, IOException { File f = new File(baseDir); f = new File(f, filename); StringWriter w = new StringWriter(); Reader fr = new InputStreamReader(new FileInputStream(f), "UTF-8"); IOUtils.copy(fr, w); fr.close(); w.close(); String contents = w.toString(); return contents; }
Code Sample 2:
private static void copyFile(String srFile, String dtFile) { try { File f1 = new File(srFile); File f2 = new File(dtFile); InputStream in = new FileInputStream(f1); OutputStream out = new FileOutputStream(f2); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); } catch (FileNotFoundException ex) { System.out.println("Error copying " + srFile + " to " + dtFile); System.out.println(ex.getMessage() + " in the specified directory."); } catch (IOException e) { System.out.println(e.getMessage()); } }
|
00
|
Code Sample 1:
private static byte[] loadBytecodePrivileged() { URL url = SecureCaller.class.getResource("SecureCallerImpl.clazz"); try { InputStream in = url.openStream(); try { ByteArrayOutputStream bout = new ByteArrayOutputStream(); for (; ; ) { int r = in.read(); if (r == -1) { return bout.toByteArray(); } bout.write(r); } } finally { in.close(); } } catch (IOException e) { throw new UndeclaredThrowableException(e); } }
Code Sample 2:
public void importNotesFromServer() { boolean downloaded = true; try { makeBackupFile(); File f = new File(UserSettings.getInstance().getNotesFile()); FileOutputStream fos = new FileOutputStream(f); String urlString = protocol + "://" + UserSettings.getInstance().getServerAddress() + UserSettings.getInstance().getServerDir() + f.getName(); setDefaultAuthenticator(); URL url = new URL(urlString); HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); InputStream is = urlc.getInputStream(); int nextByte = is.read(); while (nextByte != -1) { fos.write(nextByte); nextByte = is.read(); } fos.close(); if (urlc.getResponseCode() != HttpURLConnection.HTTP_OK) { downloaded = false; } } catch (SSLHandshakeException e) { JOptionPane.showMessageDialog(null, I18N.getInstance().getString("error.sslcertificateerror"), I18N.getInstance().getString("error.title"), JOptionPane.ERROR_MESSAGE); downloaded = false; } catch (Exception e) { downloaded = false; } if (downloaded) { deleteBackupFile(); JOptionPane.showMessageDialog(null, I18N.getInstance().getString("info.notesfiledownloaded"), I18N.getInstance().getString("info.title"), JOptionPane.INFORMATION_MESSAGE); } else { restoreFileFromBackup(); JOptionPane.showMessageDialog(null, I18N.getInstance().getString("error.notesfilenotdownloaded"), I18N.getInstance().getString("error.title"), JOptionPane.ERROR_MESSAGE); } }
|
00
|
Code Sample 1:
private boolean Try(URL url, Metafile mf) throws Throwable { InputStream is = null; HttpURLConnection con = null; boolean success = false; try { con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.connect(); is = con.getInputStream(); Response r = new Response(is); responses.add(r); peers.addAll(r.peers); Main.log.info("got " + r.peers.size() + " peers from " + url); success = true; } finally { if (is != null) is.close(); if (con != null) con.disconnect(); } return success; }
Code Sample 2:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
|
00
|
Code Sample 1:
public void onItem(FeedParserState state, String title, String link, String description, String permalink) throws FeedParserException { if (counter >= MAX_FEEDS) { throw new FeedPollerCancelException("Maximum number of items reached"); } boolean canAnnounce = false; try { if (lastDigest == null) { MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.update(title.getBytes()); lastDigest = md.digest(); canAnnounce = true; } else { MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.update(title.getBytes()); byte[] currentDigest = md.digest(); if (!MessageDigest.isEqual(currentDigest, lastDigest)) { lastDigest = currentDigest; canAnnounce = true; } } if (canAnnounce) { String shortTitle = title; if (shortTitle.length() > TITLE_MAX_LEN) { shortTitle = shortTitle.substring(0, TITLE_MAX_LEN) + " ..."; } String shortLink = IOUtil.getTinyUrl(link); Log.debug("Link:" + shortLink); for (Channel channel : channels) { channel.say(String.format("%s, %s", shortTitle, shortLink)); } } } catch (Exception e) { throw new FeedParserException(e); } counter++; }
Code Sample 2:
public static void zip(ZipOutputStream out, File f, String base) throws Exception { if (f.isDirectory()) { File[] fl = f.listFiles(); base = base.length() == 0 ? "" : base + File.separator; for (int i = 0; i < fl.length; i++) { zip(out, fl[i], base + fl[i].getName()); } } else { out.putNextEntry(new org.apache.tools.zip.ZipEntry(base)); FileInputStream in = new FileInputStream(f); IOUtils.copyStream(in, out); in.close(); } Thread.sleep(10); }
|
11
|
Code Sample 1:
public byte process(ProcessorContext<PublishRequest> context) throws InterruptedException, ProcessorException { logger.info("MapTileChacheTask:process"); PublishRequest req = context.getItem().getEntity(); if (StringUtils.isEmpty(req.getBackMap())) return TaskState.STATE_TILE_CACHED; final PublicMapPost post; final GenericDAO<PublicMapPost> postDao = DAOFactory.createDAO(PublicMapPost.class); try { ReadOnlyTransaction.beginTransaction(); } catch (DatabaseException e) { logger.error("error", e); throw new ProcessorException(e); } int numCachedTiles = 0; try { List<MapTile> backTiles = new ArrayList<MapTile>(); post = postDao.findUniqueByCriteria(Expression.eq("guid", req.getPostGuid())); final LatLngRectangle bounds = new LatLngRectangle(new LatLngPoint(post.getSWLat(), post.getSWLon()), new LatLngPoint(post.getNELat(), post.getNELon())); final String backMapGuid = "gst"; final XFile dstDir = new XFile(new XFile(Configuration.getInstance().getPublicMapStorage().toString()), backMapGuid); dstDir.mkdir(); for (int z = Math.min(Tile.getOptimalZoom(bounds, 768), 9); z <= 17; z++) { final Tile tileStart = new Tile(bounds.getSouthWest().getLat(), bounds.getSouthWest().getLng(), z); final Tile tileEnd = new Tile(bounds.getNorthEast().getLat(), bounds.getNorthEast().getLng(), z); for (double y = tileEnd.getTileCoord().getY(); y <= tileStart.getTileCoord().getY(); y++) for (double x = tileStart.getTileCoord().getX(); x <= tileEnd.getTileCoord().getX(); x++) { NASAMapTile tile = new NASAMapTile((int) x, (int) y, z); XFile file = new XFile(dstDir, tile.toKeyString()); if (file.exists() && file.isFile()) continue; backTiles.add(tile); } } try { for (MapTile tile : backTiles) { InputStream in = null; OutputStream out = null; final URL url = new URL(tile.getPath()); try { final XFile outFile = new XFile(dstDir, tile.toKeyString()); final URLConnection conn = url.openConnection(); if (conn == null || !conn.getContentType().startsWith("image")) throw new IllegalAccessException("onearth.jpl.nasa.gov service returns non-image file, " + "content-type='" + conn.getContentType() + "'"); in = conn.getInputStream(); if (in != null) { out = new XFileOutputStream(outFile); IOUtils.copy(in, out); } else throw new IllegalStateException("opened stream is null"); } finally { if (out != null) { out.flush(); out.close(); } if (in != null) in.close(); } if (++numCachedTiles % 100 == 0) { logger.info(numCachedTiles + " tiles cached"); } } } catch (Throwable e) { logger.error("map tile caching has failed: ", e); throw new ProcessorException(e); } } catch (ProcessorException e) { logger.error("map tile caching has failed: ", e); throw e; } catch (Throwable e) { logger.error("map tile caching has failed: ", e); throw new ProcessorException(e); } finally { ReadOnlyTransaction.closeTransaction(); logger.info(numCachedTiles + " tiles cached"); } return TaskState.STATE_TILE_CACHED; }
Code Sample 2:
private static void copyFile(File in, File out) throws Exception { final FileInputStream input = new FileInputStream(in); try { final FileOutputStream output = new FileOutputStream(out); try { final byte[] buf = new byte[4096]; int readBytes = 0; while ((readBytes = input.read(buf)) != -1) { output.write(buf, 0, readBytes); } } finally { output.close(); } } finally { input.close(); } }
|
00
|
Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public HttpURLConnection execute(S3Bucket pBucket, S3Object pObject, S3OperationParameters pOpParams) throws S3Exception { S3OperationParameters opParams = pOpParams; if (opParams == null) opParams = new S3OperationParameters(); HttpURLConnection result = null; URL url = getURL(pBucket, pObject, opParams.getQueryParameters()); mLogger.log(Level.FINEST, "URL: " + url.toString()); opParams.addDateHeader(); switch(mStyle) { case Path: opParams.addHostHeader(BASE_DOMAIN); break; case Subdomain: if (pBucket == null) opParams.addHostHeader(BASE_DOMAIN); else opParams.addHostHeader(pBucket.getName() + "." + BASE_DOMAIN); break; case VirtualHost: if (pBucket == null) opParams.addHostHeader(BASE_DOMAIN); else opParams.addHostHeader(pBucket.getName()); break; } if (opParams.isSign()) { StringBuilder sb = new StringBuilder(); sb.append(opParams.getVerb().toString()); sb.append(NEWLINE); sb.append(posHeader(MD5, opParams.getRequestHeaders())); sb.append(posHeader(TYPE, opParams.getRequestHeaders())); if (opParams.getQueryParameters().has(EXPIRES)) { sb.append(opParams.getQueryParameters().get(EXPIRES).getValue()); sb.append(NEWLINE); } else { sb.append(posHeader(DATE, opParams.getRequestHeaders())); } sb.append(canonicalizeAmazonHeaders(opParams.getRequestHeaders())); try { sb.append("/"); if (pBucket != null) { sb.append(URLEncoder.encode(pBucket.getName(), URL_ENCODING)); sb.append("/"); if (pObject != null) { sb.append(URLEncoder.encode(pObject.getKey(), URL_ENCODING)); } } sb.append(opParams.getQueryParameters().getAmazonSubresources().toQueryString()); String signThis = sb.toString(); mLogger.log(Level.FINEST, "String being signed: " + signThis); String sig = encode(mCredential.getMSecretAccessKey(), signThis, false); sb = new StringBuilder(); sb.append("AWS "); sb.append(mCredential.getMAccessKeyID()); sb.append(":"); sb.append(sig); opParams.addAuthorizationHeader(sb.toString()); } catch (UnsupportedEncodingException e) { throw new S3Exception("URL encoding not supported: " + URL_ENCODING, e); } } try { killHostVerifier(); URLConnection urlConn = url.openConnection(); if (!(urlConn instanceof HttpURLConnection)) throw new S3Exception("URLConnection is not instance of HttpURLConnection!"); result = (HttpURLConnection) urlConn; result.setRequestMethod(opParams.getVerb().toString()); mLogger.log(Level.FINEST, "HTTP Operation: " + opParams.getVerb().toString()); if (opParams.getVerb() == HttpVerb.PUT) { result.setDoOutput(true); } result.setRequestProperty(TYPE, ""); for (AWSParameter param : opParams.getRequestHeaders()) { result.setRequestProperty(param.getName(), param.getValue()); mLogger.log(Level.FINEST, "Header " + param.getName() + ": " + param.getValue()); } } catch (IOException e) { throw new S3Exception("Problem opening connection to URL: " + url.toString(), e); } return result; }
|
00
|
Code Sample 1:
public boolean compile(URL url, String name) { try { final InputStream stream = url.openStream(); final InputSource input = new InputSource(stream); input.setSystemId(url.toString()); return compile(input, name); } catch (IOException e) { _parser.reportError(Constants.FATAL, new ErrorMsg(e)); return false; } }
Code Sample 2:
public static String shaEncrypt(final String txt) { String enTxt = txt; MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { logger.error("Error:", e); } if (null != md) { byte[] shahash = new byte[32]; try { md.update(txt.getBytes("UTF-8"), 0, txt.length()); } catch (UnsupportedEncodingException e) { logger.error("Error:", e); } shahash = md.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < shahash.length; i++) { if (Integer.toHexString(0xFF & shahash[i]).length() == 1) { md5StrBuff.append("0").append(Integer.toHexString(0xFF & shahash[i])); } else { md5StrBuff.append(Integer.toHexString(0xFF & shahash[i])); } } enTxt = md5StrBuff.toString(); } return enTxt; }
|
11
|
Code Sample 1:
public static String generateDigest(String message, String DigestAlgorithm) { try { MessageDigest md = MessageDigest.getInstance(DigestAlgorithm); md.update(message.getBytes(), 0, message.length()); return new BigInteger(1, md.digest()).toString(16); } catch (NoSuchAlgorithmException nsae) { return null; } }
Code Sample 2:
public static String md5(String s) { try { MessageDigest digester = MessageDigest.getInstance("MD5"); digester.update(s.getBytes()); return new BigInteger(1, digester.digest()).toString(16); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } }
|
00
|
Code Sample 1:
private void importDocument(String path, boolean detectParagraphs, Parser parser, ReadingAnnotationFilter filter, String encoding) { try { Reader in = null; int contentlength = 0; if (JGloss.messages.getString("encodings.default").equals(encoding)) encoding = null; String title = ""; try { URL url = new URL(path); URLConnection c = url.openConnection(); contentlength = c.getContentLength(); String enc = c.getContentEncoding(); InputStream is = new BufferedInputStream(c.getInputStream()); if (encoding != null) in = new InputStreamReader(is, encoding); else { in = CharacterEncodingDetector.getReader(is, enc); encoding = ((InputStreamReader) in).getEncoding(); } title = url.getFile(); if (title == null || title.length() == 0) title = path; } catch (MalformedURLException ex) { File f = new File(path); contentlength = (int) f.length(); title = f.getName(); if (title.toLowerCase().endsWith("htm") || title.toLowerCase().endsWith("html")) { } InputStream is = new BufferedInputStream(new FileInputStream(path)); if (encoding != null) in = new InputStreamReader(is, encoding); else { in = CharacterEncodingDetector.getReader(is); encoding = ((InputStreamReader) in).getEncoding(); } } importFromReader(in, detectParagraphs, path, title, filter, parser, CharacterEncodingDetector.guessLength(contentlength, encoding)); } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showConfirmDialog(this, JGloss.messages.getString("error.import.exception", new Object[] { path, ex.getClass().getName(), ex.getLocalizedMessage() }), JGloss.messages.getString("error.import.title"), JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE); if (model.getDocumentName() == null) this.dispose(); } }
Code Sample 2:
public static synchronized String getURLContent(URL url) { Log log = LogUtil.getLog(FileManager.class, "getURLContent"); if (url == null) { throw new IllegalArgumentException("url shouldn't be null!"); } String content = (String) urlCache.get(url); if (content != null) { return content; } try { InputStream is = null; if ("file".equals(url.getProtocol())) { is = new java.io.FileInputStream(url.getFile()); } else { is = url.openStream(); } ByteArrayOutputStream baos = new ByteArrayOutputStream(is.available()); pump(is, baos); content = new String(baos.toByteArray()); urlCache.put(url, content); return content; } catch (FileNotFoundException e) { return null; } catch (Exception e) { e.printStackTrace(); log.error(Translator.getString(XDocletMessages.class, XDocletUtilMessages.EXCEPTION_READING_MERGE_FILE, new String[] { e.toString() })); return null; } }
|
11
|
Code Sample 1:
public static Checksum checksum(File file, Checksum checksum) throws IOException { if (file.isDirectory()) { throw new IllegalArgumentException("Checksums can't be computed on directories"); } InputStream in = null; try { in = new CheckedInputStream(new FileInputStream(file), checksum); IOUtils.copy(in, new NullOutputStream()); } finally { IOUtils.closeQuietly(in); } return checksum; }
Code Sample 2:
public static void encryptFile(String input, String output, String pwd) throws Exception { CipherOutputStream out; InputStream in; Cipher cipher; SecretKey key; byte[] byteBuffer; cipher = Cipher.getInstance("DES"); key = new SecretKeySpec(pwd.getBytes(), "DES"); cipher.init(Cipher.ENCRYPT_MODE, key); in = new FileInputStream(input); out = new CipherOutputStream(new FileOutputStream(output), cipher); byteBuffer = new byte[1024]; for (int n; (n = in.read(byteBuffer)) != -1; out.write(byteBuffer, 0, n)) ; in.close(); out.close(); }
|
00
|
Code Sample 1:
public static InputSource openInputSource(String resource) { InputSource src = null; URL url = findResource(resource); if (url != null) { try { InputStream in = url.openStream(); src = new InputSource(in); src.setSystemId(url.toExternalForm()); } catch (IOException e) { } } return src; }
Code Sample 2:
private static String calculateScenarioMD5(Scenario scenario) throws Exception { MessageDigest md = MessageDigest.getInstance("MD5"); Vector<JTest> allTests = scenario.getTests(); for (JTest t : allTests) { String name = t.getTestName() + t.getTestId(); String parameters = ""; if (t instanceof RunnerTest) { parameters = ((RunnerTest) t).getPropertiesAsString(); } md.update(name.getBytes()); md.update(parameters.getBytes()); } byte[] hash = md.digest(); BigInteger result = new BigInteger(hash); String rc = result.toString(16); return rc; }
|
00
|
Code Sample 1:
public static void main(String[] args) { URL url = null; EventHeap eh = new EventHeap("iw-room2"); Event newEvent; float chan1 = -1, chan2 = -1; try { url = new URL("http://iw--bluetooth-ap/cgi-bin/sens.cgi"); } catch (MalformedURLException e) { } byte buf[] = new byte[1000]; while (true) { try { InputStream in = url.openStream(); int length = in.read(buf); String page = new String(buf); String data = page.substring(290); if (data.startsWith("No Sensors Found")) { Thread.sleep(1000); } else { String sensorID = data.substring(15, 32); String channel1 = data.substring(163, 167); String channel2 = data.substring(266, 270); if (Float.parseFloat(channel1) != chan1) { System.out.println(sensorID); System.out.println("Channel 1:" + channel1); newEvent = new Event("iStuffInputEvent"); newEvent.addField("Device", "Slider"); newEvent.addField("ID", sensorID + ":channel1"); newEvent.addField("Value", channel1); newEvent.addField("Max", String.valueOf(5)); newEvent.addField("Min", String.valueOf(0)); eh.putEvent(newEvent); chan1 = Float.parseFloat(channel1); } } } catch (Exception e) { e.printStackTrace(); } } }
Code Sample 2:
private synchronized void renewToken() { if (!(System.currentTimeMillis() > (lastTokenRenewal + 10000))) return; lastTokenRenewal = System.currentTimeMillis(); String token = null; System.out.println("loading error - refresh token"); byte[] buff = null; try { BufferedInputStream bis = null; System.out.println("Calling timeout : " + getServingURL() + "?token_timeout=true"); URL remoteurl = new URL(getServingURL() + "?token_timeout=true"); URLConnection connection = remoteurl.openConnection(); connection.setRequestProperty("Referer", getServingURL()); int length = connection.getContentLength(); InputStream in = connection.getInputStream(); buff = new byte[length]; int bytesRead = 0; while (bytesRead < length) { bytesRead += in.read(buff, bytesRead, in.available()); } token = new String(buff); } catch (Exception e) { } if (token != null && !token.equals("")) { token = token.trim(); this.info.setToken(token); } else { System.out.println("Token returned was null"); } }
|
11
|
Code Sample 1:
static JSONObject executeMethod(HttpClient httpClient, HttpMethod method, int timeout) throws HttpRequestFailureException, HttpException, IOException, HttpRequestTimeoutException { try { method.getParams().setSoTimeout(timeout * 1000); int status = -1; JSONObject result = null; for (int i = 0; i < RETRY; i++) { System.out.println("Execute method[" + method.getURI() + "](try " + (i + 1) + ")"); status = httpClient.executeMethod(method); if (status == HttpStatus.SC_OK) { InputStream inputStream = method.getResponseBodyAsStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(inputStream, baos); String response = new String(baos.toByteArray(), "UTF-8"); System.out.println(response); result = JSONObject.fromString(response); if (result.has("status")) { String lingrStatus = result.getString("status"); if ("ok".equals(lingrStatus)) { break; } else { try { Thread.sleep(1000); } catch (InterruptedException e) { } } } } else { throw new HttpRequestFailureException(status); } } return result; } catch (SocketTimeoutException e) { throw new HttpRequestTimeoutException(e); } finally { method.releaseConnection(); } }
Code Sample 2:
public void install(Session session) throws Exception { String cfgPath = ConfigurationFactory.getConfigSonInstance().getConfigurationPath(); File setupKson = new File(cfgPath, "setup.kson"); InputStream is = null; if (setupKson.exists()) { log.debug("Reagind kson from " + setupKson.getAbsolutePath()); is = new FileInputStream(setupKson); } else { String ksonCp = "/org/chon/cms/core/setup/setup.kson"; is = Setup.class.getResourceAsStream(ksonCp); log.info("Creating initial setup.kson in " + setupKson.getAbsolutePath()); IOUtils.copy(is, new FileOutputStream(setupKson)); is = new FileInputStream(setupKson); } BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); List<String> lines = new ArrayList<String>(); while (true) { String line = br.readLine(); if (line == null) break; lines.add(line); } List<NodeCreation> ncList = readKSon(lines.toArray(new String[lines.size()])); for (NodeCreation nc : ncList) { try { createNode(session, nc); } catch (Exception e) { System.err.println("error crating node " + nc.path + " -> " + e.getMessage()); } } session.save(); }
|
11
|
Code Sample 1:
public boolean createUser(String username, String password, String name) throws Exception { boolean user_created = false; try { statement = connect.prepareStatement("SELECT COUNT(*) from toepen.users WHERE username = ? LIMIT 1"); statement.setString(1, username); resultSet = statement.executeQuery(); resultSet.next(); if (resultSet.getInt(1) == 0) { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); String password_hash = hash.toString(16); long ctime = System.currentTimeMillis() / 1000; statement = connect.prepareStatement("INSERT INTO toepen.users " + "(username, password, name, ctime) " + "VALUES (?, ?, ?, ?)"); statement.setString(1, username); statement.setString(2, password_hash); statement.setString(3, name); statement.setLong(4, ctime); if (statement.executeUpdate() > 0) { user_created = true; } } } catch (Exception ex) { System.out.println(ex); } finally { close(); return user_created; } }
Code Sample 2:
public String encryptPassword(String password) { StringBuffer encPasswd = new StringBuffer(); try { MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(password.getBytes()); byte[] digest = mdAlgorithm.digest(); for (int i = 0; i < digest.length; i++) { password = Integer.toHexString(255 & digest[i]); if (password.length() < 2) { password = "0" + password; } encPasswd.append(password); } } catch (NoSuchAlgorithmException ex) { } return encPasswd.toString(); }
|
00
|
Code Sample 1:
protected synchronized String encryptThis(String seed, String text) throws EncryptionException { String encryptedValue = null; String textToEncrypt = text; if (seed != null) { textToEncrypt = seed.toLowerCase() + text; } try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(textToEncrypt.getBytes("UTF-8")); encryptedValue = (new BASE64Encoder()).encode(md.digest()); } catch (Exception e) { throw new EncryptionException(e); } return encryptedValue; }
Code Sample 2:
protected ResourceBundle loadBundle(String prefix) { URL url = Thread.currentThread().getContextClassLoader().getResource(prefix + ".properties"); if (url != null) { try { return new PropertyResourceBundle(url.openStream()); } catch (IOException e) { throw ThrowableManagerRegistry.caught(e); } } return null; }
|
11
|
Code Sample 1:
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); }
Code Sample 2:
public void zipFile(String baseDir, String fileName, boolean encrypt) throws Exception { List fileList = getSubFiles(new File(baseDir)); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(fileName + ".temp")); ZipEntry ze = null; byte[] buf = new byte[BUFFER]; byte[] encrypByte = new byte[encrypLength]; int readLen = 0; for (int i = 0; i < fileList.size(); i++) { if (stopZipFile) { zos.close(); File zipFile = new File(fileName + ".temp"); if (zipFile.exists()) zipFile.delete(); break; } File f = (File) fileList.get(i); if (f.getAbsoluteFile().equals(fileName + ".temp")) continue; ze = new ZipEntry(getAbsFileName(baseDir, f)); ze.setSize(f.length()); ze.setTime(f.lastModified()); zos.putNextEntry(ze); InputStream is = new BufferedInputStream(new FileInputStream(f)); readLen = is.read(buf, 0, BUFFER); if (encrypt) { if (readLen >= encrypLength) { System.arraycopy(buf, 0, encrypByte, 0, encrypLength); } else if (readLen > 0) { Arrays.fill(encrypByte, (byte) 0); System.arraycopy(buf, 0, encrypByte, 0, readLen); readLen = encrypLength; } byte[] temp = CryptionControl.getInstance().encryptoECB(encrypByte, rootKey); System.arraycopy(temp, 0, buf, 0, encrypLength); } while (readLen != -1) { zos.write(buf, 0, readLen); readLen = is.read(buf, 0, BUFFER); } is.close(); } zos.close(); File zipFile = new File(fileName + ".temp"); if (zipFile.exists()) zipFile.renameTo(new File(fileName + ".zip")); }
|
11
|
Code Sample 1:
public static void copyFile(File file, File destination) throws Exception { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(file)); out = new BufferedOutputStream(new FileOutputStream(destination)); int c; while ((c = in.read()) != -1) out.write(c); } finally { try { if (out != null) out.close(); } catch (Exception e) { } try { if (in != null) in.close(); } catch (Exception e) { } } }
Code Sample 2:
private static void copyFile(String fromFile, String toFile) throws Exception { FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
|
00
|
Code Sample 1:
private static List retrieveQuotes(Report report, Symbol symbol, String prefix, TradingDate startDate, TradingDate endDate) throws ImportExportException { List quotes = new ArrayList(); String URLString = constructURL(symbol, prefix, startDate, endDate); EODQuoteFilter filter = new GoogleEODQuoteFilter(symbol); PreferencesManager.ProxyPreferences proxyPreferences = PreferencesManager.getProxySettings(); try { URL url = new URL(URLString); InputStreamReader input = new InputStreamReader(url.openStream()); BufferedReader bufferedInput = new BufferedReader(input); String line = bufferedInput.readLine(); while (line != null) { line = bufferedInput.readLine(); if (line != null) { try { EODQuote quote = filter.toEODQuote(line); quotes.add(quote); verify(report, quote); } catch (QuoteFormatException e) { report.addError(Locale.getString("GOOGLE_DISPLAY_URL") + ":" + symbol + ":" + Locale.getString("ERROR") + ": " + e.getMessage()); } } } bufferedInput.close(); } catch (BindException e) { throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); } catch (ConnectException e) { throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); } catch (UnknownHostException e) { throw new ImportExportException(Locale.getString("UNKNOWN_HOST_ERROR", e.getMessage())); } catch (NoRouteToHostException e) { throw new ImportExportException(Locale.getString("DESTINATION_UNREACHABLE_ERROR", e.getMessage())); } catch (MalformedURLException e) { throw new ImportExportException(Locale.getString("INVALID_PROXY_ERROR", proxyPreferences.host, proxyPreferences.port)); } catch (FileNotFoundException e) { } catch (IOException e) { throw new ImportExportException(Locale.getString("ERROR_DOWNLOADING_QUOTES")); } return quotes; }
Code Sample 2:
public static byte[] sendRequestV1(String url, Map<String, Object> params, String secretCode, String method, Map<String, String> files, String encoding, String signMethod, Map<String, String> headers, String contentType) { HttpClient client = new HttpClient(); byte[] result = null; if (method.equalsIgnoreCase("get")) { GetMethod getMethod = new GetMethod(url); if (contentType == null || contentType.equals("")) getMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); else getMethod.setRequestHeader("Content-Type", contentType); if (headers != null && headers.size() > 0) { Iterator<String> keys = headers.keySet().iterator(); while (keys.hasNext()) { String key = keys.next(); getMethod.setRequestHeader(key, headers.get(key)); } } try { NameValuePair[] getData; if (params != null) { if (secretCode == null) getData = new NameValuePair[params.size()]; else getData = new NameValuePair[params.size() + 1]; Iterator<?> iters = params.keySet().iterator(); int i = 0; while (iters.hasNext()) { String key = (String) iters.next(); getData[i] = new NameValuePair(key, params.get(key).toString()); i++; } if (secretCode != null) { boolean isHMac = false; if (signMethod != null && signMethod.equalsIgnoreCase("hmac")) isHMac = true; String sign = EncryptUtil.signature2(params, secretCode, "md5".equalsIgnoreCase(signMethod), isHMac, PARAMETER_SIGN); getData[i] = new NameValuePair(PARAMETER_SIGN, sign); } getMethod.setQueryString(getData); } client.executeMethod(getMethod); ByteArrayOutputStream bout = new ByteArrayOutputStream(); try { InputStream in = getMethod.getResponseBodyAsStream(); byte[] buf = new byte[500]; int count = 0; while ((count = in.read(buf)) > 0) { bout.write(buf, 0, count); } result = bout.toByteArray(); } catch (Exception ex) { ex.printStackTrace(); } finally { if (bout != null) bout.close(); } } catch (Exception ex) { logger.error(ex, ex); } finally { if (getMethod != null) getMethod.releaseConnection(); } } if (method.equalsIgnoreCase("post")) { PostMethod postMethod = new PostMethod(url); if (headers != null && headers.size() > 0) { Iterator<String> keys = headers.keySet().iterator(); while (keys.hasNext()) { String key = keys.next(); postMethod.setRequestHeader(key, headers.get(key)); } } try { if (contentType == null) { if (files != null && files.size() > 0) { Part[] parts; if (secretCode == null) parts = new Part[params.size() + files.size()]; else parts = new Part[params.size() + 1 + files.size()]; Iterator<?> iters = params.keySet().iterator(); int i = 0; while (iters.hasNext()) { String key = (String) iters.next(); parts[i] = new StringPart(key, params.get(key).toString(), "UTF-8"); i++; } if (secretCode != null) { boolean isHMac = false; if (signMethod != null && signMethod.equalsIgnoreCase("hmac")) isHMac = true; String sign = EncryptUtil.signature(params, secretCode, isHMac, PARAMETER_SIGN); parts[i] = new StringPart(PARAMETER_SIGN, sign); i++; } iters = files.keySet().iterator(); while (iters.hasNext()) { String key = (String) iters.next(); if (files.get(key).toString().startsWith("http://")) { InputStream bin = null; ByteArrayOutputStream bout = new ByteArrayOutputStream(); try { URL fileurl = new URL(files.get(key).toString()); bin = fileurl.openStream(); byte[] buf = new byte[500]; int count = 0; while ((count = bin.read(buf)) > 0) { bout.write(buf, 0, count); } parts[i] = new FilePart(key, new ByteArrayPartSource(fileurl.getFile().substring(fileurl.getFile().lastIndexOf("/") + 1), bout.toByteArray())); } catch (Exception ex) { logger.error(ex, ex); } finally { if (bin != null) bin.close(); if (bout != null) bout.close(); } } else parts[i] = new FilePart(key, new File(files.get(key).toString())); i++; } postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams())); } else { NameValuePair[] postData; if (params != null) { if (secretCode == null) postData = new NameValuePair[params.size()]; else postData = new NameValuePair[params.size() + 1]; Iterator<?> iters = params.keySet().iterator(); int i = 0; while (iters.hasNext()) { String key = (String) iters.next(); postData[i] = new NameValuePair(key, params.get(key).toString()); i++; } if (secretCode != null) { boolean isHMac = false; if (signMethod != null && signMethod.equalsIgnoreCase("hmac")) isHMac = true; String sign = EncryptUtil.signature(params, secretCode, isHMac, PARAMETER_SIGN); postData[i] = new NameValuePair(PARAMETER_SIGN, sign); } postMethod.setRequestBody(postData); } if (contentType == null || contentType.equals("")) postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); } } else { String content = (String) params.get(params.keySet().iterator().next()); RequestEntity entiry = new StringRequestEntity(content, contentType, "UTF-8"); postMethod.setRequestEntity(entiry); } client.executeMethod(postMethod); ByteArrayOutputStream bout = new ByteArrayOutputStream(); try { InputStream in = postMethod.getResponseBodyAsStream(); byte[] buf = new byte[500]; int count = 0; while ((count = in.read(buf)) > 0) { bout.write(buf, 0, count); } result = bout.toByteArray(); } catch (Exception ex) { logger.error(ex, ex); } finally { if (bout != null) bout.close(); } } catch (Exception e) { logger.error(e, e); } finally { if (postMethod != null) postMethod.releaseConnection(); } } return result; }
|
11
|
Code Sample 1:
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(); } }
Code Sample 2:
private static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
|
11
|
Code Sample 1:
public void copyFile(final File sourceFile, final File destinationFile) throws FileIOException { final FileChannel sourceChannel; try { sourceChannel = new FileInputStream(sourceFile).getChannel(); } catch (FileNotFoundException exception) { final String message = COPY_FILE_FAILED + sourceFile + " -> " + destinationFile; LOGGER.fatal(message); throw fileIOException(message, sourceFile, exception); } final FileChannel destinationChannel; try { destinationChannel = new FileOutputStream(destinationFile).getChannel(); } catch (FileNotFoundException exception) { final String message = COPY_FILE_FAILED + sourceFile + " -> " + destinationFile; LOGGER.fatal(message); throw fileIOException(message, destinationFile, exception); } try { destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); } catch (Exception exception) { final String message = COPY_FILE_FAILED + sourceFile + " -> " + destinationFile; LOGGER.fatal(message); throw fileIOException(message, null, exception); } finally { if (sourceChannel != null) { try { sourceChannel.close(); } catch (IOException exception) { LOGGER.error("closing source", exception); } } if (destinationChannel != null) { try { destinationChannel.close(); } catch (IOException exception) { LOGGER.error("closing destination", exception); } } } }
Code Sample 2:
public void copyFile(File from, File to) { try { InputStream in = new FileInputStream(from); OutputStream out = new FileOutputStream(to); int readCount; byte[] bytes = new byte[1024]; while ((readCount = in.read(bytes)) != -1) { out.write(bytes, 0, readCount); } out.flush(); in.close(); out.close(); } catch (Exception ex) { throw new BuildException(ex.getMessage(), ex); } }
|
00
|
Code Sample 1:
private static List retrieveQuotes(Report report, Symbol symbol, TradingDate startDate, TradingDate endDate) throws ImportExportException { List quotes = new ArrayList(); String URLString = constructURL(symbol, startDate, endDate); EODQuoteFilter filter = new YahooEODQuoteFilter(symbol); PreferencesManager.ProxyPreferences proxyPreferences = PreferencesManager.loadProxySettings(); try { URL url = new URL(URLString); InputStreamReader input = new InputStreamReader(url.openStream()); BufferedReader bufferedInput = new BufferedReader(input); String line = bufferedInput.readLine(); while (line != null) { line = bufferedInput.readLine(); if (line != null) { try { EODQuote quote = filter.toEODQuote(line); quotes.add(quote); verify(report, quote); } catch (QuoteFormatException e) { report.addError(Locale.getString("YAHOO") + ":" + symbol + ":" + Locale.getString("ERROR") + ": " + e.getMessage()); } } } bufferedInput.close(); } catch (BindException e) { throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); } catch (ConnectException e) { throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); } catch (UnknownHostException e) { throw new ImportExportException(Locale.getString("UNKNOWN_HOST_ERROR", e.getMessage())); } catch (NoRouteToHostException e) { throw new ImportExportException(Locale.getString("DESTINATION_UNREACHABLE_ERROR", e.getMessage())); } catch (MalformedURLException e) { throw new ImportExportException(Locale.getString("INVALID_PROXY_ERROR", proxyPreferences.host, proxyPreferences.port)); } catch (FileNotFoundException e) { } catch (IOException e) { throw new ImportExportException(Locale.getString("ERROR_DOWNLOADING_QUOTES")); } return quotes; }
Code Sample 2:
public static String login() throws Exception { if (sid == null) { String login = ROLAPClientAux.loadProperties().getProperty("user"); String password = ROLAPClientAux.loadProperties().getProperty("password"); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); String password2 = asHexString(md.digest()); String query = "/server/login?user=" + login + "&extern_password=" + password + "&password=" + password2; Vector<String> res = ROLAPClientAux.sendRequest(query); String vals[] = res.get(0).split(";"); sid = vals[0]; } return sid; }
|
00
|
Code Sample 1:
public static String md(String passwd) { MessageDigest md5 = null; String digest = passwd; try { md5 = MessageDigest.getInstance("MD5"); md5.update(passwd.getBytes()); byte[] digestData = md5.digest(); digest = byteArrayToHex(digestData); } catch (NoSuchAlgorithmException e) { LOG.warn("MD5 not supported. Using plain string as password!"); } catch (Exception e) { LOG.warn("Digest creation failed. Using plain string as password!"); } return digest; }
Code Sample 2:
public void execute() throws InstallerException { try { SQLCommand sqlCommand = new SQLCommand(connectionInfo); connection = sqlCommand.getConnection(); connection.setAutoCommit(false); sqlStatement = connection.createStatement(); double size = (double) statements.size(); for (String statement : statements) { sqlStatement.executeUpdate(statement); setCompletedPercentage(getCompletedPercentage() + (1 / size)); } connection.commit(); } catch (SQLException e) { try { connection.rollback(); } catch (SQLException e1) { throw new InstallerException(InstallerException.TRANSACTION_ROLLBACK_ERROR, new Object[] { e.getMessage() }, e); } throw new InstallerException(InstallerException.SQL_EXEC_EXCEPTION, new Object[] { e.getMessage() }, e); } catch (ClassNotFoundException e) { throw new InstallerException(InstallerException.DB_DRIVER_LOAD_ERROR, e); } finally { if (connection != null) { try { sqlStatement.close(); connection.close(); } catch (SQLException e) { } } } }
|
00
|
Code Sample 1:
public String doAdd(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { if (logger.isDebugEnabled()) { logger.debug("doAdd(ActionMapping, ActionForm, HttpServletRequest, HttpServletResponse) - start"); } t_information_EditMap editMap = new t_information_EditMap(); try { t_information_Form vo = null; vo = (t_information_Form) form; vo.setCompany(vo.getCounty()); if ("����".equals(vo.getInfo_type())) { vo.setInfo_level(null); vo.setAlert_level(null); } String str_postFIX = ""; int i_p = 0; editMap.add(vo); try { logger.info("����˾�鱨��"); String[] mobiles = request.getParameterValues("mobiles"); vo.setMobiles(mobiles); SMSService.inforAlert(vo); } catch (Exception e) { logger.error("doAdd(ActionMapping, ActionForm, HttpServletRequest, HttpServletResponse)", e); } String filename = vo.getFile().getFileName(); if (null != filename && !"".equals(filename)) { FormFile file = vo.getFile(); String realpath = getServlet().getServletContext().getRealPath("/"); realpath = realpath.replaceAll("\\\\", "/"); String inforId = vo.getId(); 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(); i_p = file.getFileName().lastIndexOf("."); str_postFIX = file.getFileName().substring(i_p, file.getFileName().length()); String fullPath = realpath + "attach/" + strAppend + str_postFIX; 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(); } } } catch (HibernateException e) { logger.error("doAdd(ActionMapping, ActionForm, HttpServletRequest, HttpServletResponse)", e); ActionErrors errors = new ActionErrors(); errors.add("org.apache.struts.action.GLOBAL_ERROR", new ActionError("error.database.save", e.toString())); saveErrors(request, errors); e.printStackTrace(); request.setAttribute("t_information_Form", form); if (logger.isDebugEnabled()) { logger.debug("doAdd(ActionMapping, ActionForm, HttpServletRequest, HttpServletResponse) - end"); } return "addpage"; } if (logger.isDebugEnabled()) { logger.debug("doAdd(ActionMapping, ActionForm, HttpServletRequest, HttpServletResponse) - end"); } return "aftersave"; }
Code Sample 2:
public static String md5(String word) { MessageDigest alg = null; try { alg = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(ServletUtils.class.getName()).log(Level.SEVERE, null, ex); } alg.reset(); alg.update(word.getBytes()); byte[] digest = alg.digest(); StringBuilder hashedWord = new StringBuilder(); String hx; for (int i = 0; i < digest.length; i++) { hx = Integer.toHexString(0xFF & digest[i]); if (hx.length() == 1) { hx = "0" + hx; } hashedWord.append(hx); } return hashedWord.toString(); }
|
11
|
Code Sample 1:
private void processBasicContent() { String[] packageNames = sourceCollector.getPackageNames(); for (int i = 0; i < packageNames.length; i++) { XdcSource[] sources = sourceCollector.getXdcSources(packageNames[i]); File dir = new File(outputDir, packageNames[i]); dir.mkdirs(); Set pkgDirs = new HashSet(); for (int j = 0; j < sources.length; j++) { XdcSource source = sources[j]; Properties patterns = source.getPatterns(); if (patterns != null) { tables.put("patterns", patterns); } pkgDirs.add(source.getFile().getParentFile()); DialectHandler dialectHandler = source.getDialectHandler(); Writer out = null; try { String sourceFilePath = source.getFile().getAbsolutePath(); source.setProcessingProperties(baseProperties, j > 0 ? sources[j - 1].getFileName() : null, j < sources.length - 1 ? sources[j + 1].getFileName() : null); String rootComment = XslUtils.transformToString(sourceFilePath, XSL_PKG + "/source-header.xsl", tables); source.setRootComment(rootComment); Document htmlDoc = XslUtils.transform(sourceFilePath, encoding, dialectHandler.getXslResourcePath(), tables); if (LOG.isInfoEnabled()) { LOG.info("Processing source file " + sourceFilePath); } out = IOUtils.getWriter(new File(dir, source.getFile().getName() + ".html"), docencoding); XmlUtils.printHtml(out, htmlDoc); if (sourceProcessor != null) { sourceProcessor.processSource(source, encoding, docencoding); } XdcSource.clearProcessingProperties(baseProperties); } catch (XmlException e) { LOG.error(e.getMessage(), e); } catch (IOException e) { LOG.error(e.getMessage(), e); } finally { if (out != null) { try { out.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } } for (Iterator iter = pkgDirs.iterator(); iter.hasNext(); ) { File docFilesDir = new File((File) iter.next(), "xdc-doc-files"); if (docFilesDir.exists() && docFilesDir.isDirectory()) { File targetDir = new File(dir, "xdc-doc-files"); targetDir.mkdirs(); try { IOUtils.copyTree(docFilesDir, targetDir); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } } }
Code Sample 2:
public static void copyFile(File in, File out) { if (!in.exists() || !in.canRead()) { LOGGER.warn("Can't copy file : " + in); return; } if (!out.getParentFile().exists()) { if (!out.getParentFile().mkdirs()) { LOGGER.info("Didn't create parent directories : " + out.getParentFile().getAbsolutePath()); } } if (!out.exists()) { try { out.createNewFile(); } catch (IOException e) { LOGGER.error("Exception creating new file : " + out.getAbsolutePath(), e); } } LOGGER.debug("Copying file : " + in + ", to : " + out); FileChannel inChannel = null; FileChannel outChannel = null; FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream(in); inChannel = fileInputStream.getChannel(); fileOutputStream = new FileOutputStream(out); outChannel = fileOutputStream.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (Exception e) { LOGGER.error("Exception copying file : " + in + ", to : " + out, e); } finally { close(fileInputStream); close(fileOutputStream); if (inChannel != null) { try { inChannel.close(); } catch (Exception e) { LOGGER.error("Exception closing input channel : ", e); } } if (outChannel != null) { try { outChannel.close(); } catch (Exception e) { LOGGER.error("Exception closing output channel : ", e); } } } }
|
11
|
Code Sample 1:
private DataFileType[] getDataFiles(Collection<ContentToSend> contentsToSend) { DataFileType[] files = new DataFileType[contentsToSend.size()]; int fileIndex = 0; for (ContentToSend contentToSend : contentsToSend) { DataFileType dataFile = DataFileType.Factory.newInstance(); dataFile.setFilename(contentToSend.getFileName()); dataFile.setId("D" + fileIndex); dataFile.setMimeType(contentToSend.getMimeType()); dataFile.setContentType(DataFileType.ContentType.EMBEDDED_BASE_64); final StringWriter stringWriter = new StringWriter(); final OutputStream encodeStream = Base64.newEncoder(stringWriter, 0, null); final InputStream is = contentToSend.getInputStream(); try { long sizeCopied = IOUtils.copyLarge(is, encodeStream); dataFile.setSize(BigDecimal.valueOf(sizeCopied)); } catch (IOException e) { throw new RuntimeException("Failed to get input to the file to be sent", e); } finally { IOUtils.closeQuietly(encodeStream); IOUtils.closeQuietly(is); } dataFile.setStringValue(stringWriter.toString()); files[fileIndex++] = dataFile; } return files; }
Code Sample 2:
private void stripOneFilex(File inFile, File outFile) throws IOException { StreamTokenizer reader = new StreamTokenizer(new FileReader(inFile)); BufferedWriter writer = new BufferedWriter(new FileWriter(outFile)); reader.slashSlashComments(false); reader.slashStarComments(false); reader.eolIsSignificant(true); int token; while ((token = reader.nextToken()) != StreamTokenizer.TT_EOF) { switch(token) { case StreamTokenizer.TT_NUMBER: throw new IllegalStateException("didn't expect TT_NUMBER: " + reader.nval); case StreamTokenizer.TT_WORD: System.out.print(reader.sval); writer.write("WORD:" + reader.sval, 0, reader.sval.length()); default: char outChar = (char) reader.ttype; System.out.print(outChar); writer.write(outChar); } } }
|
00
|
Code Sample 1:
public static void main(String[] args) { Usage u = new ccngetmeta(); for (int i = 0; i < args.length - 3; i++) { if (!CommonArguments.parseArguments(args, i, u)) { u.usage(); System.exit(1); } if (CommonParameters.startArg > i + 1) i = CommonParameters.startArg - 1; } if (args.length != CommonParameters.startArg + 3) { u.usage(); System.exit(1); } try { int readsize = 1024; CCNHandle handle = CCNHandle.open(); String metaArg = args[CommonParameters.startArg + 1]; if (!metaArg.startsWith("/")) metaArg = "/" + metaArg; ContentName fileName = MetadataProfile.getLatestVersion(ContentName.fromURI(args[CommonParameters.startArg]), ContentName.fromNative(metaArg), CommonParameters.timeout, handle); if (fileName == null) { System.out.println("File " + args[CommonParameters.startArg] + " does not exist"); System.exit(1); } if (VersioningProfile.hasTerminalVersion(fileName)) { } else { System.out.println("File " + fileName + " does not exist... exiting"); System.exit(1); } File theFile = new File(args[CommonParameters.startArg + 2]); if (theFile.exists()) { System.out.println("Overwriting file: " + args[CommonParameters.startArg + 1]); } FileOutputStream output = new FileOutputStream(theFile); long starttime = System.currentTimeMillis(); CCNInputStream input; if (CommonParameters.unversioned) input = new CCNInputStream(fileName, handle); else input = new CCNFileInputStream(fileName, handle); if (CommonParameters.timeout != null) { input.setTimeout(CommonParameters.timeout); } byte[] buffer = new byte[readsize]; int readcount = 0; long readtotal = 0; while ((readcount = input.read(buffer)) != -1) { readtotal += readcount; output.write(buffer, 0, readcount); output.flush(); } if (CommonParameters.verbose) System.out.println("ccngetfile took: " + (System.currentTimeMillis() - starttime) + "ms"); System.out.println("Retrieved content " + args[CommonParameters.startArg + 1] + " got " + readtotal + " bytes."); System.exit(0); } catch (ConfigurationException e) { System.out.println("Configuration exception in ccngetfile: " + e.getMessage()); e.printStackTrace(); } catch (MalformedContentNameStringException e) { System.out.println("Malformed name: " + args[CommonParameters.startArg] + " " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.out.println("Cannot write file or read content. " + e.getMessage()); e.printStackTrace(); } System.exit(1); }
Code Sample 2:
public void elimina(Pedido pe) throws errorSQL, errorConexionBD { System.out.println("GestorPedido.elimina()"); int id = pe.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM pedido WHERE id=" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorPedido.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorPedido.elimina(): " + e); } }
|
11
|
Code Sample 1:
public static void copyFile(File in, File out, boolean append) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out, append).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
Code Sample 2:
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { ZipInputStream zis = new ZipInputStream(new BufferedInputStream(inputResource.getInputStream())); File targetDirectoryAsFile = new File(targetDirectory); if (!targetDirectoryAsFile.exists()) { FileUtils.forceMkdir(targetDirectoryAsFile); } File target = new File(targetDirectory, targetFile); BufferedOutputStream dest = null; while (zis.getNextEntry() != null) { if (!target.exists()) { target.createNewFile(); } FileOutputStream fos = new FileOutputStream(target); dest = new BufferedOutputStream(fos); IOUtils.copy(zis, dest); dest.flush(); dest.close(); } zis.close(); if (!target.exists()) { throw new IllegalStateException("Could not decompress anything from the archive!"); } return RepeatStatus.FINISHED; }
|
11
|
Code Sample 1:
public static void main(String[] args) throws IOException { File inputFile = new File("D:/farrago.txt"); File outputFile = new File("D:/outagain.txt"); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
Code Sample 2:
private void createScript(File scriptsLocation, String relativePath, String scriptContent) { Writer fileWriter = null; try { File scriptFile = new File(scriptsLocation.getAbsolutePath() + "/" + relativePath); scriptFile.getParentFile().mkdirs(); fileWriter = new FileWriter(scriptFile); IOUtils.copy(new StringReader(scriptContent), fileWriter); } catch (IOException e) { throw new UnitilsException(e); } finally { IOUtils.closeQuietly(fileWriter); } }
|
11
|
Code Sample 1:
public static void fileCopy(File sourceFile, File destFile) throws IOException { FileChannel source = null; FileChannel destination = null; FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(sourceFile); fos = new FileOutputStream(destFile); source = fis.getChannel(); destination = fos.getChannel(); destination.transferFrom(source, 0, source.size()); } finally { fis.close(); fos.close(); if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
00
|
Code Sample 1:
public void actionPerformed(ActionEvent event) { System.out.println("STARTING on" + getQueryField().getText()); try { URL url = new URL(getQueryField().getText()); getResponseField().setText("opening URL"); DataInputStream inputStream = new DataInputStream(url.openStream()); getResponseField().setText("collating response"); String line = inputStream.readLine(); String totalString = ""; while (line != null) { totalString += line + "\n"; line = inputStream.readLine(); } System.out.println("FINISHING"); getResponseField().setText(totalString); System.out.println("FINISHED"); } catch (Exception exception) { getResponseField().setText(exception.getMessage() + "\n"); } }
Code Sample 2:
public boolean getAuth(String content) throws IOException { String resp_remote; try { URL url = new URL(remoteurl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write("md5sum=" + content); writer.close(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); resp_remote = response.toString(); wd.del(); wd.setKey(resp_remote); return true; } else { return false; } } catch (MalformedURLException e) { } catch (IOException e) { } return false; }
|
00
|
Code Sample 1:
public BasicTraceImpl() { out = System.out; traceEnable = new HashMap(); URL url = Hive.getURL("trace.cfg"); if (url != null) try { InputStream input = url.openStream(); BufferedReader in = new BufferedReader(new InputStreamReader(input)); String line; for (line = line = in.readLine(); line != null; line = in.readLine()) { int i = line.indexOf("="); if (i > 0) { String name = line.substring(0, i).trim(); String value = line.substring(i + 1).trim(); traceEnable.put(name, Boolean.valueOf(value).booleanValue() ? ((Object) (Boolean.TRUE)) : ((Object) (Boolean.FALSE))); } } input.close(); } catch (IOException io) { System.out.println(io); } TRACE = getEnable(THIS); }
Code Sample 2:
public static File extract(File source, String filename, File target) { if (source.exists() == false || filename == null || filename.trim().length() < 1 || target == null) return null; boolean isDirectory = (filename.lastIndexOf("/") == filename.length() - 1); try { Map contents = (Map) jarContents.get(source.getPath()); if (contents == null) { contents = new HashMap(); jarContents.put(source.getPath(), contents); ZipInputStream input = new ZipInputStream(new FileInputStream(source)); ZipEntry zipEntry = null; while ((zipEntry = input.getNextEntry()) != null) { if (zipEntry.isDirectory()) continue; contents.put(zipEntry.getName(), zipEntry); } input.close(); } if (isDirectory) { Iterator it = contents.keySet().iterator(); while (it.hasNext()) { String next = (String) it.next(); if (next.startsWith(filename)) { ZipEntry zipEntry = (ZipEntry) contents.get(next); int n = filename.length(); File newTarget = new File(target, zipEntry.getName().substring(n)); extract(source, next, newTarget); } } return target; } ZipEntry entry = (ZipEntry) contents.get(filename); ZipFile input = new ZipFile(source); InputStream in = input.getInputStream(entry); target.getParentFile().mkdirs(); int bytesRead; byte[] buffer = new byte[1024]; FileOutputStream output = new FileOutputStream(target); while ((bytesRead = in.read(buffer)) != -1) output.write(buffer, 0, bytesRead); output.close(); input.close(); return target; } catch (Exception ex) { ex.printStackTrace(); } return null; }
|
11
|
Code Sample 1:
public static boolean copy(File from, File to, Override override) throws IOException { FileInputStream in = null; FileOutputStream out = null; FileChannel srcChannel = null; FileChannel destChannel = null; if (override == null) override = Override.NEWER; switch(override) { case NEVER: if (to.isFile()) return false; break; case NEWER: if (to.isFile() && (from.lastModified() - LASTMODIFIED_DIFF_MILLIS) < to.lastModified()) return false; break; } to.getParentFile().mkdirs(); try { in = new FileInputStream(from); out = new FileOutputStream(to); srcChannel = in.getChannel(); destChannel = out.getChannel(); long position = 0L; long count = srcChannel.size(); while (position < count) { long chunk = Math.min(MAX_IO_CHUNK_SIZE, count - position); position += destChannel.transferFrom(srcChannel, position, chunk); } to.setLastModified(from.lastModified()); return true; } finally { CommonUtils.close(srcChannel); CommonUtils.close(destChannel); CommonUtils.close(out); CommonUtils.close(in); } }
Code Sample 2:
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); } } }
|
00
|
Code Sample 1:
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(); }
Code Sample 2:
public String encrypt(String pstrPlainText) throws Exception { if (pstrPlainText == null) { return ""; } MessageDigest md = MessageDigest.getInstance("SHA"); md.update(pstrPlainText.getBytes("UTF-8")); byte raw[] = md.digest(); return (new BASE64Encoder()).encode(raw); }
|
00
|
Code Sample 1:
public void execute(HttpResponse response) throws HttpException, IOException { StringBuffer content = new StringBuffer(); NodeSet allNodes = membershipRegistry.listAllMembers(); for (Node node : allNodes) { content.append(node.getId().toString()); content.append(SystemUtils.LINE_SEPARATOR); } StringEntity body = new StringEntity(content.toString()); body.setContentType(PLAIN_TEXT_RESPONSE_CONTENT_TYPE); response.setEntity(body); }
Code Sample 2:
public void loadFromInternet(boolean reload) { if (!reload && this.internetScoreGroupModel != null) { return; } loadingFlag = true; ProgressBar settingProgressBar = (ProgressBar) this.activity.findViewById(R.id.settingProgressBar); settingProgressBar.setVisibility(View.VISIBLE); final Timer timer = new Timer(); final Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if (loadingFlag == false) { ProgressBar settingProgressBar = (ProgressBar) BestScoreExpandableListAdapter.this.activity.findViewById(R.id.settingProgressBar); settingProgressBar.setVisibility(View.INVISIBLE); timer.cancel(); } super.handleMessage(msg); } }; final TimerTask task = new TimerTask() { @Override public void run() { Message message = new Message(); handler.sendMessage(message); } }; timer.schedule(task, 1, 50); String httpUrl = Constants.SERVER_URL + "/rollingcard.php?op=viewbestscore"; HttpGet request = new HttpGet(httpUrl); HttpClient httpClient = new DefaultHttpClient(); try { HttpResponse response = httpClient.execute(request); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String entity = EntityUtils.toString(response.getEntity()); String[] itemArray = entity.split(";"); this.internetScoreGroupModel = new ScoreGroupModel(); for (int i = 0; i < itemArray.length; i++) { String[] itemValueArray = itemArray[i].split("\\|"); if (itemValueArray.length != 3) { continue; } ScoreItemModel itemModel = new ScoreItemModel(itemValueArray[0], itemValueArray[1], itemValueArray[2]); this.internetScoreGroupModel.addItem(itemModel); } } } catch (ClientProtocolException e) { this.internetScoreGroupModel = null; e.printStackTrace(); } catch (IOException e) { this.internetScoreGroupModel = null; e.printStackTrace(); } loadingFlag = false; }
|
00
|
Code Sample 1:
private String doUploadFile(String sessionId, File file, String originalFileName) throws UnsupportedEncodingException, IOException { log(INFO, sessionId); log(INFO, file.getPath()); DefaultHttpClient httpclient = new DefaultHttpClient(); UploadFileRequest request = new UploadFileRequest(); request.setSessionId(sessionId); request.setDirectory(UUID.randomUUID().toString()); request.setFileName(originalFileName); URL url = file.toURI().toURL(); URLConnection urlCon = url.openConnection(); XStream writer = new XStream(); writer.setMode(XStream.XPATH_ABSOLUTE_REFERENCES); writer.alias("UploadFileRequest", UploadFileRequest.class); XStream reader = new XStream(); reader.setMode(XStream.XPATH_ABSOLUTE_REFERENCES); reader.alias("UploadFileResponse", UploadFileResponse.class); String strRequest = URLEncoder.encode(reader.toXML(request), "UTF-8"); HttpPost httppost = new HttpPost(MewitProperties.getMewitUrl() + "/resources/uploadFile?REQUEST=" + strRequest); FileEntity fileEntity = new FileEntity(file, urlCon.getContentType()); httppost.setEntity(fileEntity); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); if (entity != null) { String result = URLDecoder.decode(EntityUtils.toString(entity), "UTF-8"); log(INFO, result); UploadFileResponse oResponse = (UploadFileResponse) reader.fromXML(result); return oResponse.getFile(); } return null; }
Code Sample 2:
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()); }
|
11
|
Code Sample 1:
public static OMElement createOMRequest(String file, int count, String[] documentIds) throws Exception { ObjectFactory factory = new ObjectFactory(); SubmitDocumentRequest sdr = factory.createSubmitDocumentRequest(); IdType pid = factory.createIdType(); pid.setRoot("1.3.6.1.4.1.21367.2005.3.7.6fa11e467880478"); sdr.setPatientId(pid); ClassLoader classLoader = JUnitHelper.class.getClassLoader(); DocumentsType documents = factory.createDocumentsType(); for (int i = 0; i < count; ++i) { DocumentType document = factory.createDocumentType(); if ((documentIds != null) && (documentIds.length > i)) { document.setId(documentIds[i]); } CodeType type = factory.createCodeType(); type.setCode("51855-5"); type.setCodeSystem("2.16.840.1.113883.6.1"); document.setType(type); ByteArrayOutputStream bos = new ByteArrayOutputStream(); InputStream is = classLoader.getResourceAsStream(file); assertNotNull(is); IOUtils.copy(is, bos); document.setContent(bos.toByteArray()); documents.getDocument().add(document); } sdr.setDocuments(documents); QName qname = new QName(URIConstants.XDSBRIDGE_URI, "SubmitDocumentRequest"); JAXBContext jc = JAXBContext.newInstance(SubmitDocumentRequest.class); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); JAXBElement element = new JAXBElement(qname, sdr.getClass(), sdr); StringWriter sw = new StringWriter(); marshaller.marshal(element, sw); String xml = sw.toString(); logger.debug(xml); OMElement result = AXIOMUtil.stringToOM(OMAbstractFactory.getOMFactory(), xml); List<OMElement> list = XPathHelper.selectNodes(result, "./ns:Documents/ns:Document/ns:Content", URIConstants.XDSBRIDGE_URI); for (OMElement contentNode : list) { OMText binaryNode = (OMText) contentNode.getFirstOMChild(); if (binaryNode != null) { binaryNode.setOptimize(true); } } return result; }
Code Sample 2:
protected File downloadUpdate(String resource) throws AgentException { RESTCall call = makeRESTCall(resource); call.invoke(); File tmpFile; try { tmpFile = File.createTempFile("controller-update-", ".war", new File(tmpPath)); } catch (IOException e) { throw new AgentException("Failed to create temporary file", e); } InputStream is; try { is = call.getInputStream(); } catch (IOException e) { throw new AgentException("Failed to open input stream", e); } try { FileOutputStream os; try { os = new FileOutputStream(tmpFile); } catch (FileNotFoundException e) { throw new AgentException("Failed to open temporary file for writing", e); } boolean success = false; try { IOUtils.copy(is, os); success = true; } catch (IOException e) { throw new AgentException("Failed to download update", e); } finally { try { os.flush(); os.close(); } catch (IOException e) { if (!success) throw new AgentException("Failed to flush to disk", e); } } } finally { try { is.close(); } catch (IOException e) { log.error("Failed to close input stream", e); } call.disconnect(); } return tmpFile; }
|
11
|
Code Sample 1:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
Code Sample 2:
public static Object fetchCached(String address, int hours) throws MalformedURLException, IOException { String cacheName = md5(address); checkAndCreateDirectoryIfNeeded(); File r = new File(CACHELOCATION + cacheName); Date d = new Date(); long limit = d.getTime() - (1000 * 60 * 60 * hours); if (!r.exists() || (hours != -1 && r.lastModified() < limit)) { InputStream is = (InputStream) fetch(address); FileOutputStream fos = new FileOutputStream(CACHELOCATION + cacheName); int nextChar; while ((nextChar = is.read()) != -1) fos.write((char) nextChar); fos.flush(); } FileInputStream fis = new FileInputStream(CACHELOCATION + cacheName); return fis; }
|
00
|
Code Sample 1:
public static void forEachLine(final URL url, final LineListener lit, final String encoding) { try { ReaderUtils.forEachLine(url.openStream(), lit); } catch (final IOException ioe) { lit.exception(ioe); } }
Code Sample 2:
public static Properties load(URL url) { if (url == null) { return new Properties(); } InputStream in = null; try { in = url.openStream(); Properties ret = new Properties(); ret.load(in); return ret; } catch (IOException e) { throw new RuntimeException(e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOG.error("Error closing", e); } } } }
|
00
|
Code Sample 1:
protected byte[] getBytesForWebPageUsingHTTPClient(String urlString) throws ClientProtocolException, IOException { log("Retrieving url: " + urlString); DefaultHttpClient httpclient = new DefaultHttpClient(); if (this.archiveAccessSpecification.getUserID() != null) { httpclient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), new UsernamePasswordCredentials(this.archiveAccessSpecification.getUserID(), this.archiveAccessSpecification.getUserPassword())); } HttpGet httpget = new HttpGet(urlString); log("about to do request: " + httpget.getRequestLine()); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); log("-------------- Request results --------------"); log("Status line: " + response.getStatusLine()); if (entity != null) { log("Response content length: " + entity.getContentLength()); } log("contents"); byte[] bytes = null; if (entity != null) { bytes = getBytesFromInputStream(entity.getContent()); entity.consumeContent(); } log("Status code :" + response.getStatusLine().getStatusCode()); log(response.getStatusLine().getReasonPhrase()); if (response.getStatusLine().getStatusCode() != 200) return null; return bytes; }
Code Sample 2:
public static void copy(URL url, String outPath) throws IOException { System.out.println("copying from: " + url + " to " + outPath); InputStream in = url.openStream(); FileOutputStream fout = new FileOutputStream(outPath); byte[] data = new byte[8192]; int read = -1; while ((read = in.read(data)) != -1) { fout.write(data, 0, read); } fout.close(); }
|
11
|
Code Sample 1:
public void service(Request req, Response resp) { PrintStream out = null; try { out = resp.getPrintStream(8192); String env = req.getParameter("env"); String regex = req.getParameter("regex"); String deep = req.getParameter("deep"); String term = req.getParameter("term"); String index = req.getParameter("index"); String refresh = req.getParameter("refresh"); String searcher = req.getParameter("searcher"); String grep = req.getParameter("grep"); String fiServerDetails = req.getParameter("fi_server_details"); String serverDetails = req.getParameter("server_details"); String hostDetails = req.getParameter("host_details"); String name = req.getParameter("name"); String show = req.getParameter("show"); String path = req.getPath().getPath(); int page = req.getForm().getInteger("page"); if (path.startsWith("/fs")) { String fsPath = path.replaceAll("^/fs", ""); File realPath = new File("C:\\", fsPath.replace('/', File.separatorChar)); if (realPath.isDirectory()) { out.write(FileSystemDirectory.getContents(new File("c:\\"), fsPath, "/fs")); } else { resp.set("Cache", "no-cache"); FileInputStream fin = new FileInputStream(realPath); FileChannel channel = fin.getChannel(); WritableByteChannel channelOut = resp.getByteChannel(); channel.transferTo(0, realPath.length(), channelOut); channel.close(); fin.close(); System.err.println("Serving " + path + " as " + realPath.getCanonicalPath()); } } else if (path.startsWith("/files/")) { String[] segments = req.getPath().getSegments(); boolean done = false; if (segments.length > 1) { String realPath = req.getPath().getPath(1); File file = context.getFile(realPath); if (file.isFile()) { resp.set("Content-Type", context.getContentType(realPath)); FileInputStream fin = new FileInputStream(file); FileChannel channel = fin.getChannel(); WritableByteChannel channelOut = resp.getByteChannel(); long start = System.currentTimeMillis(); channel.transferTo(0, realPath.length(), channelOut); channel.close(); fin.close(); System.err.println("Time take to write [" + realPath + "] was [" + (System.currentTimeMillis() - start) + "] of size [" + file.length() + "]"); done = true; } } if (!done) { resp.set("Content-Type", "text/plain"); out.println("Can not serve directory: path"); } } else if (path.startsWith("/upload")) { FileItemFactory factory = new DiskFileItemFactory(); FileUpload upload = new FileUpload(factory); RequestAdapter adapter = new RequestAdapter(req); List<FileItem> list = upload.parseRequest(adapter); Map<String, FileItem> map = new HashMap<String, FileItem>(); for (FileItem entry : list) { String fileName = entry.getFieldName(); map.put(fileName, entry); } resp.set("Content-Type", "text/html"); out.println("<html>"); out.println("<body>"); for (int i = 0; i < 10; i++) { Part file = req.getPart("datafile" + (i + 1)); if (file != null && file.isFile()) { String partName = file.getName(); String partFileName = file.getFileName(); File partFile = new File(partFileName); FileItem item = map.get(partName); InputStream in = file.getInputStream(); String fileName = file.getFileName().replaceAll("\\\\", "_").replaceAll(":", "_"); File filePath = new File(fileName); OutputStream fileOut = new FileOutputStream(filePath); byte[] chunk = new byte[8192]; int count = 0; while ((count = in.read(chunk)) != -1) { fileOut.write(chunk, 0, count); } fileOut.close(); in.close(); out.println("<table border='1'>"); out.println("<tr><td><b>File</b></td><td>"); out.println(filePath.getCanonicalPath()); out.println("</tr></td>"); out.println("<tr><td><b>Size</b></td><td>"); out.println(filePath.length()); out.println("</tr></td>"); out.println("<tr><td><b>MD5</b></td><td>"); out.println(Digest.getSignature(Digest.Algorithm.MD5, file.getInputStream())); out.println("<br>"); out.println(Digest.getSignature(Digest.Algorithm.MD5, item.getInputStream())); if (partFile.exists()) { out.println("<br>"); out.println(Digest.getSignature(Digest.Algorithm.MD5, new FileInputStream(partFile))); } out.println("</tr></td>"); out.println("<tr><td><b>SHA1</b></td><td>"); out.println(Digest.getSignature(Digest.Algorithm.SHA1, file.getInputStream())); out.println("<br>"); out.println(Digest.getSignature(Digest.Algorithm.SHA1, item.getInputStream())); if (partFile.exists()) { out.println("<br>"); out.println(Digest.getSignature(Digest.Algorithm.SHA1, new FileInputStream(partFile))); } out.println("</tr></td>"); out.println("<tr><td><b>Header</b></td><td><pre>"); out.println(file.toString().trim()); out.println("</pre></tr></td>"); if (partFileName.toLowerCase().endsWith(".xml")) { String xml = file.getContent(); String formatted = format(xml); String fileFormatName = fileName + ".formatted"; File fileFormatOut = new File(fileFormatName); FileOutputStream formatOut = new FileOutputStream(fileFormatOut); formatOut.write(formatted.getBytes("UTF-8")); out.println("<tr><td><b>Formatted XML</b></td><td><pre>"); out.println("<a href='/" + (fileFormatName) + "'>" + partFileName + "</a>"); out.println("</pre></tr></td>"); formatOut.close(); } out.println("<table>"); } } out.println("</body>"); out.println("</html>"); } else if (path.startsWith("/sql/") && index != null && searcher != null) { String file = req.getPath().getPath(1); File root = searchEngine.index(searcher).getRoot(); SearchEngine engine = searchEngine.index(searcher); File indexFile = getStoredProcIndexFile(engine.getRoot(), index); File search = new File(root, "cpsql"); File source = new File(root, file.replace('/', File.separatorChar)); FindStoredProcs.StoredProcProject storedProcProj = FindStoredProcs.getStoredProcProject(search, indexFile); FindStoredProcs.StoredProc proc = storedProcProj.getStoredProc(source.getName()); resp.set("Content-Type", "text/html"); out.println("<html>"); out.println("<body><pre>"); for (String procName : proc.getReferences()) { FindStoredProcs.StoredProc theProc = storedProcProj.getStoredProc(procName); if (theProc != null) { String url = getRelativeURL(root, theProc.getFile()); out.println("<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'><b>" + theProc.getName() + "</b>"); } } out.println("</pre></body>"); out.println("</html>"); } else if (show != null && index != null && searcher != null) { String authentication = req.getValue("Authorization"); if (authentication == null) { resp.setCode(401); resp.setText("Authorization Required"); resp.set("Content-Type", "text/html"); resp.set("WWW-Authenticate", "Basic realm=\"DTS Subversion Repository\""); out.println("<html>"); out.println("<head>"); out.println("401 Authorization Required"); out.println("</head>"); out.println("<body>"); out.println("<h1>401 Authorization Required</h1>"); out.println("</body>"); out.println("</html>"); } else { resp.set("Content-Type", "text/html"); Principal principal = new PrincipalParser(authentication); String file = show; SearchEngine engine = searchEngine.index(searcher); File root = engine.getRoot(); File javaIndexFile = getJavaIndexFile(root, index); File storedProcIndexFile = getStoredProcIndexFile(root, index); File sql = new File(root, "cpsql"); File source = new File(root, file.replace('/', File.separatorChar)); File javaSource = new File(root, file.replace('/', File.separatorChar)); File canonical = source.getCanonicalFile(); Repository repository = Subversion.login(Scheme.HTTP, principal.getName(), principal.getPassword()); Info info = null; try { info = repository.info(canonical); } catch (Exception e) { e.printStackTrace(); } List<Change> logMessages = new ArrayList<Change>(); try { logMessages = repository.log(canonical); } catch (Exception e) { e.printStackTrace(); } FileInputStream in = new FileInputStream(canonical); List<String> lines = LineStripper.stripLines(in); out.println("<html>"); out.println("<head>"); out.println("<!-- username='" + principal.getName() + "' password='" + principal.getPassword() + "' -->"); out.println("<link rel='stylesheet' type='text/css' href='style.css'>"); out.println("<script src='highlight.js'></script>"); out.println("</head>"); out.println("<body onload=\"sh_highlightDocument('lang/', '.js')\">"); if (info != null) { out.println("<table border='1'>"); out.printf("<tr><td bgcolor=\"#C4C4C4\"><tt>Author</tt></td><td><tt>" + info.author + "</tt></td></tr>"); out.printf("<tr><td bgcolor=\"#C4C4C4\"><tt>Version</tt></td><td><tt>" + info.version + "</tt></td></tr>"); out.printf("<tr><td bgcolor=\"#C4C4C4\"><tt>URL</tt></td><td><tt>" + info.location + "</tt></td></tr>"); out.printf("<tr><td bgcolor=\"#C4C4C4\"><tt>Path</tt></td><td><tt>" + canonical + "</tt></td></tr>"); out.println("</table>"); } out.println("<table border='1''>"); out.println("<tr>"); out.println("<td valign='top' bgcolor=\"#C4C4C4\"><pre>"); FindStoredProcs.StoredProcProject storedProcProj = FindStoredProcs.getStoredProcProject(sql, storedProcIndexFile); FindStoredProcs.StoredProc storedProc = null; FindJavaSources.JavaProject project = null; FindJavaSources.JavaClass javaClass = null; List<FindJavaSources.JavaClass> importList = null; if (file.endsWith(".sql")) { storedProc = storedProcProj.getStoredProc(canonical.getName()); } else if (file.endsWith(".java")) { project = FindJavaSources.getProject(root, javaIndexFile); javaClass = project.getClass(source); importList = project.getImports(javaSource); } for (int i = 0; i < lines.size(); i++) { out.println(i); } out.println("</pre></td>"); out.print("<td valign='top'><pre"); out.print(getJavaScript(file)); out.println(">"); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); String escaped = escapeHtml(line); if (project != null) { for (FindJavaSources.JavaClass entry : importList) { String className = entry.getClassName(); String fullyQualifiedName = entry.getFullyQualifiedName(); if (line.startsWith("import") && line.indexOf(fullyQualifiedName) > -1) { File classFile = entry.getSourceFile(); String url = getRelativeURL(root, classFile); escaped = escaped.replaceAll(fullyQualifiedName + ";", "<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + fullyQualifiedName + "</a>;"); } else if (line.indexOf(className) > -1) { File classFile = entry.getSourceFile(); String url = getRelativeURL(root, classFile); escaped = escaped.replaceAll("\\s" + className + ",", " <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>,"); escaped = escaped.replaceAll("\\s" + className + "\\{", " <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>{"); escaped = escaped.replaceAll("," + className + ",", ",<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>,"); escaped = escaped.replaceAll("," + className + "\\{", ",<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>{"); escaped = escaped.replaceAll("\\s" + className + "\\s", " <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a> "); escaped = escaped.replaceAll("\\(" + className + "\\s", "(<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a> "); escaped = escaped.replaceAll("\\s" + className + "\\.", " <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>."); escaped = escaped.replaceAll("\\(" + className + "\\.", "(<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>."); escaped = escaped.replaceAll("\\s" + className + "\\(", " <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>("); escaped = escaped.replaceAll("\\(" + className + "\\(", "(<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>("); escaped = escaped.replaceAll(">" + className + ",", "><a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>,"); escaped = escaped.replaceAll(">" + className + "\\s", "><a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a> "); escaped = escaped.replaceAll(">" + className + "<", "><a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a><"); escaped = escaped.replaceAll("\\(" + className + "\\);", "(<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>)"); } } } else if (storedProc != null) { Set<String> procSet = storedProc.getTopReferences(); List<String> sortedProcs = new ArrayList(procSet); Collections.sort(sortedProcs, LONGEST_FIRST); for (String procFound : sortedProcs) { if (escaped.indexOf(procFound) != -1) { File nameFile = storedProcProj.getLocation(procFound); if (nameFile != null) { String url = getRelativeURL(root, nameFile); escaped = escaped.replaceAll("\\s" + procFound + "\\s", " <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a> "); escaped = escaped.replaceAll("\\s" + procFound + ",", " <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a>,"); escaped = escaped.replaceAll("\\s" + procFound + ";", " <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a>;"); escaped = escaped.replaceAll("," + procFound + "\\s", ",<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a> "); escaped = escaped.replaceAll("," + procFound + ",", ",<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a>,"); escaped = escaped.replaceAll("," + procFound + ";", ",<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a>;"); escaped = escaped.replaceAll("=" + procFound + "\\s", "=<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a> "); escaped = escaped.replaceAll("=" + procFound + ",", "=<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a>,"); escaped = escaped.replaceAll("=" + procFound + ";", "=<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a>;"); escaped = escaped.replaceAll("." + procFound + "\\s", ".<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a> "); escaped = escaped.replaceAll("." + procFound + ",", ".<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a>,"); escaped = escaped.replaceAll("." + procFound + ";", ".<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a>;"); } else { System.err.println("NOT FOUND: " + procFound); } } } } out.println(escaped); } out.println("</pre></td>"); out.println("</tr>"); out.println("</table>"); out.println("<table border='1'>"); out.printf("<tr><td bgcolor=\"#C4C4C4\"><tt>Revision</tt></td><td bgcolor=\"#C4C4C4\"><tt>Date</tt></td><td bgcolor=\"#C4C4C4\"><tt>Author</tt></td><td bgcolor=\"#C4C4C4\"><tt>Comment</tt></td></tr>"); DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); for (Change message : logMessages) { out.printf("<tr><td><tt>%s</tt></td><td><tt>%s</tt></td><td><tt>%s</tt></td><td><tt>%s</tt></td></tr>%n", message.version, format.format(message.date).replaceAll("\\s", " "), message.author, message.message); } out.println("</table>"); if (project != null) { out.println("<pre>"); for (FindJavaSources.JavaClass entry : importList) { String url = getRelativeURL(root, entry.getSourceFile()); out.println("import <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + entry.getFullyQualifiedName() + "</a> as " + entry.getClassName()); } out.println("</pre>"); } if (storedProc != null) { out.println("<pre>"); for (String procName : storedProc.getReferences()) { FindStoredProcs.StoredProc proc = storedProcProj.getStoredProc(procName); if (proc != null) { String url = getRelativeURL(root, proc.getFile()); out.println("using <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + proc.getName() + "</a>"); } } out.println("</pre>"); } out.println("</form>"); out.println("</body>"); out.println("</html>"); } } else if (path.endsWith(".js") || path.endsWith(".css") || path.endsWith(".formatted")) { path = path.replace('/', File.separatorChar); if (path.endsWith(".formatted")) { resp.set("Content-Type", "text/plain"); } else if (path.endsWith(".js")) { resp.set("Content-Type", "application/javascript"); } else { resp.set("Content-Type", "text/css"); } resp.set("Cache", "no-cache"); WritableByteChannel channelOut = resp.getByteChannel(); File file = new File(".", path).getCanonicalFile(); System.err.println("Serving " + path + " as " + file.getCanonicalPath()); FileChannel sourceChannel = new FileInputStream(file).getChannel(); sourceChannel.transferTo(0, file.length(), channelOut); sourceChannel.close(); channelOut.close(); } else if (env != null && regex != null) { ServerDetails details = config.getEnvironment(env).load(persister, serverDetails != null, fiServerDetails != null, hostDetails != null); List<String> tokens = new ArrayList<String>(); List<Searchable> list = details.search(regex, deep != null, tokens); Collections.sort(tokens, LONGEST_FIRST); for (String token : tokens) { System.out.println("TOKEN: " + token); } resp.set("Content-Type", "text/html"); out.println("<html>"); out.println("<head>"); out.println("<link rel='stylesheet' type='text/css' href='style.css'>"); out.println("<script src='highlight.js'></script>"); out.println("</head>"); out.println("<body onload=\"sh_highlightDocument('lang/', '.js')\">"); writeSearchBox(out, searcher, null, null, regex); out.println("<br>Found " + list.size() + " hits for <b>" + regex + "</b>"); out.println("<table border='1''>"); int countIndex = 1; for (Searchable value : list) { out.println(" <tr><td>" + countIndex++ + " <a href='" + value.getSource() + "'><b>" + value.getSource() + "</b></a></td></tr>"); out.println(" <tr><td><pre class='sh_xml'>"); StringWriter buffer = new StringWriter(); persister.write(value, buffer); String text = buffer.toString(); text = escapeHtml(text); for (String token : tokens) { text = text.replaceAll(token, "<font style='BACKGROUND-COLOR: yellow'>" + token + "</font>"); } out.println(text); out.println(" </pre></td></tr>"); } out.println("</table>"); out.println("</form>"); out.println("</body>"); out.println("</html>"); } else if (index != null && term != null && term.length() > 0) { out.println("<html>"); out.println("<head>"); out.println("<link rel='stylesheet' type='text/css' href='style.css'>"); out.println("<script src='highlight.js'></script>"); out.println("</head>"); out.println("<body onload=\"sh_highlightDocument('lang/', '.js')\">"); writeSearchBox(out, searcher, term, index, null); if (searcher == null) { searcher = searchEngine.getDefaultSearcher(); } if (refresh != null) { SearchEngine engine = searchEngine.index(searcher); File root = engine.getRoot(); File searchIndex = getJavaIndexFile(root, index); FindJavaSources.deleteProject(root, searchIndex); } boolean isRefresh = refresh != null; boolean isGrep = grep != null; boolean isSearchNames = name != null; SearchQuery query = new SearchQuery(index, term, page, isRefresh, isGrep, isSearchNames); List<SearchResult> results = searchEngine.index(searcher).search(query); writeSearchResults(query, searcher, results, out); out.println("</body>"); out.println("</html>"); } else { out.println("<html>"); out.println("<body>"); writeSearchBox(out, searcher, null, null, null); out.println("</body>"); out.println("</html>"); } out.close(); } catch (Exception e) { try { e.printStackTrace(); resp.reset(); resp.setCode(500); resp.setText("Internal Server Error"); resp.set("Content-Type", "text/html"); out.println("<html>"); out.println("<body><h1>Internal Server Error</h1><pre>"); e.printStackTrace(out); out.println("</pre></body>"); out.println("</html>"); out.close(); } catch (Exception ex) { ex.printStackTrace(); } } }
Code Sample 2:
public String getClass(EmeraldjbBean eb) throws EmeraldjbException { Entity entity = (Entity) eb; StringBuffer sb = new StringBuffer(); String myPackage = getPackageName(eb); sb.append("package " + myPackage + ";\n"); sb.append("\n"); DaoValuesGenerator valgen = new DaoValuesGenerator(); String values_class_name = valgen.getClassName(entity); sb.append("\n"); List importList = new Vector(); importList.add("java.io.FileOutputStream;"); importList.add("java.io.FileInputStream;"); importList.add("java.io.DataInputStream;"); importList.add("java.io.DataOutputStream;"); importList.add("java.io.IOException;"); importList.add("java.sql.Date;"); importList.add(valgen.getPackageName(eb) + "." + values_class_name + ";"); Iterator it = importList.iterator(); while (it.hasNext()) { String importName = (String) it.next(); sb.append("import " + importName + "\n"); } sb.append("\n"); String proto_version = entity.getPatternValue(GeneratorConst.PATTERN_STREAM_PROTO_VERSION, "1"); String streamer_class_name = getClassName(entity); sb.append("public class " + streamer_class_name + "\n"); sb.append("{" + "\n public static final int PROTO_VERSION=" + proto_version + ";"); sb.append("\n\n"); StringBuffer f_writer = new StringBuffer(); StringBuffer f_reader = new StringBuffer(); boolean has_times = false; boolean has_strings = false; it = entity.getMembers().iterator(); while (it.hasNext()) { Member member = (Member) it.next(); String nm = member.getName(); String getter = "obj." + methodGenerator.getMethodName(DaoGeneratorUtils.METHOD_GET, member); String setter = "obj." + methodGenerator.getMethodName(DaoGeneratorUtils.METHOD_SET, member); String pad = " "; JTypeBase gen_type = EmdFactory.getJTypeFactory().getJavaType(member.getType()); f_writer.append(gen_type.getToBinaryCode(pad, "dos", getter + "()")); f_reader.append(gen_type.getFromBinaryCode(pad, "din", setter)); } String reader_vars = ""; sb.append("\n public static void writeToFile(String file_nm, " + values_class_name + " obj) throws IOException" + "\n {" + "\n if (file_nm==null || file_nm.length()==0) throw new IOException(\"Bad file name (null or zero length)\");" + "\n if (obj==null) throw new IOException(\"Bad value object parameter, cannot write null object to file\");" + "\n FileOutputStream fos = new FileOutputStream(file_nm);" + "\n DataOutputStream dos = new DataOutputStream(fos);" + "\n writeStream(dos, obj);" + "\n fos.close();" + "\n } // end of writeToFile" + "\n" + "\n public static void readFromFile(String file_nm, " + values_class_name + " obj) throws IOException" + "\n {" + "\n if (file_nm==null || file_nm.length()==0) throw new IOException(\"Bad file name (null or zero length)\");" + "\n if (obj==null) throw new IOException(\"Bad value object parameter, cannot write null object to file\");" + "\n FileInputStream fis = new FileInputStream(file_nm);" + "\n DataInputStream dis = new DataInputStream(fis);" + "\n readStream(dis, obj);" + "\n fis.close();" + "\n } // end of readFromFile" + "\n" + "\n public static void writeStream(DataOutputStream dos, " + values_class_name + " obj) throws IOException" + "\n {" + "\n dos.writeByte(PROTO_VERSION);" + "\n " + f_writer + "\n } // end of writeStream" + "\n" + "\n public static void readStream(DataInputStream din, " + values_class_name + " obj) throws IOException" + "\n {" + "\n int proto_version = din.readByte();" + "\n if (proto_version==" + proto_version + ") readStreamV1(din,obj);" + "\n } // end of readStream" + "\n" + "\n public static void readStreamV1(DataInputStream din, " + values_class_name + " obj) throws IOException" + "\n {" + reader_vars + f_reader + "\n } // end of readStreamV1" + "\n" + "\n} // end of classs" + "\n\n" + "\n//**************" + "\n// End of file" + "\n//**************"); return sb.toString(); }
|
11
|
Code Sample 1:
public String getResourceAsString(String name) throws IOException { String content = null; InputStream stream = aClass.getResourceAsStream(name); if (stream != null) { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); IOUtils.copyAndClose(stream, buffer); content = buffer.toString(); } else { Assert.fail("Resource not available: " + name); } return content; }
Code Sample 2:
public void run() { Vector<Update> updates = new Vector<Update>(); if (dic != null) updates.add(dic); if (gen != null) updates.add(gen); if (res != null) updates.add(res); if (help != null) updates.add(help); for (Iterator iterator = updates.iterator(); iterator.hasNext(); ) { Update update = (Update) iterator.next(); try { File temp = File.createTempFile("fm_" + update.getType(), ".jar"); temp.deleteOnExit(); FileOutputStream out = new FileOutputStream(temp); URL url = new URL(update.getAction()); URLConnection conn = url.openConnection(); com.diccionarioderimas.Utils.setupProxy(conn); InputStream in = conn.getInputStream(); byte[] buffer = new byte[1024]; int read = 0; int total = 0; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); total += read; if (total > 10000) { progressBar.setValue(progressBar.getValue() + total); total = 0; } } out.close(); in.close(); String fileTo = basePath + "diccionariorimas.jar"; if (update.getType() == Update.GENERATOR) fileTo = basePath + "generador.jar"; else if (update.getType() == Update.RESBC) fileTo = basePath + "resbc.me"; else if (update.getType() == Update.HELP) fileTo = basePath + "help.html"; if (update.getType() == Update.RESBC) { Utils.unzip(temp, new File(fileTo)); } else { Utils.copyFile(new FileInputStream(temp), new File(fileTo)); } } catch (Exception e) { e.printStackTrace(); } } setVisible(false); if (gen != null || res != null) { try { new Main(null, basePath, false); } catch (Exception e) { new ErrorDialog(frame, e); } } String restart = ""; if (dic != null) restart += "\nAlgunas de ellas s�lo estar�n disponibles despu�s de reiniciar el diccionario."; JOptionPane.showMessageDialog(frame, "Se han terminado de realizar las actualizaciones." + restart, "Actualizaciones", JOptionPane.INFORMATION_MESSAGE); }
|
11
|
Code Sample 1:
@Override public CasAssembly build() { try { prepareForBuild(); File casWorkingDirectory = casFile.getParentFile(); DefaultCasFileReadIndexToContigLookup read2contigMap = new DefaultCasFileReadIndexToContigLookup(); AbstractDefaultCasFileLookup readIdLookup = new DefaultReadCasFileLookup(casWorkingDirectory); CasParser.parseOnlyMetaData(casFile, MultipleWrapper.createMultipleWrapper(CasFileVisitor.class, read2contigMap, readIdLookup)); ReadWriteDirectoryFileServer consedOut = DirectoryFileServer.createReadWriteDirectoryFileServer(commandLine.getOptionValue("o")); long startTime = DateTimeUtils.currentTimeMillis(); int numberOfCasContigs = read2contigMap.getNumberOfContigs(); for (long i = 0; i < numberOfCasContigs; i++) { File outputDir = consedOut.createNewDir("" + i); Command aCommand = new Command(new File("fakeCommand")); aCommand.setOption("-casId", "" + i); aCommand.setOption("-cas", commandLine.getOptionValue("cas")); aCommand.setOption("-o", outputDir.getAbsolutePath()); aCommand.setOption("-tempDir", tempDir.getAbsolutePath()); aCommand.setOption("-prefix", "temp"); if (commandLine.hasOption("useIllumina")) { aCommand.addFlag("-useIllumina"); } if (commandLine.hasOption("useClosureTrimming")) { aCommand.addFlag("-useClosureTrimming"); } if (commandLine.hasOption("trim")) { aCommand.setOption("-trim", commandLine.getOptionValue("trim")); } if (commandLine.hasOption("trimMap")) { aCommand.setOption("-trimMap", commandLine.getOptionValue("trimMap")); } if (commandLine.hasOption("chromat_dir")) { aCommand.setOption("-chromat_dir", commandLine.getOptionValue("chromat_dir")); } submitSingleCasAssemblyConversion(aCommand); } waitForAllAssembliesToFinish(); int numContigs = 0; int numReads = 0; for (int i = 0; i < numberOfCasContigs; i++) { File countMap = consedOut.getFile(i + "/temp.counts"); Scanner scanner = new Scanner(countMap); if (!scanner.hasNextInt()) { throw new IllegalStateException("single assembly conversion # " + i + " did not complete"); } numContigs += scanner.nextInt(); numReads += scanner.nextInt(); scanner.close(); } System.out.println("num contigs =" + numContigs); System.out.println("num reads =" + numReads); consedOut.createNewDir("edit_dir"); consedOut.createNewDir("phd_dir"); String prefix = commandLine.hasOption("prefix") ? commandLine.getOptionValue("prefix") : DEFAULT_PREFIX; OutputStream masterAceOut = new FileOutputStream(consedOut.createNewFile("edit_dir/" + prefix + ".ace.1")); OutputStream masterPhdOut = new FileOutputStream(consedOut.createNewFile("phd_dir/" + prefix + ".phd.ball")); OutputStream masterConsensusOut = new FileOutputStream(consedOut.createNewFile(prefix + ".consensus.fasta")); OutputStream logOut = new FileOutputStream(consedOut.createNewFile(prefix + ".log")); try { masterAceOut.write(String.format("AS %d %d%n", numContigs, numReads).getBytes()); for (int i = 0; i < numberOfCasContigs; i++) { InputStream aceIn = consedOut.getFileAsStream(i + "/temp.ace"); IOUtils.copy(aceIn, masterAceOut); InputStream phdIn = consedOut.getFileAsStream(i + "/temp.phd"); IOUtils.copy(phdIn, masterPhdOut); InputStream consensusIn = consedOut.getFileAsStream(i + "/temp.consensus.fasta"); IOUtils.copy(consensusIn, masterConsensusOut); IOUtil.closeAndIgnoreErrors(aceIn, phdIn, consensusIn); File tempDir = consedOut.getFile(i + ""); IOUtil.recursiveDelete(tempDir); } consedOut.createNewSymLink("../phd_dir/" + prefix + ".phd.ball", "edit_dir/phd.ball"); if (commandLine.hasOption("chromat_dir")) { consedOut.createNewDir("chromat_dir"); File originalChromatDir = new File(commandLine.getOptionValue("chromat_dir")); for (File chromat : originalChromatDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".scf"); } })) { File newChromatFile = consedOut.createNewFile("chromat_dir/" + FilenameUtils.getBaseName(chromat.getName())); FileOutputStream newChromat = new FileOutputStream(newChromatFile); InputStream in = new FileInputStream(chromat); IOUtils.copy(in, newChromat); IOUtil.closeAndIgnoreErrors(in, newChromat); } } System.out.println("finished making casAssemblies"); for (File traceFile : readIdLookup.getFiles()) { final String name = traceFile.getName(); String extension = FilenameUtils.getExtension(name); if (name.contains("fastq")) { if (!consedOut.contains("solexa_dir")) { consedOut.createNewDir("solexa_dir"); } if (consedOut.contains("solexa_dir/" + name)) { IOUtil.delete(consedOut.getFile("solexa_dir/" + name)); } consedOut.createNewSymLink(traceFile.getAbsolutePath(), "solexa_dir/" + name); } else if ("sff".equals(extension)) { if (!consedOut.contains("sff_dir")) { consedOut.createNewDir("sff_dir"); } if (consedOut.contains("sff_dir/" + name)) { IOUtil.delete(consedOut.getFile("sff_dir/" + name)); } consedOut.createNewSymLink(traceFile.getAbsolutePath(), "sff_dir/" + name); } } long endTime = DateTimeUtils.currentTimeMillis(); logOut.write(String.format("took %s%n", new Period(endTime - startTime)).getBytes()); } finally { IOUtil.closeAndIgnoreErrors(masterAceOut, masterPhdOut, masterConsensusOut, logOut); } } catch (Exception e) { handleException(e); } finally { cleanup(); } return null; }
Code Sample 2:
@Test public void testStandardTee() throws Exception { final byte[] test = "test".getBytes(); final InputStream source = new ByteArrayInputStream(test); final ByteArrayOutputStream destination1 = new ByteArrayOutputStream(); final ByteArrayOutputStream destination2 = new ByteArrayOutputStream(); final TeeOutputStream tee = new TeeOutputStream(destination1, destination2); org.apache.commons.io.IOUtils.copy(source, tee); tee.close(); assertArrayEquals("the two arrays are equals", test, destination1.toByteArray()); assertArrayEquals("the two arrays are equals", test, destination2.toByteArray()); assertEquals("byte count", test.length, tee.getSize()); }
|
00
|
Code Sample 1:
static String fetchURLComposeExternPackageList(String urlpath, String pkglisturlpath) { String link = pkglisturlpath + "package-list"; try { boolean relative = isRelativePath(urlpath); readPackageList((new URL(link)).openStream(), urlpath, relative); } catch (MalformedURLException exc) { return getText("doclet.MalformedURL", link); } catch (IOException exc) { return getText("doclet.URL_error", link); } return null; }
Code Sample 2:
protected static String md5(String s) throws Exception { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(s.getBytes()); byte digest[] = md.digest(); StringBuffer result = new StringBuffer(); for (int i = 0; i < digest.length; i++) { result.append(Integer.toHexString(0xFF & digest[i])); } return result.toString(); }
|
11
|
Code Sample 1:
public static Map<String, File> extractFiles(String input, File tempDirectory) throws IOException { byte data[] = new byte[BUFFER]; BufferedOutputStream out = null; FileInputStream src = new FileInputStream(input); BufferedInputStream in = new BufferedInputStream(src); ZipInputStream zipin = new ZipInputStream(in); Map<String, File> files = new HashMap<String, File>(); ZipEntry entry; while ((entry = zipin.getNextEntry()) != null) { logger.info(TAG + ": entr�e " + entry.getName() + " r�pertoire ? " + entry.isDirectory()); if (entry.isDirectory()) { logger.info(TAG + ": Ajout de l'entr�e pour le r�pertoire: " + entry.getName()); files.put(entry.getName(), extractDirectory(entry.getName(), zipin, tempDirectory)); File f = files.get(entry.getName()); if (f == null) logger.info(TAG + ": NULLL: "); continue; } File tempFile = new File(tempDirectory, entry.getName()); if (tempFile.exists()) tempFile.delete(); tempFile.createNewFile(); FileOutputStream dest = new FileOutputStream(tempFile); out = new BufferedOutputStream(dest, BUFFER); int count; for (int c = zipin.read(); c != -1; c = zipin.read()) dest.write(c); logger.info(TAG + ": Ajout de l'entr�e: " + entry.getName() + " du fichier: " + tempFile.getAbsolutePath()); files.put(entry.getName(), tempFile); out.close(); dest.close(); } zipin.close(); in.close(); src.close(); return files; }
Code Sample 2:
public void actionPerformed(ActionEvent e) { if (path.compareTo("") != 0) { imageName = (path.substring(path.lastIndexOf(File.separator) + 1, path.length())); String name = imageName.substring(0, imageName.lastIndexOf('.')); String extension = imageName.substring(imageName.lastIndexOf('.') + 1, imageName.length()); File imageFile = new File(path); directoryPath = "images" + File.separator + imageName.substring(0, 1).toUpperCase(); File directory = new File(directoryPath); directory.mkdirs(); imagePath = "." + File.separator + "images" + File.separator + imageName.substring(0, 1).toUpperCase() + File.separator + imageName; File newFile = new File(imagePath); if (myImagesBehaviour.equals(TLanguage.getString("TIGManageGalleryDialog.REPLACE_IMAGE"))) { Vector<Vector<String>> aux = TIGDataBase.imageSearchByName(name); if (aux.size() != 0) { int idImage = TIGDataBase.imageKeySearchName(name); TIGDataBase.deleteAsociatedOfImage(idImage); } } if (myImagesBehaviour.equals(TLanguage.getString("TIGManageGalleryDialog.ADD_IMAGE"))) { int i = 1; while (newFile.exists()) { imagePath = "." + File.separator + "images" + File.separator + imageName.substring(0, 1).toUpperCase() + File.separator + imageName.substring(0, imageName.lastIndexOf('.')) + "_" + i + imageName.substring(imageName.lastIndexOf('.'), imageName.length()); name = name + "_" + i; newFile = new File(imagePath); i++; } } imagePathThumb = (imagePath.substring(0, imagePath.lastIndexOf("."))).concat("_th.jpg"); imageName = name + "." + extension; try { FileChannel srcChannel = new FileInputStream(path).getChannel(); FileChannel dstChannel = new FileOutputStream(imagePath).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } TIGDataBase.insertDB(theConcepts, imageName, imageName.substring(0, imageName.lastIndexOf('.'))); image = null; if (imageFile != null) { if (TFileUtils.isJAIRequired(imageFile)) { RenderedOp src = JAI.create("fileload", imageFile.getAbsolutePath()); BufferedImage bufferedImage = src.getAsBufferedImage(); image = new ImageIcon(bufferedImage); } else { image = new ImageIcon(imageFile.getAbsolutePath()); } if (image.getImageLoadStatus() == MediaTracker.ERRORED) { int choosenOption = JOptionPane.NO_OPTION; choosenOption = JOptionPane.showConfirmDialog(null, TLanguage.getString("TIGInsertImageAction.MESSAGE"), TLanguage.getString("TIGInsertImageAction.NAME"), JOptionPane.CLOSED_OPTION, JOptionPane.ERROR_MESSAGE); } else { createThumbnail(); } } } }
|
00
|
Code Sample 1:
public void delete(DeleteInterceptorChain chain, DistinguishedName dn, LDAPConstraints constraints) throws LDAPException { Connection con = (Connection) chain.getRequest().get(JdbcInsert.MYVD_DB_CON + this.dbInsertName); if (con == null) { throw new LDAPException("Operations Error", LDAPException.OPERATIONS_ERROR, "No Database Connection"); } try { con.setAutoCommit(false); String uid = ((RDN) dn.getDN().getRDNs().get(0)).getValue(); PreparedStatement ps = con.prepareStatement(this.deleteSQL); ps.setString(1, uid); ps.executeUpdate(); con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { throw new LDAPException("Could not delete entry or rollback transaction", LDAPException.OPERATIONS_ERROR, e.toString(), e); } throw new LDAPException("Could not delete entry", LDAPException.OPERATIONS_ERROR, e.toString(), e); } }
Code Sample 2:
public static String getHash(String text) { if (text == null) return null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(text.getBytes()); byte[] hashedTextBytes = md.digest(); BigInteger hashedTextBigInteger = new BigInteger(1, hashedTextBytes); String hashedTextString = hashedTextBigInteger.toString(16); return hashedTextString; } catch (NoSuchAlgorithmException e) { LOG.warning(e.toString()); return null; } }
|
00
|
Code Sample 1:
public void run() { if (!shouldLogin) { u.p("skipping the auto-login"); return; } try { u.p("logging in to the server"); String query = "hostname=blahfoo2.com" + "&osname=" + URLEncoder.encode(System.getProperty("os.name"), "UTF-8") + "&javaver=" + URLEncoder.encode(System.getProperty("java.runtime.version"), "UTF-8") + "&timezone=" + URLEncoder.encode(TimeZone.getDefault().getID(), "UTF-8"); u.p("unencoded query: \n" + query); String login_url = "http://joshy.org:8088/org.glossitopeTracker/login.jsp?"; String url = login_url + query; u.p("final encoded url = \n" + url); InputStream in = new URL(url).openStream(); byte[] buf = new byte[256]; while (true) { int n = in.read(buf); if (n == -1) break; for (int i = 0; i < n; i++) { } } } catch (MalformedURLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } }
Code Sample 2:
private void resourceDirectoryCopy(String resource, IProject project, String target, IProgressMonitor monitor) throws URISyntaxException, IOException, CoreException { if (!target.endsWith("/")) { target += "/"; } String res = resource; if (!res.endsWith("/")) ; { res += "/"; } Enumeration<URL> it = bundle.findEntries(resource, "*", false); while (it.hasMoreElements()) { URL url = it.nextElement(); File f = new File(FileLocator.toFileURL(url).toURI()); String fName = f.getName(); boolean skip = false; for (String skiper : skipList) { if (fName.equals(skiper)) { skip = true; break; } } if (skip) { continue; } String targetName = target + fName; if (f.isDirectory()) { IFolder folder = project.getFolder(targetName); if (!folder.exists()) { folder.create(true, true, monitor); } resourceDirectoryCopy(res + f.getName(), project, targetName, monitor); } else if (f.isFile()) { IFile targetFile = project.getFile(targetName); InputStream is = null; try { is = url.openStream(); if (targetFile.exists()) { targetFile.setContents(is, true, false, monitor); } else { targetFile.create(is, true, monitor); } } catch (Exception e) { throw new IOException(e); } finally { if (is != null) { is.close(); } } } } }
|
11
|
Code Sample 1:
public static long checksum(IFile file) throws IOException { InputStream contents; try { contents = file.getContents(); } catch (CoreException e) { throw new CausedIOException("Failed to calculate checksum.", e); } CheckedInputStream in = new CheckedInputStream(contents, new Adler32()); try { IOUtils.copy(in, new NullOutputStream()); } catch (IOException e) { throw new CausedIOException("Failed to calculate checksum.", e); } finally { IOUtils.closeQuietly(in); } return in.getChecksum().getValue(); }
Code Sample 2:
public static File writeInternalFile(Context cx, URL url, String dir, String filename) { FileOutputStream fos = null; File fi = null; try { fi = newInternalFile(cx, dir, filename); fos = FileUtils.openOutputStream(fi); int length = IOUtils.copy(url.openStream(), fos); log(length + " bytes copyed."); } catch (IOException e) { AIOUtils.log("", e); } finally { try { fos.close(); } catch (IOException e) { AIOUtils.log("", e); } } return fi; }
|
00
|
Code Sample 1:
protected void processAnnotationsJndi(URL url) { try { URLConnection urlConn = url.openConnection(); DirContextURLConnection dcUrlConn; if (!(urlConn instanceof DirContextURLConnection)) { sm.getString("contextConfig.jndiUrlNotDirContextConn", url); return; } dcUrlConn = (DirContextURLConnection) urlConn; dcUrlConn.setUseCaches(false); String type = dcUrlConn.getHeaderField(ResourceAttributes.TYPE); if (ResourceAttributes.COLLECTION_TYPE.equals(type)) { Enumeration<String> dirs = dcUrlConn.list(); while (dirs.hasMoreElements()) { String dir = dirs.nextElement(); URL dirUrl = new URL(url.toString() + '/' + dir); processAnnotationsJndi(dirUrl); } } else { if (url.getPath().endsWith(".class")) { InputStream is = null; try { is = dcUrlConn.getInputStream(); processAnnotationsStream(is); } catch (IOException e) { logger.error(sm.getString("contextConfig.inputStreamJndi", url), e); } finally { if (is != null) { try { is.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } } } } } catch (IOException e) { logger.error(sm.getString("contextConfig.jndiUrl", url), e); } }
Code Sample 2:
void copyFileAscii(String src, String dest) { try { File inputFile = new File(src); File outputFile = new File(dest); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception ex) { System.err.println(ex.toString()); } }
|
11
|
Code Sample 1:
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { PrintWriter writer = null; InputStream is = null; FileOutputStream fos = null; try { writer = response.getWriter(); } catch (IOException ex) { log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } String filename = request.getHeader("X-File-Name"); try { is = request.getInputStream(); fos = new FileOutputStream(new File(targetPath + filename)); IOUtils.copy(is, fos); response.setStatus(HttpServletResponse.SC_OK); writer.print("{success: true}"); } catch (FileNotFoundException ex) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); }
Code Sample 2:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
|
11
|
Code Sample 1:
protected PredicateAnnotationRecord generatePredicateAnnotationRecord(PredicateAnnotationRecord par, String miDescriptor) { String annotClass = par.annotation.getType().substring(1, par.annotation.getType().length() - 1).replace('/', '.'); String methodName = getMethodName(par); String hashKey = annotClass + CLASS_SIG_SEPARATOR_STRING + methodName; PredicateAnnotationRecord gr = _generatedPredicateRecords.get(hashKey); if (gr != null) { _sharedAddData.cacheInfo.incCombinePredicateCacheHit(); return gr; } else { _sharedAddData.cacheInfo.incCombinePredicateCacheMiss(); } String predicateClass = ((_predicatePackage.length() > 0) ? (_predicatePackage + ".") : "") + annotClass + "Pred"; ClassFile predicateCF = null; File clonedFile = new File(_predicatePackageDir, annotClass.replace('.', '/') + "Pred.class"); if (clonedFile.exists() && clonedFile.isFile() && clonedFile.canRead()) { try { predicateCF = new ClassFile(new FileInputStream(clonedFile)); } catch (IOException ioe) { throw new ThreadCheckException("Could not open predicate class file, source=" + clonedFile, ioe); } } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { _templatePredicateClassFile.write(baos); predicateCF = new ClassFile(new ByteArrayInputStream(baos.toByteArray())); } catch (IOException ioe) { throw new ThreadCheckException("Could not open predicate template class file", ioe); } } clonedFile.getParentFile().mkdirs(); final ArrayList<String> paramNames = new ArrayList<String>(); final HashMap<String, String> paramTypes = new HashMap<String, String>(); performCombineTreeWalk(par, new ILambda.Ternary<Object, String, String, AAnnotationsAttributeInfo.Annotation.AMemberValue>() { public Object apply(String param1, String param2, AAnnotationsAttributeInfo.Annotation.AMemberValue param3) { paramNames.add(param1); paramTypes.put(param1, param2); return null; } }, ""); ArrayList<PredicateAnnotationRecord> memberPARs = new ArrayList<PredicateAnnotationRecord>(); for (String key : par.combinedPredicates.keySet()) { for (PredicateAnnotationRecord memberPAR : par.combinedPredicates.get(key)) { if ((memberPAR.predicateClass != null) && (memberPAR.predicateMI != null)) { memberPARs.add(memberPAR); } else { memberPARs.add(generatePredicateAnnotationRecord(memberPAR, miDescriptor)); } } } AUTFPoolInfo predicateClassNameItem = new ASCIIPoolInfo(predicateClass.replace('.', '/'), predicateCF.getConstantPool()); int[] l = predicateCF.addConstantPoolItems(new APoolInfo[] { predicateClassNameItem }); predicateClassNameItem = predicateCF.getConstantPoolItem(l[0]).execute(CheckUTFVisitor.singleton(), null); ClassPoolInfo predicateClassItem = new ClassPoolInfo(predicateClassNameItem, predicateCF.getConstantPool()); l = predicateCF.addConstantPoolItems(new APoolInfo[] { predicateClassItem }); predicateClassItem = predicateCF.getConstantPoolItem(l[0]).execute(CheckClassVisitor.singleton(), null); predicateCF.setThisClass(predicateClassItem); StringBuilder sb = new StringBuilder(); sb.append("(Ljava/lang/Object;"); if (par.passArguments) { sb.append("[Ljava/lang/Object;"); } for (String key : paramNames) { sb.append(paramTypes.get(key)); } sb.append(")Z"); String methodDesc = sb.toString(); MethodInfo templateMI = null; MethodInfo predicateMI = null; for (MethodInfo mi : predicateCF.getMethods()) { if ((mi.getName().toString().equals(methodName)) && (mi.getDescriptor().toString().equals(methodDesc))) { predicateMI = mi; break; } else if ((mi.getName().toString().equals("template")) && (mi.getDescriptor().toString().startsWith("(")) && (mi.getDescriptor().toString().endsWith(")Z"))) { templateMI = mi; } } if ((templateMI == null) && (predicateMI == null)) { throw new ThreadCheckException("Could not find template predicate method in class file"); } if (predicateMI == null) { AUTFPoolInfo namecpi = new ASCIIPoolInfo(methodName, predicateCF.getConstantPool()); l = predicateCF.addConstantPoolItems(new APoolInfo[] { namecpi }); namecpi = predicateCF.getConstantPoolItem(l[0]).execute(CheckUTFVisitor.singleton(), null); AUTFPoolInfo descpi = new ASCIIPoolInfo(methodDesc, predicateCF.getConstantPool()); l = predicateCF.addConstantPoolItems(new APoolInfo[] { descpi }); descpi = predicateCF.getConstantPoolItem(l[0]).execute(CheckUTFVisitor.singleton(), null); ArrayList<AAttributeInfo> list = new ArrayList<AAttributeInfo>(); for (AAttributeInfo a : templateMI.getAttributes()) { try { AAttributeInfo clonedA = (AAttributeInfo) a.clone(); list.add(clonedA); } catch (CloneNotSupportedException e) { throw new InstrumentorException("Could not clone method attributes"); } } predicateMI = new MethodInfo(templateMI.getAccessFlags(), namecpi, descpi, list.toArray(new AAttributeInfo[] {})); predicateCF.getMethods().add(predicateMI); CodeAttributeInfo.CodeProperties props = predicateMI.getCodeAttributeInfo().getProperties(); props.maxLocals += paramTypes.size() + 1 + (par.passArguments ? 1 : 0); InstructionList il = new InstructionList(predicateMI.getCodeAttributeInfo().getCode()); if ((par.combineMode == Combine.Mode.OR) || (par.combineMode == Combine.Mode.XOR) || (par.combineMode == Combine.Mode.IMPLIES)) { il.insertInstr(new GenericInstruction(Opcode.ICONST_0), predicateMI.getCodeAttributeInfo()); } else { il.insertInstr(new GenericInstruction(Opcode.ICONST_1), predicateMI.getCodeAttributeInfo()); } boolean res; res = il.advanceIndex(); assert res == true; int accumVarIndex = props.maxLocals - 1; AInstruction loadAccumInstr; AInstruction storeAccumInstr; if (accumVarIndex < 256) { loadAccumInstr = new GenericInstruction(Opcode.ILOAD, (byte) accumVarIndex); storeAccumInstr = new GenericInstruction(Opcode.ISTORE, (byte) accumVarIndex); } else { byte[] bytes = new byte[] { Opcode.ILOAD, 0, 0 }; Types.bytesFromShort((short) accumVarIndex, bytes, 1); loadAccumInstr = new WideInstruction(bytes); bytes[0] = Opcode.ISTORE; storeAccumInstr = new WideInstruction(bytes); } il.insertInstr(storeAccumInstr, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; int maxStack = 0; int paramIndex = 1; int lvIndex = 1; if (par.passArguments) { lvIndex += 1; } int memberCount = 0; for (PredicateAnnotationRecord memberPAR : memberPARs) { ++memberCount; il.insertInstr(new GenericInstruction(Opcode.ALOAD_0), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; int curStack = 1; if (memberPAR.passArguments) { if (par.passArguments) { il.insertInstr(new GenericInstruction(Opcode.ALOAD_1), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; curStack += 1; } } for (int paramNameIndex = 0; paramNameIndex < memberPAR.paramNames.size(); ++paramNameIndex) { String t = memberPAR.paramTypes.get(memberPAR.paramNames.get(paramNameIndex)); if (t.length() == 0) { throw new ThreadCheckException("Length of parameter type no. " + paramIndex + " string is 0 in " + predicateMI.getName() + " in class " + predicateCF.getThisClassName()); } byte opcode; int nextLVIndex = lvIndex; switch(t.charAt(0)) { case 'I': case 'B': case 'C': case 'S': case 'Z': opcode = Opcode.ILOAD; nextLVIndex += 1; curStack += 1; break; case 'F': opcode = Opcode.FLOAD; nextLVIndex += 1; curStack += 1; break; case '[': case 'L': opcode = Opcode.ALOAD; nextLVIndex += 1; curStack += 1; break; case 'J': opcode = Opcode.LLOAD; nextLVIndex += 2; curStack += 2; break; case 'D': opcode = Opcode.DLOAD; nextLVIndex += 2; curStack += 2; break; default: throw new ThreadCheckException("Parameter type no. " + paramIndex + ", " + t + ", is unknown in " + predicateMI.getName() + " in class " + predicateCF.getThisClassName()); } AInstruction load = Opcode.getShortestLoadStoreInstruction(opcode, (short) lvIndex); il.insertInstr(load, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; ++paramIndex; lvIndex = nextLVIndex; } if (curStack > maxStack) { maxStack = curStack; } ReferenceInstruction predicateCallInstr = new ReferenceInstruction(Opcode.INVOKESTATIC, (short) 0); int predicateCallIndex = predicateCF.addMethodToConstantPool(memberPAR.predicateClass.replace('.', '/'), memberPAR.predicateMI.getName().toString(), memberPAR.predicateMI.getDescriptor().toString()); predicateCallInstr.setReference(predicateCallIndex); il.insertInstr(predicateCallInstr, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; if ((par.combineMode == Combine.Mode.NOT) || ((par.combineMode == Combine.Mode.IMPLIES) && (memberCount == 1))) { il.insertInstr(new GenericInstruction(Opcode.ICONST_1), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; il.insertInstr(new GenericInstruction(Opcode.SWAP), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; il.insertInstr(new GenericInstruction(Opcode.ISUB), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; } il.insertInstr(loadAccumInstr, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; if (par.combineMode == Combine.Mode.OR) { il.insertInstr(new GenericInstruction(Opcode.IOR), predicateMI.getCodeAttributeInfo()); } else if ((par.combineMode == Combine.Mode.AND) || (par.combineMode == Combine.Mode.NOT)) { il.insertInstr(new GenericInstruction(Opcode.IAND), predicateMI.getCodeAttributeInfo()); } else if (par.combineMode == Combine.Mode.XOR) { il.insertInstr(new GenericInstruction(Opcode.IADD), predicateMI.getCodeAttributeInfo()); } else if (par.combineMode == Combine.Mode.IMPLIES) { il.insertInstr(new GenericInstruction(Opcode.IOR), predicateMI.getCodeAttributeInfo()); } else { assert false; } res = il.advanceIndex(); assert res == true; il.insertInstr(storeAccumInstr, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; } if (par.combineMode == Combine.Mode.XOR) { il.insertInstr(loadAccumInstr, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; il.insertInstr(new GenericInstruction(Opcode.ICONST_1), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; il.insertInstr(new GenericInstruction(Opcode.ICONST_0), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; WideBranchInstruction br2 = new WideBranchInstruction(Opcode.GOTO_W, il.getIndex() + 1); il.insertInstr(br2, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; int jumpIndex = il.getIndex(); il.insertInstr(new GenericInstruction(Opcode.ICONST_1), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; res = il.rewindIndex(3); assert res == true; BranchInstruction br1 = new BranchInstruction(Opcode.IF_ICMPEQ, jumpIndex); il.insertInstr(br1, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(4); assert res == true; } else { il.insertInstr(loadAccumInstr, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; } il.deleteInstr(predicateMI.getCodeAttributeInfo()); predicateMI.getCodeAttributeInfo().setCode(il.getCode()); props.maxStack = Math.max(maxStack, 2); predicateMI.getCodeAttributeInfo().setProperties(props.maxStack, props.maxLocals); try { FileOutputStream fos = new FileOutputStream(clonedFile); predicateCF.write(fos); fos.close(); } catch (IOException e) { throw new ThreadCheckException("Could not write cloned predicate class file, target=" + clonedFile); } } gr = new PredicateAnnotationRecord(par.annotation, predicateClass, predicateMI, paramNames, paramTypes, new ArrayList<AAnnotationsAttributeInfo.Annotation.AMemberValue>(), par.passArguments, null, new HashMap<String, ArrayList<PredicateAnnotationRecord>>()); _generatedPredicateRecords.put(hashKey, gr); return gr; }
Code Sample 2:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
|
11
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
private static void copyFile(File sourceFile, File destFile) { try { 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(); } } } catch (Exception e) { throw new RuntimeException(e); } }
|
11
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
public void actionPerformed(ActionEvent e) { int returnVal = chooser.showSaveDialog(jd); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); String fileName = file.getPath(); String ext = StringUtil.getLowerExtension(fileName); if (!"png".equals(ext)) { fileName += ".png"; file = new File(fileName); } boolean doIt = true; if (file.exists()) { int i = JOptionPane.showConfirmDialog(jd, getMessage("warn_file_exist")); if (i != JOptionPane.YES_OPTION) doIt = false; } else if (!file.getParentFile().exists()) { doIt = file.getParentFile().mkdirs(); } if (doIt) { FileChannel src = null; FileChannel dest = null; try { src = new FileInputStream(imageURL.getPath()).getChannel(); dest = new FileOutputStream(fileName).getChannel(); src.transferTo(0, src.size(), dest); } catch (FileNotFoundException e1) { warn(jd, getMessage("err_no_source_file")); } catch (IOException e2) { warn(jd, getMessage("err_output_target")); } finally { try { if (src != null) src.close(); } catch (IOException e1) { } try { if (dest != null) dest.close(); } catch (IOException e1) { } src = null; dest = null; } } } }
|
00
|
Code Sample 1:
public void connect() throws IOException { try { URL url = new URL(pluginUrl); connection = (HttpURLConnection) url.openConnection(); sendNotification(DownloadState.CONNECTION_ESTABLISHED); contentLength = connection.getContentLength(); sendNotification(DownloadState.CONTENT_LENGTH_SET); downloadedBytes = 0; } catch (java.io.IOException e) { e.printStackTrace(); throw e; } }
Code Sample 2:
@SuppressWarnings("unchecked") private void appendAttachments(final Part part) throws MessagingException, IOException { if (part.isMimeType("message/*")) { JcrMessage jcrMessage = new JcrMessage(); Message attachedMessage = null; if (part.getContent() instanceof Message) { attachedMessage = (Message) part.getContent(); } else { attachedMessage = new MStorMessage(null, (InputStream) part.getContent()); } jcrMessage.setFlags(attachedMessage.getFlags()); jcrMessage.setHeaders(attachedMessage.getAllHeaders()); jcrMessage.setReceived(attachedMessage.getReceivedDate()); jcrMessage.setExpunged(attachedMessage.isExpunged()); jcrMessage.setMessage(attachedMessage); messages.add(jcrMessage); } else if (part.isMimeType("multipart/*")) { Multipart multi = (Multipart) part.getContent(); for (int i = 0; i < multi.getCount(); i++) { appendAttachments(multi.getBodyPart(i)); } } else if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition()) || StringUtils.isNotEmpty(part.getFileName())) { JcrFile attachment = new JcrFile(); String name = null; if (StringUtils.isNotEmpty(part.getFileName())) { name = part.getFileName(); for (JcrFile attach : attachments) { if (attach.getName().equals(name)) { return; } } } else { String[] contentId = part.getHeader("Content-Id"); if (contentId != null && contentId.length > 0) { name = contentId[0]; } else { name = "attachment"; } } int count = 0; for (JcrFile attach : attachments) { if (attach.getName().equals(name)) { count++; } } if (count > 0) { name += "_" + count; } attachment.setName(name); ByteArrayOutputStream pout = new ByteArrayOutputStream(); IOUtils.copy(part.getInputStream(), pout); attachment.setDataProvider(new JcrDataProviderImpl(TYPE.BYTES, pout.toByteArray())); attachment.setMimeType(part.getContentType()); attachment.setLastModified(java.util.Calendar.getInstance()); attachments.add(attachment); } }
|
00
|
Code Sample 1:
public static void fileCopy(File src, File dest) throws IOException { IOException xforward = null; FileInputStream fis = null; FileOutputStream fos = null; FileChannel fcin = null; FileChannel fcout = null; try { fis = new FileInputStream(src); fos = new FileOutputStream(dest); fcin = fis.getChannel(); fcout = fos.getChannel(); final int MB32 = 32 * 1024 * 1024; long size = fcin.size(); long position = 0; while (position < size) { position += fcin.transferTo(position, MB32, fcout); } } catch (IOException xio) { xforward = xio; } finally { if (fis != null) try { fis.close(); fis = null; } catch (IOException xio) { } if (fos != null) try { fos.close(); fos = null; } catch (IOException xio) { } if (fcin != null && fcin.isOpen()) try { fcin.close(); fcin = null; } catch (IOException xio) { } if (fcout != null && fcout.isOpen()) try { fcout.close(); fcout = null; } catch (IOException xio) { } } if (xforward != null) { throw xforward; } }
Code Sample 2:
public byte[] loadClassFirst(final String className) { if (className.equals("com.sun.sgs.impl.kernel.KernelContext")) { final URL url = Thread.currentThread().getContextClassLoader().getResource("com/sun/sgs/impl/kernel/KernelContext.0.9.6.class.bin"); if (url != null) { try { return StreamUtil.read(url.openStream()); } catch (IOException e) { } } throw new IllegalStateException("Unable to load KernelContext.0.9.6.class.bin"); } return null; }
|
00
|
Code Sample 1:
private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } }
Code Sample 2:
private Image2D resolvePNG(URI uri) { Image2D image2D = null; if (uri.getScheme() != null) { try { URL url = new URL(uri.toString()); InputStream is = url.openStream(); BufferedImage image = PNGDecoder.decode(is); int imageType = Image2D.RGB; if (image.getType() == BufferedImage.TYPE_INT_RGB) imageType = Image2D.RGB; else if (image.getType() == BufferedImage.TYPE_INT_ARGB) imageType = Image2D.RGBA; image2D = new Image2D(imageType, image); } catch (IOException ex) { } } else { String path = uri.getPath(); File file = new File(path); if (file.getAbsoluteFile().exists()) { try { FileInputStream is = new FileInputStream(file); BufferedImage image = PNGDecoder.decode(is); int imageType = Image2D.RGB; if (image.getType() == BufferedImage.TYPE_INT_RGB) imageType = Image2D.RGB; else if (image.getType() == BufferedImage.TYPE_INT_ARGB) imageType = Image2D.RGBA; image2D = new Image2D(imageType, image); } catch (FileNotFoundException ex) { } catch (IOException ex) { } } } return image2D; }
|
11
|
Code Sample 1:
private static String hashToMD5(String sig) { try { MessageDigest lDigest = MessageDigest.getInstance("MD5"); lDigest.update(sig.getBytes()); BigInteger lHashInt = new BigInteger(1, lDigest.digest()); return String.format("%1$032X", lHashInt).toLowerCase(); } catch (NoSuchAlgorithmException lException) { throw new RuntimeException(lException); } }
Code Sample 2:
public String encryptToMD5(String info) { byte[] digesta = null; try { MessageDigest alga = MessageDigest.getInstance("MD5"); alga.update(info.getBytes()); digesta = alga.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } String rs = byte2hex(digesta); return rs; }
|
11
|
Code Sample 1:
static void conditionalCopyFile(File dst, File src) throws IOException { if (dst.equals(src)) return; if (!dst.isFile() || dst.lastModified() < src.lastModified()) { System.out.println("Copying " + src); InputStream is = new FileInputStream(src); OutputStream os = new FileOutputStream(dst); byte[] buf = new byte[8192]; int len; while ((len = is.read(buf)) > 0) os.write(buf, 0, len); os.close(); is.close(); } }
Code Sample 2:
public static void copyFromFileToFileUsingNIO(File inputFile, File outputFile) throws FileNotFoundException, IOException { FileChannel inputChannel = new FileInputStream(inputFile).getChannel(); FileChannel outputChannel = new FileOutputStream(outputFile).getChannel(); try { inputChannel.transferTo(0, inputChannel.size(), outputChannel); } catch (IOException e) { throw e; } finally { if (inputChannel != null) inputChannel.close(); if (outputChannel != null) outputChannel.close(); } }
|
11
|
Code Sample 1:
public String getCipherString(String source) throws CadenaNoCifradaException { String encryptedSource = null; MessageDigest md; try { md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(source.getBytes(encoding), 0, source.length()); sha1hash = md.digest(); encryptedSource = convertToHex(sha1hash); } catch (Exception e) { throw new CadenaNoCifradaException(e); } return encryptedSource; }
Code Sample 2:
public BigInteger generateHashing(String value, int lengthBits) { try { MessageDigest algorithm = MessageDigest.getInstance(this.algorithm); algorithm.update(value.getBytes()); byte[] digest = algorithm.digest(); BigInteger hashing = new BigInteger(+1, digest); if (lengthBits != digest.length * 8) { BigInteger length = new BigInteger("2"); length = length.pow(lengthBits); hashing = hashing.mod(length); } return hashing; } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException("Error with algorithm", e); } }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.