label
class label 2
classes | source_code
stringlengths 398
72.9k
|
---|---|
11
|
Code Sample 1:
@Deprecated public static void getAndProcessContents(String videoPageURL, int bufsize, String charset, Closure<String> process) throws IOException { URL url = null; HttpURLConnection connection = null; InputStream is = null; InputStreamReader isr = null; BufferedReader br = null; try { url = new URL(videoPageURL); connection = (HttpURLConnection) url.openConnection(); is = connection.getInputStream(); isr = new InputStreamReader(is, charset); br = new BufferedReader(isr); for (String line = br.readLine(); line != null; line = br.readLine()) { process.exec(line); } } finally { Closeables.closeQuietly(br); Closeables.closeQuietly(isr); Closeables.closeQuietly(is); HttpUtils.disconnect(connection); } }
Code Sample 2:
public static void readShaderSource(ClassLoader context, String path, URL url, StringBuffer result) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; while ((line = reader.readLine()) != null) { if (line.startsWith("#include ")) { String includeFile = line.substring(9).trim(); String next = Locator.getRelativeOf(path, includeFile); URL nextURL = Locator.getResource(next, context); if (nextURL == null) { next = includeFile; nextURL = Locator.getResource(next, context); } if (nextURL == null) { throw new FileNotFoundException("Can't find include file " + includeFile); } readShaderSource(context, next, nextURL, result); } else { result.append(line + "\n"); } } } catch (IOException e) { throw new RuntimeException(e); } }
|
11
|
Code Sample 1:
protected boolean loadJarLibrary(final String jarLib) { final String tempLib = System.getProperty("java.io.tmpdir") + File.separator + jarLib; boolean copied = IOUtils.copyFile(jarLib, tempLib); if (!copied) { return false; } System.load(tempLib); return true; }
Code Sample 2:
public void run() { FileInputStream src; FileOutputStream dest; try { src = new FileInputStream(srcName); dest = new FileOutputStream(destName); } catch (FileNotFoundException e) { e.printStackTrace(); return; } FileChannel srcC = src.getChannel(); FileChannel destC = dest.getChannel(); ByteBuffer buf = ByteBuffer.allocate(BUFFER_SIZE); try { int i; System.out.println(srcC.size()); while ((i = srcC.read(buf)) > 0) { System.out.println(buf.getChar(2)); buf.flip(); destC.write(buf); buf.compact(); } destC.close(); dest.close(); } catch (IOException e1) { e1.printStackTrace(); return; } }
|
11
|
Code Sample 1:
public static void main(String[] args) throws Exception { if (args.length != 2) { PrintUtil.prt("arguments: sourcefile, destfile"); System.exit(1); } FileChannel in = new FileInputStream(args[0]).getChannel(), out = new FileOutputStream(args[1]).getChannel(); ByteBuffer buff = ByteBuffer.allocate(BSIZE); while (in.read(buff) != -1) { PrintUtil.prt("%%%"); buff.flip(); out.write(buff); buff.clear(); } }
Code Sample 2:
@Test public void testTransactWriteAndRead() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile file = new RFile("testreadwritetrans.txt"); RFileOutputStream out = new RFileOutputStream(file, WriteMode.TRANSACTED, false, 1); out.write("test".getBytes("utf-8")); out.close(); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[4]; int readCount = in.read(buffer); in.close(); assertEquals(4, readCount); String resultRead = new String(buffer, "utf-8"); assertEquals("test", resultRead); } finally { server.stop(); } }
|
00
|
Code Sample 1:
public static void main(String[] args) throws Exception { DES des = new DES(); StreamBlockReader reader = new StreamBlockReader(new FileInputStream("D:\\test1.txt")); StreamBlockWriter writer = new StreamBlockWriter(new FileOutputStream("D:\\test2.txt")); SingleKey key = new SingleKey(new Block(64), ""); key = new SingleKey(new Block("1111111100000000111111110000000011111111000000001111111100000000"), ""); Mode mode = new ECBDESMode(des); des.decrypt(reader, writer, key, mode); }
Code Sample 2:
private void initClientConfigurationFromURL(String urlStr) throws Exception { try { URL url = ProxyURLFactory.createHttpUrl(urlStr); initClientConfiguration(url.openStream()); } catch (Exception e) { throw new Exception("Could not initialize from Client Configuration URL:" + urlStr, e); } }
|
00
|
Code Sample 1:
protected String getHashCode(String value) { if (log.isDebugEnabled()) log.debug("getHashCode(...) -> begin"); String retVal = null; try { MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(value.getBytes()); byte[] digest = mdAlgorithm.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < digest.length; i++) { sb.append(this.toHexString(digest[i])); } retVal = sb.toString(); if (log.isDebugEnabled()) log.debug("getHashCode(...) -> hashcode = " + retVal); } catch (Exception e) { log.error("getHashCode(...) -> error occured generating hashcode ", e); } if (log.isDebugEnabled()) log.debug("getHashCode(...) -> end"); return retVal; }
Code Sample 2:
private static void prepare() { System.err.println("PREPARING-----------------------------------------"); deleteHome(); InputStream configStream = null; FileOutputStream tempStream = null; try { configStream = AllTests.class.getClassLoader().getResourceAsStream("net/sf/archimede/test/resources/repository.xml"); new File("temp").mkdir(); tempStream = new FileOutputStream(new File("temp/repository.xml")); IOUtils.copy(configStream, tempStream); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (configStream != null) { configStream.close(); } } catch (IOException e) { e.printStackTrace(); } finally { if (tempStream != null) { try { tempStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } String repositoryName = "jackrabbit.repository"; Properties jndiProperties = new Properties(); jndiProperties.put("java.naming.provider.url", "http://sf.net/projects/archimede#1"); jndiProperties.put("java.naming.factory.initial", "org.apache.jackrabbit.core.jndi.provider.DummyInitialContextFactory"); startupUtil = new StartupJcrUtil(REPOSITORY_HOME, "temp/repository.xml", repositoryName, jndiProperties); startupUtil.init(); }
|
00
|
Code Sample 1:
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String requestURI = req.getRequestURI(); logger.info("The requested URI: {}", requestURI); String parameter = requestURI.substring(requestURI.lastIndexOf(ARXIVID_ENTRY) + ARXIVID_ENTRY_LENGTH); int signIndex = parameter.indexOf(StringUtil.ARXIVID_SEGMENTID_DELIMITER); String arxivId = signIndex != -1 ? parameter.substring(0, signIndex) : parameter; String segmentId = signIndex != -1 ? parameter.substring(signIndex + 1) : null; if (arxivId == null) { logger.error("The request with an empty arxiv id parameter"); return; } String filePath = segmentId == null ? format("/opt/mocassin/aux-pdf/%s" + StringUtil.arxivid2filename(arxivId, "pdf")) : "/opt/mocassin/pdf/" + StringUtil.segmentid2filename(arxivId, Integer.parseInt(segmentId), "pdf"); if (!new File(filePath).exists()) { filePath = format("/opt/mocassin/aux-pdf/%s", StringUtil.arxivid2filename(arxivId, "pdf")); } try { FileInputStream fileInputStream = new FileInputStream(filePath); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); IOUtils.copy(fileInputStream, byteArrayOutputStream); resp.setContentType("application/pdf"); resp.setHeader("Content-disposition", String.format("attachment; filename=%s", StringUtil.arxivid2filename(arxivId, "pdf"))); ServletOutputStream outputStream = resp.getOutputStream(); outputStream.write(byteArrayOutputStream.toByteArray()); outputStream.close(); } catch (FileNotFoundException e) { logger.error("Error while downloading: PDF file= '{}' not found", filePath); } catch (IOException e) { logger.error("Error while downloading the PDF file", e); } }
Code Sample 2:
private static String getDocumentAt(String urlString) { StringBuffer html_text = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) html_text.append(line + "\n"); reader.close(); } catch (MalformedURLException e) { System.out.println("����URL: " + urlString); } catch (IOException e) { e.printStackTrace(); } return html_text.toString(); }
|
11
|
Code Sample 1:
public static String encryptMD5(String str) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(str.getBytes()); byte[] hash = md5.digest(); md5.reset(); return Format.hashToHex(hash); } catch (java.security.NoSuchAlgorithmException nsae0) { return null; } }
Code Sample 2:
public static String md5Encrypt(String valueToEncrypted) { String encryptedValue = ""; try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(valueToEncrypted.getBytes()); BigInteger hash = new BigInteger(1, digest.digest()); encryptedValue = hash.toString(16); } catch (NoSuchAlgorithmException nsae) { nsae.printStackTrace(); } return encryptedValue; }
|
00
|
Code Sample 1:
public static String encryptPassword(String password) throws PasswordException { String hash = null; if (password != null && !password.equals("")) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes("UTF-8")); byte raw[] = md.digest(); hash = (new BASE64Encoder()).encode(raw); } catch (NoSuchAlgorithmException nsae) { throw new PasswordException(PasswordException.SYSTEM_ERROR); } catch (UnsupportedEncodingException uee) { throw new PasswordException(PasswordException.SYSTEM_ERROR); } } return hash; }
Code Sample 2:
public String upload() throws IOException { int idx = docIndex.incrementAndGet(); String tmpName = "namefinder/doc_" + idx + "__" + fileFileName; File tmpFile = tmpFile(tmpName); if (tmpFile.exists()) { org.apache.commons.io.FileUtils.deleteQuietly(tmpFile); } org.apache.commons.io.FileUtils.touch(tmpFile); InputStream fileStream = new FileInputStream(file); OutputStream bos = new FileOutputStream(tmpFile); IOUtils.copy(fileStream, bos); bos.close(); fileStream.close(); return tmpUrl(tmpName); }
|
11
|
Code Sample 1:
public static void checkAndUpdateGameData() { new ErrThread() { @Override public void handledRun() throws Throwable { try { URL url = new URL(ONLINE_CLIENT_DATA + "gamedata.xml"); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); int lastversion = 0; String readHeader1 = br.readLine(); String readHeader2 = br.readLine(); String[] parts = readHeader2.split(" "); lastversion = new Integer(parts[1]); GameDatabase.loadVersion(); if (GameDatabase.version < lastversion) { Logger.log(LogTypes.LOG, "Downloading new gamedata"); BufferedOutputStream bo = null; File destfile = new File(GameDatabase.dataFilePath); if (!destfile.createNewFile()) { destfile.delete(); destfile.createNewFile(); } bo = new BufferedOutputStream(new FileOutputStream(destfile)); bo.write((readHeader1 + "\n").getBytes()); bo.write((readHeader2 + "\n").getBytes()); int readedbyte; while ((readedbyte = br.read()) != -1) { bo.write(readedbyte); } bo.flush(); try { br.close(); bo.close(); } catch (Exception ex) { Logger.log(ex); } } } catch (java.net.UnknownHostException unknownHost) { Logger.log("Sourceforge is down, cannot update gamedata"); } catch (Exception e) { JOptionPane.showMessageDialog(FrameOrganizer.getClientFrame(), "The gamedata is outdated, but Coopnet couldn't update it!", "Gamedata outdated", JOptionPane.INFORMATION_MESSAGE); throw e; } finally { GameDatabase.loadVersion(); GameDatabase.load("", GameDatabase.dataFilePath); GameDatabase.detectGames(); } } }.start(); }
Code Sample 2:
public Epg unmarshallFromUrl(URL url) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String tmp = null; StringBuilder buffer = new StringBuilder(); while ((tmp = reader.readLine()) != null) { buffer.append(tmp); } return unmarshall(buffer.toString().getBytes()); }
|
11
|
Code Sample 1:
Object onSuccess() { this.mErrorExist = true; this.mErrorMdp = true; if (!mClientManager.exists(this.mNewMail)) { this.mErrorExist = false; if (mNewMdp.equals(mNewMdpConfirm)) { this.mErrorMdp = false; MessageDigest sha1Instance; try { sha1Instance = MessageDigest.getInstance("SHA1"); sha1Instance.reset(); sha1Instance.update(this.mNewMdp.getBytes()); byte[] digest = sha1Instance.digest(); BigInteger bigInt = new BigInteger(1, digest); String vHashPassword = bigInt.toString(16); Client vClient = new Client(this.mNewNom, (this.mNewPrenom != null ? this.mNewPrenom : ""), this.mNewMail, vHashPassword, this.mNewAdresse, 1); mClientManager.save(vClient); mComponentResources.discardPersistentFieldChanges(); return "Client/List"; } catch (NoSuchAlgorithmException e) { mLogger.error(e.getMessage(), e); } } } return errorZone.getBody(); }
Code Sample 2:
public static String encrypt(String passPhrase, String password) { String algorithm = "PBEWithMD5AndDES"; byte[] salt = new byte[8]; int iterations = 20; byte[] output = new byte[128]; if (passPhrase == null || "".equals(passPhrase) || password == null || "".equals(password)) { throw new GeneralException(PassPhraseCrypto.class, "encrypt", "Required parameter missing"); } try { Security.addProvider(new com.sun.crypto.provider.SunJCE()); KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray()); SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm); SecretKey secretKey = secretKeyFactory.generateSecret(keySpec); MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(passPhrase.getBytes()); byte[] input = new byte[password.length()]; input = password.getBytes(); messageDigest.update(input); byte[] digest = messageDigest.digest(); System.arraycopy(digest, 0, salt, 0, 8); AlgorithmParameterSpec algorithmParameterSpec = new PBEParameterSpec(salt, iterations); Cipher cipher = Cipher.getInstance(algorithm); int mode = Cipher.ENCRYPT_MODE; cipher.init(mode, secretKey, algorithmParameterSpec); output = cipher.doFinal(input); } catch (NoSuchAlgorithmException e) { throw new GeneralException(PassPhraseCrypto.class, "encrypt", "Algorithm not found", e); } catch (InvalidAlgorithmParameterException e) { throw new GeneralException(PassPhraseCrypto.class, "encrypt", "nvalidAlgorithmParameter", e); } catch (InvalidKeySpecException e) { throw new GeneralException(PassPhraseCrypto.class, "encrypt", "InvalidKeySpec", e); } catch (InvalidKeyException e) { throw new GeneralException(PassPhraseCrypto.class, "encrypt", "InvalidKey", e); } catch (NoSuchPaddingException e) { throw new GeneralException(PassPhraseCrypto.class, "encrypt", "NoSuchPadding", e); } catch (BadPaddingException e) { throw new GeneralException(PassPhraseCrypto.class, "encrypt", "BadPadding", e); } catch (IllegalBlockSizeException e) { throw new GeneralException(PassPhraseCrypto.class, "encrypt", "IllegalBlockSize", e); } StringBuffer result = new StringBuffer(); for (int i = 0; i < output.length; i++) { result.append(Byte.toString(output[i])); } return result.toString(); }
|
00
|
Code Sample 1:
private HttpURLConnection getHttpURLConnection(String bizDocToExecute) { StringBuffer servletURL = new StringBuffer(); servletURL.append(getBaseServletURL()); servletURL.append("?_BIZVIEW=").append(bizDocToExecute); Map<String, Object> inputParms = getInputParams(); if (inputParms != null) { Set<Entry<String, Object>> entrySet = inputParms.entrySet(); for (Entry<String, Object> entry : entrySet) { String name = entry.getKey(); String value = entry.getValue().toString(); servletURL.append("&").append(name).append("=").append(value); } } HttpURLConnection connection = null; try { URL url = new URL(servletURL.toString()); connection = (HttpURLConnection) url.openConnection(); } catch (IOException e) { Assert.fail("Failed to connect to the test servlet: " + e); } return connection; }
Code Sample 2:
private String calculateMD5(String input) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.reset(); digest.update(input.getBytes()); byte[] md5 = digest.digest(); String tmp = ""; String res = ""; for (int i = 0; i < md5.length; i++) { tmp = (Integer.toHexString(0xFF & md5[i])); if (tmp.length() == 1) { res += "0" + tmp; } else { res += tmp; } } return res; }
|
00
|
Code Sample 1:
private void handleNodeUp(long eventID, long nodeID, String eventTime) { Category log = ThreadCategory.getInstance(OutageWriter.class); if (eventID == -1 || nodeID == -1) { log.warn(EventConstants.NODE_UP_EVENT_UEI + " ignored - info incomplete - eventid/nodeid: " + eventID + "/" + nodeID); return; } Connection dbConn = null; try { dbConn = DatabaseConnectionFactory.getInstance().getConnection(); int count = 0; if (openOutageExists(dbConn, nodeID)) { try { dbConn.setAutoCommit(false); } catch (SQLException sqle) { log.error("Unable to change database AutoCommit to FALSE", sqle); return; } PreparedStatement outageUpdater = dbConn.prepareStatement(OutageConstants.DB_UPDATE_OUTAGES_FOR_NODE); outageUpdater.setLong(1, eventID); outageUpdater.setTimestamp(2, convertEventTimeIntoTimestamp(eventTime)); outageUpdater.setLong(3, nodeID); count = outageUpdater.executeUpdate(); outageUpdater.close(); } else { log.warn("\'" + EventConstants.NODE_UP_EVENT_UEI + "\' for " + nodeID + " no open record."); } try { dbConn.commit(); if (log.isDebugEnabled()) log.debug("nodeUp closed " + count + " outages for nodeid " + nodeID + " in DB"); } catch (SQLException se) { log.warn("Rolling back transaction, nodeUp could not be recorded for nodeId: " + nodeID, se); try { dbConn.rollback(); } catch (SQLException sqle) { log.warn("SQL exception during rollback, reason", sqle); } } } catch (SQLException se) { log.warn("SQL exception while handling \'nodeRegainedService\'", se); } finally { try { if (dbConn != null) dbConn.close(); } catch (SQLException e) { log.warn("Exception closing JDBC connection", e); } } }
Code Sample 2:
public Bitmap getImage() throws IOException { int recordBegin = 78 + 8 * mCount; Bitmap result = null; FileChannel channel = new FileInputStream(mFile).getChannel(); channel.position(mRecodeOffset[mPage]); ByteBuffer bodyBuffer; if (mPage + 1 < mCount) { int length = mRecodeOffset[mPage + 1] - mRecodeOffset[mPage]; bodyBuffer = channel.map(MapMode.READ_ONLY, mRecodeOffset[mPage], length); byte[] tmpCache = new byte[bodyBuffer.capacity()]; bodyBuffer.get(tmpCache); FileOutputStream o = new FileOutputStream("/sdcard/test.bmp"); o.write(tmpCache); o.flush(); o.getFD().sync(); o.close(); result = BitmapFactory.decodeByteArray(tmpCache, 0, length); } else { } channel.close(); return result; }
|
11
|
Code Sample 1:
public static void main(String[] args) { if (args.length != 2) { System.out.println("Usage: HashCalculator <Algorithm> <Input>"); System.out.println("The preferred algorithm is SHA."); } else { MessageDigest md; try { md = MessageDigest.getInstance(args[0]); md.update(args[1].getBytes()); System.out.print("Hashed value of " + args[1] + " is: "); System.out.println((new BASE64Encoder()).encode(md.digest())); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } }
Code Sample 2:
private static String digest(String myinfo) { try { MessageDigest alga = MessageDigest.getInstance("SHA"); alga.update(myinfo.getBytes()); byte[] digesta = alga.digest(); return byte2hex(digesta); } catch (Exception ex) { return myinfo; } }
|
11
|
Code Sample 1:
static void copyFile(File file, File destDir) { File destFile = new File(destDir, file.getName()); if (destFile.exists() && (!destFile.canWrite())) { throw new SyncException("Cannot overwrite " + destFile + " because " + "it is read-only"); } try { FileInputStream in = new FileInputStream(file); try { FileOutputStream out = new FileOutputStream(destFile); try { byte[] buffer = new byte[BUFFER_SIZE]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } } finally { out.close(); } } finally { in.close(); } } catch (IOException e) { throw new SyncException("I/O error copying " + file + " to " + destDir + " (message: " + e.getMessage() + ")", e); } if (!destFile.setLastModified(file.lastModified())) { throw new SyncException("Could not set last modified timestamp " + "of " + destFile); } }
Code Sample 2:
public static void copyFile(File source, File dest) throws Exception { log.warn("File names are " + source.toString() + " and " + dest.toString()); if (!dest.getParentFile().exists()) dest.getParentFile().mkdir(); FileChannel sourceChannel = new FileInputStream(source).getChannel(); FileChannel destinationChannel = new FileOutputStream(dest).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
|
11
|
Code Sample 1:
public void generate(String rootDir, RootModel root) throws Exception { IOUtils.copyStream(HTMLGenerator.class.getResourceAsStream("stylesheet.css"), new FileOutputStream(new File(rootDir, "stylesheet.css"))); Velocity.init(); VelocityContext context = new VelocityContext(); context.put("model", root); context.put("util", new VelocityUtils()); context.put("msg", messages); processTemplate("index.html", new File(rootDir, "index.html"), context); processTemplate("list.html", new File(rootDir, "list.html"), context); processTemplate("summary.html", new File(rootDir, "summary.html"), context); File imageDir = new File(rootDir, "images"); imageDir.mkdir(); IOUtils.copyStream(HTMLGenerator.class.getResourceAsStream("primarykey.gif"), new FileOutputStream(new File(imageDir, "primarykey.gif"))); File tableDir = new File(rootDir, "tables"); tableDir.mkdir(); for (TableModel table : root.getTables()) { context.put("table", table); processTemplate("table.html", new File(tableDir, table.getTableName() + ".html"), context); } }
Code Sample 2:
private static void zip(ZipOutputStream aOutputStream, final File[] aFiles, final String sArchive, final URI aRootURI, final String sFilter) throws FileError { boolean closeStream = false; if (aOutputStream == null) try { aOutputStream = new ZipOutputStream(new FileOutputStream(sArchive)); closeStream = true; } catch (final FileNotFoundException e) { throw new FileError("Can't create ODF file!", e); } try { try { for (final File curFile : aFiles) { aOutputStream.putNextEntry(new ZipEntry(URLDecoder.decode(aRootURI.relativize(curFile.toURI()).toASCIIString(), "UTF-8"))); if (curFile.isDirectory()) { aOutputStream.closeEntry(); FileUtils.zip(aOutputStream, FileUtils.getFiles(curFile, sFilter), sArchive, aRootURI, sFilter); continue; } final FileInputStream inputStream = new FileInputStream(curFile); for (int i; (i = inputStream.read(FileUtils.BUFFER)) != -1; ) aOutputStream.write(FileUtils.BUFFER, 0, i); inputStream.close(); aOutputStream.closeEntry(); } } finally { if (closeStream && aOutputStream != null) aOutputStream.close(); } } catch (final IOException e) { throw new FileError("Can't zip file to archive!", e); } if (closeStream) DocumentController.getStaticLogger().fine(aFiles.length + " files and folders zipped as " + sArchive); }
|
11
|
Code Sample 1:
public static void main(String[] args) { try { FileReader reader = new FileReader(args[0]); FileWriter writer = new FileWriter(args[1]); html2xhtml(reader, writer); writer.close(); reader.close(); } catch (Exception e) { freemind.main.Resources.getInstance().logException(e); } }
Code Sample 2:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
|
00
|
Code Sample 1:
public static boolean doPost(String urlString, Map<String, String> nameValuePairs) throws IOException { URL url = new URL(urlString); URLConnection conn = url.openConnection(); conn.setDoOutput(true); PrintWriter out = new PrintWriter(conn.getOutputStream()); boolean first = true; for (Map.Entry<String, String> pair : nameValuePairs.entrySet()) { if (first) first = false; else out.print('&'); String name = pair.getKey(); String value = pair.getValue(); out.print(name); out.print('='); out.print(URLEncoder.encode(value, "UTF-8")); } out.close(); Scanner in; StringBuilder response = new StringBuilder(); try { in = new Scanner(conn.getInputStream()); } catch (IOException ex) { if (!(conn instanceof HttpURLConnection)) throw ex; InputStream err = ((HttpURLConnection) conn).getErrorStream(); in = new Scanner(err); } while (in.hasNextLine()) { response.append(in.nextLine()); response.append("\n"); } in.close(); return true; }
Code Sample 2:
public SingularValueDecomposition(Matrix Arg) { double[][] A = Arg.getArrayCopy(); m = Arg.getRowDimension(); n = Arg.getColumnDimension(); int nu = Math.min(m, n); s = new double[Math.min(m + 1, n)]; U = new double[m][nu]; V = new double[n][n]; double[] e = new double[n]; double[] work = new double[m]; boolean wantu = true; boolean wantv = true; int nct = Math.min(m - 1, n); int nrt = Math.max(0, Math.min(n - 2, m)); for (int k = 0; k < Math.max(nct, nrt); k++) { if (k < nct) { s[k] = 0; for (int i = k; i < m; i++) { s[k] = Maths.hypot(s[k], A[i][k]); } if (s[k] != 0.0) { if (A[k][k] < 0.0) { s[k] = -s[k]; } for (int i = k; i < m; i++) { A[i][k] /= s[k]; } A[k][k] += 1.0; } s[k] = -s[k]; } for (int j = k + 1; j < n; j++) { if ((k < nct) & (s[k] != 0.0)) { double t = 0; for (int i = k; i < m; i++) { t += A[i][k] * A[i][j]; } t = -t / A[k][k]; for (int i = k; i < m; i++) { A[i][j] += t * A[i][k]; } } e[j] = A[k][j]; } if (wantu & (k < nct)) { for (int i = k; i < m; i++) { U[i][k] = A[i][k]; } } if (k < nrt) { e[k] = 0; for (int i = k + 1; i < n; i++) { e[k] = Maths.hypot(e[k], e[i]); } if (e[k] != 0.0) { if (e[k + 1] < 0.0) { e[k] = -e[k]; } for (int i = k + 1; i < n; i++) { e[i] /= e[k]; } e[k + 1] += 1.0; } e[k] = -e[k]; if ((k + 1 < m) & (e[k] != 0.0)) { for (int i = k + 1; i < m; i++) { work[i] = 0.0; } for (int j = k + 1; j < n; j++) { for (int i = k + 1; i < m; i++) { work[i] += e[j] * A[i][j]; } } for (int j = k + 1; j < n; j++) { double t = -e[j] / e[k + 1]; for (int i = k + 1; i < m; i++) { A[i][j] += t * work[i]; } } } if (wantv) { for (int i = k + 1; i < n; i++) { V[i][k] = e[i]; } } } } int p = Math.min(n, m + 1); if (nct < n) { s[nct] = A[nct][nct]; } if (m < p) { s[p - 1] = 0.0; } if (nrt + 1 < p) { e[nrt] = A[nrt][p - 1]; } e[p - 1] = 0.0; if (wantu) { for (int j = nct; j < nu; j++) { for (int i = 0; i < m; i++) { U[i][j] = 0.0; } U[j][j] = 1.0; } for (int k = nct - 1; k >= 0; k--) { if (s[k] != 0.0) { for (int j = k + 1; j < nu; j++) { double t = 0; for (int i = k; i < m; i++) { t += U[i][k] * U[i][j]; } t = -t / U[k][k]; for (int i = k; i < m; i++) { U[i][j] += t * U[i][k]; } } for (int i = k; i < m; i++) { U[i][k] = -U[i][k]; } U[k][k] = 1.0 + U[k][k]; for (int i = 0; i < k - 1; i++) { U[i][k] = 0.0; } } else { for (int i = 0; i < m; i++) { U[i][k] = 0.0; } U[k][k] = 1.0; } } } if (wantv) { for (int k = n - 1; k >= 0; k--) { if ((k < nrt) & (e[k] != 0.0)) { for (int j = k + 1; j < nu; j++) { double t = 0; for (int i = k + 1; i < n; i++) { t += V[i][k] * V[i][j]; } t = -t / V[k + 1][k]; for (int i = k + 1; i < n; i++) { V[i][j] += t * V[i][k]; } } } for (int i = 0; i < n; i++) { V[i][k] = 0.0; } V[k][k] = 1.0; } } int pp = p - 1; int iter = 0; double eps = Math.pow(2.0, -52.0); double tiny = Math.pow(2.0, -966.0); while (p > 0) { int k, kase; for (k = p - 2; k >= -1; k--) { if (k == -1) { break; } if (Math.abs(e[k]) <= tiny + eps * (Math.abs(s[k]) + Math.abs(s[k + 1]))) { e[k] = 0.0; break; } } if (k == p - 2) { kase = 4; } else { int ks; for (ks = p - 1; ks >= k; ks--) { if (ks == k) { break; } double t = (ks != p ? Math.abs(e[ks]) : 0.) + (ks != k + 1 ? Math.abs(e[ks - 1]) : 0.); if (Math.abs(s[ks]) <= tiny + eps * t) { s[ks] = 0.0; break; } } if (ks == k) { kase = 3; } else if (ks == p - 1) { kase = 1; } else { kase = 2; k = ks; } } k++; switch(kase) { case 1: { double f = e[p - 2]; e[p - 2] = 0.0; for (int j = p - 2; j >= k; j--) { double t = Maths.hypot(s[j], f); double cs = s[j] / t; double sn = f / t; s[j] = t; if (j != k) { f = -sn * e[j - 1]; e[j - 1] = cs * e[j - 1]; } if (wantv) { for (int i = 0; i < n; i++) { t = cs * V[i][j] + sn * V[i][p - 1]; V[i][p - 1] = -sn * V[i][j] + cs * V[i][p - 1]; V[i][j] = t; } } } } break; case 2: { double f = e[k - 1]; e[k - 1] = 0.0; for (int j = k; j < p; j++) { double t = Maths.hypot(s[j], f); double cs = s[j] / t; double sn = f / t; s[j] = t; f = -sn * e[j]; e[j] = cs * e[j]; if (wantu) { for (int i = 0; i < m; i++) { t = cs * U[i][j] + sn * U[i][k - 1]; U[i][k - 1] = -sn * U[i][j] + cs * U[i][k - 1]; U[i][j] = t; } } } } break; case 3: { double scale = Math.max(Math.max(Math.max(Math.max(Math.abs(s[p - 1]), Math.abs(s[p - 2])), Math.abs(e[p - 2])), Math.abs(s[k])), Math.abs(e[k])); double sp = s[p - 1] / scale; double spm1 = s[p - 2] / scale; double epm1 = e[p - 2] / scale; double sk = s[k] / scale; double ek = e[k] / scale; double b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2.0; double c = (sp * epm1) * (sp * epm1); double shift = 0.0; if ((b != 0.0) | (c != 0.0)) { shift = Math.sqrt(b * b + c); if (b < 0.0) { shift = -shift; } shift = c / (b + shift); } double f = (sk + sp) * (sk - sp) + shift; double g = sk * ek; for (int j = k; j < p - 1; j++) { double t = Maths.hypot(f, g); double cs = f / t; double sn = g / t; if (j != k) { e[j - 1] = t; } f = cs * s[j] + sn * e[j]; e[j] = cs * e[j] - sn * s[j]; g = sn * s[j + 1]; s[j + 1] = cs * s[j + 1]; if (wantv) { for (int i = 0; i < n; i++) { t = cs * V[i][j] + sn * V[i][j + 1]; V[i][j + 1] = -sn * V[i][j] + cs * V[i][j + 1]; V[i][j] = t; } } t = Maths.hypot(f, g); cs = f / t; sn = g / t; s[j] = t; f = cs * e[j] + sn * s[j + 1]; s[j + 1] = -sn * e[j] + cs * s[j + 1]; g = sn * e[j + 1]; e[j + 1] = cs * e[j + 1]; if (wantu && (j < m - 1)) { for (int i = 0; i < m; i++) { t = cs * U[i][j] + sn * U[i][j + 1]; U[i][j + 1] = -sn * U[i][j] + cs * U[i][j + 1]; U[i][j] = t; } } } e[p - 2] = f; iter = iter + 1; } break; case 4: { if (s[k] <= 0.0) { s[k] = (s[k] < 0.0 ? -s[k] : 0.0); if (wantv) { for (int i = 0; i <= pp; i++) { V[i][k] = -V[i][k]; } } } while (k < pp) { if (s[k] >= s[k + 1]) { break; } double t = s[k]; s[k] = s[k + 1]; s[k + 1] = t; if (wantv && (k < n - 1)) { for (int i = 0; i < n; i++) { t = V[i][k + 1]; V[i][k + 1] = V[i][k]; V[i][k] = t; } } if (wantu && (k < m - 1)) { for (int i = 0; i < m; i++) { t = U[i][k + 1]; U[i][k + 1] = U[i][k]; U[i][k] = t; } } k++; } iter = 0; p--; } break; } } }
|
00
|
Code Sample 1:
public static Hashtable DefaultLoginValues(String firstName, String lastName, String password, String mac, String startLocation, int major, int minor, int patch, int build, String platform, String viewerDigest, String userAgent, String author) throws Exception { Hashtable values = new Hashtable(); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes("ASCII"), 0, password.length()); byte[] raw_digest = md5.digest(); String passwordDigest = Helpers.toHexText(raw_digest); values.put("first", firstName); values.put("last", lastName); values.put("passwd", "" + password); values.put("start", startLocation); values.put("major", major); values.put("minor", minor); values.put("patch", patch); values.put("build", build); values.put("platform", platform); values.put("mac", mac); values.put("agree_to_tos", "true"); values.put("viewer_digest", viewerDigest); values.put("user-agent", userAgent + " (" + Helpers.VERSION + ")"); values.put("author", author); Vector optionsArray = new Vector(); optionsArray.addElement("inventory-root"); optionsArray.addElement("inventory-skeleton"); optionsArray.addElement("inventory-lib-root"); optionsArray.addElement("inventory-lib-owner"); optionsArray.addElement("inventory-skel-lib"); optionsArray.addElement("initial-outfit"); optionsArray.addElement("gestures"); optionsArray.addElement("event_categories"); optionsArray.addElement("event_notifications"); optionsArray.addElement("classified_categories"); optionsArray.addElement("buddy-list"); optionsArray.addElement("ui-config"); optionsArray.addElement("login-flags"); optionsArray.addElement("global-textures"); values.put("options", optionsArray); return values; }
Code Sample 2:
public static void main(String[] args) { FTPClient client = new FTPClient(); try { client.connect("192.168.1.10"); boolean login = client.login("a", "123456"); if (login) { System.out.println("Dang nhap thanh cong..."); boolean logout = client.logout(); if (logout) { System.out.println("Da Logout khoi FTP Server..."); } } else { System.out.println("Dang nhap that bai..."); } } catch (IOException e) { e.printStackTrace(); } finally { try { client.disconnect(); } catch (IOException e) { e.printStackTrace(); } } }
|
00
|
Code Sample 1:
protected StringBuffer readURL(java.net.URL url) throws IOException { StringBuffer result = new StringBuffer(4096); InputStreamReader reader = new InputStreamReader(url.openStream()); for (; ; ) { char portion[] = new char[4096]; int numRead = reader.read(portion, 0, portion.length); if (numRead < 0) break; result.append(portion, 0, numRead); } dout("Read " + result.length() + " bytes."); return result; }
Code Sample 2:
public static void copy(File source, File dest) throws IOException { if (dest.isDirectory()) { dest = new File(dest + File.separator + source.getName()); } 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); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
|
00
|
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 String fazHttpRequest(String u) { StringBuilder str = new StringBuilder(); URL url = null; URLConnection urlC = null; try { url = new URL(u.toString()); urlC = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(urlC.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { str.append(inputLine); } in.close(); } catch (Exception e) { System.out.println("[fazHttpRequest]" + e); } return (str.length() > 0) ? str.toString() : null; }
|
00
|
Code Sample 1:
public boolean refresh() { try { synchronized (text) { stream = (new URL(url)).openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); String line; StringBuilder sb = new StringBuilder(); while ((line = reader.readLine()) != null) { sb.append(line); sb.append("\n"); } text = sb.toString(); } price = 0; date = null; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); return false; } finally { if (stream != null) try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } return true; }
Code Sample 2:
public OutputStream createOutputStream(URI uri, Map<?, ?> options) throws IOException { try { URL url = new URL(uri.toString()); final URLConnection urlConnection = url.openConnection(); urlConnection.setDoOutput(true); if (urlConnection instanceof HttpURLConnection) { final HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection; httpURLConnection.setRequestMethod("PUT"); return new FilterOutputStream(urlConnection.getOutputStream()) { @Override public void close() throws IOException { super.close(); int responseCode = httpURLConnection.getResponseCode(); switch(responseCode) { case HttpURLConnection.HTTP_OK: case HttpURLConnection.HTTP_CREATED: case HttpURLConnection.HTTP_NO_CONTENT: { break; } default: { throw new IOException("PUT failed with HTTP response code " + responseCode); } } } }; } else { OutputStream result = urlConnection.getOutputStream(); final Map<Object, Object> response = getResponse(options); if (response != null) { result = new FilterOutputStream(result) { @Override public void close() throws IOException { try { super.close(); } finally { response.put(URIConverter.RESPONSE_TIME_STAMP_PROPERTY, urlConnection.getLastModified()); } } }; } return result; } } catch (RuntimeException exception) { throw new Resource.IOWrappedException(exception); } }
|
11
|
Code Sample 1:
public void testStorageByteArray() throws Exception { TranslationResponseInMemory r = new TranslationResponseInMemory(2048, "UTF-8"); { OutputStream output = r.getOutputStream(); output.write("This is an example".getBytes("UTF-8")); output.write(" and another one.".getBytes("UTF-8")); assertEquals("This is an example and another one.", r.getText()); } { InputStream input = r.getInputStream(); StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer, "UTF-8"); } finally { input.close(); writer.close(); } assertEquals("This is an example and another one.", writer.toString()); } { OutputStream output = r.getOutputStream(); output.write(" and another line".getBytes("UTF-8")); assertEquals("This is an example and another one. and another line", r.getText()); } { Writer output = r.getWriter(); output.write(" and write some more"); assertEquals("This is an example and another one. and another line and write some more", r.getText()); } { r.addText(" and even more."); assertEquals("This is an example and another one. and another line and write some more and even more.", r.getText()); } assertFalse(r.hasEnded()); r.setEndState(ResponseStateOk.getInstance()); assertTrue(r.hasEnded()); try { r.getOutputStream(); fail("Previous line should throw IOException as result closed."); } catch (IOException e) { } try { r.getWriter(); fail("Previous line should throw IOException as result closed."); } catch (IOException e) { } }
Code Sample 2:
public static void copy(String pstrFileFrom, String pstrFileTo) { try { FileChannel srcChannel = new FileInputStream(pstrFileFrom).getChannel(); FileChannel dstChannel = new FileOutputStream(pstrFileTo).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (Exception e) { throw new RuntimeException(e); } }
|
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(); 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(); } }
Code Sample 2:
public void testRenderRules() { try { MappingManager manager = new MappingManager(); OWLOntologyManager omanager = OWLManager.createOWLOntologyManager(); OWLOntology srcOntology; OWLOntology targetOntology; manager.loadMapping(rulesDoc.toURL()); srcOntology = omanager.loadOntologyFromPhysicalURI(srcURI); targetOntology = omanager.loadOntologyFromPhysicalURI(targetURI); manager.setSourceOntology(srcOntology); manager.setTargetOntology(targetOntology); Graph srcGraph = manager.getSourceGraph(); Graph targetGraph = manager.getTargetGraph(); System.out.println("Starting to render..."); FlexGraphViewFactory factory = new FlexGraphViewFactory(); factory.setColorScheme(ColorSchemes.BLUES); factory.visit(srcGraph); GraphView view = factory.getGraphView(); GraphViewRenderer renderer = new FlexGraphViewRenderer(); renderer.setGraphView(view); System.out.println("View updated with graph..."); InputStream xmlStream = renderer.renderGraphView(); StringWriter writer = new StringWriter(); IOUtils.copy(xmlStream, writer); System.out.println("Finished writing"); writer.close(); System.out.println("Finished render... XML is:"); System.out.println(writer.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (OWLOntologyCreationException e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public static void copy(String sourceFile, String targetFile) throws IOException { FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel(); FileChannel targetChannel = new FileOutputStream(targetFile).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); targetChannel.close(); }
Code Sample 2:
public String getMD5(String password) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); byte byteData[] = md.digest(); StringBuffer sb = new StringBuffer(); for(int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } return sb.toString(); }
|
00
|
Code Sample 1:
public Set<Plugin<?>> loadPluginImplementationMetaData() throws PluginRegistryException { try { final Enumeration<URL> urls = JavaSystemHelper.getResources(pluginImplementationMetaInfPath); pluginImplsSet.clear(); if (urls != null) { while (urls.hasMoreElements()) { final URL url = urls.nextElement(); echoMessages.add(PluginMessageBundle.getMessage("plugin.info.visitor.resource.found", "classes", url.getPath())); InputStream resourceInput = null; Reader reader = null; BufferedReader buffReader = null; String line; try { resourceInput = url.openStream(); reader = new InputStreamReader(resourceInput); buffReader = new BufferedReader(reader); line = buffReader.readLine(); while (line != null) { try { pluginImplsSet.add(inspectPluginImpl(Class.forName(line.trim()))); echoMessages.add(PluginMessageBundle.getMessage("plugin.info.visitor.resource.processing", "class", line)); line = buffReader.readLine(); } catch (final ClassNotFoundException cnfe) { throw new PluginRegistryException("plugin.error.load.classnotfound", cnfe, pluginImplementationMetaInfPath, line); } catch (final LinkageError ncfe) { if (LOGGER.isDebugEnabled()) { echoMessages.add(PluginMessageBundle.getMessage("plugin.info.visitor.resource.linkageError", "class", line, ncfe.getMessage())); } line = buffReader.readLine(); } } } catch (final IOException ioe) { throw new PluginRegistryException("plugin.error.load.ioe", ioe, url.getFile(), ioe.getMessage()); } finally { if (buffReader != null) { buffReader.close(); } if (reader != null) { reader.close(); } if (resourceInput != null) { resourceInput.close(); } } } } return Collections.unmodifiableSet(pluginImplsSet); } catch (final IOException ioe) { throw new PluginRegistryException("plugin.error.load.ioe", ioe, pluginImplementationMetaInfPath, ioe.getMessage()); } }
Code Sample 2:
public static StringBuffer getCachedFile(String url) throws Exception { File urlCache = new File("tmp-cache/" + url.replace('/', '-')); new File("tmp-cache/").mkdir(); if (urlCache.exists()) { BufferedReader in = new BufferedReader(new FileReader(urlCache)); StringBuffer buffer = new StringBuffer(); String input; while ((input = in.readLine()) != null) { buffer.append(input + "\n"); } in.close(); return buffer; } else { URL url2 = new URL(url.replace(" ", "%20")); BufferedReader in = new BufferedReader(new InputStreamReader(url2.openStream())); BufferedWriter cacheWriter = new BufferedWriter(new FileWriter(urlCache)); StringBuffer buffer = new StringBuffer(); String input; while ((input = in.readLine()) != null) { buffer.append(input + "\n"); cacheWriter.write(input + "\n"); } cacheWriter.close(); in.close(); return buffer; } }
|
11
|
Code Sample 1:
private static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
Code Sample 2:
public static boolean copyFile(File sourceFile, File destinationFile) { boolean copySuccessfull = false; FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destinationFile).getChannel(); long transferedBytes = destination.transferFrom(source, 0, source.size()); copySuccessfull = transferedBytes == source.size() ? true : false; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (source != null) { try { source.close(); } catch (IOException e) { e.printStackTrace(); } } if (destination != null) { try { destination.close(); } catch (IOException e) { e.printStackTrace(); } } } return copySuccessfull; }
|
00
|
Code Sample 1:
void bubbleSort(int[] a) { int i = 0; int j = a.length - 1; int aux = 0; int stop = 0; while (stop == 0) { stop = 1; i = 0; while (i < j) { if (a[i] > a[i + 1]) { aux = a[i]; a[i] = a[i + 1]; a[i + 1] = aux; stop = 0; } i = i + 1; } j = j - 1; } }
Code Sample 2:
public Project createProject(int testbedID, String name, String description) throws AdaptationException { Project project = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "INSERT INTO Projects(testbedID, name, " + "description) VALUES (" + testbedID + ", '" + name + "', '" + description + "')"; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); statement.executeUpdate(query); query = "SELECT * FROM Projects WHERE " + " testbedID = " + testbedID + " AND " + " name = '" + name + "' AND " + " description = '" + description + "'"; resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to create project failed."; log.error(msg); throw new AdaptationException(msg); } project = getProject(resultSet); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in createProject"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return project; }
|
00
|
Code Sample 1:
public String readFile(String filename) throws IOException { FTPClient ftpClient = new FTPClient(); ftpClient.connect(server, port); ftpClient.login(USERNAME, PASSWORD); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); boolean success = ftpClient.retrieveFile(filename, outputStream); ftpClient.disconnect(); if (!success) { throw new IOException("Retrieve file failed: " + filename); } return outputStream.toString(); }
Code Sample 2:
public boolean isServerAlive(String pStrURL) { boolean isAlive; long t1 = System.currentTimeMillis(); try { URL url = new URL(pStrURL); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { logger.fine(inputLine); } logger.info("** Connection successful.. **"); in.close(); isAlive = true; } catch (Exception e) { logger.info("** Connection failed.. **"); e.printStackTrace(); isAlive = false; } long t2 = System.currentTimeMillis(); logger.info("Time taken to check connection: " + (t2 - t1) + " ms."); return isAlive; }
|
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:
public HttpResponse execute() throws IOException { return new HttpResponse() { @Override public int getResponseCode() throws IOException { return conn.getResponseCode(); } @Override public InputStream getContentStream() throws IOException { InputStream errStream = conn.getErrorStream(); if (errStream != null) return errStream; else return conn.getInputStream(); } }; }
|
11
|
Code Sample 1:
public void play(File file) { try { URL url = new URL("http://127.0.0.1:8081/play.html?type=4&file=" + file.getAbsolutePath() + "&name=toto"); URLConnection connection = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
private static MappedObject sendHttpRequestToUrl(URL url, String method) throws Exception { try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(method); connection.connect(); InputStream is = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder buffer = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { buffer.append(line); } System.out.println("Read: " + buffer.toString()); connection.disconnect(); JAXBContext context = JAXBContext.newInstance(MappedObject.class); Unmarshaller unmarshaller = context.createUnmarshaller(); MappedObject mapped = (MappedObject) unmarshaller.unmarshal(new StringReader(buffer.toString())); return mapped; } catch (IOException e) { e.printStackTrace(); } throw new Exception("Could not establish connection to " + url.toExternalForm()); }
|
00
|
Code Sample 1:
static void createCompleteXML(File file) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(errorFile); fos = new FileOutputStream(file); byte[] data = new byte[Integer.parseInt(BlueXStatics.prop.getProperty("allocationUnit"))]; int offset; while ((offset = fis.read(data)) != -1) fos.write(data, 0, offset); } catch (Exception e) { e.printStackTrace(); } finally { try { fis.close(); } catch (Exception e) { } try { fos.close(); } catch (Exception e) { } } FileWriter fw = null; try { fw = new FileWriter(file, true); fw.append("</detail>"); fw.append("\n</exception>"); fw.append("\n</log>"); } catch (Exception e) { e.printStackTrace(); } finally { try { fw.close(); } catch (Exception e) { } } }
Code Sample 2:
private void readURL(URL url) throws IOException { statusLine.setText("Opening " + url.toExternalForm()); URLConnection connection = url.openConnection(); StringBuffer buffer = new StringBuffer(); BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = in.readLine()) != null) { buffer.append(line).append('\n'); statusLine.setText("Read " + buffer.length() + " bytes..."); } } finally { if (in != null) in.close(); } String type = connection.getContentType(); if (type == null) type = "text/plain"; statusLine.setText("Content type " + type); content.setContentType(type); content.setText(buffer.toString()); statusLine.setText("Done"); }
|
11
|
Code Sample 1:
private byte[] _generate() throws NoSuchAlgorithmException { if (host == null) { try { seed = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { seed = "localhost/127.0.0.1"; } catch (SecurityException e) { seed = "localhost/127.0.0.1"; } host = seed; } else { seed = host; } seed = seed + new Date().toString(); seed = seed + Long.toString(rnd.nextLong()); md = MessageDigest.getInstance(algorithm); md.update(seed.getBytes()); return md.digest(); }
Code Sample 2:
private static byte[] sha2(String... data) { byte[] digest = new byte[32]; StringBuilder buffer = new StringBuilder(); for (String s : data) { buffer.append(s); } MessageDigest sha256 = null; try { sha256 = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException ex) { assert false; } sha256.update(buffer.toString().getBytes()); try { sha256.digest(digest, 0, digest.length); } catch (DigestException ex) { assert false; } return digest; }
|
00
|
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 MusicBrainzXMLParser(URL url) throws DocumentException, IOException { URLConnection urlConnection = url.openConnection(); InputStream httpStream = urlConnection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(httpStream, "ISO-8859-1")); SAXReader reader = new SAXReader(); doc = reader.read(br); br.close(); }
|
00
|
Code Sample 1:
@ActionMethod public void mirror() throws IOException { final URL url = new URL("http://127.0.0.1:" + testPort + "/mirror"); final HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestProperty(Http11Header.AUTHORIZATION, "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="); con.setRequestProperty(Http11Header.WWW_AUTHENTICATE, "Basic realm=\"karatasi\""); final InputStream in = con.getInputStream(); final byte[] buf = new byte[4096]; textArea.setText(""); for (int bytesRead; (bytesRead = in.read(buf)) != -1; ) { textArea.append(new String(buf, 0, bytesRead)); } }
Code Sample 2:
private void createWar() throws IOException, XMLStreamException { String appName = this.fileout.getName(); int i = appName.indexOf("."); if (i != -1) appName = appName.substring(0, i); ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(this.fileout)); { ZipEntry entry = new ZipEntry("WEB-INF/web.xml"); zout.putNextEntry(entry); XMLOutputFactory factory = XMLOutputFactory.newInstance(); XMLStreamWriter w = factory.createXMLStreamWriter(zout, "ASCII"); w.writeStartDocument("ASCII", "1.0"); w.writeStartElement("web-app"); w.writeAttribute("xsi", XSI, "schemaLocation", "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml /ns/javaee/web-app_2_5.xsd"); w.writeAttribute("version", "2.5"); w.writeAttribute("xmlns", J2EE); w.writeAttribute("xmlns:xsi", XSI); w.writeStartElement("description"); w.writeCharacters("Site maintenance for " + appName); w.writeEndElement(); w.writeStartElement("display-name"); w.writeCharacters(appName); w.writeEndElement(); w.writeStartElement("servlet"); w.writeStartElement("servlet-name"); w.writeCharacters("down"); w.writeEndElement(); w.writeStartElement("jsp-file"); w.writeCharacters("/WEB-INF/jsp/down.jsp"); w.writeEndElement(); w.writeEndElement(); w.writeStartElement("servlet-mapping"); w.writeStartElement("servlet-name"); w.writeCharacters("down"); w.writeEndElement(); w.writeStartElement("url-pattern"); w.writeCharacters("/*"); w.writeEndElement(); w.writeEndElement(); w.writeEndElement(); w.writeEndDocument(); w.flush(); zout.closeEntry(); } { ZipEntry entry = new ZipEntry("WEB-INF/jsp/down.jsp"); zout.putNextEntry(entry); PrintWriter w = new PrintWriter(zout); if (this.messageFile != null) { IOUtils.copyTo(new FileReader(this.messageFile), w); } else if (this.messageString != null) { w.print("<html><body>" + this.messageString + "</body></html>"); } else { w.print("<html><body><div style='text-align:center;font-size:500%;'>Oh No !<br/><b>" + appName + "</b><br/>is down for maintenance!</div></body></html>"); } w.flush(); zout.closeEntry(); } zout.finish(); zout.flush(); zout.close(); }
|
00
|
Code Sample 1:
public static String getURLData(String stringUrl, boolean secure) throws Exception { URL url = new URL(stringUrl); HttpURLConnection httpURLConnection; if (secure) { httpURLConnection = (HttpsURLConnection) url.openConnection(); } else { httpURLConnection = (HttpURLConnection) url.openConnection(); } return getDataFromURL(httpURLConnection); }
Code Sample 2:
private void output(HttpServletResponse resp, InputStream is, long length, String fileName) throws Exception { resp.reset(); String mimeType = "image/jpeg"; resp.setContentType(mimeType); resp.setContentLength((int) length); resp.setHeader("Content-Disposition", "inline; filename=\"" + fileName + "\""); resp.setHeader("Cache-Control", "must-revalidate"); ServletOutputStream sout = resp.getOutputStream(); IOUtils.copy(is, sout); sout.flush(); resp.flushBuffer(); }
|
11
|
Code Sample 1:
public he3Decode(String in_file) { try { File out = new File(in_file + extension); File in = new File(in_file); int file_size = (int) in.length(); FileInputStream in_stream = new FileInputStream(in_file); out.createNewFile(); FileOutputStream out_stream = new FileOutputStream(out.getName()); ByteArrayOutputStream os = new ByteArrayOutputStream(file_size); byte byte_arr[] = new byte[8]; int buff_size = byte_arr.length; int _fetched = 0; int _chars_read = 0; System.out.println(appname + ".\n" + "decoding: " + in_file + "\n" + "decoding to: " + in_file + extension + "\n" + "\nreading: "); while (_fetched < file_size) { _chars_read = in_stream.read(byte_arr, 0, buff_size); if (_chars_read == -1) break; os.write(byte_arr, 0, _chars_read); _fetched += _chars_read; System.out.print("*"); } System.out.print("\ndecoding: "); out_stream.write(_decode((ByteArrayOutputStream) os)); System.out.print("complete\n\n"); } catch (java.io.FileNotFoundException fnfEx) { System.err.println("Exception: " + fnfEx.getMessage()); } catch (java.io.IOException ioEx) { System.err.println("Exception: " + ioEx.getMessage()); } }
Code Sample 2:
public static void copyFileTo(String destFileName, String resourceFileName) { if (destFileName == null || resourceFileName == null) throw new IllegalArgumentException("Argument cannot be null."); try { FileInputStream in = null; FileOutputStream out = null; File resourceFile = new File(resourceFileName); if (!resourceFile.isFile()) { System.out.println(resourceFileName + " cannot be opened."); return; } in = new FileInputStream(resourceFile); out = new FileOutputStream(new File(destFileName)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException ex) { ex.printStackTrace(); } }
|
11
|
Code Sample 1:
@Before public void setUp() throws Exception { configureSslSocketConnector(); SecurityHandler securityHandler = createBasicAuthenticationSecurityHandler(); HandlerList handlerList = new HandlerList(); handlerList.addHandler(securityHandler); handlerList.addHandler(new AbstractHandler() { @Override public void handle(String s, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, int i) throws IOException, ServletException { expected = new StringBuilder(); System.out.println("uri: " + httpServletRequest.getRequestURI()); System.out.println("queryString: " + (queryString = httpServletRequest.getQueryString())); System.out.println("method: " + httpServletRequest.getMethod()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(httpServletRequest.getInputStream(), baos); System.out.println("body: " + (body = baos.toString())); PrintWriter writer = httpServletResponse.getWriter(); writer.append("testsvar"); expected.append("testsvar"); Random r = new Random(); for (int j = 0; j < 10; j++) { int value = r.nextInt(Integer.MAX_VALUE); writer.append(value + ""); expected.append(value); } System.out.println(); writer.close(); httpServletResponse.setStatus(HttpServletResponse.SC_OK); } }); server.addHandler(handlerList); server.start(); }
Code Sample 2:
private void copyFile(File srcFile, File destFile) throws IOException { if (!(srcFile.exists() && srcFile.isFile())) throw new IllegalArgumentException("Source file doesn't exist: " + srcFile.getAbsolutePath()); if (destFile.exists() && destFile.isDirectory()) throw new IllegalArgumentException("Destination file is directory: " + destFile.getAbsolutePath()); FileInputStream in = new FileInputStream(srcFile); FileOutputStream out = new FileOutputStream(destFile); byte[] buffer = new byte[4096]; int no = 0; try { while ((no = in.read(buffer)) != -1) out.write(buffer, 0, no); } finally { in.close(); out.close(); } }
|
11
|
Code Sample 1:
@Override public byte[] read(String path) throws PersistenceException { InputStream reader = null; ByteArrayOutputStream sw = new ByteArrayOutputStream(); try { reader = new FileInputStream(path); IOUtils.copy(reader, sw); } catch (Exception e) { LOGGER.error("fail to read file - " + path, e); throw new PersistenceException(e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { LOGGER.error("fail to close reader", e); } } } return sw.toByteArray(); }
Code Sample 2:
protected void copyFile(String inputFilePath, String outputFilePath) throws GenerationException { String from = getTemplateDir() + inputFilePath; try { logger.debug("Copying from " + from + " to " + outputFilePath); InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(from); if (inputStream == null) { throw new GenerationException("Source file not found: " + from); } FileOutputStream outputStream = new FileOutputStream(new File(outputFilePath)); IOUtils.copy(inputStream, outputStream); inputStream.close(); outputStream.close(); } catch (Exception e) { throw new GenerationException("Error while copying file: " + from, e); } }
|
11
|
Code Sample 1:
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(); } }
Code Sample 2:
@Override protected svm_model loadModel(InputStream inputStream) throws IOException { File tmpFile = File.createTempFile("tmp", ".mdl"); FileOutputStream output = new FileOutputStream(tmpFile); try { IOUtils.copy(inputStream, output); return libsvm.svm.svm_load_model(tmpFile.getPath()); } finally { output.close(); tmpFile.delete(); } }
|
11
|
Code Sample 1:
private void copyFile(File source) throws IOException { File backup = new File(source.getCanonicalPath() + ".backup"); if (!backup.exists()) { FileChannel srcChannel = new FileInputStream(source).getChannel(); backup.createNewFile(); FileChannel dstChannel = new FileOutputStream(backup).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } }
Code Sample 2:
protected void createFile(File sourceActionDirectory, File destinationActionDirectory, LinkedList<String> segments) throws DuplicateActionFileException { File currentSrcDir = sourceActionDirectory; File currentDestDir = destinationActionDirectory; String segment = ""; for (int i = 0; i < segments.size() - 1; i++) { segment = segments.get(i); currentSrcDir = new File(currentSrcDir, segment); currentDestDir = new File(currentDestDir, segment); } if (currentSrcDir != null && currentDestDir != null) { File srcFile = new File(currentSrcDir, segments.getLast()); if (srcFile.exists()) { File destFile = new File(currentDestDir, segments.getLast()); if (destFile.exists()) { throw new DuplicateActionFileException(srcFile.toURI().toASCIIString()); } try { FileChannel srcChannel = new FileInputStream(srcFile).getChannel(); FileChannel destChannel = new FileOutputStream(destFile).getChannel(); ByteBuffer buffer = ByteBuffer.allocate((int) srcChannel.size()); while (srcChannel.position() < srcChannel.size()) { srcChannel.read(buffer); } srcChannel.close(); buffer.rewind(); destChannel.write(buffer); destChannel.close(); } catch (Exception ex) { ex.printStackTrace(); } } } }
|
00
|
Code Sample 1:
public void run() { if (getCommand() == null) throw new IllegalArgumentException("Given command is null!"); if (getSocketProvider() == null) throw new IllegalArgumentException("Given connection is not open!"); if (getCommand() instanceof ListCommand) { try { setReply(ReplyWorker.readReply(getSocketProvider(), true)); setStatus(ReplyWorker.FINISHED); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); } return; } else if (getCommand() instanceof RetrieveCommand) { RetrieveCommand retrieveCommand = (RetrieveCommand) getCommand(); if (retrieveCommand.getFromFile().getTransferType().intern() == Command.TYPE_I || retrieveCommand.getFromFile().getTransferType().intern() == Command.TYPE_A) { try { log.debug("Download file: " + retrieveCommand.getFromFile().toString()); FileOutputStream out = null; FileChannel channel = null; if (getDownloadMethod() == RetrieveCommand.FILE_BASED) { out = new FileOutputStream(retrieveCommand.getToFile().getFile()); channel = out.getChannel(); if (retrieveCommand.getResumePosition() != -1) { try { channel.position(retrieveCommand.getResumePosition()); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); try { channel.close(); } catch (IOException ioe2) { } return; } } } else if (getDownloadMethod() == RetrieveCommand.BYTEBUFFER_BASED) { } int amount; try { while ((amount = getSocketProvider().read(buffer)) != -1) { if (amount == 0) { try { Thread.sleep(4); } catch (InterruptedException e) { } } buffer.flip(); while (buffer.hasRemaining()) { if (getDownloadMethod() == RetrieveCommand.STREAM_BASED) { int rem = buffer.remaining(); byte[] buf = new byte[rem]; buffer.get(buf, 0, rem); this.outputPipe.write(buf, 0, rem); } else if (getDownloadMethod() == RetrieveCommand.BYTEBUFFER_BASED) { } else { channel.write(buffer); } } buffer.clear(); } buffer.flip(); while (buffer.hasRemaining()) { if (getDownloadMethod() == RetrieveCommand.STREAM_BASED) { int rem = buffer.remaining(); byte[] buf = new byte[rem]; buffer.get(buf, 0, rem); this.outputPipe.write(buf, 0, rem); } else if (getDownloadMethod() == RetrieveCommand.BYTEBUFFER_BASED) { } else { channel.write(buffer); } } buffer.clear(); setStatus(ReplyWorker.FINISHED); if (channel != null) channel.close(); if (this.outputPipe != null) this.outputPipe.close(); getSocketProvider().close(); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); } finally { try { channel.close(); getSocketProvider().close(); } catch (Exception e) { } } } catch (FileNotFoundException fnfe) { setCaughtException(fnfe); setStatus(ReplyWorker.ERROR_FILE_NOT_FOUND); } } else throw new IllegalArgumentException("Unknown file transfer type for download!"); return; } else if (getCommand() instanceof StoreCommand) { StoreCommand storeCommand = (StoreCommand) getCommand(); if (storeCommand.getToFile().getTransferType().intern() == Command.TYPE_I || storeCommand.getToFile().getTransferType().intern() == Command.TYPE_A) { try { log.debug("Upload file: " + storeCommand.getFromFile()); InputStream in = storeCommand.getStream(); int amount; int socketWrite; int socketAmount = 0; if (in instanceof FileInputStream) { FileChannel channel = ((FileInputStream) in).getChannel(); if (storeCommand.getResumePosition() != -1) { try { channel.position(storeCommand.getResumePosition()); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); try { channel.close(); } catch (IOException ioe2) { } return; } } try { while ((amount = channel.read(buffer)) != -1) { buffer.flip(); socketWrite = 0; while ((socketWrite = getSocketProvider().write(buffer)) != -1) { socketAmount += socketWrite; if (amount <= socketAmount) { break; } if (socketWrite == 0) { try { Thread.sleep(4); } catch (InterruptedException e) { } } } if (socketWrite == -1) { break; } socketAmount = 0; buffer.clear(); } setStatus(ReplyWorker.FINISHED); channel.close(); getSocketProvider().close(); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); } finally { try { channel.close(); getSocketProvider().close(); } catch (Exception e) { } } } else { try { while ((amount = in.read(buffer.array())) != -1) { buffer.flip(); buffer.limit(amount); socketWrite = 0; while ((socketWrite = getSocketProvider().write(buffer)) != -1) { socketAmount = socketWrite; if (amount <= socketAmount) { break; } if (socketWrite == 0) { try { Thread.sleep(4); } catch (InterruptedException e) { } } } if (socketWrite == -1) { break; } socketAmount = 0; buffer.clear(); } setStatus(ReplyWorker.FINISHED); in.close(); getSocketProvider().close(); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); } finally { try { in.close(); getSocketProvider().close(); } catch (Exception e) { } } } } catch (FileNotFoundException fnfe) { setCaughtException(fnfe); setStatus(ReplyWorker.ERROR_FILE_NOT_FOUND); } } else throw new IllegalArgumentException("Unknown file transfer type for upload!"); } else throw new IllegalArgumentException("Given command is not supported!"); }
Code Sample 2:
public void connect(String ftpHost, int ftpPort, String ftpUser, String ftpPwd) throws IOException { ftpClient = new FTPClient(); ftpClient.setReaderThread(false); if (ftpPort == -1) ftpClient.connect(ftpHost); else ftpClient.connect(ftpHost, ftpPort); logger.info("FTP Connection Successful: " + ftpHost); ftpClient.login(ftpUser, ftpPwd); }
|
00
|
Code Sample 1:
public void sendTemplate(String filename, TemplateValues values) throws IOException { Checker.checkEmpty(filename, "filename"); Checker.checkNull(values, "values"); URL url = _getFile(filename); boolean writeSpaces = Context.getRootContext().getRunMode() == RUN_MODE.DEV ? true : false; Template t = new Template(url.openStream(), writeSpaces); try { t.write(getWriter(), values); } catch (ErrorListException ele) { Context.getRootContext().getLogger().error(ele); } }
Code Sample 2:
public void readContents() throws IOException { fireProgressEvent(new ProgressEvent(this, ProgressEvent.PROGRESS_START, 0.0f, "loading file")); URLConnection conn = url.openConnection(); conn.connect(); filesize = conn.getContentLength(); logger.finest("filesize: " + filesize); InputStreamReader in = new InputStreamReader(conn.getInputStream()); readFirstLine(in); readHeaderLines(in); readData(in); fireProgressEvent(new ProgressEvent(this, ProgressEvent.PROGRESS_FINISH, 1.0f, "loading file")); }
|
11
|
Code Sample 1:
private void copyThemeProviderClass() throws Exception { InputStream is = getClass().getResourceAsStream("/zkthemer/ThemeProvider.class"); if (is == null) throw new RuntimeException("Cannot find ThemeProvider.class"); File outFile = new File(theme.getJarRootFile(), "zkthemer/ThemeProvider.class"); outFile.getParentFile().mkdirs(); FileOutputStream out = new FileOutputStream(outFile); IOUtils.copy(is, out); out.close(); FileUtils.writeStringToFile(new File(theme.getJarRootFile(), "zkthemer.properties"), "theme=" + theme.getName() + "\r\nfileList=" + fileList.deleteCharAt(fileList.length() - 1).toString()); }
Code Sample 2:
public void backupFile(File fromFile, File toFile) { FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } catch (IOException e) { log.error(e.getMessage()); } finally { if (from != null) try { from.close(); } catch (IOException e) { log.error(e.getMessage()); } if (to != null) try { to.close(); } catch (IOException e) { log.error(e.getMessage()); } } }
|
00
|
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 GridDirectoryList(String gridSource) throws McIDASException { try { URL url = new URL(gridSource); urlc = (AddeURLConnection) url.openConnection(); inputStream = new DataInputStream(new BufferedInputStream(urlc.getInputStream())); } catch (IOException e) { throw new McIDASException("Error opening URL for grids:" + e); } readDirectory(); }
|
11
|
Code Sample 1:
public static Photo createPhoto(String title, String userLogin, String pathToPhoto, String basePathImage) throws NoSuchAlgorithmException, IOException { String id = CryptSHA1.genPhotoID(userLogin, title); String extension = pathToPhoto.substring(pathToPhoto.lastIndexOf(".")); String destination = basePathImage + id + extension; FileInputStream fis = new FileInputStream(pathToPhoto); FileOutputStream fos = new FileOutputStream(destination); FileChannel fci = fis.getChannel(); FileChannel fco = fos.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (true) { int read = fci.read(buffer); if (read == -1) break; buffer.flip(); fco.write(buffer); buffer.clear(); } fci.close(); fco.close(); fos.close(); fis.close(); ImageIcon image; ImageIcon thumb; String destinationThumb = basePathImage + "thumb/" + id + extension; image = new ImageIcon(destination); int maxSize = 150; int origWidth = image.getIconWidth(); int origHeight = image.getIconHeight(); if (origWidth > origHeight) { thumb = new ImageIcon(image.getImage().getScaledInstance(maxSize, -1, Image.SCALE_SMOOTH)); } else { thumb = new ImageIcon(image.getImage().getScaledInstance(-1, maxSize, Image.SCALE_SMOOTH)); } BufferedImage bi = new BufferedImage(thumb.getIconWidth(), thumb.getIconHeight(), BufferedImage.TYPE_INT_RGB); Graphics g = bi.getGraphics(); g.drawImage(thumb.getImage(), 0, 0, null); try { ImageIO.write(bi, "JPG", new File(destinationThumb)); } catch (IOException ioe) { System.out.println("Error occured saving thumbnail"); } Photo photo = new Photo(id); photo.setTitle(title); photo.basePathImage = basePathImage; return photo; }
Code Sample 2:
public static void copyFile(final File in, final File out) throws IOException { final FileChannel sourceChannel = new FileInputStream(in).getChannel(); final FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
|
11
|
Code Sample 1:
public void run() { GZIPInputStream gzipInputStream = null; try { gzipInputStream = new GZIPInputStream(pipedInputStream); IOUtils.copy(gzipInputStream, outputStream); } catch (Throwable t) { ungzipThreadThrowableList.add(t); } finally { IOUtils.closeQuietly(gzipInputStream); IOUtils.closeQuietly(pipedInputStream); } }
Code Sample 2:
private void copyFile(File in, File out) { try { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } catch (IOException ex) { ex.printStackTrace(); } }
|
11
|
Code Sample 1:
public static void DecodeMapFile(String mapFile, String outputFile) throws Exception { byte magicKey = 0; byte[] buffer = new byte[2048]; int nread; InputStream map; OutputStream output; try { map = new FileInputStream(mapFile); } catch (Exception e) { throw new Exception("Map file error", e); } try { output = new FileOutputStream(outputFile); } catch (Exception e) { throw new Exception("Map file error", e); } while ((nread = map.read(buffer, 0, 2048)) != 0) { for (int i = 0; i < nread; ++i) { buffer[i] ^= magicKey; magicKey += 43; } output.write(buffer, 0, nread); } map.close(); output.close(); }
Code Sample 2:
public static void copyFile(File from, File to) { try { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); byte[] buffer = new byte[1024 * 16]; int read = 0; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } in.close(); } catch (IOException e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
public static String calcolaMd5(String messaggio) { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } md.reset(); md.update(messaggio.getBytes()); byte[] impronta = md.digest(); return new String(impronta); }
Code Sample 2:
static String getMD5Sum(String source) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(source.getBytes()); byte[] md5sum = digest.digest(); BigInteger bigInt = new BigInteger(1, md5sum); return bigInt.toString(16); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("MD5 algorithm seems to not be supported. This is a requirement!"); } }
|
00
|
Code Sample 1:
private RSSFeed getFeed(String urlToRssFeed) { try { URL url = new URL(urlToRssFeed); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); XMLReader xmlreader = parser.getXMLReader(); RSSHandler theRssHandler = new RSSHandler(); xmlreader.setContentHandler(theRssHandler); InputSource is = new InputSource(url.openStream()); xmlreader.parse(is); return theRssHandler.getFeed(); } catch (Exception ee) { return null; } }
Code Sample 2:
private static void copier(FichierElectronique source, FichierElectronique cible) throws IOException { cible.setNom(source.getNom()); cible.setTaille(source.getTaille()); cible.setTypeMime(source.getTypeMime()); cible.setSoumetteur(source.getSoumetteur()); cible.setDateDerniereModification(source.getDateDerniereModification()); cible.setEmprunteur(source.getEmprunteur()); cible.setDateEmprunt(source.getDateEmprunt()); cible.setNumeroVersion(source.getNumeroVersion()); InputStream inputStream = source.getInputStream(); OutputStream outputStream = cible.getOutputStream(); try { IOUtils.copy(inputStream, outputStream); } finally { try { inputStream.close(); } finally { outputStream.close(); } if (source instanceof FichierElectroniqueDefaut) { FichierElectroniqueDefaut fichierElectroniqueTemporaire = (FichierElectroniqueDefaut) source; fichierElectroniqueTemporaire.deleteTemp(); } } }
|
00
|
Code Sample 1:
@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(); } }
Code Sample 2:
private boolean streamDownload(URL url, File file) { try { InputStream in = url.openConnection().getInputStream(); BufferedInputStream bis = new BufferedInputStream(in); OutputStream out = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(out); int chunkSize = 63 * 1024; byte[] ba = new byte[chunkSize]; while (true) { int bytesRead = readBlocking(bis, ba, 0, chunkSize); if (bytesRead > 0) { if (bos != null) bos.write(ba, 0, bytesRead); } else { bos.close(); break; } } } catch (IOException e) { System.out.println("Error writing file " + file); return false; } System.out.println("OK writing file " + file); return true; }
|
00
|
Code Sample 1:
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); }
Code Sample 2:
public String getClass(EmeraldjbBean eb) throws EmeraldjbException { Entity entity = (Entity) eb; StringBuffer sb = new StringBuffer(); String myPackage = getPackageName(eb); sb.append("package " + myPackage + ";\n"); sb.append("\n"); DaoValuesGenerator valgen = new DaoValuesGenerator(); String values_class_name = valgen.getClassName(entity); sb.append("\n"); List importList = new Vector(); importList.add("java.io.FileOutputStream;"); importList.add("java.io.FileInputStream;"); importList.add("java.io.DataInputStream;"); importList.add("java.io.DataOutputStream;"); importList.add("java.io.IOException;"); importList.add("java.sql.Date;"); importList.add(valgen.getPackageName(eb) + "." + values_class_name + ";"); Iterator it = importList.iterator(); while (it.hasNext()) { String importName = (String) it.next(); sb.append("import " + importName + "\n"); } sb.append("\n"); String proto_version = entity.getPatternValue(GeneratorConst.PATTERN_STREAM_PROTO_VERSION, "1"); String streamer_class_name = getClassName(entity); sb.append("public class " + streamer_class_name + "\n"); sb.append("{" + "\n public static final int PROTO_VERSION=" + proto_version + ";"); sb.append("\n\n"); StringBuffer f_writer = new StringBuffer(); StringBuffer f_reader = new StringBuffer(); boolean has_times = false; boolean has_strings = false; it = entity.getMembers().iterator(); while (it.hasNext()) { Member member = (Member) it.next(); String nm = member.getName(); String getter = "obj." + methodGenerator.getMethodName(DaoGeneratorUtils.METHOD_GET, member); String setter = "obj." + methodGenerator.getMethodName(DaoGeneratorUtils.METHOD_SET, member); String pad = " "; JTypeBase gen_type = EmdFactory.getJTypeFactory().getJavaType(member.getType()); f_writer.append(gen_type.getToBinaryCode(pad, "dos", getter + "()")); f_reader.append(gen_type.getFromBinaryCode(pad, "din", setter)); } String reader_vars = ""; sb.append("\n public static void writeToFile(String file_nm, " + values_class_name + " obj) throws IOException" + "\n {" + "\n if (file_nm==null || file_nm.length()==0) throw new IOException(\"Bad file name (null or zero length)\");" + "\n if (obj==null) throw new IOException(\"Bad value object parameter, cannot write null object to file\");" + "\n FileOutputStream fos = new FileOutputStream(file_nm);" + "\n DataOutputStream dos = new DataOutputStream(fos);" + "\n writeStream(dos, obj);" + "\n fos.close();" + "\n } // end of writeToFile" + "\n" + "\n public static void readFromFile(String file_nm, " + values_class_name + " obj) throws IOException" + "\n {" + "\n if (file_nm==null || file_nm.length()==0) throw new IOException(\"Bad file name (null or zero length)\");" + "\n if (obj==null) throw new IOException(\"Bad value object parameter, cannot write null object to file\");" + "\n FileInputStream fis = new FileInputStream(file_nm);" + "\n DataInputStream dis = new DataInputStream(fis);" + "\n readStream(dis, obj);" + "\n fis.close();" + "\n } // end of readFromFile" + "\n" + "\n public static void writeStream(DataOutputStream dos, " + values_class_name + " obj) throws IOException" + "\n {" + "\n dos.writeByte(PROTO_VERSION);" + "\n " + f_writer + "\n } // end of writeStream" + "\n" + "\n public static void readStream(DataInputStream din, " + values_class_name + " obj) throws IOException" + "\n {" + "\n int proto_version = din.readByte();" + "\n if (proto_version==" + proto_version + ") readStreamV1(din,obj);" + "\n } // end of readStream" + "\n" + "\n public static void readStreamV1(DataInputStream din, " + values_class_name + " obj) throws IOException" + "\n {" + reader_vars + f_reader + "\n } // end of readStreamV1" + "\n" + "\n} // end of classs" + "\n\n" + "\n//**************" + "\n// End of file" + "\n//**************"); return sb.toString(); }
|
11
|
Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
private static void cut() { File inputFile = new File(inputFileName); BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), inputCharSet)); } catch (FileNotFoundException e) { System.err.print("Invalid File Name!"); System.err.flush(); System.exit(1); } catch (UnsupportedEncodingException e) { System.err.print("Invalid Char Set Name!"); System.err.flush(); System.exit(1); } switch(cutMode) { case charMode: { int outputFileIndex = 1; char[] readBuf = new char[charPerFile]; while (true) { int readCount = 0; try { readCount = in.read(readBuf); } catch (IOException e) { System.err.println("Read IO Error!"); System.err.flush(); System.exit(1); } if (-1 == readCount) break; else { try { int ppos = inputFileName.lastIndexOf("."); String prefixInputFileName = inputFileName.substring(0, ppos); String postfixInputFileName = "html"; DecimalFormat outputFileIndexFormat = new DecimalFormat("0000"); File outputFile = new File(prefixInputFileName + "-" + outputFileIndexFormat.format(outputFileIndex) + "." + postfixInputFileName); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), outputCharSet)); out.write(readBuf, 0, readCount); out.flush(); out.close(); outputFileIndex++; } catch (IOException e) { System.err.println("Write IO Error!"); System.err.flush(); System.exit(1); } } } break; } case lineMode: { boolean isFileEnd = false; int outputFileIndex = 1; while (!isFileEnd) { try { int ppos = inputFileName.lastIndexOf("."); String prefixInputFileName = inputFileName.substring(0, ppos); String postfixInputFileName = inputFileName.substring(ppos + 1); DecimalFormat outputFileIndexFormat = new DecimalFormat("0000"); File outputFile = new File(prefixInputFileName + outputFileIndexFormat.format(outputFileIndex) + "." + postfixInputFileName); PrintStream out = new PrintStream(new FileOutputStream(outputFile), false, outputCharSet); int p = 0; while (p < linePerFile) { String line = in.readLine(); if (null == line) { isFileEnd = true; break; } out.println(line); ++p; } out.flush(); out.close(); } catch (IOException e) { System.err.println("Write IO Error!"); System.err.flush(); System.exit(1); } ++outputFileIndex; } break; } case htmlMode: { boolean isFileEnd = false; int outputFileIndex = 1; int ppos = inputFileName.lastIndexOf("."); String prefixInputFileName = inputFileName.substring(0, ppos); String postfixInputFileName = "html"; DecimalFormat df = new DecimalFormat("0000"); while (!isFileEnd) { try { File outputFile = new File(prefixInputFileName + "-" + df.format(outputFileIndex) + "." + postfixInputFileName); PrintStream out = new PrintStream(new FileOutputStream(outputFile), false, outputCharSet); out.println("<html><head><title>" + prefixInputFileName + "-" + df.format(outputFileIndex) + "</title>" + "<meta http-equiv=\"Content-Type\"" + " content=\"text/html; " + "charset=" + outputCharSet + "\" />" + "<link rel =\"stylesheet\" " + "type=\"text/css\" " + "href=\"stylesheet.css\" />" + "</head><body><div id=\"content\">"); int p = 0; while (p < pPerFile) { String line = in.readLine(); if (null == line) { isFileEnd = true; break; } if (line.length() > 0) out.println("<p>" + line + "</p>"); ++p; } out.println("</div><a href=\"" + prefixInputFileName + "-" + df.format(outputFileIndex + 1) + "." + postfixInputFileName + "\">NEXT</a></body></html>"); out.flush(); out.close(); } catch (IOException e) { System.err.println("Write IO Error!"); System.err.flush(); System.exit(1); } ++outputFileIndex; } try { File indexFile = new File("index.html"); PrintStream out = new PrintStream(new FileOutputStream(indexFile), false, outputCharSet); out.println("<html><head><title>" + "Index" + "</title>" + "<meta http-equiv=\"Content-Type\"" + " content=\"text/html; " + "charset=" + outputCharSet + "\" />" + "<link rel =\"stylesheet\" " + "type=\"text/css\" " + "href=\"stylesheet.css\" />" + "</head><body><h2>" + htmlTitle + "</h2><div id=\"content\"><ul>"); for (int i = 1; i < outputFileIndex; i++) { out.println("<li><a href=\"" + prefixInputFileName + "-" + df.format(i) + "." + postfixInputFileName + "\">" + df.format(i) + "</a></li>"); } out.println("</ul></body></html>"); out.flush(); out.close(); } catch (IOException e) { System.err.println("Write IO Error!"); System.err.flush(); System.exit(1); } break; } } }
|
00
|
Code Sample 1:
public void run() { date = DateUtil.addMonth(-1); List list = bo.getDao().getHibernateTemplate().find("from MailAffixPojo where upload_time <'" + date + "' and to_number(sized) >" + size); if (null != list && list.size() > 0) { try { FTPClient ftp = new FTPClient(); ftp.connect(config.getHostUrl(), config.getFtpPort()); ftp.login(config.getUname(), config.getUpass()); int replyCode = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { ftp.disconnect(); return; } for (int i = 0; i < list.size(); i++) { MailAffixPojo pojo = (MailAffixPojo) list.get(i); ftp.changeWorkingDirectory(pojo.getUploadTime().substring(0, 7)); ftp.deleteFile(pojo.getAffixSaveName()); ftp.changeToParentDirectory(); bo.delete(MailAffixPojo.class, new Long(pojo.getId())); } } catch (Exception e) { e.printStackTrace(); } } }
Code Sample 2:
public void sort(int[] order, double[] values) { int temp = 0; boolean done = false; for (int i = 0; i < values.length; i++) { order[i] = i; } if (desendingValues) { while (!done) { done = true; for (int i = values.length - 2; i >= 0; i--) { if (values[order[i]] < values[order[i + 1]]) { done = false; temp = order[i]; order[i] = order[i + 1]; order[i + 1] = temp; } } } } else { while (!done) { done = true; for (int i = values.length - 2; i >= 0; i--) { if (values[order[i]] > values[order[i + 1]]) { done = false; temp = order[i]; order[i] = order[i + 1]; order[i + 1] = temp; } } } } }
|
00
|
Code Sample 1:
public void init() { this.setFormulaCalculationMode(WorkBookHandle.CALCULATE_ALWAYS); try { if (memeId < 0) { } else { conurl = new URL(ServerURL + "?meme_id=" + memeId); java.io.InputStream xmlstr = conurl.openStream(); this.removeAllWorkSheets(); this.setFormulaCalculationMode(WorkBookHandle.CALCULATE_EXPLICIT); this.setStringEncodingMode(WorkBookHandle.STRING_ENCODING_UNICODE); this.setDupeStringMode(WorkBookHandle.SHAREDUPES); ExtenXLS.parseNBind(this, xmlstr); this.setFormulaCalculationMode(WorkBookHandle.CALCULATE_ALWAYS); } } catch (Exception ex) { throw new WorkBookException("Error while connecting to: " + ServerURL + ":" + ex.toString(), WorkBookException.RUNTIME_ERROR); } }
Code Sample 2:
public static void main(String[] args) throws IOException, WrongFormatException, URISyntaxException { System.out.println(new URI("google.com.ua.css").toString()); Scanner scc = new Scanner(System.in); System.err.print(scc.nextLine().substring(1)); ServerSocket s = new ServerSocket(5354); while (true) { Socket client = s.accept(); InputStream iStream = client.getInputStream(); BufferedReader bf = new BufferedReader(new InputStreamReader(iStream)); String line = ""; while (!(line = bf.readLine()).equals("")) { System.out.println(line); } System.out.println("end of request"); new PrintWriter(client.getOutputStream()).println("hi"); bf.close(); } }
|
00
|
Code Sample 1:
private boolean serverOK(String serverAddress, String serverPort) { boolean status = false; String serverString = serverAddress + ":" + serverPort + MolConvertInNodeModel.SERVER_WSDL_PATH; System.out.println("connecting to " + serverString + "..."); try { java.net.URL url = new java.net.URL(serverString); try { java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection(); status = readContents(connection); if (status) { JOptionPane.showMessageDialog(this.getPanel(), "Connection to Server is OK"); } } catch (Exception connEx) { JOptionPane.showMessageDialog(this.getPanel(), connEx.getMessage()); logger.error(connEx.getMessage()); } } catch (java.net.MalformedURLException urlEx) { JOptionPane.showMessageDialog(this.getPanel(), urlEx.getMessage()); logger.error(urlEx.getMessage()); } return status; }
Code Sample 2:
public void testFidelity() throws ParserException, IOException { Lexer lexer; Node node; int position; StringBuffer buffer; String string; char[] ref; char[] test; URL url = new URL("http://sourceforge.net"); lexer = new Lexer(url.openConnection()); position = 0; buffer = new StringBuffer(80000); while (null != (node = lexer.nextNode())) { string = node.toHtml(); if (position != node.getStartPosition()) fail("non-contiguous" + string); buffer.append(string); position = node.getEndPosition(); if (buffer.length() != position) fail("text length differed after encountering node " + string); } ref = lexer.getPage().getText().toCharArray(); test = new char[buffer.length()]; buffer.getChars(0, buffer.length(), test, 0); assertEquals("different amounts of text", ref.length, test.length); for (int i = 0; i < ref.length; i++) if (ref[i] != test[i]) fail("character differs at position " + i + ", expected <" + ref[i] + "> but was <" + test[i] + ">"); }
|
00
|
Code Sample 1:
@org.junit.Test public void testReadWrite() throws Exception { final String reference = "testString"; final Reader reader = new StringReader(reference); final StringWriter osString = new StringWriter(); final Reader teeStream = new TeeReaderWriter(reader, osString); IOUtils.copy(teeStream, new NullWriter()); teeStream.close(); osString.toString(); }
Code Sample 2:
@Override public CheckAvailabilityResult execute(final CheckAvailabilityAction action, final ExecutionContext context) throws ActionException { if (LOGGER.isDebugEnabled()) { String serverName = null; if (action.getServerId() == CheckAvailability.FEDORA_ID) { serverName = "fedora"; } else if (action.getServerId() == CheckAvailability.KRAMERIUS_ID) { serverName = "kramerius"; } LOGGER.debug("Processing action: CheckAvailability: " + serverName); } ServerUtils.checkExpiredSession(httpSessionProvider); boolean status = true; String url = null; String usr = ""; String pass = ""; if (action.getServerId() == CheckAvailability.FEDORA_ID) { url = configuration.getFedoraHost(); usr = configuration.getFedoraLogin(); pass = configuration.getFedoraPassword(); } else if (action.getServerId() == CheckAvailability.KRAMERIUS_ID) { url = configuration.getKrameriusHost() + SOME_STATIC_KRAMERIUS_PAGE; } else { throw new ActionException("Unknown server id"); } try { URLConnection con = RESTHelper.openConnection(url, usr, pass, false); if (con instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) con; int resp = httpConnection.getResponseCode(); if (resp < 200 || resp >= 308) { status = false; LOGGER.info("Server " + url + " answered with HTTP code " + httpConnection.getResponseCode()); } } else { status = false; } } catch (MalformedURLException e) { status = false; e.printStackTrace(); } catch (IOException e) { status = false; e.printStackTrace(); } return new CheckAvailabilityResult(status, url); }
|
11
|
Code Sample 1:
private void fileCopier(String filenameFrom, String filenameTo) { FileInputStream fromStream = null; FileOutputStream toStream = null; try { fromStream = new FileInputStream(new File(filenameFrom)); if (new File(filenameTo).exists()) { new File(filenameTo).delete(); } File dirr = new File(getContactPicPath()); if (!dirr.exists()) { dirr.mkdir(); } toStream = new FileOutputStream(new File(filenameTo)); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = fromStream.read(buffer)) != -1) toStream.write(buffer, 0, bytesRead); } catch (FileNotFoundException e) { Errmsg.errmsg(e); } catch (IOException e) { Errmsg.errmsg(e); } finally { try { if (fromStream != null) { fromStream.close(); } if (toStream != null) { toStream.close(); } } catch (IOException e) { Errmsg.errmsg(e); } } }
Code Sample 2:
public MemoryBinaryBody(InputStream is) throws IOException { TempPath tempPath = TempStorage.getInstance().getRootTempPath(); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(is, out); out.close(); tempFile = out.toByteArray(); }
|
11
|
Code Sample 1:
public static String MD5(String text) throws ProducteevSignatureException { try { MessageDigest md; md = MessageDigest.getInstance(ALGORITHM); byte[] md5hash; md.update(text.getBytes("utf-8"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (NoSuchAlgorithmException nsae) { throw new ProducteevSignatureException("No such algorithm : " + ALGORITHM, nsae); } catch (UnsupportedEncodingException e) { throw new ProducteevSignatureException("No such algorithm : " + ALGORITHM, e); } }
Code Sample 2:
public static String MD5(String text) { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); return text; } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); return text; } }
|
11
|
Code Sample 1:
public 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 copyFile(final File sourceFile, final File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileInputStream inStream = null; FileOutputStream outStream = null; FileChannel source = null; FileChannel destination = null; try { source = (inStream = new FileInputStream(sourceFile)).getChannel(); destination = (outStream = new FileOutputStream(destFile)).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { closeIO(source); closeIO(inStream); closeIO(destination); closeIO(outStream); } }
|
00
|
Code Sample 1:
public Program createNewProgram(int projectID, String name, String description) throws AdaptationException { Program program = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { connection = DriverManager.getConnection(CONN_STR); connection.setAutoCommit(false); statement = connection.createStatement(); String query = "INSERT INTO Programs(projectID, name, " + "description, sourcePath) VALUES ( " + projectID + ", " + "'" + name + "', " + "'" + description + "', " + "'" + "[unknown]" + "')"; log.debug("SQL Query:\n" + query); statement.executeUpdate(query); query = "SELECT * FROM Programs WHERE " + " projectID = " + projectID + " AND " + " name = '" + name + "' AND " + " description = '" + description + "'"; resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to create program failed"; log.error(msg); throw new AdaptationException(msg); } program = getProgram(resultSet); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in createNewProgram"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return program; }
Code Sample 2:
public static boolean checkVersion(String vers) throws IOException { try { String tmp = ""; URL url = new URL("http://rbmsoft.com.br/apis/ql/index.php?url=null&versao=" + vers); BufferedInputStream buf = new BufferedInputStream(url.openStream()); int dado = 0; char letra; while ((dado = buf.read()) != -1) { letra = (char) dado; tmp += letra; } if (tmp.contains("FALSE")) { return false; } else if (tmp.contains("TRUE")) { new UpdateCheck().updateDialog(); return true; } } catch (MalformedURLException e) { e.printStackTrace(); } return false; }
|
00
|
Code Sample 1:
void loadImage(Frame frame, URL url) throws Exception { URLConnection conn = url.openConnection(); String mimeType = conn.getContentType(); long length = conn.getContentLength(); InputStream is = conn.getInputStream(); loadImage(frame, is, length, mimeType); }
Code Sample 2:
public static IEntity readFromFile(File resourceName) { InputStream inputStream = null; try { URL urlResource = ModelLoader.solveResource(resourceName.getPath()); if (urlResource != null) { inputStream = urlResource.openStream(); return (IEntity) new ObjectInputStream(inputStream).readObject(); } } catch (IOException e) { } catch (ClassNotFoundException e) { } finally { if (inputStream != null) try { inputStream.close(); } catch (IOException e) { } } return null; }
|
00
|
Code Sample 1:
public boolean delete(int id) { boolean deletionOk = false; Connection conn = null; try { conn = db.getConnection(); conn.setAutoCommit(false); String sql = "DELETE FROM keyphrases WHERE website_id=?"; PreparedStatement ps = conn.prepareStatement(sql); ps.setInt(1, id); deletionOk = ps.executeUpdate() == 1; ps.close(); sql = "DELETE FROM websites WHERE id=?"; ps = conn.prepareStatement(sql); ps.setInt(1, id); boolean success = ps.executeUpdate() == 1; deletionOk = deletionOk && success; ps.close(); conn.commit(); conn.setAutoCommit(true); } catch (SQLException sqle) { try { conn.rollback(); conn.setAutoCommit(true); } catch (SQLException sex) { throw new OsseoFailure("SQL error: roll back failed. ", sex); } throw new OsseoFailure("SQL error: cannot remove website with id " + id + ".", sqle); } finally { db.putConnection(conn); } return deletionOk; }
Code Sample 2:
public void createZipCopy(IUIContext ui, final String zipFileName, final File[] filesToZip, final FilenameFilter fileFilter, Timestamp timestamp) { TestCase.assertNotNull(ui); TestCase.assertNotNull(zipFileName); TestCase.assertFalse(zipFileName.trim().length() == 0); TestCase.assertNotNull(filesToZip); TestCase.assertNotNull(timestamp); String nameCopy = zipFileName; if (nameCopy.endsWith(".zip")) { nameCopy = nameCopy.substring(0, zipFileName.length() - 4); } nameCopy = nameCopy + "_" + timestamp.toString() + ".zip"; final String finalZip = nameCopy; IWorkspaceRunnable noResourceChangedEventsRunner = new IWorkspaceRunnable() { public void run(IProgressMonitor runnerMonitor) throws CoreException { try { Map<String, File> projectFiles = new HashMap<String, File>(); IPath basePath = new Path("/"); for (File nextLocation : filesToZip) { projectFiles.putAll(getFilesToZip(nextLocation, basePath, fileFilter)); } if (projectFiles.isEmpty()) { PlatformActivator.logDebug("Zip file (" + zipFileName + ") not created because there were no files to zip"); return; } IPath resultsPath = PlatformActivator.getDefault().getResultsPath(); File copyRoot = resultsPath.toFile(); copyRoot.mkdirs(); IPath zipFilePath = resultsPath.append(new Path(finalZip)); String zipFileName = zipFilePath.toPortableString(); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); try { out.setLevel(Deflater.DEFAULT_COMPRESSION); for (String filePath : projectFiles.keySet()) { File nextFile = projectFiles.get(filePath); FileInputStream fin = new FileInputStream(nextFile); try { out.putNextEntry(new ZipEntry(filePath)); try { byte[] bin = new byte[4096]; int bread = fin.read(bin, 0, 4096); while (bread != -1) { out.write(bin, 0, bread); bread = fin.read(bin, 0, 4096); } } finally { out.closeEntry(); } } finally { fin.close(); } } } finally { out.close(); } } catch (FileNotFoundException e) { Status error = new Status(Status.ERROR, PlatformActivator.PLUGIN_ID, Status.ERROR, e.getLocalizedMessage(), e); throw new CoreException(error); } catch (IOException e) { Status error = new Status(Status.ERROR, PlatformActivator.PLUGIN_ID, Status.ERROR, e.getLocalizedMessage(), e); throw new CoreException(error); } } }; try { IWorkspace workspace = ResourcesPlugin.getWorkspace(); workspace.run(noResourceChangedEventsRunner, workspace.getRoot(), IWorkspace.AVOID_UPDATE, new NullProgressMonitor()); } catch (CoreException ce) { PlatformActivator.logException(ce); } }
|
11
|
Code Sample 1:
public static void copyToFileAndCloseStreams(InputStream istr, File destFile) throws IOException { OutputStream ostr = null; try { ostr = new FileOutputStream(destFile); IOUtils.copy(istr, ostr); } finally { if (ostr != null) ostr.close(); if (istr != null) istr.close(); } }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
11
|
Code Sample 1:
public void setKey(String key) { MessageDigest md5; byte[] mdKey = new byte[32]; try { md5 = MessageDigest.getInstance("MD5"); md5.update(key.getBytes()); byte[] digest = md5.digest(); System.arraycopy(digest, 0, mdKey, 0, 16); System.arraycopy(digest, 0, mdKey, 16, 16); } catch (Exception e) { System.out.println("MD5 not implemented, can't generate key out of string!"); System.exit(1); } setKey(mdKey); }
Code Sample 2:
public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
|
00
|
Code Sample 1:
public static byte[] readUrl(URL url) { BufferedInputStream in = null; try { class Part { byte[] partData; int len; } in = new BufferedInputStream(url.openStream()); LinkedList<Part> parts = new LinkedList<Part>(); int len = 1; while (len > 0) { byte[] data = new byte[1024]; len = in.read(data); if (len > 0) { Part part = new Part(); part.partData = data; part.len = len; parts.add(part); } } int length = 0; for (Part part : parts) length += part.len; byte[] result = new byte[length]; int pos = 0; for (Part part : parts) { System.arraycopy(part.partData, 0, result, pos, part.len); pos += part.len; } return result; } catch (IOException e) { return null; } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } }
Code Sample 2:
public void ztest_cluster() throws Exception { Configuration.init(); TomcatServer ts1 = new TomcatServer(); ts1.registerServlet("/*", TestServlet.class.getName()); ts1.registerCluster(5554); ts1.start(5555); TomcatServer ts2 = new TomcatServer(); ts2.registerServlet("/*", TestServlet.class.getName()); ts2.registerCluster(5554); ts2.start(5556); URL url1 = new URL("http://127.0.0.1:5555/a"); HttpURLConnection c1 = (HttpURLConnection) url1.openConnection(); assert getData(c1).equals("a null"); String cookie = c1.getHeaderField("Set-Cookie"); Thread.sleep(5000); URL url2 = new URL("http://127.0.0.1:5556/a"); HttpURLConnection c2 = (HttpURLConnection) url2.openConnection(); c2.setRequestProperty("Cookie", cookie); assert getData(c2).equals("a a"); }
|
11
|
Code Sample 1:
public synchronized String encrypt(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(text.getBytes("UTF-8")); byte raw[] = md.digest(); return (new BASE64Encoder()).encode(raw); }
Code Sample 2:
public static LicenseKey parseKey(String key) throws InvalidLicenseKeyException { final String f_key = key.trim(); StringTokenizer st = new StringTokenizer(f_key, FIELD_SEPERATOR); int tc = st.countTokens(); int tc_name = tc - 9; try { final String product = st.nextToken(); final String type = st.nextToken(); final String loadStr = st.nextToken(); final int load = Integer.parseInt(loadStr); final String lowMajorVersionStr = st.nextToken(); final int lowMajorVersion = Integer.parseInt(lowMajorVersionStr); final String lowMinorVersionStr = st.nextToken(); final double lowMinorVersion = Double.parseDouble("0." + lowMinorVersionStr); final String highMajorVersionStr = st.nextToken(); final int highMajorVersion = Integer.parseInt(highMajorVersionStr); final String highMinorVersionStr = st.nextToken(); final double highMinorVersion = Double.parseDouble("0." + highMinorVersionStr); String regName = ""; for (int i = 0; i < tc_name; i++) regName += (i == 0 ? st.nextToken() : FIELD_SEPERATOR + st.nextToken()); final String randomHexStr = st.nextToken(); final String md5Str = st.nextToken(); String subKey = f_key.substring(0, f_key.indexOf(md5Str) - 1); byte[] md5; MessageDigest md = null; md = MessageDigest.getInstance("MD5"); md.update(subKey.getBytes()); md.update(FIELD_SEPERATOR.getBytes()); md.update(zuonicsPassword.getBytes()); md5 = md.digest(); String testKey = subKey + FIELD_SEPERATOR; for (int i = 0; i < md5.length; i++) testKey += Integer.toHexString(md5[i]).toUpperCase(); if (!testKey.equals(f_key)) throw new InvalidLicenseKeyException("doesn't hash"); final String f_regName = regName; return new LicenseKey() { public String getProduct() { return product; } public String getType() { return type; } public int getLoad() { return load; } public String getRegName() { return f_regName; } public double getlowVersion() { return lowMajorVersion + lowMinorVersion; } public double getHighVersion() { return highMajorVersion + highMinorVersion; } public String getRandomHexStr() { return randomHexStr; } public String getMD5HexStr() { return md5Str; } public String toString() { return f_key; } public boolean equals(Object obj) { if (obj.toString().equals(toString())) return true; return false; } }; } catch (Exception e) { throw new InvalidLicenseKeyException(e.getMessage()); } }
|
00
|
Code Sample 1:
public static byte[] generateHash(String strPassword, byte[] salt) { try { MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.update(strPassword.getBytes(CHAR_ENCODING)); md.update(salt); return md.digest(); } catch (Exception e) { e.printStackTrace(); } return null; }
Code Sample 2:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pathInfo = request.getPathInfo(); getLog().info("Process request " + pathInfo); if (null != pathInfo) { String pathId = getPathId(pathInfo); JobResources res = ContextUtil.getJobResource(pathId); if (null != res) { RequestType requType = getRequestType(request); ResultAccess access = new ResultAccess(res); Collection<Long> uIdColl = res.getUniqIds(); boolean isFiltered = false; { List<String> postSeqIds = getSeqList(request); if (!postSeqIds.isEmpty()) { isFiltered = true; uIdColl = access.loadIds(postSeqIds); } } try { if ((requType.equals(RequestType.FASTA)) || (requType.equals(RequestType.SWISSPROT))) { OutputStreamWriter out = null; out = new OutputStreamWriter(response.getOutputStream()); for (Long uid : uIdColl) { if (requType.equals(RequestType.FASTA)) { SwissProt sw = access.getSwissprotEntry(uid); if (null != sw) { PrintFactory.instance().print(ConvertFactory.instance().SwissProt2fasta(sw), out); } else { System.err.println("Not able to read Swissprot entry " + uid + " in project " + res.getBaseDir()); } } else if (requType.equals(RequestType.SWISSPROT)) { File swissFile = res.getSwissprotFile(uid); if (swissFile.exists()) { InputStream in = null; try { in = new FileInputStream(swissFile); IOUtils.copy(in, out); } catch (IOException e) { e.printStackTrace(); System.err.println("Problems with reading file to output stream " + swissFile); } finally { IOUtils.closeQuietly(in); } } else { System.err.println("Swissprot file does not exist: " + swissFile); } } } out.flush(); } else { if (uIdColl.size() <= 2) { isFiltered = false; uIdColl = res.getUniqIds(); } Tree tree = access.getTreeByUniquId(uIdColl); if (requType.equals(RequestType.TREE)) { response.getWriter().write(tree.toNewHampshireX()); } else if (requType.equals(RequestType.PNG)) { List<SwissProt> sp = access.getSwissprotEntriesByUniquId(uIdColl); ImageMap map = ImageFactory.instance().createProteinCard(sp, tree, true, res); response.setContentType("image/png"); response.addHeader("Content-Disposition", "filename=ProteinCards.png"); ImageFactory.instance().printPNG(map.getImage(), response.getOutputStream()); response.getOutputStream().flush(); } else if (requType.equals(RequestType.HTML)) { List<SwissProt> sp = access.getSwissprotEntriesByUniquId(uIdColl); createHtml(res, access, tree, request, response, sp, isFiltered); } } } catch (Exception e) { e.printStackTrace(); getLog().error("Problem with Request: " + pathInfo + "; type " + requType, e); } } else { getLog().error("Resource is null: " + pathId + "; path " + pathInfo); } } else { getLog().error("PathInfo is null!!!"); } }
|
11
|
Code Sample 1:
public static void copy(File source, File dest) throws IOException { 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); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
Code Sample 2:
private MimeTypesProvider() { File mimeTypesFile = new File(XPontusConstantsIF.XPONTUS_HOME_DIR, "mimes.properties"); try { if (!mimeTypesFile.exists()) { OutputStream os = null; InputStream is = getClass().getResourceAsStream("/net/sf/xpontus/configuration/mimetypes.properties"); os = FileUtils.openOutputStream(mimeTypesFile); IOUtils.copy(is, os); IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } provider = new XPontusMimetypesFileTypeMap(mimeTypesFile.getAbsolutePath()); MimetypesFileTypeMap.setDefaultFileTypeMap(provider); } catch (Exception err) { err.printStackTrace(); } }
|
11
|
Code Sample 1:
protected void writePage(final CacheItem entry, final TranslationResponse response, ModifyTimes times) throws IOException { if (entry == null) { return; } Set<ResponseHeader> headers = new TreeSet<ResponseHeader>(); for (ResponseHeader h : entry.getHeaders()) { if (TranslationResponse.ETAG.equals(h.getName())) { if (!times.isFileLastModifiedKnown()) { headers.add(new ResponseHeaderImpl(h.getName(), doETagStripWeakMarker(h.getValues()))); } } else { headers.add(h); } } response.addHeaders(headers); if (!times.isFileLastModifiedKnown()) { response.setLastModified(entry.getLastModified()); } response.setTranslationCount(entry.getTranslationCount()); response.setFailCount(entry.getFailCount()); OutputStream output = response.getOutputStream(); try { InputStream input = entry.getContentAsStream(); try { IOUtils.copy(input, output); } finally { input.close(); } } finally { response.setEndState(ResponseStateOk.getInstance()); } }
Code Sample 2:
@Override public void run() { try { FileChannel in = new FileInputStream(inputfile).getChannel(); long pos = 0; for (int i = 1; i <= noofparts; i++) { FileChannel out = new FileOutputStream(outputfile.getAbsolutePath() + "." + "v" + i).getChannel(); status.setText("Rozdělovač: Rozděluji část " + i + ".."); if (remainingsize >= splitsize) { in.transferTo(pos, splitsize, out); pos += splitsize; remainingsize -= splitsize; } else { in.transferTo(pos, remainingsize, out); } pb.setValue(100 * i / noofparts); out.close(); } in.close(); if (deleteOnFinish) new File(inputfile + "").delete(); status.setText("Rozdělovač: Hotovo.."); JOptionPane.showMessageDialog(null, "Rozděleno!", "Rozdělovač", JOptionPane.INFORMATION_MESSAGE); } catch (IOException ex) { } }
|
11
|
Code Sample 1:
public void load(String filename) throws VisbardException { String defaultFilename = VisbardMain.getSettingsDir() + File.separator + DEFAULT_SETTINGS_FILE; File defaultFile = new File(defaultFilename); InputStream settingsInStreamFromFile = null; try { sLogger.info("Loading settings from : " + defaultFilename); settingsInStreamFromFile = new FileInputStream(defaultFile); } catch (FileNotFoundException fnf) { sLogger.info("Unable to load custom settings from user's settings directory (" + fnf.getMessage() + "); reverting to default settings"); try { InputStream settingsInStreamFromJar = VisbardMain.class.getClassLoader().getResourceAsStream(filename); FileOutputStream settingsOutStream = new FileOutputStream(defaultFile); int c; while ((c = settingsInStreamFromJar.read()) != -1) settingsOutStream.write(c); settingsInStreamFromJar.close(); settingsOutStream.close(); settingsInStreamFromFile = new FileInputStream(defaultFile); } catch (IOException ioe) { sLogger.warn("Unable to copy default settings to user's settings directory (" + ioe.getMessage() + "); using default settings from ViSBARD distribution package"); settingsInStreamFromFile = VisbardMain.class.getClassLoader().getResourceAsStream(filename); } } this.processSettingsFile(settingsInStreamFromFile, filename); }
Code Sample 2:
public static void main(String[] args) { String host; int port; char[] passphrase; System.out.println("InstallCert - Install CA certificate to Java Keystore"); System.out.println("====================================================="); final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { if ((args.length == 1) || (args.length == 2)) { String[] c = args[0].split(":"); host = c[0]; port = (c.length == 1) ? 443 : Integer.parseInt(c[1]); String p = (args.length == 1) ? "changeit" : args[1]; passphrase = p.toCharArray(); } else { String tmpStr; do { System.out.print("Enter hostname or IP address: "); tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null); } while (tmpStr == null); host = tmpStr; System.out.print("Enter port number [443]: "); tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null); port = tmpStr == null ? 443 : Integer.parseInt(tmpStr); System.out.print("Enter keystore password [changeit]: "); tmpStr = reader.readLine(); String p = "".equals(tmpStr) ? "changeit" : tmpStr; passphrase = p.toCharArray(); } char SEP = File.separatorChar; final File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security"); final File file = new File(dir, "cacerts"); System.out.println("Loading KeyStore " + file + "..."); InputStream in = new FileInputStream(file); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(in, passphrase); in.close(); SSLContext context = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0]; SavingTrustManager tm = new SavingTrustManager(defaultTrustManager); context.init(null, new TrustManager[] { tm }, null); SSLSocketFactory factory = context.getSocketFactory(); System.out.println("Opening connection to " + host + ":" + port + "..."); SSLSocket socket = (SSLSocket) factory.createSocket(host, port); socket.setSoTimeout(10000); try { System.out.println("Starting SSL handshake..."); socket.startHandshake(); socket.close(); System.out.println(); System.out.println("No errors, certificate is already trusted"); } catch (SSLException e) { System.out.println(); e.printStackTrace(System.out); } X509Certificate[] chain = tm.chain; if (chain == null) { System.out.println("Could not obtain server certificate chain"); return; } System.out.println(); System.out.println("Server sent " + chain.length + " certificate(s):"); System.out.println(); MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest md5 = MessageDigest.getInstance("MD5"); for (int i = 0; i < chain.length; i++) { X509Certificate cert = chain[i]; System.out.println(" " + (i + 1) + " Subject " + cert.getSubjectDN()); System.out.println(" Issuer " + cert.getIssuerDN()); sha1.update(cert.getEncoded()); System.out.println(" sha1 " + toHexString(sha1.digest())); md5.update(cert.getEncoded()); System.out.println(" md5 " + toHexString(md5.digest())); System.out.println(); } System.out.print("Enter certificate to add to trusted keystore or 'q' to quit [1]: "); String line = reader.readLine().trim(); int k = -1; try { k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1; } catch (NumberFormatException e) { } if (k < 0 || k >= chain.length) { System.out.println("KeyStore not changed"); } else { try { System.out.println("Creating keystore backup"); final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); final File backupFile = new File(dir, CACERTS_KEYSTORE + "." + dateFormat.format(new java.util.Date())); final FileInputStream fis = new FileInputStream(file); final FileOutputStream fos = new FileOutputStream(backupFile); IOUtils.copy(fis, fos); fis.close(); fos.close(); } catch (Exception e) { e.printStackTrace(); } System.out.println("Installing certificate..."); X509Certificate cert = chain[k]; String alias = host + "-" + (k + 1); ks.setCertificateEntry(alias, cert); OutputStream out = new FileOutputStream(file); ks.store(out, passphrase); out.close(); System.out.println(); System.out.println(cert); System.out.println(); System.out.println("Added certificate to keystore '" + file + "' using alias '" + alias + "'"); } } catch (Exception e) { System.out.println(); System.out.println("----------------------------------------------"); System.out.println("Problem occured during installing certificate:"); e.printStackTrace(); System.out.println("----------------------------------------------"); } System.out.println("Press Enter to finish..."); try { reader.readLine(); } catch (IOException e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
private void checkForNewVersion() { try { org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(net.xan.taskstack.TaskStackApp.class).getContext().getResourceMap(NewTaskDialog.class); String versionUrl = resourceMap.getString("Application.versionFileUrl"); long startTime = System.currentTimeMillis(); System.out.println("Retrieving version file from\n" + versionUrl); URL url = new URL(versionUrl); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { if (str.startsWith("LastVersion")) { String remoteVersion = str.substring(str.indexOf("=") + 1); String localVersion = resourceMap.getString("Application.version"); System.out.println("Version file found"); System.out.println("Local version: " + localVersion); System.out.println("Remote version: " + remoteVersion); if (remoteVersion.compareTo(localVersion) > 0) { askDownloadNewVersion(remoteVersion, localVersion); } break; } } long endTime = System.currentTimeMillis(); System.out.println("Elapsed time " + (endTime - startTime) + "ms"); in.close(); } catch (MalformedURLException e) { System.err.println(e.getMessage()); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
protected void handleUrl(URL url) throws Exception { File file = new File(dir.getAbsolutePath() + "/" + new Date().getTime() + "." + this.ext); FileWriter writer = new FileWriter(file); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String s; while ((s = in.readLine()) != null) { writer.write(s + "\n"); } in.close(); writer.close(); }
|
11
|
Code Sample 1:
public static String encodeFromFile(String filename) throws java.io.IOException, URISyntaxException { String encodedData = null; Base641.InputStream bis = null; File file; try { URL url = new URL(filename); URLConnection conn = url.openConnection(); file = new File("myfile.doc"); java.io.InputStream inputStream = (java.io.InputStream) conn.getInputStream(); FileOutputStream out = new FileOutputStream(file); byte buf[] = new byte[1024]; int len; while ((len = inputStream.read(buf)) > 0) out.write(buf, 0, len); out.close(); inputStream.close(); byte[] buffer = new byte[Math.max((int) (file.length() * 1.4), 40)]; int length = 0; int numBytes = 0; bis = new Base641.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(file)), Base641.ENCODE); while ((numBytes = bis.read(buffer, length, 4096)) >= 0) { length += numBytes; } encodedData = new String(buffer, 0, length, Base641.PREFERRED_ENCODING); } catch (java.io.IOException e) { throw e; } finally { try { bis.close(); } catch (Exception e) { } } return encodedData; }
Code Sample 2:
public static byte[] readResource(Class owningClass, String resourceName) { final URL url = getResourceUrl(owningClass, resourceName); if (null == url) { throw new MissingResourceException(owningClass.toString() + " key '" + resourceName + "'", owningClass.toString(), resourceName); } LOG.info("Loading resource '" + url.toExternalForm() + "' " + "from " + owningClass); final InputStream inputStream; try { inputStream = url.openStream(); } catch (IOException e) { throw new RuntimeException("Should not happpen", e); } final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { IOUtils.copy(inputStream, outputStream); } catch (IOException e) { throw new RuntimeException("Should not happpen", e); } return outputStream.toByteArray(); }
|
00
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
private static String sendRPC(String xml) throws MalformedURLException, IOException { String str = ""; String strona = OSdbServer; String logowanie = xml; URL url = new URL(strona); URLConnection connection = url.openConnection(); connection.setRequestProperty("Connection", "Close"); connection.setRequestProperty("Content-Type", "text/xml"); connection.setDoOutput(true); connection.getOutputStream().write(logowanie.getBytes("UTF-8")); Scanner in; in = new Scanner(connection.getInputStream()); while (in.hasNextLine()) { str += in.nextLine(); } ; return str; }
|
00
|
Code Sample 1:
@LargeTest public void testThreadCheck() throws Exception { ContentResolver resolver = getContext().getContentResolver(); GoogleHttpClient client = new GoogleHttpClient(resolver, "Test", false); try { HttpGet method = new HttpGet(mServerUrl); AndroidHttpClient.setThreadBlocked(true); try { client.execute(method); fail("\"thread forbids HTTP requests\" exception expected"); } catch (RuntimeException e) { if (!e.toString().contains("forbids HTTP requests")) throw e; } finally { AndroidHttpClient.setThreadBlocked(false); } HttpResponse response = client.execute(method); assertEquals("/", EntityUtils.toString(response.getEntity())); } finally { client.close(); } }
Code Sample 2:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { log.fatal("not a http request"); return; } HttpServletRequest httpRequest = (HttpServletRequest) request; String uri = httpRequest.getRequestURI(); int pathStartIdx = 0; String resourceName = null; pathStartIdx = uri.indexOf(path); if (pathStartIdx <= -1) { log.fatal("the url pattern must match: " + path + " found uri: " + uri); return; } resourceName = uri.substring(pathStartIdx + path.length()); int suffixIdx = uri.lastIndexOf('.'); if (suffixIdx <= -1) { log.fatal("no file suffix found for resource: " + uri); return; } String suffix = uri.substring(suffixIdx + 1).toLowerCase(); String mimeType = (String) mimeTypes.get(suffix); if (mimeType == null) { log.fatal("no mimeType found for resource: " + uri); log.fatal("valid mimeTypes are: " + mimeTypes.keySet()); return; } String themeName = getThemeName(); if (themeName == null) { themeName = this.themeName; } if (!themeName.startsWith("/")) { themeName = "/" + themeName; } InputStream is = null; is = ResourceFilter.class.getResourceAsStream(themeName + resourceName); if (is != null) { IOUtils.copy(is, response.getOutputStream()); response.setContentType(mimeType); response.flushBuffer(); IOUtils.closeQuietly(response.getOutputStream()); IOUtils.closeQuietly(is); } else { log.fatal("error loading resource: " + resourceName); } }
|
11
|
Code Sample 1:
public static void fixEol(File fin) throws IOException { File fout = File.createTempFile(fin.getName(), ".fixEol", fin.getParentFile()); FileChannel in = new FileInputStream(fin).getChannel(); if (0 != in.size()) { FileChannel out = new FileOutputStream(fout).getChannel(); byte[] eol = AStringUtilities.systemNewLine.getBytes(); ByteBuffer bufOut = ByteBuffer.allocateDirect(1024 * eol.length); boolean previousIsCr = false; ByteBuffer buf = ByteBuffer.allocateDirect(1024); while (in.read(buf) > 0) { buf.limit(buf.position()); buf.position(0); while (buf.remaining() > 0) { byte b = buf.get(); if (b == '\r') { previousIsCr = true; bufOut.put(eol); } else { if (b == '\n') { if (!previousIsCr) bufOut.put(eol); } else bufOut.put(b); previousIsCr = false; } } bufOut.limit(bufOut.position()); bufOut.position(0); out.write(bufOut); bufOut.clear(); buf.clear(); } out.close(); } in.close(); fin.delete(); fout.renameTo(fin); }
Code Sample 2:
private void insertContent(ImageData imageData, Element element) { URL url = getClass().getResource(imageData.getURL()); try { File imageFileRead = new File(url.toURI()); FileInputStream inputStream = new FileInputStream(imageFileRead); String imageFileWritePath = "htmlReportFiles" + "/" + imageData.getURL(); File imageFileWrite = new File(imageFileWritePath); String[] filePathTokens = imageFileWritePath.split("/"); String directoryPathCreate = filePathTokens[0]; int i = 1; while (i < filePathTokens.length - 1) { directoryPathCreate = directoryPathCreate + "/" + filePathTokens[i]; i++; } File fileDirectoryPathCreate = new File(directoryPathCreate); if (!fileDirectoryPathCreate.exists()) { boolean successfulFileCreation = fileDirectoryPathCreate.mkdirs(); if (successfulFileCreation == false) { throw new ExplanationException("Unable to create folders in path " + directoryPathCreate); } } FileOutputStream fileOutputStream = new FileOutputStream(imageFileWrite); byte[] data = new byte[1024]; int readDataNumberOfBytes = 0; while (readDataNumberOfBytes != -1) { readDataNumberOfBytes = inputStream.read(data, 0, data.length); if (readDataNumberOfBytes != -1) { fileOutputStream.write(data, 0, readDataNumberOfBytes); } } inputStream.close(); fileOutputStream.close(); } catch (Exception ex) { throw new ExplanationException(ex.getMessage()); } String caption = imageData.getCaption(); Element imageElement = element.addElement("img"); if (imageData.getURL().charAt(0) != '/') imageElement.addAttribute("src", "htmlReportFiles" + "/" + imageData.getURL()); else imageElement.addAttribute("src", "htmlReportFiles" + imageData.getURL()); imageElement.addAttribute("alt", "image not available"); if (caption != null) { element.addElement("br"); element.addText(caption); } }
|
00
|
Code Sample 1:
private static MapEntry<String, Properties> loadFpmConf() throws ConfigurationReadException { MapEntry<String, Properties> ret = null; Scanner sc = new Scanner(CONF_PATHS).useDelimiter(SEP_P); String prev = ""; while (sc.hasNext() && !hasLoaded) { Properties fpmConf = null; boolean relative = false; String path = sc.next(); if (path.startsWith(PREV_P)) { path = path.replace(PREV_P, prev.substring(0, prev.length() - 1)); } else if (path.startsWith(REL_P)) { path = path.replace(REL_P + FS, ""); relative = true; } else if (path.contains(HOME_P)) { path = path.replace(HOME_P, USER_HOME); } prev = path; path = path.concat(MAIN_CONF_FILE); try { InputStream is = null; if (relative) { is = ClassLoader.getSystemResourceAsStream(path); path = getSystemConfDir(); Strings.getOne().createPath(path); path += MAIN_CONF_FILE; FileOutputStream os = new FileOutputStream(path); IOUtils.copy(is, os); os.flush(); os.close(); os = null; } else { is = new FileInputStream(path); } fpmConf = new Properties(); fpmConf.load(is); if (fpmConf.isEmpty()) { throw new ConfigurationReadException(); } ret = new MapEntry<String, Properties>(path, fpmConf); hasLoaded = true; } catch (FileNotFoundException e) { fpmConf = null; singleton = null; hasLoaded = false; } catch (IOException e) { throw new ConfigurationReadException(); } } return ret; }
Code Sample 2:
public static void main(String args[]) { int i, j, l; short NUMNUMBERS = 256; short numbers[] = new short[NUMNUMBERS]; Darjeeling.print("START"); for (l = 0; l < 100; l++) { for (i = 0; i < NUMNUMBERS; i++) numbers[i] = (short) (NUMNUMBERS - 1 - i); for (i = 0; i < NUMNUMBERS; i++) { for (j = 0; j < NUMNUMBERS - i - 1; j++) if (numbers[j] > numbers[j + 1]) { short temp = numbers[j]; numbers[j] = numbers[j + 1]; numbers[j + 1] = temp; } } } Darjeeling.print("END"); }
|
11
|
Code Sample 1:
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(); }
Code Sample 2:
public boolean validatePassword(UserType nameMatch, String password) { try { MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.reset(); md.update(nameMatch.getSalt().getBytes("UTF-8")); md.update(password.getBytes("UTF-8")); String encodedString = new String(Base64.encode(md.digest())); return encodedString.equals(nameMatch.getPassword()); } catch (UnsupportedEncodingException ex) { logger.fatal("Your computer does not have UTF-8 support for Java installed.", ex); logger.fatal("Shutting down..."); GlobalUITools.displayFatalExceptionMessage(null, "UTF-8 for Java not installed", ex, true); assert false : "This should never happen"; return false; } catch (NoSuchAlgorithmException ex) { String errorMessage = "Could not use algorithm " + HASH_ALGORITHM; logger.fatal(ex.getMessage()); logger.fatal(errorMessage); GlobalUITools.displayFatalExceptionMessage(null, "Could not use algorithm " + HASH_ALGORITHM, ex, true); assert false : "This could should never be reached"; return false; } }
|
11
|
Code Sample 1:
public static void copy(File src, File dest) throws IOException { if (dest.exists() && dest.isFile()) { logger.fine("cp " + src + " " + dest + " -- Destination file " + dest + " already exists. Deleting..."); dest.delete(); } final File parent = dest.getParentFile(); if (!parent.exists()) { logger.info("Directory to contain destination does not exist. Creating..."); parent.mkdirs(); } final FileInputStream fis = new FileInputStream(src); final FileOutputStream fos = new FileOutputStream(dest); final byte[] b = new byte[2048]; int n; while ((n = fis.read(b)) != -1) fos.write(b, 0, n); fis.close(); fos.close(); }
Code Sample 2:
public static void translateTableMetaData(String baseDir, String tableName, NameSpaceDefinition nsDefinition) throws Exception { setVosiNS(baseDir, "table", nsDefinition); String filename = baseDir + "table.xsl"; Scanner s = new Scanner(new File(filename)); PrintWriter fw = new PrintWriter(new File(baseDir + tableName + ".xsl")); while (s.hasNextLine()) { fw.println(s.nextLine().replaceAll("TABLENAME", tableName)); } s.close(); fw.close(); applyStyle(baseDir + "tables.xml", baseDir + tableName + ".json", baseDir + tableName + ".xsl"); }
|
00
|
Code Sample 1:
static String fetchURLComposeExternPackageList(String urlpath, String pkglisturlpath) { String link = pkglisturlpath + "package-list"; try { boolean relative = isRelativePath(urlpath); readPackageList((new URL(link)).openStream(), urlpath, relative); } catch (MalformedURLException exc) { return getText("doclet.MalformedURL", link); } catch (IOException exc) { return getText("doclet.URL_error", link); } return null; }
Code Sample 2:
public static String getTitleFromURLFast(String p_url) throws Exception { URL x_url = new URL(p_url); URLConnection x_conn = x_url.openConnection(); InputStreamReader x_is_reader = new InputStreamReader(x_conn.getInputStream()); BufferedReader x_reader = new BufferedReader(x_is_reader); String x_line = null; String x_title_line = null; String x_lc_line = null; int x_title = -1; int x_end = -1; while ((x_line = x_reader.readLine()) != null) { x_lc_line = x_line.toLowerCase(); x_title = x_lc_line.indexOf("<title"); if (x_title != -1) { x_end = x_lc_line.indexOf("</title>"); x_title_line = x_line.substring((x_title + 7), (x_end == -1 ? x_line.length() : x_end)); break; } } return x_title_line; }
|
00
|
Code Sample 1:
@Override public void downloadByUUID(final UUID uuid, final HttpServletRequest request, final HttpServletResponse response) throws IOException { if (!exportsInProgress.containsKey(uuid)) { throw new IllegalStateException("No download with UUID: " + uuid); } final File compressedFile = exportsInProgress.get(uuid).file; logger.debug("File size: " + compressedFile.length()); OutputStream output = null; InputStream fileInputStream = null; try { output = response.getOutputStream(); prepareResponse(request, response, compressedFile); fileInputStream = new FileInputStream(compressedFile); IOUtils.copy(fileInputStream, output); output.flush(); } finally { IOUtils.closeQuietly(fileInputStream); IOUtils.closeQuietly(output); } }
Code Sample 2:
public static JuneClass loadClass(Map<String, Entity> globals, String packageName, String baseClassName) { try { JuneClass $class = null; String resourceName = (packageName.length() > 0 ? packageName.replace('.', '/') + "/" : "") + baseClassName.replace('.', '$') + ".class"; URL url = Resolver.class.getClassLoader().getResource(resourceName); if (url != null) { ClassBuilder builder = new ClassBuilder(globals); InputStream stream = url.openStream(); try { new ClassReader(new BufferedInputStream(stream)).accept(builder, ClassReader.SKIP_CODE); } finally { stream.close(); } $class = builder.$class; $class.loaded = true; } return $class; } catch (Exception e) { throw Helper.throwAny(e); } }
|
11
|
Code Sample 1:
public static void main(String[] args) { Option optHelp = new Option("h", "help", false, "print this message"); Option optCerts = new Option("c", "cert", true, "use external semicolon separated X.509 certificate files"); optCerts.setArgName("certificates"); Option optPasswd = new Option("p", "password", true, "set password for opening PDF"); optPasswd.setArgName("password"); Option optExtract = new Option("e", "extract", true, "extract signed PDF revisions to given folder"); optExtract.setArgName("folder"); Option optListKs = new Option("lk", "list-keystore-types", false, "list keystore types provided by java"); Option optListCert = new Option("lc", "list-certificates", false, "list certificate aliases in a KeyStore"); Option optKsType = new Option("kt", "keystore-type", true, "use keystore type with given name"); optKsType.setArgName("keystore_type"); Option optKsFile = new Option("kf", "keystore-file", true, "use given keystore file"); optKsFile.setArgName("file"); Option optKsPass = new Option("kp", "keystore-password", true, "password for keystore file (look on -kf option)"); optKsPass.setArgName("password"); Option optFailFast = new Option("ff", "fail-fast", true, "flag which sets the Verifier to exit with error code on the first validation failure"); final Options options = new Options(); options.addOption(optHelp); options.addOption(optCerts); options.addOption(optPasswd); options.addOption(optExtract); options.addOption(optListKs); options.addOption(optListCert); options.addOption(optKsType); options.addOption(optKsFile); options.addOption(optKsPass); options.addOption(optFailFast); CommandLine line = null; try { CommandLineParser parser = new PosixParser(); line = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Illegal command used: " + exp.getMessage()); System.exit(-1); } final boolean failFast = line.hasOption("ff"); final String[] tmpArgs = line.getArgs(); if (line.hasOption("h") || args == null || args.length == 0) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(70, "java -jar Verifier.jar [file1.pdf [file2.pdf ...]]", "JSignPdf Verifier is a command line tool for verifying signed PDF documents.", options, null, true); } else if (line.hasOption("lk")) { for (String tmpKsType : KeyStoreUtils.getKeyStores()) { System.out.println(tmpKsType); } } else if (line.hasOption("lc")) { for (String tmpCert : KeyStoreUtils.getCertAliases(line.getOptionValue("kt"), line.getOptionValue("kf"), line.getOptionValue("kp"))) { System.out.println(tmpCert); } } else { final VerifierLogic tmpLogic = new VerifierLogic(line.getOptionValue("kt"), line.getOptionValue("kf"), line.getOptionValue("kp")); tmpLogic.setFailFast(failFast); if (line.hasOption("c")) { String tmpCertFiles = line.getOptionValue("c"); for (String tmpCFile : tmpCertFiles.split(";")) { tmpLogic.addX509CertFile(tmpCFile); } } byte[] tmpPasswd = null; if (line.hasOption("p")) { tmpPasswd = line.getOptionValue("p").getBytes(); } String tmpExtractDir = null; if (line.hasOption("e")) { tmpExtractDir = new File(line.getOptionValue("e")).getPath(); } for (String tmpFilePath : tmpArgs) { System.out.println("Verifying " + tmpFilePath); final File tmpFile = new File(tmpFilePath); if (!tmpFile.canRead()) { System.err.println("Couln't read the file. Check the path and permissions."); if (failFast) { System.exit(-1); } continue; } final VerificationResult tmpResult = tmpLogic.verify(tmpFilePath, tmpPasswd); if (tmpResult.getException() != null) { tmpResult.getException().printStackTrace(); System.exit(-1); } else { System.out.println("Total revisions: " + tmpResult.getTotalRevisions()); for (SignatureVerification tmpSigVer : tmpResult.getVerifications()) { System.out.println(tmpSigVer.toString()); if (tmpExtractDir != null) { try { File tmpExFile = new File(tmpExtractDir + "/" + tmpFile.getName() + "_" + tmpSigVer.getRevision() + ".pdf"); System.out.println("Extracting to " + tmpExFile.getCanonicalPath()); FileOutputStream tmpFOS = new FileOutputStream(tmpExFile.getCanonicalPath()); InputStream tmpIS = tmpLogic.extractRevision(tmpFilePath, tmpPasswd, tmpSigVer.getName()); IOUtils.copy(tmpIS, tmpFOS); tmpIS.close(); tmpFOS.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } if (failFast && SignatureVerification.isError(tmpResult.getVerificationResultCode())) { System.exit(tmpResult.getVerificationResultCode()); } } } } }
Code Sample 2:
private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base: </td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted: </td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified: </td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added: </td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed: </td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total: </td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
|
11
|
Code Sample 1:
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(); }
Code Sample 2:
public FileReader(String filePath, Configuration aConfiguration) throws IOException { file = new File(URLDecoder.decode(filePath, "UTF-8")).getCanonicalFile(); readerConf = aConfiguration; if (file.isDirectory()) { File indexFile = new File(file, "index.php"); File indexFile_1 = new File(file, "index.html"); if (indexFile.exists() && !indexFile.isDirectory()) { file = indexFile; } else if (indexFile_1.exists() && !indexFile_1.isDirectory()) { file = indexFile_1; } else { if (!readerConf.getOption("showFolders").equals("Yes")) { makeErrorPage(503, "Permision denied"); } else { FileOutputStream out = new FileOutputStream(readerConf.getOption("wwwPath") + "/temp/temp.php"); File[] files = file.listFiles(); makeHeader(200, -1, new Date(System.currentTimeMillis()).toString(), "text/html"); String title = "Index of " + file; out.write(("<html><head><title>" + title + "</title></head><body><h3>Index of " + file + "</h3><p>\n").getBytes()); for (int i = 0; i < files.length; i++) { file = files[i]; String filename = file.getName(); String description = ""; if (file.isDirectory()) { description = "<DIR>"; } out.write(("<a href=\"" + file.getPath().substring(readerConf.getOption("wwwPath").length()) + "\">" + filename + "</a> " + description + "<br>\n").getBytes()); } out.write(("</p><hr><p>yawwwserwer</p></body><html>").getBytes()); file = new File(URLDecoder.decode(readerConf.getOption("wwwPath") + "/temp/temp.php", "UTF-8")).getCanonicalFile(); } } } else if (!file.exists()) { makeErrorPage(404, "File Not Found."); } else if (getExtension() == ".exe" || getExtension().contains(".py")) { FileOutputStream out = new FileOutputStream(readerConf.getOption("wwwPath") + "/temp/temp.php"); out.write((runCommand(filePath)).getBytes()); file = new File(URLDecoder.decode(readerConf.getOption("wwwPath") + "/temp/temp.php", "UTF-8")).getCanonicalFile(); } else { System.out.println(getExtension()); makeHeader(200, file.length(), new Date(file.lastModified()).toString(), TYPES.get(getExtension()).toString()); } System.out.println(file); }
|
11
|
Code Sample 1:
public static void copy(String sourceFile, String targetFile) throws IOException { FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel(); FileChannel targetChannel = new FileOutputStream(targetFile).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); targetChannel.close(); }
Code Sample 2:
public static void copy(File src, File dst) throws IOException { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dst).getChannel(); try { dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { try { srcChannel.close(); } finally { dstChannel.close(); } } }
|
00
|
Code Sample 1:
public LinkedList<NameValuePair> getQuestion() { InputStream is = null; String result = ""; LinkedList<NameValuePair> question = new LinkedList<NameValuePair>(); try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(domain); httppost.setEntity(new UrlEncodedFormEntity(library)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString()); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } is.close(); result = sb.toString(); if (result.equals("null,")) { return null; } } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } try { JSONObject json = new JSONObject(result); JSONArray data = json.getJSONArray("data"); JSONObject quest = data.getJSONObject(0); question.add(new BasicNameValuePair("q", quest.getString("q"))); question.add(new BasicNameValuePair("a", quest.getString("a"))); question.add(new BasicNameValuePair("b", quest.getString("b"))); question.add(new BasicNameValuePair("c", quest.getString("c"))); question.add(new BasicNameValuePair("d", quest.getString("d"))); question.add(new BasicNameValuePair("correct", quest.getString("correct"))); return question; } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString()); } return null; }
Code Sample 2:
public void backupFile(File fromFile, File toFile) { FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } catch (IOException e) { log.error(e.getMessage()); } finally { if (from != null) try { from.close(); } catch (IOException e) { log.error(e.getMessage()); } if (to != null) try { to.close(); } catch (IOException e) { log.error(e.getMessage()); } } }
|
11
|
Code Sample 1:
public void write(HttpServletRequest req, HttpServletResponse res, Object bean) throws IntrospectionException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, IOException { res.setContentType(contentType); final Object r; if (HttpRpcServer.HttpRpcOutput.class.isAssignableFrom(bean.getClass())) { HttpRpcServer.HttpRpcOutput output = (HttpRpcServer.HttpRpcOutput) bean; r = output.getResult(); } else r = bean; if (r != null) { if (File.class.isAssignableFrom(r.getClass())) { File file = (File) r; InputStream in = null; try { in = new FileInputStream(file); IOUtils.copy(in, res.getOutputStream()); } finally { if (in != null) in.close(); } } else if (InputStream.class.isAssignableFrom(r.getClass())) { InputStream in = null; try { in = (InputStream) r; IOUtils.copy(in, res.getOutputStream()); } finally { if (in != null) in.close(); } } else if (XFile.class.isAssignableFrom(r.getClass())) { XFile file = (XFile) r; InputStream in = null; try { in = new XFileInputStream(file); IOUtils.copy(in, res.getOutputStream()); } finally { if (in != null) in.close(); } } res.getOutputStream().flush(); } }
Code Sample 2:
public static void copyFile(File srcFile, File destFolder) { try { File destFile = new File(destFolder, srcFile.getName()); if (destFile.exists()) { throw new BuildException("Could not copy " + srcFile + " to " + destFolder + " as " + destFile + " already exists"); } FileChannel srcChannel = null; FileChannel destChannel = null; try { srcChannel = new FileInputStream(srcFile).getChannel(); destChannel = new FileOutputStream(destFile).getChannel(); destChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { if (srcChannel != null) { srcChannel.close(); } if (destChannel != null) { destChannel.close(); } } destFile.setLastModified((srcFile.lastModified())); } catch (IOException e) { throw new BuildException("Could not copy " + srcFile + " to " + destFolder + ": " + e, e); } }
|
00
|
Code Sample 1:
@Override public InputStream getResourceAsStream(String path) { try { URL url = this.getResource(path); if (url == null) return null; return url.openStream(); } catch (Exception e) { log(e.getMessage(), e); return null; } }
Code Sample 2:
public void assign() throws Exception { if (proposalIds.equals("") || usrIds.equals("")) throw new Exception("No proposal or peer-viewer selected."); String[] pids = proposalIds.split(","); String[] uids = usrIds.split(","); int pnum = pids.length; int unum = uids.length; if (pnum == 0 || unum == 0) throw new Exception("No proposal or peer-viewer selected."); int i, j; String pStr = "update proposal set current_status='assigned' where "; for (i = 0; i < pnum; i++) { if (i > 0) pStr += " OR "; pStr += "PROPOSAL_ID=" + pids[i]; } Calendar date = Calendar.getInstance(); int day = date.get(Calendar.DATE); int month = date.get(Calendar.MONTH); int year = date.get(Calendar.YEAR); String dt = String.valueOf(year) + "-" + String.valueOf(month + 1) + "-" + String.valueOf(day); PreparedStatement prepStmt = null; try { con = database.getConnection(); con.setAutoCommit(false); prepStmt = con.prepareStatement(pStr); prepStmt.executeUpdate(); pStr = "insert into event (summary,document1,document2,document3,publicComments,privateComments,ACTION_ID,eventDate,ROLE_ID,reviewText,USR_ID,PROPOSAL_ID,SUBJECTUSR_ID) values " + "('','','','','','','assigned','" + dt + "',2,'new'," + userId + ",?,?)"; prepStmt = con.prepareStatement(pStr); for (i = 0; i < pnum; i++) { for (j = 0; j < unum; j++) { prepStmt.setString(1, pids[i]); prepStmt.setString(2, uids[j]); prepStmt.executeUpdate(); } } con.commit(); } catch (Exception e) { if (!con.isClosed()) { con.rollback(); prepStmt.close(); con.close(); } throw e; } event_Form fr = new event_Form(); for (j = 0; j < unum; j++) { fr.setUSR_ID(userId); fr.setSUBJECTUSR_ID(uids[j]); systemManager.handleEvent(SystemManager.EVENT_PROPOSAL_ASSIGNED, fr, null, null); } }
|
11
|
Code Sample 1:
@SuppressWarnings("null") public static void copyFile(File src, File dst) throws IOException { if (!dst.getParentFile().exists()) { dst.getParentFile().mkdirs(); } dst.createNewFile(); FileChannel srcC = null; FileChannel dstC = null; try { srcC = new FileInputStream(src).getChannel(); dstC = new FileOutputStream(dst).getChannel(); dstC.transferFrom(srcC, 0, srcC.size()); } finally { try { if (dst != null) { dstC.close(); } } catch (Exception e) { e.printStackTrace(); } try { if (src != null) { srcC.close(); } } catch (Exception e) { e.printStackTrace(); } } }
Code Sample 2:
public static void copyFile(String target, String source) { try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(target).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { ExceptionHelper.showErrorDialog(e); } }
|
11
|
Code Sample 1:
@Override public void doExecute(String[] args) { if (args.length != 2) { printUsage(); } else { int fileNo = 0; try { fileNo = Integer.parseInt(args[1]) - 1; } catch (NumberFormatException e) { printUsage(); return; } if (fileNo < 0) { printUsage(); return; } StorageFile[] files = (StorageFile[]) ctx.getRemoteDir().listFiles(); try { StorageFile file = files[fileNo]; File outFile = getOutFile(file); FileOutputStream out = new FileOutputStream(outFile); InputStream in = file.openStream(); IOUtils.copy(in, out); IOUtils.closeQuietly(out); afterSave(outFile); if (outFile.exists()) { print("File written to: " + outFile.getAbsolutePath()); } } catch (IOException e) { printError("Failed to load file. " + e.getMessage()); } catch (Exception e) { printUsage(); return; } } }
Code Sample 2:
public static void copyFile(File source, File destination) throws IOException { FileInputStream fis = new FileInputStream(source); FileOutputStream fos = new FileOutputStream(destination); FileChannel inCh = fis.getChannel(); FileChannel outCh = fos.getChannel(); inCh.transferTo(0, inCh.size(), outCh); inCh.close(); fis.close(); outCh.close(); fos.flush(); fos.close(); }
|
11
|
Code Sample 1:
protected static String fileName2md5(String input) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(input.getBytes("iso-8859-1")); byte[] byteHash = md.digest(); md.reset(); StringBuffer resultString = new StringBuffer(); for (int i = 0; i < byteHash.length; i++) { resultString.append(Integer.toHexString(0xFF & byteHash[i])); } return (resultString.toString()); } catch (Exception ex) { Logger.error(ex.getClass() + " " + ex.getMessage()); for (int i = 0; i < ex.getStackTrace().length; i++) Logger.error(" " + ex.getStackTrace()[i].toString()); ex.printStackTrace(); } return String.valueOf(Math.random() * Long.MAX_VALUE); }
Code Sample 2:
public static String encrypt32(String plainText) { String str = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } str = buf.toString(); System.out.println("result: " + buf.toString()); System.out.println("result: " + buf.toString().substring(8, 24)); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return str; } return str; }
|
11
|
Code Sample 1:
private void copy(File fin, File fout) throws IOException { FileOutputStream out = new FileOutputStream(fout); FileInputStream in = new FileInputStream(fin); byte[] buf = new byte[2048]; int read = in.read(buf); while (read > 0) { out.write(buf, 0, read); read = in.read(buf); } in.close(); out.close(); }
Code Sample 2:
public static String sendScripts(Session session) { Channel channel = null; String tempDirectory = ""; Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "Start sendScripts."); try { { channel = session.openChannel("exec"); final String command = "mktemp -d /tmp/scipionXXXXXXXX"; ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); String[] result = inputStreamToString(in, channel); tempDirectory = result[1]; tempDirectory = tempDirectory.replaceAll("\n", ""); Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "status:" + result[0] + "-command:" + command + "-result:" + tempDirectory); IOUtils.closeQuietly(in); channel.disconnect(); } { channel = session.openChannel("exec"); final String command = "chmod 700 " + tempDirectory; ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); String[] result = inputStreamToString(in, channel); Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "status:" + result[0] + "-command:" + command + "-result:" + result[1]); IOUtils.closeQuietly(in); channel.disconnect(); } { InputStream rsyncHelperContentInput = Thread.currentThread().getContextClassLoader().getResourceAsStream("scripts/" + RSYNC_HELPER_SCRIPT); channel = session.openChannel("exec"); final String command = "cat > " + tempDirectory + "/" + RSYNC_HELPER_SCRIPT; ((ChannelExec) channel).setCommand(command); OutputStream out = channel.getOutputStream(); channel.connect(); IOUtils.copy(rsyncHelperContentInput, out); IOUtils.closeQuietly(out); channel.disconnect(); } { channel = session.openChannel("exec"); final String command = "chmod 700 " + tempDirectory + "/" + RSYNC_HELPER_SCRIPT; ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); String[] result = inputStreamToString(in, channel); Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "status:" + result[0] + "-command:" + command + "-result:" + result[1]); IOUtils.closeQuietly(in); channel.disconnect(); } { InputStream askPassContentInput = Thread.currentThread().getContextClassLoader().getResourceAsStream("scripts/" + RSYNC_ASKPASS_SCRIPT); channel = session.openChannel("exec"); final String command = "cat > " + tempDirectory + "/" + RSYNC_ASKPASS_SCRIPT; ((ChannelExec) channel).setCommand(command); OutputStream out = channel.getOutputStream(); channel.connect(); IOUtils.copy(askPassContentInput, out); IOUtils.closeQuietly(out); channel.disconnect(); } { channel = session.openChannel("exec"); final String command = "chmod 700 " + tempDirectory + "/" + RSYNC_ASKPASS_SCRIPT; ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); String[] result = inputStreamToString(in, channel); Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "status:" + result[0] + "-command:" + command + "-result:" + result[1]); IOUtils.closeQuietly(in); channel.disconnect(); } } catch (IOException ex) { Logger.getLogger(RsyncHelper.class.getName()).log(Level.SEVERE, null, ex); } catch (JSchException ex) { Logger.getLogger(RsyncHelper.class.getName()).log(Level.SEVERE, null, ex); } Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "End sendScripts."); return tempDirectory; }
|
00
|
Code Sample 1:
public SearchHandler(String criteria, int langId) { try { URL url = new URL("http://eiffel.itba.edu.ar/hci/service/Catalog.groovy?method=GetProductListByName&criteria=" + criteria + "&language_id=" + langId); URLConnection urlc = url.openConnection(); urlc.setDoOutput(false); urlc.setAllowUserInteraction(false); BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream())); String str; StringBuffer sb = new StringBuffer(); while ((str = br.readLine()) != null) { sb.append(str); sb.append("\n"); } br.close(); String response = sb.toString(); if (response == null) { return; } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(response)); Document dom = db.parse(is); NodeList nl = dom.getElementsByTagName("product"); for (int i = 0; i < nl.getLength(); i++) { Element nodes = (Element) nl.item(i); String id = nodes.getAttribute("id").toString(); NodeList name = nodes.getElementsByTagName("name"); NodeList rank2 = nodes.getElementsByTagName("sales_rank"); NodeList price = nodes.getElementsByTagName("price"); NodeList url2 = nodes.getElementsByTagName("image_url"); String nameS = getCharacterDataFromElement((Element) name.item(0)); String rank2S = getCharacterDataFromElement((Element) rank2.item(0)); String priceS = getCharacterDataFromElement((Element) price.item(0)); String url2S = getCharacterDataFromElement((Element) url2.item(0)); list.add(new ProductShort(id, nameS, rank2S, priceS, url2S)); } } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
private static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
|
00
|
Code Sample 1:
private String grabInformationFromWeb(String query, String infoName) throws Exception { String result = ""; URL url = new URL(query); HttpURLConnection request = null; request = (HttpURLConnection) url.openConnection(); if (request != null) { InputStream in = url.openStream(); int c = 0; StringBuilder sb = new StringBuilder(); while ((c = in.read()) != -1) { sb = sb.append((char) c); } String s = sb.toString(); result = Utils.getTagValue(s, "<" + infoName + ">", "</" + infoName + ">"); in.close(); } return result; }
Code Sample 2:
@Test public void testWriteAndRead() throws Exception { JCFS.configureLoopback(dir); RFile file = new RFile("testreadwrite.txt"); RFileOutputStream out = new RFileOutputStream(file); out.write("test".getBytes("utf-8")); out.close(); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[4]; int readCount = in.read(buffer); in.close(); assertEquals(4, readCount); String resultRead = new String(buffer, "utf-8"); assertEquals("test", resultRead); }
|
11
|
Code Sample 1:
@Override public void copyFile2File(final File src, final File dest, final boolean force) throws C4JException { if (dest.exists()) if (force && !dest.delete()) throw new C4JException(format("Copying ‘%s’ to ‘%s’ failed; cannot overwrite existing file.", src.getPath(), dest.getPath())); FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(src).getChannel(); outChannel = new FileOutputStream(dest).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); if (src.canExecute()) dest.setExecutable(true, false); } catch (final IOException e) { throw new C4JException(format("Could not copy ‘%s’ to ‘%s’.", src.getPath(), dest.getPath()), e); } finally { if (inChannel != null) try { try { inChannel.close(); } catch (final IOException e) { throw new C4JException(format("Could not close input stream for ‘%s’.", src.getPath()), e); } } finally { if (outChannel != null) try { outChannel.close(); } catch (final IOException e) { throw new C4JException(format("Could not close output stream for ‘%s’.", dest.getPath()), e); } } } }
Code Sample 2:
private static void copyFile(File srcFile, File destFile, long chunkSize) throws IOException { FileInputStream is = null; FileOutputStream os = null; try { is = new FileInputStream(srcFile); FileChannel iChannel = is.getChannel(); os = new FileOutputStream(destFile, false); FileChannel oChannel = os.getChannel(); long doneBytes = 0L; long todoBytes = srcFile.length(); while (todoBytes != 0L) { long iterationBytes = Math.min(todoBytes, chunkSize); long transferredLength = oChannel.transferFrom(iChannel, doneBytes, iterationBytes); if (iterationBytes != transferredLength) { throw new IOException("Error during file transfer: expected " + iterationBytes + " bytes, only " + transferredLength + " bytes copied."); } doneBytes += transferredLength; todoBytes -= transferredLength; } } finally { if (is != null) { is.close(); } if (os != null) { os.close(); } } boolean successTimestampOp = destFile.setLastModified(srcFile.lastModified()); if (!successTimestampOp) { log.warn("Could not change timestamp for {}. Index synchronization may be slow.", destFile); } }
|
00
|
Code Sample 1:
protected static String encodePassword(String raw_password) throws DatabaseException { String clean_password = validatePassword(raw_password); try { MessageDigest md = MessageDigest.getInstance(DEFAULT_PASSWORD_DIGEST); md.update(clean_password.getBytes(DEFAULT_PASSWORD_ENCODING)); String digest = new String(Base64.encodeBase64(md.digest())); if (log.isDebugEnabled()) log.debug("encodePassword: digest=" + digest); return digest; } catch (UnsupportedEncodingException e) { throw new DatabaseException("encoding-problem with password", e); } catch (NoSuchAlgorithmException e) { throw new DatabaseException("digest-problem encoding password", e); } }
Code Sample 2:
private void fetchTree() throws IOException { String urlString = BASE_URL + TREE_URL + DATASET_URL + "&family=" + mFamily; URL url = new URL(urlString); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String toParse = in.readLine(); while (in.ready()) { String add = in.readLine(); if (add == null) break; toParse += add; } if (toParse != null && !toParse.startsWith("No tree available")) mProteinTree = new PTree(this, toParse); }
|
11
|
Code Sample 1:
@Override public void runTask(HashMap pjobParameters) throws Exception { if (hasRequiredResources(isSubTask())) { String lstrSource = getSourceFilename(); String lstrTarget = getTargetFilename(); if (getSourceDirectory() != null) { lstrSource = getSourceDirectory() + File.separator + getSourceFilename(); } if (getTargetDirectory() != null) { lstrTarget = getTargetDirectory() + File.separator + getTargetFilename(); } GZIPInputStream lgzipInput = new GZIPInputStream(new FileInputStream(lstrSource)); OutputStream lfosGUnzip = new FileOutputStream(lstrTarget); byte[] buf = new byte[1024]; int len; while ((len = lgzipInput.read(buf)) > 0) lfosGUnzip.write(buf, 0, len); lgzipInput.close(); lfosGUnzip.close(); } }
Code Sample 2:
@SuppressWarnings("static-access") @RequestMapping(value = "/upload/upload.html", method = RequestMethod.POST) protected void save(HttpServletRequest request, HttpServletResponse response) throws ServletException { UPLOAD_DIRECTORY = uploadDiretory(); File diretorioUsuario = new File(UPLOAD_DIRECTORY); boolean diretorioCriado = false; if (!diretorioUsuario.exists()) { diretorioCriado = diretorioUsuario.mkdir(); if (!diretorioCriado) throw new RuntimeException("Não foi possível criar o diretório do usuário"); } PrintWriter writer = null; InputStream is = null; FileOutputStream fos = null; try { writer = response.getWriter(); } catch (IOException ex) { System.err.println(FileUploadController.class.getName() + "has thrown an exception: " + ex.getMessage()); } String filename = request.getHeader("X-File-Name"); try { is = request.getInputStream(); fos = new FileOutputStream(new File(UPLOAD_DIRECTORY + 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}"); System.err.println(FileUploadController.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); System.err.println(FileUploadController.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:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
private void invokeTest(String queryfile, String target) { try { String query = IOUtils.toString(XPathMarkBenchmarkTest.class.getResourceAsStream(queryfile)).trim(); String args = EXEC_CMD + " \"" + query + "\" \"" + target + '"'; System.out.println("Invoke command: \n " + args); Process proc = Runtime.getRuntime().exec(args, null, benchmarkDir); InputStream is = proc.getInputStream(); File outFile = new File(outDir, queryfile + ".result"); IOUtils.copy(is, new FileOutputStream(outFile)); is.close(); int ret = proc.waitFor(); if (ret != 0) { System.out.println("process exited with value : " + ret); } } catch (IOException ioe) { throw new IllegalStateException(ioe); } catch (InterruptedException irre) { throw new IllegalStateException(irre); } }
|
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 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 static String encryptSHA(String pwd) throws NoSuchAlgorithmException { MessageDigest d = java.security.MessageDigest.getInstance("SHA-1"); d.reset(); d.update(pwd.getBytes()); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(d.digest()); }
Code Sample 2:
private static String sort(final String item) { final char[] chars = item.toCharArray(); for (int i = 1; i < chars.length; i++) { for (int j = 0; j < chars.length - 1; j++) { if (chars[j] > chars[j + 1]) { final char temp = chars[j]; chars[j] = chars[j + 1]; chars[j + 1] = temp; } } } return String.valueOf(chars); }
|
11
|
Code Sample 1:
@Override public void close() throws IOException { super.close(); byte[] signatureData = toByteArray(); ZipOutputStream zipOutputStream = new ZipOutputStream(this.targetOutputStream); ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(this.originalZipFile)); ZipEntry zipEntry; while (null != (zipEntry = zipInputStream.getNextEntry())) { if (!zipEntry.getName().equals(ODFUtil.SIGNATURE_FILE)) { ZipEntry newZipEntry = new ZipEntry(zipEntry.getName()); zipOutputStream.putNextEntry(newZipEntry); LOG.debug("copying " + zipEntry.getName()); IOUtils.copy(zipInputStream, zipOutputStream); } } zipInputStream.close(); zipEntry = new ZipEntry(ODFUtil.SIGNATURE_FILE); LOG.debug("writing " + zipEntry.getName()); zipOutputStream.putNextEntry(zipEntry); IOUtils.write(signatureData, zipOutputStream); zipOutputStream.close(); }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
00
|
Code Sample 1:
@TestTargetNew(level = TestLevel.ADDITIONAL, notes = "", method = "SecureCacheResponse", args = { }) public void test_additional() throws Exception { URL url = new URL("http://google.com"); ResponseCache.setDefault(new TestResponseCache()); HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); httpCon.setUseCaches(true); httpCon.connect(); try { Thread.sleep(5000); } catch (Exception e) { } httpCon.disconnect(); }
Code Sample 2:
public static void main(String[] args) { RSSReader rssreader = new RSSReader(); try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser parser = factory.newPullParser(); String url = args[0]; InputStreamReader stream = new InputStreamReader(new URL(url).openStream()); parser.setInput(stream); XmlSerializer writer = factory.newSerializer(); writer.setOutput(new OutputStreamWriter(System.out)); rssreader.convertRSSToHtml(parser, writer); } catch (Exception e) { e.printStackTrace(System.err); } }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.