label
class label
2 classes
source_code
stringlengths
398
72.9k
00
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 { closeQuietly(in); closeQuietly(out); } return success; } Code Sample 2: public static String getServiceContent(String serviceURL) throws IOException { URL url = new URL(serviceURL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); int code = connection.getResponseCode(); if (code == HttpURLConnection.HTTP_OK) { InputStream is = connection.getInputStream(); byte[] buffer = null; String stringBuffer = ""; buffer = new byte[4096]; int totBytes, bytes, sumBytes = 0; totBytes = connection.getContentLength(); while (true) { bytes = is.read(buffer); if (bytes <= 0) break; stringBuffer = stringBuffer + new String(buffer); } return stringBuffer; } return null; }
00
Code Sample 1: public static void loginSkyDrive() throws Exception { System.out.println("login "); u = new URL(loginurl); uc = (HttpURLConnection) u.openConnection(); uc.setRequestProperty("Cookie", msprcookie + ";" + mspokcookie); uc.setDoOutput(true); uc.setRequestMethod("POST"); uc.setInstanceFollowRedirects(false); pw = new PrintWriter(new OutputStreamWriter(uc.getOutputStream()), true); pw.print("login=dinesh007007%40hotmail.com&passwd=&SI=Sign+in&type=11&LoginOptions=3&NewUser=1&MEST=&PPSX=Passpor&PPFT=" + ppft + "&PwdPad=&sso=&i1=&i2=1&i3=10524&i4=&i12=1&i13=&i14=437&i15=624&i16=3438"); pw.flush(); pw.close(); System.out.println(uc.getResponseCode()); Map<String, List<String>> headerFields = uc.getHeaderFields(); if (headerFields.containsKey("Set-Cookie")) { List<String> header = headerFields.get("Set-Cookie"); for (int i = 0; i < header.size(); i++) { tmp = header.get(i); System.out.println(tmp); } } location = uc.getHeaderField("Location"); System.out.println("Location : " + location); System.out.println("going to open paaport page"); DefaultHttpClient d = new DefaultHttpClient(); HttpGet hg = new HttpGet("https://skydrive.live.com"); hg.setHeader("Cookie", msprcookie + ";" + mspokcookie); HttpResponse execute = d.execute(hg); HttpEntity entity = execute.getEntity(); System.out.println(EntityUtils.toString(entity)); System.out.println(execute.getStatusLine()); Header[] allHeaders = execute.getAllHeaders(); for (int i = 0; i < allHeaders.length; i++) { System.out.println(allHeaders[i].getName() + " : " + allHeaders[i].getValue()); } } Code Sample 2: public static boolean copyFile(final String src, final String dest) { if (fileExists(src)) { try { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); return true; } catch (IOException e) { Logger.getAnonymousLogger().severe(e.getLocalizedMessage()); } } return false; }
11
Code Sample 1: public void processExplicitSchemaAndWSDL(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { HashMap services = configContext.getAxisConfiguration().getServices(); String filePart = req.getRequestURL().toString(); String schema = filePart.substring(filePart.lastIndexOf("/") + 1, filePart.length()); if ((services != null) && !services.isEmpty()) { Iterator i = services.values().iterator(); while (i.hasNext()) { AxisService service = (AxisService) i.next(); InputStream stream = service.getClassLoader().getResourceAsStream("META-INF/" + schema); if (stream != null) { OutputStream out = res.getOutputStream(); res.setContentType("text/xml"); IOUtils.copy(stream, out, true); return; } } } } Code Sample 2: @Override public InputStream getInputStream() throws IOException { if (dfos == null) { int deferredOutputStreamThreshold = Config.getInstance().getDeferredOutputStreamThreshold(); dfos = new DeferredFileOutputStream(deferredOutputStreamThreshold, Definitions.PROJECT_NAME, "." + Definitions.TMP_EXTENSION); try { IOUtils.copy(is, dfos); } finally { dfos.close(); } } return dfos.getDeferredInputStream(); }
11
Code Sample 1: public String readBaseLib() throws Exception { if (_BASE_LIB_JS == null) { StringBuffer js = new StringBuffer(); try { URL url = AbstractRunner.class.getResource(_BASELIB_FILENAME); if (url != null) { InputStream is = url.openStream(); InputStreamReader reader = new InputStreamReader(is); BufferedReader bfReader = new BufferedReader(reader); String tmp = null; do { tmp = bfReader.readLine(); if (tmp != null) { js.append(tmp).append('\n'); } } while (tmp != null); bfReader.close(); reader.close(); is.close(); } } catch (Exception e) { e.printStackTrace(); throw e; } _BASE_LIB_JS = js.toString(); } return _BASE_LIB_JS; } Code Sample 2: public static String sendGetRequest(String urlStr) { String result = null; try { URL url = new URL(urlStr); System.out.println(urlStr); URLConnection conn = url.openConnection(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); String line = ""; System.out.println("aa" + line); while ((line = rd.readLine()) != null) { System.out.println("aa" + line); sb.append(line); } rd.close(); result = sb.toString(); } catch (Exception e) { e.printStackTrace(); } return result; }
00
Code Sample 1: public HttpResponse execute(HttpRequest request) throws IOException { this.request = request; buildParams(); String l = request.getUrl(); if (request instanceof HttpGet) { l = l + "?" + params; } URL url = new URL(l); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(connectTimeout); conn.setReadTimeout(readTimeout); buildHeader(); if (request instanceof HttpPost) { sendRequest(); } readResponse(); return this.response; } Code Sample 2: InputStream createInputStream(FileInfo fi) throws IOException, MalformedURLException { if (fi.inputStream != null) return fi.inputStream; else if (fi.url != null && !fi.url.equals("")) return new URL(fi.url + fi.fileName).openStream(); else { File f = new File(fi.directory + fi.fileName); if (f == null || f.isDirectory()) return null; else { InputStream is = new FileInputStream(f); if (fi.compression >= FileInfo.LZW) is = new RandomAccessStream(is); return is; } } }
11
Code Sample 1: private void copyOneFile(String oldPath, String newPath) { File copiedFile = new File(newPath); try { FileInputStream source = new FileInputStream(oldPath); FileOutputStream destination = new FileOutputStream(copiedFile); FileChannel sourceFileChannel = source.getChannel(); FileChannel destinationFileChannel = destination.getChannel(); long size = sourceFileChannel.size(); sourceFileChannel.transferTo(0, size, destinationFileChannel); source.close(); destination.close(); } catch (Exception exc) { exc.printStackTrace(); } } Code Sample 2: 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 = ("���Ƶ����ļ���������"); } }
00
Code Sample 1: @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())); } Code Sample 2: public boolean urlToSpeech(String urlPath) { boolean ok = false; try { URL url = new URL(urlPath); InputStream is = url.openStream(); ok = streamToSpeech(is); } catch (IOException ioe) { System.err.println("Can't read data from " + urlPath); } return ok; }
00
Code Sample 1: public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { response.setContentType("text/html;charset=UTF-8"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; _jspx_resourceInjector = (org.apache.jasper.runtime.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector"); out.write("\n"); out.write("\n"); out.write("\n"); String username = "test"; String password = "test"; int providerId = 1; if (request.getParameter("providerId") != null) providerId = Integer.parseInt(request.getParameter("providerId")); String thisPageContextAddress = "http://localhost:8080" + request.getContextPath(); String thisPageServingAddress = thisPageContextAddress + "/index.jsp"; String token = ""; String token_timeout = (String) request.getParameter("token_timeout"); String referer = request.getHeader("Referer"); if (token_timeout != null && token_timeout.equals("true")) { System.out.println("token timeout for referer" + referer); if (referer != null) { if (request.getSession().getServletContext().getAttribute("token_timeout_processing_lock") == null) { request.getSession().getServletContext().setAttribute("token_timeout_processing_lock", true); byte[] buff = null; BufferedInputStream bis = null; URL url = new URL(thisPageContextAddress + "/ServerAdminServlet?action=login&username=" + username + "&password=" + password); URLConnection urlc = url.openConnection(); int length = urlc.getContentLength(); InputStream in = urlc.getInputStream(); buff = new byte[length]; int bytesRead = 0; while (bytesRead < length) { bytesRead += in.read(buff, bytesRead, in.available()); } token = new String(buff); token = token.replaceAll("[\\r\\f]", ""); token = token.trim(); request.getSession().getServletContext().setAttribute("token", token); out.println(token); request.getSession().getServletContext().removeAttribute("token_timeout_processing_lock"); } else out.println("token_timeout_processing_lock"); } } else { if (request.getSession().getServletContext().getAttribute("token") == null || request.getSession().getServletContext().getAttribute("token").equals("")) { byte[] buff = null; BufferedInputStream bis = null; URL url = new URL(thisPageContextAddress + "/ServerAdminServlet?action=login&username=" + username + "&password=" + password); URLConnection urlc = url.openConnection(); int length = urlc.getContentLength(); InputStream in = urlc.getInputStream(); buff = new byte[length]; int bytesRead = 0; while (bytesRead < length) { bytesRead += in.read(buff, bytesRead, in.available()); } token = new String(buff); token = token.replaceAll("[\\r\\f]", ""); token = token.trim(); request.getSession().getServletContext().setAttribute("token", token); } out.write("\n"); out.write("<html>\n"); out.write(" <head>\n"); out.write(" <title>AJAX test </title>\n"); out.write(" <link rel=\"stylesheet\" href=\"css/default.css\" type=\"text/css\" />\n"); out.write("\n"); out.write(" <script type=\"text/javascript\" src=\"../OpenLayers-2.8/OpenLayers.js\"></script>\n"); out.write(" <script type=\"text/javascript\">\n"); out.write("\n"); out.write(" var map, layer;\n"); out.write("\n"); out.write(" var token = \""); out.print(request.getSession().getServletContext().getAttribute("token")); out.write("\";\n"); out.write("\n"); out.write("\n"); out.write(" function init(){\n"); out.write("\n"); out.write(" OpenLayers.IMAGE_RELOAD_ATTEMPTS = 5;\n"); out.write("\n"); out.write(" var options = {\n"); out.write(" maxExtent: new OpenLayers.Bounds(0, 0, 3000000, 9000000),\n"); out.write(" tileSize :new OpenLayers.Size(250, 250),\n"); out.write(" units: 'm',\n"); out.write(" projection: 'EPSG:3006',\n"); out.write(" resolutions : [1.3,2.6,4,6.6,13.2,26.5,66.1,132.3,264.6,793.8,1322.9,2645.8,13229.2,26458.3]\n"); out.write(" }\n"); out.write("\n"); out.write(" map = new OpenLayers.Map('swedenMap', options);\n"); out.write("\n"); out.write(" layer = new OpenLayers.Layer.TMS(\"TMS\", \"http://localhost:8080/WebGISTileServer/TMSServletProxy/\",\n"); out.write(" { layername: token + '/7', type: 'png' });\n"); out.write("\n"); out.write(" map.addLayer(layer);\n"); out.write("\n"); out.write(" map.addControl( new OpenLayers.Control.PanZoom() );\n"); out.write(" map.addControl( new OpenLayers.Control.PanZoomBar() );\n"); out.write(" map.addControl( new OpenLayers.Control.MouseDefaults());\n"); out.write(" map.addControl( new OpenLayers.Control.MousePosition());\n"); out.write("\n"); out.write(" map.setCenter(new OpenLayers.LonLat(555555, 6846027), 2);\n"); out.write(" }\n"); out.write(" </script>\n"); out.write(" </head>\n"); out.write(" <body onload=\"init()\">\n"); out.write("\n"); out.write(" <div id=\"container\">\n"); out.write("\n"); out.write(" <div id=\"header\">\n"); out.write(" <h1 id=\"logo\">\n"); out.write(" <span>ASP</span> MapServices\n"); out.write(" <small>Web mapping. <span>EASY</span></small>\n"); out.write(" </h1>\n"); out.write("\n"); out.write(" <ul id=\"menu\">\n"); out.write(" <li><a href=\"default.html\">Home</a></li>\n"); out.write(" <li><a href=\"demo_world.jsp\">Demonstration</a></li>\n"); out.write(" <li style=\"border-right: none;\"><a href=\"contact.html\">Contact</a></li>\n"); out.write(" </ul>\n"); out.write(" </div>\n"); out.write("\n"); out.write(" <div id=\"body\">\n"); out.write(" <ul id=\"maps-menu\">\n"); out.write(" <li><a href=\"demo_world.jsp\">World</a></li>\n"); out.write(" <li><a href=\"demo_sweden_rt90.jsp\">Sweden RT90</a></li>\n"); out.write(" <li><a href=\"demo_sweden_sweref99.jsp\">Sweden SWEREF99</a></li>\n"); out.write(" </ul>\n"); out.write("\n"); out.write(" <div id=\"swedenMap\" style=\"height:600px\"></div>\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" </body>\n"); out.write("\n"); out.write("\n"); out.write(" </head>\n"); out.write("\n"); out.write("</html>"); } out.write('\n'); out.write('\n'); } catch (Throwable t) { if (!(t instanceof SkipPageException)) { out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } Code Sample 2: private void addMaintainerScripts(TarOutputStream tar, PackageInfo info) throws IOException, ScriptDataTooLargeException { for (final MaintainerScript script : info.getMaintainerScripts().values()) { if (script.getSize() > Integer.MAX_VALUE) { throw new ScriptDataTooLargeException("The script data is too large for the tar file. script=[" + script.getType().getFilename() + "]."); } final TarEntry entry = standardEntry(script.getType().getFilename(), UnixStandardPermissions.EXECUTABLE_FILE_MODE, (int) script.getSize()); tar.putNextEntry(entry); IOUtils.copy(script.getStream(), tar); tar.closeEntry(); } }
11
Code Sample 1: private static void copySmallFile(File sourceFile, File targetFile) throws BusinessException { LOG.debug("Copying SMALL file '" + sourceFile.getAbsolutePath() + "' to '" + targetFile.getAbsolutePath() + "'."); FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(sourceFile).getChannel(); outChannel = new FileOutputStream(targetFile).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw new BusinessException("Could not copy file from '" + sourceFile.getAbsolutePath() + "' to '" + targetFile.getAbsolutePath() + "'!", e); } finally { try { if (inChannel != null) inChannel.close(); } catch (IOException e) { LOG.error("Could not close input stream!", e); } try { if (outChannel != null) outChannel.close(); } catch (IOException e) { LOG.error("Could not close output stream!", e); } } } Code Sample 2: private void copyThemeProviderClass() throws Exception { InputStream is = getClass().getResourceAsStream("/zkthemer/ThemeProvider.class"); if (is == null) throw new RuntimeException("Cannot find ThemeProvider.class"); File outFile = new File(theme.getJarRootFile(), "zkthemer/ThemeProvider.class"); outFile.getParentFile().mkdirs(); FileOutputStream out = new FileOutputStream(outFile); IOUtils.copy(is, out); out.close(); FileUtils.writeStringToFile(new File(theme.getJarRootFile(), "zkthemer.properties"), "theme=" + theme.getName() + "\r\nfileList=" + fileList.deleteCharAt(fileList.length() - 1).toString()); }
00
Code Sample 1: public static String getTextFromPart(Part part) { try { if (part != null && part.getBody() != null) { InputStream in = part.getBody().getInputStream(); String mimeType = part.getMimeType(); if (mimeType != null && MimeUtility.mimeTypeMatches(mimeType, "text/*")) { ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); in.close(); in = null; String charset = getHeaderParameter(part.getContentType(), "charset"); if (charset != null) { charset = CharsetUtil.toJavaCharset(charset); } if (charset == null) { charset = "ASCII"; } String result = out.toString(charset); out.close(); return result; } } } catch (OutOfMemoryError oom) { Log.e(Email.LOG_TAG, "Unable to getTextFromPart " + oom.toString()); } catch (Exception e) { Log.e(Email.LOG_TAG, "Unable to getTextFromPart " + e.toString()); } return null; } Code Sample 2: public void read(Model model, String url) { try { URLConnection conn = new URL(url).openConnection(); String encoding = conn.getContentEncoding(); if (encoding == null) { read(model, conn.getInputStream(), url); } else { read(model, new InputStreamReader(conn.getInputStream(), encoding), url); } } catch (IOException e) { throw new JenaException(e); } }
11
Code Sample 1: private void copyFileToPhotoFolder(File photo, String personId) { try { FileChannel in = new FileInputStream(photo).getChannel(); File dirServer = new File(Constants.PHOTO_DIR); if (!dirServer.exists()) { dirServer.mkdirs(); } File fileServer = new File(Constants.PHOTO_DIR + personId + ".jpg"); if (!fileServer.exists()) { fileServer.createNewFile(); } in.transferTo(0, in.size(), new FileOutputStream(fileServer).getChannel()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public static final void copyFile(File argSource, File argDestination) throws IOException { FileChannel srcChannel = new FileInputStream(argSource).getChannel(); FileChannel dstChannel = new FileOutputStream(argDestination).getChannel(); try { dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { srcChannel.close(); dstChannel.close(); } }
11
Code Sample 1: private void createWikiPages(WikiContext context) throws PluginException { OntologyWikiPageName owpn = new OntologyWikiPageName(omemo.getFormDataAlias().toUpperCase(), omemo.getFormDataVersionDate()); String wikiPageFullFileName = WikiPageName2FullFileName(context, owpn.toString()); String rdfFileNameWithPath = getWorkDir(context) + File.separator + owpn.toFileName(); FileOutputStream fos = null; FileInputStream fis = null; try { fos = new FileOutputStream(wikiPageFullFileName); fis = new FileInputStream(rdfFileNameWithPath); InfoExtractor infoe = new InfoExtractor(fis, omemo.getFormDataNS(), omemo.getFormDataOntLang()); infoe.writePage(getWorkDir(context), owpn, Omemo.checksWikiPageName); fis.close(); fos.close(); } catch (Exception e) { log.error("Can not read local rdf file or can not write wiki page"); throw new PluginException("Error creating wiki pages. See logs"); } } 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; }
11
Code Sample 1: private String encryptPassword(String password) throws NoSuchAlgorithmException { MessageDigest encript = MessageDigest.getInstance("MD5"); encript.update(password.getBytes()); byte[] b = encript.digest(); int size = b.length; StringBuffer h = new StringBuffer(size); for (int i = 0; i < size; i++) { h.append(b[i]); } return h.toString(); } Code Sample 2: public String getUniqueId() { String digest = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); String timeVal = "" + (System.currentTimeMillis() + 1); String localHost = ""; ; try { localHost = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { } String randVal = "" + new Random().nextInt(); String val = timeVal + localHost + randVal; md.reset(); md.update(val.getBytes()); digest = toHexString(md.digest()); } catch (NoSuchAlgorithmException e) { } return digest; }
11
Code Sample 1: public void write(HttpServletRequest req, HttpServletResponse res, Object bean) throws IntrospectionException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, IOException { res.setContentType(contentType); final Object r; if (HttpRpcServer.HttpRpcOutput.class.isAssignableFrom(bean.getClass())) { HttpRpcServer.HttpRpcOutput output = (HttpRpcServer.HttpRpcOutput) bean; r = output.getResult(); } else r = bean; if (r != null) { if (File.class.isAssignableFrom(r.getClass())) { File file = (File) r; InputStream in = null; try { in = new FileInputStream(file); IOUtils.copy(in, res.getOutputStream()); } finally { if (in != null) in.close(); } } else if (InputStream.class.isAssignableFrom(r.getClass())) { InputStream in = null; try { in = (InputStream) r; IOUtils.copy(in, res.getOutputStream()); } finally { if (in != null) in.close(); } } else if (XFile.class.isAssignableFrom(r.getClass())) { XFile file = (XFile) r; InputStream in = null; try { in = new XFileInputStream(file); IOUtils.copy(in, res.getOutputStream()); } finally { if (in != null) in.close(); } } res.getOutputStream().flush(); } } Code Sample 2: static void copy(String src, String dest) throws IOException { File ifp = new File(src); File ofp = new File(dest); if (ifp.exists() == false) { throw new IOException("file '" + src + "' does not exist"); } FileInputStream fis = new FileInputStream(ifp); FileOutputStream fos = new FileOutputStream(ofp); byte[] b = new byte[1024]; while (fis.read(b) > 0) fos.write(b); fis.close(); fos.close(); }
11
Code Sample 1: public static String getEncodedHex(String text) { MessageDigest md = null; String encodedString = null; try { md = MessageDigest.getInstance("MD5"); md.update(text.getBytes()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } Hex hex = new Hex(); encodedString = new String(hex.encode(md.digest())); md.reset(); return encodedString; } Code Sample 2: public static String toPWD(String pwd) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(pwd.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } return md5StrBuff.toString(); }
00
Code Sample 1: private Document getOpenLinkResponse(String queryDoc) throws IOException, UnvalidResponseException { URL url = new URL(WS_URI); URLConnection conn = url.openConnection(); logger.debug(".conn open"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "text/xml"); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(queryDoc); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); logger.debug(".resp obtained"); StringBuffer responseBuffer = new StringBuffer(); String line; while ((line = rd.readLine()) != null) { responseBuffer.append(line); responseBuffer.append(NEWLINE); } wr.close(); rd.close(); logger.debug(".done"); try { return documentParser.parse(responseBuffer.toString()); } catch (SAXException e) { throw new UnvalidResponseException("Response is not a valid XML file", e); } } Code Sample 2: public void dispatch(com.sun.star.util.URL aURL, com.sun.star.beans.PropertyValue[] aArguments) { if (aURL.Protocol.compareTo("org.openoffice.oosvn.oosvn:") == 0) { OoDocProperty docProperty = getProperty(); settings.setCancelFired(false); if (aURL.Path.compareTo("svnUpdate") == 0) { try { try { settings = getSerializedSettings(docProperty); } catch (NullPointerException ex) { new DialogSettings(new javax.swing.JFrame(), true, settings).setVisible(true); if (settings.getCancelFired()) return; new DialogFileChooser(new javax.swing.JFrame(), true, settings).setVisible(true); if (settings.getCancelFired()) return; } catch (Exception ex) { error("Error getting settings", ex); return; } Object[][] logs = getLogs(settings); long checkVersion = -1; if (logs.length == 0) { error("Sorry, the specified repository is empty."); return; } new DialogSVNHistory(new javax.swing.JFrame(), true, settings, logs).setVisible(true); if (settings.getCancelFired()) return; File tempDir = new File(settings.getCheckoutPath() + svnWorker.tempDir); if (tempDir.exists()) { if (deleteFileDir(tempDir) == false) { error("Error while deleting temporary checkout dir."); } } svnWorker.checkout(settings); File[] tempFiles = tempDir.listFiles(); File anyOdt = null; File thisOdt = null; for (int j = 0; j < tempFiles.length; j++) { if (tempFiles[j].toString().endsWith(".odt")) anyOdt = tempFiles[j]; if (tempFiles[j].toString().equals(settings.getCheckoutDoc()) && settings.getCheckoutDoc() != null) thisOdt = tempFiles[j]; } if (thisOdt != null) anyOdt = thisOdt; String url; if (settings.getCheckoutDoc() == null || !settings.getCheckoutDoc().equals(anyOdt.getName())) { File newOdt = new File(settings.getCheckoutPath() + "/" + anyOdt.getName()); if (newOdt.exists()) newOdt.delete(); anyOdt.renameTo(newOdt); File svnInfo = new File(settings.getCheckoutPath() + svnWorker.tempDir + "/.svn"); File newSvnInfo = new File(settings.getCheckoutPath() + "/.svn"); if (newSvnInfo.exists()) { if (deleteFileDir(newSvnInfo) == false) { error("Error while deleting temporary checkout dir."); } } url = "file:///" + newOdt.getPath().replace("\\", "/"); svnInfo.renameTo(newSvnInfo); anyOdt = newOdt; loadDocumentFromUrl(url); settings.setCheckoutDoc(anyOdt.getName()); try { settings.serializeOut(); } catch (Exception ex) { error("Error occured when re-newing settings.", ex); } } else { try { settings.serializeOut(); } catch (Exception ex) { error("Error occured when re-newing settings.", ex); } url = "file:///" + anyOdt.getPath().replace("\\", "/"); XDispatchProvider xDispatchProvider = (XDispatchProvider) UnoRuntime.queryInterface(XDispatchProvider.class, m_xFrame); PropertyValue property[] = new PropertyValue[1]; property[0] = new PropertyValue(); property[0].Name = "URL"; property[0].Value = url; XMultiServiceFactory xMSF = createProvider(); Object objDispatchHelper = m_xServiceManager.createInstanceWithContext("com.sun.star.frame.DispatchHelper", m_xContext); XDispatchHelper xDispatchHelper = (XDispatchHelper) UnoRuntime.queryInterface(XDispatchHelper.class, objDispatchHelper); xDispatchHelper.executeDispatch(xDispatchProvider, ".uno:CompareDocuments", "", 0, property); } } catch (Exception ex) { error(ex); } return; } if (aURL.Path.compareTo("svnCommit") == 0) { try { try { settings = getSerializedSettings(docProperty); } catch (Exception ex) { error("Error getting settings", ex); return; } Collection logs = svnWorker.getLogs(settings); long headRevision = svnWorker.getHeadRevisionNumber(logs); long committedRevision = -1; new DialogCommitMessage(new javax.swing.JFrame(), true, settings).setVisible(true); if (settings.getCancelFired()) return; try { settings.serializeOut(); } catch (Exception ex) { error("Error occured when re-newing settings.", ex); } if (headRevision == 0) { File impDir = new File(settings.getCheckoutPath() + svnWorker.tempDir + "/.import"); if (impDir.exists()) if (deleteFileDir(impDir) == false) { error("Error while creating temporary import directory."); return; } if (!impDir.mkdirs()) { error("Error while creating temporary import directory."); return; } File impFile = new File(settings.getCheckoutPath() + svnWorker.tempDir + "/.import/" + settings.getCheckoutDoc()); try { FileChannel srcChannel = new FileInputStream(settings.getCheckoutPath() + "/" + settings.getCheckoutDoc()).getChannel(); FileChannel dstChannel = new FileOutputStream(impFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (Exception ex) { error("Error while importing file", ex); return; } final String checkoutPath = settings.getCheckoutPath(); try { settings.setCheckoutPath(impDir.toString()); committedRevision = svnWorker.importDirectory(settings, false).getNewRevision(); } catch (Exception ex) { settings.setCheckoutPath(checkoutPath); error("Error while importing file", ex); return; } settings.setCheckoutPath(checkoutPath); if (impDir.exists()) if (deleteFileDir(impDir) == false) error("Error while creating temporary import directory."); try { File newSvnInfo = new File(settings.getCheckoutPath() + "/.svn"); if (newSvnInfo.exists()) { if (deleteFileDir(newSvnInfo) == false) { error("Error while deleting temporary checkout dir."); } } File tempDir = new File(settings.getCheckoutPath() + svnWorker.tempDir); if (tempDir.exists()) { if (deleteFileDir(tempDir) == false) { error("Error while deleting temporary checkout dir."); } } svnWorker.checkout(settings); File svnInfo = new File(settings.getCheckoutPath() + svnWorker.tempDir + "/.svn"); svnInfo.renameTo(newSvnInfo); if (deleteFileDir(tempDir) == false) { error("Error while managing working copy"); } try { settings.serializeOut(); } catch (Exception ex) { error("Error occured when re-newing settings.", ex); } } catch (Exception ex) { error("Error while checking out a working copy for the location", ex); } showMessageBox("Import succesful", "Succesfully imported as revision no. " + committedRevision); return; } else { try { committedRevision = svnWorker.commit(settings, false).getNewRevision(); } catch (Exception ex) { error("Error while committing changes. If the file is not working copy, you must use 'Checkout / Update' first.", ex); } if (committedRevision == -1) { showMessageBox("Update - no changes", "No changes was made. Maybe you must just save the changes."); } else { showMessageBox("Commit succesfull", "Commited as revision no. " + committedRevision); } } } catch (Exception ex) { error(ex); } return; } if (aURL.Path.compareTo("svnHistory") == 0) { try { try { settings = getSerializedSettings(docProperty); } catch (Exception ex) { error("Error getting settings", ex); return; } Object[][] logs = getLogs(settings); long checkVersion = settings.getCheckoutVersion(); settings.setCheckoutVersion(-99); new DialogSVNHistory(new javax.swing.JFrame(), true, settings, logs).setVisible(true); settings.setCheckoutVersion(checkVersion); } catch (Exception ex) { error(ex); } return; } if (aURL.Path.compareTo("settings") == 0) { try { settings = getSerializedSettings(docProperty); } catch (NoSerializedSettingsException ex) { try { settings.setCheckout(docProperty.getDocURL()); } catch (Exception exx) { } } catch (Exception ex) { error("Error getting settings; maybe you" + " need to save your document." + " If this is your first" + " checkout of the document, use Checkout" + " function directly."); return; } new DialogSettings(new javax.swing.JFrame(), true, settings).setVisible(true); try { settings.serializeOut(); } catch (Exception ex) { error("Error occured when saving settings.", ex); } return; } if (aURL.Path.compareTo("about") == 0) { showMessageBox("OoSvn :: About", "Autor: �t�p�n Cenek (stepan@geek.cz)"); return; } } }
11
Code Sample 1: public static void main(String[] args) { JFileChooser askDir = new JFileChooser(); askDir.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); askDir.setMultiSelectionEnabled(false); int returnVal = askDir.showOpenDialog(null); if (returnVal == JFileChooser.CANCEL_OPTION) { System.exit(returnVal); } File startDir = askDir.getSelectedFile(); ArrayList<File> files = new ArrayList<File>(); goThrough(startDir, files); SearchClient client = new SearchClient("VZFo5W5i"); MyID3 singleton = new MyID3(); for (File song : files) { try { MusicMetadataSet set = singleton.read(song); IMusicMetadata meta = set.getSimplified(); String qu = song.getName(); if (meta.getAlbum() != null) { qu = meta.getAlbum(); } else if (meta.getArtist() != null) { qu = meta.getArtist(); } if (qu.length() > 2) { ImageSearchRequest req = new ImageSearchRequest(qu); ImageSearchResults res = client.imageSearch(req); if (res.getTotalResultsAvailable().doubleValue() > 1) { System.out.println("Downloading " + res.listResults()[0].getUrl()); URL url = new URL(res.listResults()[0].getUrl()); URLConnection con = url.openConnection(); con.setConnectTimeout(10000); int realSize = con.getContentLength(); if (realSize > 0) { String mime = con.getContentType(); InputStream stream = con.getInputStream(); byte[] realData = new byte[realSize]; for (int i = 0; i < realSize; i++) { stream.read(realData, i, 1); } stream.close(); ImageData imgData = new ImageData(realData, mime, qu, 0); meta.addPicture(imgData); File temp = File.createTempFile("tempsong", "mp3"); singleton.write(song, temp, set, meta); FileChannel inChannel = new FileInputStream(temp).getChannel(); FileChannel outChannel = new FileOutputStream(song).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } temp.delete(); } } } } catch (ID3ReadException e) { } catch (MalformedURLException e) { } catch (UnsupportedEncodingException e) { } catch (ID3WriteException e) { } catch (IOException e) { } catch (SearchException e) { } } } Code Sample 2: public static final long copyFile(final File srcFile, final File dstFile, final long cpySize) throws IOException { if ((null == srcFile) || (null == dstFile)) return (-1L); final File dstFolder = dstFile.getParentFile(); if ((!dstFolder.exists()) && (!dstFolder.mkdirs())) throw new IOException("Failed to created destination folder(s)"); FileChannel srcChannel = null, dstChannel = null; try { srcChannel = new FileInputStream(srcFile).getChannel(); dstChannel = new FileOutputStream(dstFile).getChannel(); final long srcLen = srcFile.length(), copyLen = dstChannel.transferFrom(srcChannel, 0, (cpySize < 0L) ? srcLen : cpySize); if ((cpySize < 0L) && (copyLen != srcLen)) return (-2L); return copyLen; } finally { FileUtil.closeAll(srcChannel, dstChannel); } }
11
Code Sample 1: private void sendMessages() { Configuration conf = Configuration.getInstance(); for (int i = 0; i < errors.size(); i++) { String msg = null; synchronized (this) { msg = errors.get(i); if (DEBUG) System.out.println(msg); errors.remove(i); } if (!conf.getCustomerFeedback()) continue; if (conf.getApproveCustomerFeedback()) { ConfirmCustomerFeedback dialog = new ConfirmCustomerFeedback(JOptionPane.getFrameForComponent(SqlTablet.getInstance()), msg); if (dialog.getResult() == ConfirmCustomerFeedback.Result.NO) continue; } try { URL url = new URL("http://www.sqltablet.com/beta/bug.php"); URLConnection urlc = url.openConnection(); urlc.setDoOutput(true); urlc.setDoOutput(true); urlc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); DataOutputStream out = new DataOutputStream(urlc.getOutputStream()); String lines[] = msg.split("\n"); for (int l = 0; l < lines.length; l++) { String line = (l > 0 ? "&line" : "line") + l + "="; line += URLEncoder.encode(lines[l], "UTF-8"); out.write(line.getBytes()); } out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(urlc.getInputStream())); String line; while ((line = in.readLine()) != null) { if (DEBUG) System.out.println("RemoteLogger : " + line + "\n"); } in.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } 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(); }
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 void writeOutput(String directory) throws IOException { File f = new File(directory); int i = 0; if (f.isDirectory()) { for (AppInventorScreen screen : screens.values()) { File screenFile = new File(getScreenFilePath(f.getAbsolutePath(), screen)); screenFile.getParentFile().mkdirs(); screenFile.createNewFile(); FileWriter out = new FileWriter(screenFile); String initial = files.get(i).toString(); Map<String, String> types = screen.getTypes(); String[] lines = initial.split("\n"); for (String key : types.keySet()) { if (!key.trim().equals(screen.getName().trim())) { String value = types.get(key); boolean varFound = false; boolean importFound = false; for (String line : lines) { if (line.matches("^\\s*(public|private)\\s+" + value + "\\s+" + key + "\\s*=.*;$")) varFound = true; if (line.matches("^\\s*(public|private)\\s+" + value + "\\s+" + key + "\\s*;$")) varFound = true; if (line.matches("^\\s*import\\s+.*" + value + "\\s*;$")) importFound = true; } if (!varFound) initial = initial.replaceFirst("(?s)(?<=\\{\n)", "\tprivate " + value + " " + key + ";\n"); if (!importFound) initial = initial.replaceFirst("(?=import)", "import com.google.devtools.simple.runtime.components.android." + value + ";\n"); } } out.write(initial); out.close(); i++; } File manifestFile = new File(getManifestFilePath(f.getAbsolutePath(), manifest)); manifestFile.getParentFile().mkdirs(); manifestFile.createNewFile(); FileWriter out = new FileWriter(manifestFile); out.write(manifest.toString()); out.close(); File projectFile = new File(getProjectFilePath(f.getAbsolutePath(), project)); projectFile.getParentFile().mkdirs(); projectFile.createNewFile(); out = new FileWriter(projectFile); out.write(project.toString()); out.close(); String[] copyResourceFilenames = { "proguard.cfg", "project.properties", "libSimpleAndroidRuntime.jar", "\\.classpath", "res/drawable/icon.png", "\\.settings/org.eclipse.jdt.core.prefs" }; for (String copyResourceFilename : copyResourceFilenames) { InputStream is = getClass().getResourceAsStream("/resources/" + copyResourceFilename.replace("\\.", "")); File outputFile = new File(f.getAbsoluteFile() + File.separator + copyResourceFilename.replace("\\.", ".")); outputFile.getParentFile().mkdirs(); OutputStream os = new FileOutputStream(outputFile); byte[] buf = new byte[1024]; int readBytes; if (is == null) System.out.println("/resources/" + copyResourceFilename.replace("\\.", "")); if (os == null) System.out.println(f.getAbsolutePath() + File.separator + copyResourceFilename.replace("\\.", ".")); while ((readBytes = is.read(buf)) > 0) { os.write(buf, 0, readBytes); } } for (String assetName : assets) { InputStream is = new FileInputStream(new File(assetsDir.getAbsolutePath() + File.separator + assetName)); File outputFile = new File(f.getAbsoluteFile() + File.separator + assetName); outputFile.getParentFile().mkdirs(); OutputStream os = new FileOutputStream(outputFile); byte[] buf = new byte[1024]; int readBytes; while ((readBytes = is.read(buf)) > 0) { os.write(buf, 0, readBytes); } } File assetsOutput = new File(getAssetsFilePath(f.getAbsolutePath())); new File(assetsDir.getAbsoluteFile() + File.separator + "assets").renameTo(assetsOutput); } }
11
Code Sample 1: public void testReadNormal() throws Exception { archiveFileManager.executeWith(new TemporaryFileExecutor() { public void execute(File temporaryFile) throws Exception { ZipArchive archive = new ZipArchive(temporaryFile.getPath()); InputStream input = archive.getInputFrom(ARCHIVE_FILE_1); if (input != null) { ByteArrayOutputStream output = new ByteArrayOutputStream(); IOUtils.copyAndClose(input, output); assertEquals(ARCHIVE_FILE_1 + " contents not correct", ARCHIVE_FILE_1_CONTENT, output.toString()); } else { fail("cannot open " + ARCHIVE_FILE_1); } } }); } Code Sample 2: public 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); } }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: private void copyFileNFS(String sSource, String sTarget) throws Exception { FileInputStream fis = new FileInputStream(sSource); FileOutputStream fos = new FileOutputStream(sTarget); BufferedInputStream bis = new BufferedInputStream(fis); BufferedOutputStream bos = new BufferedOutputStream(fos); byte[] buf = new byte[2048]; int i = 0; while ((i = bis.read(buf)) != -1) bos.write(buf, 0, i); bis.close(); bos.close(); fis.close(); fos.close(); }
00
Code Sample 1: public static void copy(File source, File destination) { try { FileInputStream fileInputStream = new FileInputStream(source); FileOutputStream fileOutputStream = new FileOutputStream(destination); FileChannel inputChannel = fileInputStream.getChannel(); FileChannel outputChannel = fileOutputStream.getChannel(); transfer(inputChannel, outputChannel, source.length(), 1024 * 1024 * 32, true, true); fileInputStream.close(); fileOutputStream.close(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public void testServletTesterClient() throws Exception { String base_url = tester.createSocketConnector(true); URL url = new URL(base_url + "/context/hello/info"); String result = IO.toString(url.openStream()); assertEquals("<h1>Hello Servlet</h1>", result); }
00
Code Sample 1: private static String func(String sf) { int total = 0, temp; String fnctn[] = { "sin", "cos", "tan", "log", "ln", "sqrt", "!" }, temp2 = ""; int pos[] = new int[7]; for (int n = 0; n < fnctn.length; n++) { pos[n] = sf.lastIndexOf(fnctn[n]); } for (int m = 0; m < fnctn.length; m++) { total += pos[m]; } if (total == -7) { return sf; } for (int i = pos.length; i > 1; i--) { for (int j = 0; j < i - 1; j++) { if (pos[j] < pos[j + 1]) { temp = pos[j]; pos[j] = pos[j + 1]; pos[j + 1] = temp; temp2 = fnctn[j]; fnctn[j] = fnctn[j + 1]; fnctn[j + 1] = temp2; } } } if (fnctn[0].equals("sin")) { if ((pos[0] == 0 || sf.charAt(pos[0] - 1) != 'a')) { return func(Functions.sine(sf, pos[0], false)); } else { return func(Functions.asin(sf, pos[0], false)); } } else if (fnctn[0].equals("cos")) { if ((pos[0] == 0 || sf.charAt(pos[0] - 1) != 'a')) { return func(Functions.cosine(sf, pos[0], false)); } else { return func(Functions.acos(sf, pos[0], false)); } } else if (fnctn[0].equals("tan")) { if ((pos[0] == 0 || sf.charAt(pos[0] - 1) != 'a')) { return func(Functions.tangent(sf, pos[0], false)); } else { return func(Functions.atan(sf, pos[0], false)); } } else if (fnctn[0].equals("log")) { return func(Functions.logarithm(sf, pos[0])); } else if (fnctn[0].equals("ln")) { return func(Functions.lnat(sf, pos[0])); } else if (fnctn[0].equals("sqrt")) { return func(Functions.sqroot(sf, pos[0])); } else { return func(Functions.factorial(sf, pos[0])); } } Code Sample 2: static Object loadPersistentRepresentationFromFile(URL url) throws PersistenceException { PersistenceManager.persistenceURL.get().addFirst(url); ObjectInputStream ois = null; HierarchicalStreamReader reader = null; XStream xstream = null; try { Reader inputReader = new java.io.InputStreamReader(url.openStream()); try { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLStreamReader xsr = inputFactory.createXMLStreamReader(url.toExternalForm(), inputReader); reader = new StaxReader(new QNameMap(), xsr); } catch (XMLStreamException xse) { throw new PersistenceException("Error creating reader", xse); } xstream = new XStream(new StaxDriver()); xstream.setClassLoader(Gate.getClassLoader()); ois = xstream.createObjectInputStream(reader); Object res = null; Iterator urlIter = ((Collection) PersistenceManager.getTransientRepresentation(ois.readObject())).iterator(); while (urlIter.hasNext()) { URL anUrl = (URL) urlIter.next(); try { Gate.getCreoleRegister().registerDirectories(anUrl); } catch (GateException ge) { Err.prln("Could not reload creole directory " + anUrl.toExternalForm()); } } res = ois.readObject(); ois.close(); return res; } catch (PersistenceException pe) { throw pe; } catch (Exception e) { throw new PersistenceException("Error loading GAPP file", e); } finally { PersistenceManager.persistenceURL.get().removeFirst(); if (PersistenceManager.persistenceURL.get().isEmpty()) { PersistenceManager.persistenceURL.remove(); } } }
11
Code Sample 1: public 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(); } Code Sample 2: protected int doWork() { SAMFileReader reader = new SAMFileReader(IoUtil.openFileForReading(INPUT)); reader.getFileHeader().setSortOrder(SORT_ORDER); SAMFileWriter writer = new SAMFileWriterFactory().makeSAMOrBAMWriter(reader.getFileHeader(), false, OUTPUT); Iterator<SAMRecord> iterator = reader.iterator(); while (iterator.hasNext()) writer.addAlignment(iterator.next()); reader.close(); writer.close(); return 0; }
11
Code Sample 1: private void copyFile(File dir, File fileToAdd) { try { byte[] readBuffer = new byte[1024]; File file = new File(dir.getCanonicalPath() + File.separatorChar + fileToAdd.getName()); if (file.createNewFile()) { FileInputStream fis = new FileInputStream(fileToAdd); FileOutputStream fos = new FileOutputStream(file); int bytesRead; do { bytesRead = fis.read(readBuffer); fos.write(readBuffer, 0, bytesRead); } while (bytesRead == 0); fos.flush(); fos.close(); fis.close(); } else { logger.severe("unable to create file:" + file.getAbsolutePath()); } } catch (IOException ioe) { logger.severe("unable to create file:" + ioe); } } Code Sample 2: public static void copyFile(File src, File dest) throws IOException, IllegalArgumentException { if (src.isDirectory()) throw new IllegalArgumentException("Source file is a directory"); if (dest.isDirectory()) throw new IllegalArgumentException("Destination file is a directory"); int bufferSize = 4 * 1024; InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dest); byte[] buffer = new byte[bufferSize]; int bytesRead; while ((bytesRead = in.read(buffer)) >= 0) out.write(buffer, 0, bytesRead); out.close(); in.close(); }
00
Code Sample 1: public void importarHistoricoDeProventos(File pArquivoXLS, boolean pFiltrarPelaDataDeCorteDoCabecalho, Andamento pAndamento) throws IOException, SQLException, InvalidFormatException { int iLinha = -1; String nomeDaColuna = ""; Statement stmtLimpezaInicialDestino = null; OraclePreparedStatement stmtDestino = null; try { Workbook arquivo = WorkbookFactory.create(new FileInputStream(pArquivoXLS)); Sheet plan1 = arquivo.getSheetAt(0); int QUANTIDADE_DE_REGISTROS_DE_METADADOS = 2; int quantidadeDeRegistrosEstimada = plan1.getPhysicalNumberOfRows() - QUANTIDADE_DE_REGISTROS_DE_METADADOS; String vNomeDePregao, vTipoDaAcao, vDataDaAprovacao, vTipoDoProvento, vDataDoUltimoPrecoCom; BigDecimal vValorDoProvento, vUltimoPrecoCom, vProventoPorPreco; int vProventoPor1Ou1000Acoes, vPrecoPor1Ou1000Acoes; java.sql.Date vUltimoDiaCom; DateFormat formatadorData = new SimpleDateFormat("yyyyMMdd"); DateFormat formatadorPadraoData = DateFormat.getDateInstance(); Row registro; Cell celula; java.util.Date dataLimite = plan1.getRow(0).getCell(CampoDaPlanilhaDosProventosEmDinheiro.NOME_DE_PREGAO.ordinal()).getDateCellValue(); Cell celulaUltimoDiaCom; java.util.Date tmpUltimoDiaCom; stmtLimpezaInicialDestino = conDestino.createStatement(); String sql = "TRUNCATE TABLE TMP_TB_PROVENTO_EM_DINHEIRO"; stmtLimpezaInicialDestino.executeUpdate(sql); sql = "INSERT INTO TMP_TB_PROVENTO_EM_DINHEIRO(NOME_DE_PREGAO, TIPO_DA_ACAO, DATA_DA_APROVACAO, VALOR_DO_PROVENTO, PROVENTO_POR_1_OU_1000_ACOES, TIPO_DO_PROVENTO, ULTIMO_DIA_COM, DATA_DO_ULTIMO_PRECO_COM, ULTIMO_PRECO_COM, PRECO_POR_1_OU_1000_ACOES, PERC_PROVENTO_POR_PRECO) VALUES(:NOME_DE_PREGAO, :TIPO_DA_ACAO, :DATA_DA_APROVACAO, :VALOR_DO_PROVENTO, :PROVENTO_POR_1_OU_1000_ACOES, :TIPO_DO_PROVENTO, :ULTIMO_DIA_COM, :DATA_DO_ULTIMO_PRECO_COM, :ULTIMO_PRECO_COM, :PRECO_POR_1_OU_1000_ACOES, :PERC_PROVENTO_POR_PRECO)"; stmtDestino = (OraclePreparedStatement) conDestino.prepareStatement(sql); stmtDestino.setExecuteBatch(COMANDOS_POR_LOTE); int quantidadeDeRegistrosImportados = 0; final int NUMERO_DA_LINHA_INICIAL = 1; for (iLinha = NUMERO_DA_LINHA_INICIAL; true; iLinha++) { registro = plan1.getRow(iLinha); if (registro != null) { nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.ULTIMO_DIA_COM.toString(); celulaUltimoDiaCom = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.ULTIMO_DIA_COM.ordinal()); if (celulaUltimoDiaCom != null) { if (celulaUltimoDiaCom.getCellType() == Cell.CELL_TYPE_NUMERIC) { tmpUltimoDiaCom = celulaUltimoDiaCom.getDateCellValue(); if (tmpUltimoDiaCom.compareTo(dataLimite) <= 0 || !pFiltrarPelaDataDeCorteDoCabecalho) { vUltimoDiaCom = new java.sql.Date(celulaUltimoDiaCom.getDateCellValue().getTime()); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.NOME_DE_PREGAO.toString(); vNomeDePregao = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.NOME_DE_PREGAO.ordinal()).getStringCellValue().trim(); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.TIPO_DA_ACAO.toString(); vTipoDaAcao = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.TIPO_DA_ACAO.ordinal()).getStringCellValue().trim(); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.DATA_DA_APROVACAO.toString(); celula = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.DATA_DA_APROVACAO.ordinal()); try { java.util.Date tmpDataDaAprovacao; if (celula.getCellType() == Cell.CELL_TYPE_NUMERIC) { tmpDataDaAprovacao = celula.getDateCellValue(); } else { tmpDataDaAprovacao = formatadorPadraoData.parse(celula.getStringCellValue()); } vDataDaAprovacao = formatadorData.format(tmpDataDaAprovacao); } catch (ParseException ex) { vDataDaAprovacao = celula.getStringCellValue(); } nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.VALOR_DO_PROVENTO.toString(); vValorDoProvento = new BigDecimal(String.valueOf(registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.VALOR_DO_PROVENTO.ordinal()).getNumericCellValue())); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.PROVENTO_POR_1_OU_1000_ACOES.toString(); vProventoPor1Ou1000Acoes = (int) registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.PROVENTO_POR_1_OU_1000_ACOES.ordinal()).getNumericCellValue(); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.TIPO_DO_PROVENTO.toString(); vTipoDoProvento = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.TIPO_DO_PROVENTO.ordinal()).getStringCellValue().trim(); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.DATA_DO_ULTIMO_PRECO_COM.toString(); celula = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.DATA_DO_ULTIMO_PRECO_COM.ordinal()); if (celula != null) { try { java.util.Date tmpDataDoUltimoPrecoCom; if (celula.getCellType() == Cell.CELL_TYPE_NUMERIC) { tmpDataDoUltimoPrecoCom = celula.getDateCellValue(); } else { tmpDataDoUltimoPrecoCom = formatadorPadraoData.parse(celula.getStringCellValue()); } vDataDoUltimoPrecoCom = formatadorData.format(tmpDataDoUltimoPrecoCom); } catch (ParseException ex) { vDataDoUltimoPrecoCom = celula.getStringCellValue().trim(); } } else { vDataDoUltimoPrecoCom = ""; } nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.ULTIMO_PRECO_COM.toString(); vUltimoPrecoCom = new BigDecimal(String.valueOf(registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.ULTIMO_PRECO_COM.ordinal()).getNumericCellValue())); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.PRECO_POR_1_OU_1000_ACOES.toString(); vPrecoPor1Ou1000Acoes = (int) registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.PRECO_POR_1_OU_1000_ACOES.ordinal()).getNumericCellValue(); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.PROVENTO_POR_PRECO.toString(); celula = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.PROVENTO_POR_PRECO.ordinal()); if (celula != null && celula.getCellType() == Cell.CELL_TYPE_NUMERIC) { vProventoPorPreco = new BigDecimal(String.valueOf(celula.getNumericCellValue())); } else { vProventoPorPreco = null; } stmtDestino.clearParameters(); stmtDestino.setStringAtName("NOME_DE_PREGAO", vNomeDePregao); stmtDestino.setStringAtName("TIPO_DA_ACAO", vTipoDaAcao); stmtDestino.setStringAtName("DATA_DA_APROVACAO", vDataDaAprovacao); stmtDestino.setBigDecimalAtName("VALOR_DO_PROVENTO", vValorDoProvento); stmtDestino.setIntAtName("PROVENTO_POR_1_OU_1000_ACOES", vProventoPor1Ou1000Acoes); stmtDestino.setStringAtName("TIPO_DO_PROVENTO", vTipoDoProvento); stmtDestino.setDateAtName("ULTIMO_DIA_COM", vUltimoDiaCom); stmtDestino.setStringAtName("DATA_DO_ULTIMO_PRECO_COM", vDataDoUltimoPrecoCom); stmtDestino.setBigDecimalAtName("ULTIMO_PRECO_COM", vUltimoPrecoCom); stmtDestino.setIntAtName("PRECO_POR_1_OU_1000_ACOES", vPrecoPor1Ou1000Acoes); stmtDestino.setBigDecimalAtName("PERC_PROVENTO_POR_PRECO", vProventoPorPreco); int contagemDasInsercoes = stmtDestino.executeUpdate(); quantidadeDeRegistrosImportados++; } } } else { break; } double percentualCompleto = (double) quantidadeDeRegistrosImportados / quantidadeDeRegistrosEstimada * 100; pAndamento.setPercentualCompleto((int) percentualCompleto); } else { break; } } conDestino.commit(); } catch (Exception ex) { conDestino.rollback(); ProblemaNaImportacaoDeArquivo problemaDetalhado = new ProblemaNaImportacaoDeArquivo(); problemaDetalhado.nomeDoArquivo = pArquivoXLS.getName(); problemaDetalhado.linhaProblematicaDoArquivo = iLinha + 1; problemaDetalhado.colunaProblematicaDoArquivo = nomeDaColuna; problemaDetalhado.detalhesSobreOProblema = ex; throw problemaDetalhado; } finally { pAndamento.setPercentualCompleto(100); if (stmtLimpezaInicialDestino != null && (!stmtLimpezaInicialDestino.isClosed())) { stmtLimpezaInicialDestino.close(); } if (stmtDestino != null && (!stmtDestino.isClosed())) { stmtDestino.close(); } } } Code Sample 2: public void writeFile(OutputStream outputStream) throws IOException { InputStream inputStream = null; if (file != null) { try { inputStream = new FileInputStream(file); IOUtils.copy(inputStream, outputStream); } finally { if (inputStream != null) { IOUtils.closeQuietly(inputStream); } } } }
11
Code Sample 1: private static void copyFile(File source, File destination) throws IOException, SecurityException { if (!destination.exists()) destination.createNewFile(); FileChannel sourceChannel = null; FileChannel destinationChannel = null; try { sourceChannel = new FileInputStream(source).getChannel(); destinationChannel = new FileOutputStream(destination).getChannel(); long count = 0; long size = sourceChannel.size(); while ((count += destinationChannel.transferFrom(sourceChannel, 0, size - count)) < size) ; } finally { if (sourceChannel != null) sourceChannel.close(); if (destinationChannel != null) destinationChannel.close(); } } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: private void bubbleSort() { for (int i = 0; i < testfield.length; i++) { for (int j = 0; j < testfield.length - i - 1; j++) if (testfield[j] > testfield[j + 1]) { short temp = testfield[j]; testfield[j] = testfield[j + 1]; testfield[j + 1] = temp; } } } Code Sample 2: public static void init(Locale language) throws IOException { URL url = ClassLoader.getSystemResource("locales/" + language.getISO3Language() + ".properties"); if (url == null) { throw new IOException("Could not load resource locales/" + language.getISO3Language() + ".properties"); } PROPS.clear(); PROPS.load(url.openStream()); }
00
Code Sample 1: public ProgramSymbol deleteProgramSymbol(int id) throws AdaptationException { ProgramSymbol programSymbol = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "SELECT * FROM ProgramSymbols " + "WHERE id = " + id; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to delete program symbol failed."; log.error(msg); throw new AdaptationException(msg); } programSymbol = getProgramSymbol(resultSet); query = "DELETE FROM ProgramSymbols " + "WHERE id = " + id; statement.executeUpdate(query); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in deleteProgramSymbol"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return programSymbol; } Code Sample 2: public static void copyFile(File source, File destination) throws IOException { if (source == null) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } if (destination == null) { String message = Logging.getMessage("nullValue.DestinationIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } FileInputStream fis = null; FileOutputStream fos = null; FileChannel fic, foc; try { fis = new FileInputStream(source); fic = fis.getChannel(); fos = new FileOutputStream(destination); foc = fos.getChannel(); foc.transferFrom(fic, 0, fic.size()); fos.flush(); fis.close(); fos.close(); } finally { WWIO.closeStream(fis, source.getPath()); WWIO.closeStream(fos, destination.getPath()); } }
00
Code Sample 1: public void testReceiveMessageWithHttpPost() throws ClientProtocolException, IOException { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://192.167.131.126/hotel/sms/create.htm"); String receipt = "2#12345:source:079456345:200:xxx:1234567809:userfred:"; String message = "11796 book owner2 password 238 12.09.2008 3 testname surname"; HttpParams params = new BasicHttpParams(); params.setParameter("TextMessage", message); httpPost.setParams(params); HttpResponse response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); } Code Sample 2: public void addPropertyColumns(WCAChannel destination, Set<Property> properties) throws SQLException { Session session = HibernateUtil.getSessionFactory().openSession(); Connection con = session.connection(); try { createPropertyTable(destination); extendPropertyList(destination, properties); Statement statement = con.createStatement(); for (Property property : properties) { String propertyName = removeBadChars(property.getName()); statement.executeUpdate(alterTable.format(new Object[] { getTableName(destination), propertyName, property.getDBColumnType() })); } con.commit(); con.close(); session.close(); } catch (SQLException e) { con.rollback(); session.close(); throw e; } }
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 Parameters getParameters(HttpExchange http) throws IOException { ParametersImpl params = new ParametersImpl(); String query = null; if (http.getRequestMethod().equalsIgnoreCase("GET")) { query = http.getRequestURI().getRawQuery(); } else if (http.getRequestMethod().equalsIgnoreCase("POST")) { InputStream in = new MaxInputStream(http.getRequestBody()); if (in != null) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); IOUtils.copyTo(in, bytes); query = new String(bytes.toByteArray()); in.close(); } } else { throw new IOException("Method not supported " + http.getRequestMethod()); } if (query != null) { for (String s : query.split("[&]")) { s = s.replace('+', ' '); int eq = s.indexOf('='); if (eq > 0) { params.add(URLDecoder.decode(s.substring(0, eq), "UTF-8"), URLDecoder.decode(s.substring(eq + 1), "UTF-8")); } } } return params; }
00
Code Sample 1: @Override public List<Type> getArtifactTypes(String organisationName, String artifactName, String version) { if (cache != null) { Date d; try { d = cache.getTypesLastUpdate(organisationName, artifactName, version); if (d.compareTo(cacheExpirationDate) >= 0) { return cache.getTypes(organisationName, artifactName, version); } } catch (CacheAccessException e) { log.warn("cannot access cache", e); } } List<Type> types = new ArrayList<Type>(); String urlString = generateUrlString(organisationName, artifactName, version, Type.JAR); try { new URL(urlString).openStream(); types.add(Type.JAR); } catch (MalformedURLException e) { } catch (IOException e) { } urlString = generateUrlString(organisationName, artifactName, version, Type.SRC); try { new URL(urlString).openStream(); types.add(Type.SRC); } catch (MalformedURLException e) { } catch (IOException e) { } urlString = generateUrlString(organisationName, artifactName, version, Type.WAR); try { new URL(urlString).openStream(); types.add(Type.WAR); } catch (MalformedURLException e) { } catch (IOException e) { } urlString = generateUrlString(organisationName, artifactName, version, Type.ZIP); try { new URL(urlString).openStream(); types.add(Type.ZIP); } catch (MalformedURLException e) { } catch (IOException e) { } if (cache != null) { try { cache.updateTypes(organisationName, artifactName, version, types); } catch (CacheAccessException e) { log.warn("cannot access cache", e); } } return types; } Code Sample 2: public void getLyricsFromMAWebSite(TrackMABean tb) throws Exception { URL fileURL = new URL("http://www.metal-archives.com/viewlyrics.php?id=" + tb.getMaid()); URLConnection urlConnection = fileURL.openConnection(); InputStream httpStream = urlConnection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(httpStream, "ISO-8859-1")); String ligne; boolean chargerLyrics = false; StringBuffer sb = new StringBuffer(""); String lyrics = null; while ((ligne = br.readLine()) != null) { log.debug("==> " + ligne); if (chargerLyrics && ligne.indexOf("<center>") != -1) { break; } if (chargerLyrics) { sb.append(ligne.trim()); } if (!chargerLyrics && ligne.indexOf("<center>") != -1) { chargerLyrics = true; } } lyrics = sb.toString(); lyrics = lyrics.replaceAll("<br>", "\n").trim(); log.debug("Parole : " + lyrics); tb.setLyrics(lyrics); br.close(); httpStream.close(); }
11
Code Sample 1: private synchronized void persist() { Connection conn = null; try { PoolManager pm = PoolManager.getInstance(); conn = pm.getConnection(JukeXTrackStore.DB_NAME); conn.setAutoCommit(false); Statement state = conn.createStatement(); state.executeUpdate("DELETE FROM PlaylistEntry WHERE playlistid=" + this.id); if (this.size() > 0) { StringBuffer sql = new StringBuffer(); sql.append("INSERT INTO PlaylistEntry ( playlistid , trackid , position ) VALUES "); int location = 0; Iterator i = ll.iterator(); while (i.hasNext()) { long currTrackID = ((DatabaseObject) i.next()).getId(); sql.append('(').append(this.id).append(',').append(currTrackID).append(',').append(location++).append(')'); if (i.hasNext()) sql.append(','); } state.executeUpdate(sql.toString()); } conn.commit(); conn.setAutoCommit(true); state.close(); } catch (SQLException se) { try { conn.rollback(); } catch (SQLException ignore) { } log.error("Encountered an error persisting a playlist", se); } finally { try { conn.close(); } catch (SQLException ignore) { } } } Code Sample 2: public int visitStatement(String statement) throws SQLException { mySQLLogger.info(statement); if (getConnection() == null) { throw new JdbcException("cannot exec: " + statement + ", because 'not connected to database'"); } Statement stmt = getConnection().createStatement(); try { return stmt.executeUpdate(statement); } catch (SQLException ex) { getConnection().rollback(); throw ex; } finally { stmt.close(); } }
00
Code Sample 1: public void save() throws IOException { CodeTimer saveTimer; if (!dirty) { return; } saveTimer = new CodeTimer("PackedFile.save"); saveTimer.setEnabled(log.isDebugEnabled()); File newFile = new File(tmpDir.getAbsolutePath() + "/" + new GUID() + ".pak"); ZipOutputStream zout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(newFile))); zout.setLevel(1); try { saveTimer.start("contentFile"); if (hasFile(CONTENT_FILE)) { zout.putNextEntry(new ZipEntry(CONTENT_FILE)); InputStream is = getFileAsInputStream(CONTENT_FILE); IOUtils.copy(is, zout); zout.closeEntry(); } saveTimer.stop("contentFile"); saveTimer.start("propertyFile"); if (getPropertyMap().isEmpty()) { removeFile(PROPERTY_FILE); } else { zout.putNextEntry(new ZipEntry(PROPERTY_FILE)); xstream.toXML(getPropertyMap(), zout); zout.closeEntry(); } saveTimer.stop("propertyFile"); saveTimer.start("addFiles"); addedFileSet.remove(CONTENT_FILE); for (String path : addedFileSet) { zout.putNextEntry(new ZipEntry(path)); InputStream is = getFileAsInputStream(path); IOUtils.copy(is, zout); zout.closeEntry(); } saveTimer.stop("addFiles"); saveTimer.start("copyFiles"); if (file.exists()) { Enumeration<? extends ZipEntry> entries = zFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (!entry.isDirectory() && !addedFileSet.contains(entry.getName()) && !removedFileSet.contains(entry.getName()) && !CONTENT_FILE.equals(entry.getName()) && !PROPERTY_FILE.equals(entry.getName())) { zout.putNextEntry(entry); InputStream is = getFileAsInputStream(entry.getName()); IOUtils.copy(is, zout); zout.closeEntry(); } else if (entry.isDirectory()) { zout.putNextEntry(entry); zout.closeEntry(); } } } try { if (zFile != null) zFile.close(); } catch (IOException e) { } zFile = null; saveTimer.stop("copyFiles"); saveTimer.start("close"); zout.close(); zout = null; saveTimer.stop("close"); saveTimer.start("backup"); File backupFile = new File(tmpDir.getAbsolutePath() + "/" + new GUID() + ".mv"); if (file.exists()) { backupFile.delete(); if (!file.renameTo(backupFile)) { FileUtil.copyFile(file, backupFile); file.delete(); } } saveTimer.stop("backup"); saveTimer.start("finalize"); if (!newFile.renameTo(file)) FileUtil.copyFile(newFile, file); if (backupFile.exists()) backupFile.delete(); saveTimer.stop("finalize"); dirty = false; } finally { saveTimer.start("cleanup"); try { if (zFile != null) zFile.close(); } catch (IOException e) { } if (newFile.exists()) newFile.delete(); try { if (zout != null) zout.close(); } catch (IOException e) { } saveTimer.stop("cleanup"); if (log.isDebugEnabled()) log.debug(saveTimer); saveTimer = null; } } Code Sample 2: protected void syncMessages(Message message) { if (message.getEvent() == Event.CONNECT || message.getEvent() == Event.SYNC_DONE) return; logger.info(String.format("remove stale replication messages: %s", message.toString())); String className = ""; long classId = 0; if (message.getBody() instanceof Entity) { Entity entity = (Entity) message.getBody(); className = entity.getClass().getName(); classId = entity.getId(); } ConnectionProvider cp = null; Connection conn = null; PreparedStatement ps = null; try { SessionFactoryImplementor impl = (SessionFactoryImplementor) portalDao.getSessionFactory(); cp = impl.getConnectionProvider(); conn = cp.getConnection(); conn.setAutoCommit(false); ps = conn.prepareStatement("delete from light_replication_message where event=? and className=? and classId=?"); ps.setString(1, message.getEvent().toString()); ps.setString(2, className); ps.setLong(3, classId); ps.executeUpdate(); conn.commit(); ps.close(); conn.close(); } catch (Exception e) { try { conn.rollback(); ps.close(); conn.close(); } catch (Exception se) { } } }
00
Code Sample 1: private String readJsonString() { StringBuilder builder = new StringBuilder(); HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(SERVER_URL); try { HttpResponse response = client.execute(httpGet); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } } else { Log.e(TAG, "Failed to download file"); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return builder.toString(); } Code Sample 2: public void readData(RowSetInternal caller) throws SQLException { Connection con = null; try { CachedRowSet crs = (CachedRowSet) caller; if (crs.getPageSize() == 0 && crs.size() > 0) { crs.close(); } writerCalls = 0; userCon = false; con = this.connect(caller); if (con == null || crs.getCommand() == null) throw new SQLException(resBundle.handleGetObject("crsreader.connecterr").toString()); try { con.setTransactionIsolation(crs.getTransactionIsolation()); } catch (Exception ex) { ; } PreparedStatement pstmt = con.prepareStatement(crs.getCommand()); decodeParams(caller.getParams(), pstmt); try { pstmt.setMaxRows(crs.getMaxRows()); pstmt.setMaxFieldSize(crs.getMaxFieldSize()); pstmt.setEscapeProcessing(crs.getEscapeProcessing()); pstmt.setQueryTimeout(crs.getQueryTimeout()); } catch (Exception ex) { throw new SQLException(ex.getMessage()); } if (crs.getCommand().toLowerCase().indexOf("select") != -1) { ResultSet rs = pstmt.executeQuery(); if (crs.getPageSize() == 0) { crs.populate(rs); } else { pstmt = con.prepareStatement(crs.getCommand(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); decodeParams(caller.getParams(), pstmt); try { pstmt.setMaxRows(crs.getMaxRows()); pstmt.setMaxFieldSize(crs.getMaxFieldSize()); pstmt.setEscapeProcessing(crs.getEscapeProcessing()); pstmt.setQueryTimeout(crs.getQueryTimeout()); } catch (Exception ex) { throw new SQLException(ex.getMessage()); } rs = pstmt.executeQuery(); crs.populate(rs, startPosition); } rs.close(); } else { pstmt.executeUpdate(); } pstmt.close(); try { con.commit(); } catch (SQLException ex) { ; } if (getCloseConnection() == true) con.close(); } catch (SQLException ex) { throw ex; } finally { try { if (con != null && getCloseConnection() == true) { try { if (!con.getAutoCommit()) { con.rollback(); } } catch (Exception dummy) { } con.close(); con = null; } } catch (SQLException e) { } } }
00
Code Sample 1: @Deprecated public void test() { try { String query = "* <http://xmlns.com/foaf/0.1/workplaceHomepage> <http://www.deri.ie/>" + "* <http://xmlns.com/foaf/0.1/knows> *"; String url = "http://sindice.com/api/v2/search?qt=advanced&q=" + URLEncoder.encode(query, "utf-8") + "&qt=advanced"; URL urlObj = new URL(url); URLConnection con = urlObj.openConnection(); if (con != null) { Model model = ModelFactory.createDefaultModel(); model.read(con.getInputStream(), null); } System.out.println(url); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public static SubstanceSkin.ColorSchemes getColorSchemes(URL url) { List<SubstanceColorScheme> schemes = new ArrayList<SubstanceColorScheme>(); BufferedReader reader = null; Color ultraLight = null; Color extraLight = null; Color light = null; Color mid = null; Color dark = null; Color ultraDark = null; Color foreground = null; String name = null; ColorSchemeKind kind = null; boolean inColorSchemeBlock = false; try { reader = new BufferedReader(new InputStreamReader(url.openStream())); while (true) { String line = reader.readLine(); if (line == null) break; line = line.trim(); if (line.length() == 0) continue; if (line.startsWith("#")) { continue; } if (line.indexOf("{") >= 0) { if (inColorSchemeBlock) { throw new IllegalArgumentException("Already in color scheme definition"); } inColorSchemeBlock = true; name = line.substring(0, line.indexOf("{")).trim(); continue; } if (line.indexOf("}") >= 0) { if (!inColorSchemeBlock) { throw new IllegalArgumentException("Not in color scheme definition"); } inColorSchemeBlock = false; if ((name == null) || (kind == null) || (ultraLight == null) || (extraLight == null) || (light == null) || (mid == null) || (dark == null) || (ultraDark == null) || (foreground == null)) { throw new IllegalArgumentException("Incomplete specification"); } Color[] colors = new Color[] { ultraLight, extraLight, light, mid, dark, ultraDark, foreground }; if (kind == ColorSchemeKind.LIGHT) { schemes.add(getLightColorScheme(name, colors)); } else { schemes.add(getDarkColorScheme(name, colors)); } name = null; kind = null; ultraLight = null; extraLight = null; light = null; mid = null; dark = null; ultraDark = null; foreground = null; continue; } String[] split = line.split("="); if (split.length != 2) { throw new IllegalArgumentException("Unsupported format in line " + line); } String key = split[0].trim(); String value = split[1].trim(); if ("kind".equals(key)) { if (kind == null) { if ("Light".equals(value)) { kind = ColorSchemeKind.LIGHT; continue; } if ("Dark".equals(value)) { kind = ColorSchemeKind.DARK; continue; } throw new IllegalArgumentException("Unsupported format in line " + line); } throw new IllegalArgumentException("'kind' should only be defined once"); } if ("colorUltraLight".equals(key)) { if (ultraLight == null) { ultraLight = Color.decode(value); continue; } throw new IllegalArgumentException("'ultraLight' should only be defined once"); } if ("colorExtraLight".equals(key)) { if (extraLight == null) { extraLight = Color.decode(value); continue; } throw new IllegalArgumentException("'extraLight' should only be defined once"); } if ("colorLight".equals(key)) { if (light == null) { light = Color.decode(value); continue; } throw new IllegalArgumentException("'light' should only be defined once"); } if ("colorMid".equals(key)) { if (mid == null) { mid = Color.decode(value); continue; } throw new IllegalArgumentException("'mid' should only be defined once"); } if ("colorDark".equals(key)) { if (dark == null) { dark = Color.decode(value); continue; } throw new IllegalArgumentException("'dark' should only be defined once"); } if ("colorUltraDark".equals(key)) { if (ultraDark == null) { ultraDark = Color.decode(value); continue; } throw new IllegalArgumentException("'ultraDark' should only be defined once"); } if ("colorForeground".equals(key)) { if (foreground == null) { foreground = Color.decode(value); continue; } throw new IllegalArgumentException("'foreground' should only be defined once"); } throw new IllegalArgumentException("Unsupported format in line " + line); } ; } catch (IOException ioe) { throw new IllegalArgumentException(ioe); } finally { if (reader != null) { try { reader.close(); } catch (IOException ioe) { } } } return new SubstanceSkin.ColorSchemes(schemes); }
00
Code Sample 1: public void reademi(Vector<String> descriptions, Vector<String> links, String linkaddress, String idmap) { InputStream is = null; URL url; ArrayList<String> keys = new ArrayList<String>(); ArrayList<String> names = new ArrayList<String>(); try { url = new URL(idmap); is = url.openStream(); Scanner scanner = new Scanner(is); scanner.nextLine(); String line = ""; String id = ""; while (scanner.hasNextLine()) { line = scanner.nextLine(); Scanner linescanner = new Scanner(line); linescanner.useDelimiter("\t"); id = linescanner.next(); id = id.substring(0, id.length() - 2); keys.add(id); linescanner.next(); linescanner.next(); linescanner.next(); linescanner.useDelimiter("\n"); names.add(linescanner.next()); } BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(linkaddress).openStream())); String link = ""; String key = ""; String name = ""; int counter = 0; while ((line = reader.readLine()) != null) { if (line.indexOf("style=raw") != -1) { int linkstart = line.indexOf("http://www.ebi.ac.uk/cgi-bin/dbfetch?db"); int idstart = line.indexOf("id=") + 3; int linkend = line.substring(linkstart).indexOf("\"") + linkstart; link = line.substring(linkstart, linkend); key = line.substring(idstart, linkend); if (keys.indexOf(key) != -1) { name = names.get(keys.indexOf(key)); counter++; descriptions.add(counter + " " + key + " " + name); links.add(link); } } } } catch (MalformedURLException e) { } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public String parseInOneLine() throws Exception { BufferedReader br = null; InputStream httpStream = null; if (url.startsWith("http")) { URL fileURL = new URL(url); URLConnection urlConnection = fileURL.openConnection(); httpStream = urlConnection.getInputStream(); br = new BufferedReader(new InputStreamReader(httpStream, "ISO-8859-1")); } else { br = new BufferedReader(new FileReader(url)); } StringBuffer sb = new StringBuffer(); StringBuffer sbAllDoc = new StringBuffer(); String ligne = null; boolean get = false; while ((ligne = br.readLine()) != null) { log.debug(ligne); sbAllDoc.append(ligne + " "); if (ligne.indexOf("<table") != -1) { get = true; } if (get) { sb.append(ligne + " "); } if (ligne.indexOf("</table") != -1 || ligne.indexOf("</tr></font><center><a href='affichaire.php") != -1 || ligne.indexOf("</font><center><a href='afficheregion.php") != -1) { get = false; break; } } oneLine = sb.toString(); allDocInOneLine = sbAllDoc.toString(); if (oneLine.indexOf("</table") != -1) { tableTab = new TableTag(oneLine.substring(oneLine.indexOf(">") + 1, oneLine.indexOf("</table"))); } else if (oneLine.indexOf("</font><center><a href='affichaire") != -1) { tableTab = new TableTag(oneLine.substring(oneLine.indexOf(">") + 1, oneLine.indexOf("</font><center><a href='affichaire"))); } else if (oneLine.indexOf("</font><center><a href='afficheregion.php") != -1) { tableTab = new TableTag(oneLine.substring(oneLine.indexOf(">") + 1, oneLine.indexOf("</font><center><a href='afficheregion.php"))); } else { log.error("La fin du fichier HTML n'a pas ete trouvee, ca va merder..."); } br.close(); if (httpStream != null) { httpStream.close(); } return allDocInOneLine; }
11
Code Sample 1: void writeToFile(String dir, InputStream input, String fileName) throws FileNotFoundException, IOException { makeDirs(dir); FileOutputStream fo = null; try { System.out.println(Thread.currentThread().getName() + " : " + "Writing file " + fileName + " to path " + dir); File file = new File(dir, fileName); fo = new FileOutputStream(file); IOUtils.copy(input, fo); } catch (Exception e) { e.printStackTrace(); System.err.println("Failed to write " + fileName); } } Code Sample 2: private List<Document> storeDocuments(List<Document> documents) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); List<Document> newDocuments = new ArrayList<Document>(); try { session.beginTransaction(); Preference preference = new PreferenceModel(); preference = (Preference) preference.doList(preference).get(0); Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); if (documents != null && !documents.isEmpty()) { for (Iterator<Document> iter = documents.iterator(); iter.hasNext(); ) { Document document = iter.next(); if (AppConstants.STATUS_ACTIVE.equals(document.getStatus())) { try { document = (Document) preAdd(document, getParams()); File fileIn = new File(preference.getScanLocation() + File.separator + document.getName()); File fileOut = new File(preference.getStoreLocation() + File.separator + document.getName()); FileInputStream in = new FileInputStream(fileIn); FileOutputStream out = new FileOutputStream(fileOut); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); document.doAdd(document); boolean isDeleted = fileIn.delete(); System.out.println("Deleted scan folder file: " + document.getName() + ":" + isDeleted); if (isDeleted) { document.setStatus(AppConstants.STATUS_PROCESSING); int uploadCount = 0; if (document.getUploadCount() != null) { uploadCount = document.getUploadCount(); } uploadCount++; document.setUploadCount(uploadCount); newDocuments.add(document); } } catch (Exception add_ex) { add_ex.printStackTrace(); } } else if (AppConstants.STATUS_PROCESSING.equals(document.getStatus())) { int uploadCount = document.getUploadCount(); if (uploadCount < 5) { uploadCount++; document.setUploadCount(uploadCount); System.out.println("increase upload count: " + document.getName() + ":" + uploadCount); newDocuments.add(document); } else { System.out.println("delete from documents list: " + document.getName()); } } else if (AppConstants.STATUS_INACTIVE.equals(document.getStatus())) { document.setFixFlag(AppConstants.FLAG_NO); newDocuments.add(document); } } } } catch (Exception ex) { ex.printStackTrace(); } return newDocuments; }
00
Code Sample 1: public static void gunzip() throws Exception { System.out.println("gunzip()"); GZIPInputStream zipin = new GZIPInputStream(new FileInputStream("/zip/myzip.gz")); byte buffer[] = new byte[BLOCKSIZE]; FileOutputStream out = new FileOutputStream("/zip/covers"); for (int length; (length = zipin.read(buffer, 0, BLOCKSIZE)) != -1; ) out.write(buffer, 0, length); out.close(); zipin.close(); } Code Sample 2: @Override public AudioFileFormat getAudioFileFormat(URL url) throws UnsupportedAudioFileException, IOException { if (TDebug.TraceAudioFileReader) { TDebug.out("getAudioFileFormat(URL url)"); } InputStream inputStream = url.openStream(); try { return getAudioFileFormat(inputStream); } finally { if (inputStream != null) { inputStream.close(); } } }
11
Code Sample 1: public String uploadZtree(ArrayList c) { try { String id = generateRandomId(); Iterator iter = c.iterator(); URL url = new URL(ZorobotSystem.props.getProperty("zoro.url") + "auplo1.jsp"); URLConnection connection = url.openConnection(); connection.setDoOutput(true); PrintWriter out = new PrintWriter(connection.getOutputStream()); out.print("id=" + id + "&"); StringBuffer sb = new StringBuffer(); int gg = 0; while (iter.hasNext()) { if (gg++ >= 500) break; String st = (String) iter.next(); sb.append("a="); sb.append(URLEncoder.encode(st, "UTF-8")); if (iter.hasNext() && gg < 500) sb.append("&"); } out.println(sb.toString()); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; if ((inputLine = in.readLine()) != null) { if (!inputLine.equals("OK!") && inputLine.length() > 3) { System.out.println("Not OK: " + inputLine); return "xxxxxxxxxx"; } } in.close(); return id; } catch (Exception e) { e.printStackTrace(); } return null; } Code Sample 2: public static boolean downloadFile(String url, String destination) throws Exception { BufferedInputStream bi = null; BufferedOutputStream bo = null; File destfile; byte BUFFER[] = new byte[100]; java.net.URL fileurl; URLConnection conn; fileurl = new java.net.URL(url); conn = fileurl.openConnection(); long fullsize = conn.getContentLength(); long onepercent = fullsize / 100; MessageFrame.setTotalDownloadSize(fullsize); bi = new BufferedInputStream(conn.getInputStream()); destfile = new File(destination); if (!destfile.createNewFile()) { destfile.delete(); destfile.createNewFile(); } bo = new BufferedOutputStream(new FileOutputStream(destfile)); int read = 0; int sum = 0; long i = 0; while ((read = bi.read(BUFFER)) != -1) { bo.write(BUFFER, 0, read); sum += read; i += read; if (i > onepercent) { i = 0; MessageFrame.setDownloadProgress(sum); } } bi.close(); bo.close(); MessageFrame.setDownloadProgress(fullsize); return true; }
11
Code Sample 1: public void jsFunction_addFile(ScriptableFile infile) throws IOException { if (!infile.jsFunction_exists()) throw new IllegalArgumentException("Cannot add a file that doesn't exists to an archive"); ZipArchiveEntry entry = new ZipArchiveEntry(infile.getName()); entry.setSize(infile.jsFunction_getSize()); out.putArchiveEntry(entry); try { InputStream inStream = infile.jsFunction_createInputStream(); IOUtils.copy(inStream, out); inStream.close(); } finally { out.closeArchiveEntry(); } } Code Sample 2: public String postEvent(EventDocument eventDoc, Map attachments) { if (eventDoc == null || eventDoc.getEvent() == null) return null; if (queue == null) { sendEvent(eventDoc, attachments); return eventDoc.getEvent().getEventId(); } if (attachments != null) { Iterator iter = attachments.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); if (entry.getValue() instanceof DataHandler) { File file = new File(attachmentStorge + "/" + GuidUtil.generate() + entry.getKey()); try { IOUtils.copy(((DataHandler) entry.getValue()).getInputStream(), new FileOutputStream(file)); entry.setValue(file); } catch (IOException err) { err.printStackTrace(); } } } } InternalEventObject eventObj = new InternalEventObject(); eventObj.setEventDocument(eventDoc); eventObj.setAttachments(attachments); eventObj.setSessionContext(SessionContextUtil.getCurrentContext()); eventDoc.getEvent().setEventId(GuidUtil.generate()); getQueue().post(eventObj); return eventDoc.getEvent().getEventId(); }
11
Code Sample 1: private static String getDigest(String srcStr, String alg) { Assert.notNull(srcStr); Assert.notNull(alg); try { MessageDigest alga = MessageDigest.getInstance(alg); alga.update(srcStr.getBytes()); byte[] digesta = alga.digest(); return byte2hex(digesta); } catch (Exception e) { throw new RuntimeException(e); } } Code Sample 2: private static File[] getWsdls(File dirfile) throws Exception { File[] allfiles = dirfile.listFiles(); List<File> files = new ArrayList<File>(); if (allfiles != null) { MessageDigest md = MessageDigest.getInstance("MD5"); String outputDir = argMap.get(OUTPUT_DIR); for (File file : allfiles) { if (file.getName().endsWith(WSDL_SUFFIX)) { files.add(file); } if (file.getName().endsWith(WSDL_SUFFIX) || file.getName().endsWith(XSD_SUFFIX)) { md.update(FileUtil.getBytes(file)); } } computedHash = md.digest(); hashFile = new File(outputDir + File.separator + argMap.get(BASE_PACKAGE).replace('.', File.separatorChar) + File.separator + "hash.md5"); if (hashFile.exists()) { byte[] readHash = FileUtil.getBytes(hashFile); if (Arrays.equals(readHash, computedHash)) { System.out.println("Skipping generation, files not changed."); files.clear(); } } } File[] filesarr = new File[files.size()]; files.toArray(filesarr); return filesarr; }
00
Code Sample 1: Library(MainFrame mf, boolean newLibrary, String templateName, String newFileName) throws Exception { mainFrame = mf; trackMap = new HashMap<String, LibraryTrack>(); trackVec = new Vector<LibraryTrack>(); String propFileName = null; File propFile = null; String notExist = ""; String[] options = templateDesc; boolean isCurrent = mainFrame.library != null; int ix; if (!newLibrary) { propFileName = mainFrame.name + ".jampal"; propFile = new File(propFileName); } if (isCurrent) { options = new String[templateDesc.length + 1]; options[0] = "Copy of Current Library"; for (ix = 0; ix < templateDesc.length; ix++) { options[ix + 1] = templateDesc[ix]; } } boolean copyLibrary = false; if (newLibrary) { if (templateName == null) { Object resp = JOptionPane.showInputDialog(mainFrame.frame, "Please select a template.", "Select Type of Library", JOptionPane.WARNING_MESSAGE, null, options, null); if (resp == null) return; templateName = (String) resp; } for (ix = 0; ix < options.length && !options[ix].equals(templateName); ix++) ; if (isCurrent) ix--; boolean creatingPlaylist = false; BufferedReader in; if (ix == -1) { in = new BufferedReader(new FileReader(mainFrame.name + ".jampal")); copyLibrary = true; creatingPlaylist = (mainFrame.library.attributes.libraryType == 'P'); } else { in = new BufferedReader(new InputStreamReader(ClassLoader.getSystemResourceAsStream("pgbennett/jampal/" + templateNames[ix]))); creatingPlaylist = ("playlist.jampal".equals(templateNames[ix])); } if (newFileName == null) { JFileChooser fileChooser = new JFileChooser(); fileChooser.setDialogTitle("Create New Library File"); String currentDirectory = null; if (mainFrame.name != null) { File nameFile = new File(mainFrame.name); currentDirectory = nameFile.getParent(); if (currentDirectory == null) currentDirectory = "."; } if (currentDirectory == null) currentDirectory = Jampal.jampalDirectory; if (currentDirectory != null) fileChooser.setCurrentDirectory(new File(currentDirectory)); fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); fileChooser.setMultiSelectionEnabled(false); Mp3FileFilter filter = new Mp3FileFilter(); filter.setExtension("jampal", "Jampal library files"); fileChooser.addChoosableFileFilter(filter); fileChooser.setAcceptAllFileFilterUsed(false); fileChooser.setFileFilter(filter); fileChooser.setDialogType(JFileChooser.SAVE_DIALOG); int returnVal = fileChooser.showSaveDialog(mainFrame.frame); if (returnVal == fileChooser.APPROVE_OPTION) { propFile = fileChooser.getSelectedFile(); propFileName = propFile.getPath(); if (!propFileName.toLowerCase().endsWith(".jampal")) { propFileName = propFileName + ".jampal"; propFile = new File(propFileName); } } else return; } else { propFileName = newFileName; propFile = new File(propFileName); } if (propFile.exists()) { if (JOptionPane.showConfirmDialog(mainFrame.frame, "File " + propFileName + " already exists. Do you want to overwrite it ?", "Warning", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) return; } PrintWriter out = new PrintWriter(new FileOutputStream(propFile)); String libName = propFile.getName(); libName = libName.substring(0, libName.length() - 7); for (; ; ) { String line = in.readLine(); if (line == null) break; if (creatingPlaylist && line.startsWith("playlist=")) { line = "playlist=" + libName; } if (line.startsWith("libraryname=")) { line = "libraryname=" + libName + ".jmp"; } out.println(line); } in.close(); out.close(); if (!creatingPlaylist && !copyLibrary) { String playlistName = propFile.getParent() + File.separator + "playlist.jampal"; File playlistFile = new File(playlistName); if (!playlistFile.exists()) { in = new BufferedReader(new InputStreamReader(ClassLoader.getSystemResourceAsStream("pgbennett/jampal/playlist.jampal"))); out = new PrintWriter(new FileOutputStream(playlistFile)); for (; ; ) { String line = in.readLine(); if (line == null) break; out.println(line); } in.close(); out.close(); } } } if (propFileName != null) attributes = new LibraryAttributes(propFileName); insertBefore = -1; } Code Sample 2: public RecordIterator get(URL url) { RecordIterator recordIter = null; if (!SUPPORTED_PROTOCOLS.contains(url.getProtocol().toLowerCase())) { return null; } try { URL robotsUrl = new URL(url, ROBOTS_TXT); recordIter = new RecordIterator(urlInputStreamFactory.openStream(robotsUrl)); } catch (IOException e) { LOG.info("Failed to fetch " + url, e); } return recordIter; }
11
Code Sample 1: private boolean createPKCReqest(String keystoreLocation, String pw) { boolean created = false; Security.addProvider(new BouncyCastleProvider()); KeyStore ks = null; try { ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(new BufferedInputStream(new FileInputStream(keystoreLocation)), pw.toCharArray()); } catch (Exception e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error reading keystore file when creating PKC request: " + e.getMessage()); } return false; } Certificate cert = null; try { cert = ks.getCertificate("saws"); } catch (KeyStoreException e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error reading certificate from keystore file when creating PKC request: " + e.getMessage()); } return false; } PKCS10CertificationRequest request = null; PublicKey pk = cert.getPublicKey(); try { request = new PKCS10CertificationRequest("SHA1with" + pk.getAlgorithm(), new X500Principal(((X509Certificate) cert).getSubjectDN().toString()), pk, new DERSet(), (PrivateKey) ks.getKey("saws", pw.toCharArray())); PEMWriter pemWrt = new PEMWriter(new OutputStreamWriter(new FileOutputStream("sawsRequest.csr"))); pemWrt.writeObject(request); pemWrt.close(); created = true; } catch (Exception e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error creating PKC request file: " + e.getMessage()); } return false; } return created; } Code Sample 2: private static void copy(File source, File dest) throws FileNotFoundException, IOException { FileInputStream input = new FileInputStream(source); FileOutputStream output = new FileOutputStream(dest); System.out.println("Copying " + source + " to " + dest); IOUtils.copy(input, output); output.close(); input.close(); dest.setLastModified(source.lastModified()); }
00
Code Sample 1: public void check() { statusBar.setStatusText(Labels.getLabel("state.retrievingVersion")); Runnable checkVersionCode = new Runnable() { public void run() { BufferedReader reader = null; String message = null; int messageStyle = SWT.ICON_WARNING; try { URL url = new URL(Version.LATEST_VERSION_URL); URLConnection conn = url.openConnection(); reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String latestVersion = reader.readLine(); latestVersion = latestVersion.substring(latestVersion.indexOf(' ') + 1); if (!Version.getVersion().equals(latestVersion)) { message = Labels.getLabel("text.version.old"); message = message.replaceFirst("%LATEST", latestVersion); message = message.replaceFirst("%VERSION", Version.getVersion()); messageStyle = SWT.ICON_QUESTION | SWT.YES | SWT.NO; } else { message = Labels.getLabel("text.version.latest"); messageStyle = SWT.ICON_INFORMATION; } } catch (Exception e) { message = Labels.getLabel("exception.UserErrorException.version.latestFailed"); Logger.getLogger(getClass().getName()).log(Level.WARNING, message, e); } finally { try { if (reader != null) reader.close(); } catch (IOException e) { } final String messageToShow = message; final int messageStyleToShow = messageStyle; Display.getDefault().asyncExec(new Runnable() { public void run() { statusBar.setStatusText(null); MessageBox messageBox = new MessageBox(statusBar.getShell(), messageStyleToShow); messageBox.setText(Version.getFullName()); messageBox.setMessage(messageToShow); if (messageBox.open() == SWT.YES) { BrowserLauncher.openURL(Version.DOWNLOAD_URL); } } }); } } }; new Thread(checkVersionCode).start(); } Code Sample 2: public List<String> loadList(String name) { List<String> ret = new ArrayList<String>(); try { URL url = getClass().getClassLoader().getResource("lists/" + name + ".utf-8"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")); String line; while ((line = reader.readLine()) != null) { ret.add(line); } reader.close(); } catch (IOException e) { showError("No se puede cargar la lista de valores: " + name, e); } return ret; }
11
Code Sample 1: public String hash(String senha) { String result = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(senha.getBytes()); byte[] hashMd5 = md.digest(); for (int i = 0; i < hashMd5.length; i++) result += Integer.toHexString((((hashMd5[i] >> 4) & 0xf) << 4) | (hashMd5[i] & 0xf)); } catch (NoSuchAlgorithmException ex) { Logger.getInstancia().log(TipoLog.ERRO, ex); } return result; } Code Sample 2: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } }
11
Code Sample 1: private String fetchContent() throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buf = new StringBuffer(); String str; while ((str = reader.readLine()) != null) { buf.append(str); } return buf.toString(); } 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(); }
11
Code Sample 1: public static boolean copyFile(File soureFile, File destFile) { boolean copySuccess = false; if (soureFile != null && destFile != null && soureFile.exists()) { try { new File(destFile.getParent()).mkdirs(); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(destFile)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(soureFile)); for (int currentByte = in.read(); currentByte != -1; currentByte = in.read()) out.write(currentByte); in.close(); out.close(); copySuccess = true; } catch (Exception e) { copySuccess = false; } } return copySuccess; } Code Sample 2: private void copy(File source, File destination) throws PackageException { try { FileInputStream in = new FileInputStream(source); FileOutputStream out = new FileOutputStream(destination); byte[] buff = new byte[1024]; int len; while ((len = in.read(buff)) > 0) out.write(buff, 0, len); in.close(); out.close(); } catch (IOException e) { throw new PackageException("Unable to copy " + source.getPath() + " to " + destination.getPath() + " :: " + e.toString()); } }
00
Code Sample 1: public static String getMD5Hash(String data) { MessageDigest digest; try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(data.getBytes()); byte[] hash = digest.digest(); StringBuffer hexString = new StringBuffer(); String hexChar = ""; for (int i = 0; i < hash.length; i++) { hexChar = Integer.toHexString(0xFF & hash[i]); if (hexChar.length() < 2) { hexChar = "0" + hexChar; } hexString.append(hexChar); } return hexString.toString(); } catch (NoSuchAlgorithmException ex) { return null; } } Code Sample 2: private BoardPattern[] getBoardPatterns() { Resource[] resources = boardManager.getResources("boards"); BoardPattern[] boardPatterns = new BoardPattern[resources.length]; for (int i = 0; i < resources.length; i++) boardPatterns[i] = (BoardPattern) resources[i]; for (int i = 0; i < resources.length; i++) { for (int j = 0; j < resources.length - (i + 1); j++) { String name1 = boardPatterns[j].getName(); String name2 = boardPatterns[j + 1].getName(); if (name1.compareTo(name2) > 0) { BoardPattern tmp = boardPatterns[j]; boardPatterns[j] = boardPatterns[j + 1]; boardPatterns[j + 1] = tmp; } } } return boardPatterns; }
11
Code Sample 1: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); } Code Sample 2: public void save() { final JFileChooser fc = new JFileChooser(); fc.setFileFilter(new FileFilter() { public String getDescription() { return "PDF File"; } public boolean accept(File f) { return f.isDirectory() || f.getName().toLowerCase().endsWith(".pdf"); } }); if (fc.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) { return; } File targetFile = fc.getSelectedFile(); if (!targetFile.getName().toLowerCase().endsWith(".pdf")) { targetFile = new File(targetFile.getParentFile(), targetFile.getName() + ".pdf"); } if (targetFile.exists()) { if (JOptionPane.showConfirmDialog(this, "Do you want to overwrite the file?") != JOptionPane.YES_OPTION) { return; } } try { final InputStream is = new FileInputStream(filename); try { final OutputStream os = new FileOutputStream(targetFile); try { final byte[] buffer = new byte[32768]; for (int read; (read = is.read(buffer)) != -1; ) { os.write(buffer, 0, read); } } finally { os.close(); } } finally { is.close(); } } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: public void create(File target) { if ("dir".equals(type)) { File dir = new File(target, name); dir.mkdirs(); for (Resource c : children) { c.create(dir); } } else if ("package".equals(type)) { String[] dirs = name.split("\\."); File parent = target; for (String d : dirs) { parent = new File(parent, d); } parent.mkdirs(); for (Resource c : children) { c.create(parent); } } else if ("file".equals(type)) { InputStream is = getInputStream(); File file = new File(target, name); try { if (is != null) { FileOutputStream fos = new FileOutputStream(file); IOUtils.copy(is, fos); fos.flush(); fos.close(); } else { PrintStream ps = new PrintStream(file); ps.print(content); ps.flush(); ps.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else if ("zip".equals(type)) { try { unzip(target); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else { throw new RuntimeException("unknown resource type: " + type); } } Code Sample 2: private JButton getButtonImagen() { if (buttonImagen == null) { buttonImagen = new JButton(); buttonImagen.setText("Cargar Imagen"); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/data/icons/view_sidetree.png"))); buttonImagen.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new ImageFilter()); fc.setFileView(new ImageFileView()); fc.setAccessory(new ImagePreview(fc)); int returnVal = fc.showDialog(Resorces.this, "Seleccione una imagen"); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + file.separator + "data" + file.separator + "imagenes" + file.separator + file.getName(); String rutaRelativa = "data" + file.separator + "imagenes" + file.separator + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); } catch (IOException ex) { ex.printStackTrace(); } imagen.setImagenURL(rutaRelativa); System.out.println(rutaGlobal + " " + rutaRelativa); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/data/icons/view_sidetreeOK.png"))); labelImagenPreview.setIcon(gui.procesadorDatos.escalaImageIcon(imagen.getImagenURL())); } else { } } }); } return buttonImagen; }
00
Code Sample 1: @BeforeClass public static void setUpOnce() throws OWLOntologyCreationException { dbManager = (OWLDBOntologyManager) OWLDBManager.createOWLOntologyManager(OWLDataFactoryImpl.getInstance()); dbIRI = IRI.create(ontoUri); System.out.println("copying ontology to work folder..."); try { final File directory = new File("./resources/LUBM10-DB-forUpdate/"); final File[] filesToDelete = directory.listFiles(); if (filesToDelete != null && filesToDelete.length > 0) { for (final File file : filesToDelete) { if (!file.getName().endsWith(".svn")) Assert.assertTrue(file.delete()); } } final File original = new File("./resources/LUBM10-DB/LUBM10.h2.db"); final File copy = new File("./resources/LUBM10-DB-forUpdate/LUBM10.h2.db"); final FileChannel inChannel = new FileInputStream(original).getChannel(); final FileChannel outChannel = new FileOutputStream(copy).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (final IOException ioe) { System.err.println(ioe.getMessage()); Assert.fail(); } onto = (OWLMutableOntology) dbManager.loadOntology(dbIRI); factory = dbManager.getOWLDataFactory(); } Code Sample 2: public String generateMappackMD5(File mapPackFile) throws IOException, NoSuchAlgorithmException { ZipFile zip = new ZipFile(mapPackFile); try { Enumeration<? extends ZipEntry> entries = zip.entries(); MessageDigest md5Total = MessageDigest.getInstance("MD5"); MessageDigest md5 = MessageDigest.getInstance("MD5"); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) continue; String name = entry.getName(); if (name.toUpperCase().startsWith("META-INF")) continue; md5.reset(); InputStream in = zip.getInputStream(entry); byte[] data = Utilities.getInputBytes(in); in.close(); byte[] digest = md5.digest(data); log.trace("Hashsum " + Hex.encodeHexString(digest) + " includes \"" + name + "\""); md5Total.update(digest); md5Total.update(name.getBytes()); } String md5sum = Hex.encodeHexString(md5Total.digest()); log.trace("md5sum of " + mapPackFile.getName() + ": " + md5sum); return md5sum; } finally { zip.close(); } }
11
Code Sample 1: public static double[][] getCurrency() throws IOException { URL url = new URL("http://hk.finance.yahoo.com/currency"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "big5")); double currency[][] = new double[11][11]; while (true) { String line = in.readLine(); String reg = "<td\\s((align=\"right\"\\sclass=\"yfnc_tabledata1\")" + "|(class=\"yfnc_tabledata1\"\\salign=\"right\"))>" + "([\\d|\\.]+)</td>"; Matcher m = Pattern.compile(reg).matcher(line); int i = 0, j = 0; boolean isfound = false; while (m.find()) { isfound = true; currency[i][j] = Double.parseDouble(m.group(4)); if (j == 10) { j = 0; i++; } else j++; } if (isfound) break; } return currency; } 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(); }
11
Code Sample 1: public final void copyFile(final File fromFile, final File toFile) throws IOException { this.createParentPathIfNeeded(toFile); final FileChannel sourceChannel = new FileInputStream(fromFile).getChannel(); final FileChannel targetChannel = new FileOutputStream(toFile).getChannel(); final long sourceFileSize = sourceChannel.size(); sourceChannel.transferTo(0, sourceFileSize, targetChannel); } Code Sample 2: public void writeData(String name, int items, int mznum, int mzscale, long tstart, long tdelta, int[] peaks) { PrintWriter file = getWriter(name + ".txt"); file.println("999 9999"); file.println("Doe, John"); file.println("TEST Lab"); if (mzscale == 1) file.println("PALMS Positive Ion Data"); else if (mzscale == -1) file.println("PALMS Negative Ion Data"); else file.println("PALMS GJIFJIGJ Ion Data"); file.println("TEST Mission"); file.println("1 1"); file.println("1970 01 01 2008 07 09"); file.println("0"); file.println("TIME (UT SECONDS)"); file.println(mznum + 4); for (int i = 0; i < mznum + 4; i++) file.println("1.0"); for (int i = 0; i < mznum + 4; i++) file.println("9.9E29"); file.println("TOTION total MCP signal (electron units)"); file.println("HMASS high mass integral (fraction)"); file.println("UNLIST (unlisted low mass peaks (fraction)"); file.println("UFO unidentified peaks (fraction)"); for (int i = 1; i <= mznum; i++) file.println("MS" + i + " (fraction)"); int header2length = 13; file.println(header2length); for (int i = 0; i < header2length; i++) file.println("1.0"); for (int i = 0; i < header2length; i++) file.println("9.9E29"); file.println("AirCraftTime aircraft time (s)"); file.println("INDEX index ()"); file.println("SCAT scatter (V)"); file.println("JMETER joule meter ()"); file.println("ND neutral density (fraction)"); file.println("SCALEA Mass scale intercept (us)"); file.println("SCALEB mass scale slope (us)"); file.println("NUMPKS number of peaks ()"); file.println("CONF confidence (coded)"); file.println("CAT preliminary category ()"); file.println("AeroDiam aerodynamic diameter (um)"); file.println("AeroDiam1p7 aero diam if density=1.7 (um)"); file.println("TOTBACK total background subtracted (electron units)"); file.println("0"); file.println("0"); String nothing = "0.000000"; for (int i = 0; i < items; i++) { file.println(tstart + (tdelta * i)); file.println(tstart + (tdelta * i) - 3); file.println(i + 1); for (int j = 0; j < 15; j++) file.println(Math.random()); boolean peaked = false; for (int k = 1; k <= mznum; k++) { for (int j = 0; j < peaks.length && !peaked; j++) if (k == peaks[j]) { double randData = (int) (1000000 * (j + 1)); file.println(randData / 1000000); peaked = true; } if (!peaked) file.println(nothing); peaked = false; } } try { Scanner test = new Scanner(f); while (test.hasNext()) { System.out.println(test.nextLine()); } System.out.println("test"); } catch (Exception e) { } file.close(); }
00
Code Sample 1: private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); OutputStream output = getOutputStream(); if (cachedContent != null) { output.write(cachedContent); } else { FileInputStream input = new FileInputStream(dfosFile); IOUtils.copy(input, output); dfosFile.delete(); dfosFile = null; } output.close(); cachedContent = null; } Code Sample 2: public void sort(int[] order, double[] values) { int temp = 0; boolean done = false; for (int i = 0; i < values.length; i++) { order[i] = i; } if (desendingValues) { while (!done) { done = true; for (int i = values.length - 2; i >= 0; i--) { if (values[order[i]] < values[order[i + 1]]) { done = false; temp = order[i]; order[i] = order[i + 1]; order[i + 1] = temp; } } } } else { while (!done) { done = true; for (int i = values.length - 2; i >= 0; i--) { if (values[order[i]] > values[order[i + 1]]) { done = false; temp = order[i]; order[i] = order[i + 1]; order[i + 1] = temp; } } } } }
11
Code Sample 1: public static final void copy(File src, File dest) throws IOException { FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; if (!src.exists()) { throw new IOException("Source not found: " + src); } if (!src.canRead()) { throw new IOException("Source is unreadable: " + src); } if (src.isFile()) { if (!dest.exists()) { File parentdir = parent(dest); if (!parentdir.exists()) { parentdir.mkdir(); } } else if (dest.isDirectory()) { dest = new File(dest + File.separator + src); } } else if (src.isDirectory()) { if (dest.isFile()) { throw new IOException("Cannot copy directory " + src + " to file " + dest); } if (!dest.exists()) { dest.mkdir(); } } if (src.isFile()) { try { source = new FileInputStream(src); destination = new FileOutputStream(dest); 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) { } } } } else if (src.isDirectory()) { String targetfile, target, targetdest; String[] files = src.list(); for (int i = 0; i < files.length; i++) { targetfile = files[i]; target = src + File.separator + targetfile; targetdest = dest + File.separator + targetfile; if ((new File(target)).isDirectory()) { copy(new File(target), new File(targetdest)); } else { try { source = new FileInputStream(target); destination = new FileOutputStream(targetdest); 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 static void copy(FileInputStream in, File destination) throws IOException { FileChannel srcChannel = null; FileChannel dstChannel = null; try { srcChannel = in.getChannel(); dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { if (srcChannel != null) { srcChannel.close(); } if (dstChannel != null) { dstChannel.close(); } } }
11
Code Sample 1: @Override public void run() { URL url = null; FileOutputStream fos = null; FTPClient ftp = null; try { url = new URL(super.getAddress()); String host = url.getHost(); String folder = StringUtils.substringBeforeLast(url.getPath(), "/"); String fileName = StringUtils.substringAfterLast(url.getPath(), "/"); ftp = new FTPClient(host, 21); if (!ftp.connected()) { ftp.connect(); } ftp.login("anonymous", "me@mymail.com"); logger.info("Connected to " + host + "."); logger.info(ftp.getLastValidReply().getReplyText()); logger.debug("changing dir to " + folder); ftp.chdir(folder); fos = new FileOutputStream(localFileName); logger.info("Downloading file " + fileName + "..."); ftp.setType(FTPTransferType.BINARY); ftp.get(fos, fileName); logger.info("Done."); } catch (Exception e) { logger.error(e.getMessage()); logger.debug(e.getStackTrace()); } finally { try { ftp.quit(); fos.close(); } catch (Exception e) { } } } Code Sample 2: private static FTPClient getFtpClient(String ftpHost, String ftpUsername, String ftpPassword) throws SocketException, IOException { FTPClient ftp = new FTPClient(); ftp.connect(ftpHost); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return null; } if (!ftp.login(ftpUsername, ftpPassword)) { return null; } ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); return ftp; }
11
Code Sample 1: public static String getMD5(String value) { if (StringUtils.isBlank(value)) return null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(value.getBytes("UTF-8")); return toHexString(md.digest()); } catch (Throwable e) { return null; } } Code Sample 2: public static final String enCode(String algorithm, String string) { MessageDigest md; String result = ""; try { md = MessageDigest.getInstance(algorithm); md.update(string.getBytes()); result = binaryToString(md.digest()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return result; }
11
Code Sample 1: protected static String encodePassword(String raw_password) throws DatabaseException { String clean_password = validatePassword(raw_password); try { MessageDigest md = MessageDigest.getInstance(DEFAULT_PASSWORD_DIGEST); md.update(clean_password.getBytes(DEFAULT_PASSWORD_ENCODING)); String digest = new String(Base64.encodeBase64(md.digest())); if (log.isDebugEnabled()) log.debug("encodePassword: digest=" + digest); return digest; } catch (UnsupportedEncodingException e) { throw new DatabaseException("encoding-problem with password", e); } catch (NoSuchAlgorithmException e) { throw new DatabaseException("digest-problem encoding password", e); } } Code Sample 2: byte[] calculateDigest(String value) { try { MessageDigest mg = MessageDigest.getInstance("SHA1"); mg.update(value.getBytes()); return mg.digest(); } catch (Exception e) { throw Bark.unchecker(e); } }
00
Code Sample 1: public void run() { try { URL url = new URL(URL_STR + "?req=list"); URLConnection connection = url.openConnection(getProxy()); connection.setRequestProperty("User-Agent", USER_AGENT); BufferedReader bufferedRdr = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line = null; int foundCount = 0; ArrayList<String> names = new ArrayList<String>(); ArrayList<String> songs = new ArrayList<String>(); ArrayList<Integer> scores = new ArrayList<Integer>(); ArrayList<Float> factors = new ArrayList<Float>(); String[] subparts; String[] ssubparts; int tlscore; float tlfactor; while ((line = bufferedRdr.readLine()) != null) { if (line.length() > 2) { try { subparts = line.split(" ", 3); if (subparts.length != 3) { Util.debug(28, "Not enough subentry in online toplist file: ." + KeyboardHero.APP_NAME + ".tls!"); continue; } tlscore = Integer.parseInt(subparts[1]); tlfactor = Float.parseFloat(subparts[0]); scores.add(tlscore); factors.add(tlfactor); ssubparts = hexdecode(subparts[2]).split("¦", 2); if (ssubparts.length != 2) { Util.debug(26, "Not enough subsubentry in online toplist file: ." + KeyboardHero.APP_NAME + ".tls!"); continue; } songs.add(ssubparts[0]); names.add(ssubparts[1]); foundCount++; } catch (NumberFormatException e) { Util.debug(24, "Corrupted toplist score and/or level number in the online toplist!"); } catch (ArrayIndexOutOfBoundsException e) { Util.debug(25, "Corrupted toplist entry in the online toplist!"); } } } bufferedRdr.close(); ((DialogToplist) KeyboardHero.getDialogs().get("toplist")).setContent(names.toArray(new String[0]), scores.toArray(new Integer[0]), songs.toArray(new String[0]), factors.toArray(new Float[0]), foundCount, -1); } catch (Exception e) { ((DialogToplist) KeyboardHero.getDialogs().get("toplist")).setStatusText(Util.getMsg("CannotToplist") + "!\n\n" + e.toString(), false); } } Code Sample 2: public String readBaseLib() throws Exception { if (_BASE_LIB_JS == null) { StringBuffer js = new StringBuffer(); try { URL url = AbstractRunner.class.getResource(_BASELIB_FILENAME); if (url != null) { InputStream is = url.openStream(); InputStreamReader reader = new InputStreamReader(is); BufferedReader bfReader = new BufferedReader(reader); String tmp = null; do { tmp = bfReader.readLine(); if (tmp != null) { js.append(tmp).append('\n'); } } while (tmp != null); bfReader.close(); reader.close(); is.close(); } } catch (Exception e) { e.printStackTrace(); throw e; } _BASE_LIB_JS = js.toString(); } return _BASE_LIB_JS; }
11
Code Sample 1: public static String hash(String toEncripty) { if (toEncripty != null) { try { synchronized (toEncripty) { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(toEncripty.getBytes()); byte[] hash = md.digest(); StringBuffer hexString = new StringBuffer(); 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])); } toEncripty = hexString.toString(); } } catch (Exception e) { e.getMessage(); } } return toEncripty; } Code Sample 2: private static String genRandomGUID(boolean secure) { String valueBeforeMD5 = ""; String valueAfterMD5 = ""; MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); return valueBeforeMD5; } long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); String strTemp = ""; for (int i = 0; i < array.length; i++) { strTemp = (Integer.toHexString(array[i] & 0XFF)); if (strTemp.length() == 1) { valueAfterMD5 = valueAfterMD5 + "0" + strTemp; } else { valueAfterMD5 = valueAfterMD5 + strTemp; } } return valueAfterMD5.toUpperCase(); }
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 ManageUsers() { if (System.getProperty("user.home") != null) { dataFile = new File(System.getProperty("user.home") + File.separator + "MyRx" + File.separator + "MyRx.dat"); File dataFileDir = new File(System.getProperty("user.home") + File.separator + "MyRx"); dataFileDir.mkdirs(); } else { dataFile = new File("MyRx.dat"); } try { dataFile.createNewFile(); } catch (IOException e1) { logger.error(e1); JOptionPane.showMessageDialog(Menu.getMainMenu(), e1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } File oldDataFile = new File("MyRx.dat"); if (oldDataFile.exists()) { FileChannel src = null, dst = null; try { src = new FileInputStream(oldDataFile.getAbsolutePath()).getChannel(); dst = new FileOutputStream(dataFile.getAbsolutePath()).getChannel(); dst.transferFrom(src, 0, src.size()); if (!oldDataFile.delete()) { oldDataFile.deleteOnExit(); } } catch (FileNotFoundException e) { logger.error(e); JOptionPane.showMessageDialog(Menu.getMainMenu(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } catch (IOException e) { logger.error(e); JOptionPane.showMessageDialog(Menu.getMainMenu(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } finally { try { src.close(); dst.close(); } catch (IOException e) { logger.error(e); } } } }
11
Code Sample 1: public ActionForward uploadFile(ActionMapping mapping, ActionForm actForm, HttpServletRequest request, HttpServletResponse in_response) { ActionMessages errors = new ActionMessages(); ActionMessages messages = new ActionMessages(); String returnPage = "submitPocketSampleInformationPage"; UploadForm form = (UploadForm) actForm; Integer shippingId = null; try { eHTPXXLSParser parser = new eHTPXXLSParser(); String proposalCode; String proposalNumber; String proposalName; String uploadedFileName; String realXLSPath; if (request != null) { proposalCode = (String) request.getSession().getAttribute(Constants.PROPOSAL_CODE); proposalNumber = String.valueOf(request.getSession().getAttribute(Constants.PROPOSAL_NUMBER)); proposalName = proposalCode + proposalNumber.toString(); uploadedFileName = form.getRequestFile().getFileName(); String fileName = proposalName + "_" + uploadedFileName; realXLSPath = request.getRealPath("\\tmp\\") + "\\" + fileName; FormFile f = form.getRequestFile(); InputStream in = f.getInputStream(); File outputFile = new File(realXLSPath); if (outputFile.exists()) outputFile.delete(); FileOutputStream out = new FileOutputStream(outputFile); while (in.available() != 0) { out.write(in.read()); out.flush(); } out.flush(); out.close(); } else { proposalCode = "ehtpx"; proposalNumber = "1"; proposalName = proposalCode + proposalNumber.toString(); uploadedFileName = "ispyb-template41.xls"; realXLSPath = "D:\\" + uploadedFileName; } FileInputStream inFile = new FileInputStream(realXLSPath); parser.retrieveShippingId(realXLSPath); shippingId = parser.getShippingId(); String requestShippingId = form.getShippingId(); if (requestShippingId != null && !requestShippingId.equals("")) { shippingId = new Integer(requestShippingId); } ClientLogger.getInstance().debug("uploadFile for shippingId " + shippingId); if (shippingId != null) { Log.debug(" ---[uploadFile] Upload for Existing Shipment (DewarTRacking): Deleting Samples from Shipment :"); double nbSamplesContainers = DBAccess_EJB.DeleteAllSamplesAndContainersForShipping(shippingId); if (nbSamplesContainers > 0) parser.getValidationWarnings().add(new XlsUploadException("Shipment contained Samples and/or Containers", "Previous Samples and/or Containers have been deleted and replaced by new ones.")); else parser.getValidationWarnings().add(new XlsUploadException("Shipment contained no Samples and no Containers", "Samples and Containers have been added.")); } Hashtable<String, Hashtable<String, Integer>> listProteinAcronym_SampleName = new Hashtable<String, Hashtable<String, Integer>>(); ProposalFacadeLocal proposal = ProposalFacadeUtil.getLocalHome().create(); ProteinFacadeLocal protein = ProteinFacadeUtil.getLocalHome().create(); CrystalFacadeLocal crystal = CrystalFacadeUtil.getLocalHome().create(); ProposalLightValue targetProposal = (ProposalLightValue) (((ArrayList) proposal.findByCodeAndNumber(proposalCode, new Integer(proposalNumber))).get(0)); ArrayList listProteins = (ArrayList) protein.findByProposalId(targetProposal.getProposalId()); for (int p = 0; p < listProteins.size(); p++) { ProteinValue prot = (ProteinValue) listProteins.get(p); Hashtable<String, Integer> listSampleName = new Hashtable<String, Integer>(); CrystalLightValue listCrystals[] = prot.getCrystals(); for (int c = 0; c < listCrystals.length; c++) { CrystalLightValue _xtal = (CrystalLightValue) listCrystals[c]; CrystalValue xtal = crystal.findByPrimaryKey(_xtal.getPrimaryKey()); BlsampleLightValue listSamples[] = xtal.getBlsamples(); for (int s = 0; s < listSamples.length; s++) { BlsampleLightValue sample = listSamples[s]; listSampleName.put(sample.getName(), sample.getBlSampleId()); } } listProteinAcronym_SampleName.put(prot.getAcronym(), listSampleName); } parser.validate(inFile, listProteinAcronym_SampleName, targetProposal.getProposalId()); List listErrors = parser.getValidationErrors(); List listWarnings = parser.getValidationWarnings(); if (listErrors.size() == 0) { parser.open(realXLSPath); if (parser.getCrystals().size() == 0) { parser.getValidationErrors().add(new XlsUploadException("No crystals have been found", "Empty shipment")); } } Iterator errIt = listErrors.iterator(); while (errIt.hasNext()) { XlsUploadException xlsEx = (XlsUploadException) errIt.next(); errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("message.free", xlsEx.getMessage() + " ---> " + xlsEx.getSuggestedFix())); } try { saveErrors(request, errors); } catch (Exception e) { } Iterator warnIt = listWarnings.iterator(); while (warnIt.hasNext()) { XlsUploadException xlsEx = (XlsUploadException) warnIt.next(); messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("message.free", xlsEx.getMessage() + " ---> " + xlsEx.getSuggestedFix())); } try { saveMessages(request, messages); } catch (Exception e) { } if (listErrors.size() > 0) { resetCounts(shippingId); return mapping.findForward("submitPocketSampleInformationPage"); } if (listWarnings.size() > 0) returnPage = "submitPocketSampleInformationPage"; String crystalDetailsXML; XtalDetails xtalDetailsWebService = new XtalDetails(); CrystalDetailsBuilder cDE = new CrystalDetailsBuilder(); CrystalDetailsElement cd = cDE.createCrystalDetailsElement(proposalName, parser.getCrystals()); cDE.validateJAXBObject(cd); crystalDetailsXML = cDE.marshallJaxBObjToString(cd); xtalDetailsWebService.submitCrystalDetails(crystalDetailsXML); String diffractionPlan; DiffractionPlan diffractionPlanWebService = new DiffractionPlan(); DiffractionPlanBuilder dPB = new DiffractionPlanBuilder(); Iterator it = parser.getDiffractionPlans().iterator(); while (it.hasNext()) { DiffractionPlanElement dpe = (DiffractionPlanElement) it.next(); dpe.setProjectUUID(proposalName); diffractionPlan = dPB.marshallJaxBObjToString(dpe); diffractionPlanWebService.submitDiffractionPlan(diffractionPlan); } String crystalShipping; Shipping shippingWebService = new Shipping(); CrystalShippingBuilder cSB = new CrystalShippingBuilder(); Person person = cSB.createPerson("XLS Upload", null, "ISPyB", null, null, "ISPyB", null, "ispyb@esrf.fr", "0000", "0000", null, null); Laboratory laboratory = cSB.createLaboratory("Generic Laboratory", "ISPyB Lab", "Sandwich", "Somewhere", "UK", "ISPyB", "ispyb.esrf.fr", person); DeliveryAgent deliveryAgent = parser.getDeliveryAgent(); CrystalShipping cs = cSB.createCrystalShipping(proposalName, laboratory, deliveryAgent, parser.getDewars()); String shippingName; shippingName = uploadedFileName.substring(0, ((uploadedFileName.toLowerCase().lastIndexOf(".xls")) > 0) ? uploadedFileName.toLowerCase().lastIndexOf(".xls") : 0); if (shippingName.equalsIgnoreCase("")) shippingName = uploadedFileName.substring(0, ((uploadedFileName.toLowerCase().lastIndexOf(".xlt")) > 0) ? uploadedFileName.toLowerCase().lastIndexOf(".xlt") : 0); cs.setName(shippingName); crystalShipping = cSB.marshallJaxBObjToString(cs); shippingWebService.submitCrystalShipping(crystalShipping, (ArrayList) parser.getDiffractionPlans(), shippingId); ServerLogger.Log4Stat("XLS_UPLOAD", proposalName, uploadedFileName); } catch (XlsUploadException e) { resetCounts(shippingId); errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.detail", e.getMessage())); ClientLogger.getInstance().error(e.toString()); saveErrors(request, errors); return mapping.findForward("error"); } catch (Exception e) { resetCounts(shippingId); errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.detail", e.toString())); ClientLogger.getInstance().error(e.toString()); e.printStackTrace(); saveErrors(request, errors); return mapping.findForward("error"); } setCounts(shippingId); return mapping.findForward(returnPage); } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); } Code Sample 2: void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
11
Code Sample 1: public static void copy(File src, File dest) { try { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { } } Code Sample 2: public void loadXML(URL flux, int status, File file) { try { SAXBuilder sbx = new SAXBuilder(); try { if (file.exists()) { file.delete(); } if (!file.exists()) { URLConnection conn = flux.openConnection(); conn.setConnectTimeout(5000); conn.setReadTimeout(10000); InputStream is = conn.getInputStream(); OutputStream out = new FileOutputStream(file); byte buf[] = new byte[1024]; int len; while ((len = is.read(buf)) > 0) out.write(buf, 0, len); out.close(); is.close(); } } catch (Exception e) { Log.e(Constants.PROJECT_TAG, "Exeption retrieving XML", e); } try { document = sbx.build(new FileInputStream(file)); } catch (Exception e) { Log.e(Constants.PROJECT_TAG, "xml error ", e); } } catch (Exception e) { Log.e(Constants.PROJECT_TAG, "TsukiQueryError", e); } if (document != null) { root = document.getRootElement(); PopulateDatabase(root, status); } }
11
Code Sample 1: private void copyFile(File file, File dir) throws IOException { BufferedReader in = new BufferedReader(new FileReader(file)); BufferedWriter out = new BufferedWriter(new FileWriter(new File(dir.getAbsolutePath() + File.separator + file.getName()))); char[] buffer = new char[512]; int read = -1; while ((read = in.read(buffer)) > 0) { out.write(buffer, 0, read); } in.close(); out.close(); } Code Sample 2: public void visit(BosMember member) throws BosException { String relative = AddressingUtil.getRelativePath(member.getDataSourceUri(), baseUri); URL resultUrl; try { resultUrl = new URL(outputUrl, relative); File resultFile = new File(resultUrl.toURI()); resultFile.getParentFile().mkdirs(); log.info("Creating result file \"" + resultFile.getAbsolutePath() + "\"..."); IOUtils.copy(member.getInputStream(), new FileOutputStream(resultFile)); } catch (Exception e) { throw new BosException(e); } }
00
Code Sample 1: public static final void zip(final ZipOutputStream out, final File f, String base) throws Exception { if (f.isDirectory()) { final File[] fl = f.listFiles(); base = base.length() == 0 ? "" : base + File.separator; for (final File element : fl) { zip(out, element, base + element.getName()); } } else { out.putNextEntry(new org.apache.tools.zip.ZipEntry(base)); final FileInputStream in = new FileInputStream(f); IOUtils.copyStream(in, out); in.close(); } Thread.sleep(10); } Code Sample 2: public static void main(String[] args) { if (args.length != 2) { printUsage(); } String url = args[0]; String path = args[1]; BufferedReader pbsFileReader = null; try { pbsFileReader = new BufferedReader(new FileReader(path)); } catch (FileNotFoundException ex) { System.err.println("Pbs file " + path + " not found"); System.exit(1); } String line = ""; HttpURLConnection conn = null; BufferedWriter out = null; BufferedReader in = null; try { conn = (HttpURLConnection) new URL(url).openConnection(); conn.setDoOutput(true); out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream())); while (true) { line = pbsFileReader.readLine(); if (line == null) { break; } out.write(line); out.newLine(); System.err.println(line); } in = new BufferedReader(new InputStreamReader(conn.getInputStream())); line = ""; while (true) { line = in.readLine(); if (line == null) { break; } System.out.println(line); } out.close(); in.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: public static void concatenateOutput(File[] inputFiles, File outputFile) { int numberOfInputFiles = inputFiles.length; byte lf = (byte) '\n'; try { FileOutputStream fos = new FileOutputStream(outputFile); FileChannel outfc = fos.getChannel(); System.out.println("Processing " + inputFiles[0].getPath()); FileInputStream fis = new FileInputStream(inputFiles[0]); FileChannel infc = fis.getChannel(); int bufferCapacity = 100000; ByteBuffer bb = ByteBuffer.allocate(bufferCapacity); bb.clear(); while (infc.read(bb) > 0) { bb.flip(); outfc.write(bb); bb.clear(); } infc.close(); for (int f = 1; f < numberOfInputFiles; f++) { System.out.println("Processing " + inputFiles[f].getPath()); fis = new FileInputStream(inputFiles[f]); infc = fis.getChannel(); bb.clear(); int bytesread = infc.read(bb); bb.flip(); byte b = bb.get(); while (b != lf) { b = bb.get(); } outfc.write(bb); bb.clear(); while (infc.read(bb) > 0) { bb.flip(); outfc.write(bb); bb.clear(); } infc.close(); } outfc.close(); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: private boolean serverOK(String serverAddress, String serverPort) { boolean status = false; String serverString = serverAddress + ":" + serverPort + MolConvertInNodeModel.SERVER_WSDL_PATH; System.out.println("connecting to " + serverString + "..."); try { java.net.URL url = new java.net.URL(serverString); try { java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection(); status = readContents(connection); if (status) { JOptionPane.showMessageDialog(this.getPanel(), "Connection to Server is OK"); } } catch (Exception connEx) { JOptionPane.showMessageDialog(this.getPanel(), connEx.getMessage()); logger.error(connEx.getMessage()); } } catch (java.net.MalformedURLException urlEx) { JOptionPane.showMessageDialog(this.getPanel(), urlEx.getMessage()); logger.error(urlEx.getMessage()); } return status; } Code Sample 2: private void gerarFaturamento() { int opt = Funcoes.mensagemConfirma(null, "Confirma o faturamento?"); if (opt == JOptionPane.OK_OPTION) { StringBuilder insert = new StringBuilder(); insert.append("INSERT INTO RPFATURAMENTO "); insert.append("(CODEMP, CODFILIAL, CODPED, CODITPED, "); insert.append("QTDFATURADO, VLRFATURADO, QTDPENDENTE, "); insert.append("PERCCOMISFAT, VLRCOMISFAT, DTFATURADO ) "); insert.append("VALUES"); insert.append("(?,?,?,?,?,?,?,?,?,?)"); PreparedStatement ps; int parameterIndex; try { for (int i = 0; i < tab.getNumLinhas(); i++) { parameterIndex = 1; ps = con.prepareStatement(insert.toString()); ps.setInt(parameterIndex++, AplicativoRep.iCodEmp); ps.setInt(parameterIndex++, ListaCampos.getMasterFilial("RPFATURAMENTO")); ps.setInt(parameterIndex++, txtCodPed.getVlrInteger()); ps.setInt(parameterIndex++, (Integer) tab.getValor(i, ETabNota.ITEM.ordinal())); ps.setBigDecimal(parameterIndex++, (BigDecimal) tab.getValor(i, ETabNota.QTDFATURADA.ordinal())); ps.setBigDecimal(parameterIndex++, (BigDecimal) tab.getValor(i, ETabNota.VLRFATURADO.ordinal())); ps.setBigDecimal(parameterIndex++, (BigDecimal) tab.getValor(i, ETabNota.QDTPENDENTE.ordinal())); ps.setBigDecimal(parameterIndex++, (BigDecimal) tab.getValor(i, ETabNota.PERCCOMIS.ordinal())); ps.setBigDecimal(parameterIndex++, (BigDecimal) tab.getValor(i, ETabNota.VLRCOMIS.ordinal())); ps.setDate(parameterIndex++, Funcoes.dateToSQLDate(Calendar.getInstance().getTime())); ps.executeUpdate(); } gerarFaturamento.setEnabled(false); gerarComissao.setEnabled(true); Funcoes.mensagemInforma(null, "Faturamento criado para pedido " + txtCodPed.getVlrInteger()); con.commit(); } catch (Exception e) { e.printStackTrace(); Funcoes.mensagemErro(this, "Erro ao gerar faturamento!\n" + e.getMessage()); try { con.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } } } }
00
Code Sample 1: public void execute() throws InstallerException { try { SQLCommand sqlCommand = new SQLCommand(connectionInfo); connection = sqlCommand.getConnection(); connection.setAutoCommit(false); sqlStatement = connection.createStatement(); double size = (double) statements.size(); for (String statement : statements) { sqlStatement.executeUpdate(statement); setCompletedPercentage(getCompletedPercentage() + (1 / size)); } connection.commit(); } catch (SQLException e) { try { connection.rollback(); } catch (SQLException e1) { throw new InstallerException(InstallerException.TRANSACTION_ROLLBACK_ERROR, new Object[] { e.getMessage() }, e); } throw new InstallerException(InstallerException.SQL_EXEC_EXCEPTION, new Object[] { e.getMessage() }, e); } catch (ClassNotFoundException e) { throw new InstallerException(InstallerException.DB_DRIVER_LOAD_ERROR, e); } finally { if (connection != null) { try { sqlStatement.close(); connection.close(); } catch (SQLException e) { } } } } Code Sample 2: private Bitmap downloadBitmap(String url) { final AndroidHttpClient client = AndroidHttpClient.newInstance("Android"); final HttpGet getRequest = new HttpGet(url); try { HttpResponse response = client.execute(getRequest); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.w(LOG_TAG, "Error " + statusCode + " while retrieving bitmap from " + url); return null; } final HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = null; try { inputStream = entity.getContent(); final Bitmap bitmap = BitmapFactory.decodeStream(inputStream); return bitmap; } finally { if (inputStream != null) { inputStream.close(); } entity.consumeContent(); } } } catch (Exception e) { getRequest.abort(); Log.w(LOG_TAG, "Error while retrieving bitmap from " + url, e); } finally { if (client != null) { client.close(); } } return null; }
11
Code Sample 1: private String readHtmlFile(String htmlFileName) { StringBuffer buffer = new StringBuffer(); java.net.URL url = getClass().getClassLoader().getResource("freestyleLearning/homeCore/help/" + htmlFileName); try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String string = " "; while (string != null) { string = reader.readLine(); if (string != null) buffer.append(string); } } catch (Exception exc) { System.out.println(exc); } return new String(buffer); } Code Sample 2: private static String getData(String myurl) throws Exception { System.out.println("getdata"); URL url = new URL(myurl); uc = (HttpURLConnection) url.openConnection(); br = new BufferedReader(new InputStreamReader(uc.getInputStream())); String temp = "", k = ""; while ((temp = br.readLine()) != null) { System.out.println(temp); k += temp; } br.close(); return k; }
00
Code Sample 1: public void reset(String componentName, int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? " + "AND component_name = ?"); psta.setInt(1, currentPilot); psta.setString(2, componentName); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } } Code Sample 2: @Override public URLConnection getResourceConnection(String name) throws ResourceException { try { URLConnection c = super.getResourceConnection(name); return c; } catch (ResourceException e) { while (name.startsWith(ServletHelpers.SCRIPT_DIR.getAbsolutePath())) name = name.substring(ServletHelpers.SCRIPT_DIR.getAbsolutePath().length()); name = name.replaceAll("\\\\", "/"); if (name.startsWith("/")) name = name.substring(1); File script = new File(ServletHelpers.SCRIPT_DIR, name); if (script.canRead()) { try { URL url = new URL("file", "", script.getAbsolutePath()); return url.openConnection(); } catch (IOException x) { throw new ResourceException("IOError", x); } } else throw new ResourceException(String.format("Script not found! [%s]", script.getAbsolutePath())); } }
00
Code Sample 1: @Override public void run() { Shell currentShell = Display.getCurrent().getActiveShell(); if (DMManager.getInstance().getOntology() == null) return; DataRecordSet data = DMManager.getInstance().getOntology().getDataView().dataset(); InputDialog input = new InputDialog(currentShell, Resources.I18N.getString("vikamine.dtp.title"), Resources.I18N.getString("vikamine.dtp.export.tablename"), data.getRelationName(), null); input.open(); String tablename = input.getValue(); if (tablename == null) return; super.getProfile().connect(); IManagedConnection mc = super.getProfile().getManagedConnection("java.sql.Connection"); java.sql.Connection sql = (java.sql.Connection) mc.getConnection().getRawConnection(); try { sql.setAutoCommit(false); DatabaseMetaData dbmd = sql.getMetaData(); ResultSet tables = dbmd.getTables(null, null, tablename, new String[] { "TABLE" }); if (tables.next()) { if (!MessageDialog.openConfirm(currentShell, Resources.I18N.getString("vikamine.dtp.title"), Resources.I18N.getString("vikamine.dtp.export.overwriteTable"))) return; Statement statement = sql.createStatement(); statement.executeUpdate("DROP TABLE " + tablename); statement.close(); } String createTableQuery = null; for (int i = 0; i < data.getNumAttributes(); i++) { if (DMManager.getInstance().getOntology().isIDAttribute(data.getAttribute(i))) continue; if (createTableQuery == null) createTableQuery = ""; else createTableQuery += ","; createTableQuery += getColumnDefinition(data.getAttribute(i)); } Statement statement = sql.createStatement(); statement.executeUpdate("CREATE TABLE " + tablename + "(" + createTableQuery + ")"); statement.close(); exportRecordSet(data, sql, tablename); sql.commit(); sql.setAutoCommit(true); MessageDialog.openInformation(currentShell, Resources.I18N.getString("vikamine.dtp.title"), Resources.I18N.getString("vikamine.dtp.export.successful")); } catch (SQLException e) { try { sql.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } MessageDialog.openError(currentShell, Resources.I18N.getString("vikamine.dtp.title"), Resources.I18N.getString("vikamine.dtp.export.failed")); e.printStackTrace(); } } Code Sample 2: public List<String> makeQuery(String query) { List<String> result = new ArrayList<String>(); try { query = URLUTF8Encoder.encode(query); URL url = new URL("http://ajax.googleapis.com/ajax/services/search/web?start=0&rsz=large&v=1.0&q=" + query); URLConnection connection = url.openConnection(); connection.addRequestProperty("Referer", "http://poo.sk"); String line; StringBuilder builder = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((line = reader.readLine()) != null) { builder.append(line); } String response = builder.toString(); JSONObject json = new JSONObject(response); Long count = Long.decode(json.getJSONObject("responseData").getJSONObject("cursor").getString("estimatedResultCount")); LOG.info("Found " + count + " potential pages"); JSONArray ja = json.getJSONObject("responseData").getJSONArray("results"); for (int i = 0; i < ja.length(); i++) { JSONObject j = ja.getJSONObject(i); result.add(j.getString("url")); } } catch (Exception e) { LOG.error("Couldnt query Google for some reason check exception below"); e.printStackTrace(); } return result; }
11
Code Sample 1: private static String fetchImageViaHttp(URL imgUrl) throws IOException { String sURL = imgUrl.toString(); String imgFile = imgUrl.getPath(); HttpURLConnection cnx = (HttpURLConnection) imgUrl.openConnection(); String uri = null; try { cnx.setAllowUserInteraction(false); cnx.setDoOutput(true); cnx.addRequestProperty("Cache-Control", "no-cache"); RequestContext ctx = RequestContext.get(); if (ctx != null) cnx.addRequestProperty("User-Agent", ctx.header("user-agent")); else cnx.addRequestProperty("User-Agent", user_agent); cnx.addRequestProperty("Referer", sURL.substring(0, sURL.indexOf('/', sURL.indexOf('.')) + 1)); cnx.connect(); if (cnx.getResponseCode() != HttpURLConnection.HTTP_OK) return null; InputStream imgData = cnx.getInputStream(); String ext = FilenameUtils.getExtension(imgFile).toLowerCase(); if (!Multimedia.isImageFile("aa." + ext)) ext = "jpg"; uri = FMT_FN.format(new Date()) + RandomStringUtils.randomAlphanumeric(4) + '.' + ext; File fileDest = new File(img_path + uri); if (!fileDest.getParentFile().exists()) fileDest.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(fileDest); try { IOUtils.copy(imgData, fos); } finally { IOUtils.closeQuietly(imgData); IOUtils.closeQuietly(fos); } } finally { cnx.disconnect(); } return RequestContext.get().contextPath() + "/uploads/img/" + uri; } Code Sample 2: public static void copyFile(File sourceFile, File destFile) throws IOException { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(sourceFile); os = new FileOutputStream(destFile); IOUtils.copy(is, os); } finally { try { if (os != null) os.close(); } catch (Exception e) { } try { if (is != null) is.close(); } catch (Exception e) { } } }
00
Code Sample 1: public static String Sha1(String s) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] hash = new byte[40]; md.update(s.getBytes("iso-8859-1"), 0, s.length()); hash = md.digest(); return toHex(hash); } catch (Exception e) { e.printStackTrace(); return null; } } Code Sample 2: public static void copyFile(File source, File destination) { if (!source.exists()) { return; } if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) { destination.getParentFile().mkdirs(); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { ioe.printStackTrace(); } }
00
Code Sample 1: public SukuData updatePerson(String usertext, SukuData req) { String insPers; String userid = Utils.toUsAscii(usertext); if (userid != null && userid.length() > 16) { userid = userid.substring(0, 16); } StringBuilder sb = new StringBuilder(); sb.append("insert into unit (pid,tag,privacy,groupid,sex,sourcetext,privatetext,userrefn"); if (userid != null) { sb.append(",createdby"); } sb.append(") values (?,?,?,?,?,?,?,? "); if (userid != null) { sb.append(",'" + userid + "'"); } sb.append(")"); insPers = sb.toString(); String updPers; sb = new StringBuilder(); sb.append("update unit set privacy=?,groupid=?,sex=?,sourcetext=?," + "privatetext=?,userrefn=?,Modified=now()"); if (userid != null) { sb.append(",modifiedby = '" + userid + "' where pid = ?"); } else { sb.append(" where pid = ?"); } updPers = sb.toString(); sb = new StringBuilder(); String updSql; sb.append("update unitnotice set "); sb.append("surety=?,Privacy=?,NoticeType=?,Description=?,"); sb.append("DatePrefix=?,FromDate=?,ToDate=?,Place=?,"); sb.append("Village=?,Farm=?,Croft=?,Address=?,"); sb.append("PostalCode=?,PostOffice=?,State=?,Country=?,Email=?,"); sb.append("NoteText=?,MediaFilename=?,MediaTitle=?,Prefix=?,"); sb.append("Surname=?,Givenname=?,Patronym=?,PostFix=?,"); sb.append("SourceText=?,PrivateText=?,RefNames=?,RefPlaces=?,Modified=now()"); if (userid != null) { sb.append(",modifiedby = '" + userid + "'"); } sb.append(" where pnid = ?"); updSql = sb.toString(); sb = new StringBuilder(); String insSql; sb.append("insert into unitnotice ("); sb.append("surety,Privacy,NoticeType,Description,"); sb.append("DatePrefix,FromDate,ToDate,Place,"); sb.append("Village,Farm,Croft,Address,"); sb.append("PostalCode,PostOffice,State,Country,Email,"); sb.append("NoteText,MediaFilename,MediaTitle,Prefix,"); sb.append("Surname,Givenname,Patronym,PostFix,"); sb.append("SourceText,PrivateText,RefNames,Refplaces,pnid,pid,tag"); if (userid != null) { sb.append(",createdby"); } sb.append(") values ("); sb.append("?,?,?,?,?,?,?,?," + "?,?,?,?,?,?,?,?," + "?,?,?,?,?,?,?,?,"); sb.append("?,?,?,?,?,?,?,?"); if (userid != null) { sb.append(",'" + userid + "'"); } sb.append(")"); insSql = sb.toString(); sb = new StringBuilder(); String updLangSql; sb.append("update unitlanguage set "); sb.append("NoticeType=?,Description=?," + "Place=?,"); sb.append("NoteText=?,MediaTitle=?,Modified=now() "); if (userid != null) { sb.append(",modifiedby = '" + userid + "'"); } sb.append("where pnid=? and langCode = ?"); updLangSql = sb.toString(); sb = new StringBuilder(); String insLangSql; sb.append("insert into unitlanguage (pnid,pid,tag,langcode,"); sb.append("NoticeType,Description,Place,"); sb.append("NoteText,MediaTitle"); if (userid != null) { sb.append(",createdby"); } sb.append(") values (?,?,?,?,?,?,?,?,?"); if (userid != null) { sb.append(",'" + userid + "'"); } sb.append(")"); insLangSql = sb.toString(); String delOneLangSql = "delete from unitlanguage where pnid = ? and langcode = ? "; String updRowSql = "update unitnotice set noticerow = ? where pnid = ? "; String delSql = "delete from unitnotice where pnid = ? "; String delAllLangSql = "delete from Unitlanguage where pnid = ? "; SukuData res = new SukuData(); UnitNotice[] nn = req.persLong.getNotices(); if (nn != null) { String prevName = ""; String prevOccu = ""; for (int i = 0; i < nn.length; i++) { if (nn[i].getTag().equals("NAME")) { String thisName = Utils.nv(nn[i].getGivenname()) + "/" + Utils.nv(nn[i].getPatronym()) + "/" + Utils.nv(nn[i].getPrefix()) + "/" + Utils.nv(nn[i].getSurname()) + "/" + Utils.nv(nn[i].getPostfix()); if (thisName.equals(prevName) && !prevName.equals("")) { if (nn[i].isToBeDeleted() == false) { String e = Resurses.getString("IDENTICAL_NAMES_ERROR") + " [" + req.persLong.getPid() + "] idx [" + i + "] = " + thisName; logger.warning(e); if (req.persLong.getPid() > 0) { res.resu = e; return res; } } } prevName = thisName; } else if (nn[i].getTag().equals("OCCU")) { String thisOccu = Utils.nv(nn[i].getDescription()); if (thisOccu.equals(prevOccu) && !prevOccu.equals("")) { if (nn[i].isToBeDeleted() == false) { String e = Resurses.getString("IDENTICAL_OCCU_ERROR") + " [" + req.persLong.getPid() + "] idx [" + i + "] = '" + thisOccu + "'"; logger.warning(e); if (req.persLong.getPid() > 0) { res.resu = e; return res; } } } prevOccu = thisOccu; } } } int pid = 0; try { con.setAutoCommit(false); Statement stm; PreparedStatement pst; if (req.persLong.getPid() > 0) { res.resultPid = req.persLong.getPid(); pid = req.persLong.getPid(); if (req.persLong.isMainModified()) { if (req.persLong.getModified() == null) { pst = con.prepareStatement(updPers + " and modified is null "); } else { pst = con.prepareStatement(updPers + " and modified = ?"); } pst.setString(1, req.persLong.getPrivacy()); pst.setString(2, req.persLong.getGroupId()); pst.setString(3, req.persLong.getSex()); pst.setString(4, req.persLong.getSource()); pst.setString(5, req.persLong.getPrivateText()); pst.setString(6, req.persLong.getRefn()); pst.setInt(7, req.persLong.getPid()); if (req.persLong.getModified() != null) { pst.setTimestamp(8, req.persLong.getModified()); } int lukuri = pst.executeUpdate(); if (lukuri != 1) { logger.warning("Person update for pid " + pid + " failed [" + lukuri + "] (Should be 1)"); throw new SQLException("TRANSACTION_ERROR_1"); } String apara = null; String bpara = null; String cpara = null; String dpara = null; if (req.persLong.getSex().equals("M")) { apara = "FATH"; bpara = "MOTH"; cpara = "HUSB"; dpara = "WIFE"; } else if (req.persLong.getSex().equals("F")) { bpara = "FATH"; apara = "MOTH"; dpara = "HUSB"; cpara = "WIFE"; } if (apara != null) { String sqlParent = "update relation as b set tag=? " + "where b.rid in (select a.rid from relation as a " + "where a.pid = ? and a.pid <> b.rid and a.tag='CHIL') " + "and tag=?"; PreparedStatement ppare = con.prepareStatement(sqlParent); ppare.setString(1, apara); ppare.setInt(2, req.persLong.getPid()); ppare.setString(3, bpara); int resup = ppare.executeUpdate(); logger.fine("updated count for person parent= " + resup); String sqlSpouse = "update relation as b set tag=? " + "where b.rid in (select a.rid " + "from relation as a where a.pid = ? and a.pid <> b.pid " + "and a.tag in ('HUSB','WIFE')) and tag=?"; ppare = con.prepareStatement(sqlSpouse); ppare.setString(1, cpara); ppare.setInt(2, req.persLong.getPid()); ppare.setString(3, dpara); resup = ppare.executeUpdate(); logger.fine("updated count for person spouse= " + resup); } } } else { stm = con.createStatement(); ResultSet rs = stm.executeQuery("select nextval('unitseq')"); if (rs.next()) { pid = rs.getInt(1); res.resultPid = pid; } else { throw new SQLException("Sequence unitseq error"); } rs.close(); pst = con.prepareStatement(insPers); pst.setInt(1, pid); pst.setString(2, req.persLong.getTag()); pst.setString(3, req.persLong.getPrivacy()); pst.setString(4, req.persLong.getGroupId()); pst.setString(5, req.persLong.getSex()); pst.setString(6, req.persLong.getSource()); pst.setString(7, req.persLong.getPrivateText()); pst.setString(8, req.persLong.getRefn()); int lukuri = pst.executeUpdate(); if (lukuri != 1) { logger.warning("Person created for pid " + pid + " gave result " + lukuri); } } PreparedStatement pstDel = con.prepareStatement(delSql); PreparedStatement pstDelLang = con.prepareStatement(delAllLangSql); PreparedStatement pstUpdRow = con.prepareStatement(updRowSql); if (nn != null) { for (int i = 0; i < nn.length; i++) { UnitNotice n = nn[i]; int pnid = 0; if (n.isToBeDeleted()) { pstDelLang.setInt(1, n.getPnid()); int landelcnt = pstDelLang.executeUpdate(); pstDel.setInt(1, n.getPnid()); int delcnt = pstDel.executeUpdate(); if (delcnt != 1) { logger.warning("Person notice [" + n.getTag() + "]delete for pid " + pid + " failed [" + delcnt + "] (Should be 1)"); throw new SQLException("TRANSACTION_ERROR_2"); } String text = "Poistettiin " + delcnt + " riviä [" + landelcnt + "] kieliversiota pid = " + n.getPid() + " tag=" + n.getTag(); logger.fine(text); } else if (n.getPnid() == 0 || n.isToBeUpdated()) { if (n.getPnid() == 0) { stm = con.createStatement(); ResultSet rs = stm.executeQuery("select nextval('unitnoticeseq')"); if (rs.next()) { pnid = rs.getInt(1); } else { throw new SQLException("Sequence unitnoticeseq error"); } rs.close(); pst = con.prepareStatement(insSql); } else { if (n.getModified() == null) { pst = con.prepareStatement(updSql + " and modified is null "); } else { pst = con.prepareStatement(updSql + " and modified = ?"); } pnid = n.getPnid(); } if (n.isToBeUpdated() || n.getPnid() == 0) { pst.setInt(1, n.getSurety()); pst.setString(2, n.getPrivacy()); pst.setString(3, n.getNoticeType()); pst.setString(4, n.getDescription()); pst.setString(5, n.getDatePrefix()); pst.setString(6, n.getFromDate()); pst.setString(7, n.getToDate()); pst.setString(8, n.getPlace()); pst.setString(9, n.getVillage()); pst.setString(10, n.getFarm()); pst.setString(11, n.getCroft()); pst.setString(12, n.getAddress()); pst.setString(13, n.getPostalCode()); pst.setString(14, n.getPostOffice()); pst.setString(15, n.getState()); pst.setString(16, n.getCountry()); pst.setString(17, n.getEmail()); pst.setString(18, n.getNoteText()); pst.setString(19, n.getMediaFilename()); pst.setString(20, n.getMediaTitle()); pst.setString(21, n.getPrefix()); pst.setString(22, n.getSurname()); pst.setString(23, n.getGivenname()); pst.setString(24, n.getPatronym()); pst.setString(25, n.getPostfix()); pst.setString(26, n.getSource()); pst.setString(27, n.getPrivateText()); if (n.getRefNames() == null) { pst.setNull(28, Types.ARRAY); } else { Array xx = con.createArrayOf("varchar", n.getRefNames()); pst.setArray(28, xx); } if (n.getRefPlaces() == null) { pst.setNull(29, Types.ARRAY); } else { Array xx = con.createArrayOf("varchar", n.getRefPlaces()); pst.setArray(29, xx); } } if (n.getPnid() > 0) { pst.setInt(30, n.getPnid()); if (n.getModified() != null) { pst.setTimestamp(31, n.getModified()); } int luku = pst.executeUpdate(); if (luku != 1) { logger.warning("Person notice [" + n.getTag() + "] update for pid " + pid + " failed [" + luku + "] (Should be 1)"); throw new SQLException("TRANSACTION_ERROR_3"); } logger.fine("Päivitettiin " + luku + " tietuetta pnid=[" + n.getPnid() + "]"); } else { pst.setInt(30, pnid); pst.setInt(31, pid); pst.setString(32, n.getTag()); int luku = pst.executeUpdate(); logger.fine("Luotiin " + luku + " tietue pnid=[" + pnid + "]"); } if (n.getMediaData() == null) { String sql = "update unitnotice set mediadata = null where pnid = ?"; pst = con.prepareStatement(sql); pst.setInt(1, pnid); int lukuri = pst.executeUpdate(); if (lukuri != 1) { logger.warning("media deleted for pnid " + n.getPnid() + " gave result " + lukuri); } } else { String UPDATE_IMAGE_DATA = "update UnitNotice set MediaData = ?," + "mediaWidth = ?,mediaheight = ? where PNID = ? "; PreparedStatement ps = this.con.prepareStatement(UPDATE_IMAGE_DATA); ps.setBytes(1, n.getMediaData()); Dimension d = n.getMediaSize(); ps.setInt(2, d.width); ps.setInt(3, d.height); ps.setInt(4, pnid); ps.executeUpdate(); } } if (n.getLanguages() != null) { for (int l = 0; l < n.getLanguages().length; l++) { UnitLanguage ll = n.getLanguages()[l]; if (ll.isToBeDeleted()) { if (ll.getPnid() > 0) { pst = con.prepareStatement(delOneLangSql); pst.setInt(1, ll.getPnid()); pst.setString(2, ll.getLangCode()); int lukuri = pst.executeUpdate(); if (lukuri != 1) { logger.warning("language deleted for pnid " + n.getPnid() + " [" + ll.getLangCode() + "] gave result " + lukuri); } } } if (ll.isToBeUpdated()) { if (ll.getPnid() == 0) { pst = con.prepareStatement(insLangSql); pst.setInt(1, n.getPnid()); pst.setInt(2, pid); pst.setString(3, n.getTag()); pst.setString(4, ll.getLangCode()); pst.setString(5, ll.getNoticeType()); pst.setString(6, ll.getDescription()); pst.setString(7, ll.getPlace()); pst.setString(8, ll.getNoteText()); pst.setString(9, ll.getMediaTitle()); int lukuri = pst.executeUpdate(); if (lukuri != 1) { logger.warning("language added for pnid " + n.getPnid() + " [" + ll.getLangCode() + "] gave result " + lukuri); } } else { pst = con.prepareStatement(updLangSql); pst.setString(1, ll.getNoticeType()); pst.setString(2, ll.getDescription()); pst.setString(3, ll.getPlace()); pst.setString(4, ll.getNoteText()); pst.setString(5, ll.getMediaTitle()); pst.setInt(6, ll.getPnid()); pst.setString(7, ll.getLangCode()); int lukuri = pst.executeUpdate(); if (lukuri != 1) { logger.warning("language for pnid " + ll.getPnid() + " [" + ll.getLangCode() + "] gave result " + lukuri); } pst.close(); } } } } if (n.getPnid() > 0) { pnid = n.getPnid(); } pstUpdRow.setInt(1, i + 1); pstUpdRow.setInt(2, pnid); pstUpdRow.executeUpdate(); } } if (req.relations != null) { if (req.persLong.getPid() == 0) { req.persLong.setPid(pid); for (int i = 0; i < req.relations.length; i++) { Relation r = req.relations[i]; if (r.getPid() == 0) { r.setPid(pid); } } } updateRelations(userid, req); } con.commit(); } catch (Exception e) { try { con.rollback(); } catch (SQLException e1) { logger.log(Level.WARNING, "Person update rollback failed", e1); } logger.log(Level.WARNING, "person update rolled back for [" + pid + "]", e); res.resu = e.getMessage(); return res; } finally { try { con.setAutoCommit(true); } catch (SQLException e) { logger.log(Level.WARNING, "set autocommit failed", e); } } return res; } Code Sample 2: public static String MD5(String str, String encoding) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } messageDigest.reset(); try { messageDigest.update(str.getBytes(encoding)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } return md5StrBuff.toString(); }
00
Code Sample 1: public void run() { try { System.out.println("Setting page on Cobra"); SimpleHtmlRendererContext rendererContext = new SimpleHtmlRendererContext(htmlPanel, new SimpleUserAgentContext()); int nodeBaseEnd = furl.indexOf("/", 10); if (nodeBaseEnd == -1) nodeBaseEnd = furl.length(); String nodeBase = furl.substring(0, nodeBaseEnd); InputStream pageStream = new URL(furl).openStream(); BufferedReader pageStreamReader = new BufferedReader(new InputStreamReader(pageStream)); String pageContent = ""; String line; while ((line = pageStreamReader.readLine()) != null) pageContent += line; pageContent = borderImages(pageContent, nodeBase); htmlPanel.setHtml(pageContent, furl, rendererContext); } catch (Exception e) { System.out.println("Error loading page " + furl + " : " + e); } } Code Sample 2: public static boolean verify(String password, String encryptedPassword) { MessageDigest digest = null; int size = 0; String base64 = null; if (encryptedPassword.regionMatches(true, 0, "{CRYPT}", 0, 7)) { throw new InternalError("Not implemented"); } else if (encryptedPassword.regionMatches(true, 0, "{SHA}", 0, 5)) { size = 20; base64 = encryptedPassword.substring(5); try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{SSHA}", 0, 6)) { size = 20; base64 = encryptedPassword.substring(6); try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{MD5}", 0, 5)) { size = 16; base64 = encryptedPassword.substring(5); try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{SMD5}", 0, 6)) { size = 16; base64 = encryptedPassword.substring(6); try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else { return false; } byte[] data = Base64.decode(base64.toCharArray()); byte[] orig = new byte[size]; System.arraycopy(data, 0, orig, 0, size); digest.reset(); digest.update(password.getBytes()); if (data.length > size) { digest.update(data, size, data.length - size); } return MessageDigest.isEqual(digest.digest(), orig); }
00
Code Sample 1: public void execute() throws BuildException { Project proj = getProject(); if (templateFile == null) throw new BuildException("Template file not set"); if (targetFile == null) throw new BuildException("Target file not set"); try { File template = new File(templateFile); File target = new File(targetFile); if (!template.exists()) throw new BuildException("Template file does not exist " + template.toString()); if (!template.canRead()) throw new BuildException("Cannot read template file: " + template.toString()); if (((!append) && (!overwrite)) && (!target.exists())) throw new BuildException("Target file already exists and append and overwrite are false " + target.toString()); if (VERBOSE) { System.out.println("ProcessTemplate: tmpl in " + template.toString()); System.out.println("ProcessTemplate: file out " + target.toString()); } BufferedReader reader = new BufferedReader(new FileReader(template)); BufferedWriter writer = new BufferedWriter(new FileWriter(targetFile, append)); parse(reader, writer); writer.flush(); writer.close(); } catch (Exception e) { if (VERBOSE) e.printStackTrace(); throw new BuildException(e); } } Code Sample 2: public static String encryptPassword(String password) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { LOG.error(e); } try { md.update(password.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { LOG.error(e); } return (new BASE64Encoder()).encode(md.digest()); }
00
Code Sample 1: public void testSnapPullWithMasterUrl() throws Exception { copyFile(new File(CONF_DIR + "solrconfig-slave1.xml"), new File(slave.getConfDir(), "solrconfig.xml")); slaveJetty.stop(); slaveJetty = createJetty(slave); slaveClient = createNewSolrServer(slaveJetty.getLocalPort()); for (int i = 0; i < 500; i++) index(masterClient, "id", i, "name", "name = " + i); masterClient.commit(); NamedList masterQueryRsp = query("*:*", masterClient); SolrDocumentList masterQueryResult = (SolrDocumentList) masterQueryRsp.get("response"); assertEquals(500, masterQueryResult.getNumFound()); String masterUrl = "http://localhost:" + slaveJetty.getLocalPort() + "/solr/replication?command=fetchindex&masterUrl="; masterUrl += "http://localhost:" + masterJetty.getLocalPort() + "/solr/replication"; URL url = new URL(masterUrl); InputStream stream = url.openStream(); try { stream.close(); } catch (IOException e) { } Thread.sleep(3000); NamedList slaveQueryRsp = query("*:*", slaveClient); SolrDocumentList slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response"); assertEquals(500, slaveQueryResult.getNumFound()); String cmp = TestDistributedSearch.compare(masterQueryResult, slaveQueryResult, 0, null); assertEquals(null, cmp); } Code Sample 2: private final synchronized Vector<Class<?>> findSubclasses(URL location, String packageName, Class<?> superClass) { Map<Class<?>, URL> thisResult = new TreeMap<Class<?>, URL>(CLASS_COMPARATOR); Vector<Class<?>> v = new Vector<Class<?>>(); String fqcn = searchClass.getName(); List<URL> knownLocations = new ArrayList<URL>(); knownLocations.add(location); for (int loc = 0; loc < knownLocations.size(); loc++) { URL url = knownLocations.get(loc); File directory = new File(url.getFile()); if (directory.exists()) { String[] files = directory.list(); for (int i = 0; i < files.length; i++) if (files[i].endsWith(".class")) { String classname = files[i].substring(0, files[i].length() - 6); try { Class<?> c = Class.forName(packageName + "." + classname); if (superClass.isAssignableFrom(c) && !fqcn.equals(packageName + "." + classname)) thisResult.put(c, url); } catch (ClassNotFoundException cnfex) { errors.add(cnfex); } catch (Exception ex) { errors.add(ex); } } } else try { JarURLConnection conn = (JarURLConnection) url.openConnection(); JarFile jarFile = conn.getJarFile(); Enumeration<JarEntry> e = jarFile.entries(); while (e.hasMoreElements()) { JarEntry entry = e.nextElement(); String entryname = entry.getName(); if (!entry.isDirectory() && entryname.endsWith(".class")) { String classname = entryname.substring(0, entryname.length() - 6); if (classname.startsWith("/")) classname = classname.substring(1); classname = classname.replace('/', '.'); System.err.println("Trying " + classname); try { Class c = Class.forName(classname); if (superClass.isAssignableFrom(c) && !fqcn.equals(classname)) thisResult.put(c, url); } catch (ClassNotFoundException cnfex) { errors.add(cnfex); } catch (NoClassDefFoundError ncdfe) { errors.add(ncdfe); } catch (UnsatisfiedLinkError ule) { errors.add(ule); } catch (Exception exception) { errors.add(exception); } catch (Error error) { errors.add(error); } } } } catch (IOException ioex) { errors.add(ioex); } } results.putAll(thisResult); Iterator<Class<?>> it = thisResult.keySet().iterator(); while (it.hasNext()) v.add(it.next()); return v; }
00
Code Sample 1: public 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 void copyFile(File in, File out, boolean append) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out, append).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
00
Code Sample 1: public static void fileTrans(String filePath, String urlString, String urlString2, String serverIp, int port) { try { URL url = new URL(urlString); url.openStream(); } catch (Exception e) { e.printStackTrace(); } File file = new File(filePath); try { FileInputStream fis = new FileInputStream(file); Socket server = new Socket(InetAddress.getByName(serverIp), port); OutputStream outputStream = server.getOutputStream(); DataOutputStream dataOutputStream = new DataOutputStream(new BufferedOutputStream(outputStream)); byte[] buffer = new byte[2048]; int num = fis.read(buffer); while (num != -1) { dataOutputStream.write(buffer, 0, num); dataOutputStream.flush(); num = fis.read(buffer); } fis.close(); dataOutputStream.close(); server.close(); } catch (Exception e) { e.printStackTrace(); } try { URL url2 = new URL(urlString2); url2.openStream(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public Graph<N, E> read(final URL url) throws IOException { if (url == null) { throw new IllegalArgumentException("url must not be null"); } InputStream inputStream = null; try { inputStream = url.openStream(); return read(inputStream); } catch (IOException e) { throw e; } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException e) { } } }
00
Code Sample 1: private boolean adjust(String stationUrl) throws LastFMError { try { URL url = new URL("http://" + mBaseURL + "/adjust.php?session=" + mSession + "&url=" + URLEncoder.encode(stationUrl, "UTF-8")); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); InputStream is = conn.getInputStream(); InputStreamReader reader = new InputStreamReader(is); BufferedReader stringReader = new BufferedReader(reader); Utils.OptionsParser options = new Utils.OptionsParser(stringReader); if (!options.parse()) options = null; stringReader.close(); if ("OK".equals(options.get("response"))) { return true; } else { Log.e(TAG, "Adjust failed: \"" + options.get("response") + "\""); return false; } } catch (MalformedURLException e) { Log.e(TAG, "in adjust", e); throw new LastFMError("Adjust failed:" + e.toString()); } catch (UnsupportedEncodingException e) { Log.e(TAG, "in adjust", e); throw new LastFMError("Adjust failed:" + e.toString()); } catch (IOException e) { Log.e(TAG, "in adjust", e); throw new LastFMError("Station not found:" + stationUrl); } } Code Sample 2: @Override public final boolean exists() { try { final URLConnection uc = this.url.openConnection(); uc.connect(); uc.getInputStream().close(); return true; } catch (final IOException e) { return false; } }
11
Code Sample 1: private void foundNewVersion() { updater = new UpdaterView(); updater.setLabelText("Initiating Updater..."); updater.setProgress(0); updater.setLocationRelativeTo(null); updater.setVisible(true); URL pathUrl = ClassLoader.getSystemResource("img/icon.png"); String path = pathUrl.toString(); path = path.substring(4, path.length() - 14); try { file = new File(new URI(path)); updaterFile = new File(new URI(path.substring(0, path.length() - 4) + "Updater.jar")); if (updaterFile.exists()) { updaterFile.delete(); } updater.setProgress(25); SwingUtilities.invokeLater(new Runnable() { public void run() { try { FileChannel in = (new FileInputStream(file)).getChannel(); FileChannel out = (new FileOutputStream(updaterFile)).getChannel(); in.transferTo(0, file.length(), out); updater.setProgress(50); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } startUpdater(); } }); } catch (URISyntaxException e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "Update error! Could not create Updater. Check folder permission.", "Error", JOptionPane.ERROR_MESSAGE); } } Code Sample 2: public void copyJarContent(File jarPath, File targetDir) throws IOException { log.info("Copying natives from " + jarPath.getName()); JarFile jar = new JarFile(jarPath); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry file = entries.nextElement(); File f = new File(targetDir, file.getName()); log.info("Copying native - " + file.getName()); File parentFile = f.getParentFile(); parentFile.mkdirs(); if (file.isDirectory()) { f.mkdir(); continue; } InputStream is = null; FileOutputStream fos = null; try { is = jar.getInputStream(file); fos = new FileOutputStream(f); IOUtils.copy(is, fos); } finally { if (fos != null) fos.close(); if (is != null) is.close(); } } }
00
Code Sample 1: @Override public String resolveItem(String oldJpgFsPath) throws DatabaseException { if (oldJpgFsPath == null || "".equals(oldJpgFsPath)) throw new NullPointerException("oldJpgFsPath"); try { getConnection().setAutoCommit(false); } catch (SQLException e) { LOGGER.warn("Unable to set autocommit off", e); } PreparedStatement statement = null; String ret = null; try { statement = getConnection().prepareStatement(SELECT_ITEM_STATEMENT); statement.setString(1, oldJpgFsPath); ResultSet rs = statement.executeQuery(); int i = 0; int id = -1; int rowsAffected = 0; while (rs.next()) { id = rs.getInt("id"); ret = rs.getString("imageFile"); i++; } if (id != -1 && new File(ret).exists()) { statement = getConnection().prepareStatement(UPDATE_ITEM_STATEMENT); statement.setInt(1, id); rowsAffected = statement.executeUpdate(); } else { return null; } if (rowsAffected == 1) { getConnection().commit(); LOGGER.debug("DB has been updated."); } else { getConnection().rollback(); LOGGER.error("DB has not been updated -> rollback!"); } } catch (SQLException e) { LOGGER.error(e); } finally { closeConnection(); } return ret; } Code Sample 2: private void delay(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { String url = request.getRequestURL().toString(); if (delayed.contains(url)) { delayed.remove(url); LOGGER.info(MessageFormat.format("Loading delayed resource at url = [{0}]", url)); chain.doFilter(request, response); } else { LOGGER.info("Returning resource = [LoaderApplication.swf]"); InputStream input = null; OutputStream output = null; try { input = getClass().getResourceAsStream("LoaderApplication.swf"); output = response.getOutputStream(); delayed.add(url); response.setHeader("Cache-Control", "no-cache"); IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(input); } } }
11
Code Sample 1: private static void extract(ZipFile zipFile) throws Exception { FileUtils.deleteQuietly(WEBKIT_DIR); WEBKIT_DIR.mkdirs(); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) { new File(WEBKIT_DIR, entry.getName()).mkdirs(); continue; } InputStream inputStream = zipFile.getInputStream(entry); File outputFile = new File(WEBKIT_DIR, entry.getName()); FileOutputStream outputStream = new FileOutputStream(outputFile); IOUtils.copy(inputStream, outputStream); IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } } Code Sample 2: public void actionPerformed(ActionEvent e) { final File inputFile = KeyboardHero.midiFile(); try { if (inputFile == null) return; final File dir = (new File(Util.DATA_FOLDER + MidiSong.MIDI_FILES_DIR)); if (dir.exists()) { if (!dir.isDirectory()) { Util.error(Util.getMsg("Err_MidiFilesDirNotDirectory"), dir.getParent()); return; } } else if (!dir.mkdirs()) { Util.error(Util.getMsg("Err_CouldntMkDir"), dir.getParent()); return; } File outputFile = new File(dir.getPath() + File.separator + inputFile.getName()); if (!outputFile.exists() || KeyboardHero.confirm("Que_FileExistsOverwrite")) { final FileChannel inChannel = new FileInputStream(inputFile).getChannel(); inChannel.transferTo(0, inChannel.size(), new FileOutputStream(outputFile).getChannel()); } } catch (Exception ex) { Util.getMsg(Util.getMsg("Err_CouldntImportSong"), ex.toString()); } SongSelector.refresh(); }
00
Code Sample 1: private void process(int optind, String args[]) throws IOException, XMLStreamException { final int srlimit = 500; final QName att_title = new QName("title"); final QName att_sroffset = new QName("sroffset"); String sroffset = null; String srnamespace = null; if (!this.srnamespaces.isEmpty()) { StringBuilder sb = new StringBuilder(); for (Integer i : this.srnamespaces) { if (sb.length() > 0) sb.append("|"); sb.append(String.valueOf(i)); } srnamespace = sb.toString(); } StringBuilder terms = new StringBuilder(); while (optind < args.length) { if (terms.length() > 0) terms.append(" "); terms.append(args[optind++]); } while (true) { String url = this.base_api + "?action=query" + "&list=search" + "&format=xml" + "&srsearch=" + URLEncoder.encode(terms.toString(), "UTF-8") + (srnamespace != null ? "&srnamespace=" + srnamespace : "") + (sroffset == null ? "" : "&sroffset=" + sroffset) + "&srlimit=" + srlimit + "&srwhat=text&srprop=timestamp"; sroffset = null; LOG.info(url); XMLEventReader reader = this.xmlInputFactory.createXMLEventReader(openStream(url)); while (reader.hasNext()) { XMLEvent event = reader.nextEvent(); if (event.isStartElement()) { StartElement e = event.asStartElement(); String name = e.getName().getLocalPart(); Attribute att = null; if (name.equals("p") && (att = e.getAttributeByName(att_title)) != null) { System.out.println(att.getValue()); } else if (name.equals("search") && (att = e.getAttributeByName(att_sroffset)) != null) { sroffset = att.getValue(); } } } reader.close(); if (sroffset == null) break; } } Code Sample 2: private static final void copyFile(File srcFile, File destDir, byte[] buffer) { try { File destFile = new File(destDir, srcFile.getName()); InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); int bytesRead; while ((bytesRead = in.read(buffer)) != -1) out.write(buffer, 0, bytesRead); in.close(); out.close(); } catch (IOException ioe) { System.err.println("Couldn't copy file '" + srcFile + "' to directory '" + destDir + "'"); } }
00
Code Sample 1: public static Collection providers(Class service, ClassLoader loader) { List classList = new ArrayList(); List nameSet = new ArrayList(); String name = "META-INF/services/" + service.getName(); Enumeration services; try { services = (loader == null) ? ClassLoader.getSystemResources(name) : loader.getResources(name); } catch (IOException ioe) { System.err.println("Service: cannot load " + name); return classList; } while (services.hasMoreElements()) { URL url = (URL) services.nextElement(); InputStream input = null; BufferedReader reader = null; try { input = url.openStream(); reader = new BufferedReader(new InputStreamReader(input, "utf-8")); String line = reader.readLine(); while (line != null) { int ci = line.indexOf('#'); if (ci >= 0) line = line.substring(0, ci); line = line.trim(); int si = line.indexOf(' '); if (si >= 0) line = line.substring(0, si); line = line.trim(); if (line.length() > 0) { if (!nameSet.contains(line)) nameSet.add(line); } line = reader.readLine(); } } catch (IOException ioe) { System.err.println("Service: problem with: " + url); } finally { try { if (input != null) input.close(); if (reader != null) reader.close(); } catch (IOException ioe2) { System.err.println("Service: problem with: " + url); } } } Iterator names = nameSet.iterator(); while (names.hasNext()) { String className = (String) names.next(); try { classList.add(Class.forName(className, true, loader).newInstance()); } catch (ClassNotFoundException e) { System.err.println("Service: cannot find class: " + className); } catch (InstantiationException e) { System.err.println("Service: cannot instantiate: " + className); } catch (IllegalAccessException e) { System.err.println("Service: illegal access to: " + className); } catch (NoClassDefFoundError e) { System.err.println("Service: " + e + " for " + className); } catch (Exception e) { System.err.println("Service: exception for: " + className + " " + e); } } return classList; } Code Sample 2: public synchronized String encrypt(String plaintext) throws Exception { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new Exception(e.getMessage()); } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new Exception(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
00
Code Sample 1: public static String encodeString(String encodeType, String str) { if (encodeType.equals("md5of16")) { MD5 m = new MD5(); return m.getMD5ofStr16(str); } else if (encodeType.equals("md5of32")) { MD5 m = new MD5(); return m.getMD5ofStr(str); } else { try { MessageDigest gv = MessageDigest.getInstance(encodeType); gv.update(str.getBytes()); return new BASE64Encoder().encode(gv.digest()); } catch (java.security.NoSuchAlgorithmException e) { logger.error("BASE64加密失败", e); return null; } } } Code Sample 2: public String[] getFile() { List<String> records = new ArrayList<String>(); FTPClient ftp = new FTPClient(); try { int reply; FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX); ftp.configure(conf); ftp.connect(host, port); System.out.println("Connected to " + host + "."); System.out.print(ftp.getReplyString()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); } ftp.login(user, password); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused login."); } InputStream is = ftp.retrieveFileStream(remotedir + "/" + remotefile); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line = null; while ((line = br.readLine()) != null) { if (!line.equals("")) { records.add(line); } } br.close(); isr.close(); is.close(); ftp.logout(); } catch (IOException e) { e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { ioe.printStackTrace(); } } } return records.toArray(new String[0]); }
00
Code Sample 1: public static String hashString(String sPassword) { if (sPassword == null || sPassword.equals("")) { return "empty:"; } else { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(sPassword.getBytes("UTF-8")); byte[] res = md.digest(); return "sha1:" + byte2hex(res); } catch (NoSuchAlgorithmException e) { return "plain:" + sPassword; } catch (UnsupportedEncodingException e) { return "plain:" + sPassword; } } } Code Sample 2: public static boolean reportException(Throwable ex, HashMap<String, String> suppl) { if (Activator.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.P_CRASH_REPORTING)) { logger.debug("Report exception to devs..."); String data = "reportType=exception&" + "message=" + ex.getMessage(); data += "&build=" + Platform.getBundle("de.uni_mannheim.swt.codeconjurer").getHeaders().get("Bundle-Version"); int ln = 0; for (StackTraceElement el : ex.getStackTrace()) { data += "&st_line_" + ++ln + "=" + el.getClassName() + "#" + el.getMethodName() + "<" + el.getLineNumber() + ">"; } data += "&lines=" + ln; data += "&Suppl-Description=" + ex.toString(); data += "&Suppl-Server=" + Activator.getDefault().getPreferenceStore().getString(PreferenceConstants.P_SERVER); data += "&Suppl-User=" + Activator.getDefault().getPreferenceStore().getString(PreferenceConstants.P_USERNAME); if (suppl != null) { for (String key : suppl.keySet()) { data += "&Suppl-" + key + "=" + suppl.get(key); } } try { URL url = new URL("http://www.merobase.com:7777/org.code_conjurer.udc/CrashReport"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(data); writer.flush(); StringBuffer answer = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = reader.readLine()) != null) { answer.append(line + "\r\n"); } writer.close(); reader.close(); logger.debug(answer.toString()); } catch (Exception e) { logger.debug("Could not report exception"); return false; } return true; } else { logger.debug("Reporting not wished!"); return false; } }
00
Code Sample 1: private String httpGet(String urlString, boolean postStatus) throws Exception { URL url; URLConnection conn; String answer = ""; try { if (username.equals("") || password.equals("")) throw new AuthNotProvidedException(); url = new URL(urlString); conn = url.openConnection(); conn.setRequestProperty("Authorization", "Basic " + getAuthentificationString()); if (postStatus) { conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); DataOutputStream das = new DataOutputStream(conn.getOutputStream()); String content = "status=" + URLEncoder.encode(statusMessage, "UTF-8") + "&source=" + URLEncoder.encode("sametimetwitterclient", "UTF-8"); das.writeBytes(content); das.flush(); das.close(); } InputStream is = (InputStream) conn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; while ((line = br.readLine()) != null) { answer += line + "\n"; } br.close(); } catch (FileNotFoundException ex) { System.out.println(ex.toString()); throw new RuntimeException("Page not Found. Maybe Twitter-API has changed."); } catch (UnknownHostException ex) { System.out.println(ex.toString()); throw new RuntimeException("Network connection problems. Could not find twitter.com"); } catch (IOException ex) { System.out.println("IO-Exception"); if (ex.getMessage().indexOf("401") > -1) { authenthicated = AUTH_BAD; throw new AuthNotAcceptedException(); } System.out.println(ex.toString()); } if (checkForError(answer) != null) { throw new RuntimeException(checkForError(answer)); } authenthicated = AUTH_OK; return answer; } Code Sample 2: @Override protected Class<?> findClass(String name) throws ClassNotFoundException { String classFile = name.replace('.', '/') + ".class"; InputStream classInputStream = null; for (JarFile java3DJar : this.java3DJars) { JarEntry jarEntry = java3DJar.getJarEntry(classFile); if (jarEntry != null) { try { classInputStream = java3DJar.getInputStream(jarEntry); } catch (IOException ex) { throw new ClassNotFoundException("Couldn't read class " + name, ex); } } } if (classInputStream == null) { URL url = getResource(classFile); if (url == null) { throw new ClassNotFoundException("Class " + name); } try { classInputStream = url.openStream(); } catch (IOException ex) { throw new ClassNotFoundException("Couldn't read class " + name, ex); } } try { ByteArrayOutputStream out = new ByteArrayOutputStream(); BufferedInputStream in = new BufferedInputStream(classInputStream); byte[] buffer = new byte[8096]; int size; while ((size = in.read(buffer)) != -1) { out.write(buffer, 0, size); } in.close(); return defineClass(name, out.toByteArray(), 0, out.size(), this.protectionDomain); } catch (IOException ex) { throw new ClassNotFoundException("Class " + name, ex); } }
00
Code Sample 1: @RequestMapping("/import") public String importPicture(@ModelAttribute PictureImportCommand command) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); URL url = command.getUrl(); IOUtils.copy(url.openStream(), baos); byte[] imageData = imageFilterService.touchupImage(baos.toByteArray()); String filename = StringUtils.substringAfterLast(url.getPath(), "/"); String email = userService.getCurrentUser().getEmail(); Picture picture = new Picture(email, filename, command.getDescription(), imageData); pictureRepository.store(picture); return "redirect:/picture/gallery"; } Code Sample 2: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = random.nextLong(); } sbValueBeforeMD5.append(sid); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { } }
00
Code Sample 1: public static String getRolesString(HttpServletRequest hrequest, HttpServletResponse hresponse, String username, String servicekey) { String registerapp = SSOFilter.getRegisterapp(); String u = SSOUtil.addParameter(registerapp + "/api/getroles", "username", username); u = SSOUtil.addParameter(u, "servicekey", servicekey); String roles = ""; try { URL url = new URL(u); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { roles = line.trim(); } reader.close(); } catch (MalformedURLException e) { return null; } catch (IOException e) { return null; } if ("error".equals(roles)) { return ""; } return roles.trim(); } Code Sample 2: public static void main(String args[]) { org.apache.xml.security.Init.init(); String signatureFileName = args[0]; javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setAttribute("http://xml.org/sax/features/namespaces", Boolean.TRUE); try { long start = System.currentTimeMillis(); org.apache.xml.security.Init.init(); File f = new File(signatureFileName); System.out.println("Verifying " + signatureFileName); javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder(); org.w3c.dom.Document doc = db.parse(new java.io.FileInputStream(f)); VerifyExampleTest vf = new VerifyExampleTest(); vf.verify(doc); Constants.setSignatureSpecNSprefix("dsig"); Element sigElement = null; NodeList nodes = doc.getElementsByTagNameNS(org.apache.xml.security.utils.Constants.SignatureSpecNS, "Signature"); if (nodes.getLength() != 0) { System.out.println("Found " + nodes.getLength() + " Signature elements."); for (int i = 0; i < nodes.getLength(); i++) { sigElement = (Element) nodes.item(i); XMLSignature signature = new XMLSignature(sigElement, ""); KeyInfo ki = signature.getKeyInfo(); signature.addResourceResolver(new OfflineResolver()); if (ki != null) { if (ki.containsX509Data()) { System.out.println("Could find a X509Data element in the KeyInfo"); } KeyInfo kinfo = signature.getKeyInfo(); X509Certificate cert = null; if (kinfo.containsRetrievalMethod()) { RetrievalMethod m = kinfo.itemRetrievalMethod(0); URL url = new URL(m.getURI()); CertificateFactory cf = CertificateFactory.getInstance("X.509"); cert = (X509Certificate) cf.generateCertificate(url.openStream()); } else { cert = signature.getKeyInfo().getX509Certificate(); } if (cert != null) { System.out.println("The XML signature is " + (signature.checkSignatureValue(cert) ? "valid (good)" : "invalid !!!!! (bad)")); } else { System.out.println("Did not find a Certificate"); PublicKey pk = signature.getKeyInfo().getPublicKey(); if (pk != null) { System.out.println("The XML signatur is " + (signature.checkSignatureValue(pk) ? "valid (good)" : "invalid !!!!! (bad)")); } else { System.out.println("Did not find a public key, so I can't check the signature"); } } } else { System.out.println("Did not find a KeyInfo"); } } } long end = System.currentTimeMillis(); double elapsed = end - start; System.out.println("verified:" + elapsed); } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: public static byte[] ComputeForText(String ThisString) throws Exception { byte[] Result; MessageDigest MD5Hasher; MD5Hasher = MessageDigest.getInstance("MD5"); MD5Hasher.update(ThisString.replaceAll("\r", "").getBytes("iso-8859-1")); Result = MD5Hasher.digest(); return Result; } Code Sample 2: private static String getProviderName(URL url, PrintStream err) { InputStream in = null; try { in = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8")); String result = null; while (true) { String line = reader.readLine(); if (line == null) { break; } int commentPos = line.indexOf('#'); if (commentPos >= 0) { line = line.substring(0, commentPos); } line = line.trim(); int len = line.length(); if (len != 0) { if (result != null) { print(err, "checkconfig.multiproviders", url.toString()); return null; } result = line; } } if (result == null) { print(err, "checkconfig.missingprovider", url.toString()); return null; } return result; } catch (IOException e) { print(err, "configconfig.read", url.toString(), e); return null; } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } }
00
Code Sample 1: private List _getWeathersFromYahoo(String city) { System.out.println("== get weather information of " + city + " from yahoo =="); try { URL url = new URL(URL + cities.get(city).toString()); InputStream input = url.openStream(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(false); SAXParser parser = factory.newSAXParser(); YahooHandler yh = new YahooHandler(); yh.setCity(city); parser.parse(input, yh); return yh.getWeathers(); } catch (MalformedURLException e) { throw new WeatherException("MalformedURLException"); } catch (IOException e) { throw new WeatherException("无法读取数据。"); } catch (ParserConfigurationException e) { throw new WeatherException("ParserConfigurationException"); } catch (SAXException e) { throw new WeatherException("数据格式错误,无法解析。"); } } Code Sample 2: private String hash(String clearPassword) { if (salt == 0) return null; MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e) { throw new AssertionError("Can't find the SHA1 algorithm in the java.security package"); } String saltString = String.valueOf(salt); md.update(saltString.getBytes()); md.update(clearPassword.getBytes()); byte[] digestBytes = md.digest(); StringBuffer digestSB = new StringBuffer(); for (int i = 0; i < digestBytes.length; i++) { int lowNibble = digestBytes[i] & 0x0f; int highNibble = (digestBytes[i] >> 4) & 0x0f; digestSB.append(Integer.toHexString(highNibble)); digestSB.append(Integer.toHexString(lowNibble)); } String digestStr = digestSB.toString(); return digestStr; }
11
Code Sample 1: public void newGuidSeed(boolean secure) { SecureRandom sr = new SecureRandom(); long secureInitializer = sr.nextLong(); Random rand = new Random(secureInitializer); String host_ip = ""; try { host_ip = InetAddress.getLocalHost().toString(); } catch (UnknownHostException err) { err.printStackTrace(); } MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException err) { err.printStackTrace(); } try { long time = System.currentTimeMillis(); long randNumber = 0; if (secure) { randNumber = sr.nextLong(); } else { randNumber = rand.nextLong(); } sbBeforeMd5.append(host_ip); sbBeforeMd5.append(":"); sbBeforeMd5.append(Long.toString(time)); sbBeforeMd5.append(":"); sbBeforeMd5.append(Long.toString(randNumber)); seed = sbBeforeMd5.toString(); md5.update(seed.getBytes()); byte[] array = md5.digest(); StringBuffer temp_sb = new StringBuffer(); for (int i = 0; i < array.length; i++) { int b = array[i] & 0xFF; if (b < 0x10) temp_sb.append('0'); temp_sb.append(Integer.toHexString(b)); } rawGUID = temp_sb.toString(); } catch (Exception err) { err.printStackTrace(); } } Code Sample 2: public static String generateHash(String msg) throws NoSuchAlgorithmException { if (msg == null) { throw new IllegalArgumentException("Input string can not be null"); } MessageDigest m = MessageDigest.getInstance("MD5"); m.reset(); m.update(msg.getBytes()); byte[] digest = m.digest(); BigInteger bigInt = new BigInteger(1, digest); String hashText = bigInt.toString(16); while (hashText.length() < 32) { hashText = "0" + hashText; } return hashText; }
00
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public T02OTSUnitTestCase(String name) throws java.io.IOException { super(name); java.net.URL url = ClassLoader.getSystemResource("host0.cosnaming.jndi.properties"); jndiProps = new java.util.Properties(); jndiProps.load(url.openStream()); }
11
Code Sample 1: private static String getDigest(String srcStr, String alg) { Assert.notNull(srcStr); Assert.notNull(alg); try { MessageDigest alga = MessageDigest.getInstance(alg); alga.update(srcStr.getBytes()); byte[] digesta = alga.digest(); return byte2hex(digesta); } catch (Exception e) { throw new RuntimeException(e); } } Code Sample 2: public static String getEncryptedPwd(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException { byte[] pwd = null; SecureRandom random = new SecureRandom(); byte[] salt = new byte[SALT_LENGTH]; random.nextBytes(salt); MessageDigest md = null; md = MessageDigest.getInstance("MD5"); md.update(salt); md.update(password.getBytes("UTF-8")); byte[] digest = md.digest(); pwd = new byte[digest.length + SALT_LENGTH]; System.arraycopy(salt, 0, pwd, 0, SALT_LENGTH); System.arraycopy(digest, 0, pwd, SALT_LENGTH, digest.length); return byteToHexString(pwd); }
11
Code Sample 1: private static void copyFile(File sourceFile, File destFile) throws IOException { System.out.println(sourceFile.getAbsolutePath()); System.out.println(destFile.getAbsolutePath()); FileChannel source = new FileInputStream(sourceFile).getChannel(); try { FileChannel destination = new FileOutputStream(destFile).getChannel(); try { destination.transferFrom(source, 0, source.size()); } finally { if (destination != null) { destination.close(); } } } finally { source.close(); } } Code Sample 2: protected static String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); URLConnection c = url.openConnection(); c.setConnectTimeout(2000); IOUtils.copy(c.getInputStream(), output); return output.toString(); }
11
Code Sample 1: public static void copy(File source, File dest) throws IOException { if (dest.isDirectory()) { dest = new File(dest + File.separator + source.getName()); } FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } } Code Sample 2: private void processHelpFile() { InputStream in = null; if (line.hasOption("helpfile")) { OutputStream out = null; try { String filename = line.getOptionValue("helpfile"); in = new FileInputStream(filename); filename = filename.replace('\\', '/'); filename = filename.substring(filename.lastIndexOf('/') + 1); File outFile = new File(outputDir, filename); if (LOG.isInfoEnabled()) { LOG.info("Processing generated file " + outFile.getAbsolutePath()); } out = new FileOutputStream(outFile); baseProperties.setProperty("helpfile", filename); IOUtils.copy(in, out); } catch (FileNotFoundException e) { LOG.error(e.getMessage(), e); } catch (IOException e) { LOG.error(e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } if (out != null) { try { out.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } return; } Properties props = new Properties(baseProperties); ClassLoader cl = this.getClass().getClassLoader(); Document doc = null; try { in = cl.getResourceAsStream(RESOURCE_PKG + "/help-doc.xml"); doc = XmlUtils.parse(in); } catch (XmlException e) { LOG.error(e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } transformResource(doc, "help-doc.xsl", props, "help-doc.html"); baseProperties.setProperty("helpfile", "help-doc.html"); }
00
Code Sample 1: public Book importFromURL(URL url) { InputStream is = null; try { is = url.openStream(); return importFromStream(is, url.toString()); } catch (Exception ex) { throw ModelException.Aide.wrap(ex); } finally { if (is != null) { try { is.close(); } catch (IOException ex) { throw ModelException.Aide.wrap(ex); } } } } Code Sample 2: public String sendXml(URL url, String xmlMessage, boolean isResponseExpected) throws IOException { if (url == null) { throw new IllegalArgumentException("url == null"); } if (xmlMessage == null) { throw new IllegalArgumentException("xmlMessage == null"); } LOGGER.finer("url = " + url); LOGGER.finer("xmlMessage = :" + xmlMessage + ":"); LOGGER.finer("isResponseExpected = " + isResponseExpected); String answer = null; try { URLConnection urlConnection = url.openConnection(); urlConnection.setRequestProperty("Content-type", "text/xml"); urlConnection.setDoOutput(true); urlConnection.setUseCaches(false); Writer writer = null; try { writer = new OutputStreamWriter(urlConnection.getOutputStream()); writer.write(xmlMessage); writer.flush(); } finally { if (writer != null) { writer.close(); } } LOGGER.finer("message written"); StringBuilder sb = new StringBuilder(); BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); if (isResponseExpected) { String inputLine; while ((inputLine = in.readLine()) != null) { sb.append(inputLine).append("\n"); } answer = sb.toString(); LOGGER.finer("response read"); } } catch (FileNotFoundException e) { LOGGER.log(Level.SEVERE, "No response", e); } finally { if (in != null) { in.close(); } } } catch (ConnectException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } LOGGER.finer("answer = :" + answer + ":"); return answer; }