label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: private void post(String title, Document content, Set<String> tags) throws HttpException, IOException, TransformerException { PostMethod method = null; try { method = new PostMethod("http://www.blogger.com/feeds/" + this.blogId + "/posts/default"); method.addRequestHeader("GData-Version", String.valueOf(GDataVersion)); method.addRequestHeader("Authorization", "GoogleLogin auth=" + this.AuthToken); Document dom = this.domBuilder.newDocument(); Element entry = dom.createElementNS(Atom.NS, "entry"); dom.appendChild(entry); entry.setAttribute("xmlns", Atom.NS); Element titleNode = dom.createElementNS(Atom.NS, "title"); entry.appendChild(titleNode); titleNode.setAttribute("type", "text"); titleNode.appendChild(dom.createTextNode(title)); Element contentNode = dom.createElementNS(Atom.NS, "content"); entry.appendChild(contentNode); contentNode.setAttribute("type", "xhtml"); contentNode.appendChild(dom.importNode(content.getDocumentElement(), true)); for (String tag : tags) { Element category = dom.createElementNS(Atom.NS, "category"); category.setAttribute("scheme", "http://www.blogger.com/atom/ns#"); category.setAttribute("term", tag); entry.appendChild(category); } StringWriter out = new StringWriter(); this.xml2ascii.transform(new DOMSource(dom), new StreamResult(out)); method.setRequestEntity(new StringRequestEntity(out.toString(), "application/atom+xml", "UTF-8")); int status = getHttpClient().executeMethod(method); if (status == 201) { IOUtils.copyTo(method.getResponseBodyAsStream(), System.out); } else { throw new HttpException("post returned http-code=" + status + " expected 201 (CREATE)"); } } catch (TransformerException err) { throw err; } catch (HttpException err) { throw err; } catch (IOException err) { throw err; } finally { if (method != null) method.releaseConnection(); } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: public URL rawGetURLfromWebID(String id) { try { System.out.println("Resolving id" + id); String resolve = "/webid/ResolverServlet?wpid=MeetingMachine&method=form&uri=" + id + "&href=_[text/url]"; String resolver = "http://webid.hpl.hp.com:5190"; URL url = new URL(resolve + resolver); URLConnection c = url.openConnection(); c.setDoOutput(true); c.setDoInput(true); c.setUseCaches(false); } catch (Exception e) { if (PropertyEventHeap.debug) { PropertyEventHeap.log("rawGetURLfromWebID " + e); } } return null; } Code Sample 2: public static <T extends Comparable<T>> void BubbleSortComparable1(T[] num) { int j; boolean flag = true; // set flag to true to begin first pass T temp; // holding variable while (flag) { flag = false; // set flag to false awaiting a possible swap for (j = 0; j < num.length - 1; j++) { if (num[j].compareTo(num[j + 1]) > 0) // change to > for ascending sort { temp = num[j]; // swap elements num[j] = num[j + 1]; num[j + 1] = temp; flag = true; // shows a swap occurred } } } }
11
Code Sample 1: @Test public void testTrainingDefault() throws IOException { File temp = File.createTempFile("fannj_", ".tmp"); temp.deleteOnExit(); IOUtils.copy(this.getClass().getResourceAsStream("xor.data"), new FileOutputStream(temp)); List<Layer> layers = new ArrayList<Layer>(); layers.add(Layer.create(2)); layers.add(Layer.create(3, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); layers.add(Layer.create(1, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); Fann fann = new Fann(layers); Trainer trainer = new Trainer(fann); float desiredError = .001f; float mse = trainer.train(temp.getPath(), 500000, 1000, desiredError); assertTrue("" + mse, mse <= desiredError); } Code Sample 2: private byte[] getBytes(String resource) throws IOException { InputStream is = HttpServletFileDownloadTest.class.getResourceAsStream(resource); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(is, out); IOUtils.closeQuietly(is); return out.toByteArray(); }
11
Code Sample 1: private void addPNMLFileToLibrary(File selected) { try { FileChannel srcChannel = new FileInputStream(selected.getAbsolutePath()).getChannel(); FileChannel dstChannel = new FileOutputStream(new File(matchingOrderXML).getParent() + "/" + selected.getName()).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); order.add(new ComponentDescription(false, selected.getName().replaceAll(".pnml", ""), 1.0)); updateComponentList(); } catch (IOException ioe) { JOptionPane.showMessageDialog(dialog, "Could not add the PNML file " + selected.getName() + " to the library!"); } } Code Sample 2: public void backupFile(File fromFile, File toFile) { FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } catch (IOException e) { log.error(e.getMessage()); } finally { if (from != null) try { from.close(); } catch (IOException e) { log.error(e.getMessage()); } if (to != null) try { to.close(); } catch (IOException e) { log.error(e.getMessage()); } } }
00
Code Sample 1: protected void doBackupOrganizeType() throws Exception { Connection con = null; PreparedStatement ps = null; ResultSet result = null; String strSelQuery = "SELECT organize_type_id,organize_type_name,width " + "FROM " + Common.ORGANIZE_TYPE_TABLE; String strInsQuery = "INSERT INTO " + Common.ORGANIZE_TYPE_B_TABLE + " " + "(version_no,organize_type_id,organize_type_name,width) " + "VALUES (?,?,?,?)"; DBOperation dbo = factory.createDBOperation(POOL_NAME); try { try { con = dbo.getConnection(); con.setAutoCommit(false); ps = con.prepareStatement(strSelQuery); result = ps.executeQuery(); ps = con.prepareStatement(strInsQuery); while (result.next()) { ps.setInt(1, this.versionNO); ps.setString(2, result.getString("organize_type_id")); ps.setString(3, result.getString("organize_type_name")); ps.setInt(4, result.getInt("width")); int resultCount = ps.executeUpdate(); if (resultCount != 1) { con.rollback(); throw new CesSystemException("Organize_backup.doBackupOrganizeType(): ERROR Inserting data " + "in T_SYS_ORGANIZE_B_TYPE INSERT !! resultCount = " + resultCount); } } con.commit(); } catch (SQLException se) { con.rollback(); throw new CesSystemException("Organize_backup.doBackupOrganizeType(): SQLException: " + se); } finally { con.setAutoCommit(true); close(dbo, ps, result); } } catch (SQLException se) { throw new CesSystemException("Organize_backup.doBackupOrganizeType(): SQLException while committing or rollback"); } } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.B64InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: public static void rewrite(String[] args) throws IOException, CodeCheckException { ClassWriter writer = new ClassWriter(); writer.readClass(new FileInputStream(args[0])); for (Iterator i = writer.getMethods().iterator(); i.hasNext(); ) { MethodInfo method = (MethodInfo) i.next(); CodeAttribute attribute = method.getCodeAttribute(); int origStack = attribute.getMaxStack(); System.out.print(method.getName()); attribute.codeCheck(); System.out.println(" " + origStack + " " + attribute.getMaxStack()); } BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(args[1])); writer.writeClass(outStream); outStream.close(); } Code Sample 2: public static void decoupe(String input_file_path) { final int BUFFER_SIZE = 2000000; try { FileInputStream fr = new FileInputStream(input_file_path); byte[] cbuf = new byte[BUFFER_SIZE]; int n_read = 0; int i = 0; boolean bContinue = true; while (bContinue) { n_read = fr.read(cbuf, 0, BUFFER_SIZE); if (n_read == -1) break; FileOutputStream fo = new FileOutputStream("f_" + ++i); fo.write(cbuf, 0, n_read); fo.close(); } fr.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); response.setContentType("text/html"); HttpSession session = request.getSession(); String session_id = session.getId(); File session_fileDir = new File(destinationDir + java.io.File.separator + session_id); session_fileDir.mkdir(); DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); fileItemFactory.setSizeThreshold(1 * 1024 * 1024); fileItemFactory.setRepository(tmpDir); ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); String pathToFile = new String(); try { List items = uploadHandler.parseRequest(request); Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); if (item.isFormField()) { ; } else { pathToFile = getServletContext().getRealPath("/") + "files" + java.io.File.separator + session_id; File file = new File(pathToFile + java.io.File.separator + item.getName()); item.write(file); getContents(file, pathToFile); ComtorStandAlone.setMode(Mode.CLOUD); Comtor.start(pathToFile); } } try { File reportFile = new File(pathToFile + java.io.File.separator + "comtorReport.txt"); String reportURLString = AWSServices.storeReportS3(reportFile, session_id).toString(); if (reportURLString.startsWith("https")) reportURLString = reportURLString.replaceFirst("https", "http"); String requestURL = request.getRequestURL().toString(); String url = requestURL.substring(0, requestURL.lastIndexOf("/")); out.println("<html><head/><body>"); out.println("<a href=\"" + url + "\">Return to home</a>&nbsp;&nbsp;"); out.println("<a href=\"" + reportURLString + "\">Report URL</a><br/><hr/>"); Scanner scan = new Scanner(reportFile); out.println("<pre>"); while (scan.hasNextLine()) out.println(scan.nextLine()); out.println("</pre><hr/>"); out.println("<a href=\"" + url + "\">Return to home</a>&nbsp;&nbsp;"); out.println("<a href=\"" + reportURLString + "\">Report URL</a><br/>"); out.println("</body></html>"); } catch (Exception ex) { System.err.println(ex); } } catch (FileUploadException ex) { System.err.println("Error encountered while parsing the request" + ex); } catch (Exception ex) { System.err.println("Error encountered while uploading file" + ex); } } Code Sample 2: private String getSearchResults(String id) { try { final URL url = new URL("http://www.jaap.nl/api/jaapAPI.do?clientId=iPhone&limit=5&request=details&id=" + id + "&format=JSON&field=street_nr&field=zip&field=city&field=price&field=thumb&field=since&field=houseType&field=area&field=rooms&field=id"); final StringBuilder builder = new StringBuilder(); final BufferedReader rd = new BufferedReader(new InputStreamReader(url.openStream())); String s = ""; while ((s = rd.readLine()) != null) { builder.append(s); } rd.close(); return builder.toString(); } catch (Exception e) { e.printStackTrace(); } return null; }
11
Code Sample 1: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (req.getParameter("i") != null) { String img = req.getParameter("i"); if (img == null) { resp.sendError(404, "Image was null"); return; } File f = null; if (img.startsWith("file")) { try { f = new File(new URI(img)); } catch (URISyntaxException e) { resp.sendError(500, e.getMessage()); return; } } else { f = new File(img); } if (f.exists()) { f = f.getCanonicalFile(); if (f.getName().endsWith(".jpg") || f.getName().endsWith(".png")) { resp.setContentType("image/png"); FileInputStream fis = null; OutputStream os = resp.getOutputStream(); try { fis = new FileInputStream(f); IOUtils.copy(fis, os); } finally { os.flush(); if (fis != null) fis.close(); } } } return; } String mediaUrl = "/media" + req.getPathInfo(); String parts[] = mediaUrl.split("/"); mediaHandler.handleRequest(parts, req, resp); } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: public void process(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { String UrlStr = req.getRequestURL().toString(); URL domainurl = new URL(UrlStr); domain = domainurl.getHost(); pathinfo = req.getPathInfo(); String user_agent = req.getHeader("user-agent"); UserAgent userAgent = UserAgent.parseUserAgentString(user_agent); String browser = userAgent.getBrowser().getName(); String[] shot_domain_array = domain.split("\\."); shot_domain = shot_domain_array[1] + "." + shot_domain_array[2]; if (browser.equalsIgnoreCase("Robot/Spider") || browser.equalsIgnoreCase("Lynx") || browser.equalsIgnoreCase("Downloading Tool")) { JSONObject domainJsonObject = CsvReader.CsvReader("domainparUpdated.csv", shot_domain); log.info(domainJsonObject.toString()); } else { String title; String locale; String facebookid; String color; String headImage; String google_ad_client; String google_ad_slot1; String google_ad_width1; String google_ad_height1; String google_ad_slot2; String google_ad_width2; String google_ad_height2; String google_ad_slot3; String google_ad_width3; String google_ad_height3; String countrycode = null; String city = null; String gmclickval = null; String videos = null; int intcount = 0; String strcount = "0"; boolean countExist = false; Cookie[] cookies = req.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals("count")) { strcount = cookies[i].getValue(); if (strcount != null && strcount.length() > 0) { log.info("Check count " + strcount + " path " + cookies[i].getPath()); intcount = Integer.parseInt(strcount); intcount++; } else { intcount = 1; } log.info("New count " + intcount); LongLivedCookie count = new LongLivedCookie("count", Integer.toString(intcount)); resp.addCookie(count); countExist = true; } if (cookies[i].getName().equals("countrycode")) { countrycode = cookies[i].getValue(); } if (cookies[i].getName().equals("city")) { city = cookies[i].getValue(); } if (cookies[i].getName().equals("videos")) { videos = cookies[i].getValue(); log.info("Welcome videos " + videos); } if (cookies[i].getName().equals("gmclick")) { log.info("gmclick exist!!"); gmclickval = cookies[i].getValue(); if (intcount % 20 == 0 && intcount > 0) { log.info("Cancell gmclick -> " + gmclickval + " intcount " + intcount + " path " + cookies[i].getPath()); Cookie gmclick = new Cookie("gmclick", "0"); gmclick.setPath("/"); gmclick.setMaxAge(0); resp.addCookie(gmclick); } } } if (!countExist) { LongLivedCookie count = new LongLivedCookie("count", "0"); resp.addCookie(count); log.info(" Not First visit count Don't Exist!!"); } if (videos == null) { LongLivedCookie videoscookies = new LongLivedCookie("videos", "0"); resp.addCookie(videoscookies); log.info("Not First visit VIDEOS Don't Exist!!"); } } else { LongLivedCookie count = new LongLivedCookie("count", strcount); resp.addCookie(count); LongLivedCookie videosfirstcookies = new LongLivedCookie("videos", "0"); resp.addCookie(videosfirstcookies); log.info("First visit count = " + intcount + " videos 0"); } String[] dompar = CommUtils.CsvParsing(domain, "domainpar.csv"); title = dompar[0]; locale = dompar[1]; facebookid = dompar[2]; color = dompar[3]; headImage = dompar[4]; google_ad_client = dompar[5]; google_ad_slot1 = dompar[6]; google_ad_width1 = dompar[7]; google_ad_height1 = dompar[8]; google_ad_slot2 = dompar[9]; google_ad_width2 = dompar[10]; google_ad_height2 = dompar[11]; google_ad_slot3 = dompar[12]; google_ad_width3 = dompar[13]; google_ad_height3 = dompar[14]; String ip = req.getRemoteHost(); if ((countrycode == null) || (city == null)) { String ipServiceCall = "http://api.ipinfodb.com/v2/ip_query.php?key=abbb04fd823793c5343a046e5d56225af37861b9020e9bc86313eb20486b6133&ip=" + ip + "&output=json"; String strCallResult = ""; URL url = new URL(ipServiceCall); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF8")); StringBuffer response = new StringBuffer(); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); strCallResult = response.toString(); try { JSONObject jso = new JSONObject(strCallResult); log.info("Status -> " + jso.get("Status").toString()); log.info("City -> " + jso.get("City").toString()); city = jso.get("City").toString(); countrycode = jso.get("CountryCode").toString(); log.info("countrycode -> " + countrycode); if ((city.length() == 0) || (city == null)) { LongLivedCookie cookcity = new LongLivedCookie("city", "Helsinki"); resp.addCookie(cookcity); city = "Helsinki"; } else { LongLivedCookie cookcity = new LongLivedCookie("city", city); resp.addCookie(cookcity); } if (countrycode.length() == 0 || (countrycode == null) || countrycode.equals("RD")) { LongLivedCookie cookcountrycode = new LongLivedCookie("countrycode", "FI"); resp.addCookie(cookcountrycode); countrycode = "FI"; } else { LongLivedCookie cookcountrycode = new LongLivedCookie("countrycode", countrycode); resp.addCookie(cookcountrycode); } } catch (JSONException e) { log.severe(e.getMessage()); } finally { if ((countrycode == null) || (city == null)) { log.severe("need use finally!!!"); countrycode = "FI"; city = "Helsinki"; LongLivedCookie cookcity = new LongLivedCookie("city", "Helsinki"); resp.addCookie(cookcity); LongLivedCookie cookcountrycode = new LongLivedCookie("countrycode", "FI"); resp.addCookie(cookcountrycode); } } } JSONArray startjsonarray = new JSONArray(); JSONArray memjsonarray = new JSONArray(); Map<String, Object> map = new HashMap<String, Object>(); Map<String, Object> mapt = new HashMap<String, Object>(); mapt.put("img", headImage); mapt.put("color", color); mapt.put("title", title); mapt.put("locale", locale); mapt.put("domain", domain); mapt.put("facebookid", facebookid); mapt.put("ip", ip); mapt.put("countrycode", countrycode); mapt.put("city", city); map.put("theme", mapt); startjsonarray.put(map); String[] a = { "mem0", "mem20", "mem40", "mem60", "mem80", "mem100", "mem120", "mem140", "mem160", "mem180" }; List memlist = Arrays.asList(a); Collections.shuffle(memlist); Map<String, Object> mammap = new HashMap<String, Object>(); mammap.put("memlist", memlist); memjsonarray.put(mammap); log.info(memjsonarray.toString()); resp.setContentType("text/html"); resp.setCharacterEncoding("UTF-8"); PrintWriter out = resp.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">"); out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:fb=\"http://www.facebook.com/2008/fbml\">"); out.println("<head>"); out.println("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">"); out.println("<meta name=\"gwt:property\" content=\"locale=" + locale + "\">"); out.println("<link type=\"text/css\" rel=\"stylesheet\" href=\"NewTube.css\">"); out.println("<title>" + title + "</title>"); out.println("<script type=\"text/javascript\" language=\"javascript\" src=\"newtube/newtube.nocache.js\"></script>"); out.println("<script type='text/javascript'>var jsonStartParams = " + startjsonarray.toString() + ";</script>"); out.println("<script type='text/javascript'>var girlsphones = " + CommUtils.CsvtoJson("girlsphones.csv").toString() + ";</script>"); out.println("<script type='text/javascript'>"); out.println("var mem = " + memjsonarray.toString() + ";"); out.println("</script>"); out.println("</head>"); out.println("<body>"); out.println("<div id='fb-root'></div>"); out.println("<script>"); out.println("window.fbAsyncInit = function() {"); out.println("FB.init({appId: '" + facebookid + "', status: true, cookie: true,xfbml: true});};"); out.println("(function() {"); out.println("var e = document.createElement('script'); e.async = true;"); out.println("e.src = document.location.protocol +"); out.println("'//connect.facebook.net/" + locale + "/all.js';"); out.println("document.getElementById('fb-root').appendChild(e);"); out.println("}());"); out.println("</script>"); out.println("<div id=\"start\"></div>"); out.println("<div id=\"seo_content\">"); BufferedReader bufRdr = new BufferedReader(new InputStreamReader(new FileInputStream(domain + ".html"), "UTF8")); String contline = null; while ((contline = bufRdr.readLine()) != null) { out.println(contline); } bufRdr.close(); if (countrycode != null && !countrycode.equalsIgnoreCase("US") && !countrycode.equalsIgnoreCase("IE") && !countrycode.equalsIgnoreCase("UK") && intcount > 2 && intcount < 51) { out.println("<script type=\"text/javascript\"><!--"); out.println("google_ad_client = \"" + google_ad_client + "\";"); out.println("google_ad_slot = \"" + google_ad_slot1 + "\";"); out.println("google_ad_width = " + google_ad_width1 + ";"); out.println("google_ad_height = " + google_ad_height1 + ";"); out.println("//-->"); out.println("</script>"); out.println("<script type=\"text/javascript\""); out.println("src=\"" + google_ad_client + ".js\">"); out.println("</script>"); out.println("<script type=\"text/javascript\"><!--"); out.println("google_ad_client = \"" + google_ad_client + "\";"); out.println("google_ad_slot = \"" + google_ad_slot2 + "\";"); out.println("google_ad_width = " + google_ad_width2 + ";"); out.println("google_ad_height = " + google_ad_height2 + ";"); out.println("//-->"); out.println("</script>"); out.println("<script type=\"text/javascript\""); out.println("src=\"" + google_ad_client + ".js\">"); out.println("</script>"); out.println("<script type=\"text/javascript\"><!--"); out.println("google_ad_client = \"" + google_ad_client + "\";"); out.println("google_ad_slot = \"" + google_ad_slot3 + "\";"); out.println("google_ad_width = " + google_ad_width3 + ";"); out.println("google_ad_height = " + google_ad_height3 + ";"); out.println("//-->"); out.println("</script>"); out.println("<script type=\"text/javascript\""); out.println("src=\"" + google_ad_client + ".js\">"); out.println("</script>"); } if (countrycode != null && !countrycode.equalsIgnoreCase("US") && !countrycode.equalsIgnoreCase("IE") && !countrycode.equalsIgnoreCase("UK") && intcount > 50) { out.println("<script type=\"text/javascript\"><!--"); out.println("google_ad_client = \"" + "pub-9496078135369870" + "\";"); out.println("google_ad_slot = \"" + "8683942065" + "\";"); out.println("google_ad_width = " + "160" + ";"); out.println("google_ad_height = " + "600" + ";"); out.println("//-->"); out.println("</script>"); out.println("<script type=\"text/javascript\""); out.println("src=\"pub-9496078135369870" + "" + ".js\">"); out.println("</script>"); out.println("<script type=\"text/javascript\"><!--"); out.println("google_ad_client = \"" + "pub-9496078135369870" + "\";"); out.println("google_ad_slot = \"" + "0941291340" + "\";"); out.println("google_ad_width = " + "728" + ";"); out.println("google_ad_height = " + "90" + ";"); out.println("//-->"); out.println("</script>"); out.println("<script type=\"text/javascript\""); out.println("src=\"" + "pub-9496078135369870" + ".js\">"); out.println("</script>"); out.println("<script type=\"text/javascript\"><!--"); out.println("google_ad_client = \"" + "pub-9496078135369870" + "\";"); out.println("google_ad_slot = \"" + "4621616265" + "\";"); out.println("google_ad_width = " + "468" + ";"); out.println("google_ad_height = " + "60" + ";"); out.println("//-->"); out.println("</script>"); out.println("<script type=\"text/javascript\""); out.println("src=\"" + "pub-9496078135369870" + ".js\">"); out.println("</script>"); } out.println("</div>"); out.println("</body></html>"); out.close(); } } Code Sample 2: public static void copy(File srcDir, File dstDir) throws IOException { if (srcDir.isDirectory()) { if (!dstDir.exists()) dstDir.mkdir(); String[] children = srcDir.list(); for (int i = 0; i < children.length; i++) copy(new File(srcDir, children[i]), new File(dstDir, children[i])); } else { InputStream in = null; OutputStream out = null; try { in = new FileInputStream(srcDir); out = new FileOutputStream(dstDir); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); } finally { Util.close(in); Util.close(out); } } }
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 { 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: private void putAlgosFromJar(File jarfile, AlgoDir dir, Model model) throws FileNotFoundException, IOException { URLClassLoader urlLoader = new URLClassLoader(new URL[] { jarfile.toURI().toURL() }); JarInputStream jis = new JarInputStream(new FileInputStream(jarfile)); JarEntry entry = jis.getNextJarEntry(); String name = null; String tmpdir = System.getProperty("user.dir") + File.separator + Application.getProperty("dir.tmp") + File.separator; byte[] buffer = new byte[1000]; while (entry != null) { name = entry.getName(); if (name.endsWith(".class")) { name = name.substring(0, name.length() - 6); name = name.replace('/', '.'); try { Class<?> cls = urlLoader.loadClass(name); if (IAlgorithm.class.isAssignableFrom(cls) && !cls.isInterface() && ((cls.getModifiers() & Modifier.ABSTRACT) == 0)) { dir.addAlgorithm(cls); model.putClass(cls.getName(), cls); } else if (ISerializable.class.isAssignableFrom(cls)) { model.putClass(cls.getName(), cls); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } else if (Constants.isAllowedImageType(name)) { int lastSep = name.lastIndexOf("/"); if (lastSep != -1) { String dirs = tmpdir + name.substring(0, lastSep); File d = new File(dirs); if (!d.exists()) d.mkdirs(); } String filename = tmpdir + name; File f = new File(filename); if (!f.exists()) { f.createNewFile(); FileOutputStream fos = new FileOutputStream(f); int read = -1; while ((read = jis.read(buffer)) != -1) { fos.write(buffer, 0, read); } fos.close(); } } entry = jis.getNextJarEntry(); } }
11
Code Sample 1: @SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { PositionParser pp; Database.init("XIDResult"); pp = new PositionParser("01:33:50.904+30:39:35.79"); String url = "http://simbad.u-strasbg.fr/simbad/sim-script?submit=submit+script&script="; String script = "format object \"%IDLIST[%-30*]|-%COO(A)|%COO(D)|%OTYPELIST(S)\"\n"; String tmp = ""; script += pp.getPosition() + " radius=1m"; url += URLEncoder.encode(script, "ISO-8859-1"); URL simurl = new URL(url); BufferedReader in = new BufferedReader(new InputStreamReader(simurl.openStream())); String boeuf; boolean data_found = false; JSONObject retour = new JSONObject(); JSONArray dataarray = new JSONArray(); JSONArray colarray = new JSONArray(); JSONObject jsloc = new JSONObject(); jsloc.put("sTitle", "ID"); colarray.add(jsloc); jsloc = new JSONObject(); jsloc.put("sTitle", "Position"); colarray.add(jsloc); jsloc = new JSONObject(); jsloc.put("sTitle", "Type"); colarray.add(jsloc); retour.put("aoColumns", colarray); int datasize = 0; while ((boeuf = in.readLine()) != null) { if (data_found) { String[] fields = boeuf.trim().split("\\|", -1); int pos = fields.length - 1; if (pos >= 3) { String type = fields[pos]; pos--; String dec = fields[pos]; pos--; String ra = fields[pos]; String id = ""; for (int i = 0; i < pos; i++) { id += fields[i]; if (i < (pos - 1)) { id += "|"; } } if (id.length() <= 30) { JSONArray darray = new JSONArray(); darray.add(id.trim()); darray.add(ra + " " + dec); darray.add(type.trim()); dataarray.add(darray); datasize++; } } } else if (boeuf.startsWith("::data")) { data_found = true; } } retour.put("aaData", dataarray); retour.put("iTotalRecords", datasize); retour.put("iTotalDisplayRecords", datasize); System.out.println(retour.toJSONString()); in.close(); } 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 static int executeUpdate(EOAdaptorChannel channel, String sql, boolean autoCommit) throws SQLException { int rowsUpdated; boolean wasOpen = channel.isOpen(); if (!wasOpen) { channel.openChannel(); } Connection conn = ((JDBCContext) channel.adaptorContext()).connection(); try { Statement stmt = conn.createStatement(); try { rowsUpdated = stmt.executeUpdate(sql); if (autoCommit) { conn.commit(); } } catch (SQLException ex) { if (autoCommit) { conn.rollback(); } throw new RuntimeException("Failed to execute the statement '" + sql + "'.", ex); } finally { stmt.close(); } } finally { if (!wasOpen) { channel.closeChannel(); } } return rowsUpdated; } Code Sample 2: private boolean sendMsg(TACMessage msg) { try { String msgStr = msg.getMessageString(); URLConnection conn = url.openConnection(); conn.setRequestProperty("Content-Length", "" + msgStr.length()); conn.setDoOutput(true); OutputStream output = conn.getOutputStream(); output.write(msgStr.getBytes()); output.flush(); InputStream input = conn.getInputStream(); int len = conn.getContentLength(); int totalRead = 0; int read; byte[] content = new byte[len]; while ((len > totalRead) && (read = input.read(content, totalRead, len - totalRead)) > 0) { totalRead += read; } output.close(); input.close(); if (len < totalRead) { log.severe("truncated message response for " + msg.getType()); return false; } else { msgStr = new String(content); msg.setReceivedMessage(msgStr); msg.deliverMessage(); } return true; } catch (Exception e) { log.log(Level.SEVERE, "could not send message", e); return false; } }
11
Code Sample 1: private String fetchLocalPage(String page) throws IOException { final String fullUrl = HOST + page; LOG.debug("Fetching local page: " + fullUrl); URL url = new URL(fullUrl); URLConnection connection = url.openConnection(); StringBuilder sb = new StringBuilder(); BufferedReader input = null; try { input = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line = null; while ((line = input.readLine()) != null) { sb.append(line).append("\n"); } } finally { if (input != null) try { input.close(); } catch (IOException e) { LOG.error("Could not close reader!", e); } } return sb.toString(); } Code Sample 2: public void testBasic() { CameraInfo ci = C328rCameraInfo.getInstance(); assertNotNull(ci); assertNotNull(ci.getCapabilities()); assertFalse(ci.getCapabilities().isEmpty()); System.out.println(ci.getUrl()); URL url = ci.getUrl(); try { URLConnection conn = url.openConnection(); conn.connect(); InputStream is = conn.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line = null; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public static void copyFile(File 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(); }
11
Code Sample 1: @Override public void run() { File dir = new File(loggingDir); if (!dir.isDirectory()) { logger.error("Logging directory \"" + dir.getAbsolutePath() + "\" does not exist."); return; } File file = new File(dir, new Date().toString().replaceAll("[ ,:]", "") + "LoadBalancerLog.txt"); FileWriter writer; try { writer = new FileWriter(file); } catch (IOException e) { e.printStackTrace(); return; } int counter = 0; while (!isInterrupted() && counter < numProbes) { try { writer.write(System.currentTimeMillis() + "," + currentPending + "," + currentThreads + "," + droppedTasks + "," + executionExceptions + "," + currentWeight + "," + averageWaitTime + "," + averageExecutionTime + "#"); writer.flush(); } catch (IOException e) { e.printStackTrace(); break; } counter++; try { sleep(probeTime); } catch (InterruptedException e) { e.printStackTrace(); break; } } try { writer.close(); } catch (IOException e) { e.printStackTrace(); return; } FileReader reader; try { reader = new FileReader(file); } catch (FileNotFoundException e2) { e2.printStackTrace(); return; } Vector<StatStorage> dataV = new Vector<StatStorage>(); int c; try { c = reader.read(); } catch (IOException e1) { e1.printStackTrace(); c = -1; } String entry = ""; Date startTime = null; Date stopTime = null; while (c != -1) { if (c == 35) { String parts[] = entry.split(","); if (startTime == null) startTime = new Date(Long.parseLong(parts[0])); if (parts.length > 0) dataV.add(parse(parts)); stopTime = new Date(Long.parseLong(parts[0])); entry = ""; } else { entry += (char) c; } try { c = reader.read(); } catch (IOException e) { e.printStackTrace(); } } try { reader.close(); } catch (IOException e) { e.printStackTrace(); } if (dataV.size() > 0) { int[] dataPending = new int[dataV.size()]; int[] dataOccupied = new int[dataV.size()]; long[] dataDropped = new long[dataV.size()]; long[] dataException = new long[dataV.size()]; int[] dataWeight = new int[dataV.size()]; long[] dataExecution = new long[dataV.size()]; long[] dataWait = new long[dataV.size()]; for (int i = 0; i < dataV.size(); i++) { dataPending[i] = dataV.get(i).pending; dataOccupied[i] = dataV.get(i).occupied; dataDropped[i] = dataV.get(i).dropped; dataException[i] = dataV.get(i).exceptions; dataWeight[i] = dataV.get(i).currentWeight; dataExecution[i] = (long) dataV.get(i).executionTime; dataWait[i] = (long) dataV.get(i).waitTime; } String startName = startTime.toString(); startName = startName.replaceAll("[ ,:]", ""); file = new File(dir, startName + "pending.gif"); SimpleChart.drawChart(file, 640, 480, dataPending, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "occupied.gif"); SimpleChart.drawChart(file, 640, 480, dataOccupied, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "dropped.gif"); SimpleChart.drawChart(file, 640, 480, dataDropped, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "exceptions.gif"); SimpleChart.drawChart(file, 640, 480, dataException, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "weight.gif"); SimpleChart.drawChart(file, 640, 480, dataWeight, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "execution.gif"); SimpleChart.drawChart(file, 640, 480, dataExecution, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "wait.gif"); SimpleChart.drawChart(file, 640, 480, dataWait, startTime, stopTime, new Color(0, 0, 0)); } recordedExecutionThreads = 0; recordedWaitingThreads = 0; averageExecutionTime = 0; averageWaitTime = 0; if (!isLocked) { debugThread = new DebugThread(); debugThread.start(); } } Code Sample 2: protected void extractArchive(File archive) { ZipInputStream zis = null; FileOutputStream fos; ZipEntry entry; File curEntry; int n; try { zis = new ZipInputStream(new FileInputStream(archive)); while ((entry = zis.getNextEntry()) != null) { curEntry = new File(workingDir, entry.getName()); if (entry.isDirectory()) { System.out.println("skip directory: " + entry.getName()); continue; } System.out.print("zip-entry (file): " + entry.getName()); System.out.println(" ==> real path: " + curEntry.getAbsolutePath()); if (!curEntry.getParentFile().exists()) curEntry.getParentFile().mkdirs(); fos = new FileOutputStream(curEntry); while ((n = zis.read(buf, 0, buf.length)) > -1) fos.write(buf, 0, n); fos.close(); zis.closeEntry(); } } catch (Throwable t) { t.printStackTrace(); } finally { try { if (zis != null) zis.close(); } catch (Throwable t) { } } }
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: public static ByteBuffer join(ByteBuffer buffer1, ByteBuffer buffer2) { if (buffer2 == null || buffer2.remaining() == 0) return NIOUtils.copy(buffer1); if (buffer1 == null || buffer1.remaining() == 0) return NIOUtils.copy(buffer2); ByteBuffer buffer = ByteBuffer.allocate(buffer1.remaining() + buffer2.remaining()); buffer.put(buffer1); buffer.put(buffer2); buffer.flip(); return buffer; }
11
Code Sample 1: 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); FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException(MM.PHRASES.getPhrase("25") + " " + source_name); if (!source_file.canRead()) throw new FileCopyException(MM.PHRASES.getPhrase("26") + " " + MM.PHRASES.getPhrase("27") + ": " + 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(MM.PHRASES.getPhrase("28") + " " + MM.PHRASES.getPhrase("29") + ": " + dest_name); System.out.print(MM.PHRASES.getPhrase("19") + dest_name + MM.PHRASES.getPhrase("30") + ": "); System.out.flush(); response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new FileCopyException(MM.PHRASES.getPhrase("31")); } else throw new FileCopyException(MM.PHRASES.getPhrase("28") + " " + MM.PHRASES.getPhrase("32") + ": " + dest_name); } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException(MM.PHRASES.getPhrase("28") + " " + MM.PHRASES.getPhrase("33") + ": " + dest_name); if (!parentdir.canWrite()) throw new FileCopyException(MM.PHRASES.getPhrase("28") + " " + MM.PHRASES.getPhrase("34") + ": " + dest_name); } source = new FileInputStream(source_file); destination = new FileOutputStream(destination_file); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); 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) { ; } } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: public static StringBuffer readURLText(URL url, StringBuffer errorText) { StringBuffer page = new StringBuffer(""); String thisLine; try { BufferedReader source = new BufferedReader(new InputStreamReader(url.openStream())); while ((thisLine = source.readLine()) != null) { page.append(thisLine + "\n"); } return page; } catch (Exception e) { return errorText; } } Code Sample 2: public static void generate(final InputStream input, String format, Point dimension, IPath outputLocation) throws CoreException { MultiStatus status = new MultiStatus(GraphVizActivator.ID, 0, "Errors occurred while running Graphviz", null); File dotInput = null, dotOutput = outputLocation.toFile(); ByteArrayOutputStream dotContents = new ByteArrayOutputStream(); try { dotInput = File.createTempFile(TMP_FILE_PREFIX, DOT_EXTENSION); FileOutputStream tmpDotOutputStream = null; try { IOUtils.copy(input, dotContents); tmpDotOutputStream = new FileOutputStream(dotInput); IOUtils.copy(new ByteArrayInputStream(dotContents.toByteArray()), tmpDotOutputStream); } finally { IOUtils.closeQuietly(tmpDotOutputStream); } IStatus result = runDot(format, dimension, dotInput, dotOutput); if (dotOutput.isFile()) { if (!result.isOK() && Platform.inDebugMode()) LogUtils.log(status); return; } } catch (IOException e) { status.add(new Status(IStatus.ERROR, GraphVizActivator.ID, "", e)); } finally { dotInput.delete(); IOUtils.closeQuietly(input); } throw new CoreException(status); }
11
Code Sample 1: public void add(Site site) throws Exception { DBOperation dbo = null; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { String sqlStr = "insert into t_ip_site (id,name,description,ascii_name,site_path,remark_number,increment_index,use_status,appserver_id) VALUES(?,?,?,?,?,?,?,?,?)"; dbo = createDBOperation(); connection = dbo.getConnection(); connection.setAutoCommit(false); preparedStatement = connection.prepareStatement(sqlStr); preparedStatement.setInt(1, site.getSiteID()); preparedStatement.setString(2, site.getName()); preparedStatement.setString(3, site.getDescription()); preparedStatement.setString(4, site.getAsciiName()); preparedStatement.setString(5, site.getPath()); preparedStatement.setInt(6, site.getRemarkNumber()); preparedStatement.setString(7, site.getIncrementIndex().trim()); preparedStatement.setString(8, String.valueOf(site.getUseStatus())); preparedStatement.setString(9, String.valueOf(site.getAppserverID())); preparedStatement.executeUpdate(); String[] path = new String[1]; path[0] = site.getPath(); selfDefineAdd(path, site, connection, preparedStatement); connection.commit(); int resID = site.getSiteID() + Const.SITE_TYPE_RES; String resName = site.getName(); int resTypeID = Const.RES_TYPE_ID; int operateTypeID = Const.OPERATE_TYPE_ID; String remark = ""; AuthorityManager am = new AuthorityManager(); am.createExtResource(Integer.toString(resID), resName, resTypeID, operateTypeID, remark); site.wirteFile(); } catch (SQLException ex) { connection.rollback(); log.error("����վ��ʧ��!", ex); throw ex; } finally { close(resultSet, null, preparedStatement, connection, dbo); } } Code Sample 2: public static void insertTableData(Connection dest, TableMetaData tableMetaData) throws Exception { PreparedStatement ps = null; try { dest.setAutoCommit(false); String sql = "INSERT INTO " + tableMetaData.getSchema() + "." + tableMetaData.getTableName() + " ("; for (String columnName : tableMetaData.getColumnsNames()) { sql += columnName + ","; } sql = sql.substring(0, sql.length() - 1); sql += ") VALUES ("; for (String columnName : tableMetaData.getColumnsNames()) { sql += "?" + ","; } sql = sql.substring(0, sql.length() - 1); sql += ")"; IOHelper.writeInfo(sql); ps = dest.prepareStatement(sql); for (Row r : tableMetaData.getData()) { try { int param = 1; for (String columnName : tableMetaData.getColumnsNames()) { if (dest instanceof OracleConnection) { if (tableMetaData.getColumnsTypes().get(columnName).equalsIgnoreCase("BLOB")) { BLOB blob = new BLOB((OracleConnection) dest, (byte[]) r.getRowData().get(columnName)); ((OraclePreparedStatement) ps).setBLOB(param, blob); } else if (tableMetaData.getColumnsTypes().get(columnName).equalsIgnoreCase("CLOB")) { ((OraclePreparedStatement) ps).setStringForClob(param, (String) r.getRowData().get(columnName)); } else if (tableMetaData.getColumnsTypes().get(columnName).equalsIgnoreCase("LONG")) { ps.setBytes(param, (byte[]) r.getRowData().get(columnName)); } } else { IOHelper.writeInfo(columnName + " = " + r.getRowData().get(columnName)); ps.setObject(param, r.getRowData().get(columnName)); } param++; } if (ps.executeUpdate() != 1) { dest.rollback(); updateTableData(dest, tableMetaData, r); } } catch (Exception ex) { try { dest.rollback(); updateTableData(dest, tableMetaData, r); } catch (Exception ex2) { IOHelper.writeError("Error in update " + sql, ex2); } } ps.clearParameters(); } dest.commit(); dest.setAutoCommit(true); } finally { if (ps != null) ps.close(); } }
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: public static void copy(FileInputStream source, FileOutputStream dest) throws IOException { FileChannel in = null, out = null; try { in = source.getChannel(); out = dest.getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
00
Code Sample 1: protected void readInput(String filename, List<String> list) throws IOException { URL url = GeneratorBase.class.getResource(filename); if (url == null) { throw new FileNotFoundException("specified file not available - " + filename); } BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { list.add(line.trim()); } } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { } } } } Code Sample 2: public QueryResult doSearch(String searchTerm, Integer searchInReceivedItems, Integer searchInSentItems, Integer searchInSupervisedItems, Integer startRow, Integer resultCount, Boolean searchArchived, Boolean searchInItemsNeededAttentionOnly) throws UnsupportedEncodingException, IOException { String sessionId = (String) RuntimeAccess.getInstance().getSession().getAttribute("SESSION_ID"); DefaultHttpClient httpclient = new DefaultHttpClient(); QueryResult queryResult = new QueryResult(); SearchRequest request = new SearchRequest(); SearchItemsQuery query = new SearchItemsQuery(); query.setArchiveIncluded(searchArchived); log(INFO, "searchTerm=" + searchTerm); log(INFO, "search in received=" + searchInReceivedItems); log(INFO, "search in sent=" + searchInSentItems); log(INFO, "search in supervised=" + searchInSupervisedItems); List<String> filters = new ArrayList<String>(); if (searchInItemsNeededAttentionOnly == false) { if (searchInReceivedItems != null) { filters.add("ALL_RECEIVED_ITEMS"); } if (searchInSentItems != null) { filters.add("ALL_SENT_ITEMS"); } if (searchInSupervisedItems != null) { filters.add("ALL_SUPERVISED_ITEMS"); } } else { if (searchInReceivedItems != null) { filters.add("RECEIVED_ITEMS_NEEDED_ATTENTION"); } if (searchInSentItems != null) { filters.add("SENT_ITEMS_NEEDED_ATTENTION"); } } query.setFilters(filters); query.setId("1234"); query.setOwner(sessionId); query.setReferenceOnly(false); query.setSearchTerm(searchTerm); query.setUseOR(false); request.setStartRow(startRow); request.setResultCount(resultCount); request.setQuery(query); request.setSessionId(sessionId); XStream writer = new XStream(); writer.setMode(XStream.XPATH_ABSOLUTE_REFERENCES); writer.alias("SearchRequest", SearchRequest.class); XStream reader = new XStream(); reader.setMode(XStream.XPATH_ABSOLUTE_REFERENCES); reader.alias("SearchResponse", SearchResponse.class); String strRequest = URLEncoder.encode(reader.toXML(request), "UTF-8"); HttpGet httpget = new HttpGet(MewitProperties.getMewitUrl() + "/resources/search?REQUEST=" + strRequest); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { String result = URLDecoder.decode(EntityUtils.toString(entity), "UTF-8"); SearchResponse searchResponse = (SearchResponse) reader.fromXML(result); List<Item> items = searchResponse.getItems(); queryResult.setItems(items); queryResult.setTotal(searchResponse.getTotalResultCount()); queryResult.setStartRow(searchResponse.getStartRow()); } return queryResult; }
11
Code Sample 1: public static void copyFile(File source, File dest) { try { FileChannel in = new FileInputStream(source).getChannel(); if (!dest.getParentFile().exists()) dest.getParentFile().mkdirs(); FileChannel out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public static void decompress(final File file, final File folder, final boolean deleteZipAfter) throws IOException { final ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(file.getCanonicalFile()))); ZipEntry ze; try { while (null != (ze = zis.getNextEntry())) { final File f = new File(folder.getCanonicalPath(), ze.getName()); if (f.exists()) f.delete(); if (ze.isDirectory()) { f.mkdirs(); continue; } f.getParentFile().mkdirs(); final OutputStream fos = new BufferedOutputStream(new FileOutputStream(f)); try { try { final byte[] buf = new byte[8192]; int bytesRead; while (-1 != (bytesRead = zis.read(buf))) fos.write(buf, 0, bytesRead); } finally { fos.close(); } } catch (final IOException ioe) { f.delete(); throw ioe; } } } finally { zis.close(); } if (deleteZipAfter) file.delete(); }
00
Code Sample 1: public static void bubbleSort(Drawable[] list) { boolean swapped; do { swapped = false; for (int i = 0; i < list.length - 1; ++i) { if (list[i].getSortValue() > list[i + 1].getSortValue()) { Drawable temp = list[i]; list[i] = list[i + 1]; list[i + 1] = temp; swapped = true; } } } while (swapped); } Code Sample 2: public Constructor run() throws Exception { String path = "META-INF/services/" + BeanletApplicationContext.class.getName(); ClassLoader loader = Thread.currentThread().getContextClassLoader(); final Enumeration<URL> urls; if (loader == null) { urls = BeanletApplicationContext.class.getClassLoader().getResources(path); } else { urls = loader.getResources(path); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); try { String className = null; while ((className = reader.readLine()) != null) { final String name = className.trim(); if (!name.startsWith("#") && !name.startsWith(";") && !name.startsWith("//")) { final Class<?> cls; if (loader == null) { cls = Class.forName(name); } else { cls = Class.forName(name, true, loader); } int m = cls.getModifiers(); if (BeanletApplicationContext.class.isAssignableFrom(cls) && !Modifier.isAbstract(m) && !Modifier.isInterface(m)) { Constructor constructor = cls.getDeclaredConstructor(); if (!Modifier.isPublic(constructor.getModifiers())) { constructor.setAccessible(true); } return constructor; } else { throw new ClassCastException(cls.getName()); } } } } finally { reader.close(); } } throw new BeanletApplicationException("No " + "BeanletApplicationContext implementation " + "found."); }
00
Code Sample 1: @Override public void checkConnection(byte[] options) throws Throwable { Properties opts = PropertiesUtils.deserializeProperties(options); String server = opts.getProperty(TRANSFER_OPTION_SERVER); String username = opts.getProperty(TRANSFER_OPTION_USERNAME); String password = opts.getProperty(TRANSFER_OPTION_PASSWORD); String filePath = opts.getProperty(TRANSFER_OPTION_FILEPATH); URL url = new URL(PROTOCOL_PREFIX + username + ":" + password + "@" + server + filePath + ";type=i"); URLConnection urlc = url.openConnection(BackEnd.getProxy(Proxy.Type.SOCKS)); urlc.setConnectTimeout(Preferences.getInstance().preferredTimeOut * 1000); urlc.setReadTimeout(Preferences.getInstance().preferredTimeOut * 1000); urlc.connect(); } Code Sample 2: protected String getPageText(final String url) { StringBuilder b = new StringBuilder(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String line = null; while ((line = reader.readLine()) != null) { b.append(line).append('\n'); } } catch (IOException ex) { ex.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException ex) { ex.printStackTrace(); } } } return b.toString(); }
00
Code Sample 1: public void addGames(List<Game> games) throws StadiumException, SQLException { Connection conn = ConnectionManager.getManager().getConnection(); conn.setAutoCommit(false); PreparedStatement stm = null; ResultSet rs = null; try { for (Game game : games) { stm = conn.prepareStatement(Statements.SELECT_STADIUM); stm.setString(1, game.getStadiumName()); stm.setString(2, game.getStadiumCity()); rs = stm.executeQuery(); int stadiumId = -1; while (rs.next()) { stadiumId = rs.getInt("stadiumID"); } if (stadiumId == -1) throw new StadiumException("No such stadium"); stm = conn.prepareStatement(Statements.INSERT_GAME); stm.setInt(1, stadiumId); stm.setDate(2, game.getGameDate()); stm.setTime(3, game.getGameTime()); stm.setString(4, game.getTeamA()); stm.setString(5, game.getTeamB()); stm.executeUpdate(); int gameId = getMaxId(); List<SectorPrice> sectorPrices = game.getSectorPrices(); for (SectorPrice price : sectorPrices) { stm = conn.prepareStatement(Statements.INSERT_TICKET_PRICE); stm.setInt(1, gameId); stm.setInt(2, price.getSectorId()); stm.setInt(3, price.getPrice()); stm.executeUpdate(); } } } catch (SQLException e) { conn.rollback(); throw e; } finally { rs.close(); stm.close(); } conn.commit(); conn.setAutoCommit(true); } Code Sample 2: private String transferWSDL(String wsdlURL, String userPassword) throws WiseConnectionException { String filePath = null; try { URL endpoint = new URL(wsdlURL); HttpURLConnection conn = (HttpURLConnection) endpoint.openConnection(); conn.setDoOutput(false); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); conn.setRequestProperty("Connection", "close"); if (userPassword != null) { conn.setRequestProperty("Authorization", "Basic " + (new BASE64Encoder()).encode(userPassword.getBytes())); } InputStream is = null; if (conn.getResponseCode() == 200) { is = conn.getInputStream(); } else { is = conn.getErrorStream(); InputStreamReader isr = new InputStreamReader(is); StringWriter sw = new StringWriter(); char[] buf = new char[200]; int read = 0; while (read != -1) { read = isr.read(buf); sw.write(buf); } throw new WiseConnectionException("Remote server's response is an error: " + sw.toString()); } File file = new File(tmpDeployDir, new StringBuffer("Wise").append(IDGenerator.nextVal()).append(".xml").toString()); OutputStream fos = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copyStream(fos, is); fos.close(); is.close(); filePath = file.getPath(); } catch (WiseConnectionException wce) { throw wce; } catch (Exception e) { throw new WiseConnectionException("Wsdl download failed!", e); } return filePath; }
00
Code Sample 1: @Override public void downloadByUUID(final UUID uuid, final HttpServletRequest request, final HttpServletResponse response) throws IOException { if (!exportsInProgress.containsKey(uuid)) { throw new IllegalStateException("No download with UUID: " + uuid); } final File compressedFile = exportsInProgress.get(uuid).file; logger.debug("File size: " + compressedFile.length()); OutputStream output = null; InputStream fileInputStream = null; try { output = response.getOutputStream(); prepareResponse(request, response, compressedFile); fileInputStream = new FileInputStream(compressedFile); IOUtils.copy(fileInputStream, output); output.flush(); } finally { IOUtils.closeQuietly(fileInputStream); IOUtils.closeQuietly(output); } } Code Sample 2: void bubbleSort(int[] a) { int i = 0; int j = a.length - 1; int aux = 0; int stop = 0; while (stop == 0) { stop = 1; i = 0; while (i < j) { if (a[i] > a[i + 1]) { aux = a[i]; a[i] = a[i + 1]; a[i + 1] = aux; stop = 0; } i = i + 1; } j = j - 1; } }
00
Code Sample 1: public static byte[] encode(String origin, String algorithm) throws NoSuchAlgorithmException { String resultStr = null; resultStr = new String(origin); MessageDigest md = MessageDigest.getInstance(algorithm); md.update(resultStr.getBytes()); return md.digest(); } Code Sample 2: protected synchronized Long putModel(String table, String linkTable, String type, TupleBinding binding, LocatableModel model) { try { if (model.getId() != null && !"".equals(model.getId())) { ps7.setInt(1, Integer.parseInt(model.getId())); ps7.execute(); ps6.setInt(1, Integer.parseInt(model.getId())); ps6.execute(); } if (persistenceMethod == PostgreSQLStore.BYTEA) { ps1.setString(1, model.getContig()); ps1.setInt(2, model.getStartPosition()); ps1.setInt(3, model.getStopPosition()); ps1.setString(4, type); DatabaseEntry objData = new DatabaseEntry(); binding.objectToEntry(model, objData); ps1.setBytes(5, objData.getData()); ps1.executeUpdate(); } else if (persistenceMethod == PostgreSQLStore.OID || persistenceMethod == PostgreSQLStore.FIELDS) { ps1b.setString(1, model.getContig()); ps1b.setInt(2, model.getStartPosition()); ps1b.setInt(3, model.getStopPosition()); ps1b.setString(4, type); DatabaseEntry objData = new DatabaseEntry(); binding.objectToEntry(model, objData); int oid = lobj.create(LargeObjectManager.READ | LargeObjectManager.WRITE); LargeObject obj = lobj.open(oid, LargeObjectManager.WRITE); obj.write(objData.getData()); obj.close(); ps1b.setInt(5, oid); ps1b.executeUpdate(); } ResultSet rs = null; PreparedStatement ps = conn.prepareStatement("select currval('" + table + "_" + table + "_id_seq')"); rs = ps.executeQuery(); int modelId = -1; if (rs != null) { if (rs.next()) { modelId = rs.getInt(1); } } rs.close(); ps.close(); for (String key : model.getTags().keySet()) { int tagId = -1; if (tags.get(key) != null) { tagId = tags.get(key); } else { ps2.setString(1, key); rs = ps2.executeQuery(); if (rs != null) { while (rs.next()) { tagId = rs.getInt(1); } } rs.close(); } if (tagId < 0) { ps3.setString(1, key); ps3.setString(2, model.getTags().get(key)); ps3.executeUpdate(); rs = ps4.executeQuery(); if (rs != null) { if (rs.next()) { tagId = rs.getInt(1); tags.put(key, tagId); } } rs.close(); } ps5.setInt(1, tagId); ps5.executeUpdate(); } conn.commit(); return (new Long(modelId)); } catch (SQLException e) { try { conn.rollback(); } catch (SQLException e2) { e2.printStackTrace(); } e.printStackTrace(); System.err.println(e.getMessage()); } catch (Exception e) { try { conn.rollback(); } catch (SQLException e2) { e2.printStackTrace(); } e.printStackTrace(); System.err.println(e.getMessage()); } return (null); }
00
Code Sample 1: public static void bubbleSort(Auto[] xs) { boolean unsorted = true; while (unsorted) { unsorted = false; for (int i = 0; i < xs.length - 1; i++) { if (!(xs[i].getPreis() >= xs[i + 1].getPreis())) { Auto dummy = xs[i]; xs[i] = xs[i + 1]; xs[i + 1] = dummy; unsorted = true; } } } } Code Sample 2: private static Map<String, File> loadServiceCache() { ArrayList<String> preferredOrder = new ArrayList<String>(); HashMap<String, File> serviceFileMapping = new HashMap<String, File>(); File file = new File(IsqlToolkit.getBaseDirectory(), CACHE_FILE); if (!file.exists()) { return serviceFileMapping; } if (file.canRead()) { FileReader fileReader = null; try { fileReader = new FileReader(file); BufferedReader lineReader = new BufferedReader(fileReader); while (lineReader.ready()) { String data = lineReader.readLine(); if (data.charAt(0) == '#') { continue; } int idx0 = 0; int idx1 = data.indexOf(SERVICE_FIELD_SEPERATOR); String name = StringUtilities.decodeASCII(data.substring(idx0, idx1)); String uri = StringUtilities.decodeASCII(data.substring(idx1 + 1)); if (name.equalsIgnoreCase(KEY_SERVICE_LIST)) { StringTokenizer st = new StringTokenizer(uri, SERVICE_SEPERATOR); while (st.hasMoreTokens()) { String serviceName = st.nextToken(); preferredOrder.add(serviceName.toLowerCase().trim()); } continue; } try { URL url = new URL(uri); File serviceFile = new File(url.getFile()); if (serviceFile.isDirectory()) { logger.warn(messages.format("compatability_kit.service_mapped_to_directory", name, uri)); continue; } else if (!serviceFile.canRead()) { logger.warn(messages.format("compatability_kit.service_not_readable", name, uri)); continue; } else if (!serviceFile.exists()) { logger.warn(messages.format("compatability_kit.service_does_not_exist", name, uri)); continue; } String bindName = name.toLowerCase().trim(); InputStream inputStream = null; try { inputStream = url.openStream(); InputSource inputSource = new InputSource(inputStream); bindName = ServiceDigester.parseService(inputSource, IsqlToolkit.getSharedEntityResolver()).getName(); } catch (Exception error) { continue; } if (serviceFileMapping.put(bindName, serviceFile) != null) { logger.warn(messages.format("compatability_kit.service_duplicate_name_error", name, uri)); } } catch (MalformedURLException e) { logger.error(messages.format("compatability_kit.service_uri_error", name, uri), e); } } } catch (IOException ioe) { logger.error("compatability_kit.service_generic_error", ioe); } finally { if (fileReader != null) { try { fileReader.close(); } catch (Throwable ignored) { } } } } return serviceFileMapping; }
00
Code Sample 1: @Override public InputStream getDataStream(int bufferSize) throws IOException { InputStream in = manager == null ? url.openStream() : manager.getResourceInputStream(this); if (in instanceof ByteArrayInputStream || in instanceof BufferedInputStream) { return in; } return bufferSize == 0 ? new BufferedInputStream(in) : new BufferedInputStream(in, bufferSize); } Code Sample 2: @Test public void testEncryptDecrypt() throws IOException { BlockCipher cipher = new SerpentEngine(); Random rnd = new Random(); byte[] key = new byte[256 / 8]; rnd.nextBytes(key); byte[] iv = new byte[cipher.getBlockSize()]; rnd.nextBytes(iv); byte[] data = new byte[1230000]; new Random().nextBytes(data); ByteArrayOutputStream bout = new ByteArrayOutputStream(); CryptOutputStream eout = new CryptOutputStream(bout, cipher, key); eout.write(data); eout.close(); byte[] eData = bout.toByteArray(); ByteArrayInputStream bin = new ByteArrayInputStream(eData); CryptInputStream din = new CryptInputStream(bin, cipher, key); bout = new ByteArrayOutputStream(); IOUtils.copy(din, bout); eData = bout.toByteArray(); Assert.assertTrue(Arrays.areEqual(data, eData)); }
00
Code Sample 1: public HttpURLConnection getConnection(String urlString) throws IOException { URL url = new URL(urlString); HttpURLConnection connection = null; if (_proxy == null) { connection = (HttpURLConnection) url.openConnection(); } else { URLConnection con = url.openConnection(_proxy); String encodedUserPwd = new String(Base64.encodeBase64((_username + ":" + _password).getBytes())); con.setRequestProperty("Proxy-Authorization", "Basic " + encodedUserPwd); connection = (HttpURLConnection) con; } return connection; } 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; }
11
Code Sample 1: @Action(value = "ajaxFileUploads", results = { }) public void ajaxFileUploads() throws IOException { String extName = ""; String newFilename = ""; String nowTimeStr = ""; String realpath = ""; if (Validate.StrNotNull(this.getImgdirpath())) { realpath = "Uploads/" + this.getImgdirpath() + "/"; } else { realpath = this.isexistdir(); } SimpleDateFormat sDateFormat; Random r = new Random(); String savePath = ServletActionContext.getServletContext().getRealPath(""); savePath = savePath + realpath; HttpServletResponse response = ServletActionContext.getResponse(); int rannum = (int) (r.nextDouble() * (99999 - 1000 + 1)) + 10000; sDateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); nowTimeStr = sDateFormat.format(new Date()); String filename = request.getHeader("X-File-Name"); if (filename.lastIndexOf(".") >= 0) { extName = filename.substring(filename.lastIndexOf(".")); } newFilename = nowTimeStr + rannum + extName; PrintWriter writer = null; InputStream is = null; FileOutputStream fos = null; try { writer = response.getWriter(); } catch (IOException ex) { log.debug(ImgTAction.class.getName() + "has thrown an exception:" + ex.getMessage()); } try { is = request.getInputStream(); fos = new FileOutputStream(new File(savePath + newFilename)); IOUtils.copy(is, fos); response.setStatus(response.SC_OK); writer.print("{success:'" + realpath + newFilename + "'}"); } catch (FileNotFoundException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log.debug(ImgTAction.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log.debug(ImgTAction.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { this.setImgdirpath(null); fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); } Code Sample 2: public static void main(String[] args) { if (args.length <= 0) { System.out.println(" *** SQL script generator and executor ***"); System.out.println(" You must specify name of the file with SQL script data"); System.out.println(" Fisrt rows of this file must be:"); System.out.println(" 1) JDBC driver class for your DBMS"); System.out.println(" 2) URL for your database instance"); System.out.println(" 3) user in that database (with administrator priviliges)"); System.out.println(" 4) password of that user"); System.out.println(" Next rows can have: '@' before schema to create,"); System.out.println(" '#' before table to create, '&' before table to insert,"); System.out.println(" '$' before trigger (inverse 'FK on delete cascade') to create,"); System.out.println(" '>' before table to drop, '<' before schema to drop."); System.out.println(" Other rows contain parameters of these actions:"); System.out.println(" for & action each parameter is a list of values,"); System.out.println(" for @ -//- is # acrion, for # -//- is column/constraint "); System.out.println(" definition or $ action. $ syntax to delete from table:"); System.out.println(" fullNameOfTable:itsColInWhereClause=matchingColOfThisTable"); System.out.println(" '!' before row means that it is a comment."); System.out.println(" If some exception is occured, all script is rolled back."); System.out.println(" If you specify 2nd command line argument - file name too -"); System.out.println(" connection will be established but all statements will"); System.out.println(" be saved in that output file and not transmitted to DB"); System.out.println(" If you specify 3nd command line argument - connect_string -"); System.out.println(" connect information will be added to output file"); System.out.println(" in the form 'connect user/password@connect_string'"); System.exit(0); } try { String[] info = new String[4]; BufferedReader reader = new BufferedReader(new FileReader(new File(args[0]))); Writer writer = null; try { for (int i = 0; i < 4; i++) info[i] = reader.readLine(); try { Class.forName(info[0]); Connection connection = DriverManager.getConnection(info[1], info[2], info[3]); SQLScript script = new SQLScript(connection); if (args.length > 1) { writer = new FileWriter(args[1]); if (args.length > 2) writer.write("connect " + info[2] + "/" + info[3] + "@" + args[2] + script.statementTerminator); } try { System.out.println(script.executeScript(reader, writer) + " updates has been performed during script execution"); } catch (SQLException e4) { reader.close(); if (writer != null) writer.close(); System.out.println(" Script execution error: " + e4); } connection.close(); } catch (Exception e3) { reader.close(); if (writer != null) writer.close(); System.out.println(" Connection error: " + e3); } } catch (IOException e2) { System.out.println("Error in file " + args[0]); } } catch (FileNotFoundException e1) { System.out.println("File " + args[0] + " not found"); } }
11
Code Sample 1: public static void main(String[] args) throws IOException, DataFormatException { byte in_buf[] = new byte[20000]; if (args.length < 2) { System.out.println("too few arguments"); System.exit(0); } String inputName = args[0]; InputStream in = new FileInputStream(inputName); int index = 0; for (int i = 1; i < args.length; i++) { int size = Integer.parseInt(args[i]); boolean copy = size >= 0; if (size < 0) { size = -size; } OutputStream out = null; if (copy) { index++; out = new FileOutputStream(inputName + "." + index + ".dat"); } while (size > 0) { int read = in.read(in_buf, 0, Math.min(in_buf.length, size)); if (read < 0) { break; } size -= read; if (copy) { out.write(in_buf, 0, read); } } if (copy) { out.close(); } } index++; OutputStream out = new FileOutputStream(inputName + "." + index + ".dat"); while (true) { int read = in.read(in_buf); if (read < 0) { break; } out.write(in_buf, 0, read); } out.close(); in.close(); } Code Sample 2: public BufferedWriter createWriter(File outfile, String encoding) throws UnsupportedEncodingException, IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outfile)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot; ZipInputStream zis = new ZipInputStream(new FileInputStream(infile)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); return new BufferedWriter(new OutputStreamWriter(zos, "UTF-8")); }
00
Code Sample 1: public static void extract(final File destDir, final ZipInfo zipInfo, final IProgressMonitor monitor) throws IOException { if (!destDir.exists()) destDir.mkdirs(); for (String key : zipInfo.getEntryKeys()) { ZipEntry entry = zipInfo.getEntry(key); InputStream in = zipInfo.getInputStream(entry); File entryDest = new File(destDir, entry.getName()); entryDest.getParentFile().mkdirs(); if (!entry.isDirectory()) { OutputStream out = new FileOutputStream(new File(destDir, entry.getName())); try { IOUtils.copy(in, out); out.flush(); if (monitor != null) monitor.worked(1); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } } if (monitor != null) monitor.done(); } Code Sample 2: public static final String getUniqueKey() { String digest = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); String timeVal = "" + (System.currentTimeMillis() + 1); String localHost = ""; ; try { localHost = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { println("Warn: getUniqueKey(), Error trying to get localhost" + e.getMessage()); } String randVal = "" + new Random().nextInt(); String val = timeVal + localHost + randVal; md.reset(); md.update(val.getBytes()); digest = toHexString(md.digest()); } catch (NoSuchAlgorithmException e) { println("Warn: getUniqueKey() " + e); } return digest; }
00
Code Sample 1: protected String getPageText(final String url) { StringBuilder b = new StringBuilder(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String line = null; while ((line = reader.readLine()) != null) { b.append(line).append('\n'); } } catch (IOException ex) { ex.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException ex) { ex.printStackTrace(); } } } return b.toString(); } Code Sample 2: public static void copyFile(File in, File out) throws ObclipseException { try { FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(in).getChannel(); outChannel = new FileOutputStream(out).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } catch (FileNotFoundException e) { Msg.error("The file ''{0}'' to copy does not exist!", e, in.getAbsolutePath()); } catch (IOException e) { Msg.ioException(in, out, e); } }
00
Code Sample 1: public void display(WebPage page, HttpServletRequest req, HttpServletResponse resp) throws DisplayException { page.getDisplayInitialiser().initDisplay(new HttpRequestDisplayContext(req), req); StreamProvider is = (StreamProvider) req.getAttribute(INPUTSTREAM_KEY); if (is == null) { throw new IllegalStateException("No OutputStreamDisplayHandlerXML.InputStream found in request attribute" + " OutputStreamDisplayHandlerXML.INPUTSTREAM_KEY"); } resp.setContentType(is.getMimeType()); resp.setHeader("Content-Disposition", "attachment;filename=" + is.getName()); try { InputStream in = is.getInputStream(); OutputStream out = resp.getOutputStream(); if (in != null) { IOUtils.copy(in, out); } is.write(resp.getOutputStream()); resp.flushBuffer(); } catch (IOException e) { throw new DisplayException("Error writing input stream to response", e); } } Code Sample 2: public void reset(int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? "); psta.setInt(1, currentPilot); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
11
Code Sample 1: public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; } Code Sample 2: public String copyImages(Document doc, String sXML, String newPath, String tagName, String itemName) { NodeList nl = null; Node n = null; NamedNodeMap nnp = null; Node nsrc = null; URL url = null; String sFilename = ""; String sNewPath = ""; int index; String sOldPath = ""; try { nl = doc.getElementsByTagName(tagName); for (int i = 0; i < nl.getLength(); i++) { n = nl.item(i); nnp = n.getAttributes(); nsrc = nnp.getNamedItem(itemName); String sTemp = nsrc.getTextContent(); url = new URL("file", "localhost", sTemp); sOldPath = url.getPath(); sOldPath = sOldPath.replace('/', File.separatorChar); int indexFirstSlash = sOldPath.indexOf(File.separatorChar); String sSourcePath; if (itemName.equals("data")) sSourcePath = sOldPath; else sSourcePath = sOldPath.substring(indexFirstSlash + 1); index = sOldPath.lastIndexOf(File.separatorChar); sFilename = sOldPath.substring(index + 1); sNewPath = newPath + 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(); } sXML = sXML.replace(nsrc.getTextContent(), sFilename); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return sXML; }
00
Code Sample 1: public static void runDBUpdate() { if (!updateRunning) { if (updateJob != null) updateJob.cancel(); updateJob = new Job("Worm Database Update") { protected IStatus run(IProgressMonitor monitor) { try { updateRunning = true; distributor = getFromFile("[SERVER]", "csz", getAppPath() + "/server.ini"); MAC = getFromFile("[SPECIFICINFO]", "MAC", getAppPath() + "/register.ini"); serial = getFromFile("[SPECIFICINFO]", "serial", getAppPath() + "/register.ini"); if (MAC.equals("not_found") || serial.equals("not_found") || !serial.startsWith(distributor)) { try { MAC = getFromFile("[SPECIFICINFO]", "MAC", getAppPath() + "/register.ini"); serial = getFromFile("[SPECIFICINFO]", "serial", getAppPath() + "/register.ini"); } catch (Exception e) { System.out.println(e); } } else { try { url = new URL("http://" + getFromFile("[SERVER]", "url", getAppPath() + "/server.ini")); } catch (MalformedURLException e) { System.out.println(e); } download = "/download2.php?distributor=" + distributor + "&&mac=" + MAC + "&&serial=" + serial; readXML(); if (htmlMessage.contains("error")) { try { PrintWriter pw = new PrintWriter(getAppPath() + "/register.ini"); pw.write(""); pw.close(); } catch (IOException e) { System.out.println(e); } setProperty(IProgressConstants.ICON_PROPERTY, IconImg.liveUpIco); if (isModal(this)) { showResults2(); } else { setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE); setProperty(IProgressConstants.ACTION_PROPERTY, getUpdateCompletedAction2()); } } else { if (!getDBVersion().equals(latestVersion)) { try { OutputStream out = null; HttpURLConnection conn = null; InputStream in = null; int size; try { URL url = new URL(fileLoc); String outFile = getAppPath() + "/temp/" + getFileName(url); File oFile = new File(outFile); oFile.delete(); out = new BufferedOutputStream(new FileOutputStream(outFile)); monitor.beginTask("Connecting to NWD Server", 100); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(20000); conn.connect(); if (conn.getResponseCode() / 100 != 2) { System.out.println("Error: " + conn.getResponseCode()); return null; } monitor.worked(100); monitor.done(); size = conn.getContentLength(); monitor.beginTask("Download Worm Definition", size); in = conn.getInputStream(); byte[] buffer; String downloadedSize; long numWritten = 0; boolean status = true; while (status) { if (size - numWritten > 1024) { buffer = new byte[1024]; } else { buffer = new byte[(int) (size - numWritten)]; } int read = in.read(buffer); if (read == -1) { break; } out.write(buffer, 0, read); numWritten += read; downloadedSize = Long.toString(numWritten / 1024) + " KB"; monitor.worked(read); monitor.subTask(downloadedSize + " of " + Integer.toString(size / 1024) + " KB"); if (size == numWritten) { status = false; } if (monitor.isCanceled()) return Status.CANCEL_STATUS; } if (in != null) { in.close(); } if (out != null) { out.close(); } try { ZipFile zFile = new ZipFile(outFile); Enumeration all = zFile.entries(); while (all.hasMoreElements()) { ZipEntry zEntry = (ZipEntry) all.nextElement(); long zSize = zEntry.getSize(); if (zSize > 0) { if (zEntry.getName().endsWith("script")) { InputStream instream = zFile.getInputStream(zEntry); FileOutputStream fos = new FileOutputStream(oldLoc[0]); int ch; while ((ch = instream.read()) != -1) { fos.write(ch); } instream.close(); fos.close(); } else if (zEntry.getName().endsWith("data")) { InputStream instream = zFile.getInputStream(zEntry); FileOutputStream fos = new FileOutputStream(oldLoc[1]); int ch; while ((ch = instream.read()) != -1) { fos.write(ch); } instream.close(); fos.close(); } } } File xFile = new File(outFile); xFile.deleteOnExit(); } catch (Exception e) { e.printStackTrace(); } try { monitor.done(); monitor.beginTask("Install Worm Definition", 10000); monitor.worked(2500); CorePlugin.getDefault().getRawPacketHandler().removeRawPacketListener(p); p = null; if (!wormDB.getConn().isClosed()) { shutdownDB(); } System.out.println(wormDB.getConn().isClosed()); for (int i = 0; i < 2; i++) { try { Process pid = Runtime.getRuntime().exec("cmd /c copy \"" + oldLoc[i].replace("/", "\\") + "\" \"" + newLoc[i].replace("/", "\\") + "\"/y"); } catch (Exception e) { e.printStackTrace(); } new File(oldLoc[i]).deleteOnExit(); } monitor.worked(2500); initialArray(); p = new PacketPrinter(); CorePlugin.getDefault().getRawPacketHandler().addRawPacketListener(p); monitor.worked(2500); monitor.done(); setProperty(IProgressConstants.ICON_PROPERTY, IconImg.liveUpIco); if (isModal(this)) { showResults(); } else { setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE); setProperty(IProgressConstants.ACTION_PROPERTY, getUpdateCompletedAction()); } } catch (Exception e) { setProperty(IProgressConstants.ICON_PROPERTY, IconImg.liveUpIco); if (isModal(this)) { showResults2(); } else { setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE); setProperty(IProgressConstants.ACTION_PROPERTY, getUpdateCompletedAction2()); } System.out.println(e); } finally { } } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { setProperty(IProgressConstants.ICON_PROPERTY, IconImg.liveUpIco); if (isModal(this)) { showResults2(); } else { setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE); setProperty(IProgressConstants.ACTION_PROPERTY, getUpdateCompletedAction2()); } e.printStackTrace(); } } else { cancel(); setProperty(IProgressConstants.ICON_PROPERTY, IconImg.liveUpIco); if (isModal(this)) { showResults1(); } else { setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE); setProperty(IProgressConstants.ACTION_PROPERTY, getUpdateCompletedAction1()); } } } } return Status.OK_STATUS; } catch (Exception e) { showResults2(); return Status.OK_STATUS; } finally { lock.release(); updateRunning = false; if (getValue("AUTO_UPDATE")) schedule(10800000); } } }; updateJob.schedule(); } } Code Sample 2: @edu.umd.cs.findbugs.annotations.SuppressWarnings({ "DLS", "REC" }) public static String shaEncode(String val) { String output = null; try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(val.getBytes()); byte[] digest = md.digest(); output = base64Encode(digest); } catch (Exception e) { } return output; }
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: public static String hash(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
00
Code Sample 1: 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: protected InputStream openStreamInternal(String userAgent, Iterator mimeTypes, Iterator encodingTypes) throws IOException { if (stream != null) return stream; hasBeenOpened = true; URL url = null; try { url = buildURL(); } catch (MalformedURLException mue) { throw new IOException("Unable to make sense of URL for connection"); } if (url == null) return null; URLConnection urlC = url.openConnection(); if (urlC instanceof HttpURLConnection) { if (userAgent != null) urlC.setRequestProperty(HTTP_USER_AGENT_HEADER, userAgent); if (mimeTypes != null) { String acceptHeader = ""; while (mimeTypes.hasNext()) { acceptHeader += mimeTypes.next(); if (mimeTypes.hasNext()) acceptHeader += ","; } urlC.setRequestProperty(HTTP_ACCEPT_HEADER, acceptHeader); } if (encodingTypes != null) { String encodingHeader = ""; while (encodingTypes.hasNext()) { encodingHeader += encodingTypes.next(); if (encodingTypes.hasNext()) encodingHeader += ","; } urlC.setRequestProperty(HTTP_ACCEPT_ENCODING_HEADER, encodingHeader); } contentType = urlC.getContentType(); contentEncoding = urlC.getContentEncoding(); } return (stream = urlC.getInputStream()); }
11
Code Sample 1: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public void extractPrincipalClasses(String[] info, int numFiles) { String methodName = ""; String finalClass = ""; String WA; String MC; String RA; int[] readCount = new int[numFiles]; int[] writeCount = new int[numFiles]; int[] methodCallCount = new int[numFiles]; int writeMax1; int writeMax2; int readMax; int methodCallMax; int readMaxIndex = 0; int writeMaxIndex1 = 0; int writeMaxIndex2; int methodCallMaxIndex = 0; try { MethodsDestClass = new BufferedWriter(new FileWriter("InfoFiles/MethodsDestclass.txt")); FileInputStream fstreamWriteAttr = new FileInputStream("InfoFiles/WriteAttributes.txt"); DataInputStream inWriteAttr = new DataInputStream(fstreamWriteAttr); BufferedReader writeAttr = new BufferedReader(new InputStreamReader(inWriteAttr)); FileInputStream fstreamMethodsCalled = new FileInputStream("InfoFiles/MethodsCalled.txt"); DataInputStream inMethodsCalled = new DataInputStream(fstreamMethodsCalled); BufferedReader methodsCalled = new BufferedReader(new InputStreamReader(inMethodsCalled)); FileInputStream fstreamReadAttr = new FileInputStream("InfoFiles/ReadAttributes.txt"); DataInputStream inReadAttr = new DataInputStream(fstreamReadAttr); BufferedReader readAttr = new BufferedReader(new InputStreamReader(inReadAttr)); while ((WA = writeAttr.readLine()) != null && (RA = readAttr.readLine()) != null && (MC = methodsCalled.readLine()) != null) { WA = writeAttr.readLine(); RA = readAttr.readLine(); MC = methodsCalled.readLine(); while (WA.compareTo("EndOfClass") != 0 && RA.compareTo("EndOfClass") != 0 && MC.compareTo("EndOfClass") != 0) { methodName = writeAttr.readLine(); readAttr.readLine(); methodsCalled.readLine(); WA = writeAttr.readLine(); MC = methodsCalled.readLine(); RA = readAttr.readLine(); while (true) { if (WA.compareTo("EndOfMethod") == 0 && RA.compareTo("EndOfMethod") == 0 && MC.compareTo("EndOfMethod") == 0) { break; } if (WA.compareTo("EndOfMethod") != 0) { if (WA.indexOf(".") > 0) { WA = WA.substring(0, WA.indexOf(".")); } } if (RA.compareTo("EndOfMethod") != 0) { if (RA.indexOf(".") > 0) { RA = RA.substring(0, RA.indexOf(".")); } } if (MC.compareTo("EndOfMethod") != 0) { if (MC.indexOf(".") > 0) { MC = MC.substring(0, MC.indexOf(".")); } } for (int i = 0; i < numFiles && info[i] != null; i++) { if (info[i].compareTo(WA) == 0) { writeCount[i]++; } if (info[i].compareTo(RA) == 0) { readCount[i]++; } if (info[i].compareTo(MC) == 0) { methodCallCount[i]++; } } if (WA.compareTo("EndOfMethod") != 0) { WA = writeAttr.readLine(); } if (MC.compareTo("EndOfMethod") != 0) { MC = methodsCalled.readLine(); } if (RA.compareTo("EndOfMethod") != 0) { RA = readAttr.readLine(); } } WA = writeAttr.readLine(); MC = methodsCalled.readLine(); RA = readAttr.readLine(); writeMax1 = writeCount[0]; writeMaxIndex1 = 0; for (int i = 1; i < numFiles; i++) { if (writeCount[i] > writeMax1) { writeMax1 = writeCount[i]; writeMaxIndex1 = i; } } writeCount[writeMaxIndex1] = 0; writeMax2 = writeCount[0]; writeMaxIndex2 = 0; for (int i = 1; i < numFiles; i++) { if (writeCount[i] > writeMax2) { writeMax2 = writeCount[i]; writeMaxIndex2 = i; } } readMax = readCount[0]; readMaxIndex = 0; for (int i = 1; i < numFiles; i++) { if (readCount[i] > readMax) { readMax = readCount[i]; readMaxIndex = i; } } methodCallMax = methodCallCount[0]; methodCallMaxIndex = 0; for (int i = 1; i < numFiles; i++) { if (methodCallCount[i] > methodCallMax) { methodCallMax = methodCallCount[i]; methodCallMaxIndex = i; } } boolean isNotEmpty = false; if (writeMax1 > 0 && writeMax2 == 0) { finalClass = info[writeMaxIndex1]; isNotEmpty = true; } else if (writeMax1 == 0) { if (readMax != 0) { finalClass = info[readMaxIndex]; isNotEmpty = true; } else if (methodCallMax != 0) { finalClass = info[methodCallMaxIndex]; isNotEmpty = true; } } if (isNotEmpty == true) { MethodsDestClass.write(methodName); MethodsDestClass.newLine(); MethodsDestClass.write(finalClass); MethodsDestClass.newLine(); isNotEmpty = false; } for (int j = 0; j < numFiles; j++) { readCount[j] = 0; writeCount[j] = 0; methodCallCount[j] = 0; } } } writeAttr.close(); methodsCalled.close(); readAttr.close(); MethodsDestClass.close(); int sizeInfoArray = 0; sizeInfoArray = infoArraySize(); boolean classWritten = false; principleClass = new String[100]; principleMethod = new String[100]; principleMethodsClass = new String[100]; String infoArray[] = new String[sizeInfoArray]; String field; int counter = 0; FileInputStream fstreamDestMethod = new FileInputStream("InfoFiles/MethodsDestclass.txt"); DataInputStream inDestMethod = new DataInputStream(fstreamDestMethod); BufferedReader destMethod = new BufferedReader(new InputStreamReader(inDestMethod)); PrincipleClassGroup = new BufferedWriter(new FileWriter("InfoFiles/PrincipleClassGroup.txt")); while ((field = destMethod.readLine()) != null) { infoArray[counter] = field; counter++; } for (int i = 0; i < numFiles; i++) { for (int j = 0; j < counter - 1 && info[i] != null; j++) { if (infoArray[j + 1].compareTo(info[i]) == 0) { if (classWritten == false) { PrincipleClassGroup.write(infoArray[j + 1]); PrincipleClassGroup.newLine(); principleClass[principleClassCount] = infoArray[j + 1]; principleClassCount++; classWritten = true; } PrincipleClassGroup.write(infoArray[j]); principleMethod[principleMethodCount] = infoArray[j]; principleMethodsClass[principleMethodCount] = infoArray[j + 1]; principleMethodCount++; PrincipleClassGroup.newLine(); } } if (classWritten == true) { PrincipleClassGroup.write("EndOfClass"); PrincipleClassGroup.newLine(); classWritten = false; } } destMethod.close(); PrincipleClassGroup.close(); readFileCount = readFileCount(); writeFileCount = writeFileCount(); methodCallFileCount = methodCallFileCount(); readArray = new String[readFileCount]; writeArray = new String[writeFileCount]; callArray = new String[methodCallFileCount]; initializeArrays(); constructFundamentalView(); constructInteractionView(); constructAssociationView(); } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: public static void upLoadFile(File sourceFile, File targetFile) throws IOException { FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(sourceFile).getChannel(); outChannel = new FileOutputStream(targetFile).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } finally { try { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } catch (IOException e) { e.printStackTrace(); } } } Code Sample 2: private static void compressZip(String source, String dest) throws Exception { File baseFolder = new File(source); if (baseFolder.exists()) { if (baseFolder.isDirectory()) { List<File> fileList = getSubFiles(new File(source)); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(dest)); zos.setEncoding("GBK"); ZipEntry entry = null; byte[] buf = new byte[2048]; int readLen = 0; for (int i = 0; i < fileList.size(); i++) { File file = fileList.get(i); if (file.isDirectory()) { entry = new ZipEntry(getAbsFileName(source, file) + "/"); } else { entry = new ZipEntry(getAbsFileName(source, file)); } entry.setSize(file.length()); entry.setTime(file.lastModified()); zos.putNextEntry(entry); if (file.isFile()) { InputStream in = new BufferedInputStream(new FileInputStream(file)); while ((readLen = in.read(buf, 0, 1024)) != -1) { zos.write(buf, 0, readLen); } in.close(); } } zos.close(); } else { throw new Exception("Can not do this operation!."); } } else { baseFolder.mkdirs(); compressZip(source, dest); } }
11
Code Sample 1: public int deleteRecord(Publisher publisher, MmdQueryCriteria criteria) throws Exception { int nRows = 0; if (!publisher.getIsAdministrator()) { throw new ImsServiceException("DeleteRecordsRequest: not authorized."); } PreparedStatement st = null; ManagedConnection mc = returnConnection(); Connection con = mc.getJdbcConnection(); DatabaseMetaData dmt = con.getMetaData(); String database = dmt.getDatabaseProductName().toLowerCase(); boolean autoCommit = con.getAutoCommit(); con.setAutoCommit(false); try { StringBuilder sbWhere = new StringBuilder(); Map<String, Object> args = criteria.appendWherePhrase(null, sbWhere, publisher); StringBuilder sbData = new StringBuilder(); if (database.contains("mysql")) { sbData.append(" DELETE ").append(getResourceDataTableName()).append(" FROM ").append(getResourceDataTableName()); sbData.append(" LEFT JOIN ").append(getResourceTableName()); sbData.append(" ON ").append(getResourceDataTableName()).append(".ID=").append(getResourceTableName()).append(".ID WHERE ").append(getResourceTableName()).append(".ID in ("); sbData.append(" SELECT ID FROM ").append(getResourceTableName()).append(" "); if (sbWhere.length() > 0) { sbData.append(" WHERE ").append(sbWhere.toString()); } sbData.append(")"); } else { sbData.append(" DELETE FROM ").append(getResourceDataTableName()); sbData.append(" WHERE ").append(getResourceDataTableName()).append(".ID in ("); sbData.append(" SELECT ID FROM ").append(getResourceTableName()).append(" "); if (sbWhere.length() > 0) { sbData.append(" WHERE ").append(sbWhere.toString()); } sbData.append(")"); } st = con.prepareStatement(sbData.toString()); criteria.applyArgs(st, 1, args); logExpression(sbData.toString()); st.executeUpdate(); StringBuilder sbSql = new StringBuilder(); sbSql.append("DELETE FROM ").append(getResourceTableName()).append(" "); if (sbWhere.length() > 0) { sbSql.append(" WHERE ").append(sbWhere.toString()); } closeStatement(st); st = con.prepareStatement(sbSql.toString()); criteria.applyArgs(st, 1, args); logExpression(sbSql.toString()); nRows = st.executeUpdate(); con.commit(); } catch (Exception ex) { con.rollback(); throw ex; } finally { closeStatement(st); con.setAutoCommit(autoCommit); } return nRows; } Code Sample 2: public void insertComponent() throws SQLException { Connection connection = null; PreparedStatement ps = null; try { Class.forName("com.mysql.jdbc.Driver"); connection = (Connection) DriverManager.getConnection(this.jdbcURL); connection.setAutoCommit(false); String query = "INSERT INTO components(name,rate,quantity, description) VALUES(?,?,?,?)"; ps = (PreparedStatement) connection.prepareStatement(query); ps.setString(1, this.name); ps.setDouble(2, this.rate); ps.setInt(3, this.quantity); ps.setString(4, this.description); ps.executeUpdate(); connection.commit(); } catch (Exception ex) { connection.rollback(); } finally { try { connection.close(); } catch (Exception ex) { } try { ps.close(); } catch (Exception ex) { } } }
00
Code Sample 1: public String GetUserPage(String User, int pagetocrawl) { int page = pagetocrawl; URL url; String line, finalstring; StringBuffer buffer = new StringBuffer(); setStatus("Start moling...."); startTimer(); try { url = new URL(HTMLuserpage + User + "?setcount=100&page=" + page); HttpURLConnection connect = (HttpURLConnection) url.openConnection(); connect.addRequestProperty("User-Agent", userAgent); System.out.println("moling: page " + page + " of " + User); BufferedReader input = new BufferedReader(new InputStreamReader(connect.getInputStream())); while ((line = input.readLine()) != null) { buffer.append(line); buffer.append("\n"); } input.close(); connect.disconnect(); stopTimer(); setStatus("Dauer : " + dauerMs() + " ms"); finalstring = buffer.toString(); return finalstring; } catch (MalformedURLException e) { System.err.println("Bad URL: " + e); return null; } catch (IOException io) { System.err.println("IOException: " + io); return null; } } Code Sample 2: private static void copy(String sourceName, String destName) throws IOException { File source = new File(sourceName); File dest = new File(destName); FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
11
Code Sample 1: public void copy(File from, String to) throws SystemException { assert from != null; File dst = new File(folder, to); dst.getParentFile().mkdirs(); FileChannel in = null; FileChannel out = null; try { if (!dst.exists()) dst.createNewFile(); in = new FileInputStream(from).getChannel(); out = new FileOutputStream(dst).getChannel(); in.transferTo(0, in.size(), out); } catch (IOException e) { throw new SystemException(e); } finally { try { if (in != null) in.close(); } catch (Exception e1) { } try { if (out != null) out.close(); } catch (Exception e1) { } } } Code Sample 2: public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { long time = System.currentTimeMillis(); String text = request.getParameter("text"); String parsedQueryString = request.getQueryString(); if (text == null) { String[] fonts = new File(ctx.getRealPath("/WEB-INF/fonts/")).list(); text = "accepted params: text,font,size,color,background,nocache,aa,break"; response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<p>"); out.println("Usage: " + request.getServletPath() + "?params[]<BR>"); out.println("Acceptable Params are: <UL>"); out.println("<LI><B>text</B><BR>"); out.println("The body of the image"); out.println("<LI><B>font</B><BR>"); out.println("Available Fonts (in folder '/WEB-INF/fonts/') <UL>"); for (int i = 0; i < fonts.length; i++) { if (!"CVS".equals(fonts[i])) { out.println("<LI>" + fonts[i]); } } out.println("</UL>"); out.println("<LI><B>size</B><BR>"); out.println("An integer, i.e. size=100"); out.println("<LI><B>color</B><BR>"); out.println("in rgb, i.e. color=255,0,0"); out.println("<LI><B>background</B><BR>"); out.println("in rgb, i.e. background=0,0,255"); out.println("transparent, i.e. background=''"); out.println("<LI><B>aa</B><BR>"); out.println("antialias (does not seem to work), aa=true"); out.println("<LI><B>nocache</B><BR>"); out.println("if nocache is set, we will write out the image file every hit. Otherwise, will write it the first time and then read the file"); out.println("<LI><B>break</B><BR>"); out.println("An integer greater than 0 (zero), i.e. break=20"); out.println("</UL>"); out.println("</UL>"); out.println("Example:<BR>"); out.println("&lt;img border=1 src=\"" + request.getServletPath() + "?font=arial.ttf&text=testing&color=255,0,0&size=100\"&gt;<BR>"); out.println("<img border=1 src='" + request.getServletPath() + "?font=arial.ttf&text=testing&color=255,0,0&size=100'><BR>"); out.println("</body>"); out.println("</html>"); return; } String myFile = (request.getQueryString() == null) ? "empty" : PublicEncryptionFactory.digestString(parsedQueryString).replace('\\', '_').replace('/', '_'); myFile = Config.getStringProperty("PATH_TO_TITLE_IMAGES") + myFile + ".png"; File file = new File(ctx.getRealPath(myFile)); if (!file.exists() || (request.getParameter("nocache") != null)) { StringTokenizer st = null; Iterator i = hm.entrySet().iterator(); while (i.hasNext()) { Map.Entry entry = (Map.Entry) i.next(); String key = (String) entry.getKey(); if (parsedQueryString.indexOf(key) > -1) { String val = (String) entry.getValue(); parsedQueryString = UtilMethods.replace(parsedQueryString, key, val); } } st = new StringTokenizer(parsedQueryString, "&"); while (st.hasMoreTokens()) { try { String x = st.nextToken(); String key = x.split("=")[0]; String val = x.split("=")[1]; if ("text".equals(key)) { text = val; } } catch (Exception e) { } } text = URLDecoder.decode(text, "UTF-8"); Logger.debug(this.getClass(), "building title image:" + file.getAbsolutePath()); file.createNewFile(); try { String font_file = "/WEB-INF/fonts/arial.ttf"; if (request.getParameter("font") != null) { font_file = "/WEB-INF/fonts/" + request.getParameter("font"); } font_file = ctx.getRealPath(font_file); float size = 20.0f; if (request.getParameter("size") != null) { size = Float.parseFloat(request.getParameter("size")); } Color background = Color.white; if (request.getParameter("background") != null) { if (request.getParameter("background").equals("transparent")) try { background = new Color(Color.TRANSLUCENT); } catch (Exception e) { } else try { st = new StringTokenizer(request.getParameter("background"), ","); int x = Integer.parseInt(st.nextToken()); int y = Integer.parseInt(st.nextToken()); int z = Integer.parseInt(st.nextToken()); background = new Color(x, y, z); } catch (Exception e) { } } Color color = Color.black; if (request.getParameter("color") != null) { try { st = new StringTokenizer(request.getParameter("color"), ","); int x = Integer.parseInt(st.nextToken()); int y = Integer.parseInt(st.nextToken()); int z = Integer.parseInt(st.nextToken()); color = new Color(x, y, z); } catch (Exception e) { Logger.info(this, e.getMessage()); } } int intBreak = 0; if (request.getParameter("break") != null) { try { intBreak = Integer.parseInt(request.getParameter("break")); } catch (Exception e) { } } java.util.ArrayList<String> lines = null; if (intBreak > 0) { lines = new java.util.ArrayList<String>(10); lines.ensureCapacity(10); int start = 0; String line = null; int offSet; for (; ; ) { try { for (; isWhitespace(text.charAt(start)); ++start) ; if (isWhitespace(text.charAt(start + intBreak - 1))) { lines.add(text.substring(start, start + intBreak)); start += intBreak; } else { for (offSet = -1; !isWhitespace(text.charAt(start + intBreak + offSet)); ++offSet) ; lines.add(text.substring(start, start + intBreak + offSet)); start += intBreak + offSet; } } catch (Exception e) { if (text.length() > start) lines.add(leftTrim(text.substring(start))); break; } } } else { java.util.StringTokenizer tokens = new java.util.StringTokenizer(text, "|"); if (tokens.hasMoreTokens()) { lines = new java.util.ArrayList<String>(10); lines.ensureCapacity(10); for (; tokens.hasMoreTokens(); ) lines.add(leftTrim(tokens.nextToken())); } } Font font = Font.createFont(Font.TRUETYPE_FONT, new FileInputStream(font_file)); font = font.deriveFont(size); BufferedImage buffer = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = buffer.createGraphics(); if (request.getParameter("aa") != null) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); } else { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } FontRenderContext fc = g2.getFontRenderContext(); Rectangle2D fontBounds = null; Rectangle2D textLayoutBounds = null; TextLayout tl = null; boolean useTextLayout = false; useTextLayout = Boolean.parseBoolean(request.getParameter("textLayout")); int width = 0; int height = 0; int offSet = 0; if (1 < lines.size()) { int heightMultiplier = 0; int maxWidth = 0; for (; heightMultiplier < lines.size(); ++heightMultiplier) { fontBounds = font.getStringBounds(lines.get(heightMultiplier), fc); tl = new TextLayout(lines.get(heightMultiplier), font, fc); textLayoutBounds = tl.getBounds(); if (maxWidth < Math.ceil(fontBounds.getWidth())) maxWidth = (int) Math.ceil(fontBounds.getWidth()); } width = maxWidth; int boundHeigh = (int) Math.ceil((!useTextLayout ? fontBounds.getHeight() : textLayoutBounds.getHeight())); height = boundHeigh * lines.size(); offSet = ((int) (boundHeigh * 0.2)) * (lines.size() - 1); } else { fontBounds = font.getStringBounds(text, fc); tl = new TextLayout(text, font, fc); textLayoutBounds = tl.getBounds(); width = (int) fontBounds.getWidth(); height = (int) Math.ceil((!useTextLayout ? fontBounds.getHeight() : textLayoutBounds.getHeight())); } buffer = new BufferedImage(width, height - offSet, BufferedImage.TYPE_INT_ARGB); g2 = buffer.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setFont(font); g2.setColor(background); if (!background.equals(new Color(Color.TRANSLUCENT))) g2.fillRect(0, 0, width, height); g2.setColor(color); if (1 < lines.size()) { for (int numLine = 0; numLine < lines.size(); ++numLine) { int y = (int) Math.ceil((!useTextLayout ? fontBounds.getY() : textLayoutBounds.getY())); g2.drawString(lines.get(numLine), 0, -y * (numLine + 1)); } } else { int y = (int) Math.ceil((!useTextLayout ? fontBounds.getY() : textLayoutBounds.getY())); g2.drawString(text, 0, -y); } BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file)); ImageIO.write(buffer, "png", out); out.close(); } catch (Exception ex) { Logger.info(this, ex.toString()); } } response.setContentType("image/png"); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); OutputStream os = response.getOutputStream(); byte[] buf = new byte[4096]; int i = 0; while ((i = bis.read(buf)) != -1) { os.write(buf, 0, i); } os.close(); bis.close(); Logger.debug(this.getClass(), "time to build title: " + (System.currentTimeMillis() - time) + "ms"); return; }
11
Code Sample 1: public File copyFile(File f) throws IOException { File t = createNewFile("fm", "cpy"); FileOutputStream fos = new FileOutputStream(t); FileChannel foc = fos.getChannel(); FileInputStream fis = new FileInputStream(f); FileChannel fic = fis.getChannel(); foc.transferFrom(fic, 0, fic.size()); foc.close(); fic.close(); return t; } Code Sample 2: public static boolean copy(File from, File to, Override override) throws IOException { FileInputStream in = null; FileOutputStream out = null; FileChannel srcChannel = null; FileChannel destChannel = null; if (override == null) override = Override.NEWER; switch(override) { case NEVER: if (to.isFile()) return false; break; case NEWER: if (to.isFile() && (from.lastModified() - LASTMODIFIED_DIFF_MILLIS) < to.lastModified()) return false; break; } to.getParentFile().mkdirs(); try { in = new FileInputStream(from); out = new FileOutputStream(to); srcChannel = in.getChannel(); destChannel = out.getChannel(); long position = 0L; long count = srcChannel.size(); while (position < count) { long chunk = Math.min(MAX_IO_CHUNK_SIZE, count - position); position += destChannel.transferFrom(srcChannel, position, chunk); } to.setLastModified(from.lastModified()); return true; } finally { CommonUtils.close(srcChannel); CommonUtils.close(destChannel); CommonUtils.close(out); CommonUtils.close(in); } }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: private static void convertToOnline(final String filePath, final DocuBean docuBean) throws Exception { File source = new File(filePath + File.separator + docuBean.getFileName()); File dir = new File(filePath + File.separator + docuBean.getId()); if (!dir.exists()) { dir.mkdir(); } File in = source; boolean isSpace = false; if (source.getName().indexOf(" ") != -1) { in = new File(StringUtils.replace(source.getName(), " ", "")); try { IOUtils.copyFile(source, in); } catch (IOException e) { e.printStackTrace(); } isSpace = true; } File finalPdf = null; try { String outPath = dir.getAbsolutePath(); final File pdf = DocViewerConverter.toPDF(in, outPath); convertToSwf(pdf, outPath, docuBean); finalPdf = new File(outPath + File.separator + FileUtils.getFilePrefix(StringUtils.replace(source.getName(), " ", "")) + "_decrypted.pdf"); if (!finalPdf.exists()) { finalPdf = pdf; } pdfByFirstPageToJpeg(finalPdf, outPath, docuBean); if (docuBean.getSuccess() == 2 && dir.listFiles().length < 2) { docuBean.setSuccess(3); } } catch (Exception e) { throw e; } finally { if (isSpace) { IOUtils.delete(in); } } }
00
Code Sample 1: static String fetchURLComposeExternPackageList(String urlpath, String pkglisturlpath) { String link = pkglisturlpath + "package-list"; try { boolean relative = isRelativePath(urlpath); readPackageList((new URL(link)).openStream(), urlpath, relative); } catch (MalformedURLException exc) { return getText("doclet.MalformedURL", link); } catch (IOException exc) { return getText("doclet.URL_error", link); } return null; } Code Sample 2: public static void compress(final File zip, final Map<InputStream, String> entries, final IProgressMonitor monitor) throws IOException { if (zip == null || entries == null || CollectionUtils.isEmpty(entries.keySet())) throw new IllegalArgumentException("One ore more parameters are empty!"); if (zip.exists()) zip.delete(); else if (!zip.getParentFile().exists()) zip.getParentFile().mkdirs(); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zip))); out.setLevel(Deflater.BEST_COMPRESSION); try { for (InputStream inputStream : entries.keySet()) { ZipEntry zipEntry = new ZipEntry(skipBeginningSlash(entries.get(inputStream))); out.putNextEntry(zipEntry); IOUtils.copy(inputStream, out); out.closeEntry(); inputStream.close(); if (monitor != null) monitor.worked(1); } } finally { IOUtils.closeQuietly(out); } }
00
Code Sample 1: public String getLastReleaseVersion() throws TransferException { try { URL url = new URL("http://jtbdivelogbook.sourceforge.net/version.properties"); URLConnection urlConn = url.openConnection(); urlConn.setDoInput(true); urlConn.setUseCaches(false); urlConn.setReadTimeout(20000); urlConn.setConnectTimeout(10000); Properties props = new Properties(); InputStream is = urlConn.getInputStream(); props.load(is); is.close(); String lastVersion = props.getProperty(PROPERTY_LAST_RELEASE); if (lastVersion == null) { LOGGER.warn("Couldn't find property " + PROPERTY_LAST_RELEASE); } return lastVersion; } catch (MalformedURLException e) { LOGGER.error(e); throw new TransferException(e); } catch (IOException e) { LOGGER.error(e); throw new TransferException(e); } } Code Sample 2: public void sendTemplate(String filename, TemplateValues values) throws IOException { Checker.checkEmpty(filename, "filename"); Checker.checkNull(values, "values"); URL url = _getFile(filename); boolean writeSpaces = Context.getRootContext().getRunMode() == RUN_MODE.DEV ? true : false; Template t = new Template(url.openStream(), writeSpaces); try { t.write(getWriter(), values); } catch (ErrorListException ele) { Context.getRootContext().getLogger().error(ele); } }
00
Code Sample 1: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { final Map<String, String> fileAttr = new HashMap<String, String>(); boolean download = false; String dw = req.getParameter("d"); if (StringUtils.isNotEmpty(dw) && StringUtils.equals(dw, "true")) { download = true; } final ByteArrayOutputStream imageOutputStream = new ByteArrayOutputStream(DEFAULT_CONTENT_LENGTH_SIZE); InputStream imageInputStream = null; try { imageInputStream = getImageAsStream(req, fileAttr); IOUtils.copy(imageInputStream, imageOutputStream); resp.setHeader("Cache-Control", "no-store"); resp.setHeader("Pragma", "no-cache"); resp.setDateHeader("Expires", 0); resp.setContentType(fileAttr.get("mimetype")); if (download) { resp.setHeader("Content-Disposition", "attachment; filename=\"" + fileAttr.get("filename") + "\""); } final ServletOutputStream responseOutputStream = resp.getOutputStream(); responseOutputStream.write(imageOutputStream.toByteArray()); responseOutputStream.flush(); responseOutputStream.close(); } catch (Exception e) { e.printStackTrace(); resp.setContentType("text/html"); resp.getWriter().println("<h1>Sorry... cannot find document</h1>"); } finally { IOUtils.closeQuietly(imageInputStream); IOUtils.closeQuietly(imageOutputStream); } } Code Sample 2: private SpequlosResponse executeGet(String targetURL, String urlParameters) { URL url; HttpURLConnection connection = null; boolean succ = false; try { url = new URL(targetURL + "?" + urlParameters); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length)); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer log = new StringBuffer(); ArrayList<String> response = new ArrayList<String>(); while ((line = rd.readLine()) != null) { if (line.startsWith("<div class=\"qos\">")) { System.out.println("here is the line : " + line); String resp = line.split(">")[1].split("<")[0]; System.out.println("here is the splitted line : " + resp); if (!resp.startsWith("None")) { succ = true; String[] values = resp.split(" "); ArrayList<String> realvalues = new ArrayList<String>(); for (String s : values) { realvalues.add(s); } if (realvalues.size() == 5) { realvalues.add(2, realvalues.get(2) + " " + realvalues.get(3)); realvalues.remove(3); realvalues.remove(3); } for (String n : realvalues) { response.add(n); } } } else { log.append(line); log.append('\r'); } } rd.close(); SpequlosResponse speqresp = new SpequlosResponse(response, log.toString(), succ); return speqresp; } catch (Exception e) { e.printStackTrace(); String log = "Please check the availability of Spequlos server!<br />" + "URL:" + targetURL + "<br />" + "PARAMETERS:" + urlParameters + "<br />"; return new SpequlosResponse(null, log, succ); } finally { if (connection != null) connection.disconnect(); } }
11
Code Sample 1: public boolean copyFile(File destinationFolder, File fromFile) { boolean result = false; String toFileName = destinationFolder.getAbsolutePath() + "/" + fromFile.getName(); File toFile = new File(toFileName); FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (from != null) { try { from.close(); } catch (IOException e2) { e2.printStackTrace(); } if (to != null) { try { to.close(); result = true; } catch (IOException e3) { e3.printStackTrace(); } } } } return result; } Code Sample 2: public void process(String src, String dest) { try { KanjiDAO kanjiDAO = KanjiDAOFactory.getDAO(); MorphologicalAnalyzer mecab = MorphologicalAnalyzer.getInstance(); if (mecab.isActive()) { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(src), "UTF8")); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dest), "UTF8")); String line; bw.write("// // // \r\n$title=\r\n$singer=\r\n$id=\r\n\r\n + _______ // 0 0 0 0 0 0 0\r\n\r\n"); while ((line = br.readLine()) != null) { System.out.println(line); String segment[] = line.split("//"); String japanese = null; String english = null; if (segment.length > 1) english = segment[1].trim(); if (segment.length > 0) japanese = segment[0].trim().replaceAll(" ", "_"); boolean first = true; if (japanese != null) { ArrayList<ExtractedWord> wordList = mecab.extractWord(japanese); Iterator<ExtractedWord> iter = wordList.iterator(); while (iter.hasNext()) { ExtractedWord word = iter.next(); if (first) { first = false; bw.write("*"); } else bw.write(" "); if (word.isParticle) bw.write("- "); else bw.write("+ "); if (!word.original.equals(word.reading)) { System.out.println("--> " + JapaneseString.toRomaji(word.original) + " / " + JapaneseString.toRomaji(word.reading)); KReading[] kr = ReadingAnalyzer.analyzeReadingStub(word.original, word.reading, kanjiDAO); if (kr != null) { for (int i = 0; i < kr.length; i++) { if (i > 0) bw.write(" "); bw.write(kr[i].kanji); if (kr[i].type != KReading.KANA) { bw.write("|"); bw.write(kr[i].reading); } } } else { bw.write(word.original); bw.write("|"); bw.write(word.reading); } } else { bw.write(word.original); } bw.write(" // \r\n"); } if (english != null) { bw.write(english); bw.write("\r\n"); } bw.write("\r\n"); } } br.close(); bw.close(); } else { System.out.println("Mecab couldn't be initialized"); } } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: public void readPage(String search) { InputStream is = null; try { URL url = new URL("http://www.english-german-dictionary.com/index.php?search=" + search.trim()); is = url.openStream(); InputStreamReader isr = new InputStreamReader(is, "ISO-8859-15"); Scanner scan = new Scanner(isr); String str = new String(); String translate = new String(); String temp; while (scan.hasNextLine()) { temp = (scan.nextLine()); if (temp.contains("<td style='padding-top:4px;' class='ergebnisse_res'>")) { int anfang = temp.indexOf("-->") + 3; temp = temp.substring(anfang); temp = temp.substring(0, temp.indexOf("<!--")); translate = temp.trim(); } else if (temp.contains("<td style='' class='ergebnisse_art'>") || temp.contains("<td style='' class='ergebnisse_art_dif'>") || temp.contains("<td style='padding-top:4px;' class='ergebnisse_art'>")) { if (searchEnglish == false && searchGerman == false) { searchEnglish = temp.contains("<td style='' class='ergebnisse_art'>"); searchGerman = temp.contains("<td style='' class='ergebnisse_art_dif'>"); } int anfang1 = temp.lastIndexOf("'>") + 2; temp = temp.substring(anfang1, temp.lastIndexOf("</td>")); String to = temp.trim() + " "; temp = scan.nextLine(); int anfang2 = temp.lastIndexOf("\">") + 2; temp = (to != null ? to : "") + temp.substring(anfang2, temp.lastIndexOf("</a>")); str += translate + " - " + temp + "\n"; germanList.add(translate); englishList.add(temp.trim()); } } if (searchEnglish) { List<String> temp2 = englishList; englishList = germanList; germanList = temp2; } } catch (Exception e) { e.printStackTrace(); } finally { if (is != null) try { is.close(); } catch (IOException e) { } } } Code Sample 2: public void handler(List<GoldenBoot> gbs, TargetPage target) { try { URL url = new URL(target.getUrl()); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; String include = "Top Scorers"; while ((line = reader.readLine()) != null) { if (line.indexOf(include) != -1) { buildGildenBoot(line, gbs); break; } } reader.close(); } catch (MalformedURLException e) { } catch (IOException e) { } }
11
Code Sample 1: public static byte[] crypt(String key, String salt) throws NoSuchAlgorithmException { int key_len = key.length(); if (salt.startsWith(saltPrefix)) { salt = salt.substring(saltPrefix.length()); } int salt_len = Math.min(getDollarLessLength(salt), 8); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(key.getBytes()); md5.update(saltPrefix.getBytes()); md5.update(salt.getBytes(), 0, salt_len); MessageDigest md5_alt = MessageDigest.getInstance("MD5"); md5_alt.update(key.getBytes()); md5_alt.update(salt.getBytes(), 0, salt_len); md5_alt.update(key.getBytes()); byte[] altResult = md5_alt.digest(); int cnt; for (cnt = key_len; cnt > 16; cnt -= 16) { md5.update(altResult, 0, 16); } md5.update(altResult, 0, cnt); altResult[0] = 0; for (cnt = key_len; cnt > 0; cnt >>= 1) { md5.update(((cnt & 1) != 0) ? altResult : key.getBytes(), 0, 1); } altResult = md5.digest(); for (cnt = 0; cnt < 1000; cnt++) { md5.reset(); if ((cnt & 1) != 0) { md5.update(key.getBytes()); } else { md5.update(altResult, 0, 16); } if ((cnt % 3) != 0) { md5.update(salt.getBytes(), 0, salt_len); } if ((cnt % 7) != 0) { md5.update(key.getBytes()); } if ((cnt & 1) != 0) { md5.update(altResult, 0, 16); } else { md5.update(key.getBytes()); } altResult = md5.digest(); } StringBuilder sb = new StringBuilder(); sb.append(saltPrefix); sb.append(new String(salt.getBytes(), 0, salt_len)); sb.append('$'); sb.append(b64From24bit(altResult[0], altResult[6], altResult[12], 4)); sb.append(b64From24bit(altResult[1], altResult[7], altResult[13], 4)); sb.append(b64From24bit(altResult[2], altResult[8], altResult[14], 4)); sb.append(b64From24bit(altResult[3], altResult[9], altResult[15], 4)); sb.append(b64From24bit(altResult[4], altResult[10], altResult[5], 4)); sb.append(b64From24bit((byte) 0, (byte) 0, altResult[11], 2)); return sb.toString().getBytes(); } Code Sample 2: public static String SHA512(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-512"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("UTF-8"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public void adjustPadding(File file, int paddingSize, long audioStart) throws FileNotFoundException, IOException { logger.finer("Need to move audio file to accomodate tag"); FileChannel fcIn = null; FileChannel fcOut; ByteBuffer paddingBuffer = ByteBuffer.wrap(new byte[paddingSize]); File paddedFile; try { paddedFile = File.createTempFile(Utils.getMinBaseFilenameAllowedForTempFile(file), ".new", file.getParentFile()); logger.finest("Created temp file:" + paddedFile.getName() + " for " + file.getName()); } catch (IOException ioe) { logger.log(Level.SEVERE, ioe.getMessage(), ioe); if (ioe.getMessage().equals(FileSystemMessage.ACCESS_IS_DENIED.getMsg())) { logger.severe(ErrorMessage.GENERAL_WRITE_FAILED_TO_CREATE_TEMPORARY_FILE_IN_FOLDER.getMsg(file.getName(), file.getParentFile().getPath())); throw new UnableToCreateFileException(ErrorMessage.GENERAL_WRITE_FAILED_TO_CREATE_TEMPORARY_FILE_IN_FOLDER.getMsg(file.getName(), file.getParentFile().getPath())); } else { logger.severe(ErrorMessage.GENERAL_WRITE_FAILED_TO_CREATE_TEMPORARY_FILE_IN_FOLDER.getMsg(file.getName(), file.getParentFile().getPath())); throw new UnableToCreateFileException(ErrorMessage.GENERAL_WRITE_FAILED_TO_CREATE_TEMPORARY_FILE_IN_FOLDER.getMsg(file.getName(), file.getParentFile().getPath())); } } try { fcOut = new FileOutputStream(paddedFile).getChannel(); } catch (FileNotFoundException ioe) { logger.log(Level.SEVERE, ioe.getMessage(), ioe); logger.severe(ErrorMessage.GENERAL_WRITE_FAILED_TO_MODIFY_TEMPORARY_FILE_IN_FOLDER.getMsg(file.getName(), file.getParentFile().getPath())); throw new UnableToModifyFileException(ErrorMessage.GENERAL_WRITE_FAILED_TO_MODIFY_TEMPORARY_FILE_IN_FOLDER.getMsg(file.getName(), file.getParentFile().getPath())); } try { fcIn = new FileInputStream(file).getChannel(); long written = fcOut.write(paddingBuffer); logger.finer("Copying:" + (file.length() - audioStart) + "bytes"); long audiolength = file.length() - audioStart; if (audiolength <= MAXIMUM_WRITABLE_CHUNK_SIZE) { long written2 = fcIn.transferTo(audioStart, audiolength, fcOut); logger.finer("Written padding:" + written + " Data:" + written2); if (written2 != audiolength) { throw new RuntimeException(ErrorMessage.MP3_UNABLE_TO_ADJUST_PADDING.getMsg(audiolength, written2)); } } else { long noOfChunks = audiolength / MAXIMUM_WRITABLE_CHUNK_SIZE; long lastChunkSize = audiolength % MAXIMUM_WRITABLE_CHUNK_SIZE; long written2 = 0; for (int i = 0; i < noOfChunks; i++) { written2 += fcIn.transferTo(audioStart + (i * MAXIMUM_WRITABLE_CHUNK_SIZE), MAXIMUM_WRITABLE_CHUNK_SIZE, fcOut); } written2 += fcIn.transferTo(audioStart + (noOfChunks * MAXIMUM_WRITABLE_CHUNK_SIZE), lastChunkSize, fcOut); logger.finer("Written padding:" + written + " Data:" + written2); if (written2 != audiolength) { throw new RuntimeException(ErrorMessage.MP3_UNABLE_TO_ADJUST_PADDING.getMsg(audiolength, written2)); } } long lastModified = file.lastModified(); if (fcIn != null) { if (fcIn.isOpen()) { fcIn.close(); } } if (fcOut != null) { if (fcOut.isOpen()) { fcOut.close(); } } replaceFile(file, paddedFile); paddedFile.setLastModified(lastModified); } finally { try { if (fcIn != null) { if (fcIn.isOpen()) { fcIn.close(); } } if (fcOut != null) { if (fcOut.isOpen()) { fcOut.close(); } } } catch (Exception e) { logger.log(Level.WARNING, "Problem closing channels and locks:" + e.getMessage(), e); } } }
11
Code Sample 1: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: @Test public void testCopy_readerToOutputStream_Encoding_nullEncoding() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); Reader reader = new InputStreamReader(in, "US-ASCII"); ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, false, true); IOUtils.copy(reader, out, null); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); }
11
Code Sample 1: public static void createModelZip(String filename, String tempdir) throws EDITSException { try { 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(); } catch (Exception e) { throw new EDITSException("Can not create a model in file " + filename + " from folder " + tempdir); } } Code Sample 2: private String sendMessage(HttpURLConnection connection, String reqMessage) throws IOException, XMLStreamException { if (msgLog.isTraceEnabled()) msgLog.trace("Outgoing SOAPMessage\n" + reqMessage); BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream()); out.write(reqMessage.getBytes("UTF-8")); out.close(); InputStream inputStream = null; if (connection.getResponseCode() < 400) inputStream = connection.getInputStream(); else inputStream = connection.getErrorStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); IOUtils.copyStream(baos, inputStream); inputStream.close(); byte[] byteArray = baos.toByteArray(); String resMessage = new String(byteArray, "UTF-8"); if (msgLog.isTraceEnabled()) msgLog.trace("Incoming Response SOAPMessage\n" + resMessage); return resMessage; }
00
Code Sample 1: public static String move_tags(String sessionid, String absolutePathForTheMovedTags, String absolutePathForTheDestinationTag) { String resultJsonString = "some problem existed inside the create_new_tag() function if you see this string"; try { Log.d("current running function name:", "move_tags"); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://mt0-app.cloud.cm/rpc/json"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("c", "Storage")); nameValuePairs.add(new BasicNameValuePair("m", "move_tag")); nameValuePairs.add(new BasicNameValuePair("absolute_new_parent_tag", absolutePathForTheDestinationTag)); nameValuePairs.add(new BasicNameValuePair("absolute_tags", absolutePathForTheMovedTags)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httppost.setHeader("Cookie", "PHPSESSID=" + sessionid); HttpResponse response = httpclient.execute(httppost); resultJsonString = EntityUtils.toString(response.getEntity()); return resultJsonString; } catch (Exception e) { e.printStackTrace(); } return resultJsonString; } Code Sample 2: static String getMD5Hash(String str) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] b = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < b.length; i++) { int v = (int) b[i]; v = v < 0 ? 0x100 + v : v; String cc = Integer.toHexString(v); if (cc.length() == 1) sb.append('0'); sb.append(cc); } return sb.toString(); }
00
Code Sample 1: public InputStream getInputStream(IProgressMonitor monitor) throws IOException, CoreException { if (in == null && url != null) { if (connection == null) connection = url.openConnection(); if (monitor != null) { this.in = openStreamWithCancel(connection, monitor); } else { this.in = connection.getInputStream(); } if (in != null) { this.lastModified = connection.getLastModified(); } } return in; } Code Sample 2: public static void main(String[] args) { if (args.length < 2) { System.out.println(" *** DDL (creates) and DML (inserts) script importer from DB ***"); System.out.println(" You must specify name of the file with script importing data"); System.out.println(" Fisrt rows of this file must be:"); System.out.println(" 1) JDBC driver class for your DBMS"); System.out.println(" 2) URL for your database instance"); System.out.println(" 3) user in that database (with sufficient priviliges)"); System.out.println(" 4) password of that user"); System.out.println(" Next rows can have:"); System.out.println(" '}' before table to create,"); System.out.println(" '{' before schema to create tables in,"); System.out.println(" ')' before table to insert into,"); System.out.println(" '(' before schema to insert into tables in."); System.out.println(" '!' before row means that it is a comment."); System.out.println(" If some exception is occured, all script is rolled back."); System.out.println(" 2nd command line argument is name of output file;"); System.out.println(" if its extension is *.sql, its format is standard SQL"); System.out.println(" otherwize format is short one, understanded by SQLScript tool"); System.out.println(" Connection information remains unchanged in the last format"); System.out.println(" but in the first one it takes form 'connect user/password@URL'"); System.out.println(" where URL can be formed with different rools for different DBMSs"); System.out.println(" If file (with short format header) already exists and you specify"); System.out.println(" 3rd command line argument -db, we generate objects in the database"); System.out.println(" (known from the file header; must differ from 1st DB) but not in file"); System.out.println(" Note: when importing to a file of short format, line separators"); System.out.println(" in VARCHARS will be lost; LOBs will be empty for any file"); System.exit(0); } try { String[] info = new String[4]; BufferedReader reader = new BufferedReader(new FileReader(new File(args[0]))); Writer writer = null; Connection outConnection = null; try { for (int i = 0; i < info.length; i++) info[i] = reader.readLine(); try { Class.forName(info[0]); Connection connection = DriverManager.getConnection(info[1], info[2], info[3]); int format = args[1].toLowerCase().endsWith("sql") ? SQL_FORMAT : SHORT_FORMAT; File file = new File(args[1]); if (format == SHORT_FORMAT) { if (file.exists() && args.length > 2 && args[2].equalsIgnoreCase("-db")) { String[] outInfo = new String[info.length]; BufferedReader outReader = new BufferedReader(new FileReader(file)); for (int i = 0; i < outInfo.length; i++) outInfo[i] = reader.readLine(); outReader.close(); if (!(outInfo[1].equals(info[1]) && outInfo[2].equals(info[2]))) { Class.forName(info[0]); outConnection = DriverManager.getConnection(outInfo[1], outInfo[2], outInfo[3]); format = SQL_FORMAT; } } } if (outConnection == null) writer = new BufferedWriter(new FileWriter(file)); SQLImporter script = new SQLImporter(outConnection, connection); script.setFormat(format); if (format == SQL_FORMAT) { writer.write("connect " + info[2] + "/" + info[3] + "@" + script.getDatabaseURL(info[1]) + script.statementTerminator); } else { for (int i = 0; i < info.length; i++) writer.write(info[i] + lineSep); writer.write(lineSep); } try { System.out.println(script.executeScript(reader, writer) + " operations with tables has been generated during import"); } catch (SQLException e4) { reader.close(); if (writer != null) writer.close(); else outConnection.close(); System.out.println(" Script generation error: " + e4); } connection.close(); } catch (Exception e3) { reader.close(); if (writer != null) writer.close(); System.out.println(" Connection error: " + e3); } } catch (IOException e2) { System.out.println("Error in file " + args[0]); } } catch (FileNotFoundException e1) { System.out.println("File " + args[0] + " not found"); } }
00
Code Sample 1: private void publishMap(LWMap map) throws IOException { File savedMap = PublishUtil.saveMap(map); InputStream istream = new BufferedInputStream(new FileInputStream(savedMap)); OutputStream ostream = new BufferedOutputStream(new FileOutputStream(ActionUtil.selectFile("ConceptMap", "vue"))); int fileLength = (int) savedMap.length(); byte bytes[] = new byte[fileLength]; while (istream.read(bytes, 0, fileLength) != -1) ostream.write(bytes, 0, fileLength); istream.close(); ostream.close(); } Code Sample 2: public static String plainToMD(LoggerCollection loggerCol, String input) { byte[] byteHash = null; MessageDigest md = null; StringBuilder md4result = new StringBuilder(); try { md = MessageDigest.getInstance("MD4", new BouncyCastleProvider()); md.reset(); md.update(input.getBytes("UnicodeLittleUnmarked")); byteHash = md.digest(); for (int i = 0; i < byteHash.length; i++) { md4result.append(Integer.toHexString(0xFF & byteHash[i])); } } catch (UnsupportedEncodingException ex) { loggerCol.logException(CLASSDEBUG, "de.searchworkorange.lib.misc.hash.MD4Hash", Level.FATAL, ex); } catch (NoSuchAlgorithmException ex) { loggerCol.logException(CLASSDEBUG, "de.searchworkorange.lib.misc.hash.MD4Hash", Level.FATAL, ex); } return (md4result.toString()); }
00
Code Sample 1: public static String md5Encode(String s) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(s.getBytes()); return toHexString(md.digest()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return s; } } Code Sample 2: public static void main(String[] args) throws Exception { for (int n = 0; n < 8; n++) { new Thread() { public void run() { try { URL url = new URL("http://localhost:8080/WebGISTileServer/index.jsp?token_timeout=true"); URLConnection uc = url.openConnection(); uc.addRequestProperty("Referer", "http://localhost:8080/index.jsp"); BufferedReader rd = new BufferedReader(new InputStreamReader(uc.getInputStream())); String line; while ((line = rd.readLine()) != null) System.out.println(line); } catch (Exception e) { e.printStackTrace(); } } }.start(); } }
11
Code Sample 1: public void copy(String pathFileIn, String pathFileOut) { try { File inputFile = new File(pathFileIn); File outputFile = new File(pathFileOut); FileReader in = new FileReader(inputFile); File outDir = new File(DirOut); if (!outDir.exists()) outDir.mkdirs(); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); this.printColumn(inputFile.getName(), outputFile.getPath()); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: private void copyFile(File file, File targetFile) { try { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(targetFile)); byte[] tmp = new byte[8192]; int read = -1; while ((read = bis.read(tmp)) > 0) { bos.write(tmp, 0, read); } bis.close(); bos.close(); } catch (Exception e) { if (!targetFile.delete()) { System.err.println("Ups, created copy cant be deleted (" + targetFile.getAbsolutePath() + ")"); } } }
00
Code Sample 1: private void createContents(final Shell shell) { Package currentPackage = Package.getPackage("org.sf.pkb.gui"); String author = currentPackage.getImplementationVendor(); String version = currentPackage.getImplementationVersion(); if (author == null || author.trim().length() == 0) { author = "Felton Fee"; } if (version != null && version.trim().length() > 0) { version = "V" + version; } else { version = ""; } FormData data = null; shell.setLayout(new FormLayout()); Label label1 = new Label(shell, SWT.NONE); label1.setImage(Resources.IMAGE_PKB); data = new FormData(); data.top = new FormAttachment(0, 20); data.left = new FormAttachment(0, 20); label1.setLayoutData(data); Label label2 = new Label(shell, SWT.NONE); label2.setText(PreferenceDialog.PKBProperty.DEFAULT_rebrand_application_title + " " + version); Font font = new Font(shell.getDisplay(), "Arial", 12, SWT.NONE); label2.setFont(font); data = new FormData(); data.top = new FormAttachment(0, 25); data.left = new FormAttachment(label1, 15); data.right = new FormAttachment(100, -25); label2.setLayoutData(data); CustomSeparator separator1 = new CustomSeparator(shell, SWT.SHADOW_IN | SWT.HORIZONTAL); data = new FormData(); data.top = new FormAttachment(label2, 20); data.left = new FormAttachment(0, 0); data.right = new FormAttachment(100, 0); separator1.setLayoutData(data); Label label3 = new Label(shell, SWT.NONE); label3.setText("Written by " + author + " <"); data = new FormData(); data.top = new FormAttachment(separator1, 10); data.left = new FormAttachment(0, 15); label3.setLayoutData(data); Hyperlink link = new Hyperlink(shell, SWT.NONE | SWT.NO_FOCUS); link.setText(PKBMain.CONTACT_EMAIL); link.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { Program.launch("mailto:" + PKBMain.CONTACT_EMAIL + "?subject=[" + PKBMain.PRODUCT_ALEX_PKB + "]"); } }); data = new FormData(); data.top = new FormAttachment(separator1, 10); data.left = new FormAttachment(label3, 2); link.setLayoutData(data); Label label4 = new Label(shell, SWT.NONE); label4.setText(">"); data = new FormData(); data.top = new FormAttachment(separator1, 10); data.left = new FormAttachment(link, 2); data.right = new FormAttachment(100, -20); label4.setLayoutData(data); Label label6 = new Label(shell, SWT.NONE); label6.setText("Web site:"); data = new FormData(); data.top = new FormAttachment(label4, 10); data.left = new FormAttachment(0, 15); label6.setLayoutData(data); Hyperlink link1 = new Hyperlink(shell, SWT.NONE | SWT.NO_FOCUS); link1.setText(PKBMain.PRODUCT_WEBSITE); link1.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { Program.launch(PKBMain.PRODUCT_WEBSITE); } }); data = new FormData(); data.top = new FormAttachment(label4, 10); data.left = new FormAttachment(label6, 2); link1.setLayoutData(data); Button closeBtn = new Button(shell, SWT.PUSH); closeBtn.setText("Close"); closeBtn.setLayoutData(data); closeBtn.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { shell.close(); } }); data = new FormData(); data.top = new FormAttachment(label6, 10); data.right = new FormAttachment(100, -20); data.bottom = new FormAttachment(100, -10); closeBtn.setLayoutData(data); Button checkVersionBtn = new Button(shell, SWT.PUSH); checkVersionBtn.setText("Check version"); checkVersionBtn.setLayoutData(data); checkVersionBtn.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { try { URL url = new URL(PKBMain.PRODUCT_WEBSITE + "/latest-version.txt"); Properties prop = new Properties(); prop.load(url.openStream()); Package currentPackage = Package.getPackage("org.sf.pkb.gui"); String version = currentPackage.getImplementationVersion(); if (version == null) { version = ""; } String remoteVersion = prop.getProperty("version") + " b" + prop.getProperty("build"); if (remoteVersion.trim().compareTo(version.trim()) != 0) { StringBuffer buf = new StringBuffer(); buf.append("<HTML><BODY>").append("<h3 style='color: #0033FF'>You do not have the latest version. <br/> ").append("The latest version is PKB ").append(prop.getProperty("version") + " b" + prop.getProperty("build")).append(".</h3><A HREF='").append(prop.getProperty("url")).append("' TARGET='_BLANK'>Please download here </a> <br/><br/>").append("<B>It is strongly suggested to backup your knowledge base before install or unzip the new package!</B>").append("</BODY></HTML>"); MainScreen.Widget.getKnowledgeContentPanel().showTextInBrowser(buf.toString()); } else { StringBuffer buf = new StringBuffer(); buf.append("<HTML><BODY>").append("<h3 style='color: #0033FF'>You already had the latest version - ALEX PKB ").append(prop.getProperty("version") + " b" + prop.getProperty("build")).append(".</h3>").append("</BODY></HTML>"); MainScreen.Widget.getKnowledgeContentPanel().showTextInBrowser(buf.toString()); } } catch (Exception ex) { ex.printStackTrace(); } shell.close(); } }); data = new FormData(); data.top = new FormAttachment(label6, 10); data.right = new FormAttachment(closeBtn, -5); data.bottom = new FormAttachment(100, -10); checkVersionBtn.setLayoutData(data); shell.setDefaultButton(closeBtn); } Code Sample 2: public static String CreateHash(String s) { String str = s.toString(); if (str == null || str.length() == 0) { throw new IllegalArgumentException("String cannot be null or empty"); } StringBuffer hexString = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); 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])); } } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return (hexString.toString()); }
11
Code Sample 1: private boolean enregistreToi() { PrintWriter lEcrivain; String laDest = "./img_types/" + sonImage; if (!new File("./img_types").exists()) { new File("./img_types").mkdirs(); } try { FileChannel leFicSource = new FileInputStream(sonFichier).getChannel(); FileChannel leFicDest = new FileOutputStream(laDest).getChannel(); leFicSource.transferTo(0, leFicSource.size(), leFicDest); leFicSource.close(); leFicDest.close(); lEcrivain = new PrintWriter(new FileWriter(new File("bundll/types.jay"), true)); lEcrivain.println(sonNom); lEcrivain.println(sonImage); if (sonOptionRadio1.isSelected()) { lEcrivain.println("0:?"); } if (sonOptionRadio2.isSelected()) { lEcrivain.println("1:" + JOptionPane.showInputDialog(null, "Vous avez choisis de rendre ce terrain difficile � franchir.\nVeuillez en indiquer la raison.", "Demande de pr�cision", JOptionPane.INFORMATION_MESSAGE)); } if (sonOptionRadio3.isSelected()) { lEcrivain.println("2:?"); } lEcrivain.close(); return true; } catch (Exception lException) { return false; } } 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 convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public 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); }
00
Code Sample 1: public String hash(String text) { try { MessageDigest md = MessageDigest.getInstance(hashFunction); md.update(text.getBytes(charset)); byte[] raw = md.digest(); return new String(encodeHex(raw)); } catch (Exception e) { throw new RuntimeException(e); } } Code Sample 2: public static void copyFile(File src, File dst) throws IOException { FileChannel inChannel = new FileInputStream(src).getChannel(); FileChannel outChannel = new FileOutputStream(dst).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } }
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: public static void main(String[] args) throws Exception { String linesep = System.getProperty("line.separator"); FileOutputStream fos = new FileOutputStream(new File("lib-licenses.txt")); fos.write(new String("JCP contains the following libraries. Please read this for comments on copyright etc." + linesep + linesep).getBytes()); fos.write(new String("Chemistry Development Kit, master version as of " + new Date().toString() + " (http://cdk.sf.net)" + linesep).getBytes()); fos.write(new String("Copyright 1997-2009 The CDK Development Team" + linesep).getBytes()); fos.write(new String("License: LGPL v2 (http://www.gnu.org/licenses/old-licenses/gpl-2.0.html)" + linesep).getBytes()); fos.write(new String("Download: https://sourceforge.net/projects/cdk/files/" + linesep).getBytes()); fos.write(new String("Source available at: http://sourceforge.net/scm/?type=git&group_id=20024" + linesep + linesep).getBytes()); File[] files = new File(args[0]).listFiles(new JarFileFilter()); for (int i = 0; i < files.length; i++) { if (new File(files[i].getPath() + ".meta").exists()) { Map<String, Map<String, String>> metaprops = readProperties(new File(files[i].getPath() + ".meta")); Iterator<String> itsect = metaprops.keySet().iterator(); while (itsect.hasNext()) { String section = itsect.next(); fos.write(new String(metaprops.get(section).get("Library") + " " + metaprops.get(section).get("Version") + " (" + metaprops.get(section).get("Homepage") + ")" + linesep).getBytes()); fos.write(new String("Copyright " + metaprops.get(section).get("Copyright") + linesep).getBytes()); fos.write(new String("License: " + metaprops.get(section).get("License") + " (" + metaprops.get(section).get("LicenseURL") + ")" + linesep).getBytes()); fos.write(new String("Download: " + metaprops.get(section).get("Download") + linesep).getBytes()); fos.write(new String("Source available at: " + metaprops.get(section).get("SourceCode") + linesep + linesep).getBytes()); } } if (new File(files[i].getPath() + ".extra").exists()) { fos.write(new String("The author says:" + linesep).getBytes()); FileInputStream in = new FileInputStream(new File(files[i].getPath() + ".extra")); int len; byte[] buf = new byte[1024]; while ((len = in.read(buf)) > 0) { fos.write(buf, 0, len); } } fos.write(linesep.getBytes()); } fos.close(); }
11
Code Sample 1: public void SetRoles(Connection conn, User user, String[] roles) throws NpsException { if (!IsSysAdmin() && !IsLocalAdmin()) throw new NpsException(ErrorHelper.ACCESS_NOPRIVILEGE); PreparedStatement pstmt = null; ResultSet rs = null; try { String sql = "delete from userrole where userid=?"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, user.id); pstmt.executeUpdate(); if (roles != null && roles.length > 0) { try { pstmt.close(); } catch (Exception e1) { } sql = "insert into userrole(userid,roleid) values(?,?)"; pstmt = conn.prepareStatement(sql); for (int i = 0; i < roles.length; i++) { if (roles[i] != null && roles[i].length() > 0) { pstmt.setString(1, user.GetId()); pstmt.setString(2, roles[i]); pstmt.executeUpdate(); } } } try { pstmt.close(); } catch (Exception e1) { } if (user.roles_by_name != null) user.roles_by_name.clear(); if (user.roles_by_id != null) user.roles_by_id.clear(); if (roles != null && roles.length > 0) { sql = "select b.* from UserRole a,Role b where a.roleid = b.id and a.userid=?"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, user.id); rs = pstmt.executeQuery(); while (rs.next()) { if (user.roles_by_name == null) user.roles_by_name = new Hashtable(); if (user.roles_by_id == null) user.roles_by_id = new Hashtable(); user.roles_by_name.put(rs.getString("name"), rs.getString("id")); user.roles_by_id.put(rs.getString("id"), rs.getString("name")); } } } catch (Exception e) { try { conn.rollback(); } catch (Exception e1) { } nps.util.DefaultLog.error(e); } finally { if (rs != null) try { rs.close(); } catch (Exception e) { } if (pstmt != null) try { pstmt.close(); } catch (Exception e1) { } } } Code Sample 2: public static boolean update(Cargo cargo) { int result = 0; Connection c = DBConnection.getConnection(); PreparedStatement pst = null; if (c == null) { return false; } try { c.setAutoCommit(false); String sql = "update cargo set nome = (?) where id_cargo= ?"; pst = c.prepareStatement(sql); pst.setString(1, cargo.getNome()); pst.setInt(2, cargo.getCodigo()); result = pst.executeUpdate(); c.commit(); } catch (SQLException e) { try { c.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } System.out.println("[CargoDAO.update] Erro ao atualizar -> " + e.getMessage()); } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } if (result > 0) { return true; } else { return false; } }
00
Code Sample 1: public static void copyFile(FileInputStream source, FileOutputStream target) throws Exception { FileChannel inChannel = source.getChannel(); FileChannel outChannel = target.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 TreeMap getStrainMap() { TreeMap strainMap = new TreeMap(); String server = ""; try { Datasource[] ds = DatasourceManager.getDatasouce(alias, version, DatasourceManager.ALL_CONTAINS_GROUP); for (int i = 0; i < ds.length; i++) { if (ds[i].getDescription().startsWith(MOUSE_DBSNP)) { if (ds[i].getServer().length() == 0) { Connection con = ds[i].getConnection(); strainMap = Action.lineMode.regularSQL.GenotypeDataSearchAction.getStrainMap(con); break; } else { server = ds[i].getServer(); HashMap serverUrlMap = InitXml.getInstance().getServerMap(); String serverUrl = (String) serverUrlMap.get(server); URL url = new URL(serverUrl + servletName); URLConnection uc = url.openConnection(); uc.setDoOutput(true); OutputStream os = uc.getOutputStream(); StringBuffer buf = new StringBuffer(); buf.append("viewType=getstrains"); buf.append("&hHead=" + hHead); buf.append("&hCheck=" + version); PrintStream ps = new PrintStream(os); ps.print(buf.toString()); ps.close(); ObjectInputStream ois = new ObjectInputStream(uc.getInputStream()); strainMap = (TreeMap) ois.readObject(); ois.close(); } } } } catch (Exception e) { log.error("strain map", e); } return strainMap; }
00
Code Sample 1: private static String getDocumentAt(String urlString) { StringBuffer html_text = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) html_text.append(line + "\n"); reader.close(); } catch (MalformedURLException e) { System.out.println("����URL: " + urlString); } catch (IOException e) { e.printStackTrace(); } return html_text.toString(); } Code Sample 2: public static synchronized Map<String, Object> getURLContentMap(String wwwurl) throws IOException, URISyntaxException { Map<String, Object> resultMap = new HashMap<String, Object>(); URI uri = new URI(wwwurl); URL url = new URL(uri.toASCIIString()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10 * 1000); HttpURLConnection.setFollowRedirects(true); try { conn.setRequestMethod("GET"); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.17) Gecko/20110421 Red Hat/3.6-1.el5_6 Firefox/3.6.17"); for (String key : conn.getHeaderFields().keySet()) { List<String> headerInfo = conn.getHeaderFields().get(key); if (headerInfo.size() > 0) { resultMap.put(key, headerInfo.get(0)); } } String contentType = conn.getContentType(); if (!(contentType == null || contentType.toLowerCase().contains("text") || contentType.toLowerCase().contains("html"))) { return resultMap; } ByteArrayOutputStream outstream = new ByteArrayOutputStream(); InputStream instream = conn.getInputStream(); synchronized (instream) { int readSize = 0; int totalSize = 0; byte[] contentByte = null; byte[] buffer = new byte[1024]; while ((readSize = instream.read(buffer)) > 0) { outstream.write(buffer, 0, readSize); totalSize += readSize; if (totalSize >= MAX_CONTENT_SIZE) { contentByte = ("[FAILD] content size is larger than " + MAX_CONTENT_SIZE + " byte.").getBytes(); } } if (contentByte == null) { contentByte = outstream.toByteArray(); } instream.close(); outstream.close(); resultMap.put(contentByteField, contentByte); } } finally { } return resultMap; }
11
Code Sample 1: public static void createZipFromDataset(String localResourceId, File dataset, File metadata) { CommunicationLogger.warning("System entered ZipFactory"); try { String tmpDir = System.getProperty("java.io.tmpdir"); String outFilename = tmpDir + "/" + localResourceId + ".zip"; CommunicationLogger.warning("File name: " + outFilename); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename)); byte[] buf = new byte[1024]; FileInputStream in = new FileInputStream(dataset); out.putNextEntry(new ZipEntry(dataset.getName())); int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in = new FileInputStream(metadata); out.putNextEntry(new ZipEntry(metadata.getName())); while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.closeEntry(); in.close(); out.close(); } catch (IOException e) { System.out.println("IO EXCEPTION: " + e.getMessage()); } } Code Sample 2: public static void main(String[] args) throws FileNotFoundException, IOException { String filePath = "/Users/francisbaril/Downloads/test-1.pdf"; String testFilePath = "/Users/francisbaril/Desktop/testpdfbox/test.pdf"; File file = new File(filePath); final File testFile = new File(testFilePath); if (testFile.exists()) { testFile.delete(); } IOUtils.copy(new FileInputStream(file), new FileOutputStream(testFile)); System.out.println(getLongProperty(new FileInputStream(testFile), PROPRIETE_ID_IGID)); }
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: protected void copyFile(String from, String to, String workingDirectory) throws Exception { URL monitorCallShellScriptUrl = Thread.currentThread().getContextClassLoader().getResource(from); File f = new File(monitorCallShellScriptUrl.getFile()); String directoryPath = f.getAbsolutePath(); String fileName = from; InputStream in = null; if (directoryPath.indexOf(".jar!") > -1) { URL urlJar = new URL(directoryPath.substring(directoryPath.indexOf("file:"), directoryPath.indexOf('!'))); JarFile jf = new JarFile(urlJar.getFile()); JarEntry je = jf.getJarEntry(from); fileName = je.getName(); in = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName); } else { in = new FileInputStream(f); } File outScriptFile = new File(to); FileOutputStream fos = new FileOutputStream(outScriptFile); int nextChar; while ((nextChar = in.read()) != -1) fos.write(nextChar); fos.flush(); fos.close(); try { LinuxCommandExecutor cmdExecutor = new LinuxCommandExecutor(); cmdExecutor.setWorkingDirectory(workingDirectory); cmdExecutor.runCommand("chmod 777 " + to); } catch (Exception e) { throw e; } }
11
Code Sample 1: public boolean authorize(String username, String password, String filename) { open(filename); boolean isAuthorized = false; StringBuffer encPasswd = null; try { MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(password.getBytes()); byte[] digest = mdAlgorithm.digest(); 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); } } catch (NoSuchAlgorithmException ex) { } String encPassword = encPasswd.toString(); String tempPassword = getPassword(username); System.out.println("epass" + encPassword); System.out.println("pass" + tempPassword); if (tempPassword.equals(encPassword)) { isAuthorized = true; } else { isAuthorized = false; } close(); return isAuthorized; } Code Sample 2: public static byte[] hash(String identifier) { if (function.equals("SHA-1")) { try { MessageDigest md = MessageDigest.getInstance(function); md.reset(); byte[] code = md.digest(identifier.getBytes()); byte[] value = new byte[KEY_LENGTH / 8]; int shrink = code.length / value.length; int bitCount = 1; for (int j = 0; j < code.length * 8; j++) { int currBit = ((code[j / 8] & (1 << (j % 8))) >> j % 8); if (currBit == 1) bitCount++; if (((j + 1) % shrink) == 0) { int shrinkBit = (bitCount % 2 == 0) ? 0 : 1; value[j / shrink / 8] |= (shrinkBit << ((j / shrink) % 8)); bitCount = 1; } } return value; } catch (Exception e) { e.printStackTrace(); } } if (function.equals("CRC32")) { CRC32 crc32 = new CRC32(); crc32.reset(); crc32.update(identifier.getBytes()); long code = crc32.getValue(); code &= (0xffffffffffffffffL >>> (64 - KEY_LENGTH)); byte[] value = new byte[KEY_LENGTH / 8]; for (int i = 0; i < value.length; i++) { value[value.length - i - 1] = (byte) ((code >> 8 * i) & 0xff); } return value; } if (function.equals("Java")) { int code = identifier.hashCode(); code &= (0xffffffff >>> (32 - KEY_LENGTH)); byte[] value = new byte[KEY_LENGTH / 8]; for (int i = 0; i < value.length; i++) { value[value.length - i - 1] = (byte) ((code >> 8 * i) & 0xff); } return value; } return null; }
11
Code Sample 1: protected void setUp() throws Exception { this.testOutputDirectory = new File(getClass().getResource("/").getPath()); this.pluginFile = new File(this.testOutputDirectory, "/plugin.zip"); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(pluginFile)); zos.putNextEntry(new ZipEntry("WEB-INF/")); zos.putNextEntry(new ZipEntry("WEB-INF/classes/")); zos.putNextEntry(new ZipEntry("WEB-INF/classes/system.properties")); System.getProperties().store(zos, null); zos.closeEntry(); zos.putNextEntry(new ZipEntry("WEB-INF/lib/")); zos.putNextEntry(new ZipEntry("WEB-INF/lib/plugin.jar")); File jarFile = new File(this.testOutputDirectory.getPath() + "/plugin.jar"); JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarFile)); jos.putNextEntry(new ZipEntry("vqwiki/")); jos.putNextEntry(new ZipEntry("vqwiki/plugins/")); jos.putNextEntry(new ZipEntry("vqwiki/plugins/system.properties")); System.getProperties().store(jos, null); jos.closeEntry(); jos.close(); IOUtils.copy(new FileInputStream(jarFile), zos); zos.closeEntry(); zos.close(); jarFile.delete(); pcl = new PluginClassLoader(new File(testOutputDirectory, "/work")); pcl.addPlugin(pluginFile); } Code Sample 2: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: public void copyFile(String oldPathFile, String newPathFile) { try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPathFile); if (oldfile.exists()) { InputStream inStream = new FileInputStream(oldPathFile); FileOutputStream fs = new FileOutputStream(newPathFile); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); } } catch (Exception e) { message = ("���Ƶ����ļ���������"); } } Code Sample 2: private void fetch() throws IOException { if (getAttachmentUrl() != null && (!getAttachmentUrl().isEmpty())) { InputStream input = null; ByteArrayOutputStream output = null; try { URL url = new URL(getAttachmentUrl()); input = url.openStream(); output = new ByteArrayOutputStream(); int i; while ((i = input.read()) != -1) { output.write(i); } this.data = output.toByteArray(); } finally { if (input != null) { input.close(); } if (output != null) { output.close(); } } } }
00
Code Sample 1: @Override public void sendContent(OutputStream out, Range range, Map<String, String> params, String contentType) throws IOException { LOGGER.debug("DOWNLOAD - Send content: " + realFile.getAbsolutePath()); LOGGER.debug("Output stream: " + out.toString()); if (ServerConfiguration.isDynamicSEL()) { LOGGER.error("IS DINAMIC SEL????"); } else { } if (".tokens".equals(realFile.getName()) || ".response".equals(realFile.getName()) || ".request".equals(realFile.getName()) || isAllowedClient) { FileInputStream in = null; try { in = new FileInputStream(realFile); int bytes = IOUtils.copy(in, out); LOGGER.debug("System resource or Allowed Client wrote bytes: " + bytes); out.flush(); } catch (Exception e) { LOGGER.error("Error while uploading over encryption system " + realFile.getName() + " file", e); } finally { IOUtils.closeQuietly(in); } } else { FileInputStream in = null; try { in = new FileInputStream(realFile); int bytes = IOUtils.copy(in, out); LOGGER.debug("System resource or Allowed Client wrote bytes: " + bytes); out.flush(); } catch (Exception e) { LOGGER.error("Error while uploading over encryption system " + realFile.getName() + " file", e); } finally { IOUtils.closeQuietly(in); } } } Code Sample 2: public InputStream retrieveStream(String url) { HttpGet getRequest = new HttpGet(url); try { HttpResponse getResponse = client.execute(getRequest); final int statusCode = getResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + url); return null; } HttpEntity getResponseEntity = getResponse.getEntity(); return getResponseEntity.getContent(); } catch (IOException e) { getRequest.abort(); Log.w(getClass().getSimpleName(), "Error for URL " + url, e); } return null; }
00
Code Sample 1: public void updatePortletName(PortletName portletNameBean) { DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); String sql = "update WM_PORTAL_PORTLET_NAME " + "set TYPE=? " + "where ID_SITE_CTX_TYPE=?"; ps = dbDyn.prepareStatement(sql); ps.setString(1, portletNameBean.getPortletName()); RsetTools.setLong(ps, 2, portletNameBean.getPortletId()); int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of updated record - " + i1); dbDyn.commit(); } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error save portlet name"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } } Code Sample 2: protected String readFileUsingHttp(String fileUrlName) { String response = ""; try { URL url = new URL(fileUrlName); URLConnection connection = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) connection; httpConn.setRequestProperty("Content-Type", "text/html"); httpConn.setRequestProperty("Content-Length", "0"); httpConn.setRequestMethod("GET"); httpConn.setDoOutput(true); httpConn.setDoInput(true); httpConn.setAllowUserInteraction(false); InputStreamReader isr = new InputStreamReader(httpConn.getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine = ""; while ((inputLine = in.readLine()) != null) { response += inputLine + "\n"; } if (response.endsWith("\n")) { response = response.substring(0, response.length() - 1); } in.close(); } catch (Exception x) { x.printStackTrace(); } return response; }
11
Code Sample 1: public static String getURL(String urlString, String getData, String postData) { try { if (getData != null) if (!getData.equals("")) urlString += "?" + getData; URL url = new URL(urlString); URLConnection connection = url.openConnection(); if (!postData.equals("")) { connection.setDoOutput(true); PrintWriter out = new PrintWriter(connection.getOutputStream()); out.print(postData); out.close(); } BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); int inputLine; String output = ""; while ((inputLine = in.read()) != -1) output += (char) inputLine; in.close(); return output; } catch (Exception e) { return null; } } 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: public static String md5(String text) { String encrypted = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(text.getBytes()); encrypted = hex(md.digest()); } catch (NoSuchAlgorithmException nsaEx) { } return encrypted; } Code Sample 2: public static void copyFile(File sourceFile, File destFile) throws IOException { log.info("Copying file '" + sourceFile + "' to '" + destFile + "'"); if (!sourceFile.isFile()) { throw new IllegalArgumentException("The sourceFile '" + sourceFile + "' does not exist or is not a normal file."); } if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); long numberOfBytes = destination.transferFrom(source, 0, source.size()); log.debug("Transferred " + numberOfBytes + " bytes from '" + sourceFile + "' to '" + destFile + "'."); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
11
Code Sample 1: public static void main(String[] args) throws Exception { TripleDES tdes = new TripleDES(); StreamBlockReader reader = new StreamBlockReader(new FileInputStream("D:\\test.txt")); StreamBlockWriter writer = new StreamBlockWriter(new FileOutputStream("D:\\testTDESENC.txt")); SingleKey key = new SingleKey(new Block(128), ""); key = new SingleKey(new Block("01011101110000101001100111001011101000001110111101001001101101101101100000011101100100110000101100001110000001111101001101001101"), ""); Mode mode = new ECBTripleDESMode(tdes); tdes.encrypt(reader, writer, key, mode); } Code Sample 2: public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; }
00
Code Sample 1: public void scan() throws Throwable { client = new FTPClient(); log.info("connecting to " + host + "..."); client.connect(host); log.info(client.getReplyString()); log.info("logging in..."); client.login("anonymous", ""); log.info(client.getReplyString()); Date date = Calendar.getInstance().getTime(); xmlDocument = new XMLDocument(host, dir, date); scanDirectory(dir); } Code Sample 2: public static String getProgramVersion() { String s = "0"; try { URL url; URLConnection urlConn; DataInputStream dis; url = new URL("http://www.dombosfest.org.yu/log/yamiversion.dat"); urlConn = url.openConnection(); urlConn.setDoInput(true); urlConn.setUseCaches(false); dis = new DataInputStream(urlConn.getInputStream()); while ((dis.readUTF()) != null) { s = dis.readUTF(); } dis.close(); } catch (MalformedURLException mue) { System.out.println("mue:" + mue.getMessage()); } catch (IOException ioe) { System.out.println("ioe:" + ioe.getMessage()); } return s; }
00
Code Sample 1: public static void fileUpload() throws IOException { HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); file = new File("H:\\FileServeUploader.java"); HttpPost httppost = new HttpPost(postURL); httppost.setHeader("Cookie", uprandcookie + ";" + autologincookie); MultipartEntity mpEntity = new MultipartEntity(); ContentBody cbFile = new FileBody(file); mpEntity.addPart("MAX_FILE_SIZE", new StringBody("2097152000")); mpEntity.addPart("UPLOAD_IDENTIFIER", new StringBody(uid)); mpEntity.addPart("go", new StringBody("1")); mpEntity.addPart("files", cbFile); httppost.setEntity(mpEntity); System.out.println("Now uploading your file into depositfiles..........................."); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println(response.getStatusLine()); if (resEntity != null) { uploadresponse = EntityUtils.toString(resEntity); downloadlink = parseResponse(uploadresponse, "ud_download_url = '", "'"); deletelink = parseResponse(uploadresponse, "ud_delete_url = '", "'"); System.out.println("download link : " + downloadlink); System.out.println("delete link : " + deletelink); } } Code Sample 2: private static void copyFile(File sourceFile, File destFile) { try { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } catch (Exception e) { throw new RuntimeException(e); } }
11
Code Sample 1: private static void insertModuleInEar(File fromEar, File toEar, String moduleType, String moduleName, String contextRoot) throws Exception { ZipInputStream earFile = new ZipInputStream(new FileInputStream(fromEar)); FileOutputStream fos = new FileOutputStream(toEar); ZipOutputStream tempZip = new ZipOutputStream(fos); ZipEntry next = earFile.getNextEntry(); while (next != null) { ByteArrayOutputStream content = new ByteArrayOutputStream(); byte[] data = new byte[30000]; int numberread; while ((numberread = earFile.read(data)) != -1) { content.write(data, 0, numberread); } if (next.getName().equals("META-INF/application.xml")) { content = insertModule(earFile, next, content, moduleType, moduleName, contextRoot); next = new ZipEntry("META-INF/application.xml"); } tempZip.putNextEntry(next); tempZip.write(content.toByteArray()); next = earFile.getNextEntry(); } earFile.close(); tempZip.close(); fos.close(); } Code Sample 2: public static void copyfile(String src, String dst) throws IOException { dst = new File(dst).getAbsolutePath(); new File(new File(dst).getParent()).mkdirs(); FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
00
Code Sample 1: public static void contentTrans(String contents, String urlString, String urlString2, String serverIp, int port) { try { URL url = new URL(urlString); url.openStream(); } catch (Exception e) { e.printStackTrace(); } try { Socket server = new Socket(InetAddress.getByName(serverIp), port); OutputStream outputStream = server.getOutputStream(); BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")); bufferedWriter.write(contents); bufferedWriter.flush(); bufferedWriter.close(); server.close(); } catch (Exception e) { e.printStackTrace(); } try { URL url2 = new URL(urlString2); url2.openStream(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: String processURLInput(String inputURL) throws SoaplabException { try { File tmpFile = File.createTempFile("gowlab.", null); tmpFile.deleteOnExit(); Object data = inputs.get(inputURL); URL url = new URL(data.toString()); if (url.getProtocol().equals("file")) logAndThrow("Trying to get local file '" + url.toString() + "' is not allowed."); URLConnection uc = url.openConnection(); uc.connect(); InputStream in = uc.getInputStream(); byte[] buffer = new byte[256]; DataOutputStream fileout = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(tmpFile))); int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { fileout.write(buffer, 0, bytesRead); } fileout.close(); return tmpFile.getAbsolutePath(); } catch (IOException e) { logAndThrow("In processURLData: " + e.toString()); } return null; }
00
Code Sample 1: @SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { PositionParser pp; Database.init("XIDResult"); pp = new PositionParser("01:33:50.904+30:39:35.79"); String url = "http://simbad.u-strasbg.fr/simbad/sim-script?submit=submit+script&script="; String script = "format object \"%IDLIST[%-30*]|-%COO(A)|%COO(D)|%OTYPELIST(S)\"\n"; String tmp = ""; script += pp.getPosition() + " radius=1m"; url += URLEncoder.encode(script, "ISO-8859-1"); URL simurl = new URL(url); BufferedReader in = new BufferedReader(new InputStreamReader(simurl.openStream())); String boeuf; boolean data_found = false; JSONObject retour = new JSONObject(); JSONArray dataarray = new JSONArray(); JSONArray colarray = new JSONArray(); JSONObject jsloc = new JSONObject(); jsloc.put("sTitle", "ID"); colarray.add(jsloc); jsloc = new JSONObject(); jsloc.put("sTitle", "Position"); colarray.add(jsloc); jsloc = new JSONObject(); jsloc.put("sTitle", "Type"); colarray.add(jsloc); retour.put("aoColumns", colarray); int datasize = 0; while ((boeuf = in.readLine()) != null) { if (data_found) { String[] fields = boeuf.trim().split("\\|", -1); int pos = fields.length - 1; if (pos >= 3) { String type = fields[pos]; pos--; String dec = fields[pos]; pos--; String ra = fields[pos]; String id = ""; for (int i = 0; i < pos; i++) { id += fields[i]; if (i < (pos - 1)) { id += "|"; } } if (id.length() <= 30) { JSONArray darray = new JSONArray(); darray.add(id.trim()); darray.add(ra + " " + dec); darray.add(type.trim()); dataarray.add(darray); datasize++; } } } else if (boeuf.startsWith("::data")) { data_found = true; } } retour.put("aaData", dataarray); retour.put("iTotalRecords", datasize); retour.put("iTotalDisplayRecords", datasize); System.out.println(retour.toJSONString()); in.close(); } Code Sample 2: public String md5(String phrase) { MessageDigest m; String coded = new String(); try { m = MessageDigest.getInstance("MD5"); m.update(phrase.getBytes(), 0, phrase.length()); coded = (new BigInteger(1, m.digest()).toString(16)).toString(); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } return coded; }
00
Code Sample 1: public static List<String> readListFile(URL url) { List<String> names = new ArrayList<String>(); if (url != null) { InputStream in = null; try { in = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = ""; while ((line = reader.readLine()) != null) { if (!line.startsWith("#")) { names.add(line); } } } catch (Exception e) { throw new RuntimeException(e); } finally { try { if (in != null) in.close(); } catch (IOException e) { e.printStackTrace(); } } } return names; } Code Sample 2: ArrayList<String> remoteSampling(IntersectionFile[] intersectionFiles, double[][] points) { logger.info("begin REMOTE sampling, number of threads " + intersectConfig.getThreadCount() + ", number of layers=" + intersectionFiles.length + ", number of coordinates=" + points.length); ArrayList<String> output = null; try { long start = System.currentTimeMillis(); URL url = new URL(intersectConfig.getLayerIndexUrl() + "/intersect/batch"); URLConnection c = url.openConnection(); c.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(c.getOutputStream()); out.write("fids="); for (int i = 0; i < intersectionFiles.length; i++) { if (i > 0) { out.write(","); } out.write(intersectionFiles[i].getFieldId()); } out.write("&points="); for (int i = 0; i < points.length; i++) { if (i > 0) { out.write(","); } out.write(String.valueOf(points[i][0])); out.write(","); out.write(String.valueOf(points[i][1])); } out.close(); CSVReader csv = new CSVReader(new InputStreamReader(new GZIPInputStream(c.getInputStream()))); long mid = System.currentTimeMillis(); ArrayList<StringBuilder> tmpOutput = new ArrayList<StringBuilder>(); for (int i = 0; i < intersectionFiles.length; i++) { tmpOutput.add(new StringBuilder()); } String[] line; int row = 0; csv.readNext(); while ((line = csv.readNext()) != null) { for (int i = 2; i < line.length && i - 2 < tmpOutput.size(); i++) { if (row > 0) { tmpOutput.get(i - 2).append("\n"); } tmpOutput.get(i - 2).append(line[i]); } row++; } csv.close(); output = new ArrayList<String>(); for (int i = 0; i < tmpOutput.size(); i++) { output.add(tmpOutput.get(i).toString()); tmpOutput.set(i, null); } long end = System.currentTimeMillis(); logger.info("sample time for " + 5 + " layers and " + 3 + " coordinates: get response=" + (mid - start) + "ms, write response=" + (end - mid) + "ms"); } catch (Exception e) { e.printStackTrace(); } return output; }
00
Code Sample 1: public void getDownloadInfo(String _url) throws Exception { cl = new DefaultHttpClient(); InfoAuthPromter hp = new InfoAuthPromter(); cl.setCredentialsProvider(hp); head = new HttpHead(_url); head.setHeader("User-Agent", "test"); head.setHeader("Accept", "*/*"); head.setHeader("Range", "bytes=0-"); HttpResponse resp = cl.execute(head); ent = resp.getEntity(); int code = resp.getStatusLine().getStatusCode(); if (code == 401) { throw new Exception("HTTP Auth Failed"); } AuthManager.putAuth(getSite(), auth); setURL(head.getURI().toString()); setSize(ent.getContentLength()); setRangeEnd(getSize() - 1); setResumable(code == 206); } Code Sample 2: @Override public void saveStructure(long userId, TreeStructureInfo info, List<TreeStructureNode> structure) throws DatabaseException { if (info == null) throw new NullPointerException("info"); if (structure == null) throw new NullPointerException("structure"); try { getConnection().setAutoCommit(false); } catch (SQLException e) { LOGGER.warn("Unable to set autocommit off", e); } PreparedStatement insertInfoSt = null, insSt = null; try { insertInfoSt = getConnection().prepareStatement(INSERT_INFO); insertInfoSt.setLong(1, userId); insertInfoSt.setString(2, info.getDescription() != null ? info.getDescription() : ""); insertInfoSt.setString(3, info.getBarcode()); insertInfoSt.setString(4, info.getName()); insertInfoSt.setString(5, info.getInputPath()); insertInfoSt.setString(6, info.getModel()); insertInfoSt.executeUpdate(); PreparedStatement seqSt = getConnection().prepareStatement(INFO_VALUE); ResultSet rs = seqSt.executeQuery(); int key = -1; while (rs.next()) { key = rs.getInt(1); } if (key == -1) { getConnection().rollback(); throw new DatabaseException("Unable to obtain new id from DB when executing query: " + insertInfoSt); } int total = 0; for (TreeStructureNode node : structure) { insSt = getConnection().prepareStatement(INSERT_NODE); insSt.setLong(1, key); insSt.setString(2, node.getPropId()); insSt.setString(3, node.getPropParent()); insSt.setString(4, node.getPropName()); insSt.setString(5, node.getPropPicture()); insSt.setString(6, node.getPropType()); insSt.setString(7, node.getPropTypeId()); insSt.setString(8, node.getPropPageType()); insSt.setString(9, node.getPropDateIssued()); insSt.setString(10, node.getPropAltoPath()); insSt.setString(11, node.getPropOcrPath()); insSt.setBoolean(12, node.getPropExist()); total += insSt.executeUpdate(); } if (total != structure.size()) { getConnection().rollback(); throw new DatabaseException("Unable to insert _ALL_ nodes: " + total + " nodes were inserted of " + structure.size()); } getConnection().commit(); } catch (SQLException e) { LOGGER.error("Queries: \"" + insertInfoSt + "\" and \"" + insSt + "\"", e); } finally { closeConnection(); } }
00
Code Sample 1: private void doOp(String urlString) { URL url = null; try { url = new URL(urlString); } catch (MalformedURLException e) { e.printStackTrace(); return; } URLConnection conn = null; try { conn = url.openConnection(); conn.setRequestProperty("Authorization", "Basic " + (new BASE64Encoder()).encode((System.getProperty("fedoragsearch.fgsUserName") + ":" + System.getProperty("fedoragsearch.fgsPassword")).getBytes())); conn.connect(); } catch (IOException e) { e.printStackTrace(); return; } content = null; try { content = conn.getContent(); } catch (IOException e) { e.printStackTrace(); return; } String line; BufferedReader br = new BufferedReader(new InputStreamReader((InputStream) content)); try { while ((line = br.readLine()) != null) System.out.println(line); } catch (IOException e1) { e1.printStackTrace(); } } Code Sample 2: public static TestResponse post(String urlString, byte[] data, String contentType, String accept) throws IOException { HttpURLConnection httpCon = null; byte[] result = null; byte[] errorResult = null; try { URL url = new URL(urlString); httpCon = (HttpURLConnection) url.openConnection(); httpCon.setDoOutput(true); httpCon.setRequestMethod("POST"); httpCon.setRequestProperty("Content-Type", contentType); httpCon.setRequestProperty("Accept", accept); if (data != null) { OutputStream output = httpCon.getOutputStream(); output.write(data); output.close(); } BufferedInputStream in = new BufferedInputStream(httpCon.getInputStream()); ByteArrayOutputStream os = new ByteArrayOutputStream(); int next = in.read(); while (next > -1) { os.write(next); next = in.read(); } os.flush(); result = os.toByteArray(); os.close(); } catch (IOException e) { e.printStackTrace(); } finally { InputStream errorStream = httpCon.getErrorStream(); if (errorStream != null) { BufferedInputStream errorIn = new BufferedInputStream(errorStream); ByteArrayOutputStream errorOs = new ByteArrayOutputStream(); int errorNext = errorIn.read(); while (errorNext > -1) { errorOs.write(errorNext); errorNext = errorIn.read(); } errorOs.flush(); errorResult = errorOs.toByteArray(); errorOs.close(); } return new TestResponse(httpCon.getResponseCode(), errorResult, result); } }
00
Code Sample 1: private void connect() throws Exception { if (client != null) throw new IllegalStateException("Already connected."); try { _logger.debug("About to connect to ftp server " + server + " port " + port); client = new FTPClient(); client.connect(server, port); if (!FTPReply.isPositiveCompletion(client.getReplyCode())) { throw new Exception("Unable to connect to FTP server " + server + " port " + port + " got error [" + client.getReplyString() + "]"); } _logger.info("Connected to ftp server " + server + " port " + port); _logger.debug(client.getReplyString()); _logger.debug("FTP server is [" + client.getSystemName() + "]"); if (!client.login(username, password)) { throw new Exception("Invalid username / password combination for FTP server " + server + " port " + port); } _logger.debug("Log in successful."); if (passiveMode) { client.enterLocalPassiveMode(); _logger.debug("Passive mode selected."); } else { client.enterLocalActiveMode(); _logger.debug("Active mode selected."); } if (binaryMode) { client.setFileType(FTP.BINARY_FILE_TYPE); _logger.debug("BINARY mode selected."); } else { client.setFileType(FTP.ASCII_FILE_TYPE); _logger.debug("ASCII mode selected."); } if (client.changeWorkingDirectory(remoteRootDir)) { _logger.debug("Changed directory to " + remoteRootDir); } else { if (client.makeDirectory(remoteRootDir)) { _logger.debug("Created directory " + remoteRootDir); if (client.changeWorkingDirectory(remoteRootDir)) { _logger.debug("Changed directory to " + remoteRootDir); } else { throw new Exception("Cannot change directory to [" + remoteRootDir + "] on FTP server " + server + " port " + port); } } else { throw new Exception("Cannot create directory [" + remoteRootDir + "] on FTP server " + server + " port " + port); } } } catch (Exception e) { disconnect(); throw e; } } Code Sample 2: public void compressImage(InputStream input, OutputStream output, DjatokaEncodeParam params) throws DjatokaException { if (params == null) params = new DjatokaEncodeParam(); File inputFile = null; try { inputFile = File.createTempFile("tmp", ".tif"); IOUtils.copyStream(input, new FileOutputStream(inputFile)); if (params.getLevels() == 0) { ImageRecord dim = ImageRecordUtils.getImageDimensions(inputFile.getAbsolutePath()); params.setLevels(ImageProcessingUtils.getLevelCount(dim.getWidth(), dim.getHeight())); dim = null; } } catch (IOException e1) { logger.error("Unexpected file format; expecting uncompressed TIFF", e1); throw new DjatokaException("Unexpected file format; expecting uncompressed TIFF"); } String out = STDOUT; File winOut = null; if (isWindows) { try { winOut = File.createTempFile("pipe_", ".jp2"); } catch (IOException e) { logger.error(e, e); throw new DjatokaException(e); } out = winOut.getAbsolutePath(); } String command = getKduCompressCommand(inputFile.getAbsolutePath(), out, params); logger.debug("compressCommand: " + command); Runtime rt = Runtime.getRuntime(); try { final Process process = rt.exec(command, envParams, new File(env)); if (out.equals(STDOUT)) { IOUtils.copyStream(process.getInputStream(), output); } else if (isWindows) { FileInputStream fis = new FileInputStream(out); IOUtils.copyStream(fis, output); fis.close(); } process.waitFor(); if (process != null) { String errorCheck = null; try { errorCheck = new String(IOUtils.getByteArray(process.getErrorStream())); } catch (Exception e1) { logger.error(e1, e1); } process.getInputStream().close(); process.getOutputStream().close(); process.getErrorStream().close(); process.destroy(); if (errorCheck != null) throw new DjatokaException(errorCheck); } } catch (IOException e) { logger.error(e, e); throw new DjatokaException(e); } catch (InterruptedException e) { logger.error(e, e); throw new DjatokaException(e); } if (inputFile != null) inputFile.delete(); if (winOut != null) winOut.delete(); }
11
Code Sample 1: public void xtestFile1() throws Exception { InputStream inputStream = new FileInputStream(IOTest.FILE); OutputStream outputStream = new FileOutputStream("C:/Temp/testFile1.mp4"); IOUtils.copy(inputStream, outputStream); inputStream.close(); outputStream.close(); } Code Sample 2: public void testAllowClosingInputStreamTwice() throws IOException { OutputStream outputStream = fileSystem.createOutputStream(_("hello"), OutputMode.OVERWRITE); outputStream.write(new byte[] { 1, 2, 3 }); outputStream.close(); InputStream inputStream = fileSystem.createInputStream(_("hello")); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); IOUtils.copy(inputStream, buffer); inputStream.close(); inputStream.close(); }
11
Code Sample 1: static byte[] getPassword(final String name, final String password) { try { final MessageDigest messageDigest = MessageDigest.getInstance("SHA"); messageDigest.update(name.getBytes()); messageDigest.update(password.getBytes()); return messageDigest.digest(); } catch (final NoSuchAlgorithmException e) { throw new JobException(e); } } Code Sample 2: public void write(PDDocument doc) throws COSVisitorException { document = doc; SecurityHandler securityHandler = document.getSecurityHandler(); if (securityHandler != null) { try { securityHandler.prepareDocumentForEncryption(document); this.willEncrypt = true; } catch (IOException e) { throw new COSVisitorException(e); } catch (CryptographyException e) { throw new COSVisitorException(e); } } else { this.willEncrypt = false; } COSDocument cosDoc = document.getDocument(); COSDictionary trailer = cosDoc.getTrailer(); COSArray idArray = (COSArray) trailer.getDictionaryObject("ID"); if (idArray == null) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(Long.toString(System.currentTimeMillis()).getBytes()); COSDictionary info = (COSDictionary) trailer.getDictionaryObject("Info"); if (info != null) { Iterator values = info.getValues().iterator(); while (values.hasNext()) { md.update(values.next().toString().getBytes()); } } idArray = new COSArray(); COSString id = new COSString(md.digest()); idArray.add(id); idArray.add(id); trailer.setItem("ID", idArray); } catch (NoSuchAlgorithmException e) { throw new COSVisitorException(e); } } cosDoc.accept(this); }
00
Code Sample 1: private void loadProperties() throws IOException { if (properties == null) { return; } printDebugIfEnabled("Loading properties"); InputStream inputStream = configurationSource.openStream(); Properties newProperties = new Properties(); try { newProperties.load(inputStream); } finally { inputStream.close(); } String importList = newProperties.getProperty(KEY_IMPORT); if (importList != null) { importList = importList.trim(); if (importList.length() > 0) { String[] filesToImport = importList.split(","); if (filesToImport != null && filesToImport.length != 0) { String configurationContext = configurationSource.toExternalForm(); int lastSlash = configurationContext.lastIndexOf('/'); lastSlash += 1; configurationContext = configurationContext.substring(0, lastSlash); for (int i = 0; i < filesToImport.length; i++) { String filenameToImport = filesToImport[i]; URL urlToImport = new URL(configurationContext + filenameToImport); InputStream importStream = null; try { printDebugIfEnabled("Importing file", urlToImport); importStream = urlToImport.openStream(); newProperties.load(importStream); } catch (IOException e) { printError("Error importing properties file: " + filenameToImport + "(" + urlToImport + ")", e, true); } finally { if (importStream != null) importStream.close(); } } } } } if (devDebug) { Set properties = newProperties.entrySet(); printDebugIfEnabled("_____ Properties List START _____"); for (Iterator iterator = properties.iterator(); iterator.hasNext(); ) { Map.Entry entry = (Map.Entry) iterator.next(); printDebugIfEnabled((String) entry.getKey(), entry.getValue()); } printDebugIfEnabled("______ Properties List END ______"); } properties.clear(); properties.putAll(newProperties); } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: public void insertStringInFile(String file, String textToInsert, long fromByte, long toByte) throws Exception { String tmpFile = file + ".tmp"; BufferedInputStream in = null; BufferedOutputStream out = null; long byteCount = 0; try { in = new BufferedInputStream(new FileInputStream(new File(file))); out = new BufferedOutputStream(new FileOutputStream(tmpFile)); long size = fromByte; byte[] buf = null; if (size == 0) { } else { buf = new byte[(int) size]; int length = -1; if ((length = in.read(buf)) != -1) { out.write(buf, 0, length); byteCount = byteCount + length; } else { String msg = "Failed to read the first '" + size + "' bytes of file '" + file + "'. This might be a programming error."; logger.warning(msg); throw new Exception(msg); } } buf = textToInsert.getBytes(); int length = buf.length; out.write(buf, 0, length); byteCount = byteCount + length; long skipLength = toByte - fromByte; long skippedBytes = in.skip(skipLength); if (skippedBytes == -1) { } else { buf = new byte[4096]; length = -1; while ((length = in.read(buf)) != -1) { out.write(buf, 0, length); byteCount = byteCount + length; } } in.close(); in = null; out.close(); out = null; File fileToDelete = new File(file); boolean wasDeleted = fileToDelete.delete(); if (!wasDeleted) { String msg = "Failed to delete the original file '" + file + "' to replace it with the modified file after text insertion."; logger.warning(msg); throw new Exception(msg); } File fileToRename = new File(tmpFile); boolean wasRenamed = fileToRename.renameTo(fileToDelete); if (!wasRenamed) { String msg = "Failed to rename tmp file '" + tmpFile + "' to the name of the original file '" + file + "'"; logger.warning(msg); throw new Exception(msg); } } catch (Exception e) { logger.log(Level.WARNING, "Failed to read/write file '" + file + "'.", e); throw e; } finally { if (in != null) { try { in.close(); } catch (IOException e) { logger.log(Level.FINEST, "Ignoring error closing input file '" + file + "'.", e); } } if (out != null) { try { out.close(); } catch (IOException e) { logger.log(Level.FINEST, "Ignoring error closing output file '" + tmpFile + "'.", e); } } } } Code Sample 2: public static void zipDirectory(String dir, String zipfile) throws IOException, IllegalArgumentException { File d = new File(dir); if (!d.isDirectory()) throw new IllegalArgumentException("Not a directory: " + dir); String[] entries = d.list(); byte[] buffer = new byte[4096]; int bytesRead; ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile)); for (int i = 0; i < entries.length; i++) { File f = new File(d, entries[i]); if (f.isDirectory()) continue; FileInputStream in = new FileInputStream(f); ZipEntry entry = new ZipEntry(f.getPath()); out.putNextEntry(entry); while ((bytesRead = in.read(buffer)) != -1) out.write(buffer, 0, bytesRead); in.close(); } out.close(); }
11
Code Sample 1: private void handleUpload(CommonsMultipartFile file, String newFileName, String uploadDir) throws IOException, FileNotFoundException { File dirPath = new File(uploadDir); if (!dirPath.exists()) { dirPath.mkdirs(); } InputStream stream = file.getInputStream(); OutputStream bos = new FileOutputStream(uploadDir + newFileName); IOUtils.copy(stream, bos); } Code Sample 2: @Override public String getPath() { InputStream in = null; OutputStream out = null; File file = null; try { file = File.createTempFile("java-storage_" + RandomStringUtils.randomAlphanumeric(32), ".tmp"); file.deleteOnExit(); out = new FileOutputStream(file); in = openStream(); IOUtils.copy(in, out); } catch (IOException e) { throw new RuntimeException(); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } if (file != null && file.exists()) { return file.getPath(); } return null; }
11
Code Sample 1: private static void replaceEntityMappings(File signserverearpath, File entityMappingXML) throws ZipException, IOException { ZipInputStream earFile = new ZipInputStream(new FileInputStream(signserverearpath)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream tempZip = new ZipOutputStream(baos); ZipEntry next = earFile.getNextEntry(); while (next != null) { ByteArrayOutputStream content = new ByteArrayOutputStream(); byte[] data = new byte[30000]; int numberread; while ((numberread = earFile.read(data)) != -1) { content.write(data, 0, numberread); } if (next.getName().equals("signserver-ejb.jar")) { content = replaceEntityMappings(content, entityMappingXML); next = new ZipEntry("signserver-ejb.jar"); } tempZip.putNextEntry(next); tempZip.write(content.toByteArray()); next = earFile.getNextEntry(); } earFile.close(); tempZip.close(); FileOutputStream fos = new FileOutputStream(signserverearpath); fos.write(baos.toByteArray()); fos.close(); } Code Sample 2: public static void CreateBackupOfDataFile(String _src, String _dest) { try { File src = new File(_src); File dest = new File(_dest); if (new File(_src).exists()) { 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(); } } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: public static String upload_file(String sessionid, String localFilePath, String remoteTagPath) { String jsonstring = "If you see this message, there is some problem inside the function:upload_file()"; String srcPath = localFilePath; String uploadUrl = "https://s2.cloud.cm/rpc/json/?session_id=" + sessionid + "&c=Storage&m=upload_file&tag=" + remoteTagPath; String end = "\r\n"; String twoHyphens = "--"; String boundary = "******"; try { URL url = new URL(uploadUrl); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(true); httpURLConnection.setUseCaches(false); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setRequestProperty("Connection", "Keep-Alive"); httpURLConnection.setRequestProperty("Charset", "UTF-8"); httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream()); dos.writeBytes(twoHyphens + boundary + end); dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + srcPath.substring(srcPath.lastIndexOf("/") + 1) + "\"" + end); dos.writeBytes(end); FileInputStream fis = new FileInputStream(srcPath); byte[] buffer = new byte[8192]; int count = 0; while ((count = fis.read(buffer)) != -1) { dos.write(buffer, 0, count); } fis.close(); dos.writeBytes(end); dos.writeBytes(twoHyphens + boundary + twoHyphens + end); dos.flush(); InputStream is = httpURLConnection.getInputStream(); InputStreamReader isr = new InputStreamReader(is, "utf-8"); BufferedReader br = new BufferedReader(isr); jsonstring = br.readLine(); dos.close(); is.close(); return jsonstring; } catch (Exception e) { e.printStackTrace(); } return jsonstring; } Code Sample 2: public static String calculateHA2(String uri) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(getBytes("GET", ISO_8859_1)); md.update((byte) ':'); md.update(getBytes(uri, ISO_8859_1)); return toHexString(md.digest()); } catch (NoSuchAlgorithmException err) { throw new RuntimeException(err); } }
00
Code Sample 1: @Override public void action(String msg, String uri, Gateway gateway) throws Exception { String city = "成都"; if (msg.indexOf("#") != -1) { city = msg.substring(msg.indexOf("#") + 1); } String url = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx/getWeather?theCityCode={city}&theUserID="; url = url.replace("{city}", URLEncoder.encode(city, "UTF8")); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); if (conn.getResponseCode() == 200) { SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(conn.getInputStream()); List strings = doc.getRootElement().getChildren(); String[] sugguestions = getText(strings.get(6)).split("\n"); StringBuffer buffer = new StringBuffer(); buffer.append("欢迎使用MapleSMS的天气服务!\n"); buffer.append("你查询的是 " + getText(strings.get(1)) + "的天气。\n"); buffer.append(getText(strings.get(4)) + "。\n"); buffer.append(getText(strings.get(5)) + "。\n"); buffer.append(sugguestions[0] + "\n"); buffer.append(sugguestions[1] + "\n"); buffer.append(sugguestions[7] + "\n"); buffer.append("感谢你使用MapleSMS的天气服务!祝你愉快!"); gateway.sendSMS(uri, buffer.toString()); } else { gateway.sendSMS(uri, "对不起,你输入的城市格式有误,请检查后再试~"); } } Code Sample 2: public static boolean start(RootDoc root) { Logger log = Logger.getLogger("DocletGenerator"); if (destination == null) { try { ruleListenerDef = IOUtils.toString(GeneratorOfXmlSchemaForConvertersDoclet.class.getResourceAsStream("/RuleListenersFragment.xsd"), "UTF-8"); String fn = System.getenv("annocultor.xconverter.destination.file.name"); fn = (fn == null) ? "./../../../src/site/resources/schema/XConverterInclude.xsd" : fn; destination = new File(fn); if (destination.exists()) { destination.delete(); } FileOutputStream os; os = new FileOutputStream(new File(destination.getParentFile(), "XConverter.xsd")); IOUtils.copy(new AutoCloseInputStream(GeneratorOfXmlSchemaForConvertersDoclet.class.getResourceAsStream("/XConverterTemplate.xsd")), os); os.close(); os = new FileOutputStream(destination); IOUtils.copy(new AutoCloseInputStream(GeneratorOfXmlSchemaForConvertersDoclet.class.getResourceAsStream("/XConverterInclude.xsd")), os); os.close(); } catch (Exception e) { try { throw new RuntimeException("On destination " + destination.getCanonicalPath(), e); } catch (IOException e1) { throw new RuntimeException(e1); } } } try { String s = Utils.loadFileToString(destination.getCanonicalPath(), "\n"); int breakPoint = s.indexOf(XSD_TEXT_TO_REPLACED_WITH_GENERATED_XML_SIGNATURES); if (breakPoint < 0) { throw new Exception("Signature not found in XSD: " + XSD_TEXT_TO_REPLACED_WITH_GENERATED_XML_SIGNATURES); } String preambula = s.substring(0, breakPoint); String appendix = s.substring(breakPoint); destination.delete(); PrintWriter schemaWriter = new PrintWriter(destination); schemaWriter.print(preambula); ClassDoc[] classes = root.classes(); for (int i = 0; i < classes.length; ++i) { ClassDoc cd = classes[i]; PrintWriter documentationWriter = null; if (getSuperClasses(cd).contains(Rule.class.getName())) { for (ConstructorDoc constructorDoc : cd.constructors()) { if (constructorDoc.isPublic()) { if (isMeantForXMLAccess(constructorDoc)) { if (documentationWriter == null) { File file = new File("./../../../src/site/xdoc/rules." + cd.name() + ".xml"); documentationWriter = new PrintWriter(file); log.info("Generating doc for rule " + file.getCanonicalPath()); printRuleDocStart(cd, documentationWriter); } boolean initFound = false; for (MethodDoc methodDoc : cd.methods()) { if ("init".equals(methodDoc.name())) { if (methodDoc.parameters().length == 0) { initFound = true; break; } } } if (!initFound) { } printConstructorSchema(constructorDoc, schemaWriter); if (documentationWriter != null) { printConstructorDoc(constructorDoc, documentationWriter); } } } } } if (documentationWriter != null) { printRuleDocEnd(documentationWriter); } } schemaWriter.print(appendix); schemaWriter.close(); log.info("Saved to " + destination.getCanonicalPath()); } catch (Exception e) { throw new RuntimeException(e); } return true; }
00
Code Sample 1: int doOne(int bid, int tid, int aid, int delta) { int aBalance = 0; if (Conn == null) { incrementFailedTransactionCount(); return 0; } try { if (prepared_stmt) { pstmt1.setInt(1, delta); pstmt1.setInt(2, aid); pstmt1.executeUpdate(); pstmt1.clearWarnings(); pstmt2.setInt(1, aid); ResultSet RS = pstmt2.executeQuery(); pstmt2.clearWarnings(); while (RS.next()) { aBalance = RS.getInt(1); } pstmt3.setInt(1, delta); pstmt3.setInt(2, tid); pstmt3.executeUpdate(); pstmt3.clearWarnings(); pstmt4.setInt(1, delta); pstmt4.setInt(2, bid); pstmt4.executeUpdate(); pstmt4.clearWarnings(); pstmt5.setInt(1, tid); pstmt5.setInt(2, bid); pstmt5.setInt(3, aid); pstmt5.setInt(4, delta); pstmt5.executeUpdate(); pstmt5.clearWarnings(); } else { Statement Stmt = Conn.createStatement(); String Query = "UPDATE accounts "; Query += "SET Abalance = Abalance + " + delta + " "; Query += "WHERE Aid = " + aid; int res = Stmt.executeUpdate(Query); Stmt.clearWarnings(); Query = "SELECT Abalance "; Query += "FROM accounts "; Query += "WHERE Aid = " + aid; ResultSet RS = Stmt.executeQuery(Query); Stmt.clearWarnings(); while (RS.next()) { aBalance = RS.getInt(1); } Query = "UPDATE tellers "; Query += "SET Tbalance = Tbalance + " + delta + " "; Query += "WHERE Tid = " + tid; Stmt.executeUpdate(Query); Stmt.clearWarnings(); Query = "UPDATE branches "; Query += "SET Bbalance = Bbalance + " + delta + " "; Query += "WHERE Bid = " + bid; Stmt.executeUpdate(Query); Stmt.clearWarnings(); Query = "INSERT INTO history(Tid, Bid, Aid, delta) "; Query += "VALUES ("; Query += tid + ","; Query += bid + ","; Query += aid + ","; Query += delta + ")"; Stmt.executeUpdate(Query); Stmt.clearWarnings(); Stmt.close(); } if (transactions) { Conn.commit(); } return aBalance; } catch (Exception E) { if (verbose) { System.out.println("Transaction failed: " + E.getMessage()); E.printStackTrace(); } incrementFailedTransactionCount(); if (transactions) { try { Conn.rollback(); } catch (SQLException E1) { } } } return 0; } Code Sample 2: public void run() { try { ThreadGroup transfers = new ThreadGroup("transfers"); URL url = new URL("jar:http://jopenrpg.sourceforge.net/files/dev/pythonlib.jar!/"); JarURLConnection juc = (JarURLConnection) url.openConnection(); File top = new File(System.getProperty("user.home"), "jopenrpg"); final JarFile jarfile = juc.getJarFile(); Enumeration enumer = jarfile.entries(); while (enumer.hasMoreElements()) { final JarEntry entry = (JarEntry) enumer.nextElement(); final File f = new File(top, entry.getName()); if (entry.isDirectory()) { f.mkdirs(); } else { if (!entry.getName().startsWith("META-INF")) new Thread(transfers, new Runnable() { public void run() { try { BufferedReader br = new BufferedReader(new InputStreamReader(jarfile.getInputStream(entry))); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f))); StringBuffer buf = new StringBuffer(); while (br.ready()) { buf.append(br.read()); } bw.write(buf.toString(), 0, buf.length()); bw.close(); br.close(); } catch (Exception ex) { System.out.println(ex); } } }).start(); } } while (transfers.activeCount() > 0) yield(); SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(ReferenceManager.getInstance().getMainFrame(), "Jython libraries installed."); } }); } catch (Exception ex) { ex.printStackTrace(); } }
00
Code Sample 1: @Override public void writeToContent(Object principal, String uniqueId, InputStream ins) throws IOException, ContentException { if (writable) { URL url = buildURL(uniqueId); URLConnection connection = url.openConnection(); OutputStream outs = connection.getOutputStream(); try { ContentUtil.pipe(ins, outs); } finally { try { outs.close(); } catch (Exception ex) { log.log(Level.WARNING, "unable to close " + url, ex); } } } else { throw new ContentException("not writable"); } } Code Sample 2: public void testHandler() throws MalformedURLException, IOException { assertTrue("This test can only be run once in a single JVM", imageHasNotBeenInstalledInThisJVM); URL url; Handler.installImageUrlHandler((ImageSource) new ClassPathXmlApplicationContext("org/springframework/richclient/image/application-context.xml").getBean("imageSource")); try { url = new URL("image:test"); imageHasNotBeenInstalledInThisJVM = false; } catch (MalformedURLException e) { fail("protocol was not installed"); } url = new URL("image:image.that.does.not.exist"); try { url.openConnection(); fail(); } catch (NoSuchImageResourceException e) { } url = new URL("image:test.image.key"); url.openConnection(); }
00
Code Sample 1: private void createIDocPluginProject(IProgressMonitor monitor, String sourceFileName, String pluginName, String pluginNameJCo) throws CoreException, IOException { monitor.subTask(MessageFormat.format(Messages.ProjectGenerator_CreatePluginTaskDescription, pluginName)); final Map<String, byte[]> files = readArchiveFile(sourceFileName); monitor.worked(10); IProject project = workspaceRoot.getProject(pluginName); if (project.exists()) { project.delete(true, true, new SubProgressMonitor(monitor, 5)); } else { monitor.worked(5); } project.create(new SubProgressMonitor(monitor, 5)); project.open(new SubProgressMonitor(monitor, 5)); IProjectDescription description = project.getDescription(); description.setNatureIds(new String[] { JavaCore.NATURE_ID, PLUGIN_NATURE_ID }); project.setDescription(description, new SubProgressMonitor(monitor, 5)); IJavaProject javaProject = JavaCore.create(project); IFolder binDir = project.getFolder("bin"); IPath binPath = binDir.getFullPath(); javaProject.setOutputLocation(binPath, new SubProgressMonitor(monitor, 5)); project.getFile("sapidoc3.jar").create(new ByteArrayInputStream(files.get("sapidoc3.jar")), true, new SubProgressMonitor(monitor, 15)); IFolder metaInfFolder = project.getFolder("META-INF"); metaInfFolder.create(true, true, new SubProgressMonitor(monitor, 5)); StringBuilder manifest = new StringBuilder(); manifest.append("Manifest-Version: 1.0\n"); manifest.append("Bundle-ManifestVersion: 2\n"); manifest.append("Bundle-Name: SAP IDoc Library v3\n"); manifest.append(MessageFormat.format("Bundle-SymbolicName: {0}\n", pluginName)); manifest.append("Bundle-Version: 7.11.0\n"); manifest.append("Bundle-ClassPath: bin/,\n"); manifest.append(" sapidoc3.jar\n"); manifest.append("Bundle-Vendor: SAP AG, Walldorf (packaged using RCER)\n"); manifest.append("Bundle-RequiredExecutionEnvironment: J2SE-1.5\n"); manifest.append("Export-Package: com.sap.conn.idoc,\n"); manifest.append(" com.sap.conn.idoc.jco,\n"); manifest.append(" com.sap.conn.idoc.rt.cp,\n"); manifest.append(" com.sap.conn.idoc.rt.record,\n"); manifest.append(" com.sap.conn.idoc.rt.record.impl,\n"); manifest.append(" com.sap.conn.idoc.rt.trace,\n"); manifest.append(" com.sap.conn.idoc.rt.util,\n"); manifest.append(" com.sap.conn.idoc.rt.xml\n"); manifest.append("Bundle-ActivationPolicy: lazy\n"); manifest.append(MessageFormat.format("Require-Bundle: {0}\n", pluginNameJCo)); writeTextFile(monitor, manifest, metaInfFolder.getFile("MANIFEST.MF")); final IPath jcoPath = new Path(MessageFormat.format("/{0}/sapidoc3.jar", pluginName)); IClasspathEntry jcoEntry = JavaCore.newLibraryEntry(jcoPath, Path.EMPTY, Path.EMPTY, true); javaProject.setRawClasspath(new IClasspathEntry[] { jcoEntry }, new SubProgressMonitor(monitor, 5)); StringBuilder buildProperties = new StringBuilder(); buildProperties.append("bin.includes = META-INF/,\\\n"); buildProperties.append(" sapidoc3.jar,\\\n"); buildProperties.append(" .\n"); writeTextFile(monitor, buildProperties, project.getFile("build.properties")); exportableBundles.add(modelManager.findModel(project)); } Code Sample 2: public static boolean downloadRegPage() { String filename = "register.php?csz=" + checkEmptyString(jDtr) + "&&mac=" + MAC + "&&uname=" + checkEmptyString(InstallName) + "&&cname=" + checkEmptyString(InstallCompany) + "&&winuname=" + checkEmptyString(WinName) + "&&wincname=" + checkEmptyString(WinCompany) + "&&age=" + checkEmptyString(jAge) + "&&sal=" + checkEmptyString(jSal) + "&&sta=" + checkEmptyString(jSta) + "&&sex=" + checkEmptyString(jSex) + "&&con=" + checkEmptyString(jCon) + "&&occ=" + checkEmptyString(jOcc) + "&&int=" + checkEmptyString(jInt) + "&&ver=" + checkEmptyString(jVer) + "&&mor=" + checkEmptyString(jTyp); URL url1 = null; try { url1 = new URL(url + filename); } catch (MalformedURLException e1) { } int status = 0; try { status = ((HttpURLConnection) url1.openConnection()).getResponseCode(); } catch (IOException e1) { System.out.println(e1); } if (status == 200) { return true; } else { return false; } }
00
Code Sample 1: public ISOMsg filter(ISOChannel channel, ISOMsg m, LogEvent evt) throws VetoException { if (key == null || fields == null) throw new VetoException("MD5Filter not configured"); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(getKey()); int[] f = getFields(m); for (int i = 0; i < f.length; i++) { int fld = f[i]; if (m.hasField(fld)) { ISOComponent c = m.getComponent(fld); if (c instanceof ISOBinaryField) md.update((byte[]) c.getValue()); else md.update(((String) c.getValue()).getBytes()); } } byte[] digest = md.digest(); if (m.getDirection() == ISOMsg.OUTGOING) { m.set(new ISOBinaryField(64, digest, 0, 8)); m.set(new ISOBinaryField(128, digest, 8, 8)); } else { byte[] rxDigest = new byte[16]; if (m.hasField(64)) System.arraycopy((byte[]) m.getValue(64), 0, rxDigest, 0, 8); if (m.hasField(128)) System.arraycopy((byte[]) m.getValue(128), 0, rxDigest, 8, 8); if (!Arrays.equals(digest, rxDigest)) { evt.addMessage(m); evt.addMessage("MAC expected: " + ISOUtil.hexString(digest)); evt.addMessage("MAC received: " + ISOUtil.hexString(rxDigest)); throw new VetoException("invalid MAC"); } m.unset(64); m.unset(128); } } catch (NoSuchAlgorithmException e) { throw new VetoException(e); } catch (ISOException e) { throw new VetoException(e); } return m; } Code Sample 2: private boolean Try(URL url, Metafile mf) throws Throwable { InputStream is = null; HttpURLConnection con = null; boolean success = false; try { con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.connect(); is = con.getInputStream(); Response r = new Response(is); responses.add(r); peers.addAll(r.peers); Main.log.info("got " + r.peers.size() + " peers from " + url); success = true; } finally { if (is != null) is.close(); if (con != null) con.disconnect(); } return success; }
00
Code Sample 1: public OutputStream createOutputStream(URI uri, Map<?, ?> options) throws IOException { try { URL url = new URL(uri.toString()); final URLConnection urlConnection = url.openConnection(); urlConnection.setDoOutput(true); if (urlConnection instanceof HttpURLConnection) { final HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection; httpURLConnection.setRequestMethod("PUT"); return new FilterOutputStream(urlConnection.getOutputStream()) { @Override public void close() throws IOException { super.close(); int responseCode = httpURLConnection.getResponseCode(); switch(responseCode) { case HttpURLConnection.HTTP_OK: case HttpURLConnection.HTTP_CREATED: case HttpURLConnection.HTTP_NO_CONTENT: { break; } default: { throw new IOException("PUT failed with HTTP response code " + responseCode); } } } }; } else { OutputStream result = urlConnection.getOutputStream(); final Map<Object, Object> response = getResponse(options); if (response != null) { result = new FilterOutputStream(result) { @Override public void close() throws IOException { try { super.close(); } finally { response.put(URIConverter.RESPONSE_TIME_STAMP_PROPERTY, urlConnection.getLastModified()); } } }; } return result; } } catch (RuntimeException exception) { throw new Resource.IOWrappedException(exception); } } Code Sample 2: public static void copyFile(File sourceFile, File destFile) { FileChannel source = null; FileChannel destination = null; try { if (!destFile.exists()) { destFile.createNewFile(); } source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } catch (Exception e) { e.printStackTrace(); } finally { try { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } catch (Exception e) { e.printStackTrace(); } } }