label
class label 2
classes | source_code
stringlengths 398
72.9k
|
|---|---|
00
|
Code Sample 1:
private List<File> ungzipFile(File directory, File compressedFile) throws IOException { List<File> files = new ArrayList<File>(); TarArchiveInputStream in = new TarArchiveInputStream(new GZIPInputStream(new FileInputStream(compressedFile))); try { TarArchiveEntry entry = in.getNextTarEntry(); while (entry != null) { if (entry.isDirectory()) { log.warn("TAR archive contains directories which are being ignored"); entry = in.getNextTarEntry(); continue; } String fn = new File(entry.getName()).getName(); if (fn.startsWith(".")) { log.warn("TAR archive contains a hidden file which is being ignored"); entry = in.getNextTarEntry(); continue; } File targetFile = new File(directory, fn); if (targetFile.exists()) { log.warn("TAR archive contains duplicate filenames, only the first is being extracted"); entry = in.getNextTarEntry(); continue; } files.add(targetFile); log.debug("Extracting file: " + entry.getName() + " to: " + targetFile.getAbsolutePath()); OutputStream fout = new BufferedOutputStream(new FileOutputStream(targetFile)); InputStream entryIn = new FileInputStream(entry.getFile()); IOUtils.copy(entryIn, fout); fout.close(); entryIn.close(); } } finally { in.close(); } return files; }
Code Sample 2:
private String hashString(String key) { MessageDigest digest; try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(key.getBytes()); byte[] hash = digest.digest(); BigInteger bi = new BigInteger(1, hash); return String.format("%0" + (hash.length << 1) + "X", bi) + KERNEL_VERSION; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return "" + key.hashCode(); } }
|
11
|
Code Sample 1:
private void copy(String imgPath, String path) { try { File input = new File(imgPath); File output = new File(path, input.getName()); if (output.exists()) { if (!MessageDialog.openQuestion(getShell(), "Overwrite", "There is already an image file " + input.getName() + " under the package.\n Do you really want to overwrite it?")) return; } byte[] data = new byte[1024]; FileInputStream fis = new FileInputStream(imgPath); BufferedInputStream bis = new BufferedInputStream(fis); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(output)); int length; while ((length = bis.read(data)) > 0) { bos.write(data, 0, length); bos.flush(); } bos.close(); fis.close(); IJavaProject ijp = VisualSwingPlugin.getCurrentProject(); if (ijp != null) { ijp.getProject().refreshLocal(IResource.DEPTH_INFINITE, null); view.refresh(); view.expandAll(); } } catch (Exception e) { VisualSwingPlugin.getLogger().error(e); } }
Code Sample 2:
@Test public void testWriteAndReadBigger() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile file = new RFile("testreadwrite.txt"); RFileOutputStream out = new RFileOutputStream(file); String body = ""; int size = 50 * 1024; for (int i = 0; i < size; i++) { body = body + "a"; } out.write(body.getBytes("utf-8")); out.close(); File expected = new File(dir, "testreadwrite.txt"); assertTrue(expected.isFile()); assertEquals(body.length(), expected.length()); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[body.length()]; int readCount = in.read(buffer); in.close(); assertEquals(body.length(), readCount); String resultRead = new String(buffer, "utf-8"); assertEquals(body, resultRead); } finally { server.stop(); } }
|
00
|
Code Sample 1:
public void writeData(String name, int items, int mznum, int mzscale, long tstart, long tdelta, int[] peaks) { PrintWriter file = getWriter(name + ".txt"); file.println("999 9999"); file.println("Doe, John"); file.println("TEST Lab"); if (mzscale == 1) file.println("PALMS Positive Ion Data"); else if (mzscale == -1) file.println("PALMS Negative Ion Data"); else file.println("PALMS GJIFJIGJ Ion Data"); file.println("TEST Mission"); file.println("1 1"); file.println("1970 01 01 2008 07 09"); file.println("0"); file.println("TIME (UT SECONDS)"); file.println(mznum + 4); for (int i = 0; i < mznum + 4; i++) file.println("1.0"); for (int i = 0; i < mznum + 4; i++) file.println("9.9E29"); file.println("TOTION total MCP signal (electron units)"); file.println("HMASS high mass integral (fraction)"); file.println("UNLIST (unlisted low mass peaks (fraction)"); file.println("UFO unidentified peaks (fraction)"); for (int i = 1; i <= mznum; i++) file.println("MS" + i + " (fraction)"); int header2length = 13; file.println(header2length); for (int i = 0; i < header2length; i++) file.println("1.0"); for (int i = 0; i < header2length; i++) file.println("9.9E29"); file.println("AirCraftTime aircraft time (s)"); file.println("INDEX index ()"); file.println("SCAT scatter (V)"); file.println("JMETER joule meter ()"); file.println("ND neutral density (fraction)"); file.println("SCALEA Mass scale intercept (us)"); file.println("SCALEB mass scale slope (us)"); file.println("NUMPKS number of peaks ()"); file.println("CONF confidence (coded)"); file.println("CAT preliminary category ()"); file.println("AeroDiam aerodynamic diameter (um)"); file.println("AeroDiam1p7 aero diam if density=1.7 (um)"); file.println("TOTBACK total background subtracted (electron units)"); file.println("0"); file.println("0"); String nothing = "0.000000"; for (int i = 0; i < items; i++) { file.println(tstart + (tdelta * i)); file.println(tstart + (tdelta * i) - 3); file.println(i + 1); for (int j = 0; j < 15; j++) file.println(Math.random()); boolean peaked = false; for (int k = 1; k <= mznum; k++) { for (int j = 0; j < peaks.length && !peaked; j++) if (k == peaks[j]) { double randData = (int) (1000000 * (j + 1)); file.println(randData / 1000000); peaked = true; } if (!peaked) file.println(nothing); peaked = false; } } try { Scanner test = new Scanner(f); while (test.hasNext()) { System.out.println(test.nextLine()); } System.out.println("test"); } catch (Exception e) { } file.close(); }
Code Sample 2:
public void sendLargePostRequest(final int size) throws IOException { String encodedData = URLEncoder.encode("test", WebCastellumParameter.DEFAULT_CHARACTER_ENCODING.getValue()) + "=" + URLEncoder.encode("this is just a mass test", WebCastellumParameter.DEFAULT_CHARACTER_ENCODING.getValue()); encodedData += "&" + URLEncoder.encode("payload", WebCastellumParameter.DEFAULT_CHARACTER_ENCODING.getValue()) + "=" + createTestdata(size); final long start = System.currentTimeMillis(); final long end; HttpURLConnection connection = (HttpURLConnection) this.url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); connection.setFollowRedirects(true); connection.setInstanceFollowRedirects(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + encodedData.length()); DataOutputStream output = null; BufferedReader reader = null; try { output = new DataOutputStream(connection.getOutputStream()); output.writeBytes(encodedData); output.flush(); reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = reader.readLine()) != null) { } end = System.currentTimeMillis(); } finally { if (output != null) { try { output.close(); } catch (IOException ignored) { } } if (reader != null) { try { reader.close(); } catch (IOException ignored) { } } } System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); System.out.println("Duration: " + (end - start) + " ms"); }
|
00
|
Code Sample 1:
@Test public void testPersistor() throws Exception { PreparedStatement ps; ps = connection.prepareStatement("delete from privatadresse"); ps.executeUpdate(); ps.close(); ps = connection.prepareStatement("delete from adresse"); ps.executeUpdate(); ps.close(); ps = connection.prepareStatement("delete from person"); ps.executeUpdate(); ps.close(); Persistor p; Adresse csd = new LieferAdresse(); csd.setStrasse("Amalienstrasse 68"); modificationTracker.addNewParticipant(csd); Person markus = new Person(); markus.setName("markus"); modificationTracker.addNewParticipant(markus); markus.getPrivatAdressen().add(csd); Person martin = new Person(); martin.setName("martin"); modificationTracker.addNewParticipant(martin); p = new Persistor(getSchemaMapping(), idGenerator, modificationTracker); p.persist(); Adresse bia = new LieferAdresse(); modificationTracker.addNewParticipant(bia); bia.setStrasse("dr. boehringer gasse"); markus.getAdressen().add(bia); bia.setPerson(martin); markus.setContactPerson(martin); p = new Persistor(getSchemaMapping(), idGenerator, modificationTracker); try { p.persist(); connection.commit(); } catch (Exception e) { connection.rollback(); throw e; } }
Code Sample 2:
public File copyLocalFileAsTempFileInExternallyAccessableDir(String localFileRef) throws IOException { log.debug("copyLocalFileAsTempFileInExternallyAccessableDir"); File f = this.createTempFileInExternallyAccessableDir(); FileChannel srcChannel = new FileInputStream(localFileRef).getChannel(); FileChannel dstChannel = new FileOutputStream(f).getChannel(); log.debug("before transferring via FileChannel from src-inputStream: " + localFileRef + " to dest-outputStream: " + f.getAbsolutePath()); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); log.debug("copyLocalFileAsTempFileInExternallyAccessableDir returning: " + f.getAbsolutePath()); return f; }
|
11
|
Code Sample 1:
private static void backupFile(File file) { FileChannel in = null, out = null; try { if (!file.getName().endsWith(".bak")) { in = new FileInputStream(file).getChannel(); out = new FileOutputStream(new File(file.toString() + ".bak")).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } } catch (Exception e) { e.getMessage(); } finally { try { System.gc(); if (in != null) in.close(); if (out != null) out.close(); } catch (Exception e) { e.getMessage(); } } }
Code Sample 2:
public void testAllowClosingInputStreamTwice() throws IOException { OutputStream outputStream = fileSystem.createOutputStream(_("hello"), OutputMode.OVERWRITE); outputStream.write(new byte[] { 1, 2, 3 }); outputStream.close(); InputStream inputStream = fileSystem.createInputStream(_("hello")); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); IOUtils.copy(inputStream, buffer); inputStream.close(); inputStream.close(); }
|
11
|
Code Sample 1:
public static void copyFile(File source, File target) throws Exception { if (source == null || target == null) { throw new IllegalArgumentException("The arguments may not be null."); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dtnChannel = new FileOutputStream(target).getChannel(); srcChannel.transferTo(0, srcChannel.size(), dtnChannel); srcChannel.close(); dtnChannel.close(); } catch (Exception e) { String message = "Unable to copy file '" + source.getName() + "' to '" + target.getName() + "'."; logger.error(message, e); throw new Exception(message, e); } }
Code Sample 2:
protected void setTestContent(IDfDocument document, String testFileName) throws Exception { InputStream testFileIs = new BufferedInputStream(FileHelper.getFileAsStreamFromClassPath(testFileName)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(testFileIs, baos); String contentType = formatHelper.getFormatForExtension(FileHelper.getFileExtension(testFileName)); document.setContentType(contentType); document.setContent(baos); }
|
00
|
Code Sample 1:
public JsonValue get(Url url) { try { URLConnection connection = new URL(url + "").openConnection(); return createItemFromResponse(url, connection); } catch (IOException e) { throw ItemscriptError.internalError(this, "get.IOException", e); } }
Code Sample 2:
public static long writePropertiesInOpenXMLDocument(String ext, InputStream in, OutputStreamProvider outProvider, Map<String, String> properties) { in = new BufferedInputStream(in); try { File tempPptx = null; POIXMLDocument doc; if (ext.toLowerCase().equals("docx")) { doc = new XWPFDocument(in); } else if (ext.toLowerCase().equals("xlsx")) { doc = new XSSFWorkbook(in); } else if (ext.toLowerCase().equals("pptx")) { tempPptx = File.createTempFile("temp", "pptx"); OutputStream tempPptxOut = new FileOutputStream(tempPptx); tempPptxOut = new BufferedOutputStream(tempPptxOut); IOUtils.copy(in, tempPptxOut); tempPptxOut.close(); doc = new XSLFSlideShow(tempPptx.getAbsolutePath()); } else { throw new IllegalArgumentException("Writing properties for a " + ext + " file is not supported"); } for (Map.Entry<String, String> property : properties.entrySet()) { CoreProperties coreProperties = doc.getProperties().getCoreProperties(); if (property.getKey().equals(Metadata.TITLE)) { coreProperties.setTitle(property.getValue()); } else if (property.getKey().equals(Metadata.AUTHOR)) { coreProperties.setCreator(property.getValue()); } else if (property.getKey().equals(Metadata.KEYWORDS)) { coreProperties.getUnderlyingProperties().setKeywordsProperty(property.getValue()); } else if (property.getKey().equals(Metadata.COMMENTS)) { coreProperties.setDescription(property.getValue()); } else if (property.getKey().equals(Metadata.SUBJECT)) { coreProperties.setSubjectProperty(property.getValue()); } else if (property.getKey().equals(Metadata.COMPANY)) { doc.getProperties().getExtendedProperties().getUnderlyingProperties().setCompany(property.getValue()); } else { org.apache.poi.POIXMLProperties.CustomProperties customProperties = doc.getProperties().getCustomProperties(); if (customProperties.contains(property.getKey())) { int index = 0; for (CTProperty prop : customProperties.getUnderlyingProperties().getPropertyArray()) { if (prop.getName().equals(property.getKey())) { customProperties.getUnderlyingProperties().removeProperty(index); break; } index++; } } customProperties.addProperty(property.getKey(), property.getValue()); } } in.close(); File tempOpenXMLDocumentFile = File.createTempFile("temp", "tmp"); OutputStream tempOpenXMLDocumentOut = new FileOutputStream(tempOpenXMLDocumentFile); tempOpenXMLDocumentOut = new BufferedOutputStream(tempOpenXMLDocumentOut); doc.write(tempOpenXMLDocumentOut); tempOpenXMLDocumentOut.close(); long length = tempOpenXMLDocumentFile.length(); InputStream tempOpenXMLDocumentIn = new FileInputStream(tempOpenXMLDocumentFile); tempOpenXMLDocumentIn = new BufferedInputStream(tempOpenXMLDocumentIn); OutputStream out = null; try { out = outProvider.getOutputStream(); out = new BufferedOutputStream(out); IOUtils.copy(tempOpenXMLDocumentIn, out); out.flush(); } finally { IOUtils.closeQuietly(out); } if (!FileUtils.deleteQuietly(tempOpenXMLDocumentFile)) { tempOpenXMLDocumentFile.deleteOnExit(); } if (tempPptx != null && !FileUtils.deleteQuietly(tempPptx)) { tempPptx.deleteOnExit(); } return length; } catch (IOException e) { throw new RuntimeException(e); } catch (InvalidFormatException e) { throw new RuntimeException(e); } catch (OpenXML4JException e) { throw new RuntimeException(e); } catch (XmlException e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(in); } }
|
00
|
Code Sample 1:
public void deleteSynchrnServerFile(SynchrnServerVO synchrnServerVO) throws Exception { FTPClient ftpClient = new FTPClient(); ftpClient.setControlEncoding("euc-kr"); if (!EgovWebUtil.isIPAddress(synchrnServerVO.getServerIp())) { throw new RuntimeException("IP is needed. (" + synchrnServerVO.getServerIp() + ")"); } InetAddress host = InetAddress.getByName(synchrnServerVO.getServerIp()); ftpClient.connect(host, Integer.parseInt(synchrnServerVO.getServerPort())); ftpClient.login(synchrnServerVO.getFtpId(), synchrnServerVO.getFtpPassword()); FTPFile[] fTPFile = null; try { ftpClient.changeWorkingDirectory(synchrnServerVO.getSynchrnLc()); fTPFile = ftpClient.listFiles(synchrnServerVO.getSynchrnLc()); for (int i = 0; i < fTPFile.length; i++) { if (synchrnServerVO.getDeleteFileNm().equals(fTPFile[i].getName())) ftpClient.deleteFile(fTPFile[i].getName()); } SynchrnServer synchrnServer = new SynchrnServer(); synchrnServer.setServerId(synchrnServerVO.getServerId()); synchrnServer.setReflctAt("N"); synchrnServerDAO.processSynchrn(synchrnServer); } catch (Exception e) { System.out.println(e); } finally { ftpClient.logout(); } }
Code Sample 2:
public URL grabCover(String artist, String title) { if (idf.jCheckBox3.isSelected()) { println("Searching cover for: " + artist); artist = artist.trim(); URL url = null; int searchnumber = 0; try { URL yahoo = new URL("http://www.gracenote.com/search/?query=" + artist.toLowerCase().replaceAll(" ", "+") + "&search_type=artist"); BufferedReader in = new BufferedReader(new InputStreamReader(yahoo.openStream())); println("" + yahoo); String inputLine; String line = ""; while ((inputLine = in.readLine()) != null) line += inputLine; boolean notfound = true; String cut = line; while (notfound) { String search = "<div class=\"album-name large\"><strong>Album:</strong> <a href=\""; if (line.indexOf(search) <= 0) { println("Artist was not found!"); in.close(); return null; } cut = cut.substring(cut.indexOf(search) + search.length()); String test = cut.substring(0, cut.indexOf("\"")); URL secondurl = new URL("http://www.gracenote.com" + test); println("" + secondurl); BufferedReader secin = new BufferedReader(new InputStreamReader(secondurl.openStream())); String secinputLine; String secline = ""; while ((secinputLine = secin.readLine()) != null) secline += secinputLine; if (!(secline.toUpperCase().indexOf(title.toUpperCase()) < 0 && idf.jCheckBox2.isSelected())) { String secsearch = "<div class=\"album-image\"><img src=\""; String seccut = secline.substring(secline.indexOf(secsearch) + secsearch.length()); seccut = seccut.substring(0, seccut.indexOf("\"")); url = new URL("http://www.gracenote.com" + seccut); if (url.toString().indexOf("covers/default") <= 0 && url.toString().indexOf("covers/") > 0) { notfound = false; } } secin.close(); } in.close(); println(url.toString()); } catch (Exception e) { println("error " + e + "\n"); e.printStackTrace(); } return url; } else { return null; } }
|
11
|
Code Sample 1:
@Test public void testCopyOverSize() throws IOException { final InputStream in = new ByteArrayInputStream(TEST_DATA); final ByteArrayOutputStream out = new ByteArrayOutputStream(TEST_DATA.length); final int cpySize = ExtraIOUtils.copy(in, out, TEST_DATA.length + Long.SIZE); assertEquals("Mismatched copy size", TEST_DATA.length, cpySize); final byte[] outArray = out.toByteArray(); assertArrayEquals("Mismatched data", TEST_DATA, outArray); }
Code Sample 2:
protected void copy(File src, File dest) throws IOException { if (src.isDirectory() && dest.isFile()) throw new IOException("Cannot copy a directory to a file"); if (src.isDirectory()) { File newDir = new File(dest, src.getName()); if (!newDir.mkdirs()) throw new IOException("Cannot create a new Directory"); File[] entries = src.listFiles(); for (int i = 0; i < entries.length; ++i) copy(entries[i], newDir); return; } if (dest.isDirectory()) { File newFile = new File(dest, src.getName()); newFile.createNewFile(); copy(src, newFile); return; } try { if (src.length() == 0) { dest.createNewFile(); return; } FileChannel fc = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); long transfered = 0; long totalLength = src.length(); while (transfered < totalLength) { long num = fc.transferTo(transfered, totalLength - transfered, dstChannel); if (num == 0) throw new IOException("Error while copying"); transfered += num; } dstChannel.close(); fc.close(); } catch (IOException e) { if (os.equals("Unix")) { _logger.fine("Trying to use cp to copy file..."); File cp = new File("/usr/bin/cp"); if (!cp.exists()) cp = new File("/bin/cp"); if (!cp.exists()) cp = new File("/usr/local/bin/cp"); if (!cp.exists()) cp = new File("/sbin/cp"); if (!cp.exists()) cp = new File("/usr/sbin/cp"); if (!cp.exists()) cp = new File("/usr/local/sbin/cp"); if (cp.exists()) { Process cpProcess = Runtime.getRuntime().exec(cp.getAbsolutePath() + " '" + src.getAbsolutePath() + "' '" + dest.getAbsolutePath() + "'"); int errCode; try { errCode = cpProcess.waitFor(); } catch (java.lang.InterruptedException ie) { throw e; } return; } } throw e; } }
|
11
|
Code Sample 1:
private static void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException { if (entry.isDirectory()) { createDir(new File(outputDir, entry.getName())); return; } File outputFile = new File(outputDir, entry.getName()); if (!outputFile.getParentFile().exists()) { createDir(outputFile.getParentFile()); } BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); try { IOUtils.copy(inputStream, outputStream); } finally { outputStream.close(); inputStream.close(); } }
Code Sample 2:
private void copyfile(File srcFile, File dstDir) throws FileNotFoundException, IOException { if (srcFile.isDirectory()) { File newDestDir = new File(dstDir, srcFile.getName()); newDestDir.mkdir(); String fileNameList[] = srcFile.list(); for (int i = 0; i < fileNameList.length; i++) { File newSouceFile = new File(srcFile, fileNameList[i]); copyfile(newSouceFile, newDestDir); } } else { File newDestFile = new File(dstDir, srcFile.getName()); FileInputStream in = new FileInputStream(srcFile); FileOutputStream out = new FileOutputStream(newDestFile); FileChannel inChannel = in.getChannel(); FileChannel outChannel = out.getChannel(); long i; Logger.log("copyFile before- copiedSize = " + copiedSize); for (i = 0; i < srcFile.length() - BLOCK_LENGTH; i += BLOCK_LENGTH) { synchronized (this) { inChannel.transferTo(i, BLOCK_LENGTH, outChannel); copiedSize += BLOCK_LENGTH; } } synchronized (this) { inChannel.transferTo(i, srcFile.length() - i, outChannel); copiedSize += srcFile.length() - i; } Logger.log("copyFile after copy- copiedSize = " + copiedSize + "srcFile.length = " + srcFile.length() + "diff = " + (copiedSize - srcFile.length())); in.close(); out.close(); outChannel = null; Logger.log("File copied."); } }
|
00
|
Code Sample 1:
public static void copyFiles(String strPath, String dstPath) throws IOException { File src = new File(strPath); File dest = new File(dstPath); if (src.isDirectory()) { dest.mkdirs(); String list[] = src.list(); for (int i = 0; i < list.length; i++) { String dest1 = dest.getAbsolutePath() + File.separatorChar + list[i]; String src1 = src.getAbsolutePath() + File.separatorChar + list[i]; copyFiles(src1, dest1); } } else { FileInputStream fin = new FileInputStream(src); FileOutputStream fout = new FileOutputStream(dest); int c; while ((c = fin.read()) >= 0) fout.write(c); fin.close(); fout.close(); } }
Code Sample 2:
public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
|
11
|
Code Sample 1:
protected synchronized void doLogin(long timeout, String eventMask) throws IOException, AuthenticationFailedException, TimeoutException { ChallengeAction challengeAction; ManagerResponse challengeResponse; String challenge; String key; LoginAction loginAction; ManagerResponse loginResponse; if (socket == null) { connect(); } if (!socket.isConnected()) { connect(); } synchronized (protocolIdentifier) { if (protocolIdentifier.value == null) { try { protocolIdentifier.wait(timeout); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } if (protocolIdentifier.value == null) { disconnect(); if (reader != null && reader.getTerminationException() != null) { throw reader.getTerminationException(); } else { throw new TimeoutException("Timeout waiting for protocol identifier"); } } } challengeAction = new ChallengeAction("MD5"); try { challengeResponse = sendAction(challengeAction); } catch (Exception e) { disconnect(); throw new AuthenticationFailedException("Unable to send challenge action", e); } if (challengeResponse instanceof ChallengeResponse) { challenge = ((ChallengeResponse) challengeResponse).getChallenge(); } else { disconnect(); throw new AuthenticationFailedException("Unable to get challenge from Asterisk. ChallengeAction returned: " + challengeResponse.getMessage()); } try { MessageDigest md; md = MessageDigest.getInstance("MD5"); if (challenge != null) { md.update(challenge.getBytes()); } if (password != null) { md.update(password.getBytes()); } key = ManagerUtil.toHexString(md.digest()); } catch (NoSuchAlgorithmException ex) { disconnect(); throw new AuthenticationFailedException("Unable to create login key using MD5 Message Digest", ex); } loginAction = new LoginAction(username, "MD5", key, eventMask); try { loginResponse = sendAction(loginAction); } catch (Exception e) { disconnect(); throw new AuthenticationFailedException("Unable to send login action", e); } if (loginResponse instanceof ManagerError) { disconnect(); throw new AuthenticationFailedException(loginResponse.getMessage()); } version = determineVersion(); writer.setTargetVersion(version); ConnectEvent connectEvent = new ConnectEvent(this); connectEvent.setProtocolIdentifier(getProtocolIdentifier()); connectEvent.setDateReceived(DateUtil.getDate()); fireEvent(connectEvent); }
Code Sample 2:
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; } }
|
11
|
Code Sample 1:
protected static URL[] createUrls(URL jarUrls[]) { ArrayList<URL> additionalUrls = new ArrayList<URL>(Arrays.asList(jarUrls)); for (URL ju : jarUrls) { try { JarFile jar = new JarFile(ju.getFile()); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry j = entries.nextElement(); if (j.isDirectory()) continue; if (j.getName().startsWith("lib/") && j.getName().endsWith(".jar")) { URL url = new URL("jar:" + ju.getProtocol() + ":" + ju.getFile() + "!/" + j.getName()); InputStream is = url.openStream(); File tmpFile = File.createTempFile("SCDeploy", ".jar"); FileOutputStream fos = new FileOutputStream(tmpFile); IOUtils.copy(is, fos); is.close(); fos.close(); additionalUrls.add(new URL("file://" + tmpFile.getAbsolutePath())); } } } catch (IOException e) { } } return additionalUrls.toArray(new URL[] {}); }
Code Sample 2:
public static void buildPerMovieDiffBinary(String completePath, String slopeOneDataFolderName, String slopeOneDataFileName) { try { File inFile = new File(completePath + fSep + "SmartGRAPE" + fSep + slopeOneDataFolderName + fSep + slopeOneDataFileName); FileChannel inC = new FileInputStream(inFile).getChannel(); for (int i = 1; i <= 17770; i++) { File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + slopeOneDataFolderName + fSep + "Movie-" + i + "-SlopeOneData.txt"); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf = ByteBuffer.allocate(17770 * 10); for (int j = 1; j < i; j++) { ByteBuffer bbuf = ByteBuffer.allocate(12); inC.position((17769 * 17770 * 6) - ((17769 - (j - 1)) * (17770 - (j - 1)) * 6) + (i - j - 1) * 12); inC.read(bbuf); bbuf.flip(); buf.putShort(bbuf.getShort()); bbuf.getShort(); buf.putInt(bbuf.getInt()); buf.putFloat(-bbuf.getFloat()); } buf.putShort(new Integer(i).shortValue()); buf.putInt(0); buf.putFloat(0.0f); ByteBuffer remainingBuf = inC.map(FileChannel.MapMode.READ_ONLY, (17769 * 17770 * 6) - ((17769 - (i - 1)) * (17770 - (i - 1)) * 6), (17770 - i) * 12); while (remainingBuf.hasRemaining()) { remainingBuf.getShort(); buf.putShort(remainingBuf.getShort()); buf.putInt(remainingBuf.getInt()); buf.putFloat(remainingBuf.getFloat()); } buf.flip(); outC.write(buf); buf.clear(); outC.close(); } } catch (Exception e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
private void addEMInformation() { try { long emDate = System.currentTimeMillis(); if (_local == true) { File emFile = new File("emprotz.dat"); if (!emFile.exists()) { return; } emDate = emFile.lastModified(); } if (emDate > this._emFileDate) { this._emFileDate = emDate; this._emDate = emDate; for (int ii = 0; ii < this._projectInfo.size(); ii++) { Information info = getInfo(ii); if (info != null) { info._emDeadline = null; info._emFrames = null; info._emValue = null; } } Reader reader = null; if (_local == true) { reader = new FileReader("emprotz.dat"); } else { StringBuffer urlName = new StringBuffer(); urlName.append("http://home.comcast.net/"); urlName.append("~wxdude1/emsite/download/"); urlName.append("emprotz.zip"); try { URL url = new URL(urlName.toString()); InputStream stream = url.openStream(); ZipInputStream zip = new ZipInputStream(stream); zip.getNextEntry(); reader = new InputStreamReader(zip); } catch (MalformedURLException mue) { mue.printStackTrace(); } } BufferedReader file = new BufferedReader(reader); try { String line1 = null; int count = 0; while ((line1 = file.readLine()) != null) { String line2 = (line1 != null) ? file.readLine() : null; String line3 = (line2 != null) ? file.readLine() : null; String line4 = (line3 != null) ? file.readLine() : null; count++; if ((count > 1) && (line1 != null) && (line2 != null) && (line3 != null) && (line4 != null)) { if (line1.length() > 2) { int posBegin = line1.indexOf("\"", 0); int posEnd = line1.indexOf("\"", posBegin + 1); if ((posBegin >= 0) && (posEnd >= 0)) { String project = line1.substring(posBegin + 1, posEnd - posBegin); int projectNum = Integer.parseInt(project); Integer deadline = Integer.valueOf(line2.trim()); Double value = Double.valueOf(line3.trim()); Integer frames = Integer.valueOf(line4.trim()); Information info = getInfo(projectNum); if (info == null) { info = createInfo(projectNum); } if (info._emValue == null) { info._emDeadline = deadline; info._emFrames = frames; info._emValue = value; } } } } } } catch (Exception e) { e.printStackTrace(); } finally { file.close(); } } } catch (FileNotFoundException e) { } catch (IOException e) { } }
Code Sample 2:
public JythonWrapperAction(AActionBO.ActionDTO dto, URL url) throws IOException { super(dto); InputStream in = url.openStream(); InputStreamReader rin = new InputStreamReader(in); BufferedReader reader = new BufferedReader(rin); StringBuffer s = new StringBuffer(); String str; while ((str = reader.readLine()) != null) { s.append(str); s.append("\n"); } in.close(); script = s.toString(); }
|
11
|
Code Sample 1:
public static void copyFile(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { log.error(e, e); } finally { if (in != null) in.close(); if (out != null) out.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 static void copy(File source, File sink) throws IOException { if (source == null) throw new NullPointerException("Source file must not be null"); if (sink == null) throw new NullPointerException("Target file must not be null"); if (!source.exists()) throw new IOException("Source file " + source.getPath() + " does not exist"); if (!source.isFile()) throw new IOException("Source file " + source.getPath() + " is not a regular file"); if (!source.canRead()) throw new IOException("Source file " + source.getPath() + " can not be read (missing acces right)"); if (!sink.exists()) throw new IOException("Target file " + sink.getPath() + " does not exist"); if (!sink.isFile()) throw new IOException("Target file " + sink.getPath() + " is not a regular file"); if (!sink.canWrite()) throw new IOException("Target file " + sink.getPath() + " is write protected"); InputStream input = null; OutputStream output = null; try { input = new FileInputStream(source); output = new FileOutputStream(sink); byte[] buffer = new byte[1024]; while (input.available() > 0) { int bread = input.read(buffer); if (bread > 0) output.write(buffer, 0, bread); } } finally { if (input != null) try { input.close(); } catch (IOException x) { } if (output != null) try { output.close(); } catch (IOException x) { } } }
Code Sample 2:
private static final void copyFile(File srcFile, File destDir, byte[] buffer) { try { File destFile = new File(destDir, srcFile.getName()); InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); int bytesRead; while ((bytesRead = in.read(buffer)) != -1) out.write(buffer, 0, bytesRead); in.close(); out.close(); } catch (IOException ioe) { System.err.println("Couldn't copy file '" + srcFile + "' to directory '" + destDir + "'"); } }
|
11
|
Code Sample 1:
private static synchronized boolean doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { destFile = new File(destFile + FILE_SEPARATOR + srcFile.getName()); } FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } return destFile.exists(); }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
11
|
Code Sample 1:
private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } }
Code Sample 2:
public void setPassword(String password) { MessageDigest md; try { md = MessageDigest.getInstance("SHA-256"); md.update(password.getBytes("UTF-8")); byte[] digest = md.digest(); String encodedPassword = Base64.encode(digest); this.password = encodedPassword; } catch (NoSuchAlgorithmException e) { logger.log(Level.SEVERE, "Password creation failed", e); throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { logger.log(Level.SEVERE, "Password creation failed", e); throw new RuntimeException(e); } }
|
11
|
Code Sample 1:
private boolean _copyPath(String source, String destination, Object handler) { try { FileInputStream fis = new FileInputStream(_fullPathForPath(source)); FileOutputStream fos = new FileOutputStream(_fullPathForPath(destination)); byte[] buffer = new byte[fis.available()]; int read; for (read = fis.read(buffer); read >= 0; read = fis.read(buffer)) { fos.write(buffer, 0, read); } fis.close(); fos.close(); return true; } catch (IOException ioe) { ioe.printStackTrace(); return false; } }
Code Sample 2:
public static boolean copyFile(File dest, File source) { FileInputStream fis = null; FileOutputStream fos = null; boolean rv = false; byte[] buf = new byte[1000000]; int bytesRead = 0; if (!dest.getParentFile().exists()) dest.getParentFile().mkdirs(); try { fis = new FileInputStream(source); fos = new FileOutputStream(dest); while ((bytesRead = fis.read(buf)) > 0) fos.write(buf, 0, bytesRead); fis.close(); fis = null; fos.close(); fos = null; rv = true; } catch (Throwable t) { throw new ApplicationException("copy error (" + source.getAbsolutePath() + " => " + dest.getAbsolutePath(), t); } finally { if (fis != null) { try { fis.close(); } catch (Exception e) { } fis = null; } if (fos != null) { try { fos.close(); } catch (Exception e) { } fos = null; } } return rv; }
|
11
|
Code Sample 1:
private void loadMap() { final String wordList = "vietwordlist.txt"; try { File dataFile = new File(supportDir, wordList); if (!dataFile.exists()) { final ReadableByteChannel input = Channels.newChannel(ClassLoader.getSystemResourceAsStream("dict/" + dataFile.getName())); final FileChannel output = new FileOutputStream(dataFile).getChannel(); output.transferFrom(input, 0, 1000000L); input.close(); output.close(); } long fileLastModified = dataFile.lastModified(); if (map == null) { map = new HashMap(); } else { if (fileLastModified <= mapLastModified) { return; } map.clear(); } mapLastModified = fileLastModified; BufferedReader bs = new BufferedReader(new InputStreamReader(new FileInputStream(dataFile), "UTF-8")); String accented; while ((accented = bs.readLine()) != null) { String plain = VietUtilities.stripDiacritics(accented); map.put(plain.toLowerCase(), accented); } bs.close(); } catch (IOException e) { map = null; e.printStackTrace(); JOptionPane.showMessageDialog(this, myResources.getString("Cannot_find_\"") + wordList + myResources.getString("\"_in\n") + supportDir.toString(), VietPad.APP_NAME, JOptionPane.ERROR_MESSAGE); } }
Code Sample 2:
public void decryptFile(String encryptedFile, String decryptedFile, String password) throws Exception { CipherInputStream in; OutputStream out; Cipher cipher; SecretKey key; byte[] byteBuffer; cipher = Cipher.getInstance("DES"); key = new SecretKeySpec(password.getBytes(), "DES"); cipher.init(Cipher.DECRYPT_MODE, key); in = new CipherInputStream(new FileInputStream(encryptedFile), cipher); out = new FileOutputStream(decryptedFile); 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:
@Test public void testWriteAndRead() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile file = new RFile("testreadwrite.txt"); RFileOutputStream out = new RFileOutputStream(file); out.write("test".getBytes("utf-8")); out.close(); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[4]; int readCount = in.read(buffer); in.close(); assertEquals(4, readCount); String resultRead = new String(buffer, "utf-8"); assertEquals("test", resultRead); } finally { server.stop(); } }
Code Sample 2:
@Override public void doHandler(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (request.getRequestURI().indexOf("png") != -1) { response.setContentType("image/png"); } else if (request.getRequestURI().indexOf("gif") != -1) { response.setContentType("image/gif"); } else { response.setContentType("image/x-icon"); } BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream()); try { URL url = new URL("http://" + configCenter.getUcoolOnlineIp() + request.getRequestURI()); BufferedInputStream in = new BufferedInputStream(url.openStream()); byte[] data = new byte[4096]; int size = in.read(data); while (size != -1) { bos.write(data, 0, size); size = in.read(data); } in.close(); bos.flush(); bos.close(); in.close(); } catch (Exception e) { } bos.flush(); }
|
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:
protected byte[] bytesFromJar(String path) throws IOException { URL url = new URL(path); InputStream is = url.openStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int n; while ((n = is.read(buffer)) >= 0) baos.write(buffer, 0, n); is.close(); return baos.toByteArray(); }
|
11
|
Code Sample 1:
public void saveUserUpFile(UserInfo userInfo, String distFileName, InputStream instream) throws IOException { String fullPicFile = BBSCSUtil.getUserWebFilePath(userInfo.getId()) + distFileName; String fullPicFileSmall = BBSCSUtil.getUserWebFilePath(userInfo.getId()) + distFileName + Constant.IMG_SMALL_FILEPREFIX; OutputStream bos = new FileOutputStream(fullPicFile); IOUtils.copy(instream, bos); ImgUtil.reduceImg(fullPicFile, fullPicFileSmall, this.getSysConfig().getFaceWidth(), this.getSysConfig().getFaceHigh(), 0); }
Code Sample 2:
public File copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); copyChannel(inChannel, outChannel); return out; }
|
11
|
Code Sample 1:
public static String hashString(String sPassword) { if (sPassword == null || sPassword.equals("")) { return "empty:"; } else { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(sPassword.getBytes("UTF-8")); byte[] res = md.digest(); return "sha1:" + StringUtils.byte2hex(res); } catch (NoSuchAlgorithmException e) { return "plain:" + sPassword; } catch (UnsupportedEncodingException e) { return "plain:" + sPassword; } } }
Code Sample 2:
public static String hash(String str) { if (str == null || str.length() == 0) { throw new CaptureSecurityException("String to encript cannot be null or zero length"); } StringBuilder hexString = new StringBuilder(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] hash = md.digest(); for (byte element : hash) { if ((0xff & element) < 0x10) { hexString.append('0').append(Integer.toHexString((0xFF & element))); } else { hexString.append(Integer.toHexString(0xFF & element)); } } } catch (NoSuchAlgorithmException e) { throw new CaptureSecurityException(e); } return hexString.toString(); }
|
11
|
Code Sample 1:
public static void downloadJars(IProject project, String repositoryUrl, String jarDirectory, String[] jars) { try { File tmpFile = null; for (String jar : jars) { try { tmpFile = File.createTempFile("tmpPlugin_", ".zip"); URL url = new URL(repositoryUrl + jarDirectory + jar); String destFilename = new File(url.getFile()).getName(); File destFile = new File(project.getLocation().append("lib").append(jarDirectory).toFile(), destFilename); InputStream inputStream = null; FileOutputStream outputStream = null; try { URLConnection urlConnection = url.openConnection(); inputStream = urlConnection.getInputStream(); outputStream = new FileOutputStream(tmpFile); IOUtils.copy(inputStream, outputStream); } finally { if (outputStream != null) { outputStream.close(); } if (inputStream != null) { inputStream.close(); } } FileUtils.copyFile(tmpFile, destFile); } finally { if (tmpFile != null) { tmpFile.delete(); } } } } catch (Exception ex) { ex.printStackTrace(); } }
Code Sample 2:
public static void copyFile(File srcFile, File desFile) throws IOException { AssertUtility.notNull(srcFile); AssertUtility.notNull(desFile); FileInputStream fis = new FileInputStream(srcFile); FileOutputStream fos = new FileOutputStream(desFile); try { FileChannel srcChannel = fis.getChannel(); FileChannel dstChannel = fos.getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } finally { fis.close(); fos.close(); } }
|
11
|
Code Sample 1:
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { final Map<String, String> fileAttr = new HashMap<String, String>(); boolean download = false; String dw = req.getParameter("d"); if (StringUtils.isNotEmpty(dw) && StringUtils.equals(dw, "true")) { download = true; } final ByteArrayOutputStream imageOutputStream = new ByteArrayOutputStream(DEFAULT_CONTENT_LENGTH_SIZE); InputStream imageInputStream = null; try { imageInputStream = getImageAsStream(req, fileAttr); IOUtils.copy(imageInputStream, imageOutputStream); resp.setHeader("Cache-Control", "no-store"); resp.setHeader("Pragma", "no-cache"); resp.setDateHeader("Expires", 0); resp.setContentType(fileAttr.get("mimetype")); if (download) { resp.setHeader("Content-Disposition", "attachment; filename=\"" + fileAttr.get("filename") + "\""); } final ServletOutputStream responseOutputStream = resp.getOutputStream(); responseOutputStream.write(imageOutputStream.toByteArray()); responseOutputStream.flush(); responseOutputStream.close(); } catch (Exception e) { e.printStackTrace(); resp.setContentType("text/html"); resp.getWriter().println("<h1>Sorry... cannot find document</h1>"); } finally { IOUtils.closeQuietly(imageInputStream); IOUtils.closeQuietly(imageOutputStream); } }
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:
@Test public final void testCheckCookies() { URL url = null; try { url = new URL("http://localhost:8080"); } catch (MalformedURLException e1) { e1.printStackTrace(); } StringBuffer content = new StringBuffer(); try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0; H010818)"); cookie = connection.getHeaderField("Set-Cookie"); if (cookie != null) System.out.println("cookie: " + cookie.toString()); connection.setDoInput(true); InputStream is = connection.getInputStream(); byte[] buffer = new byte[2048]; int count; while (-1 != (count = is.read(buffer))) { content.append(new String(buffer, 0, count)); } } catch (IOException e) { System.out.print(e.getMessage()); return; } }
Code Sample 2:
private void encryptChkFile(ProjectMember member, File chkFile) throws Exception { final java.io.FileReader reader = new java.io.FileReader(chkFile); final File encryptedChkFile = new File(member.createOutputFileName(outputPath, "chk")); FileOutputStream outfile = null; ObjectOutputStream outstream = null; Utilities.discardBooleanResult(encryptedChkFile.getParentFile().mkdirs()); outfile = new FileOutputStream(encryptedChkFile); outstream = new ObjectOutputStream(outfile); outstream.writeObject(new Format().parse(reader)); reader.close(); outfile.close(); outstream.close(); }
|
00
|
Code Sample 1:
public InputStream sendGetMessage(Properties args) throws IOException { String argString = ""; if (args != null) { argString = "?" + toEncodedString(args); } URL url = new URL(servlet.toExternalForm() + argString); URLConnection con = url.openConnection(); con.setUseCaches(false); sendHeaders(con); return con.getInputStream(); }
Code Sample 2:
public static String getMD5(final String text) { if (null == text) return null; final MessageDigest algorithm; try { algorithm = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } algorithm.reset(); algorithm.update(text.getBytes()); final byte[] digest = algorithm.digest(); final StringBuffer hexString = new StringBuffer(); for (byte b : digest) { String str = Integer.toHexString(0xFF & b); str = str.length() == 1 ? '0' + str : str; hexString.append(str); } return hexString.toString(); }
|
00
|
Code Sample 1:
public static String encryptPassword(String username, String realm, String password) throws GeneralSecurityException { MessageDigest md = null; md = MessageDigest.getInstance("MD5"); md.update(username.getBytes()); md.update(":".getBytes()); md.update(realm.getBytes()); md.update(":".getBytes()); md.update(password.getBytes()); byte[] hash = md.digest(); return toHex(hash, hash.length); }
Code Sample 2:
private static void extract(ZipFile zipFile) throws Exception { FileUtils.deleteQuietly(WEBKIT_DIR); WEBKIT_DIR.mkdirs(); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) { new File(WEBKIT_DIR, entry.getName()).mkdirs(); continue; } InputStream inputStream = zipFile.getInputStream(entry); File outputFile = new File(WEBKIT_DIR, entry.getName()); FileOutputStream outputStream = new FileOutputStream(outputFile); IOUtils.copy(inputStream, outputStream); IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } }
|
00
|
Code Sample 1:
@Override public void handler(Map<String, Match> result, TargetPage target) { List<String> lines = new LinkedList<String>(); List<String> page = new LinkedList<String>(); try { URL url = new URL(target.getUrl()); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); String line = null; while ((line = reader.readLine()) != null) { page.add(line); } reader.close(); } catch (MalformedURLException e) { } catch (IOException e) { } try { result.put("27 svk par fix", MatchEventFactory.getFix27()); result.put("41 svk ita fix", MatchEventFactory.getFix41()); result.put("01 rsa mex", MatchEventFactory.get01()); result.put("02 uru fra", MatchEventFactory.get02()); result.put("04 kor gre", MatchEventFactory.get04()); result.put("03 arg ngr", MatchEventFactory.get03()); result.put("05 eng usa", MatchEventFactory.get05()); result.put("06 alg slo", MatchEventFactory.get06()); result.put("08 scg gha", MatchEventFactory.get08()); result.put("07 ger aus", MatchEventFactory.get07()); result.put("09 end den", MatchEventFactory.get09()); result.put("10 jpn cmr", MatchEventFactory.get10()); result.put("11 ita par", MatchEventFactory.get11()); result.put("12 nzl svk", MatchEventFactory.get12()); result.put("13 civ por", MatchEventFactory.get13()); result.put("14 bra prk", MatchEventFactory.get14()); result.put("15 hon chi", MatchEventFactory.get15()); result.put("16 esp sui", MatchEventFactory.get16()); result.put("17 rsa uru", MatchEventFactory.get17()); result.put("20 arg kor", MatchEventFactory.get20()); result.put("19 gre ngr", MatchEventFactory.get19()); result.put("18 fra mex", MatchEventFactory.get18()); result.put("21 ger scg", MatchEventFactory.get21()); result.put("22 slo usa", MatchEventFactory.get22()); result.put("23 eng alg", MatchEventFactory.get23()); result.put("25 end jpn", MatchEventFactory.get25()); result.put("24 gha aus", MatchEventFactory.get24()); result.put("26 cmr den", MatchEventFactory.get26()); result.put("27 slo par", MatchEventFactory.get27()); result.put("28 ita nzl", MatchEventFactory.get28()); result.put("29 bra civ", MatchEventFactory.get29()); result.put("30 por prk", MatchEventFactory.get30()); result.put("31 chi sui", MatchEventFactory.get31()); result.put("32 esp hon", MatchEventFactory.get32()); result.put("34 fra rsa", MatchEventFactory.get34()); result.put("33 mex uru", MatchEventFactory.get33()); result.put("35 ngr kor", MatchEventFactory.get35()); result.put("36 gre arg", MatchEventFactory.get36()); result.put("38 usa alg", MatchEventFactory.get38()); result.put("37 slo eng", MatchEventFactory.get37()); result.put("39 gha ger", MatchEventFactory.get39()); result.put("40 aus scg", MatchEventFactory.get40()); result.put("42 par nzl", MatchEventFactory.get42()); result.put("41 slo ita", MatchEventFactory.get41()); result.put("44 cmr ned", MatchEventFactory.get44()); result.put("43 den jpn", MatchEventFactory.get43()); result.put("45 por bra", MatchEventFactory.get45()); result.put("46 prk civ", MatchEventFactory.get46()); result.put("47 chi esp", MatchEventFactory.get47()); result.put("48 sui hon", MatchEventFactory.get48()); result.put("49 uru kor", MatchEventFactory.get49Team()); result.put("50 usa gha", MatchEventFactory.get50Team()); result.put("51 ger eng", MatchEventFactory.get51Team()); result.put("52 arg mex", MatchEventFactory.get52Team()); result.put("53 ned svk", MatchEventFactory.get53Team()); result.put("54 bra chi", MatchEventFactory.get54Team()); result.put("55 par jpn", MatchEventFactory.get55Team()); result.put("56 esp por", MatchEventFactory.get56Team()); result.put("57 ned bra", MatchEventFactory.get57Team()); result.put("58 uru gha", MatchEventFactory.get58Team()); result.put("59 arg ger", MatchEventFactory.get59Team()); result.put("49", MatchEventFactory.get49()); result.put("50", MatchEventFactory.get50()); result.put("51", MatchEventFactory.get51()); result.put("52", MatchEventFactory.get52()); result.put("53", MatchEventFactory.get53()); result.put("54", MatchEventFactory.get54()); this.stage2MatchHandler("318295", "55", "2010-06-29 22:30", result); this.stage2MatchHandler("318296", "56", "2010-06-30 02:30", result); this.stage2MatchHandler("318297", "57", "2010-07-02 22:00", result); this.stage2MatchHandler("318298", "58", "2010-07-03 02:30", result); this.stage2MatchHandler("318299", "59", "2010-07-03 22:00", result); this.stage2MatchHandler("318300", "60", "2010-07-04 02:30", result); this.stage2MatchHandler("318301", "61", "2010-07-07 02:30", result); this.stage2MatchHandler("318302", "62", "2010-07-08 02:30", result); this.stage2MatchHandler("318303", "63", "2010-07-11 02:30", result); this.stage2MatchHandler("318304", "64", "2010-07-12 02:30", result); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
public List<T_new> executeGet(HttpTransport transport, String targetUrl) throws HttpResponseException, IOException { HttpRequest req = transport.buildGetRequest(); req.setUrl(targetUrl); NotifyFeed feed = req.execute().parseAs(NotifyFeed.class); if (feed.entry == null) { return Collections.emptyList(); } List<T_new> results = new ArrayList<T_new>(); for (NotifyEntry e : feed.entry) { StringBuilder buffer = new StringBuilder(); if (e.id != null) { buffer.append(e.id); } buffer.append("@"); if (e.updated != null) { buffer.append(e.updated.toStringRfc3339().substring(0, 19) + "Z"); } Key key = Datastore.createKey(T_new.class, buffer.toString()); T_new news = new T_new(); news.setTitle(e.title); if (e.content != null) { news.setNewText(e.content.substring(0, Math.min(e.content.length(), 500))); } if (e.status != null && e.content == null) { news.setNewText(e.status); } if (e.updated != null) { news.setCreatedAt(new Date(e.updated.value)); } news.setContentUrl(e.getAlternate()); if (e.author != null) { news.setAuthor(e.author.name); } news.setKey(key); results.add(news); } return results; }
|
11
|
Code Sample 1:
private long generateNativeInstallExe(File nativeInstallFile, String instTemplate, File instClassFile) throws IOException { InputStream reader = getClass().getResourceAsStream("/" + instTemplate); ByteArrayOutputStream content = new ByteArrayOutputStream(); String installClassVarStr = "000000000000"; byte[] buf = new byte[installClassVarStr.length()]; NumberFormat nf = NumberFormat.getInstance(Locale.US); nf.setGroupingUsed(false); nf.setMinimumIntegerDigits(installClassVarStr.length()); int installClassStopPos = 0; long installClassOffset = reader.available(); int position = 0; System.out.println(VAGlobals.i18n("VAArchiver_GenerateInstallExe")); reader.read(buf, 0, buf.length); position = 1; for (int n = 0; n < 3; n++) { while ((!new String(buf).equals("clname_here_")) && (!new String(buf).equals("clstart_here")) && (!new String(buf).equals("clstop_here_"))) { content.write(buf[0]); int nextb = reader.read(); position++; shiftArray(buf); buf[buf.length - 1] = (byte) nextb; } if (new String(buf).equals("clname_here_")) { VAGlobals.printDebug(" clname_here_ found at " + (position - 1)); StringBuffer clnameBuffer = new StringBuffer(64); clnameBuffer.append(instClassName_); for (int i = clnameBuffer.length() - 1; i < 64; i++) { clnameBuffer.append('.'); } byte[] clnameBytes = clnameBuffer.toString().getBytes(); for (int i = 0; i < 64; i++) { content.write(clnameBytes[i]); position++; } reader.skip(64 - buf.length); reader.read(buf, 0, buf.length); } else if (new String(buf).equals("clstart_here")) { VAGlobals.printDebug(" clstart_here found at " + (position - 1)); buf = nf.format(installClassOffset).getBytes(); for (int i = 0; i < buf.length; i++) { content.write(buf[i]); position++; } reader.read(buf, 0, buf.length); } else if (new String(buf).equals("clstop_here_")) { VAGlobals.printDebug(" clstop_here_ found at " + (position - 1)); installClassStopPos = position - 1; content.write(buf); position += 12; reader.read(buf, 0, buf.length); } } content.write(buf); buf = new byte[2048]; int read = reader.read(buf); while (read > 0) { content.write(buf, 0, read); read = reader.read(buf); } reader.close(); FileInputStream classStream = new FileInputStream(instClassFile); read = classStream.read(buf); while (read > 0) { content.write(buf, 0, read); read = classStream.read(buf); } classStream.close(); content.close(); byte[] contentBytes = content.toByteArray(); installClassVarStr = nf.format(contentBytes.length); byte[] installClassVarBytes = installClassVarStr.getBytes(); for (int i = 0; i < installClassVarBytes.length; i++) { contentBytes[installClassStopPos + i] = installClassVarBytes[i]; } FileOutputStream out = new FileOutputStream(nativeInstallFile); out.write(contentBytes); out.close(); return installClassOffset; }
Code Sample 2:
public static void copy(FileInputStream source, FileOutputStream dest) throws IOException { FileChannel in = null, out = null; try { in = source.getChannel(); out = dest.getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
|
11
|
Code Sample 1:
public String generateDigest(String password, String saltHex, String algorithm) throws NoSuchAlgorithmException { if (algorithm.equalsIgnoreCase("crypt")) { return "{CRYPT}" + UnixCrypt.crypt(password); } else if (algorithm.equalsIgnoreCase("sha")) { algorithm = "SHA-1"; } else if (algorithm.equalsIgnoreCase("md5")) { algorithm = "MD5"; } MessageDigest msgDigest = MessageDigest.getInstance(algorithm); byte[] salt = {}; if (saltHex != null) { salt = fromHex(saltHex); } String label = null; if (algorithm.startsWith("SHA")) { label = (salt.length > 0) ? "{SSHA}" : "{SHA}"; } else if (algorithm.startsWith("MD5")) { label = (salt.length > 0) ? "{SMD5}" : "{MD5}"; } msgDigest.reset(); msgDigest.update(password.getBytes()); msgDigest.update(salt); byte[] pwhash = msgDigest.digest(); StringBuffer digest = new StringBuffer(label); digest.append(Base64.encode(concatenate(pwhash, salt))); return digest.toString(); }
Code Sample 2:
public byte[] getCoded(String name, String pass) { byte[] digest = null; if (pass != null && 0 < pass.length()) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(name.getBytes()); md.update(pass.getBytes()); digest = md.digest(); } catch (Exception e) { e.printStackTrace(); digest = null; } } return digest; }
|
00
|
Code Sample 1:
private void writeAndCheckFile(DataFileReader reader, String base, String path, String hash, Reference ref, boolean hashall) throws Exception { Data data = ref.data; File file = new File(base + path); file.getParentFile().mkdirs(); if (Debug.level > 1) System.err.println("read file " + data.file + " at index " + data.index); OutputStream output = new FileOutputStream(file); if (hashall) output = new DigestOutputStream(output, MessageDigest.getInstance("MD5")); reader.read(output, data.index, data.file); output.close(); if (hashall) { String filehash = StringUtils.toHex(((DigestOutputStream) output).getMessageDigest().digest()); if (!hash.equals(filehash)) throw new RuntimeException("hash wasn't equal for " + file); } file.setLastModified(ref.lastmod); if (file.length() != data.size) throw new RuntimeException("corrupted file " + file); }
Code Sample 2:
public void testPreparedStatement0009() throws Exception { Connection cx = getConnection(); dropTable("#t0009"); Statement stmt = cx.createStatement(); stmt.executeUpdate("create table #t0009 " + " (i integer not null, " + " s char(10) not null) "); cx.setAutoCommit(false); PreparedStatement pStmt = cx.prepareStatement("insert into #t0009 values (?, ?)"); int rowsToAdd = 8; final String theString = "abcdefghijklmnopqrstuvwxyz"; int count = 0; for (int i = 1; i <= rowsToAdd; i++) { pStmt.setInt(1, i); pStmt.setString(2, theString.substring(0, i)); count += pStmt.executeUpdate(); } assertTrue(count == rowsToAdd); cx.rollback(); stmt = cx.createStatement(); ResultSet rs = stmt.executeQuery("select s, i from #t0009"); assertNotNull(rs); count = 0; while (rs.next()) { count++; assertTrue(rs.getString(1).trim().length() == rs.getInt(2)); } assertTrue(count == 0); cx.commit(); rowsToAdd = 6; count = 0; for (int i = 1; i <= rowsToAdd; i++) { pStmt.setInt(1, i); pStmt.setString(2, theString.substring(0, i)); count += pStmt.executeUpdate(); } assertTrue(count == rowsToAdd); cx.commit(); rs = stmt.executeQuery("select s, i from #t0009"); count = 0; while (rs.next()) { count++; assertTrue(rs.getString(1).trim().length() == rs.getInt(2)); } assertTrue(count == rowsToAdd); cx.commit(); cx.setAutoCommit(true); }
|
11
|
Code Sample 1:
public void write(URL exportUrl, OutputStream output) throws Exception { if (exportUrl == null || output == null) { throw new DocumentListException("null passed in for required parameters"); } MediaContent mc = new MediaContent(); mc.setUri(exportUrl.toString()); MediaSource ms = service.getMedia(mc); InputStream input = ms.getInputStream(); IOUtils.copy(input, output); }
Code Sample 2:
public static void copy(File src, File dest) throws IOException { OutputStream stream = new FileOutputStream(dest); FileInputStream fis = new FileInputStream(src); byte[] buffer = new byte[16384]; while (fis.available() != 0) { int read = fis.read(buffer); stream.write(buffer, 0, read); } stream.flush(); }
|
11
|
Code Sample 1:
private void appendArchive(File instClass) throws IOException { FileOutputStream out = new FileOutputStream(instClass.getName(), true); FileInputStream zipStream = new FileInputStream("install.jar"); byte[] buf = new byte[2048]; int read = zipStream.read(buf); while (read > 0) { out.write(buf, 0, read); read = zipStream.read(buf); } zipStream.close(); out.close(); }
Code Sample 2:
public static boolean copy(File source, File dest) { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) { e.printStackTrace(); return false; } return true; }
|
11
|
Code Sample 1:
public void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; Closer c = new Closer(); try { source = c.register(new FileInputStream(sourceFile).getChannel()); destination = c.register(new FileOutputStream(destFile).getChannel()); destination.transferFrom(source, 0, source.size()); } catch (IOException e) { c.doNotThrow(); throw e; } finally { c.closeAll(); } }
Code Sample 2:
private void generateDocFile(String srcFileName, String s, String destFileName) { try { ZipFile docxFile = new ZipFile(new File(srcFileName)); ZipEntry documentXML = docxFile.getEntry("word/document.xml"); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); InputStream documentXMLIS1 = docxFile.getInputStream(documentXML); Document doc = dbf.newDocumentBuilder().parse(documentXMLIS1); Transformer t = TransformerFactory.newInstance().newTransformer(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); t.transform(new DOMSource(doc), new StreamResult(baos)); ZipOutputStream docxOutFile = new ZipOutputStream(new FileOutputStream(destFileName)); Enumeration<ZipEntry> entriesIter = (Enumeration<ZipEntry>) docxFile.entries(); while (entriesIter.hasMoreElements()) { ZipEntry entry = entriesIter.nextElement(); if (entry.getName().equals("word/document.xml")) { docxOutFile.putNextEntry(new ZipEntry(entry.getName())); byte[] datas = s.getBytes("UTF-8"); docxOutFile.write(datas, 0, datas.length); docxOutFile.closeEntry(); } else if (entry.getName().equals("word/media/image1.png")) { InputStream incoming = new FileInputStream("c:/aaa.jpg"); byte[] data = new byte[incoming.available()]; int readCount = incoming.read(data, 0, data.length); docxOutFile.putNextEntry(new ZipEntry(entry.getName())); docxOutFile.write(data, 0, readCount); docxOutFile.closeEntry(); } else { InputStream incoming = docxFile.getInputStream(entry); byte[] data = new byte[incoming.available()]; int readCount = incoming.read(data, 0, data.length); docxOutFile.putNextEntry(new ZipEntry(entry.getName())); docxOutFile.write(data, 0, readCount); docxOutFile.closeEntry(); } } docxOutFile.close(); } catch (Exception e) { } }
|
11
|
Code Sample 1:
public static String getMD5(String input) { String res = ""; try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(input.getBytes("ISO8859_1")); byte[] md5 = algorithm.digest(); String tmp = ""; for (int i = 0; i < md5.length; i++) { tmp = (Integer.toHexString(0xFF & md5[i])); if (tmp.length() == 1) { res += "0" + tmp; } else { res += tmp; } } } catch (Exception ex) { } return res; }
Code Sample 2:
public void invoke(MessageContext msgContext) throws AxisFault { log.debug("Enter: MD5AttachHandler::invoke"); try { Message msg = msgContext.getRequestMessage(); SOAPConstants soapConstants = msgContext.getSOAPConstants(); org.apache.axis.message.SOAPEnvelope env = (org.apache.axis.message.SOAPEnvelope) msg.getSOAPEnvelope(); org.apache.axis.message.SOAPBodyElement sbe = env.getFirstBody(); org.w3c.dom.Element sbElement = sbe.getAsDOM(); org.w3c.dom.Node n = sbElement.getFirstChild(); for (; n != null && !(n instanceof org.w3c.dom.Element); n = n.getNextSibling()) ; org.w3c.dom.Element paramElement = (org.w3c.dom.Element) n; String href = paramElement.getAttribute(soapConstants.getAttrHref()); org.apache.axis.Part ap = msg.getAttachmentsImpl().getAttachmentByReference(href); javax.activation.DataHandler dh = org.apache.axis.attachments.AttachmentUtils.getActivationDataHandler(ap); org.w3c.dom.Node timeNode = paramElement.getFirstChild(); long startTime = -1; if (timeNode != null && timeNode instanceof org.w3c.dom.Text) { String startTimeStr = ((org.w3c.dom.Text) timeNode).getData(); startTime = Long.parseLong(startTimeStr); } long receivedTime = System.currentTimeMillis(); long elapsedTime = -1; if (startTime > 0) elapsedTime = receivedTime - startTime; String elapsedTimeStr = elapsedTime + ""; java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); java.io.InputStream attachmentStream = dh.getInputStream(); int bread = 0; byte[] buf = new byte[64 * 1024]; do { bread = attachmentStream.read(buf); if (bread > 0) { md.update(buf, 0, bread); } } while (bread > -1); attachmentStream.close(); buf = null; String contentType = dh.getContentType(); if (contentType != null && contentType.length() != 0) { md.update(contentType.getBytes("US-ASCII")); } sbe = env.getFirstBody(); sbElement = sbe.getAsDOM(); n = sbElement.getFirstChild(); for (; n != null && !(n instanceof org.w3c.dom.Element); n = n.getNextSibling()) ; paramElement = (org.w3c.dom.Element) n; String MD5String = org.apache.axis.encoding.Base64.encode(md.digest()); String senddata = " elapsedTime=" + elapsedTimeStr + " MD5=" + MD5String; paramElement.appendChild(paramElement.getOwnerDocument().createTextNode(senddata)); sbe = new org.apache.axis.message.SOAPBodyElement(sbElement); env.clearBody(); env.addBodyElement(sbe); msg = new Message(env); msgContext.setResponseMessage(msg); } catch (Exception e) { log.error(Messages.getMessage("exception00"), e); throw AxisFault.makeFault(e); } log.debug("Exit: MD5AttachHandler::invoke"); }
|
00
|
Code Sample 1:
public void startImport(ActionEvent evt) { final PsiExchange psiExchange = PsiExchangeFactory.createPsiExchange(IntactContext.getCurrentInstance().getSpringContext()); for (final URL url : urlsToImport) { try { if (log.isInfoEnabled()) log.info("Importing: " + url); psiExchange.importIntoIntact(url.openStream()); } catch (IOException e) { handleException(e); return; } } addInfoMessage("File successfully imported", Arrays.asList(urlsToImport).toString()); }
Code Sample 2:
private static void copyContent(final File srcFile, final File dstFile, final boolean gzipContent) throws IOException { final File dstFolder = dstFile.getParentFile(); dstFolder.mkdirs(); if (!dstFolder.exists()) { throw new RuntimeException("Unable to create the folder " + dstFolder.getAbsolutePath()); } final InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(dstFile); if (gzipContent) { out = new GZIPOutputStream(out); } try { final byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } } finally { in.close(); out.close(); } }
|
00
|
Code Sample 1:
public boolean synch(boolean verbose) { try { this.verbose = verbose; if (verbose) System.out.println(" -- Synchronizing: " + destDir + " to " + urlStr); URLConnection urc = new URL(urlStr + "/" + MANIFEST).openConnection(); InputStream is = urc.getInputStream(); BufferedReader r = new BufferedReader(new InputStreamReader(is)); while (true) { String str = r.readLine(); if (str == null) { break; } dealWith(str); } is.close(); } catch (Exception ex) { System.out.println("Synchronization of " + destDir + " failed."); ex.printStackTrace(); return false; } return true; }
Code Sample 2:
public byte[] computeMD5(String plainText) throws VHException { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { throw new VHException("The MD5 hash algorithm is not available.", ex); } try { md.update(plainText.getBytes("UTF-8")); } catch (UnsupportedEncodingException ex) { throw new VHException("The UTF-8 encoding is not supported.", ex); } return md.digest(); }
|
11
|
Code Sample 1:
public static String md5(String string) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(string.getBytes()); byte[] result = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < result.length; i++) { hexString.append(Integer.toHexString((result[i] & 0xFF) | 0x100).toLowerCase().substring(1, 3)); } return hexString.toString(); }
Code Sample 2:
private static String processStr(String srcStr, String sign) throws NoSuchAlgorithmException, NullPointerException { if (null == srcStr) { throw new java.lang.NullPointerException("��Ҫ���ܵ��ַ�ΪNull"); } MessageDigest digest; String algorithm = "MD5"; String result = ""; digest = MessageDigest.getInstance(algorithm); digest.update(srcStr.getBytes()); byte[] byteRes = digest.digest(); int length = byteRes.length; for (int i = 0; i < length; i++) { result = result + byteHEX(byteRes[i], sign); } return result; }
|
11
|
Code Sample 1:
public GetMyDocuments() { String urlString = dms_url + "/servlet/com.ufnasoft.dms.server.ServerGetMyDocuments"; String rvalue = ""; String filename = dms_home + FS + "temp" + FS + username + "mydocuments.xml"; try { String urldata = urlString + "?username=" + URLEncoder.encode(username, "UTF-8") + "&key=" + URLEncoder.encode(key, "UTF-8") + "&filename=" + URLEncoder.encode(username, "UTF-8") + "mydocuments.xml"; ; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); URL u = new URL(urldata); DataInputStream is = new DataInputStream(u.openStream()); FileOutputStream os = new FileOutputStream(filename); int iBufSize = is.available(); byte inBuf[] = new byte[20000 * 1024]; int iNumRead; while ((iNumRead = is.read(inBuf, 0, iBufSize)) > 0) os.write(inBuf, 0, iNumRead); os.close(); is.close(); File f = new File(filename); InputStream inputstream = new FileInputStream(f); Document document = parser.parse(inputstream); NodeList nodelist = document.getElementsByTagName("document"); int num = nodelist.getLength(); myDocsData = new String[num][4]; myDocsToolTip = new String[num]; myDocumentImageName = new String[num]; myDocIds = new int[num]; for (int i = 0; i < num; i++) { myDocsData[i][0] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "filename")); myDocsData[i][1] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "project")); myDocsData[i][2] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "deadline")); myDocsData[i][3] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "workingfolder")); myDocsToolTip[i] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "title")); myDocumentImageName[i] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "imagename")); myDocIds[i] = (new Integer(new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "documentid")))).intValue(); } } catch (MalformedURLException ex) { System.out.println(ex); } catch (ParserConfigurationException ex) { System.out.println(ex); } catch (NullPointerException ex) { } catch (Exception ex) { System.out.println(ex); } }
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 void copyOneFile(String oldPath, String newPath) { File copiedFile = new File(newPath); try { FileInputStream source = new FileInputStream(oldPath); 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(); } }
Code Sample 2:
public static void main(String[] args) throws Exception { String localSrc = args[0]; String dst = args[1]; InputStream in = new BufferedInputStream(new FileInputStream(localSrc)); Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(URI.create(dst), conf); OutputStream out = fs.create(new Path(dst), new Progressable() { public void progress() { System.out.print("."); } }); IOUtils.copyBytes(in, out, 4096, true); }
|
00
|
Code Sample 1:
public Source resolve(String href, String base) throws TransformerException { if (href.endsWith(".txt")) { try { URL url = new URL(new URL(base), href); java.io.InputStream in = url.openConnection().getInputStream(); java.io.InputStreamReader reader = new java.io.InputStreamReader(in, "iso-8859-1"); StringBuffer sb = new StringBuffer(); while (true) { int c = reader.read(); if (c < 0) break; sb.append((char) c); } com.icl.saxon.expr.TextFragmentValue tree = new com.icl.saxon.expr.TextFragmentValue(sb.toString(), url.toString(), (com.icl.saxon.Controller) transformer); return tree.getFirst(); } catch (Exception err) { throw new TransformerException(err); } } else { return null; } }
Code Sample 2:
protected void init() throws MXQueryException { String add = getStringValueOrEmpty(subIters[0]); if (add == null) { currentToken = BooleanToken.FALSE_TOKEN; return; } URI uri; if (!TypeLexicalConstraints.isValidURI(add)) throw new DynamicException(ErrorCodes.F0017_INVALID_ARGUMENT_TO_FN_DOC, "Invalid URI given to fn:doc-available", loc); try { if (TypeLexicalConstraints.isAbsoluteURI(add)) { uri = new URI(add); } else { uri = new URI(IOLib.convertToAndroid(add)); } } catch (URISyntaxException se) { throw new DynamicException(ErrorCodes.F0017_INVALID_ARGUMENT_TO_FN_DOC, "Invalid URI given to fn:doc-available", loc); } if (add.startsWith("http://")) { URL url; try { url = uri.toURL(); } catch (MalformedURLException e) { throw new DynamicException(ErrorCodes.F0017_INVALID_ARGUMENT_TO_FN_DOC, "Invalid URI given to fn:doc-available", loc); } try { InputStream in = url.openStream(); in.close(); } catch (IOException e) { currentToken = BooleanToken.FALSE_TOKEN; return; } currentToken = BooleanToken.TRUE_TOKEN; } else { try { BufferedReader in = new BufferedReader(new InputStreamReader(MXQuery.getContext().openFileInput(uri.toString()))); currentToken = BooleanToken.TRUE_TOKEN; } catch (FileNotFoundException e) { currentToken = BooleanToken.FALSE_TOKEN; } catch (IOException e) { currentToken = BooleanToken.FALSE_TOKEN; } } }
|
11
|
Code Sample 1:
public static void transfer(FileInputStream fileInStream, FileOutputStream fileOutStream) throws IOException { FileChannel fileInChannel = fileInStream.getChannel(); FileChannel fileOutChannel = fileOutStream.getChannel(); long fileInSize = fileInChannel.size(); try { long transferred = fileInChannel.transferTo(0, fileInSize, fileOutChannel); if (transferred != fileInSize) { throw new IOException("transfer() did not complete"); } } finally { ensureClose(fileInChannel, fileOutChannel); } }
Code Sample 2:
private static boolean prepareProbeFile(String completePath, String outputFile) { try { File inFile = new File(completePath + fSep + "probe.txt"); FileChannel inC = new FileInputStream(inFile).getChannel(); BufferedReader br = new BufferedReader(new FileReader(inFile)); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + outputFile); FileChannel outC = new FileOutputStream(outFile, true).getChannel(); boolean endOfFile = true; short movieName = 0; int customer = 0; while (endOfFile) { String line = br.readLine(); if (line != null) { if (line.indexOf(":") >= 0) { movieName = new Short(line.substring(0, line.length() - 1)).shortValue(); } else { customer = new Integer(line).intValue(); ByteBuffer outBuf = ByteBuffer.allocate(6); outBuf.putShort(movieName); outBuf.putInt(customer); outBuf.flip(); outC.write(outBuf); } } else endOfFile = false; } br.close(); outC.close(); return true; } catch (IOException e) { System.err.println(e); return false; } }
|
11
|
Code Sample 1:
private void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
Code Sample 2:
public static void main(String[] args) throws Exception { File rootDir = new File("C:\\dev\\workspace_fgd\\gouvqc_crggid\\WebContent\\WEB-INF\\upload"); File storeDir = new File(rootDir, "storeDir"); File workDir = new File(rootDir, "workDir"); LoggerFacade loggerFacade = new CommonsLoggingLogger(logger); final FileResourceManager frm = new SmbFileResourceManager(storeDir.getPath(), workDir.getPath(), true, loggerFacade); frm.start(); final String resourceId = "811375c8-7cae-4429-9a0e-9222f47dab45"; { if (!frm.resourceExists(resourceId)) { String txId = frm.generatedUniqueTxId(); frm.startTransaction(txId); FileInputStream inputStream = new FileInputStream(resourceId); frm.createResource(txId, resourceId); OutputStream outputStream = frm.writeResource(txId, resourceId); IOUtils.copy(inputStream, outputStream); IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); frm.prepareTransaction(txId); frm.commitTransaction(txId); } } for (int i = 0; i < 30; i++) { final int index = i; new Thread() { @Override public void run() { try { String txId = frm.generatedUniqueTxId(); frm.startTransaction(txId); InputStream inputStream = frm.readResource(resourceId); frm.prepareTransaction(txId); frm.commitTransaction(txId); synchronized (System.out) { System.out.println(index + " ***********************" + txId + " (début)"); } String contenu = TikaUtils.getParsedContent(inputStream, "file.pdf"); synchronized (System.out) { System.out.println(index + " ***********************" + txId + " (fin)"); } } catch (ResourceManagerSystemException e) { throw new RuntimeException(e); } catch (ResourceManagerException e) { throw new RuntimeException(e); } catch (TikaException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } }.start(); } Thread.sleep(60000); frm.stop(FileResourceManager.SHUTDOWN_MODE_NORMAL); }
|
00
|
Code Sample 1:
public void getDownloadInfo(String _url) throws Exception { cl = new DefaultHttpClient(); InfoAuthPromter hp = new InfoAuthPromter(); cl.setCredentialsProvider(hp); head = new HttpHead(_url); head.setHeader("User-Agent", "test"); head.setHeader("Accept", "*/*"); head.setHeader("Range", "bytes=0-"); HttpResponse resp = cl.execute(head); ent = resp.getEntity(); int code = resp.getStatusLine().getStatusCode(); if (code == 401) { throw new Exception("HTTP Auth Failed"); } AuthManager.putAuth(getSite(), auth); setURL(head.getURI().toString()); setSize(ent.getContentLength()); setRangeEnd(getSize() - 1); setResumable(code == 206); }
Code Sample 2:
public static void main(String[] args) throws IOException { InputStream stream = null; FileOutputStream fos = null; File in = new File("in.txt"); try { URL url = new URL(args[0]); stream = url.openStream(); fos = new FileOutputStream(in); int i; while ((i = stream.read()) != -1) { fos.write(i); } fos.flush(); fos.close(); new FileRunner(in, new File("out.txt")).run(); FileReader reader = new FileReader("out.txt"); System.out.println(reader.toString()); } finally { if (stream != null) stream.close(); } }
|
00
|
Code Sample 1:
public String postData(String url, List<NameValuePair> nameValuePairs) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); StringBuilder sb = new StringBuilder(); try { httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); Header[] headers = response.getAllHeaders(); for (int i = 0; i < headers.length; i++) { Log.i(TAG, "HEADER: " + headers[i].getName() + " - " + headers[i].getValue()); } InputStream is = response.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line = ""; while ((line = reader.readLine()) != null) { System.out.println("Parsing line... " + line); sb.append(line); if (line.contains("<html xmlns:fn")) { String gtinCode = line.substring(line.indexOf("GLN:") + 165, line.indexOf("GLN:") + 176); Log.i(TAG, "OUT: " + gtinCode); break; } } Log.i(TAG, "Post Communication OK"); } catch (ClientProtocolException e) { Log.e(TAG, "ClientProtocolException ", e); } catch (IOException e) { Log.e(TAG, "HTTP Not Available", e); } return sb.toString(); }
Code Sample 2:
private InputStream getInputStream(final String pUrlStr) throws IOException { URL url; int responseCode; String encoding; url = new URL(pUrlStr); myActiveConnection = (HttpURLConnection) url.openConnection(); myActiveConnection.setRequestProperty("Accept-Encoding", "gzip, deflate"); responseCode = myActiveConnection.getResponseCode(); if (responseCode != RESPONSECODE_OK) { String message; String apiErrorMessage; apiErrorMessage = myActiveConnection.getHeaderField("Error"); if (apiErrorMessage != null) { message = "Received API HTTP response code " + responseCode + " with message \"" + apiErrorMessage + "\" for URL \"" + pUrlStr + "\"."; } else { message = "Received API HTTP response code " + responseCode + " for URL \"" + pUrlStr + "\"."; } throw new OsmosisRuntimeException(message); } myActiveConnection.setConnectTimeout(TIMEOUT); encoding = myActiveConnection.getContentEncoding(); responseStream = myActiveConnection.getInputStream(); if (encoding != null && encoding.equalsIgnoreCase("gzip")) { responseStream = new GZIPInputStream(responseStream); } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) { responseStream = new InflaterInputStream(responseStream, new Inflater(true)); } return responseStream; }
|
11
|
Code Sample 1:
protected String encrypt(String text) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); md.update(text.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } catch (Exception ex) { throw new TiiraException(ex); } }
Code Sample 2:
public String md5(String password) { MessageDigest m = null; try { m = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { } m.update(password.getBytes(), 0, password.length()); return new BigInteger(1, m.digest()).toString(16); }
|
11
|
Code Sample 1:
public static void main(String[] args) throws Exception { String linesep = System.getProperty("line.separator"); FileOutputStream fos = new FileOutputStream(new File("lib-licenses.txt")); fos.write(new String("JCP contains the following libraries. Please read this for comments on copyright etc." + linesep + linesep).getBytes()); fos.write(new String("Chemistry Development Kit, master version as of " + new Date().toString() + " (http://cdk.sf.net)" + linesep).getBytes()); fos.write(new String("Copyright 1997-2009 The CDK Development Team" + linesep).getBytes()); fos.write(new String("License: LGPL v2 (http://www.gnu.org/licenses/old-licenses/gpl-2.0.html)" + linesep).getBytes()); fos.write(new String("Download: https://sourceforge.net/projects/cdk/files/" + linesep).getBytes()); fos.write(new String("Source available at: http://sourceforge.net/scm/?type=git&group_id=20024" + linesep + linesep).getBytes()); File[] files = new File(args[0]).listFiles(new JarFileFilter()); for (int i = 0; i < files.length; i++) { if (new File(files[i].getPath() + ".meta").exists()) { Map<String, Map<String, String>> metaprops = readProperties(new File(files[i].getPath() + ".meta")); Iterator<String> itsect = metaprops.keySet().iterator(); while (itsect.hasNext()) { String section = itsect.next(); fos.write(new String(metaprops.get(section).get("Library") + " " + metaprops.get(section).get("Version") + " (" + metaprops.get(section).get("Homepage") + ")" + linesep).getBytes()); fos.write(new String("Copyright " + metaprops.get(section).get("Copyright") + linesep).getBytes()); fos.write(new String("License: " + metaprops.get(section).get("License") + " (" + metaprops.get(section).get("LicenseURL") + ")" + linesep).getBytes()); fos.write(new String("Download: " + metaprops.get(section).get("Download") + linesep).getBytes()); fos.write(new String("Source available at: " + metaprops.get(section).get("SourceCode") + linesep + linesep).getBytes()); } } if (new File(files[i].getPath() + ".extra").exists()) { fos.write(new String("The author says:" + linesep).getBytes()); FileInputStream in = new FileInputStream(new File(files[i].getPath() + ".extra")); int len; byte[] buf = new byte[1024]; while ((len = in.read(buf)) > 0) { fos.write(buf, 0, len); } } fos.write(linesep.getBytes()); } fos.close(); }
Code Sample 2:
public static void main(String[] args) { FileInputStream in; DeflaterOutputStream out; FileOutputStream fos; FileDialog fd; fd = new FileDialog(new Frame(), "Find a file to deflate", FileDialog.LOAD); fd.show(); if (fd.getFile() != null) { try { in = new FileInputStream(new File(fd.getDirectory(), fd.getFile())); fos = new FileOutputStream(new File("Deflated.out")); out = new DeflaterOutputStream(fos, new Deflater(Deflater.DEFLATED, true)); int bytes_read = 0; byte[] buffer = new byte[1024]; while ((bytes_read = in.read(buffer)) != -1) { out.write(buffer, 0, bytes_read); } fos.flush(); fos.close(); out.flush(); out.close(); in.close(); } catch (Exception e) { e.printStackTrace(); } System.out.println("Done"); } }
|
11
|
Code Sample 1:
@Test public void test() throws JDOMException, IOException { InputStream is = this.getClass().getResourceAsStream("putRegularVehicle.xml"); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); IOUtils.copy(is, byteArrayOutputStream); TrafficModelDefinition def = MDFReader.read(byteArrayOutputStream.toByteArray()); TrafficSimulationEngine se = new TrafficSimulationEngine(); se.init(def); int linkId = 2; int segmentId = 3; Map<Integer, Set<Integer>> linkSegments = new HashMap<Integer, Set<Integer>>(); Set<Integer> segments = new HashSet<Integer>(); segments.add(segmentId); linkSegments.put(linkId, segments); FrameProperties frameProperties = new FrameProperties(linkSegments, new HashSet<Integer>()); se.setFrameProperties(frameProperties); for (float time = 0; time < 60; time += 0.1f) { se.step(0.1f); System.out.println("*** Time: " + time); for (RoadObject roadObject : se.getDynamicObjects()) { Vehicle vehicle = (Vehicle) roadObject; System.out.println(vehicle.getVehicleId() + ":\tX=" + vehicle.getPosition() + "\tV=" + vehicle.getSpeed()); } } }
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(); }
|
11
|
Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
private JButton getButtonSonido() { if (buttonSonido == null) { buttonSonido = new JButton(); buttonSonido.setText(Messages.getString("gui.AdministracionResorces.15")); buttonSonido.setIcon(new ImageIcon("data/icons/view_sidetree.png")); buttonSonido.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new SoundFilter()); int returnVal = fc.showDialog(AdministracionResorces.this, Messages.getString("gui.AdministracionResorces.17")); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + "/" + rutaDatos + "sonidos/" + file.getName(); String rutaRelativa = rutaDatos + "sonidos/" + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); imagen.setSonidoURL(rutaRelativa); System.out.println(rutaGlobal + " " + rutaRelativa); buttonSonido.setIcon(new ImageIcon("data/icons/view_sidetreeOK.png")); gui.getAudio().reproduceAudio(imagen); } catch (IOException ex) { ex.printStackTrace(); } } else { } } }); } return buttonSonido; }
|
11
|
Code Sample 1:
private static synchronized boolean doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { destFile = new File(destFile + FILE_SEPARATOR + srcFile.getName()); } FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } return destFile.exists(); }
Code Sample 2:
boolean createSessionArchive(String archiveFilename) { byte[] buffer = new byte[1024]; try { ZipOutputStream archive = new ZipOutputStream(new FileOutputStream(archiveFilename)); for (mAnnotationsCursor.moveToFirst(); !mAnnotationsCursor.isAfterLast(); mAnnotationsCursor.moveToNext()) { FileInputStream in = new FileInputStream(mAnnotationsCursor.getString(ANNOTATIONS_FILE_NAME)); archive.putNextEntry(new ZipEntry("audio" + (mAnnotationsCursor.getPosition() + 1) + ".3gpp")); int length; while ((length = in.read(buffer)) > 0) archive.write(buffer, 0, length); archive.closeEntry(); in.close(); } archive.close(); } catch (IOException e) { Toast.makeText(mActivity, mActivity.getString(R.string.error_zip) + " " + e.getMessage(), Toast.LENGTH_SHORT).show(); return false; } return true; }
|
00
|
Code Sample 1:
public static String calcResponse(String ha1, String nonce, String nonceCount, String cnonce, String qop, String method, String uri) throws FatalException, MD5DigestException { MD5Encoder encoder = new MD5Encoder(); String ha2 = null; MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (Exception e) { throw new FatalException(e); } if (method == null || uri == null) { throw new MD5DigestException(WebdavStatus.SC_BAD_REQUEST, "method or uri"); } if (qop != null && qop.equals("auth-int")) { throw new MD5DigestException(WebdavStatus.SC_UNSUPPORTED_MEDIA_TYPE); } if (nonce == null) { throw new MD5DigestException(WebdavStatus.SC_BAD_REQUEST, "nonce"); } if (qop != null && (qop.equals("auth") || qop.equals("auth-int"))) { if (nonceCount == null || cnonce == null) { throw new MD5DigestException(WebdavStatus.SC_BAD_REQUEST, "nc or cnonce"); } } md5.update((method + ":" + uri).getBytes()); ha2 = encoder.encode(md5.digest()); md5.update((ha1 + ":" + nonce + ":").getBytes()); if (qop != null && (qop.equals("auth") || qop.equals("auth-int"))) { md5.update((nonceCount + ":" + cnonce + ":" + qop + ":").getBytes()); } md5.update(ha2.getBytes()); String response = encoder.encode(md5.digest()); return response; }
Code Sample 2:
public static List<String> retrieveLanguages() throws Exception { List<String> result = new ArrayList<String>(); URL url = new URL("http://translatewiki.net/w/i.php?title=Special:MessageGroupStats&group=out-osm-site"); String str = StreamUtil.toString(url.openStream()); Pattern pattern = Pattern.compile(".*language=([^;\"]+).*"); Matcher m = pattern.matcher(str); while (m.find()) { String lang = m.group(1); if (!result.contains(lang)) { result.add(lang); } } return result; }
|
11
|
Code Sample 1:
private static String loadUrlToString(String a_url) throws IOException { URL l_url1 = new URL(a_url); BufferedReader br = new BufferedReader(new InputStreamReader(l_url1.openStream())); String l_content = ""; String l_ligne = null; l_content = br.readLine(); while ((l_ligne = br.readLine()) != null) { l_content += AA.SL + l_ligne; } return l_content; }
Code Sample 2:
void loadSVG(String svgFileURL) { try { URL url = new URL(svgFileURL); URLConnection c = url.openConnection(); c.setRequestProperty("Accept-Encoding", "gzip"); InputStream is = c.getInputStream(); String encoding = c.getContentEncoding(); if ("gzip".equals(encoding) || "x-gzip".equals(encoding) || svgFileURL.toLowerCase().endsWith(".svgz")) { is = new GZIPInputStream(is); } is = new BufferedInputStream(is); Document svgDoc = AppletUtils.parse(is, false); if (svgDoc != null) { if (grMngr.mainView.isBlank() == null) { grMngr.mainView.setBlank(cfgMngr.backgroundColor); } SVGReader.load(svgDoc, grMngr.mSpace, true, svgFileURL); grMngr.seekBoundingBox(); grMngr.buildLogicalStructure(); ConfigManager.defaultFont = VText.getMainFont(); grMngr.reveal(); if (grMngr.previousLocations.size() == 1) { grMngr.previousLocations.removeElementAt(0); } if (grMngr.rView != null) { grMngr.rView.getGlobalView(grMngr.mSpace.getCamera(1), 100); } grMngr.cameraMoved(null, null, 0); } else { System.err.println("An error occured while loading file " + svgFileURL); } } catch (Exception ex) { grMngr.reveal(); ex.printStackTrace(); } }
|
00
|
Code Sample 1:
public String postData(String url, List<NameValuePair> nameValuePairs) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); StringBuilder sb = new StringBuilder(); try { httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); Header[] headers = response.getAllHeaders(); for (int i = 0; i < headers.length; i++) { Log.i(TAG, "HEADER: " + headers[i].getName() + " - " + headers[i].getValue()); } InputStream is = response.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line = ""; while ((line = reader.readLine()) != null) { System.out.println("Parsing line... " + line); sb.append(line); if (line.contains("<html xmlns:fn")) { String gtinCode = line.substring(line.indexOf("GLN:") + 165, line.indexOf("GLN:") + 176); Log.i(TAG, "OUT: " + gtinCode); break; } } Log.i(TAG, "Post Communication OK"); } catch (ClientProtocolException e) { Log.e(TAG, "ClientProtocolException ", e); } catch (IOException e) { Log.e(TAG, "HTTP Not Available", e); } return sb.toString(); }
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(); } }
|
00
|
Code Sample 1:
public static void copy(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
Code Sample 2:
public 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(); }
|
00
|
Code Sample 1:
@Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { URL url = new URL(System.getenv("plugg_home") + "/" + systemId); System.out.println("SystemId = " + systemId); return new InputSource(url.openStream()); }
Code Sample 2:
public static Search Search(String searchString) throws Exception { Uri.Builder builder = new Uri.Builder(); builder.scheme("http"); builder.authority("www.goodreads.com"); builder.path("search/search"); builder.appendQueryParameter("format", "xml"); builder.appendQueryParameter("key", _ConsumerKey); builder.appendQueryParameter("q", searchString); HttpClient httpClient = new DefaultHttpClient(); HttpGet getSearchResponse = new HttpGet(builder.build().toString()); HttpResponse searchResponse = httpClient.execute(getSearchResponse); Response searchResponseData = ResponseParser.parse(searchResponse.getEntity().getContent()); return searchResponseData.get_Search(); }
|
11
|
Code Sample 1:
public static void convertEncoding(File infile, File outfile, String from, String to) throws IOException, UnsupportedEncodingException { InputStream in; if (infile != null) in = new FileInputStream(infile); else in = System.in; OutputStream out; outfile.createNewFile(); if (outfile != null) out = new FileOutputStream(outfile); else out = System.out; if (from == null) from = System.getProperty("file.encoding"); if (to == null) to = "Unicode"; Reader r = new BufferedReader(new InputStreamReader(in, from)); Writer w = new BufferedWriter(new OutputStreamWriter(out, to)); char[] buffer = new char[4096]; int len; while ((len = r.read(buffer)) != -1) w.write(buffer, 0, len); r.close(); w.close(); }
Code Sample 2:
public String openFileAsText(String resource) throws IOException { StringWriter wtr = new StringWriter(); InputStreamReader rdr = new InputStreamReader(openFile(resource)); try { IOUtils.copy(rdr, wtr); } finally { IOUtils.closeQuietly(rdr); } return wtr.toString(); }
|
11
|
Code Sample 1:
public static void resize(File originalFile, File resizedFile, int width, String format) throws IOException { if (format != null && "gif".equals(format.toLowerCase())) { resize(originalFile, resizedFile, width, 1); return; } FileInputStream fis = new FileInputStream(originalFile); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); int readLength = -1; int bufferSize = 1024; byte bytes[] = new byte[bufferSize]; while ((readLength = fis.read(bytes, 0, bufferSize)) != -1) { byteStream.write(bytes, 0, readLength); } byte[] in = byteStream.toByteArray(); fis.close(); byteStream.close(); Image inputImage = Toolkit.getDefaultToolkit().createImage(in); waitForImage(inputImage); int imageWidth = inputImage.getWidth(null); if (imageWidth < 1) throw new IllegalArgumentException("image width " + imageWidth + " is out of range"); int imageHeight = inputImage.getHeight(null); if (imageHeight < 1) throw new IllegalArgumentException("image height " + imageHeight + " is out of range"); int height = -1; double scaleW = (double) imageWidth / (double) width; double scaleY = (double) imageHeight / (double) height; if (scaleW >= 0 && scaleY >= 0) { if (scaleW > scaleY) { height = -1; } else { width = -1; } } Image outputImage = inputImage.getScaledInstance(width, height, java.awt.Image.SCALE_DEFAULT); checkImage(outputImage); encode(new FileOutputStream(resizedFile), outputImage, format); }
Code Sample 2:
public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
|
11
|
Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
public static void saveZipComponents(ZipComponents zipComponents, File zipFile) throws FileNotFoundException, IOException, Exception { ZipOutputStream zipOutStream = new ZipOutputStream(new FileOutputStream(zipFile)); for (ZipComponent comp : zipComponents.getComponents()) { ZipEntry newEntry = new ZipEntry(comp.getName()); zipOutStream.putNextEntry(newEntry); if (comp.isDirectory()) { } else { if (comp.getName().endsWith("document.xml") || comp.getName().endsWith("document.xml.rels")) { } InputStream inputStream = comp.getInputStream(); IOUtils.copy(inputStream, zipOutStream); inputStream.close(); } } zipOutStream.close(); }
|
00
|
Code Sample 1:
private static ImageIcon tryLoadImageIconFromResource(String filename, String path, int width, int height) { ImageIcon icon = null; try { URL url = cl.getResource(path + pathSeparator + fixFilename(filename)); if (url != null && url.openStream() != null) { icon = new ImageIcon(url); } } catch (Exception e) { } if (icon == null) { return null; } if ((icon.getIconWidth() == width) && (icon.getIconHeight() == height)) { return icon; } else { return new ImageIcon(icon.getImage().getScaledInstance(width, height, java.awt.Image.SCALE_SMOOTH)); } }
Code Sample 2:
private void sendData(HttpServletResponse response, MediaBean mediaBean) throws IOException { if (logger.isInfoEnabled()) logger.info("sendData[" + mediaBean + "]"); response.setContentLength(mediaBean.getContentLength()); response.setContentType(mediaBean.getContentType()); response.addHeader("Last-Modified", mediaBean.getLastMod()); response.addHeader("Cache-Control", "must-revalidate"); response.addHeader("content-disposition", "attachment, filename=" + (new Date()).getTime() + "_" + mediaBean.getFileName()); byte[] content = mediaBean.getContent(); InputStream is = null; OutputStream os = null; try { os = response.getOutputStream(); is = new ByteArrayInputStream(content); IOUtils.copy(is, os); } catch (IOException e) { logger.error(e, e); } finally { if (is != null) try { is.close(); } catch (IOException e) { } if (os != null) try { os.close(); } catch (IOException e) { } } }
|
11
|
Code Sample 1:
public static void main(String[] args) { File file = null; try { file = File.createTempFile("TestFileChannel", ".dat"); final ByteBuffer buffer = ByteBuffer.allocateDirect(4); final ByteChannel output = new FileOutputStream(file).getChannel(); buffer.putInt(MAGIC_INT); buffer.flip(); output.write(buffer); output.close(); final ByteChannel input = new FileInputStream(file).getChannel(); buffer.clear(); while (buffer.hasRemaining()) { input.read(buffer); } input.close(); buffer.flip(); final int file_int = buffer.getInt(); if (file_int != MAGIC_INT) { System.out.println("TestFileChannel FAILURE"); System.out.println("Wrote " + Integer.toHexString(MAGIC_INT) + " but read " + Integer.toHexString(file_int)); } else { System.out.println("TestFileChannel SUCCESS"); } } catch (Exception e) { System.out.println("TestFileChannel FAILURE"); e.printStackTrace(System.out); } finally { if (null != file) { file.delete(); } } }
Code Sample 2:
private static boolean moveFiles(String sourceDir, String targetDir) { boolean isFinished = false; boolean fileMoved = false; File stagingDir = new File(sourceDir); if (!stagingDir.exists()) { System.out.println(getTimeStamp() + "ERROR - source directory does not exist."); return true; } if (stagingDir.listFiles() == null) { System.out.println(getTimeStamp() + "ERROR - Empty file list. Possible permission error on source directory " + sourceDir); return true; } File[] fileList = stagingDir.listFiles(); for (int x = 0; x < fileList.length; x++) { File f = fileList[x]; if (f.getName().startsWith(".")) { continue; } String targetFileName = targetDir + File.separator + f.getName(); String operation = "move"; boolean success = f.renameTo(new File(targetFileName)); if (success) { fileMoved = true; } else { operation = "mv"; try { Process process = Runtime.getRuntime().exec(new String[] { "mv", f.getCanonicalPath(), targetFileName }); process.waitFor(); process.destroy(); if (!new File(targetFileName).exists()) { success = false; } else { success = true; fileMoved = true; } } catch (Exception e) { success = false; } if (!success) { operation = "copy"; FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(f).getChannel(); File outFile = new File(targetFileName); out = new FileOutputStream(outFile).getChannel(); in.transferTo(0, in.size(), out); in.close(); in = null; out.close(); out = null; f.delete(); success = true; } catch (Exception e) { success = false; } finally { if (in != null) { try { in.close(); } catch (Exception e) { } } if (out != null) { try { out.close(); } catch (Exception e) { } } } } } if (success) { System.out.println(getTimeStamp() + operation + " " + f.getAbsolutePath() + " to " + targetDir); fileMoved = true; } else { System.out.println(getTimeStamp() + "ERROR - " + operation + " " + f.getName() + " to " + targetFileName + " failed."); isFinished = true; } } if (fileMoved && !isFinished) { try { currentLastActivity = System.currentTimeMillis(); updateLastActivity(currentLastActivity); } catch (NumberFormatException e) { System.out.println(getTimeStamp() + "ERROR: NumberFormatException when trying to update lastActivity."); isFinished = true; } catch (IOException e) { System.out.println(getTimeStamp() + "ERROR: IOException when trying to update lastActivity. " + e.toString()); isFinished = true; } } return isFinished; }
|
11
|
Code Sample 1:
public ServiceAdapterIfc deploy(String session, String name, byte jarBytes[], String jarName, String serviceClass, String serviceInterface) throws RemoteException, MalformedURLException, StartServiceException, SessionException { try { File jarFile = new File(jarName); jarName = jarFile.getName(); String jarName2 = jarName; jarFile = new File(jarName2); int n = 0; while (jarFile.exists()) { jarName2 = jarName + n++; jarFile = new File(jarName2); } FileOutputStream fos = new FileOutputStream(jarName2); IOUtils.copy(new ByteArrayInputStream(jarBytes), fos); SCClassLoader cl = new SCClassLoader(new URL[] { new URL("file://" + jarFile.getAbsolutePath()) }, getMasterNode().getSCClassLoaderCounter()); return startService(session, name, serviceClass, serviceInterface, cl); } catch (SessionException e) { throw e; } catch (Exception e) { throw new StartServiceException("Could not deploy service: " + e.getMessage(), e); } }
Code Sample 2:
public BasePolicy(String flaskPath) throws Exception { SWIGTYPE_p_p_policy p_p_pol = apol.new_policy_t_p_p(); if (!flaskPath.endsWith("/")) flaskPath += "/"; File tmpPolConf = File.createTempFile("tmpBasePolicy", ".conf"); BufferedWriter tmpPolFile = new BufferedWriter(new FileWriter(tmpPolConf)); BufferedReader secClassFile = new BufferedReader(new FileReader(flaskPath + "security_classes")); int bufSize = 1024; char[] buffer = new char[bufSize]; int read; while ((read = secClassFile.read(buffer)) > 0) { tmpPolFile.write(buffer, 0, read); } secClassFile.close(); BufferedReader sidsFile = new BufferedReader(new FileReader(flaskPath + "initial_sids")); while ((read = sidsFile.read(buffer)) > 0) { tmpPolFile.write(buffer, 0, read); } sidsFile.close(); BufferedReader axxVecFile = new BufferedReader(new FileReader(flaskPath + "access_vectors")); while ((read = axxVecFile.read(buffer)) > 0) { tmpPolFile.write(buffer, 0, read); } axxVecFile.close(); tmpPolFile.write("attribute ricka; \ntype rick_t; \nrole rick_r types rick_t; \nuser rick_u roles rick_r;\nsid kernel rick_u:rick_r:rick_t\nfs_use_xattr ext3 rick_u:rick_r:rick_t;\ngenfscon proc / rick_u:rick_r:rick_t\n"); tmpPolFile.flush(); tmpPolFile.close(); if (apol.open_policy(tmpPolConf.getAbsolutePath(), p_p_pol) == 0) { Policy = apol.policy_t_p_p_value(p_p_pol); if (Policy == null) { throw new Exception("Failed to allocate memory for policy_t struct."); } tmpPolConf.delete(); } else { throw new IOException("Failed to open/parse base policy file: " + tmpPolConf.getAbsolutePath()); } }
|
00
|
Code Sample 1:
public static synchronized String encrypt(String plaintext) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = null; md = MessageDigest.getInstance("SHA"); md.update(plaintext.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
Code Sample 2:
public void sendResponse(DjdocRequest req, HttpServletResponse res) throws IOException { File file = (File) req.getResult(); InputStream in = null; try { in = new FileInputStream(file); IOUtils.copy(in, res.getOutputStream()); } finally { if (in != null) { in.close(); } } }
|
11
|
Code Sample 1:
public static Properties parse() { try { String userHome = System.getProperty("user.home"); File dsigFolder = new File(userHome, ".dsig"); if (!dsigFolder.exists() && !dsigFolder.mkdir()) { throw new IOException("Could not create .dsig folder in user home directory"); } File settingsFile = new File(dsigFolder, "settings.properties"); if (!settingsFile.exists()) { InputStream is = UserHomeSettingsParser.class.getResourceAsStream("/defaultSettings.properties"); if (is != null) { IOUtils.copy(is, new FileOutputStream(settingsFile)); } } if (settingsFile.exists()) { Properties p = new Properties(); FileInputStream fis = new FileInputStream(settingsFile); p.load(fis); IOUtils.closeQuietly(fis); return p; } } catch (IOException e) { logger.warn("Error while initialize settings", e); } return null; }
Code Sample 2:
public void copyTo(File folder) { if (!isNewFile()) { return; } if (!folder.exists()) { folder.mkdir(); } File dest = new File(folder, name); try { FileInputStream in = new FileInputStream(currentPath); FileOutputStream out = new FileOutputStream(dest); byte[] readBuf = new byte[1024 * 512]; int readLength; long totalCopiedSize = 0; boolean canceled = false; while ((readLength = in.read(readBuf)) != -1) { out.write(readBuf, 0, readLength); } in.close(); out.close(); if (canceled) { dest.delete(); } else { currentPath = dest; newFile = false; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
public static void main(String arg[]) { try { String readFile = arg[0]; String writeFile = arg[1]; java.io.FileInputStream ss = new java.io.FileInputStream(readFile); ManagedMemoryDataSource ms = new ManagedMemoryDataSource(ss, 1024 * 1024, "foo/data", true); javax.activation.DataHandler dh = new javax.activation.DataHandler(ms); java.io.InputStream is = dh.getInputStream(); java.io.FileOutputStream fo = new java.io.FileOutputStream(writeFile); byte[] buf = new byte[512]; int read = 0; do { read = is.read(buf); if (read > 0) { fo.write(buf, 0, read); } } while (read > -1); fo.close(); is.close(); } catch (java.lang.Exception e) { log.error(Messages.getMessage("exception00"), e); } }
Code Sample 2:
public static void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
|
00
|
Code Sample 1:
public static void copyFile(File source, String target) throws FileNotFoundException, IOException { File fout = new File(target); fout.mkdirs(); fout.delete(); fout = new File(target); FileChannel in = new FileInputStream(source).getChannel(); FileChannel out = new FileOutputStream(target).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); }
Code Sample 2:
private ArrayList execAtParentServer(ArrayList paramList) throws Exception { ArrayList outputList = null; String message = ""; try { HashMap serverUrlMap = InitXml.getInstance().getServerMap(); Iterator it = serverUrlMap.keySet().iterator(); while (it.hasNext()) { String server = (String) it.next(); String serverUrl = (String) serverUrlMap.get(server); serverUrl = serverUrl + Primer3Manager.servletName; URL url = new URL(serverUrl); URLConnection uc = url.openConnection(); uc.setDoOutput(true); OutputStream os = uc.getOutputStream(); StringBuffer buf = new StringBuffer(); buf.append("actionType=designparent"); for (int i = 0; i < paramList.size(); i++) { Primer3Param param = (Primer3Param) paramList.get(i); if (i == 0) { buf.append("&sequence=" + param.getSequence()); buf.append("&upstream_size" + upstreamSize); buf.append("&downstreamSize" + downstreamSize); buf.append("&MARGIN_LENGTH=" + marginLength); buf.append("&OVERLAP_LENGTH=" + overlapLength); buf.append("&MUST_XLATE_PRODUCT_MIN_SIZE=" + param.getPrimerProductMinSize()); buf.append("&MUST_XLATE_PRODUCT_MAX_SIZE=" + param.getPrimerProductMaxSize()); buf.append("&PRIMER_PRODUCT_OPT_SIZE=" + param.getPrimerProductOptSize()); buf.append("&PRIMER_MAX_END_STABILITY=" + param.getPrimerMaxEndStability()); buf.append("&PRIMER_MAX_MISPRIMING=" + param.getPrimerMaxMispriming()); buf.append("&PRIMER_PAIR_MAX_MISPRIMING=" + param.getPrimerPairMaxMispriming()); buf.append("&PRIMER_MIN_SIZE=" + param.getPrimerMinSize()); buf.append("&PRIMER_OPT_SIZE=" + param.getPrimerOptSize()); buf.append("&PRIMER_MAX_SIZE=" + param.getPrimerMaxSize()); buf.append("&PRIMER_MIN_TM=" + param.getPrimerMinTm()); buf.append("&PRIMER_OPT_TM=" + param.getPrimerOptTm()); buf.append("&PRIMER_MAX_TM=" + param.getPrimerMaxTm()); buf.append("&PRIMER_MAX_DIFF_TM=" + param.getPrimerMaxDiffTm()); buf.append("&PRIMER_MIN_GC=" + param.getPrimerMinGc()); buf.append("&PRIMER_OPT_GC_PERCENT=" + param.getPrimerOptGcPercent()); buf.append("&PRIMER_MAX_GC=" + param.getPrimerMaxGc()); buf.append("&PRIMER_SELF_ANY=" + param.getPrimerSelfAny()); buf.append("&PRIMER_SELF_END=" + param.getPrimerSelfEnd()); buf.append("&PRIMER_NUM_NS_ACCEPTED=" + param.getPrimerNumNsAccepted()); buf.append("&PRIMER_MAX_POLY_X=" + param.getPrimerMaxPolyX()); buf.append("&PRIMER_GC_CLAMP=" + param.getPrimerGcClamp()); } buf.append("&target=" + param.getPrimerSequenceId() + "," + (param.getTarget())[0] + "," + (param.getTarget())[1]); } PrintStream ps = new PrintStream(os); ps.print(buf.toString()); ps.close(); ObjectInputStream ois = new ObjectInputStream(uc.getInputStream()); outputList = (ArrayList) ois.readObject(); ois.close(); } } catch (IOException e1) { e1.printStackTrace(); } if ((outputList == null || outputList.size() == 0) && message != null && message.length() > 0) { throw new Exception(message); } return outputList; }
|
00
|
Code Sample 1:
public static void copy(File source, File destination) { try { FileInputStream fileInputStream = new FileInputStream(source); FileOutputStream fileOutputStream = new FileOutputStream(destination); FileChannel inputChannel = fileInputStream.getChannel(); FileChannel outputChannel = fileOutputStream.getChannel(); transfer(inputChannel, outputChannel, source.length(), 1024 * 1024 * 32, true, true); fileInputStream.close(); fileOutputStream.close(); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
@Override public void loadTest(StoryCardModel story) { String strUrl = story.getStoryCard().getAcceptanceTestUrl(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder loader; try { URL url = new URL(strUrl); loader = factory.newDocumentBuilder(); Document document; document = loader.parse(url.openStream()); this.numPass = Integer.parseInt(((Element) document.getElementsByTagName("num-pass").item(0)).getFirstChild().getNodeValue()); this.numFail = Integer.parseInt(((Element) document.getElementsByTagName("num-fail").item(0)).getFirstChild().getNodeValue()); this.numRuns = Integer.parseInt(((Element) document.getElementsByTagName("num-runs").item(0)).getFirstChild().getNodeValue()); this.numExceptions = Integer.parseInt(((Element) document.getElementsByTagName("num-exceptions").item(0)).getFirstChild().getNodeValue()); this.wikiText = ((Element) document.getElementsByTagName("wiki").item(0)).getFirstChild().getNodeValue(); } catch (Exception e) { util.Logger.singleton().error(e); } }
|
00
|
Code Sample 1:
public InputStream getEntry(String entryPath) throws IOException { if (!entries.contains(entryPath)) { return null; } JarInputStream jis = new JarInputStream(new BufferedInputStream(url.openStream())); do { ZipEntry ze = jis.getNextEntry(); if (ze == null) { break; } if (ze.getName().equals(entryPath)) { return jis; } } while (true); assert (false); return null; }
Code Sample 2:
private void checkSettings() throws ConfigurationException { List serverList = getConfiguration().getServerList(); for (Object aServerList : serverList) { JiraServerDetails jiraServerDetails = (JiraServerDetails) aServerList; URL url = null; try { if (jiraServerDetails.getBaseurl() == null || "".equals(jiraServerDetails.getBaseurl())) { throw new ConfigurationException("BaseURL is empty."); } url = new URL(jiraServerDetails.getBaseurl()); String content = getURLContent(url.openConnection().getInputStream()); if (content.indexOf("Atlassian JIRA") == -1) { throw new ConfigurationException("URL (" + url.toString() + ") Doesn't put to an installation of Atlassian JIRA"); } try { jiraServerDetails.getRpcClient(true).login(); } catch (JiraException e) { throw new ConfigurationException("Jira Server ( " + url.toString() + " ) is earlier than 2.6 or has RPC disabled."); } } catch (MalformedURLException e) { throw new ConfigurationException("Malformed URL: " + url); } catch (IOException e) { throw new ConfigurationException("Unable to contact server: " + url); } try { MyIssuesFeedBuilder feed = new MyIssuesFeedBuilder(new JiraServerDetails[] { jiraServerDetails }); feed.buildFeedData(); } catch (FeedException feedException) { throw new ConfigurationException(feedException.getMessage()); } } }
|
11
|
Code Sample 1:
private void execute(File file) throws IOException { if (file == null) throw new RuntimeException("undefined file"); if (!file.exists()) throw new RuntimeException("file not found :" + file); if (!file.isFile()) throw new RuntimeException("not a file :" + file); String login = cfg.getProperty(GC_USERNAME); String password = null; if (cfg.containsKey(GC_PASSWORD)) { password = cfg.getProperty(GC_PASSWORD); } else { password = new String(Base64.decode(cfg.getProperty(GC_PASSWORD64))); } PostMethod post = null; try { HttpClient client = new HttpClient(); post = new PostMethod("https://" + projectName + ".googlecode.com/files"); post.addRequestHeader("User-Agent", getClass().getName()); post.addRequestHeader("Authorization", "Basic " + Base64.encode(login + ":" + password)); List<Part> parts = new ArrayList<Part>(); String s = this.summary; if (StringUtils.isBlank(s)) { s = file.getName() + " (" + TimeUtils.toYYYYMMDD() + ")"; } parts.add(new StringPart("summary", s)); for (String lbl : this.labels) { if (StringUtils.isBlank(lbl)) continue; parts.add(new StringPart("label", lbl.trim())); } parts.add(new FilePart("filename", file)); MultipartRequestEntity requestEntity = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams()); post.setRequestEntity(requestEntity); int status = client.executeMethod(post); if (status != 201) { throw new IOException("http status !=201 : " + post.getResponseBodyAsString()); } else { IOUtils.copyTo(post.getResponseBodyAsStream(), new NullOutputStream()); } } finally { if (post != null) post.releaseConnection(); } }
Code Sample 2:
public final void deliver(final String from, final String recipient, final InputStream data) throws TooMuchDataException, IOException { System.out.println("FROM: " + from); System.out.println("TO: " + recipient); final File tmpDir = new File(System.getProperty("java.io.tmpdir")); final File file = new File(tmpDir, recipient); final FileWriter fw = new FileWriter(file); try { IOUtils.copy(data, fw); } finally { fw.close(); } }
|
11
|
Code Sample 1:
@Override public void run() { File dir = new File(loggingDir); if (!dir.isDirectory()) { logger.error("Logging directory \"" + dir.getAbsolutePath() + "\" does not exist."); return; } File file = new File(dir, new Date().toString().replaceAll("[ ,:]", "") + "LoadBalancerLog.txt"); FileWriter writer; try { writer = new FileWriter(file); } catch (IOException e) { e.printStackTrace(); return; } int counter = 0; while (!isInterrupted() && counter < numProbes) { try { writer.write(System.currentTimeMillis() + "," + currentPending + "," + currentThreads + "," + droppedTasks + "," + executionExceptions + "," + currentWeight + "," + averageWaitTime + "," + averageExecutionTime + "#"); writer.flush(); } catch (IOException e) { e.printStackTrace(); break; } counter++; try { sleep(probeTime); } catch (InterruptedException e) { e.printStackTrace(); break; } } try { writer.close(); } catch (IOException e) { e.printStackTrace(); return; } FileReader reader; try { reader = new FileReader(file); } catch (FileNotFoundException e2) { e2.printStackTrace(); return; } Vector<StatStorage> dataV = new Vector<StatStorage>(); int c; try { c = reader.read(); } catch (IOException e1) { e1.printStackTrace(); c = -1; } String entry = ""; Date startTime = null; Date stopTime = null; while (c != -1) { if (c == 35) { String parts[] = entry.split(","); if (startTime == null) startTime = new Date(Long.parseLong(parts[0])); if (parts.length > 0) dataV.add(parse(parts)); stopTime = new Date(Long.parseLong(parts[0])); entry = ""; } else { entry += (char) c; } try { c = reader.read(); } catch (IOException e) { e.printStackTrace(); } } try { reader.close(); } catch (IOException e) { e.printStackTrace(); } if (dataV.size() > 0) { int[] dataPending = new int[dataV.size()]; int[] dataOccupied = new int[dataV.size()]; long[] dataDropped = new long[dataV.size()]; long[] dataException = new long[dataV.size()]; int[] dataWeight = new int[dataV.size()]; long[] dataExecution = new long[dataV.size()]; long[] dataWait = new long[dataV.size()]; for (int i = 0; i < dataV.size(); i++) { dataPending[i] = dataV.get(i).pending; dataOccupied[i] = dataV.get(i).occupied; dataDropped[i] = dataV.get(i).dropped; dataException[i] = dataV.get(i).exceptions; dataWeight[i] = dataV.get(i).currentWeight; dataExecution[i] = (long) dataV.get(i).executionTime; dataWait[i] = (long) dataV.get(i).waitTime; } String startName = startTime.toString(); startName = startName.replaceAll("[ ,:]", ""); file = new File(dir, startName + "pending.gif"); SimpleChart.drawChart(file, 640, 480, dataPending, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "occupied.gif"); SimpleChart.drawChart(file, 640, 480, dataOccupied, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "dropped.gif"); SimpleChart.drawChart(file, 640, 480, dataDropped, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "exceptions.gif"); SimpleChart.drawChart(file, 640, 480, dataException, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "weight.gif"); SimpleChart.drawChart(file, 640, 480, dataWeight, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "execution.gif"); SimpleChart.drawChart(file, 640, 480, dataExecution, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "wait.gif"); SimpleChart.drawChart(file, 640, 480, dataWait, startTime, stopTime, new Color(0, 0, 0)); } recordedExecutionThreads = 0; recordedWaitingThreads = 0; averageExecutionTime = 0; averageWaitTime = 0; if (!isLocked) { debugThread = new DebugThread(); debugThread.start(); } }
Code Sample 2:
private void copyFile(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 void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String version = req.getParameter("version"); String cdn = req.getParameter("cdn"); String dependencies = req.getParameter("dependencies"); String optimize = req.getParameter("optimize"); String cacheFile = null; String result = null; boolean isCached = false; Boolean isError = true; if (!version.equals("1.3.2")) { result = "invalid version: " + version; } if (!cdn.equals("google") && !cdn.equals("aol")) { result = "invalide CDN type: " + cdn; } if (!optimize.equals("comments") && !optimize.equals("shrinksafe") && !optimize.equals("none") && !optimize.equals("shrinksafe.keepLines")) { result = "invalid optimize type: " + optimize; } if (!dependencies.matches("^[\\w\\-\\,\\s\\.]+$")) { result = "invalid dependency list: " + dependencies; } try { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { result = e.getMessage(); } if (result == null) { md.update(dependencies.getBytes()); String digest = (new BASE64Encoder()).encode(md.digest()).replace('+', '~').replace('/', '_').replace('=', '_'); cacheFile = cachePath + "/" + version + "/" + cdn + "/" + digest + "/" + optimize + ".js"; File file = new File(cacheFile); if (file.exists()) { isCached = true; isError = false; } } if (result == null && !isCached) { BuilderContextAction contextAction = new BuilderContextAction(builderPath, version, cdn, dependencies, optimize); ContextFactory.getGlobal().call(contextAction); Exception exception = contextAction.getException(); if (exception != null) { result = exception.getMessage(); } else { result = contextAction.getResult(); FileUtil.writeToFile(cacheFile, result, null, true); isError = false; } } } catch (Exception e) { result = e.getMessage(); } res.setCharacterEncoding("utf-8"); if (isError) { result = result.replaceAll("\\\"", "\\\""); result = "<html><head><script type=\"text/javascript\">alert(\"" + result + "\");</script></head><body></body></html>"; PrintWriter writer = res.getWriter(); writer.append(result); } else { res.setHeader("Content-Type", "application/x-javascript"); res.setHeader("Content-disposition", "attachment; filename=dojo.js"); res.setHeader("Content-Encoding", "gzip"); File file = new File(cacheFile); BufferedInputStream in = new java.io.BufferedInputStream(new DataInputStream(new FileInputStream(file))); OutputStream out = res.getOutputStream(); byte[] bytes = new byte[64000]; int bytesRead = 0; while (bytesRead != -1) { bytesRead = in.read(bytes); if (bytesRead != -1) { out.write(bytes, 0, bytesRead); } } } }
Code Sample 2:
public static String SHA1(String string) throws XLWrapException { MessageDigest md; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new XLWrapException("SHA-1 message digest is not available."); } byte[] data = new byte[40]; md.update(string.getBytes()); data = md.digest(); StringBuffer buf = new StringBuffer(); for (int i = 0; i < data.length; i++) { int halfbyte = (data[i] >>> 4) & 0x0F; int two_halfs = 0; do { if ((0 <= halfbyte) && (halfbyte <= 9)) buf.append((char) ('0' + halfbyte)); else buf.append((char) ('a' + (halfbyte - 10))); halfbyte = data[i] & 0x0F; } while (two_halfs++ < 1); } return buf.toString(); }
|
00
|
Code Sample 1:
public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); }
Code Sample 2:
public InputStream sendCommandRaw(String command, boolean usePost) throws IOException { try { String fullCommand = prefix + command + fixSuffix(command, suffix); long curGap = System.currentTimeMillis() - lastCommandTime; long delayTime = minimumCommandPeriod - curGap; delay(delayTime); URI uri = new URI(fullCommand); URL url = uri.toURL(); if (trace || traceSends) { System.out.println("Sending--> " + url); } if (logFile != null) { logFile.println("Sending--> " + url); } InputStream is = null; for (int i = 0; i < tryCount; i++) { try { URLConnection urc = url.openConnection(); if (usePost) { if (urc instanceof HttpURLConnection) { ((HttpURLConnection) urc).setRequestMethod("POST"); } } if (getTimeout() != -1) { urc.setReadTimeout(getTimeout()); urc.setConnectTimeout(getTimeout()); } is = new BufferedInputStream(urc.getInputStream()); break; } catch (FileNotFoundException e) { throw e; } catch (IOException e) { System.out.println(name + " Error: " + e + " cmd: " + command); } } lastCommandTime = System.currentTimeMillis(); if (is == null) { System.out.println(name + " retry failure cmd: " + url); throw new IOException("Can't send command"); } return is; } catch (URISyntaxException ex) { throw new IOException("bad uri " + ex); } }
|
00
|
Code Sample 1:
public final String hashPassword(final String password) { try { if (salt == null) { salt = new byte[16]; SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); sr.setSeed(System.currentTimeMillis()); sr.nextBytes(salt); } MessageDigest md = MessageDigest.getInstance("SHA"); md.update(salt); md.update(password.getBytes("UTF-8")); byte[] hash = md.digest(); for (int i = 0; i < (1999); i++) { md.reset(); hash = md.digest(hash); } return byteToString(hash, 60); } catch (Exception exception) { log.error(exception); return null; } }
Code Sample 2:
public void readMESHDescriptorFileIntoFiles(String outfiledir) { String inputLine, ins; String filename = getMESHdescriptorfilename(); String uid = ""; String name = ""; String description = ""; String element_of = ""; Vector treenr = new Vector(); Vector related = new Vector(); Vector synonyms = new Vector(); Vector actions = new Vector(); Vector chemicals = new Vector(); Vector allCASchemicals = new Vector(); Set CAS = new TreeSet(); Map treenr2uid = new TreeMap(); Map uid2name = new TreeMap(); String cut1, cut2; try { BufferedReader in = new BufferedReader(new FileReader(filename)); String outfile = outfiledir + "\\mesh"; BufferedWriter out_concept = new BufferedWriter(new FileWriter(outfile + "_concept.txt")); BufferedWriter out_concept_name = new BufferedWriter(new FileWriter(outfile + "_concept_name.txt")); BufferedWriter out_relation = new BufferedWriter(new FileWriter(outfile + "_relation.txt")); BufferedWriter cas_mapping = new BufferedWriter(new FileWriter(outfile + "to_cas_mapping.txt")); BufferedWriter ec_mapping = new BufferedWriter(new FileWriter(outfile + "to_ec_mapping.txt")); Connection db = tools.openDB("kb"); String query = "SELECT hierarchy_complete,uid FROM mesh_tree, mesh_graph_uid_name WHERE term=name"; ResultSet rs = tools.executeQuery(db, query); while (rs.next()) { String db_treenr = rs.getString("hierarchy_complete"); String db_uid = rs.getString("uid"); treenr2uid.put(db_treenr, db_uid); } db.close(); System.out.println("Reading in the DUIDs ..."); BufferedReader in_for_mapping = new BufferedReader(new FileReader(filename)); inputLine = getNextLine(in_for_mapping); boolean leave = false; while ((in_for_mapping != null) && (inputLine != null)) { if (inputLine.startsWith("<DescriptorRecord DescriptorClass")) { inputLine = getNextLine(in_for_mapping); cut1 = "<DescriptorUI>"; cut2 = "</DescriptorUI>"; String mesh_uid = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); if (mesh_uid.compareTo("D041441") == 0) leave = true; inputLine = getNextLine(in_for_mapping); inputLine = getNextLine(in_for_mapping); cut1 = "<String>"; cut2 = "</String>"; String mesh_name = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); uid2name.put(mesh_uid, mesh_name); } inputLine = getNextLine(in_for_mapping); } in_for_mapping.close(); BufferedReader in_ec_numbers = new BufferedReader(new FileReader("e:\\projects\\ondex\\ec_concept_acc.txt")); Set ec_numbers = new TreeSet(); String ec_line = in_ec_numbers.readLine(); while (in_ec_numbers.ready()) { StringTokenizer st = new StringTokenizer(ec_line); st.nextToken(); ec_numbers.add(st.nextToken()); ec_line = in_ec_numbers.readLine(); } in_ec_numbers.close(); tools.printDate(); inputLine = getNextLine(in); while (inputLine != null) { if (inputLine.startsWith("<DescriptorRecord DescriptorClass")) { treenr.clear(); related.clear(); synonyms.clear(); actions.clear(); chemicals.clear(); boolean id_ready = false; boolean line_read = false; while ((inputLine != null) && (!inputLine.startsWith("</DescriptorRecord>"))) { line_read = false; if ((inputLine.startsWith("<DescriptorUI>")) && (!id_ready)) { cut1 = "<DescriptorUI>"; cut2 = "</DescriptorUI>"; uid = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); inputLine = getNextLine(in); inputLine = getNextLine(in); cut1 = "<String>"; cut2 = "</String>"; name = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); id_ready = true; } if (inputLine.compareTo("<SeeRelatedList>") == 0) { while ((inputLine != null) && (inputLine.indexOf("</SeeRelatedList>") == -1)) { if (inputLine.startsWith("<DescriptorUI>")) { cut1 = "<DescriptorUI>"; cut2 = "</DescriptorUI>"; String id = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); related.add(id); } inputLine = getNextLine(in); line_read = true; } } if (inputLine.compareTo("<TreeNumberList>") == 0) { while ((inputLine != null) && (inputLine.indexOf("</TreeNumberList>") == -1)) { if (inputLine.startsWith("<TreeNumber>")) { cut1 = "<TreeNumber>"; cut2 = "</TreeNumber>"; String id = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); treenr.add(id); } inputLine = getNextLine(in); line_read = true; } } if (inputLine.startsWith("<Concept PreferredConceptYN")) { boolean prefConcept = false; if (inputLine.compareTo("<Concept PreferredConceptYN=\"Y\">") == 0) prefConcept = true; while ((inputLine != null) && (inputLine.indexOf("</Concept>") == -1)) { if (inputLine.startsWith("<CASN1Name>") && prefConcept) { cut1 = "<CASN1Name>"; cut2 = "</CASN1Name>"; String casn1 = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); String chem_name = casn1; String chem_description = ""; if (casn1.length() > chem_name.length() + 2) chem_description = casn1.substring(chem_name.length() + 2, casn1.length()); String reg_number = ""; inputLine = getNextLine(in); if (inputLine.startsWith("<RegistryNumber>")) { cut1 = "<RegistryNumber>"; cut2 = "</RegistryNumber>"; reg_number = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); } Vector chemical = new Vector(); String type = ""; if (reg_number.startsWith("EC")) { type = "EC"; reg_number = reg_number.substring(3, reg_number.length()); } else { type = "CAS"; } chemical.add(type); chemical.add(reg_number); chemical.add(chem_name); chemical.add(chem_description); chemicals.add(chemical); if (type.compareTo("CAS") == 0) { if (!CAS.contains(reg_number)) { CAS.add(reg_number); allCASchemicals.add(chemical); } } } if (inputLine.startsWith("<ScopeNote>") && prefConcept) { cut1 = "<ScopeNote>"; description = inputLine.substring(cut1.length(), inputLine.length()); } if (inputLine.startsWith("<TermUI>")) { inputLine = getNextLine(in); cut1 = "<String>"; cut2 = "</String>"; String syn = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); if (syn.indexOf("&") != -1) { String syn1 = syn.substring(0, syn.indexOf("&")); String syn2 = syn.substring(syn.indexOf("amp;") + 4, syn.length()); syn = syn1 + " & " + syn2; } if (name.compareTo(syn) != 0) synonyms.add(syn); } if (inputLine.startsWith("<PharmacologicalAction>")) { inputLine = getNextLine(in); inputLine = getNextLine(in); cut1 = "<DescriptorUI>"; cut2 = "</DescriptorUI>"; String act_ui = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); actions.add(act_ui); } inputLine = getNextLine(in); line_read = true; } } if (!line_read) inputLine = getNextLine(in); } String pos_tag = ""; element_of = "MESHD"; String is_primary = "0"; out_concept.write(uid + "\t" + pos_tag + "\t" + description + "\t" + element_of + "\t"); out_concept.write(is_primary + "\n"); String name_stemmed = ""; String name_tagged = ""; element_of = "MESHD"; String is_unique = "0"; int is_preferred = 1; String original_name = name; String is_not_substring = "0"; out_concept_name.write(uid + "\t" + name + "\t" + name_stemmed + "\t"); out_concept_name.write(name_tagged + "\t" + element_of + "\t"); out_concept_name.write(is_unique + "\t" + is_preferred + "\t"); out_concept_name.write(original_name + "\t" + is_not_substring + "\n"); is_preferred = 0; for (int i = 0; i < synonyms.size(); i++) { name = (String) synonyms.get(i); original_name = name; out_concept_name.write(uid + "\t" + name + "\t" + name_stemmed + "\t"); out_concept_name.write(name_tagged + "\t" + element_of + "\t"); out_concept_name.write(is_unique + "\t" + is_preferred + "\t"); out_concept_name.write(original_name + "\t" + is_not_substring + "\n"); } String rel_type = "is_r"; element_of = "MESHD"; String from_name = name; for (int i = 0; i < related.size(); i++) { String to_uid = (String) related.get(i); String to_name = (String) uid2name.get(to_uid); out_relation.write(uid + "\t" + to_uid + "\t"); out_relation.write(rel_type + "\t" + element_of + "\t"); out_relation.write(from_name + "\t" + to_name + "\n"); } rel_type = "is_a"; element_of = "MESHD"; related.clear(); for (int i = 0; i < treenr.size(); i++) { String tnr = (String) treenr.get(i); if (tnr.length() > 3) tnr = tnr.substring(0, tnr.lastIndexOf(".")); String rel_uid = (String) treenr2uid.get(tnr); if (rel_uid != null) related.add(rel_uid); else System.out.println(uid + ": No DUI found for " + tnr); } for (int i = 0; i < related.size(); i++) { String to_uid = (String) related.get(i); String to_name = (String) uid2name.get(to_uid); out_relation.write(uid + "\t" + to_uid + "\t"); out_relation.write(rel_type + "\t" + element_of + "\t"); out_relation.write(from_name + "\t" + to_name + "\n"); } if (related.size() == 0) System.out.println(uid + ": No is_a relations"); rel_type = "act"; element_of = "MESHD"; for (int i = 0; i < actions.size(); i++) { String to_uid = (String) actions.get(i); String to_name = (String) uid2name.get(to_uid); out_relation.write(uid + "\t" + to_uid + "\t"); out_relation.write(rel_type + "\t" + element_of + "\t"); out_relation.write(from_name + "\t" + to_name + "\n"); } String method = "IMPM"; String score = "1.0"; for (int i = 0; i < chemicals.size(); i++) { Vector chemical = (Vector) chemicals.get(i); String type = (String) chemical.get(0); String chem = (String) chemical.get(1); if (!ec_numbers.contains(chem) && (type.compareTo("EC") == 0)) { if (chem.compareTo("1.14.-") == 0) chem = "1.14.-.-"; else System.out.println("MISSING EC: " + chem); } String id = type + ":" + chem; String entry = uid + "\t" + id + "\t" + method + "\t" + score + "\n"; if (type.compareTo("CAS") == 0) cas_mapping.write(entry); else ec_mapping.write(entry); } } else inputLine = getNextLine(in); } System.out.println("End import descriptors"); tools.printDate(); in.close(); out_concept.close(); out_concept_name.close(); out_relation.close(); cas_mapping.close(); ec_mapping.close(); outfile = outfiledir + "\\cas"; out_concept = new BufferedWriter(new FileWriter(outfile + "_concept.txt")); out_concept_name = new BufferedWriter(new FileWriter(outfile + "_concept_name.txt")); BufferedWriter out_concept_acc = new BufferedWriter(new FileWriter(outfile + "_concept_acc.txt")); for (int i = 0; i < allCASchemicals.size(); i++) { Vector chemical = (Vector) allCASchemicals.get(i); String cas_id = "CAS:" + (String) chemical.get(1); String cas_name = (String) chemical.get(2); String cas_pos_tag = ""; String cas_description = (String) chemical.get(3); String cas_element_of = "CAS"; String cas_is_primary = "0"; out_concept.write(cas_id + "\t" + cas_pos_tag + "\t" + cas_description + "\t"); out_concept.write(cas_element_of + "\t" + cas_is_primary + "\n"); String cas_name_stemmed = ""; String cas_name_tagged = ""; String cas_is_unique = "0"; String cas_is_preferred = "0"; String cas_original_name = cas_name; String cas_is_not_substring = "0"; out_concept_name.write(cas_id + "\t" + cas_name + "\t" + cas_name_stemmed + "\t"); out_concept_name.write(cas_name_tagged + "\t" + cas_element_of + "\t"); out_concept_name.write(cas_is_unique + "\t" + cas_is_preferred + "\t"); out_concept_name.write(cas_original_name + "\t" + cas_is_not_substring + "\n"); out_concept_acc.write(cas_id + "\t" + (String) chemical.get(1) + "\t"); out_concept_acc.write(cas_element_of + "\n"); } out_concept.close(); out_concept_name.close(); out_concept_acc.close(); } catch (Exception e) { settings.writeLog("Error while reading MESH descriptor file: " + e.getMessage()); } }
|
11
|
Code Sample 1:
public static String md5(String input) { String res = ""; try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(input.getBytes()); byte[] md5 = algorithm.digest(); String tmp = ""; for (int i = 0; i < md5.length; i++) { tmp = (Integer.toHexString(0xFF & md5[i])); if (tmp.length() == 1) res += "0" + tmp; else res += tmp; } } catch (NoSuchAlgorithmException ex) { } return res; }
Code Sample 2:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { try { URL url = new URL(upgradeURL); InputStream in = url.openStream(); BufferedInputStream buffIn = new BufferedInputStream(in); FileOutputStream out = new FileOutputStream(""); String bytes = ""; int data = buffIn.read(); int downloadedByteCount = 1; while (data != -1) { out.write(data); bytes.concat(Character.toString((char) data)); buffIn.read(); downloadedByteCount++; updateProgressBar(downloadedByteCount); } out.close(); buffIn.close(); MessageDigest m = MessageDigest.getInstance("MD5"); m.update(bytes.getBytes()); String hash = m.digest().toString(); if (hash.length() == 31) { hash = "0" + hash; } if (!hash.equalsIgnoreCase(md5Hash)) { } } catch (MalformedURLException e) { } catch (IOException io) { } catch (NoSuchAlgorithmException a) { } }
|
00
|
Code Sample 1:
public ReqJsonContent(String useragent, String urlstr, String domain, String pathinfo, String alarmMessage) throws IOException { URL url = new URL(urlstr); URLConnection conn = url.openConnection(); conn.setRequestProperty("user-agent", useragent); conn.setRequestProperty("pathinfo", pathinfo); conn.setRequestProperty("domain", domain); try { BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF8")); response = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); jsonContectResult = response.toString(); } catch (SocketTimeoutException e) { log.severe(alarmMessage + "-> " + e.getMessage()); jsonContectResult = null; } catch (Exception e) { log.severe(alarmMessage + "-> " + e.getMessage()); jsonContectResult = null; } }
Code Sample 2:
public void delete(String name) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); AttributeTable attribute = new AttributeTable(); attribute.deleteAllForType(stmt, name); String sql = "delete from AttributeCategories " + "where CategoryName = '" + name + "'"; stmt.executeUpdate(sql); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } }
|
00
|
Code Sample 1:
public void update() { new Thread(new Runnable() { @Override public void run() { try { jButton1.setEnabled(false); jButton2.setEnabled(false); URL url = new URL(updatePath + "currentVersion.txt"); URLConnection con = url.openConnection(); con.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String line; for (int i = 0; (line = in.readLine()) != null; i++) { URL fileUrl = new URL(updatePath + line); URLConnection filecon = fileUrl.openConnection(); InputStream stream = fileUrl.openStream(); int oneChar, count = 0; int size = filecon.getContentLength(); jProgressBar1.setMaximum(size); jProgressBar1.setValue(0); File testFile = new File(line); String build = ""; for (String dirtest : line.split("/")) { build += dirtest; if (!build.contains(".")) { File dirfile = new File(build); if (!dirfile.exists()) { dirfile.mkdir(); } } build += "/"; } if (testFile.length() == size) { } else { transferFile(line, fileUrl, size); if (line.endsWith("documents.zip")) { ZipInputStream in2 = new ZipInputStream(new FileInputStream(line)); ZipEntry entry; String pathDoc = line.split("documents.zip")[0]; File docDir = new File(pathDoc + "documents"); if (!docDir.exists()) { docDir.mkdir(); } while ((entry = in2.getNextEntry()) != null) { String outFilename = pathDoc + "documents/" + entry.getName(); OutputStream out = new BufferedOutputStream(new FileOutputStream(outFilename)); byte[] buf = new byte[1024]; int len; while ((len = in2.read(buf)) > 0) { out.write(buf, 0, len); } out.close(); } in2.close(); } if (line.endsWith("mysql.zip")) { ZipFile zipfile = new ZipFile(line); Enumeration entries = zipfile.entries(); String pathDoc = line.split("mysql.zip")[0]; File docDir = new File(pathDoc + "mysql"); if (!docDir.exists()) { docDir.mkdir(); } while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (entry.isDirectory()) { System.err.println("Extracting directory: " + entry.getName()); (new File(pathDoc + "mysql/" + entry.getName())).mkdir(); continue; } System.err.println("Extracting file: " + entry.getName()); InputStream in2 = zipfile.getInputStream(entry); OutputStream out = new BufferedOutputStream(new FileOutputStream(pathDoc + "mysql/" + entry.getName())); byte[] buf = new byte[1024]; int len; while ((len = in2.read(buf)) > 0) { out.write(buf, 0, len); } in2.close(); out.close(); } } } jProgressBar2.setValue(i + 1); labelFileProgress.setText((i + 1) + "/" + numberFiles); } labelStatus.setText("Update Finished"); jButton1.setVisible(false); jButton2.setText("Finished"); jButton1.setEnabled(true); jButton2.setEnabled(true); } catch (IOException ex) { Logger.getLogger(Updater.class.getName()).log(Level.SEVERE, null, ex); } } }).start(); }
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:
private void initStreams() throws IOException { if (audio != null) { audio.close(); } if (url != null) { audio = new OggInputStream(url.openStream()); } else { audio = new OggInputStream(ResourceLoader.getResourceAsStream(ref)); } }
Code Sample 2:
public FTPClient sample1a(String server, int port, String username, String password) throws SocketException, IOException { FTPClient ftpClient = new FTPClient(); ftpClient.connect(server, port); ftpClient.login(username, password); return ftpClient; }
|
11
|
Code Sample 1:
public static final String md5(final String s) { try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte messageDigest[] = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { String h = Integer.toHexString(0xFF & messageDigest[i]); while (h.length() < 2) h = "0" + h; hexString.append(h); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { } return ""; }
Code Sample 2:
public static String toPWD(String pwd) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(pwd.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } return md5StrBuff.toString(); }
|
00
|
Code Sample 1:
private void addConfigurationResource(final String fileName, NotFoundPolicy notFoundPolicy) { try { final ClassLoader cl = this.getClass().getClassLoader(); final Properties p = new Properties(); final URL url = cl.getResource(fileName); if (url == null) { throw new NakedObjectException("Failed to load configuration resource: " + fileName); } p.load(url.openStream()); LOG.info("configuration resource " + fileName + " loaded"); configuration.add(p); } catch (final Exception e) { if (notFoundPolicy == NotFoundPolicy.FAIL_FAST) { throw new NakedObjectException(e); } LOG.info("configuration resource " + fileName + " not found, but not needed"); } }
Code Sample 2:
public void testSimpleHttpPostsHTTP10() throws Exception { int reqNo = 20; Random rnd = new Random(); List testData = new ArrayList(reqNo); for (int i = 0; i < reqNo; i++) { int size = rnd.nextInt(5000); byte[] data = new byte[size]; rnd.nextBytes(data); testData.add(data); } this.server.registerHandler("*", new HttpRequestHandler() { public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (request instanceof HttpEntityEnclosingRequest) { HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] data = EntityUtils.toByteArray(incoming); ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(false); response.setEntity(outgoing); } else { StringEntity outgoing = new StringEntity("No content"); response.setEntity(outgoing); } } }); this.server.start(); this.client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_0); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); HttpHost host = new HttpHost("localhost", this.server.getPort()); try { for (int r = 0; r < reqNo; r++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, this.client.getParams()); } BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/"); byte[] data = (byte[]) testData.get(r); ByteArrayEntity outgoing = new ByteArrayEntity(data); post.setEntity(outgoing); HttpResponse response = this.client.execute(post, host, conn); assertEquals(HttpVersion.HTTP_1_0, response.getStatusLine().getProtocolVersion()); byte[] received = EntityUtils.toByteArray(response.getEntity()); byte[] expected = (byte[]) testData.get(r); assertEquals(expected.length, received.length); for (int i = 0; i < expected.length; i++) { assertEquals(expected[i], received[i]); } if (!this.client.keepAlive(response)) { conn.close(); } } HttpConnectionMetrics cm = conn.getMetrics(); assertEquals(reqNo, cm.getRequestCount()); assertEquals(reqNo, cm.getResponseCount()); } finally { conn.close(); this.server.shutdown(); } }
|
00
|
Code Sample 1:
public void doActionxxx() { try { System.out.println("app: ggc"); String server_name = "http://192.168.4.3:8080/"; server_name = server_name.trim(); if (server_name.length() == 0) { server_name = "http://www.atech-software.com/"; } else { if (!server_name.startsWith("http://")) server_name = "http://" + server_name; if (!server_name.endsWith("/")) server_name = server_name + "/"; } URL url = new URL(server_name + "ATechUpdateGetFile?" + "" + "file_id=1" + "&" + "version_requested=1"); InputStream is = url.openStream(); RandomAccessFile raf = new RandomAccessFile("/home/andy/test.jpg", "rw"); ArrayList<Integer> list = new ArrayList<Integer>(); float size = 671200; long current_size = 0; System.out.println("File size: " + is.available()); byte[] array = new byte[1024]; while (is.available() > 0) { if (is.available() < 1024) { array = new byte[is.available()]; } is.read(array); raf.write(array); current_size += array.length; System.out.println("Progress: " + ((current_size / size) * 100)); } System.out.println("Size Arr: " + list.size()); CheckSumUtility csu = new CheckSumUtility(); System.out.println("Checksum: " + csu.getChecksumValue("/home/andy/test.jpg")); } catch (Exception ex) { ex.printStackTrace(); } }
Code Sample 2:
public void add(final String name, final String content) { forBundle(new BundleManipulator() { public boolean includeEntry(String entryName) { return !name.equals(entryName); } public void finish(Bundle bundle, ZipOutputStream zout) throws IOException { zout.putNextEntry(new ZipEntry(name)); IOUtils.copy(new StringReader(content), zout, "UTF-8"); } }); }
|
11
|
Code Sample 1:
public static final TreeSet<String> getValues(String baseurl, String rftId, String svcId) { TreeSet<String> values = new TreeSet<String>(); String[] fragments = rftId.split("/"); String e_repoUri = null; String e_svcId = null; try { e_repoUri = URLEncoder.encode(rftId, "UTF-8"); e_svcId = URLEncoder.encode(svcId, "UTF-8"); } catch (UnsupportedEncodingException e) { log.error("UnsupportedEncodingException resulted attempting to encode " + rftId); } String openurl = baseurl + "/" + fragments[2] + "/openurl-aDORe7" + "?rft_id=" + e_repoUri + "&svc_id=" + e_svcId + "&url_ver=Z39.88-2004"; log.info("Obtaining Content Values from: " + openurl); try { URL url = new URL(openurl); long s = System.currentTimeMillis(); URLConnection conn = url.openConnection(); int timeoutMs = 1000 * 60 * 30; conn.setConnectTimeout(timeoutMs); conn.setReadTimeout(timeoutMs); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); log.info("Query Time: " + (System.currentTimeMillis() - s) + "ms"); String line; while ((line = in.readLine()) != null) { values.add(line); } in.close(); } catch (Exception ex) { log.error("problem with openurl:" + openurl + ex.getMessage()); throw new RuntimeException(ex); } return values; }
Code Sample 2:
public void refreshStatus() { if (!enabledDisplay) return; try { String url = getServerFortURL(); BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String data = null; int counter = 0; while ((data = reader.readLine()) != null && counter < 9) { status[counter] = UNKNOWN; if (data.matches(".*_alsius.gif.*")) { status[counter] = ALSIUS; counter++; } if (data.matches(".*_syrtis.gif.*")) { status[counter] = SYRTIS; counter++; } if (data.matches(".*_ignis.gif.*")) { status[counter] = IGNIS; counter++; } } } catch (Exception exc) { for (int i = 0; i < status.length; i++) status[i] = UNKNOWN; } }
|
00
|
Code Sample 1:
protected void xInitGUI() { this.jlHead.setText(formater.getText("select_marc21_title")); this.jlResId.setText(formater.getText("select_marc21_label_text")); this.jlResId.setToolTipText(formater.getText("select_marc21_label_description")); ElvisListModel model = new ElvisListModel(); this.jlResourceList.setModel(model); try { URL urlListResources = new URL(ElvisRegistry.getInstance().getProperty("elvis.server") + "/servlet/listResources?xpath=document()//Book"); InputStream streamResources = urlListResources.openStream(); XmlPullParser xpp = XmlPullParserFactory.newInstance().newPullParser(); xpp.setInput(new InputStreamReader(streamResources)); int type = xpp.getEventType(); while (type != XmlPullParser.END_DOCUMENT) { if (type == XmlPullParser.START_TAG && "Resource".equals(xpp.getName())) { model.add(xpp.getAttributeValue("", "resId"), xpp.getAttributeValue("", "author"), xpp.getAttributeValue("", "title")); } type = xpp.next(); } streamResources.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } catch (XmlPullParserException xppe) { xppe.printStackTrace(); } ListSelectionModel selectionModel = this.jlResourceList.getSelectionModel(); selectionModel.addListSelectionListener(new ListSelectionListener() { /** * @param e Description of the Parameter * @see javax.swing.event.ListSelectionListener#valueChanged(javax.swing.event.ListSelectionEvent) */ public void valueChanged(ListSelectionEvent e) { int index = e.getFirstIndex(); boolean isAdjusting = e.getValueIsAdjusting(); if (!isAdjusting) { ElvisListModel _model = (ElvisListModel) jlResourceList.getModel(); jtfResId.setText(_model.get(index).getId()); } } }); }
Code Sample 2:
private static String getVisitorId(String guid, String account, String userAgent, Cookie cookie) throws NoSuchAlgorithmException, UnsupportedEncodingException { if (cookie != null && cookie.getValue() != null) { return cookie.getValue(); } String message; if (!isEmpty(guid)) { message = guid + account; } else { message = userAgent + getRandomNumber() + UUID.randomUUID().toString(); } MessageDigest m = MessageDigest.getInstance("MD5"); m.update(message.getBytes("UTF-8"), 0, message.length()); byte[] sum = m.digest(); BigInteger messageAsNumber = new BigInteger(1, sum); String md5String = messageAsNumber.toString(16); while (md5String.length() < 32) { md5String = "0" + md5String; } return "0x" + md5String.substring(0, 16); }
|
11
|
Code Sample 1:
public static String SHA(String s) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(s.getBytes(), 0, s.getBytes().length); byte[] hash = md.digest(); StringBuilder sb = new StringBuilder(); int msb; int lsb = 0; int i; for (i = 0; i < hash.length; i++) { msb = ((int) hash[i] & 0x000000FF) / 16; lsb = ((int) hash[i] & 0x000000FF) % 16; sb.append(hexChars[msb]); sb.append(hexChars[lsb]); } return sb.toString(); } catch (NoSuchAlgorithmException e) { return null; } }
Code Sample 2:
public static String digest(String text, String algorithm, String charsetName) { try { MessageDigest md = MessageDigest.getInstance(algorithm); md.update(text.getBytes(charsetName), 0, text.length()); return convertToHex(md.digest()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("unexpected exception: " + e, e); } catch (UnsupportedEncodingException e) { throw new RuntimeException("unexpected exception: " + e, e); } }
|
11
|
Code Sample 1:
void run(String[] args) { InputStream istream = System.in; System.out.println("TradeMaximizer " + version); String filename = parseArgs(args, false); if (filename != null) { System.out.println("Input from: " + filename); try { if (filename.startsWith("http:") || filename.startsWith("ftp:")) { URL url = new URL(filename); istream = url.openStream(); } else istream = new FileInputStream(filename); } catch (IOException ex) { fatalError(ex.toString()); } } List<String[]> wantLists = readWantLists(istream); if (wantLists == null) return; if (options.size() > 0) { System.out.print("Options:"); for (String option : options) System.out.print(" " + option); System.out.println(); } System.out.println(); try { MessageDigest digest = MessageDigest.getInstance("MD5"); for (String[] wset : wantLists) { for (String w : wset) { digest.update((byte) ' '); digest.update(w.getBytes()); } digest.update((byte) '\n'); } System.out.println("Input Checksum: " + toHexString(digest.digest())); } catch (NoSuchAlgorithmException ex) { } parseArgs(args, true); if (iterations > 1 && seed == -1) { seed = System.currentTimeMillis(); System.out.println("No explicit SEED, using " + seed); } if (!(metric instanceof MetricSumSquares) && priorityScheme != NO_PRIORITIES) System.out.println("Warning: using priorities with the non-default metric is normally worthless"); buildGraph(wantLists); if (showMissing && officialNames != null && officialNames.size() > 0) { for (String name : usedNames) officialNames.remove(name); List<String> missing = new ArrayList<String>(officialNames); Collections.sort(missing); for (String name : missing) { System.out.println("**** Missing want list for official name " + name); } System.out.println(); } if (showErrors && errors.size() > 0) { Collections.sort(errors); System.out.println("ERRORS:"); for (String error : errors) System.out.println(error); System.out.println(); } long startTime = System.currentTimeMillis(); graph.removeImpossibleEdges(); List<List<Graph.Vertex>> bestCycles = graph.findCycles(); int bestMetric = metric.calculate(bestCycles); if (iterations > 1) { System.out.println(metric); graph.saveMatches(); for (int i = 0; i < iterations - 1; i++) { graph.shuffle(); List<List<Graph.Vertex>> cycles = graph.findCycles(); int newMetric = metric.calculate(cycles); if (newMetric < bestMetric) { bestMetric = newMetric; bestCycles = cycles; graph.saveMatches(); System.out.println(metric); } else if (verbose) System.out.println("# " + metric); } System.out.println(); graph.restoreMatches(); } long stopTime = System.currentTimeMillis(); displayMatches(bestCycles); if (showElapsedTime) System.out.println("Elapsed time = " + (stopTime - startTime) + "ms"); }
Code Sample 2:
public static String hash(String arg) throws NoSuchAlgorithmException { String input = arg; String output; MessageDigest md = MessageDigest.getInstance("SHA"); md.update(input.getBytes()); output = Hex.encodeHexString(md.digest()); return output; }
|
11
|
Code Sample 1:
private ChangeCapsule fetchServer(OWLOntology ontologyURI, Long sequenceNumber) throws IOException { String requestString = "http://" + InetAddress.getLocalHost().getHostName() + ":8080/ChangeServer"; requestString += "?fetch=" + URLEncoder.encode(ontologyURI.getURI().toString(), "UTF-8"); requestString += "&number" + sequenceNumber; URL url = new URL(requestString); BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer returned = new StringBuffer(); String str; while (null != ((str = input.readLine()))) { returned.append(str); } input.close(); ChangeCapsule cp = new ChangeCapsule(returned.toString()); return cp; }
Code Sample 2:
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.listview); HttpGet request = new HttpGet(SERVICE_URI + "/json/getroutes/1"); request.setHeader("Accept", "application/json"); request.setHeader("Content-type", "application/json"); DefaultHttpClient httpClient = new DefaultHttpClient(); String theString = new String(""); try { HttpResponse response = httpClient.execute(request); HttpEntity responseEntity = response.getEntity(); InputStream stream = responseEntity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); Vector<String> vectorOfStrings = new Vector<String>(); String tempString = new String(); String tempStringAgent = new String(); String tempStringClient = new String(); String tempStringRoute = new String(); String tempStringZone = new String(); StringBuilder builder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { builder.append(line); } stream.close(); theString = builder.toString(); JSONObject json = new JSONObject(theString); Log.i("_GetClient_", "<jsonobject>\n" + json.toString() + "\n</jsonobject>"); this.dm = new DataManipulator(this); JSONArray nameArray = json.getJSONArray("GetRoutesByAgentResult"); for (int i = 0; i < nameArray.length(); i++) { tempStringAgent = nameArray.getJSONObject(i).getString("Agent"); tempStringClient = nameArray.getJSONObject(i).getString("Client"); tempStringRoute = nameArray.getJSONObject(i).getString("Route"); tempStringZone = nameArray.getJSONObject(i).getString("Zone"); Log.i("_GetClient_", "<Agent" + i + ">" + tempStringAgent + "</Agent" + i + ">\n"); Log.i("_GetClient_", "<Client" + i + ">" + tempStringClient + "</Client" + i + ">\n"); Log.i("_GetClient_", "<Route" + i + ">" + tempStringRoute + "</Route" + i + ">\n"); Log.i("_GetClient_", "<Zone" + i + ">" + tempStringZone + "</Zone" + i + ">\n"); tempString = nameArray.getJSONObject(i).getString("Client") + "\n" + nameArray.getJSONObject(i).getString("Route") + "\n" + nameArray.getJSONObject(i).getString("Zone"); vectorOfStrings.add(new String(tempString)); } int orderCount = vectorOfStrings.size(); String[] orderTimeStamps = new String[orderCount]; vectorOfStrings.copyInto(orderTimeStamps); setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, orderTimeStamps)); } catch (Exception e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public static double[][] getCurrency() throws IOException { URL url = new URL("http://hk.finance.yahoo.com/currency"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "big5")); double currency[][] = new double[11][11]; while (true) { String line = in.readLine(); String reg = "<td\\s((align=\"right\"\\sclass=\"yfnc_tabledata1\")" + "|(class=\"yfnc_tabledata1\"\\salign=\"right\"))>" + "([\\d|\\.]+)</td>"; Matcher m = Pattern.compile(reg).matcher(line); int i = 0, j = 0; boolean isfound = false; while (m.find()) { isfound = true; currency[i][j] = Double.parseDouble(m.group(4)); if (j == 10) { j = 0; i++; } else j++; } if (isfound) break; } return currency; }
Code Sample 2:
public void concatFiles() throws IOException { Writer writer = null; try { final File targetFile = new File(getTargetDirectory(), getTargetFile()); targetFile.getParentFile().mkdirs(); if (null != getEncoding()) { getLog().info("Writing aggregated file with encoding '" + getEncoding() + "'"); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile), getEncoding())); } else { getLog().info("WARNING: writing aggregated file with system encoding"); writer = new FileWriter(targetFile); } for (File file : getFiles()) { Reader reader = null; try { if (null != getEncoding()) { getLog().info("Reading file " + file.getCanonicalPath() + " with encoding '" + getEncoding() + "'"); reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), getEncoding())); } else { getLog().info("WARNING: Reading file " + file.getCanonicalPath() + " with system encoding"); reader = new FileReader(file); } IOUtils.copy(reader, writer); final String delimiter = getDelimiter(); if (delimiter != null) { writer.write(delimiter.toCharArray()); } } finally { IOUtils.closeQuietly(reader); } } } finally { IOUtils.closeQuietly(writer); } }
|
00
|
Code Sample 1:
private void openConnection() throws IOException { connection = (HttpURLConnection) url.openConnection(Global.getProxy()); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "text/xml; charset=" + XmlRpcMessages.getString("XmlRpcClient.Encoding")); if (requestProperties != null) { for (Iterator propertyNames = requestProperties.keySet().iterator(); propertyNames.hasNext(); ) { String propertyName = (String) propertyNames.next(); connection.setRequestProperty(propertyName, (String) requestProperties.get(propertyName)); } } }
Code Sample 2:
public void login() { if (email.isEmpty() || pass.isEmpty()) { NotifyUtil.warn("Acount Data", "You need to specify and account e-mail and password.", false); return; } final ProgressHandle handle = ProgressHandleFactory.createHandle("Connecting to Facebook ..."); final Runnable task = new Runnable() { @Override public void run() { handle.start(); handle.switchToIndeterminate(); FacebookJsonRestClient client = new FacebookJsonRestClient(API_KEY, SECRET); client.setIsDesktop(true); HttpURLConnection connection; List<String> cookies; try { String token = client.auth_createToken(); String post_url = "http://www.facebook.com/login.php"; String get_url = "http://www.facebook.com/login.php" + "?api_key=" + API_KEY + "&v=1.0" + "&auth_token=" + token; HttpURLConnection.setFollowRedirects(true); connection = (HttpURLConnection) new URL(get_url).openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401"); connection.setRequestProperty("Host", "www.facebook.com"); connection.setRequestProperty("Accept-Charset", "UFT-8"); connection.connect(); cookies = connection.getHeaderFields().get("Set-Cookie"); connection = (HttpURLConnection) new URL(post_url).openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401"); connection.setRequestProperty("Host", "www.facebook.com"); connection.setRequestProperty("Accept-Charset", "UFT-8"); if (cookies != null) { for (String cookie : cookies) { connection.addRequestProperty("Cookie", cookie.split(";", 2)[0]); } } String params = "api_key=" + API_KEY + "&auth_token=" + token + "&email=" + URLEncoder.encode(email, "UTF-8") + "&pass=" + URLEncoder.encode(pass, "UTF-8") + "&v=1.0"; connection.setRequestProperty("Content-Length", Integer.toString(params.length())); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setDoOutput(true); connection.connect(); connection.getOutputStream().write(params.toString().getBytes("UTF-8")); connection.getOutputStream().close(); cookies = connection.getHeaderFields().get("Set-Cookie"); if (cookies == null) { ActionListener listener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String url = "http://www.chartsy.org/facebook/"; DesktopUtil.browseAndWarn(url, null); } }; NotifyUtil.show("Application Permission", "You need to grant permission first.", MessageType.WARNING, listener, false); connection.disconnect(); loggedIn = false; } else { sessionKey = client.auth_getSession(token); sessionSecret = client.getSessionSecret(); loggedIn = true; } connection.disconnect(); handle.finish(); } catch (FacebookException fex) { handle.finish(); NotifyUtil.error("Login Error", fex.getMessage(), fex, false); } catch (IOException ioex) { handle.finish(); NotifyUtil.error("Login Error", ioex.getMessage(), ioex, false); } } }; WindowManager.getDefault().invokeWhenUIReady(task); }
|
00
|
Code Sample 1:
public static String generateDigest(String password, String saltHex, String alg) { try { MessageDigest sha = MessageDigest.getInstance(alg); byte[] salt = new byte[0]; if (saltHex != null) { salt = fromHex(saltHex); } String label = null; if (alg.startsWith("SHA")) { label = (salt.length <= 0) ? "{SHA}" : "{SSHA}"; } else if (alg.startsWith("MD5")) { label = (salt.length <= 0) ? "{MD5}" : "{SMD5}"; } sha.reset(); sha.update(password.getBytes()); sha.update(salt); byte[] pwhash = sha.digest(); StringBuffer digest = new StringBuffer(label); digest.append(Base64.encode(concatenate(pwhash, salt)).toCharArray()); return digest.toString(); } catch (NoSuchAlgorithmException nsae) { throw new RuntimeException("failed to find " + "algorithm for password hashing.", nsae); } }
Code Sample 2:
public PropertiesImpl(URL url) { this(); InputStream in = null; lock.lock(); try { in = url.openStream(); PropertiesLexer lexer = new PropertiesLexer(in); lexer.lex(); List<PropertiesToken> list = lexer.getList(); new PropertiesParser(list, this).parse(); } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) try { in.close(); } catch (IOException e) { } lock.unlock(); } }
|
11
|
Code Sample 1:
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("application/json"); resp.setCharacterEncoding("utf-8"); String format = req.getParameter("format"); EntityManager em = EMF.get().createEntityManager(); String uname = (req.getParameter("uname") == null) ? "" : req.getParameter("uname"); String passwd = (req.getParameter("passwd") == null) ? "" : req.getParameter("passwd"); String name = (req.getParameter("name") == null) ? "" : req.getParameter("name"); String email = (req.getParameter("email") == null) ? "" : req.getParameter("email"); if (uname == null || uname.equals("") || uname.length() < 4) { if (format != null && format.equals("xml")) resp.getWriter().print(Error.unameTooShort(uname).toXML(em)); else resp.getWriter().print(Error.unameTooShort(uname).toJSON(em)); resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } if (User.fromUserName(em, uname) != null) { if (format != null && format.equals("xml")) resp.getWriter().print(Error.userExists(uname).toXML(em)); else resp.getWriter().print(Error.userExists(uname).toJSON(em)); resp.setStatus(HttpServletResponse.SC_CONFLICT); em.close(); return; } if (passwd.equals("") || passwd.length() < 6) { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); if (format != null && format.equals("xml")) resp.getWriter().print(Error.passwdTooShort(uname).toXML(em)); else resp.getWriter().print(Error.passwdTooShort(uname).toJSON(em)); em.close(); return; } User u = new User(); u.setUsername(uname); u.setPasswd(passwd); u.setName(name); u.setEmail(email); u.setPaid(false); StringBuffer apikey = new StringBuffer(); try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); String api = System.nanoTime() + "" + System.identityHashCode(this) + "" + uname; algorithm.update(api.getBytes()); byte[] digest = algorithm.digest(); for (int i = 0; i < digest.length; i++) { apikey.append(Integer.toHexString(0xFF & digest[i])); } } catch (NoSuchAlgorithmException e) { resp.setStatus(500); if (format != null && format.equals("xml")) resp.getWriter().print(Error.unknownError().toXML(em)); else resp.getWriter().print(Error.unknownError().toJSON(em)); log.severe(e.toString()); em.close(); return; } u.setApiKey(apikey.toString()); EntityTransaction tx = em.getTransaction(); tx.begin(); try { em.persist(u); tx.commit(); } catch (Throwable t) { log.severe("Error adding user " + uname + " Reason:" + t.getMessage()); tx.rollback(); resp.setStatus(500); if (format != null && format.equals("xml")) resp.getWriter().print(Error.unknownError().toXML(em)); else resp.getWriter().print(Error.unknownError().toJSON(em)); return; } log.info("User " + u.getName() + " was created successfully"); resp.setStatus(HttpServletResponse.SC_CREATED); if (format != null && format.equals("xml")) resp.getWriter().print(u.toXML(em)); else resp.getWriter().print(u.toJSON(em)); em.close(); }
Code Sample 2:
private String digestMd5(final String password) { String base64; try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(password.getBytes()); base64 = fr.cnes.sitools.util.Base64.encodeBytes(digest.digest()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } return "{MD5}" + base64; }
|
00
|
Code Sample 1:
public static BufferedReader openForReading(String name, URI base, ClassLoader classLoader) throws IOException { if ((name == null) || name.trim().equals("")) { return null; } if (name.trim().equals("System.in")) { if (STD_IN == null) { STD_IN = new BufferedReader(new InputStreamReader(System.in)); } return STD_IN; } URL url = nameToURL(name, base, classLoader); if (url == null) { throw new IOException("Could not convert \"" + name + "\" with base \"" + base + "\" to a URL."); } InputStreamReader inputStreamReader = null; try { inputStreamReader = new InputStreamReader(url.openStream()); } catch (IOException ex) { try { URL possibleJarURL = ClassUtilities.jarURLEntryResource(url.toString()); if (possibleJarURL != null) { inputStreamReader = new InputStreamReader(possibleJarURL.openStream()); } return new BufferedReader(inputStreamReader); } catch (Exception ex2) { try { if (inputStreamReader != null) { inputStreamReader.close(); } } catch (IOException ex3) { } IOException ioException = new IOException("Failed to open \"" + url + "\"."); ioException.initCause(ex); throw ioException; } } return new BufferedReader(inputStreamReader); }
Code Sample 2:
@Override protected Object transform(Row inputs) throws FunctionException { StringBuffer buffer = new StringBuffer(); for (IColumn c : inputs.getColumns()) { buffer.append(c.getValueAsString() + "|"); } try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(buffer.toString().getBytes()); byte[] hash = digest.digest(); return getHex(hash); } catch (Exception e) { throw new FunctionException(e); } }
|
11
|
Code Sample 1:
@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); } }
Code Sample 2:
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.addHeader("Cache-Control", "max-age=" + Constants.HTTP_CACHE_SECONDS); String uuid = req.getRequestURI().substring(req.getRequestURI().indexOf(Constants.SERVLET_FULL_PREFIX) + Constants.SERVLET_FULL_PREFIX.length() + 1); boolean notScale = ClientUtils.toBoolean(req.getParameter(Constants.URL_PARAM_NOT_SCALE)); ServletOutputStream os = resp.getOutputStream(); if (uuid != null && !"".equals(uuid)) { try { String mimetype = fedoraAccess.getMimeTypeForStream(uuid, FedoraUtils.IMG_FULL_STREAM); if (mimetype == null) { mimetype = "image/jpeg"; } ImageMimeType loadFromMimeType = ImageMimeType.loadFromMimeType(mimetype); if (loadFromMimeType == ImageMimeType.JPEG || loadFromMimeType == ImageMimeType.PNG) { StringBuffer sb = new StringBuffer(); sb.append(config.getFedoraHost()).append("/objects/").append(uuid).append("/datastreams/IMG_FULL/content"); InputStream is = RESTHelper.get(sb.toString(), config.getFedoraLogin(), config.getFedoraPassword(), false); if (is == null) { return; } try { IOUtils.copyStreams(is, os); } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Unable to open full image.", e); } finally { os.flush(); if (is != null) { try { is.close(); } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Unable to close stream.", e); } finally { is = null; } } } } else { Image rawImg = KrameriusImageSupport.readImage(uuid, FedoraUtils.IMG_FULL_STREAM, this.fedoraAccess, 0, loadFromMimeType); BufferedImage scaled = null; if (!notScale) { scaled = KrameriusImageSupport.getSmallerImage(rawImg, 1250, 1000); } else { scaled = KrameriusImageSupport.getSmallerImage(rawImg, 2500, 2000); } KrameriusImageSupport.writeImageToStream(scaled, "JPG", os); resp.setContentType(ImageMimeType.JPEG.getValue()); resp.setStatus(HttpURLConnection.HTTP_OK); } } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Unable to open full image.", e); } catch (XPathExpressionException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Unable to create XPath expression.", e); } finally { os.flush(); } } }
|
00
|
Code Sample 1:
private void btnOkActionPerformed(java.awt.event.ActionEvent evt) { try { int id = 0; String sql = "SELECT MAX(ID) as MAX_ID from CORE_USER_GROUPS"; PreparedStatement pStmt = Database.getMyConnection().prepareStatement(sql); ResultSet rs = pStmt.executeQuery(); if (rs.next()) { id = rs.getInt("MAX_ID") + 1; } else { id = 1; } Database.close(pStmt); sql = "INSERT INTO CORE_USER_GROUPS" + " (ID, GRP_NAME, GRP_DESC, DATE_INITIAL, DATE_FINAL, IND_STATUS)" + " VALUES (?, ?, ?, ?, ?, ?)"; pStmt = Database.getMyConnection().prepareStatement(sql); pStmt.setInt(1, id); pStmt.setString(2, txtGrpName.getText()); pStmt.setString(3, txtGrpDesc.getText()); pStmt.setDate(4, Utils.getTodaySql()); pStmt.setDate(5, Date.valueOf("9999-12-31")); pStmt.setString(6, "A"); pStmt.executeUpdate(); Database.getMyConnection().commit(); Database.close(pStmt); MessageBox.ok("New group added successfully", this); rs = getGroups(); tblGroups.setModel(new GroupsTableModel(rs)); Database.close(rs); } catch (SQLException e) { log.error("Failed with update operation \n" + e.getMessage()); MessageBox.ok("Failed to create the new group in the database", this); try { Database.getMyConnection().rollback(); } catch (Exception inner) { } ; } catch (IllegalArgumentException e) { log.error("Illegal argument for the DATE_FINAL \n" + e.getMessage()); MessageBox.ok("Failed to create the new group in the database", this); try { Database.getMyConnection().rollback(); } catch (Exception inner) { } ; } finally { txtGrpName.setEnabled(false); txtGrpDesc.setEnabled(false); btnOk.setEnabled(false); btnCancel.requestFocus(); } }
Code Sample 2:
private void downloadFile(String url, File destFile) { try { System.out.println("Downloading " + url + " to " + destFile + "..."); destFile.getParentFile().mkdirs(); OutputStream out = new FileOutputStream(destFile); URLConnection conn = new URL(url).openConnection(); InputStream in = conn.getInputStream(); int totalSize = conn.getContentLength(), downloadedSize = 0, size; byte[] buffer = new byte[32768]; ProgressMonitor pm = new ProgressMonitor(null, "Downloading " + url, "", 0, totalSize); pm.setMillisToDecideToPopup(100); pm.setMillisToPopup(500); boolean canceled = false; while ((size = in.read(buffer)) > 0 && !(canceled = pm.isCanceled())) { out.write(buffer, 0, size); pm.setProgress(downloadedSize += size); pm.setNote((100 * downloadedSize / totalSize) + "% finished"); } in.close(); out.close(); if (canceled) { destFile.delete(); fatalError("Starting canceled", "Downloading canceled. Exiting..."); } pm.close(); } catch (IOException ex) { ex.printStackTrace(); destFile.delete(); fatalError("Download Error", "Couldn't download file " + url + ": " + ex); } }
|
00
|
Code Sample 1:
private String hash(String message) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e) { throw new AssertionError("Can't find the SHA1 algorithm in the java.security package"); } String saltString = String.valueOf(12345); md.update(saltString.getBytes()); md.update(message.getBytes()); byte[] digestBytes = md.digest(); StringBuffer digestSB = new StringBuffer(); for (int i = 0; i < digestBytes.length; i++) { int lowNibble = digestBytes[i] & 0x0f; int highNibble = (digestBytes[i] >> 4) & 0x0f; digestSB.append(Integer.toHexString(highNibble)); digestSB.append(Integer.toHexString(lowNibble)); } String digestStr = digestSB.toString().trim(); return digestStr; }
Code Sample 2:
public static void reset() throws Exception { Session session = DataStaticService.getHibernateSessionFactory().openSession(); try { Connection connection = session.connection(); try { Statement statement = connection.createStatement(); try { statement.executeUpdate("delete from Tag"); connection.commit(); } finally { statement.close(); } } catch (HibernateException e) { connection.rollback(); throw new Exception(e); } catch (SQLException e) { connection.rollback(); throw new Exception(e); } } catch (SQLException e) { throw new Exception(e); } finally { session.close(); } }
|
00
|
Code Sample 1:
public static void main(String[] args) throws IOException { httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); loginLocalhostr(); initialize(); HttpOptions httpoptions = new HttpOptions(localhostrurl); HttpResponse myresponse = httpclient.execute(httpoptions); HttpEntity myresEntity = myresponse.getEntity(); System.out.println(EntityUtils.toString(myresEntity)); fileUpload(); }
Code Sample 2:
public static Document getXHTMLDocument(URL _url) throws IOException { final Tidy tidy = new Tidy(); tidy.setQuiet(true); tidy.setShowWarnings(false); tidy.setXmlOut(true); final BufferedInputStream input_stream = new BufferedInputStream(_url.openStream()); return tidy.parseDOM(input_stream, null); }
|
00
|
Code Sample 1:
private FTPClient getClient() throws SocketException, IOException { FTPClient ftp = new FTPClient(); ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); ftp.setDefaultPort(getPort()); ftp.connect(getIp()); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { log.warn("FTP server refused connection: {}", getIp()); ftp.disconnect(); return null; } if (!ftp.login(getUsername(), getPassword())) { log.warn("FTP server refused login: {}, user: {}", getIp(), getUsername()); ftp.logout(); ftp.disconnect(); return null; } ftp.setControlEncoding(getEncoding()); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); return ftp; }
Code Sample 2:
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { PrintWriter writer = null; InputStream is = null; FileOutputStream fos = null; try { writer = response.getWriter(); } catch (IOException ex) { log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } String filename = request.getHeader("X-File-Name"); try { is = request.getInputStream(); fos = new FileOutputStream(new File(realPath + filename)); IOUtils.copy(is, fos); response.setStatus(response.SC_OK); writer.print("{success: true}"); } catch (FileNotFoundException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); }
|
11
|
Code Sample 1:
@Override public void handler(Map<String, Match> result, TargetPage target) { List<String> lines = new LinkedList<String>(); List<String> page = new LinkedList<String>(); try { URL url = new URL(target.getUrl()); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); String line = null; while ((line = reader.readLine()) != null) { page.add(line); } reader.close(); } catch (MalformedURLException e) { } catch (IOException e) { } try { result.put("27 svk par fix", MatchEventFactory.getFix27()); result.put("41 svk ita fix", MatchEventFactory.getFix41()); result.put("01 rsa mex", MatchEventFactory.get01()); result.put("02 uru fra", MatchEventFactory.get02()); result.put("04 kor gre", MatchEventFactory.get04()); result.put("03 arg ngr", MatchEventFactory.get03()); result.put("05 eng usa", MatchEventFactory.get05()); result.put("06 alg slo", MatchEventFactory.get06()); result.put("08 scg gha", MatchEventFactory.get08()); result.put("07 ger aus", MatchEventFactory.get07()); result.put("09 end den", MatchEventFactory.get09()); result.put("10 jpn cmr", MatchEventFactory.get10()); result.put("11 ita par", MatchEventFactory.get11()); result.put("12 nzl svk", MatchEventFactory.get12()); result.put("13 civ por", MatchEventFactory.get13()); result.put("14 bra prk", MatchEventFactory.get14()); result.put("15 hon chi", MatchEventFactory.get15()); result.put("16 esp sui", MatchEventFactory.get16()); result.put("17 rsa uru", MatchEventFactory.get17()); result.put("20 arg kor", MatchEventFactory.get20()); result.put("19 gre ngr", MatchEventFactory.get19()); result.put("18 fra mex", MatchEventFactory.get18()); result.put("21 ger scg", MatchEventFactory.get21()); result.put("22 slo usa", MatchEventFactory.get22()); result.put("23 eng alg", MatchEventFactory.get23()); result.put("25 end jpn", MatchEventFactory.get25()); result.put("24 gha aus", MatchEventFactory.get24()); result.put("26 cmr den", MatchEventFactory.get26()); result.put("27 slo par", MatchEventFactory.get27()); result.put("28 ita nzl", MatchEventFactory.get28()); result.put("29 bra civ", MatchEventFactory.get29()); result.put("30 por prk", MatchEventFactory.get30()); result.put("31 chi sui", MatchEventFactory.get31()); result.put("32 esp hon", MatchEventFactory.get32()); result.put("34 fra rsa", MatchEventFactory.get34()); result.put("33 mex uru", MatchEventFactory.get33()); result.put("35 ngr kor", MatchEventFactory.get35()); result.put("36 gre arg", MatchEventFactory.get36()); result.put("38 usa alg", MatchEventFactory.get38()); result.put("37 slo eng", MatchEventFactory.get37()); result.put("39 gha ger", MatchEventFactory.get39()); result.put("40 aus scg", MatchEventFactory.get40()); result.put("42 par nzl", MatchEventFactory.get42()); result.put("41 slo ita", MatchEventFactory.get41()); result.put("44 cmr ned", MatchEventFactory.get44()); result.put("43 den jpn", MatchEventFactory.get43()); result.put("45 por bra", MatchEventFactory.get45()); result.put("46 prk civ", MatchEventFactory.get46()); result.put("47 chi esp", MatchEventFactory.get47()); result.put("48 sui hon", MatchEventFactory.get48()); result.put("49 uru kor", MatchEventFactory.get49Team()); result.put("50 usa gha", MatchEventFactory.get50Team()); result.put("51 ger eng", MatchEventFactory.get51Team()); result.put("52 arg mex", MatchEventFactory.get52Team()); result.put("53 ned svk", MatchEventFactory.get53Team()); result.put("54 bra chi", MatchEventFactory.get54Team()); result.put("55 par jpn", MatchEventFactory.get55Team()); result.put("56 esp por", MatchEventFactory.get56Team()); result.put("57 ned bra", MatchEventFactory.get57Team()); result.put("58 uru gha", MatchEventFactory.get58Team()); result.put("59 arg ger", MatchEventFactory.get59Team()); result.put("49", MatchEventFactory.get49()); result.put("50", MatchEventFactory.get50()); result.put("51", MatchEventFactory.get51()); result.put("52", MatchEventFactory.get52()); result.put("53", MatchEventFactory.get53()); result.put("54", MatchEventFactory.get54()); this.stage2MatchHandler("318295", "55", "2010-06-29 22:30", result); this.stage2MatchHandler("318296", "56", "2010-06-30 02:30", result); this.stage2MatchHandler("318297", "57", "2010-07-02 22:00", result); this.stage2MatchHandler("318298", "58", "2010-07-03 02:30", result); this.stage2MatchHandler("318299", "59", "2010-07-03 22:00", result); this.stage2MatchHandler("318300", "60", "2010-07-04 02:30", result); this.stage2MatchHandler("318301", "61", "2010-07-07 02:30", result); this.stage2MatchHandler("318302", "62", "2010-07-08 02:30", result); this.stage2MatchHandler("318303", "63", "2010-07-11 02:30", result); this.stage2MatchHandler("318304", "64", "2010-07-12 02:30", result); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
private static void loadQueryProcessorFactories() { qpFactoryMap = new HashMap<String, QueryProcessorFactoryIF>(); Enumeration<URL> resources = null; try { resources = QueryUtils.class.getClassLoader().getResources(RESOURCE_STRING); } catch (IOException e) { log.error("Error while trying to look for " + "QueryProcessorFactoryIF implementations.", e); } while (resources != null && resources.hasMoreElements()) { URL url = resources.nextElement(); InputStream is = null; try { is = url.openStream(); } catch (IOException e) { log.warn("Error opening stream to QueryProcessorFactoryIF service description.", e); } if (is != null) { BufferedReader rdr = new BufferedReader(new InputStreamReader(is)); String line; try { while ((line = rdr.readLine()) != null) { try { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Class<?> c = Class.forName(line, true, classLoader); if (QueryProcessorFactoryIF.class.isAssignableFrom(c)) { QueryProcessorFactoryIF factory = (QueryProcessorFactoryIF) c.newInstance(); qpFactoryMap.put(factory.getQueryLanguage().toUpperCase(), factory); } else { log.warn("Wrong entry for QueryProcessorFactoryIF service " + "description, '" + line + "' is not implementing the " + "correct interface."); } } catch (Exception e) { log.warn("Could not create an instance for " + "QueryProcessorFactoryIF service '" + line + "'."); } } } catch (IOException e) { log.warn("Could not read from QueryProcessorFactoryIF " + "service descriptor.", e); } } } if (!qpFactoryMap.containsKey(DEFAULT_LANGUAGE)) { qpFactoryMap.put(DEFAULT_LANGUAGE, new TologQueryProcessorFactory()); } }
|
11
|
Code Sample 1:
public void startElement(String uri, String tag, String qName, org.xml.sax.Attributes attributes) throws SAXException { wabclient.Attributes prop = new wabclient.Attributes(attributes); try { if (tag.equals("window")) { if (prop == null) { System.err.println("window without properties"); return; } int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); Color bgcolor = prop.getValue("bgcolor", Color.white); String caption = prop.getValue("caption", ""); layout = prop.getValue("layout", 0); boolean statusbar = prop.getValue("statusbar", false); if (sheet.opentype == WABSheet.LAYERED) { Point pos = frame.getNextMDIPos(); sheet.setBounds(pos.x, pos.y, 400, 200); sheet.setNormalBounds(new Rectangle(pos.x, pos.y, 400, 200)); } else { sheet.setBounds(x, y, width, height); sheet.setNormalBounds(new Rectangle(x, y, width, height)); } if (sheet.opentype == WABSheet.MAXIMIZED) sheet.setMaximum(true); else sheet.setMaximum(false); sheet.setTitle(caption); frame.addSheetToMenu(caption); sheet.setBackground(bgcolor); if (layout == 1) sheet.getContentPane().setLayout(new FlowLayout()); else if (layout == 2) sheet.getContentPane().setLayout(new BorderLayout()); else sheet.getContentPane().setLayout(null); } else if (tag.equals("menu")) { if (prop == null) { System.err.println("menu without properties"); return; } String id = prop.getValue("id", ""); String label = prop.getValue("label", ""); if ((id != null && id.equals("WINDOW_MENU") || label.equalsIgnoreCase("window"))) { windowMenu = new JMenu(); menu = windowMenu; sheet.setWindowMenu(menu); } else { menu = new JMenu(); } menu.setText(label); sheet.menubar.add(menu); } else if (tag.equals("menuitem")) { if (prop == null) { System.err.println("menuitem without properties"); return; } JMenuItem item; String action = prop.getValue("action", ""); String label = prop.getValue("label", ""); boolean visible = prop.getValue("visible", true); String icon = prop.getValue("icon", ""); if (action.equals("WINDOW_OVERLAPPED")) { item = windowMenuOverlapped = new JMenuItem(); item.setActionCommand("10001"); item.addActionListener(frame); } else if (action.equals("WINDOW_TILE_HORIZONTALLY")) { item = windowMenuTile = new JMenuItem(); item.setActionCommand("10002"); item.addActionListener(frame); } else if (action.equals("WINDOW_TILE_VERTICALLY")) { item = windowMenuArrange = new JMenuItem(); item.setActionCommand("10003"); item.addActionListener(frame); } else { item = new JMenuItem(); item.setActionCommand(action); item.addActionListener((WABClient) global); } item.setText(label); if (!visible) menu.setVisible(false); menu.add(item); if (frame.getToolBar() != null) { if (icon.length() > 0) { try { ImageIcon img = new ImageIcon(new URL(icon)); BufferedImage image = new BufferedImage(25, 25, BufferedImage.TYPE_4BYTE_ABGR); Graphics g = image.createGraphics(); g.setColor(new Color(0, 0, 0, 0)); g.fillRect(0, 0, 25, 25); g.drawImage(img.getImage(), 4, 4, 16, 16, (ImageObserver) null); BufferedImage pressed = new BufferedImage(25, 25, BufferedImage.TYPE_4BYTE_ABGR); g = pressed.createGraphics(); g.setColor(new Color(0, 0, 0, 0)); g.fillRect(0, 0, 25, 25); g.drawImage(img.getImage(), 5, 5, 16, 16, (ImageObserver) null); g.setColor(new Color(132, 132, 132)); g.drawLine(0, 0, 24, 0); g.drawLine(0, 0, 0, 24); g.setColor(new Color(255, 255, 255)); g.drawLine(24, 24, 24, 0); g.drawLine(24, 24, 0, 24); BufferedImage over = new BufferedImage(25, 25, BufferedImage.TYPE_4BYTE_ABGR); g = over.createGraphics(); g.setColor(new Color(0, 0, 0, 0)); g.fillRect(0, 0, 25, 25); g.drawImage(img.getImage(), 4, 4, 16, 16, (ImageObserver) null); g.setColor(new Color(255, 255, 255)); g.drawLine(0, 0, 24, 0); g.drawLine(0, 0, 0, 24); g.setColor(new Color(132, 132, 132)); g.drawLine(24, 24, 24, 0); g.drawLine(24, 24, 0, 24); JButton b = new JButton(new ImageIcon(image)); b.setRolloverEnabled(true); b.setPressedIcon(new ImageIcon(pressed)); b.setRolloverIcon(new ImageIcon(over)); b.setToolTipText(label); b.setActionCommand(action); b.setFocusPainted(false); b.setBorderPainted(false); b.setContentAreaFilled(false); b.setMargin(new Insets(0, 0, 0, 0)); b.addActionListener(sheet); sheet.toolbar.add(b); } catch (Exception e) { } } } } else if (tag.equals("separator")) { menu.addSeparator(); } else if (tag.equals("choice")) { if (prop == null) { System.err.println("choice without properties"); return; } combo = new JComboBox(); list = null; int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); String id = prop.getValue("id", ""); Object constraints = prop.getValue("constraints"); boolean editable = prop.getValue("editable", false); boolean visible = prop.getValue("visible", true); boolean enabled = prop.getValue("enabled", true); combo_text = prop.getValue("text", ""); combo.setBounds(x, y, width, height); combo.setName((String) id); if (editable) { combo.setEditable(editable); combo.setSelectedItem(combo_text); } if (!visible) combo.setVisible(false); if (!enabled) combo.setEnabled(false); if (layout == 0) sheet.getContentPane().add(combo); else sheet.getContentPane().add(combo, constraints); } else if (tag.equals("list")) { if (prop == null) { System.err.println("list without properties"); return; } list = new JList(); combo = null; listdata = new Vector(); int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); String id = prop.getValue("id", ""); Object constraints = prop.getValue("constraints"); list.setName((String) id); list.setListData(listdata); JScrollPane sp = new JScrollPane(list); sp.setBounds(x, y, width, height); if (layout == 0) sheet.getContentPane().add(sp); else sheet.getContentPane().add(sp, constraints); } else if (tag.equals("option")) { if (prop == null) { System.err.println("choice.option without properties"); return; } String value = prop.getValue("value", ""); String text = prop.getValue("text", ""); if (list != null) listdata.addElement(new ComboOption(text, value)); if (combo != null) { ComboOption co = new ComboOption(text, value); combo.addItem(co); if (combo_text.equals(text.trim())) combo.setSelectedItem(co); } } else if (tag.equals("label")) { if (prop == null) { System.err.println("label without properties"); return; } JLabel label = new JLabel(); int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); String text = prop.getValue("text", ""); Object constraints = prop.getValue("constraints"); boolean visible = prop.getValue("visible", true); label.setBounds(x, y, width, height); label.setText(text); if (!visible) label.setVisible(false); if (layout == 0) sheet.getContentPane().add(label); else sheet.getContentPane().add(label, constraints); } else if (tag.equals("button")) { if (prop == null) { System.err.println("button without properties"); return; } JButton btn = new JButton(); int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); String id = prop.getValue("id", ""); String text = prop.getValue("text", ""); String onmouseup = prop.getValue("onmouseup", ""); Object constraints = prop.getValue("constraints"); btn.setBounds(x, y, width, height); btn.setText(text); btn.addActionListener(sheet); btn.setActionCommand(onmouseup); if (layout == 0) sheet.getContentPane().add(btn); else sheet.getContentPane().add(btn, constraints); } else if (tag.equals("radiobutton")) { if (prop == null) { System.err.println("radiobutton without properties"); return; } JRadioButton rb = new JRadioButton(); int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); String id = prop.getValue("id", ""); String text = prop.getValue("text", ""); Object constraints = prop.getValue("constraints"); String checked = prop.getValue("checked", "false"); rb.setBounds(x, y, width, height); rb.setText(text); rb.setName((String) id); rb.addActionListener(sheet); rb.setSelected(checked.equalsIgnoreCase("true")); if (layout == 0) sheet.getContentPane().add(rb); else sheet.getContentPane().add(rb, constraints); } else if (tag.equals("checkbox")) { if (prop == null) { System.err.println("checkbox without properties"); return; } JCheckBox cb = new JCheckBox(); int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); String id = prop.getValue("id", ""); String text = prop.getValue("text", ""); String onmouseup = prop.getValue("onmouseup", ""); Object constraints = prop.getValue("constraints"); String checked = prop.getValue("checked", "false"); cb.setBounds(x, y, width, height); cb.setText(text); cb.setName((String) id); cb.setSelected(checked.equalsIgnoreCase("true")); if (layout == 0) sheet.getContentPane().add(cb); else sheet.getContentPane().add(cb, constraints); } else if (tag.equals("image")) { if (prop == null) { System.err.println("image without properties"); return; } JLabel label = new JLabel(); int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); String src = prop.getValue("src", ""); Object constraints = prop.getValue("constraints"); label.setIcon(new ImageIcon(new URL(src))); label.setBounds(x, y, width, height); if (layout == 0) sheet.getContentPane().add(label); else sheet.getContentPane().add(label, constraints); } else if (tag.equals("singlelineedit")) { if (prop == null) { System.err.println("singlelineedit without properties"); return; } String pwd = prop.getValue("password", ""); JTextField sle; if (pwd.equalsIgnoreCase("true")) sle = new JPasswordField(); else sle = new JTextField(); int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); Object id = prop.getValue("id"); String text = prop.getValue("text", ""); Object constraints = prop.getValue("constraints"); sle.setBounds(x, y, width, height); sle.setText(text); sle.setName((String) id); if (layout == 0) sheet.getContentPane().add(sle); else sheet.getContentPane().add(sle, constraints); } else if (tag.equals("treeview")) { if (prop == null) { System.err.println("treeview without properties"); return; } treeview_root = new DefaultMutableTreeNode("root"); treeview = new JTree(treeview_root); Object constraints = prop.getValue("constraints"); sheet.getContentPane().add(new JScrollPane(treeview), constraints); } else if (tag.equals("treeitem")) { if (prop == null) { System.err.println("treeview.treeitem without properties"); return; } String text = prop.getValue("text", ""); String value = prop.getValue("value", ""); DefaultMutableTreeNode node = new DefaultMutableTreeNode(text); treeview_root.add(node); } else if (tag.equals("table")) { if (prop == null) { System.err.println("table without properties"); return; } String id = prop.getValue("id", ""); table = new JTable(); model = new DefaultTableModel() { public boolean isCellEditable(int row, int col) { return false; } }; table.setModel(model); table.setName((String) id); Object constraints = prop.getValue("constraints"); sheet.getContentPane().add(new JScrollPane(table), constraints); rowNumber = 0; columnNumber = 0; headerWidths = new Vector(); } else if (tag.equals("header")) { if (prop == null) { System.err.println("table.header without properties"); return; } String text = prop.getValue("text", ""); int width = prop.getValue("width", 0); headerWidths.addElement(new Integer(width)); model.addColumn(text); } else if (tag.equals("row")) { rowNumber++; columnNumber = 0; model.setRowCount(rowNumber); } else if (tag.equals("column")) { columnNumber++; if (prop == null) { System.err.println("table.column without properties"); return; } String value = prop.getValue("value", ""); model.setValueAt(value, rowNumber - 1, columnNumber - 1); } else if (tag.equals("script")) { sheet.beginScript(); String url = prop.getValue("src"); if (url.length() > 0) { try { BufferedReader r = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String buffer; while (true) { buffer = r.readLine(); if (buffer == null) break; sheet.script += buffer + "\n"; } r.close(); sheet.endScript(); } catch (IOException ioe) { System.err.println("[IOError] " + ioe.getMessage()); System.exit(0); } } } else System.err.println("[sheet] unparsed tag: " + tag); } catch (Exception e) { e.printStackTrace(System.err); } }
Code Sample 2:
public void load() throws ResourceInstantiationException { if (null == url) { throw new ResourceInstantiationException("URL not set (null)."); } try { BufferedReader defReader = new BomStrippingInputStreamReader((url).openStream(), ENCODING); String line; LinearNode node; while (null != (line = defReader.readLine())) { node = new LinearNode(line); try { this.add(node); } catch (GateRuntimeException ex) { throw new ResourceInstantiationException(ex); } } defReader.close(); isModified = false; } catch (Exception x) { throw new ResourceInstantiationException(x); } }
|
11
|
Code Sample 1:
public void sorter() { String inputLine1, inputLine2; String epiNames[] = new String[1000]; String epiEpisodes[] = new String[1000]; int lineCounter = 0; try { String pluginDir = pluginInterface.getPluginDirectoryName(); String eplist_file = pluginDir + System.getProperty("file.separator") + "EpisodeList.txt"; File episodeList = new File(eplist_file); if (!episodeList.isFile()) { episodeList.createNewFile(); } final BufferedReader in = new BufferedReader(new FileReader(episodeList)); while ((inputLine1 = in.readLine()) != null) { if ((inputLine2 = in.readLine()) != null) { epiNames[lineCounter] = inputLine1; epiEpisodes[lineCounter] = inputLine2; lineCounter++; } } in.close(); int epiLength = epiNames.length; for (int i = 0; i < (lineCounter); i++) { for (int j = 0; j < (lineCounter - 1); j++) { if (epiNames[j].compareToIgnoreCase(epiNames[j + 1]) > 0) { String temp = epiNames[j]; epiNames[j] = epiNames[j + 1]; epiNames[j + 1] = temp; String temp2 = epiEpisodes[j]; epiEpisodes[j] = epiEpisodes[j + 1]; epiEpisodes[j + 1] = temp2; } } } File episodeList2 = new File(eplist_file); BufferedWriter bufWriter = new BufferedWriter(new FileWriter(episodeList2)); for (int i = 0; i <= lineCounter; i++) { if (epiNames[i] == null) { break; } bufWriter.write(epiNames[i] + "\n"); bufWriter.write(epiEpisodes[i] + "\n"); } bufWriter.close(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
public static int[] sortDescending(int input[]) { int[] order = new int[input.length]; for (int i = 0; i < order.length; i++) order[i] = i; for (int i = input.length; --i >= 0; ) { for (int j = 0; j < i; j++) { if (input[j] < input[j + 1]) { int mem = input[j]; input[j] = input[j + 1]; input[j + 1] = mem; int id = order[j]; order[j] = order[j + 1]; order[j + 1] = id; } } } return order; }
|
11
|
Code Sample 1:
public void copyFile(File s, File t) { try { FileChannel in = (new FileInputStream(s)).getChannel(); FileChannel out = (new FileOutputStream(t)).getChannel(); in.transferTo(0, s.length(), out); in.close(); out.close(); } catch (Exception e) { System.out.println(e); } }
Code Sample 2:
public static void encryptFile(String infile, String outfile, String keyFile) throws Exception { javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, getKey()); java.io.FileInputStream in = new java.io.FileInputStream(infile); java.io.FileOutputStream fileOut = new java.io.FileOutputStream(outfile); javax.crypto.CipherOutputStream out = new javax.crypto.CipherOutputStream(fileOut, cipher); byte[] buffer = new byte[kBufferSize]; int length; while ((length = in.read(buffer)) != -1) out.write(buffer, 0, length); in.close(); out.close(); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.