label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: @Override public void render(IContentNode contentNode, Request req, Response resp, Application app, ServerInfo serverInfo) { Node fileNode = contentNode.getNode(); try { Node res = fileNode.getNode("jcr:content"); if (checkLastModified(res, req.getServletRequset(), resp.getServletResponse())) { return; } Property data = res.getProperty("jcr:data"); InputStream is = data.getBinary().getStream(); int contentLength = (int) data.getBinary().getSize(); String mime; if (res.hasProperty("jcr:mimeType")) { mime = res.getProperty("jcr:mimeType").getString(); } else { mime = serverInfo.getSerlvetContext().getMimeType(fileNode.getName()); } if (mime != null && mime.startsWith("image")) { int w = req.getInt("w", 0); int h = req.getInt("h", 0); String fmt = req.get("fmt"); if (w != 0 || h != 0 || fmt != null) { Resource imgRes = ImageResource.create(is, mime.substring(6), w, h, req.getInt("cut", 0), fmt); imgRes.process(serverInfo); return; } } resp.getServletResponse().setContentType(mime); resp.getServletResponse().setContentLength(contentLength); OutputStream os = resp.getServletResponse().getOutputStream(); IOUtils.copy(is, os); os.flush(); os.close(); } catch (PathNotFoundException e) { e.printStackTrace(); } catch (RepositoryException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public void jsFunction_extract(ScriptableFile outputFile) throws IOException, FileSystemException, ArchiveException { InputStream is = file.jsFunction_createInputStream(); OutputStream output = outputFile.jsFunction_createOutputStream(); BufferedInputStream buf = new BufferedInputStream(is); ArchiveInputStream input = ScriptableZipArchive.getFactory().createArchiveInputStream(buf); try { long count = 0; while (input.getNextEntry() != null) { if (count == offset) { IOUtils.copy(input, output); break; } count++; } } finally { input.close(); output.close(); is.close(); } }
11
Code Sample 1: public static String[] putFECSplitFile(String uri, File file, int htl, boolean mode) { FcpFECUtils fecutils = null; Vector segmentHeaders = null; Vector segmentFileMaps = new Vector(); Vector checkFileMaps = new Vector(); Vector segmentKeyMaps = new Vector(); Vector checkKeyMaps = new Vector(); int fileLength = (int) file.length(); String output = new String(); int maxThreads = frame1.frostSettings.getIntValue("splitfileUploadThreads"); Thread[] chunkThreads = null; String[][] chunkResults = null; Thread[] checkThreads = null; String[][] checkResults = null; int threadCount = 0; String board = getBoard(file); { fecutils = new FcpFECUtils(frame1.frostSettings.getValue("nodeAddress"), frame1.frostSettings.getIntValue("nodePort")); synchronized (fecutils.getClass()) { try { segmentHeaders = fecutils.FECSegmentFile("OnionFEC_a_1_2", fileLength); } catch (Exception e) { } } int chunkCnt = 0; int checkCnt = 0; synchronized (fecutils.getClass()) { try { Socket fcpSock; BufferedInputStream fcpIn; PrintStream fcpOut; for (int i = 0; i < segmentHeaders.size(); i++) { int blockCount = (int) ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).BlockCount; int blockNo = 0; fcpSock = new Socket(InetAddress.getByName(frame1.frostSettings.getValue("nodeAddress")), frame1.frostSettings.getIntValue("nodePort")); fcpSock.setSoTimeout(1800000); fcpOut = new PrintStream(fcpSock.getOutputStream()); fcpIn = new BufferedInputStream(fcpSock.getInputStream()); FileInputStream fileIn = new FileInputStream(file); File[] chunkFiles = new File[blockCount]; { System.out.println("Processing segment " + i); fileIn.skip(((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).Offset); long segLength = ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).BlockCount * ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).BlockSize; System.out.println("segLength = " + Long.toHexString(segLength)); String headerString = "SegmentHeader\n" + ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).reconstruct() + "EndMessage\n"; String dataHeaderString = "\0\0\0\2FECEncodeSegment\nMetadataLength=" + Long.toHexString(headerString.length()) + "\nDataLength=" + Long.toHexString(headerString.length() + segLength) + "\nData\n" + headerString; System.out.print(dataHeaderString); fcpOut.print(dataHeaderString); long count = 0; while (count < segLength) { byte[] buffer = new byte[(int) ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).BlockSize]; System.out.println(Long.toHexString(((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).Offset + count)); int inbytes = fileIn.read(buffer); if (inbytes < 0) { System.out.println("End of input file - no data"); for (int j = 0; j < buffer.length; j++) buffer[j] = 0; inbytes = buffer.length; } if (inbytes < buffer.length) { System.out.println("End of input file - not enough data"); for (int j = inbytes; j < buffer.length; j++) buffer[j] = 0; inbytes = buffer.length; } if (inbytes > segLength - count) inbytes = (int) (segLength - count); fcpOut.write(buffer); File uploadMe = new File(frame1.keypool + String.valueOf(System.currentTimeMillis()) + "-" + chunkCnt + ".tmp"); chunkFiles[blockNo] = uploadMe; uploadMe.deleteOnExit(); FileOutputStream fileOut = new FileOutputStream(uploadMe); fileOut.write(buffer, 0, (int) inbytes); fileOut.close(); count += inbytes; chunkCnt++; ; blockNo++; if (blockNo >= blockCount) break; } segmentFileMaps.add(chunkFiles); fcpOut.flush(); fileIn.close(); } int checkNo = 0; int checkBlockCount = (int) ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).CheckBlockCount; File[] checkFiles = new File[checkBlockCount]; File uploadMe = null; FileOutputStream outFile = null; { String currentLine; long checkBlockSize = ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).CheckBlockSize; int checkPtr = 0; int length = 0; do { boolean started = false; currentLine = fecutils.getLine(fcpIn).trim(); if (currentLine.equals("DataChunk")) { started = true; } if (currentLine.startsWith("Length=")) { length = Integer.parseInt((currentLine.split("="))[1], 16); } if (currentLine.equals("Data")) { int currentRead; byte[] buffer = new byte[(int) length]; if (uploadMe == null) { uploadMe = new File(frame1.keypool + String.valueOf(System.currentTimeMillis()) + "-chk-" + checkCnt + ".tmp"); uploadMe.deleteOnExit(); outFile = new FileOutputStream(uploadMe); } currentRead = fcpIn.read(buffer); while (currentRead < length) { currentRead += fcpIn.read(buffer, currentRead, length - currentRead); } outFile.write(buffer); checkPtr += currentRead; if (checkPtr == checkBlockSize) { outFile.close(); checkFiles[checkNo] = uploadMe; uploadMe = null; checkNo++; checkCnt++; checkPtr = 0; } } } while (currentLine.length() > 0); checkFileMaps.add(checkFiles); } fcpOut.close(); fcpIn.close(); fcpSock.close(); } } catch (Exception e) { System.out.println("putFECSplitFile NOT GOOD " + e.toString()); } } int chunkNo = 0; int uploadedBytes = 0; for (int i = 0; i < segmentFileMaps.size(); i++) { File[] currentFileMap = (File[]) segmentFileMaps.get(i); chunkThreads = new Thread[currentFileMap.length]; chunkResults = new String[currentFileMap.length][2]; threadCount = 0; for (int j = 0; j < currentFileMap.length; j++) { if (DEBUG) System.out.println("Chunk: " + chunkNo); while (getActiveThreads(chunkThreads) >= maxThreads) mixed.wait(5000); chunkThreads[threadCount] = new putKeyThread("CHK@", currentFileMap[j], htl, chunkResults, threadCount, mode); chunkThreads[threadCount].start(); threadCount++; uploadedBytes += currentFileMap[j].length(); updateUploadTable(file, uploadedBytes, mode); mixed.wait(1000); chunkNo++; } while (getActiveThreads(chunkThreads) > 0) { if (DEBUG) System.out.println("Active Splitfile inserts remaining: " + getActiveThreads(chunkThreads)); mixed.wait(3000); } segmentKeyMaps.add(chunkResults); } int checkNo = 0; for (int i = 0; i < checkFileMaps.size(); i++) { File[] currentFileMap = (File[]) checkFileMaps.get(i); checkThreads = new Thread[currentFileMap.length]; checkResults = new String[currentFileMap.length][2]; threadCount = 0; for (int j = 0; j < currentFileMap.length; j++) { if (DEBUG) System.out.println("Check: " + checkNo); while (getActiveThreads(checkThreads) >= maxThreads) mixed.wait(5000); checkThreads[threadCount] = new putKeyThread("CHK@", currentFileMap[j], htl, checkResults, threadCount, mode); checkThreads[threadCount].start(); threadCount++; uploadedBytes += currentFileMap[j].length(); updateUploadTable(file, uploadedBytes, mode); mixed.wait(1000); checkNo++; } while (getActiveThreads(checkThreads) > 0) { if (DEBUG) System.out.println("Active Checkblock inserts remaining: " + getActiveThreads(checkThreads)); mixed.wait(3000); } checkKeyMaps.add(checkResults); } checkThreads = null; } String redirect = null; { synchronized (fecutils.getClass()) { try { redirect = fecutils.FECMakeMetadata(segmentHeaders, segmentKeyMaps, checkKeyMaps, "Frost"); } catch (Exception e) { System.out.println("putFECSplitFile NOT GOOD " + e.toString()); } } String[] sortedRedirect = redirect.split("\n"); for (int z = 0; z < sortedRedirect.length; z++) System.out.println(sortedRedirect[z]); int sortStart = -1; int sortEnd = -1; for (int line = 0; line < sortedRedirect.length; line++) { if (sortedRedirect[line].equals("Document")) { sortStart = line + 1; break; } } for (int line = sortStart; line < sortedRedirect.length; line++) { if (sortedRedirect[line].equals("End")) { sortEnd = line; break; } } System.out.println("sortStart " + sortStart + " sortEnd " + sortEnd); if (sortStart < sortEnd) Arrays.sort(sortedRedirect, sortStart, sortEnd); redirect = new String(); for (int line = 0; line < sortedRedirect.length; line++) redirect += sortedRedirect[line] + "\n"; System.out.println(redirect); } int tries = 0; String[] result = { "Error", "Error" }; while (!result[0].equals("Success") && !result[0].equals("KeyCollision") && tries < 8) { tries++; try { FcpConnection connection = new FcpConnection(frame1.frostSettings.getValue("nodeAddress"), frame1.frostSettings.getValue("nodePort")); output = connection.putKeyFromFile(uri, null, redirect.getBytes(), htl, mode); } catch (FcpToolsException e) { if (DEBUG) System.out.println("FcpToolsException " + e); frame1.displayWarning(e.toString()); } catch (UnknownHostException e) { if (DEBUG) System.out.println("UnknownHostException"); frame1.displayWarning(e.toString()); } catch (IOException e) { if (DEBUG) System.out.println("IOException"); frame1.displayWarning(e.toString()); } result = result(output); mixed.wait(3000); if (DEBUG) System.out.println("*****" + result[0] + " " + result[1] + " "); } if ((result[0].equals("Success") || result[0].equals("KeyCollision")) && mode) { try { GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("GMT")); String dirdate = cal.get(Calendar.YEAR) + "."; dirdate += cal.get(Calendar.MONTH) + 1 + "."; dirdate += cal.get(Calendar.DATE); String fileSeparator = System.getProperty("file.separator"); String destination = frame1.keypool + board + fileSeparator + dirdate + fileSeparator; FcpConnection connection = new FcpConnection(frame1.frostSettings.getValue("nodeAddress"), frame1.frostSettings.getValue("nodePort")); String contentKey = result(connection.putKeyFromFile(uri, null, redirect.getBytes(), htl, false))[1]; String prefix = new String("freenet:"); if (contentKey.startsWith(prefix)) contentKey = contentKey.substring(prefix.length()); FileAccess.writeFile("Already uploaded today", destination + contentKey + ".lck"); } catch (Exception e) { } } return result; } Code Sample 2: public String openFileAsText(String resource) throws IOException { StringWriter wtr = new StringWriter(); InputStreamReader rdr = new InputStreamReader(openFile(resource)); try { IOUtils.copy(rdr, wtr); } finally { IOUtils.closeQuietly(rdr); } return wtr.toString(); }
11
Code Sample 1: public void modify(ModifyInterceptorChain chain, DistinguishedName dn, ArrayList<LDAPModification> mods, LDAPConstraints constraints) throws LDAPException { Connection con = (Connection) chain.getRequest().get(JdbcInsert.MYVD_DB_CON + this.dbInsertName); if (con == null) { throw new LDAPException("Operations Error", LDAPException.OPERATIONS_ERROR, "No Database Connection"); } try { con.setAutoCommit(false); HashMap<String, String> ldap2db = (HashMap<String, String>) chain.getRequest().get(JdbcInsert.MYVD_DB_LDAP2DB + this.dbInsertName); Iterator<LDAPModification> it = mods.iterator(); String sql = "UPDATE " + this.tableName + " SET "; while (it.hasNext()) { LDAPModification mod = it.next(); if (mod.getOp() != LDAPModification.REPLACE) { throw new LDAPException("Only modify replace allowed", LDAPException.OBJECT_CLASS_VIOLATION, ""); } sql += ldap2db.get(mod.getAttribute().getName()) + "=? "; } sql += " WHERE " + this.rdnField + "=?"; PreparedStatement ps = con.prepareStatement(sql); it = mods.iterator(); int i = 1; while (it.hasNext()) { LDAPModification mod = it.next(); ps.setString(i, mod.getAttribute().getStringValue()); i++; } String uid = ((RDN) dn.getDN().getRDNs().get(0)).getValue(); ps.setString(i, uid); ps.executeUpdate(); con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { throw new LDAPException("Could not delete entry or rollback transaction", LDAPException.OPERATIONS_ERROR, e.toString(), e); } throw new LDAPException("Could not delete entry", LDAPException.OPERATIONS_ERROR, e.toString(), e); } } Code Sample 2: public boolean save(String trxName) { if (m_value == null || (!(m_value instanceof String || m_value instanceof byte[])) || (m_value instanceof String && m_value.toString().length() == 0) || (m_value instanceof byte[] && ((byte[]) m_value).length == 0)) { StringBuffer sql = new StringBuffer("UPDATE ").append(m_tableName).append(" SET ").append(m_columnName).append("=null WHERE ").append(m_whereClause); int no = DB.executeUpdate(sql.toString(), trxName); log.fine("save [" + trxName + "] #" + no + " - no data - set to null - " + m_value); if (no == 0) log.warning("[" + trxName + "] - not updated - " + sql); return true; } StringBuffer sql = new StringBuffer("UPDATE ").append(m_tableName).append(" SET ").append(m_columnName).append("=? WHERE ").append(m_whereClause); boolean success = true; if (DB.isRemoteObjects()) { log.fine("[" + trxName + "] - Remote - " + m_value); Server server = CConnection.get().getServer(); try { if (server != null) { success = server.updateLOB(sql.toString(), m_displayType, m_value, trxName, SecurityToken.getInstance()); if (CLogMgt.isLevelFinest()) log.fine("server.updateLOB => " + success); return success; } log.log(Level.SEVERE, "AppsServer not found"); } catch (RemoteException ex) { log.log(Level.SEVERE, "AppsServer error", ex); } return false; } log.fine("[" + trxName + "] - Local - " + m_value); Trx trx = null; if (trxName != null) trx = Trx.get(trxName, false); Connection con = null; if (trx != null) con = trx.getConnection(); if (con == null) con = DB.createConnection(false, Connection.TRANSACTION_READ_COMMITTED); if (con == null) { log.log(Level.SEVERE, "Could not get Connection"); return false; } PreparedStatement pstmt = null; success = true; try { pstmt = con.prepareStatement(sql.toString()); if (m_displayType == DisplayType.TextLong) pstmt.setString(1, (String) m_value); else pstmt.setBytes(1, (byte[]) m_value); int no = pstmt.executeUpdate(); if (no != 1) { log.warning("[" + trxName + "] - Not updated #" + no + " - " + sql); success = false; } } catch (Throwable e) { log.log(Level.SEVERE, "[" + trxName + "] - " + sql, e); success = false; } finally { DB.close(pstmt); pstmt = null; } if (success) { if (trx != null) { trx = null; con = null; } else { try { con.commit(); } catch (Exception e) { log.log(Level.SEVERE, "[" + trxName + "] - commit ", e); success = false; } finally { try { con.close(); } catch (SQLException e) { } con = null; } } } if (!success) { log.severe("[" + trxName + "] - rollback"); if (trx != null) { trx.rollback(); trx = null; con = null; } else { try { con.rollback(); } catch (Exception ee) { log.log(Level.SEVERE, "[" + trxName + "] - rollback", ee); } finally { try { con.close(); } catch (SQLException e) { } con = null; } } } return success; }
00
Code Sample 1: public void deletePortletName(PortletNameBean portletNameBean) { DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); if (portletNameBean.getPortletId() == null) throw new IllegalArgumentException("portletNameId is null"); String sql = "delete from WM_PORTAL_PORTLET_NAME " + "where ID_SITE_CTX_TYPE=?"; ps = dbDyn.prepareStatement(sql); RsetTools.setLong(ps, 1, portletNameBean.getPortletId()); int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of deleted records - " + i1); dbDyn.commit(); } catch (Exception e) { try { dbDyn.rollback(); } catch (Exception e001) { } String es = "Error delete portlet name"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } } Code Sample 2: @Override public void setOntology1Document(URL url1) throws IllegalArgumentException { if (url1 == null) throw new IllegalArgumentException("Input parameter URL for ontology 1 is null."); try { ont1 = OWLManager.createOWLOntologyManager().loadOntologyFromOntologyDocument(url1.openStream()); } catch (IOException e) { throw new IllegalArgumentException("Cannot open stream for ontology 1 from given URL."); } catch (OWLOntologyCreationException e) { throw new IllegalArgumentException("Cannot load ontology 1 from given URL."); } }
00
Code Sample 1: public boolean check(Object credentials) { try { byte[] digest = null; if (credentials instanceof Password || credentials instanceof String) { synchronized (__TYPE) { if (__md == null) __md = MessageDigest.getInstance("MD5"); __md.reset(); __md.update(credentials.toString().getBytes(StringUtil.__ISO_8859_1)); digest = __md.digest(); } if (digest == null || digest.length != _digest.length) return false; for (int i = 0; i < digest.length; i++) if (digest[i] != _digest[i]) return false; return true; } else if (credentials instanceof MD5) { MD5 md5 = (MD5) credentials; if (_digest.length != md5._digest.length) return false; for (int i = 0; i < _digest.length; i++) if (_digest[i] != md5._digest[i]) return false; return true; } else if (credentials instanceof Credential) { return ((Credential) credentials).check(this); } else { log.warn("Can't check " + credentials.getClass() + " against MD5"); return false; } } catch (Exception e) { log.warn(LogSupport.EXCEPTION, e); return false; } } Code Sample 2: protected void doGetPost(HttpServletRequest req, HttpServletResponse resp, boolean post) throws ServletException, IOException { if (responseBufferSize > 0) resp.setBufferSize(responseBufferSize); String pathinfo = req.getPathInfo(); if (pathinfo == null) { String urlstring = req.getParameter(REMOTE_URL); if (urlstring == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, ResourceBundle.getBundle(MESSAGES, req.getLocale(), new UTF8ResourceBundleControl()).getString("error.nourl")); return; } boolean allowCookieForwarding = "true".equals(req.getParameter(ALLOW_COOKIE_FORWARDING)); boolean allowFormDataForwarding = "true".equals(req.getParameter(ALLOW_FORM_DATA_FORWARDING)); String target = new JGlossURLRewriter(req.getContextPath() + req.getServletPath(), new URL(HttpUtils.getRequestURL(req).toString()), null, allowCookieForwarding, allowFormDataForwarding).rewrite(urlstring, true); resp.sendRedirect(target); return; } Set connectionAllowedProtocols; if (req.isSecure()) connectionAllowedProtocols = secureAllowedProtocols; else connectionAllowedProtocols = allowedProtocols; Object[] oa = JGlossURLRewriter.parseEncodedPath(pathinfo); if (oa == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, MessageFormat.format(ResourceBundle.getBundle(MESSAGES, req.getLocale(), new UTF8ResourceBundleControl()).getString("error.malformedrequest"), new Object[] { pathinfo })); return; } boolean allowCookieForwarding = ((Boolean) oa[0]).booleanValue(); boolean allowFormDataForwarding = ((Boolean) oa[1]).booleanValue(); String urlstring = (String) oa[2]; getServletContext().log("received request for " + urlstring); if (urlstring.toLowerCase().indexOf(req.getServletPath().toLowerCase()) != -1) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, MessageFormat.format(ResourceBundle.getBundle(MESSAGES, req.getLocale()).getString("error.addressnotallowed"), new Object[] { urlstring })); return; } if (urlstring.indexOf(':') == -1) { if (req.isSecure()) { if (secureAllowedProtocols.contains("https")) urlstring = "https://" + urlstring; } else { if (allowedProtocols.contains("http")) urlstring = "http://" + urlstring; } } URL url; try { url = new URL(urlstring); } catch (MalformedURLException ex) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, MessageFormat.format(ResourceBundle.getBundle(MESSAGES, req.getLocale()).getString("error.malformedurl"), new Object[] { urlstring })); return; } String protocol = url.getProtocol(); if (!connectionAllowedProtocols.contains(protocol)) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, MessageFormat.format(ResourceBundle.getBundle(MESSAGES, req.getLocale()).getString("error.protocolnotallowed"), new Object[] { protocol })); getServletContext().log("protocol not allowed accessing " + url.toString()); return; } boolean remoteIsHttp = protocol.equals("http") || protocol.equals("https"); boolean forwardCookies = remoteIsHttp && enableCookieForwarding && allowCookieForwarding; boolean forwardFormData = remoteIsHttp && enableFormDataForwarding && allowFormDataForwarding && (enableFormDataSecureInsecureForwarding || !req.isSecure() || url.getProtocol().equals("https")); if (forwardFormData) { String query = req.getQueryString(); if (query != null && query.length() > 0) { if (url.getQuery() == null || url.getQuery().length() == 0) url = new URL(url.toExternalForm() + "?" + query); else url = new URL(url.toExternalForm() + "&" + query); } } JGlossURLRewriter rewriter = new JGlossURLRewriter(new URL(req.getScheme(), req.getServerName(), req.getServerPort(), req.getContextPath() + req.getServletPath()).toExternalForm(), url, connectionAllowedProtocols, allowCookieForwarding, allowFormDataForwarding); URLConnection connection = url.openConnection(); if (forwardFormData && post && remoteIsHttp) { getServletContext().log("using POST"); try { ((HttpURLConnection) connection).setRequestMethod("POST"); } catch (ClassCastException ex) { getServletContext().log("failed to set method POST: " + ex.getMessage()); } connection.setDoInput(true); connection.setDoOutput(true); } String acceptEncoding = buildAcceptEncoding(req.getHeader("accept-encoding")); getServletContext().log("accept-encoding: " + acceptEncoding); if (acceptEncoding != null) connection.setRequestProperty("Accept-Encoding", acceptEncoding); forwardRequestHeaders(connection, req); if (forwardCookies && (enableCookieSecureInsecureForwarding || !req.isSecure() || url.getProtocol().equals("https"))) CookieTools.addRequestCookies(connection, req.getCookies(), getServletContext()); try { connection.connect(); } catch (UnknownHostException ex) { resp.sendError(HttpServletResponse.SC_BAD_GATEWAY, MessageFormat.format(ResourceBundle.getBundle(MESSAGES, req.getLocale()).getString("error.unknownhost"), new Object[] { url.toExternalForm(), url.getHost() })); return; } catch (IOException ex) { resp.sendError(HttpServletResponse.SC_BAD_GATEWAY, MessageFormat.format(ResourceBundle.getBundle(MESSAGES, req.getLocale()).getString("error.connect"), new Object[] { url.toExternalForm(), ex.getClass().getName(), ex.getMessage() })); return; } if (forwardFormData && post && remoteIsHttp) { InputStream is = req.getInputStream(); OutputStream os = connection.getOutputStream(); byte[] buf = new byte[512]; int len; while ((len = is.read(buf)) != -1) os.write(buf, 0, len); is.close(); os.close(); } forwardResponseHeaders(connection, req, resp, rewriter); if (forwardCookies && (enableCookieSecureInsecureForwarding || req.isSecure() || !url.getProtocol().equals("https"))) CookieTools.addResponseCookies(connection, resp, req.getServerName(), req.getContextPath() + req.getServletPath(), req.isSecure(), getServletContext()); if (remoteIsHttp) { try { int response = ((HttpURLConnection) connection).getResponseCode(); getServletContext().log("response code " + response); resp.setStatus(response); if (response == 304) return; } catch (ClassCastException ex) { getServletContext().log("failed to read response code: " + ex.getMessage()); } } String type = connection.getContentType(); getServletContext().log("content type " + type + " url " + connection.getURL().toString()); boolean supported = false; if (type != null) { for (int i = 0; i < rewrittenContentTypes.length; i++) if (type.startsWith(rewrittenContentTypes[i])) { supported = true; break; } } if (supported) { String encoding = connection.getContentEncoding(); supported = encoding == null || encoding.endsWith("gzip") || encoding.endsWith("deflate") || encoding.equals("identity"); } if (supported) rewrite(connection, req, resp, rewriter); else tunnel(connection, req, resp); }
11
Code Sample 1: private byte[] hash(String toHash) { try { MessageDigest md5 = MessageDigest.getInstance("MD5", "BC"); md5.update(toHash.getBytes("ISO-8859-1")); return md5.digest(); } catch (Exception ex) { ex.printStackTrace(); return null; } } Code Sample 2: public String digest(String algorithm, String text) { MessageDigest digester = null; try { digester = MessageDigest.getInstance(algorithm); digester.update(text.getBytes(Digester.ENCODING)); } catch (NoSuchAlgorithmException nsae) { _log.error(nsae, nsae); } catch (UnsupportedEncodingException uee) { _log.error(uee, uee); } byte[] bytes = digester.digest(); if (_BASE_64) { return Base64.encode(bytes); } else { return new String(Hex.encodeHex(bytes)); } }
00
Code Sample 1: @Override public synchronized void deleteHttpSessionStatistics(String contextName, String project, Date dateFrom, Date dateTo) throws DatabaseException { final Connection connection = this.getConnection(); try { connection.setAutoCommit(false); String queryString = "DELETE " + this.getHttpSessionInvocationsSchemaAndTableName() + " FROM " + this.getHttpSessionInvocationsSchemaAndTableName() + " INNER JOIN " + this.getHttpSessionElementsSchemaAndTableName() + " ON " + this.getHttpSessionElementsSchemaAndTableName() + ".element_id = " + this.getHttpSessionInvocationsSchemaAndTableName() + ".element_id WHERE "; if (contextName != null) { queryString = queryString + " context_name LIKE ? AND "; } if (project != null) { queryString = queryString + " project LIKE ? AND "; } if (dateFrom != null) { queryString = queryString + " start_timestamp >= ? AND "; } if (dateTo != null) { queryString = queryString + " start_timestamp <= ? AND "; } queryString = DefaultDatabaseHandler.removeOrphanWhereAndAndFromSelect(queryString); final PreparedStatement preparedStatement = DebugPreparedStatement.prepareStatement(connection, queryString); int indexCounter = 1; if (contextName != null) { preparedStatement.setString(indexCounter, contextName); indexCounter = indexCounter + 1; } if (project != null) { preparedStatement.setString(indexCounter, project); indexCounter = indexCounter + 1; } if (dateFrom != null) { preparedStatement.setTimestamp(indexCounter, new Timestamp(dateFrom.getTime())); indexCounter = indexCounter + 1; } if (dateTo != null) { preparedStatement.setTimestamp(indexCounter, new Timestamp(dateTo.getTime())); indexCounter = indexCounter + 1; } preparedStatement.executeUpdate(); preparedStatement.close(); connection.commit(); } catch (final SQLException e) { try { connection.rollback(); } catch (final SQLException ex) { JeeObserverServerContext.logger.log(Level.SEVERE, "Transaction rollback error.", ex); } JeeObserverServerContext.logger.log(Level.SEVERE, e.getMessage()); throw new DatabaseException("Error deleting HTTP session statistics.", e); } finally { this.releaseConnection(connection); } } Code Sample 2: public String addShare2(String appid, String appkey, String oauth_token, String oauth_token_secret, String openid, String format, Webpage webpage) throws Exception { String shareUrl = "http://openapi.qzone.qq.com/share/add_share"; String oauth_signature = ""; long oauth_timestamp = new Date().getTime() / 1000; String oauth_nonce = (Math.random() + "").replaceFirst("^0.", ""); List<NameValuePair> shareParameters = new ArrayList<NameValuePair>(); shareParameters.add(new BasicNameValuePair("format", format)); shareParameters.add(new BasicNameValuePair("images", webpage.images)); shareParameters.add(new BasicNameValuePair("oauth_consumer_key", appid)); shareParameters.add(new BasicNameValuePair("oauth_nonce", oauth_nonce)); shareParameters.add(new BasicNameValuePair("oauth_signature_method", "HMAC-SHA1")); shareParameters.add(new BasicNameValuePair("oauth_timestamp", oauth_timestamp + "")); shareParameters.add(new BasicNameValuePair("oauth_token", oauth_token)); shareParameters.add(new BasicNameValuePair("oauth_version", "1.0")); shareParameters.add(new BasicNameValuePair("openid", openid)); shareParameters.add(new BasicNameValuePair("title", webpage.title)); shareParameters.add(new BasicNameValuePair("url", webpage.url)); String stepA1 = "POST"; String stepA2 = URLEncoder.encode(shareUrl, "UTF-8"); String stepA3 = ""; for (int i = 0; i < shareParameters.size(); i++) { NameValuePair item = shareParameters.get(i); stepA3 += item.getName() + "=" + item.getValue(); if (i < shareParameters.size() - 1) { stepA3 += "&"; } } stepA3 = URLEncoder.encode(stepA3, "UTF-8"); String stepA = stepA1 + "&" + stepA2 + "&" + stepA3; String stepB = appkey + "&" + oauth_token_secret; Mac mac = Mac.getInstance("HmacSHA1"); SecretKeySpec spec = new SecretKeySpec(stepB.getBytes("US-ASCII"), "HmacSHA1"); mac.init(spec); byte[] oauthSignature = mac.doFinal(stepA.getBytes("US-ASCII")); oauth_signature = Base64Encoder.encode(oauthSignature); shareParameters.add(new BasicNameValuePair("oauth_signature", oauth_signature)); HttpPost sharePost = new HttpPost(shareUrl); sharePost.setHeader("Referer", "http://openapi.qzone.qq.com"); sharePost.setHeader("Host", "openapi.qzone.qq.com"); sharePost.setHeader("Accept-Language", "zh-cn"); sharePost.setHeader("Content-Type", "application/x-www-form-urlencoded"); sharePost.setEntity(new UrlEncodedFormEntity(shareParameters, "UTF-8")); DefaultHttpClient httpclient = HttpClientUtils.getHttpClient(); HttpResponse loginPostRes = httpclient.execute(sharePost); String shareHtml = HttpClientUtils.getHtml(loginPostRes, "UTF-8", false); return shareHtml; }
11
Code Sample 1: public void actionPerformed(ActionEvent e) { if (path.compareTo("") != 0) { imageName = (path.substring(path.lastIndexOf(imageFile.separator) + 1, path.length())); File imageFile = new File(path); directoryPath = "Images" + imageFile.separator + imageName.substring(0, 1).toUpperCase(); File directory = new File(directoryPath); directory.mkdirs(); imagePath = "." + imageFile.separator + "Images" + imageFile.separator + imageName.substring(0, 1).toUpperCase() + imageFile.separator + imageName; File newFile = new File(imagePath); int i = 1; while (newFile.exists()) { imagePath = "." + imageFile.separator + "Images" + imageFile.separator + imageName.substring(0, imageName.lastIndexOf('.')) + "_" + i + imageName.substring(imageName.lastIndexOf('.'), imageName.length()); newFile = new File(imagePath); i++; } imagePathThumb = (imagePath.substring(0, imagePath.lastIndexOf("."))).concat("_th.jpg"); dataBase.insertDB(theConcepts, imageName, imageName.substring(0, imageName.lastIndexOf('.'))); try { FileChannel srcChannel = new FileInputStream(path).getChannel(); FileChannel dstChannel = new FileOutputStream(imagePath).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } image = null; if (imageFile != null) { if (TFileUtils.isJAIRequired(imageFile)) { RenderedOp src = JAI.create("fileload", imageFile.getAbsolutePath()); BufferedImage bufferedImage = src.getAsBufferedImage(); image = new ImageIcon(bufferedImage); } else { image = new ImageIcon(imageFile.getAbsolutePath()); } if (image.getImageLoadStatus() == MediaTracker.ERRORED) { int choosenOption = JOptionPane.NO_OPTION; choosenOption = JOptionPane.showConfirmDialog(null, TLanguage.getString("TIGInsertImageAction.MESSAGE"), TLanguage.getString("TIGInsertImageAction.NAME"), JOptionPane.CLOSED_OPTION, JOptionPane.ERROR_MESSAGE); } else { try { int thumbWidth = PREVIEW_WIDTH; int thumbHeight = PREVIEW_HEIGHT; double thumbRatio = (double) thumbWidth / (double) thumbHeight; int imageWidth = image.getIconWidth(); int imageHeight = image.getIconHeight(); double imageRatio = (double) imageWidth / (double) imageHeight; if (thumbRatio < imageRatio) { thumbHeight = (int) (thumbWidth / imageRatio); } else { thumbWidth = (int) (thumbHeight * imageRatio); } BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = thumbImage.createGraphics(); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.drawImage(image.getImage(), 0, 0, thumbWidth, thumbHeight, null); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(imagePathThumb)); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage); int quality = 100; quality = Math.max(0, Math.min(quality, 100)); param.setQuality((float) quality / 100.0f, false); encoder.setJPEGEncodeParam(param); encoder.encode(thumbImage); out.close(); } catch (Exception ex) { System.out.println(ex.getMessage()); System.out.println(ex.toString()); } } } } } Code Sample 2: public static void copy(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws IOException { InputStream input = (InputStream) ((NativeJavaObject) args[0]).unwrap(); OutputStream output = (OutputStream) ((NativeJavaObject) args[1]).unwrap(); IOUtils.copy(input, output); }
11
Code Sample 1: @Test public void unacceptableMimeTypeTest() throws IOException { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://localhost:8080/alfresco/sword/deposit/company_home"); File file = new File("/Library/Application Support/Apple/iChat Icons/Planets/Mars.gif"); FileEntity entity = new FileEntity(file, "text/xml"); entity.setChunked(true); httppost.setEntity(entity); Date date = new Date(); Long time = date.getTime(); httppost.addHeader("content-disposition", "filename=x" + time + "x.gif"); System.out.println("Executing request...." + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { InputStream is = resEntity.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = ""; while ((line = br.readLine()) != null) { if (!line.isEmpty()) System.out.println(line); } } if (resEntity != null) { resEntity.consumeContent(); } httpclient.getConnectionManager().shutdown(); } Code Sample 2: public int doEndTag() throws JspException { HttpSession session = pageContext.getSession(); try { IntactUserI user = (IntactUserI) session.getAttribute(Constants.USER_KEY); String urlStr = user.getSourceURL(); if (urlStr == null) { return EVAL_PAGE; } URL url = null; try { url = new URL(urlStr); } catch (MalformedURLException me) { String decodedUrl = URLDecoder.decode(urlStr, "UTF-8"); pageContext.getOut().write("The source is malformed : <a href=\"" + decodedUrl + "\" target=\"_blank\">" + decodedUrl + "</a>"); return EVAL_PAGE; } StringBuffer httpContent = new StringBuffer(); httpContent.append("<!-- URL : " + urlStr + "-->"); String tmpLine; try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); while ((tmpLine = reader.readLine()) != null) { httpContent.append(tmpLine); } reader.close(); } catch (IOException ioe) { user.resetSourceURL(); String decodedUrl = URLDecoder.decode(urlStr, "UTF-8"); pageContext.getOut().write("Unable to display the source at : <a href=\"" + decodedUrl + "\" target=\"_blank\">" + decodedUrl + "</a>"); return EVAL_PAGE; } pageContext.getOut().write(httpContent.toString()); } catch (Exception e) { e.printStackTrace(); throw new JspException("Error when trying to get HTTP content"); } return EVAL_PAGE; }
00
Code Sample 1: public void copyFile(String oldPathFile, String newPathFile) { try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPathFile); if (oldfile.exists()) { InputStream inStream = new FileInputStream(oldPathFile); FileOutputStream fs = new FileOutputStream(newPathFile); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); } } catch (Exception e) { message = ("���Ƶ����ļ���������"); } } Code Sample 2: private byte[] md5Digest(String pPassword) { if (pPassword == null) { throw new NullPointerException("input null text for hashing"); } try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(pPassword.getBytes()); return md.digest(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Cannot find MD5 algorithm"); } }
11
Code Sample 1: private void load(Runestone stone) throws RunesExceptionRuneExecution, RunesExceptionNoSuchContent { final Tokeniser tokeniser = stone.<Tokeniser>getContent("tokeniser").iterator().next(); rules = new HashMap<Node, List<GazRule>>(); System.out.println("Loading Gaz from: " + _url); if (_url == null) return; BufferedReader typesIn = null, entryIn = null; try { typesIn = new BufferedReader(new InputStreamReader(_url.openStream())); String tData = typesIn.readLine(); while (tData != null) { Map<String, Map> gaz = new HashMap<String, Map>(); String[] data = tData.split(":"); URL listURL = new URL(_url, data[0]); System.err.println("Loading from " + listURL); entryIn = new BufferedReader(new InputStreamReader(listURL.openStream())); String entry = entryIn.readLine(); while (entry != null) { entry = entry.trim(); if (!entry.equals("")) { final List<Token> tokens; try { tokens = tokeniser.tokenise(entry); } catch (IOException e) { throw new RunesExceptionRuneExecution(e, this); } Map<String, Map> m = gaz; for (Token t : tokens) { String token = t.getString(); if (_case_insensitive_gazetteer) token = token.toLowerCase(); @SuppressWarnings("unchecked") Map<String, Map> next = m.get(token); if (next == null) next = new HashMap<String, Map>(); m.put(token, next); m = next; } m.put(STOP, null); } entry = entryIn.readLine(); } for (Map.Entry<String, Map> er : gaz.entrySet()) { NodeAbstract start = new NodeStringImpl(TOKEN_TYPE, null); if (_case_insensitive_gazetteer) { start.addFeature(TOKEN_HAS_STRING, new NodeRegExpImpl(TOKEN_STRING, "(?i:" + er.getKey().toLowerCase() + ")")); } else { start.addFeature(TOKEN_HAS_STRING, new NodeStringImpl(TOKEN_STRING, er.getKey())); } @SuppressWarnings("unchecked") Transition transition = mapToTransition(er.getValue()); String major = data[1]; String minor = (data.length == 3 ? data[2] : null); GazRule gr = new GazRule(major, minor, transition); List<GazRule> rl = rules.get(start); if (rl == null) rl = new ArrayList<GazRule>(); rl.add(gr); rules.put(start, rl); } entryIn.close(); System.err.println(rules.size()); tData = typesIn.readLine(); } } catch (IOException e) { throw new RunesExceptionRuneExecution(e, this); } finally { try { if (typesIn != null) typesIn.close(); } catch (IOException e) { } try { if (entryIn != null) entryIn.close(); } catch (IOException e) { } } } Code Sample 2: @SuppressWarnings("unchecked") public void handle(Map<String, Object> data, String urlPath) { try { URL url = new URL(urlPath); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); String line = null; CMGroup currentGroup = null; List<CMGroup> groups = (List<CMGroup>) data.get(CMConstants.GROUP); List<CMTag> tags = (List<CMTag>) data.get(CMConstants.TAG); List<CMTagGroup> tagGroups = (List<CMTagGroup>) data.get(CMConstants.TAG_GROUP); while ((line = reader.readLine()) != null) { CMGroup group = null; try { group = FetchUtil.getCMGroup(line); } catch (Exception e) { CMLog.getLogger(this).severe("getCMGroup error:" + line); } if (group != null) { if (currentGroup != null) { groups.add(currentGroup); } currentGroup = group; } CMTag tag = null; try { tag = FetchUtil.getCMTag(line); } catch (Exception e) { CMLog.getLogger(this).severe("getCMTag error:" + line); } if (tag != null) { CMTagGroup tagGroup = new CMTagGroup(); tagGroup.setGroupName(currentGroup.getName()); tagGroup.setTagName(tag.getName()); tags.add(tag); tagGroups.add(tagGroup); } } groups.add(currentGroup); reader.close(); } catch (MalformedURLException e) { CMLog.getLogger(this).severe("GTagHandler error:" + e.getMessage()); e.printStackTrace(); } catch (IOException e) { CMLog.getLogger(this).severe("GTagHandler error:" + e.getMessage()); e.printStackTrace(); } }
11
Code Sample 1: public static void copyFile(String source, String dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(new File(source)).getChannel(); out = new FileOutputStream(new File(dest)).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) in.close(); if (out != null) out.close(); } } Code Sample 2: protected void saveSelectedFiles() { if (dataList.getSelectedRowCount() == 0) { return; } if (dataList.getSelectedRowCount() == 1) { Object obj = model.getItemAtRow(sorter.convertRowIndexToModel(dataList.getSelectedRow())); AttachFile entry = (AttachFile) obj; JFileChooser fc = new JFileChooser(); fc.setSelectedFile(new File(fc.getCurrentDirectory(), entry.getCurrentPath().getName())); if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { File current = entry.getCurrentPath(); File dest = fc.getSelectedFile(); try { FileInputStream in = new FileInputStream(current); FileOutputStream out = new FileOutputStream(dest); byte[] readBuf = new byte[1024 * 512]; int readLength; while ((readLength = in.read(readBuf)) != -1) { out.write(readBuf, 0, readLength); } in.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return; } else { JFileChooser fc = new JFileChooser(); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { for (Integer idx : dataList.getSelectedRows()) { Object obj = model.getItemAtRow(sorter.convertRowIndexToModel(idx)); AttachFile entry = (AttachFile) obj; File current = entry.getCurrentPath(); File dest = new File(fc.getSelectedFile(), entry.getName()); try { FileInputStream in = new FileInputStream(current); FileOutputStream out = new FileOutputStream(dest); byte[] readBuf = new byte[1024 * 512]; int readLength; while ((readLength = in.read(readBuf)) != -1) { out.write(readBuf, 0, readLength); } in.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } return; } }
11
Code Sample 1: public void testStorageStringWriter() throws Exception { TranslationResponseInMemory r = new TranslationResponseInMemory(2048, "UTF-8"); { Writer w = r.getWriter(); w.write("This is an example"); w.write(" and another one."); w.flush(); 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()); } try { r.getOutputStream(); fail("Is not allowed as you already called getWriter()."); } catch (IOException e) { } { Writer output = r.getWriter(); output.write(" and another line"); 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 some more."); assertEquals("This is an example and another one. and another line and write some more and some more.", r.getText()); } r.setEndState(ResponseStateOk.getInstance()); assertEquals(ResponseStateOk.getInstance(), r.getEndState()); try { r.getWriter(); fail("Previous line should throw IOException as result closed."); } catch (IOException e) { } } Code Sample 2: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } }
00
Code Sample 1: public static String read(URL url) throws Exception { String filename = Integer.toString(url.toString().hashCode()); boolean cached = false; File dir = new File(Config.CACHE_PATH); for (File file : dir.listFiles()) { if (!file.isFile()) continue; if (file.getName().equals(filename)) { filename = file.getName(); cached = true; break; } } File file = new File(Config.CACHE_PATH, filename); if (Config.USE_CACHE && cached) return read(file); System.out.println(">> CACHE HIT FAILED."); InputStream in = null; try { in = url.openStream(); } catch (Exception e) { System.out.println(">> OPEN STREAM FAILED: " + url.toString()); return null; } String content = read(in); save(file, content); return content; } Code Sample 2: public boolean setTraceUrl(String s) { try { url = new URL(s); istream = url.openConnection(); last_contentLenght = 0; reader = new BufferedReader(new InputStreamReader(istream.getInputStream())); } catch (MalformedURLException malformedurlexception) { System.out.println("Trace2Png: MalformedURLException: " + s); return false; } catch (IOException ioexception) { System.out.println("Trace2Png: IOException: " + s); return false; } trace = t2pNewTrace(); return true; }
11
Code Sample 1: public void writeFile(String resource, InputStream is) throws IOException { File f = prepareFsReferenceAsFile(resource); FileOutputStream fos = new FileOutputStream(f); BufferedOutputStream bos = new BufferedOutputStream(fos); try { IOUtils.copy(is, bos); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(bos); } } Code Sample 2: public void xtest12() throws Exception { PDFManager manager = new ITextManager(); InputStream pdf = new FileInputStream("/tmp/090237098008f637.pdf"); InputStream page1 = manager.cut(pdf, 36, 36); OutputStream outputStream = new FileOutputStream("/tmp/090237098008f637-1.pdf"); IOUtils.copy(page1, outputStream); outputStream.close(); pdf.close(); }
00
Code Sample 1: @RequestMapping(value = "/verdocumentoFisico.html", method = RequestMethod.GET) public String editFile(ModelMap model, @RequestParam("id") int idAnexo) { Anexo anexo = anexoService.selectById(idAnexo); model.addAttribute("path", anexo.getAnexoCaminho()); try { InputStream is = new FileInputStream(new File(config.baseDir + "/arquivos_upload_direto/" + anexo.getAnexoCaminho())); FileOutputStream fos = new FileOutputStream(new File(config.baseDir + "/temp/" + anexo.getAnexoCaminho())); IOUtils.copy(is, fos); Runtime.getRuntime().exec("chmod 777 " + config.tempDir + anexo.getAnexoCaminho()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "verdocumentoFisico"; } Code Sample 2: static final void saveModule(Module module, DBConnector connector) throws IOException { String type = "pre"; if (module.isPreModule()) type = "pre"; else if (module.isPostModule()) type = "post"; else if (module.isExceptionModule()) type = "exception"; else throw new IllegalArgumentException("Module must be of a known type."); Properties props = module.getState(); Connection con = null; PreparedStatement ps = null; Statement st = null; try { con = connector.getDB(); con.setAutoCommit(false); st = con.createStatement(); st.executeUpdate("DELETE FROM instance where id=" + module.getId()); st.executeUpdate("DELETE FROM instance_property where instance_id=" + module.getId()); ps = con.prepareStatement("INSERT INTO instance VALUES (?, ?, ?, ?)"); ps.setInt(1, module.getId()); ps.setBoolean(2, module.getActive()); ps.setString(3, module.getClass().getName()); ps.setString(4, type); ps.executeUpdate(); ps.close(); ps = con.prepareStatement("INSERT INTO instance_property values(?, ?, ?)"); for (Enumeration<Object> keys = props.keys(); keys.hasMoreElements(); ) { String key = (String) keys.nextElement(); String value = props.getProperty(key); ps.setInt(1, module.getId()); ps.setString(2, key); ps.setString(3, value); ps.addBatch(); } ps.executeBatch(); con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } throw new IOException(e.getMessage()); } finally { if (st != null) { try { st.close(); } catch (SQLException ignore) { } } if (ps != null) { try { ps.close(); } catch (SQLException ignore) { } } if (con != null) { try { con.close(); } catch (SQLException ignore) { } } } }
00
Code Sample 1: public QueryOutput run() throws Exception { boolean success = false; QueryOutput output = null; if (correlator != null || inMemMaster != null || customMatcher != null) { List<Object[]> rows = inMemMaster == null ? (correlator == null ? customMatcher.onCycleEnd() : correlator.onCycleEnd()) : inMemMaster.onCycleEnd(); if (rows.isEmpty()) { success = true; return null; } output = new DirectQueryOutput(rows); } else { connection = queryContext.createConnection(); try { connection.setAutoCommit(false); connection.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); thePreparedStatement = connection.prepareStatement(thePreparedStatementSQL); RowStatusHelper.setStatusValues(statusAndPositions, thePreparedStatement, queryContext.getRunCount()); long newResultIdsAfter = lastRowIdInsertedNow; int rows = thePreparedStatement.executeUpdate(); if (rows <= 0) { success = true; return null; } lastRowIdInsertedNow = getLastRowIdInResultTable(newResultIdsAfter, rows); output = new DBQueryOutput(newResultIdsAfter, lastRowIdInsertedNow, rows, timeKeeper.getTimeMsecs()); success = true; } finally { if (connection != null) { if (success) { connection.commit(); } else { connection.rollback(); } } } } return output; } Code Sample 2: public static boolean urlStrIsDir(String urlStr) { if (urlStr.endsWith("/")) return true; int lastSlash = urlStr.lastIndexOf('/'); int lastPeriod = urlStr.lastIndexOf('.'); if (lastPeriod != -1 && (lastSlash == -1 || lastPeriod > lastSlash)) return false; String urlStrWithSlash = urlStr + "/"; try { URL url = new URL(urlStrWithSlash); InputStream f = url.openStream(); f.close(); return true; } catch (Exception e) { return false; } }
00
Code Sample 1: public static void main(String[] a) { ArrayList<String> allFilesToBeCopied = new ArrayList<String>(); new File(outputDir).mkdirs(); try { FileReader fis = new FileReader(completeFileWithDirToCathFileList); BufferedReader bis = new BufferedReader(fis); String line = ""; String currentCombo = ""; while ((line = bis.readLine()) != null) { String[] allEntries = line.split("\\s+"); String fileName = allEntries[0]; String thisCombo = allEntries[1] + allEntries[2] + allEntries[3] + allEntries[4]; if (currentCombo.equals(thisCombo)) { } else { System.out.println("merke: " + fileName); allFilesToBeCopied.add(fileName); currentCombo = thisCombo; } } System.out.println(allFilesToBeCopied.size()); for (String file : allFilesToBeCopied) { try { FileChannel srcChannel = new FileInputStream(CathDir + file).getChannel(); FileChannel dstChannel = new FileOutputStream(outputDir + file).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { e.printStackTrace(); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public void createBankSignature() { byte b; try { _bankMessageDigest = MessageDigest.getInstance("MD5"); _bankSig = Signature.getInstance("MD5/RSA/PKCS#1"); _bankSig.initSign((PrivateKey) _bankPrivateKey); _bankMessageDigest.update(getBankString().getBytes()); _bankMessageDigestBytes = _bankMessageDigest.digest(); _bankSig.update(_bankMessageDigestBytes); _bankSignatureBytes = _bankSig.sign(); } catch (Exception e) { } ; }
11
Code Sample 1: private String protectMarkup(String content, String markupRegex, String replaceSource, String replaceTarget) { Matcher matcher = Pattern.compile(markupRegex, Pattern.MULTILINE | Pattern.DOTALL).matcher(content); StringBuffer result = new StringBuffer(); while (matcher.find()) { String protectedMarkup = matcher.group(); protectedMarkup = protectedMarkup.replaceAll(replaceSource, replaceTarget); try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.reset(); digest.update(protectedMarkup.getBytes("UTF-8")); String hash = bytesToHash(digest.digest()); matcher.appendReplacement(result, hash); c_protectionMap.put(hash, protectedMarkup); m_hashList.add(hash); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } matcher.appendTail(result); return result.toString(); } Code Sample 2: @Override public String getMD5(String host) { String res = ""; Double randNumber = Math.random() + System.currentTimeMillis(); try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(randNumber.toString().getBytes()); byte[] md5 = algorithm.digest(); String tmp = ""; for (int i = 0; i < md5.length; i++) { tmp = (Integer.toHexString(0xFF & md5[i])); if (tmp.length() == 1) { res += "0" + tmp; } else { res += tmp; } } } catch (Exception ex) { } return res; }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: private boolean writeResource(PluginProxy eclipseInstallPlugin, ResourceProxy translation, LocaleProxy locale) throws Exception { String translationResourceName = determineTranslatedResourceName(translation, locale); String pluginNameInDirFormat = eclipseInstallPlugin.getName().replace(Messages.getString("Characters_period"), File.separator); if (translation.getRelativePath().contains(pluginNameInDirFormat)) { return writeResourceToBundleClasspath(translation, locale); } else if (translationResourceName.contains(File.separator)) { String resourcePath = translationResourceName.substring(0, translationResourceName.lastIndexOf(File.separatorChar)); File resourcePathDirectory = new File(directory.getPath() + File.separatorChar + resourcePath); resourcePathDirectory.mkdirs(); } File fragmentResource = new File(directory.getPath() + File.separatorChar + translationResourceName); File translatedResource = new File(translation.getFileResource().getAbsolutePath()); FileChannel inputChannel = new FileInputStream(translatedResource).getChannel(); FileChannel outputChannel = new FileOutputStream(fragmentResource).getChannel(); inputChannel.transferTo(0, inputChannel.size(), outputChannel); inputChannel.close(); outputChannel.close(); return true; }
11
Code Sample 1: private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { try { URL url = new URL(upgradeURL); InputStream in = url.openStream(); BufferedInputStream buffIn = new BufferedInputStream(in); FileOutputStream out = new FileOutputStream(""); String bytes = ""; int data = buffIn.read(); int downloadedByteCount = 1; while (data != -1) { out.write(data); bytes.concat(Character.toString((char) data)); buffIn.read(); downloadedByteCount++; updateProgressBar(downloadedByteCount); } out.close(); buffIn.close(); MessageDigest m = MessageDigest.getInstance("MD5"); m.update(bytes.getBytes()); String hash = m.digest().toString(); if (hash.length() == 31) { hash = "0" + hash; } if (!hash.equalsIgnoreCase(md5Hash)) { } } catch (MalformedURLException e) { } catch (IOException io) { } catch (NoSuchAlgorithmException a) { } } Code Sample 2: public void test_digest() throws UnsupportedEncodingException { MessageDigest sha = null; try { sha = MessageDigest.getInstance("SHA"); assertNotNull(sha); } catch (NoSuchAlgorithmException e) { fail("getInstance did not find algorithm"); } sha.update(MESSAGE.getBytes("UTF-8")); byte[] digest = sha.digest(); assertTrue("bug in SHA", MessageDigest.isEqual(digest, MESSAGE_DIGEST)); sha.reset(); for (int i = 0; i < 63; i++) { sha.update((byte) 'a'); } digest = sha.digest(); assertTrue("bug in SHA", MessageDigest.isEqual(digest, MESSAGE_DIGEST_63_As)); sha.reset(); for (int i = 0; i < 64; i++) { sha.update((byte) 'a'); } digest = sha.digest(); assertTrue("bug in SHA", MessageDigest.isEqual(digest, MESSAGE_DIGEST_64_As)); sha.reset(); for (int i = 0; i < 65; i++) { sha.update((byte) 'a'); } digest = sha.digest(); assertTrue("bug in SHA", MessageDigest.isEqual(digest, MESSAGE_DIGEST_65_As)); testSerializationSHA_DATA_1(sha); testSerializationSHA_DATA_2(sha); }
00
Code Sample 1: public static final InputStream openStream(Bundle bundle, IPath file, boolean localized) throws IOException { URL url = null; if (!localized) { url = findInPlugin(bundle, file); if (url == null) url = findInFragments(bundle, file); } else { url = FindSupport.find(bundle, file); } if (url != null) return url.openStream(); throw new IOException("Cannot find " + file.toString()); } Code Sample 2: public static Channel getChannelFromSite(String siteURL) throws LinkNotFoundException, MalformedURLException, SAXException, IOException { String channelURL = ""; siteURL = siteURL.trim(); if (!siteURL.startsWith("http://")) { siteURL = "http://" + siteURL; } URL url = new URL(siteURL); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String[] lines = new String[3]; for (int i = 0; i < lines.length; i++) { if ((lines[i] = in.readLine()) == null) { lines[i] = ""; break; } } if (lines[0].contains("xml version")) { if (lines[0].contains("rss") || lines[1].contains("rss")) { channelURL = siteURL; } if (lines[0].contains("Atom") || lines[1].contains("Atom") || lines[2].contains("Atom")) { channelURL = siteURL; } } in.close(); in = new BufferedReader(new InputStreamReader(url.openStream())); String iconURL = null; String inputLine; if ("".equals(channelURL)) { boolean isIconURLFound = false; boolean isChannelURLFound = false; while ((inputLine = in.readLine()) != null) { if (inputLine.contains("type=\"image/x-icon\"") || inputLine.toLowerCase().contains("rel=\"shortcut icon\"")) { String tmp = new String(inputLine); String[] smallLines = inputLine.replace(">", ">\n").split("\n"); for (String smallLine : smallLines) { if (smallLine.contains("type=\"image/x-icon\"") || smallLine.toLowerCase().contains("rel=\"shortcut icon\"")) { tmp = smallLine; break; } } isIconURLFound = true; iconURL = tmp.replaceAll("^.*href=\"", ""); iconURL = iconURL.replaceAll("\".*", ""); tmp = null; String originalSiteURL = new String(siteURL); siteURL = getHome(siteURL); if (iconURL.charAt(0) == '/') { if (siteURL.charAt(siteURL.length() - 1) == '/') { iconURL = siteURL + iconURL.substring(1); } else { iconURL = siteURL + iconURL; } } else if (!iconURL.startsWith("http://")) { if (siteURL.charAt(siteURL.length() - 1) == '/') { iconURL = siteURL + iconURL; } else { iconURL = siteURL + "/" + iconURL; } } siteURL = originalSiteURL; if (isChannelURLFound && isIconURLFound) { break; } } if ((inputLine.contains("type=\"application/rss+xml\"") || inputLine.contains("type=\"application/atom+xml\"")) && !isChannelURLFound) { if (!inputLine.contains("href=")) { while ((inputLine = in.readLine()) != null) { if (inputLine.contains("href=")) { break; } } } inputLine = inputLine.replace(">", ">\n"); String[] smallLines = inputLine.split("\n"); for (String smallLine : smallLines) { if (smallLine.contains("type=\"application/rss+xml\"") || smallLine.contains("type=\"application/atom+xml\"")) { inputLine = smallLine; break; } } channelURL = inputLine.replaceAll("^.*href=\"", ""); channelURL = channelURL.replaceAll("\".*", ""); if (channelURL.charAt(0) == '/') { if (siteURL.charAt(siteURL.length() - 1) == '/') { channelURL = siteURL + channelURL.substring(1); } else { channelURL = siteURL + channelURL; } } else if (!channelURL.startsWith("http://")) { if (siteURL.charAt(siteURL.length() - 1) == '/') { channelURL = siteURL + channelURL; } else { channelURL = siteURL + "/" + channelURL; } } isChannelURLFound = true; if (isChannelURLFound && isIconURLFound) { break; } } if (inputLine.contains("</head>".toLowerCase())) { break; } } in.close(); if ("".equals(channelURL)) { throw new LinkNotFoundException(); } } channel = getChannelFromXML(channelURL.trim()); if (iconURL == null || "".equals(iconURL.trim())) { iconURL = "favicon.ico"; if (siteURL.equalsIgnoreCase(channel.getChannelURL())) { siteURL = channel.getLink(); } siteURL = getHome(siteURL); if (siteURL.charAt(siteURL.length() - 1) == '/') { iconURL = siteURL + iconURL; } else { iconURL = siteURL + "/" + iconURL; } } try { String iconFileName = getHome(channel.getLink()); if (iconFileName.startsWith("http://")) { iconFileName = iconFileName.substring(7); } iconFileName = iconFileName.replaceAll("\\W", " ").trim().replace(" ", "_").concat(".ico"); String iconPath = JReader.getConfig().getShortcutIconsDir() + File.separator + iconFileName; InputStream inIcon = new URL(iconURL).openStream(); OutputStream outIcon = new FileOutputStream(iconPath); byte[] buf = new byte[1024]; int len; while ((len = inIcon.read(buf)) > 0) { outIcon.write(buf, 0, len); } inIcon.close(); outIcon.close(); channel.setIconPath(iconPath); } catch (Exception e) { } return channel; }
11
Code Sample 1: private void doDecrypt(boolean createOutput) throws IOException { FileInputStream input = null; FileOutputStream output = null; File tempOutput = null; try { input = new FileInputStream(infile); String cipherBaseFilename = basename(infile); byte[] magic = new byte[MAGIC.length]; input.read(magic); for (int i = 0; i < MAGIC.length; i++) { if (MAGIC[i] != magic[i]) throw new IOException("Not a BORK file (bad magic number)"); } short version = readShort(input); if (version / 1000 > VERSION / 1000) throw new IOException("File created by an incompatible future version: " + version + " > " + VERSION); String cipherName = readString(input); Cipher cipher = createCipher(cipherName, createSessionKey(password, cipherBaseFilename)); CipherInputStream decryptedInput = new CipherInputStream(input, cipher); long headerCrc = Unsigned.promote(readInt(decryptedInput)); decryptedInput.resetCRC(); outfile = new File(outputDir, readString(decryptedInput)); if (!createOutput || outfile.exists()) { skipped = true; return; } tempOutput = File.createTempFile("bork", null, outputDir); tempOutput.deleteOnExit(); byte[] buffer = new byte[BUFFER_SIZE]; output = new FileOutputStream(tempOutput); int bytesRead; while ((bytesRead = decryptedInput.read(buffer)) != -1) output.write(buffer, 0, bytesRead); output.close(); output = null; if (headerCrc != decryptedInput.getCRC()) { outfile = null; throw new IOException("CRC mismatch: password is probably incorrect"); } if (!tempOutput.renameTo(outfile)) throw new IOException("Failed to rename temp output file " + tempOutput + " to " + outfile); outfile.setLastModified(infile.lastModified()); } finally { close(input); close(output); if (tempOutput != null) tempOutput.delete(); } } Code Sample 2: @Test public void testCascadeTraining() throws IOException { File temp = File.createTempFile("fannj_", ".tmp"); temp.deleteOnExit(); IOUtils.copy(this.getClass().getResourceAsStream("parity8.train"), new FileOutputStream(temp)); Fann fann = new FannShortcut(8, 1); Trainer trainer = new Trainer(fann); float desiredError = .00f; float mse = trainer.cascadeTrain(temp.getPath(), 30, 1, desiredError); assertTrue("" + mse, mse <= desiredError); }
11
Code Sample 1: private byte[] md5Digest(String pPassword) { if (pPassword == null) { throw new NullPointerException("input null text for hashing"); } try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(pPassword.getBytes()); return md.digest(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Cannot find MD5 algorithm"); } } Code Sample 2: public static String generate(String source) { byte[] SHA = new byte[20]; try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.update(source.getBytes()); SHA = digest.digest(); } catch (NoSuchAlgorithmException e) { System.out.println("NO SUCH ALGORITHM EXCEPTION: " + e.getMessage()); } CommunicationLogger.warning("SHA1 DIGEST: " + SHA); return SHA.toString(); }
00
Code Sample 1: public static void invokeServlet(String op, String user) throws Exception { boolean isSayHi = true; try { if (!"sayHi".equals(op)) { isSayHi = false; } URL url = new URL("http://localhost:9080/helloworld/*.do"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream())); out.write("Operation=" + op); if (!isSayHi) { out.write("&User=" + user); } out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); boolean correctReturn = false; String response; if (isSayHi) { while ((response = in.readLine()) != null) { if (response.contains("Bonjour")) { System.out.println(" sayHi server return: Bonjour"); correctReturn = true; break; } } } else { while ((response = in.readLine()) != null) { if (response.contains("Hello CXF")) { System.out.println(" greetMe server return: Hello CXF"); correctReturn = true; break; } } } if (!correctReturn) { System.out.println("Can't got correct return from server."); } in.close(); } catch (MalformedURLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public MpegPresentation(URL url) throws IOException { File file = new File(url.getPath()); InputStream input = url.openStream(); DataInputStream ds = new DataInputStream(input); try { parseFile(ds); prepareTracks(); if (audioTrackBox != null && audioHintTrackBox != null) { audioTrack = new AudioTrack(audioTrackBox, audioHintTrackBox, file); } if (videoTrackBox != null && videoHintTrackBox != null) { videoTrack = new VideoTrack(videoTrackBox, videoHintTrackBox, file); } } finally { ds.close(); input.close(); } }
11
Code Sample 1: private static long copy(InputStream source, OutputStream sink) { try { return IOUtils.copyLarge(source, sink); } catch (IOException e) { throw new FaultException("System error copying stream", e); } finally { IOUtils.closeQuietly(source); IOUtils.closeQuietly(sink); } } Code Sample 2: protected void copyFile(final File in, final File out) throws IOException { final FileChannel inChannel = new FileInputStream(in).getChannel(); final FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (final IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } }
00
Code Sample 1: 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(); } Code Sample 2: public void run() { BufferedInputStream bis = null; URLConnection url = null; String textType = null; StringBuffer sb = new StringBuffer(); try { if (!location.startsWith("http://")) { location = "http://" + location; } url = (new URL(location)).openConnection(); size = url.getContentLength(); textType = url.getContentType(); lastModified = url.getIfModifiedSince(); InputStream is = url.getInputStream(); bis = new BufferedInputStream(is); if (textType.startsWith("text/plain")) { int i; i = bis.read(); ++position; status = " Reading From URL..."; this.setChanged(); this.notifyObservers(); while (i != END_OF_STREAM) { sb.append((char) i); i = bis.read(); ++position; if (position % (size / 25) == 0) { this.setChanged(); this.notifyObservers(); } if (abortLoading) { break; } } status = " Finished reading URL..."; } else if (textType.startsWith("text/html")) { int i; i = bis.read(); char c = (char) i; ++position; status = " Reading From URL..."; this.setChanged(); this.notifyObservers(); boolean enclosed = false; if (c == '<') { enclosed = true; } while (i != END_OF_STREAM) { if (enclosed) { if (c == '>') { enclosed = false; } } else { if (c == '<') { enclosed = true; } else { sb.append((char) i); } } i = bis.read(); c = (char) i; ++position; if (size == 0) { if (position % (size / 25) == 0) { this.setChanged(); this.notifyObservers(); } } if (abortLoading) { break; } } status = " Finished reading URL..."; } else { status = " Unable to read document type: " + textType + "..."; } bis.close(); try { document.insertString(0, sb.toString(), SimpleAttributeSet.EMPTY); } catch (BadLocationException ble) { ble.printStackTrace(); } finished = true; this.setChanged(); this.notifyObservers(); } catch (IOException ioe) { try { document.insertString(0, sb.toString(), SimpleAttributeSet.EMPTY); } catch (BadLocationException ble) { ble.printStackTrace(); } status = " IO Error Reading From URL..."; finished = true; this.setChanged(); this.notifyObservers(); } }
11
Code Sample 1: private static void copy(String from_name, String to_name) throws IOException { File from_file = new File(from_name); File to_file = new File(to_name); if (!from_file.exists()) abort("�������� ���� �� ���������" + from_file); if (!from_file.isFile()) abort("���������� ����������� ��������" + from_file); if (!from_file.canRead()) abort("�������� ���� ���������� ��� ������" + from_file); if (from_file.isDirectory()) to_file = new File(to_file, from_file.getName()); if (to_file.exists()) { if (!to_file.canWrite()) abort("�������� ���� ���������� ��� ������" + to_file); System.out.println("������������ ������� ����?" + to_file.getName() + "?(Y/N):"); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) abort("������������ ���� �� ��� �����������"); } else { String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("������� ���������� �� ���������" + parent); if (!dir.isFile()) abort("�� �������� ���������" + parent); if (!dir.canWrite()) abort("������ �� ������" + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } Code Sample 2: public static void buildPerMovieDiffBinary(String completePath, String slopeOneDataFolderName, String slopeOneDataFileName) { try { File inFile = new File(completePath + fSep + "SmartGRAPE" + fSep + slopeOneDataFolderName + fSep + slopeOneDataFileName); FileChannel inC = new FileInputStream(inFile).getChannel(); for (int i = 1; i <= 17770; i++) { File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + slopeOneDataFolderName + fSep + "Movie-" + i + "-SlopeOneData.txt"); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf = ByteBuffer.allocate(17770 * 10); for (int j = 1; j < i; j++) { ByteBuffer bbuf = ByteBuffer.allocate(12); inC.position((17769 * 17770 * 6) - ((17769 - (j - 1)) * (17770 - (j - 1)) * 6) + (i - j - 1) * 12); inC.read(bbuf); bbuf.flip(); buf.putShort(bbuf.getShort()); bbuf.getShort(); buf.putInt(bbuf.getInt()); buf.putFloat(-bbuf.getFloat()); } buf.putShort(new Integer(i).shortValue()); buf.putInt(0); buf.putFloat(0.0f); ByteBuffer remainingBuf = inC.map(FileChannel.MapMode.READ_ONLY, (17769 * 17770 * 6) - ((17769 - (i - 1)) * (17770 - (i - 1)) * 6), (17770 - i) * 12); while (remainingBuf.hasRemaining()) { remainingBuf.getShort(); buf.putShort(remainingBuf.getShort()); buf.putInt(remainingBuf.getInt()); buf.putFloat(remainingBuf.getFloat()); } buf.flip(); outC.write(buf); buf.clear(); outC.close(); } } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: public String doUpload(@ParamName(name = "file") MultipartFile file, @ParamName(name = "uploadDirectory") String _uploadDirectory) throws IOException { String sessionId = (String) RuntimeAccess.getInstance().getSession().getAttribute("SESSION_ID"); String tempUploadDir = MewitProperties.getTemporaryUploadDirectory(); if (!tempUploadDir.endsWith("/") && !tempUploadDir.endsWith("\\")) { tempUploadDir += "\\"; } String fileName = null; int position = file.getOriginalFilename().lastIndexOf("."); if (position <= 0) { fileName = java.util.UUID.randomUUID().toString(); } else { fileName = java.util.UUID.randomUUID().toString() + file.getOriginalFilename().substring(position); } File outputFile = new File(tempUploadDir, fileName); log(INFO, "writing the content of uploaded file to: " + outputFile); FileOutputStream fos = new FileOutputStream(outputFile); IOUtils.copy(file.getInputStream(), fos); file.getInputStream().close(); fos.close(); return doUploadFile(sessionId, outputFile, file.getOriginalFilename()); } Code Sample 2: public static void decompressFile(File f) throws IOException { File target = new File(f.toString().substring(0, f.toString().length() - 3)); System.out.print("Decompressing: " + f.getName() + ".. "); long initialSize = f.length(); GZIPInputStream in = new GZIPInputStream(new FileInputStream(f)); FileOutputStream fos = new FileOutputStream(target); byte[] buf = new byte[1024]; int read; while ((read = in.read(buf)) != -1) { fos.write(buf, 0, read); } System.out.println("Done."); fos.close(); in.close(); long endSize = target.length(); System.out.println("Initial size: " + initialSize + "; Decompressed size: " + endSize); }
00
Code Sample 1: private List<String> getRobots(String beginURL, String contextRoot) { List<String> vtRobots = new ArrayList<String>(); BufferedReader bfReader = null; try { URL urlx = new URL(beginURL + "/" + contextRoot + "/" + "robots.txt"); URLConnection urlConn = urlx.openConnection(); urlConn.setUseCaches(false); bfReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); String sxLine = ""; while ((sxLine = bfReader.readLine()) != null) { if (sxLine.startsWith("Disallow:")) { vtRobots.add(sxLine.substring(10)); } } } catch (Exception e) { PetstoreUtil.getLogger().log(Level.SEVERE, "Exception" + e); vtRobots = null; } finally { try { if (bfReader != null) { bfReader.close(); } } catch (Exception ee) { } } return vtRobots; } Code Sample 2: public boolean moveFileSafely(final File in, final File out) throws IOException { FileInputStream fis = null; FileOutputStream fos = null; FileChannel inChannel = null; FileChannel outChannel = null; final File tempOut = File.createTempFile("move", ".tmp"); try { fis = new FileInputStream(in); fos = new FileOutputStream(tempOut); inChannel = fis.getChannel(); outChannel = fos.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } finally { try { if (inChannel != null) inChannel.close(); } catch (IOException e) { LogUtils.debugf(JRobinConverter.class, "failed to close channel %s", inChannel); } try { if (outChannel != null) outChannel.close(); } catch (IOException e) { LogUtils.debugf(JRobinConverter.class, "failed to close channel %s", outChannel); } try { if (fis != null) fis.close(); } catch (IOException e) { LogUtils.debugf(JRobinConverter.class, "failed to close stream %s", fis); } try { if (fos != null) fos.close(); } catch (IOException e) { LogUtils.debugf(JRobinConverter.class, "failed to close stream %s", fos); } } out.delete(); if (!out.exists()) { tempOut.renameTo(out); return in.delete(); } return false; }
11
Code Sample 1: public String postEvent(EventDocument eventDoc, Map attachments) { if (eventDoc == null || eventDoc.getEvent() == null) return null; if (jmsTemplate == null) { sendEvent(eventDoc, attachments); return eventDoc.getEvent().getEventId(); } if (attachments != null) { Iterator iter = attachments.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); if (entry.getValue() instanceof DataHandler) { File file = new File(attachmentStorge + "/" + GuidUtil.generate() + entry.getKey()); try { IOUtils.copy(((DataHandler) entry.getValue()).getInputStream(), new FileOutputStream(file)); entry.setValue(file); } catch (IOException err) { err.printStackTrace(); } } } } InternalEventObject eventObj = new InternalEventObject(); eventObj.setEventDocument(eventDoc); eventObj.setAttachments(attachments); eventObj.setSessionContext(SessionContextUtil.getCurrentContext()); eventDoc.getEvent().setEventId(GuidUtil.generate()); if (destinationName != null) jmsTemplate.convertAndSend(destinationName, eventObj); else jmsTemplate.convertAndSend(eventObj); return eventDoc.getEvent().getEventId(); } Code Sample 2: public static byte[] readUrl(URL url) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); InputStream is = url.openStream(); try { IOUtils.copy(is, os); return os.toByteArray(); } finally { is.close(); } }
11
Code Sample 1: public static boolean copy(File source, File target, boolean owrite) { if (!source.exists()) { log.error("Invalid input to copy: source " + source + "doesn't exist"); return false; } else if (!source.isFile()) { log.error("Invalid input to copy: source " + source + "isn't a file."); return false; } else if (target.exists() && !owrite) { log.error("Invalid input to copy: target " + target + " exists."); return false; } try { BufferedInputStream in = new BufferedInputStream(new FileInputStream(source)); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(target)); byte buffer[] = new byte[1024]; int read = -1; while ((read = in.read(buffer, 0, 1024)) != -1) out.write(buffer, 0, read); out.flush(); out.close(); in.close(); return true; } catch (IOException e) { log.error("Copy failed: ", e); return false; } } Code Sample 2: private static void processFile(String file) throws IOException { FileInputStream in = new FileInputStream(file); int read = 0; byte[] buf = new byte[2048]; ByteArrayOutputStream bout = new ByteArrayOutputStream(); while ((read = in.read(buf)) > 0) bout.write(buf, 0, read); in.close(); String converted = bout.toString().replaceAll("@project.name@", projectNameS).replaceAll("@base.package@", basePackageS).replaceAll("@base.dir@", baseDir).replaceAll("@webapp.dir@", webAppDir).replaceAll("path=\"target/classes\"", "path=\"src/main/webapp/WEB-INF/classes\""); FileOutputStream out = new FileOutputStream(file); out.write(converted.getBytes()); out.close(); }
11
Code Sample 1: public void sendContent(OutputStream out, Range range, Map map, String string) throws IOException, NotAuthorizedException, BadRequestException { System.out.println("sendContent " + file); RFileInputStream in = new RFileInputStream(file); try { IOUtils.copyLarge(in, out); } finally { in.close(); } } Code Sample 2: public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public static void copyFile(File source, File destination) throws IOException { if (source == null) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } if (destination == null) { String message = Logging.getMessage("nullValue.DestinationIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } FileInputStream fis = null; FileOutputStream fos = null; FileChannel fic, foc; try { fis = new FileInputStream(source); fic = fis.getChannel(); fos = new FileOutputStream(destination); foc = fos.getChannel(); foc.transferFrom(fic, 0, fic.size()); fos.flush(); fis.close(); fos.close(); } finally { WWIO.closeStream(fis, source.getPath()); WWIO.closeStream(fos, destination.getPath()); } }
00
Code Sample 1: private synchronized Document executeHttpMethod(final HttpUriRequest httpRequest) throws UnauthorizedException, ThrottledException, ApiException { if (!isNextRequestAllowed()) { try { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Wait " + WAITING_TIME + "ms for request."); } wait(WAITING_TIME); } catch (InterruptedException ie) { throw new ApiException("Waiting for request interrupted.", ie); } } try { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Perform request."); } HttpResponse httpResponse = httpClient.execute(httpRequest); switch(httpResponse.getStatusLine().getStatusCode()) { case HTTP_OK: HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null) { InputStream responseStream = httpEntity.getContent(); if (responseStream == null) { throw new ApiException("TODO"); } else { String response = null; try { response = IOUtils.toString(responseStream, RESPONSE_ENCODING); } catch (IOException ioe) { throw new ApiException("Problem reading response", ioe); } catch (RuntimeException re) { httpRequest.abort(); throw new ApiException("Problem reading response", re); } finally { responseStream.close(); } StringReader responseReader = new StringReader(response); Document document = documentBuilder.parse(new InputSource(responseReader)); return document; } } case HTTP_UNAVAILABLE: throw new ThrottledException("TODO"); case HTTP_UNAUTHORIZED: throw new UnauthorizedException("TODO"); default: throw new ApiException("Unexpected HTTP status code: " + httpResponse.getStatusLine().getStatusCode()); } } catch (SAXException se) { throw new ApiException("TODO", se); } catch (IOException ioe) { throw new ApiException("TODO", ioe); } finally { updateLastRequestTimestamp(); } } Code Sample 2: @Override public void configure() { initResouce(); if (this.locale == null) { this.locale = Locale.getDefault(); } InputStream[] ins = new InputStream[getResourceList().size()]; try { int i = 0; for (URL url : getResourceList()) { ins[i++] = url.openStream(); } this.resources = new ValidatorResources(ins); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } catch (SAXException e) { e.printStackTrace(); throw new RuntimeException(e); } }
00
Code Sample 1: private synchronized jdbcResultSet executeHTTP(String s) throws SQLException { byte result[]; try { URL url = new URL(sConnect); String p = StringConverter.unicodeToHexString(sUser); p += "+" + StringConverter.unicodeToHexString(sPassword); p += "+" + StringConverter.unicodeToHexString(s); URLConnection c = url.openConnection(); c.setDoOutput(true); OutputStream os = c.getOutputStream(); os.write(p.getBytes(ENCODING)); os.close(); c.connect(); InputStream is = (InputStream) c.getContent(); BufferedInputStream in = new BufferedInputStream(is); int len = c.getContentLength(); result = new byte[len]; for (int i = 0; i < len; i++) { int r = in.read(); result[i] = (byte) r; } } catch (Exception e) { throw Trace.error(Trace.CONNECTION_IS_BROKEN, e.getMessage()); } return new jdbcResultSet(new Result(result)); } Code Sample 2: @Override public int onPut(Operation operation) { synchronized (MuleObexRequestHandler.connections) { MuleObexRequestHandler.connections++; if (logger.isDebugEnabled()) { logger.debug("Connection accepted, total number of connections: " + MuleObexRequestHandler.connections); } } int result = ResponseCodes.OBEX_HTTP_OK; try { headers = operation.getReceivedHeaders(); if (!this.maxFileSize.equals(ObexServer.UNLIMMITED_FILE_SIZE)) { Long fileSize = (Long) headers.getHeader(HeaderSet.LENGTH); if (fileSize == null) { result = ResponseCodes.OBEX_HTTP_LENGTH_REQUIRED; } if (fileSize > this.maxFileSize) { result = ResponseCodes.OBEX_HTTP_REQ_TOO_LARGE; } } if (result != ResponseCodes.OBEX_HTTP_OK) { InputStream in = operation.openInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); in.close(); out.close(); data = out.toByteArray(); if (interrupted) { data = null; result = ResponseCodes.OBEX_HTTP_GONE; } } return result; } catch (IOException e) { return ResponseCodes.OBEX_HTTP_UNAVAILABLE; } finally { synchronized (this) { this.notify(); } synchronized (MuleObexRequestHandler.connections) { MuleObexRequestHandler.connections--; if (logger.isDebugEnabled()) { logger.debug("Connection closed, total number of connections: " + MuleObexRequestHandler.connections); } } } }
11
Code Sample 1: public static Drawable fetchCachedDrawable(String url) throws MalformedURLException, IOException { Log.d(LOG_TAG, "Fetching cached : " + url); String cacheName = md5(url); checkAndCreateDirectoryIfNeeded(); File r = new File(CACHELOCATION + cacheName); if (!r.exists()) { InputStream is = (InputStream) fetch(url); FileOutputStream fos = new FileOutputStream(CACHELOCATION + cacheName); int nextChar; while ((nextChar = is.read()) != -1) fos.write((char) nextChar); fos.flush(); } FileInputStream fis = new FileInputStream(CACHELOCATION + cacheName); Drawable d = Drawable.createFromStream(fis, "src"); return d; } Code Sample 2: public static boolean copyFile(File from, File to, byte[] buf) { if (buf == null) buf = new byte[BUFFER_SIZE]; FileInputStream from_s = null; FileOutputStream to_s = null; try { from_s = new FileInputStream(from); to_s = new FileOutputStream(to); for (int bytesRead = from_s.read(buf); bytesRead != -1; bytesRead = from_s.read(buf)) to_s.write(buf, 0, bytesRead); from_s.close(); from_s = null; to_s.getFD().sync(); to_s.close(); to_s = null; } catch (IOException ioe) { return false; } finally { if (from_s != null) { try { from_s.close(); } catch (IOException ioe) { } } if (to_s != null) { try { to_s.close(); } catch (IOException ioe) { } } } return true; }
00
Code Sample 1: public void _testConvertIntoOneFile() { File csvFile = new File("C:/DE311/solution_workspace/WorkbookTaglib/WorkbookTagDemoWebapp/src/main/resources/csv/google.csv"); try { Charset guessedCharset = com.glaforge.i18n.io.CharsetToolkit.guessEncoding(csvFile, 4096); CSVReader reader = new CSVReader(new BufferedReader(new InputStreamReader(new FileInputStream(csvFile), guessedCharset))); Writer writer = new FileWriter("/temp/test.html"); int nbLines = CsvConverterUtils.countLines(new BufferedReader(new FileReader(csvFile))); HtmlConverter conv = new HtmlConverter(); conv.convert(reader, writer, nbLines); } catch (Exception e) { fail(e.getMessage()); } } Code Sample 2: @Override public void parse() throws DocumentException, IOException { URL url = new URL(this.XMLAddress); URLConnection con = url.openConnection(); BufferedReader bStream = new BufferedReader(new InputStreamReader(con.getInputStream())); String str; bStream.readLine(); while ((str = bStream.readLine()) != null) { String[] tokens = str.split("(\\s+)"); String charCode = tokens[0].replaceAll("([0-9+])", ""); Float value = Float.parseFloat(tokens[2].trim().replace(",", ".")); ResultUnit unit = new ResultUnit(charCode, value, DEFAULT_MULTIPLIER); this.set.add(unit); } }
11
Code Sample 1: public static void copy(File source, File dest) throws FileNotFoundException, IOException { FileInputStream input = new FileInputStream(source); FileOutputStream output = new FileOutputStream(dest); System.out.println("Copying " + source + " to " + dest); IOUtils.copy(input, output); output.close(); input.close(); dest.setLastModified(source.lastModified()); } Code Sample 2: public static boolean buildCFItem2ItemStats(String outFileName, String movieAvgFileName, String custAvgFileName) { try { File infile = new File(completePath + fSep + "SmartGRAPE" + fSep + movieAvgFileName); FileChannel inC = new FileInputStream(infile).getChannel(); int size = (int) inC.size(); ByteBuffer map = inC.map(FileChannel.MapMode.READ_ONLY, 0, size); TShortFloatHashMap movieAverages = new TShortFloatHashMap(17770, 1); inC.close(); while (map.hasRemaining()) { movieAverages.put(map.getShort(), map.getFloat()); } map = null; infile = new File(completePath + fSep + "SmartGRAPE" + fSep + custAvgFileName); inC = new FileInputStream(infile).getChannel(); size = (int) inC.size(); map = inC.map(FileChannel.MapMode.READ_ONLY, 0, size); TIntFloatHashMap custAverages = new TIntFloatHashMap(480189, 1); inC.close(); while (map.hasRemaining()) { custAverages.put(map.getInt(), map.getFloat()); } File outfile = new File(completePath + fSep + "SmartGRAPE" + fSep + outFileName); FileChannel outC = new FileOutputStream(outfile, true).getChannel(); short[] movies = CustomersAndRatingsPerMovie.keys(); Arrays.sort(movies); int noMovies = movies.length; for (int i = 0; i < noMovies - 1; i++) { short movie1 = movies[i]; TIntByteHashMap testMovieCustAndRatingsMap = (TIntByteHashMap) CustomersAndRatingsPerMovie.get(movie1); int[] customers1 = testMovieCustAndRatingsMap.keys(); Arrays.sort(customers1); System.out.println("Processing movie: " + movie1); for (int j = i + 1; j < noMovies; j++) { short movie2 = movies[j]; TIntByteHashMap otherMovieCustAndRatingsMap = (TIntByteHashMap) CustomersAndRatingsPerMovie.get(movie2); int[] customers2 = otherMovieCustAndRatingsMap.keys(); TIntArrayList intersectSet = CustOverLapForTwoMoviesCustom(customers1, customers2); int count = 0; float diffRating = 0; float pearsonCorr = 0; float cosineCorr = 0; float adjustedCosineCorr = 0; float sumX = 0; float sumY = 0; float sumXY = 0; float sumX2 = 0; float sumY2 = 0; float sumXYPearson = 0; float sumX2Pearson = 0; float sumY2Pearson = 0; float sumXYACos = 0; float sumX2ACos = 0; float sumY2ACos = 0; if ((intersectSet.size() == 0) || (intersectSet == null)) { count = 0; diffRating = 0; } else { count = intersectSet.size(); for (int l = 0; l < count; l++) { int commonCust = intersectSet.getQuick(l); byte ratingX = testMovieCustAndRatingsMap.get(commonCust); sumX += ratingX; byte ratingY = otherMovieCustAndRatingsMap.get(commonCust); sumY += ratingY; sumX2 += ratingX * ratingX; sumY2 += ratingY * ratingY; sumXY += ratingX * ratingY; diffRating += ratingX - ratingY; sumXYPearson += (ratingX - movieAverages.get(movie1)) * (ratingY - movieAverages.get(movie2)); sumX2Pearson += Math.pow((ratingX - movieAverages.get(movie1)), 2); sumY2Pearson += Math.pow((ratingY - movieAverages.get(movie2)), 2); float custAverage = custAverages.get(commonCust); sumXYACos += (ratingX - custAverage) * (ratingY - custAverage); sumX2ACos += Math.pow((ratingX - custAverage), 2); sumY2ACos += Math.pow((ratingY - custAverage), 2); } } double pearsonDenominator = Math.sqrt(sumX2Pearson) * Math.sqrt(sumY2Pearson); if (pearsonDenominator == 0.0) { pearsonCorr = 0; } else { pearsonCorr = new Double(sumXYPearson / pearsonDenominator).floatValue(); } double adjCosineDenominator = Math.sqrt(sumX2ACos) * Math.sqrt(sumY2ACos); if (adjCosineDenominator == 0.0) { adjustedCosineCorr = 0; } else { adjustedCosineCorr = new Double(sumXYACos / adjCosineDenominator).floatValue(); } double cosineDenominator = Math.sqrt(sumX2) * Math.sqrt(sumY2); if (cosineDenominator == 0.0) { cosineCorr = 0; } else { cosineCorr = new Double(sumXY / cosineDenominator).floatValue(); } ByteBuffer buf = ByteBuffer.allocate(44); buf.putShort(movie1); buf.putShort(movie2); buf.putInt(count); buf.putFloat(diffRating); buf.putFloat(sumXY); buf.putFloat(sumX); buf.putFloat(sumY); buf.putFloat(sumX2); buf.putFloat(sumY2); buf.putFloat(pearsonCorr); buf.putFloat(adjustedCosineCorr); buf.putFloat(cosineCorr); buf.flip(); outC.write(buf); buf.clear(); } } outC.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
11
Code Sample 1: private void duplicateIndices(Connection scon, Connection dcon, String table) { try { String idx_name, idx_att, query; ResultSet idxs = scon.getMetaData().getIndexInfo(null, null, table, false, false); Statement stmt = dcon.createStatement(); while (idxs.next()) { idx_name = idxs.getString(6); idx_att = idxs.getString(9); idx_name += "_" + idx_att + "_idx"; logger.debug("Creating index " + idx_name); query = "CREATE INDEX " + idx_name + " ON " + table + "(" + idx_att + ")"; stmt.executeUpdate(query); dcon.commit(); } } catch (Exception e) { logger.error("Unable to copy indices " + e); try { dcon.rollback(); } catch (SQLException e1) { logger.fatal(e1); } } } Code Sample 2: private void gravaOp(Vector<?> op) { PreparedStatement ps = null; String sql = null; ResultSet rs = null; int seqop = 0; Date dtFabrOP = null; try { sql = "SELECT MAX(SEQOP) FROM PPOP WHERE CODEMP=? AND CODFILIAL=? AND CODOP=?"; ps = con.prepareStatement(sql); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, ListaCampos.getMasterFilial("PPOP")); ps.setInt(3, txtCodOP.getVlrInteger().intValue()); rs = ps.executeQuery(); if (rs.next()) { seqop = rs.getInt(1) + 1; } rs.close(); ps.close(); con.commit(); sql = "SELECT DTFABROP FROM PPOP WHERE CODEMP=? AND CODFILIAL=? AND CODOP=? AND SEQOP=?"; ps = con.prepareStatement(sql); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, ListaCampos.getMasterFilial("PPOP")); ps.setInt(3, txtCodOP.getVlrInteger().intValue()); ps.setInt(4, txtSeqOP.getVlrInteger().intValue()); rs = ps.executeQuery(); if (rs.next()) { dtFabrOP = rs.getDate(1); } rs.close(); ps.close(); con.commit(); sql = "INSERT INTO PPOP (CODEMP,CODFILIAL,CODOP,SEQOP,CODEMPPD,CODFILIALPD,CODPROD,SEQEST,DTFABROP," + "QTDPREVPRODOP,QTDFINALPRODOP,DTVALIDPDOP,CODEMPLE,CODFILIALLE,CODLOTE,CODEMPTM,CODFILIALTM,CODTIPOMOV," + "CODEMPAX,CODFILIALAX,CODALMOX,CODEMPOPM,CODFILIALOPM,CODOPM,SEQOPM,QTDDISTIOP,QTDSUGPRODOP)" + " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; ps = con.prepareStatement(sql); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, ListaCampos.getMasterFilial("PPOP")); ps.setInt(3, txtCodOP.getVlrInteger().intValue()); ps.setInt(4, seqop); ps.setInt(5, Aplicativo.iCodEmp); ps.setInt(6, ListaCampos.getMasterFilial("PPESTRUTURA")); ps.setInt(7, ((Integer) op.elementAt(4)).intValue()); ps.setInt(8, ((Integer) op.elementAt(6)).intValue()); ps.setDate(9, dtFabrOP); ps.setFloat(10, ((BigDecimal) op.elementAt(7)).floatValue()); ps.setFloat(11, 0); ps.setDate(12, (Funcoes.strDateToSqlDate((String) op.elementAt(11)))); ps.setInt(13, Aplicativo.iCodEmp); ps.setInt(14, ListaCampos.getMasterFilial("EQLOTE")); ps.setString(15, ((String) op.elementAt(10))); ps.setInt(16, Aplicativo.iCodEmp); ps.setInt(17, ListaCampos.getMasterFilial("EQTIPOMOV")); ps.setInt(18, buscaTipoMov()); ps.setInt(19, ((Integer) op.elementAt(13)).intValue()); ps.setInt(20, ((Integer) op.elementAt(14)).intValue()); ps.setInt(21, ((Integer) op.elementAt(12)).intValue()); ps.setInt(22, Aplicativo.iCodEmp); ps.setInt(23, ListaCampos.getMasterFilial("PPOP")); ps.setInt(24, txtCodOP.getVlrInteger().intValue()); ps.setInt(25, txtSeqOP.getVlrInteger().intValue()); ps.setFloat(26, ((BigDecimal) op.elementAt(9)).floatValue()); ps.setFloat(27, ((BigDecimal) op.elementAt(7)).floatValue()); ps.executeUpdate(); ps.close(); con.commit(); geraRMA(seqop); } catch (SQLException e) { Funcoes.mensagemErro(null, "Erro ao gerar OP's de distribui��o!\n" + e.getMessage()); try { con.rollback(); } catch (SQLException eb) { } } }
11
Code Sample 1: private void fillTemplate(String resource, OutputStream outputStream, Map<String, String> replacements) throws IOException { URL url = Tools.getResource(resource); if (url == null) { throw new IOException("could not find resource"); } BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, Charset.forName("UTF-8"))); String line = null; do { line = reader.readLine(); if (line != null) { for (String key : replacements.keySet()) { String value = replacements.get(key); if (key != null) { line = line.replace(key, value); } } writer.write(line); writer.newLine(); } } while (line != null); reader.close(); writer.close(); } Code Sample 2: public static int ToGSML(GeoSciML_Mapping mapping, String strTemplate, String strRequest, PrintWriter sortie, String requestedSRS) throws Exception { String level = "info."; if (ConnectorServlet.debug) level = "debug."; Log log = LogFactory.getLog(level + "fr.brgm.exows.gml2gsml.Gml2Gsml"); log.debug(strRequest); String tagFeature = "FIELDS"; URL url2Request = new URL(strRequest); URLConnection conn = url2Request.openConnection(); Date dDebut = new Date(); BufferedReader buffin = new BufferedReader(new InputStreamReader(conn.getInputStream())); String strLine = null; int nbFeatures = 0; Template template = VelocityCreator.createTemplate("/fr/brgm/exows/gml2gsml/templates/" + strTemplate); while ((strLine = buffin.readLine()) != null) { if (strLine.indexOf(tagFeature) != -1) { nbFeatures++; GSMLFeatureGeneric feature = createGSMLFeatureFromGMLFeatureString(mapping, strLine); VelocityContext context = new VelocityContext(); context.put("feature", feature); String outputFeatureMember = VelocityCreator.createXMLbyContext(context, template); sortie.println(outputFeatureMember); } } buffin.close(); Date dFin = new Date(); String output = "GEOSCIML : " + nbFeatures + " features handled - time : " + (dFin.getTime() - dDebut.getTime()) / 1000 + " [" + dDebut + " // " + dFin + "]"; log.trace(output); return nbFeatures; }
11
Code Sample 1: public static void main(String args[]) throws Exception { File file = new File("D:/work/love.txt"); @SuppressWarnings("unused") ZipFile zipFile = new ZipFile("D:/work/test1.zip"); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("D:/work/test1.zip")); zos.setEncoding("GBK"); ZipEntry entry = null; if (file.isDirectory()) { entry = new ZipEntry(getAbsFileName(source, file) + "/"); } else { entry = new ZipEntry(getAbsFileName(source, file)); } entry.setSize(file.length()); entry.setTime(file.lastModified()); zos.putNextEntry(entry); int readLen = 0; byte[] buf = new byte[2048]; if (file.isFile()) { InputStream in = new BufferedInputStream(new FileInputStream(file)); while ((readLen = in.read(buf, 0, 2048)) != -1) { zos.write(buf, 0, readLen); } in.close(); } zos.close(); } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: public static void entering(String[] args) throws IOException, CodeCheckException { ClassWriter writer = new ClassWriter(); writer.readClass(new BufferedInputStream(new FileInputStream(args[0]))); int constantIndex = writer.getStringConstantIndex("Entering "); int fieldRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Fieldref, "java/lang/System", "out", "Ljava/io/PrintStream;"); int printlnRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Methodref, "java/io/PrintStream", "println", "(Ljava/lang/String;)V"); int printRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Methodref, "java/io/PrintStream", "print", "(Ljava/lang/String;)V"); for (Iterator i = writer.getMethods().iterator(); i.hasNext(); ) { MethodInfo method = (MethodInfo) i.next(); if (method.getName().equals("readConstant")) continue; CodeAttribute attribute = method.getCodeAttribute(); ArrayList instructions = new ArrayList(10); byte[] operands; operands = new byte[2]; NetByte.intToPair(fieldRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("getstatic"), 0, operands, false)); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("dup"), 0, null, false)); instructions.add(Instruction.appropriateLdc(constantIndex, false)); operands = new byte[2]; NetByte.intToPair(printRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("invokevirtual"), 0, operands, false)); instructions.add(Instruction.appropriateLdc(writer.getStringConstantIndex(method.getName()), false)); operands = new byte[2]; NetByte.intToPair(printlnRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("invokevirtual"), 0, operands, false)); attribute.insertInstructions(0, 0, instructions); attribute.codeCheck(); } BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(args[1])); writer.writeClass(outStream); outStream.close(); } Code Sample 2: protected byte[] retrieveImageData() throws IOException { URL url = new URL(imageUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); int fileSize = connection.getContentLength(); Log.d(LOG_TAG, "fetching image " + imageUrl + " (" + (fileSize <= 0 ? "size unknown" : Integer.toString(fileSize)) + ")"); BufferedInputStream istream = new BufferedInputStream(connection.getInputStream()); try { if (fileSize <= 0) { Log.w(LOG_TAG, "Server did not set a Content-Length header, will default to buffer size of " + defaultBufferSize + " bytes"); ByteArrayOutputStream buf = new ByteArrayOutputStream(defaultBufferSize); byte[] buffer = new byte[defaultBufferSize]; int bytesRead = 0; while (bytesRead != -1) { bytesRead = istream.read(buffer, 0, defaultBufferSize); if (bytesRead > 0) buf.write(buffer, 0, bytesRead); } return buf.toByteArray(); } else { byte[] imageData = new byte[fileSize]; int bytesRead = 0; int offset = 0; while (bytesRead != -1 && offset < fileSize) { bytesRead = istream.read(imageData, offset, fileSize - offset); offset += bytesRead; } return imageData; } } finally { try { istream.close(); connection.disconnect(); } catch (Exception ignore) { } } }
00
Code Sample 1: public static void main(String[] args) { String fe = null, fk = null, f1 = null, f2 = null; DecimalFormat df = new DecimalFormat("000"); int key = 0; int i = 1; for (; ; ) { System.out.println("==================================================="); System.out.println("\n2009 BME\tTeam ESC's Compare\n"); System.out.println("===================================================\n"); System.out.println(" *** Menu ***\n"); System.out.println("1. Fajlok osszehasonlitasa"); System.out.println("2. Hasznalati utasitas"); System.out.println("3. Kilepes"); System.out.print("\nKivalasztott menu szama: "); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { key = reader.read(); switch(key) { case '3': System.exit(0); break; case '2': System.out.println("\n @author Bedo Zotlan - F3VFDE"); System.out.println("Team ESC's Compare"); System.out.println("2009."); System.out.println(); System.out.println("(1) A program ket fajl osszahesonlitasat vegzi. A fajloknak a program gyokerkonyvtaraban kell lenniuk!"); System.out.println("(2) A menubol ertelem szeruen valasztunk az opciok kozul, majd a program keresere megadjuk a ket osszehasonlitando " + "fajl nevet kiterjesztessel egyutt, kulonben hibat kapunk!"); System.out.println("(3) Miutan elvegeztuk az osszehasonlitasokat a program mindegyiket kimenti a compare_xxx.txt fajlba, azonban ha kilepunk a programbol, " + "majd utana ismet elinditjuk es elkezdunk osszehasonlitasokat vegezni, akkor felulirhatja " + "az elozo futtatasbol kapott fajlainkat, erre kulonosen figyelni kell!"); System.out.println("(4) A kimeneti compare_xxx.txt fajlon kivul minden egyes osszehasonlitott fajlrol csinal egy <fajl neve>.<fajl kiterjesztese>.numbered " + "nevu fajlt, ami annyiban ter el az eredeti fajloktol, hogy soronkent sorszamozva vannak!"); System.out.println("(5) Egy nem ures es egy ures fajl osszehasonlitasa utan azt az eredmenyt kapjuk, hogy \"OK, megyezenek!\". Ez termeszetesen hibas" + " es a kimeneti fajlunk is ures lesz. Ezt szinten keruljuk el, ne hasonlitsunk ures fajlokhoz mas fajlokat!"); System.out.println("(6) A fajlok megtekintesehez Notepad++ 5.0.0 verzioja ajanlott legalabb!\n"); break; case '1': { System.out.print("\nAz etalon adatokat tartalmazo fajl neve: "); try { int lnNo = 1; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String inFileName = br.readLine(); BufferedReader bin = new BufferedReader(new FileReader(inFileName)); BufferedWriter bout = new BufferedWriter(new FileWriter(inFileName + ".numbered")); fe = (inFileName + ".numbered"); f1 = inFileName; String aLine; while ((aLine = bin.readLine()) != null) bout.write("Line " + df.format(lnNo++) + ": " + aLine + "\n"); bin.close(); bout.close(); } catch (IOException e) { System.out.println("Hibas fajlnev"); } System.out.print("A kapott adatokat tartalmazo fajl neve: "); try { int lnNo = 1; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String inFileName = br.readLine(); BufferedReader bin = new BufferedReader(new FileReader(inFileName)); BufferedWriter bout = new BufferedWriter(new FileWriter(inFileName + ".numbered")); fk = (inFileName + ".numbered"); f2 = inFileName; String aLine_k; while ((aLine_k = bin.readLine()) != null) bout.write("Line " + df.format(lnNo++) + ": " + aLine_k + "\n"); bin.close(); bout.close(); } catch (IOException e) { System.out.println("Hibas fajlnev"); } try { int lnNo_c = 1; int mstk = 0; BufferedReader bin_e = new BufferedReader(new FileReader(fe)); BufferedReader bin_k = new BufferedReader(new FileReader(fk)); BufferedWriter bout = new BufferedWriter(new FileWriter("compare_" + i++ + ".txt")); Calendar actDate = Calendar.getInstance(); bout.write("==================================================\n"); bout.write("\n2009 BME\tTeam ESC's Compare"); bout.write("\n" + actDate.get(Calendar.YEAR) + "." + (actDate.get(Calendar.MONTH) + 1) + "." + actDate.get(Calendar.DATE) + ".\n" + actDate.get(Calendar.HOUR) + ":" + actDate.get(Calendar.MINUTE) + "\n\n"); bout.write("==================================================\n"); bout.write("Az etalon ertekekkel teli fajl neve: " + f1 + "\n"); bout.write("A kapott ertekekkel teli fajl neve: " + f2 + "\n\n"); System.out.println("==================================================\n"); System.out.println("\n2009 BME\tTeam ESC's Compare"); System.out.println(actDate.get(Calendar.YEAR) + "." + (actDate.get(Calendar.MONTH) + 1) + "." + actDate.get(Calendar.DATE) + ".\n" + actDate.get(Calendar.HOUR) + ":" + actDate.get(Calendar.MINUTE) + "\n"); System.out.println("==================================================\n"); System.out.println("\nAz etalon ertekekkel teli fajl neve: " + f1); System.out.println("A kapott ertekekkel teli fajl neve: " + f2 + "\n"); String aLine_c1 = null, aLine_c2 = null; File fa = new File(fe); File fb = new File(fk); if (fa.length() != fb.length()) { bout.write("\nOsszehasonlitas eredmenye: HIBA, nincs egyezes!\n Kulonbozo meretu fajlok: " + fa.length() + " byte illetve " + fb.length() + " byte!\n"); System.out.println("\nOsszehasonlitas eredmenye: HIBA, nincs egyezes!\n Kulonbozo meretu fajlok: " + fa.length() + " byte illetve " + fb.length() + " byte!\n"); } else { while (((aLine_c1 = bin_e.readLine()) != null) && ((aLine_c2 = bin_k.readLine()) != null)) if (aLine_c1.equals(aLine_c2)) { } else { mstk++; bout.write("#" + df.format(lnNo_c) + ": HIBA --> \t" + f1 + " : " + aLine_c1 + " \n\t\t\t\t\t" + f2 + " : " + aLine_c2 + "\n"); System.out.println("#" + df.format(lnNo_c) + ": HIBA -->\t " + f1 + " : " + aLine_c1 + " \n\t\t\t" + f2 + " : " + aLine_c2 + "\n"); lnNo_c++; } if (mstk != 0) { bout.write("\nOsszehasonlitas eredmenye: HIBA, nincs egyezes!"); bout.write("\nHibas sorok szama: " + mstk); System.out.println("\nOsszehasonlitas eredmenye: HIBA, nincs egyezes!"); System.out.println("Hibas sorok szama: " + mstk); } else { bout.write("\nOsszehasonlitas eredmenye: OK, megegyeznek!"); System.out.println("\nOsszehasonlitas eredm�nye: OK, megegyeznek!\n"); } } bin_e.close(); bin_k.close(); fa.delete(); fb.delete(); bout.close(); } catch (IOException e) { System.out.println("Hibas fajl"); } break; } } } catch (Exception e) { System.out.println("A fut�s sor�n hiba t�rt�nt!"); } } } Code Sample 2: public static String encryptPassword(String username, String realm, String password) throws GeneralSecurityException { MessageDigest md = null; md = MessageDigest.getInstance("MD5"); md.update(username.getBytes()); md.update(":".getBytes()); md.update(realm.getBytes()); md.update(":".getBytes()); md.update(password.getBytes()); byte[] hash = md.digest(); return toHex(hash, hash.length); }
11
Code Sample 1: private void refreshCacheFile(RepositoryFile file, File cacheFile) throws FileNotFoundException, IOException { FileOutputStream fos = new FileOutputStream(cacheFile); InputStream is = file.getInputStream(); int count = IOUtils.copy(is, fos); logger.debug("===========================================================> wrote bytes to cache " + count); fos.flush(); IOUtils.closeQuietly(fos); IOUtils.closeQuietly(file.getInputStream()); } Code Sample 2: private void fileCopy(File filename) throws IOException { if (this.stdOut) { this.fileDump(filename); return; } File source_file = new File(spoolPath + "/" + filename); File destination_file = new File(copyPath + "/" + filename); FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException("no such source file: " + source_file); if (!source_file.canRead()) throw new FileCopyException("source file is unreadable: " + source_file); if (destination_file.exists()) { if (destination_file.isFile()) { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); if (!destination_file.canWrite()) throw new FileCopyException("destination file is unwriteable: " + destination_file); if (!this.overwrite) { System.out.print("File " + destination_file + " already exists. Overwrite? (Y/N): "); System.out.flush(); if (!in.readLine().toUpperCase().equals("Y")) throw new FileCopyException("copy cancelled."); } } else throw new FileCopyException("destination is not a file: " + destination_file); } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException("destination directory doesn't exist: " + destination_file); if (!parentdir.canWrite()) throw new FileCopyException("destination directory is unwriteable: " + destination_file); } source = new FileInputStream(source_file); destination = new FileOutputStream(destination_file); buffer = new byte[1024]; while ((bytes_read = source.read(buffer)) != -1) { destination.write(buffer, 0, bytes_read); } System.out.println("File " + filename + " successfull copied to " + destination_file); if (this.keep == false && source_file.isFile()) { try { source.close(); } catch (Exception e) { } if (source_file.delete()) { new File(this.spoolPath + "/info/" + filename + ".desc").delete(); } } } finally { if (source != null) try { source.close(); } catch (IOException e) { } if (destination != null) try { destination.flush(); } catch (IOException e) { } if (destination != null) try { destination.close(); } catch (IOException e) { } } }
00
Code Sample 1: public void zipUp() throws PersistenceException { ZipOutputStream out = null; try { if (!backup.exists()) backup.createNewFile(); out = new ZipOutputStream(new FileOutputStream(backup)); out.setLevel(Deflater.DEFAULT_COMPRESSION); for (String file : backupDirectory.list()) { logger.debug("Deflating: " + file); FileInputStream in = null; try { in = new FileInputStream(new File(backupDirectory, file)); out.putNextEntry(new ZipEntry(file)); IOUtils.copy(in, out); } finally { out.closeEntry(); if (null != in) in.close(); } } FileUtils.deleteDirectory(backupDirectory); } catch (Exception ex) { logger.error("Unable to ZIP the backup {" + backupDirectory.getAbsolutePath() + "}.", ex); throw new PersistenceException(ex); } finally { try { if (null != out) out.close(); } catch (IOException e) { logger.error("Unable to close ZIP output stream.", e); } } } Code Sample 2: @Override public List<String> transform(String urlString) { String result = ""; InputStream inputStream = null; try { URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("User-agent", "finance news monitor"); connection.setRequestProperty("From", "romilly.cocking@gmail.com"); connection.setInstanceFollowRedirects(true); inputStream = connection.getInputStream(); result = StringUtils.join(IOUtils.readLines(inputStream).toArray(), lineSeparator); } catch (MalformedURLException e) { log.warn("Malformed url " + urlString); } catch (IOException e) { log.warn("error reading from url " + urlString, e); } if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { log.warn("could not close url " + urlString, e); } } return enlist(result); }
00
Code Sample 1: public void run() { int requestCount = 0; long i0 = System.currentTimeMillis(); while (requestCount != maxRequests) { long r0 = System.currentTimeMillis(); try { url = new URL(requestedUrl); logger.debug("Requesting Url, " + url.toString()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); while ((httpResponse = in.readLine()) != null) { logger.trace("Http Response = " + httpResponse); } } catch (Exception e) { logger.fatal("Exception thrown retrievng Url = " + requestedUrl + ", " + e); notification.setNotification(e.toString()); } long r1 = System.currentTimeMillis(); requestedElapsedTime = r1 - r0; logger.debug("Request(" + this.getName() + "/" + this.getId() + ") #" + requestCount + " processed, took " + requestedElapsedTime + "ms"); requestCount++; } long i1 = System.currentTimeMillis(); iterationElapsedTime = i1 - i0; logger.trace("Iteration elapsed time is " + iterationElapsedTime + "ms for thread ID " + this.getId()); status.incrementIterationsComplete(); logger.info("Iteration for Url = " + requestedUrl + ", (" + this.getName() + "/" + this.getId() + ") took " + iterationElapsedTime + "ms"); try { logger.debug("Joining thread(" + this.getId() + ")"); this.join(100); } catch (Exception e) { logger.fatal(e); notification.setNotification(e.toString()); } } Code Sample 2: private void writeToFile(Body b, File mime4jFile) throws FileNotFoundException, IOException { if (b instanceof TextBody) { String charset = CharsetUtil.toJavaCharset(b.getParent().getCharset()); if (charset == null) { charset = "ISO8859-1"; } OutputStream out = new FileOutputStream(mime4jFile); IOUtils.copy(((TextBody) b).getReader(), out, charset); } else { OutputStream out = new FileOutputStream(mime4jFile); IOUtils.copy(((BinaryBody) b).getInputStream(), out); } }
11
Code Sample 1: public static void copyTo(File inFile, File outFile) throws IOException { char[] cbuff = new char[32768]; BufferedReader reader = new BufferedReader(new FileReader(inFile)); BufferedWriter writer = new BufferedWriter(new FileWriter(outFile)); int readedBytes = 0; long absWrittenBytes = 0; while ((readedBytes = reader.read(cbuff, 0, cbuff.length)) != -1) { writer.write(cbuff, 0, readedBytes); absWrittenBytes += readedBytes; } reader.close(); writer.close(); } Code Sample 2: public void onUpload$btnFileUpload(UploadEvent ue) { BufferedInputStream in = null; BufferedOutputStream out = null; if (ue == null) { System.out.println("unable to upload file"); return; } else { System.out.println("fileUploaded()"); } try { Media m = ue.getMedia(); System.out.println("m.getContentType(): " + m.getContentType()); System.out.println("m.getFormat(): " + m.getFormat()); try { InputStream is = m.getStreamData(); in = new BufferedInputStream(is); File baseDir = new File(UPLOAD_PATH); if (!baseDir.exists()) { baseDir.mkdirs(); } final File file = new File(UPLOAD_PATH + m.getName()); OutputStream fout = new FileOutputStream(file); out = new BufferedOutputStream(fout); IOUtils.copy(in, out); if (m.getFormat().equals("zip") || m.getFormat().equals("x-gzip")) { final String filename = m.getName(); Messagebox.show("Archive file detected. Would you like to unzip this file?", "ALA Spatial Portal", Messagebox.YES + Messagebox.NO, Messagebox.QUESTION, new EventListener() { @Override public void onEvent(Event event) throws Exception { try { int response = ((Integer) event.getData()).intValue(); if (response == Messagebox.YES) { System.out.println("unzipping file to: " + UPLOAD_PATH); boolean success = Zipper.unzipFile(filename, new FileInputStream(file), UPLOAD_PATH, false); if (success) { Messagebox.show("File unzipped: '" + filename + "'"); } else { Messagebox.show("Unable to unzip '" + filename + "' "); } } else { System.out.println("leaving archive file alone"); } } catch (NumberFormatException nfe) { System.out.println("Not a valid response"); } } }); } else { Messagebox.show("File '" + m.getName() + "' successfully uploaded"); } } catch (IOException e) { System.out.println("IO Exception while saving file: "); e.printStackTrace(System.out); } catch (Exception e) { System.out.println("General Exception: "); e.printStackTrace(System.out); } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException e) { System.out.println("IO Exception while closing stream: "); e.printStackTrace(System.out); } } } catch (Exception e) { System.out.println("Error uploading file."); e.printStackTrace(System.out); } }
11
Code Sample 1: public void handle() { FileChannel srcChannel, destChannel; String destOutFile = databaseName + ".script." + System.currentTimeMillis(); String destOutFileCompressed = databaseName + ".script." + System.currentTimeMillis() + ".gz"; if (rotateDest != null) { (new File(rotateDest)).mkdirs(); if (destOutFile.indexOf("/") != -1) { destOutFile = rotateDest + "/" + destOutFile.substring(destOutFile.lastIndexOf("/") + 1); } if (destOutFileCompressed.indexOf("/") != -1) { destOutFileCompressed = rotateDest + "/" + destOutFileCompressed.substring(destOutFileCompressed.lastIndexOf("/") + 1); } } if (rotateCompress) { try { GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(destOutFileCompressed)); FileInputStream in = new FileInputStream(databaseName + ".script"); byte buf[] = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.finish(); out.close(); buf = null; in = null; out = null; Debug.debug("Rotated database file '" + databaseName + ".script' to '" + destOutFileCompressed + "'"); } catch (Exception e) { Debug.debug("Unable to rotate database file '" + databaseName + ".script': " + e); } } else { try { srcChannel = new FileInputStream(databaseName + ".script").getChannel(); } catch (IOException e) { Debug.debug("Unable to read file '" + databaseName + ".script' for database rotation."); return; } try { destChannel = new FileOutputStream(destOutFile).getChannel(); } catch (IOException e) { Debug.debug("Unable to rotate file to '" + destOutFile + "': " + e.getMessage()); return; } try { destChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); destChannel.close(); srcChannel = null; destChannel = null; } catch (IOException e) { Debug.debug("Unable to copy data for file rotation: " + e.getMessage()); return; } Debug.debug("Rotated database file '" + databaseName + ".script' to '" + destOutFile + "'"); } if (rotateDest != null) { long comparisonTime = rotateDays * (60 * 60 * 24 * 1000); long currentTime = System.currentTimeMillis(); File fileList[] = (new File(rotateDest)).listFiles(); DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); java.util.Date date = new java.util.Date(currentTime); String archiveFile = format1.format(date).toString() + ".zip"; if (rotateArchive != null) { archiveFile = rotateArchive + "/" + archiveFile; (new File(rotateArchive)).mkdirs(); } Archive archive = new Archive(archiveFile); for (int i = 0; i < fileList.length; i++) { String currentFilename = fileList[i].getName(); long timeDifference = (currentTime - fileList[i].lastModified()); if ((rotateCompress && currentFilename.endsWith(".gz")) || (!rotateCompress && currentFilename.indexOf(".script.") != -1)) { if (rotateDest != null) { currentFilename = rotateDest + "/" + currentFilename; } if (timeDifference > comparisonTime) { archive.addFile(fileList[i].getName(), currentFilename); fileList[i].delete(); } } } archive = null; fileList = null; format1 = null; date = null; } } 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: private static void reconfigureDebug() { useFile = false; logValue = 0; String methodString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.method']/@value"); String levelString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.level']/@value"); String quietString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.quiet']/@value"); String fileString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.file']/@value"); String filemodeString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.filemode']/@value"); String calltraceString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.calltrace']/@value"); String rotateTimeoutString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatetimeout']/@value"); String rotateDestString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatedest']/@value"); String rotateCompressString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatecompress']/@value"); String rotateDaysString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatedays']/@value"); String rotateArchiveString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatearchive']/@value"); String rotateDeleteString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatedelete']/@value"); String dirName = "."; if (rotateTimeoutString != null) { rotateTimeout = Integer.parseInt(rotateTimeoutString); } if (rotateDestString != null) { rotateDest = rotateDestString; } if (rotateCompressString != null && rotateCompressString.equalsIgnoreCase("true")) { rotateCompress = true; } if (rotateDaysString != null) { rotateDays = Integer.parseInt(rotateDaysString); } if (rotateArchiveString != null) { rotateArchive = rotateArchiveString; } if (rotateDeleteString != null && rotateDeleteString.equalsIgnoreCase("true")) { rotateDelete = true; } if (fileString != null && fileString.indexOf("/") != -1) { dirName = fileString.substring(0, fileString.lastIndexOf("/")); (new File(dirName)).mkdirs(); } if (methodString != null) { logMethod = methodString; } else { logMethod = "file"; } if (levelString != null) { logValue = Integer.parseInt(levelString); } else { logValue = 0; } if (calltraceString != null && calltraceString.equalsIgnoreCase("true")) { calltrace = true; } else { calltrace = false; } if (logMethod == null) { logMethod = "file"; } if (quietString != null) { if (quietString.equalsIgnoreCase("true")) { beQuiet = true; } } if (logMethod != null) { if (logMethod.equalsIgnoreCase("file")) { if (fileString != null) { logFile = fileString; } else { logFile = "log.txt"; } useFile = true; } } else { System.err.println("*** A debugging method (debug.method) is required in properties file!"); System.err.println("*** Please refer to configuration documentation."); System.exit(-1); } timesRepeated = 0; lastMessage = null; if (useFile) { logfile = new File(logFile); try { if (filemodeString != null && filemodeString.equalsIgnoreCase("append")) { ps = new PrintStream(new FileOutputStream(logfile, true)); } else { ps = new PrintStream(new FileOutputStream(logfile)); } isFile = true; Calendar calendar = new GregorianCalendar(); Date date = calendar.getTime(); DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z"); ps.println(); ps.println("--- Log file opened " + format1.format(date) + " ---"); } catch (FileNotFoundException e) { System.out.println("Debug: Unable to instantiate debugger: " + e.getMessage()); System.exit(-1); } catch (Exception e) { System.out.println("Debug: Unable to instantiate debugger - internal error: " + e.getMessage()); System.exit(-1); } } if (!registeredSchedule) { registeredSchedule = true; if (Server.getScheduler() != null) { Server.getScheduler().register("Log File Rotator for '" + logFile + "'", new SchedulerInterface() { public int getScheduleRate() { if (rotateTimeout != 0) { return rotateTimeout / 10; } return 0; } public void handle() { FileChannel srcChannel, destChannel; String destOutFile = logFile + "." + System.currentTimeMillis(); String destOutFileCompressed = logFile + "." + System.currentTimeMillis() + ".gz"; if (rotateDest != null) { (new File(rotateDest)).mkdirs(); if (destOutFile.indexOf("/") != -1) { destOutFile = rotateDest + "/" + destOutFile.substring(destOutFile.lastIndexOf("/") + 1); } if (destOutFileCompressed.indexOf("/") != -1) { destOutFileCompressed = rotateDest + "/" + destOutFileCompressed.substring(destOutFileCompressed.lastIndexOf("/") + 1); } } if (rotateCompress) { try { GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(destOutFileCompressed)); FileInputStream in = new FileInputStream(logFile); byte buf[] = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.finish(); out.close(); buf = null; in = null; out = null; Debug.debug("Rotated log file '" + logFile + "' to '" + destOutFileCompressed + "'"); } catch (Exception e) { Debug.debug("Unable to rotate log file '" + logFile + "': " + e); } } else { try { srcChannel = new FileInputStream(logFile).getChannel(); } catch (IOException e) { Debug.debug("Unable to read log file '" + logFile + "': " + e.getMessage()); return; } try { destChannel = new FileOutputStream(destOutFile).getChannel(); } catch (IOException e) { Debug.debug("Unable to rotate log file to '" + destOutFile + "': " + e.getMessage()); return; } try { destChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); destChannel.close(); srcChannel = null; destChannel = null; } catch (IOException e) { Debug.debug("Unable to copy data for file rotation: " + e.getMessage()); return; } Debug.debug("Rotated log file '" + logFile + "' to '" + destOutFile + "'"); } if (rotateDelete && isFile) { try { ps.close(); } catch (Exception e) { } isFile = false; ps = null; (new File(logFile)).delete(); reconfigureDebug(); } if (rotateDest != null) { long comparisonTime = rotateDays * (60 * 60 * 24 * 1000); long currentTime = System.currentTimeMillis(); File fileList[] = (new File(rotateDest)).listFiles(); DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); java.util.Date date = new java.util.Date(currentTime); String archiveFile = format1.format(date).toString() + ".zip"; if (rotateArchive != null) { archiveFile = rotateArchive + "/" + archiveFile; (new File(rotateArchive)).mkdirs(); } Archive archive = new Archive(archiveFile); for (int i = 0; i < fileList.length; i++) { String currentFilename = fileList[i].getName(); long timeDifference = (currentTime - fileList[i].lastModified()); if ((rotateCompress && currentFilename.endsWith(".gz")) || (!rotateCompress && currentFilename.indexOf(logFile + ".") != -1)) { if (rotateDest != null) { currentFilename = rotateDest + "/" + currentFilename; } if (timeDifference > comparisonTime) { archive.addFile(fileList[i].getName(), currentFilename); fileList[i].delete(); } } } archive = null; fileList = null; format1 = null; date = null; } } public String identString() { return "Debug Rotator for logs"; } }); } } } Code Sample 2: public static void copy(File fromFile, File toFile) throws IOException { if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFile.getCanonicalPath()); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFile.getCanonicalPath()); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFile.getCanonicalPath()); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFile.getCanonicalPath()); throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[1024 * 1024]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); if (fromFile.isHidden()) { } toFile.setLastModified(fromFile.lastModified()); toFile.setExecutable(fromFile.canExecute()); toFile.setReadable(fromFile.canRead()); toFile.setWritable(toFile.canWrite()); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
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: @Override public String fetchElectronicEdition(Publication pub) { final String url = baseURL + pub.getKey() + ".html"; logger.info("fetching pub ee from local cache at: " + url); HttpMethod method = null; String responseBody = ""; method = new GetMethod(url); method.setFollowRedirects(true); try { if (StringUtils.isNotBlank(method.getURI().getScheme())) { InputStream is = null; StringWriter writer = new StringWriter(); try { client.executeMethod(method); Header contentType = method.getResponseHeader("Content-Type"); if (contentType != null && StringUtils.isNotBlank(contentType.getValue()) && contentType.getValue().indexOf("text/html") >= 0) { is = method.getResponseBodyAsStream(); IOUtils.copy(is, writer); responseBody = writer.toString(); } else { logger.info("ignoring non-text/html response from page: " + url + " content-type:" + contentType); } } catch (HttpException he) { logger.error("Http error connecting to '" + url + "'"); logger.error(he.getMessage()); } catch (IOException ioe) { logger.error("Unable to connect to '" + url + "'"); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(writer); } } } catch (URIException e) { logger.error(e); } finally { method.releaseConnection(); } return responseBody; }
11
Code Sample 1: public Object next() { if (!hasNext()) { throw new NoSuchElementException(); } this.currentGafFilePath = this.url; try { if (this.httpURL != null) { LOG.info("Reading URL :" + httpURL); InputStream is = this.httpURL.openStream(); int index = this.httpURL.toString().lastIndexOf('/'); String file = this.httpURL.toString().substring(index + 1); File downloadLocation = new File(GoConfigManager.getInstance().getGafUploadDir(), "tmp-" + file); OutputStream out = new FileOutputStream(downloadLocation); IOUtils.copy(is, out); out.close(); is = new FileInputStream(downloadLocation); if (url.endsWith(".gz")) { is = new GZIPInputStream(is); } this.currentGafFile = this.currentGafFilePath.substring(this.currentGafFilePath.lastIndexOf("/") + 1); this.httpURL = null; return is; } else { String file = files[counter++].getName(); this.currentGafFile = file; if (!this.currentGafFilePath.endsWith(file)) currentGafFilePath += file; LOG.info("Returning input stream for the file: " + file); _connect(); ftpClient.changeWorkingDirectory(path); InputStream is = ftpClient.retrieveFileStream(file); File downloadLocation = new File(GoConfigManager.getInstance().getGafUploadDir(), file); OutputStream out = new FileOutputStream(downloadLocation); IOUtils.copy(is, out); out.close(); System.out.println("Download complete....."); is = new FileInputStream(downloadLocation); if (file.endsWith(".gz")) { is = new GZIPInputStream(is); } return is; } } catch (IOException ex) { throw new RuntimeException(ex); } } Code Sample 2: public void runDynusT() { final String[] exeFiles = new String[] { "DynusT.exe", "DLL_ramp.dll", "Ramp_Meter_Fixed_CDLL.dll", "Ramp_Meter_Feedback_CDLL.dll", "Ramp_Meter_Feedback_FDLL.dll", "libifcoremd.dll", "libmmd.dll", "Ramp_Meter_Fixed_FDLL.dll", "libiomp5md.dll" }; final String[] modelFiles = new String[] { "network.dat", "scenario.dat", "control.dat", "ramp.dat", "incident.dat", "movement.dat", "vms.dat", "origin.dat", "destination.dat", "StopCap4Way.dat", "StopCap2Way.dat", "YieldCap.dat", "WorkZone.dat", "GradeLengthPCE.dat", "leftcap.dat", "system.dat", "output_option.dat", "bg_demand_adjust.dat", "xy.dat", "TrafficFlowModel.dat", "parameter.dat" }; log.info("Creating iteration-directory..."); File iterDir = new File(this.tmpDir); if (!iterDir.exists()) { iterDir.mkdir(); } log.info("Copying application files to iteration-directory..."); for (String filename : exeFiles) { log.info(" Copying " + filename); IOUtils.copyFile(new File(this.dynusTDir + "/" + filename), new File(this.tmpDir + "/" + filename)); } log.info("Copying model files to iteration-directory..."); for (String filename : modelFiles) { log.info(" Copying " + filename); IOUtils.copyFile(new File(this.modelDir + "/" + filename), new File(this.tmpDir + "/" + filename)); } String logfileName = this.tmpDir + "/dynus-t.log"; String cmd = this.tmpDir + "/DynusT.exe"; log.info("running command: " + cmd); int timeout = 14400; int exitcode = ExeRunner.run(cmd, logfileName, timeout); if (exitcode != 0) { throw new RuntimeException("There was a problem running Dynus-T. exit code: " + exitcode); } }
00
Code Sample 1: protected Source getStylesheetSource(Resource stylesheetLocation) throws ApplicationContextException { if (logger.isDebugEnabled()) { logger.debug("Loading XSLT stylesheet from " + stylesheetLocation); } try { URL url = stylesheetLocation.getURL(); String urlPath = url.toString(); String systemId = urlPath.substring(0, urlPath.lastIndexOf('/') + 1); return new StreamSource(url.openStream(), systemId); } catch (IOException ex) { throw new ApplicationContextException("Can't load XSLT stylesheet from " + stylesheetLocation, ex); } } Code Sample 2: @Override protected RemoteInvocationResult doExecuteRequest(HttpInvokerClientConfiguration config, ByteArrayOutputStream baos) throws IOException, ClassNotFoundException { HttpPost postMethod = new HttpPost(config.getServiceUrl()); postMethod.setEntity(new ByteArrayEntity(baos.toByteArray())); HttpResponse rsp = httpClient.execute(postMethod); StatusLine sl = rsp.getStatusLine(); if (sl.getStatusCode() >= 300) { throw new IOException("Did not receive successful HTTP response: status code = " + sl.getStatusCode() + ", status message = [" + sl.getReasonPhrase() + "]"); } HttpEntity entity = rsp.getEntity(); InputStream responseBody = entity.getContent(); return readRemoteInvocationResult(responseBody, config.getCodebaseUrl()); }
00
Code Sample 1: @Override public CasAssembly build() { try { prepareForBuild(); File casWorkingDirectory = casFile.getParentFile(); DefaultCasFileReadIndexToContigLookup read2contigMap = new DefaultCasFileReadIndexToContigLookup(); AbstractDefaultCasFileLookup readIdLookup = new DefaultReadCasFileLookup(casWorkingDirectory); CasParser.parseOnlyMetaData(casFile, MultipleWrapper.createMultipleWrapper(CasFileVisitor.class, read2contigMap, readIdLookup)); ReadWriteDirectoryFileServer consedOut = DirectoryFileServer.createReadWriteDirectoryFileServer(commandLine.getOptionValue("o")); long startTime = DateTimeUtils.currentTimeMillis(); int numberOfCasContigs = read2contigMap.getNumberOfContigs(); for (long i = 0; i < numberOfCasContigs; i++) { File outputDir = consedOut.createNewDir("" + i); Command aCommand = new Command(new File("fakeCommand")); aCommand.setOption("-casId", "" + i); aCommand.setOption("-cas", commandLine.getOptionValue("cas")); aCommand.setOption("-o", outputDir.getAbsolutePath()); aCommand.setOption("-tempDir", tempDir.getAbsolutePath()); aCommand.setOption("-prefix", "temp"); if (commandLine.hasOption("useIllumina")) { aCommand.addFlag("-useIllumina"); } if (commandLine.hasOption("useClosureTrimming")) { aCommand.addFlag("-useClosureTrimming"); } if (commandLine.hasOption("trim")) { aCommand.setOption("-trim", commandLine.getOptionValue("trim")); } if (commandLine.hasOption("trimMap")) { aCommand.setOption("-trimMap", commandLine.getOptionValue("trimMap")); } if (commandLine.hasOption("chromat_dir")) { aCommand.setOption("-chromat_dir", commandLine.getOptionValue("chromat_dir")); } submitSingleCasAssemblyConversion(aCommand); } waitForAllAssembliesToFinish(); int numContigs = 0; int numReads = 0; for (int i = 0; i < numberOfCasContigs; i++) { File countMap = consedOut.getFile(i + "/temp.counts"); Scanner scanner = new Scanner(countMap); if (!scanner.hasNextInt()) { throw new IllegalStateException("single assembly conversion # " + i + " did not complete"); } numContigs += scanner.nextInt(); numReads += scanner.nextInt(); scanner.close(); } System.out.println("num contigs =" + numContigs); System.out.println("num reads =" + numReads); consedOut.createNewDir("edit_dir"); consedOut.createNewDir("phd_dir"); String prefix = commandLine.hasOption("prefix") ? commandLine.getOptionValue("prefix") : DEFAULT_PREFIX; OutputStream masterAceOut = new FileOutputStream(consedOut.createNewFile("edit_dir/" + prefix + ".ace.1")); OutputStream masterPhdOut = new FileOutputStream(consedOut.createNewFile("phd_dir/" + prefix + ".phd.ball")); OutputStream masterConsensusOut = new FileOutputStream(consedOut.createNewFile(prefix + ".consensus.fasta")); OutputStream logOut = new FileOutputStream(consedOut.createNewFile(prefix + ".log")); try { masterAceOut.write(String.format("AS %d %d%n", numContigs, numReads).getBytes()); for (int i = 0; i < numberOfCasContigs; i++) { InputStream aceIn = consedOut.getFileAsStream(i + "/temp.ace"); IOUtils.copy(aceIn, masterAceOut); InputStream phdIn = consedOut.getFileAsStream(i + "/temp.phd"); IOUtils.copy(phdIn, masterPhdOut); InputStream consensusIn = consedOut.getFileAsStream(i + "/temp.consensus.fasta"); IOUtils.copy(consensusIn, masterConsensusOut); IOUtil.closeAndIgnoreErrors(aceIn, phdIn, consensusIn); File tempDir = consedOut.getFile(i + ""); IOUtil.recursiveDelete(tempDir); } consedOut.createNewSymLink("../phd_dir/" + prefix + ".phd.ball", "edit_dir/phd.ball"); if (commandLine.hasOption("chromat_dir")) { consedOut.createNewDir("chromat_dir"); File originalChromatDir = new File(commandLine.getOptionValue("chromat_dir")); for (File chromat : originalChromatDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".scf"); } })) { File newChromatFile = consedOut.createNewFile("chromat_dir/" + FilenameUtils.getBaseName(chromat.getName())); FileOutputStream newChromat = new FileOutputStream(newChromatFile); InputStream in = new FileInputStream(chromat); IOUtils.copy(in, newChromat); IOUtil.closeAndIgnoreErrors(in, newChromat); } } System.out.println("finished making casAssemblies"); for (File traceFile : readIdLookup.getFiles()) { final String name = traceFile.getName(); String extension = FilenameUtils.getExtension(name); if (name.contains("fastq")) { if (!consedOut.contains("solexa_dir")) { consedOut.createNewDir("solexa_dir"); } if (consedOut.contains("solexa_dir/" + name)) { IOUtil.delete(consedOut.getFile("solexa_dir/" + name)); } consedOut.createNewSymLink(traceFile.getAbsolutePath(), "solexa_dir/" + name); } else if ("sff".equals(extension)) { if (!consedOut.contains("sff_dir")) { consedOut.createNewDir("sff_dir"); } if (consedOut.contains("sff_dir/" + name)) { IOUtil.delete(consedOut.getFile("sff_dir/" + name)); } consedOut.createNewSymLink(traceFile.getAbsolutePath(), "sff_dir/" + name); } } long endTime = DateTimeUtils.currentTimeMillis(); logOut.write(String.format("took %s%n", new Period(endTime - startTime)).getBytes()); } finally { IOUtil.closeAndIgnoreErrors(masterAceOut, masterPhdOut, masterConsensusOut, logOut); } } catch (Exception e) { handleException(e); } finally { cleanup(); } return null; } Code Sample 2: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
11
Code Sample 1: public SequenceIterator call(SequenceIterator[] arguments, XPathContext context) throws XPathException { try { String encodedString = ((StringValue) arguments[0].next()).getStringValue(); byte[] decodedBytes = Base64.decode(encodedString); if (arguments.length > 1 && ((BooleanValue) arguments[1].next()).getBooleanValue()) { ByteArrayInputStream bis = new ByteArrayInputStream(decodedBytes); GZIPInputStream zis = new GZIPInputStream(bis); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(zis, baos); decodedBytes = baos.toByteArray(); } Document doc = XmlUtils.stringToDocument(new String(decodedBytes, "UTF-8")); Source source = new DOMSource(doc.getDocumentElement()); XPathEvaluator evaluator = new XPathEvaluator(context.getConfiguration()); NodeInfo[] infos = new NodeInfo[] { evaluator.setSource(source) }; return new ArrayIterator(infos); } catch (Exception e) { throw new XPathException("Could not base64 decode string", e); } } Code Sample 2: @Override public void run() { log.debug("Now running...."); log.debug("Current env. variables:"); try { this.infoNotifiers("Environment parameters after modifications:"); this.logEnvironment(); this.infoNotifiers("Dump thread will now run..."); this.endNotifiers(); this.process = this.pb.start(); this.process.waitFor(); if (this.process.exitValue() != 0) { this.startNotifiers(); this.infoNotifiers("Dump Failed. Return status: " + this.process.exitValue()); this.endNotifiers(); return; } List<String> cmd = new LinkedList<String>(); cmd.add("gzip"); cmd.add(info.getDumpFileName()); File basePath = this.pb.directory(); this.pb = new ProcessBuilder(cmd); this.pb.directory(basePath); log.debug("Executing: " + StringUtils.join(cmd.iterator(), ' ')); this.process = this.pb.start(); this.process.waitFor(); if (this.process.exitValue() != 0) { this.startNotifiers(); this.infoNotifiers("Dump GZip Failed. Return status: " + this.process.exitValue()); this.endNotifiers(); return; } info.setDumpFileName(info.getDumpFileName() + ".gz"); info.setMD5SumFileName(info.getDumpFileName() + ".md5sum"); cmd = new LinkedList<String>(); cmd.add("md5sum"); cmd.add("-b"); cmd.add(info.getDumpFileName()); log.debug("Executing: " + StringUtils.join(cmd.iterator(), ' ')); this.pb = new ProcessBuilder(cmd); this.pb.directory(basePath); this.process = this.pb.start(); BufferedOutputStream md5sumFileOut = new BufferedOutputStream(new FileOutputStream(basePath.getAbsolutePath() + File.separatorChar + info.getMD5SumFileName())); IOUtils.copy(this.process.getInputStream(), md5sumFileOut); this.process.waitFor(); md5sumFileOut.flush(); md5sumFileOut.close(); if (this.process.exitValue() != 0) { this.startNotifiers(); this.infoNotifiers("Dump GZip MD5Sum Failed. Return status: " + this.process.exitValue()); this.endNotifiers(); return; } else { this.startNotifiers(); this.infoNotifiers("Dump, gzip and md5sum sucessfuly completed."); this.endNotifiers(); } } catch (IOException e) { String message = "IOException launching command: " + e.getMessage(); log.error(message, e); throw new IllegalStateException(message, e); } catch (InterruptedException e) { String message = "InterruptedException launching command: " + e.getMessage(); log.error(message, e); throw new IllegalStateException(message, e); } catch (IntegrationException e) { String message = "IntegrationException launching command: " + e.getMessage(); log.error(message, e); throw new IllegalStateException(message, e); } }
11
Code Sample 1: private void getImage(String filename) throws MalformedURLException, IOException, SAXException, FileNotFoundException { String url = Constants.STRATEGICDOMINATION_URL + "/images/gameimages/" + filename; WebRequest req = new GetMethodWebRequest(url); SiteResponse response = getSiteResponse(req); File file = new File("etc/images/" + filename); FileOutputStream outputStream = new FileOutputStream(file); IOUtils.copy(response.getInputStream(), outputStream); } Code Sample 2: public void copyFile2(String src, String dest) throws IOException { FileWriter fw = null; FileReader fr = null; BufferedReader br = null; BufferedWriter bw = null; File source = null; try { fr = new FileReader(src); fw = new FileWriter(dest); br = new BufferedReader(fr); bw = new BufferedWriter(fw); source = new File(src); int fileLength = (int) source.length(); char charBuff[] = new char[fileLength]; while (br.read(charBuff, 0, fileLength) != -1) bw.write(charBuff, 0, fileLength); } catch (FileNotFoundException fnfe) { throw new FileCopyException(src + " " + MM.PHRASES.getPhrase("35")); } catch (IOException ioe) { throw new FileCopyException(MM.PHRASES.getPhrase("36")); } finally { try { if (br != null) br.close(); if (bw != null) bw.close(); } catch (IOException ioe) { } } }
11
Code Sample 1: private static void copierScriptChargement(File webInfDir, String initialDataChoice) { File chargementInitialDir = new File(webInfDir, "chargementInitial"); File fichierChargement = new File(chargementInitialDir, "ScriptChargementInitial.sql"); File fichierChargementAll = new File(chargementInitialDir, "ScriptChargementInitial-All.sql"); File fichierChargementTypesDocument = new File(chargementInitialDir, "ScriptChargementInitial-TypesDocument.sql"); File fichierChargementVide = new File(chargementInitialDir, "ScriptChargementInitial-Vide.sql"); if (fichierChargement.exists()) { fichierChargement.delete(); } File fichierUtilise = null; if ("all".equals(initialDataChoice)) { fichierUtilise = fichierChargementAll; } else if ("typesDocument".equals(initialDataChoice)) { fichierUtilise = fichierChargementTypesDocument; } else if ("empty".equals(initialDataChoice)) { fichierUtilise = fichierChargementVide; } if (fichierUtilise != null && fichierUtilise.exists()) { FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(fichierUtilise).getChannel(); destination = new FileOutputStream(fichierChargement).getChannel(); destination.transferFrom(source, 0, source.size()); } catch (Exception e) { throw new RuntimeException(e); } finally { if (source != null) { try { source.close(); } catch (Exception e) { e.printStackTrace(); } } if (destination != null) { try { destination.close(); } catch (Exception e) { e.printStackTrace(); } } } } } Code Sample 2: public static void copyFile(File source, File destination) { if (!source.exists()) { return; } if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) { destination.getParentFile().mkdirs(); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { ioe.printStackTrace(); } }
11
Code Sample 1: public List<BadassEntry> parse() { mBadassEntries = new ArrayList<BadassEntry>(); try { URL url = new URL(mUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; boolean flag1 = false; while ((line = reader.readLine()) != null) { line = line.trim(); if (!flag1 && line.contains(START_PARSE)) flag1 = true; if (flag1 && line.contains(STOP_PARSE)) break; if (flag1) { if (line.contains(ENTRY_HINT)) { parseBadass(line); } } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return mBadassEntries; } Code Sample 2: public String selectFROM() throws Exception { BufferedReader in = null; String data = null; try { HttpClient httpclient = new DefaultHttpClient(); URI uri = new URI("http://**.**.**.**/OctopusManager/index2.php"); HttpGet request = new HttpGet(); request.setURI(uri); HttpResponse httpresponse = httpclient.execute(request); HttpEntity httpentity = httpresponse.getEntity(); in = new BufferedReader(new InputStreamReader(httpentity.getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; while ((line = in.readLine()) != null) { sb.append(line); } in.close(); data = sb.toString(); return data; } finally { if (in != null) { try { in.close(); return data; } catch (Exception e) { e.printStackTrace(); } } } }
11
Code Sample 1: public static void unzip(String destDir, String zipPath) { PrintWriter stdout = new PrintWriter(System.out, true); int read = 0; byte[] data = new byte[1024]; ZipEntry entry; try { ZipInputStream in = new ZipInputStream(new FileInputStream(zipPath)); stdout.println(zipPath); while ((entry = in.getNextEntry()) != null) { if (entry.getMethod() == ZipEntry.DEFLATED) { stdout.println(" Inflating: " + entry.getName()); } else { stdout.println(" Extracting: " + entry.getName()); } FileOutputStream out = new FileOutputStream(destDir + File.separator + entry.getName()); while ((read = in.read(data, 0, 1024)) != -1) { out.write(data, 0, read); } out.close(); } in.close(); stdout.println(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: public Stopper(String stopWordsFile) { try { BufferedReader br = null; FileReader fr = null; if (stopWordsFile.startsWith("http")) { URL url = new URL(stopWordsFile); br = new BufferedReader(new InputStreamReader(url.openStream())); } else { fr = new FileReader(new File(stopWordsFile)); br = new BufferedReader(fr); } String line = null; while ((line = br.readLine()) != null) { line = line.trim(); stopWords.put(line, ""); } fr.close(); } catch (Exception e) { System.out.println("Stopwords not Found"); return; } } Code Sample 2: public String parse(String term) throws OntologyAdaptorException { try { String sUrl = getUrl(term); if (sUrl.length() > 0) { URL url = new URL(sUrl); InputStream in = url.openStream(); StringBuilder sb = new StringBuilder(); BufferedReader r = new BufferedReader(new InputStreamReader(in)); String line = null; while ((line = r.readLine()) != null) { if (sb.length() > 0) { sb.append("\r\n"); } sb.append(line); } return sb.toString(); } else { return ""; } } catch (Exception ex) { throw new OntologyAdaptorException("Convertion to lucene failed.", ex); } }
00
Code Sample 1: @Test public void testSecondary() throws Exception { ConnectionFactoryIF cf = new DefaultConnectionFactory(PropertyUtils.loadProperties(StreamUtils.getInputStream(propfile)), false); Connection conn = cf.requestConnection(); try { Statement stm = conn.createStatement(); stm.executeUpdate("drop table if exists first"); stm.executeUpdate("drop table if exists first_changes"); stm.executeUpdate("drop table if exists second"); stm.executeUpdate("drop table if exists second_changes"); stm.executeUpdate("create table first (a integer, b varchar, c integer, d date)"); stm.executeUpdate("create table first_changes (a integer, b varchar, c integer, d date, ct varchar, cd integer)"); stm.executeUpdate("create table second (a integer, b varchar, c integer, d date)"); stm.executeUpdate("create table second_changes (a integer, b varchar, c integer, d date, ct varchar, cd integer)"); stm.executeUpdate("insert into first (a,b,c,d) values (1,'a',10, date '2007-01-01')"); stm.executeUpdate("insert into first (a,b,c,d) values (2,'b',20, date '2007-01-02')"); stm.executeUpdate("insert into first (a,b,c,d) values (3,'c',30, date '2007-01-03')"); stm.executeUpdate("insert into first (a,b,c,d) values (4,'d',40, date '2007-01-04')"); stm.executeUpdate("insert into second (a,b,c,d) values (1,'e',50, date '2007-02-01')"); stm.executeUpdate("insert into second (a,b,c,d) values (2,'f',60, date '2007-02-02')"); stm.executeUpdate("insert into second (a,b,c,d) values (3,'g',70, date '2007-02-03')"); stm.executeUpdate("insert into second (a,b,c,d) values (4,'h',80, date '2007-02-04')"); conn.commit(); RelationMapping mapping = RelationMapping.readFromClasspath("net/ontopia/topicmaps/db2tm/JDBCDataSourceTest-secondary.xml"); TopicMapStoreIF store = new InMemoryTopicMapStore(); LocatorIF baseloc = URIUtils.getURILocator("base:foo"); store.setBaseAddress(baseloc); TopicMapIF topicmap = store.getTopicMap(); Processor.addRelations(mapping, null, topicmap, baseloc); exportTopicMap(topicmap, "after-first-sync"); stm.executeUpdate("insert into second_changes (a,b,c,d,ct,cd) values (2,'f',60,date '2007-02-02', 'r', 2)"); stm.executeUpdate("delete from second where a = 2"); conn.commit(); Processor.synchronizeRelations(mapping, null, topicmap, baseloc); exportTopicMap(topicmap, "after-second-sync"); mapping.close(); stm.executeUpdate("drop table first"); stm.executeUpdate("drop table first_changes"); stm.executeUpdate("drop table second"); stm.executeUpdate("drop table second_changes"); stm.close(); store.close(); conn.commit(); } catch (Exception e) { conn.rollback(); throw e; } finally { conn.close(); } } Code Sample 2: protected void saveResponse(final WebResponse response, final WebRequest request) throws IOException { counter_++; final String extension = chooseExtension(response.getContentType()); final File f = createFile(request.getUrl(), extension); final InputStream input = response.getContentAsStream(); final OutputStream output = new FileOutputStream(f); try { IOUtils.copy(response.getContentAsStream(), output); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } final URL url = response.getWebRequest().getUrl(); LOG.info("Created file " + f.getAbsolutePath() + " for response " + counter_ + ": " + url); final StringBuilder buffer = new StringBuilder(); buffer.append("tab[tab.length] = {code: " + response.getStatusCode() + ", "); buffer.append("fileName: '" + f.getName() + "', "); buffer.append("contentType: '" + response.getContentType() + "', "); buffer.append("method: '" + request.getHttpMethod().name() + "', "); if (request.getHttpMethod() == HttpMethod.POST && request.getEncodingType() == FormEncodingType.URL_ENCODED) { buffer.append("postParameters: " + nameValueListToJsMap(request.getRequestParameters()) + ", "); } buffer.append("url: '" + escapeJSString(url.toString()) + "', "); buffer.append("loadTime: " + response.getLoadTime() + ", "); final byte[] bytes = IOUtils.toByteArray(response.getContentAsStream()); buffer.append("responseSize: " + ((bytes == null) ? 0 : bytes.length) + ", "); buffer.append("responseHeaders: " + nameValueListToJsMap(response.getResponseHeaders())); buffer.append("};\n"); appendToJSFile(buffer.toString()); }
11
Code Sample 1: protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF-8"); try { String content = ""; URL url = new URL(request.getParameter("url")); URLConnection connection = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = in.readLine()) != null) { content += line + "\n"; } in.close(); String result = getResult(content); response.setContentType("text/plain"); PrintWriter out = response.getWriter(); out.println(result); } catch (Exception e) { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(getErrorPage(e)); } } Code Sample 2: public String parse(String queryText) throws ParseException { try { StringBuilder sb = new StringBuilder(); queryText = Val.chkStr(queryText); if (queryText.length() > 0) { URL url = new URL(getUrl(queryText)); InputStream in = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = null; while ((line = reader.readLine()) != null) { if (sb.length() > 0) { sb.append("\r\n"); } sb.append(line); } } return sb.toString(); } catch (IOException ex) { throw new ParseException("Ontology parser is unable to parse term: \"" + queryText + "\" due to internal error: " + ex.getMessage()); } }
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 void updateResult(Result result) throws UnsupportedEncodingException { HttpPost updateRequest = populateUpdateRequest(result); HttpClient client = clientProvider.getHttpClient(); try { HttpResponse response = client.execute(updateRequest); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream input = entity.getContent(); if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) { System.out.println("Request was not accepted by the collection server. Reason:"); System.out.println("Status: " + response.getStatusLine().getStatusCode()); } for (int c = 0; (c = input.read()) > -1; ) { System.out.print((char) c); } entity.consumeContent(); } } catch (ClientProtocolException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } }
11
Code Sample 1: public static String getHash(String text) { if (text == null) return null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(text.getBytes()); byte[] hashedTextBytes = md.digest(); BigInteger hashedTextBigInteger = new BigInteger(1, hashedTextBytes); String hashedTextString = hashedTextBigInteger.toString(16); return hashedTextString; } catch (NoSuchAlgorithmException e) { LOG.warning(e.toString()); return null; } } Code Sample 2: private String hash(String message) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e) { throw new AssertionError("Can't find the SHA1 algorithm in the java.security package"); } String saltString = String.valueOf(12345); md.update(saltString.getBytes()); md.update(message.getBytes()); byte[] digestBytes = md.digest(); StringBuffer digestSB = new StringBuffer(); for (int i = 0; i < digestBytes.length; i++) { int lowNibble = digestBytes[i] & 0x0f; int highNibble = (digestBytes[i] >> 4) & 0x0f; digestSB.append(Integer.toHexString(highNibble)); digestSB.append(Integer.toHexString(lowNibble)); } String digestStr = digestSB.toString().trim(); return digestStr; }
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 static boolean unzipWithWarning(File source, File targetDirectory, OverwriteValue policy) { try { if (!source.exists()) return false; ZipInputStream input = new ZipInputStream(new FileInputStream(source)); ZipEntry zipEntry = null; byte[] buffer = new byte[1024]; while ((zipEntry = input.getNextEntry()) != null) { if (zipEntry.isDirectory()) continue; File newFile = new File(targetDirectory, zipEntry.getName()); if (newFile.exists()) { switch(policy.value) { case NO_TO_ALL: continue; case YES_TO_ALL: break; default: switch(policy.value = confirmOverwrite(zipEntry.getName())) { case NO_TO_ALL: case NO: continue; default: } } } newFile.getParentFile().mkdirs(); int bytesRead; FileOutputStream output = new FileOutputStream(newFile); while ((bytesRead = input.read(buffer)) != -1) output.write(buffer, 0, bytesRead); output.close(); input.closeEntry(); } input.close(); } catch (Exception exc) { exc.printStackTrace(); return false; } return true; }
00
Code Sample 1: public APIResponse create(User user) throws Exception { APIResponse response = new APIResponse(); connection = (HttpURLConnection) new URL(url + "/api/user/create").openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); connection.setUseCaches(false); connection.setConnectTimeout(TIMEOUT); connection.connect(); marshaller.marshal(user, new MappedXMLStreamWriter(new MappedNamespaceConvention(new Configuration()), new OutputStreamWriter(connection.getOutputStream(), "utf-8"))); connection.getOutputStream().flush(); connection.getOutputStream().close(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { JSONObject obj = new JSONObject(new String(new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8")).readLine())); response.setDone(true); response.setMessage(unmarshaller.unmarshal(new MappedXMLStreamReader(obj, new MappedNamespaceConvention(new Configuration())))); connection.getInputStream().close(); } else { response.setDone(false); response.setMessage("Create User Error Code: Http (" + connection.getResponseCode() + ")"); } connection.disconnect(); return response; } Code Sample 2: public String calculateProjectMD5(String scenarioName) throws Exception { Scenario s = ScenariosManager.getInstance().getScenario(scenarioName); s.loadParametersAndValues(); String scenarioMD5 = calculateScenarioMD5(s); Map<ProjectComponent, String> map = getProjectMD5(new ProjectComponent[] { ProjectComponent.resources, ProjectComponent.classes, ProjectComponent.suts, ProjectComponent.libs }); map.put(ProjectComponent.currentScenario, scenarioMD5); MessageDigest md = MessageDigest.getInstance("MD5"); Iterator<String> iter = map.values().iterator(); while (iter.hasNext()) { md.update(iter.next().getBytes()); } byte[] hash = md.digest(); BigInteger result = new BigInteger(hash); String rc = result.toString(16); return rc; }
00
Code Sample 1: public static void readUrlWriteFileTest(String url, String fileName) throws Exception { System.out.println("Initiated reading source queue URL: " + url); InputStream instream = new URL(url).openStream(); Serializer serializer = new Serializer(); Response response = (Response) serializer.parse(instream); Queue queue = response.getQueue(); instream.close(); System.out.println("Completed reading source queue URL (jobs=" + queue.size() + ")"); System.out.println("Initiated writing target queue File: " + fileName); OutputStream outstream = new FileOutputStream(fileName); serializer.write(response, outstream); outstream.close(); System.out.println("Completed writing target queue file."); } 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:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
00
Code Sample 1: public static String getHash(String password, String salt) { try { MessageDigest messageDigest = null; messageDigest = MessageDigest.getInstance(SHA_512); messageDigest.reset(); messageDigest.update(salt.getBytes("UTF-8")); messageDigest.update(password.getBytes("UTF-8")); byte[] input = messageDigest.digest(); for (int i = 0; i < 1000; i++) { messageDigest.reset(); input = messageDigest.digest(input); } Formatter formatter = new Formatter(); for (byte i : input) { formatter.format("%02x", i); } return formatter.toString(); } catch (NoSuchAlgorithmException e) { return ""; } catch (UnsupportedEncodingException e) { return ""; } } Code Sample 2: private static void addIngredient(int recipeId, String name, String amount, int measureId, int shopFlag) throws Exception { PreparedStatement pst = null; try { pst = conn.prepareStatement("INSERT INTO ingredients (recipe_id, name, amount, measure_id, shop_flag) VALUES (?,?,?,?,?)"); pst.setInt(1, recipeId); pst.setString(2, name); pst.setString(3, amount); pst.setInt(4, measureId); pst.setInt(5, shopFlag); pst.executeUpdate(); conn.commit(); } catch (Exception e) { conn.rollback(); throw new Exception("Ainesosan lis�ys ep�onnistui. Poikkeus: " + e.getMessage()); } }
00
Code Sample 1: public void reset(String componentName, int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? " + "AND component_name = ?"); psta.setInt(1, currentPilot); psta.setString(2, componentName); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } } 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: private static void copyFile(String src, String dst) throws InvocationTargetException { try { FileChannel srcChannel; srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (FileNotFoundException e) { throw new InvocationTargetException(e, Messages.ALFWizardCreationAction_errorSourceFilesNotFound); } catch (IOException e) { throw new InvocationTargetException(e, Messages.ALFWizardCreationAction_errorCopyingFiles); } } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: public void copyAffix(MailAffix affix, long mailId1, long mailId2) throws Exception { File file = new File(this.getResDir(mailId1) + affix.getAttachAlias()); if (file.exists()) { File file2 = new File(this.getResDir(mailId2) + affix.getAttachAlias()); if (!file2.exists()) { file2.createNewFile(); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file2)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(file)); int read; while ((read = in.read()) != -1) { out.write(read); } out.flush(); in.close(); out.close(); } } else { log.debug(file.getAbsolutePath() + file.getName() + "�����ڣ������ļ�ʧ�ܣ���������"); } } 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(); }
00
Code Sample 1: private String mkSid() { String temp = toString(); MessageDigest messagedigest = null; try { messagedigest = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } messagedigest.update(temp.getBytes()); byte digest[] = messagedigest.digest(); String chk = ""; for (int i = 0; i < digest.length; i++) { String s = Integer.toHexString(digest[i] & 0xFF); chk += ((s.length() == 1) ? "0" + s : s); } return chk.toString(); } Code Sample 2: @Override public String execute() throws Exception { SystemContext sc = getSystemContext(); if (sc.getExpireTime() == -1) { return LOGIN; } else if (upload != null) { try { Enterprise e = LicenceUtils.get(upload); sc.setEnterpriseName(e.getEnterpriseName()); sc.setExpireTime(e.getExpireTime()); String webPath = ServletActionContext.getServletContext().getRealPath("/"); File desFile = new File(webPath, LicenceUtils.LICENCE_FILE_NAME); FileChannel sourceChannel = new FileInputStream(upload).getChannel(); FileChannel destinationChannel = new FileOutputStream(desFile).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); return LOGIN; } catch (Exception e) { } } return "license"; }
00
Code Sample 1: private Object[] retrieveSecondURL(URL url, RSLink link) { link.setStatus(RSLink.STATUS_WAITING); Object[] result = new Object[2]; HttpURLConnection httpConn = null; BufferedReader inr = null; DataOutputStream outs = null; Pattern mirrorLinePattern = Pattern.compile("'<input.+checked.+type=\"radio\".+name=\"mirror\".+\\\\'.+\\\\'"); Pattern mirrorUrlPattern = Pattern.compile("\\\\'.+\\\\'"); Pattern counterPattern = Pattern.compile("var c=[0-9]+;"); Pattern counterIntPattern = Pattern.compile("[0-9]+"); try { String line = null; String urlLine = null; Integer counter = null; String postData = URLEncoder.encode("dl.start", "UTF-8") + "=" + URLEncoder.encode("Free", "UTF-8"); httpConn = (HttpURLConnection) url.openConnection(); httpConn.setRequestMethod("POST"); httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpConn.setRequestProperty("Content-Length", "" + Integer.toString(postData.getBytes().length)); httpConn.setRequestProperty("Content-Language", "en-US"); httpConn.setDoOutput(true); httpConn.setDoInput(true); outs = new DataOutputStream(httpConn.getOutputStream()); outs.writeBytes(postData); outs.flush(); inr = new BufferedReader(new InputStreamReader(httpConn.getInputStream())); Matcher matcher = null; while ((line = inr.readLine()) != null) { matcher = mirrorLinePattern.matcher(line); if (matcher.find()) { matcher = mirrorUrlPattern.matcher(line); if (matcher.find()) { urlLine = matcher.group().substring(2, matcher.group().length() - 2); result[0] = new URL(urlLine); } } matcher = counterPattern.matcher(line); if (matcher.find()) { matcher = counterIntPattern.matcher(line); if (matcher.find()) { counter = new Integer(matcher.group()); result[1] = counter; } } } } catch (IOException ex) { log("I/O Exception!"); } finally { try { if (outs != null) outs.close(); if (inr != null) inr.close(); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Can not close some connections:\n" + ex.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE); } if (httpConn != null) httpConn.disconnect(); link.setStatus(RSLink.STATUS_NOTHING); return result; } } Code Sample 2: public int getDBVersion() throws MigrationException { int dbVersion; PreparedStatement ps; try { Connection conn = getConnection(); ps = conn.prepareStatement("SELECT version FROM " + getTablename()); try { ResultSet rs = ps.executeQuery(); try { if (rs.next()) { dbVersion = rs.getInt(1); if (rs.next()) { throw new MigrationException("Too many version in table: " + getTablename()); } } else { ps.close(); ps = conn.prepareStatement("INSERT INTO " + getTablename() + " (version) VALUES (?)"); ps.setInt(1, 1); try { ps.executeUpdate(); } finally { ps.close(); } dbVersion = 1; } } finally { rs.close(); } } finally { ps.close(); } } catch (SQLException e) { logger.log(Level.WARNING, "Could not access " + tablename + ": " + e); dbVersion = 0; Connection conn = getConnection(); try { if (!conn.getAutoCommit()) { conn.rollback(); } conn.setAutoCommit(false); } catch (SQLException e1) { throw new MigrationException("Could not reset transaction state", e1); } } return dbVersion; }
11
Code Sample 1: private static Vector<String> getIgnoreList() { try { URL url = DeclarationTranslation.class.getClassLoader().getResource("ignorelist"); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream())); Vector<String> ret = new Vector<String>(); String line = null; while ((line = bufferedReader.readLine()) != null) { ret.add(line); } return ret; } catch (Exception e) { return null; } } Code Sample 2: private Long queryServer(OWLOntology ontologyURI) throws IOException { String requestString = "http://" + InetAddress.getLocalHost().getHostName() + ":8080/ChangeServer"; requestString += "?query=" + URLEncoder.encode(ontologyURI.getURI().toString(), "UTF-8"); URL url = new URL(requestString); BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer returned = new StringBuffer(); String str; while (null != ((str = input.readLine()))) { returned.append(str); } input.close(); return new Long(returned.toString()); }
11
Code Sample 1: public static void writeToPetrify(TransitionSystem ts, Writer bw) throws IOException { File temp = new File("_temp"); BufferedWriter tw = new BufferedWriter(new FileWriter(temp)); BufferedReader tr = new BufferedReader(new FileReader(temp)); HashSet<ModelGraphVertex> sources = new HashSet<ModelGraphVertex>(); HashSet<ModelGraphVertex> dests = new HashSet<ModelGraphVertex>(); ArrayList transitions = ts.getEdges(); HashSet<String> events = new HashSet<String>(); for (int i = 0; i < transitions.size(); i++) { TransitionSystemEdge transition = (TransitionSystemEdge) transitions.get(i); events.add(replaceBadSymbols(transition.getIdentifier())); sources.add(transition.getSource()); dests.add(transition.getDest()); if (ts.getStateNameFlag() == TransitionSystem.ID) { tw.write("s" + transition.getSource().getId() + " "); tw.write(replaceBadSymbols(transition.getIdentifier()) + " "); tw.write("s" + transition.getDest().getId() + "\n"); } else { tw.write(replaceBadSymbols(transition.getSource().getIdentifier()) + " "); tw.write(replaceBadSymbols(transition.getIdentifier()) + " "); tw.write(replaceBadSymbols(transition.getDest().getIdentifier()) + "\n"); } } tw.close(); bw.write(".model " + ts.getName().replaceAll(" ", "_") + "\n"); bw.write(".dummy "); Iterator it = events.iterator(); while (it.hasNext()) bw.write(it.next() + " "); bw.write("\n"); bw.write(".state graph" + "\n"); int c; while ((c = tr.read()) != -1) bw.write(c); tr.close(); temp.delete(); for (ModelGraphVertex dest : dests) { if (sources.contains(dest)) { sources.remove(dest); } } ModelGraphVertex source = sources.isEmpty() ? null : sources.iterator().next(); if (ts.getStateNameFlag() == TransitionSystem.ID) { if (!ts.hasExplicitEnd()) bw.write(".marking {s0}" + "\n"); else bw.write(".marking {s" + source.getId() + "}\n"); } else if (source != null) { bw.write(".marking {" + replaceBadSymbols(source.getIdentifier()) + "}\n"); } bw.write(".end"); } Code Sample 2: private void copyIntoFile(String resource, File output) throws IOException { FileOutputStream out = null; InputStream in = null; try { out = FileUtils.openOutputStream(output); in = GroovyInstanceTest.class.getResourceAsStream(resource); IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(in); } }
11
Code Sample 1: @Override protected void loadInternals(final File internDir, final ExecutionMonitor exec) throws IOException, CanceledExecutionException { List<String> taxa = new Vector<String>(); String domain = m_domain.getStringValue(); String id = ""; if (domain.equalsIgnoreCase("Eukaryota")) id = "eukaryota"; try { URL url = new URL("http://www.ebi.ac.uk/genomes/" + id + ".details.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String link = ""; String key = ""; String name = ""; int counter = 0; String line = ""; while ((line = reader.readLine()) != null) { String[] st = line.split("\t"); ena_details ena = new ena_details(st[0], st[1], st[2], st[3], st[4]); ENADataHolder.instance().put(ena.desc, ena); taxa.add(ena.desc); } reader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: protected boolean registerFromFile(URI providerList) { boolean registeredSomething = false; InputStream urlStream = null; try { urlStream = providerList.toURL().openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(urlStream, "UTF-8")); String provider; while ((provider = reader.readLine()) != null) { int comment = provider.indexOf('#'); if (comment != -1) { provider = provider.substring(0, comment); } provider = provider.trim(); if (provider.length() > 0) { try { registeredSomething |= registerAssoc(provider); } catch (Exception allElse) { if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { LOG.log(Level.WARNING, "Failed to register \'" + provider + "\'", allElse); } } } } } catch (IOException ex) { LOG.log(Level.WARNING, "Failed to read provider list " + providerList, ex); return false; } finally { if (null != urlStream) { try { urlStream.close(); } catch (IOException ignored) { } } } return registeredSomething; }
00
Code Sample 1: public void connect() throws FTPException { try { ftp = new FTPClient(); ftp.connect(host); if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) { ftp.login(this.username, this.password); } else { ftp.disconnect(); throw new FTPException("Não foi possivel se conectar no servidor FTP"); } isConnected = true; } catch (Exception ex) { throw new FTPException(ex); } } Code Sample 2: public String parse(String term) throws OntologyAdaptorException { try { String sUrl = getUrl(term); if (sUrl.length() > 0) { URL url = new URL(sUrl); InputStream in = url.openStream(); StringBuilder sb = new StringBuilder(); BufferedReader r = new BufferedReader(new InputStreamReader(in)); String line = null; while ((line = r.readLine()) != null) { if (sb.length() > 0) { sb.append("\r\n"); } sb.append(line); } return sb.toString(); } else { return ""; } } catch (Exception ex) { throw new OntologyAdaptorException("Convertion to lucene failed.", ex); } }
00
Code Sample 1: public static List<String> getFiles(int year, int month, int day, String type) throws Exception { ArrayList<String> list = new ArrayList<String>(); URL url = new URL(baseUrl + "/" + year + "/" + ((month > 9) ? month : ("0" + month)) + "/" + ((day > 9) ? day : ("0" + day))); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = br.readLine()) != null && line != "") { if (line.startsWith("<tr>") && line.indexOf("[TXT]") >= 0) { int i = line.indexOf("href="); i = i + 6; int j = line.indexOf("\"", i); String filename = line.substring(i, j); if (filename.matches(".*" + type + ".*")) { list.add(filename); } } } br.close(); return list; } Code Sample 2: 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(); } }
11
Code Sample 1: public HashMap parseFile(File newfile) throws IOException { String s; String[] tokens; int nvalues = 0; double num1, num2, num3; boolean baddata = false; URL url = newfile.toURL(); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); HashMap data = new HashMap(); while ((s = br.readLine()) != null) { tokens = s.split("\\s+"); nvalues = tokens.length; if (nvalues == 2) { data.put(new String(tokens[0]), new Double(Double.parseDouble(tokens[1]))); } else { System.out.println("Sorry, trouble reading reference file."); } } return data; } Code Sample 2: public static void main(String[] args) { StringBuffer htmlPage; htmlPage = new StringBuffer(); double min = 99999.99; double max = 0; double value = 0; try { URL url = new URL("http://search.ebay.com/" + args[0]); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = in.readLine()) != null) { htmlPage.append(line); htmlPage.append("\n"); } } catch (Exception ex) { ex.printStackTrace(); } Pattern p = Pattern.compile("\\$([\\d\\.]+)", Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(htmlPage); while (m.find()) { if (m.start(0) < m.end(0)) { value = Double.parseDouble(m.group(1)); if (value < min) { min = value; } if (value > max) { max = value; } } } if (min == 99999.99) { min = 0; } System.out.println(args[0] + "," + min + "," + max); System.exit(0); }
11
Code Sample 1: 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); } } Code Sample 2: public ActualTask(TEditor editor, TIGDataBase dataBase, String directoryPath, Vector images) { int i; lengthOfTask = images.size(); Element dataBaseXML = new Element("dataBase"); for (i = 0; ((i < images.size()) && !stop && !cancel); i++) { Vector imagen = new Vector(2); imagen = (Vector) images.elementAt(i); String element = (String) imagen.elementAt(0); current = i; String pathSrc = System.getProperty("user.dir") + File.separator + "images" + File.separator + element.substring(0, 1).toUpperCase() + File.separator + element; String name = pathSrc.substring(pathSrc.lastIndexOf(File.separator) + 1, pathSrc.length()); String pathDst = directoryPath + name; try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } Vector<String> keyWords = new Vector<String>(); keyWords = TIGDataBase.asociatedConceptSearch(element); Element image = new Element("image"); image.setAttribute("name", name); if (keyWords.size() != 0) { for (int k = 0; k < keyWords.size(); k++) { Element category = new Element("category"); category.setText(keyWords.get(k).trim()); image.addContent(category); } } dataBaseXML.addContent(image); } Document doc = new Document(dataBaseXML); try { XMLOutputter out = new XMLOutputter(); FileOutputStream f = new FileOutputStream(directoryPath + "images.xml"); out.output(doc, f); f.flush(); f.close(); } catch (Exception e) { e.printStackTrace(); } current = lengthOfTask; }
00
Code Sample 1: public void refreshFileItem(YahooInfo legroup) throws Exception { String lapage = new String(""); String ledir = new String(""); Pattern pat; Matcher mat; Pattern pat2; Matcher mat2; int data; URL myurl = new URL("http://groups.yahoo.com/mygroups"); URLConnection conn; URI myuri = new URI("http://groups.yahoo.com/mygroups"); YahooInfo yi; clearItem(legroup); for (int i = 0; i < UrlList.size(); i++) { if (UrlList.get(i).getGroup().equals(legroup.getGroup()) && UrlList.get(i).getDir().startsWith(legroup.getDir())) { if (UrlList.get(i).isGroup()) { System.out.print(UrlList.get(i).getGroup() + " : "); myuri = new URI(UrlList.get(i).getUrl()); myurl = new URL(UrlList.get(i).getUrl()); conn = myurl.openConnection(); conn.connect(); System.out.println(conn.getHeaderField(0).toString()); if (!Pattern.matches("HTTP/... 2.. .*", conn.getHeaderField(0).toString())) { System.out.println(conn.getHeaderField(0).toString()); return; } InputStream in = conn.getInputStream(); lapage = ""; for (data = in.read(); data != -1; data = in.read()) lapage += (char) data; pat = Pattern.compile("<li> <a href=\"(.+?)\".*?>Files</a></li>"); mat = pat.matcher(lapage); if (mat.find()) { yi = new YahooInfo(UrlList.get(i).getGroup(), "/", "", myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL().toString()); UrlList.add(yi); } } if (UrlList.get(i).isDir()) { System.out.println(UrlList.get(i).getGroup() + UrlList.get(i).getDir()); myuri = new URI(UrlList.get(i).getUrl()); myurl = new URL(UrlList.get(i).getUrl()); do { myurl = new URL(myurl.toString()); conn = myurl.openConnection(); conn.connect(); if (!Pattern.matches("HTTP/... 2.. .*", conn.getHeaderField(0).toString())) { System.out.println(conn.getHeaderField(0).toString()); return; } System.out.print("p"); InputStream in = conn.getInputStream(); lapage = ""; for (data = in.read(); data != -1; data = in.read()) lapage += (char) data; pat = Pattern.compile("<span class=\"title\">\n<a href=\"(.+?/)\">(.+?)</a>"); mat = pat.matcher(lapage); while (mat.find()) { ledir = new String(UrlList.get(i).getDir()); pat2 = Pattern.compile("([A-Za-z0-9]+)"); mat2 = pat2.matcher(mat.group(2)); while (mat2.find()) { ledir += mat2.group(1); } ledir += "/"; yi = new YahooInfo(UrlList.get(i).getGroup(), ledir, "", myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL().toString()); UrlList.add(yi); } pat = Pattern.compile("<span class=\"title\">\n<a href=\"(.+?yahoofs.+?)\".*?>(.+?)</a>"); mat = pat.matcher(lapage); while (mat.find()) { yi = new YahooInfo(UrlList.get(i).getGroup(), UrlList.get(i).getDir(), mat.group(2), myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL().toString()); UrlList.add(yi); } System.out.println(""); pat = Pattern.compile("<a href=\"(.+?)\">Next"); mat = pat.matcher(lapage); myurl = null; if (mat.find()) { myurl = myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL(); } } while (myurl != null); } } } } Code Sample 2: protected HttpResponse executeRequest(AbstractHttpRequest request) throws ConnectionException, RequestCancelledException { try { HttpResponse response = getHttpClient().execute(request); if (!response.is2xxSuccess()) { throw new ConnectionException(); } return response; } catch (IOException ex) { throw new ConnectionException(); } catch (TimeoutException ex) { throw new ConnectionException(); } }
11
Code Sample 1: public File extractID3v2TagDataIntoFile(File outputFile) throws TagNotFoundException, IOException { int startByte = (int) ((MP3AudioHeader) audioHeader).getMp3StartByte(); if (startByte >= 0) { FileInputStream fis = new FileInputStream(file); FileChannel fc = fis.getChannel(); ByteBuffer bb = ByteBuffer.allocate(startByte); fc.read(bb); FileOutputStream out = new FileOutputStream(outputFile); out.write(bb.array()); out.close(); fc.close(); fis.close(); return outputFile; } throw new TagNotFoundException("There is no ID3v2Tag data in this file"); } Code Sample 2: private static void writeOneAttachment(Context context, Writer writer, OutputStream out, Attachment attachment) throws IOException, MessagingException { writeHeader(writer, "Content-Type", attachment.mMimeType + ";\n name=\"" + attachment.mFileName + "\""); writeHeader(writer, "Content-Transfer-Encoding", "base64"); writeHeader(writer, "Content-Disposition", "attachment;" + "\n filename=\"" + attachment.mFileName + "\";" + "\n size=" + Long.toString(attachment.mSize)); writeHeader(writer, "Content-ID", attachment.mContentId); writer.append("\r\n"); InputStream inStream = null; try { Uri fileUri = Uri.parse(attachment.mContentUri); inStream = context.getContentResolver().openInputStream(fileUri); writer.flush(); Base64OutputStream base64Out = new Base64OutputStream(out); IOUtils.copy(inStream, base64Out); base64Out.close(); } catch (FileNotFoundException fnfe) { } catch (IOException ioe) { throw new MessagingException("Invalid attachment.", ioe); } }
11
Code Sample 1: public ZIPSignatureService(InputStream documentInputStream, SignatureFacet signatureFacet, OutputStream documentOutputStream, RevocationDataService revocationDataService, TimeStampService timeStampService, String role, IdentityDTO identity, byte[] photo, DigestAlgo signatureDigestAlgo) throws IOException { super(signatureDigestAlgo); this.temporaryDataStorage = new HttpSessionTemporaryDataStorage(); this.documentOutputStream = documentOutputStream; this.tmpFile = File.createTempFile("eid-dss-", ".zip"); FileOutputStream fileOutputStream; fileOutputStream = new FileOutputStream(this.tmpFile); IOUtils.copy(documentInputStream, fileOutputStream); addSignatureFacet(new ZIPSignatureFacet(this.tmpFile, signatureDigestAlgo)); XAdESSignatureFacet xadesSignatureFacet = new XAdESSignatureFacet(getSignatureDigestAlgorithm()); xadesSignatureFacet.setRole(role); addSignatureFacet(xadesSignatureFacet); addSignatureFacet(new KeyInfoSignatureFacet(true, false, false)); addSignatureFacet(new XAdESXLSignatureFacet(timeStampService, revocationDataService, getSignatureDigestAlgorithm())); addSignatureFacet(signatureFacet); if (null != identity) { IdentitySignatureFacet identitySignatureFacet = new IdentitySignatureFacet(identity, photo, getSignatureDigestAlgorithm()); addSignatureFacet(identitySignatureFacet); } } Code Sample 2: public void copyFile(String oldPathFile, String newPathFile) { try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPathFile); if (oldfile.exists()) { InputStream inStream = new FileInputStream(oldPathFile); FileOutputStream fs = new FileOutputStream(newPathFile); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); } } catch (Exception e) { message = ("���Ƶ����ļ���������"); } }
11
Code Sample 1: @Override public void copierPhotos(FileInputStream fichierACopier, FileOutputStream fichierDestination) { FileChannel in = null; FileChannel out = null; try { in = fichierACopier.getChannel(); out = fichierDestination.getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: public static DBData resolveDBasURL(java.net.URL url) throws Exception { DBData data = null; InputStream fi = null; EnhancedStreamTokenizer tokenizer = null; try { fi = url.openStream(); tokenizer = new EnhancedStreamTokenizer(new BufferedReader(new InputStreamReader(fi))); initializeTokenizer(tokenizer); } catch (Exception e) { Console.getInstance().println("\nError occured while opening URL '" + url.toString() + "'"); Console.getInstance().println(e); return null; } if (tokenizer != null) { try { } finally { System.gc(); } } return data; } Code Sample 2: public byte[] pipeBytes() { byte ba[] = null; try { URL url = new URL(server); conn = (HttpURLConnection) url.openConnection(); InputStream is = conn.getInputStream(); ByteArrayOutputStream tout = new ByteArrayOutputStream(); int nmax = 10000; byte b[] = new byte[nmax + 1]; int nread = 0; while ((nread = is.read(b, 0, nmax)) >= 0) tout.write(b, 0, nread); ba = tout.toByteArray(); } catch (Exception ex) { System.err.println(ex); } return ba; }
11
Code Sample 1: public ResourceMigrator getCompletedResourceMigrator() { return new ResourceMigrator() { public void migrate(InputMetadata meta, InputStream inputStream, OutputCreator outputCreator) throws IOException, ResourceMigrationException { OutputStream outputStream = outputCreator.createOutputStream(); IOUtils.copy(inputStream, outputStream); } }; } Code Sample 2: public static Drawable fetchCachedDrawable(String url) throws MalformedURLException, IOException { Log.d(LOG_TAG, "Fetching cached : " + url); String cacheName = md5(url); checkAndCreateDirectoryIfNeeded(); File r = new File(CACHELOCATION + cacheName); if (!r.exists()) { InputStream is = (InputStream) fetch(url); FileOutputStream fos = new FileOutputStream(CACHELOCATION + cacheName); int nextChar; while ((nextChar = is.read()) != -1) fos.write((char) nextChar); fos.flush(); } FileInputStream fis = new FileInputStream(CACHELOCATION + cacheName); Drawable d = Drawable.createFromStream(fis, "src"); return d; }
11
Code Sample 1: @NotNull private Properties loadProperties() { File file = new File(homeLocator.getHomeDir(), configFilename); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { throw new RuntimeException("IOException while creating \"" + file.getAbsolutePath() + "\".", e); } } if (!file.canRead() || !file.canWrite()) { throw new RuntimeException("Cannot read and write from file: " + file.getAbsolutePath()); } if (lastModifiedByUs < file.lastModified()) { if (logger.isLoggable(Level.FINE)) { logger.fine("File \"" + file + "\" is newer on disk. Read it ..."); } Properties properties = new Properties(); try { FileInputStream in = new FileInputStream(file); try { properties.loadFromXML(in); } catch (InvalidPropertiesFormatException e) { FileOutputStream out = new FileOutputStream(file); try { properties.storeToXML(out, comment); } finally { out.close(); } } finally { in.close(); } } catch (IOException e) { throw new RuntimeException("IOException while reading from \"" + file.getAbsolutePath() + "\".", e); } this.lastModifiedByUs = file.lastModified(); this.properties = properties; if (logger.isLoggable(Level.FINE)) { logger.fine("... read done."); } } assert this.properties != null; return this.properties; } Code Sample 2: @Override public void run() { log.debug("Now running...."); log.debug("Current env. variables:"); try { this.infoNotifiers("Environment parameters after modifications:"); this.logEnvironment(); this.infoNotifiers("Dump thread will now run..."); this.endNotifiers(); this.process = this.pb.start(); this.process.waitFor(); if (this.process.exitValue() != 0) { this.startNotifiers(); this.infoNotifiers("Dump Failed. Return status: " + this.process.exitValue()); this.endNotifiers(); return; } List<String> cmd = new LinkedList<String>(); cmd.add("gzip"); cmd.add(info.getDumpFileName()); File basePath = this.pb.directory(); this.pb = new ProcessBuilder(cmd); this.pb.directory(basePath); log.debug("Executing: " + StringUtils.join(cmd.iterator(), ' ')); this.process = this.pb.start(); this.process.waitFor(); if (this.process.exitValue() != 0) { this.startNotifiers(); this.infoNotifiers("Dump GZip Failed. Return status: " + this.process.exitValue()); this.endNotifiers(); return; } info.setDumpFileName(info.getDumpFileName() + ".gz"); info.setMD5SumFileName(info.getDumpFileName() + ".md5sum"); cmd = new LinkedList<String>(); cmd.add("md5sum"); cmd.add("-b"); cmd.add(info.getDumpFileName()); log.debug("Executing: " + StringUtils.join(cmd.iterator(), ' ')); this.pb = new ProcessBuilder(cmd); this.pb.directory(basePath); this.process = this.pb.start(); BufferedOutputStream md5sumFileOut = new BufferedOutputStream(new FileOutputStream(basePath.getAbsolutePath() + File.separatorChar + info.getMD5SumFileName())); IOUtils.copy(this.process.getInputStream(), md5sumFileOut); this.process.waitFor(); md5sumFileOut.flush(); md5sumFileOut.close(); if (this.process.exitValue() != 0) { this.startNotifiers(); this.infoNotifiers("Dump GZip MD5Sum Failed. Return status: " + this.process.exitValue()); this.endNotifiers(); return; } else { this.startNotifiers(); this.infoNotifiers("Dump, gzip and md5sum sucessfuly completed."); this.endNotifiers(); } } catch (IOException e) { String message = "IOException launching command: " + e.getMessage(); log.error(message, e); throw new IllegalStateException(message, e); } catch (InterruptedException e) { String message = "InterruptedException launching command: " + e.getMessage(); log.error(message, e); throw new IllegalStateException(message, e); } catch (IntegrationException e) { String message = "IntegrationException launching command: " + e.getMessage(); log.error(message, e); throw new IllegalStateException(message, e); } }
00
Code Sample 1: public void actionPerformed(ActionEvent e) { if (e.getSource() == cancel) { email.setText(""); name.setText(""); category.setSelectedIndex(0); subject.setText(""); message.setText(""); setVisible(false); } else { StringBuffer errors = new StringBuffer(); if (email.getText().trim().equals("")) errors.append("El campo 'Email' es obligatorio<br/>"); if (name.getText().trim().equals("")) errors.append("El campo 'Nombre' es obligatorio<br/>"); if (subject.getText().trim().equals("")) errors.append("El campo 'T�tulo' es obligatorio<br/>"); if (message.getText().trim().equals("")) errors.append("No hay conrtenido en el mensaje<br/>"); if (errors.length() > 0) { JOptionPane.showMessageDialog(this, "<html><b>Error</b><br/>" + errors.toString() + "</html>", "Error", JOptionPane.ERROR_MESSAGE); } else { try { StringBuffer params = new StringBuffer(); params.append("name=").append(URLEncoder.encode(name.getText(), "UTF-8")).append("&category=").append(URLEncoder.encode((String) category.getSelectedItem(), "UTF-8")).append("&title=").append(URLEncoder.encode(subject.getText(), "UTF-8")).append("&email=").append(URLEncoder.encode(email.getText(), "UTF-8")).append("&id=").append(URLEncoder.encode(MainWindow.getUserPreferences().getUniqueId() + "", "UTF-8")).append("&body=").append(URLEncoder.encode(message.getText(), "UTF-8")); URL url = new URL("http://www.cronopista.com/diccionario2/sendMessage.php"); URLConnection connection = url.openConnection(); Utils.setupProxy(connection); connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write(params.toString()); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String decodedString; while ((decodedString = in.readLine()) != null) { System.out.println(decodedString); } in.close(); email.setText(""); name.setText(""); category.setSelectedIndex(0); subject.setText(""); message.setText(""); setVisible(false); } catch (Exception ex) { JOptionPane.showMessageDialog(this, "<html><b>Error</b><br/>Ha ocurrido un error enviando tu mensaje.<br/>" + "Por favor, int�ntalo m�s tarde o ponte en contacto conmigo a trav�s de www.cronopista.com</html>", "Error", JOptionPane.ERROR_MESSAGE); } } } } Code Sample 2: public void testIsVersioned() throws ServiceException, IOException { JCRNodeSource emptySource = loadTestSource(); assertTrue(emptySource.isVersioned()); OutputStream sourceOut = emptySource.getOutputStream(); assertNotNull(sourceOut); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } assertTrue(emptySource.isVersioned()); }
11
Code Sample 1: public void removeGames(List<Game> games) throws SQLException { Connection conn = ConnectionManager.getManager().getConnection(); PreparedStatement stm = null; conn.setAutoCommit(false); try { for (Game game : games) { stm = conn.prepareStatement(Statements.DELETE_GAME); stm.setInt(1, game.getGameID()); stm.executeUpdate(); } } catch (SQLException e) { conn.rollback(); throw e; } finally { if (stm != null) stm.close(); } conn.commit(); conn.setAutoCommit(true); } Code Sample 2: public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt.executeUpdate(sql); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } }
00
Code Sample 1: private void convertClasses(File source, File destination) throws PostProcessingException, CodeCheckException, IOException { Stack sourceStack = new Stack(); Stack destinationStack = new Stack(); sourceStack.push(source); destinationStack.push(destination); while (!sourceStack.isEmpty()) { source = (File) sourceStack.pop(); destination = (File) destinationStack.pop(); if (!destination.exists()) destination.mkdirs(); File[] files = source.listFiles(); for (int i = 0; i < files.length; i++) { File current = (File) files[i]; if (current.isDirectory()) { sourceStack.push(current); destinationStack.push(new File(destination, current.getName())); } else if (current.getName().endsWith(".class")) { ClassWriter writer = new ClassWriter(); InputStream is = new BufferedInputStream(new FileInputStream(current)); writer.readClass(is); is.close(); if ((getStatusFlags(writer.getClassName(writer.getCurrentClassIndex())) & PP_PROCESSED) != 0) { ClassWriter[] auxWriter = new ClassWriter[1]; transformClass(writer, auxWriter); File output = new File(destination, current.getName()); OutputStream os = new BufferedOutputStream(new FileOutputStream(output)); writer.writeClass(os); os.close(); if (auxWriter[0] != null) { String className = auxWriter[0].getClassName(auxWriter[0].getCurrentClassIndex()); className = className.substring(className.lastIndexOf('.') + 1, className.length()); output = new File(destination, className + ".class"); os = new BufferedOutputStream(new FileOutputStream(output)); auxWriter[0].writeClass(os); os.close(); } } } } } } Code Sample 2: @Test public final void testCheckCookies() { URL url = null; try { url = new URL("http://localhost:8080"); } catch (MalformedURLException e1) { e1.printStackTrace(); } StringBuffer content = new StringBuffer(); try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0; H010818)"); cookie = connection.getHeaderField("Set-Cookie"); if (cookie != null) System.out.println("cookie: " + cookie.toString()); connection.setDoInput(true); InputStream is = connection.getInputStream(); byte[] buffer = new byte[2048]; int count; while (-1 != (count = is.read(buffer))) { content.append(new String(buffer, 0, count)); } } catch (IOException e) { System.out.print(e.getMessage()); return; } }
00
Code Sample 1: static void copyFile(File file, File file1) throws IOException { byte abyte0[] = new byte[512]; FileInputStream fileinputstream = new FileInputStream(file); FileOutputStream fileoutputstream = new FileOutputStream(file1); int i; while ((i = fileinputstream.read(abyte0)) > 0) fileoutputstream.write(abyte0, 0, i); fileinputstream.close(); fileoutputstream.close(); } Code Sample 2: private static void checkForUpdates() { LOGGER.debug("Checking for Updates"); new Thread() { @Override public void run() { String lastVersion = null; try { URL projectSite = new URL("http://code.google.com/p/g15lastfm/"); URLConnection urlC = projectSite.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(urlC.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { if (inputLine.contains("<strong>Current version:")) { lastVersion = inputLine; break; } } in.close(); if (lastVersion != null && lastVersion.length() > 0) { lastVersion = lastVersion.substring(lastVersion.indexOf("Current version:") + 16); lastVersion = lastVersion.substring(0, lastVersion.indexOf("</strong>")).trim(); LOGGER.debug("last Version=" + lastVersion); } if (lastVersion.equals(getVersion())) LOGGER.debug("Not necessary to update"); else { LOGGER.debug("New update found!"); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (JOptionPane.showConfirmDialog(null, "New version of G15Lastfm is available to download!", "New Update for G15Lastfm", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { LOGGER.debug("User choose to update, opening browser."); Desktop desktop = Desktop.getDesktop(); try { desktop.browse(new URI("http://code.google.com/p/g15lastfm/")); } catch (IOException e) { LOGGER.debug(e); } catch (URISyntaxException e) { LOGGER.debug(e); } } else { LOGGER.debug("User choose to not update."); } } }); } } catch (Exception e) { LOGGER.debug(e); } } }.start(); }
11
Code Sample 1: protected void handleUrl(URL url) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String s; boolean moreResults = false; while ((s = in.readLine()) != null) { if (s.indexOf("<h1>Search Results</h1>") > -1) { System.err.println("found severals result"); moreResults = true; } else if (s.indexOf("Download <a href=") > -1) { if (s.indexOf("in JCAMP-DX format.") > -1) { System.err.println("download masspec"); super.handleUrl(new URL((url.getProtocol() + "://" + url.getHost() + s.substring(s.indexOf("\"") + 1, s.lastIndexOf("\""))).replaceAll("amp;", ""))); } moreResults = false; } if (moreResults == true) { if (s.indexOf("<li><a href=\"/cgi/cbook.cgi?ID") > -1) { System.err.println("\tdownloading new url " + new URL((url.getProtocol() + "://" + url.getHost() + s.substring(s.indexOf("\"") + 1, s.lastIndexOf("\""))).replaceAll("amp;", ""))); this.handleUrl(new URL((url.getProtocol() + "://" + url.getHost() + s.substring(s.indexOf("\"") + 1, s.lastIndexOf("\""))).replaceAll("amp;", ""))); } } } } Code Sample 2: @Test public void GetBingSearchResult() throws UnsupportedEncodingException { String query = "Scanner Java example"; String request = "http://api.bing.net/xml.aspx?AppId=731DD1E61BE6DE4601A3008DC7A0EB379149EC29" + "&Version=2.2&Market=en-US&Query=" + URLEncoder.encode(query, "UTF-8") + "&Sources=web+spell&Web.Count=50"; try { URL url = new URL(request); System.out.println("Host : " + url.getHost()); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; String finalContents = ""; while ((inputLine = reader.readLine()) != null) { finalContents += "\n" + inputLine; } Document doc = Jsoup.parse(finalContents); Elements eles = doc.getElementsByTag("web:Url"); for (Element ele : eles) { System.out.println(ele.text()); } } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: public static Set<Street> getVias(String pURL) { Set<Street> result = new HashSet<Street>(); String iniCuerr = "<cuerr>"; String finCuerr = "</cuerr>"; String iniDesErr = "<des>"; String finDesErr = "</des>"; String iniVia = "<calle>"; String finVia = "</calle>"; String iniCodVia = "<cv>"; String finCodVia = "</cv>"; String iniTipoVia = "<tv>"; String finTipoVia = "</tv>"; String iniNomVia = "<nv>"; String finNomVia = "</nv>"; boolean error = false; int ini, fin; try { URL url = new URL(pURL); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String str; Street via; while ((str = br.readLine()) != null) { if (str.contains(iniCuerr)) { ini = str.indexOf(iniCuerr) + iniCuerr.length(); fin = str.indexOf(finCuerr); if (Integer.parseInt(str.substring(ini, fin)) > 0) error = true; } if (error) { if (str.contains(iniDesErr)) { ini = str.indexOf(iniDesErr) + iniDesErr.length(); fin = str.indexOf(finDesErr); throw (new Exception(str.substring(ini, fin))); } } else { if (str.contains(iniVia)) { via = new Street(); while ((str = br.readLine()) != null && !str.contains(finVia)) { if (str.contains(iniCodVia)) { ini = str.indexOf(iniCodVia) + iniCodVia.length(); fin = str.indexOf(finCodVia); via.setCodeStreet(Integer.parseInt(str.substring(ini, fin))); } if (str.contains(iniTipoVia)) { TypeStreet tipo = new TypeStreet(); if (!str.contains(finTipoVia)) tipo.setCodetpStreet(""); else { ini = str.indexOf(iniTipoVia) + iniTipoVia.length(); fin = str.indexOf(finTipoVia); tipo.setCodetpStreet(str.substring(ini, fin)); } tipo.setDescription(getDescripcionTipoVia(tipo.getCodetpStreet())); via.setTypeStreet(tipo); } if (str.contains(iniNomVia)) { ini = str.indexOf(iniNomVia) + iniNomVia.length(); fin = str.indexOf(finNomVia); via.setStreetName(str.substring(ini, fin).trim()); } } result.add(via); } } } br.close(); } catch (Exception e) { System.err.println(e); } return result; } Code Sample 2: private String calculateMD5(String value) { String finalString; try { MessageDigest md5Alg = MessageDigest.getInstance("MD5"); md5Alg.reset(); md5Alg.update(value.getBytes()); byte messageDigest[] = md5Alg.digest(); StringBuilder hexString = new StringBuilder(256); for (int i = 0; i < messageDigest.length; i++) { String hex = Integer.toHexString(0xFF & messageDigest[i]); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } finalString = hexString.toString(); } catch (NoSuchAlgorithmException exc) { throw new RuntimeException("Hashing error happened:", exc); } return finalString; }
11
Code Sample 1: public File extractID3v2TagDataIntoFile(File outputFile) throws TagNotFoundException, IOException { int startByte = (int) ((MP3AudioHeader) audioHeader).getMp3StartByte(); if (startByte >= 0) { FileInputStream fis = new FileInputStream(file); FileChannel fc = fis.getChannel(); ByteBuffer bb = ByteBuffer.allocate(startByte); fc.read(bb); FileOutputStream out = new FileOutputStream(outputFile); out.write(bb.array()); out.close(); fc.close(); fis.close(); return outputFile; } throw new TagNotFoundException("There is no ID3v2Tag data in this file"); } 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 { closeQuietly(in); closeQuietly(out); } return success; }
11
Code Sample 1: public static final void main(String[] args) throws FileNotFoundException, IOException { ArrayList<String[]> result = new ArrayList<String[]>(); IStream is = new StreamImpl(); IOUtils.copy(new FileInputStream("H:\\7-项目预算表.xlsx"), is.getOutputStream()); int count = loadExcel(result, is, 0, 0, -1, 16, 1); System.out.println(count); for (String[] rs : result) { for (String r : rs) { System.out.print(r + "\t"); } System.out.println(); } } Code Sample 2: void copyFile(String src, String dest) throws IOException { int amount; byte[] buffer = new byte[4096]; FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dest); while ((amount = in.read(buffer)) != -1) out.write(buffer, 0, amount); in.close(); out.close(); }
00
Code Sample 1: private Document getDocument(URL url) throws SAXException, IOException { InputStream is; try { is = url.openStream(); } catch (IOException io) { System.out.println("parameter error : The specified reading data is mistaken."); System.out.println(" Request URL is " + sourceUri); throw new IOException("\t" + io.toString()); } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = null; try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException pce) { System.out.println("error : The error of DocumentBuilder instance generation"); throw new RuntimeException(pce.toString()); } Document doc; try { doc = builder.parse(is); } catch (Exception e) { System.out.println("error : parse of reading data went wrong."); System.out.println(" Request URL is " + sourceUri); throw new RuntimeException(e.toString()); } return doc; } Code Sample 2: public static final void copyFile(String srcFilename, String dstFilename) throws IOException { FileInputStream fis = null; FileOutputStream fos = null; FileChannel ifc = null; FileChannel ofc = null; Util.copyBuffer.clear(); try { fis = new FileInputStream(srcFilename); ifc = fis.getChannel(); fos = new FileOutputStream(dstFilename); ofc = fos.getChannel(); int sz = (int) ifc.size(); int n = 0; while (n < sz) { if (ifc.read(Util.copyBuffer) < 0) { break; } Util.copyBuffer.flip(); n += ofc.write(Util.copyBuffer); Util.copyBuffer.compact(); } } finally { try { if (ifc != null) { ifc.close(); } else if (fis != null) { fis.close(); } } catch (IOException exc) { } try { if (ofc != null) { ofc.close(); } else if (fos != null) { fos.close(); } } catch (IOException exc) { } } }
00
Code Sample 1: public final synchronized boolean isValidLicenseFile() throws LicenseNotSetupException { if (!isSetup()) { throw new LicenseNotSetupException(); } boolean returnValue = false; Properties properties = getLicenseFile(); logger.debug("isValidLicenseFile: License to validate:"); logger.debug(properties); StringBuffer validationStringBuffer = new StringBuffer(); validationStringBuffer.append(LICENSE_KEY_KEY + ":" + properties.getProperty(LICENSE_KEY_KEY) + ","); validationStringBuffer.append(LICENSE_FILE_STATUS_KEY + ":" + properties.getProperty(LICENSE_FILE_STATUS_KEY) + ","); validationStringBuffer.append(LICENSE_FILE_USERS_KEY + ":" + properties.getProperty(LICENSE_FILE_USERS_KEY) + ","); validationStringBuffer.append(LICENSE_FILE_MAC_KEY + ":" + properties.getProperty(LICENSE_FILE_MAC_KEY) + ","); validationStringBuffer.append(LICENSE_FILE_HOST_NAME_KEY + ":" + properties.getProperty(LICENSE_FILE_HOST_NAME_KEY) + ","); validationStringBuffer.append(LICENSE_FILE_OFFSET_KEY + ":" + properties.getProperty(LICENSE_FILE_OFFSET_KEY) + ","); validationStringBuffer.append(LICENSE_FILE_EXP_DATE_KEY + ":" + properties.getProperty(LICENSE_FILE_EXP_DATE_KEY) + ","); validationStringBuffer.append(LICENSE_EXPIRES_KEY + ":" + properties.getProperty(LICENSE_EXPIRES_KEY)); logger.debug("isValidLicenseFile: Validation String Buffer: " + validationStringBuffer.toString()); String validationKey = (String) properties.getProperty(LICENSE_FILE_SHA_KEY); try { MessageDigest messageDigest = MessageDigest.getInstance("SHA-1"); messageDigest.update(validationStringBuffer.toString().getBytes()); String newValidation = Base64.encode(messageDigest.digest()); if (newValidation.equals(validationKey)) { if (getMACAddress().equals(Settings.getInstance().getMACAddress())) { returnValue = true; } } } catch (Exception exception) { System.out.println("Exception in LicenseInstanceVO.isValidLicenseFile"); } return returnValue; } Code Sample 2: @Override public InputStream getResourceStream(final String arg0) throws ResourceNotFoundException { try { final ServletContext context = CContext.getInstance().getContext(); final URL url = context.getResource(arg0); return url.openStream(); } catch (final Exception e) { return null; } }
11
Code Sample 1: @Override public void execute(String[] args) throws Exception { Options cmdLineOptions = getCommandOptions(); try { GnuParser parser = new GnuParser(); CommandLine commandLine = parser.parse(cmdLineOptions, TolvenPlugin.getInitArgs()); String srcRepositoryURLString = commandLine.getOptionValue(CMD_LINE_SRC_REPOSITORYURL_OPTION); Plugins libraryPlugins = RepositoryMetadata.getRepositoryPlugins(new URL(srcRepositoryURLString)); String srcPluginId = commandLine.getOptionValue(CMD_LINE_SRC_PLUGIN_ID_OPTION); PluginDetail plugin = RepositoryMetadata.getPluginDetail(srcPluginId, libraryPlugins); if (plugin == null) { throw new RuntimeException("Could not locate plugin: " + srcPluginId + " in repository: " + srcRepositoryURLString); } String srcPluginVersionString = commandLine.getOptionValue(CMD_LINE_SRC_PLUGIN_VERSION_OPTION); PluginVersionDetail srcPluginVersion = null; if (srcPluginVersion == null) { srcPluginVersion = RepositoryMetadata.getLatestVersion(plugin); } else { srcPluginVersion = RepositoryMetadata.getPluginVersionDetail(srcPluginVersionString, plugin); } if (plugin == null) { throw new RuntimeException("Could not find a plugin version for: " + srcPluginId + " in repository: " + srcRepositoryURLString); } String destPluginId = commandLine.getOptionValue(CMD_LINE_DEST_PLUGIN_ID_OPTION); FileUtils.deleteDirectory(getPluginTmpDir()); URL srcURL = new URL(srcPluginVersion.getUri()); File newPluginDir = new File(getPluginTmpDir(), destPluginId); try { InputStream in = null; FileOutputStream out = null; File tmpZip = new File(getPluginTmpDir(), new File(srcURL.getFile()).getName()); try { in = srcURL.openStream(); out = new FileOutputStream(tmpZip); IOUtils.copy(in, out); TolvenZip.unzip(tmpZip, newPluginDir); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } if (tmpZip != null) { tmpZip.delete(); } } File pluginManifestFile = new File(newPluginDir, "tolven-plugin.xml"); if (!pluginManifestFile.exists()) { throw new RuntimeException(srcURL.toExternalForm() + "has no plugin manifest"); } Plugin pluginManifest = RepositoryMetadata.getPlugin(pluginManifestFile.toURI().toURL()); pluginManifest.setId(destPluginId); String destPluginVersion = commandLine.getOptionValue(CMD_LINE_DEST_PLUGIN_VERSION_OPTION); if (destPluginVersion == null) { destPluginVersion = DEFAULT_DEST_VERSION; } pluginManifest.setVersion(destPluginVersion); String pluginManifestXML = RepositoryMetadata.getPluginManifest(pluginManifest); FileUtils.writeStringToFile(pluginManifestFile, pluginManifestXML); File pluginFragmentManifestFile = new File(newPluginDir, "tolven-plugin-fragment.xml"); if (pluginFragmentManifestFile.exists()) { PluginFragment pluginManifestFragment = RepositoryMetadata.getPluginFragment(pluginFragmentManifestFile.toURI().toURL()); Requires requires = pluginManifestFragment.getRequires(); if (requires == null) { throw new RuntimeException("No <requires> detected for plugin fragment in: " + srcURL.toExternalForm()); } if (requires.getImport().size() != 1) { throw new RuntimeException("There should be only one import for plugin fragment in: " + srcURL.toExternalForm()); } requires.getImport().get(0).setPluginId(destPluginId); requires.getImport().get(0).setPluginVersion(destPluginVersion); String pluginFragmentManifestXML = RepositoryMetadata.getPluginFragmentManifest(pluginManifestFragment); FileUtils.writeStringToFile(pluginFragmentManifestFile, pluginFragmentManifestXML); } String destDirname = commandLine.getOptionValue(CMD_LINE_DEST_DIR_OPTION); File destDir = new File(destDirname); File destZip = new File(destDir, destPluginId + "-" + destPluginVersion + ".zip"); destDir.mkdirs(); TolvenZip.zip(newPluginDir, destZip); } finally { if (newPluginDir != null) { FileUtils.deleteDirectory(newPluginDir); } } } catch (ParseException ex) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(getClass().getName(), cmdLineOptions); throw new RuntimeException("Could not parse command line for: " + getClass().getName(), ex); } } Code Sample 2: public void run() { Pair p = null; try { while ((p = queue.pop()) != null) { GetMethod get = new GetMethod(p.getRemoteUri()); try { get.setFollowRedirects(true); get.setRequestHeader("Mariner-Application", "prerenderer"); get.setRequestHeader("Mariner-DeviceName", deviceName); int iGetResultCode = httpClient.executeMethod(get); if (iGetResultCode != 200) { throw new IOException("Got response code " + iGetResultCode + " for a request for " + p.getRemoteUri()); } InputStream is = get.getResponseBodyAsStream(); File localFile = new File(deviceFile, p.getLocalUri()); localFile.getParentFile().mkdirs(); OutputStream os = new FileOutputStream(localFile); IOUtils.copy(is, os); os.close(); } finally { get.releaseConnection(); } } } catch (Exception ex) { result = ex; } }
00
Code Sample 1: public static String scramble(String text) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(text.getBytes("UTF-8")); StringBuffer sb = new StringBuffer(); for (byte b : md.digest()) sb.append(Integer.toString(b & 0xFF, 16)); return sb.toString(); } catch (UnsupportedEncodingException e) { return null; } catch (NoSuchAlgorithmException e) { return null; } } Code Sample 2: public void copy(final File source, final File dest) throws IOException { final FileInputStream in = new FileInputStream(source); try { final FileOutputStream out = new FileOutputStream(dest); try { final FileChannel inChannel = in.getChannel(); final FileChannel outChannel = out.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } finally { out.close(); } } finally { in.close(); } }
11
Code Sample 1: private void copyFile(String from, String to) throws Exception { URL monitorCallShellScriptUrl = Thread.currentThread().getContextClassLoader().getResource(from); File inScriptFile = null; try { inScriptFile = new File(monitorCallShellScriptUrl.toURI()); } catch (URISyntaxException e) { throw e; } File outScriptFile = new File(to); FileChannel inChannel = new FileInputStream(inScriptFile).getChannel(); FileChannel outChannel = new FileOutputStream(outScriptFile).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } try { LinuxCommandExecutor cmdExecutor = new LinuxCommandExecutor(); cmdExecutor.setWorkingDirectory(workingDirectory); cmdExecutor.runCommand("chmod 777 " + to); } catch (Exception e) { throw e; } } Code Sample 2: public static void copyDirectory(File sourceDirectory, File targetDirectory) throws IOException { File[] sourceFiles = sourceDirectory.listFiles(FILE_FILTER); File[] sourceDirectories = sourceDirectory.listFiles(DIRECTORY_FILTER); targetDirectory.mkdirs(); if (sourceFiles != null && sourceFiles.length > 0) { for (int i = 0; i < sourceFiles.length; i++) { File sourceFile = sourceFiles[i]; FileInputStream fis = new FileInputStream(sourceFile); FileOutputStream fos = new FileOutputStream(targetDirectory + File.separator + sourceFile.getName()); FileChannel fcin = fis.getChannel(); FileChannel fcout = fos.getChannel(); ByteBuffer buf = ByteBuffer.allocateDirect(8192); long size = fcin.size(); long n = 0; while (n < size) { buf.clear(); if (fcin.read(buf) < 0) { break; } buf.flip(); n += fcout.write(buf); } fcin.close(); fcout.close(); fis.close(); fos.close(); } } if (sourceDirectories != null && sourceDirectories.length > 0) { for (int i = 0; i < sourceDirectories.length; i++) { File directory = sourceDirectories[i]; File newTargetDirectory = new File(targetDirectory, directory.getName()); copyDirectory(directory, newTargetDirectory); } } }