label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: public static long toFile(final DigitalObject object, final File file) { try { FileOutputStream fOut = new FileOutputStream(file); long bytesCopied = IOUtils.copyLarge(object.getContent().getInputStream(), fOut); fOut.close(); return bytesCopied; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return 0; } Code Sample 2: public static String email_get_public_hash(String email) { try { if (email != null) { email = email.trim().toLowerCase(); CRC32 crc32 = new CRC32(); crc32.reset(); crc32.update(email.getBytes()); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); return crc32.getValue() + " " + new String(md5.digest(email.getBytes())); } } catch (Exception e) { } return ""; }
00
Code Sample 1: public HttpURLConnection proxiedURLConnection(URL url, String serverName) throws IOException, PussycatException { if (this.httpProxy == null || this.httpProxy.equals("") || PussycatUtils.isLocalURL(url.toString()) || url.toString().contains(serverName)) { System.getProperties().put("proxySet", "false"); } else { System.getProperties().put("proxySet", "true"); } if (System.getProperties().getProperty("proxySet").equals("true")) { return (java.net.HttpURLConnection) url.openConnection(new java.net.Proxy(java.net.Proxy.Type.HTTP, new java.net.InetSocketAddress(this.httpProxy, this.httpProxyPort))); } else { return (java.net.HttpURLConnection) url.openConnection(); } } Code Sample 2: private void announce(String trackerURL, byte[] hash, byte[] peerId, int port) { try { String strUrl = trackerURL + "?info_hash=" + URLEncoder.encode(new String(hash, Constants.BYTE_ENCODING), Constants.BYTE_ENCODING).replaceAll("\\+", "%20") + "&peer_id=" + URLEncoder.encode(new String(peerId, Constants.BYTE_ENCODING), Constants.BYTE_ENCODING).replaceAll("\\+", "%20") + "&port=" + port + "&uploaded=0&downloaded=0&left=0&numwant=50&no_peer_id=1&compact=1"; URL url = new URL(strUrl); URLConnection con = url.openConnection(); con.connect(); con.getContent(); } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: private void copy(String inputPath, String outputPath, String name) { try { FileReader in = new FileReader(inputPath + name); FileWriter out = new FileWriter(outputPath + name); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: private static void copyFile(String fromFile, String toFile) throws Exception { FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
00
Code Sample 1: public void addUser(String username, String password, String filename) { String data = ""; try { open(filename); MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(password.getBytes()); byte[] digest = mdAlgorithm.digest(); StringBuffer encPasswd = new StringBuffer(); for (int i = 0; i < digest.length; i++) { password = Integer.toHexString(255 & digest[i]); if (password.length() < 2) { password = "0" + password; } encPasswd.append(password); data = username + " " + encPasswd + "\r\n"; } try { long length = file.length(); file.seek(length); file.write(data.getBytes()); } catch (IOException ex) { ex.printStackTrace(); } close(); } catch (NoSuchAlgorithmException ex) { } } Code Sample 2: public static void downloadFileFromHTTP(String address) { OutputStream out = null; URLConnection conn = null; InputStream in = null; int lastSlashIndex = address.lastIndexOf('/'); if (!(lastSlashIndex >= 0 && lastSlashIndex < address.length() - 1)) { System.err.println("Could not figure out local file name for " + address); } else { try { String localFileName; if (!ZeroFileSettings.getDownloadFolder().equals("")) localFileName = ZeroFileSettings.getDownloadFolder() + "/" + address.substring(lastSlashIndex + 1).replace("%20", " "); else localFileName = System.getProperty("user.home") + "/" + address.substring(lastSlashIndex + 1).replace("%20", " "); URL url = new URL(address); out = new BufferedOutputStream(new FileOutputStream(localFileName)); conn = url.openConnection(); in = conn.getInputStream(); byte[] buffer = new byte[1024]; int numRead; long numWritten = 0; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); numWritten += numRead; } } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException ioe) { System.out.println(ioe); } } } }
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: private void serveCGI(TinyCGI script) throws IOException, TinyWebThreadException { parseHTTPHeaders(); OutputStream cgiOut = null; File tempFile = null; try { if (script == null) sendError(500, "Internal Error", "Couldn't load script."); if (script instanceof TinyCGIHighVolume) { tempFile = File.createTempFile("cgi", null); cgiOut = new FileOutputStream(tempFile); } else { cgiOut = new ByteArrayOutputStream(); } script.service(inputStream, cgiOut, env); } catch (Exception cgie) { this.exceptionEncountered = cgie; if (tempFile != null) tempFile.delete(); if (clientSocket == null) { return; } else if (cgie instanceof TinyCGIException) { TinyCGIException tce = (TinyCGIException) cgie; sendError(tce.getStatus(), tce.getTitle(), tce.getText(), tce.getOtherHeaders()); } else { StringWriter w = new StringWriter(); cgie.printStackTrace(new PrintWriter(w)); sendError(500, "CGI Error", "Error running script: " + "<PRE>" + w.toString() + "</PRE>"); } } finally { if (script != null) doneWithScript(script); } InputStream cgiResults = null; long totalSize = 0; if (tempFile == null) { byte[] results = ((ByteArrayOutputStream) cgiOut).toByteArray(); totalSize = results.length; cgiResults = new ByteArrayInputStream(results); } else { cgiOut.close(); totalSize = tempFile.length(); cgiResults = new FileInputStream(tempFile); } String contentType = null, statusString = "OK", line, header; StringBuffer otherHeaders = new StringBuffer(); StringBuffer text = new StringBuffer(); int status = 200; int headerLength = 0; while (true) { line = readLine(cgiResults, true); headerLength += line.length(); if (line.charAt(0) == '\r' || line.charAt(0) == '\n') break; header = parseHeader(line, text); if (header.toUpperCase().equals("STATUS")) { statusString = text.toString(); status = Integer.parseInt(statusString.substring(0, 3)); statusString = statusString.substring(4); } else if (header.toUpperCase().equals("CONTENT-TYPE")) contentType = text.toString(); else { if (header.toUpperCase().equals("LOCATION")) status = 302; otherHeaders.append(header).append(": ").append(text.toString()).append(CRLF); } } sendHeaders(status, statusString, contentType, totalSize - headerLength, -1, otherHeaders.toString()); byte[] buf = new byte[2048]; int bytesRead; while ((bytesRead = cgiResults.read(buf)) != -1) outputStream.write(buf, 0, bytesRead); outputStream.flush(); try { cgiResults.close(); if (tempFile != null) tempFile.delete(); } catch (IOException ioe) { } }
11
Code Sample 1: public static String md5(String value) throws NoSuchAlgorithmException { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); try { messageDigest.update(value.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { messageDigest.update(value.getBytes()); } byte[] bytes = messageDigest.digest(); return byteArrayToHexString(bytes); } Code Sample 2: public static String SHA1(String text) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(text.getBytes()); byte byteData[] = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } StringBuffer hexString = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { String hex = Integer.toHexString(0xff & byteData[i]); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); }
00
Code Sample 1: public synchronized void run() { logger.info("SEARCH STARTED"); JSONObject json = null; logger.info("Opening urlConnection"); URLConnection connection = null; try { connection = url.openConnection(); connection.addRequestProperty("Referer", HTTP_REFERER); } catch (IOException e) { logger.warn("PROBLEM CONTACTING GOOGLE"); e.printStackTrace(); } String line; StringBuilder builder = new StringBuilder(); BufferedReader reader; try { reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((line = reader.readLine()) != null) { builder.append(line); } } catch (IOException e) { logger.warn("PROBLEM RETREIVING DATA FROM GOOGLE"); e.printStackTrace(); } logger.info("Google RET: " + builder.toString()); try { json = new JSONObject(builder.toString()); json.append("query", q); } catch (JSONException e) { logger.warn("PROBLEM RETREIVING DATA FROM GOOGLE"); e.printStackTrace(); } sc.onSearchFinished(json); } Code Sample 2: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
00
Code Sample 1: public void update() { Vector invalids = new Vector(); for (int i = 0; i < urls.size(); i++) { URL url = null; try { url = new URL((String) urls.elementAt(i)); InputStream stream = url.openStream(); stream.close(); } catch (MalformedURLException urlE) { Logger.logWarning("Malformed URL: " + urls.elementAt(i)); } catch (IOException ioE) { invalids.addElement(url); } } for (int i = 0; i < invalids.size(); i++) { urls.removeElement(invalids.elementAt(i)); Logger.logInfo("Removed " + invalids.elementAt(i) + " - no longer available"); } } Code Sample 2: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String cacheName = req.getParameter("cacheName"); if (cacheName == null || cacheName.equals("")) { resp.getWriter().println("parameter cacheName required"); return; } else { StringBuffer urlStr = new StringBuffer(); urlStr.append(BASE_URL); urlStr.append("?"); urlStr.append("cacheName="); urlStr.append("rpcwc.bo.cache."); urlStr.append(cacheName); URL url = new URL(urlStr.toString()); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; StringBuffer output = new StringBuffer(); while ((line = reader.readLine()) != null) { output.append(line); output.append(System.getProperty("line.separator")); } reader.close(); resp.getWriter().println(output.toString()); } }
11
Code Sample 1: protected static String encodePassword(String raw_password) throws DatabaseException { String clean_password = validatePassword(raw_password); try { MessageDigest md = MessageDigest.getInstance(DEFAULT_PASSWORD_DIGEST); md.update(clean_password.getBytes(DEFAULT_PASSWORD_ENCODING)); String digest = new String(Base64.encodeBase64(md.digest())); if (log.isDebugEnabled()) log.debug("encodePassword: digest=" + digest); return digest; } catch (UnsupportedEncodingException e) { throw new DatabaseException("encoding-problem with password", e); } catch (NoSuchAlgorithmException e) { throw new DatabaseException("digest-problem encoding password", e); } } Code Sample 2: public static String encrypt(String value) { MessageDigest messageDigest; byte[] raw = null; try { messageDigest = MessageDigest.getInstance("SHA"); messageDigest.update(((String) value).getBytes("UTF-8")); raw = messageDigest.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return (new BASE64Encoder()).encode(raw); }
00
Code Sample 1: @Override protected URLConnection openConnection(URL url) throws IOException { try { final HttpServlet servlet; String path = url.getPath(); if (path.matches("reg:.+")) { String registerName = path.replaceAll("reg:([^/]*)/.*", "$1"); servlet = register.get(registerName); if (servlet == null) throw new RuntimeException("No servlet registered with name " + registerName); } else { String servletClassName = path.replaceAll("([^/]*)/.*", "$1"); servlet = (HttpServlet) Class.forName(servletClassName).newInstance(); } final MockHttpServletRequest req = new MockHttpServletRequest().setMethod("GET"); final MockHttpServletResponse resp = new MockHttpServletResponse(); return new HttpURLConnection(url) { @Override public int getResponseCode() throws IOException { serviceIfNeeded(); return resp.status; } @Override public InputStream getInputStream() throws IOException { serviceIfNeeded(); if (resp.status == 500) throw new IOException("Server responded with error 500"); byte[] array = resp.out.toByteArray(); return new ByteArrayInputStream(array); } @Override public InputStream getErrorStream() { try { serviceIfNeeded(); } catch (IOException e) { throw new RuntimeException(e); } if (resp.status != 500) return null; return new ByteArrayInputStream(resp.out.toByteArray()); } @Override public OutputStream getOutputStream() throws IOException { return req.tmp; } @Override public void addRequestProperty(String key, String value) { req.addHeader(key, value); } @Override public void connect() throws IOException { } @Override public boolean usingProxy() { return false; } @Override public void disconnect() { } private boolean called; private void serviceIfNeeded() throws IOException { try { if (!called) { called = true; req.setMethod(getRequestMethod()); servlet.service(req, resp); } } catch (ServletException e) { throw new RuntimeException(e); } } }; } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } Code Sample 2: public void doRecurringPayment(Subscription subscription) { int amount = Math.round(subscription.getTotalCostWithDiscounts() * 100.0f); String currency = subscription.getCurrency(); String aliasCC = subscription.getAliasCC(); String expm = subscription.getLastCardExpm(); String expy = subscription.getLastCardExpy(); String subscriptionId = String.valueOf(subscription.getSubscriptionId()); StringBuffer xmlSB = new StringBuffer(""); xmlSB.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); xmlSB.append("<authorizationService version=\"1\">\n"); xmlSB.append(" <body merchantId=\"" + getMerchantId() + "\" testOnly=\"" + getTestOnly() + "\">\n"); xmlSB.append(" <transaction refno=\"" + REF_NO + "\">\n"); xmlSB.append(" <request>\n"); xmlSB.append(" <amount>" + amount + "</amount>\n"); xmlSB.append(" <currency>" + currency + "</currency>\n"); xmlSB.append(" <aliasCC>" + aliasCC + "</aliasCC>\n"); xmlSB.append(" <expm>" + expm + "</expm>\n"); xmlSB.append(" <expy>" + expy + "</expy>\n"); xmlSB.append(" <subscriptionId>" + subscriptionId + "</subscriptionId>\n"); xmlSB.append(" </request>\n"); xmlSB.append(" </transaction>\n"); xmlSB.append(" </body>\n"); xmlSB.append("</authorizationService>\n"); String xmlS = xmlSB.toString(); try { java.net.URL murl = new java.net.URL(getRecurringPaymentUrl()); java.net.HttpURLConnection mcon = (java.net.HttpURLConnection) murl.openConnection(); mcon.setRequestMethod("POST"); mcon.setRequestProperty("encoding", "UTF-8"); mcon.setRequestProperty("Content-Type", "text/xml"); mcon.setRequestProperty("Content-length", String.valueOf(xmlS.length())); mcon.setDoOutput(true); java.io.OutputStream outs = mcon.getOutputStream(); outs.write(xmlS.getBytes("UTF-8")); outs.close(); java.io.BufferedReader inps = new java.io.BufferedReader(new java.io.InputStreamReader(mcon.getInputStream())); StringBuffer respSB = new StringBuffer(""); String s = null; while ((s = inps.readLine()) != null) { respSB.append(s); } inps.close(); String respXML = respSB.toString(); processReccurentPaymentResponce(respXML); } catch (Exception ex) { throw new SecurusException(ex); } }
00
Code Sample 1: static List<String> readZipFilesOftypeToFolder(String zipFileLocation, String outputDir, String fileType) { List<String> list = new ArrayList<String>(); ZipFile zipFile = readZipFile(zipFileLocation); FileOutputStream output = null; InputStream inputStream = null; Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zipFile.entries(); try { while (entries.hasMoreElements()) { java.util.zip.ZipEntry entry = entries.nextElement(); String entryName = entry.getName(); if (entryName != null && entryName.toLowerCase().endsWith(fileType)) { inputStream = zipFile.getInputStream(entry); String fileName = outputDir + entryName.substring(entryName.lastIndexOf("/")); File file = new File(fileName); output = new FileOutputStream(file); IOUtils.copy(inputStream, output); list.add(fileName); } } } catch (Exception e) { throw new RuntimeException(e); } finally { try { if (output != null) output.close(); if (inputStream != null) inputStream.close(); if (zipFile != null) zipFile.close(); } catch (IOException e) { throw new RuntimeException(e); } } return list; } Code Sample 2: public String generateFilename() { MessageDigest md; byte[] sha1hash = new byte[40]; Random r = new Random(); String fileName = ""; String token = ""; while (true) { token = Long.toString(Math.abs(r.nextLong()), 36) + Long.toString(System.currentTimeMillis()); try { md = MessageDigest.getInstance("SHA-1"); md.update(token.getBytes("iso-8859-1"), 0, token.length()); sha1hash = md.digest(); } catch (Exception e) { log.log(Level.WARNING, e.getMessage(), e); } fileName = convertToHex(sha1hash); if (!new File(Configuration.ImageUploadPath + fileName).exists()) { break; } } return fileName; }
00
Code Sample 1: public String quebraLink(String link) throws StringIndexOutOfBoundsException { link = link.replace(".url", ""); int cod = 0; final String linkInit = link.replace("#", ""); boolean estado = false; char letra; String linkOrig; String newlink = ""; linkOrig = link.replace("#", ""); linkOrig = linkOrig.replace(".url", ""); linkOrig = linkOrig.replace(".html", ""); linkOrig = linkOrig.replace("http://", ""); if (linkOrig.contains("clubedodownload")) { for (int i = 7; i < linkInit.length(); i++) { if (linkOrig.charAt(i) == '/') { for (int j = i + 1; j < linkOrig.length(); j++) { newlink += linkOrig.charAt(j); } if (newlink.contains("//:ptth")) { newlink = inverteFrase(newlink); if (isValid(newlink)) { return newlink; } } else if (newlink.contains("http://")) { if (isValid(newlink)) { return newlink; } } } } } if (linkOrig.contains("protetordelink.tv")) { for (int i = linkOrig.length() - 1; i >= 0; i--) { letra = linkOrig.charAt(i); if (letra == '/') { for (int j = i + 1; j < linkOrig.length(); j++) { newlink += linkOrig.charAt(j); } newlink = HexToChar(newlink); if (newlink.contains("ptth")) { if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); newlink = inverteFrase(newlink); if (isValid(newlink)) { return newlink; } } else { newlink = inverteFrase(newlink); if (isValid(newlink)) { return newlink; } } } else { if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } } } if (linkOrig.contains("baixeaquifilmes")) { for (int i = 0; i < linkOrig.length(); i++) { letra = linkOrig.charAt(i); if (letra == '?') { for (int j = i + 1; j < linkOrig.length(); j++) { newlink += linkOrig.charAt(j); } if (newlink.contains(":ptth")) { newlink = inverteFrase(newlink); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } else { if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } } } if (linkOrig.contains("downloadsgratis")) { for (int i = 0; i < linkOrig.length(); i++) { letra = linkOrig.charAt(i); if (letra == '!') { for (int j = i + 1; j < linkOrig.length(); j++) { newlink += linkOrig.charAt(j); } if (precisaRepassar(QuebraLink.decode64(newlink))) { newlink = quebraLink(QuebraLink.decode64(newlink)); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } } newlink = ""; if (linkOrig.contains("vinxp")) { System.out.println("é"); for (int i = 1; i < linkOrig.length(); i++) { if (linkOrig.charAt(i) == '=') { for (int j = i + 1; j < linkOrig.length(); j++) { newlink += linkOrig.charAt(j); } break; } } if (newlink.contains(".vinxp")) { newlink = newlink.replace(".vinxp", ""); } newlink = decodeCifraDeCesar(newlink); System.out.println(newlink); return newlink; } if (linkOrig.contains("?")) { String linkTemporary = ""; newlink = ""; if (linkOrig.contains("go!")) { linkOrig = linkOrig.replace("?go!", "?"); } if (linkOrig.contains("=")) { for (int i = 0; i < linkOrig.length(); i++) { letra = linkOrig.charAt(i); if (letra == '=') { for (int j = i + 1; j < linkOrig.length(); j++) { newlink += linkOrig.charAt(j); } linkTemporary = QuebraLink.decode64(newlink); break; } } if (linkTemporary.contains("http")) { newlink = ""; for (int i = 0; i < linkTemporary.length(); i++) { letra = linkTemporary.charAt(i); if (letra == 'h') { for (int j = i; j < linkTemporary.length(); j++) { newlink += linkTemporary.charAt(j); } newlink = newlink.replace("!og", ""); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } } if (linkTemporary.contains("ptth")) { newlink = ""; linkTemporary = inverteFrase(linkTemporary); for (int i = 0; i < linkTemporary.length(); i++) { letra = linkTemporary.charAt(i); if (letra == 'h') { for (int j = i; j < linkTemporary.length(); j++) { newlink += linkTemporary.charAt(j); } newlink = newlink.replace("!og", ""); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } } } linkTemporary = ""; for (int i = 0; i < linkOrig.length(); i++) { letra = linkOrig.charAt(i); if (letra == '?') { for (int j = i + 1; j < linkOrig.length(); j++) { linkTemporary += linkOrig.charAt(j); } link = QuebraLink.decode64(linkTemporary); break; } } if (link.contains("http")) { newlink = ""; for (int i = 0; i < link.length(); i++) { letra = link.charAt(i); if (letra == 'h') { for (int j = i; j < link.length(); j++) { newlink += link.charAt(j); } newlink = newlink.replace("!og", ""); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } } if (link.contains("ptth")) { newlink = ""; linkTemporary = inverteFrase(link); for (int i = 0; i < linkTemporary.length(); i++) { letra = linkTemporary.charAt(i); if (letra == 'h') { for (int j = i; j < linkTemporary.length(); j++) { newlink += linkTemporary.charAt(j); } newlink = newlink.replace("!og", ""); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } } linkOrig = linkInit; link = linkOrig; newlink = ""; } if (linkOrig.contains("?")) { String linkTemporary = ""; newlink = ""; if (linkOrig.contains("go!")) { linkOrig = linkOrig.replace("?go!", "?"); } if (linkOrig.contains("=")) { for (int i = 0; i < linkOrig.length(); i++) { letra = linkOrig.charAt(i); if (letra == '=') { for (int j = i + 1; j < linkOrig.length(); j++) { newlink += linkOrig.charAt(j); } linkTemporary = linkTemporary.replace(".", ""); try { linkTemporary = HexToChar(newlink); } catch (Exception e) { System.err.println("erro hex 1º"); estado = true; } break; } } if (linkTemporary.contains("http") && !estado) { newlink = ""; for (int i = 0; i < linkTemporary.length(); i++) { letra = linkTemporary.charAt(i); if (letra == 'h') { for (int j = i; j < linkTemporary.length(); j++) { newlink += linkTemporary.charAt(j); } newlink = newlink.replace("!og", ""); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } } if (linkTemporary.contains("ptth") && !estado) { newlink = ""; linkTemporary = inverteFrase(linkTemporary); for (int i = 0; i < linkTemporary.length(); i++) { letra = linkTemporary.charAt(i); if (letra == 'h') { for (int j = i; j < linkTemporary.length(); j++) { newlink += linkTemporary.charAt(j); } newlink = newlink.replace("!og", ""); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } } } estado = false; linkTemporary = ""; for (int i = 0; i < linkOrig.length(); i++) { letra = linkOrig.charAt(i); if (letra == '?') { for (int j = i + 1; j < linkOrig.length(); j++) { linkTemporary += linkOrig.charAt(j); } linkTemporary = linkTemporary.replace(".", ""); try { link = HexToChar(linkTemporary); } catch (Exception e) { System.err.println("erro hex 2º"); estado = true; } break; } } if (link.contains("http") && !estado) { newlink = ""; for (int i = 0; i < link.length(); i++) { letra = link.charAt(i); if (letra == 'h') { for (int j = i; j < link.length(); j++) { newlink += link.charAt(j); } newlink = newlink.replace("!og", ""); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } } if (link.contains("ptth") && !estado) { newlink = ""; linkTemporary = inverteFrase(link); for (int i = 0; i < linkTemporary.length(); i++) { letra = linkTemporary.charAt(i); if (letra == 'h') { for (int j = i; j < linkTemporary.length(); j++) { newlink += linkTemporary.charAt(j); } newlink = newlink.replace("!og", ""); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } } linkOrig = linkInit; link = linkOrig; newlink = ""; } if (linkOrig.contains("?") && !linkOrig.contains("id=") && !linkOrig.contains("url=") && !linkOrig.contains("link=") && !linkOrig.contains("r=http") && !linkOrig.contains("r=ftp")) { for (int i = 0; i < linkOrig.length(); i++) { letra = linkOrig.charAt(i); if (letra == '?') { newlink = ""; for (int j = i + 1; j < linkOrig.length(); j++) { newlink += linkOrig.charAt(j); } if (newlink.contains("ptth")) { newlink = inverteFrase(newlink); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } else { if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } } } if ((link.contains("url=")) || (link.contains("link=")) || (link.contains("?r=http")) || (link.contains("?r=ftp"))) { if (!link.contains("//:ptth")) { for (int i = 0; i < link.length(); i++) { letra = link.charAt(i); if (letra == '=') { for (int j = i + 1; j < link.length(); j++) { letra = link.charAt(j); newlink += letra; } break; } } if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } if (linkOrig.contains("//:ptth") || linkOrig.contains("//:sptth")) { if (linkOrig.contains("=")) { for (int i = 0; i < linkOrig.length(); i++) { letra = linkOrig.charAt(i); if (letra == '=') { for (int j = linkOrig.length() - 1; j > i; j--) { letra = linkOrig.charAt(j); newlink += letra; } break; } } if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } newlink = inverteFrase(linkOrig); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } if (linkOrig.contains("?go!")) { linkOrig = linkOrig.replace("?go!", "?down!"); newlink = linkOrig; if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } if (linkOrig.contains("down!")) { linkOrig = linkOrig.replace("down!", ""); return quebraLink(linkOrig); } newlink = ""; for (int i = linkOrig.length() - 4; i >= 0; i--) { letra = linkOrig.charAt(i); if (letra == '=') { for (int j = i + 1; j < linkOrig.length(); j++) { newlink += linkOrig.charAt(j); } break; } } String ltmp = ""; try { ltmp = HexToChar(newlink); } catch (Exception e) { System.err.println("erro hex 3º"); } if (ltmp.contains("http://")) { if (precisaRepassar(ltmp)) { ltmp = quebraLink(ltmp); if (isValid(ltmp)) { newlink = ltmp; return newlink; } } else { if (isValid(ltmp)) { newlink = ltmp; return newlink; } } } else if (ltmp.contains("//:ptth")) { ltmp = inverteFrase(ltmp); if (precisaRepassar(ltmp)) { ltmp = quebraLink(ltmp); if (isValid(ltmp)) { newlink = ltmp; return newlink; } } else { if (isValid(ltmp)) { newlink = ltmp; return newlink; } } } else { ltmp = newlink; } ltmp = decode64(newlink); if (ltmp.contains("http://")) { if (precisaRepassar(ltmp)) { ltmp = quebraLink(newlink); if (isValid(ltmp)) { newlink = ltmp; return newlink; } } else { if (isValid(ltmp)) { newlink = ltmp; return newlink; } } } else if (ltmp.contains("//:ptth")) { ltmp = inverteFrase(ltmp); if (precisaRepassar(ltmp)) { newlink = quebraLink(newlink); if (isValid(ltmp)) { newlink = ltmp; return newlink; } } else { if (isValid(ltmp)) { newlink = ltmp; return newlink; } } } else { ltmp = newlink; } try { ltmp = decodeAscii(newlink); } catch (NumberFormatException e) { System.err.println("erro ascii"); } if (ltmp.contains("http://")) { if (precisaRepassar(ltmp)) { ltmp = quebraLink(newlink); if (isValid(ltmp)) { newlink = ltmp; return newlink; } } else { if (isValid(ltmp)) { newlink = ltmp; return newlink; } } } else if (ltmp.contains("//:ptth")) { ltmp = inverteFrase(ltmp); if (precisaRepassar(ltmp)) { ltmp = quebraLink(ltmp); if (isValid(ltmp)) { newlink = ltmp; return newlink; } } else { if (isValid(ltmp)) { newlink = ltmp; return newlink; } } } else { ltmp = null; } newlink = ""; int cont = 0; letra = '\0'; ltmp = ""; newlink = ""; for (int i = linkOrig.length() - 4; i >= 0; i--) { letra = linkOrig.charAt(i); if (letra == '=' || letra == '?') { for (int j = i + 1; j < linkOrig.length(); j++) { if (linkOrig.charAt(j) == '.') { break; } newlink += linkOrig.charAt(j); } break; } } ltmp = newlink; String tmp = ""; String tmp2 = ""; do { try { tmp = HexToChar(ltmp); tmp2 = HexToChar(inverteFrase(ltmp)); if (!tmp.isEmpty() && tmp.length() > 5 && !tmp.contains("") && !tmp.contains("§") && !tmp.contains("�") && !tmp.contains("")) { ltmp = HexToChar(ltmp); } else if (!inverteFrase(tmp2).isEmpty() && inverteFrase(tmp2).length() > 5 && !inverteFrase(tmp2).contains("”") && !inverteFrase(tmp2).contains("§") && !inverteFrase(tmp2).contains("�")) { ltmp = HexToChar(inverteFrase(ltmp)); } } catch (NumberFormatException e) { } tmp = decode64(ltmp); tmp2 = decode64(inverteFrase(ltmp)); if (!tmp.contains("�") && !tmp.contains("ޚ")) { ltmp = decode64(ltmp); } else if (!tmp2.contains("�") && !tmp2.contains("ޚ")) { ltmp = decode64(inverteFrase(ltmp)); } try { tmp = decodeAscii(ltmp); tmp2 = decodeAscii(inverteFrase(ltmp)); if (!tmp.contains("Œ") && !tmp.contains("�") && !tmp.contains("§") && !tmp.contains("½") && !tmp.contains("*") && !tmp.contains("\"") && !tmp.contains("^")) { ltmp = decodeAscii(ltmp); } else if (!tmp2.contains("Œ") && !tmp2.contains("�") && !tmp2.contains("§") && !tmp2.contains("½") && !tmp2.contains("*") && !tmp2.contains("\"") && !tmp2.contains("^")) { ltmp = decodeAscii(inverteFrase(ltmp)); } } catch (NumberFormatException e) { } cont++; if (ltmp.contains("http")) { newlink = ltmp; if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } else if (ltmp.contains("ptth")) { newlink = inverteFrase(ltmp); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } while (!isValid(newlink) && cont <= 20); tmp = null; tmp2 = null; ltmp = null; String leitura = ""; try { leitura = readHTML(linkInit); } catch (IOException e) { } leitura = leitura.toLowerCase(); if (leitura.contains("trocabotao")) { newlink = ""; for (int i = leitura.indexOf("trocabotao"); i < leitura.length(); i++) { if (Character.isDigit(leitura.charAt(i))) { int tmpInt = i; while (Character.isDigit(leitura.charAt(tmpInt))) { newlink += leitura.charAt(tmpInt); tmpInt++; } cod = Integer.parseInt(newlink); break; } } if (cod != 0) { for (int i = 7; i < linkInit.length(); i++) { letra = linkInit.charAt(i); if (letra == '/') { newlink = linkInit.substring(0, i + 1) + "linkdiscover.php?cod=" + cod; break; } } DataInputStream dat = null; try { URL url = new URL(newlink); InputStream in = url.openStream(); dat = new DataInputStream(new BufferedInputStream(in)); leitura = ""; int dado; while ((dado = dat.read()) != -1) { letra = (char) dado; leitura += letra; } newlink = leitura.replaceAll(" ", ""); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } catch (MalformedURLException ex) { System.out.println("URL mal formada."); } catch (IOException e) { } finally { try { if (dat != null) { dat.close(); } } catch (IOException e) { System.err.println("Falha ao fechar fluxo."); } } } } if (precisaRepassar(linkInit)) { if (linkInit.substring(8).contains("http")) { newlink = linkInit.substring(linkInit.indexOf("http", 8), linkInit.length()); if (isValid(newlink)) { return newlink; } } } newlink = ""; StringBuffer strBuf = null; try { strBuf = new StringBuffer(readHTML(linkInit)); for (String tmp3 : getLibrary()) { if (strBuf.toString().toLowerCase().contains(tmp3)) { for (int i = strBuf.toString().indexOf(tmp3); i >= 0; i--) { if (strBuf.toString().charAt(i) == '"') { for (int j = i + 1; j < strBuf.length(); j++) { if (strBuf.toString().charAt(j) == '"') { if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } else { newlink += strBuf.toString().charAt(j); } } } } } } } catch (IOException ex) { } GUIQuebraLink.isBroken = false; return "Desculpe o link não pode ser quebrado."; } Code Sample 2: public static JuneClass loadClass(Map<String, Entity> globals, String packageName, String baseClassName) { try { JuneClass $class = null; String resourceName = (packageName.length() > 0 ? packageName.replace('.', '/') + "/" : "") + baseClassName.replace('.', '$') + ".class"; URL url = Resolver.class.getClassLoader().getResource(resourceName); if (url != null) { ClassBuilder builder = new ClassBuilder(globals); InputStream stream = url.openStream(); try { new ClassReader(new BufferedInputStream(stream)).accept(builder, ClassReader.SKIP_CODE); } finally { stream.close(); } $class = builder.$class; $class.loaded = true; } return $class; } catch (Exception e) { throw Helper.throwAny(e); } }
00
Code Sample 1: private byte[] md5Digest(String pPassword) { if (pPassword == null) { throw new NullPointerException("input null text for hashing"); } try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(pPassword.getBytes()); return md.digest(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Cannot find MD5 algorithm"); } } Code Sample 2: private boolean CheckConnection() { boolean b = false; String host = "" + Settings.getHost(); String user = "" + Settings.getUser(); String pass = "" + Settings.getPass(); int port = Settings.getPort(); if (!ftp.isConnected()) { try { int reply; ftp.connect(host, port); ftp.login(user, pass); ftp.enterLocalPassiveMode(); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); Settings.out("Error, connection refused from the FTP server." + host, 4); b = false; } else { b = true; } } catch (IOException e) { b = false; Settings.out("Error : " + e.toString(), 4); if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } } else { b = true; } return b; }
00
Code Sample 1: public void run() { synchronized (stateLock) { if (started) { return; } else { started = true; running = true; } } BufferedInputStream bis = null; BufferedOutputStream bos = null; BufferedReader br = null; try { checkState(); progressString = "Opening connection to remote resource"; progressUpdated = true; final URLConnection link; try { link = url.openConnection(); link.connect(); } catch (Exception e) { progressString = "Failed to open connection to remote resource"; progressUpdated = true; throw e; } checkState(); progressString = "Getting length of remote resource"; progressUpdated = true; final int length = link.getContentLength(); synchronized (lengthLock) { totalLength = length; } progressUpdated = true; checkState(); progressString = "Opening input stream to remote resource"; progressUpdated = true; try { final InputStream input = link.getInputStream(); if (target instanceof File) { bis = new BufferedInputStream(input); } else if (target instanceof StringBuilder) { final String contentType = link.getContentType().toLowerCase(Locale.ENGLISH); String charset = null; final Matcher m = Pattern.compile(".*charset[\\s]*=([^;]++).*").matcher(contentType); if (m.find()) { charset = m.group(1).trim(); } if ((charset != null) && !charset.isEmpty()) { try { br = new BufferedReader(new InputStreamReader(input, charset)); } catch (Exception e) { br = null; } } if (br == null) { br = new BufferedReader(new InputStreamReader(input)); } } } catch (Exception e) { progressString = "Failed to open input stream to remote resource"; progressUpdated = true; throw e; } if (target instanceof File) { checkState(); progressString = "Opening output stream to local file"; progressUpdated = true; try { final File f = (File) target; final File parent = f.getParentFile(); if ((parent != null) && !parent.exists()) { parent.mkdirs(); } bos = new BufferedOutputStream(new FileOutputStream(f)); } catch (Exception e) { progressString = "Failed to open output stream to local file"; progressUpdated = true; throw e; } } progressString = "Downloading"; progressUpdated = true; try { if (target instanceof File) { final byte[] byteBuffer = new byte[BUFFER_SIZE]; while (true) { checkState(); final int byteCount = bis.read(byteBuffer, 0, BUFFER_SIZE); if (byteCount == -1) { break; } bos.write(byteBuffer, 0, byteCount); synchronized (lengthLock) { downloadedLength += byteCount; } progressUpdated = true; } } else if (target instanceof StringBuilder) { final char[] charBuffer = new char[BUFFER_SIZE]; final StringBuilder sb = (StringBuilder) target; while (true) { checkState(); final int charCount = br.read(charBuffer, 0, BUFFER_SIZE); if (charCount == -1) { break; } sb.append(charBuffer, 0, charCount); synchronized (lengthLock) { downloadedLength += charCount; } progressUpdated = true; } } } catch (Exception e) { progressString = "Failed to download remote resource"; progressUpdated = true; throw e; } progressString = "Download completed"; progressUpdated = true; } catch (Exception e) { error = e; } finally { for (Closeable c : new Closeable[] { bis, br, bos }) { if (c != null) { try { c.close(); } catch (Exception e) { } } } synchronized (stateLock) { running = false; completed = true; } } } Code Sample 2: protected void readLockssConfigFile(URL url, List<String> peers) { PrintWriter out = null; try { out = new PrintWriter(new OutputStreamWriter(System.out, "utf8"), true); out.println("unicode-output-ready"); } catch (UnsupportedEncodingException ex) { System.out.println(ex.toString()); return; } XMLInputFactory xmlif = XMLInputFactory.newInstance(); xmlif.setProperty("javax.xml.stream.isCoalescing", java.lang.Boolean.TRUE); xmlif.setProperty("javax.xml.stream.isNamespaceAware", java.lang.Boolean.TRUE); XMLStreamReader xmlr = null; BufferedInputStream stream = null; long starttime = System.currentTimeMillis(); out.println("Starting to parse the remote config xml[" + url + "]"); int elementCount = 0; int topPropertyCounter = 0; int propertyTagLevel = 0; try { stream = new BufferedInputStream(url.openStream()); xmlr = xmlif.createXMLStreamReader(stream, "utf8"); int eventType = xmlr.getEventType(); String curElement = ""; String targetTagName = "property"; String peerListAttrName = "id.initialV3PeerList"; boolean sentinel = false; boolean valueline = false; while (xmlr.hasNext()) { eventType = xmlr.next(); switch(eventType) { case XMLEvent.START_ELEMENT: curElement = xmlr.getLocalName(); if (curElement.equals("property")) { topPropertyCounter++; propertyTagLevel++; int count = xmlr.getAttributeCount(); if (count > 0) { for (int i = 0; i < count; i++) { if (xmlr.getAttributeValue(i).equals(peerListAttrName)) { sentinel = true; out.println("!!!!!! hit the" + peerListAttrName); out.println("attr=" + xmlr.getAttributeName(i)); out.println("vl=" + xmlr.getAttributeValue(i)); out.println(">>>>>>>>>>>>>> start :property tag (" + topPropertyCounter + ") >>>>>>>>>>>>>>"); out.println(">>>>>>>>>>>>>> property tag level (" + propertyTagLevel + ") >>>>>>>>>>>>>>"); out.print(xmlr.getAttributeName(i).toString()); out.print("="); out.print("\""); out.print(xmlr.getAttributeValue(i)); out.println(""); } } } } if (sentinel && curElement.equals("value")) { valueline = true; String ipAd = xmlr.getElementText(); peers.add(ipAd); } break; case XMLEvent.CHARACTERS: break; case XMLEvent.ATTRIBUTE: if (curElement.equals(targetTagName)) { } break; case XMLEvent.END_ELEMENT: if (xmlr.getLocalName().equals("property")) { if (sentinel) { out.println("========= end of the target property element"); sentinel = false; valueline = false; } elementCount++; propertyTagLevel--; } else { } break; case XMLEvent.END_DOCUMENT: } } } catch (MalformedURLException ue) { } catch (IOException ex) { } catch (XMLStreamException ex) { } finally { if (xmlr != null) { try { xmlr.close(); } catch (XMLStreamException ex) { } } if (stream != null) { try { stream.close(); } catch (IOException ex) { } } } }
11
Code Sample 1: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0L; if (secure) rand = mySecureRand.nextLong(); else rand = myRand.nextLong(); sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte array[] = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; j++) { int b = array[j] & 0xff; if (b < 16) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } Code Sample 2: private String getRandomGUID(final boolean secure) { MessageDigest md5 = null; final StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } try { final long time = System.currentTimeMillis(); final long rand; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(id); sbValueBeforeMD5.append(SEMI_COLON); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(SEMI_COLON); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); final byte[] array = md5.digest(); final StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { final int bufferIndex = array[j] & SHIFT_SPACE; if (ZERO_TEST > bufferIndex) sb.append(CHAR_ZERO); sb.append(Integer.toHexString(bufferIndex)); } return sb.toString(); } catch (Exception e) { throw new RuntimeException(e); } }
00
Code Sample 1: public void copyFile(File in, File out) throws Exception { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } Code Sample 2: public static Object getInputStream(String name, boolean showMsg, URL appletDocumentBase, String appletProxy) { String errorMessage = null; int iurlPrefix; for (iurlPrefix = urlPrefixes.length; --iurlPrefix >= 0; ) if (name.startsWith(urlPrefixes[iurlPrefix])) break; boolean isURL = (iurlPrefix >= 0); boolean isApplet = (appletDocumentBase != null); InputStream in = null; int length; try { if (isApplet || isURL) { if (isApplet && isURL && appletProxy != null) name = appletProxy + "?url=" + URLEncoder.encode(name, "utf-8"); URL url = (isApplet ? new URL(appletDocumentBase, name) : new URL(name)); name = url.toString(); if (showMsg) Logger.info("FileManager opening " + url.toString()); URLConnection conn = url.openConnection(); length = conn.getContentLength(); in = conn.getInputStream(); } else { if (showMsg) Logger.info("FileManager opening " + name); File file = new File(name); length = (int) file.length(); in = new FileInputStream(file); } return new MonitorInputStream(in, length); } catch (Exception e) { try { if (in != null) in.close(); } catch (IOException e1) { } errorMessage = "" + e; } return errorMessage; }
00
Code Sample 1: public void actionPerformed(ActionEvent e) { if (path.compareTo("") != 0) { imageName = (path.substring(path.lastIndexOf(File.separator) + 1, path.length())); String name = imageName.substring(0, imageName.lastIndexOf('.')); String extension = imageName.substring(imageName.lastIndexOf('.') + 1, imageName.length()); File imageFile = new File(path); directoryPath = "images" + File.separator + imageName.substring(0, 1).toUpperCase(); File directory = new File(directoryPath); directory.mkdirs(); imagePath = "." + File.separator + "images" + File.separator + imageName.substring(0, 1).toUpperCase() + File.separator + imageName; File newFile = new File(imagePath); if (myImagesBehaviour.equals(TLanguage.getString("TIGManageGalleryDialog.REPLACE_IMAGE"))) { Vector<Vector<String>> aux = TIGDataBase.imageSearchByName(name); if (aux.size() != 0) { int idImage = TIGDataBase.imageKeySearchName(name); TIGDataBase.deleteAsociatedOfImage(idImage); } } if (myImagesBehaviour.equals(TLanguage.getString("TIGManageGalleryDialog.ADD_IMAGE"))) { int i = 1; while (newFile.exists()) { imagePath = "." + File.separator + "images" + File.separator + imageName.substring(0, 1).toUpperCase() + File.separator + imageName.substring(0, imageName.lastIndexOf('.')) + "_" + i + imageName.substring(imageName.lastIndexOf('.'), imageName.length()); name = name + "_" + i; newFile = new File(imagePath); i++; } } imagePathThumb = (imagePath.substring(0, imagePath.lastIndexOf("."))).concat("_th.jpg"); imageName = name + "." + extension; try { FileChannel srcChannel = new FileInputStream(path).getChannel(); FileChannel dstChannel = new FileOutputStream(imagePath).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } TIGDataBase.insertDB(theConcepts, imageName, imageName.substring(0, imageName.lastIndexOf('.'))); image = null; if (imageFile != null) { if (TFileUtils.isJAIRequired(imageFile)) { RenderedOp src = JAI.create("fileload", imageFile.getAbsolutePath()); BufferedImage bufferedImage = src.getAsBufferedImage(); image = new ImageIcon(bufferedImage); } else { image = new ImageIcon(imageFile.getAbsolutePath()); } if (image.getImageLoadStatus() == MediaTracker.ERRORED) { int choosenOption = JOptionPane.NO_OPTION; choosenOption = JOptionPane.showConfirmDialog(null, TLanguage.getString("TIGInsertImageAction.MESSAGE"), TLanguage.getString("TIGInsertImageAction.NAME"), JOptionPane.CLOSED_OPTION, JOptionPane.ERROR_MESSAGE); } else { createThumbnail(); } } } } Code Sample 2: public RSClassLoader(Map<String, byte[]> classes, URL source) { try { CodeSource codeSource = new CodeSource(source, (CodeSigner[]) null); domain = new ProtectionDomain(codeSource, getPermissions()); this.classes = classes; String s = getClass().getResource("RSClassLoader.class").toString(); s = s.replace("bot/RSClassLoader.class", "client/RandomAccessFile.class"); URL url = new URL(s); InputStream is = null; try { ByteArrayOutputStream bos = new ByteArrayOutputStream(5000); is = new BufferedInputStream(url.openStream()); byte[] buff = new byte[1024]; int len = -1; while ((len = is.read(buff)) != -1) bos.write(buff, 0, len); byte[] data = bos.toByteArray(); this.classes.put("org.rsbot.client.RandomAccessFile", data); } catch (IOException e) { e.printStackTrace(); } finally { if (is != null) is.close(); } } catch (final Exception ignored) { } }
00
Code Sample 1: @Test public void testAuthorizedMirror() throws IOException { final URL url = new URL("http://127.0.0.1:" + testPort + "/mirror?version=5&direction=just+right"); final HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestProperty("Authorization", "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="); con.setRequestProperty("WWW-Authenticate", "Basic realm=\"karatasi\""); con.setRequestProperty("testline1", "1234567890"); assertEquals("Expecting resource to exist.", HttpURLConnection.HTTP_OK, con.getResponseCode()); assertEquals("mirror responds with Content-Type text/plain.", "text/plain", con.getContentType()); assertNull("The server does not use any special encoding.", con.getContentEncoding()); int bytesRemaining = con.getContentLength(); final InputStream err = con.getErrorStream(); assertNull("Expecting no error stream.", err); final InputStream in = con.getInputStream(); final byte[] buf = new byte[bytesRemaining]; for (int bytesRead; bytesRemaining > 0 && (bytesRead = in.read(buf, buf.length - bytesRemaining, bytesRemaining)) != -1; bytesRemaining -= bytesRead) { } assertEquals("Expecting server to send not fewer bytes as indicated.", 0, bytesRemaining); final String testResult = new String(buf, "ASCII"); assertContains("Response has to contain this line.", testResult, "url direction::just right\r\n"); assertContains("Response has to contain this line.", testResult, "url version::5\r\n"); assertContains("Response has to contain this line.", testResult, "body authorization::Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==\r\n"); assertContains("Response has to contain this line.", testResult, "body www-authenticate::Basic realm=\"karatasi\"\r\n"); assertContains("Response has to contain this line.", testResult, "body testline1::1234567890\r\n"); } Code Sample 2: protected static void copyFile(File in, File out) throws IOException { java.io.FileWriter filewriter = null; java.io.FileReader filereader = null; try { filewriter = new java.io.FileWriter(out); filereader = new java.io.FileReader(in); char[] buf = new char[4096]; int nread = filereader.read(buf, 0, 4096); while (nread >= 0) { filewriter.write(buf, 0, nread); nread = filereader.read(buf, 0, 4096); } buf = null; } finally { try { filereader.close(); } catch (Throwable t) { } try { filewriter.close(); } catch (Throwable t) { } } }
11
Code Sample 1: private void serializeWithClass(Class theClass, int count, String comment) { for (int c = 0; c < 10; c++) { if (c == 9) { beginAction(1, "persistence write/read", count, comment); } String tempFile = ".tmp.archive"; SerializeClassInterface theInstance = null; try { theInstance = (SerializeClassInterface) theClass.newInstance(); } catch (Exception e) { e.printStackTrace(); } if (theInstance == null) { System.err.println("error: Couldn't initialize class to " + "be serialized!"); return; } reset(); for (int i = 0; i < count; i++) { try { FileOutputStream fout = new FileOutputStream(tempFile); BufferedOutputStream bout = new BufferedOutputStream(fout); ObjectOutputStream oout = new ObjectOutputStream(bout); oout.writeObject(theInstance); oout.flush(); oout.close(); } catch (IOException ioe) { System.err.println("serializing: " + tempFile + ":" + ioe.toString()); } try { FileInputStream fin = new FileInputStream(tempFile); BufferedInputStream bin = new BufferedInputStream(fin); ObjectInputStream oin = new ObjectInputStream(bin); theInstance = (SerializeClassInterface) oin.readObject(); oin.close(); } catch (Exception e) { System.err.println("deserializing: " + tempFile + ":" + e.toString()); break; } proceed(); } reset(); if (c == 9) { endAction(); } } } Code Sample 2: public void objectParserAssesmentItem(int file, int currentquestion, Resource resTemp) { NodeList nl = null; Node n = null; NamedNodeMap nnp = null; Node nsrc = null; URL url = null; String sFilename = ""; String sNewPath = ""; int indexLastSeparator; String sOldPath = ""; try { if (file == 1) { nl = doc.getElementsByTagName("object"); } else { nl = doc_[currentquestion].getElementsByTagName("object"); } for (int i = 0; i < nl.getLength(); i++) { n = nl.item(i); nnp = n.getAttributes(); nsrc = nnp.getNamedItem("data"); String sTemp = nsrc.getTextContent(); url = new URL("file", "localhost", sTemp); sOldPath = url.getFile(); sOldPath = sOldPath.replace('/', File.separatorChar); indexLastSeparator = sOldPath.lastIndexOf(File.separatorChar); String sSourcePath = sOldPath; sFilename = sOldPath.substring(indexLastSeparator + 1); sNewPath = this.sTempLocation + sFilename; FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(sSourcePath).getChannel(); out = new FileOutputStream(sNewPath).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } if (file == 1) { sXml = sXml.replace(nsrc.getTextContent(), sFilename); } else { sXml_[currentquestion] = sXml_[currentquestion].replace(nsrc.getTextContent(), sFilename); } lsImages.add(sFilename); resTemp.addFile(sFilename); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: private static void tryToMerge(String url) { if ("none".equalsIgnoreCase(url)) return; Properties nullProps = new Properties(); FileProperties propsIn = new FileProperties(nullProps, nullProps); try { propsIn.load(new URL(url).openStream()); } catch (Exception e) { } if (propsIn.isEmpty()) return; for (Iterator i = propsIn.entrySet().iterator(); i.hasNext(); ) { Map.Entry e = (Map.Entry) i.next(); String propKey = ((String) e.getKey()).trim(); if (!propKey.startsWith(MERGE_PROP_PREFIX)) continue; String settingName = propKey.substring(MERGE_PROP_PREFIX.length()); if (getVal(settingName) == null) { String settingVal = ((String) e.getValue()).trim(); set(settingName, settingVal); } } } Code Sample 2: public static String stringToHash(String text) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); md.update(text.getBytes("iso-8859-1"), 0, text.length()); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("Should not happened: SHA-1 algorithm is missing."); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Should not happened: Could not encode text bytes '" + text + "' to iso-8859-1."); } return new String(Base64.encodeBase64(md.digest())); }
11
Code Sample 1: public void run() { BufferedReader inp = null; try { String urlString = "http://www.hubtracker.com/query.php?action=add&username=" + user + "&password=" + pass + "&email=" + e_mail + "&address=" + Vars.Hub_Host; URL url = new URL(urlString); URLConnection conn; if (!Vars.Proxy_Host.equals("")) conn = url.openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(Vars.Proxy_Host, Vars.Proxy_Port))); else conn = url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.connect(); inp = new BufferedReader(new InputStreamReader(conn.getInputStream())); String xx; while ((xx = inp.readLine()) != null) PluginMain.result += "\n" + xx; if (curCmd != null) this.curCmd.cur_client.sendFromBot("[hubtracker:] " + PluginMain.result); else PluginMain.curFrame.showMsg(); inp.close(); inp = null; } catch (MalformedURLException ue) { PluginMain.result = ue.toString(); } catch (Exception e) { PluginMain.result = e.toString(); } done = true; } Code Sample 2: String openUrlAsString(String address, int maxLines) { StringBuffer sb; try { URL url = new URL(address); InputStream in = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); sb = new StringBuffer(); int count = 0; String line; while ((line = br.readLine()) != null && count++ < maxLines) sb.append(line + "\n"); in.close(); } catch (IOException e) { sb = null; } return sb != null ? new String(sb) : null; }
00
Code Sample 1: public void updateChecksum() { try { MessageDigest md = MessageDigest.getInstance("SHA"); List<Parameter> sortedKeys = new ArrayList<Parameter>(parameter_instances.keySet()); for (Parameter p : sortedKeys) { if (parameter_instances.get(p) != null && !(parameter_instances.get(p) instanceof OptionalDomain.OPTIONS) && !(parameter_instances.get(p).equals(FlagDomain.FLAGS.OFF))) { md.update(parameter_instances.get(p).toString().getBytes()); } } this.checksum = md.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } Code Sample 2: public static void main(String[] args) { LogFrame.getInstance(); for (int i = 0; i < args.length; i++) { String arg = args[i]; if (arg.trim().startsWith(DEBUG_PARAMETER_NAME + "=")) { properties.put(DEBUG_PARAMETER_NAME, arg.trim().substring(DEBUG_PARAMETER_NAME.length() + 1).trim()); if (properties.getProperty(DEBUG_PARAMETER_NAME).toLowerCase().equals(DEBUG_TRUE)) { DEBUG = true; } } else if (arg.trim().startsWith(AUTOCONNECT_PARAMETER_NAME + "=")) { properties.put(AUTOCONNECT_PARAMETER_NAME, arg.trim().substring(AUTOCONNECT_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(SITE_CONFIG_URL_PARAMETER_NAME + "=")) { properties.put(SITE_CONFIG_URL_PARAMETER_NAME, arg.trim().substring(SITE_CONFIG_URL_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(LOAD_PLUGINS_PARAMETER_NAME + "=")) { properties.put(LOAD_PLUGINS_PARAMETER_NAME, arg.trim().substring(LOAD_PLUGINS_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(DOCSERVICE_URL_PARAMETER_NAME + "=")) { properties.put(DOCSERVICE_URL_PARAMETER_NAME, arg.trim().substring(DOCSERVICE_URL_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(CORPUS_ID_PARAMETER_NAME + "=")) { properties.put(CORPUS_ID_PARAMETER_NAME, arg.trim().substring(CORPUS_ID_PARAMETER_NAME.length() + 1).trim()); } else { System.out.println("WARNING! Unknown or undefined parameter: '" + arg.trim() + "'"); } } System.out.println("Annic GUI startup parameters:"); System.out.println("------------------------------"); for (Object propName : properties.keySet()) { System.out.println(propName.toString() + "=" + properties.getProperty((String) propName)); } System.out.println("------------------------------"); if (properties.getProperty(SITE_CONFIG_URL_PARAMETER_NAME) == null || properties.getProperty(SITE_CONFIG_URL_PARAMETER_NAME).length() == 0) { String err = "Mandatory parameter '" + SITE_CONFIG_URL_PARAMETER_NAME + "' is missing.\n\nApplication will exit."; System.out.println(err); JOptionPane.showMessageDialog(new JFrame(), err, "Error!", JOptionPane.ERROR_MESSAGE); System.exit(-1); } try { String context = System.getProperty(CONTEXT); if (context == null || "".equals(context)) { context = DEFAULT_CONTEXT; } String s = System.getProperty(GateConstants.GATE_HOME_PROPERTY_NAME); if (s == null || s.length() == 0) { File f = File.createTempFile("foo", ""); String gateHome = f.getParent().toString() + context; f.delete(); System.setProperty(GateConstants.GATE_HOME_PROPERTY_NAME, gateHome); f = new File(System.getProperty(GateConstants.GATE_HOME_PROPERTY_NAME)); if (!f.exists()) { f.mkdirs(); } } s = System.getProperty(GateConstants.PLUGINS_HOME_PROPERTY_NAME); if (s == null || s.length() == 0) { System.setProperty(GateConstants.PLUGINS_HOME_PROPERTY_NAME, System.getProperty(GateConstants.GATE_HOME_PROPERTY_NAME) + "/plugins"); File f = new File(System.getProperty(GateConstants.PLUGINS_HOME_PROPERTY_NAME)); if (!f.exists()) { f.mkdirs(); } } s = System.getProperty(GateConstants.GATE_SITE_CONFIG_PROPERTY_NAME); if (s == null || s.length() == 0) { System.setProperty(GateConstants.GATE_SITE_CONFIG_PROPERTY_NAME, System.getProperty(GateConstants.GATE_HOME_PROPERTY_NAME) + "/gate.xml"); } if (properties.getProperty(SITE_CONFIG_URL_PARAMETER_NAME) != null && properties.getProperty(SITE_CONFIG_URL_PARAMETER_NAME).length() > 0) { File f = new File(System.getProperty(GateConstants.GATE_SITE_CONFIG_PROPERTY_NAME)); if (f.exists()) { f.delete(); } f.getParentFile().mkdirs(); f.createNewFile(); URL url = new URL(properties.getProperty(SITE_CONFIG_URL_PARAMETER_NAME)); InputStream is = url.openStream(); FileOutputStream fos = new FileOutputStream(f); int i = is.read(); while (i != -1) { fos.write(i); i = is.read(); } fos.close(); is.close(); } try { Gate.init(); gate.Main.applyUserPreferences(); } catch (Exception e) { e.printStackTrace(); } s = BASE_PLUGIN_NAME + "," + properties.getProperty(LOAD_PLUGINS_PARAMETER_NAME); System.out.println("Loading plugins: " + s); loadPlugins(s, true); } catch (Throwable e) { e.printStackTrace(); } MainFrame.getInstance().setVisible(true); MainFrame.getInstance().pack(); if (properties.getProperty(AUTOCONNECT_PARAMETER_NAME, "").toLowerCase().equals(AUTOCONNECT_TRUE)) { if (properties.getProperty(CORPUS_ID_PARAMETER_NAME) == null || properties.getProperty(CORPUS_ID_PARAMETER_NAME).length() == 0) { String err = "Can't autoconnect. A parameter '" + CORPUS_ID_PARAMETER_NAME + "' is missing."; System.out.println(err); JOptionPane.showMessageDialog(MainFrame.getInstance(), err, "Error!", JOptionPane.ERROR_MESSAGE); ActionShowAnnicConnectDialog.getInstance().actionPerformed(null); } else { ActionConnectToAnnicGUI.getInstance().actionPerformed(null); } } else { ActionShowAnnicConnectDialog.getInstance().actionPerformed(null); } }
11
Code Sample 1: public void run() { FileInputStream src; try { src = new FileInputStream(srcName); } catch (FileNotFoundException e) { e.printStackTrace(); return; } FileOutputStream dest; FileChannel srcC = src.getChannel(); ByteBuffer buf = ByteBuffer.allocateDirect(BUFFER_SIZE); try { int i = 1; int fileNo = 0; long maxByte = this.maxSize << 10; long nbByte = srcC.size(); long nbFile = (nbByte / maxByte) + 1; for (fileNo = 0; fileNo < nbFile; fileNo++) { long fileByte = 0; String destName = srcName + "_" + fileNo; dest = new FileOutputStream(destName); FileChannel destC = dest.getChannel(); while ((i > 0) && fileByte < maxByte) { i = srcC.read(buf); buf.flip(); fileByte += i; destC.write(buf); buf.compact(); } destC.close(); dest.close(); } } catch (IOException e1) { e1.printStackTrace(); return; } } Code Sample 2: public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); }
00
Code Sample 1: public static String getImportFileBody(String fileName, HttpSession session) { FTPClient ftp = new FTPClient(); CofaxToolsUser user = (CofaxToolsUser) session.getAttribute("user"); String fileTransferFolder = CofaxToolsServlet.fileTransferFolder; String importFTPServer = (String) user.workingPubConfigElementsHash.get("IMPORTFTPSERVER"); String importFTPLogin = (String) user.workingPubConfigElementsHash.get("IMPORTFTPLOGIN"); String importFTPPassword = (String) user.workingPubConfigElementsHash.get("IMPORTFTPPASSWORD"); String importFTPFilePath = (String) user.workingPubConfigElementsHash.get("IMPORTFTPFILEPATH"); String body = (""); try { int reply; ftp.connect(importFTPServer); CofaxToolsUtil.log("CofaxToolsFTP getImportFileBody connecting to server " + importFTPServer); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return ("CofaxToolsFTP getImportFileBody ERROR: FTP server refused connection."); } else { ftp.login(importFTPLogin, importFTPPassword); } try { boolean change = ftp.changeWorkingDirectory(importFTPFilePath); CofaxToolsUtil.log("CofaxToolsFTP getImportFileBody changing to directory: " + importFTPFilePath); CofaxToolsUtil.log("Results: " + change); OutputStream output; output = new FileOutputStream(fileTransferFolder + fileName); boolean retrieve = ftp.retrieveFile(fileName, output); CofaxToolsUtil.log("CofaxToolsFTP getImportFileBody retrieving file: " + fileName); CofaxToolsUtil.log("CofaxToolsFTP getImportFileBody results: " + change); output.close(); body = CofaxToolsUtil.readFile(fileTransferFolder + fileName, true); CofaxToolsUtil.log("CofaxToolsFTP getImportFileBody deleting remote file: " + importFTPFilePath + fileName); boolean delete = ftp.deleteFile(importFTPFilePath + fileName); CofaxToolsUtil.log("CofaxToolsFTP getImportFileBody results: " + delete); CofaxToolsUtil.log("CofaxToolsFTP getImportFileBody disconnecting from server:" + importFTPServer); ftp.logout(); ftp.disconnect(); } catch (java.io.IOException e) { return ("CofaxToolsFTP getImportFileBody ERROR: cannot write file: " + fileName); } } catch (IOException e) { return ("CofaxToolsFTP getImportFileBody ERROR: could not connect to server: " + e); } return (body); } Code Sample 2: public AudioInputStream getAudioInputStream(URL url) throws UnsupportedAudioFileException, IOException { InputStream urlStream = url.openStream(); AudioFileFormat fileFormat = null; try { fileFormat = getFMT(urlStream, false); } finally { if (fileFormat == null) { urlStream.close(); } } return new AudioInputStream(urlStream, fileFormat.getFormat(), fileFormat.getFrameLength()); }
00
Code Sample 1: private String generateHash(String key, String data) throws ChiropteraException { try { MessageDigest md = MessageDigest.getInstance(Constants.Connection.Auth.MD5); md.update(key.getBytes()); byte[] raw = md.digest(); String s = toHexString(raw); SecretKey skey = new SecretKeySpec(s.getBytes(), Constants.Connection.Auth.HMACMD5); Mac mac = Mac.getInstance(skey.getAlgorithm()); mac.init(skey); byte digest[] = mac.doFinal(data.getBytes()); String digestB64 = BaculaBase64.binToBase64(digest); return digestB64.substring(0, digestB64.length()); } catch (NoSuchAlgorithmException e) { throw new ChiropteraException(Constants.Chiroptera.Errors.HASH, e.getMessage(), e); } catch (InvalidKeyException e) { throw new ChiropteraException(Constants.Chiroptera.Errors.HASH, e.getMessage(), e); } } Code Sample 2: public static void copy(String inputFile, String outputFile) throws Exception { try { 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) { throw new Exception("Could not copy " + inputFile + " into " + outputFile + " because:\n" + e.getMessage()); } }
00
Code Sample 1: private void bubbleSort(int values[]) { int len = values.length - 1; for (int i = 0; i < len; i++) { for (int j = 0; j < len - i; j++) { if (values[j] > values[j + 1]) { int tmp = values[j]; values[j] = values[j + 1]; values[j + 1] = tmp; } } } } Code Sample 2: public static void saveURL(URL url, Writer writer) throws IOException { BufferedInputStream in = new BufferedInputStream(url.openStream()); for (int c = in.read(); c != -1; c = in.read()) { writer.write(c); } }
11
Code Sample 1: public static String sendRequest(String urlstring) { URL url; String line; Log.i("DVBMonitor", "Please wait while receiving data from dvb..."); try { url = new URL(urlstring); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); if ((line = in.readLine()) != null) { return line; } else { return null; } } catch (Exception ex) { Log.e("DVBMonitor", ex.toString() + " while sending request to dvb"); return null; } } Code Sample 2: @SuppressWarnings("unchecked") public static <T extends Class> Collection<T> listServices(T serviceType, ClassLoader classLoader) throws IOException, ClassNotFoundException { final Collection<T> result = new LinkedHashSet<T>(); final Enumeration<URL> resouces = classLoader.getResources("META-INF/services/" + serviceType.getName()); while (resouces.hasMoreElements()) { final URL url = resouces.nextElement(); final BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); try { String line = reader.readLine(); while (line != null) { if (line.startsWith("#")) { } else if ("".equals(line.trim())) { } else { final T implClass = (T) Class.forName(line, true, classLoader); if (!serviceType.isAssignableFrom(implClass)) { throw new IllegalStateException(String.format("%s: class %s does not implement required interfafce %s", url, implClass, serviceType)); } result.add(implClass); } line = reader.readLine(); } } finally { reader.close(); } } return result; }
00
Code Sample 1: public static void upload(FTPDetails ftpDetails) { FTPClient ftp = new FTPClient(); try { String host = ftpDetails.getHost(); logger.info("Connecting to ftp host: " + host); ftp.connect(host); logger.info("Received reply from ftp :" + ftp.getReplyString()); ftp.login(ftpDetails.getUserName(), ftpDetails.getPassword()); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.makeDirectory(ftpDetails.getRemoterDirectory()); logger.info("Created directory :" + ftpDetails.getRemoterDirectory()); ftp.changeWorkingDirectory(ftpDetails.getRemoterDirectory()); BufferedInputStream ftpInput = new BufferedInputStream(new FileInputStream(new File(ftpDetails.getLocalFilePath()))); OutputStream storeFileStream = ftp.storeFileStream(ftpDetails.getRemoteFileName()); IOUtils.copy(ftpInput, storeFileStream); logger.info("Copied file : " + ftpDetails.getLocalFilePath() + " >>> " + host + ":/" + ftpDetails.getRemoterDirectory() + "/" + ftpDetails.getRemoteFileName()); ftpInput.close(); storeFileStream.close(); ftp.logout(); ftp.disconnect(); logger.info("Logged out. "); } catch (Exception e) { throw new RuntimeException(e); } } Code Sample 2: public static String md5(String password) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); return hash.toString(16); } catch (NoSuchAlgorithmException ex) { return password; } }
00
Code Sample 1: public Download(URL url, int segs) { this.url = url; Mediator.register(this); status = "Starting..."; try { totalSize = url.openConnection().getContentLength(); name = url.getPath().substring(url.getPath().lastIndexOf('/') + 1); if (name.isEmpty()) { name = "UNKNOWN"; } tempFolder = new File(Configuration.PARTS_FOLDER, getName()); tempFolder.mkdir(); } catch (IOException ex) { Logger.post(Logger.Level.WARNING, "URL could not be opened: " + url); } dest = new File(System.getProperty("user.home") + File.separator + name); if (segs > totalSize) { segs = totalSize; } Properties props = new Properties(); props.setProperty("url", getUrl().toString()); props.setProperty("segments", String.valueOf(segs)); try { props.storeToXML(new FileOutputStream(new File(getTempFolder(), "index.xml")), "Warning: Editing this file may compromise the integrity of the download"); } catch (IOException ex) { ex.printStackTrace(); } segments = new Segment[segs]; for (int i = 0; i < segs; i++) { segments[i] = new Segment(this, i); } Thread thread = new Thread(this); thread.setDaemon(true); thread.start(); status = "Downloading..."; Mediator.post(new DownloadStatusChanged(this)); Logger.post(Logger.Level.INFO, "Starting download: " + getName()); } Code Sample 2: public Document searchRelease(String id) throws Exception { Document doc = null; URL url = new URL("http://" + disgogsUrl + "/release/" + id + "?f=xml&api_key=" + apiKey[0]); HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.addRequestProperty("Accept-Encoding", "gzip"); BufferedReader ir = null; if (uc.getInputStream() != null) { ir = new BufferedReader(new InputStreamReader(new GZIPInputStream(uc.getInputStream()), "ISO8859_1")); SAXBuilder builder = new SAXBuilder(); doc = builder.build(ir); } return doc; }
11
Code Sample 1: protected static List<Pattern> getBotPatterns() { List<Pattern> patterns = new ArrayList<Pattern>(); try { Enumeration<URL> urls = AbstractPustefixRequestHandler.class.getClassLoader().getResources("META-INF/org/pustefixframework/http/bot-user-agents.txt"); while (urls.hasMoreElements()) { URL url = urls.nextElement(); InputStream in = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf8")); String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (!line.startsWith("#")) { Pattern pattern = Pattern.compile(line); patterns.add(pattern); } } in.close(); } } catch (IOException e) { throw new RuntimeException("Error reading bot user-agent configuration", e); } return patterns; } Code Sample 2: public static String upload(File tmpFile, URL url) throws IOException { StringBuffer reply = new StringBuffer(); URLConnection uc = url.openConnection(); ClientHttpRequest request = new ClientHttpRequest(uc); String file = "file"; String filename = tmpFile.getName(); InputStream fileinput = new FileInputStream(tmpFile); request.setParameter(file, filename, fileinput); InputStream serverInput = request.post(); BufferedReader in = new BufferedReader(new InputStreamReader(serverInput)); String line = in.readLine(); while (line != null) { reply.append(line + "\n"); line = in.readLine(); } in.close(); return reply.toString(); }
11
Code Sample 1: public static synchronized String encrypt(String plaintext) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = null; md = MessageDigest.getInstance("SHA"); md.update(plaintext.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } Code Sample 2: public static String md(String passwd) { MessageDigest md5 = null; String digest = passwd; try { md5 = MessageDigest.getInstance("MD5"); md5.update(passwd.getBytes()); byte[] digestData = md5.digest(); digest = byteArrayToHex(digestData); } catch (NoSuchAlgorithmException e) { LOG.warn("MD5 not supported. Using plain string as password!"); } catch (Exception e) { LOG.warn("Digest creation failed. Using plain string as password!"); } return digest; }
11
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: public File copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); copyChannel(inChannel, outChannel); return out; }
11
Code Sample 1: public void elimina(Pedido pe) throws errorSQL, errorConexionBD { System.out.println("GestorPedido.elimina()"); int id = pe.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM pedido WHERE id=" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorPedido.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorPedido.elimina(): " + e); } } Code Sample 2: public void insertProfile() throws ClassNotFoundException, SQLException { Connection connection = null; PreparedStatement ps1 = null; PreparedStatement ps2 = null; PreparedStatement ps3 = null; try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection(this.url); connection.setAutoCommit(false); String query1 = "INSERT INTO customers(name,password) VALUES(?,?)"; ps1 = connection.prepareStatement(query1); ps1.setString(1, this.name); ps1.setString(2, this.password); String query2 = "INSERT INTO customer_roles(name,role_name) VALUES(?,?)"; ps2 = connection.prepareStatement(query2); ps2.setString(1, this.name); ps2.setString(2, "user"); String query3 = "INSERT INTO customers_profile(name,first_name,middle_name,last_name,address1,address2,city,post_box,email,country)" + "VALUES(?,?,?,?,?,?,?,?,?,?)"; ps3 = connection.prepareStatement(query3); ps3.setString(1, this.name); ps3.setString(2, this.firstName); ps3.setString(3, this.middleName); ps3.setString(4, this.lastName); ps3.setString(5, this.address1); ps3.setString(6, this.address2); ps3.setString(7, this.city); ps3.setString(8, this.postBox); ps3.setString(9, this.email); ps3.setString(10, this.country); ps1.executeUpdate(); ps2.executeUpdate(); ps3.executeUpdate(); connection.commit(); } catch (Exception ex) { connection.rollback(); } finally { try { this.connection.close(); } catch (Exception ex) { } try { ps1.close(); } catch (Exception ex) { } try { ps2.close(); } catch (Exception ex) { } try { ps3.close(); } catch (Exception ex) { } } }
11
Code Sample 1: protected void copyFile(File from, File to) throws IOException { to.getParentFile().mkdirs(); InputStream in = new FileInputStream(from); try { OutputStream out = new FileOutputStream(to); try { byte[] buf = new byte[1024]; int readLength; while ((readLength = in.read(buf)) > 0) { out.write(buf, 0, readLength); } } finally { out.close(); } } finally { in.close(); } } Code Sample 2: public static void copyFile(File src, File dst) throws IOException { LogUtil.d(TAG, "Copying file %s to %s", src, dst); FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(src).getChannel(); outChannel = new FileOutputStream(dst).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } finally { closeSafe(inChannel); closeSafe(outChannel); } }
11
Code Sample 1: public static void unzipModel(String filename, String tempdir) throws Exception { try { BufferedOutputStream dest = null; FileInputStream fis = new FileInputStream(filename); int BUFFER = 2048; ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis)); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { int count; byte data[] = new byte[BUFFER]; FileOutputStream fos = new FileOutputStream(tempdir + entry.getName()); dest = new BufferedOutputStream(fos, BUFFER); while ((count = zis.read(data, 0, BUFFER)) != -1) dest.write(data, 0, count); dest.flush(); dest.close(); } zis.close(); } catch (Exception e) { e.printStackTrace(); throw new Exception("Can not expand model in \"" + tempdir + "\" because:\n" + e.getMessage()); } } Code Sample 2: public void testCreateNewXMLFile() throws InvalidNodeTypeDefException, ParseException, Exception { JCRNodeSource emptySource = loadTestSource(); assertEquals(false, emptySource.exists()); OutputStream sourceOut = emptySource.getOutputStream(); assertNotNull(sourceOut); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } InputStream expected = getClass().getResourceAsStream(CONTENT_FILE); JCRNodeSource persistentSource = loadTestSource(); assertEquals(true, persistentSource.exists()); InputStream actual = persistentSource.getInputStream(); try { assertTrue(isXmlEqual(expected, actual)); } finally { expected.close(); actual.close(); } JCRNodeSource tmpSrc = (JCRNodeSource) resolveSource(BASE_URL + "users/alexander.saar"); persistentSource.delete(); tmpSrc.delete(); }
11
Code Sample 1: protected int sendData(String submitName, String submitValue) throws HttpException, IOException, SAXException { PostMethod postMethod = null; try { postMethod = new PostMethod(getDocumentBase().toString()); postMethod.getParams().setCookiePolicy(org.apache.commons.httpclient.cookie.CookiePolicy.IGNORE_COOKIES); postMethod.addRequestHeader("Cookie", getWikiPrefix() + "_session=" + getSession() + "; " + getWikiPrefix() + "UserID=" + getUserId() + "; " + getWikiPrefix() + "UserName=" + getUserName() + "; "); List<Part> parts = new ArrayList<Part>(); for (String s : new String[] { "wpSection", "wpEdittime", "wpScrolltop", "wpStarttime", "wpEditToken" }) { parts.add(new StringPart(s, StringEscapeUtils.unescapeJava(getNonNullParameter(s)))); } parts.add(new StringPart("action", "edit")); parts.add(new StringPart("wpTextbox1", getArticleContent())); parts.add(new StringPart("wpSummary", getSummary())); parts.add(new StringPart("wpAutoSummary", Digest.MD5.isImplemented() ? Digest.MD5.encrypt(getSummary()) : "")); parts.add(new StringPart(submitName, submitValue)); MultipartRequestEntity requestEntity = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), postMethod.getParams()); postMethod.setRequestEntity(requestEntity); int status = getHttpClient().executeMethod(postMethod); IOUtils.copyTo(postMethod.getResponseBodyAsStream(), System.err); return status; } catch (HttpException err) { throw err; } catch (IOException err) { throw err; } finally { if (postMethod != null) postMethod.releaseConnection(); } } Code Sample 2: public Reader transform(Reader reader, Map<String, Object> parameterMap) { try { File file = File.createTempFile("srx2", ".srx"); file.deleteOnExit(); Writer writer = getWriter(getFileOutputStream(file.getAbsolutePath())); transform(reader, writer, parameterMap); writer.close(); Reader resultReader = getReader(getFileInputStream(file.getAbsolutePath())); return resultReader; } catch (IOException e) { throw new IORuntimeException(e); } }
00
Code Sample 1: public static void loadPackage1(String ycCode) { InputStream input = null; try { TrustManager[] trustAllCerts = new TrustManager[] { new FakeTrustManager() }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); URL url = Retriever.getPackage1Url(String.valueOf(YouthClub.getMiniModel().getBasics().getTeamId()), ycCode); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection uc = (HttpsURLConnection) url.openConnection(); uc.setHostnameVerifier(new FakeHostnameVerifier()); uc.setConnectTimeout(CONNECTION_TIMEOUT); uc.setReadTimeout(CONNECTION_TIMEOUT); input = uc.getInputStream(); StringBuilder sb = new StringBuilder(); int c; while ((c = input.read()) != -1) { sb.append((char) c); } Document doc = YouthClub.getMiniModel().getXMLParser().parseString(sb.toString()); String target = System.getProperty("user.home") + System.getProperty("file.separator") + "youthclub_" + new SimpleDateFormat("yyyyMMdd_HHmm").format(new Date()) + ".xml"; YouthClub.getMiniModel().getXMLParser().writeXML(doc, target); Debug.log("YC XML saved to " + target); } catch (Exception e) { Debug.logException(e); } finally { if (input != null) { try { input.close(); } catch (IOException e) { } } } } Code Sample 2: public boolean excuteBackup(String backupOrginlDrctry, String targetFileNm, String archiveFormat) throws JobExecutionException { File targetFile = new File(targetFileNm); File srcFile = new File(backupOrginlDrctry); if (!srcFile.exists()) { log.error("백업원본디렉토리[" + srcFile.getAbsolutePath() + "]가 존재하지 않습니다."); throw new JobExecutionException("백업원본디렉토리[" + srcFile.getAbsolutePath() + "]가 존재하지 않습니다."); } if (srcFile.isFile()) { log.error("백업원본디렉토리[" + srcFile.getAbsolutePath() + "]가 파일입니다. 디렉토리명을 지정해야 합니다. "); throw new JobExecutionException("백업원본디렉토리[" + srcFile.getAbsolutePath() + "]가 파일입니다. 디렉토리명을 지정해야 합니다. "); } boolean result = false; FileInputStream finput = null; FileOutputStream fosOutput = null; ArchiveOutputStream aosOutput = null; ArchiveEntry entry = null; try { log.debug("charter set : " + Charset.defaultCharset().name()); fosOutput = new FileOutputStream(targetFile); aosOutput = new ArchiveStreamFactory().createArchiveOutputStream(archiveFormat, fosOutput); if (ArchiveStreamFactory.TAR.equals(archiveFormat)) { ((TarArchiveOutputStream) aosOutput).setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); } File[] fileArr = srcFile.listFiles(); ArrayList list = EgovFileTool.getSubFilesByAll(fileArr); for (int i = 0; i < list.size(); i++) { File sfile = new File((String) list.get(i)); finput = new FileInputStream(sfile); if (ArchiveStreamFactory.TAR.equals(archiveFormat)) { entry = new TarArchiveEntry(sfile, new String(sfile.getAbsolutePath().getBytes(Charset.defaultCharset().name()), "8859_1")); ((TarArchiveEntry) entry).setSize(sfile.length()); } else { entry = new ZipArchiveEntry(sfile.getAbsolutePath()); ((ZipArchiveEntry) entry).setSize(sfile.length()); } aosOutput.putArchiveEntry(entry); IOUtils.copy(finput, aosOutput); aosOutput.closeArchiveEntry(); finput.close(); result = true; } aosOutput.close(); } catch (Exception e) { log.error("백업화일생성중 에러가 발생했습니다. 에러 : " + e.getMessage()); log.debug(e); result = false; throw new JobExecutionException("백업화일생성중 에러가 발생했습니다.", e); } finally { try { if (finput != null) finput.close(); } catch (Exception e2) { log.error("IGNORE:", e2); } try { if (aosOutput != null) aosOutput.close(); } catch (Exception e2) { log.error("IGNORE:", e2); } try { if (fosOutput != null) fosOutput.close(); } catch (Exception e2) { log.error("IGNORE:", e2); } try { if (result == false) targetFile.delete(); } catch (Exception e2) { log.error("IGNORE:", e2); } } return result; }
11
Code Sample 1: public static Hashtable DefaultLoginValues(String firstName, String lastName, String password, String mac, String startLocation, int major, int minor, int patch, int build, String platform, String viewerDigest, String userAgent, String author) throws Exception { Hashtable values = new Hashtable(); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes("ASCII"), 0, password.length()); byte[] raw_digest = md5.digest(); String passwordDigest = Helpers.toHexText(raw_digest); values.put("first", firstName); values.put("last", lastName); values.put("passwd", "" + password); values.put("start", startLocation); values.put("major", major); values.put("minor", minor); values.put("patch", patch); values.put("build", build); values.put("platform", platform); values.put("mac", mac); values.put("agree_to_tos", "true"); values.put("viewer_digest", viewerDigest); values.put("user-agent", userAgent + " (" + Helpers.VERSION + ")"); values.put("author", author); Vector optionsArray = new Vector(); optionsArray.addElement("inventory-root"); optionsArray.addElement("inventory-skeleton"); optionsArray.addElement("inventory-lib-root"); optionsArray.addElement("inventory-lib-owner"); optionsArray.addElement("inventory-skel-lib"); optionsArray.addElement("initial-outfit"); optionsArray.addElement("gestures"); optionsArray.addElement("event_categories"); optionsArray.addElement("event_notifications"); optionsArray.addElement("classified_categories"); optionsArray.addElement("buddy-list"); optionsArray.addElement("ui-config"); optionsArray.addElement("login-flags"); optionsArray.addElement("global-textures"); values.put("options", optionsArray); return values; } Code Sample 2: public synchronized String encrypt(String password) { try { MessageDigest md = null; md = MessageDigest.getInstance("SHA-1"); md.update(password.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } catch (NoSuchAlgorithmException e) { System.out.println("Algorithm SHA-1 is not supported"); return null; } catch (UnsupportedEncodingException e) { System.out.println("UTF-8 encoding is not supported"); return null; } }
00
Code Sample 1: public synchronized void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { CacheEntry entry = null; Tenant tenant = null; if (!tenantInfo.getTenants().isEmpty()) { tenant = tenantInfo.getMatchingTenant(request); if (tenant == null) { tenant = tenantInfo.getTenants().get(0); } entry = tenantToCacheEntry.get(tenant.getName()); } else { entry = cacheEntry; } if (entry == null) { File tempDir = (File) servletContext.getAttribute("javax.servlet.context.tempdir"); tempDir = new File(tempDir, "pustefix-sitemap-cache"); if (!tempDir.exists()) { tempDir.mkdirs(); } entry = new CacheEntry(); entry.file = new File(tempDir, "sitemap" + (tenant == null ? "" : "-" + tenant.getName()) + ".xml"); try { String host = AbstractPustefixRequestHandler.getServerName(request); Document doc = getSearchEngineSitemap(tenant, host); Transformer trf = TransformerFactory.newInstance().newTransformer(); trf.setOutputProperty(OutputKeys.INDENT, "yes"); FileOutputStream out = new FileOutputStream(entry.file); MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException x) { throw new RuntimeException("Can't create message digest", x); } DigestOutputStream digestOutput = new DigestOutputStream(out, digest); trf.transform(new DOMSource(doc), new StreamResult(digestOutput)); digestOutput.close(); byte[] digestBytes = digest.digest(); entry.etag = MD5Utils.byteToHex(digestBytes); } catch (Exception x) { throw new ServletException("Error creating sitemap", x); } } String reqETag = request.getHeader("If-None-Match"); if (reqETag != null) { if (entry.etag.equals(reqETag)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.flushBuffer(); return; } } long reqMod = request.getDateHeader("If-Modified-Since"); if (reqMod != -1) { if (entry.file.lastModified() < reqMod + 1000) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.flushBuffer(); return; } } response.setContentType("application/xml"); response.setContentLength((int) entry.file.length()); response.setDateHeader("Last-Modified", entry.file.lastModified()); response.setHeader("ETag", entry.etag); OutputStream out = new BufferedOutputStream(response.getOutputStream()); InputStream in = new FileInputStream(entry.file); int bytes_read; byte[] buffer = new byte[8]; while ((bytes_read = in.read(buffer)) != -1) { out.write(buffer, 0, bytes_read); } out.flush(); in.close(); out.close(); } Code Sample 2: public void login(LoginData loginData) throws ConnectionEstablishException, AccessDeniedException { try { int reply; this.ftpClient.connect(loginData.getFtpServer()); reply = this.ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { this.ftpClient.disconnect(); throw (new ConnectionEstablishException("FTP server refused connection.")); } } catch (IOException e) { if (this.ftpClient.isConnected()) { try { this.ftpClient.disconnect(); } catch (IOException f) { } } e.printStackTrace(); throw (new ConnectionEstablishException("Could not connect to server.", e)); } try { if (!this.ftpClient.login(loginData.getFtpBenutzer(), loginData.getFtpPasswort())) { this.logout(); throw (new AccessDeniedException("Could not login into server.")); } } catch (IOException ioe) { ioe.printStackTrace(); throw (new AccessDeniedException("Could not login into server.", ioe)); } }
11
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 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) { ; } } } }
00
Code Sample 1: protected void downloadJar(URL downloadURL, File jarFile, IProgressListener pl) { BufferedOutputStream out = null; InputStream in = null; URLConnection urlConnection = null; try { urlConnection = downloadURL.openConnection(); out = new BufferedOutputStream(new FileOutputStream(jarFile)); in = urlConnection.getInputStream(); int len = in.available(); Log.log("downloading jar with size: " + urlConnection.getContentLength()); if (len < 1) len = 1024; byte[] buffer = new byte[len]; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } out.close(); in.close(); } catch (Exception e) { } finally { if (out != null) { try { out.close(); } catch (IOException ignore) { } } if (in != null) { try { in.close(); } catch (IOException ignore) { } } } } Code Sample 2: static Object loadPersistentRepresentationFromFile(URL url) throws PersistenceException { PersistenceManager.persistenceURL.get().addFirst(url); ObjectInputStream ois = null; HierarchicalStreamReader reader = null; XStream xstream = null; try { Reader inputReader = new java.io.InputStreamReader(url.openStream()); try { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLStreamReader xsr = inputFactory.createXMLStreamReader(url.toExternalForm(), inputReader); reader = new StaxReader(new QNameMap(), xsr); } catch (XMLStreamException xse) { throw new PersistenceException("Error creating reader", xse); } xstream = new XStream(new StaxDriver()); xstream.setClassLoader(Gate.getClassLoader()); ois = xstream.createObjectInputStream(reader); Object res = null; Iterator urlIter = ((Collection) PersistenceManager.getTransientRepresentation(ois.readObject())).iterator(); while (urlIter.hasNext()) { URL anUrl = (URL) urlIter.next(); try { Gate.getCreoleRegister().registerDirectories(anUrl); } catch (GateException ge) { Err.prln("Could not reload creole directory " + anUrl.toExternalForm()); } } res = ois.readObject(); ois.close(); return res; } catch (PersistenceException pe) { throw pe; } catch (Exception e) { throw new PersistenceException("Error loading GAPP file", e); } finally { PersistenceManager.persistenceURL.get().removeFirst(); if (PersistenceManager.persistenceURL.get().isEmpty()) { PersistenceManager.persistenceURL.remove(); } } }
11
Code Sample 1: public ChatClient registerPlayer(int playerId, String playerLogin) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.reset(); md.update(playerLogin.getBytes("UTF-8"), 0, playerLogin.length()); byte[] accountToken = md.digest(); byte[] token = generateToken(accountToken); ChatClient chatClient = new ChatClient(playerId, token); players.put(playerId, chatClient); return chatClient; } Code Sample 2: protected static byte[] hashPassword(byte[] saltBytes, String plaintextPassword) throws AssertionError { MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { throw (AssertionError) new AssertionError("No MD5 message digest supported.").initCause(ex); } digest.update(saltBytes); try { digest.update(plaintextPassword.getBytes("utf-8")); } catch (UnsupportedEncodingException ex) { throw (AssertionError) new AssertionError("No UTF-8 encoding supported.").initCause(ex); } byte[] passwordBytes = digest.digest(); return passwordBytes; }
11
Code Sample 1: public Logging() throws Exception { File home = new File(System.getProperty("user.home"), ".jorgan"); if (!home.exists()) { home.mkdirs(); } File logging = new File(home, "logging.properties"); if (!logging.exists()) { InputStream input = getClass().getResourceAsStream("logging.properties"); OutputStream output = null; try { output = new FileOutputStream(logging); IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } } FileInputStream input = null; try { input = new FileInputStream(logging); LogManager.getLogManager().readConfiguration(input); } finally { IOUtils.closeQuietly(input); } } Code Sample 2: public static void zipFile(String file, String entry) throws IOException { FileInputStream in = new FileInputStream(file); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file + ".zip")); out.putNextEntry(new ZipEntry(entry)); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read); in.close(); out.closeEntry(); out.close(); File fin = new File(file); fin.delete(); }
11
Code Sample 1: PackageFileImpl(PackageDirectoryImpl dir, String name, InputStream data) throws IOException { this.dir = dir; this.name = name; this.updates = dir.getUpdates(); ByteArrayOutputStream stream = new ByteArrayOutputStream(); IOUtils.copy(data, stream); updates.setNewData(getFullName(), stream.toByteArray()); stream.close(); } Code Sample 2: public ResourceMigrator createDefaultResourceMigrator(NotificationReporter reporter, boolean strictMode) throws ResourceMigrationException { return new ResourceMigrator() { public void migrate(InputMetadata meta, InputStream inputStream, OutputCreator outputCreator) throws IOException, ResourceMigrationException { OutputStream outputStream = outputCreator.createOutputStream(); IOUtils.copy(inputStream, outputStream); } }; }
11
Code Sample 1: protected final void loadLogFile(String filename) throws IOException { cleanUp(true, false); InputStream is = null; OutputStream os = null; File f = File.createTempFile("log", null); try { is = getClass().getResourceAsStream(filename); Assert.isTrue(is != null, "File not found: " + filename); os = new FileOutputStream(f); IOUtils.copy(is, os); setLogFile(f); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } } Code Sample 2: public static void copy(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); } 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) { ; } } }
11
Code Sample 1: public Object next() { if (!hasNext()) { throw new NoSuchElementException(); } this.currentGafFilePath = this.url; try { if (this.httpURL != null) { LOG.info("Reading URL :" + httpURL); InputStream is = this.httpURL.openStream(); int index = this.httpURL.toString().lastIndexOf('/'); String file = this.httpURL.toString().substring(index + 1); File downloadLocation = new File(GoConfigManager.getInstance().getGafUploadDir(), "tmp-" + file); OutputStream out = new FileOutputStream(downloadLocation); IOUtils.copy(is, out); out.close(); is = new FileInputStream(downloadLocation); if (url.endsWith(".gz")) { is = new GZIPInputStream(is); } this.currentGafFile = this.currentGafFilePath.substring(this.currentGafFilePath.lastIndexOf("/") + 1); this.httpURL = null; return is; } else { String file = files[counter++].getName(); this.currentGafFile = file; if (!this.currentGafFilePath.endsWith(file)) currentGafFilePath += file; LOG.info("Returning input stream for the file: " + file); _connect(); ftpClient.changeWorkingDirectory(path); InputStream is = ftpClient.retrieveFileStream(file); File downloadLocation = new File(GoConfigManager.getInstance().getGafUploadDir(), file); OutputStream out = new FileOutputStream(downloadLocation); IOUtils.copy(is, out); out.close(); System.out.println("Download complete....."); is = new FileInputStream(downloadLocation); if (file.endsWith(".gz")) { is = new GZIPInputStream(is); } return is; } } catch (IOException ex) { throw new RuntimeException(ex); } } Code Sample 2: public static void main(String[] a) { ArrayList<String> allFilesToBeCopied = new ArrayList<String>(); new File(outputDir).mkdirs(); try { FileReader fis = new FileReader(completeFileWithDirToCathFileList); BufferedReader bis = new BufferedReader(fis); String line = ""; String currentCombo = ""; while ((line = bis.readLine()) != null) { String[] allEntries = line.split("\\s+"); String fileName = allEntries[0]; String thisCombo = allEntries[1] + allEntries[2] + allEntries[3] + allEntries[4]; if (currentCombo.equals(thisCombo)) { } else { System.out.println("merke: " + fileName); allFilesToBeCopied.add(fileName); currentCombo = thisCombo; } } System.out.println(allFilesToBeCopied.size()); for (String file : allFilesToBeCopied) { try { FileChannel srcChannel = new FileInputStream(CathDir + file).getChannel(); FileChannel dstChannel = new FileOutputStream(outputDir + file).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { e.printStackTrace(); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: public static void copy(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); } 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) { ; } } } Code Sample 2: public static void main(String[] args) throws Exception { String localSrc = args[0]; String dst = args[1]; InputStream in = new BufferedInputStream(new FileInputStream(localSrc)); Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(URI.create(dst), conf); OutputStream out = fs.create(new Path(dst), new Progressable() { public void progress() { System.out.print("."); } }); IOUtils.copyBytes(in, out, 4096, true); }
11
Code Sample 1: public static FileChannel newFileChannel(File file, String rw, boolean enableException) throws IOException { if (file == null) return null; if (rw == null || rw.length() == 0) { return null; } rw = rw.toLowerCase(); if (rw.equals(MODE_READ)) { if (FileUtil.exists(file, enableException)) { FileInputStream fis = new FileInputStream(file); FileChannel ch = fis.getChannel(); setObjectMap(ch.hashCode(), fis, FIS); return ch; } } else if (rw.equals(MODE_WRITE)) { FileOutputStream fos = new FileOutputStream(file); FileChannel ch = fos.getChannel(); setObjectMap(ch.hashCode(), fos, FOS_W); return ch; } else if (rw.equals(MODE_APPEND)) { if (FileUtil.exists(file, enableException)) { RandomAccessFile raf = new RandomAccessFile(file, "rw"); FileChannel ch = raf.getChannel(); ch.position(ch.size()); setObjectMap(ch.hashCode(), raf, FOS_A); return ch; } } else if (rw.equals(MODE_READ_WRITE)) { if (FileUtil.exists(file, enableException)) { RandomAccessFile raf = new RandomAccessFile(file, rw); FileChannel ch = raf.getChannel(); setObjectMap(ch.hashCode(), raf, RAF); return ch; } } else { throw new IllegalArgumentException("Illegal read/write type : [" + rw + "]\n" + "You can use following types for: \n" + " (1) Read Only = \"r\"\n" + " (2) Write Only = \"w\"\n" + " (3) Read/Write = \"rw\"\n" + " (4) Append = \"a\""); } return null; } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: public void writeToFile(File out) throws IOException, DocumentException { FileChannel inChannel = new FileInputStream(pdf_file).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: public Object downloadFile(File destinationFile, URL[] urls, DownloadListener listener, Object checksum, long length, PRIORITY priority) throws DownloadException { URL url = urls[0]; if (!url.getProtocol().equalsIgnoreCase("http")) { throw new DownloadException(" Only HTTP is supported in this version "); } if (!destinationFile.exists()) { try { destinationFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); throw new DownloadException("Unable to download from URL : " + url.toString()); } } HeadMethod head = new HeadMethod(url.toString()); HttpClient httpClient = new HttpClient(); try { httpClient.executeMethod(head); Header[] headers = head.getResponseHeaders(); for (Header header : headers) { System.out.println(header); } Header header = head.getResponseHeader("Content-Length"); Object contentLength = header.getValue(); Long fileLength = Long.parseLong(contentLength.toString()); System.out.println(length + " : " + fileLength); GetMethod get = new GetMethod(url.toString()); httpClient.executeMethod(get); InputStream ins = get.getResponseBodyAsStream(); FileOutputStream fos = new FileOutputStream(destinationFile); IOUtils.copy(ins, fos); System.out.println(" DOWNLOADED FILE"); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
11
Code Sample 1: public static void copyFile(File input, File output) throws Exception { FileReader in = new FileReader(input); FileWriter out = new FileWriter(output); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } 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; }
00
Code Sample 1: private void buildCache() { cache = new HashMap<String, byte[]>(); JarInputStream jis = null; BufferedInputStream bis = null; URL[] urls = getURLs(); for (URL url : urls) { try { if (url.getPath().endsWith(".jar")) { jis = new JarInputStream(url.openStream()); bis = new BufferedInputStream(jis); JarEntry jarEntry = null; while ((jarEntry = jis.getNextJarEntry()) != null) { String name = jarEntry.getName(); if (!jarEntry.isDirectory() && name.toLowerCase().endsWith(".class")) { String className = name.replaceAll("/", ".").substring(0, name.length() - 6); if (isClassLoaderConditonVerified(className)) { ByteArrayOutputStream baos = null; BufferedOutputStream bos = null; try { baos = new ByteArrayOutputStream(); bos = new BufferedOutputStream(baos); int i = -1; while ((i = bis.read()) != -1) { bos.write(i); } bos.flush(); cache.put(className, baos.toByteArray()); } finally { if (baos != null) { try { baos.close(); } catch (IOException ignore) { } } if (bos != null) { try { bos.close(); } catch (IOException ex) { } } } jis.closeEntry(); } } } try { jis.close(); } catch (IOException ignore) { } } else { File file = new File(url.getFile()); buildCacheFromFile(file, null); } } catch (IOException ex) { continue; } } } Code Sample 2: private void duplicateTable(Connection scon, Connection dcon, String table) { logger.debug("Duplicating table " + table); Statement creTab, stmt; ResultSet tuples, columns, keys; int c; String insert = ""; PreparedStatement insTup; try { columns = scon.getMetaData().getColumns(null, null, table, null); keys = scon.getMetaData().getPrimaryKeys(null, null, table); creTab = dcon.createStatement(); creTab.execute(getCreateTableCommand(columns, keys)); stmt = scon.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); stmt.setFetchSize(50); tuples = stmt.executeQuery("SELECT * FROM " + table); c = tuples.getMetaData().getColumnCount(); insert = "INSERT INTO " + table + " VALUES("; for (int j = 1; j <= c; j++) insert += "?,"; insert = insert.substring(0, insert.length() - 1) + ")"; logger.debug("Insert pattern " + insert); insTup = dcon.prepareStatement(insert); while (tuples.next()) { for (int j = 1; j <= c; j++) insTup.setObject(j, tuples.getObject(j)); insTup.executeUpdate(); } dcon.commit(); } catch (Exception e) { logger.error("Unable to copy table " + table + ": " + e); try { dcon.rollback(); } catch (SQLException e1) { logger.fatal(e1); } } }
11
Code Sample 1: public CmsSetupTestResult execute(CmsSetupBean setupBean) { CmsSetupTestResult testResult = new CmsSetupTestResult(this); String basePath = setupBean.getWebAppRfsPath(); if (!basePath.endsWith(File.separator)) { basePath += File.separator; } File file1; Random rnd = new Random(); do { file1 = new File(basePath + "test" + rnd.nextInt(1000)); } while (file1.exists()); boolean success = false; try { file1.createNewFile(); FileWriter fw = new FileWriter(file1); fw.write("aA1"); fw.close(); success = true; FileReader fr = new FileReader(file1); success = success && (fr.read() == 'a'); success = success && (fr.read() == 'A'); success = success && (fr.read() == '1'); success = success && (fr.read() == -1); fr.close(); success = file1.delete(); success = !file1.exists(); } catch (Exception e) { success = false; } if (!success) { testResult.setRed(); testResult.setInfo("OpenCms cannot be installed without read and write privileges for path " + basePath + "! Please check you are running your servlet container with the right user and privileges."); testResult.setHelp("Not enough permissions to create/read/write a file"); testResult.setResult(RESULT_FAILED); } else { testResult.setGreen(); testResult.setResult(RESULT_PASSED); } return testResult; } Code Sample 2: @Override public void close() throws IOException { super.close(); byte[] signatureData = toByteArray(); ZipOutputStream zipOutputStream = new ZipOutputStream(this.targetOutputStream); ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(this.originalZipFile)); ZipEntry zipEntry; while (null != (zipEntry = zipInputStream.getNextEntry())) { if (!zipEntry.getName().equals(ASiCUtil.SIGNATURE_FILE)) { ZipEntry newZipEntry = new ZipEntry(zipEntry.getName()); zipOutputStream.putNextEntry(newZipEntry); LOG.debug("copying " + zipEntry.getName()); IOUtils.copy(zipInputStream, zipOutputStream); } } zipInputStream.close(); zipEntry = new ZipEntry(ASiCUtil.SIGNATURE_FILE); LOG.debug("writing " + zipEntry.getName()); zipOutputStream.putNextEntry(zipEntry); IOUtils.write(signatureData, zipOutputStream); zipOutputStream.close(); }
00
Code Sample 1: protected HttpURLConnection frndTrySend(HttpURLConnection h) throws OAIException { HttpURLConnection http = h; boolean done = false; GregorianCalendar sendTime = new GregorianCalendar(); GregorianCalendar testTime = new GregorianCalendar(); GregorianCalendar retryTime = null; String retryAfter; int retryCount = 0; do { try { http.setRequestProperty("User-Agent", strUserAgent); http.setRequestProperty("From", strFrom); if (strUser != null && strUser.length() > 0) { byte[] encodedPassword = (strUser + ":" + strPassword).getBytes(); BASE64Encoder encoder = new BASE64Encoder(); http.setRequestProperty("Authorization", "Basic " + encoder.encode(encodedPassword)); } sendTime.setTime(new Date()); http.connect(); if (http.getResponseCode() == HttpURLConnection.HTTP_OK) { done = true; } else if (http.getResponseCode() == HttpURLConnection.HTTP_UNAVAILABLE) { retryCount++; if (retryCount > iRetryLimit) { throw new OAIException(OAIException.RETRY_LIMIT_ERR, "The RetryLimit " + iRetryLimit + " has been exceeded"); } else { retryAfter = http.getHeaderField("Retry-After"); if (retryAfter == null) { throw new OAIException(OAIException.RETRY_AFTER_ERR, "No Retry-After header"); } else { try { int sec = Integer.parseInt(retryAfter); sendTime.add(Calendar.SECOND, sec); retryTime = sendTime; } catch (NumberFormatException ne) { try { Date retryDate = DateFormat.getDateInstance().parse(retryAfter); retryTime = new GregorianCalendar(); retryTime.setTime(retryDate); } catch (ParseException pe) { throw new OAIException(OAIException.CRITICAL_ERR, pe.getMessage()); } } if (retryTime != null) { testTime.setTime(new Date()); testTime.add(Calendar.MINUTE, iMaxRetryMinutes); if (retryTime.getTime().before(testTime.getTime())) { try { while (retryTime.getTime().after(new Date())) { Thread.sleep(60000); } URL url = http.getURL(); http.disconnect(); http = (HttpURLConnection) url.openConnection(); } catch (InterruptedException ie) { throw new OAIException(OAIException.CRITICAL_ERR, ie.getMessage()); } } else { throw new OAIException(OAIException.RETRY_AFTER_ERR, "Retry time(" + retryAfter + " sec) is too long"); } } else { throw new OAIException(OAIException.RETRY_AFTER_ERR, retryAfter + "is not a valid Retry-After header"); } } } } else if (http.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN) { throw new OAIException(OAIException.CRITICAL_ERR, http.getResponseMessage()); } else { retryCount++; if (retryCount > iRetryLimit) { throw new OAIException(OAIException.RETRY_LIMIT_ERR, "The RetryLimit " + iRetryLimit + " has been exceeded"); } else { int sec = 10 * ((int) Math.exp(retryCount)); sendTime.add(Calendar.SECOND, sec); retryTime = sendTime; try { while (retryTime.getTime().after(new Date())) { Thread.sleep(sec * 1000); } URL url = http.getURL(); http.disconnect(); http = (HttpURLConnection) url.openConnection(); } catch (InterruptedException ie) { throw new OAIException(OAIException.CRITICAL_ERR, ie.getMessage()); } } } } catch (IOException ie) { throw new OAIException(OAIException.CRITICAL_ERR, ie.getMessage()); } } while (!done); return http; } Code Sample 2: public void sendMessageToServer(String msg, Map<String, String> args, StringCallback cb, URLConstructor ctor) { try { int tmpPort = port; for (; tmpPort < port + 10; tmpPort++) { Socket tmpSock; try { tmpSock = socketsManager.connect(new InetSocketAddress(host, port), 5000); tmpSock.close(); break; } catch (IOException e) { } } Map<String, String> newArgs = new HashMap<String, String>(args); newArgs.put("_f", String.valueOf(System.currentTimeMillis())); String request = ctor.constructURL(msg, newArgs); HttpClient client = new SimpleLimeHttpClient(); HttpGet get = new HttpGet("http://" + host + ":" + port + "/" + request); HttpProtocolParams.setVersion(client.getParams(), HttpVersion.HTTP_1_1); HttpResponse response = client.execute(get); String res = ""; if (response.getEntity() != null) { String result; if (response.getEntity() != null) { result = EntityUtils.toString(response.getEntity()); } else { result = null; } res = result; } cb.process(res); } catch (IOException e) { fail(e); } catch (HttpException e) { fail(e); } catch (URISyntaxException e) { fail(e); } catch (InterruptedException e) { fail(e); } }
11
Code Sample 1: private static byte[] createMD5(String seed) throws UnsupportedEncodingException, NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(seed.getBytes("UTF-8")); return md5.digest(); } Code Sample 2: public static String md5hash(String input) { try { MessageDigest sha1Digest = MessageDigest.getInstance("MD5"); sha1Digest.update(input.getBytes()); return byteArrayToString(sha1Digest.digest()); } catch (Exception e) { logger.error(e.getMessage(), e); } return ""; }
00
Code Sample 1: public static Map<String, File> extractFiles(String input, File tempDirectory) throws IOException { byte data[] = new byte[BUFFER]; BufferedOutputStream out = null; FileInputStream src = new FileInputStream(input); BufferedInputStream in = new BufferedInputStream(src); ZipInputStream zipin = new ZipInputStream(in); Map<String, File> files = new HashMap<String, File>(); ZipEntry entry; while ((entry = zipin.getNextEntry()) != null) { logger.info(TAG + ": entr�e " + entry.getName() + " r�pertoire ? " + entry.isDirectory()); if (entry.isDirectory()) { logger.info(TAG + ": Ajout de l'entr�e pour le r�pertoire: " + entry.getName()); files.put(entry.getName(), extractDirectory(entry.getName(), zipin, tempDirectory)); File f = files.get(entry.getName()); if (f == null) logger.info(TAG + ": NULLL: "); continue; } File tempFile = new File(tempDirectory, entry.getName()); if (tempFile.exists()) tempFile.delete(); tempFile.createNewFile(); FileOutputStream dest = new FileOutputStream(tempFile); out = new BufferedOutputStream(dest, BUFFER); int count; for (int c = zipin.read(); c != -1; c = zipin.read()) dest.write(c); logger.info(TAG + ": Ajout de l'entr�e: " + entry.getName() + " du fichier: " + tempFile.getAbsolutePath()); files.put(entry.getName(), tempFile); out.close(); dest.close(); } zipin.close(); in.close(); src.close(); return files; } Code Sample 2: public void run() { try { HttpPost httpPostRequest = new HttpPost(Feesh.device_URL); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("c", "feed")); nameValuePairs.add(new BasicNameValuePair("amount", String.valueOf(foodAmount))); nameValuePairs.add(new BasicNameValuePair("type", String.valueOf(foodType))); httpPostRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse httpResponse = (HttpResponse) new DefaultHttpClient().execute(httpPostRequest); HttpEntity entity = httpResponse.getEntity(); String resultString = ""; if (entity != null) { InputStream instream = entity.getContent(); resultString = convertStreamToString(instream); instream.close(); } Message msg_toast = new Message(); msg_toast.obj = resultString; toast_handler.sendMessage(msg_toast); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: public String digestResponse() { String digest = null; if (null == nonce) return null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(username.getBytes()); md.update(":".getBytes()); md.update(realm.getBytes()); md.update(":".getBytes()); md.update(password.getBytes()); byte[] d = md.digest(); if (null != algorithm && -1 != (algorithm.toLowerCase()).indexOf("md5-sess")) { md = MessageDigest.getInstance("MD5"); md.update(d); md.update(":".getBytes()); md.update(nonce.getBytes()); md.update(":".getBytes()); md.update(cnonce.getBytes()); d = md.digest(); } byte[] a1 = bytesToHex(d); md = MessageDigest.getInstance("MD5"); md.update(method.getBytes()); md.update(":".getBytes()); md.update(uri.getBytes()); d = md.digest(); byte[] a2 = bytesToHex(d); md = MessageDigest.getInstance("MD5"); md.update(a1); md.update(":".getBytes()); md.update(nonce.getBytes()); md.update(":".getBytes()); if (null != qop) { md.update(nonceCount.getBytes()); md.update(":".getBytes()); md.update(cnonce.getBytes()); md.update(":".getBytes()); md.update(qop.getBytes()); md.update(":".getBytes()); } md.update(a2); d = md.digest(); byte[] r = bytesToHex(d); digest = new String(r); } catch (Exception e) { e.printStackTrace(); } return digest; } Code Sample 2: public Scene load(URL url) throws FileNotFoundException, IncorrectFormatException, ParsingErrorException { BufferedReader reader; if (baseUrl == null) setBaseUrlFromUrl(url); try { reader = new BufferedReader(new InputStreamReader(url.openStream())); } catch (IOException e) { throw new FileNotFoundException(e.getMessage()); } fromUrl = true; return load(reader); }
00
Code Sample 1: private String determineGuardedHtml() { StringBuffer buf = new StringBuffer(); if (m_guardedButtonPresent) { buf.append("\n<span id='" + getHtmlIdPrefix() + PUSH_PAGE_SUFFIX + "' style='display:none'>\n"); String location = m_guardedHtmlLocation != null ? m_guardedHtmlLocation : (String) Config.getProperty(Config.PROP_PRESENTATION_DEFAULT_GUARDED_HTML_LOCATION); String html = (String) c_guardedHtmlCache.get(location); if (html == null) { if (log.isDebugEnabled()) log.debug(this.NAME + ".determineGuardedHtml: Reading the Guarded Html Fragment: " + location); URL url = getUrl(location); if (url != null) { BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buf1 = new StringBuffer(); String line = null; while ((line = in.readLine()) != null) { buf1.append(line); buf1.append('\n'); } html = buf1.toString(); } catch (IOException e) { log.warn(this.NAME + ".determineGuardedHtml: Failed to read the Guarded Html Fragment: " + location, e); } finally { try { if (in != null) in.close(); } catch (IOException ex) { log.warn(this.NAME + ".determineGuardedHtml: Failed to close the Guarded Html Fragment: " + location, ex); } } } else { log.warn("Failed to read the Guarded Html Fragment: " + location); } if (html == null) html = "Transaction in Progress"; c_guardedHtmlCache.put(location, html); } buf.append(html); buf.append("\n</span>\n"); } return buf.toString(); } Code Sample 2: public static String encryptPassword(String password) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes()); byte[] hash = md.digest(); int hashLength = hash.length; StringBuffer hashStringBuf = new StringBuffer(); String byteString; int byteLength; for (int index = 0; index < hashLength; index++) { byteString = String.valueOf(hash[index] + 128); byteLength = byteString.length(); switch(byteLength) { case 1: byteString = "00" + byteString; break; case 2: byteString = "0" + byteString; break; } hashStringBuf.append(byteString); } return hashStringBuf.toString(); } catch (NoSuchAlgorithmException nsae) { log.error("Error getting password hash: " + nsae.getMessage()); return null; } }
00
Code Sample 1: public void run() { waiting(200); try { URL url = new URL(urlAddress); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); XMLHandlerSingleAlbum myXMLHandler = new XMLHandlerSingleAlbum(); xr.setContentHandler(myXMLHandler); xr.parse(new InputSource(url.openStream())); statuscode = myXMLHandler.statuscode; if (statuscode != 200 && statuscode != 206) { throw new Exception(); } genre = myXMLHandler.genre; genreId = myXMLHandler.genreId; labelId = myXMLHandler.labelId; label = myXMLHandler.label; date = myXMLHandler.releaseDate; rating = myXMLHandler.rating; imageURL = myXMLHandler.imageURL; artist = myXMLHandler.artist; artistId = myXMLHandler.artistId; numberOfTracks = myXMLHandler.nItems; trackNames = myXMLHandler.tracks; handlerSetContent.sendEmptyMessage(0); dialog.dismiss(); updateImage(); } catch (Exception e) { final Exception ef = e; nameTextView.post(new Runnable() { public void run() { nameTextView.setText(R.string.couldnt_get_album_info); } }); } if (dialog.isShowing()) { dialog.dismiss(); } handlerDoneLoading.sendEmptyMessage(0); } Code Sample 2: public HttpURLConnection openConnection() throws IOException { URL url = new URL("http", host, request); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(method); connection.setRequestProperty("Host", host); for (Map.Entry<String, List<String>> entry : mapOfHeaders.entrySet()) { for (String value : entry.getValue()) { connection.addRequestProperty(entry.getKey(), value); } } return connection; }
00
Code Sample 1: public void compressFile(String filePath) { String outPut = filePath + ".zip"; try { FileInputStream in = new FileInputStream(filePath); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(outPut)); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read); in.close(); out.close(); } catch (Exception c) { c.printStackTrace(); } } Code Sample 2: public static String encrypt(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(); }
11
Code Sample 1: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { logger.debug("Random GUID error: " + e.getMessage()); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } Code Sample 2: public static byte[] hash(final byte[] saltBefore, final String content, final byte[] saltAfter, final int repeatedHashingCount) throws NoSuchAlgorithmException, UnsupportedEncodingException { if (content == null) return null; final MessageDigest digest = MessageDigest.getInstance(DIGEST); if (digestLength == -1) digestLength = digest.getDigestLength(); for (int i = 0; i < repeatedHashingCount; i++) { if (i > 0) digest.update(digest.digest()); digest.update(saltBefore); digest.update(content.getBytes(WebCastellumParameter.DEFAULT_CHARACTER_ENCODING.getValue())); digest.update(saltAfter); } return digest.digest(); }
00
Code Sample 1: public static void initStaticStuff() { Enumeration<URL> urls = null; try { urls = Play.class.getClassLoader().getResources("play.static"); } catch (Exception e) { } while (urls != null && urls.hasMoreElements()) { URL url = urls.nextElement(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); String line = null; while ((line = reader.readLine()) != null) { try { Class.forName(line); } catch (Exception e) { System.out.println("! Cannot init static : " + line); } } } catch (Exception ex) { Logger.error(ex, "Cannot load %s", url); } } } Code Sample 2: public byte[] download(URL url, OutputStream out) throws IOException { boolean returnByByteArray = (out == null); ByteArrayOutputStream helper = null; if (returnByByteArray) { helper = new ByteArrayOutputStream(); } String s = url.toExternalForm(); URLConnection conn = url.openConnection(); String name = Launcher.getFileName(s); InputStream in = conn.getInputStream(); total = url.openConnection().getContentLength(); setStatusText(String.format("Downloading %s (%.2fMB)...", name, ((float) total / 1024 / 1024))); long justNow = System.currentTimeMillis(); int numRead = -1; byte[] buffer = new byte[2048]; while ((numRead = in.read(buffer)) != -1) { size += numRead; if (returnByByteArray) { helper.write(buffer, 0, numRead); } else { out.write(buffer, 0, numRead); } long now = System.currentTimeMillis(); if ((now - justNow) > 250) { setProgress((int) (((float) size / (float) total) * 100)); justNow = now; } } hideProgress(); if (returnByByteArray) { return helper.toByteArray(); } else { return null; } }
00
Code Sample 1: private void initStreams() throws IOException { if (audio != null) { audio.close(); } if (url != null) { audio = new OggInputStream(url.openStream()); } else { audio = new OggInputStream(ResourceLoader.getResourceAsStream(ref)); } } Code Sample 2: public void copyImage(String from, String to) { File inputFile = new File(from); File outputFile = new File(to); try { if (inputFile.canRead()) { FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); byte[] buf = new byte[65536]; int c; while ((c = in.read(buf)) > 0) out.write(buf, 0, c); in.close(); out.close(); } } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: public static DownloadedContent downloadContent(final InputStream is) throws IOException { if (is == null) { return new DownloadedContent.InMemory(new byte[] {}); } final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final byte[] buffer = new byte[1024]; int nbRead; try { while ((nbRead = is.read(buffer)) != -1) { bos.write(buffer, 0, nbRead); if (bos.size() > MAX_IN_MEMORY) { final File file = File.createTempFile("htmlunit", ".tmp"); file.deleteOnExit(); final FileOutputStream fos = new FileOutputStream(file); bos.writeTo(fos); IOUtils.copyLarge(is, fos); fos.close(); return new DownloadedContent.OnFile(file); } } } finally { IOUtils.closeQuietly(is); } return new DownloadedContent.InMemory(bos.toByteArray()); } Code Sample 2: void loadSVG(String svgFileURL) { try { URL url = new URL(svgFileURL); URLConnection c = url.openConnection(); c.setRequestProperty("Accept-Encoding", "gzip"); InputStream is = c.getInputStream(); String encoding = c.getContentEncoding(); if ("gzip".equals(encoding) || "x-gzip".equals(encoding) || svgFileURL.toLowerCase().endsWith(".svgz")) { is = new GZIPInputStream(is); } is = new BufferedInputStream(is); Document svgDoc = AppletUtils.parse(is, false); if (svgDoc != null) { if (grMngr.mainView.isBlank() == null) { grMngr.mainView.setBlank(cfgMngr.backgroundColor); } SVGReader.load(svgDoc, grMngr.mSpace, true, svgFileURL); grMngr.seekBoundingBox(); grMngr.buildLogicalStructure(); ConfigManager.defaultFont = VText.getMainFont(); grMngr.reveal(); if (grMngr.previousLocations.size() == 1) { grMngr.previousLocations.removeElementAt(0); } if (grMngr.rView != null) { grMngr.rView.getGlobalView(grMngr.mSpace.getCamera(1), 100); } grMngr.cameraMoved(null, null, 0); } else { System.err.println("An error occured while loading file " + svgFileURL); } } catch (Exception ex) { grMngr.reveal(); ex.printStackTrace(); } }
11
Code Sample 1: public static String MD5(String text) { byte[] md5hash = new byte[32]; try { MessageDigest md; md = MessageDigest.getInstance("MD5"); md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } return convertToHex(md5hash); } Code Sample 2: public static String criptografar(String senha) { if (senha == null) { return null; } try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(senha.getBytes()); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(digest.digest()); } catch (NoSuchAlgorithmException ns) { LoggerFactory.getLogger(UtilAdrs.class).error(Msg.EXCEPTION_MESSAGE, UtilAdrs.class.getSimpleName(), ns); return senha; } }
00
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: @Provides @Singleton Properties provideCfg() { InputStream propStream = null; URL url = Thread.currentThread().getContextClassLoader().getResource(PROPERTY_FILE); Properties cfg = new Properties(); if (url != null) { try { log.info("Loading app config from properties: " + url.toURI()); propStream = url.openStream(); cfg.load(propStream); return cfg; } catch (Exception e) { log.warn(e); } } if (cfg.size() < 1) { log.info(PROPERTY_FILE + " doesnt contain any configuration for application properties."); } return cfg; }
00
Code Sample 1: public void connect() throws IOException { try { URL url = new URL(pluginUrl); connection = (HttpURLConnection) url.openConnection(); sendNotification(DownloadState.CONNECTION_ESTABLISHED); contentLength = connection.getContentLength(); sendNotification(DownloadState.CONTENT_LENGTH_SET); downloadedBytes = 0; } catch (java.io.IOException e) { e.printStackTrace(); throw e; } } Code Sample 2: public String parse(String queryText) throws ParseException { try { StringBuilder sb = new StringBuilder(); queryText = Val.chkStr(queryText); if (queryText.length() > 0) { URL url = new URL(getUrl(queryText)); InputStream in = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = null; while ((line = reader.readLine()) != null) { if (sb.length() > 0) { sb.append("\r\n"); } sb.append(line); } } return sb.toString(); } catch (IOException ex) { throw new ParseException("Ontology parser is unable to parse term: \"" + queryText + "\" due to internal error: " + ex.getMessage()); } }
00
Code Sample 1: public void create(Session session) { Connection conn = session.getConnection(this); Statement stat = null; StringBuilder out = new StringBuilder(256); Appendable sql = out; List<MetaTable> tables = new ArrayList<MetaTable>(); List<MetaColumn> newColumns = new ArrayList<MetaColumn>(); List<MetaColumn> foreignColumns = new ArrayList<MetaColumn>(); List<MetaIndex> indexes = new ArrayList<MetaIndex>(); boolean createSequenceTable = false; int tableTotalCount = getTableTotalCount(); try { stat = conn.createStatement(); if (isSequenceTableRequired()) { PreparedStatement ps = null; ResultSet rs = null; Throwable exception = null; String logMsg = ""; try { sql = getDialect().printSequenceCurrentValue(findFirstSequencer(), out); ps = conn.prepareStatement(sql.toString()); ps.setString(1, "-"); rs = ps.executeQuery(); } catch (Throwable e) { exception = e; } if (exception != null) { switch(MetaParams.ORM2DLL_POLICY.of(ormHandler.getParameters())) { case VALIDATE: throw new IllegalStateException(logMsg, exception); case CREATE_DDL: case CREATE_OR_UPDATE_DDL: createSequenceTable = true; } } if (LOGGER.isLoggable(Level.INFO)) { logMsg = "Table '" + SqlDialect.COMMON_SEQ_TABLE_NAME + "' {0} available on the database '{1}'."; logMsg = MessageFormat.format(logMsg, exception != null ? "is not" : "is", getId()); LOGGER.log(Level.INFO, logMsg); } try { if (exception != null) { conn.rollback(); } } finally { close(null, ps, rs, false); } } boolean ddlOnly = false; switch(MetaParams.ORM2DLL_POLICY.of(ormHandler.getParameters())) { case CREATE_DDL: ddlOnly = true; case CREATE_OR_UPDATE_DDL: case VALIDATE: boolean change = isModelChanged(conn, tables, newColumns, indexes); if (change && ddlOnly) { if (tables.size() < tableTotalCount) { return; } } break; case DO_NOTHING: default: return; } switch(MetaParams.CHECK_KEYWORDS.of(getParams())) { case WARNING: case EXCEPTION: Set<String> keywords = getDialect().getKeywordSet(conn); for (MetaTable table : tables) { if (table.isTable()) { checkKeyWord(MetaTable.NAME.of(table), table, keywords); for (MetaColumn column : MetaTable.COLUMNS.of(table)) { checkKeyWord(MetaColumn.NAME.of(column), table, keywords); } } } for (MetaColumn column : newColumns) { checkKeyWord(MetaColumn.NAME.of(column), column.getTable(), keywords); } for (MetaIndex index : indexes) { checkKeyWord(MetaIndex.NAME.of(index), MetaIndex.TABLE.of(index), keywords); } } if (tableTotalCount == tables.size()) for (String schema : getSchemas(tables)) { out.setLength(0); sql = getDialect().printCreateSchema(schema, out); if (isUsable(sql)) { try { stat.executeUpdate(sql.toString()); } catch (SQLException e) { LOGGER.log(Level.INFO, "{0}: {1}; {2}", new Object[] { e.getClass().getName(), sql.toString(), e.getMessage() }); conn.rollback(); } } } int tableCount = 0; for (MetaTable table : tables) { if (table.isTable()) { tableCount++; out.setLength(0); sql = getDialect().printTable(table, out); executeUpdate(sql, stat); foreignColumns.addAll(table.getForeignColumns()); } } for (MetaColumn column : newColumns) { out.setLength(0); sql = getDialect().printAlterTable(column, out); executeUpdate(sql, stat); if (column.isForeignKey()) { foreignColumns.add(column); } } for (MetaIndex index : indexes) { out.setLength(0); sql = getDialect().printIndex(index, out); executeUpdate(sql, stat); } for (MetaColumn column : foreignColumns) { if (column.isForeignKey()) { out.setLength(0); MetaTable table = MetaColumn.TABLE.of(column); sql = getDialect().printForeignKey(column, table, out); executeUpdate(sql, stat); } } if (createSequenceTable) { out.setLength(0); sql = getDialect().printSequenceTable(this, out); executeUpdate(sql, stat); } List<MetaTable> cTables = null; switch(MetaParams.COMMENT_POLICY.of(ormHandler.getParameters())) { case FOR_NEW_OBJECT: cTables = tables; break; case ALWAYS: case ON_ANY_CHANGE: cTables = TABLES.getList(this); break; case NEVER: cTables = Collections.emptyList(); break; default: throw new IllegalStateException("Unsupported parameter"); } if (!cTables.isEmpty()) { sql = out; createTableComments(cTables, stat, out); } conn.commit(); } catch (Throwable e) { try { conn.rollback(); } catch (SQLException ex) { LOGGER.log(Level.WARNING, "Can't rollback DB" + getId(), ex); } throw new IllegalArgumentException(Session.SQL_ILLEGAL + sql, e); } } Code Sample 2: private void download(URL url, File outFile) throws IOException { System.out.println("Trying to download: " + url); InputStream in = null; OutputStream out = null; try { URLConnection conn = url.openConnection(); in = conn.getInputStream(); out = new BufferedOutputStream(new FileOutputStream(outFile)); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > -1) { out.write(buf, 0, len); } } finally { if (in != null) { try { in.close(); } catch (IOException e) { logger.error("Unable to close stream.", e); } } if (out != null) { try { out.close(); } catch (IOException e) { logger.error("Unable to close stream.", e); } } } }
00
Code Sample 1: public void zip_compressFiles() throws Exception { FileInputStream in = null; File f1 = new File("C:\\WINDOWS\\regedit.exe"); File f2 = new File("C:\\WINDOWS\\win.ini"); File file = new File("C:\\" + NTUtil.class.getName() + ".zip"); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file)); out.putNextEntry(new ZipEntry("regedit.exe")); in = new FileInputStream(f1); while (in.available() > 0) { out.write(in.read()); } in.close(); out.closeEntry(); out.putNextEntry(new ZipEntry("win.ini")); in = new FileInputStream(f2); while (in.available() > 0) { out.write(in.read()); } in.close(); out.closeEntry(); out.close(); } Code Sample 2: private void importUrl() throws ExtractaException { UITools.changeCursor(UITools.WAIT_CURSOR, this); try { m_sUrlString = m_urlTF.getText(); URL url = new URL(m_sUrlString); Document document = DomHelper.parseHtml(url.openStream()); m_inputPanel.setDocument(document); Edl edl = new Edl(); edl.addUrlDescriptor(new UrlDescriptor(m_sUrlString)); m_resultPanel.setContext(new ResultContext(edl, document, url)); setModified(true); } catch (IOException ex) { throw new ExtractaException("Can not open URL!", ex); } finally { UITools.changeCursor(UITools.DEFAULT_CURSOR, this); } }
11
Code Sample 1: @Override public void aggregate() { Connection connection = null; PreparedStatement prestm = null; try { if (logger.isInfoEnabled()) logger.info("aggregate table <" + origin + "> start..."); Class.forName(driver); connection = DriverManager.getConnection(url, username, password); String tableExistsResult = ""; prestm = connection.prepareStatement("show tables from " + schema + " like '" + getDestination() + "';"); ResultSet rs = prestm.executeQuery(); if (rs.next()) tableExistsResult = rs.getString(1); rs.close(); prestm.close(); if (StringUtils.isBlank(tableExistsResult)) { String createTableSql = ""; prestm = connection.prepareStatement("show create table " + getOrigin() + ";"); rs = prestm.executeQuery(); if (rs.next()) createTableSql = rs.getString(2); rs.close(); prestm.close(); createTableSql = createTableSql.replaceAll("`" + getOrigin() + "`", "`" + getDestination() + "`"); createTableSql = createTableSql.replaceAll("auto_increment", ""); createTableSql = createTableSql.replaceAll("AUTO_INCREMENT", ""); Matcher matcher = stripRelationTablePattern.matcher(createTableSql); if (matcher.find()) createTableSql = matcher.replaceAll(""); matcher = normalizePattern.matcher(createTableSql); if (matcher.find()) createTableSql = matcher.replaceAll("\n )"); Statement stm = connection.createStatement(); stm.execute(createTableSql); if (logger.isDebugEnabled()) logger.debug("table '" + getDestination() + "' created!"); } else if (logger.isDebugEnabled()) logger.debug("table '" + getDestination() + "' already exists"); long currentRows = 0L; prestm = connection.prepareStatement("select count(*) from " + origin); rs = prestm.executeQuery(); if (rs.next()) currentRows = rs.getLong(1); rs.close(); prestm.close(); if (logger.isInfoEnabled()) logger.info("found " + currentRows + " record"); prestm = connection.prepareStatement("select max(d_insDate) from " + destination); rs = prestm.executeQuery(); Date from = null; if (rs.next()) from = rs.getTimestamp(1); rs.close(); prestm.close(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String fromStr = null; if (from != null) fromStr = sdf.format(from); if (logger.isInfoEnabled()) logger.info("last record date:" + fromStr); if (currentRows > 0) { connection.setAutoCommit(false); if (from != null && fromStr != null) { prestm = connection.prepareStatement("INSERT INTO " + destination + " SELECT * FROM " + origin + " WHERE d_insDate > '" + fromStr + "'"); if (logger.isDebugEnabled()) logger.debug("Query: INSERT INTO " + destination + " SELECT * FROM " + origin + " WHERE d_insDate > '" + fromStr + "'"); } else { prestm = connection.prepareStatement("INSERT INTO " + destination + " SELECT * FROM " + origin); if (logger.isDebugEnabled()) logger.debug("Query: INSERT INTO " + destination + " SELECT * FROM " + origin); } int rows = prestm.executeUpdate(); prestm.close(); if (logger.isInfoEnabled()) logger.info(" > " + rows + " rows aggregated"); connection.commit(); } else if (logger.isInfoEnabled()) logger.info("no aggregation need"); if (logger.isInfoEnabled()) logger.info("aggregate table " + origin + " end"); } catch (SQLException e) { logger.error(e, e); if (applicationContext != null) applicationContext.publishEvent(new TrapEvent(this, "dbcon", "Errore SQL durante l'aggregazione dei dati della tabella " + origin, e)); try { connection.rollback(); } catch (SQLException e1) { } } catch (Throwable e) { logger.error(e, e); if (applicationContext != null) applicationContext.publishEvent(new TrapEvent(this, "generic", "Errore generico durante l'aggregazione dei dati della tabella " + origin, e)); try { connection.rollback(); } catch (SQLException e1) { } } finally { try { if (prestm != null) prestm.close(); } catch (SQLException e) { } try { if (connection != null) connection.close(); } catch (SQLException e) { } } } Code Sample 2: private String AddAction(ResultSet node, String modo) throws SQLException { Connection cn = null; Connection cndef = null; String schema = boRepository.getDefaultSchemaName(boApplication.getDefaultApplication()).toLowerCase(); try { cn = this.getRepositoryConnection(p_ctx.getApplication(), p_ctx.getBoSession().getRepository().getName(), 1); cndef = this.getRepositoryConnection(p_ctx.getApplication(), p_ctx.getBoSession().getRepository().getName(), 2); String dml = null; String objecttype = node.getString("OBJECTTYPE"); if (objecttype.equalsIgnoreCase("T")) { boolean exists = existsTable(p_ctx, schema, node.getString("OBJECTNAME").toLowerCase()); String[] sysflds = { "SYS_USER", "SYS_ICN", "SYS_DTCREATE", "SYS_DTSAVE", "SYS_ORIGIN" }; String[] sysfdef = { "VARCHAR(25)", "NUMERIC(7)", "TIMESTAMP DEFAULT now()", "TIMESTAMP", "VARCHAR(30)" }; String[] sysftyp = { "C", "N", "D", "D", "C" }; String[] sysfsiz = { "25", "7", "", "", "30" }; String[] sysfndef = { "", "", "", "", "" }; String[] sysfdes = { "", "", "", "", "" }; if (!exists && !modo.equals("3")) { dml = "CREATE TABLE " + node.getString("OBJECTNAME") + " ("; for (int i = 0; i < sysflds.length; i++) { dml += (sysflds[i] + " " + sysfdef[i] + ((i < (sysflds.length - 1)) ? "," : ")")); } String vt = node.getString("OBJECTNAME"); if (node.getString("SCHEMA").equals("DEF")) { vt = "NGD_" + vt; } else if (node.getString("SCHEMA").equals("SYS")) { vt = "SYS_" + vt; } executeDDL(dml, node.getString("SCHEMA")); } if (modo.equals("3") && exists) { executeDDL("DROP TABLE " + node.getString("OBJECTNAME"), node.getString("SCHEMA")); CallableStatement call = cndef.prepareCall("DELETE FROM NGTDIC WHERE TABLENAME=?"); call.setString(1, node.getString("OBJECTNAME")); call.executeUpdate(); call.close(); } checkDicFields(node.getString("OBJECTNAME"), node.getString("SCHEMA"), sysflds, sysftyp, sysfsiz, sysfndef, sysfdes); } if (objecttype.equalsIgnoreCase("F")) { boolean fldchg = false; boolean fldexi = false; PreparedStatement pstm = cn.prepareStatement("select column_name,udt_name,character_maximum_length,numeric_precision,numeric_scale from information_schema.columns" + " where table_name=? and column_name=? and table_schema=?"); pstm.setString(1, node.getString("TABLENAME").toLowerCase()); pstm.setString(2, node.getString("OBJECTNAME").toLowerCase()); pstm.setString(3, schema); ResultSet rslt = pstm.executeQuery(); if (rslt.next()) { int fieldsiz = rslt.getInt(3); int fielddec = rslt.getInt(5); if (",C,N,".indexOf("," + getNgtFieldTypeFromDDL(rslt.getString(2)) + ",") != -1) { if (getNgtFieldTypeFromDDL(rslt.getString(2)).equals("N")) { fieldsiz = rslt.getInt(4); } if (fielddec != 0) { if (!(fieldsiz + "," + fielddec).equals(node.getString("FIELDSIZE"))) { fldchg = true; } } else { if (!((fieldsiz == 0) && ((node.getString("FIELDSIZE") == null) || (node.getString("FIELDSIZE").length() == 0)))) { if (!("" + fieldsiz).equals(node.getString("FIELDSIZE"))) { fldchg = true; } } } } fldexi = true; } else { fldexi = false; } rslt.close(); pstm.close(); boolean drop = false; if (("20".indexOf(modo) != -1) && !fldexi) { dml = "ALTER TABLE " + node.getString("TABLENAME") + " add \"" + node.getString("OBJECTNAME").toLowerCase() + "\" "; } else if (("20".indexOf(modo) != -1) && fldexi && fldchg) { dml = "ALTER TABLE " + node.getString("TABLENAME") + " ALTER COLUMN \"" + node.getString("OBJECTNAME").toLowerCase() + "\" "; } else if (modo.equals("3") && fldexi) { dml = "ALTER TABLE " + node.getString("TABLENAME") + " drop COLUMN \"" + node.getString("OBJECTNAME").toLowerCase() + "\" "; String sql = "SELECT tc.constraint_name,tc.constraint_type" + " FROM information_schema.table_constraints tc" + " LEFT JOIN information_schema.key_column_usage kcu" + " ON tc.constraint_catalog = kcu.constraint_catalog" + " AND tc.constraint_schema = kcu.constraint_schema" + " AND tc.constraint_name = kcu.constraint_name" + " LEFT JOIN information_schema.referential_constraints rc" + " ON tc.constraint_catalog = rc.constraint_catalog" + " AND tc.constraint_schema = rc.constraint_schema" + " AND tc.constraint_name = rc.constraint_name" + " LEFT JOIN information_schema.constraint_column_usage ccu" + " ON rc.unique_constraint_catalog = ccu.constraint_catalog" + " AND rc.unique_constraint_schema = ccu.constraint_schema" + " AND rc.unique_constraint_name = ccu.constraint_name" + " WHERE tc.table_name = ?" + " AND kcu.column_name = ?" + " and tc.table_schema=?"; PreparedStatement pstmrelc = cn.prepareStatement(sql); pstmrelc.setString(1, node.getString("TABLENAME").toLowerCase()); pstmrelc.setString(2, node.getString("OBJECTNAME").toLowerCase()); pstmrelc.setString(3, schema); ResultSet rsltrelc = pstmrelc.executeQuery(); while (rsltrelc.next()) { String constname = rsltrelc.getString(1); String consttype = rsltrelc.getString(2); PreparedStatement pstmdic = cndef.prepareStatement("DELETE FROM NGTDIC WHERE TABLENAME=? AND OBJECTTYPE=? AND OBJECTNAME=?"); pstmdic.setString(1, node.getString("TABLENAME")); pstmdic.setString(2, consttype.equals("R") ? "FK" : "PK"); pstmdic.setString(3, constname); int nrecs = pstmdic.executeUpdate(); pstm.close(); executeDDL("ALTER TABLE " + node.getString("TABLENAME") + " DROP CONSTRAINT " + constname, node.getString("SCHEMA")); } rsltrelc.close(); pstmrelc.close(); } if ((dml != null) && (dml.length() > 0) && !modo.equals("3")) { String mfield = node.getString("MACROFIELD"); if ((mfield != null) && !(!mfield.equals("TEXTOLIVRE") && !mfield.equals("NUMEROLIVRE") && !mfield.equals("TEXT") && !mfield.equals("BLOB") && !mfield.equals("MDATA"))) { String ngtft = ""; if (mfield.equals("TEXTOLIVRE")) { ngtft = "C"; } else if (mfield.equals("NUMEROLIVRE")) { ngtft = "N"; } else if (mfield.equals("RAW")) { ngtft = "RAW"; } else if (mfield.equals("TIMESTAMP")) { ngtft = "TIMESTAMP"; } else if (mfield.equals("MDATA")) { ngtft = "D"; } else if (mfield.equals("TEXT")) { ngtft = "CL"; } else if (mfield.equals("BLOB")) { ngtft = "BL"; } dml += getDDLFieldFromNGT(ngtft, node.getString("FIELDSIZE")); } else if ((mfield != null) && (mfield.length() > 0)) { dml += getMacrofieldDef(cndef, node.getString("MACROFIELD")); } else { dml += getDDLFieldFromNGT(node.getString("FIELDTYPE"), node.getString("FIELDSIZE")); } } String[] flds = new String[1]; flds[0] = node.getString("OBJECTNAME"); if (dml != null) { executeDDL(dml, node.getString("SCHEMA")); } } if (objecttype.equalsIgnoreCase("V")) { String viewText = null; PreparedStatement pstmrelc = cn.prepareStatement("SELECT view_definition FROM information_schema.views WHERE table_name=? " + "and table_schema=?"); pstmrelc.setString(1, node.getString("OBJECTNAME").toLowerCase()); pstmrelc.setString(2, schema.toLowerCase()); ResultSet rsltrelc = pstmrelc.executeQuery(); boolean exists = false; if (rsltrelc.next()) { exists = true; viewText = rsltrelc.getString(1); viewText = viewText.substring(0, viewText.length() - 1); } rsltrelc.close(); pstmrelc.close(); if (!modo.equals("3")) { String vExpression = node.getString("EXPRESSION"); if (!vExpression.toLowerCase().equals(viewText)) { dml = "CREATE OR REPLACE VIEW \"" + node.getString("OBJECTNAME") + "\" AS \n" + vExpression; executeDDL(dml, node.getString("SCHEMA")); } } else { if (exists) { dml = "DROP VIEW " + node.getString("OBJECTNAME"); executeDDL(dml, node.getString("SCHEMA")); CallableStatement call = cndef.prepareCall("DELETE FROM NGTDIC WHERE TABLENAME=?"); call.setString(1, node.getString("OBJECTNAME")); call.executeUpdate(); call.close(); } } } if (objecttype.startsWith("PCK")) { String templatestr = node.getString("EXPRESSION"); String bstr = "/*begin_package*/"; String estr = "/*end_package*/"; if ("02".indexOf(modo) != -1) { if (templatestr.indexOf(bstr) != -1) { int defpos; dml = templatestr.substring(templatestr.indexOf(bstr), defpos = templatestr.indexOf(estr)); dml = "create or replace package " + node.getString("OBJECTNAME") + " is \n" + dml + "end " + node.getString("OBJECTNAME") + ";\n"; executeDDL(dml, node.getString("SCHEMA")); bstr = "/*begin_package_body*/"; estr = "/*end_package_body*/"; if (templatestr.indexOf(bstr, defpos) != -1) { dml = templatestr.substring(templatestr.indexOf(bstr, defpos), templatestr.indexOf(estr, defpos)); dml = "create or replace package body " + node.getString("OBJECTNAME") + " is \n" + dml + "end " + node.getString("OBJECTNAME") + ";\n"; executeDDL(dml, node.getString("SCHEMA")); } } else { } } } if (objecttype.startsWith("PK") || objecttype.startsWith("UN")) { String sql = "SELECT kcu.column_name" + " FROM information_schema.table_constraints tc" + " LEFT JOIN information_schema.key_column_usage kcu" + " ON tc.constraint_catalog = kcu.constraint_catalog" + " AND tc.constraint_schema = kcu.constraint_schema" + " AND tc.constraint_name = kcu.constraint_name" + " LEFT JOIN information_schema.referential_constraints rc" + " ON tc.constraint_catalog = rc.constraint_catalog" + " AND tc.constraint_schema = rc.constraint_schema" + " AND tc.constraint_name = rc.constraint_name" + " LEFT JOIN information_schema.constraint_column_usage ccu" + " ON rc.unique_constraint_catalog = ccu.constraint_catalog" + " AND rc.unique_constraint_schema = ccu.constraint_schema" + " AND rc.unique_constraint_name = ccu.constraint_name" + " WHERE tc.table_name = ?" + " AND tc.constraint_name = ?" + " and tc.table_schema=? order by ordinal_position"; PreparedStatement pstm = cn.prepareStatement(sql); pstm.setString(1, node.getString("TABLENAME").toLowerCase()); pstm.setString(2, node.getString("OBJECTNAME").toLowerCase()); pstm.setString(3, schema.toLowerCase()); boolean isunique = objecttype.startsWith("UN"); ResultSet rslt = pstm.executeQuery(); boolean exists = false; StringBuffer expression = new StringBuffer(); while (rslt.next()) { if (exists) { expression.append(','); } exists = true; expression.append(rslt.getString(1)); } boolean diff = !expression.toString().toUpperCase().equals(node.getString("EXPRESSION")); rslt.close(); pstm.close(); if ((modo.equals("3") || diff) && exists) { sql = "SELECT tc.constraint_name,tc.table_name" + " FROM information_schema.table_constraints tc" + " LEFT JOIN information_schema.key_column_usage kcu" + " ON tc.constraint_catalog = kcu.constraint_catalog" + " AND tc.constraint_schema = kcu.constraint_schema" + " AND tc.constraint_name = kcu.constraint_name" + " LEFT JOIN information_schema.referential_constraints rc" + " ON tc.constraint_catalog = rc.constraint_catalog" + " AND tc.constraint_schema = rc.constraint_schema" + " AND tc.constraint_name = rc.constraint_name" + " LEFT JOIN information_schema.constraint_column_usage ccu" + " ON rc.unique_constraint_catalog = ccu.constraint_catalog" + " AND rc.unique_constraint_schema = ccu.constraint_schema" + " AND rc.unique_constraint_name = ccu.constraint_name" + " WHERE ccu.constraint_name = ?" + " and tc.table_schema=?"; PreparedStatement pstmrefs = cn.prepareStatement(sql); pstmrefs.setString(1, node.getString("OBJECTNAME").toLowerCase()); pstmrefs.setString(2, schema.toLowerCase()); ResultSet rsltrefs = pstmrefs.executeQuery(); while (rsltrefs.next()) { PreparedStatement pstmdelref = cndef.prepareStatement("DELETE NGTDIC WHERE OBJECTNAME=? AND SCHEMA=? AND TABLENAME=? AND OBJECTTYPE='FK'"); pstmdelref.setString(1, rsltrefs.getString(1)); pstmdelref.setString(2, node.getString("SCHEMA")); pstmdelref.setString(3, rsltrefs.getString(2)); pstmdelref.executeUpdate(); pstmdelref.close(); executeDDL("alter table " + rsltrefs.getString(2) + " drop constraint " + rsltrefs.getString(1), node.getString("SCHEMA")); } rsltrefs.close(); pstmrefs.close(); String insql = "'" + node.getString("EXPRESSION").toLowerCase().replaceAll(",", "\\',\\'") + "'"; sql = "SELECT tc.constraint_name" + " FROM information_schema.table_constraints tc" + " LEFT JOIN information_schema.key_column_usage kcu" + " ON tc.constraint_catalog = kcu.constraint_catalog" + " AND tc.constraint_schema = kcu.constraint_schema" + " AND tc.constraint_name = kcu.constraint_name" + " LEFT JOIN information_schema.referential_constraints rc" + " ON tc.constraint_catalog = rc.constraint_catalog" + " AND tc.constraint_schema = rc.constraint_schema" + " AND tc.constraint_name = rc.constraint_name" + " LEFT JOIN information_schema.constraint_column_usage ccu" + " ON rc.unique_constraint_catalog = ccu.constraint_catalog" + " AND rc.unique_constraint_schema = ccu.constraint_schema" + " AND rc.unique_constraint_name = ccu.constraint_name" + " WHERE tc.table_name=? and " + "kcu.column_name in (" + insql + ")" + " and tc.table_schema=?"; pstmrefs = cn.prepareStatement(sql); pstmrefs.setString(1, node.getString("TABLENAME").toLowerCase()); pstmrefs.setString(2, schema.toLowerCase()); rsltrefs = pstmrefs.executeQuery(); while (rsltrefs.next()) { PreparedStatement pstmdelref = cndef.prepareStatement("DELETE NGTDIC WHERE OBJECTNAME=? AND SCHEMA=? AND TABLENAME=? AND OBJECTTYPE='FK'"); pstmdelref.setString(1, rsltrefs.getString(1)); pstmdelref.setString(2, node.getString("SCHEMA")); pstmdelref.setString(3, node.getString("TABLENAME")); pstmdelref.executeUpdate(); pstmdelref.close(); executeDDL("alter table " + node.getString("TABLENAME") + " drop constraint " + rsltrefs.getString(1), node.getString("SCHEMA")); } rsltrefs.close(); pstmrefs.close(); if (exists && diff) { dml = "alter table " + node.getString("TABLENAME") + " drop constraint " + node.getString("OBJECTNAME"); try { executeDDL(dml, node.getString("SCHEMA")); } catch (Exception e) { logger.warn(LoggerMessageLocalizer.getMessage("ERROR_EXCUTING_DDL") + " (" + dml + ") " + e.getMessage()); } } } if (!modo.equals("3") && (!exists || diff)) { if (isunique) { dml = "alter table " + node.getString("TABLENAME") + " add constraint " + node.getString("OBJECTNAME") + " unique (" + node.getString("EXPRESSION") + ")"; } else { dml = "alter table " + node.getString("TABLENAME") + " add primary key (" + node.getString("EXPRESSION") + ")"; } executeDDL(dml, node.getString("SCHEMA")); } } if (objecttype.startsWith("FK")) { String sql = "SELECT kcu.column_name" + " FROM information_schema.table_constraints tc" + " LEFT JOIN information_schema.key_column_usage kcu" + " ON tc.constraint_catalog = kcu.constraint_catalog" + " AND tc.constraint_schema = kcu.constraint_schema" + " AND tc.constraint_name = kcu.constraint_name" + " LEFT JOIN information_schema.referential_constraints rc" + " ON tc.constraint_catalog = rc.constraint_catalog" + " AND tc.constraint_schema = rc.constraint_schema" + " AND tc.constraint_name = rc.constraint_name" + " LEFT JOIN information_schema.constraint_column_usage ccu" + " ON rc.unique_constraint_catalog = ccu.constraint_catalog" + " AND rc.unique_constraint_schema = ccu.constraint_schema" + " AND rc.unique_constraint_name = ccu.constraint_name" + " WHERE tc.constraint_name=?" + " and tc.table_name=?" + " and tc.table_schema=? order by ordinal_position"; PreparedStatement pstm = cn.prepareStatement(sql); pstm.setString(1, node.getString("OBJECTNAME").toLowerCase()); pstm.setString(2, node.getString("TABLENAME").toLowerCase()); pstm.setString(3, schema.toLowerCase()); ResultSet rslt = pstm.executeQuery(); boolean exists = false; String cExpress = ""; String express = node.getString("EXPRESSION"); if (rslt.next()) { exists = true; if (cExpress.length() > 0) cExpress += ","; cExpress += rslt.getString(1); } rslt.close(); pstm.close(); if (exists && !express.equals(cExpress)) { dml = "alter table " + node.getString("TABLENAME") + " drop constraint " + node.getString("OBJECTNAME"); executeDDL(dml, node.getString("SCHEMA")); } if (!modo.equals("3") && (!exists || !express.equals(cExpress))) { dml = "alter table " + node.getString("TABLENAME") + " add constraint " + node.getString("OBJECTNAME") + " foreign key (" + node.getString("EXPRESSION") + ") references " + node.getString("TABLEREFERENCE") + "(" + node.getString("FIELDREFERENCE") + ")"; executeDDL(dml, node.getString("SCHEMA")); } } if (objecttype.startsWith("IDX")) { boolean unflag = false; String sql = "SELECT n.nspname" + " FROM pg_catalog.pg_class c" + " JOIN pg_catalog.pg_index i ON i.indexrelid = c.oid" + " JOIN pg_catalog.pg_class c2 ON i.indrelid = c2.oid" + " LEFT JOIN pg_catalog.pg_user u ON u.usesysid = c.relowner" + " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace" + " where c.relname=? and c.relkind='i' and n.nspname=?"; PreparedStatement pstm = cn.prepareStatement(sql); pstm.setString(1, node.getString("OBJECTNAME").toLowerCase()); pstm.setString(2, schema.toLowerCase()); ResultSet rslt = pstm.executeQuery(); boolean drop = false; boolean exists = false; boolean dbunflag = false; String oldexpression = ""; String newexpression = ""; if (rslt.next()) { exists = true; if ((unflag && !(dbunflag = rslt.getString(1).equals("UNIQUE")))) { drop = true; } rslt.close(); pstm.close(); sql = "SELECT kcu.column_name" + " FROM information_schema.table_constraints tc" + " LEFT JOIN information_schema.key_column_usage kcu" + " ON tc.constraint_catalog = kcu.constraint_catalog" + " AND tc.constraint_schema = kcu.constraint_schema" + " AND tc.constraint_name = kcu.constraint_name" + " LEFT JOIN information_schema.referential_constraints rc" + " ON tc.constraint_catalog = rc.constraint_catalog" + " AND tc.constraint_schema = rc.constraint_schema" + " AND tc.constraint_name = rc.constraint_name" + " LEFT JOIN information_schema.constraint_column_usage ccu" + " ON rc.unique_constraint_catalog = ccu.constraint_catalog" + " AND rc.unique_constraint_schema = ccu.constraint_schema" + " AND rc.unique_constraint_name = ccu.constraint_name" + " WHERE tc.constraint_name=?" + " and tc.table_name=?" + " and tc.table_schema=? and tc.constraint_type='UNIQUE'"; pstm = cn.prepareStatement(sql); pstm.setString(1, node.getString("OBJECTNAME").toLowerCase()); pstm.setString(2, node.getString("TABLENAME").toLowerCase()); pstm.setString(3, schema.toLowerCase()); rslt = pstm.executeQuery(); while (rslt.next()) { oldexpression += (((oldexpression.length() > 0) ? "," : "") + rslt.getString(1)); } rslt.close(); pstm.close(); } else { rslt.close(); pstm.close(); } String aux = node.getString("EXPRESSION"); String[] nexo; if (aux != null) { nexo = node.getString("EXPRESSION").split(","); } else { nexo = new String[0]; } for (byte i = 0; i < nexo.length; i++) { newexpression += (((newexpression.length() > 0) ? "," : "") + ((nexo[i]).toUpperCase().trim())); } if (!drop) { drop = (!newexpression.equals(oldexpression)) && !oldexpression.equals(""); } if (exists && (drop || modo.equals("3"))) { if (!dbunflag) { dml = "DROP INDEX " + node.getString("OBJECTNAME"); } else { dml = "ALTER TABLE " + node.getString("TABLENAME") + " DROP CONSTRAINT " + node.getString("OBJECTNAME"); } executeDDL(dml, node.getString("SCHEMA")); exists = false; } if (!exists && !modo.equals("3")) { if (!node.getString("OBJECTNAME").equals("") && !newexpression.equals("")) { if (!unflag) { dml = "CREATE INDEX " + node.getString("OBJECTNAME") + " ON " + node.getString("TABLENAME") + "(" + newexpression + ")"; } else { dml = "ALTER TABLE " + node.getString("TABLENAME") + " ADD CONSTRAINT " + node.getString("OBJECTNAME") + " UNIQUE (" + newexpression + ")"; } executeDDL(dml, node.getString("SCHEMA")); } } } updateDictionaryTable(node, modo); return dml; } catch (SQLException e) { cn.rollback(); cndef.rollback(); throw (e); } finally { } }
00
Code Sample 1: private InputStream getDomainMap() { String domainMap = Configuration.getString(MAPPING_KEY); InputStream is = new StringBufferInputStream(domainMap); if ("".equals(domainMap)) { try { URL url = getClass().getResource(XML_FILE_NAME).toURI().toURL(); is = url.openStream(); } catch (URISyntaxException e) { LOG.warn("Could not find domainmapping file", e); } catch (MalformedURLException e) { LOG.warn("Could not find domainmapping file", e); } catch (IOException e) { LOG.warn("Error reading/fetching domain map", e); } } return is; } Code Sample 2: @Override public InputStream getInputStream() throws IOException { if (dfos == null) { int deferredOutputStreamThreshold = Config.getInstance().getDeferredOutputStreamThreshold(); dfos = new DeferredFileOutputStream(deferredOutputStreamThreshold, Definitions.PROJECT_NAME, "." + Definitions.TMP_EXTENSION); try { IOUtils.copy(is, dfos); } finally { dfos.close(); } } return dfos.getDeferredInputStream(); }
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: @HttpAction(name = "map.saveOrUpdate", method = { HttpAction.Method.post }, responseType = "text/plain") @HttpAuthentication(method = { HttpAuthentication.Method.WSSE }) public String saveOrUpdate(FileItem file, User user, MapOriginal map) throws HttpRpcException { File tmpFile; GenericDAO<MapOriginal> mapDao = DAOFactory.createDAO(MapOriginal.class); try { assert (file != null); String jobid = null; if (file.getContentType().startsWith("image/")) { tmpFile = File.createTempFile("gmap", "img"); OutputStream out = new FileOutputStream(tmpFile); IOUtils.copy(file.getInputStream(), out); out.flush(); out.close(); map.setState(MapOriginal.MapState.UPLOAD); map.setUser(user); map.setMapPath(tmpFile.getPath()); map.setThumbnailUrl("/map/inproc.gif"); map.setMimeType(file.getContentType()); mapDao.saveOrUpdate(map); jobid = PoolFactory.getClientPool().put(map, TaskState.STATE_MO_FINISH, MapOverrideStrategy.class); } return jobid; } catch (IOException e) { logger.error(e); throw ERROR_INTERNAL; } catch (DAOException e) { logger.error(e); throw ERROR_INTERNAL; } }
11
Code Sample 1: public static byte[] generatePasswordHash(String s) { byte[] password = { 00 }; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(s.getBytes()); password = md5.digest(); return password; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return password; } Code Sample 2: private boolean keysMatch(String keyNMinusOne, String keyN) { boolean match = false; try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.reset(); digest.update(keyNMinusOne.getBytes()); byte[] hashedBytes = digest.digest(); String encodedHashedKey = new String(com.Ostermiller.util.Base64.encode(hashedBytes)); match = encodedHashedKey.equals(keyN); } catch (NoSuchAlgorithmException e) { } return match; }
11
Code Sample 1: public static boolean copyFile(File source, File dest) throws IOException { int answer = JOptionPane.YES_OPTION; if (dest.exists()) { answer = JOptionPane.showConfirmDialog(null, "File " + dest.getAbsolutePath() + "\n already exists. Overwrite?", "Warning", JOptionPane.YES_NO_OPTION); } if (answer == JOptionPane.NO_OPTION) return false; dest.createNewFile(); InputStream in = null; OutputStream out = null; try { in = new FileInputStream(source); out = new FileOutputStream(dest); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } return true; } catch (Exception e) { return false; } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } Code Sample 2: public void compressFile(String filePath) { String outPut = filePath + ".zip"; try { FileInputStream in = new FileInputStream(filePath); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(outPut)); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read); in.close(); out.close(); } catch (Exception c) { c.printStackTrace(); } }
00
Code Sample 1: @SuppressWarnings("unchecked") private final D loadMeta(URL url) throws IOException { SAXParser saxParser; try { saxParser = SAX_PARSER_FACTORY.newSAXParser(); } catch (ParserConfigurationException e) { throw new Error(e); } catch (SAXException e) { throw new Error(e); } try { saxParser.setProperty("http://xml.org/sax/features/validation", false); } catch (SAXNotRecognizedException e) { e.printStackTrace(); } catch (SAXNotSupportedException e) { e.printStackTrace(); } MetaParser handler = new MetaParser(); try { saxParser.parse(url.openStream(), handler); } catch (SAXException e) { throw new ParsingException(e); } return ((D) handler.getMetaData()); } Code Sample 2: protected void downloadCacheFile(File file) throws Exception { ApplicationProperties app = ApplicationProperties.getInstance(); String address = app.getProperty(JabberConstants.PROPERTY_JABBER_SERVERLIST, DEFAULT_SERVER_URL); URL url = new URL(address); file.createNewFile(); OutputStream cache = new FileOutputStream(file); InputStream input = url.openStream(); byte buffer[] = new byte[1024]; int bytesRead = 0; while ((bytesRead = input.read(buffer)) >= 0) cache.write(buffer, 0, bytesRead); input.close(); cache.close(); }
11
Code Sample 1: public static void main(String[] args) throws IOException { String urltext = "http://www.vogella.de"; URL url = new URL(urltext); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } in.close(); } Code Sample 2: private static String getDocumentAt(String urlString) { StringBuffer html_text = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) html_text.append(line + "\n"); reader.close(); } catch (MalformedURLException e) { System.out.println("����URL: " + urlString); } catch (IOException e) { e.printStackTrace(); } return html_text.toString(); }
00
Code Sample 1: @RequestMapping("/import") public String importPicture(@ModelAttribute PictureImportCommand command) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); URL url = command.getUrl(); IOUtils.copy(url.openStream(), baos); byte[] imageData = imageFilterService.touchupImage(baos.toByteArray()); String filename = StringUtils.substringAfterLast(url.getPath(), "/"); String email = userService.getCurrentUser().getEmail(); Picture picture = new Picture(email, filename, command.getDescription(), imageData); pictureRepository.store(picture); return "redirect:/picture/gallery"; } Code Sample 2: private final synchronized Vector<Class<?>> findSubclasses(URL location, String packageName, Class<?> superClass) { Map<Class<?>, URL> thisResult = new TreeMap<Class<?>, URL>(CLASS_COMPARATOR); Vector<Class<?>> v = new Vector<Class<?>>(); String fqcn = searchClass.getName(); List<URL> knownLocations = new ArrayList<URL>(); knownLocations.add(location); for (int loc = 0; loc < knownLocations.size(); loc++) { URL url = knownLocations.get(loc); 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 { Class<?> c = Class.forName(packageName + "." + classname); if (superClass.isAssignableFrom(c) && !fqcn.equals(packageName + "." + classname)) thisResult.put(c, url); } catch (ClassNotFoundException cnfex) { errors.add(cnfex); } catch (Exception ex) { errors.add(ex); } } } else try { JarURLConnection conn = (JarURLConnection) url.openConnection(); JarFile jarFile = conn.getJarFile(); Enumeration<JarEntry> e = jarFile.entries(); while (e.hasMoreElements()) { JarEntry entry = e.nextElement(); String entryname = entry.getName(); if (!entry.isDirectory() && entryname.endsWith(".class")) { String classname = entryname.substring(0, entryname.length() - 6); if (classname.startsWith("/")) classname = classname.substring(1); classname = classname.replace('/', '.'); System.err.println("Trying " + classname); try { Class c = Class.forName(classname); if (superClass.isAssignableFrom(c) && !fqcn.equals(classname)) thisResult.put(c, url); } catch (ClassNotFoundException cnfex) { errors.add(cnfex); } catch (NoClassDefFoundError ncdfe) { errors.add(ncdfe); } catch (UnsatisfiedLinkError ule) { errors.add(ule); } catch (Exception exception) { errors.add(exception); } catch (Error error) { errors.add(error); } } } } catch (IOException ioex) { errors.add(ioex); } } results.putAll(thisResult); Iterator<Class<?>> it = thisResult.keySet().iterator(); while (it.hasNext()) v.add(it.next()); return v; }
00
Code Sample 1: public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String url = request.getParameter("proxyurl"); URLConnection conn = new URL(url).openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); Enumeration params = request.getParameterNames(); boolean first = true; while (params.hasMoreElements()) { String param = (String) params.nextElement(); if (!param.equals("proxyurl")) { if (first) { first = false; } else { dos.writeBytes("&"); } dos.writeBytes(URLEncoder.encode(param)); dos.writeBytes("="); dos.writeBytes(URLEncoder.encode(request.getParameter(param))); } } dos.close(); Reader in = new InputStreamReader(conn.getInputStream(), response.getCharacterEncoding()); response.setContentType(conn.getContentType()); response.setContentLength(conn.getContentLength()); Writer out = response.getWriter(); char[] buf = new char[256]; int len; while ((len = in.read(buf)) != -1) { out.write(buf, 0, len); } in.close(); out.close(); String log = request.getParameter("logging"); if (log != null && log.toLowerCase().equals("true")) logRequest(request); } Code Sample 2: public Element rootFromURL(URL url) throws org.jdom.JDOMException, java.io.IOException { Element e; try { InputStream stream = new BufferedInputStream(url.openConnection().getInputStream()); return getRootViaURI(verify, stream); } catch (org.jdom.input.JDOMParseException e4) { throw e4; } catch (org.jdom.JDOMException e1) { if (!openWarn1) reportError1(url.toString(), e1); openWarn1 = true; try { InputStream stream = new BufferedInputStream(url.openConnection().getInputStream()); e = getRootViaURL(verify, stream); log.info("getRootViaURL succeeded as 2nd try"); return e; } catch (org.jdom.JDOMException e2) { if (!openWarn2) reportError2(url.toString(), e2); openWarn2 = true; InputStream stream = new BufferedInputStream(url.openConnection().getInputStream()); e = getRootViaRelative(verify, stream); log.info("GetRootViaRelative succeeded as 3rd try"); new Exception().printStackTrace(); return e; } } }
00
Code Sample 1: public void testReaderWriterUC2() throws Exception { String inFile = "test_data/mri.png"; String outFile = "test_output/mri__smooth_testReaderWriter.png"; itkImageFileReaderUC2_Pointer reader = itkImageFileReaderUC2.itkImageFileReaderUC2_New(); itkImageFileWriterUC2_Pointer writer = itkImageFileWriterUC2.itkImageFileWriterUC2_New(); reader.SetFileName(inFile); writer.SetFileName(outFile); writer.SetInput(reader.GetOutput()); writer.Update(); } Code Sample 2: private Properties loadDefaultProperties() throws IOException { Properties merged = new Properties(); try { merged.setProperty("user", System.getProperty("user.name")); } catch (java.lang.SecurityException se) { } ClassLoader cl = getClass().getClassLoader(); if (cl == null) cl = ClassLoader.getSystemClassLoader(); if (cl == null) { logger.debug("Can't find a classloader for the Driver; not loading driver configuration"); return merged; } logger.debug("Loading driver configuration via classloader " + cl); ArrayList urls = new ArrayList(); Enumeration urlEnum = cl.getResources("org/postgresql/driverconfig.properties"); while (urlEnum.hasMoreElements()) { urls.add(urlEnum.nextElement()); } for (int i = urls.size() - 1; i >= 0; i--) { URL url = (URL) urls.get(i); logger.debug("Loading driver configuration from: " + url); InputStream is = url.openStream(); merged.load(is); is.close(); } return merged; }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: private static void recurseFiles(File root, File file, TarArchiveOutputStream taos, boolean absolute) throws IOException { if (file.isDirectory()) { File[] files = file.listFiles(); for (File file2 : files) { recurseFiles(root, file2, taos, absolute); } } else if ((!file.getName().endsWith(".tar")) && (!file.getName().endsWith(".TAR"))) { String filename = null; if (absolute) { filename = file.getAbsolutePath().substring(root.getAbsolutePath().length()); } else { filename = file.getName(); } TarArchiveEntry tae = new TarArchiveEntry(filename); tae.setSize(file.length()); taos.putArchiveEntry(tae); FileInputStream fis = new FileInputStream(file); IOUtils.copy(fis, taos); taos.closeArchiveEntry(); } }
11
Code Sample 1: public static String fetchURL(final String u) { String retStr = ""; try { final URL url = new URL(u); final BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { retStr += line; } reader.close(); } catch (final MalformedURLException e) { logger.severe("MalformedURLException calling url" + e.getMessage()); } catch (final IOException e) { logger.severe("IOException calling url" + e.getMessage()); } return retStr; } Code Sample 2: public List<DemandeChargement> getArtistToLoadFromWiki() throws Exception { URL fileURL = new URL("http://beastchild.free.fr/wiki/doku.php?id=music"); URLConnection urlConnection = fileURL.openConnection(); InputStream httpStream = urlConnection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(httpStream, "ISO-8859-1")); String ligne; List<DemandeChargement> dem = new ArrayList<DemandeChargement>(); while ((ligne = br.readLine()) != null) { if (ligne.indexOf("&lt;@@@&gt;") != -1) { String maidS = ligne.substring(ligne.indexOf("&lt;@@@&gt;") + 11, ligne.indexOf("&lt;/@@@&gt;")).trim(); try { long maid = Long.parseLong(maidS); log.info("MAID to load : " + maid); dem.add(new DemandeChargement(maid)); } catch (Exception e) { log.error("Impossible de recuperer le MAID : " + maidS); } } } br.close(); httpStream.close(); return dem; }
11
Code Sample 1: public static String generateHash(String string, String algoritmo) { try { MessageDigest md = MessageDigest.getInstance(algoritmo); md.update(string.getBytes()); byte[] result = md.digest(); int firstPart; int lastPart; StringBuilder sBuilder = new StringBuilder(); for (int i = 0; i < result.length; i++) { firstPart = ((result[i] >> 4) & 0xf) << 4; lastPart = result[i] & 0xf; if (firstPart == 0) sBuilder.append("0"); sBuilder.append(Integer.toHexString(firstPart | lastPart)); } return sBuilder.toString(); } catch (NoSuchAlgorithmException ex) { return null; } } Code Sample 2: private StringBuffer hashPassword(StringBuffer password, String mode) { MessageDigest m = null; StringBuffer hash = new StringBuffer(); try { m = MessageDigest.getInstance(mode); m.update(password.toString().getBytes("UTF8")); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] digest = m.digest(); for (int i = 0; i < digest.length; i++) { String hex = Integer.toHexString(digest[i]); if (hex.length() == 1) hex = "0" + hex; hex = hex.substring(hex.length() - 2); hash.append(hex); } return hash; }
00
Code Sample 1: public String fetchContent(PathObject file) throws NetworkException { if (file.isFetched()) { return file.getContent(); } if (!"f".equals(file.getType())) { return null; } HttpClient client = HttpConfig.newInstance(); HttpGet get = new HttpGet(HttpConfig.bbsURL() + HttpConfig.BBS_ANC + file.getPath()); try { HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); Document doc = XmlOperator.readDocument(entity.getContent()); return BBSBodyParseHelper.parsePathContent(doc, file); } catch (Exception e) { e.printStackTrace(); throw new NetworkException(e); } } Code Sample 2: public static Vector getVectorForm(String u, String usr, String pwd) { Vector response = new Vector(); logger.debug("Attempting to call: " + u); logger.debug("Creating Authenticator: usr=" + usr + ", pwd=" + pwd); Authenticator.setDefault(new CustomAuthenticator(usr, pwd)); try { URL url = new URL(u); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { response.add(str); } in.close(); logger.debug("Response: " + response.toString()); } catch (MalformedURLException e) { logger.error(e); logger.trace(e, e); } catch (IOException e) { logger.error(e); logger.trace(e, e); } return response; }
00
Code Sample 1: public static int sendButton(String url, String id, String command) throws ClientProtocolException, IOException { String connectString = url + "/rest/button/" + id + "/" + command; HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(connectString); HttpResponse response = client.execute(post); int code = response.getStatusLine().getStatusCode(); return code; } Code Sample 2: @Override public User createUser(User bean) throws SitoolsException { checkUser(); if (!User.isValid(bean)) { throw new SitoolsException("CREATE_USER_MALFORMED"); } Connection cx = null; try { cx = ds.getConnection(); cx.setAutoCommit(false); PreparedStatement st = cx.prepareStatement(jdbcStoreResource.CREATE_USER); int i = 1; st.setString(i++, bean.getIdentifier()); st.setString(i++, bean.getFirstName()); st.setString(i++, bean.getLastName()); st.setString(i++, bean.getSecret()); st.setString(i++, bean.getEmail()); st.executeUpdate(); st.close(); createProperties(bean, cx); if (!cx.getAutoCommit()) { cx.commit(); } } catch (SQLException e) { try { cx.rollback(); } catch (SQLException e1) { e1.printStackTrace(); throw new SitoolsException("CREATE_USER ROLLBACK" + e1.getMessage(), e1); } e.printStackTrace(); throw new SitoolsException("CREATE_USER " + e.getMessage(), e); } finally { closeConnection(cx); } return getUserById(bean.getIdentifier()); }
11
Code Sample 1: public static void copyFile(File src, File dest) throws IOException { if (!src.exists()) throw new IOException("File not found '" + src.getAbsolutePath() + "'"); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(src)); byte[] read = new byte[128]; int len = 128; while ((len = in.read(read)) > 0) out.write(read, 0, len); out.flush(); out.close(); in.close(); } Code Sample 2: public void downloadTranslationsAndReload() { File languages = new File(this.translationsFile); try { URL languageURL = new URL(languageServer); InputStream is = languageURL.openStream(); OutputStream os = new FileOutputStream(languages); byte[] read = new byte[512000]; int bytesRead = 0; do { bytesRead = is.read(read); if (bytesRead > 0) { os.write(read, 0, bytesRead); } } while (bytesRead > 0); is.close(); os.close(); this.loadTranslations(); } catch (Exception e) { System.err.println("Remote languages file not found!"); if (languages.exists()) { try { XMLDecoder loader = new XMLDecoder(new FileInputStream(languages)); this.languages = (Hashtable) loader.readObject(); loader.close(); } catch (Exception ex) { ex.printStackTrace(); this.languages.put(naiveLanguage, new Hashtable()); } } else this.languages.put(naiveLanguage, new Hashtable()); } }
11
Code Sample 1: public boolean limpiarContrincantexRonda(jugadorxDivxRonda unjxdxr) { int intResult = 0; String sql = "UPDATE jugadorxdivxronda " + " SET idPareoRival = 0 " + " WHERE idJugxDivxRnd = " + unjxdxr.getIdJugxDivxRnd(); try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); intResult = ps.executeUpdate(); connection.commit(); } catch (SQLException ex) { ex.printStackTrace(); try { connection.rollback(); } catch (SQLException exe) { exe.printStackTrace(); } } finally { conexionBD.close(ps); conexionBD.close(connection); } return (intResult > 0); } Code Sample 2: public void rename(String virtualWiki, String oldTopicName, String newTopicName) throws Exception { Connection conn = DatabaseConnection.getConnection(); try { boolean commit = false; conn.setAutoCommit(false); try { PreparedStatement pstm = conn.prepareStatement(STATEMENT_RENAME); try { pstm.setString(1, newTopicName); pstm.setString(2, oldTopicName); pstm.setString(3, virtualWiki); if (pstm.executeUpdate() == 0) throw new SQLException("Unable to rename topic " + oldTopicName + " on wiki " + virtualWiki); } finally { pstm.close(); } doUnlockTopic(conn, virtualWiki, oldTopicName); doRenameAllVersions(conn, virtualWiki, oldTopicName, newTopicName); commit = true; } finally { if (commit) conn.commit(); else conn.rollback(); } } finally { conn.close(); } }
11
Code Sample 1: public static void copyFile(File src, File dest) throws IOException { log.debug("Copying file: '" + src + "' to '" + dest + "'"); FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } Code Sample 2: public static void createModelZip(String filename, String tempdir, boolean overwrite) throws Exception { FileTools.checkOutput(filename, overwrite); BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream(filename); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); int BUFFER = 2048; byte data[] = new byte[BUFFER]; File f = new File(tempdir); for (File fs : f.listFiles()) { FileInputStream fi = new FileInputStream(fs.getAbsolutePath()); origin = new BufferedInputStream(fi, BUFFER); ZipEntry entry = new ZipEntry(fs.getName()); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) out.write(data, 0, count); out.closeEntry(); origin.close(); } out.close(); }
11
Code Sample 1: public void testSystemPropertyConnector() throws Exception { final String rootFolderPath = "test/ConnectorTest/fs/".toLowerCase(); final Connector connector = new SystemPropertyConnector(); final ContentResolver contentResolver = new UnionContentResolver(); final FSContentResolver fsContentResolver = new FSContentResolver(); fsContentResolver.setRootFolderPath(rootFolderPath); contentResolver.addContentResolver(fsContentResolver); contentResolver.addContentResolver(new ClasspathContentResolver()); connector.setContentResolver(contentResolver); String resultString; byte[] resultContent; Object resultObject; resultString = connector.getString("helloWorldPath"); assertNull(resultString); resultContent = connector.getContent("helloWorldPath"); assertNull(resultContent); resultObject = connector.getObject("helloWorldPath"); assertNull(resultObject); System.setProperty("helloWorldPath", "org/settings4j/connector/HelloWorld2.txt"); resultString = connector.getString("helloWorldPath"); assertNotNull(resultString); assertEquals("org/settings4j/connector/HelloWorld2.txt", resultString); resultContent = connector.getContent("helloWorldPath"); assertNotNull(resultContent); assertEquals("Hello World 2", new String(resultContent, "UTF-8")); resultObject = connector.getObject("helloWorldPath"); assertNull(resultObject); System.setProperty("helloWorldPath", "file:org/settings4j/connector/HelloWorld2.txt"); resultString = connector.getString("helloWorldPath"); assertNotNull(resultString); assertEquals("file:org/settings4j/connector/HelloWorld2.txt", resultString); resultContent = connector.getContent("helloWorldPath"); assertNull(resultObject); resultObject = connector.getObject("helloWorldPath"); assertNull(resultObject); System.setProperty("helloWorldPath", "classpath:org/settings4j/connector/HelloWorld2.txt"); resultString = connector.getString("helloWorldPath"); assertNotNull(resultString); assertEquals("classpath:org/settings4j/connector/HelloWorld2.txt", resultString); resultContent = connector.getContent("helloWorldPath"); assertNotNull(resultContent); assertEquals("Hello World 2", new String(resultContent, "UTF-8")); resultObject = connector.getObject("helloWorldPath"); assertNull(resultObject); final InputStream helloWorldIS = new ByteArrayInputStream("Hello World 2 - Test".getBytes("UTF-8")); FileUtils.forceMkdir(new File(rootFolderPath + "/org/settings4j/connector")); final String helloWorldPath = rootFolderPath + "/org/settings4j/connector/HelloWorld2.txt"; final FileOutputStream fileOutputStream = new FileOutputStream(new File(helloWorldPath)); IOUtils.copy(helloWorldIS, fileOutputStream); IOUtils.closeQuietly(helloWorldIS); IOUtils.closeQuietly(fileOutputStream); LOG.info("helloWorld2Path: " + helloWorldPath); System.setProperty("helloWorldPath", "file:org/settings4j/connector/HelloWorld2.txt"); resultString = connector.getString("helloWorldPath"); assertNotNull(resultString); assertEquals("file:org/settings4j/connector/HelloWorld2.txt", resultString); resultContent = connector.getContent("helloWorldPath"); assertNotNull(resultContent); assertEquals("Hello World 2 - Test", new String(resultContent, "UTF-8")); resultObject = connector.getObject("helloWorldPath"); assertNull(resultObject); System.setProperty("helloWorldPath", "org/settings4j/connector/HelloWorld2.txt"); resultString = connector.getString("helloWorldPath"); assertNotNull(resultString); assertEquals("org/settings4j/connector/HelloWorld2.txt", resultString); resultContent = connector.getContent("helloWorldPath"); resultContent = connector.getContent("helloWorldPath"); assertNotNull(resultContent); assertEquals("Hello World 2 - Test", new String(resultContent, "UTF-8")); resultObject = connector.getObject("helloWorldPath"); assertNull(resultObject); System.setProperty("helloWorldPath", "classpath:org/settings4j/connector/HelloWorld2.txt"); resultString = connector.getString("helloWorldPath"); assertNotNull(resultString); assertEquals("classpath:org/settings4j/connector/HelloWorld2.txt", resultString); resultContent = connector.getContent("helloWorldPath"); assertNotNull(resultContent); assertEquals("Hello World 2", new String(resultContent, "UTF-8")); resultObject = connector.getObject("helloWorldPath"); assertNull(resultObject); } Code Sample 2: public void actionPerformed(ActionEvent e) { if (path.compareTo("") != 0) { imageName = (path.substring(path.lastIndexOf(imageFile.separator) + 1, path.length())); File imageFile = new File(path); directoryPath = "Images" + imageFile.separator + imageName.substring(0, 1).toUpperCase(); File directory = new File(directoryPath); directory.mkdirs(); imagePath = "." + imageFile.separator + "Images" + imageFile.separator + imageName.substring(0, 1).toUpperCase() + imageFile.separator + imageName; File newFile = new File(imagePath); int i = 1; while (newFile.exists()) { imagePath = "." + imageFile.separator + "Images" + imageFile.separator + imageName.substring(0, imageName.lastIndexOf('.')) + "_" + i + imageName.substring(imageName.lastIndexOf('.'), imageName.length()); newFile = new File(imagePath); i++; } imagePathThumb = (imagePath.substring(0, imagePath.lastIndexOf("."))).concat("_th.jpg"); dataBase.insertDB(theConcepts, imageName, imageName.substring(0, imageName.lastIndexOf('.'))); try { FileChannel srcChannel = new FileInputStream(path).getChannel(); FileChannel dstChannel = new FileOutputStream(imagePath).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } image = null; if (imageFile != null) { if (TFileUtils.isJAIRequired(imageFile)) { RenderedOp src = JAI.create("fileload", imageFile.getAbsolutePath()); BufferedImage bufferedImage = src.getAsBufferedImage(); image = new ImageIcon(bufferedImage); } else { image = new ImageIcon(imageFile.getAbsolutePath()); } if (image.getImageLoadStatus() == MediaTracker.ERRORED) { int choosenOption = JOptionPane.NO_OPTION; choosenOption = JOptionPane.showConfirmDialog(null, TLanguage.getString("TIGInsertImageAction.MESSAGE"), TLanguage.getString("TIGInsertImageAction.NAME"), JOptionPane.CLOSED_OPTION, JOptionPane.ERROR_MESSAGE); } else { try { int thumbWidth = PREVIEW_WIDTH; int thumbHeight = PREVIEW_HEIGHT; double thumbRatio = (double) thumbWidth / (double) thumbHeight; int imageWidth = image.getIconWidth(); int imageHeight = image.getIconHeight(); double imageRatio = (double) imageWidth / (double) imageHeight; if (thumbRatio < imageRatio) { thumbHeight = (int) (thumbWidth / imageRatio); } else { thumbWidth = (int) (thumbHeight * imageRatio); } BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = thumbImage.createGraphics(); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.drawImage(image.getImage(), 0, 0, thumbWidth, thumbHeight, null); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(imagePathThumb)); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage); int quality = 100; quality = Math.max(0, Math.min(quality, 100)); param.setQuality((float) quality / 100.0f, false); encoder.setJPEGEncodeParam(param); encoder.encode(thumbImage); out.close(); } catch (Exception ex) { System.out.println(ex.getMessage()); System.out.println(ex.toString()); } } } } }
00
Code Sample 1: private void parseUrl() { URLLexer lexer; URLParser parser; if (this.parent != null) { this.hops = ((HTTPFile) this.parent).hops - 1; } if (this.searchFilter.accept(this.url.getPath())) { if (!visited.contains(this.url.toExternalForm())) { if (this.hops > 0) { try { visited.add(this.url.toExternalForm()); InputStream in = this.url.openStream(); lexer = new URLLexer(this.url.openStream()); parser = new URLParser(lexer); URL[] urls = parser.htmlDocument(this.url); if (Debug.debug) { Debug.getInstance().info(this.getClass().getName() + ".parseUrl(): Found the following URLs in " + this.url.toExternalForm() + " : " + StringUtil.ArrayToString(urls, 10)); } for (int i = 0; i < urls.length; i++) { this.addInternal(urls[i]); } } catch (IOException e) { if (Debug.debug) { Debug.getInstance().error(e.getMessage()); } } catch (RecognitionException e) { if (Debug.debug) { Debug.getInstance().error("Problems while lexing " + this.url.toExternalForm() + " : " + e.getMessage(), e); } } catch (TokenStreamException e) { if (Debug.debug) { Debug.getInstance().error("Problems while parsing " + this.url.toExternalForm() + " : " + e.getMessage(), e); } } } } else { if (Debug.debug) { Debug.getInstance().info(this.getClass().getName() + ".parseUrl(): Skipping URL " + this.url.toExternalForm() + " : Maximum depth reached."); } } } else { if (Debug.debug) { Debug.getInstance().info(this.getClass().getName() + ".parseUrl(): Skipping URL " + this.url.toExternalForm() + " : Already parsed."); } } } Code Sample 2: public boolean setDeleteCliente(int IDcliente) { boolean delete = false; try { stm = conexion.prepareStatement("delete clientes where IDcliente='" + IDcliente + "'"); stm.executeUpdate(); conexion.commit(); delete = true; } catch (SQLException e) { System.out.println("Error en la eliminacion del registro en tabla clientes " + e.getMessage()); try { conexion.rollback(); } catch (SQLException ee) { System.out.println(ee.getMessage()); } return delete = false; } return delete; }
00
Code Sample 1: private Properties loadDefaultProperties() throws IOException { Properties merged = new Properties(); try { merged.setProperty("user", System.getProperty("user.name")); } catch (java.lang.SecurityException se) { } ClassLoader cl = getClass().getClassLoader(); if (cl == null) cl = ClassLoader.getSystemClassLoader(); if (cl == null) { logger.debug("Can't find a classloader for the Driver; not loading driver configuration"); return merged; } logger.debug("Loading driver configuration via classloader " + cl); ArrayList urls = new ArrayList(); Enumeration urlEnum = cl.getResources("org/postgresql/driverconfig.properties"); while (urlEnum.hasMoreElements()) { urls.add(urlEnum.nextElement()); } for (int i = urls.size() - 1; i >= 0; i--) { URL url = (URL) urls.get(i); logger.debug("Loading driver configuration from: " + url); InputStream is = url.openStream(); merged.load(is); is.close(); } return merged; } Code Sample 2: public boolean checkTypeChange(Class<?> clazz, File buildDir, File refFile) throws MojoExecutionException { if (!clazz.isPrimitive()) { ClassLoader cl = clazz.getClassLoader(); if (cl == loader) { if (clazz.isArray()) return checkTypeChange(getArrayType(clazz), buildDir, refFile); String path = clazz.getName().replace('.', File.separatorChar) + ".class"; File file = new File(buildDir, path); long lastMod = Long.MAX_VALUE; if (!file.exists()) { URL url = cl.getResource(path); if (url == null) throw new MojoExecutionException("Can't get URL for webservice class '" + clazz.getName() + "' from jar file."); else { try { JarURLConnection con = (JarURLConnection) url.openConnection(); lastMod = con.getJarEntry().getTime(); } catch (IOException x) { throw new MojoExecutionException("Can't get modification time for webservice class '" + clazz.getName() + "' from jar file."); } } } else { lastMod = file.lastModified(); } if (refFile.lastModified() < lastMod) return true; if (clazz.isInterface()) { Class<?>[] itfs = clazz.getInterfaces(); for (int i = 0; i < itfs.length; i++) { boolean changed = checkTypeChange(itfs[i], buildDir, refFile); if (changed) return true; } } else { Class<?> sup = clazz.getSuperclass(); boolean changed = checkTypeChange(sup, buildDir, refFile); if (changed) return true; } } } return false; }
11
Code Sample 1: private static void copyFile(File source, File dest, boolean visibleFilesOnly) throws IOException { if (visibleFilesOnly && isHiddenOrDotFile(source)) { return; } if (dest.exists()) { System.err.println("Destination File Already Exists: " + dest); } FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } Code Sample 2: public void concatFiles() throws IOException { Writer writer = null; try { final File targetFile = new File(getTargetDirectory(), getTargetFile()); targetFile.getParentFile().mkdirs(); if (null != getEncoding()) { getLog().info("Writing aggregated file with encoding '" + getEncoding() + "'"); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile), getEncoding())); } else { getLog().info("WARNING: writing aggregated file with system encoding"); writer = new FileWriter(targetFile); } for (File file : getFiles()) { Reader reader = null; try { if (null != getEncoding()) { getLog().info("Reading file " + file.getCanonicalPath() + " with encoding '" + getEncoding() + "'"); reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), getEncoding())); } else { getLog().info("WARNING: Reading file " + file.getCanonicalPath() + " with system encoding"); reader = new FileReader(file); } IOUtils.copy(reader, writer); final String delimiter = getDelimiter(); if (delimiter != null) { writer.write(delimiter.toCharArray()); } } finally { IOUtils.closeQuietly(reader); } } } finally { IOUtils.closeQuietly(writer); } }
00
Code Sample 1: public int extractDocumentsInternal(DocumentHolder holder, DocumentFactory docFactory) { FTPClient client = new FTPClient(); try { client.connect(site, port == 0 ? 21 : port); client.login(user, password); visitDirectory(client, "", path, holder, docFactory); client.disconnect(); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { } return fileCount; } Code Sample 2: public void load(URL urlin) throws IOException { index = hs.getDoIndex(); loaded = false; url = urlin; int c, i; htmlDocLength = 0; HtmlReader in = new HtmlReader(new InputStreamReader(url.openStream(), charset)); try { if (debug >= 2) System.out.print("Loading " + urlin.toString() + " ... "); while ((c = in.read()) >= 0) { htmlDoc[htmlDocLength++] = (char) (c); if (htmlDocLength == htmlDocMaxLength) { char[] newHtmlDoc = new char[2 * htmlDocMaxLength]; System.arraycopy(htmlDoc, 0, newHtmlDoc, 0, htmlDocMaxLength); htmlDocMaxLength = 2 * htmlDocMaxLength; htmlDoc = newHtmlDoc; } } if (debug >= 2) System.out.println("done."); } catch (ArrayIndexOutOfBoundsException aioobe) { if (debug >= 1) System.out.println("Error, reading file into memory (too big) - skipping " + urlin.toString()); loaded = false; return; } in.close(); fetchURLpos = 0; dumpPos = 0; dumpLastChar = SPACE; loaded = true; frameset = false; titledone = false; headdone = false; checkhead = false; checkbody = false; }
11
Code Sample 1: public void downSync(Vector v) throws SQLException { try { con = allocateConnection(tableName); PreparedStatement update = con.prepareStatement("update cal_Event set owner=?,subject=?,text=?,place=?," + "contactperson=?,startdate=?,enddate=?,starttime=?,endtime=?,allday=?," + "syncstatus=?,dirtybits=? where OId=? and syncstatus=?"); PreparedStatement insert = con.prepareStatement("insert into cal_Event (owner,subject,text,place," + "contactperson,startdate,enddate,starttime,endtime,allday,syncstatus," + "dirtybits) values(?,?,?,?,?,?,?,?,?,?,?,?)"); PreparedStatement insert1 = con.prepareStatement(DBUtil.getQueryCurrentOID(con, "cal_Event", "newoid")); PreparedStatement delete1 = con.prepareStatement("delete from cal_Event_Remind where event=?"); PreparedStatement delete2 = con.prepareStatement("delete from cal_Event where OId=? " + "and (syncstatus=? or syncstatus=?)"); for (int i = 0; i < v.size(); i++) { try { DO = (EventDO) v.elementAt(i); if (DO.getSyncstatus() == INSERT) { insert.setBigDecimal(1, DO.getOwner()); insert.setString(2, DO.getSubject()); insert.setString(3, DO.getText()); insert.setString(4, DO.getPlace()); insert.setString(5, DO.getContactperson()); insert.setDate(6, DO.getStartdate()); insert.setDate(7, DO.getEnddate()); insert.setTime(8, DO.getStarttime()); insert.setTime(9, DO.getEndtime()); insert.setBoolean(10, DO.getAllday()); insert.setInt(11, RESET); insert.setInt(12, RESET); con.executeUpdate(insert, null); con.reset(); rs = con.executeQuery(insert1, null); if (rs.next()) DO.setOId(rs.getBigDecimal("newoid")); con.reset(); } else if (DO.getSyncstatus() == UPDATE) { update.setBigDecimal(1, DO.getOwner()); update.setString(2, DO.getSubject()); update.setString(3, DO.getText()); update.setString(4, DO.getPlace()); update.setString(5, DO.getContactperson()); update.setDate(6, DO.getStartdate()); update.setDate(7, DO.getEnddate()); update.setTime(8, DO.getStarttime()); update.setTime(9, DO.getEndtime()); update.setBoolean(10, DO.getAllday()); update.setInt(11, RESET); update.setInt(12, RESET); update.setBigDecimal(13, DO.getOId()); update.setInt(14, RESET); con.executeUpdate(update, null); con.reset(); } else if (DO.getSyncstatus() == DELETE) { try { con.setAutoCommit(false); delete1.setBigDecimal(1, DO.getOId()); con.executeUpdate(delete1, null); delete2.setBigDecimal(1, DO.getOId()); delete2.setInt(2, RESET); delete2.setInt(3, DELETE); if (con.executeUpdate(delete2, null) < 1) { con.rollback(); } else { con.commit(); } } catch (Exception e) { con.rollback(); throw e; } finally { con.reset(); } } } catch (Exception e) { if (DO != null) logError("Sync-EventDO.owner = " + DO.getOwner().toString() + " oid = " + (DO.getOId() != null ? DO.getOId().toString() : "NULL"), e); } } if (rs != null) { rs.close(); } } catch (SQLException e) { if (DEBUG) logError("", e); throw e; } finally { release(); } } Code Sample 2: public void delUser(User user) throws SQLException, IOException, ClassNotFoundException { String dbUserID; String stockSymbol; Statement stmt = con.createStatement(); try { con.setAutoCommit(false); dbUserID = user.getUserID(); if (getUser(dbUserID) != null) { ResultSet rs1 = stmt.executeQuery("SELECT userID, symbol " + "FROM UserStocks WHERE userID = '" + dbUserID + "'"); while (rs1.next()) { try { stockSymbol = rs1.getString("symbol"); delUserStocks(dbUserID, stockSymbol); } catch (SQLException ex) { throw new SQLException("Deletion of user stock holding failed: " + ex.getMessage()); } } try { stmt.executeUpdate("DELETE FROM Users WHERE " + "userID = '" + dbUserID + "'"); } catch (SQLException ex) { throw new SQLException("User deletion failed: " + ex.getMessage()); } } else throw new IOException("User not found in database - cannot delete."); try { con.commit(); } catch (SQLException ex) { throw new SQLException("Transaction commit failed: " + ex.getMessage()); } } catch (SQLException ex) { try { con.rollback(); } catch (SQLException sqx) { throw new SQLException("Transaction failed then rollback failed: " + sqx.getMessage()); } throw new SQLException("Transaction failed; was rolled back: " + ex.getMessage()); } stmt.close(); }
11
Code Sample 1: public void init() throws Exception { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); int code = conn.getResponseCode(); if (code != 200) throw new IOException("Error fetching robots.txt; respose code is " + code); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String buff; StringBuilder builder = new StringBuilder(); while ((buff = reader.readLine()) != null) builder.append(buff); parseRobots(builder.toString()); } Code Sample 2: private String doExecute(AbortableHttpRequest method) throws Throwable { HttpClient client = CLIENT.newInstance(); HttpResponse rsp = client.execute((HttpUriRequest) method); HttpEntity entity = rsp.getEntity(); if (entity == null) throw new RequestError("No entity in method"); InputStream in = null; try { in = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder inStr = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { inStr.append(line).append("\r\n"); } entity.consumeContent(); return inStr.toString(); } catch (IOException ex) { LOG.error("IO exception: " + ex.getMessage()); throw ex; } catch (RuntimeException ex) { method.abort(); throw ex; } finally { if (in != null) in.close(); } }
11
Code Sample 1: public static void main(String[] args) { String WTKdir = null; String sourceFile = null; String instrFile = null; String outFile = null; String jadFile = null; Manifest mnf; if (args.length == 0) { usage(); return; } int i = 0; while (i < args.length && args[i].startsWith("-")) { if (("-WTK".equals(args[i])) && (i < args.length - 1)) { i++; WTKdir = args[i]; } else if (("-source".equals(args[i])) && (i < args.length - 1)) { i++; sourceFile = args[i]; } else if (("-instr".equals(args[i])) && (i < args.length - 1)) { i++; instrFile = args[i]; } else if (("-o".equals(args[i])) && (i < args.length - 1)) { i++; outFile = args[i]; } else if (("-jad".equals(args[i])) && (i < args.length - 1)) { i++; jadFile = args[i]; } else { System.out.println("Error: Unrecognized option: " + args[i]); System.exit(0); } i++; } if (WTKdir == null || sourceFile == null || instrFile == null) { System.out.println("Error: Missing parameter!!!"); usage(); return; } if (outFile == null) outFile = sourceFile; FileInputStream fisJar; try { fisJar = new FileInputStream(sourceFile); } catch (FileNotFoundException e1) { System.out.println("Cannot find source jar file: " + sourceFile); e1.printStackTrace(); return; } FileOutputStream fosJar; File aux = null; try { aux = File.createTempFile("predef", "aux"); fosJar = new FileOutputStream(aux); } catch (IOException e1) { System.out.println("Cannot find temporary jar file: " + aux); e1.printStackTrace(); return; } JarFile instrJar = null; Enumeration en = null; File tempDir = null; try { instrJar = new JarFile(instrFile); en = instrJar.entries(); tempDir = File.createTempFile("jbtp", ""); tempDir.delete(); System.out.println("Create directory: " + tempDir.mkdirs()); tempDir.deleteOnExit(); } catch (IOException e) { System.out.println("Cannot open instrumented file: " + instrFile); e.printStackTrace(); return; } String[] wtklib = new java.io.File(WTKdir + File.separator + "lib").list(new OnlyJar()); String preverifyCmd = WTKdir + File.separator + "bin" + File.separator + "preverify -classpath " + WTKdir + File.separator + "lib" + File.separator + CLDC_JAR + File.pathSeparator + WTKdir + File.separator + "lib" + File.separator + MIDP_JAR + File.pathSeparator + WTKdir + File.separator + "lib" + File.separator + WMA_JAR + File.pathSeparator + instrFile; for (int k = 0; k < wtklib.length; k++) { preverifyCmd += File.pathSeparator + WTKdir + File.separator + "lib" + wtklib[k]; } preverifyCmd += " " + "-d " + tempDir.getAbsolutePath() + " "; while (en.hasMoreElements()) { JarEntry je = (JarEntry) en.nextElement(); String jeName = je.getName(); if (jeName.endsWith(".class")) jeName = jeName.substring(0, jeName.length() - 6); preverifyCmd += jeName + " "; } try { Process p = Runtime.getRuntime().exec(preverifyCmd); if (p.waitFor() != 0) { BufferedReader in = new BufferedReader(new InputStreamReader(p.getErrorStream())); System.out.println("Error calling the preverify command."); while (in.ready()) { System.out.print("" + in.readLine()); } System.out.println(); in.close(); return; } } catch (Exception e) { System.out.println("Cannot execute preverify command"); e.printStackTrace(); return; } File[] listOfFiles = computeFiles(tempDir); System.out.println("-------------------------------\n" + "Files to insert: "); String[] strFiles = new String[listOfFiles.length]; int l = tempDir.toString().length() + 1; for (int j = 0; j < listOfFiles.length; j++) { strFiles[j] = listOfFiles[j].toString().substring(l); strFiles[j] = strFiles[j].replace(File.separatorChar, '/'); System.out.println(strFiles[j]); } System.out.println("-------------------------------"); try { JarInputStream jis = new JarInputStream(fisJar); mnf = jis.getManifest(); JarOutputStream jos = new JarOutputStream(fosJar, mnf); nextJar: for (JarEntry je = jis.getNextJarEntry(); je != null; je = jis.getNextJarEntry()) { String s = je.getName(); for (int k = 0; k < strFiles.length; k++) { if (strFiles[k].equals(s)) continue nextJar; } jos.putNextEntry(je); byte[] b = new byte[512]; for (int k = jis.read(b, 0, 512); k >= 0; k = jis.read(b, 0, 512)) { jos.write(b, 0, k); } } jis.close(); for (int j = 0; j < strFiles.length; j++) { FileInputStream fis = new FileInputStream(listOfFiles[j]); JarEntry je = new JarEntry(strFiles[j]); jos.putNextEntry(je); byte[] b = new byte[512]; while (fis.available() > 0) { int k = fis.read(b, 0, 512); jos.write(b, 0, k); } fis.close(); } jos.close(); fisJar.close(); fosJar.close(); } catch (IOException e) { System.out.println("Cannot read/write jar file."); e.printStackTrace(); return; } try { FileOutputStream fos = new FileOutputStream(outFile); FileInputStream fis = new FileInputStream(aux); byte[] b = new byte[512]; while (fis.available() > 0) { int k = fis.read(b, 0, 512); fos.write(b, 0, k); } fis.close(); fos.close(); } catch (IOException e) { System.out.println("Cannot write output jar file: " + outFile); e.printStackTrace(); } Iterator it; Attributes atr; atr = mnf.getMainAttributes(); it = atr.keySet().iterator(); if (jadFile != null) { FileOutputStream fos; try { File outJarFile = new File(outFile); fos = new FileOutputStream(jadFile); PrintStream psjad = new PrintStream(fos); while (it.hasNext()) { Object ats = it.next(); psjad.println(ats + ": " + atr.get(ats)); } psjad.println("MIDlet-Jar-URL: " + outFile); psjad.println("MIDlet-Jar-Size: " + outJarFile.length()); fos.close(); } catch (IOException eio) { System.out.println("Cannot create jad file."); eio.printStackTrace(); } } } Code Sample 2: public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); }
00
Code Sample 1: @Test public void testXMLDBURLStreamHandler() { System.out.println("testXMLDBURLStreamHandler"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { URL url = new URL(XMLDB_URL_1); InputStream is = url.openStream(); copyDocument(is, baos); is.close(); } catch (Exception ex) { ex.printStackTrace(); LOG.error(ex); fail(ex.getMessage()); } } Code Sample 2: private JButton getButtonImagen() { if (buttonImagen == null) { buttonImagen = new JButton(); buttonImagen.setText(Messages.getString("gui.AdministracionResorces.6")); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/es/unizar/cps/tecnoDiscap/data/icons/view_sidetree.png"))); buttonImagen.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new ImageFilter()); fc.setAccessory(new ImagePreview(fc)); int returnVal = fc.showDialog(AdministracionResorces.this, Messages.getString("gui.AdministracionResorces.8")); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + "/" + rutaDatos + "imagenes/" + file.getName(); String rutaRelativa = rutaDatos + "imagenes/" + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); imagen.setImagenURL(rutaRelativa); gui.getEntrenamientoIzquierdaLabel().setIcon(gui.getProcesadorDatos().escalaImageIcon(((Imagen) gui.getComboBoxImagenesIzquierda().getSelectedItem()).getImagenURL())); gui.getEntrenamientoDerechaLabel().setIcon(gui.getProcesadorDatos().escalaImageIcon(((Imagen) gui.getComboBoxImagenesDerecha().getSelectedItem()).getImagenURL())); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/es/unizar/cps/tecnoDiscap/data/icons/view_sidetreeOK.png"))); labelImagenPreview.setIcon(gui.getProcesadorDatos().escalaImageIcon(imagen.getImagenURL())); } catch (IOException ex) { ex.printStackTrace(); } } else { } } }); } return buttonImagen; }
00
Code Sample 1: @Override public void login() { loginsuccessful = false; try { HttpParams params = new BasicHttpParams(); params.setParameter("http.useragent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6"); DefaultHttpClient httpclient = new DefaultHttpClient(params); NULogger.getLogger().info("Trying to log in to HotFile"); HttpPost httppost = new HttpPost("http://www.hotfile.com/login.php"); httppost.setHeader("Referer", "http://www.hotfile.com/"); httppost.setHeader("Cache-Control", "max-age=0"); httppost.setHeader("Origin", "http://www.hotfile.com/"); httppost.setHeader("Accept", "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("returnto", "%2F")); formparams.add(new BasicNameValuePair("user", getUsername())); formparams.add(new BasicNameValuePair("pass", getPassword())); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); httppost.setEntity(entity); HttpResponse httpresponse = httpclient.execute(httppost); if (httpresponse.getFirstHeader("Set-Cookie") == null) { NULogger.getLogger().info("HotFile Login not successful"); loginsuccessful = false; username = ""; password = ""; JOptionPane.showMessageDialog(NeembuuUploader.getInstance(), "<html><b>" + HOSTNAME + "</b> " + TranslationProvider.get("neembuuuploader.accounts.loginerror") + "</html>", HOSTNAME, JOptionPane.WARNING_MESSAGE); AccountsManager.getInstance().setVisible(true); } else { Iterator<Cookie> it = httpclient.getCookieStore().getCookies().iterator(); while (it.hasNext()) { hfcookie = it.next(); if (hfcookie.getName().equals("auth")) { NULogger.getLogger().log(Level.INFO, "hotfile login successful auth:{0}", hfcookie.getValue()); loginsuccessful = true; HostsPanel.getInstance().hotFileCheckBox.setEnabled(true); username = getUsername(); password = getPassword(); break; } } } } catch (Exception ex) { NULogger.getLogger().log(Level.SEVERE, "{0}: Error in Hotfile Login", getClass().getName()); } } Code Sample 2: public Texture loadTexture(String file) throws IOException { URL imageUrl = urlFactory.makeUrl(file); Texture cached = textureLoader.getImageFromCache(imageUrl); if (cached != null) return cached; Image image; if (zip) { ZipInputStream zis = new ZipInputStream(url.openStream()); ZipEntry entry; boolean found = false; while ((entry = zis.getNextEntry()) != null) { if (file.equals(entry.getName())) { found = true; break; } } if (!found) { throw new IOException("Cannot find file \"" + file + "\"."); } int extIndex = file.lastIndexOf('.'); if (extIndex == -1) { throw new IOException("Cannot parse file extension."); } String fileExt = file.substring(extIndex); image = TextureManager.loadImage(fileExt, zis, true); } else { image = TextureManager.loadImage(imageUrl, true); } return textureLoader.loadTexture(imageUrl, image); }
11
Code Sample 1: public static void copyFile5(File srcFile, File destFile) throws IOException { InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); IOUtils.copyLarge(in, out); in.close(); out.close(); } Code Sample 2: private boolean copyAvecProgressNIO(File sRC2, File dEST2, JProgressBar progressEnCours) throws IOException { boolean resultat = false; FileInputStream fis = new FileInputStream(sRC2); FileOutputStream fos = new FileOutputStream(dEST2); java.nio.channels.FileChannel channelSrc = fis.getChannel(); java.nio.channels.FileChannel channelDest = fos.getChannel(); progressEnCours.setValue(0); progressEnCours.setString(sRC2 + " : 0 %"); channelSrc.transferTo(0, channelSrc.size(), channelDest); progressEnCours.setValue(100); progressEnCours.setString(sRC2 + " : 100 %"); if (channelSrc.size() == channelDest.size()) { resultat = true; } else { resultat = false; } fis.close(); fos.close(); return (resultat); }
11
Code Sample 1: public void copyToCurrentDir(File _copyFile, String _fileName) throws IOException { File outputFile = new File(getCurrentPath() + File.separator + _fileName); FileReader in; FileWriter out; if (!outputFile.exists()) { outputFile.createNewFile(); } in = new FileReader(_copyFile); out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); reList(); } Code Sample 2: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String uuid = req.getParameterValues(Constants.PARAM_UUID)[0]; String datastream = null; if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_FOXML_PREFIX)) { resp.addHeader("Content-Disposition", "attachment; ContentType = \"text/xml\"; filename=\"" + uuid + "_server_version.foxml\""); } else { datastream = req.getParameterValues(Constants.PARAM_DATASTREAM)[0]; resp.addHeader("Content-Disposition", "attachment; ContentType = \"text/xml\"; filename=\"" + uuid + "_server_version_" + datastream + ".xml\""); } ServletOutputStream os = resp.getOutputStream(); if (uuid != null && !"".equals(uuid)) { try { StringBuffer sb = new StringBuffer(); if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_FOXML_PREFIX)) { sb.append(config.getFedoraHost()).append("/objects/").append(uuid).append("/objectXML"); } else if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_DATASTREAMS_PREFIX)) { sb.append(config.getFedoraHost()).append("/objects/").append(uuid).append("/datastreams/").append(datastream).append("/content"); } InputStream is = RESTHelper.get(sb.toString(), config.getFedoraLogin(), config.getFedoraPassword(), false); if (is == null) { return; } try { if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_DATASTREAMS_PREFIX)) { os.write(Constants.XML_HEADER_WITH_BACKSLASHES.getBytes()); } IOUtils.copyStreams(is, os); } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Problem with downloading foxml.", e); } finally { os.flush(); if (is != null) { try { is.close(); } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Problem with downloading foxml.", e); } finally { is = null; } } } } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Problem with downloading foxml.", e); } finally { os.flush(); } } }
11
Code Sample 1: public void testReadNormal() throws Exception { archiveFileManager.executeWith(new TemporaryFileExecutor() { public void execute(File temporaryFile) throws Exception { ZipArchive archive = new ZipArchive(temporaryFile.getPath()); InputStream input = archive.getInputFrom(ARCHIVE_FILE_1); if (input != null) { ByteArrayOutputStream output = new ByteArrayOutputStream(); IOUtils.copyAndClose(input, output); assertEquals(ARCHIVE_FILE_1 + " contents not correct", ARCHIVE_FILE_1_CONTENT, output.toString()); } else { fail("cannot open " + ARCHIVE_FILE_1); } } }); } Code Sample 2: public static void copy(File source, File dest) throws java.io.IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
00
Code Sample 1: void openTextFile(String urlString, boolean install) { StringBuffer sb = null; try { URL url = new URL(urlString); InputStream in = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); sb = new StringBuffer(); String line; while ((line = br.readLine()) != null) sb.append(line + "\n"); in.close(); } catch (IOException e) { if (!(install && urlString.endsWith("StartupMacros.txt"))) IJ.error("URL Opener", "" + e); sb = null; } if (sb != null) { if (install) (new MacroInstaller()).install(new String(sb)); else { int index = urlString.lastIndexOf("/"); if (index != -1 && index <= urlString.length() - 1) urlString = urlString.substring(index + 1); (new Editor()).create(urlString, new String(sb)); } } } Code Sample 2: public void sendMail() throws Exception { try { if (param.length > 0) { System.setProperty("mail.host", param[0].trim()); URL url = new URL("mailto:" + param[1].trim()); URLConnection conn = url.openConnection(); PrintWriter out = new PrintWriter(conn.getOutputStream(), true); out.print("To:" + param[1].trim() + "\n"); out.print("Subject: " + param[2] + "\n"); out.print("MIME-Version: 1.0\n"); out.print("Content-Type: multipart/mixed; boundary=\"tcppop000\"\n\n"); out.print("--tcppop000\n"); out.print("Content-Type: text/plain\n"); out.print("Content-Transfer-Encoding: 7bit\n\n\n"); out.print(param[3] + "\n\n\n"); out.print("--tcppop000\n"); String filename = param[4].trim(); int sep = filename.lastIndexOf(File.separator); if (sep > 0) { filename = filename.substring(sep + 1, filename.length()); } out.print("Content-Type: text/html; name=\"" + filename + "\"\n"); out.print("Content-Transfer-Encoding: binary\n"); out.print("Content-Disposition: attachment; filename=\"" + filename + "\"\n\n"); System.out.println("FOR ATTACHMENT Content-Transfer-Encoding: binary "); RandomAccessFile file = new RandomAccessFile(param[4].trim(), "r"); byte[] buffer = new byte[(int) file.length()]; file.readFully(buffer); file.close(); String fileContent = new String(buffer); out.print(fileContent); out.print("\n"); out.print("--tcppop000--"); out.close(); } else { } } catch (MalformedURLException e) { throw e; } catch (IOException e) { throw e; } }