label
class label 2
classes | source_code
stringlengths 398
72.9k
|
---|---|
00
|
Code Sample 1:
public ICCColorSpaceExt createICCColorSpaceExt(BridgeContext ctx, Element paintedElement, String iccProfileName) { ICCColorSpaceExt cs = cache.request(iccProfileName.toLowerCase()); if (cs != null) { return cs; } Document doc = paintedElement.getOwnerDocument(); NodeList list = doc.getElementsByTagNameNS(SVG_NAMESPACE_URI, SVG_COLOR_PROFILE_TAG); int n = list.getLength(); Element profile = null; for (int i = 0; i < n; i++) { Node node = list.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element profileNode = (Element) node; String nameAttr = profileNode.getAttributeNS(null, SVG_NAME_ATTRIBUTE); if (iccProfileName.equalsIgnoreCase(nameAttr)) { profile = profileNode; } } } if (profile == null) return null; String href = XLinkSupport.getXLinkHref(profile); ICC_Profile p = null; if (href != null) { String baseURI = ((SVGOMDocument) doc).getURL(); ParsedURL purl = new ParsedURL(baseURI, href); if (!purl.complete()) throw new BridgeException(paintedElement, ERR_URI_MALFORMED, new Object[] { href }); try { ParsedURL pDocURL = null; if (baseURI != null) { pDocURL = new ParsedURL(baseURI); } ctx.getUserAgent().checkLoadExternalResource(purl, pDocURL); p = ICC_Profile.getInstance(purl.openStream()); } catch (IOException e) { throw new BridgeException(paintedElement, ERR_URI_IO, new Object[] { href }); } catch (SecurityException e) { throw new BridgeException(paintedElement, ERR_URI_UNSECURE, new Object[] { href }); } } if (p == null) { return null; } int intent = convertIntent(profile); cs = new ICCColorSpaceExt(p, intent); cache.put(iccProfileName.toLowerCase(), cs); return cs; }
Code Sample 2:
public static String getEncryptedPwd(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException { byte[] pwd = null; SecureRandom random = new SecureRandom(); byte[] salt = new byte[SALT_LENGTH]; random.nextBytes(salt); MessageDigest md = null; md = MessageDigest.getInstance("MD5"); md.update(salt); md.update(password.getBytes("UTF-8")); byte[] digest = md.digest(); pwd = new byte[digest.length + SALT_LENGTH]; System.arraycopy(salt, 0, pwd, 0, SALT_LENGTH); System.arraycopy(digest, 0, pwd, SALT_LENGTH, digest.length); return byteToHexString(pwd); }
|
00
|
Code Sample 1:
public static org.osid.repository.AssetIterator search(Repository repository, SearchCriteria lSearchCriteria) throws org.osid.repository.RepositoryException { try { NodeList fieldNode = null; if (lSearchCriteria.getSearchOperation() == SearchCriteria.FIND_OBJECTS) { URL url = new URL("http", repository.getAddress(), repository.getPort(), SEARCH_STRING + URLEncoder.encode(lSearchCriteria.getKeywords() + WILDCARD, "ISO-8859-1")); XPathFactory factory = XPathFactory.newInstance(); XPath xPath = factory.newXPath(); xPath.setNamespaceContext(new FedoraNamespaceContext()); InputSource inputSource = new InputSource(url.openStream()); fieldNode = (NodeList) xPath.evaluate("/pre:result/pre:resultList/pre:objectFields", inputSource, XPathConstants.NODESET); if (fieldNode.getLength() > 0) { inputSource = new InputSource(url.openStream()); XPathExpression xSession = xPath.compile("//pre:token/text()"); String token = xSession.evaluate(inputSource); lSearchCriteria.setToken(token); } } return getAssetIterator(repository, fieldNode); } catch (Throwable t) { throw wrappedException("search", t); } }
Code Sample 2:
public String fileUpload(final ResourceType type, final String currentFolder, final String fileName, final InputStream inputStream) throws InvalidCurrentFolderException, WriteException { String absolutePath = getRealUserFilesAbsolutePath(RequestCycleHandler.getUserFilesAbsolutePath(ThreadLocalData.getRequest())); File typeDir = getOrCreateResourceTypeDir(absolutePath, type); File currentDir = new File(typeDir, currentFolder); if (!currentDir.exists() || !currentDir.isDirectory()) throw new InvalidCurrentFolderException(); File newFile = new File(currentDir, fileName); File fileToSave = UtilsFile.getUniqueFile(newFile.getAbsoluteFile()); try { IOUtils.copyLarge(inputStream, new FileOutputStream(fileToSave)); } catch (IOException e) { throw new WriteException(); } return fileToSave.getName(); }
|
00
|
Code Sample 1:
public static void bubbleSort(Auto[] xs) { boolean unsorted = true; while (unsorted) { unsorted = false; for (int i = 0; i < xs.length - 1; i++) { if (!(xs[i].getPreis() >= xs[i + 1].getPreis())) { Auto dummy = xs[i]; xs[i] = xs[i + 1]; xs[i + 1] = dummy; unsorted = true; } } } }
Code Sample 2:
protected InputSource getInputSource(URL url, AtomicReference<Date> checkModifiedDate) throws IOException { String proto = url.getProtocol().toLowerCase(Locale.ENGLISH); if (!("http".equals(proto) || "https".equals(proto))) throw new IllegalArgumentException("OAI only allows HTTP(S) as network protocol!"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(timeout * 1000); conn.setReadTimeout(timeout * 1000); StringBuilder ua = new StringBuilder("Java/").append(System.getProperty("java.version")).append(" (").append(de.pangaea.metadataportal.Package.getProductName()).append('/').append(de.pangaea.metadataportal.Package.getVersion()).append("; OAI downloader)"); conn.setRequestProperty("User-Agent", ua.toString()); conn.setRequestProperty("Accept-Encoding", "gzip, deflate, identity;q=0.3, *;q=0"); conn.setRequestProperty("Accept-Charset", "utf-8, *;q=0.1"); conn.setRequestProperty("Accept", "text/xml, application/xml, *;q=0.1"); if (checkModifiedDate != null && checkModifiedDate.get() != null) conn.setIfModifiedSince(checkModifiedDate.get().getTime()); conn.setUseCaches(false); conn.setFollowRedirects(true); log.debug("Opening connection..."); InputStream in = null; try { conn.connect(); in = conn.getInputStream(); } catch (IOException ioe) { int after, code; try { after = conn.getHeaderFieldInt("Retry-After", -1); code = conn.getResponseCode(); } catch (IOException ioe2) { after = -1; code = -1; } if (code == HttpURLConnection.HTTP_UNAVAILABLE && after > 0) throw new RetryAfterIOException(after, ioe); throw ioe; } if (checkModifiedDate != null) { if (conn.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) { log.debug("File not modified since " + checkModifiedDate.get()); if (in != null) in.close(); return null; } long d = conn.getLastModified(); checkModifiedDate.set((d == 0L) ? null : new Date(d)); } String encoding = conn.getContentEncoding(); if (encoding == null) encoding = "identity"; encoding = encoding.toLowerCase(Locale.ENGLISH); log.debug("HTTP server uses " + encoding + " content encoding."); if ("gzip".equals(encoding)) in = new GZIPInputStream(in); else if ("deflate".equals(encoding)) in = new InflaterInputStream(in); else if (!"identity".equals(encoding)) throw new IOException("Server uses an invalid content encoding: " + encoding); String contentType = conn.getContentType(); String charset = null; if (contentType != null) { contentType = contentType.toLowerCase(Locale.ENGLISH); int charsetStart = contentType.indexOf("charset="); if (charsetStart >= 0) { int charsetEnd = contentType.indexOf(";", charsetStart); if (charsetEnd == -1) charsetEnd = contentType.length(); charsetStart += "charset=".length(); charset = contentType.substring(charsetStart, charsetEnd).trim(); } } log.debug("Charset from Content-Type: '" + charset + "'"); InputSource src = new InputSource(in); src.setSystemId(url.toString()); src.setEncoding(charset); return src; }
|
11
|
Code Sample 1:
public void connected(String address, int port) { connected = true; try { if (localConnection) { byte key[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; si.setEncryptionKey(key); } else { saveData(address, port); MessageDigest mds = MessageDigest.getInstance("SHA"); mds.update(connectionPassword.getBytes("UTF-8")); si.setEncryptionKey(mds.digest()); } if (!si.login(username, password)) { si.disconnect(); connected = false; showErrorMessage(this, "Authentication Failure"); restore(); return; } SwingUtilities.invokeLater(new Runnable() { public void run() { connectionLabel.setText(""); progressLabel = new JLabel("Loading... Please wait."); progressLabel.setOpaque(true); progressLabel.setBackground(Color.white); replaceComponent(progressLabel); cancelButton.setEnabled(true); xx.remove(helpButton); } }); } catch (Exception e) { System.out.println("connected: Exception: " + e + "\r\n"); } ; }
Code Sample 2:
public static String getMD5Hash(String data) { MessageDigest digest; try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(data.getBytes()); byte[] hash = digest.digest(); StringBuffer hexString = new StringBuffer(); String hexChar = ""; for (int i = 0; i < hash.length; i++) { hexChar = Integer.toHexString(0xFF & hash[i]); if (hexChar.length() < 2) { hexChar = "0" + hexChar; } hexString.append(hexChar); } return hexString.toString(); } catch (NoSuchAlgorithmException ex) { return null; } }
|
11
|
Code Sample 1:
public void onMessage(Message message) { LOG.debug("onMessage"); DownloadMessage downloadMessage; try { downloadMessage = new DownloadMessage(message); } catch (JMSException e) { LOG.error("JMS error: " + e.getMessage(), e); return; } String caName = downloadMessage.getCaName(); boolean update = downloadMessage.isUpdate(); LOG.debug("issuer: " + caName); CertificateAuthorityEntity certificateAuthority = this.certificateAuthorityDAO.findCertificateAuthority(caName); if (null == certificateAuthority) { LOG.error("unknown certificate authority: " + caName); return; } if (!update && Status.PROCESSING != certificateAuthority.getStatus()) { LOG.debug("CA status not marked for processing"); return; } String crlUrl = certificateAuthority.getCrlUrl(); if (null == crlUrl) { LOG.warn("No CRL url for CA " + certificateAuthority.getName()); certificateAuthority.setStatus(Status.NONE); return; } NetworkConfig networkConfig = this.configurationDAO.getNetworkConfig(); HttpClient httpClient = new HttpClient(); if (null != networkConfig) { httpClient.getHostConfiguration().setProxy(networkConfig.getProxyHost(), networkConfig.getProxyPort()); } HttpClientParams httpClientParams = httpClient.getParams(); httpClientParams.setParameter("http.socket.timeout", new Integer(1000 * 20)); LOG.debug("downloading CRL from: " + crlUrl); GetMethod getMethod = new GetMethod(crlUrl); getMethod.addRequestHeader("User-Agent", "jTrust CRL Client"); int statusCode; try { statusCode = httpClient.executeMethod(getMethod); } catch (Exception e) { downloadFailed(caName, crlUrl); throw new RuntimeException(); } if (HttpURLConnection.HTTP_OK != statusCode) { LOG.debug("HTTP status code: " + statusCode); downloadFailed(caName, crlUrl); throw new RuntimeException(); } String crlFilePath; File crlFile = null; try { crlFile = File.createTempFile("crl-", ".der"); InputStream crlInputStream = getMethod.getResponseBodyAsStream(); OutputStream crlOutputStream = new FileOutputStream(crlFile); IOUtils.copy(crlInputStream, crlOutputStream); IOUtils.closeQuietly(crlInputStream); IOUtils.closeQuietly(crlOutputStream); crlFilePath = crlFile.getAbsolutePath(); LOG.debug("temp CRL file: " + crlFilePath); } catch (IOException e) { downloadFailed(caName, crlUrl); if (null != crlFile) { crlFile.delete(); } throw new RuntimeException(e); } try { this.notificationService.notifyHarvester(caName, crlFilePath, update); } catch (JMSException e) { crlFile.delete(); throw new RuntimeException(e); } }
Code Sample 2:
@Test public void testCopy_inputStreamToWriter_nullIn() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); try { IOUtils.copy((InputStream) null, writer); fail(); } catch (NullPointerException ex) { } }
|
00
|
Code Sample 1:
private int getRootNodeId(DataSource dataSource) throws SQLException { Connection conn = null; Statement st = null; ResultSet rs = null; String query = null; try { conn = dataSource.getConnection(); st = conn.createStatement(); query = "select " + col.id + " from " + DB.Tbl.tree + " where " + col.parentId + " is null"; rs = st.executeQuery(query); while (rs.next()) { return rs.getInt(col.id); } query = "insert into " + DB.Tbl.tree + "(" + col.lKey + ", " + col.rKey + ", " + col.level + ") values(1,2,0)"; st.executeUpdate(query, new String[] { col.id }); rs = st.getGeneratedKeys(); while (rs.next()) { int genId = rs.getInt(1); rs.close(); conn.commit(); return genId; } throw new SQLException("Не удается создать корневой элемент для дерева."); } finally { try { rs.close(); } catch (Exception e) { } try { st.close(); } catch (Exception e) { } try { conn.rollback(); } catch (Exception e) { } try { conn.close(); } catch (Exception e) { } } }
Code Sample 2:
@Test public void testRegister() { try { String username = "muchu"; String password = "123"; MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); String passwordMd5 = new String(md5.digest()); LogService logServiceMock = EasyMock.createMock(LogService.class); DbService dbServiceMock = EasyMock.createMock(DbService.class); userServ.setDbServ(dbServiceMock); userServ.setLogger(logServiceMock); IFeelerUser user = new FeelerUserImpl(); user.setUsername(username); user.setPassword(passwordMd5); logServiceMock.info(DbUserServiceImpl.class, ">>>rigister " + username + "<<<"); EasyMock.expect(dbServiceMock.queryFeelerUser(username)).andReturn(null); dbServiceMock.addFeelerUser(username, passwordMd5); logServiceMock.info(DbUserServiceImpl.class, ">>>identification " + username + "<<<"); EasyMock.expect(dbServiceMock.queryFeelerUser(username)).andReturn(user); EasyMock.replay(dbServiceMock, logServiceMock); Assert.assertTrue(userServ.register(username, password)); EasyMock.verify(dbServiceMock, logServiceMock); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
public static void unzip(File sourceZipFile, File unzipDestinationDirectory, FileFilter filter) throws IOException { unzipDestinationDirectory.mkdirs(); if (!unzipDestinationDirectory.exists()) { throw new IOException("Unable to create destination directory: " + unzipDestinationDirectory); } ZipFile zipFile; zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ); Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries(); while (zipFileEntries.hasMoreElements()) { ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); if (!entry.isDirectory()) { String currentEntry = entry.getName(); File destFile = new File(unzipDestinationDirectory, currentEntry); if (filter == null || filter.accept(destFile)) { File destinationParent = destFile.getParentFile(); destinationParent.mkdirs(); BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry)); FileOutputStream fos = new FileOutputStream(destFile); IOUtils.copyLarge(is, fos); fos.flush(); IOUtils.closeQuietly(fos); } } } zipFile.close(); }
Code Sample 2:
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) throw new IOException("Destination '" + destFile + "' exists but is a directory"); FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); if (preserveFileDate) destFile.setLastModified(srcFile.lastModified()); }
|
11
|
Code Sample 1:
public static String hashMD5(String password) { String hashword = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); hashword = hash.toString(16); } catch (NoSuchAlgorithmException nsae) { } return hashword; }
Code Sample 2:
private String getMD5Str(String str) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(str.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } return md5StrBuff.toString(); }
|
11
|
Code Sample 1:
static Object executeMethod(HttpMethod method, int timeout, boolean array) throws HttpRequestFailureException, HttpException, IOException, HttpRequestTimeoutException { try { method.getParams().setSoTimeout(timeout * 1000); int status = -1; Object result = null; System.out.println("Execute method: " + method.getPath() + " " + method.getQueryString()); TwitterclipseConfig config = TwitterclipsePlugin.getDefault().getTwitterclipseConfiguration(); HttpClient httpClient = HttpClientUtils.createHttpClient(TWITTER_BASE_URL, config.getUserId(), config.getPassword()); status = httpClient.executeMethod(method); System.out.println("Received response. status = " + status); if (status == HttpStatus.SC_OK) { InputStream inputStream = method.getResponseBodyAsStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(inputStream, baos); String response = new String(baos.toByteArray(), "UTF-8"); System.out.println(response); if (array) result = JSONArray.fromString(response); else result = JSONObject.fromString(response); } else { throw new HttpRequestFailureException(status); } return result; } catch (SocketTimeoutException e) { throw new HttpRequestTimeoutException(e); } finally { method.releaseConnection(); } }
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; } }
|
00
|
Code Sample 1:
static JSONObject executeMethod(HttpClient httpClient, HttpMethod method, int timeout) throws HttpRequestFailureException, HttpException, IOException, HttpRequestTimeoutException { try { method.getParams().setSoTimeout(timeout * 1000); int status = -1; JSONObject result = null; for (int i = 0; i < RETRY; i++) { System.out.println("Execute method[" + method.getURI() + "](try " + (i + 1) + ")"); status = httpClient.executeMethod(method); if (status == HttpStatus.SC_OK) { InputStream inputStream = method.getResponseBodyAsStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(inputStream, baos); String response = new String(baos.toByteArray(), "UTF-8"); System.out.println(response); result = JSONObject.fromString(response); if (result.has("status")) { String lingrStatus = result.getString("status"); if ("ok".equals(lingrStatus)) { break; } else { try { Thread.sleep(1000); } catch (InterruptedException e) { } } } } else { throw new HttpRequestFailureException(status); } } return result; } catch (SocketTimeoutException e) { throw new HttpRequestTimeoutException(e); } finally { method.releaseConnection(); } }
Code Sample 2:
public void process(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { String UrlStr = req.getRequestURL().toString(); URL domainurl = new URL(UrlStr); domain = domainurl.getHost(); pathinfo = req.getPathInfo(); String user_agent = req.getHeader("user-agent"); UserAgent userAgent = UserAgent.parseUserAgentString(user_agent); String browser = userAgent.getBrowser().getName(); String[] shot_domain_array = domain.split("\\."); shot_domain = shot_domain_array[1] + "." + shot_domain_array[2]; if (browser.equalsIgnoreCase("Robot/Spider") || browser.equalsIgnoreCase("Lynx") || browser.equalsIgnoreCase("Downloading Tool")) { JSONObject domainJsonObject = CsvReader.CsvReader("domainparUpdated.csv", shot_domain); log.info(domainJsonObject.toString()); } else { String title; String locale; String facebookid; String color; String headImage; String google_ad_client; String google_ad_slot1; String google_ad_width1; String google_ad_height1; String google_ad_slot2; String google_ad_width2; String google_ad_height2; String google_ad_slot3; String google_ad_width3; String google_ad_height3; String countrycode = null; String city = null; String gmclickval = null; String videos = null; int intcount = 0; String strcount = "0"; boolean countExist = false; Cookie[] cookies = req.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals("count")) { strcount = cookies[i].getValue(); if (strcount != null && strcount.length() > 0) { log.info("Check count " + strcount + " path " + cookies[i].getPath()); intcount = Integer.parseInt(strcount); intcount++; } else { intcount = 1; } log.info("New count " + intcount); LongLivedCookie count = new LongLivedCookie("count", Integer.toString(intcount)); resp.addCookie(count); countExist = true; } if (cookies[i].getName().equals("countrycode")) { countrycode = cookies[i].getValue(); } if (cookies[i].getName().equals("city")) { city = cookies[i].getValue(); } if (cookies[i].getName().equals("videos")) { videos = cookies[i].getValue(); log.info("Welcome videos " + videos); } if (cookies[i].getName().equals("gmclick")) { log.info("gmclick exist!!"); gmclickval = cookies[i].getValue(); if (intcount % 20 == 0 && intcount > 0) { log.info("Cancell gmclick -> " + gmclickval + " intcount " + intcount + " path " + cookies[i].getPath()); Cookie gmclick = new Cookie("gmclick", "0"); gmclick.setPath("/"); gmclick.setMaxAge(0); resp.addCookie(gmclick); } } } if (!countExist) { LongLivedCookie count = new LongLivedCookie("count", "0"); resp.addCookie(count); log.info(" Not First visit count Don't Exist!!"); } if (videos == null) { LongLivedCookie videoscookies = new LongLivedCookie("videos", "0"); resp.addCookie(videoscookies); log.info("Not First visit VIDEOS Don't Exist!!"); } } else { LongLivedCookie count = new LongLivedCookie("count", strcount); resp.addCookie(count); LongLivedCookie videosfirstcookies = new LongLivedCookie("videos", "0"); resp.addCookie(videosfirstcookies); log.info("First visit count = " + intcount + " videos 0"); } String[] dompar = CommUtils.CsvParsing(domain, "domainpar.csv"); title = dompar[0]; locale = dompar[1]; facebookid = dompar[2]; color = dompar[3]; headImage = dompar[4]; google_ad_client = dompar[5]; google_ad_slot1 = dompar[6]; google_ad_width1 = dompar[7]; google_ad_height1 = dompar[8]; google_ad_slot2 = dompar[9]; google_ad_width2 = dompar[10]; google_ad_height2 = dompar[11]; google_ad_slot3 = dompar[12]; google_ad_width3 = dompar[13]; google_ad_height3 = dompar[14]; String ip = req.getRemoteHost(); if ((countrycode == null) || (city == null)) { String ipServiceCall = "http://api.ipinfodb.com/v2/ip_query.php?key=abbb04fd823793c5343a046e5d56225af37861b9020e9bc86313eb20486b6133&ip=" + ip + "&output=json"; String strCallResult = ""; URL url = new URL(ipServiceCall); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF8")); StringBuffer response = new StringBuffer(); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); strCallResult = response.toString(); try { JSONObject jso = new JSONObject(strCallResult); log.info("Status -> " + jso.get("Status").toString()); log.info("City -> " + jso.get("City").toString()); city = jso.get("City").toString(); countrycode = jso.get("CountryCode").toString(); log.info("countrycode -> " + countrycode); if ((city.length() == 0) || (city == null)) { LongLivedCookie cookcity = new LongLivedCookie("city", "Helsinki"); resp.addCookie(cookcity); city = "Helsinki"; } else { LongLivedCookie cookcity = new LongLivedCookie("city", city); resp.addCookie(cookcity); } if (countrycode.length() == 0 || (countrycode == null) || countrycode.equals("RD")) { LongLivedCookie cookcountrycode = new LongLivedCookie("countrycode", "FI"); resp.addCookie(cookcountrycode); countrycode = "FI"; } else { LongLivedCookie cookcountrycode = new LongLivedCookie("countrycode", countrycode); resp.addCookie(cookcountrycode); } } catch (JSONException e) { log.severe(e.getMessage()); } finally { if ((countrycode == null) || (city == null)) { log.severe("need use finally!!!"); countrycode = "FI"; city = "Helsinki"; LongLivedCookie cookcity = new LongLivedCookie("city", "Helsinki"); resp.addCookie(cookcity); LongLivedCookie cookcountrycode = new LongLivedCookie("countrycode", "FI"); resp.addCookie(cookcountrycode); } } } JSONArray startjsonarray = new JSONArray(); JSONArray memjsonarray = new JSONArray(); Map<String, Object> map = new HashMap<String, Object>(); Map<String, Object> mapt = new HashMap<String, Object>(); mapt.put("img", headImage); mapt.put("color", color); mapt.put("title", title); mapt.put("locale", locale); mapt.put("domain", domain); mapt.put("facebookid", facebookid); mapt.put("ip", ip); mapt.put("countrycode", countrycode); mapt.put("city", city); map.put("theme", mapt); startjsonarray.put(map); String[] a = { "mem0", "mem20", "mem40", "mem60", "mem80", "mem100", "mem120", "mem140", "mem160", "mem180" }; List memlist = Arrays.asList(a); Collections.shuffle(memlist); Map<String, Object> mammap = new HashMap<String, Object>(); mammap.put("memlist", memlist); memjsonarray.put(mammap); log.info(memjsonarray.toString()); resp.setContentType("text/html"); resp.setCharacterEncoding("UTF-8"); PrintWriter out = resp.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">"); out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:fb=\"http://www.facebook.com/2008/fbml\">"); out.println("<head>"); out.println("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">"); out.println("<meta name=\"gwt:property\" content=\"locale=" + locale + "\">"); out.println("<link type=\"text/css\" rel=\"stylesheet\" href=\"NewTube.css\">"); out.println("<title>" + title + "</title>"); out.println("<script type=\"text/javascript\" language=\"javascript\" src=\"newtube/newtube.nocache.js\"></script>"); out.println("<script type='text/javascript'>var jsonStartParams = " + startjsonarray.toString() + ";</script>"); out.println("<script type='text/javascript'>var girlsphones = " + CommUtils.CsvtoJson("girlsphones.csv").toString() + ";</script>"); out.println("<script type='text/javascript'>"); out.println("var mem = " + memjsonarray.toString() + ";"); out.println("</script>"); out.println("</head>"); out.println("<body>"); out.println("<div id='fb-root'></div>"); out.println("<script>"); out.println("window.fbAsyncInit = function() {"); out.println("FB.init({appId: '" + facebookid + "', status: true, cookie: true,xfbml: true});};"); out.println("(function() {"); out.println("var e = document.createElement('script'); e.async = true;"); out.println("e.src = document.location.protocol +"); out.println("'//connect.facebook.net/" + locale + "/all.js';"); out.println("document.getElementById('fb-root').appendChild(e);"); out.println("}());"); out.println("</script>"); out.println("<div id=\"start\"></div>"); out.println("<div id=\"seo_content\">"); BufferedReader bufRdr = new BufferedReader(new InputStreamReader(new FileInputStream(domain + ".html"), "UTF8")); String contline = null; while ((contline = bufRdr.readLine()) != null) { out.println(contline); } bufRdr.close(); if (countrycode != null && !countrycode.equalsIgnoreCase("US") && !countrycode.equalsIgnoreCase("IE") && !countrycode.equalsIgnoreCase("UK") && intcount > 2 && intcount < 51) { out.println("<script type=\"text/javascript\"><!--"); out.println("google_ad_client = \"" + google_ad_client + "\";"); out.println("google_ad_slot = \"" + google_ad_slot1 + "\";"); out.println("google_ad_width = " + google_ad_width1 + ";"); out.println("google_ad_height = " + google_ad_height1 + ";"); out.println("//-->"); out.println("</script>"); out.println("<script type=\"text/javascript\""); out.println("src=\"" + google_ad_client + ".js\">"); out.println("</script>"); out.println("<script type=\"text/javascript\"><!--"); out.println("google_ad_client = \"" + google_ad_client + "\";"); out.println("google_ad_slot = \"" + google_ad_slot2 + "\";"); out.println("google_ad_width = " + google_ad_width2 + ";"); out.println("google_ad_height = " + google_ad_height2 + ";"); out.println("//-->"); out.println("</script>"); out.println("<script type=\"text/javascript\""); out.println("src=\"" + google_ad_client + ".js\">"); out.println("</script>"); out.println("<script type=\"text/javascript\"><!--"); out.println("google_ad_client = \"" + google_ad_client + "\";"); out.println("google_ad_slot = \"" + google_ad_slot3 + "\";"); out.println("google_ad_width = " + google_ad_width3 + ";"); out.println("google_ad_height = " + google_ad_height3 + ";"); out.println("//-->"); out.println("</script>"); out.println("<script type=\"text/javascript\""); out.println("src=\"" + google_ad_client + ".js\">"); out.println("</script>"); } if (countrycode != null && !countrycode.equalsIgnoreCase("US") && !countrycode.equalsIgnoreCase("IE") && !countrycode.equalsIgnoreCase("UK") && intcount > 50) { out.println("<script type=\"text/javascript\"><!--"); out.println("google_ad_client = \"" + "pub-9496078135369870" + "\";"); out.println("google_ad_slot = \"" + "8683942065" + "\";"); out.println("google_ad_width = " + "160" + ";"); out.println("google_ad_height = " + "600" + ";"); out.println("//-->"); out.println("</script>"); out.println("<script type=\"text/javascript\""); out.println("src=\"pub-9496078135369870" + "" + ".js\">"); out.println("</script>"); out.println("<script type=\"text/javascript\"><!--"); out.println("google_ad_client = \"" + "pub-9496078135369870" + "\";"); out.println("google_ad_slot = \"" + "0941291340" + "\";"); out.println("google_ad_width = " + "728" + ";"); out.println("google_ad_height = " + "90" + ";"); out.println("//-->"); out.println("</script>"); out.println("<script type=\"text/javascript\""); out.println("src=\"" + "pub-9496078135369870" + ".js\">"); out.println("</script>"); out.println("<script type=\"text/javascript\"><!--"); out.println("google_ad_client = \"" + "pub-9496078135369870" + "\";"); out.println("google_ad_slot = \"" + "4621616265" + "\";"); out.println("google_ad_width = " + "468" + ";"); out.println("google_ad_height = " + "60" + ";"); out.println("//-->"); out.println("</script>"); out.println("<script type=\"text/javascript\""); out.println("src=\"" + "pub-9496078135369870" + ".js\">"); out.println("</script>"); } out.println("</div>"); out.println("</body></html>"); out.close(); } }
|
11
|
Code Sample 1:
private void copyFiles(File oldFolder, File newFolder) { for (File fileToCopy : oldFolder.listFiles()) { File copiedFile = new File(newFolder.getAbsolutePath() + "\\" + fileToCopy.getName()); try { FileInputStream source = new FileInputStream(fileToCopy); FileOutputStream destination = new FileOutputStream(copiedFile); FileChannel sourceFileChannel = source.getChannel(); FileChannel destinationFileChannel = destination.getChannel(); long size = sourceFileChannel.size(); sourceFileChannel.transferTo(0, size, destinationFileChannel); source.close(); destination.close(); } catch (Exception exc) { exc.printStackTrace(); } } }
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); } }
|
00
|
Code Sample 1:
protected void downloadFile(String filename, java.io.File targetFile, File partFile, ProgressMonitor monitor) throws java.io.IOException { FileOutputStream out = null; InputStream is = null; try { filename = toCanonicalFilename(filename); URL url = new URL(root + filename.substring(1)); URLConnection urlc = url.openConnection(); int i = urlc.getContentLength(); monitor.setTaskSize(i); out = new FileOutputStream(partFile); is = urlc.getInputStream(); monitor.started(); copyStream(is, out, monitor); monitor.finished(); out.close(); is.close(); if (!partFile.renameTo(targetFile)) { throw new IllegalArgumentException("unable to rename " + partFile + " to " + targetFile); } } catch (IOException e) { if (out != null) out.close(); if (is != null) is.close(); if (partFile.exists() && !partFile.delete()) { throw new IllegalArgumentException("unable to delete " + partFile); } throw e; } }
Code Sample 2:
public static void find(String pckgname, Class<?> tosubclass) { String name = new String(pckgname); if (!name.startsWith("/")) { name = "/" + name; } name = name.replace('.', '/'); URL url = tosubclass.getResource(name); System.out.println(name + "->" + url); if (url == null) return; File directory = new File(url.getFile()); if (directory.exists()) { String[] files = directory.list(); for (int i = 0; i < files.length; i++) { if (files[i].endsWith(".class")) { String classname = files[i].substring(0, files[i].length() - 6); try { Object o = Class.forName(pckgname + "." + classname).newInstance(); if (tosubclass.isInstance(o)) { System.out.println(classname); } } catch (ClassNotFoundException cnfex) { System.err.println(cnfex); } catch (InstantiationException iex) { } catch (IllegalAccessException iaex) { } } } } else { try { JarURLConnection conn = (JarURLConnection) url.openConnection(); String starts = conn.getEntryName(); JarFile jfile = conn.getJarFile(); Enumeration<JarEntry> e = jfile.entries(); while (e.hasMoreElements()) { ZipEntry entry = e.nextElement(); String entryname = entry.getName(); if (entryname.startsWith(starts) && (entryname.lastIndexOf('/') <= starts.length()) && entryname.endsWith(".class")) { String classname = entryname.substring(0, entryname.length() - 6); if (classname.startsWith("/")) classname = classname.substring(1); classname = classname.replace('/', '.'); try { Object o = Class.forName(classname).newInstance(); if (tosubclass.isInstance(o)) { System.out.println(classname.substring(classname.lastIndexOf('.') + 1)); } } catch (ClassNotFoundException cnfex) { System.err.println(cnfex); } catch (InstantiationException iex) { } catch (IllegalAccessException iaex) { } } } } catch (IOException ioex) { System.err.println(ioex); } } }
|
00
|
Code Sample 1:
protected String connectPost(String urlString, String parameter) { String response = null; try { URL url = new URL(urlString); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); log.fine(connection.getURL().toString()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(parameter.getBytes()); out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); response = in.readLine(); in.close(); log.finest(response); } catch (Exception e) { log.log(Level.SEVERE, urlString, e); } return response; }
Code Sample 2:
public void insertJobLog(String userId, String[] checkId, String checkType, String objType) throws Exception { DBOperation dbo = null; Connection connection = null; PreparedStatement preStm = null; String sql = "insert into COFFICE_JOBLOG_CHECKAUTH (USER_ID,CHECK_ID,CHECK_TYPE,OBJ_TYPE) values (?,?,?,?)"; String cleanSql = "delete from COFFICE_JOBLOG_CHECKAUTH where " + "user_id = '" + userId + "' and check_type = '" + checkType + "' and obj_type = '" + objType + "'"; try { dbo = createDBOperation(); connection = dbo.getConnection(); connection.setAutoCommit(false); preStm = connection.prepareStatement(cleanSql); int dCount = preStm.executeUpdate(); preStm = connection.prepareStatement(sql); String sHaveIns = ","; for (int j = 0; j < checkId.length; j++) { if (sHaveIns.indexOf("," + checkId[j] + ",") < 0) { preStm.setInt(1, Integer.parseInt(userId)); preStm.setInt(2, Integer.parseInt(checkId[j])); preStm.setInt(3, Integer.parseInt(checkType)); preStm.setInt(4, Integer.parseInt(objType)); preStm.executeUpdate(); sHaveIns += checkId[j] + ","; } } connection.commit(); } catch (Exception ex) { log.debug((new Date().toString()) + " ������Ȩ��ʧ��! "); try { connection.rollback(); } catch (SQLException e) { throw e; } throw ex; } finally { close(null, null, preStm, connection, dbo); } }
|
11
|
Code Sample 1:
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PrintWriter out = null; ServletOutputStream outstream = null; try { String action = req.getParameter("nmrshiftdbaction"); String relativepath = ServletUtils.expandRelative(this.getServletConfig(), "/WEB-INF"); TurbineConfig tc = new TurbineConfig(relativepath + "..", relativepath + getServletConfig().getInitParameter("properties")); tc.init(); int spectrumId = -1; DBSpectrum spectrum = null; Export export = null; String format = req.getParameter("format"); if (action.equals("test")) { try { res.setContentType("text/plain"); out = res.getWriter(); List l = DBSpectrumPeer.executeQuery("select SPECTRUM_ID from SPECTRUM limit 1"); if (l.size() > 0) spectrumId = ((Record) l.get(0)).getValue(1).asInt(); out.write("success"); } catch (Exception ex) { out.write("failure"); } } else if (action.equals("rss")) { int numbertoexport = 10; out = res.getWriter(); if (req.getParameter("numbertoexport") != null) { try { numbertoexport = Integer.parseInt(req.getParameter("numbertoexport")); if (numbertoexport < 1 || numbertoexport > 20) throw new NumberFormatException("Number to small/large"); } catch (NumberFormatException ex) { out.println("The parameter <code>numbertoexport</code>must be an integer from 1 to 20"); } } res.setContentType("text/xml"); RssWriter rssWriter = new RssWriter(); rssWriter.setWriter(res.getWriter()); AtomContainerSet soac = new AtomContainerSet(); String query = "select distinct MOLECULE.MOLECULE_ID from MOLECULE, SPECTRUM where SPECTRUM.MOLECULE_ID = MOLECULE.MOLECULE_ID and SPECTRUM.REVIEW_FLAG =\"true\" order by MOLECULE.DATE desc;"; List l = NmrshiftdbUserPeer.executeQuery(query); for (int i = 0; i < numbertoexport; i++) { if (i == l.size()) break; DBMolecule mol = DBMoleculePeer.retrieveByPK(new NumberKey(((Record) l.get(i)).getValue(1).asInt())); IMolecule cdkmol = mol.getAsCDKMoleculeAsEntered(1); soac.addAtomContainer(cdkmol); rssWriter.getLinkmap().put(cdkmol, mol.getEasylink(req)); rssWriter.getDatemap().put(cdkmol, mol.getDate()); rssWriter.getTitlemap().put(cdkmol, mol.getChemicalNamesAsOneStringWithFallback()); rssWriter.getCreatormap().put(cdkmol, mol.getNmrshiftdbUser().getUserName()); rssWriter.setCreator(GeneralUtils.getAdminEmail(getServletConfig())); Vector v = mol.getDBCanonicalNames(); for (int k = 0; k < v.size(); k++) { DBCanonicalName canonName = (DBCanonicalName) v.get(k); if (canonName.getDBCanonicalNameType().getCanonicalNameType() == "INChI") { rssWriter.getInchimap().put(cdkmol, canonName.getName()); break; } } rssWriter.setTitle("NMRShiftDB"); rssWriter.setLink("http://www.nmrshiftdb.org"); rssWriter.setDescription("NMRShiftDB is an open-source, open-access, open-submission, open-content web database for chemical structures and their nuclear magnetic resonance data"); rssWriter.setPublisher("NMRShiftDB.org"); rssWriter.setImagelink("http://www.nmrshiftdb.org/images/nmrshift-logo.gif"); rssWriter.setAbout("http://www.nmrshiftdb.org/NmrshiftdbServlet?nmrshiftdbaction=rss"); Collection coll = new ArrayList(); Vector spectra = mol.selectSpectra(null); for (int k = 0; k < spectra.size(); k++) { Element el = ((DBSpectrum) spectra.get(k)).getCmlSpect(); Element el2 = el.getChildElements().get(0); el.removeChild(el2); coll.add(el2); } rssWriter.getMultiMap().put(cdkmol, coll); } rssWriter.write(soac); } else if (action.equals("getattachment")) { res.setContentType("application/zip"); outstream = res.getOutputStream(); DBSample sample = DBSamplePeer.retrieveByPK(new NumberKey(req.getParameter("sampleid"))); outstream.write(sample.getAttachment()); } else if (action.equals("createreport")) { res.setContentType("application/pdf"); outstream = res.getOutputStream(); boolean yearly = req.getParameter("style").equals("yearly"); int yearstart = Integer.parseInt(req.getParameter("yearstart")); int yearend = Integer.parseInt(req.getParameter("yearend")); int monthstart = 0; int monthend = 0; if (!yearly) { monthstart = Integer.parseInt(req.getParameter("monthstart")); monthend = Integer.parseInt(req.getParameter("monthend")); } int type = Integer.parseInt(req.getParameter("type")); JasperReport jasperReport = (JasperReport) JRLoader.loadObject(relativepath + "/reports/" + (yearly ? "yearly" : "monthly") + "_report_" + type + ".jasper"); Map parameters = new HashMap(); if (yearly) parameters.put("HEADER", "Report for years " + yearstart + " - " + yearend); else parameters.put("HEADER", "Report for " + monthstart + "/" + yearstart + " - " + monthend + "/" + yearend); DBConnection dbconn = TurbineDB.getConnection(); Connection conn = dbconn.getConnection(); Statement stmt = conn.createStatement(); ResultSet rs = null; if (type == 1) { rs = stmt.executeQuery("select YEAR(DATE) as YEAR, " + (yearly ? "" : " MONTH(DATE) as MONTH, ") + "AFFILIATION_1, AFFILIATION_2, MACHINE.NAME as NAME, count(*) as C, sum(WISHED_SPECTRUM like '%13C%' or WISHED_SPECTRUM like '%variable temperature%' or WISHED_SPECTRUM like '%ID sel. NOE%' or WISHED_SPECTRUM like '%solvent suppression%' or WISHED_SPECTRUM like '%standard spectrum%') as 1_D, sum(WISHED_SPECTRUM like '%H,H-COSY%' or WISHED_SPECTRUM like '%NOESY%' or WISHED_SPECTRUM like '%HMQC%' or WISHED_SPECTRUM like '%HMBC%') as 2_D, sum(OTHER_WISHED_SPECTRUM!='') as SPECIAL, sum(OTHER_NUCLEI!='') as HETERO, sum(PROCESS='self') as SELF, sum(PROCESS='robot') as ROBOT, sum(PROCESS='worker') as OPERATOR from (SAMPLE join TURBINE_USER using (USER_ID)) join MACHINE on MACHINE.MACHINE_ID=SAMPLE.MACHINE where YEAR(DATE)>=" + yearstart + " and YEAR(DATE)<=" + yearend + " and LOGIN_NAME<>'testuser' group by YEAR, " + (yearly ? "" : "MONTH, ") + "AFFILIATION_1, AFFILIATION_2, MACHINE.NAME"); } else if (type == 2) { rs = stmt.executeQuery("select YEAR(DATE) as YEAR, " + (yearly ? "" : " MONTH(DATE) as MONTH, ") + "MACHINE.NAME as NAME, count(*) as C, sum(WISHED_SPECTRUM like '%13C%' or WISHED_SPECTRUM like '%variable temperature%' or WISHED_SPECTRUM like '%ID sel. NOE%' or WISHED_SPECTRUM like '%solvent suppression%' or WISHED_SPECTRUM like '%standard spectrum%') as 1_D, sum(WISHED_SPECTRUM like '%H,H-COSY%' or WISHED_SPECTRUM like '%NOESY%' or WISHED_SPECTRUM like '%HMQC%' or WISHED_SPECTRUM like '%HMBC%') as 2_D, sum(OTHER_WISHED_SPECTRUM!='') as SPECIAL, sum(OTHER_NUCLEI!='') as HETERO, sum(PROCESS='self') as SELF, sum(PROCESS='robot') as ROBOT, sum(PROCESS='worker') as OPERATOR from (SAMPLE join TURBINE_USER using (USER_ID)) join MACHINE on MACHINE.MACHINE_ID=SAMPLE.MACHINE group by YEAR, " + (yearly ? "" : "MONTH, ") + "MACHINE.NAME"); } JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, new JRResultSetDataSource(rs)); JasperExportManager.exportReportToPdfStream(jasperPrint, outstream); dbconn.close(); } else if (action.equals("exportcmlbyinchi")) { res.setContentType("text/xml"); out = res.getWriter(); String inchi = req.getParameter("inchi"); String spectrumtype = req.getParameter("spectrumtype"); Criteria crit = new Criteria(); crit.add(DBCanonicalNamePeer.NAME, inchi); crit.addJoin(DBCanonicalNamePeer.MOLECULE_ID, DBSpectrumPeer.MOLECULE_ID); crit.addJoin(DBSpectrumPeer.SPECTRUM_TYPE_ID, DBSpectrumTypePeer.SPECTRUM_TYPE_ID); crit.add(DBSpectrumTypePeer.NAME, spectrumtype); try { GeneralUtils.logToSql(crit.toString(), null); } catch (Exception ex) { } Vector spectra = DBSpectrumPeer.doSelect(crit); if (spectra.size() == 0) { out.write("No such molecule or spectrum"); } else { Element cmlElement = new Element("cml"); cmlElement.addAttribute(new Attribute("convention", "nmrshiftdb-convention")); cmlElement.setNamespaceURI("http://www.xml-cml.org/schema"); Element parent = ((DBSpectrum) spectra.get(0)).getDBMolecule().getCML(1); nu.xom.Node cmldoc = parent.getChild(0); ((Element) cmldoc).setNamespaceURI("http://www.xml-cml.org/schema"); parent.removeChildren(); cmlElement.appendChild(cmldoc); for (int k = 0; k < spectra.size(); k++) { Element parentspec = ((DBSpectrum) spectra.get(k)).getCmlSpect(); Node spectrumel = parentspec.getChild(0); parentspec.removeChildren(); cmlElement.appendChild(spectrumel); ((Element) spectrumel).setNamespaceURI("http://www.xml-cml.org/schema"); } out.write(cmlElement.toXML()); } } else if (action.equals("namelist")) { res.setContentType("application/zip"); outstream = res.getOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zipout = new ZipOutputStream(baos); Criteria crit = new Criteria(); crit.addJoin(DBMoleculePeer.MOLECULE_ID, DBSpectrumPeer.MOLECULE_ID); crit.add(DBSpectrumPeer.REVIEW_FLAG, "true"); Vector v = DBMoleculePeer.doSelect(crit); for (int i = 0; i < v.size(); i++) { if (i % 500 == 0) { if (i != 0) { zipout.write(new String("<p>The list is continued <a href=\"nmrshiftdb.names." + i + ".html\">here</a></p></body></html>").getBytes()); zipout.closeEntry(); } zipout.putNextEntry(new ZipEntry("nmrshiftdb.names." + i + ".html")); zipout.write(new String("<html><body><h1>This is a list of strcutures in <a href=\"http://www.nmrshiftdb.org\">NMRShiftDB</a>, starting at " + i + ", Its main purpose is to be found by search engines</h1>").getBytes()); } DBMolecule mol = (DBMolecule) v.get(i); zipout.write(new String("<p><a href=\"" + mol.getEasylink(req) + "\">").getBytes()); Vector cannames = mol.getDBCanonicalNames(); for (int k = 0; k < cannames.size(); k++) { zipout.write(new String(((DBCanonicalName) cannames.get(k)).getName() + " ").getBytes()); } Vector chemnames = mol.getDBChemicalNames(); for (int k = 0; k < chemnames.size(); k++) { zipout.write(new String(((DBChemicalName) chemnames.get(k)).getName() + " ").getBytes()); } zipout.write(new String("</a>. Information we have got: NMR spectra").getBytes()); Vector spectra = mol.selectSpectra(); for (int k = 0; k < spectra.size(); k++) { zipout.write(new String(((DBSpectrum) spectra.get(k)).getDBSpectrumType().getName() + ", ").getBytes()); } if (mol.hasAny3d()) zipout.write(new String("3D coordinates, ").getBytes()); zipout.write(new String("File formats: CML, mol, png, jpeg").getBytes()); zipout.write(new String("</p>").getBytes()); } zipout.write(new String("</body></html>").getBytes()); zipout.closeEntry(); zipout.close(); InputStream is = new ByteArrayInputStream(baos.toByteArray()); byte[] buf = new byte[32 * 1024]; int nRead = 0; while ((nRead = is.read(buf)) != -1) { outstream.write(buf, 0, nRead); } } else if (action.equals("predictor")) { if (req.getParameter("symbol") == null) { res.setContentType("text/plain"); out = res.getWriter(); out.write("please give the symbol to create the predictor for in the request with symbol=X (e. g. symbol=C"); } res.setContentType("application/zip"); outstream = res.getOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zipout = new ZipOutputStream(baos); String filename = "org/openscience/nmrshiftdb/PredictionTool.class"; zipout.putNextEntry(new ZipEntry(filename)); JarInputStream jip = new JarInputStream(new FileInputStream(ServletUtils.expandRelative(getServletConfig(), "/WEB-INF/lib/nmrshiftdb-lib.jar"))); JarEntry entry = jip.getNextJarEntry(); while (entry.getName().indexOf("PredictionTool.class") == -1) { entry = jip.getNextJarEntry(); } for (int i = 0; i < entry.getSize(); i++) { zipout.write(jip.read()); } zipout.closeEntry(); zipout.putNextEntry(new ZipEntry("nmrshiftdb.csv")); int i = 0; org.apache.turbine.util.db.pool.DBConnection conn = TurbineDB.getConnection(); HashMap mapsmap = new HashMap(); while (true) { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("select HOSE_CODE, VALUE, SYMBOL from HOSE_CODES where CONDITION_TYPE='m' and WITH_RINGS=0 and SYMBOL='" + req.getParameter("symbol") + "' limit " + (i * 1000) + ", 1000"); int m = 0; while (rs.next()) { String code = rs.getString(1); Double value = new Double(rs.getString(2)); String symbol = rs.getString(3); if (mapsmap.get(symbol) == null) { mapsmap.put(symbol, new HashMap()); } for (int spheres = 6; spheres > 0; spheres--) { StringBuffer hoseCodeBuffer = new StringBuffer(); StringTokenizer st = new StringTokenizer(code, "()/"); for (int k = 0; k < spheres; k++) { if (st.hasMoreTokens()) { String partcode = st.nextToken(); hoseCodeBuffer.append(partcode); } if (k == 0) { hoseCodeBuffer.append("("); } else if (k == 3) { hoseCodeBuffer.append(")"); } else { hoseCodeBuffer.append("/"); } } String hoseCode = hoseCodeBuffer.toString(); if (((HashMap) mapsmap.get(symbol)).get(hoseCode) == null) { ((HashMap) mapsmap.get(symbol)).put(hoseCode, new ArrayList()); } ((ArrayList) ((HashMap) mapsmap.get(symbol)).get(hoseCode)).add(value); } m++; } i++; stmt.close(); if (m == 0) break; } Set keySet = mapsmap.keySet(); Iterator it = keySet.iterator(); while (it.hasNext()) { String symbol = (String) it.next(); HashMap hosemap = ((HashMap) mapsmap.get(symbol)); Set keySet2 = hosemap.keySet(); Iterator it2 = keySet2.iterator(); while (it2.hasNext()) { String hoseCode = (String) it2.next(); ArrayList list = ((ArrayList) hosemap.get(hoseCode)); double[] values = new double[list.size()]; for (int k = 0; k < list.size(); k++) { values[k] = ((Double) list.get(k)).doubleValue(); } zipout.write(new String(symbol + "|" + hoseCode + "|" + Statistics.minimum(values) + "|" + Statistics.average(values) + "|" + Statistics.maximum(values) + "\r\n").getBytes()); } } zipout.closeEntry(); zipout.close(); InputStream is = new ByteArrayInputStream(baos.toByteArray()); byte[] buf = new byte[32 * 1024]; int nRead = 0; i = 0; while ((nRead = is.read(buf)) != -1) { outstream.write(buf, 0, nRead); } } else if (action.equals("exportspec") || action.equals("exportmol")) { if (spectrumId > -1) spectrum = DBSpectrumPeer.retrieveByPK(new NumberKey(spectrumId)); else spectrum = DBSpectrumPeer.retrieveByPK(new NumberKey(req.getParameter("spectrumid"))); export = new Export(spectrum); } else if (action.equals("exportmdl")) { res.setContentType("text/plain"); outstream = res.getOutputStream(); DBMolecule mol = DBMoleculePeer.retrieveByPK(new NumberKey(req.getParameter("moleculeid"))); outstream.write(mol.getStructureFile(Integer.parseInt(req.getParameter("coordsetid")), false).getBytes()); } else if (action.equals("exportlastinputs")) { format = action; } else if (action.equals("printpredict")) { res.setContentType("text/html"); out = res.getWriter(); HttpSession session = req.getSession(); VelocityContext context = PredictPortlet.getContext(session, true, true, new StringBuffer(), getServletConfig(), req, true); StringWriter w = new StringWriter(); Velocity.mergeTemplate("predictprint.vm", "ISO-8859-1", context, w); out.println(w.toString()); } else { res.setContentType("text/html"); out = res.getWriter(); out.println("No valid action"); } if (format == null) format = ""; if (format.equals("pdf") || format.equals("rtf")) { res.setContentType("application/" + format); out = res.getWriter(); } if (format.equals("docbook")) { res.setContentType("application/zip"); outstream = res.getOutputStream(); } if (format.equals("svg")) { res.setContentType("image/x-svg"); out = res.getWriter(); } if (format.equals("tiff")) { res.setContentType("image/tiff"); outstream = res.getOutputStream(); } if (format.equals("jpeg")) { res.setContentType("image/jpeg"); outstream = res.getOutputStream(); } if (format.equals("png")) { res.setContentType("image/png"); outstream = res.getOutputStream(); } if (format.equals("mdl") || format.equals("txt") || format.equals("cml") || format.equals("cmlboth") || format.indexOf("exsection") == 0) { res.setContentType("text/plain"); out = res.getWriter(); } if (format.equals("simplehtml") || format.equals("exportlastinputs")) { res.setContentType("text/html"); out = res.getWriter(); } if (action.equals("exportlastinputs")) { int numbertoexport = 4; if (req.getParameter("numbertoexport") != null) { try { numbertoexport = Integer.parseInt(req.getParameter("numbertoexport")); if (numbertoexport < 1 || numbertoexport > 20) throw new NumberFormatException("Number to small/large"); } catch (NumberFormatException ex) { out.println("The parameter <code>numbertoexport</code>must be an integer from 1 to 20"); } } NmrshiftdbUser user = null; try { user = NmrshiftdbUserPeer.getByName(req.getParameter("username")); } catch (NmrshiftdbException ex) { out.println("Seems <code>username</code> is not OK: " + ex.getMessage()); } if (user != null) { List l = NmrshiftdbUserPeer.executeQuery("SELECT LAST_DOWNLOAD_DATE FROM TURBINE_USER where LOGIN_NAME=\"" + user.getUserName() + "\";"); Date lastDownloadDate = ((Record) l.get(0)).getValue(1).asDate(); if (((new Date().getTime() - lastDownloadDate.getTime()) / 3600000) < 24) { out.println("Your last download was at " + lastDownloadDate + ". You may download your last inputs only once a day. Sorry for this, but we need to be carefull with resources. If you want to put your last inputs on your homepage best use some sort of cache (e. g. use wget for downlaod with crond and link to this static resource))!"); } else { NmrshiftdbUserPeer.executeStatement("UPDATE TURBINE_USER SET LAST_DOWNLOAD_DATE=NOW() where LOGIN_NAME=\"" + user.getUserName() + "\";"); Vector<String> parameters = new Vector<String>(); String query = "select distinct MOLECULE.MOLECULE_ID from MOLECULE, SPECTRUM where SPECTRUM.MOLECULE_ID = MOLECULE.MOLECULE_ID and SPECTRUM.REVIEW_FLAG =\"true\" and SPECTRUM.USER_ID=" + user.getUserId() + " order by MOLECULE.DATE desc;"; l = NmrshiftdbUserPeer.executeQuery(query); String url = javax.servlet.http.HttpUtils.getRequestURL(req).toString(); url = url.substring(0, url.length() - 17); for (int i = 0; i < numbertoexport; i++) { if (i == l.size()) break; DBMolecule mol = DBMoleculePeer.retrieveByPK(new NumberKey(((Record) l.get(i)).getValue(1).asInt())); parameters.add(new String("<a href=\"" + url + "/portal/pane0/Results?nmrshiftdbaction=showDetailsFromHome&molNumber=" + mol.getMoleculeId() + "\"><img src=\"" + javax.servlet.http.HttpUtils.getRequestURL(req).toString() + "?nmrshiftdbaction=exportmol&spectrumid=" + ((DBSpectrum) mol.getDBSpectrums().get(0)).getSpectrumId() + "&format=jpeg&size=150x150&backcolor=12632256\"></a>")); } VelocityContext context = new VelocityContext(); context.put("results", parameters); StringWriter w = new StringWriter(); Velocity.mergeTemplate("lateststructures.vm", "ISO-8859-1", context, w); out.println(w.toString()); } } } if (action.equals("exportspec")) { if (format.equals("txt")) { String lastsearchtype = req.getParameter("lastsearchtype"); if (lastsearchtype.equals(NmrshiftdbConstants.TOTALSPECTRUM) || lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)) { List l = ParseUtils.parseSpectrumFromSpecFile(req.getParameter("lastsearchvalues")); spectrum.initSimilarity(l, lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)); } Vector v = spectrum.getOptions(); DBMolecule mol = spectrum.getDBMolecule(); out.print(mol.getChemicalNamesAsOneString(false) + mol.getMolecularFormula(false) + "; " + mol.getMolecularWeight() + " Dalton\n\r"); out.print("\n\rAtom\t"); if (spectrum.getDBSpectrumType().getElementSymbol() == ("H")) out.print("Mult.\t"); out.print("Meas."); if (lastsearchtype.equals(NmrshiftdbConstants.TOTALSPECTRUM) || lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)) { out.print("\tInput\tDiff"); } out.print("\n\r"); out.print("No.\t"); if (spectrum.getDBSpectrumType().getElementSymbol() == ("H")) out.print("\t"); out.print("Shift"); if (lastsearchtype.equals(NmrshiftdbConstants.TOTALSPECTRUM) || lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)) { out.print("\tShift\tM-I"); } out.print("\n\r"); for (int i = 0; i < v.size(); i++) { out.print(((ValuesForVelocityBean) v.get(i)).getDisplayText() + "\t" + ((ValuesForVelocityBean) v.get(i)).getRange()); if (lastsearchtype.equals(NmrshiftdbConstants.TOTALSPECTRUM) || lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)) { out.print("\t" + ((ValuesForVelocityBean) v.get(i)).getNameForElements() + "\t" + ((ValuesForVelocityBean) v.get(i)).getDelta()); } out.print("\n\r"); } } if (format.equals("simplehtml")) { String i1 = export.getImage(false, "jpeg", ServletUtils.expandRelative(this.getServletConfig(), "/nmrshiftdbhtml") + "/tmp/" + System.currentTimeMillis(), true); export.pictures[0] = new File(i1).getName(); String i2 = export.getImage(true, "jpeg", ServletUtils.expandRelative(this.getServletConfig(), "/nmrshiftdbhtml") + "/tmp/" + System.currentTimeMillis(), true); export.pictures[1] = new File(i2).getName(); String docbook = export.getHtml(); out.print(docbook); } if (format.equals("pdf") || format.equals("rtf")) { String svgSpec = export.getSpecSvg(400, 200); String svgspecfile = relativepath + "/tmp/" + System.currentTimeMillis() + "s.svg"; new FileOutputStream(svgspecfile).write(svgSpec.getBytes()); export.pictures[1] = svgspecfile; String molSvg = export.getMolSvg(true); String svgmolfile = relativepath + "/tmp/" + System.currentTimeMillis() + "m.svg"; new FileOutputStream(svgmolfile).write(molSvg.getBytes()); export.pictures[0] = svgmolfile; String docbook = export.getDocbook("pdf", "SVG"); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(new StreamSource("file:" + GeneralUtils.getNmrshiftdbProperty("docbookxslpath", getServletConfig()) + "/fo/docbook.xsl")); ByteArrayOutputStream baos = new ByteArrayOutputStream(); transformer.transform(new StreamSource(new StringReader(docbook)), new StreamResult(baos)); FopFactory fopFactory = FopFactory.newInstance(); FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); OutputStream out2 = new ByteArrayOutputStream(); Fop fop = fopFactory.newFop(format.equals("rtf") ? MimeConstants.MIME_RTF : MimeConstants.MIME_PDF, foUserAgent, out2); TransformerFactory factory = TransformerFactory.newInstance(); transformer = factory.newTransformer(); Source src = new StreamSource(new StringReader(baos.toString())); Result res2 = new SAXResult(fop.getDefaultHandler()); transformer.transform(src, res2); out.print(out2.toString()); } if (format.equals("docbook")) { String i1 = relativepath + "/tmp/" + System.currentTimeMillis() + ".svg"; new FileOutputStream(i1).write(export.getSpecSvg(300, 200).getBytes()); export.pictures[0] = new File(i1).getName(); String i2 = relativepath + "/tmp/" + System.currentTimeMillis() + ".svg"; new FileOutputStream(i2).write(export.getMolSvg(true).getBytes()); export.pictures[1] = new File(i2).getName(); String docbook = export.getDocbook("pdf", "SVG"); String docbookfile = relativepath + "/tmp/" + System.currentTimeMillis() + ".xml"; new FileOutputStream(docbookfile).write(docbook.getBytes()); ByteArrayOutputStream baos = export.makeZip(new String[] { docbookfile, i1, i2 }); outstream.write(baos.toByteArray()); } if (format.equals("svg")) { out.print(export.getSpecSvg(400, 200)); } if (format.equals("tiff") || format.equals("jpeg") || format.equals("png")) { InputStream is = new FileInputStream(export.getImage(false, format, relativepath + "/tmp/" + System.currentTimeMillis(), true)); byte[] buf = new byte[32 * 1024]; int nRead = 0; while ((nRead = is.read(buf)) != -1) { outstream.write(buf, 0, nRead); } } if (format.equals("cml")) { out.print(spectrum.getCmlSpect().toXML()); } if (format.equals("cmlboth")) { Element cmlElement = new Element("cml"); cmlElement.addAttribute(new Attribute("convention", "nmrshiftdb-convention")); cmlElement.setNamespaceURI("http://www.xml-cml.org/schema"); Element parent = spectrum.getDBMolecule().getCML(1, spectrum.getDBSpectrumType().getName().equals("1H")); nu.xom.Node cmldoc = parent.getChild(0); ((Element) cmldoc).setNamespaceURI("http://www.xml-cml.org/schema"); parent.removeChildren(); cmlElement.appendChild(cmldoc); Element parentspec = spectrum.getCmlSpect(); Node spectrumel = parentspec.getChild(0); parentspec.removeChildren(); cmlElement.appendChild(spectrumel); ((Element) spectrumel).setNamespaceURI("http://www.xml-cml.org/schema"); out.write(cmlElement.toXML()); } if (format.indexOf("exsection") == 0) { StringTokenizer st = new StringTokenizer(format, "-"); st.nextToken(); String template = st.nextToken(); Criteria crit = new Criteria(); crit.add(DBSpectrumPeer.USER_ID, spectrum.getUserId()); Vector v = spectrum.getDBMolecule().getDBSpectrums(crit); VelocityContext context = new VelocityContext(); context.put("spectra", v); context.put("molecule", spectrum.getDBMolecule()); StringWriter w = new StringWriter(); Velocity.mergeTemplate("exporttemplates/" + template, "ISO-8859-1", context, w); out.write(w.toString()); } } if (action.equals("exportmol")) { int width = -1; int height = -1; if (req.getParameter("size") != null) { StringTokenizer st = new StringTokenizer(req.getParameter("size"), "x"); width = Integer.parseInt(st.nextToken()); height = Integer.parseInt(st.nextToken()); } boolean shownumbers = true; if (req.getParameter("shownumbers") != null && req.getParameter("shownumbers").equals("false")) { shownumbers = false; } if (req.getParameter("backcolor") != null) { export.backColor = new Color(Integer.parseInt(req.getParameter("backcolor"))); } if (req.getParameter("markatom") != null) { export.selected = Integer.parseInt(req.getParameter("markatom")) - 1; } if (format.equals("svg")) { out.print(export.getMolSvg(true)); } if (format.equals("tiff") || format.equals("jpeg") || format.equals("png")) { InputStream is = new FileInputStream(export.getImage(true, format, relativepath + "/tmp/" + System.currentTimeMillis(), width, height, shownumbers, null)); byte[] buf = new byte[32 * 1024]; int nRead = 0; while ((nRead = is.read(buf)) != -1) { outstream.write(buf, 0, nRead); } } if (format.equals("mdl")) { out.println(spectrum.getDBMolecule().getStructureFile(1, false)); } if (format.equals("cml")) { out.println(spectrum.getDBMolecule().getCMLString(1)); } } if (out != null) out.flush(); else outstream.flush(); } catch (Exception ex) { ex.printStackTrace(); out.print(GeneralUtils.logError(ex, "NmrshiftdbServlet", null, true)); out.flush(); } }
Code Sample 2:
public static void copyFile(final File sourceFile, final File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileInputStream inStream = null; FileOutputStream outStream = null; FileChannel source = null; FileChannel destination = null; try { source = (inStream = new FileInputStream(sourceFile)).getChannel(); destination = (outStream = new FileOutputStream(destFile)).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { closeIO(source); closeIO(inStream); closeIO(destination); closeIO(outStream); } }
|
11
|
Code Sample 1:
public static String crypt(String str) { if (str == null || str.length() == 0) { throw new IllegalArgumentException("String to encript cannot be null or zero length"); } StringBuffer hexString = new StringBuffer(); MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } md.update(str.getBytes()); byte[] hash = md.digest(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) { hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); } else { hexString.append(Integer.toHexString(0xFF & hash[i])); } } return hexString.toString(); }
Code Sample 2:
private void getRandomGUID(boolean secure) { MessageDigest md5; StringBuilder sbValueBeforeHash = new StringBuilder(); try { md5 = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new ApplicationIllegalArgumentException(e); } long time = System.nanoTime(); long rand = 0; if (secure) { rand = MySecureRand.nextLong(); } else { rand = MyRand.nextLong(); } sbValueBeforeHash.append(SId); sbValueBeforeHash.append(":"); sbValueBeforeHash.append(Long.toString(time)); sbValueBeforeHash.append(":"); sbValueBeforeHash.append(Long.toString(rand)); valueBeforeHash = sbValueBeforeHash.toString(); md5.update(valueBeforeHash.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) { sb.append('0'); } sb.append(Integer.toHexString(b)); } valueAfterHash = sb.toString(); }
|
00
|
Code Sample 1:
private String getData(String myurl) throws Exception { URL url = new URL(myurl); uc = (HttpURLConnection) url.openConnection(); br = new BufferedReader(new InputStreamReader(uc.getInputStream())); String temp = "", k = ""; while ((temp = br.readLine()) != null) { k += temp; } br.close(); return k; }
Code Sample 2:
public FTPClient connect(String host, String userId, String password, String alias) throws IOException { FTPClient client = null; if (connections.get(alias) != null) { client = (FTPClient) connections.get(alias); if (client.isConnected() == false) { client.connect(host); } } else { client = new FTPClient(); client.connect(host); client.login(userId, password); connections.put(alias, client); } return client; }
|
00
|
Code Sample 1:
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; }
Code Sample 2:
@Override public void onClick(View v) { GsmCellLocation gcl = (GsmCellLocation) tm.getCellLocation(); int cid = gcl.getCid(); int lac = gcl.getLac(); int mcc = Integer.valueOf(tm.getNetworkOperator().substring(0, 3)); int mnc = Integer.valueOf(tm.getNetworkOperator().substring(3, 5)); try { JSONObject holder = new JSONObject(); holder.put("version", "1.1.0"); holder.put("host", "maps.google.com"); holder.put("request_address", true); JSONArray array = new JSONArray(); JSONObject data = new JSONObject(); data.put("cell_id", cid); data.put("location_area_code", lac); data.put("mobile_country_code", mcc); data.put("mobile_network_code", mnc); array.put(data); holder.put("cell_towers", array); DefaultHttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost("http://www.google.com/loc/json"); StringEntity se = new StringEntity(holder.toString()); post.setEntity(se); HttpResponse resp = client.execute(post); HttpEntity entity = resp.getEntity(); BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent())); StringBuffer sb = new StringBuffer(); String result = br.readLine(); while (result != null) { sb.append(result); result = br.readLine(); } JSONObject jsonObject = new JSONObject(sb.toString()); JSONObject jsonObject1 = new JSONObject(jsonObject.getString("location")); getAddress(jsonObject1.getString("latitude"), jsonObject1.getString("longitude")); } catch (Exception e) { } }
|
00
|
Code Sample 1:
public static void copyFile(HttpServletResponse response, String file) throws IOException { response.setContentType(FileUtils.getContentType(file)); response.setContentLength(FileUtils.getContentLength(file)); response.setHeader("Content-Length", Integer.toString(FileUtils.getContentLength(file))); InputStream input = new FileInputStream(file); OutputStream output = response.getOutputStream(); IOUtils.copy(input, output, true); }
Code Sample 2:
public int executar(String sql, Boolean retornaAutoIncremento) { int autoIncremento = 0; try { for (Connection conn : conexoes) { stm = conn.createStatement(); stm.executeUpdate(sql); } for (Connection conn : conexoes) { conn.commit(); } } catch (Exception ex) { try { for (Connection conn : conexoes) { conn.rollback(); } return 0; } catch (SQLException Sqlex) { Logger.getLogger(Persistencia.class.getName()).log(Level.SEVERE, null, Sqlex); } } if (retornaAutoIncremento) autoIncremento = getUltimoIdentificador(); return autoIncremento; }
|
11
|
Code Sample 1:
private void initLogging() { File logging = new File(App.getHome(), "logging.properties"); if (!logging.exists()) { InputStream input = getClass().getResourceAsStream("logging.properties-setup"); OutputStream output = null; try { output = new FileOutputStream(logging); IOUtils.copy(input, output); } catch (Exception ex) { } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } } FileInputStream input = null; try { input = new FileInputStream(logging); LogManager.getLogManager().readConfiguration(input); } catch (Exception ex) { } finally { IOUtils.closeQuietly(input); } }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
00
|
Code Sample 1:
protected void runTests(URL pBaseURL, String pName, String pHref) throws Exception { URL url = new URL(pBaseURL, pHref); InputSource isource = new InputSource(url.openStream()); isource.setSystemId(url.toString()); Document document = getDocumentBuilder().parse(isource); NodeList schemas = document.getElementsByTagNameNS(null, "Schema"); for (int i = 0; i < schemas.getLength(); i++) { Element schema = (Element) schemas.item(i); runTest(url, schema.getAttribute("name"), schema.getAttribute("href")); } }
Code Sample 2:
public void login(String username, String key) { if (isLogged()) { return; } if (null == this.username || null == this.key) { this.username = username; this.key = key; } final ProgressHandle handle = ProgressHandleFactory.createHandle("Logining into DreamHost"); handle.start(); working = true; fireChangeEvent(); RequestProcessor.getDefault().post(new Runnable() { public void run() { try { HttpsURLConnection connection = (HttpsURLConnection) urlGenerator(DreamHostCommands.CMD_DOMAIN_LIST_DOMAINS, null).openConnection(); String response = getResponse(connection); Document document = builder.parse(new ByteArrayInputStream(response.getBytes())); String result = document.getElementsByTagName("result").item(0).getTextContent(); logged = result.equals("success"); } catch (SAXException ex) { Logger.getLogger(DreamHostConnector.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(DreamHostConnector.class.getName()).log(Level.SEVERE, null, ex); } finally { if (isLogged()) { NbPreferences.forModule(DreamHostConnector.class).put("username", getUsername()); NbPreferences.forModule(DreamHostConnector.class).put("key", getKey()); } handle.finish(); working = false; fireChangeEvent(); } } }); }
|
11
|
Code Sample 1:
public static void copy(final File src, final File dest) throws IOException { OutputStream stream = new FileOutputStream(dest); FileInputStream fis = new FileInputStream(src); byte[] buffer = new byte[16384]; while (fis.available() != 0) { int read = fis.read(buffer); stream.write(buffer, 0, read); } stream.flush(); }
Code Sample 2:
public static void printResource(OutputStream os, String resourceName) throws IOException { InputStream is = null; try { is = ResourceLoader.loadResource(resourceName); if (is == null) { throw new IOException("Given resource not found!"); } IOUtils.copy(is, os); } finally { IOUtils.closeQuietly(is); } }
|
00
|
Code Sample 1:
protected void sort(int a) { int[] masiv = new int[a + 1]; Random fff = new Random(); for (int i = 0; i <= a; i++) { masiv[i] = fff.nextInt(9); } int d; for (int j = 0; j < a; j++) { for (int i = 0; i < a; i++) { if (masiv[i] < masiv[i + 1]) { } else { d = masiv[i]; masiv[i] = masiv[i + 1]; masiv[i + 1] = d; } } } while (a != 0) { System.out.println("sort: " + masiv[a]); a--; } }
Code Sample 2:
public boolean urlToSpeech(String urlPath) { boolean ok = false; try { URL url = new URL(urlPath); InputStream is = url.openStream(); ok = streamToSpeech(is); } catch (IOException ioe) { System.err.println("Can't read data from " + urlPath); } return ok; }
|
11
|
Code Sample 1:
public static boolean copy(File source, File dest) { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) { e.printStackTrace(); return false; } return true; }
Code Sample 2:
public static void copy_file(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); System.out.print("Overwrite existing file " + toFile.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")) 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[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
|
00
|
Code Sample 1:
protected void sort(int a) { int[] masiv = new int[a + 1]; Random fff = new Random(); for (int i = 0; i <= a; i++) { masiv[i] = fff.nextInt(9); } int d; for (int j = 0; j < a; j++) { for (int i = 0; i < a; i++) { if (masiv[i] < masiv[i + 1]) { } else { d = masiv[i]; masiv[i] = masiv[i + 1]; masiv[i + 1] = d; } } } while (a != 0) { System.out.println("sort: " + masiv[a]); a--; } }
Code Sample 2:
public String getUser() { try { HttpGet get = new HttpGet("http://twemoi.status.net/api/account/verify_credentials.xml"); consumer.sign(get); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(get); if (response != null) { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { this.enviarMensaje("Error: Usuario no autenticado en la red de Status"); return ""; } StringBuffer sBuf = new StringBuffer(); String linea; BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); while ((linea = reader.readLine()) != null) { sBuf.append(linea); } reader.close(); response.getEntity().consumeContent(); get.abort(); String salida = sBuf.toString(); String user_name = salida.split("</screen_name>")[0].split("<screen_name>")[1]; return user_name; } } catch (UnsupportedEncodingException e) { this.enviarMensaje("Error: Usuario no autenticado en la red de Status"); } catch (IOException e) { this.enviarMensaje("Error: Usuario no autenticado en la red de Status"); } catch (OAuthMessageSignerException e) { this.enviarMensaje("Error: Usuario no autenticado en la red de Status"); } catch (OAuthExpectationFailedException e) { this.enviarMensaje("Error: Usuario no autenticado en la red de Status"); } catch (OAuthCommunicationException e) { this.enviarMensaje("Error: Usuario no autenticado en la red de Status"); } return null; }
|
11
|
Code Sample 1:
static void conditionalCopyFile(File dst, File src) throws IOException { if (dst.equals(src)) return; if (!dst.isFile() || dst.lastModified() < src.lastModified()) { System.out.println("Copying " + src); InputStream is = new FileInputStream(src); OutputStream os = new FileOutputStream(dst); byte[] buf = new byte[8192]; int len; while ((len = is.read(buf)) > 0) os.write(buf, 0, len); os.close(); is.close(); } }
Code Sample 2:
public byte[] read(IFile input) { InputStream contents = null; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); contents = input.getContents(); IOUtils.copy(contents, baos); return baos.toByteArray(); } catch (IOException e) { Activator.logUnexpected(null, e); } catch (CoreException e) { Activator.logUnexpected(null, e); } finally { IOUtils.closeQuietly(contents); } return null; }
|
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:
@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); } }
|
11
|
Code Sample 1:
public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); }
Code Sample 2:
private void copyTemplateFile(String sourceRoot, String targetRoot, String extension) throws Exception { String inputFileName = sourceRoot + extension; String outputFileName = targetRoot + extension; System.out.println("Copying resource file: " + outputFileName); File inputFile = new File(inputFileName); if (!inputFile.exists() || !inputFile.canRead()) { throw new Exception("Could not read from the file " + inputFileName); } File outputFile = new File(outputFileName); if (!outputFile.exists()) { if (!outputFile.createNewFile() || !outputFile.canWrite()) throw new Exception("Could not write to the file " + outputFileName); } FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); try { char[] buffer = new char[1024]; int nread = 0; while ((nread = in.read(buffer)) != -1) { out.write(buffer, 0, nread); } } finally { in.close(); out.close(); } }
|
00
|
Code Sample 1:
public Usuario insertUsuario(IUsuario usuario) throws SQLException { Connection conn = null; String insert = "insert into Usuario (idusuario, nome, email, telefone, cpf, login, senha) " + "values " + "(nextval('seq_usuario'), '" + usuario.getNome() + "', '" + usuario.getEmail() + "', " + "'" + usuario.getTelefone() + "', '" + usuario.getCpf() + "', '" + usuario.getLogin() + "', '" + usuario.getSenha() + "')"; try { conn = connectionFactory.getConnection(true); conn.setAutoCommit(false); Statement stmt = conn.createStatement(); Integer result = stmt.executeUpdate(insert); if (result == 1) { String sqlSelect = "select last_value from seq_usuario"; ResultSet rs = stmt.executeQuery(sqlSelect); while (rs.next()) { usuario.setIdUsuario(rs.getInt("last_value")); } if (usuario instanceof Requerente) { RequerenteDAO requerenteDAO = new RequerenteDAO(); requerenteDAO.insertRequerente((Requerente) usuario, conn); } else if (usuario instanceof RecursoHumano) { RecursoHumanoDAO recursoHumanoDAO = new RecursoHumanoDAO(); recursoHumanoDAO.insertRecursoHumano((RecursoHumano) usuario, conn); } } conn.commit(); } catch (SQLException e) { conn.rollback(); throw e; } finally { conn.close(); } return null; }
Code Sample 2:
public static boolean joinFiles(File dest, Collection<File> sources) { FileInputStream fis = null; FileOutputStream fos = null; boolean rv = false; byte[] buf = new byte[1000000]; int bytesRead = 0; if (!dest.getParentFile().exists()) dest.getParentFile().mkdirs(); try { fos = new FileOutputStream(dest); for (File source : sources) { fis = new FileInputStream(source); while ((bytesRead = fis.read(buf)) > 0) fos.write(buf, 0, bytesRead); fis.close(); fis = null; } fos.close(); fos = null; rv = true; } catch (Throwable t) { throw new ApplicationException("error joining files to " + dest.getAbsolutePath(), t); } finally { if (fis != null) { try { fis.close(); } catch (Exception e) { } fis = null; } if (fos != null) { try { fos.close(); } catch (Exception e) { } fos = null; } } return rv; }
|
11
|
Code Sample 1:
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { Object msg = e.getMessage(); if (!(msg instanceof HttpMessage) && !(msg instanceof HttpChunk)) { ctx.sendUpstream(e); return; } HttpMessage currentMessage = this.currentMessage; File localFile = this.file; if (currentMessage == null) { HttpMessage m = (HttpMessage) msg; if (m.isChunked()) { final String localName = UUID.randomUUID().toString(); List<String> encodings = m.getHeaders(HttpHeaders.Names.TRANSFER_ENCODING); encodings.remove(HttpHeaders.Values.CHUNKED); if (encodings.isEmpty()) { m.removeHeader(HttpHeaders.Names.TRANSFER_ENCODING); } this.currentMessage = m; this.file = new File(Play.tmpDir, localName); this.out = new FileOutputStream(file, true); } else { ctx.sendUpstream(e); } } else { final HttpChunk chunk = (HttpChunk) msg; if (maxContentLength != -1 && (localFile.length() > (maxContentLength - chunk.getContent().readableBytes()))) { currentMessage.setHeader(HttpHeaders.Names.WARNING, "play.netty.content.length.exceeded"); } else { IOUtils.copyLarge(new ChannelBufferInputStream(chunk.getContent()), this.out); if (chunk.isLast()) { this.out.flush(); this.out.close(); currentMessage.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(localFile.length())); currentMessage.setContent(new FileChannelBuffer(localFile)); this.out = null; this.currentMessage = null; this.file = null; Channels.fireMessageReceived(ctx, currentMessage, e.getRemoteAddress()); } } } }
Code Sample 2:
private void copyMerge(Path[] sources, OutputStream out) throws IOException { Configuration conf = getConf(); for (int i = 0; i < sources.length; ++i) { FileSystem fs = sources[i].getFileSystem(conf); InputStream in = fs.open(sources[i]); try { IOUtils.copyBytes(in, out, conf, false); } finally { in.close(); } } }
|
00
|
Code Sample 1:
public Vector decode(final URL url) throws IOException { LineNumberReader reader; if (owner != null) { reader = new LineNumberReader(new InputStreamReader(new ProgressMonitorInputStream(owner, "Loading " + url, url.openStream()))); } else { reader = new LineNumberReader(new InputStreamReader(url.openStream())); } Vector v = new Vector(); String line; Vector events; try { while ((line = reader.readLine()) != null) { StringBuffer buffer = new StringBuffer(line); for (int i = 0; i < 1000; i++) { buffer.append(reader.readLine()).append("\n"); } events = decodeEvents(buffer.toString()); if (events != null) { v.addAll(events); } } } finally { partialEvent = null; try { if (reader != null) { reader.close(); } } catch (Exception e) { e.printStackTrace(); } } return v; }
Code Sample 2:
public static String encryptPassword(String password) throws PasswordException { String hash = null; if (password != null && !password.equals("")) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes("UTF-8")); byte raw[] = md.digest(); hash = String.valueOf(Base64Coder.encode(raw)); } catch (NoSuchAlgorithmException nsae) { throw new PasswordException(PasswordException.SYSTEM_ERROR); } catch (UnsupportedEncodingException uee) { throw new PasswordException(PasswordException.SYSTEM_ERROR); } } return hash; }
|
00
|
Code Sample 1:
public static SearchItem loadRecord(String id, boolean isContact) { String line = null; try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(isContact ? URL_RECORD_CONTACT : URL_RECORD_COMPANY); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(6); nameValuePairs.add(new BasicNameValuePair("format", "xml")); nameValuePairs.add(new BasicNameValuePair("token", Common.token)); nameValuePairs.add(new BasicNameValuePair("id", id)); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpClient.execute(httpPost); line = EntityUtils.toString(response.getEntity()); Document document = XMLfunctions.XMLfromString(line); NodeList nodes = document.getElementsByTagName("response"); Element e = (Element) nodes.item(0); String Name__Last__First_ = XMLfunctions.getValue(e, isContact ? "Name__Last__First_" : "Name"); String phone = ""; if (!isContact) phone = XMLfunctions.getValue(e, "Phone"); String Email1 = XMLfunctions.getValue(e, isContact ? "Personal_Email" : "Email"); String Home_Fax = XMLfunctions.getValue(e, isContact ? "Home_Fax" : "Fax1"); String Address1 = XMLfunctions.getValue(e, "Address1"); String Address2 = XMLfunctions.getValue(e, "Address2"); String City = XMLfunctions.getValue(e, "City"); String State = XMLfunctions.getValue(e, "State"); String Zip = XMLfunctions.getValue(e, "Zip"); String Country = XMLfunctions.getValue(e, "Country"); String Profile = XMLfunctions.getValue(e, "Profile"); String success = XMLfunctions.getValue(e, "success"); String error = XMLfunctions.getValue(e, "error"); SearchItem item = new SearchItem(); item.set(1, Name__Last__First_); item.set(2, phone); item.set(3, phone); item.set(4, Email1); item.set(5, Home_Fax); item.set(6, Address1); item.set(7, Address2); item.set(8, City); item.set(9, State); item.set(10, Zip); item.set(11, Profile); item.set(12, Country); item.set(13, success); item.set(14, error); return item; } catch (Exception e) { line = "<results status=\"error\"><msg>Can't connect to server</msg></results>"; line = null; } return null; }
Code Sample 2:
public String plainStringToMD5(String input) { MessageDigest md = null; byte[] byteHash = null; StringBuffer resultString = new StringBuffer(); try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.exit(-1); } md.reset(); md.update(input.getBytes()); byteHash = md.digest(); for (int i = 0; i < byteHash.length; i++) { resultString.append(Integer.toHexString(0xFF & byteHash[i])); } return (resultString.toString()); }
|
00
|
Code Sample 1:
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String contentType = req.getParameter("type"); String arg = req.getParameter("file"); if (arg == null) { resp.sendError(404, "Missing File Arg"); return; } File f = new File(arg); if (!f.exists()) { resp.sendError(404, "Missing File: " + f); return; } if (contentType != null) { resp.setContentType(contentType); } log.debug("Requested File: " + f + " as type: " + contentType); resp.setContentLength((int) f.length()); FileInputStream fis = null; try { fis = new FileInputStream(f); OutputStream os = resp.getOutputStream(); IOUtils.copyLarge(fis, os); os.flush(); fis.close(); } catch (Throwable e) { log.error("Failed to send file: " + f); resp.sendError(500, "Failed to get file " + f); } finally { IOUtils.closeQuietly(fis); } }
Code Sample 2:
public static void main(String[] args) throws IOException { httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); loginLocalhostr(); initialize(); HttpOptions httpoptions = new HttpOptions(localhostrurl); HttpResponse myresponse = httpclient.execute(httpoptions); HttpEntity myresEntity = myresponse.getEntity(); System.out.println(EntityUtils.toString(myresEntity)); fileUpload(); }
|
11
|
Code Sample 1:
public void testCodingFromFileSmaller() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); WritableByteChannel channel = newChannel(baos); HttpParams params = new BasicHttpParams(); SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 16); File tmpFile = File.createTempFile("testFile", "txt"); FileOutputStream fout = new FileOutputStream(tmpFile); OutputStreamWriter wrtout = new OutputStreamWriter(fout); wrtout.write("stuff;"); wrtout.write("more stuff;"); wrtout.flush(); wrtout.close(); FileChannel fchannel = new FileInputStream(tmpFile).getChannel(); encoder.transfer(fchannel, 0, 20); String s = baos.toString("US-ASCII"); assertTrue(encoder.isCompleted()); assertEquals("stuff;more stuff", s); tmpFile.delete(); }
Code Sample 2:
private void copyResource(final String resourceName, final File file) throws IOException { assertTrue(resourceName.startsWith("/")); InputStream in = null; boolean suppressExceptionOnClose = true; try { in = this.getClass().getResourceAsStream(resourceName); assertNotNull("Resource '" + resourceName + "' not found.", in); OutputStream out = null; try { out = new FileOutputStream(file); IOUtils.copy(in, out); suppressExceptionOnClose = false; } finally { try { if (out != null) { out.close(); } } catch (final IOException e) { if (!suppressExceptionOnClose) { throw e; } } } } finally { try { if (in != null) { in.close(); } } catch (final IOException e) { if (!suppressExceptionOnClose) { throw e; } } } }
|
00
|
Code Sample 1:
protected URLConnection openConnection(URL url) throws IOException { log.log(Level.FINE, url.toString()); MSServletRequest urlManager = new MSServletRequest(url); MicroServlet servlet = getServlet(urlManager); return (new MSConnection(url, servlet, urlManager)); }
Code Sample 2:
private static String sendGetRequest(String endpoint, String requestParameters) throws Exception { String result = null; if (endpoint.startsWith("http://")) { StringBuffer data = new StringBuffer(); String urlStr = prepareUrl(endpoint, requestParameters); URL url = new URL(urlStr); URLConnection conn = url.openConnection(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); result = sb.toString(); } return result; }
|
00
|
Code Sample 1:
public static synchronized String toMD5(String str) { Nulls.failIfNull(str, "Cannot create an MD5 encryption form a NULL string"); String hashword = null; try { MessageDigest md5 = MessageDigest.getInstance(MD5); md5.update(str.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); hashword = hash.toString(16); return Strings.padLeft(hashword, 32, "0"); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } return hashword; }
Code Sample 2:
public static void nioJoinFiles(FileLib.FileValidator validator, File target, File[] sources) { boolean big_files = false; for (int i = 0; i < sources.length; i++) { if (sources[i].length() > Integer.MAX_VALUE) { big_files = true; break; } } if (big_files) { joinFiles(validator, target, sources); } else { System.out.println(i18n.getString("jdk14_comment")); FileOutputStream fos = null; try { fos = new FileOutputStream(target); FileChannel fco = fos.getChannel(); FileInputStream fis = null; for (int i = 0; i < sources.length; i++) { fis = new FileInputStream(sources[i]); FileChannel fci = fis.getChannel(); java.nio.MappedByteBuffer map; try { map = fci.map(FileChannel.MapMode.READ_ONLY, 0, (int) sources[i].length()); fco.write(map); fci.close(); } catch (IOException ioe) { JOptionPane.showMessageDialog(null, ioe, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); try { fis.close(); fos.close(); } catch (IOException e) { } } finally { fis.close(); } } fco.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, e, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); } finally { try { if (fos != null) fos.close(); } catch (IOException e) { } } } }
|
00
|
Code Sample 1:
public static void copyResourceToFile(Class owningClass, String resourceName, File destinationDir) { final byte[] resourceBytes = readResource(owningClass, resourceName); final ByteArrayInputStream inputStream = new ByteArrayInputStream(resourceBytes); final File destinationFile = new File(destinationDir, resourceName); final FileOutputStream fileOutputStream; try { fileOutputStream = new FileOutputStream(destinationFile); } catch (FileNotFoundException e) { throw new RuntimeException(e); } try { IOUtils.copy(inputStream, fileOutputStream); } catch (IOException e) { throw new RuntimeException(e); } }
Code Sample 2:
public static String encrypt(String password, String algorithm, byte[] salt) { StringBuffer buffer = new StringBuffer(); MessageDigest digest = null; int size = 0; if ("CRYPT".equalsIgnoreCase(algorithm)) { throw new InternalError("Not implemented"); } else if ("SHA".equalsIgnoreCase(algorithm) || "SSHA".equalsIgnoreCase(algorithm)) { size = 20; if (salt != null && salt.length > 0) { buffer.append("{SSHA}"); } else { buffer.append("{SHA}"); } try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if ("MD5".equalsIgnoreCase(algorithm) || "SMD5".equalsIgnoreCase(algorithm)) { size = 16; if (salt != null && salt.length > 0) { buffer.append("{SMD5}"); } else { buffer.append("{MD5}"); } try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } int outSize = size; digest.reset(); digest.update(password.getBytes()); if (salt != null && salt.length > 0) { digest.update(salt); outSize += salt.length; } byte[] out = new byte[outSize]; System.arraycopy(digest.digest(), 0, out, 0, size); if (salt != null && salt.length > 0) { System.arraycopy(salt, 0, out, size, salt.length); } buffer.append(Base64.encode(out)); return buffer.toString(); }
|
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 void compress(File target, Set<File> files) throws CacheOperationException, ConfigurationException { ZipOutputStream zipOutput = null; try { zipOutput = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(target))); for (File file : files) { BufferedInputStream fileInput = null; File cachePathName = new File(cacheFolder, file.getPath()); try { if (!cachePathName.exists()) { throw new CacheOperationException("Expected to add file ''{0}'' to export archive ''{1}'' (Account : {2}) but it " + "has gone missing (cause unknown). This can indicate implementation or deployment " + "error. Aborting export operation as a safety precaution.", cachePathName.getPath(), target.getAbsolutePath(), account.getOid()); } fileInput = new BufferedInputStream(new FileInputStream(cachePathName)); ZipEntry entry = new ZipEntry(file.getPath()); entry.setSize(cachePathName.length()); entry.setTime(cachePathName.lastModified()); zipOutput.putNextEntry(entry); cacheLog.debug("Added new export zip entry ''{0}''.", file.getPath()); int count, total = 0; int buffer = 2048; byte[] data = new byte[buffer]; while ((count = fileInput.read(data, 0, buffer)) != -1) { zipOutput.write(data, 0, count); total += count; } zipOutput.flush(); if (total != cachePathName.length()) { throw new CacheOperationException("Only wrote {0} out of {1} bytes when archiving file ''{2}'' (Account : {3}). " + "This could have occured either due implementation error or file I/O error. " + "Aborting archive operation to prevent a potentially corrupt export archive to " + "be created.", total, cachePathName.length(), cachePathName.getPath(), account.getOid()); } else { cacheLog.debug("Wrote {0} out of {1} bytes to zip entry ''{2}''", total, cachePathName.length(), file.getPath()); } } catch (SecurityException e) { throw new ConfigurationException("Security manager has denied r/w access when attempting to read file ''{0}'' and " + "write it to archive ''{1}'' (Account : {2}) : {3}", e, cachePathName.getPath(), target, account.getOid(), e.getMessage()); } catch (IllegalArgumentException e) { throw new CacheOperationException("Error creating ZIP archive for account ID = {0} : {1}", e, account.getOid(), e.getMessage()); } catch (FileNotFoundException e) { throw new CacheOperationException("Attempted to include file ''{0}'' in export archive but it has gone missing " + "(Account : {1}). Possible implementation error in local file cache. Aborting " + "export operation as a precaution ({2})", e, cachePathName.getPath(), account.getOid(), e.getMessage()); } catch (ZipException e) { throw new CacheOperationException("Error writing export archive for account ID = {0} : {1}", e, account.getOid(), e.getMessage()); } catch (IOException e) { throw new CacheOperationException("I/O error while creating export archive for account ID = {0}. " + "Operation aborted ({1})", e, account.getOid(), e.getMessage()); } finally { if (zipOutput != null) { try { zipOutput.closeEntry(); } catch (Throwable t) { cacheLog.warn("Unable to close zip entry for file ''{0}'' in export archive ''{1}'' " + "(Account : {2}) : {3}.", t, file.getPath(), target.getAbsolutePath(), account.getOid(), t.getMessage()); } } if (fileInput != null) { try { fileInput.close(); } catch (Throwable t) { cacheLog.warn("Failed to close input stream from file ''{0}'' being added " + "to export archive (Account : {1}) : {2}", t, cachePathName.getPath(), account.getOid(), t.getMessage()); } } } } } catch (FileNotFoundException e) { throw new CacheOperationException("Unable to create target export archive ''{0}'' for account {1) : {2}", e, target, account.getOid(), e.getMessage()); } finally { try { if (zipOutput != null) { zipOutput.close(); } } catch (Throwable t) { cacheLog.warn("Failed to close the stream to export archive ''{0}'' : {1}.", t, target, t.getMessage()); } } }
|
00
|
Code Sample 1:
public static void main(String[] args) throws IOException { System.out.println("Start filtering zgps..."); final Config config = ConfigUtils.loadConfig(args[0]); final String CONFIG_MODULE = "GPSFilterZGPS"; File sourceFileSelectedStages = new File(config.findParam(CONFIG_MODULE, "sourceFileSelectedStages")); File sourceFileZGPS = new File(config.findParam(CONFIG_MODULE, "sourceFileZGPS")); File targetFile = new File(config.findParam(CONFIG_MODULE, "targetFile")); System.out.println("Start reading selected stages..."); FilterZGPSSelectedStages selectedStages = new FilterZGPSSelectedStages(); selectedStages.createSelectedStages(sourceFileSelectedStages); System.out.println("Done. " + selectedStages.getSelectedStages().size() + " stages were stored"); System.out.println("Start reading and writing zgps..."); try { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(sourceFileZGPS))); BufferedWriter out = new BufferedWriter(new FileWriter(targetFile)); out.write(in.readLine()); out.newLine(); String lineFromInputFile; while ((lineFromInputFile = in.readLine()) != null) { String[] entries = lineFromInputFile.split("\t"); if (selectedStages.containsStage(Integer.parseInt(entries[0]), Integer.parseInt(entries[1]), Integer.parseInt(entries[2]))) { out.write(lineFromInputFile); out.newLine(); out.flush(); } } in.close(); out.close(); } catch (FileNotFoundException e) { System.out.println("Could not find source file for selected stages."); e.printStackTrace(); } catch (IOException e) { System.out.println("IO Exception while reading or writing zgps."); e.printStackTrace(); } System.out.println("Done."); }
Code Sample 2:
@Override public VocabularyLocation next() { try { if (!urls.isEmpty()) { final URL url = urls.poll(); return new VocabularyLocation(url.toExternalForm(), VocabularyFormat.RDFXML, 0, url.openStream()); } if (!files.isEmpty()) { File file = files.poll(); return new VocabularyLocation(file.getCanonicalPath(), file.getName().endsWith(".ntriples") ? VocabularyFormat.NTRIPLES : VocabularyFormat.RDFXML, file.lastModified(), new FileInputStream(file)); } if (nextZipEntry != null) { String zipEntryAsString = IOUtils.toString(new CloseShieldInputStream(in), "UTF-8"); VocabularyLocation location = new VocabularyLocation(nextZipEntry.getName(), nextZipEntry.getName().endsWith(".rdf") ? VocabularyFormat.RDFXML : null, nextZipEntry.getTime(), IOUtils.toInputStream(zipEntryAsString, "UTF-8")); findNextZipEntry(); return location; } } catch (Exception e) { throw new RuntimeException(e); } throw new NoSuchElementException(); }
|
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 LispObject execute(LispObject first, LispObject second) throws ConditionThrowable { Pathname zipfilePathname = coerceToPathname(first); byte[] buffer = new byte[4096]; try { String zipfileNamestring = zipfilePathname.getNamestring(); if (zipfileNamestring == null) return error(new SimpleError("Pathname has no namestring: " + zipfilePathname.writeToString())); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfileNamestring)); LispObject list = second; while (list != NIL) { Pathname pathname = coerceToPathname(list.CAR()); String namestring = pathname.getNamestring(); if (namestring == null) { out.close(); File zipfile = new File(zipfileNamestring); zipfile.delete(); return error(new SimpleError("Pathname has no namestring: " + pathname.writeToString())); } File file = new File(namestring); FileInputStream in = new FileInputStream(file); ZipEntry entry = new ZipEntry(file.getName()); out.putNextEntry(entry); int n; while ((n = in.read(buffer)) > 0) out.write(buffer, 0, n); out.closeEntry(); in.close(); list = list.CDR(); } out.close(); } catch (IOException e) { return error(new LispError(e.getMessage())); } return zipfilePathname; }
|
00
|
Code Sample 1:
public static String EncryptString(String method, String input) { MessageDigest md = null; byte[] byteHash = null; StringBuffer resultString = new StringBuffer(); if (method.equals("SHA1") || method.equals("MD5")) { try { md = MessageDigest.getInstance(method); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); return null; } } else { return null; } md.reset(); md.update(input.getBytes()); byteHash = md.digest(); for (int i = 0; i < byteHash.length; i++) { String tmp = Integer.toHexString(0xff & byteHash[i]); if (tmp.length() < 2) tmp = "0" + tmp; resultString.append(tmp); } return (resultString.toString()); }
Code Sample 2:
public String getHtmlSource(String url) { StringBuffer codeBuffer = null; BufferedReader in = null; URLConnection uc = null; try { uc = new URL(url).openConnection(); uc.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)"); in = new BufferedReader(new InputStreamReader(uc.getInputStream(), "utf-8")); codeBuffer = new StringBuffer(); String tempCode = ""; while ((tempCode = in.readLine()) != null) { codeBuffer.append(tempCode).append("\n"); } in.close(); tempCode = null; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (null != in) in = null; if (null != uc) uc = null; } return codeBuffer.toString(); }
|
11
|
Code Sample 1:
public static void main(String[] args) throws IOException { if (args.length == 0) { System.out.println("Usage: \nGZIPcompress file\n" + "\tUses GZIP compression to compress " + "the file to test.gz"); System.exit(1); } BufferedReader in = new BufferedReader(new FileReader(args[0])); BufferedOutputStream out = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream("test.gz"))); System.out.println("Writing file"); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); System.out.println("Reading file"); BufferedReader in2 = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream("test.gz")))); String s; while ((s = in2.readLine()) != null) System.out.println(s); }
Code Sample 2:
public static void copyFile(File source, File dest) throws IOException { if (source.equals(dest)) return; FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
|
00
|
Code Sample 1:
private Scanner getUrlScanner(String strUrl) { URL urlParticipants = null; Scanner scannerParticipants; try { urlParticipants = new URL(strUrl); URLConnection connParticipants; if (StringUtils.isBlank(this.configProxyIp)) { connParticipants = urlParticipants.openConnection(); } else { SocketAddress address = new InetSocketAddress(this.configProxyIp, this.configProxyPort); Proxy proxy = new Proxy(Proxy.Type.HTTP, address); connParticipants = urlParticipants.openConnection(proxy); } InputStream streamParticipant = connParticipants.getInputStream(); String charSet = StringUtils.substringAfterLast(connParticipants.getContentType(), "charset="); scannerParticipants = new Scanner(streamParticipant, charSet); } catch (MalformedURLException e) { throw new IcehorsetoolsRuntimeException(MessageFormat.format(Lang.get(this.getClass(), "MalformedURLException"), new Object[] { urlParticipants.toString() })); } catch (IOException e) { throw new IcehorsetoolsRuntimeException(MessageFormat.format(Lang.get(this.getClass(), "IOException"), new Object[] { urlParticipants.toString() })); } return scannerParticipants; }
Code Sample 2:
public static String sendGetRequest(String urlStr) { String result = null; try { URL url = new URL(urlStr); System.out.println(urlStr); URLConnection conn = url.openConnection(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); String line = ""; System.out.println("aa" + line); while ((line = rd.readLine()) != null) { System.out.println("aa" + line); sb.append(line); } rd.close(); result = sb.toString(); } catch (Exception e) { e.printStackTrace(); } return result; }
|
00
|
Code Sample 1:
void serialize(ZipOutputStream out) throws IOException { if ("imsmanifest.xml".equals(getFullName())) return; out.putNextEntry(new ZipEntry(getFullName())); IOUtils.copy(getDataStream(), out); out.closeEntry(); }
Code Sample 2:
private void downloadFile(String url, File destFile) { try { System.out.println("Downloading " + url + " to " + destFile + "..."); destFile.getParentFile().mkdirs(); OutputStream out = new FileOutputStream(destFile); URLConnection conn = new URL(url).openConnection(); InputStream in = conn.getInputStream(); int totalSize = conn.getContentLength(), downloadedSize = 0, size; byte[] buffer = new byte[32768]; ProgressMonitor pm = new ProgressMonitor(null, "Downloading " + url, "", 0, totalSize); pm.setMillisToDecideToPopup(100); pm.setMillisToPopup(500); boolean canceled = false; while ((size = in.read(buffer)) > 0 && !(canceled = pm.isCanceled())) { out.write(buffer, 0, size); pm.setProgress(downloadedSize += size); pm.setNote((100 * downloadedSize / totalSize) + "% finished"); } in.close(); out.close(); if (canceled) { destFile.delete(); fatalError("Starting canceled", "Downloading canceled. Exiting..."); } pm.close(); } catch (IOException ex) { ex.printStackTrace(); destFile.delete(); fatalError("Download Error", "Couldn't download file " + url + ": " + ex); } }
|
00
|
Code Sample 1:
public static int gunzipFile(File file_input, File dir_output) { GZIPInputStream gzip_in_stream; try { FileInputStream in = new FileInputStream(file_input); BufferedInputStream source = new BufferedInputStream(in); gzip_in_stream = new GZIPInputStream(source); } catch (IOException e) { return STATUS_IN_FAIL; } String file_input_name = file_input.getName(); String file_output_name = file_input_name.substring(0, file_input_name.length() - 3); File output_file = new File(dir_output, file_output_name); byte[] input_buffer = new byte[BUF_SIZE]; int len = 0; try { FileOutputStream out = new FileOutputStream(output_file); BufferedOutputStream destination = new BufferedOutputStream(out, BUF_SIZE); while ((len = gzip_in_stream.read(input_buffer, 0, BUF_SIZE)) != -1) destination.write(input_buffer, 0, len); destination.flush(); out.close(); } catch (IOException e) { return STATUS_GUNZIP_FAIL; } try { gzip_in_stream.close(); } catch (IOException e) { } return STATUS_OK; }
Code Sample 2:
public boolean visar() throws SQLException, ClassNotFoundException, Exception { Connection conn = null; PreparedStatement ps = null; Date fechaSystem = new Date(); DateFormat aaaammdd = new SimpleDateFormat("yyyyMMdd"); DateFormat hhmmss = new SimpleDateFormat("HHmmss"); DateFormat sss = new SimpleDateFormat("S"); String ss = sss.format(fechaSystem); if (ss.length() > 2) { ss = ss.substring(0, 2); } boolean visado = false; try { conn = ToolsBD.getConn(); conn.setAutoCommit(false); String sentenciaSql = "UPDATE BZMODIF SET FZJCUSVI=?, FZJFVISA=?, FZJHVISA=?" + ((hayVisadoExtracto) ? ", FZJIEXTR=?" : "") + ((hayVisadoRemitente) ? ", FZJIREMI=?" : "") + " WHERE FZJCENSA='E' AND FZJCAGCO=? AND FZJNUMEN=? AND FZJANOEN=? AND FZJFMODI=? AND FZJHMODI=?"; ps = conn.prepareStatement(sentenciaSql); ps.setString(1, usuarioVisado); ps.setInt(2, Integer.parseInt(aaaammdd.format(fechaSystem))); ps.setInt(3, Integer.parseInt(hhmmss.format(fechaSystem) + ss)); int contador = 4; if (hayVisadoExtracto) { ps.setString(contador++, "X"); } if (hayVisadoRemitente) { ps.setString(contador++, "X"); } ps.setInt(contador++, oficina); ps.setInt(contador++, numeroRegistro); ps.setInt(contador++, anoEntrada); ps.setString(contador++, fechaModificacion); ps.setString(contador++, horaModificacion); int registrosAfectados = ps.executeUpdate(); if (registrosAfectados > 0 && !hayVisadoExtracto && !hayVisadoRemitente) { visado = true; } if (registrosAfectados > 0 && (hayVisadoExtracto || hayVisadoRemitente)) { boolean generado = generarBZVISAD(conn, Integer.parseInt(aaaammdd.format(fechaSystem)), Integer.parseInt(hhmmss.format(fechaSystem) + ss)); if (generado) { visado = actualizarBZENTRA(conn); } String rem = ""; String com = ""; if (hayVisadoRemitente) { if (!remitente.trim().equals("")) { rem = remitente; } else { javax.naming.InitialContext contexto = new javax.naming.InitialContext(); Object ref = contexto.lookup("es.caib.regweb.ValoresHome"); ValoresHome home = (ValoresHome) javax.rmi.PortableRemoteObject.narrow(ref, ValoresHome.class); Valores valor = home.create(); rem = valor.recuperaRemitenteCastellano(entidad1, entidad2 + ""); valor.remove(); } } else { if (!altres.trim().equals("")) { rem = remitente; } else { javax.naming.InitialContext contexto = new javax.naming.InitialContext(); Object ref = contexto.lookup("es.caib.regweb.ValoresHome"); ValoresHome home = (ValoresHome) javax.rmi.PortableRemoteObject.narrow(ref, ValoresHome.class); Valores valor = home.create(); rem = valor.recuperaRemitenteCastellano(entidad1Old, entidad2Old + ""); valor.remove(); } } if (hayVisadoExtracto) { com = extracto; } else { com = comentario; } try { Class t = Class.forName("es.caib.regweb.module.PluginHook"); Class[] partypes = { String.class, Integer.class, Integer.class, Integer.class, Integer.class, String.class, String.class, String.class, Integer.class, Integer.class, String.class, Integer.class, String.class, String.class, Integer.class, Integer.class, Integer.class, String.class, String.class, String.class }; Object[] params = { "V", new Integer(anoEntrada), new Integer(numeroRegistro), new Integer(oficina), new Integer(fechaDocumento), rem, com, tipoDocumento, new Integer(fechaRegistro), new Integer(fzacagge), fora, new Integer(destinatario), idioma, null, null, null, null, null, null, null }; java.lang.reflect.Method metodo = t.getMethod("entrada", partypes); metodo.invoke(null, params); } catch (IllegalAccessException iae) { } catch (IllegalArgumentException iae) { } catch (InvocationTargetException ite) { } catch (NullPointerException npe) { } catch (ExceptionInInitializerError eiie) { } catch (NoSuchMethodException nsme) { } catch (SecurityException se) { } catch (LinkageError le) { } catch (ClassNotFoundException le) { } } conn.commit(); int fzahsis = Integer.parseInt(hhmmss.format(fechaSystem) + ss); String Stringsss = sss.format(fechaSystem); switch(Stringsss.length()) { case (1): Stringsss = "00" + Stringsss; break; case (2): Stringsss = "0" + Stringsss; break; } int horamili = Integer.parseInt(hhmmss.format(fechaSystem) + Stringsss); int fzafsis = Integer.parseInt(aaaammdd.format(fechaSystem)); logLopdBZMODIF("UPDATE", sessioEjb.getCallerPrincipal().getName().toUpperCase(), fzafsis, horamili, 'E', numeroRegistro, anoEntrada, oficina, Integer.parseInt(fechaModificacion), Integer.parseInt(horaModificacion)); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); e.printStackTrace(); visado = false; try { if (conn != null) conn.rollback(); else System.out.println("ERROR: No es pot fer rollback sense connexió!"); } catch (Exception ex) { System.out.println("Error: " + ex.getMessage()); ex.printStackTrace(); } } finally { ToolsBD.closeConn(conn, ps, null); } return visado; }
|
11
|
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:
public static void nioJoinFiles(FileLib.FileValidator validator, File target, File[] sources) { boolean big_files = false; for (int i = 0; i < sources.length; i++) { if (sources[i].length() > Integer.MAX_VALUE) { big_files = true; break; } } if (big_files) { joinFiles(validator, target, sources); } else { System.out.println(i18n.getString("jdk14_comment")); FileOutputStream fos = null; try { fos = new FileOutputStream(target); FileChannel fco = fos.getChannel(); FileInputStream fis = null; for (int i = 0; i < sources.length; i++) { fis = new FileInputStream(sources[i]); FileChannel fci = fis.getChannel(); java.nio.MappedByteBuffer map; try { map = fci.map(FileChannel.MapMode.READ_ONLY, 0, (int) sources[i].length()); fco.write(map); fci.close(); } catch (IOException ioe) { JOptionPane.showMessageDialog(null, ioe, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); try { fis.close(); fos.close(); } catch (IOException e) { } } finally { fis.close(); } } fco.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, e, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); } finally { try { if (fos != null) fos.close(); } catch (IOException e) { } } } }
|
11
|
Code Sample 1:
private void copyFile(String fileName, String messageID, boolean isError) { try { File inputFile = new File(fileName); File outputFile = null; if (isError) { outputFile = new File(provider.getErrorDataLocation(folderName) + messageID + ".xml"); } else { outputFile = new File(provider.getDataProcessedLocation(folderName) + messageID + ".xml"); } FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception e) { } }
Code Sample 2:
@RequestMapping("/download") public void download(HttpServletRequest request, HttpServletResponse response) { InputStream input = null; ServletOutputStream output = null; try { String savePath = request.getSession().getServletContext().getRealPath("/upload"); String fileType = ".log"; String dbFileName = "83tomcat日志测试哦"; String downloadFileName = dbFileName + fileType; String finalPath = "\\2011-12\\01\\8364b45f-244d-41b6-bbf48df32064a935"; downloadFileName = new String(downloadFileName.getBytes("GBK"), "ISO-8859-1"); File downloadFile = new File(savePath + finalPath); if (!downloadFile.getParentFile().exists()) { downloadFile.getParentFile().mkdirs(); } if (!downloadFile.isFile()) { FileUtils.touch(downloadFile); } response.setContentType("aapplication/vnd.ms-excel ;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); response.setHeader("content-disposition", "attachment; filename=" + downloadFileName); input = new FileInputStream(downloadFile); output = response.getOutputStream(); IOUtils.copy(input, output); output.flush(); } catch (Exception e) { logger.error("Exception: ", e); } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(input); } }
|
00
|
Code Sample 1:
@Override protected IStatus run(final IProgressMonitor monitor) { try { showTileInfo(remoteFileName, -1); System.out.println(" connect " + host); ftp.connect(); showTileInfo(remoteFileName, -2); System.out.println(" login " + user + " " + password); ftp.login(user, password); System.out.println(" set passive mode"); ftp.setConnectMode(FTPConnectMode.PASV); System.out.println(" set type binary"); ftp.setType(FTPTransferType.BINARY); showTileInfo(remoteFileName, -3); System.out.println(" chdir " + remoteFilePath); ftp.chdir(remoteFilePath); ftp.setProgressMonitor(new FTPProgressMonitor() { public void bytesTransferred(final long count) { tileInfoMgr.updateSRTMTileInfo(TileEventId.SRTM_DATA_LOADING_MONITOR, remoteFileName, count); } }); showTileInfo(remoteFileName, -4); System.out.println(" get " + remoteFileName + " -> " + localName + " ..."); ftp.get(localName, remoteFileName); System.out.println(" quit"); ftp.quit(); } catch (final UnknownHostException e) { return new Status(IStatus.ERROR, TourbookPlugin.PLUGIN_ID, IStatus.ERROR, NLS.bind(Messages.error_message_cannotConnectToServer, host), e); } catch (final SocketTimeoutException e) { return new Status(IStatus.ERROR, TourbookPlugin.PLUGIN_ID, IStatus.ERROR, NLS.bind(Messages.error_message_timeoutWhenConnectingToServer, host), e); } catch (final Exception e) { e.printStackTrace(); tileInfoMgr.updateSRTMTileInfo(TileEventId.SRTM_DATA_ERROR_LOADING, remoteFileName, 0); } finally { tileInfoMgr.updateSRTMTileInfo(TileEventId.SRTM_DATA_END_LOADING, remoteFileName, 0); } return Status.OK_STATUS; }
Code Sample 2:
private void downloadFile(String name, URL url, File file) throws IOException { InputStream in = null; FileOutputStream out = null; try { URLConnection conn = url.openConnection(); conn.setConnectTimeout(10000); conn.setReadTimeout(10000); int expectedSize = conn.getContentLength(); progressPanel.downloadStarting(name, expectedSize == -1); int downloaded = 0; byte[] buf = new byte[1024]; int length; in = conn.getInputStream(); out = new FileOutputStream(file); while ((in != null) && ((length = in.read(buf)) != -1)) { downloaded += length; out.write(buf, 0, length); if (expectedSize != -1) progressPanel.downloadProgress((downloaded * 100) / expectedSize); } out.flush(); } finally { progressPanel.downloadFinished(); if (out != null) out.close(); if (in != null) in.close(); } }
|
00
|
Code Sample 1:
public static String md5(String str) { try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(str.getBytes()); byte messageDigest[] = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) hexString.append(Integer.toHexString(0xFF & messageDigest[i])); String md5 = hexString.toString(); Log.v(FileUtil.class.getName(), md5); return md5; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; }
Code Sample 2:
private void doLogin() { try { println("Logging in as '" + username.getText() + "'"); URL url = new URL("http://" + hostname + "/migrate"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(URLEncoder.encode("login", "UTF-8") + "=" + encodeCredentials()); wr.flush(); BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(in); Element root = doc.getDocumentElement(); in.close(); if (root.getAttribute("success").equals("false")) { println("Login Failed: " + getTextContent(root)); JOptionPane.showMessageDialog(this, "Login Failed: " + getTextContent(root), "Login Failed", JOptionPane.ERROR_MESSAGE); } else { token = root.hasAttribute("token") ? root.getAttribute("token") : null; if (token != null) { startImport(); } } } catch (Exception e) { ErrorReporter.showError(e, this); println(e.toString()); } }
|
00
|
Code Sample 1:
private String httpGet(String urlString, boolean postStatus) throws Exception { URL url; URLConnection conn; String answer = ""; try { if (username.equals("") || password.equals("")) throw new AuthNotProvidedException(); url = new URL(urlString); conn = url.openConnection(); conn.setRequestProperty("Authorization", "Basic " + getAuthentificationString()); if (postStatus) { conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); DataOutputStream das = new DataOutputStream(conn.getOutputStream()); String content = "status=" + URLEncoder.encode(statusMessage, "UTF-8") + "&source=" + URLEncoder.encode("sametimetwitterclient", "UTF-8"); das.writeBytes(content); das.flush(); das.close(); } InputStream is = (InputStream) conn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; while ((line = br.readLine()) != null) { answer += line + "\n"; } br.close(); } catch (FileNotFoundException ex) { System.out.println(ex.toString()); throw new RuntimeException("Page not Found. Maybe Twitter-API has changed."); } catch (UnknownHostException ex) { System.out.println(ex.toString()); throw new RuntimeException("Network connection problems. Could not find twitter.com"); } catch (IOException ex) { System.out.println("IO-Exception"); if (ex.getMessage().indexOf("401") > -1) { authenthicated = AUTH_BAD; throw new AuthNotAcceptedException(); } System.out.println(ex.toString()); } if (checkForError(answer) != null) { throw new RuntimeException(checkForError(answer)); } authenthicated = AUTH_OK; return answer; }
Code Sample 2:
public static void main(String[] args) throws IOException { System.setProperty("java.protocol.xfile", "com.luzan.common.nfs"); if (args.length < 1) usage(); final String cmd = args[0]; if ("delete".equalsIgnoreCase(cmd)) { final String path = getParameter(args, 1); XFile xfile = new XFile(path); if (!xfile.exists()) { System.out.print("File doean't exist.\n"); System.exit(1); } xfile.delete(); } else if ("copy".equalsIgnoreCase(cmd)) { final String pathFrom = getParameter(args, 1); final String pathTo = getParameter(args, 2); final XFile xfileFrom = new XFile(pathFrom); final XFile xfileTo = new XFile(pathTo); if (!xfileFrom.exists()) { System.out.print("File doesn't exist.\n"); System.exit(1); } final String mime = getParameter(args, 3, null); final XFileInputStream in = new XFileInputStream(xfileFrom); final XFileOutputStream xout = new XFileOutputStream(xfileTo); if (!StringUtils.isEmpty(mime)) { final com.luzan.common.nfs.s3.XFileExtensionAccessor xfa = ((com.luzan.common.nfs.s3.XFileExtensionAccessor) xfileTo.getExtensionAccessor()); if (xfa != null) { xfa.setMimeType(mime); xfa.setContentLength(xfileFrom.length()); } } IOUtils.copy(in, xout); xout.flush(); xout.close(); in.close(); } }
|
00
|
Code Sample 1:
protected int getResponseCode(String address) throws Exception { URL url = new URL(address); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setUseCaches(false); try { con.connect(); return con.getResponseCode(); } finally { con.disconnect(); } }
Code Sample 2:
public static String unsecureHashConstantSalt(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException { password = SALT3 + password; MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes(), 0, password.length()); password += convertToHex(md5.digest()) + SALT4; MessageDigest md = MessageDigest.getInstance("SHA-512"); byte[] sha1hash = new byte[40]; md.update(password.getBytes("UTF-8"), 0, password.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
|
11
|
Code Sample 1:
public static void downloadJars(IProject project, String repositoryUrl, String jarDirectory, String[] jars) { try { File tmpFile = null; for (String jar : jars) { try { tmpFile = File.createTempFile("tmpPlugin_", ".zip"); URL url = new URL(repositoryUrl + jarDirectory + jar); String destFilename = new File(url.getFile()).getName(); File destFile = new File(project.getLocation().append("lib").append(jarDirectory).toFile(), destFilename); InputStream inputStream = null; FileOutputStream outputStream = null; try { URLConnection urlConnection = url.openConnection(); inputStream = urlConnection.getInputStream(); outputStream = new FileOutputStream(tmpFile); IOUtils.copy(inputStream, outputStream); } finally { if (outputStream != null) { outputStream.close(); } if (inputStream != null) { inputStream.close(); } } FileUtils.copyFile(tmpFile, destFile); } finally { if (tmpFile != null) { tmpFile.delete(); } } } } catch (Exception ex) { ex.printStackTrace(); } }
Code Sample 2:
public void copieFichier(String fileIn, String fileOut) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(fileIn).getChannel(); out = new FileOutputStream(fileOut).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) { } } } }
|
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:
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(); } }
|
11
|
Code Sample 1:
private static void copyFile(File sourceFile, File destFile) throws IOException { System.out.println(sourceFile.getAbsolutePath()); System.out.println(destFile.getAbsolutePath()); FileChannel source = new FileInputStream(sourceFile).getChannel(); try { FileChannel destination = new FileOutputStream(destFile).getChannel(); try { destination.transferFrom(source, 0, source.size()); } finally { if (destination != null) { destination.close(); } } } finally { source.close(); } }
Code Sample 2:
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String arg = req.getParameter("file"); if (arg == null) { resp.sendError(404, "Missing 'file' Arg"); return; } int mfid = NumberUtils.toInt(arg); Object sageFile = MediaFileAPI.GetMediaFileForID(mfid); if (sageFile == null) { resp.sendError(404, "Sage File not found " + mfid); return; } int seconds = NumberUtils.toInt(req.getParameter("ss"), -1); long offset = NumberUtils.toLong(req.getParameter("sb"), -1); if (seconds < 0 && offset < 0) { resp.sendError(501, "Missing 'ss' or 'sb' args"); return; } int width = NumberUtils.toInt(req.getParameter("w"), 320); int height = NumberUtils.toInt(req.getParameter("h"), 320); File dir = new File(Phoenix.getInstance().getUserCacheDir(), "videothumb/" + mfid); if (!dir.exists()) { dir.mkdirs(); } String prefix = ""; if (offset > 0) { prefix = "O" + offset; } else { prefix = "S" + seconds; } File f = new File(dir, prefix + "_" + width + "_" + height + ".jpg").getCanonicalFile(); if (!f.exists()) { try { generateThumbnailNew(sageFile, f, seconds, offset, width, height); } catch (Exception e) { e.printStackTrace(); resp.sendError(503, "Failed to generate thumbnail\n " + e.getMessage()); return; } } if (!f.exists()) { resp.sendError(404, "Missing File: " + f); return; } resp.setContentType("image/jpeg"); resp.setContentLength((int) f.length()); FileInputStream fis = null; try { fis = new FileInputStream(f); OutputStream os = resp.getOutputStream(); IOUtils.copyLarge(fis, os); os.flush(); fis.close(); } catch (Throwable e) { log.error("Failed to send file: " + f); resp.sendError(500, "Failed to get file " + f); } finally { IOUtils.closeQuietly(fis); } }
|
00
|
Code Sample 1:
public String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
Code Sample 2:
public static final void zip(final ZipOutputStream out, final File f, String base) throws Exception { if (f.isDirectory()) { final File[] fl = f.listFiles(); base = base.length() == 0 ? "" : base + File.separator; for (final File element : fl) { zip(out, element, base + element.getName()); } } else { out.putNextEntry(new org.apache.tools.zip.ZipEntry(base)); final FileInputStream in = new FileInputStream(f); IOUtils.copyStream(in, out); in.close(); } Thread.sleep(10); }
|
00
|
Code Sample 1:
private List<String> getContainedFilePaths(URL url) throws Exception { JarInputStream jis = new JarInputStream(url.openStream()); ZipEntry zentry = null; ArrayList<String> fullNames = new ArrayList<String>(); while ((zentry = jis.getNextEntry()) != null) { String name = zentry.getName(); if (!zentry.isDirectory()) { fullNames.add(name); } } jis.close(); return (fullNames); }
Code Sample 2:
protected String insertCommand(String command) throws ServletException { String digest; try { MessageDigest md = MessageDigest.getInstance(m_messagedigest_algorithm); md.update(command.getBytes()); byte bytes[] = new byte[20]; m_random.nextBytes(bytes); md.update(bytes); digest = bytesToHex(md.digest()); } catch (NoSuchAlgorithmException e) { throw new ServletException("NoSuchAlgorithmException while " + "attempting to generate graph ID: " + e); } String id = System.currentTimeMillis() + "-" + digest; m_map.put(id, command); return id; }
|
11
|
Code Sample 1:
public void run() { try { FileChannel in = (new FileInputStream(file)).getChannel(); FileChannel out = (new FileOutputStream(updaterFile)).getChannel(); in.transferTo(0, file.length(), out); updater.setProgress(50); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } startUpdater(); }
Code Sample 2:
@Action(value = "ajaxFileUploads", results = { }) public void ajaxFileUploads() throws IOException { String extName = ""; String newFilename = ""; String nowTimeStr = ""; String realpath = ""; if (Validate.StrNotNull(this.getImgdirpath())) { realpath = "Uploads/" + this.getImgdirpath() + "/"; } else { realpath = this.isexistdir(); } SimpleDateFormat sDateFormat; Random r = new Random(); String savePath = ServletActionContext.getServletContext().getRealPath(""); savePath = savePath + realpath; HttpServletResponse response = ServletActionContext.getResponse(); int rannum = (int) (r.nextDouble() * (99999 - 1000 + 1)) + 10000; sDateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); nowTimeStr = sDateFormat.format(new Date()); String filename = request.getHeader("X-File-Name"); if (filename.lastIndexOf(".") >= 0) { extName = filename.substring(filename.lastIndexOf(".")); } newFilename = nowTimeStr + rannum + extName; PrintWriter writer = null; InputStream is = null; FileOutputStream fos = null; try { writer = response.getWriter(); } catch (IOException ex) { log.debug(ImgTAction.class.getName() + "has thrown an exception:" + ex.getMessage()); } try { is = request.getInputStream(); fos = new FileOutputStream(new File(savePath + newFilename)); IOUtils.copy(is, fos); response.setStatus(response.SC_OK); writer.print("{success:'" + realpath + newFilename + "'}"); } catch (FileNotFoundException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log.debug(ImgTAction.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log.debug(ImgTAction.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { this.setImgdirpath(null); fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); }
|
11
|
Code Sample 1:
public static void main(String[] args) throws MalformedURLException, IOException { InputStream in = null; try { in = new URL("hdfs://localhost:8020/user/leeing/maxtemp/sample.txt").openStream(); IOUtils.copyBytes(in, System.out, 8192, false); } finally { IOUtils.closeStream(in); System.out.println("\nend."); } }
Code Sample 2:
private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } }
|
00
|
Code Sample 1:
public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException { String bundleName = toBundleName(baseName, locale); String resourceName = toResourceName(bundleName, "properties"); ResourceBundle bundle = null; InputStream stream = null; if (reload) { URL url = loader.getResource(resourceName); if (url != null) { URLConnection connection = url.openConnection(); if (connection != null) { connection.setUseCaches(false); stream = connection.getInputStream(); } } } else { stream = loader.getResourceAsStream(resourceName); } if (stream != null) { try { bundle = new PropertyResourceBundle(new InputStreamReader(stream, "UTF-8")); } finally { stream.close(); } } return bundle; }
Code Sample 2:
private void _scanForMetaData(URL _url) throws java.io.IOException { if (DEBUG.Enabled) System.out.println(this + " _scanForMetaData: xml props " + mXMLpropertyList); if (DEBUG.Enabled) System.out.println("*** Opening connection to " + _url); markAccessAttempt(); Properties metaData = scrapeHTMLmetaData(_url.openConnection(), 2048); if (DEBUG.Enabled) System.out.println("*** Got meta-data " + metaData); markAccessSuccess(); String title = metaData.getProperty("title"); if (title != null && title.length() > 0) { setProperty("title", title); title = title.replace('\n', ' ').trim(); setTitle(title); } try { setByteSize(Integer.parseInt((String) getProperty("contentLength"))); } catch (Exception e) { } }
|
11
|
Code Sample 1:
public static long writeInputStreamToOutputStream(final InputStream in, final OutputStream out) { long size = 0; try { size = IOUtils.copyLarge(in, out); } catch (IOException e1) { e1.printStackTrace(); } return size; }
Code Sample 2:
public void save(File f, AudioFileFormat.Type t) throws IOException { if (t.getExtension().equals("raw")) { IOUtils.copy(makeInputStream(), new FileOutputStream(f)); } else { AudioSystem.write(makeStream(), t, f); } }
|
11
|
Code Sample 1:
public static String getMD5(String input) { String res = ""; try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(input.getBytes("ISO8859_1")); byte[] md5 = algorithm.digest(); String tmp = ""; for (int i = 0; i < md5.length; i++) { tmp = (Integer.toHexString(0xFF & md5[i])); if (tmp.length() == 1) { res += "0" + tmp; } else { res += tmp; } } } catch (Exception ex) { } return res; }
Code Sample 2:
public byte[] getCoded(String name, String pass) { byte[] digest = null; if (pass != null && 0 < pass.length()) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(name.getBytes()); md.update(pass.getBytes()); digest = md.digest(); } catch (Exception e) { e.printStackTrace(); digest = null; } } return digest; }
|
00
|
Code Sample 1:
private String buildShaHashOf(String source) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(source.getBytes()); return new BigInteger(1, md.digest()).toString(16); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return ""; } }
Code Sample 2:
public static List importSymbol(Report report, Symbol symbol, TradingDate startDate, TradingDate endDate) throws IOException { List quotes = new ArrayList(); String URLString = constructURL(symbol, startDate, endDate); QuoteFilter filter = new YahooQuoteFilter(symbol); PreferencesManager.ProxyPreferences proxyPreferences = PreferencesManager.loadProxySettings(); try { URL url = new URL(URLString); InputStreamReader input = new InputStreamReader(url.openStream()); BufferedReader bufferedInput = new BufferedReader(input); String line = bufferedInput.readLine(); while (line != null) { line = bufferedInput.readLine(); if (line != null) { try { Quote quote = filter.toQuote(line); quotes.add(quote); verify(report, quote); } catch (QuoteFormatException e) { report.addError(Locale.getString("YAHOO") + ":" + symbol + ":" + Locale.getString("ERROR") + ": " + e.getMessage()); } } } bufferedInput.close(); } catch (BindException e) { DesktopManager.showErrorMessage(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); throw new IOException(); } catch (ConnectException e) { DesktopManager.showErrorMessage(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); throw new IOException(); } catch (UnknownHostException e) { DesktopManager.showErrorMessage(Locale.getString("UNKNOWN_HOST_ERROR", e.getMessage())); throw new IOException(); } catch (NoRouteToHostException e) { DesktopManager.showErrorMessage(Locale.getString("DESTINATION_UNREACHABLE_ERROR", e.getMessage())); throw new IOException(); } catch (MalformedURLException e) { DesktopManager.showErrorMessage(Locale.getString("INVALID_PROXY_ERROR", proxyPreferences.host, proxyPreferences.port)); throw new IOException(); } catch (FileNotFoundException e) { report.addError(Locale.getString("YAHOO") + ":" + symbol + ":" + Locale.getString("ERROR") + ": " + Locale.getString("NO_QUOTES_FOUND")); } catch (IOException e) { DesktopManager.showErrorMessage(Locale.getString("ERROR_DOWNLOADING_QUOTES")); throw new IOException(); } return quotes; }
|
11
|
Code Sample 1:
private void copyFile(String inputPath, String basis, String filename) throws GLMRessourceFileException { try { FileChannel inChannel = new FileInputStream(new File(inputPath)).getChannel(); File target = new File(basis, filename); FileChannel outChannel = new FileOutputStream(target).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); inChannel.close(); outChannel.close(); } catch (Exception e) { throw new GLMRessourceFileException(7); } }
Code Sample 2:
private void copyTemplateFile(String sourceRoot, String targetRoot, String extension) throws Exception { String inputFileName = sourceRoot + extension; String outputFileName = targetRoot + extension; System.out.println("Copying resource file: " + outputFileName); File inputFile = new File(inputFileName); if (!inputFile.exists() || !inputFile.canRead()) { throw new Exception("Could not read from the file " + inputFileName); } File outputFile = new File(outputFileName); if (!outputFile.exists()) { if (!outputFile.createNewFile() || !outputFile.canWrite()) throw new Exception("Could not write to the file " + outputFileName); } FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); try { char[] buffer = new char[1024]; int nread = 0; while ((nread = in.read(buffer)) != -1) { out.write(buffer, 0, nread); } } finally { in.close(); out.close(); } }
|
11
|
Code Sample 1:
public void testCryptHash() { Log.v("Test", "[*] testCryptHash()"); String testStr = "Hash me"; byte messageDigest[]; MessageDigest digest = null; try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(testStr.getBytes()); messageDigest = digest.digest(); digest.digest(testStr.getBytes()); digest = java.security.MessageDigest.getInstance("SHA1"); digest.update(testStr.getBytes()); messageDigest = digest.digest(); digest = null; digest = java.security.MessageDigest.getInstance("SHA1"); digest.update(imei.getBytes()); messageDigest = digest.digest(); hashedImei = this.toHex(messageDigest); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } }
Code Sample 2:
@Transient private String md5sum(String text) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(text.getBytes()); byte messageDigest[] = md.digest(); return bufferToHex(messageDigest, 0, messageDigest.length); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; }
|
00
|
Code Sample 1:
public static boolean doExecuteBatchSQL(List<String> sql) { session = currentSession(); Connection conn = session.connection(); PreparedStatement ps = null; try { conn.setAutoCommit(false); Iterator iter = sql.iterator(); while (iter.hasNext()) { String sqlstr = (String) iter.next(); log("[SmsManager] doing sql:" + sqlstr); ps = conn.prepareStatement(sqlstr); ps.executeUpdate(); } conn.commit(); conn.setAutoCommit(true); return true; } catch (SQLException e) { e.printStackTrace(); try { conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } return false; } finally { if (conn != null) try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } closeHibernateSession(); } }
Code Sample 2:
public Configuration(URL url) { InputStream in = null; try { load(in = url.openStream()); } catch (Exception e) { throw new RuntimeException("Could not load configuration from " + url, e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } }
|
11
|
Code Sample 1:
@Override public String getPath() { InputStream in = null; OutputStream out = null; File file = null; try { file = File.createTempFile("java-storage_" + RandomStringUtils.randomAlphanumeric(32), ".tmp"); file.deleteOnExit(); out = new FileOutputStream(file); in = openStream(); IOUtils.copy(in, out); } catch (IOException e) { throw new RuntimeException(); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } if (file != null && file.exists()) { return file.getPath(); } return null; }
Code Sample 2:
public void checkFilesAndCopyValid(String filename) { downloadResults(); loadResults(); File tmpFolderF = new File(tmpFolder); deleteFileFromTMPFolder(tmpFolderF); ZipReader zr = new ZipReader(); zr.UnzipFile(filename); try { LogManager.getInstance().log("Ov��uji odevzdan� soubory a kop�ruji validovan�:"); LogManager.getInstance().log(""); JAXBElement<?> element = ElementJAXB.getJAXBElement(); Ppa1VysledkyCviceniType pvct = (Ppa1VysledkyCviceniType) element.getValue(); File zipFolder = new File(tmpFolder).listFiles()[0].listFiles()[0].listFiles()[0]; File[] zipFolderList = zipFolder.listFiles(); for (File studentDirectory : zipFolderList) { if (studentDirectory.isDirectory()) { String osobniCisloZeSlozky = studentDirectory.getName().split("-")[0]; LogManager.getInstance().changeLog("Prov��ov�n� soubor� studenta s ��slem: " + osobniCisloZeSlozky); List<StudentType> students = (List<StudentType>) pvct.getStudent(); for (StudentType student : students) { if (student.getOsobniCislo().equals(osobniCisloZeSlozky)) { int pzp = student.getDomaciUlohy().getPosledniZpracovanyPokus().getCislo().intValue(); DomaciUlohyType dut = student.getDomaciUlohy(); ChybneOdevzdaneType chot = dut.getChybneOdevzdane(); ObjectFactory of = new ObjectFactory(); File[] pokusyDirectories = studentDirectory.listFiles(); NodeList souboryNL = result.getElementsByTagName("soubor"); int start = souboryNL.getLength() - 1; boolean samostatnaPrace = false; for (int i = (pokusyDirectories.length - 1); i >= 0; i--) { if ((pokusyDirectories[i].isDirectory()) && (pzp < Integer.parseInt(pokusyDirectories[i].getName().split("_")[1].trim()))) { File testedFile = pokusyDirectories[i].listFiles()[0]; if ((testedFile.exists()) && (testedFile.isFile())) { String[] partsOfFilename = testedFile.getName().split("_"); String osobniCisloZeSouboru = "", priponaSouboru = ""; String[] posledniCastSouboru = null; if (partsOfFilename.length == 4) { posledniCastSouboru = partsOfFilename[3].split("[.]"); osobniCisloZeSouboru = posledniCastSouboru[0]; if (posledniCastSouboru.length <= 1) priponaSouboru = ""; else priponaSouboru = posledniCastSouboru[1]; } String samostatnaPraceNazev = Konfigurace.getInstance().getSamostatnaPraceNazev(); List<SouborType> lst = chot.getSoubor(); if (testedFile.getName().startsWith(samostatnaPraceNazev)) { samostatnaPrace = true; } else { samostatnaPrace = false; if (partsOfFilename.length != 4) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("�patn� struktura jm�na souboru."); lst.add(st); continue; } else if (!testedFile.getName().startsWith("Ppa1_cv")) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("�patn� za��tek jm�na souboru."); lst.add(st); continue; } else if (!priponaSouboru.equals("java")) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("�patn� p��pona souboru."); lst.add(st); continue; } else if (!osobniCisloZeSouboru.equals(osobniCisloZeSlozky)) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("Nesouhlas� osobn� ��sla."); lst.add(st); continue; } else if (partsOfFilename[3].split("[.]").length > 2) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("V�ce p��pon souboru."); lst.add(st); continue; } else { long cisloCviceni, cisloUlohy; try { if (partsOfFilename[1].length() == 4) { String cisloS = partsOfFilename[1].substring(2); long cisloL = Long.parseLong(cisloS); cisloCviceni = cisloL; } else { throw new NumberFormatException(); } } catch (NumberFormatException e) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("Chyb� (nebo je chybn�) ��slo cvi�en�"); lst.add(st); continue; } try { if (partsOfFilename[2].length() > 0) { String cisloS = partsOfFilename[2]; long cisloL = Long.parseLong(cisloS); cisloUlohy = cisloL; } else { throw new NumberFormatException(); } } catch (NumberFormatException e) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("Chyb� (nebo je chybn�) ��slo �lohy"); lst.add(st); continue; } CislaUloh ci = new CislaUloh(); List<long[]> cviceni = ci.getSeznamCviceni(); boolean nalezenoCv = false, nalezenaUl = false; for (long[] c : cviceni) { if (c[0] == cisloCviceni) { for (int j = 1; j < c.length; j++) { if (c[j] == cisloUlohy) { nalezenaUl = true; break; } } nalezenoCv = true; break; } } if (!nalezenoCv) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("Neplatn� ��slo cvi�en�"); lst.add(st); continue; } if (!nalezenaUl) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("Neplatn� ��slo �lohy"); lst.add(st); continue; } } } } Calendar dateFromZipFile = null; File zipFile = new File(filename); if (zipFile.exists()) { String[] s = zipFile.getName().split("_"); if (s.length >= 3) { String[] date = s[1].split("-"), time = s[2].split("-"); dateFromZipFile = new GregorianCalendar(); dateFromZipFile.set(Integer.parseInt(date[0]), Integer.parseInt(date[1]) - 1, Integer.parseInt(date[2]), Integer.parseInt(time[0]), Integer.parseInt(time[1]), 0); } } boolean shodaJmenaSouboru = false; String vysledekValidaceSouboru = ""; for (int j = start; j >= 0; j--) { NodeList vlastnostiSouboruNL = souboryNL.item(j).getChildNodes(); for (int k = 0; k < vlastnostiSouboruNL.getLength(); k++) { if (vlastnostiSouboruNL.item(k).getNodeName().equals("cas")) { String[] obsahElementuCas = vlastnostiSouboruNL.item(k).getTextContent().split(" "); String[] datumZElementu = obsahElementuCas[0].split("-"), casZElementu = obsahElementuCas[1].split("-"); Calendar datumACasZElementu = new GregorianCalendar(); datumACasZElementu.set(Integer.parseInt(datumZElementu[0]), Integer.parseInt(datumZElementu[1]) - 1, Integer.parseInt(datumZElementu[2]), Integer.parseInt(casZElementu[0]), Integer.parseInt(casZElementu[1]), Integer.parseInt(casZElementu[2])); if ((dateFromZipFile != null) && (datumACasZElementu.compareTo(dateFromZipFile) > 0)) { shodaJmenaSouboru = false; break; } } if (vlastnostiSouboruNL.item(k).getNodeName().equals("nazev")) { shodaJmenaSouboru = vlastnostiSouboruNL.item(k).getTextContent().equals(testedFile.getName()); } if (vlastnostiSouboruNL.item(k).getNodeName().equals("vysledek")) { vysledekValidaceSouboru = vlastnostiSouboruNL.item(k).getTextContent(); } } if (shodaJmenaSouboru) { start = --j; break; } } if (shodaJmenaSouboru && !samostatnaPrace) { boolean odevzdanoVcas = false; String cisloCviceniS = testedFile.getName().split("_")[1].substring(2); int cisloCviceniI = Integer.parseInt(cisloCviceniS); String cisloUlohyS = testedFile.getName().split("_")[2]; int cisloUlohyI = Integer.parseInt(cisloUlohyS); List<CviceniType> lct = student.getDomaciUlohy().getCviceni(); for (CviceniType ct : lct) { if (ct.getCislo().intValue() == cisloCviceniI) { MezniTerminOdevzdaniVcasType mtovt = ct.getMezniTerminOdevzdaniVcas(); Calendar mtovGC = new GregorianCalendar(); mtovGC.set(mtovt.getDatum().getYear(), mtovt.getDatum().getMonth() - 1, mtovt.getDatum().getDay(), 23, 59, 59); Calendar fileTimeStamp = new GregorianCalendar(); fileTimeStamp.setTimeInMillis(testedFile.lastModified()); String[] datumSouboru = String.format("%tF", fileTimeStamp).split("-"); String[] casSouboru = String.format("%tT", fileTimeStamp).split(":"); XMLGregorianCalendar xmlGCDate = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(Integer.parseInt(datumSouboru[0]), Integer.parseInt(datumSouboru[1]), Integer.parseInt(datumSouboru[2]), DatatypeConstants.FIELD_UNDEFINED); XMLGregorianCalendar xmlGCTime = DatatypeFactory.newInstance().newXMLGregorianCalendarTime(Integer.parseInt(casSouboru[0]), Integer.parseInt(casSouboru[1]), Integer.parseInt(casSouboru[2]), DatatypeConstants.FIELD_UNDEFINED); if (fileTimeStamp.compareTo(mtovGC) <= 0) odevzdanoVcas = true; else odevzdanoVcas = false; List<UlohaType> lut = ct.getUloha(); for (UlohaType ut : lut) { if (ut.getCislo().intValue() == cisloUlohyI) { List<OdevzdanoType> lot = ut.getOdevzdano(); OdevzdanoType ot = of.createOdevzdanoType(); ot.setDatum(xmlGCDate); ot.setCas(xmlGCTime); OdevzdanoVcasType ovt = of.createOdevzdanoVcasType(); ovt.setVysledek(odevzdanoVcas); ValidatorType vt = of.createValidatorType(); vt.setVysledek(vysledekValidaceSouboru.equals("true")); ot.setOdevzdanoVcas(ovt); ot.setValidator(vt); lot.add(ot); if (vt.isVysledek()) { String test = String.format("%s%s%02d", validovane, File.separator, ct.getCislo().intValue()); if (!(new File(test).exists())) { LogManager.getInstance().log("Nebyla provedena p��prava soubor�. Chyb� slo�ka " + test.substring(Ppa1Cviceni.USER_DIR.length()) + "."); return; } else { copyValidFile(testedFile, ct.getCislo().intValue()); } } break; } } break; } } } else if (shodaJmenaSouboru && samostatnaPrace) { String[] partsOfFilename = testedFile.getName().split("_"); String[] partsOfLastPartOfFilename = partsOfFilename[partsOfFilename.length - 1].split("[.]"); String osobniCisloZeSouboru = partsOfLastPartOfFilename[0]; String priponaZeSouboru = partsOfLastPartOfFilename[partsOfLastPartOfFilename.length - 1]; if ((partsOfLastPartOfFilename.length == 2) && (priponaZeSouboru.equals("java"))) { if (student.getOsobniCislo().equals(osobniCisloZeSouboru)) { Calendar fileTimeStamp = new GregorianCalendar(); fileTimeStamp.setTimeInMillis(testedFile.lastModified()); String[] datumSouboru = String.format("%tF", fileTimeStamp).split("-"); String[] casSouboru = String.format("%tT", fileTimeStamp).split(":"); XMLGregorianCalendar xmlGCDate = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(Integer.parseInt(datumSouboru[0]), Integer.parseInt(datumSouboru[1]), Integer.parseInt(datumSouboru[2]), DatatypeConstants.FIELD_UNDEFINED); XMLGregorianCalendar xmlGCTime = DatatypeFactory.newInstance().newXMLGregorianCalendarTime(Integer.parseInt(casSouboru[0]), Integer.parseInt(casSouboru[1]), Integer.parseInt(casSouboru[2]), DatatypeConstants.FIELD_UNDEFINED); List<UlozenoType> lut = student.getSamostatnaPrace().getUlozeno(); if (lut.isEmpty()) { File samostatnaPraceNewFile = new File(sp + File.separator + testedFile.getName()); if (samostatnaPraceNewFile.exists()) { samostatnaPraceNewFile.delete(); samostatnaPraceNewFile.createNewFile(); } String EOL = "" + (char) 0x0D + (char) 0x0A; FileReader fr = new FileReader(testedFile); BufferedReader br = new BufferedReader(fr); FileWriter fw = new FileWriter(samostatnaPraceNewFile); String line; while ((line = br.readLine()) != null) fw.write(line + EOL); br.close(); fw.close(); samostatnaPraceNewFile.setLastModified(testedFile.lastModified()); } UlozenoType ut = of.createUlozenoType(); ut.setDatum(xmlGCDate); ut.setCas(xmlGCTime); lut.add(0, ut); } } } } } PosledniZpracovanyPokusType pzpt = new PosledniZpracovanyPokusType(); String[] slozkaPoslednihoPokusu = pokusyDirectories[pokusyDirectories.length - 1].getName().split("_"); int cisloPokusu = Integer.parseInt(slozkaPoslednihoPokusu[slozkaPoslednihoPokusu.length - 1].trim()); pzpt.setCislo(new BigInteger(String.valueOf(cisloPokusu))); student.getDomaciUlohy().setPosledniZpracovanyPokus(pzpt); break; } } } } ElementJAXB.setJAXBElement(element); LogManager.getInstance().log("Ov��ov�n� a kop�rov�n� odevzdan�ch soubor� dokon�eno."); } catch (FileNotFoundException e) { e.printStackTrace(); LogManager.getInstance().log("Nastala chyba p�i ov��ov�n� a kop�rov�n�."); } catch (DatatypeConfigurationException e) { e.printStackTrace(); LogManager.getInstance().log("Nastala chyba p�i ov��ov�n� a kop�rov�n�."); } catch (IOException e) { e.printStackTrace(); LogManager.getInstance().log("Nastala chyba p�i ov��ov�n� a kop�rov�n�."); } LogManager.getInstance().log("Maz�n� rozbalen�ch soubor� ..."); deleteFileFromTMPFolder(tmpFolderF); LogManager.getInstance().changeLog("Maz�n� rozbalen�ch soubor� ... OK"); }
|
11
|
Code Sample 1:
public void testCopyFolderContents() throws IOException { log.info("Running: testCopyFolderContents()"); IOUtils.copyFolderContents(srcFolderName, destFolderName); Assert.assertTrue(destFile1.exists() && destFile1.isFile()); Assert.assertTrue(destFile2.exists() && destFile2.isFile()); Assert.assertTrue(destFile3.exists() && destFile3.isFile()); }
Code Sample 2:
@Test public void testWriteAndReadSecondLevel() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile directory1 = new RFile("directory1"); RFile directory2 = new RFile(directory1, "directory2"); RFile file = new RFile(directory2, "testreadwrite2nd.txt"); RFileOutputStream out = new RFileOutputStream(file); out.write("test".getBytes("utf-8")); out.close(); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[4]; int readCount = in.read(buffer); in.close(); assertEquals(4, readCount); String resultRead = new String(buffer, "utf-8"); assertEquals("test", resultRead); } finally { server.stop(); } }
|
00
|
Code Sample 1:
private BibtexDatabase importInspireEntries(String key, OutputPrinter frame) { String url = constructUrl(key); try { HttpURLConnection conn = (HttpURLConnection) (new URL(url)).openConnection(); conn.setRequestProperty("User-Agent", "Jabref"); InputStream inputStream = conn.getInputStream(); INSPIREBibtexFilterReader reader = new INSPIREBibtexFilterReader(new InputStreamReader(inputStream)); ParserResult pr = BibtexParser.parse(reader); return pr.getDatabase(); } catch (IOException e) { frame.showMessage(Globals.lang("An Exception ocurred while accessing '%0'", url) + "\n\n" + e.toString(), Globals.lang(getKeyName()), JOptionPane.ERROR_MESSAGE); } catch (RuntimeException e) { frame.showMessage(Globals.lang("An Error occurred while fetching from INSPIRE source (%0):", new String[] { url }) + "\n\n" + e.getMessage(), Globals.lang(getKeyName()), JOptionPane.ERROR_MESSAGE); } return null; }
Code Sample 2:
public void run() { if (currentNode == null || currentNode.equals("")) { JOptionPane.showMessageDialog(null, "Please select a genome to download first", "Error", JOptionPane.ERROR_MESSAGE); return; } String localFile = parameter.getTemporaryFilesPath() + currentNode; String remotePath = NCBI_FTP_PATH + currentPath; String remoteFile = remotePath + "/" + currentNode; try { ftp.connect(NCBI_FTP_HOST); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); JOptionPane.showMessageDialog(null, "FTP server refused connection", "Error", JOptionPane.ERROR_MESSAGE); } ftp.login("anonymous", "[email protected]"); inProgress = true; ftp.setFileType(FTPClient.BINARY_FILE_TYPE); long size = getFileSize(remotePath, currentNode); if (size == -1) throw new FileNotFoundException(); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(localFile)); BufferedInputStream in = new BufferedInputStream(ftp.retrieveFileStream(remoteFile), ftp.getBufferSize()); byte[] b = new byte[1024]; long bytesTransferred = 0; int tick = 0; int oldTick = 0; int len; while ((len = in.read(b)) != -1) { out.write(b, 0, len); bytesTransferred += 1024; if ((tick = new Long(bytesTransferred * 100 / size).intValue()) > oldTick) { progressBar.setValue(tick < 100 ? tick : 99); oldTick = tick; } } in.close(); out.close(); ftp.completePendingCommand(); progressBar.setValue(100); fileDownloaded = localFile; JOptionPane.showMessageDialog(null, "File successfully downloaded", "Congratulation!", JOptionPane.INFORMATION_MESSAGE); ftp.logout(); } catch (SocketException ex) { JOptionPane.showMessageDialog(null, "Error occurs while trying to connect server", "Error", JOptionPane.ERROR_MESSAGE); } catch (FileNotFoundException ex) { JOptionPane.showMessageDialog(null, "This file is not found on the server", "Error", JOptionPane.ERROR_MESSAGE); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Error occurs while fetching data", "Error", JOptionPane.ERROR_MESSAGE); } finally { inProgress = false; if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } }
|
11
|
Code Sample 1:
private final void saveCopy(String source, String destination) { BufferedInputStream from = null; BufferedOutputStream to = null; try { from = new BufferedInputStream(new FileInputStream(source)); to = new BufferedOutputStream(new FileOutputStream(destination)); byte[] buffer = new byte[65535]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } catch (Exception e) { LogWriter.writeLog("Exception " + e + " copying file"); } try { to.close(); from.close(); } catch (Exception e) { LogWriter.writeLog("Exception " + e + " closing files"); } to = null; from = null; }
Code Sample 2:
public static void copyFromFileToFileUsingNIO(File inputFile, File outputFile) throws FileNotFoundException, IOException { FileChannel inputChannel = new FileInputStream(inputFile).getChannel(); FileChannel outputChannel = new FileOutputStream(outputFile).getChannel(); try { inputChannel.transferTo(0, inputChannel.size(), outputChannel); } catch (IOException e) { throw e; } finally { if (inputChannel != null) inputChannel.close(); if (outputChannel != null) outputChannel.close(); } }
|
00
|
Code Sample 1:
public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet("https://portal.sun.com/portal/dt"); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println("Login form get: " + response.getStatusLine()); if (entity != null) { entity.consumeContent(); } System.out.println("Initial set of cookies:"); List<Cookie> cookies = httpclient.getCookieStore().getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } HttpPost httpost = new HttpPost("https://portal.sun.com/amserver/UI/Login?" + "org=self_registered_users&" + "goto=/portal/dt&" + "gotoOnFail=/portal/dt?error=true"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("IDToken1", "username")); nvps.add(new BasicNameValuePair("IDToken2", "password")); httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); response = httpclient.execute(httpost); entity = response.getEntity(); System.out.println("Login form get: " + response.getStatusLine()); if (entity != null) { entity.consumeContent(); } System.out.println("Post logon cookies:"); cookies = httpclient.getCookieStore().getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } }
Code Sample 2:
public Document getKmlStream(String streetname, String number, String neighbourhood, String city, String state) throws RotaException { StringBuffer urlsb = new StringBuffer(resourceBundle.getString(Constants.URL_SEARCH)); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); InputStream in = null; HttpURLConnection httpConnection = null; Document doc = null; dbf.setValidating(false); String proxy = resourceBundle.getString(Constants.PROXY_HOST); String port = resourceBundle.getString(Constants.PROXY_PORT); try { String address = String.format("%s+%s+%s+%s+%s", URLEncoder.encode(streetname.trim(), Constants.URL_ENCODING), URLEncoder.encode(number.trim(), Constants.URL_ENCODING), URLEncoder.encode(neighbourhood.trim(), Constants.URL_ENCODING), URLEncoder.encode(city.trim(), Constants.URL_ENCODING), URLEncoder.encode(state.trim(), Constants.URL_ENCODING)); DocumentBuilder df = dbf.newDocumentBuilder(); urlsb.append(address); urlsb.append(resourceBundle.getString(Constants.GOOGLE_TYPE_OUTPUT)); urlsb.append(resourceBundle.getString(Constants.SENSOR)); urlsb.append(resourceBundle.getString(Constants.GOOGLE_KEY)); urlsb.append(resourceBundle.getString(Constants.GOOGLE_KEY_VALUE)); String addressUTF8 = urlsb.toString(); URL url = new URL(addressUTF8); Properties systemproperties = System.getProperties(); if (proxy != null && !proxy.equals("")) { systemproperties.setProperty("http.proxyHost", proxy); systemproperties.setProperty("http.proxyPort", port); } httpConnection = (HttpURLConnection) url.openConnection(); httpConnection.connect(); in = httpConnection.getInputStream(); doc = df.parse(in); in.close(); httpConnection.disconnect(); if (doc == null || !verificaStatusRequisicao(doc)) { throw new RotaException("N�o foi poss�vel realizar a geodecodifica��o com o endere�o informado!"); } return doc; } catch (UnsupportedEncodingException ue) { logger.error(ue); throw new RotaException("Encoding n�o suportado : " + ue.getMessage()); } catch (MalformedURLException ma) { logger.error(ma); throw new RotaException("Erro na URL : " + ma.getMessage()); } catch (ParserConfigurationException pe) { logger.error(pe); throw new RotaException("Erro ao realizar o parser da configura��o : " + pe.getMessage()); } catch (SAXException sa) { logger.error(sa); throw new RotaException("Erro de SAX : " + sa.getMessage()); } catch (ConnectException co) { logger.error(co); throw new RotaException("N�o foi poss�vel estabelecer a conex�o http : " + co.getMessage()); } catch (IOException io) { logger.error(io); throw new RotaException("Erro de io : ", io); } catch (Exception ex) { throw new RotaException("N�o foi poss�vel gerar a rota : " + ex.getMessage()); } finally { if (in != null) { try { in.close(); } catch (Exception ex) { throw new RotaException("N�o foi poss�vel fechar o stream de dados ! : " + ex.getMessage()); } } if (httpConnection != null) { httpConnection.disconnect(); } } }
|
00
|
Code Sample 1:
public static void insertTableData(Connection dest, TableMetaData tableMetaData) throws Exception { PreparedStatement ps = null; try { dest.setAutoCommit(false); String sql = "INSERT INTO " + tableMetaData.getSchema() + "." + tableMetaData.getTableName() + " ("; for (String columnName : tableMetaData.getColumnsNames()) { sql += columnName + ","; } sql = sql.substring(0, sql.length() - 1); sql += ") VALUES ("; for (String columnName : tableMetaData.getColumnsNames()) { sql += "?" + ","; } sql = sql.substring(0, sql.length() - 1); sql += ")"; IOHelper.writeInfo(sql); ps = dest.prepareStatement(sql); for (Row r : tableMetaData.getData()) { try { int param = 1; for (String columnName : tableMetaData.getColumnsNames()) { if (dest instanceof OracleConnection) { if (tableMetaData.getColumnsTypes().get(columnName).equalsIgnoreCase("BLOB")) { BLOB blob = new BLOB((OracleConnection) dest, (byte[]) r.getRowData().get(columnName)); ((OraclePreparedStatement) ps).setBLOB(param, blob); } else if (tableMetaData.getColumnsTypes().get(columnName).equalsIgnoreCase("CLOB")) { ((OraclePreparedStatement) ps).setStringForClob(param, (String) r.getRowData().get(columnName)); } else if (tableMetaData.getColumnsTypes().get(columnName).equalsIgnoreCase("LONG")) { ps.setBytes(param, (byte[]) r.getRowData().get(columnName)); } } else { IOHelper.writeInfo(columnName + " = " + r.getRowData().get(columnName)); ps.setObject(param, r.getRowData().get(columnName)); } param++; } if (ps.executeUpdate() != 1) { dest.rollback(); updateTableData(dest, tableMetaData, r); } } catch (Exception ex) { try { dest.rollback(); updateTableData(dest, tableMetaData, r); } catch (Exception ex2) { IOHelper.writeError("Error in update " + sql, ex2); } } ps.clearParameters(); } dest.commit(); dest.setAutoCommit(true); } finally { if (ps != null) ps.close(); } }
Code Sample 2:
public static final String getHash(int iterationNb, String password, String salt) { try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.reset(); digest.update(salt.getBytes("UTF-8")); byte[] input = digest.digest(password.getBytes("UTF-8")); for (int i = 0; i < iterationNb; i++) { digest.reset(); input = digest.digest(input); } String hashedValue = encoder.encode(input); LOG.finer("Creating hash '" + hashedValue + "' with iterationNb '" + iterationNb + "' and password '" + password + "' and salt '" + salt + "'!!"); return hashedValue; } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException("Problem in the getHash method.", ex); } }
|
11
|
Code Sample 1:
public MoteDeploymentConfiguration updateMoteDeploymentConfiguration(int mdConfigID, int programID, int radioPowerLevel) throws AdaptationException { MoteDeploymentConfiguration mdc = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "UPDATE MoteDeploymentConfigurations SET " + "programID = " + programID + ", " + "radioPowerLevel = " + radioPowerLevel + " " + "WHERE id = " + mdConfigID; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); statement.executeUpdate(query); query = "SELECT * from MoteDeploymentConfigurations WHERE " + "id = " + mdConfigID; resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Unable to select updated config."; log.error(msg); ; throw new AdaptationException(msg); } mdc = getMoteDeploymentConfiguration(resultSet); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in updateMoteDeploymentConfiguration"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return mdc; }
Code Sample 2:
private void handleNodeDown(long eventID, long nodeID, String eventTime) { Category log = ThreadCategory.getInstance(OutageWriter.class); if (eventID == -1 || nodeID == -1) { log.warn(EventConstants.NODE_DOWN_EVENT_UEI + " ignored - info incomplete - eventid/nodeid: " + eventID + "/" + nodeID); return; } Connection dbConn = null; try { dbConn = DatabaseConnectionFactory.getInstance().getConnection(); try { dbConn.setAutoCommit(false); } catch (SQLException sqle) { log.error("Unable to change database AutoCommit to FALSE", sqle); return; } PreparedStatement activeSvcsStmt = dbConn.prepareStatement(OutageConstants.DB_GET_ACTIVE_SERVICES_FOR_NODE); PreparedStatement openStmt = dbConn.prepareStatement(OutageConstants.DB_OPEN_RECORD); PreparedStatement newOutageWriter = dbConn.prepareStatement(OutageConstants.DB_INS_NEW_OUTAGE); PreparedStatement getNextOutageIdStmt = dbConn.prepareStatement(OutageManagerConfigFactory.getInstance().getGetNextOutageID()); newOutageWriter = dbConn.prepareStatement(OutageConstants.DB_INS_NEW_OUTAGE); if (log.isDebugEnabled()) log.debug("handleNodeDown: creating new outage entries..."); activeSvcsStmt.setLong(1, nodeID); ResultSet activeSvcsRS = activeSvcsStmt.executeQuery(); while (activeSvcsRS.next()) { String ipAddr = activeSvcsRS.getString(1); long serviceID = activeSvcsRS.getLong(2); if (openOutageExists(dbConn, nodeID, ipAddr, serviceID)) { if (log.isDebugEnabled()) log.debug("handleNodeDown: " + nodeID + "/" + ipAddr + "/" + serviceID + " already down"); } else { long outageID = -1; ResultSet seqRS = getNextOutageIdStmt.executeQuery(); if (seqRS.next()) { outageID = seqRS.getLong(1); } seqRS.close(); newOutageWriter.setLong(1, outageID); newOutageWriter.setLong(2, eventID); newOutageWriter.setLong(3, nodeID); newOutageWriter.setString(4, ipAddr); newOutageWriter.setLong(5, serviceID); newOutageWriter.setTimestamp(6, convertEventTimeIntoTimestamp(eventTime)); newOutageWriter.executeUpdate(); if (log.isDebugEnabled()) log.debug("handleNodeDown: Recording outage for " + nodeID + "/" + ipAddr + "/" + serviceID); } } activeSvcsRS.close(); try { dbConn.commit(); if (log.isDebugEnabled()) log.debug("Outage recorded for all active services for " + nodeID); } catch (SQLException se) { log.warn("Rolling back transaction, nodeDown could not be recorded for nodeId: " + nodeID, se); try { dbConn.rollback(); } catch (SQLException sqle) { log.warn("SQL exception during rollback, reason", sqle); } } activeSvcsStmt.close(); openStmt.close(); newOutageWriter.close(); } catch (SQLException sqle) { log.warn("SQL exception while handling \'nodeDown\'", sqle); } finally { try { if (dbConn != null) dbConn.close(); } catch (SQLException e) { log.warn("Exception closing JDBC connection", e); } } }
|
00
|
Code Sample 1:
public static BufferedReader openForReading(String name, URI base, ClassLoader classLoader) throws IOException { if ((name == null) || name.trim().equals("")) { return null; } if (name.trim().equals("System.in")) { if (STD_IN == null) { STD_IN = new BufferedReader(new InputStreamReader(System.in)); } return STD_IN; } URL url = nameToURL(name, base, classLoader); if (url == null) { throw new IOException("Could not convert \"" + name + "\" with base \"" + base + "\" to a URL."); } InputStreamReader inputStreamReader = null; try { inputStreamReader = new InputStreamReader(url.openStream()); } catch (IOException ex) { try { URL possibleJarURL = ClassUtilities.jarURLEntryResource(url.toString()); if (possibleJarURL != null) { inputStreamReader = new InputStreamReader(possibleJarURL.openStream()); } return new BufferedReader(inputStreamReader); } catch (Exception ex2) { try { if (inputStreamReader != null) { inputStreamReader.close(); } } catch (IOException ex3) { } IOException ioException = new IOException("Failed to open \"" + url + "\"."); ioException.initCause(ex); throw ioException; } } return new BufferedReader(inputStreamReader); }
Code Sample 2:
public void copyNIO(File in, File out) throws IOException { FileInputStream inStream = null; FileOutputStream outStream = null; FileChannel sourceChannel = null; FileChannel destinationChannel = null; try { inStream = new FileInputStream(in); outStream = new FileOutputStream(out); sourceChannel = inStream.getChannel(); destinationChannel = outStream.getChannel(); destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); } finally { if (sourceChannel != null) sourceChannel.close(); if (destinationChannel != null) destinationChannel.close(); if (inStream != null) inStream.close(); if (outStream != null) outStream.close(); } }
|
11
|
Code Sample 1:
public void run(Preprocessor pp) throws SijappException { for (int i = 0; i < this.filenames.length; i++) { File srcFile = new File(this.srcDir, this.filenames[i]); BufferedReader reader; try { InputStreamReader isr = new InputStreamReader(new FileInputStream(srcFile), "CP1251"); reader = new BufferedReader(isr); } catch (Exception e) { throw (new SijappException("File " + srcFile.getPath() + " could not be read")); } File destFile = new File(this.destDir, this.filenames[i]); BufferedWriter writer; try { (new File(destFile.getParent())).mkdirs(); OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(destFile), "CP1251"); writer = new BufferedWriter(osw); } catch (Exception e) { throw (new SijappException("File " + destFile.getPath() + " could not be written")); } try { pp.run(reader, writer); } catch (SijappException e) { try { reader.close(); } catch (IOException f) { } try { writer.close(); } catch (IOException f) { } try { destFile.delete(); } catch (SecurityException f) { } throw (new SijappException(srcFile.getPath() + ":" + e.getMessage())); } try { reader.close(); } catch (IOException e) { } try { writer.close(); } catch (IOException e) { } } }
Code Sample 2:
public void store(String path, InputStream stream) throws IOException { toIgnore.add(normalizePath(path)); ZipEntry entry = new ZipEntry(path); zipOutput.putNextEntry(entry); IOUtils.copy(stream, zipOutput); zipOutput.closeEntry(); }
|
00
|
Code Sample 1:
public static void v2ljastaVeebileht(String s) throws IOException { URL url = new URL(s); InputStream is = url.openConnection().getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; while ((line = br.readLine()) != null) { System.out.println(line); } }
Code Sample 2:
public static List<String> retrieveLanguages() throws Exception { List<String> result = new ArrayList<String>(); URL url = new URL("http://translatewiki.net/w/i.php?title=Special:MessageGroupStats&group=out-osm-site"); String str = StreamUtil.toString(url.openStream()); Pattern pattern = Pattern.compile(".*language=([^;\"]+).*"); Matcher m = pattern.matcher(str); while (m.find()) { String lang = m.group(1); if (!result.contains(lang)) { result.add(lang); } } return result; }
|
11
|
Code Sample 1:
private WikiSiteContentInfo createInfoIndexSite(Long domainId) { final UserInfo user = getSecurityService().getCurrentUser(); final Locale locale = new Locale(user.getLocale()); final String country = locale.getLanguage(); InputStream inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("wiki_index_" + country + ".xhtml"); if (inStream == null) { inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("wiki_index.xhtml"); } if (inStream == null) { inStream = new ByteArrayInputStream(DEFAULT_WIKI_INDEX_SITE_TEXT.getBytes()); } if (inStream != null) { ByteArrayOutputStream out = new ByteArrayOutputStream(); try { IOUtils.copyLarge(inStream, out); return createIndexVersion(domainId, out.toString(), user); } catch (IOException exception) { LOGGER.error("Error creating info page.", exception); } finally { try { inStream.close(); out.close(); } catch (IOException exception) { LOGGER.error("Error reading wiki_index.xhtml", exception); } } } return null; }
Code Sample 2:
public void format(File source, File target) { if (!source.exists()) { throw new IllegalArgumentException("Source '" + source + " doesn't exist"); } if (!source.isFile()) { throw new IllegalArgumentException("Source '" + source + " is not a file"); } target.mkdirs(); String fileExtension = source.getName().substring(source.getName().lastIndexOf(".") + 1); String _target = source.getName().replace(fileExtension, "html"); target = new File(target.getPath() + "/" + _target); try { Reader reader = new FileReader(source); Writer writer = new FileWriter(target); this.format(reader, writer); } catch (Exception e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
public static void copiaAnexos(String from, String to, AnexoTO[] anexoTO) { FileChannel in = null, out = null; for (int i = 0; i < anexoTO.length; i++) { try { in = new FileInputStream(new File((uploadDiretorio.concat(from)).concat(File.separator + anexoTO[i].getNome()))).getChannel(); out = new FileOutputStream(new File((uploadDiretorio.concat(to)).concat(File.separator + anexoTO[i].getNome()))).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) try { in.close(); } catch (IOException e) { e.printStackTrace(); } if (out != null) try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Code Sample 2:
private void regattaBackup() { SwingWorker sw = new SwingWorker() { Regatta lRegatta = fRegatta; public Object construct() { String fullName = lRegatta.getSaveDirectory() + lRegatta.getSaveName(); System.out.println(MessageFormat.format(res.getString("MainMessageBackingUp"), new Object[] { fullName + BAK })); try { FileInputStream fis = new FileInputStream(new File(fullName)); FileOutputStream fos = new FileOutputStream(new File(fullName + BAK)); int bufsize = 1024; byte[] buffer = new byte[bufsize]; int n = 0; while ((n = fis.read(buffer, 0, bufsize)) >= 0) fos.write(buffer, 0, n); fos.flush(); fos.close(); } catch (java.io.IOException ex) { Util.showError(ex, true); } return null; } }; sw.start(); }
|
11
|
Code Sample 1:
public long copyFileWithPaths(String userBaseDir, String sourcePath, String destinPath) throws Exception { if (userBaseDir.endsWith(sep)) { userBaseDir = userBaseDir.substring(0, userBaseDir.length() - sep.length()); } String file1FullPath = new String(); if (sourcePath.startsWith(sep)) { file1FullPath = new String(userBaseDir + sourcePath); } else { file1FullPath = new String(userBaseDir + sep + sourcePath); } String file2FullPath = new String(); if (destinPath.startsWith(sep)) { file2FullPath = new String(userBaseDir + destinPath); } else { file2FullPath = new String(userBaseDir + sep + destinPath); } long plussQuotaSize = 0; BufferedInputStream in = null; BufferedOutputStream out = null; byte dataBuff[] = new byte[bufferSize]; File fileordir = new File(file1FullPath); if (fileordir.exists()) { if (fileordir.isFile()) { File file2 = new File(file2FullPath); if (file2.exists()) { plussQuotaSize -= file2.length(); file2.delete(); } FileUtils.getInstance().createDirectory(file2.getParent()); in = new BufferedInputStream(new FileInputStream(file1FullPath), bufferSize); out = new BufferedOutputStream(new FileOutputStream(file2FullPath), bufferSize); int readLen; while ((readLen = in.read(dataBuff)) > 0) { out.write(dataBuff, 0, readLen); plussQuotaSize += readLen; } out.flush(); in.close(); out.close(); } if (fileordir.isDirectory()) { String[] entryList = fileordir.list(); if (entryList.length > 0) { for (int pos = 0; pos < entryList.length; pos++) { String entryName = entryList[pos]; String file1FullPathEntry = new String(file1FullPath.concat(entryList[pos])); String file2FullPathEntry = new String(file2FullPath.concat(entryList[pos])); File file2 = new File(file2FullPathEntry); if (file2.exists()) { plussQuotaSize -= file2.length(); file2.delete(); } FileUtils.getInstance().createDirectory(file2.getParent()); in = new BufferedInputStream(new FileInputStream(file1FullPathEntry), bufferSize); out = new BufferedOutputStream(new FileOutputStream(file2FullPathEntry), bufferSize); int readLen; while ((readLen = in.read(dataBuff)) > 0) { out.write(dataBuff, 0, readLen); plussQuotaSize += readLen; } out.flush(); in.close(); out.close(); } } } } else { throw new Exception("Source file or dir not exist ! file1FullPath = (" + file1FullPath + ")"); } return plussQuotaSize; }
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(); } } }
|
11
|
Code Sample 1:
private void buildBundle() { if (targetProject == null) { MessageDialog.openError(getShell(), "Error", "No target SPAB project selected!"); return; } if (projectProcessDirSelector.getText().trim().length() == 0) { MessageDialog.openError(getShell(), "Error", "No process directory selected for project " + targetProject.getName() + "!"); return; } deleteBundleFile(); try { File projectDir = targetProject.getLocation().toFile(); File projectProcessesDir = new File(projectDir, projectProcessDirSelector.getText()); boolean bpmoCopied = IOUtils.copyProcessFilesSecure(getBPMOFile(), projectProcessesDir); boolean sbpelCopied = IOUtils.copyProcessFilesSecure(getSBPELFile(), projectProcessesDir); boolean xmlCopied = IOUtils.copyProcessFilesSecure(getBPEL4SWSFile(), projectProcessesDir); bundleFile = IOUtils.archiveBundle(projectDir, Activator.getDefault().getStateLocation().toFile()); if (bpmoCopied) { new File(projectProcessesDir, getBPMOFile().getName()).delete(); } if (sbpelCopied) { new File(projectProcessesDir, getSBPELFile().getName()).delete(); } if (xmlCopied) { new File(projectProcessesDir, getBPEL4SWSFile().getName()).delete(); } } catch (Throwable anyError) { LogManager.logError(anyError); MessageDialog.openError(getShell(), "Error", "Error building SPAB :\n" + anyError.getMessage()); updateBundleUI(); return; } bpmoFile = getBPMOFile(); sbpelFile = getSBPELFile(); xmlFile = getBPEL4SWSFile(); updateBundleUI(); getWizard().getContainer().updateButtons(); }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
00
|
Code Sample 1:
private void prepareUrlFile(ZipEntryRef zer, String nodeDir, String reportDir) throws Exception { URL url = new URL(zer.getUri()); URLConnection conn = url.openConnection(); String fcopyName = reportDir + File.separator + zer.getFilenameFromHttpHeader(conn.getHeaderFields()); logger.debug("download " + zer.getUri() + " in " + fcopyName); BufferedOutputStream bw; bw = new BufferedOutputStream(new FileOutputStream(fcopyName)); BufferedInputStream reader = new BufferedInputStream(conn.getInputStream()); byte[] inputLine = new byte[100000]; ; while (reader.read(inputLine) > 0) { bw.write(inputLine); } bw.close(); reader.close(); zer.setUri(fcopyName); }
Code Sample 2:
public static String hexMD5(String value) { try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(value.getBytes("utf-8")); byte[] digest = messageDigest.digest(); return byteToHexString(digest); } catch (Exception ex) { throw new UnexpectedException(ex); } }
|
00
|
Code Sample 1:
public static void cpdir(File src, File dest) throws BrutException { dest.mkdirs(); File[] files = src.listFiles(); for (int i = 0; i < files.length; i++) { File file = files[i]; File destFile = new File(dest.getPath() + File.separatorChar + file.getName()); if (file.isDirectory()) { cpdir(file, destFile); continue; } try { InputStream in = new FileInputStream(file); OutputStream out = new FileOutputStream(destFile); IOUtils.copy(in, out); in.close(); out.close(); } catch (IOException ex) { throw new BrutException("Could not copy file: " + file, ex); } } }
Code Sample 2:
public int download(String fileName) { OutputStream out = null; URLConnection conn = null; InputStream in = null; int numRead = 0; int totalRead = 0; try { URL url = new URL(URL); out = new BufferedOutputStream(new FileOutputStream(fileName)); conn = url.openConnection(); in = conn.getInputStream(); byte[] buffer = new byte[1024]; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); totalRead += numRead; } } catch (IOException exception) { totalRead = 0; } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException ioe) { } return totalRead; } }
|
00
|
Code Sample 1:
public void copyFile(File from, File to) { try { InputStream in = new FileInputStream(from); OutputStream out = new FileOutputStream(to); int readCount; byte[] bytes = new byte[1024]; while ((readCount = in.read(bytes)) != -1) { out.write(bytes, 0, readCount); } out.flush(); in.close(); out.close(); } catch (Exception ex) { throw new BuildException(ex.getMessage(), ex); } }
Code Sample 2:
private long getLastModified(Set resourcePaths, Map jarPaths) throws Exception { long lastModified = 0; Iterator paths = resourcePaths.iterator(); while (paths.hasNext()) { String path = (String) paths.next(); URL url = context.getServletContext().getResource(path); if (url == null) { log.debug("Null url " + path); break; } long lastM = url.openConnection().getLastModified(); if (lastM > lastModified) lastModified = lastM; if (log.isDebugEnabled()) { log.debug("Last modified " + path + " " + lastM); } } if (jarPaths != null) { paths = jarPaths.values().iterator(); while (paths.hasNext()) { File jarFile = (File) paths.next(); long lastM = jarFile.lastModified(); if (lastM > lastModified) lastModified = lastM; if (log.isDebugEnabled()) { log.debug("Last modified " + jarFile.getAbsolutePath() + " " + lastM); } } } return lastModified; }
|
00
|
Code Sample 1:
public void fileUpload() throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(postURL); MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); reqEntity.addPart("fff", new MonitoredFileBody(file, uploadProgress)); httppost.setEntity(reqEntity); NULogger.getLogger().info("Now uploading your file into 2shared.com. Please wait......................"); status = UploadStatus.UPLOADING; HttpResponse response = httpclient.execute(httppost); status = UploadStatus.GETTINGLINK; HttpEntity resEntity = response.getEntity(); if (resEntity != null) { String page = EntityUtils.toString(resEntity); NULogger.getLogger().log(Level.INFO, "PAGE :{0}", page); } }
Code Sample 2:
public static boolean predictDataSet(String completePath, String Type, String predictionOutputFileName, String CFDataFolderName) { try { if (Type.equalsIgnoreCase("Qualifying")) { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CompleteQualifyingDataInByteFormat.txt"); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); TShortObjectHashMap qualMap = new TShortObjectHashMap(17770, 1); ByteBuffer qualmappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); while (qualmappedfile.hasRemaining()) { short movie = qualmappedfile.getShort(); int customer = qualmappedfile.getInt(); if (qualMap.containsKey(movie)) { TIntArrayList arr = (TIntArrayList) qualMap.get(movie); arr.add(customer); qualMap.put(movie, arr); } else { TIntArrayList arr = new TIntArrayList(); arr.add(customer); qualMap.put(movie, arr); } } System.out.println("Populated qualifying hashmap"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionOutputFileName); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf; TShortObjectHashMap movieDiffStats; double finalPrediction; short[] movies = qualMap.keys(); Arrays.sort(movies); for (int i = 0; i < movies.length; i++) { short movieToProcess = movies[i]; movieDiffStats = loadMovieDiffStats(completePath, movieToProcess, CFDataFolderName); TIntArrayList customersToProcess = (TIntArrayList) qualMap.get(movieToProcess); for (int j = 0; j < customersToProcess.size(); j++) { int customerToProcess = customersToProcess.getQuick(j); finalPrediction = predictPearsonWeightedSlopeOneRating(knn, movieToProcess, customerToProcess, movieDiffStats); if (finalPrediction == finalPrediction) { if (finalPrediction < 1.0) finalPrediction = 1.0; else if (finalPrediction > 5.0) finalPrediction = 5.0; } else finalPrediction = movieAverages.get(movieToProcess); buf = ByteBuffer.allocate(10); buf.putShort(movieToProcess); buf.putInt(customerToProcess); buf.putFloat(new Double(finalPrediction).floatValue()); buf.flip(); outC.write(buf); } } outC.close(); return true; } else if (Type.equalsIgnoreCase("Probe")) { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CompleteProbeDataInByteFormat.txt"); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); TShortObjectHashMap probeMap = new TShortObjectHashMap(17770, 1); ByteBuffer probemappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); while (probemappedfile.hasRemaining()) { short movie = probemappedfile.getShort(); int customer = probemappedfile.getInt(); byte rating = probemappedfile.get(); if (probeMap.containsKey(movie)) { TIntByteHashMap actualRatings = (TIntByteHashMap) probeMap.get(movie); actualRatings.put(customer, rating); probeMap.put(movie, actualRatings); } else { TIntByteHashMap actualRatings = new TIntByteHashMap(); actualRatings.put(customer, rating); probeMap.put(movie, actualRatings); } } System.out.println("Populated probe hashmap"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionOutputFileName); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf; double finalPrediction; TShortObjectHashMap movieDiffStats; short[] movies = probeMap.keys(); Arrays.sort(movies); for (int i = 0; i < movies.length; i++) { short movieToProcess = movies[i]; movieDiffStats = loadMovieDiffStats(completePath, movieToProcess, CFDataFolderName); TIntByteHashMap custRatingsToProcess = (TIntByteHashMap) probeMap.get(movieToProcess); TIntArrayList customersToProcess = new TIntArrayList(custRatingsToProcess.keys()); for (int j = 0; j < customersToProcess.size(); j++) { int customerToProcess = customersToProcess.getQuick(j); byte rating = custRatingsToProcess.get(customerToProcess); finalPrediction = predictPearsonWeightedSlopeOneRating(knn, movieToProcess, customerToProcess, movieDiffStats); if (finalPrediction == finalPrediction) { if (finalPrediction < 1.0) finalPrediction = 1.0; else if (finalPrediction > 5.0) finalPrediction = 5.0; } else { finalPrediction = movieAverages.get(movieToProcess); System.out.println("NaN Prediction"); } buf = ByteBuffer.allocate(11); buf.putShort(movieToProcess); buf.putInt(customerToProcess); buf.put(rating); buf.putFloat(new Double(finalPrediction).floatValue()); buf.flip(); outC.write(buf); } } outC.close(); return true; } else return false; } catch (Exception e) { e.printStackTrace(); return false; } }
|
11
|
Code Sample 1:
public static void fileCopy(final File src, final File dest, final boolean overwrite) throws IOException { if (!dest.exists() || (dest.exists() && overwrite)) { final FileChannel srcChannel = new FileInputStream(src).getChannel(); final FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } }
Code Sample 2:
public static boolean copyFile(String src, String dst) { FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(new File(src)).getChannel(); outChannel = new FileOutputStream(new File(dst)).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (FileNotFoundException e) { e.printStackTrace(); MessageGenerator.briefError("ERROR could not find/access file(s): " + src + " and/or " + dst); return false; } catch (IOException e) { MessageGenerator.briefError("ERROR copying file: " + src + " to " + dst); return false; } finally { try { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } catch (IOException e) { MessageGenerator.briefError("Error closing files involved in copying: " + src + " and " + dst); return false; } } return true; }
|
00
|
Code Sample 1:
@Override public List<WebSearchResult> search(String term) { List<GoogleResult> results = null; try { URL url = new URL(GoogleWebSearch.GOOGLE_URL + URLEncoder.encode(term, GoogleWebSearch.CHARSET)); Reader reader = new InputStreamReader(url.openStream(), GoogleWebSearch.CHARSET); GoogleResponse jsonResults = new Gson().fromJson(reader, GoogleResponse.class); results = jsonResults.getResponseData().getResults(); } catch (Exception e) { e.printStackTrace(); } List<WebSearchResult> googleResults = new ArrayList<WebSearchResult>(); if (results != null) { googleResults.addAll(results); } return googleResults; }
Code Sample 2:
public static Dictionary getDefaultConfig(BundleContext bc) { final Dictionary config = new Hashtable(); config.put(HttpConfig.HTTP_ENABLED_KEY, getPropertyAsBoolean(bc, "org.knopflerfish.http.enabled", "true")); config.put(HttpConfig.HTTPS_ENABLED_KEY, getPropertyAsBoolean(bc, "org.knopflerfish.http.secure.enabled", "true")); config.put(HttpConfig.HTTP_PORT_KEY, getPropertyAsInteger(bc, "org.osgi.service.http.port", HTTP_PORT_DEFAULT)); config.put(HttpConfig.HTTPS_PORT_KEY, getPropertyAsInteger(bc, "org.osgi.service.http.secure.port", HTTPS_PORT_DEFAULT)); config.put(HttpConfig.HOST_KEY, getPropertyAsString(bc, "org.osgi.service.http.hostname", "")); Properties mimeProps = new Properties(); try { mimeProps.load(HttpConfig.class.getResourceAsStream("/mime.default")); String propurl = getPropertyAsString(bc, "org.knopflerfish.http.mime.props", ""); if (propurl.length() > 0) { URL url = new URL(propurl); Properties userMimeProps = new Properties(); userMimeProps.load(url.openStream()); Enumeration e = userMimeProps.keys(); while (e.hasMoreElements()) { String key = (String) e.nextElement(); mimeProps.put(key, userMimeProps.getProperty(key)); } } } catch (MalformedURLException ignore) { } catch (IOException ignore) { } Vector mimeVector = new Vector(mimeProps.size()); Enumeration e = mimeProps.keys(); while (e.hasMoreElements()) { String key = (String) e.nextElement(); mimeVector.addElement(new String[] { key, mimeProps.getProperty(key) }); } config.put(HttpConfig.MIME_PROPS_KEY, mimeVector); config.put(HttpConfig.SESSION_TIMEOUT_KEY, getPropertyAsInteger(bc, "org.knopflerfish.http.session.timeout.default", 1200)); config.put(HttpConfig.CONNECTION_TIMEOUT_KEY, getPropertyAsInteger(bc, "org.knopflerfish.http.connection.timeout", 30)); config.put(HttpConfig.CONNECTION_MAX_KEY, getPropertyAsInteger(bc, "org.knopflerfish.http.connection.max", 50)); config.put(HttpConfig.DNS_LOOKUP_KEY, getPropertyAsBoolean(bc, "org.knopflerfish.http.dnslookup", "false")); config.put(HttpConfig.RESPONSE_BUFFER_SIZE_DEFAULT_KEY, getPropertyAsInteger(bc, "org.knopflerfish.http.response.buffer.size.default", 16384)); config.put(HttpConfig.DEFAULT_CHAR_ENCODING_KEY, getPropertyAsString(bc, HttpConfig.DEFAULT_CHAR_ENCODING_KEY, "ISO-8859-1")); config.put(HttpConfig.REQ_CLIENT_AUTH_KEY, getPropertyAsBoolean(bc, "org.knopflerfish.http.req.client.auth", "false")); return config; }
|
00
|
Code Sample 1:
public void copyContent(long mailId1, long mailId2) throws Exception { File file1 = new File(this.getMailDir(mailId1) + "/"); File file2 = new File(this.getMailDir(mailId2) + "/"); this.recursiveDir(file2); if (file1.isDirectory()) { File[] files = file1.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i].isFile()) { File file2s = new File(file2.getAbsolutePath() + "/" + files[i].getName()); if (!file2s.exists()) { file2s.createNewFile(); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file2s)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(files[i])); int read; while ((read = in.read()) != -1) { out.write(read); } out.flush(); if (in != null) { try { in.close(); } catch (IOException ex1) { ex1.printStackTrace(); } } if (out != null) { try { out.close(); } catch (IOException ex) { ex.printStackTrace(); } } } } } } } }
Code Sample 2:
@Test public void test01_ok_failed_500() throws Exception { DefaultHttpClient client = new DefaultHttpClient(); try { HttpPost post = new HttpPost(chartURL); HttpResponse response = client.execute(post); assertEquals("failed code for ", 500, response.getStatusLine().getStatusCode()); } finally { client.getConnectionManager().shutdown(); } }
|
00
|
Code Sample 1:
private void openConnection() throws IOException { connection = (HttpURLConnection) url.openConnection(Global.getProxy()); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "text/xml; charset=" + XmlRpcMessages.getString("XmlRpcClient.Encoding")); if (requestProperties != null) { for (Iterator propertyNames = requestProperties.keySet().iterator(); propertyNames.hasNext(); ) { String propertyName = (String) propertyNames.next(); connection.setRequestProperty(propertyName, (String) requestProperties.get(propertyName)); } } }
Code Sample 2:
public void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType(s_contentType); response.setHeader("Cache-control", "no-cache"); InputStream graphStream = getGraphStream(request); OutputStream out = getOutputStream(response); IOUtils.copy(graphStream, out); out.flush(); }
|
00
|
Code Sample 1:
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(); }
Code Sample 2:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
|
11
|
Code Sample 1:
private void appendArchive() throws Exception { String cmd; if (profile == CompilationProfile.UNIX_GCC) { cmd = "cat"; } else if (profile == CompilationProfile.MINGW_WINDOWS) { cmd = "type"; } else { throw new Exception("Unknown cat equivalent for profile " + profile); } compFrame.writeLine("<span style='color: green;'>" + cmd + " \"" + imageArchive.getAbsolutePath() + "\" >> \"" + outputFile.getAbsolutePath() + "\"</span>"); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outputFile, true)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(imageArchive)); int read; while ((read = in.read()) != -1) { out.write(read); } in.close(); out.close(); }
Code Sample 2:
public void convert(File file, String fromEncoding, String toEncoding) throws IOException { InputStream in = new FileInputStream(file); StringWriter cache = new StringWriter(); Reader reader = new InputStreamReader(in, fromEncoding); char[] buffer = new char[128]; int read; while ((read = reader.read(buffer)) > -1) { cache.write(buffer, 0, read); } reader.close(); in.close(); Log.warn(this, "read from file " + file + " (" + fromEncoding + "):" + cache); OutputStream out = new FileOutputStream(file); OutputStreamWriter writer = new OutputStreamWriter(out, toEncoding); writer.write(cache.toString()); cache.close(); writer.close(); out.close(); }
|
11
|
Code Sample 1:
private void fetchTree() throws IOException { String urlString = BASE_URL + TREE_URL + DATASET_URL + "&family=" + mFamily; URL url = new URL(urlString); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String toParse = in.readLine(); while (in.ready()) { String add = in.readLine(); if (add == null) break; toParse += add; } if (toParse != null && !toParse.startsWith("No tree available")) mProteinTree = new PTree(this, toParse); }
Code Sample 2:
public static String getInstanceUserdata() throws IOException { int retries = 0; while (true) { try { URL url = new URL("http://169.254.169.254/latest/user-data/"); InputStreamReader rdr = new InputStreamReader(url.openStream()); StringWriter wtr = new StringWriter(); char[] buf = new char[1024]; int bytes; while ((bytes = rdr.read(buf)) > -1) { if (bytes > 0) { wtr.write(buf, 0, bytes); } } rdr.close(); return wtr.toString(); } catch (IOException ex) { if (retries == 5) { logger.debug("Problem getting user data, retries exhausted..."); return null; } else { logger.debug("Problem getting user data, retrying..."); try { Thread.sleep((int) Math.pow(2.0, retries) * 1000); } catch (InterruptedException e) { } retries++; } } } }
|
11
|
Code Sample 1:
public static String Sha1(String s) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] hash = new byte[40]; md.update(s.getBytes("iso-8859-1"), 0, s.length()); hash = md.digest(); return toHex(hash); } catch (Exception e) { e.printStackTrace(); return null; } }
Code Sample 2:
public String getMD5String(String par1Str) { try { String s = (new StringBuilder()).append(field_27370_a).append(par1Str).toString(); MessageDigest messagedigest = MessageDigest.getInstance("MD5"); messagedigest.update(s.getBytes(), 0, s.length()); return (new BigInteger(1, messagedigest.digest())).toString(16); } catch (NoSuchAlgorithmException nosuchalgorithmexception) { throw new RuntimeException(nosuchalgorithmexception); } }
|
00
|
Code Sample 1:
public void run() { try { HttpURLConnection con = (HttpURLConnection) url.openConnection(); Osm2Model osm = new Osm2Model(pedestrian, filterCyclic); osm.progress.connect(this, "progress(int)"); osm.parseFile(con.getInputStream(), con.getContentLength()); if (osm.somethingImported()) { done.emit(); } else { nothing.emit(); } } catch (Exception e) { failed.emit(); } }
Code Sample 2:
public void copyFile(String source_name, String dest_name) throws IOException { File source_file = new File(source_name); File destination_file = new File(dest_name); Reader source = null; Writer destination = null; char[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException("FileCopy: no such source file: " + source_name); if (!source_file.canRead()) throw new FileCopyException("FileCopy: source file " + "is unreadable: " + source_name); if (destination_file.exists()) { if (destination_file.isFile()) { DataInputStream in = new DataInputStream(System.in); String response; if (!destination_file.canWrite()) throw new FileCopyException("FileCopy: destination " + "file is unwriteable: " + dest_name); } else { throw new FileCopyException("FileCopy: destination " + "is not a file: " + dest_name); } } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException("FileCopy: destination " + "directory doesn't exist: " + dest_name); if (!parentdir.canWrite()) throw new FileCopyException("FileCopy: destination " + "directory is unwriteable: " + dest_name); } source = new BufferedReader(new FileReader(source_file)); destination = new BufferedWriter(new FileWriter(destination_file)); buffer = new char[1024]; while (true) { bytes_read = source.read(buffer, 0, 1024); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } finally { if (source != null) { try { source.close(); } catch (IOException e) { ; } } if (destination != null) { try { destination.close(); } catch (IOException e) { ; } } } }
|
11
|
Code Sample 1:
public static boolean copy(File source, File target) { try { if (!source.exists()) return false; target.getParentFile().mkdirs(); InputStream input = new FileInputStream(source); OutputStream output = new FileOutputStream(target); byte[] buf = new byte[1024]; int len; while ((len = input.read(buf)) > 0) output.write(buf, 0, len); input.close(); output.close(); return true; } catch (Exception exc) { exc.printStackTrace(); return false; } }
Code Sample 2:
public void execute(File tsvFile, File xmlFile) { BufferedReader reader = null; Writer writer = null; Boolean isFileSuccessfullyConverted = Boolean.TRUE; TableConfiguration tableConfig = null; try { xmlFile.getParentFile().mkdirs(); reader = new BufferedReader(new InputStreamReader(new FileInputStream(tsvFile), INPUT_ENCODING)); writer = new OutputStreamWriter(new FileOutputStream(xmlFile), OUTPUT_ENCODING); tableConfig = Tsv2DocbookConverter.convert2(tableConfigManager, idScanner.extractIdentification(tsvFile), reader, writer, inputPolisher); isFileSuccessfullyConverted = (tableConfig != null); } catch (UnsupportedEncodingException e) { logger.error("Failed to create reader with UTF-8 encoding: " + e.getMessage(), e); } catch (FileNotFoundException fnfe) { logger.error("Failed to open tsv input file '" + tsvFile + "'. " + fnfe.getMessage()); } catch (Throwable cause) { logger.error("Failed to convert input tsv file '" + tsvFile + "'.", cause); } finally { if (reader != null) { try { reader.close(); } catch (IOException ioe) { logger.warn("Unable to close input file.", ioe); } } if (writer != null) { try { writer.close(); } catch (IOException ioe) { logger.warn("Unable to close output file.", ioe); } } } if (isFileSuccessfullyConverted) { String newOutputFileName = tableConfig.getFileName(idScanner.extractIdentification(tsvFile)); if (newOutputFileName != null) { File newOutputFile = new File(xmlFile.getParentFile(), newOutputFileName); if (!xmlFile.renameTo(newOutputFile)) { logger.warn("Unable to rename '" + xmlFile + "' to '" + newOutputFile + "'."); logger.info("Created successfully '" + xmlFile + "'."); } else { logger.info("Created successfully '" + newOutputFileName + "'."); } } else { logger.info("Created successfully '" + xmlFile + "'."); } } else { logger.warn("Unable to convert input tsv file '" + Tsv2DocBookApplication.trimPath(sourceDir, tsvFile) + "' to docbook."); if (xmlFile.exists() && !xmlFile.delete()) { logger.warn("Unable to remove (empty) output file '" + xmlFile + "', which was created as target for the docbook table."); } } }
|
00
|
Code Sample 1:
public static void addClasses(URL url) { BufferedReader reader = null; String line; ClassLoader cl = Thread.currentThread().getContextClassLoader(); try { reader = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = reader.readLine()) != null) { line = line.trim(); if ((line.length() == 0) || line.startsWith(";")) { continue; } try { classes.add(Class.forName(line, true, cl)); } catch (Throwable t) { } } } catch (Throwable t) { } finally { if (reader != null) { try { reader.close(); } catch (Throwable t) { } } } }
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 void loginToServer() { new Thread(new Runnable() { public void run() { if (!shouldLogin) { u.p("skipping the auto-login"); return; } try { u.p("logging in to the server"); String query = "hostname=blahfoo2.com" + "&osname=" + URLEncoder.encode(System.getProperty("os.name"), "UTF-8") + "&javaver=" + URLEncoder.encode(System.getProperty("java.runtime.version"), "UTF-8") + "&timezone=" + URLEncoder.encode(TimeZone.getDefault().getID(), "UTF-8"); u.p("unencoded query: \n" + query); String login_url = "http://joshy.org:8088/org.glossitopeTracker/login.jsp?"; String url = login_url + query; u.p("final encoded url = \n" + url); InputStream in = new URL(url).openStream(); byte[] buf = new byte[256]; while (true) { int n = in.read(buf); if (n == -1) break; for (int i = 0; i < n; i++) { } } } catch (MalformedURLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } }, "LoginToServerAction").start(); }
Code Sample 2:
@Test public void testTrainingQuickprop() throws IOException { File temp = File.createTempFile("fannj_", ".tmp"); temp.deleteOnExit(); IOUtils.copy(this.getClass().getResourceAsStream("xor.data"), new FileOutputStream(temp)); List<Layer> layers = new ArrayList<Layer>(); layers.add(Layer.create(2)); layers.add(Layer.create(3, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); layers.add(Layer.create(1, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); Fann fann = new Fann(layers); Trainer trainer = new Trainer(fann); trainer.setTrainingAlgorithm(TrainingAlgorithm.FANN_TRAIN_QUICKPROP); float desiredError = .001f; float mse = trainer.train(temp.getPath(), 500000, 1000, desiredError); assertTrue("" + mse, mse <= desiredError); }
|
11
|
Code Sample 1:
public static void main(String[] args) { File container = new File(ArchiveFeature.class.getProtectionDomain().getCodeSource().getLocation().toURI()); if (container == null) { throw new RuntimeException("this use-case isn't being invoked from the executable jar"); } JarFile jarFile = new JarFile(container); String artifactName = PROJECT_DIST_ARCHIVE + ".tar.gz"; File artifactFile = new File(".", artifactName); ZipEntry artifactEntry = jarFile.getEntry(artifactName); InputStream source = jarFile.getInputStream(artifactEntry); try { FileOutputStream dest = new FileOutputStream(artifactFile); try { IOUtils.copy(source, dest); } finally { IOUtils.closeQuietly(dest); } } finally { IOUtils.closeQuietly(source); } Project project = new Project(); project.setName("project"); project.init(); Target target = new Target(); target.setName("target"); project.addTarget(target); project.addBuildListener(new Log4jListener()); Untar untar = new Untar(); untar.setTaskName("untar"); untar.setSrc(artifactFile); untar.setDest(new File(".")); Untar.UntarCompressionMethod method = new Untar.UntarCompressionMethod(); method.setValue("gzip"); untar.setCompression(method); untar.setProject(project); untar.setOwningTarget(target); target.addTask(untar); untar.execute(); }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
00
|
Code Sample 1:
private static synchronized void calcLocalFileHash() { long startTime = System.currentTimeMillis(); if (currentFileHash != null) return; List fileList = getAllFiles("/", new AllFilesFilter()); int len = 0; byte[] buf = new byte[1024]; try { MessageDigest digest = MessageDigest.getInstance("SHA"); for (Iterator i = fileList.iterator(); i.hasNext(); ) { String path = (String) i.next(); LocalFileResource lfr = new LocalFileResource(path); if (lfr.isDirectory()) { digest.update(path.getBytes("UTF-8")); continue; } InputStream stream = lfr.getFileAsInputStream(); while ((len = stream.read(buf)) != -1) { digest.update(buf, 0, len); } stream.close(); } currentFileHash = new String(Hex.encodeHex(digest.digest())); } catch (Exception e) { log.error("No SHA found ...?", e); currentFileHash = "unknown" + System.currentTimeMillis(); } finally { if (log.isDebugEnabled()) log.debug("Needed " + (System.currentTimeMillis() - startTime) + "ms for hash calculation"); } }
Code Sample 2:
public static void resize(File originalFile, File resizedFile, int width, String format) throws IOException { if (format != null && "gif".equals(format.toLowerCase())) { resize(originalFile, resizedFile, width, 1); return; } FileInputStream fis = new FileInputStream(originalFile); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); int readLength = -1; int bufferSize = 1024; byte bytes[] = new byte[bufferSize]; while ((readLength = fis.read(bytes, 0, bufferSize)) != -1) { byteStream.write(bytes, 0, readLength); } byte[] in = byteStream.toByteArray(); fis.close(); byteStream.close(); Image inputImage = Toolkit.getDefaultToolkit().createImage(in); waitForImage(inputImage); int imageWidth = inputImage.getWidth(null); if (imageWidth < 1) throw new IllegalArgumentException("image width " + imageWidth + " is out of range"); int imageHeight = inputImage.getHeight(null); if (imageHeight < 1) throw new IllegalArgumentException("image height " + imageHeight + " is out of range"); int height = -1; double scaleW = (double) imageWidth / (double) width; double scaleY = (double) imageHeight / (double) height; if (scaleW >= 0 && scaleY >= 0) { if (scaleW > scaleY) { height = -1; } else { width = -1; } } Image outputImage = inputImage.getScaledInstance(width, height, java.awt.Image.SCALE_DEFAULT); checkImage(outputImage); encode(new FileOutputStream(resizedFile), outputImage, format); }
|
11
|
Code Sample 1:
public static void encrypt(File plain, File symKey, File ciphered, String algorithm) throws IOException, ClassNotFoundException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { Key key = null; try { ObjectInputStream in = new ObjectInputStream(new FileInputStream(symKey)); key = (Key) in.readObject(); } catch (IOException ioe) { KeyGenerator generator = KeyGenerator.getInstance(algorithm); key = generator.generateKey(); ObjectOutputStream out = new ObjectOutputStream(new java.io.FileOutputStream(symKey)); out.writeObject(key); out.close(); } Cipher cipher = Cipher.getInstance(algorithm); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getEncoded(), algorithm)); FileInputStream in = new FileInputStream(plain); CipherOutputStream out = new CipherOutputStream(new FileOutputStream(ciphered), cipher); byte[] buffer = new byte[4096]; for (int read = in.read(buffer); read > -1; read = in.read(buffer)) { out.write(buffer, 0, read); } out.close(); }
Code Sample 2:
private static void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException { if (entry.isDirectory()) { createDir(new File(outputDir, entry.getName())); return; } File outputFile = new File(outputDir, entry.getName()); if (!outputFile.getParentFile().exists()) { createDir(outputFile.getParentFile()); } BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); try { IOUtils.copy(inputStream, outputStream); } finally { outputStream.close(); inputStream.close(); } }
|
00
|
Code Sample 1:
private static void ensureJavaScriptHostBytes(TreeLogger logger) throws UnableToCompleteException { if (javaScriptHostBytes != null) { return; } String className = JavaScriptHost.class.getName(); try { String path = className.replace('.', '/') + ".class"; ClassLoader cl = Thread.currentThread().getContextClassLoader(); URL url = cl.getResource(path); if (url != null) { javaScriptHostBytes = getClassBytesFromStream(url.openStream()); } else { logger.log(TreeLogger.ERROR, "Could not find required bootstrap class '" + className + "' in the classpath", null); throw new UnableToCompleteException(); } } catch (IOException e) { logger.log(TreeLogger.ERROR, "Error reading class bytes for " + className, e); throw new UnableToCompleteException(); } }
Code Sample 2:
private void writeData(IBaseType dataType, Writer writer) throws XMLStreamException { InputStream isData; DataType data = (DataType) baseType; if (data.isSetInputStream()) { isData = data.getInputStream(); try { IOUtils.copy(isData, writer); } catch (IOException e) { throw new XMLStreamException("DataType fail writing streaming data ", e); } } else if (data.isSetOutputStream()) { throw new XMLStreamException("DataType only can write streaming input, its an output stream (only for reading) "); } else { new CharactersEventImpl(startElement.getLocation(), String.valueOf(baseType.asData()), false).writeAsEncodedUnicode(writer); } }
|
11
|
Code Sample 1:
public static void nuovoAcquisto(int quantita, Date d, double price, int id) throws SQLException { MyDBConnection c = new MyDBConnection(); c.init(); Connection conn = c.getMyConnection(); PreparedStatement ps = conn.prepareStatement(insertAcquisto); ps.setInt(1, quantita); ps.setDate(2, d); ps.setDouble(3, price); ps.setInt(4, id); ps.executeUpdate(); double newPrice = price; int newQ = quantita; ResultSet rs = MyDBConnection.executeQuery(queryPrezzo.replace("?", "" + id), conn); if (rs.next()) { int oldQ = rs.getInt(1); double oldPrice = rs.getDouble(2); newQ = quantita + oldQ; newPrice = (oldPrice * oldQ + price * quantita) / newQ; updatePortafoglio(conn, newPrice, newQ, id); } else insertPortafoglio(conn, id, newPrice, newQ); try { conn.commit(); } catch (SQLException e) { conn.rollback(); throw new SQLException("Effettuato rollback dopo " + e.getMessage()); } finally { c.close(); } }
Code Sample 2:
public void reset(int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? "); psta.setInt(1, currentPilot); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
|
11
|
Code Sample 1:
public static void rewrite(String[] args) throws IOException, CodeCheckException { ClassWriter writer = new ClassWriter(); writer.readClass(new FileInputStream(args[0])); for (Iterator i = writer.getMethods().iterator(); i.hasNext(); ) { MethodInfo method = (MethodInfo) i.next(); CodeAttribute attribute = method.getCodeAttribute(); int origStack = attribute.getMaxStack(); System.out.print(method.getName()); attribute.codeCheck(); System.out.println(" " + origStack + " " + attribute.getMaxStack()); } BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(args[1])); writer.writeClass(outStream); outStream.close(); }
Code Sample 2:
public byte[] getResponseContent() throws IOException { if (responseContent == null) { InputStream is = getResponseStream(); if (is == null) { responseContent = new byte[0]; } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); IOUtils.copy(is, baos); responseContent = baos.toByteArray(); } } return responseContent; }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.