label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: public static String digest(String algorithm, String text) { MessageDigest mDigest = null; try { mDigest = MessageDigest.getInstance(algorithm); mDigest.update(text.getBytes(ENCODING)); } catch (NoSuchAlgorithmException nsae) { _log.error(nsae, nsae); } catch (UnsupportedEncodingException uee) { _log.error(uee, uee); } byte[] raw = mDigest.digest(); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(raw); } Code Sample 2: public void get(String path, File fileToGet) throws IOException { FTPClient ftp = new FTPClient(); try { int reply = 0; ftp.connect(this.endpointURL, this.endpointPort); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); throw new IOException("Ftp get server refused connection."); } if (!ftp.login("anonymous", "")) { ftp.logout(); throw new IOException("FTP: server wrong passwd"); } ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); OutputStream output = new FileOutputStream(fileToGet.getName()); if (ftp.retrieveFile(path, output) != true) { ftp.logout(); output.close(); throw new IOException("FTP get exception, maybe file not found"); } ftp.logout(); } catch (Exception e) { throw new IOException(e.getMessage()); } }
00
Code Sample 1: public static void copyFile3(File srcFile, File destFile) throws IOException { InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); byte[] buf = new byte[1024]; int len; while((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); } Code Sample 2: protected InputStream transform(URL url) throws IOException { TransformerFactory tf = TransformerFactory.newInstance(); InputStream xsl_is = null; InputStream url_is = null; ByteArrayOutputStream os = null; byte[] output; try { xsl_is = Classes.getThreadClassLoader().getResourceAsStream(getStylesheet()); url_is = new BufferedInputStream(url.openStream()); os = new ByteArrayOutputStream(); Transformer tr = tf.newTransformer(new StreamSource(xsl_is)); tr.transform(new StreamSource(url_is), new StreamResult(os)); output = os.toByteArray(); } catch (TransformerConfigurationException tce) { throw new IOException(tce.getLocalizedMessage()); } catch (TransformerException te) { throw new IOException(te.getLocalizedMessage()); } finally { try { if (os != null) os.close(); } catch (Throwable t) { } try { if (url_is != null) url_is.close(); } catch (Throwable t) { } try { if (xsl_is != null) xsl_is.close(); } catch (Throwable t) { } } if (logService.isEnabledFor(LogLevel.TRACE)) logService.log(LogLevel.TRACE, new String(output)); return new ByteArrayInputStream(output); }
00
Code Sample 1: private String mkSid() { String temp = toString(); MessageDigest messagedigest = null; try { messagedigest = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } messagedigest.update(temp.getBytes()); byte digest[] = messagedigest.digest(); String chk = ""; for (int i = 0; i < digest.length; i++) { String s = Integer.toHexString(digest[i] & 0xFF); chk += ((s.length() == 1) ? "0" + s : s); } return chk.toString(); } Code Sample 2: private static String getSuitableWCSVersion(String host, String _version) throws ConnectException, IOException { String request = WCSProtocolHandler.buildCapabilitiesSuitableVersionRequest(host, _version); String version = new String(); StringReader reader = null; DataInputStream dis = null; try { URL url = new URL(request); byte[] buffer = new byte[1024]; dis = new DataInputStream(url.openStream()); dis.readFully(buffer); reader = new StringReader(new String(buffer)); KXmlParser kxmlParser = null; kxmlParser = new KXmlParser(); kxmlParser.setInput(reader); kxmlParser.nextTag(); if (kxmlParser.getEventType() != KXmlParser.END_DOCUMENT) { if ((kxmlParser.getName().compareTo(CapabilitiesTags.WCS_CAPABILITIES_ROOT1_0_0) == 0)) { version = kxmlParser.getAttributeValue("", CapabilitiesTags.VERSION); } } reader.close(); dis.close(); return version; } catch (ConnectException conEx) { throw new ConnectException(conEx.getMessage()); } catch (IOException ioEx) { throw new IOException(ioEx.getMessage()); } catch (XmlPullParserException xmlEx) { xmlEx.printStackTrace(); return ""; } finally { if (reader != null) { try { reader.close(); } catch (Exception ex) { ex.printStackTrace(); } } if (dis != null) { try { dis.close(); } catch (Exception ex) { ex.printStackTrace(); } } } }
00
Code Sample 1: @Override public void run() { try { bitmapDrawable = new BitmapDrawable(new URL(url).openStream()); imageCache.put(id, new SoftReference<Drawable>(bitmapDrawable)); log("image::: put: id = " + id + " "); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } handler.post(new Runnable() { @Override public void run() { iv.setImageDrawable(bitmapDrawable); } }); } Code Sample 2: @Override public void sendData(String serverUrl, String fileName, String type, InputStream is) throws IOException { ClientSession clientSession = null; try { if (logger.isDebugEnabled()) { logger.debug("Connecting to " + serverUrl); } clientSession = (ClientSession) Connector.open(serverUrl); HeaderSet hsConnectReply = clientSession.connect(clientSession.createHeaderSet()); if (hsConnectReply.getResponseCode() != ResponseCodes.OBEX_HTTP_OK) { throw new IOException("Connect Error " + hsConnectReply.getResponseCode()); } HeaderSet hsOperation = clientSession.createHeaderSet(); hsOperation.setHeader(HeaderSet.NAME, fileName); if (type != null) { hsOperation.setHeader(HeaderSet.TYPE, type); } hsOperation.setHeader(HeaderSet.LENGTH, new Long(is.available())); Operation po = clientSession.put(hsOperation); OutputStream os = po.openOutputStream(); IOUtils.copy(is, os); os.flush(); os.close(); if (logger.isDebugEnabled()) { logger.debug("put responseCode " + po.getResponseCode()); } po.close(); HeaderSet hsDisconnect = clientSession.disconnect(null); if (logger.isDebugEnabled()) { logger.debug("disconnect responseCode " + hsDisconnect.getResponseCode()); } if (hsDisconnect.getResponseCode() != ResponseCodes.OBEX_HTTP_OK) { throw new IOException("Send Error " + hsConnectReply.getResponseCode()); } } finally { if (clientSession != null) { try { clientSession.close(); } catch (IOException ignore) { if (logger.isDebugEnabled()) { logger.debug("IOException during clientSession.close()", ignore); } } } clientSession = null; } }
11
Code Sample 1: @Override public RServiceResponse execute(final NexusServiceRequest inData) throws NexusServiceException { final RServiceRequest data = (RServiceRequest) inData; final RServiceResponse retval = new RServiceResponse(); final StringBuilder result = new StringBuilder("R service call results:\n"); RSession session; RConnection connection = null; try { result.append("Session Attachment: \n"); final byte[] sessionBytes = data.getSession(); if (sessionBytes != null && sessionBytes.length > 0) { session = RUtils.getInstance().bytesToSession(sessionBytes); result.append(" attaching to " + session + "\n"); connection = session.attach(); } else { result.append(" creating new session\n"); connection = new RConnection(data.getServerAddress()); } result.append("Input Parameters: \n"); for (String attributeName : data.getInputVariables().keySet()) { final Object parameter = data.getInputVariables().get(attributeName); if (parameter instanceof URI) { final FileObject file = VFS.getManager().resolveFile(((URI) parameter).toString()); final RFileOutputStream ros = connection.createFile(file.getName().getBaseName()); IOUtils.copy(file.getContent().getInputStream(), ros); connection.assign(attributeName, file.getName().getBaseName()); } else { connection.assign(attributeName, RUtils.getInstance().convertToREXP(parameter)); } result.append(" " + parameter.getClass().getSimpleName() + " " + attributeName + "=" + parameter + "\n"); } final REXP rExpression = connection.eval(RUtils.getInstance().wrapCode(data.getCode().replace('\r', '\n'))); result.append("Execution results:\n" + rExpression.asString() + "\n"); if (rExpression.isNull() || rExpression.asString().startsWith("Error")) { retval.setErr(rExpression.asString()); throw new NexusServiceException("R error: " + rExpression.asString()); } result.append("Output Parameters:\n"); final String[] rVariables = connection.eval("ls();").asStrings(); for (String varname : rVariables) { final String[] rVariable = connection.eval("class(" + varname + ")").asStrings(); if (rVariable.length == 2 && "file".equals(rVariable[0]) && "connection".equals(rVariable[1])) { final String rFileName = connection.eval("showConnections(TRUE)[" + varname + "]").asString(); result.append(" R File ").append(varname).append('=').append(rFileName).append('\n'); final RFileInputStream rInputStream = connection.openFile(rFileName); final File file = File.createTempFile("nexus-" + data.getRequestId(), ".dat"); IOUtils.copy(rInputStream, new FileOutputStream(file)); retval.getOutputVariables().put(varname, file.getCanonicalFile().toURI()); } else { final Object varvalue = RUtils.getInstance().convertREXP(connection.eval(varname)); retval.getOutputVariables().put(varname, varvalue); final String printValue = varvalue == null ? "null" : varvalue.getClass().isArray() ? Arrays.asList(varvalue).toString() : varvalue.toString(); result.append(" ").append(varvalue == null ? "" : varvalue.getClass().getSimpleName()).append(' ').append(varname).append('=').append(printValue).append('\n'); } } } catch (ClassNotFoundException cnfe) { retval.setErr(cnfe.getMessage()); LOGGER.error("Rserve Exception", cnfe); } catch (RserveException rse) { retval.setErr(rse.getMessage()); LOGGER.error("Rserve Exception", rse); } catch (REXPMismatchException rme) { retval.setErr(rme.getMessage()); LOGGER.error("REXP Mismatch Exception", rme); } catch (IOException rme) { retval.setErr(rme.getMessage()); LOGGER.error("IO Exception copying file ", rme); } finally { result.append("Session Detachment:\n"); if (connection != null) { RSession outSession; if (retval.isKeepSession()) { try { outSession = connection.detach(); } catch (RserveException e) { LOGGER.debug("Error detaching R session", e); outSession = null; } } else { outSession = null; } final boolean close = outSession == null; if (!close) { retval.setSession(RUtils.getInstance().sessionToBytes(outSession)); result.append(" suspended session for later use\n"); } connection.close(); retval.setSession(null); result.append(" session closed.\n"); } } retval.setOut(result.toString()); return retval; } Code Sample 2: private FileLog(LOG_LEVEL displayLogLevel, LOG_LEVEL logLevel, String logPath) { this.logLevel = logLevel; this.displayLogLevel = displayLogLevel; if (null != logPath) { logFile = new File(logPath, "current.log"); log(LOG_LEVEL.DEBUG, "FileLog", "Initialising logfile " + logFile.getAbsolutePath() + " ."); try { if (logFile.exists()) { if (!logFile.renameTo(new File(logPath, System.currentTimeMillis() + ".log"))) { File newFile = new File(logPath, System.currentTimeMillis() + ".log"); if (newFile.exists()) { log(LOG_LEVEL.WARN, "FileLog", "The file (" + newFile.getAbsolutePath() + newFile.getName() + ") already exists, will overwrite it."); newFile.delete(); } newFile.createNewFile(); FileInputStream inStream = new FileInputStream(logFile); FileOutputStream outStream = new FileOutputStream(newFile); byte buffer[] = null; int offSet = 0; while (inStream.read(buffer, offSet, 2048) != -1) { outStream.write(buffer); offSet += 2048; } inStream.close(); outStream.close(); logFile.delete(); logFile = new File(logPath, "current.log"); } } logFile.createNewFile(); } catch (IOException e) { logFile = null; } } else { logFile = null; } }
11
Code Sample 1: public void transport(File file) throws TransportException { if (file.exists()) { if (file.isDirectory()) { File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { transport(file); } } else if (file.isFile()) { try { FileChannel inChannel = new FileInputStream(file).getChannel(); FileChannel outChannel = new FileOutputStream(getOption("destination")).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { log.error("File transfer failed", e); } } } } Code Sample 2: public static void copy(String file1, String file2) throws IOException { File inputFile = new File(file1); File outputFile = new File(file2); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); System.out.println("Copy file from: " + file1 + " to: " + file2); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: private static void copyFile(File sourceFile, File targetFile) throws FileSaveException { try { FileInputStream inputStream = new FileInputStream(sourceFile); FileOutputStream outputStream = new FileOutputStream(targetFile); FileChannel readableChannel = inputStream.getChannel(); FileChannel writableChannel = outputStream.getChannel(); writableChannel.truncate(0); writableChannel.transferFrom(readableChannel, 0, readableChannel.size()); inputStream.close(); outputStream.close(); } catch (IOException ioException) { String exceptionMessage = "An error occurred when copying from the file \"" + sourceFile.getAbsolutePath() + "\" to the file \"" + targetFile.getAbsolutePath() + "\"."; throw new FileSaveException(exceptionMessage, ioException); } }
11
Code Sample 1: public Object construct() { String fullName = lRegatta.getSaveDirectory() + lRegatta.getSaveName(); System.out.println(MessageFormat.format(res.getString("MainMessageBackingUp"), new Object[] { fullName + BAK })); try { FileInputStream fis = new FileInputStream(new File(fullName)); FileOutputStream fos = new FileOutputStream(new File(fullName + BAK)); int bufsize = 1024; byte[] buffer = new byte[bufsize]; int n = 0; while ((n = fis.read(buffer, 0, bufsize)) >= 0) fos.write(buffer, 0, n); fos.flush(); fos.close(); } catch (java.io.IOException ex) { Util.showError(ex, true); } return null; } Code Sample 2: public static void copy(final File src, File dst, final boolean overwrite) throws IOException, IllegalArgumentException { if (!src.isFile() || !src.exists()) { throw new IllegalArgumentException("Source file '" + src.getAbsolutePath() + "' not found!"); } if (dst.exists()) { if (dst.isDirectory()) { dst = new File(dst, src.getName()); } else if (dst.isFile()) { if (!overwrite) { throw new IllegalArgumentException("Destination file '" + dst.getAbsolutePath() + "' already exists!"); } } else { throw new IllegalArgumentException("Invalid destination object '" + dst.getAbsolutePath() + "'!"); } } final File dstParent = dst.getParentFile(); if (!dstParent.exists()) { if (!dstParent.mkdirs()) { throw new IOException("Failed to create directory " + dstParent.getAbsolutePath()); } } long fileSize = src.length(); if (fileSize > 20971520l) { final FileInputStream in = new FileInputStream(src); final FileOutputStream out = new FileOutputStream(dst); try { int doneCnt = -1; final int bufSize = 32768; final byte buf[] = new byte[bufSize]; while ((doneCnt = in.read(buf, 0, bufSize)) >= 0) { if (doneCnt == 0) { Thread.yield(); } else { out.write(buf, 0, doneCnt); } } out.flush(); } finally { try { in.close(); } catch (final IOException e) { } try { out.close(); } catch (final IOException e) { } } } else { final FileInputStream fis = new FileInputStream(src); final FileOutputStream fos = new FileOutputStream(dst); final FileChannel in = fis.getChannel(), out = fos.getChannel(); try { long offs = 0, doneCnt = 0; final long copyCnt = Math.min(65536, fileSize); do { doneCnt = in.transferTo(offs, copyCnt, out); offs += doneCnt; fileSize -= doneCnt; } while (fileSize > 0); } finally { try { in.close(); } catch (final IOException e) { } try { out.close(); } catch (final IOException e) { } try { fis.close(); } catch (final IOException e) { } try { fos.close(); } catch (final IOException e) { } } } }
00
Code Sample 1: public void go() throws FBConnectionException, FBErrorException, IOException { clearError(); results = new LoginResults(); URL url = new URL(getHost() + getPath()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("X-FB-User", getUser()); conn.setRequestProperty("X-FB-Auth", makeResponse()); conn.setRequestProperty("X-FB-Mode", "Login"); conn.setRequestProperty("X-FB-Login.ClientVersion", agent); conn.connect(); Element fbresponse; try { fbresponse = readXML(conn); } catch (FBConnectionException fbce) { throw fbce; } catch (FBErrorException fbee) { throw fbee; } catch (Exception e) { FBConnectionException fbce = new FBConnectionException("XML parsing failed"); fbce.attachSubException(e); throw fbce; } NodeList nl = fbresponse.getElementsByTagName("LoginResponse"); for (int i = 0; i < nl.getLength(); i++) { if (nl.item(i) instanceof Element && hasError((Element) nl.item(i))) { error = true; FBErrorException e = new FBErrorException(); e.setErrorCode(errorcode); e.setErrorText(errortext); throw e; } } results.setMessage(DOMUtil.getAllElementText(fbresponse, "Message")); results.setServerTime(DOMUtil.getAllElementText(fbresponse, "ServerTime")); NodeList quotas = fbresponse.getElementsByTagName("Quota"); for (int i = 0; i < quotas.getLength(); i++) { if (quotas.item(i) instanceof Node) { NodeList children = quotas.item(i).getChildNodes(); for (int j = 0; j < children.getLength(); j++) { if (children.item(j) instanceof Element) { Element working = (Element) children.item(j); if (working.getNodeName().equals("Remaining")) { try { results.setQuotaRemaining(Long.parseLong(DOMUtil.getSimpleElementText(working))); } catch (Exception e) { } } if (working.getNodeName().equals("Used")) { try { results.setQuotaUsed(Long.parseLong(DOMUtil.getSimpleElementText(working))); } catch (Exception e) { } } if (working.getNodeName().equals("Total")) { try { results.setQuotaTotal(Long.parseLong(DOMUtil.getSimpleElementText(working))); } catch (Exception e) { } } } } } } results.setRawXML(getLastRawXML()); return; } Code Sample 2: public ScoreModel(URL url) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line; list = new ArrayList<ScoreModelItem>(); map = new HashMap<String, ScoreModelItem>(); line = in.readLine(); int n = 1; String[] rowAttrib; ScoreModelItem item; while ((line = in.readLine()) != null) { rowAttrib = line.split(";"); item = new ScoreModelItem(n, Double.valueOf(rowAttrib[3]), Double.valueOf(rowAttrib[4]), Double.valueOf(rowAttrib[2]), Double.valueOf(rowAttrib[5]), rowAttrib[1]); list.add(item); map.put(item.getHash(), item); n++; } in.close(); }
00
Code Sample 1: private void addJarToPackages(URL jarurl, File jarfile, boolean cache) { try { boolean caching = this.jarfiles != null; URLConnection jarconn = null; boolean localfile = true; if (jarfile == null) { jarconn = jarurl.openConnection(); if (jarconn.getURL().getProtocol().equals("file")) { String jarfilename = jarurl.getFile(); jarfilename = jarfilename.replace('/', File.separatorChar); jarfile = new File(jarfilename); } else { localfile = false; } } if (localfile && !jarfile.exists()) { return; } Hashtable zipPackages = null; long mtime = 0; String jarcanon = null; JarXEntry entry = null; boolean brandNew = false; if (caching) { if (localfile) { mtime = jarfile.lastModified(); jarcanon = jarfile.getCanonicalPath(); } else { mtime = jarconn.getLastModified(); jarcanon = jarurl.toString(); } entry = (JarXEntry) this.jarfiles.get(jarcanon); if ((entry == null || !(new File(entry.cachefile).exists())) && cache) { message("processing new jar, '" + jarcanon + "'"); String jarname; if (localfile) { jarname = jarfile.getName(); } else { jarname = jarurl.getFile(); int slash = jarname.lastIndexOf('/'); if (slash != -1) jarname = jarname.substring(slash + 1); } jarname = jarname.substring(0, jarname.length() - 4); entry = new JarXEntry(jarname); this.jarfiles.put(jarcanon, entry); brandNew = true; } if (mtime != 0 && entry != null && entry.mtime == mtime) { zipPackages = readCacheFile(entry, jarcanon); } } if (zipPackages == null) { caching = caching && cache; if (caching) { this.indexModified = true; if (entry.mtime != 0) { message("processing modified jar, '" + jarcanon + "'"); } entry.mtime = mtime; } InputStream jarin; if (jarconn == null) { jarin = new BufferedInputStream(new FileInputStream(jarfile)); } else { jarin = jarconn.getInputStream(); } zipPackages = getZipPackages(jarin); if (caching) { writeCacheFile(entry, jarcanon, zipPackages, brandNew); } } addPackages(zipPackages, jarcanon); } catch (IOException ioe) { ioe.printStackTrace(); warning("skipping bad jar, '" + (jarfile != null ? jarfile.toString() : jarurl.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(); }
00
Code Sample 1: private void handleSSI(HttpData data) throws HttpError, IOException { File tempFile = TempFileHandler.getTempFile(); FileOutputStream out = new FileOutputStream(tempFile); BufferedReader in = new BufferedReader(new FileReader(data.realPath)); String[] env = getEnvironmentVariables(data); if (ssi == null) { ssi = new BSssi(); } ssi.addEnvironment(env); if (data.resp == null) { SimpleResponse resp = new SimpleResponse(); resp.setHeader("Content-Type", "text/html"); moreHeaders(resp); resp.setHeader("Connection", "close"); data.resp = resp; resp.write(data.out); } String t; int start; Enumeration en; boolean anIfCondition = true; while ((t = in.readLine()) != null) { if ((start = t.indexOf("<!--#")) > -1) { if (anIfCondition) out.write(t.substring(0, start).getBytes()); try { en = ssi.parse(t.substring(start)).elements(); SSICommand command; while (en.hasMoreElements()) { command = (SSICommand) en.nextElement(); logger.fine("Command=" + command); switch(command.getCommand()) { case BSssi.CMD_IF_TRUE: anIfCondition = true; break; case BSssi.CMD_IF_FALSE: anIfCondition = false; break; case BSssi.CMD_CGI: out.flush(); if (command.getFileType() != null && command.getFileType().startsWith("shtm")) { HttpData d = newHttpData(data); d.out = out; d.realPath = HttpThread.getMappedFilename(command.getMessage(), data.req.getUrl()); new SsiHandler(d, ssi).perform(); } else { String application = getExtension(command.getFileType()); if (application == null) { writePaused(new FileInputStream(HttpThread.getMappedFilename(command.getMessage(), data.req.getUrl())), out, pause); } else { String parameter = ""; if (command.getMessage().indexOf("php") >= 0) { parameter = "-f "; } Process p = Runtime.getRuntime().exec(application + " " + parameter + HttpThread.getMappedFilename(command.getMessage(), data.req.getUrl())); BufferedReader pIn = new BufferedReader(new InputStreamReader(p.getInputStream())); String aLine; while ((aLine = pIn.readLine()) != null) out.write((aLine + "\n").getBytes()); pIn.close(); } } break; case BSssi.CMD_EXEC: Process p = Runtime.getRuntime().exec(command.getMessage()); BufferedReader pIn = new BufferedReader(new InputStreamReader(p.getInputStream())); String aLine; while ((aLine = pIn.readLine()) != null) out.write((aLine + "\n").getBytes()); BufferedReader pErr = new BufferedReader(new InputStreamReader(p.getErrorStream())); while ((aLine = pErr.readLine()) != null) out.write((aLine + "\n").getBytes()); pIn.close(); pErr.close(); p.destroy(); break; case BSssi.CMD_INCLUDE: File incFile = HttpThread.getMappedFilename(command.getMessage()); if (incFile.exists() && incFile.canRead()) { writePaused(new FileInputStream(incFile), out, pause); } break; case BSssi.CMD_FILESIZE: long sizeBytes = HttpThread.getMappedFilename(command.getMessage(), data.req.getUrl()).length(); double smartSize; String unit = "bytes"; if (command.getFileType().trim().equals("abbrev")) { if (sizeBytes > 1000000) { smartSize = sizeBytes / 1024000.0; unit = "M"; } else if (sizeBytes > 1000) { smartSize = sizeBytes / 1024.0; unit = "K"; } else { smartSize = sizeBytes; unit = "bytes"; } NumberFormat numberFormat = new DecimalFormat("#,##0", new DecimalFormatSymbols(Locale.ENGLISH)); out.write((numberFormat.format(smartSize) + "" + unit).getBytes()); } else { NumberFormat numberFormat = new DecimalFormat("#,###,##0", new DecimalFormatSymbols(Locale.ENGLISH)); out.write((numberFormat.format(sizeBytes) + " " + unit).getBytes()); } break; case BSssi.CMD_FLASTMOD: out.write(ssi.format(new Date(HttpThread.getMappedFilename(command.getMessage(), data.req.getUrl()).lastModified()), TimeZone.getTimeZone("GMT")).getBytes()); break; case BSssi.CMD_NOECHO: break; case BSssi.CMD_ECHO: default: out.write(command.getMessage().getBytes()); break; } } } catch (Exception e) { e.printStackTrace(); out.write((ssi.getErrorMessage() + " " + e.getMessage()).getBytes()); } if (anIfCondition) out.write("\n".getBytes()); } else { if (anIfCondition) out.write((t + "\n").getBytes()); } out.flush(); } in.close(); out.close(); data.fileData.setContentType("text/html"); data.fileData.setFile(tempFile); writePaused(new FileInputStream(tempFile), data.out, pause); logger.fine("HandleSSI done for " + data.resp); } Code Sample 2: public static String getMD5(String _pwd) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(_pwd.getBytes()); return toHexadecimal(new String(md.digest()).getBytes()); } catch (NoSuchAlgorithmException x) { x.printStackTrace(); return ""; } }
11
Code Sample 1: private void getRandomGuid(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = secureRandom.nextLong(); } else { rand = random.nextLong(); } sbValueBeforeMD5.append(id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } Code Sample 2: public static boolean isMatchingAsPassword(final String password, final String amd5Password) { boolean response = false; try { final MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(password.getBytes()); final byte[] md5Byte = algorithm.digest(); final StringBuffer buffer = new StringBuffer(); for (final byte b : md5Byte) { if ((b <= 15) && (b >= 0)) { buffer.append("0"); } buffer.append(Integer.toHexString(0xFF & b)); } response = (amd5Password != null) && amd5Password.equals(buffer.toString()); } catch (final NoSuchAlgorithmException e) { ProjektUtil.LOG.error("No digester MD5 found in classpath!", e); } return response; }
00
Code Sample 1: @HttpAction(name = "map.saveOrUpdate", method = { HttpAction.Method.post }, responseType = "text/plain") @HttpAuthentication(method = { HttpAuthentication.Method.WSSE }) public String saveOrUpdate(FileItem file, User user, MapOriginal map) throws HttpRpcException { File tmpFile; GenericDAO<MapOriginal> mapDao = DAOFactory.createDAO(MapOriginal.class); try { assert (file != null); String jobid = null; if (file.getContentType().startsWith("image/")) { tmpFile = File.createTempFile("gmap", "img"); OutputStream out = new FileOutputStream(tmpFile); IOUtils.copy(file.getInputStream(), out); out.flush(); out.close(); map.setState(MapOriginal.MapState.UPLOAD); map.setUser(user); map.setMapPath(tmpFile.getPath()); map.setThumbnailUrl("/map/inproc.gif"); map.setMimeType(file.getContentType()); mapDao.saveOrUpdate(map); jobid = PoolFactory.getClientPool().put(map, TaskState.STATE_MO_FINISH, MapOverrideStrategy.class); } return jobid; } catch (IOException e) { logger.error(e); throw ERROR_INTERNAL; } catch (DAOException e) { logger.error(e); throw ERROR_INTERNAL; } } Code Sample 2: private final void reOrderFriendsListByOnlineStatus() { boolean flag = true; while (flag) { flag = false; for (int i = 0; i < friendsCount - 1; i++) if (friendsListOnlineStatus[i] < friendsListOnlineStatus[i + 1]) { int j = friendsListOnlineStatus[i]; friendsListOnlineStatus[i] = friendsListOnlineStatus[i + 1]; friendsListOnlineStatus[i + 1] = j; long l = friendsListLongs[i]; friendsListLongs[i] = friendsListLongs[i + 1]; friendsListLongs[i + 1] = l; flag = true; } } }
00
Code Sample 1: public void testSavepoint4() throws Exception { Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #savepoint4 (data int)"); stmt.close(); con.setAutoCommit(false); for (int i = 0; i < 3; i++) { System.out.println("iteration: " + i); PreparedStatement pstmt = con.prepareStatement("INSERT INTO #savepoint4 (data) VALUES (?)"); pstmt.setInt(1, 1); assertTrue(pstmt.executeUpdate() == 1); Savepoint savepoint = con.setSavepoint(); assertNotNull(savepoint); assertTrue(savepoint.getSavepointId() == 1); try { savepoint.getSavepointName(); assertTrue(false); } catch (SQLException e) { } pstmt.setInt(1, 2); assertTrue(pstmt.executeUpdate() == 1); pstmt.close(); pstmt = con.prepareStatement("SELECT SUM(data) FROM #savepoint4"); ResultSet rs = pstmt.executeQuery(); assertTrue(rs.next()); assertTrue(rs.getInt(1) == 3); assertTrue(!rs.next()); pstmt.close(); rs.close(); con.rollback(savepoint); pstmt = con.prepareStatement("SELECT SUM(data) FROM #savepoint4"); rs = pstmt.executeQuery(); assertTrue(rs.next()); assertTrue(rs.getInt(1) == 1); assertTrue(!rs.next()); pstmt.close(); rs.close(); con.rollback(); } con.setAutoCommit(true); } Code Sample 2: public static String getMd5Password(final String password) { String response = null; try { final MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(password.getBytes()); final byte[] md5Byte = algorithm.digest(); final StringBuffer buffer = new StringBuffer(); for (final byte b : md5Byte) { if ((b <= 15) && (b >= 0)) { buffer.append("0"); } buffer.append(Integer.toHexString(0xFF & b)); } response = buffer.toString(); } catch (final NoSuchAlgorithmException e) { ProjektUtil.LOG.error("No digester MD5 found in classpath!", e); } return response; }
11
Code Sample 1: @Override protected AuthenticationHandlerResponse authenticateInternal(final Connection c, final AuthenticationCriteria criteria) throws LdapException { byte[] hash = new byte[DIGEST_SIZE]; try { final MessageDigest md = MessageDigest.getInstance(passwordScheme); md.update(criteria.getCredential().getBytes()); hash = md.digest(); } catch (NoSuchAlgorithmException e) { throw new LdapException(e); } final LdapAttribute la = new LdapAttribute("userPassword", String.format("{%s}%s", passwordScheme, LdapUtil.base64Encode(hash)).getBytes()); final CompareOperation compare = new CompareOperation(c); final CompareRequest request = new CompareRequest(criteria.getDn(), la); request.setControls(getAuthenticationControls()); final Response<Boolean> compareResponse = compare.execute(request); return new AuthenticationHandlerResponse(compareResponse.getResult(), compareResponse.getResultCode(), c, null, compareResponse.getControls()); } Code Sample 2: @SuppressWarnings("unused") private String getMD5(String value) { MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { return ""; } md5.reset(); md5.update(value.getBytes()); byte[] messageDigest = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { hexString.append(Integer.toHexString(0xFF & messageDigest[i])); } String hashedPassword = hexString.toString(); return hashedPassword; }
00
Code Sample 1: @Override public boolean update(String consulta, boolean autocommit, int transactionIsolation, Connection cx) throws SQLException { filasUpdate = 0; if (!consulta.contains(";")) { this.tipoConsulta = new Scanner(consulta); if (this.tipoConsulta.hasNext()) { execConsulta = this.tipoConsulta.next(); if (execConsulta.equalsIgnoreCase("update")) { Connection conexion = cx; Statement st = null; try { conexion.setAutoCommit(autocommit); if (transactionIsolation == 1 || transactionIsolation == 2 || transactionIsolation == 4 || transactionIsolation == 8) { conexion.setTransactionIsolation(transactionIsolation); } else { throw new IllegalArgumentException("Valor invalido sobre TransactionIsolation,\n TRANSACTION_NONE no es soportado por MySQL"); } st = (Statement) conexion.createStatement(ResultSetImpl.TYPE_SCROLL_SENSITIVE, ResultSetImpl.CONCUR_UPDATABLE); conexion.setReadOnly(false); filasUpdate = st.executeUpdate(consulta.trim(), Statement.RETURN_GENERATED_KEYS); if (filasUpdate > -1) { if (autocommit == false) { conexion.commit(); } return true; } else { return false; } } catch (MySQLIntegrityConstraintViolationException e) { System.out.println("Posible duplicacion de DATOS"); if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } e.printStackTrace(); return false; } catch (MySQLNonTransientConnectionException e) { if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } e.printStackTrace(); return false; } catch (MySQLDataException e) { System.out.println("Datos incorrectos"); if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } return false; } catch (MySQLSyntaxErrorException e) { System.out.println("Error en la sintaxis de la Consulta en MySQL"); if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } return false; } catch (SQLException e) { if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } e.printStackTrace(); return false; } finally { try { if (st != null) { if (!st.isClosed()) { st.close(); } } if (!conexion.isClosed()) { conexion.close(); } } catch (NullPointerException ne) { ne.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } } else { throw new IllegalArgumentException("No es una instruccion Update"); } } else { try { throw new JMySQLException("Error Grave , notifique al departamento de Soporte Tecnico \n" + email); } catch (JMySQLException ex) { Logger.getLogger(JMySQL.class.getName()).log(Level.SEVERE, null, ex); return false; } } } else { throw new IllegalArgumentException("No estan permitidas las MultiConsultas en este metodo"); } } Code Sample 2: public static void uploadFile(File in, String out, String host, int port, String path, String login, String password, boolean renameIfExist) throws IOException { FTPClient ftp = null; try { m_logCat.info("Uploading " + in + " to " + host + ":" + port + " at " + path); ftp = new FTPClient(); int reply; ftp.connect(host, port); m_logCat.info("Connected to " + host + "... Trying to authenticate"); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); m_logCat.error("FTP server " + host + " refused connection."); throw new IOException("Cannot connect to the FTP Server: connection refused."); } if (!ftp.login(login, password)) { ftp.logout(); throw new IOException("Cannot connect to the FTP Server: login / password is invalid!"); } ftp.setFileType(FTP.BINARY_FILE_TYPE); if (!ftp.changeWorkingDirectory(path)) { m_logCat.warn("Remote working directory: " + path + "does not exist on the FTP Server ..."); m_logCat.info("Trying to create remote directory: " + path); if (!ftp.makeDirectory(path)) { m_logCat.error("Failed to create remote directory: " + path); throw new IOException("Failed to store " + in + " in the remote directory: " + path); } if (!ftp.changeWorkingDirectory(path)) { m_logCat.error("Failed to change directory. Unexpected error"); throw new IOException("Failed to change to remote directory : " + path); } } if (out == null) { out = in.getName(); if (out.startsWith("/")) { out = out.substring(1); } } if (renameIfExist) { String[] files = ftp.listNames(); String f = in + out; for (int i = 0; i < files.length; i++) { if (files[i].equals(out)) { m_logCat.debug("Found existing file on the server: " + out); boolean rename_ok = false; String bak = "_bak"; int j = 0; String newExt = null; while (!rename_ok) { if (j == 0) newExt = bak; else newExt = bak + j; if (ftp.rename(out, out + newExt)) { m_logCat.info(out + " renamed to " + out + newExt); rename_ok = true; } else { m_logCat.warn("Renaming to " + out + newExt + " has failed!, trying again ..."); j++; } } break; } } } InputStream input = new FileInputStream(in); m_logCat.info("Starting transfert of " + in); ftp.storeFile(out, input); m_logCat.info(in + " uploaded successfully"); input.close(); ftp.logout(); } catch (FTPConnectionClosedException e) { m_logCat.error("Server closed connection.", e); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { } } } }
11
Code Sample 1: private void moveFile(File orig, File target) throws IOException { byte buffer[] = new byte[1000]; int bread = 0; FileInputStream fis = new FileInputStream(orig); FileOutputStream fos = new FileOutputStream(target); while (bread != -1) { bread = fis.read(buffer); if (bread != -1) fos.write(buffer, 0, bread); } fis.close(); fos.close(); orig.delete(); } Code Sample 2: static void conditionalCopyFile(File dst, File src) throws IOException { if (dst.equals(src)) return; if (!dst.isFile() || dst.lastModified() < src.lastModified()) { System.out.println("Copying " + src); InputStream is = new FileInputStream(src); OutputStream os = new FileOutputStream(dst); byte[] buf = new byte[8192]; int len; while ((len = is.read(buf)) > 0) os.write(buf, 0, len); os.close(); is.close(); } }
11
Code Sample 1: private boolean saveDocumentXml(String repository, String tempRepo) { boolean result = true; try { XPath xpath = XPathFactory.newInstance().newXPath(); String expression = "documents/document"; InputSource insource = new InputSource(new FileInputStream(tempRepo + File.separator + AppConstants.DMS_XML)); NodeList nodeList = (NodeList) xpath.evaluate(expression, insource, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); System.out.println(node.getNodeName()); DocumentModel document = new DocumentModel(); NodeList childs = node.getChildNodes(); for (int j = 0; j < childs.getLength(); j++) { Node child = childs.item(j); if (child.getNodeType() == Node.ELEMENT_NODE) { if (child.getNodeName() != null && child.getFirstChild() != null && child.getFirstChild().getNodeValue() != null) { System.out.println(child.getNodeName() + "::" + child.getFirstChild().getNodeValue()); } if (Document.FLD_ID.equals(child.getNodeName())) { if (child.getFirstChild() != null) { String szId = child.getFirstChild().getNodeValue(); if (szId != null && szId.length() > 0) { try { document.setId(new Long(szId)); } catch (Exception e) { e.printStackTrace(); } } } } else if (document.FLD_NAME.equals(child.getNodeName())) { document.setName(child.getFirstChild().getNodeValue()); document.setTitle(document.getName()); document.setDescr(document.getName()); document.setExt(getExtension(document.getName())); } else if (document.FLD_LOCATION.equals(child.getNodeName())) { document.setLocation(child.getFirstChild().getNodeValue()); } else if (document.FLD_OWNER.equals(child.getNodeName())) { Long id = new Long(child.getFirstChild().getNodeValue()); User user = new UserModel(); user.setId(id); user = (User) userService.find(user); if (user != null && user.getId() != null) { document.setOwner(user); } } } } boolean isSave = docService.save(document); if (isSave) { String repo = preference.getRepository(); Calendar calendar = Calendar.getInstance(); StringBuffer sbRepo = new StringBuffer(repo); sbRepo.append(File.separator); StringBuffer sbFolder = new StringBuffer(sdf.format(calendar.getTime())); sbFolder.append(File.separator).append(calendar.get(Calendar.HOUR_OF_DAY)); File fileFolder = new File(sbRepo.append(sbFolder).toString()); if (!fileFolder.exists()) { fileFolder.mkdirs(); } FileChannel fcSource = null, fcDest = null; try { StringBuffer sbFile = new StringBuffer(fileFolder.getAbsolutePath()); StringBuffer fname = new StringBuffer(document.getId().toString()); fname.append(".").append(document.getExt()); sbFile.append(File.separator).append(fname); fcSource = new FileInputStream(tempRepo + File.separator + document.getName()).getChannel(); fcDest = new FileOutputStream(sbFile.toString()).getChannel(); fcDest.transferFrom(fcSource, 0, fcSource.size()); document.setLocation(sbFolder.toString()); document.setSize(fcSource.size()); log.info("Batch upload file " + document.getName() + " into [" + document.getLocation() + "] as " + document.getName() + "." + document.getExt()); folder.setId(DEFAULT_FOLDER); folder = (Folder) folderService.find(folder); if (folder != null && folder.getId() != null) { document.setFolder(folder); } workspace.setId(DEFAULT_WORKSPACE); workspace = (Workspace) workspaceService.find(workspace); if (workspace != null && workspace.getId() != null) { document.setWorkspace(workspace); } user.setId(DEFAULT_USER); user = (User) userService.find(user); if (user != null && user.getId() != null) { document.setCrtby(user.getId()); } document.setCrtdate(new Date()); document = (DocumentModel) docService.resetDuplicateDocName(document); docService.save(document); DocumentIndexer.indexDocument(preference, document); } catch (FileNotFoundException notFoundEx) { log.error("saveFile file not found: " + document.getName(), notFoundEx); } catch (IOException ioEx) { log.error("saveFile IOException: " + document.getName(), ioEx); } finally { try { if (fcSource != null) { fcSource.close(); } if (fcDest != null) { fcDest.close(); } } catch (Exception e) { log.error(e.getMessage(), e); } } } } } catch (Exception e) { result = false; e.printStackTrace(); } return result; } Code Sample 2: private void doPOST(HttpURLConnection connection, InputStream inputXML) throws MessageServiceException { try { OutputStream requestStream = new BufferedOutputStream(connection.getOutputStream()); IOUtils.copyAndClose(inputXML, requestStream); connection.connect(); } catch (IOException e) { throw new MessageServiceException(e.getMessage(), e); } }
11
Code Sample 1: public void writeTo(OutputStream out) throws IOException { if (!closed) { throw new IOException("Stream not closed"); } if (isInMemory()) { memoryOutputStream.writeTo(out); } else { FileInputStream fis = new FileInputStream(outputFile); try { IOUtils.copy(fis, out); } finally { IOUtils.closeQuietly(fis); } } } Code Sample 2: @Test public void testStandardTee() throws Exception { final byte[] test = "test".getBytes(); final InputStream source = new ByteArrayInputStream(test); final ByteArrayOutputStream destination1 = new ByteArrayOutputStream(); final ByteArrayOutputStream destination2 = new ByteArrayOutputStream(); final TeeOutputStream tee = new TeeOutputStream(destination1, destination2); org.apache.commons.io.IOUtils.copy(source, tee); tee.close(); assertArrayEquals("the two arrays are equals", test, destination1.toByteArray()); assertArrayEquals("the two arrays are equals", test, destination2.toByteArray()); assertEquals("byte count", test.length, tee.getSize()); }
00
Code Sample 1: private byte[] getMD5(String string) throws IMException { byte[] buffer = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(string.getBytes("utf-8")); buffer = md.digest(); buffer = getHexString(buffer); } catch (NoSuchAlgorithmException e) { throw new IMException(e); } catch (UnsupportedEncodingException ue) { throw new IMException(ue); } return buffer; } Code Sample 2: public byte[] getByteCode() throws IOException { InputStream in = null; ByteArrayOutputStream buf = new ByteArrayOutputStream(2048); try { in = url.openStream(); int b = in.read(); while (b != -1) { buf.write(b); b = in.read(); } } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } return buf.toByteArray(); }
00
Code Sample 1: @Override public User updateUser(User bean) throws SitoolsException { checkUser(); Connection cx = null; try { cx = ds.getConnection(); cx.setAutoCommit(false); PreparedStatement st; int i = 1; if (bean.getSecret() != null && !"".equals(bean.getSecret())) { st = cx.prepareStatement(jdbcStoreResource.UPDATE_USER_WITH_PW); st.setString(i++, bean.getFirstName()); st.setString(i++, bean.getLastName()); st.setString(i++, bean.getSecret()); st.setString(i++, bean.getEmail()); st.setString(i++, bean.getIdentifier()); } else { st = cx.prepareStatement(jdbcStoreResource.UPDATE_USER_WITHOUT_PW); st.setString(i++, bean.getFirstName()); st.setString(i++, bean.getLastName()); st.setString(i++, bean.getEmail()); st.setString(i++, bean.getIdentifier()); } st.executeUpdate(); st.close(); if (bean.getProperties() != null) { deleteProperties(bean.getIdentifier(), cx); createProperties(bean, cx); } if (!cx.getAutoCommit()) { cx.commit(); } } catch (SQLException e) { try { cx.rollback(); } catch (SQLException e1) { throw new SitoolsException("UPDATE_USER ROLLBACK" + e1.getMessage(), e1); } throw new SitoolsException("UPDATE_USER " + e.getMessage(), e); } finally { closeConnection(cx); } return getUserById(bean.getIdentifier()); } Code Sample 2: private InputStream get(String url, long startOffset, long expectedLength) throws ClientProtocolException, IOException { url = normalizeUrl(url); Log.i(LOG_TAG, "Get " + url); mHttpGet = new HttpGet(url); int expectedStatusCode = HttpStatus.SC_OK; if (startOffset > 0) { String range = "bytes=" + startOffset + "-"; if (expectedLength >= 0) { range += expectedLength - 1; } Log.i(LOG_TAG, "requesting byte range " + range); mHttpGet.addHeader("Range", range); expectedStatusCode = HttpStatus.SC_PARTIAL_CONTENT; } HttpResponse response = mHttpClient.execute(mHttpGet); long bytesToSkip = 0; int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != expectedStatusCode) { if ((statusCode == HttpStatus.SC_OK) && (expectedStatusCode == HttpStatus.SC_PARTIAL_CONTENT)) { Log.i(LOG_TAG, "Byte range request ignored"); bytesToSkip = startOffset; } else { throw new IOException("Unexpected Http status code " + statusCode + " expected " + expectedStatusCode); } } HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); if (bytesToSkip > 0) { is.skip(bytesToSkip); } return is; }
11
Code Sample 1: @Override public boolean register(String username, String password) { this.getLogger().info(DbUserServiceImpl.class, ">>>rigister " + username + "<<<"); try { if (this.getDbServ().queryFeelerUser(username) != null) { return false; } MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); String passwordMd5 = new String(md5.digest()); this.getDbServ().addFeelerUser(username, passwordMd5); return this.identification(username, password); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return false; } } Code Sample 2: public String encrypt(String pwd) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); System.out.println("Error"); } try { md5.update(pwd.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "That is not a valid encrpytion type"); } byte raw[] = md5.digest(); String empty = ""; String hash = ""; for (byte b : raw) { String tmp = empty + Integer.toHexString(b & 0xff); if (tmp.length() == 1) { tmp = 0 + tmp; } hash += tmp; } return hash; }
11
Code Sample 1: public static String scramble(String text) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(text.getBytes("UTF-8")); StringBuffer sb = new StringBuffer(); for (byte b : md.digest()) sb.append(Integer.toString(b & 0xFF, 16)); return sb.toString(); } catch (UnsupportedEncodingException e) { return null; } catch (NoSuchAlgorithmException e) { return null; } } Code Sample 2: public synchronized String encrypt(String plaintext) throws Exception { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new MyException(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; }
11
Code Sample 1: private static String getDocumentAt(String urlString) { StringBuffer html_text = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) html_text.append(line + "\n"); reader.close(); } catch (MalformedURLException e) { System.out.println("����URL: " + urlString); } catch (IOException e) { e.printStackTrace(); } return html_text.toString(); } Code Sample 2: private void initializeTree() { InputStreamReader reader = null; BufferedReader buffReader = null; try { for (int i = 0; i < ORDER.length; i++) { int index = ORDER[i]; String indexName = index < 10 ? "0" + index : (index > 20 ? "big" : "" + index); URL url = EmptyClass.class.getResource("engchar" + indexName + ".dic"); logger.info("... Loading: " + "engchar" + indexName + ".dic = {" + url + "}"); reader = new InputStreamReader(url.openStream()); buffReader = new BufferedReader(reader); String line = null; String word = null; do { line = buffReader.readLine(); if (line != null) { boolean plural = line.endsWith("/S"); boolean forbidden = line.endsWith("/X"); if (plural) { int stringIndex = line.indexOf("/S"); word = new String(line.substring(0, stringIndex)); } else if (forbidden) { int stringIndex = line.indexOf("/X"); word = new String(line.substring(0, stringIndex)); } else { word = line.toString(); } if (tree == null) { tree = new BKTree(); } tree.insertDictionaryWord(word, plural, forbidden); } } while (line != null); } logger.debug("Loading supplemental dictionary..."); List<String> listOfWords = KSupplementalDictionaryUtil.getWords(); for (String word : listOfWords) { tree.insertDictionaryWord(word, false, false); } initialized = true; } catch (Exception exception) { logger.error("Error", exception); } finally { if (reader != null) { try { reader.close(); } catch (Exception ex) { } } if (buffReader != null) { try { buffReader.close(); } catch (Exception ex) { } } } }
11
Code Sample 1: public static boolean copy(InputStream is, File file) { try { FileOutputStream fos = new FileOutputStream(file); IOUtils.copy(is, fos); is.close(); fos.close(); return true; } catch (Exception e) { System.err.println(e.getMessage()); return false; } } Code Sample 2: @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String fileName = request.getParameter("tegsoftFileName"); if (fileName.startsWith("Tegsoft_BACKUP_")) { fileName = fileName.substring("Tegsoft_BACKUP_".length()); String targetFileName = "/home/customer/" + fileName; response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); FileInputStream is = new FileInputStream(targetFileName); IOUtils.copy(is, response.getOutputStream()); is.close(); return; } if (fileName.equals("Tegsoft_ASTMODULES")) { String targetFileName = tobeHome + "/setup/Tegsoft_ASTMODULES.tgz"; response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); FileInputStream is = new FileInputStream(targetFileName); IOUtils.copy(is, response.getOutputStream()); is.close(); return; } if (fileName.equals("Tegsoft_ASTSBIN")) { String targetFileName = tobeHome + "/setup/Tegsoft_ASTSBIN.tgz"; response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); FileInputStream is = new FileInputStream(targetFileName); IOUtils.copy(is, response.getOutputStream()); is.close(); return; } if (!fileName.startsWith("Tegsoft_")) { return; } if (!fileName.endsWith(".zip")) { return; } if (fileName.indexOf("_") < 0) { return; } fileName = fileName.substring(fileName.indexOf("_") + 1); if (fileName.indexOf("_") < 0) { return; } String fileType = fileName.substring(0, fileName.indexOf("_")); String destinationFileName = tobeHome + "/setup/Tegsoft_" + fileName; if (!new File(destinationFileName).exists()) { if ("FORMS".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/forms", tobeHome + "/setup/Tegsoft_" + fileName); } else if ("IMAGES".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/image", tobeHome + "/setup/Tegsoft_" + fileName); } else if ("VIDEOS".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/videos", tobeHome + "/setup/Tegsoft_" + fileName); } else if ("TEGSOFTJARS".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/WEB-INF/lib/", tobeHome + "/setup/Tegsoft_" + fileName, "Tegsoft", "jar"); } else if ("TOBEJARS".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/WEB-INF/lib/", tobeHome + "/setup/Tegsoft_" + fileName, "Tobe", "jar"); } else if ("ALLJARS".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/WEB-INF/lib/", tobeHome + "/setup/Tegsoft_" + fileName); } else if ("DB".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/sql", tobeHome + "/setup/Tegsoft_" + fileName); } else if ("CONFIGSERVICE".equals(fileType)) { FileUtil.createZipPackage("/tegsoft/src/java/TegsoftTelecom/configFiles/init.d/", tobeHome + "/setup/Tegsoft_" + fileName, "tegsoft", null); } else if ("CONFIGSCRIPTS".equals(fileType)) { FileUtil.createZipPackage("/tegsoft/src/java/TegsoftTelecom/configFiles/root/", tobeHome + "/setup/Tegsoft_" + fileName, "tegsoft", null); } else if ("CONFIGFOP".equals(fileType)) { FileUtil.createZipPackage("/tegsoft/src/java/TegsoftTelecom/configFiles/fop/", tobeHome + "/setup/Tegsoft_" + fileName); } else if ("CONFIGASTERISK".equals(fileType)) { FileUtil.createZipPackage("/tegsoft/src/java/TegsoftTelecom/configFiles/asterisk/", tobeHome + "/setup/Tegsoft_" + fileName); } } response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); FileInputStream is = new FileInputStream(destinationFileName); IOUtils.copy(is, response.getOutputStream()); is.close(); } catch (Exception ex) { ex.printStackTrace(); } }
00
Code Sample 1: private void downloadFile(String directory, String fileName) { URL url = null; String urlstr = updateURL + directory + fileName; int position = 0; try { Logger.msg(threadName + "Download new file from " + urlstr); url = new URL(urlstr); URLConnection conn = url.openConnection(); BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(updateDirectory + System.getProperty("file.separator") + fileName)); int i = in.read(); while (i != -1) { if (isInterrupted()) { setWasInterrupted(); in.close(); out.flush(); out.close(); interrupt(); return; } out.write(i); i = in.read(); position += 1; if (position % 1000 == 0) { Enumeration<DownloadFilesListener> en = listener.elements(); while (en.hasMoreElements()) { DownloadFilesListener currentListener = en.nextElement(); currentListener.progress(1000); } } } Enumeration<DownloadFilesListener> en = listener.elements(); while (en.hasMoreElements()) { DownloadFilesListener currentListener = en.nextElement(); currentListener.progress(1000); } in.close(); out.flush(); out.close(); Logger.msg(threadName + "Saved file " + fileName + " to " + updateDirectory + System.getProperty("file.separator") + fileName); } catch (Exception e) { Logger.err(threadName + "Error (" + e.toString() + ")"); } } Code Sample 2: public static String digestString(String data, String algorithm) { String result = null; if (data != null) { try { MessageDigest _md = MessageDigest.getInstance(algorithm); _md.update(data.getBytes()); byte[] _digest = _md.digest(); String _ds; _ds = toHexString(_digest, 0, _digest.length); result = _ds; } catch (NoSuchAlgorithmException e) { result = null; } } return result; }
00
Code Sample 1: public static Document validateXml(File messageFile, URL inputUrl, String[] catalogs) throws IOException, ParserConfigurationException, Exception, SAXException, FileNotFoundException { InputSource source = new InputSource(inputUrl.openStream()); Document logDoc = DomUtil.getNewDom(); XMLReader reader = SaxUtil.getXMLFormatLoggingXMLReader(log, logDoc, true, catalogs); reader.parse(source); InputStream logStream = DomUtil.serializeToInputStream(logDoc, "utf-8"); System.out.println("Creating message file \"" + messageFile.getAbsolutePath() + "\"..."); OutputStream fos = new FileOutputStream(messageFile); IOUtils.copy(logStream, fos); return logDoc; } Code Sample 2: public static String MD5(String str) { try { MessageDigest md5 = MessageDigest.getInstance("md5"); md5.update(str.getBytes(), 0, str.length()); String sig = new BigInteger(1, md5.digest()).toString(); return sig; } catch (NoSuchAlgorithmException e) { System.err.println("Can not use md5 algorithm"); } return null; }
11
Code Sample 1: private void copy(String inputPath, String outputPath, String name) { try { FileReader in = new FileReader(inputPath + name); FileWriter out = new FileWriter(outputPath + name); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
00
Code Sample 1: private void uploadFileToWebSite(String siteDir, String channelAsciiName, Map synFileList) throws Exception { if (siteDir == null) { siteDir = ""; } log.debug("uploadFileToWebSite begin! siteDir:= " + siteDir + " currDate:= " + new Date().toString()); siteDir = new File(siteDir).getPath() + File.separator; FTPClient client = new FTPClient(); try { for (int i = 0; i < 3; i++) { try { client.connect(ftpServerIp, ftpPort); break; } catch (IOException ex2) { if (i == 2) { log.error("ftp����������ʧ��,�Ѿ�����3��!", ex2); throw new IOException("ftp����������ʧ��,�Ѿ�����3��!" + ex2.toString()); } } } for (int i = 0; i < 3; i++) { try { client.login(ftpLoginUser, ftpPassword); break; } catch (IOException ex3) { if (i == 2) { log.error("��¼ftp������ʧ��,�Ѿ�����3��!", ex3); throw new IOException("��¼ftp������ʧ��,�Ѿ�����3��!" + ex3.toString()); } } } log.debug("Ftp login is over !"); client.syst(); String ftpWD = client.printWorkingDirectory(); log.debug("client.initiateListParsing() is over !"); client.setFileType(FTPClient.BINARY_FILE_TYPE); client.enterLocalPassiveMode(); Iterator iterator = synFileList.keySet().iterator(); ArrayList alKey = new ArrayList(); while (iterator.hasNext()) { alKey.add((String) iterator.next()); } log.debug("FTP Files size:= " + alKey.size()); String basePath = ftpRootPath + (channelAsciiName == null || channelAsciiName.trim().equals("") ? "" : File.separator + channelAsciiName); log.debug("localRootPath:= " + localRootPath + " basePath:= " + basePath); String path; boolean isSuc; String sFileSep = File.separator; String sRep = ""; if (basePath.startsWith("/")) { sFileSep = "/"; sRep = "\\"; } else if (basePath.startsWith("\\")) { sFileSep = "\\"; sRep = "/"; } if (!"".equals(sRep)) { basePath = StringUtil.replaceAll(basePath, sRep, sFileSep); while (basePath.startsWith(sFileSep)) basePath = basePath.substring(1); } for (int j = 0; j < alKey.size(); j++) { String key = (String) alKey.get(j); File file = new File(siteDir + key); String filePath = file.getParent(); String fileName = file.getName(); if (fileName == null || filePath == null || !file.exists() || filePath.length() < localRootPath.length()) { continue; } filePath = filePath.substring(localRootPath.length()); FileInputStream fis = null; String temp1; ArrayList alTemp; int iInd; try { path = basePath + (filePath == null || filePath.trim().equals("") || filePath.equals(File.separator) ? "" : File.separator + filePath); if (!"".equals(sRep)) { path = StringUtil.replaceAll(path, sRep, sFileSep); } if (!client.changeWorkingDirectory(path)) { isSuc = client.makeDirectory(path); if (isSuc) { log.debug(" **** makeDirectory1(" + path + "): " + isSuc); } else { temp1 = path; alTemp = new ArrayList(); iInd = temp1.lastIndexOf(sFileSep); alTemp.add(temp1.substring(iInd)); temp1 = temp1.substring(0, iInd); isSuc = client.makeDirectory(temp1); if (isSuc) { log.debug(" **** makeDirectory2(" + temp1 + "): " + isSuc); } while (!"".equals(temp1) && !isSuc) { iInd = temp1.lastIndexOf(sFileSep); alTemp.add(temp1.substring(iInd)); temp1 = temp1.substring(0, iInd); isSuc = client.makeDirectory(temp1); if (isSuc) { log.debug(" **** makeDirectory3(" + temp1 + "): " + isSuc); } } for (int i = alTemp.size(); i > 0; i--) { temp1 += alTemp.get(i - 1); isSuc = client.makeDirectory(temp1); log.debug(" **** makeDirectory4(" + temp1 + "): " + isSuc); } } client.changeWorkingDirectory(path); } fis = new FileInputStream(file); client.storeFile(fileName, fis); client.changeWorkingDirectory(ftpWD); } catch (Throwable ex1) { log.error("ͬ���ļ�����:������ļ�Ϊ:" + file.getPath()); ex1.printStackTrace(); } finally { try { fis.close(); } catch (RuntimeException e1) { log.error("close()����!"); e1.printStackTrace(); } file = null; } } } catch (Throwable ex) { log.error("ͬ��ʧ��--1202!", ex); ex.printStackTrace(); } finally { if (client != null && client.isConnected()) { client.disconnect(); } } } Code Sample 2: public static String encryptPassword(String password) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes()); byte[] hash = md.digest(); int hashLength = hash.length; StringBuffer hashStringBuf = new StringBuffer(); String byteString; int byteLength; for (int index = 0; index < hash.length; index++) { byteString = String.valueOf(hash[index] + 128); byteLength = byteString.length(); switch(byteLength) { case 1: byteString = "00" + byteString; break; case 2: byteString = "0" + byteString; break; } hashStringBuf.append(byteString); } return hashStringBuf.toString(); } catch (NoSuchAlgorithmException nsae) { System.out.println("Error getting password hash - " + nsae.getMessage()); return null; } }
11
Code Sample 1: public void constructAssociationView() { String className; String methodName; String field; boolean foundRead = false; boolean foundWrite = false; boolean classWritten = false; try { AssocView = new BufferedWriter(new FileWriter("InfoFiles/AssociationView.txt")); FileInputStream fstreamPC = new FileInputStream("InfoFiles/PrincipleClassGroup.txt"); DataInputStream inPC = new DataInputStream(fstreamPC); BufferedReader PC = new BufferedReader(new InputStreamReader(inPC)); while ((field = PC.readLine()) != null) { className = field; AssocView.write(className); AssocView.newLine(); classWritten = true; while ((methodName = PC.readLine()) != null) { if (methodName.contentEquals("EndOfClass")) break; AssocView.write("StartOfMethod"); AssocView.newLine(); AssocView.write(methodName); AssocView.newLine(); for (int i = 0; i < readFileCount && foundRead == false; i++) { if (methodName.compareTo(readArray[i]) == 0) { foundRead = true; for (int j = 1; readArray[i + j].compareTo("EndOfMethod") != 0; j++) { if (readArray[i + j].indexOf(".") > 0) { field = readArray[i + j].substring(0, readArray[i + j].indexOf(".")); if (isPrincipleClass(field) == true) { AssocView.write(readArray[i + j]); AssocView.newLine(); } } } } } for (int i = 0; i < writeFileCount && foundWrite == false; i++) { if (methodName.compareTo(writeArray[i]) == 0) { foundWrite = true; for (int j = 1; writeArray[i + j].compareTo("EndOfMethod") != 0; j++) { if (writeArray[i + j].indexOf(".") > 0) { field = writeArray[i + j].substring(0, writeArray[i + j].indexOf(".")); if (isPrincipleClass(field) == true) { AssocView.write(writeArray[i + j]); AssocView.newLine(); } } } } } AssocView.write("EndOfMethod"); AssocView.newLine(); foundRead = false; foundWrite = false; } if (classWritten == true) { AssocView.write("EndOfClass"); AssocView.newLine(); classWritten = false; } } PC.close(); AssocView.close(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public File createTemporaryFile() throws IOException { URL url = clazz.getResource(resource); if (url == null) { throw new IOException("No resource available from '" + clazz.getName() + "' for '" + resource + "'"); } String extension = getExtension(resource); String prefix = "resource-temporary-file-creator"; File file = File.createTempFile(prefix, extension); InputStream input = url.openConnection().getInputStream(); FileOutputStream output = new FileOutputStream(file); com.volantis.synergetics.io.IOUtils.copyAndClose(input, output); return file; }
11
Code Sample 1: public static String encrypt(String txt) throws Exception { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(txt.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } Code Sample 2: private String getCoded(String pass) { String passSecret = ""; try { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(pass.getBytes("UTF8")); byte s[] = m.digest(); for (int i = 0; i < s.length; i++) { passSecret += Integer.toHexString((0x000000ff & s[i]) | 0xffffff00).substring(6); } } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return passSecret; }
11
Code Sample 1: private void unpackBundle() throws IOException { File useJarPath = null; if (DownloadManager.isWindowsVista()) { useJarPath = lowJarPath; File jarDir = useJarPath.getParentFile(); if (jarDir != null) { jarDir.mkdirs(); } } else { useJarPath = jarPath; } DownloadManager.log("Unpacking " + this + " to " + useJarPath); InputStream rawStream = new FileInputStream(localPath); JarInputStream in = new JarInputStream(rawStream) { public void close() throws IOException { } }; try { File jarTmp = null; JarEntry entry; while ((entry = in.getNextJarEntry()) != null) { String entryName = entry.getName(); if (entryName.equals("classes.pack")) { File packTmp = new File(useJarPath + ".pack"); packTmp.getParentFile().mkdirs(); DownloadManager.log("Writing temporary .pack file " + packTmp); OutputStream tmpOut = new FileOutputStream(packTmp); try { DownloadManager.send(in, tmpOut); } finally { tmpOut.close(); } jarTmp = new File(useJarPath + ".tmp"); DownloadManager.log("Writing temporary .jar file " + jarTmp); unpack(packTmp, jarTmp); packTmp.delete(); } else if (!entryName.startsWith("META-INF")) { File dest; if (DownloadManager.isWindowsVista()) { dest = new File(lowJavaPath, entryName.replace('/', File.separatorChar)); } else { dest = new File(DownloadManager.JAVA_HOME, entryName.replace('/', File.separatorChar)); } if (entryName.equals(BUNDLE_JAR_ENTRY_NAME)) dest = useJarPath; File destTmp = new File(dest + ".tmp"); boolean exists = dest.exists(); if (!exists) { DownloadManager.log(dest + ".mkdirs()"); dest.getParentFile().mkdirs(); } try { DownloadManager.log("Using temporary file " + destTmp); FileOutputStream out = new FileOutputStream(destTmp); try { byte[] buffer = new byte[2048]; int c; while ((c = in.read(buffer)) > 0) out.write(buffer, 0, c); } finally { out.close(); } if (exists) dest.delete(); DownloadManager.log("Renaming from " + destTmp + " to " + dest); if (!destTmp.renameTo(dest)) { throw new IOException("unable to rename " + destTmp + " to " + dest); } } catch (IOException e) { if (!exists) throw e; } } } if (jarTmp != null) { if (useJarPath.exists()) jarTmp.delete(); else if (!jarTmp.renameTo(useJarPath)) { throw new IOException("unable to rename " + jarTmp + " to " + useJarPath); } } if (DownloadManager.isWindowsVista()) { DownloadManager.log("Using broker to move " + name); if (!DownloadManager.moveDirWithBroker(DownloadManager.getKernelJREDir() + name)) { throw new IOException("unable to create " + name); } DownloadManager.log("Broker finished " + name); } DownloadManager.log("Finished unpacking " + this); } finally { rawStream.close(); } if (deleteOnInstall) { localPath.delete(); } } Code Sample 2: public void init(File file) { InputStream is = null; ByteArrayOutputStream os = null; try { is = new FileInputStream(file); os = new ByteArrayOutputStream(); IOUtils.copy(is, os); } catch (Throwable e) { throw new VisualizerEngineException("Unexcpected exception while reading MDF file", e); } if (simulationEngine != null) simulationEngine.stopSimulation(); simulationEngine = new TrafficAsynchSimulationEngine(); simulationEngine.init(MDFReader.read(os.toByteArray())); simulationEngineThread = null; }
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 { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: private BufferedReader getReader(final String fileUrl) throws IOException { InputStreamReader reader; try { reader = new FileReader(fileUrl); } catch (FileNotFoundException e) { URL url = new URL(fileUrl); reader = new InputStreamReader(url.openStream()); } return new BufferedReader(reader); }
11
Code Sample 1: private void copy(FileInfo inputFile, FileInfo outputFile) { try { FileReader in = new FileReader(inputFile.file); FileWriter out = new FileWriter(outputFile.file); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); outputFile.file.setLastModified(inputFile.lastModified); } catch (IOException e) { } } Code Sample 2: public void testRenderRules() { try { MappingManager manager = new MappingManager(); OWLOntologyManager omanager = OWLManager.createOWLOntologyManager(); OWLOntology srcOntology; OWLOntology targetOntology; manager.loadMapping(rulesDoc.toURL()); srcOntology = omanager.loadOntologyFromPhysicalURI(srcURI); targetOntology = omanager.loadOntologyFromPhysicalURI(targetURI); manager.setSourceOntology(srcOntology); manager.setTargetOntology(targetOntology); Graph srcGraph = manager.getSourceGraph(); Graph targetGraph = manager.getTargetGraph(); System.out.println("Starting to render..."); FlexGraphViewFactory factory = new FlexGraphViewFactory(); factory.setColorScheme(ColorSchemes.BLUES); factory.visit(srcGraph); GraphView view = factory.getGraphView(); GraphViewRenderer renderer = new FlexGraphViewRenderer(); renderer.setGraphView(view); System.out.println("View updated with graph..."); InputStream xmlStream = renderer.renderGraphView(); StringWriter writer = new StringWriter(); IOUtils.copy(xmlStream, writer); System.out.println("Finished writing"); writer.close(); System.out.println("Finished render... XML is:"); System.out.println(writer.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (OWLOntologyCreationException e) { e.printStackTrace(); } }
00
Code Sample 1: public void testClickToCallOutDirection() throws Exception { init(); SipCall[] receiverCalls = new SipCall[receiversCount]; receiverCalls[0] = sipPhoneReceivers[0].createSipCall(); receiverCalls[1] = sipPhoneReceivers[1].createSipCall(); receiverCalls[0].listenForIncomingCall(); receiverCalls[1].listenForIncomingCall(); logger.info("Trying to reach url : " + CLICK2DIAL_URL + CLICK2DIAL_PARAMS); URL url = new URL(CLICK2DIAL_URL + CLICK2DIAL_PARAMS); InputStream in = url.openConnection().getInputStream(); byte[] buffer = new byte[10000]; int len = in.read(buffer); String httpResponse = ""; for (int q = 0; q < len; q++) httpResponse += (char) buffer[q]; logger.info("Received the follwing HTTP response: " + httpResponse); receiverCalls[0].waitForIncomingCall(timeout); assertTrue(receiverCalls[0].sendIncomingCallResponse(Response.RINGING, "Ringing", 0)); assertTrue(receiverCalls[0].sendIncomingCallResponse(Response.OK, "OK", 0)); receiverCalls[1].waitForIncomingCall(timeout); assertTrue(receiverCalls[1].sendIncomingCallResponse(Response.RINGING, "Ringing", 0)); assertTrue(receiverCalls[1].sendIncomingCallResponse(Response.OK, "OK", 0)); assertTrue(receiverCalls[1].waitForAck(timeout)); assertTrue(receiverCalls[0].waitForAck(timeout)); assertTrue(receiverCalls[0].disconnect()); assertTrue(receiverCalls[1].waitForDisconnect(timeout)); assertTrue(receiverCalls[1].respondToDisconnect()); } Code Sample 2: public String preProcessHTML(String uri) { final StringBuffer buf = new StringBuffer(); try { HTMLDocument doc = new HTMLDocument() { public HTMLEditorKit.ParserCallback getReader(int pos) { return new HTMLEditorKit.ParserCallback() { public void handleText(char[] data, int pos) { buf.append(data); buf.append('\n'); } }; } }; URL url = new URI(uri).toURL(); URLConnection conn = url.openConnection(); Reader rd = new InputStreamReader(conn.getInputStream()); new ParserDelegator().parse(rd, doc.getReader(0), Boolean.TRUE); } catch (MalformedURLException e) { System.err.println(e.getMessage()); e.printStackTrace(); } catch (URISyntaxException e) { System.err.println(e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println(e.getMessage()); e.printStackTrace(); } return buf.toString(); }
00
Code Sample 1: public String selectFROM() throws Exception { BufferedReader in = null; String data = null; try { HttpClient httpclient = new DefaultHttpClient(); URI uri = new URI("http://**.**.**.**/OctopusManager/index2.php"); HttpGet request = new HttpGet(); request.setURI(uri); HttpResponse httpresponse = httpclient.execute(request); HttpEntity httpentity = httpresponse.getEntity(); in = new BufferedReader(new InputStreamReader(httpentity.getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; while ((line = in.readLine()) != null) { sb.append(line); } in.close(); data = sb.toString(); return data; } finally { if (in != null) { try { in.close(); return data; } catch (Exception e) { e.printStackTrace(); } } } } Code Sample 2: private void copyFile(File sourceFile, File destFile) throws IOException { if (!sourceFile.exists()) { return; } if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); if (destination != null && source != null) { destination.transferFrom(source, 0, source.size()); } if (source != null) { source.close(); } if (destination != null) { destination.close(); } }
11
Code Sample 1: public static boolean copyFileToDir(File inputFile, File outputDir) { try { String outputFileName = inputFile.getName(); int index = 1; while (existFileInDir(outputFileName, outputDir)) { outputFileName = index + inputFile.getName(); index++; } String directory = getDirectoryWithSlash(outputDir.getAbsolutePath()); File outputFile = new File(directory + outputFileName); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException e) { return false; } return true; } Code Sample 2: public static void main(String[] args) throws IOException { long start = System.currentTimeMillis(); FileResourceManager frm = CommonsTransactionContext.configure(new File("C:/tmp")); try { frm.start(); } catch (ResourceManagerSystemException e) { throw new RuntimeException(e); } FileInputStream is = new FileInputStream("C:/Alfresco/WCM_Eval_Guide2.0.pdf"); CommonsTransactionOutputStream os = new CommonsTransactionOutputStream(new Ownerr()); IOUtils.copy(is, os); IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); try { frm.stop(FileResourceManager.SHUTDOWN_MODE_NORMAL); } catch (ResourceManagerSystemException e) { throw new RuntimeException(e); } System.out.println(System.currentTimeMillis() - start); }
00
Code Sample 1: public void buildCache() { CacheManager.resetCache(); XMLCacheBuilder cacheBuilder = CompositePageUtil.getCacheBuilder(); if (cacheBuilder == null) return; String pathStr = cacheBuilder.getPath(); if (pathStr == null) return; String[] paths = pathStr.split("\n"); for (int i = 0; i < paths.length; i++) { try { String path = paths[i]; URL url = new URL(path); HttpURLConnection huc = (HttpURLConnection) url.openConnection(); huc.setDoInput(true); huc.setDoOutput(true); huc.setUseCaches(false); huc.setRequestProperty("Content-Type", "text/html"); DataOutputStream dos = new DataOutputStream(huc.getOutputStream()); dos.flush(); dos.close(); huc.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: public static void writeToFile(final File file, final InputStream in) throws IOException { IOUtils.createFile(file); FileOutputStream fos = null; try { fos = new FileOutputStream(file); IOUtils.copyStream(in, fos); } finally { IOUtils.closeIO(fos); } } Code Sample 2: public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { long time = System.currentTimeMillis(); String text = request.getParameter("text"); String parsedQueryString = request.getQueryString(); if (text == null) { String[] fonts = new File(ctx.getRealPath("/WEB-INF/fonts/")).list(); text = "accepted params: text,font,size,color,background,nocache,aa,break"; response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<p>"); out.println("Usage: " + request.getServletPath() + "?params[]<BR>"); out.println("Acceptable Params are: <UL>"); out.println("<LI><B>text</B><BR>"); out.println("The body of the image"); out.println("<LI><B>font</B><BR>"); out.println("Available Fonts (in folder '/WEB-INF/fonts/') <UL>"); for (int i = 0; i < fonts.length; i++) { if (!"CVS".equals(fonts[i])) { out.println("<LI>" + fonts[i]); } } out.println("</UL>"); out.println("<LI><B>size</B><BR>"); out.println("An integer, i.e. size=100"); out.println("<LI><B>color</B><BR>"); out.println("in rgb, i.e. color=255,0,0"); out.println("<LI><B>background</B><BR>"); out.println("in rgb, i.e. background=0,0,255"); out.println("transparent, i.e. background=''"); out.println("<LI><B>aa</B><BR>"); out.println("antialias (does not seem to work), aa=true"); out.println("<LI><B>nocache</B><BR>"); out.println("if nocache is set, we will write out the image file every hit. Otherwise, will write it the first time and then read the file"); out.println("<LI><B>break</B><BR>"); out.println("An integer greater than 0 (zero), i.e. break=20"); out.println("</UL>"); out.println("</UL>"); out.println("Example:<BR>"); out.println("&lt;img border=1 src=\"" + request.getServletPath() + "?font=arial.ttf&text=testing&color=255,0,0&size=100\"&gt;<BR>"); out.println("<img border=1 src='" + request.getServletPath() + "?font=arial.ttf&text=testing&color=255,0,0&size=100'><BR>"); out.println("</body>"); out.println("</html>"); return; } String myFile = (request.getQueryString() == null) ? "empty" : PublicEncryptionFactory.digestString(parsedQueryString).replace('\\', '_').replace('/', '_'); myFile = Config.getStringProperty("PATH_TO_TITLE_IMAGES") + myFile + ".png"; File file = new File(ctx.getRealPath(myFile)); if (!file.exists() || (request.getParameter("nocache") != null)) { StringTokenizer st = null; Iterator i = hm.entrySet().iterator(); while (i.hasNext()) { Map.Entry entry = (Map.Entry) i.next(); String key = (String) entry.getKey(); if (parsedQueryString.indexOf(key) > -1) { String val = (String) entry.getValue(); parsedQueryString = UtilMethods.replace(parsedQueryString, key, val); } } st = new StringTokenizer(parsedQueryString, "&"); while (st.hasMoreTokens()) { try { String x = st.nextToken(); String key = x.split("=")[0]; String val = x.split("=")[1]; if ("text".equals(key)) { text = val; } } catch (Exception e) { } } text = URLDecoder.decode(text, "UTF-8"); Logger.debug(this.getClass(), "building title image:" + file.getAbsolutePath()); file.createNewFile(); try { String font_file = "/WEB-INF/fonts/arial.ttf"; if (request.getParameter("font") != null) { font_file = "/WEB-INF/fonts/" + request.getParameter("font"); } font_file = ctx.getRealPath(font_file); float size = 20.0f; if (request.getParameter("size") != null) { size = Float.parseFloat(request.getParameter("size")); } Color background = Color.white; if (request.getParameter("background") != null) { if (request.getParameter("background").equals("transparent")) try { background = new Color(Color.TRANSLUCENT); } catch (Exception e) { } else try { st = new StringTokenizer(request.getParameter("background"), ","); int x = Integer.parseInt(st.nextToken()); int y = Integer.parseInt(st.nextToken()); int z = Integer.parseInt(st.nextToken()); background = new Color(x, y, z); } catch (Exception e) { } } Color color = Color.black; if (request.getParameter("color") != null) { try { st = new StringTokenizer(request.getParameter("color"), ","); int x = Integer.parseInt(st.nextToken()); int y = Integer.parseInt(st.nextToken()); int z = Integer.parseInt(st.nextToken()); color = new Color(x, y, z); } catch (Exception e) { Logger.info(this, e.getMessage()); } } int intBreak = 0; if (request.getParameter("break") != null) { try { intBreak = Integer.parseInt(request.getParameter("break")); } catch (Exception e) { } } java.util.ArrayList<String> lines = null; if (intBreak > 0) { lines = new java.util.ArrayList<String>(10); lines.ensureCapacity(10); int start = 0; String line = null; int offSet; for (; ; ) { try { for (; isWhitespace(text.charAt(start)); ++start) ; if (isWhitespace(text.charAt(start + intBreak - 1))) { lines.add(text.substring(start, start + intBreak)); start += intBreak; } else { for (offSet = -1; !isWhitespace(text.charAt(start + intBreak + offSet)); ++offSet) ; lines.add(text.substring(start, start + intBreak + offSet)); start += intBreak + offSet; } } catch (Exception e) { if (text.length() > start) lines.add(leftTrim(text.substring(start))); break; } } } else { java.util.StringTokenizer tokens = new java.util.StringTokenizer(text, "|"); if (tokens.hasMoreTokens()) { lines = new java.util.ArrayList<String>(10); lines.ensureCapacity(10); for (; tokens.hasMoreTokens(); ) lines.add(leftTrim(tokens.nextToken())); } } Font font = Font.createFont(Font.TRUETYPE_FONT, new FileInputStream(font_file)); font = font.deriveFont(size); BufferedImage buffer = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = buffer.createGraphics(); if (request.getParameter("aa") != null) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); } else { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } FontRenderContext fc = g2.getFontRenderContext(); Rectangle2D fontBounds = null; Rectangle2D textLayoutBounds = null; TextLayout tl = null; boolean useTextLayout = false; useTextLayout = Boolean.parseBoolean(request.getParameter("textLayout")); int width = 0; int height = 0; int offSet = 0; if (1 < lines.size()) { int heightMultiplier = 0; int maxWidth = 0; for (; heightMultiplier < lines.size(); ++heightMultiplier) { fontBounds = font.getStringBounds(lines.get(heightMultiplier), fc); tl = new TextLayout(lines.get(heightMultiplier), font, fc); textLayoutBounds = tl.getBounds(); if (maxWidth < Math.ceil(fontBounds.getWidth())) maxWidth = (int) Math.ceil(fontBounds.getWidth()); } width = maxWidth; int boundHeigh = (int) Math.ceil((!useTextLayout ? fontBounds.getHeight() : textLayoutBounds.getHeight())); height = boundHeigh * lines.size(); offSet = ((int) (boundHeigh * 0.2)) * (lines.size() - 1); } else { fontBounds = font.getStringBounds(text, fc); tl = new TextLayout(text, font, fc); textLayoutBounds = tl.getBounds(); width = (int) fontBounds.getWidth(); height = (int) Math.ceil((!useTextLayout ? fontBounds.getHeight() : textLayoutBounds.getHeight())); } buffer = new BufferedImage(width, height - offSet, BufferedImage.TYPE_INT_ARGB); g2 = buffer.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setFont(font); g2.setColor(background); if (!background.equals(new Color(Color.TRANSLUCENT))) g2.fillRect(0, 0, width, height); g2.setColor(color); if (1 < lines.size()) { for (int numLine = 0; numLine < lines.size(); ++numLine) { int y = (int) Math.ceil((!useTextLayout ? fontBounds.getY() : textLayoutBounds.getY())); g2.drawString(lines.get(numLine), 0, -y * (numLine + 1)); } } else { int y = (int) Math.ceil((!useTextLayout ? fontBounds.getY() : textLayoutBounds.getY())); g2.drawString(text, 0, -y); } BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file)); ImageIO.write(buffer, "png", out); out.close(); } catch (Exception ex) { Logger.info(this, ex.toString()); } } response.setContentType("image/png"); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); OutputStream os = response.getOutputStream(); byte[] buf = new byte[4096]; int i = 0; while ((i = bis.read(buf)) != -1) { os.write(buf, 0, i); } os.close(); bis.close(); Logger.debug(this.getClass(), "time to build title: " + (System.currentTimeMillis() - time) + "ms"); return; }
00
Code Sample 1: public void run() { long starttime = (new Date()).getTime(); Matcher m = Pattern.compile("(\\S+);(\\d+)").matcher(Destination); boolean completed = false; if (OutFile.length() > IncommingProcessor.MaxPayload) { logger.warn("Payload is too large!"); close(); } else { if (m.find()) { Runnable cl = new Runnable() { public void run() { WaitToClose(); } }; Thread t = new Thread(cl); t.start(); S = null; try { String ip = m.group(1); int port = Integer.valueOf(m.group(2)); SerpentEngine eng = new SerpentEngine(); byte[] keybytes = new byte[eng.getBlockSize()]; byte[] ivbytes = new byte[eng.getBlockSize()]; Random.nextBytes(keybytes); Random.nextBytes(ivbytes); KeyParameter keyparm = new KeyParameter(keybytes); ParametersWithIV keyivparm = new ParametersWithIV(keyparm, ivbytes); byte[] parmbytes = BCUtils.writeParametersWithIV(keyivparm); OAEPEncoding enc = new OAEPEncoding(new ElGamalEngine(), new RIPEMD128Digest()); enc.init(true, PublicKey); byte[] encbytes = enc.encodeBlock(parmbytes, 0, parmbytes.length); PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new SerpentEngine())); cipher.init(true, keyivparm); byte[] inbuffer = new byte[128]; byte[] outbuffer = new byte[256]; int readlen = 0; int cryptlen = 0; FileInputStream fis = new FileInputStream(OutFile); FileOutputStream fos = new FileOutputStream(TmpFile); readlen = fis.read(inbuffer); while (readlen >= 0) { if (readlen > 0) { cryptlen = cipher.processBytes(inbuffer, 0, readlen, outbuffer, 0); fos.write(outbuffer, 0, cryptlen); } readlen = fis.read(inbuffer); } cryptlen = cipher.doFinal(outbuffer, 0); if (cryptlen > 0) { fos.write(outbuffer, 0, cryptlen); } fos.close(); fis.close(); S = new Socket(ip, port); DataOutputStream dos = new DataOutputStream(S.getOutputStream()); dos.writeInt(encbytes.length); dos.write(encbytes); dos.writeLong(TmpFile.length()); fis = new FileInputStream(TmpFile); readlen = fis.read(inbuffer); while (readlen >= 0) { dos.write(inbuffer, 0, readlen); readlen = fis.read(inbuffer); } DataInputStream dis = new DataInputStream(S.getInputStream()); byte[] encipbytes = StreamUtils.readBytes(dis); cipher.init(false, keyivparm); byte[] decipbytes = new byte[encipbytes.length]; int len = cipher.processBytes(encipbytes, 0, encipbytes.length, decipbytes, 0); len += cipher.doFinal(decipbytes, len); byte[] realbytes = new byte[len]; System.arraycopy(decipbytes, 0, realbytes, 0, len); String ipstr = new String(realbytes, "ISO-8859-1"); Callback.Success(ipstr); completed = true; dos.write(0); dos.flush(); close(); } catch (Exception e) { close(); if (!completed) { e.printStackTrace(); Callback.Fail(e.getMessage()); } } } else { close(); logger.warn("Improper destination string. " + Destination); Callback.Fail("Improper destination string. " + Destination); } } CloseWait(); long newtime = (new Date()).getTime(); long timediff = newtime - starttime; logger.debug("Outgoing processor took: " + timediff); } Code Sample 2: static void sort(int[] a) { int i = 0; while (i < a.length - 1) { int j = 0; while (j < (a.length - i) - 1) { if (a[j] > a[j + 1]) { int aux = a[j]; a[j] = a[j + 1]; a[j + 1] = aux; } j = j + 1; } i = i + 1; } }
00
Code Sample 1: private void findRxnFileByUrl() throws MalformedURLException, IOException { URL url = new URL(MessageFormat.format(rxnUrl, reactionId.toString())); LOGGER.debug("Retrieving RXN file by URL " + url); URLConnection con = url.openConnection(java.net.Proxy.NO_PROXY); con.connect(); InputStream is = null; InputStreamReader isr = null; BufferedReader br = null; try { is = con.getInputStream(); isr = new InputStreamReader(is); br = new BufferedReader(isr); String line = null; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line).append('\n'); } rxnFile = sb.toString(); } catch (IOException e) { LOGGER.warn("Unable to retrieve RXN", e); } finally { if (br != null) { br.close(); } if (isr != null) { isr.close(); } if (is != null) { is.close(); } } } Code Sample 2: public static void notify(String msg) throws Exception { String url = "http://api.clickatell.com/http/sendmsg?"; url = add(url, "user", user); url = add(url, "password", password); url = add(url, "api_id", apiId); url = add(url, "to", to); url = add(url, "text", msg); URL u = new URL(url); URLConnection c = u.openConnection(); InputStream is = c.getInputStream(); IOUtils.copy(is, System.out); IOUtils.closeQuietly(is); System.out.println(); }
11
Code Sample 1: protected void initGame() { try { for (File fonte : files) { String absolutePath = outputDir.getAbsolutePath(); String separator = System.getProperty("file.separator"); String name = fonte.getName(); String destName = name.substring(0, name.length() - 3); File destino = new File(absolutePath + separator + destName + "jme"); FileInputStream reader = new FileInputStream(fonte); OutputStream writer = new FileOutputStream(destino); conversor.setProperty("mtllib", fonte.toURL()); conversor.convert(reader, writer); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } super.finish(); } Code Sample 2: public String[][] getProjectTreeData() { String[][] treeData = null; String filename = dms_home + FS + "temp" + FS + username + "projects.xml"; String urlString = dms_url + "/servlet/com.ufnasoft.dms.server.ServerGetProjects"; try { String urldata = urlString + "?username=" + URLEncoder.encode(username, "UTF-8") + "&key=" + URLEncoder.encode(key, "UTF-8") + "&filename=" + URLEncoder.encode(username, "UTF-8") + "projects.xml"; System.out.println(urldata); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); DocumentBuilder parser = factory.newDocumentBuilder(); URL u = new URL(urldata); DataInputStream is = new DataInputStream(u.openStream()); FileOutputStream os = new FileOutputStream(filename); int iBufSize = is.available(); byte inBuf[] = new byte[20000 * 1024]; int iNumRead; while ((iNumRead = is.read(inBuf, 0, iBufSize)) > 0) os.write(inBuf, 0, iNumRead); os.close(); is.close(); File f = new File(filename); InputStream inputstream = new FileInputStream(f); Document document = parser.parse(inputstream); NodeList nodelist = document.getElementsByTagName("j"); int num = nodelist.getLength(); treeData = new String[num][5]; for (int i = 0; i < num; i++) { treeData[i][0] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "i")); treeData[i][1] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "pi")); treeData[i][2] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "p")); treeData[i][3] = ""; treeData[i][4] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "f")); } } catch (MalformedURLException ex) { System.out.println(ex); } catch (ParserConfigurationException ex) { System.out.println(ex); } catch (NullPointerException e) { } catch (Exception ex) { System.out.println(ex); } return treeData; }
00
Code Sample 1: public static void get_PK_data() { try { FileWriter file_writer = new FileWriter("xml_data/PK_data_dump.xml"); BufferedWriter file_buffered_writer = new BufferedWriter(file_writer); URL fdt = new URL("http://opendata.5t.torino.it/get_pk"); URLConnection url_connection = fdt.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(url_connection.getInputStream())); String input_line; int num_lines = 0; while ((input_line = in.readLine()) != null) { file_buffered_writer.write(input_line + "\n"); num_lines++; } System.out.println("Parking :: Writed " + num_lines + " lines."); in.close(); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } } Code Sample 2: private String readWebpage() { BufferedReader in = null; StringBuffer sb = new StringBuffer(); try { URI uri = new URI("file:///www.vogella.de"); IProxyService proxyService = getProxyService(); IProxyData[] proxyDataForHost = proxyService.select(uri); for (IProxyData data : proxyDataForHost) { if (data.getHost() != null) { System.setProperty("http.proxySet", "true"); System.setProperty("http.proxyHost", data.getHost()); } if (data.getHost() != null) { System.setProperty("http.proxyPort", String.valueOf(data.getPort())); } } proxyService = null; URL url; url = uri.toURL(); in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { sb.append(inputLine + "\n"); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } return sb.toString(); }
00
Code Sample 1: public static void main(String[] args) { String u = "http://portal.acm.org/results.cfm?query=%28Author%3A%22" + "Boehm%2C+Barry" + "%22%29&srt=score%20dsc&short=0&source_disp=&since_month=&since_year=&before_month=&before_year=&coll=ACM&dl=ACM&termshow=matchboolean&range_query=&CFID=22704101&CFTOKEN=37827144&start=1"; URL url = null; AcmSearchresultPageParser_2010May cb = new AcmSearchresultPageParser_2010May(); try { url = new URL(u); HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.setUseCaches(false); InputStream is = uc.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); ParserDelegator pd = new ParserDelegator(); pd.parse(br, cb, true); br.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("all doc num= " + cb.getAllDocNum()); for (int i = 0; i < cb.getEachResultStartPositions().size(); i++) { HashMap<String, Integer> m = cb.getEachResultStartPositions().get(i); System.out.println(i + "pos= " + m); } } Code Sample 2: public Configuration(URL url) { InputStream in = null; try { load(in = url.openStream()); } catch (Exception e) { throw new RuntimeException("Could not load configuration from " + url, e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } }
00
Code Sample 1: public void readURL(URL url) throws IOException, ParserConfigurationException, SAXException { URLConnection connection; if (proxy == null) { connection = url.openConnection(); } else { connection = url.openConnection(proxy); } connection.setConnectTimeout(connectTimeout); connection.setReadTimeout(readTimeout); connection.connect(); InputStream in = connection.getInputStream(); readInputStream(in); } Code Sample 2: public synchronized void readProject(URL url, boolean addMembers) throws IOException { _url = url; try { readProject(url.openStream(), addMembers); } catch (IOException e) { Argo.log.info("Couldn't open InputStream in ArgoParser.load(" + url + ") " + e); e.printStackTrace(); lastLoadMessage = e.toString(); throw e; } }
00
Code Sample 1: public static void main(String[] args) throws Exception { FileChannel fc = new FileOutputStream("data.txt").getChannel(); fc.write(ByteBuffer.wrap("Some text ".getBytes())); fc.close(); fc = new RandomAccessFile("data.txt", "rw").getChannel(); fc.position(fc.size()); fc.write(ByteBuffer.wrap("Some more".getBytes())); fc.close(); fc = new FileInputStream("data.txt").getChannel(); ByteBuffer buff = ByteBuffer.allocate(BSIZE); fc.read(buff); buff.flip(); while (buff.hasRemaining()) System.out.print((char) buff.get()); } Code Sample 2: private List<Intrebare> citesteIntrebari() throws IOException { ArrayList<Intrebare> intrebari = new ArrayList<Intrebare>(); try { URL url = new URL(getCodeBase(), "../intrebari.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader((url.openStream()))); String intrebare; while ((intrebare = reader.readLine()) != null) { Collection<String> raspunsuri = new ArrayList<String>(); Collection<String> predicate = new ArrayList<String>(); String raspuns = ""; while (!"".equals(raspuns = reader.readLine())) { raspunsuri.add(raspuns); predicate.add(reader.readLine()); } Intrebare i = new Intrebare(intrebare, raspunsuri.toArray(new String[raspunsuri.size()]), predicate.toArray(new String[predicate.size()])); intrebari.add(i); } } catch (ArgumentExcetpion e) { e.printStackTrace(); } return intrebari; }
00
Code Sample 1: public String fetchContent(PathObject file) throws NetworkException { if (file.isFetched()) { return file.getContent(); } if (!"f".equals(file.getType())) { return null; } HttpClient client = HttpConfig.newInstance(); HttpGet get = new HttpGet(HttpConfig.bbsURL() + HttpConfig.BBS_ANC + file.getPath()); try { HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); Document doc = XmlOperator.readDocument(entity.getContent()); return BBSBodyParseHelper.parsePathContent(doc, file); } catch (Exception e) { e.printStackTrace(); throw new NetworkException(e); } } Code Sample 2: private void copyFile(String sourceFilename, String targetFilename) throws IOException { File source = new File(sourceFilename); File target = new File(targetFilename); InputStream in = new FileInputStream(source); OutputStream out = new FileOutputStream(target); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
00
Code Sample 1: public String getImageURL(String text) { String imgURL = ""; try { URL url = new URL("http://images.search.yahoo.com/search/images?p=" + URLEncoder.encode(text)); URLConnection connection = url.openConnection(); DataInputStream in = new DataInputStream(connection.getInputStream()); String line; Pattern imgPattern = Pattern.compile("isrc=\"([^\"]*)\""); while ((line = in.readLine()) != null) { Matcher match = imgPattern.matcher(line); if (match.find()) { imgURL = match.group(1); break; } } in.close(); } catch (Exception e) { } return imgURL; } Code Sample 2: public SimplePropertiesMessageRepository() { properties = new Properties(); try { URL url = SimplePropertiesIconRepository.class.getResource(PROPERTIES_FILE_NAME); properties.load(url.openStream()); } catch (Exception e) { throw new Error("Messages file not found: " + PROPERTIES_FILE_NAME); } }
00
Code Sample 1: public boolean actualizarIdPartida(int idJugadorDiv, int idRonda, int idPartida) { int intResult = 0; String sql = "UPDATE jugadorxdivxronda " + " SET idPartida = " + idPartida + " WHERE jugadorxDivision_idJugadorxDivision = " + idJugadorDiv + " AND ronda_numeroRonda = " + idRonda; try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); intResult = ps.executeUpdate(); connection.commit(); } catch (SQLException ex) { ex.printStackTrace(); try { connection.rollback(); } catch (SQLException exe) { exe.printStackTrace(); } } finally { conexionBD.close(ps); conexionBD.close(connection); } return (intResult > 0); } Code Sample 2: public static void main(String[] args) { final MavenDeployerGui gui = new MavenDeployerGui(); final Chooser repositoryChooser = new Chooser(gui.formPanel, JFileChooser.DIRECTORIES_ONLY); final Chooser artifactChooser = new Chooser(gui.formPanel, JFileChooser.FILES_ONLY); final Chooser pomChooser = new Chooser(gui.formPanel, JFileChooser.FILES_ONLY, new POMFilter()); gui.cancel.setEnabled(false); gui.cbDeployPOM.setVisible(false); gui.cbDeployPOM.setEnabled(false); gui.mavenBin.setText(findMavenExecutable()); gui.repositoryBrowser.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { File repo = repositoryChooser.chooseFrom(currentDir); if (repo != null) { currentDir = repositoryChooser.currentFolder; gui.repositoryURL.setText(repo.getAbsolutePath()); } } }); gui.artifactBrowser.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { File artifact = artifactChooser.chooseFrom(currentDir); if (artifact != null) { currentDir = artifactChooser.currentFolder; gui.artifactFile.setText(artifact.getAbsolutePath()); } } }); gui.deploy.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { deployer = new Deployer(gui, pom); deployer.execute(); } }); gui.clear.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { gui.console.setText(""); } }); gui.cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (deployer != null) { deployer.stop(); deployer = null; } } }); gui.cbDeployPOM.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { readPOM(gui); } }); gui.loadPOM.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { pom = pomChooser.chooseFrom(currentDir); if (pom != null) { currentDir = pomChooser.currentFolder; readPOM(gui); gui.cbDeployPOM.setText("Deploy also " + pom.getAbsolutePath()); gui.cbDeployPOM.setEnabled(true); gui.cbDeployPOM.setVisible(true); } } }); String version = ""; try { URL url = Thread.currentThread().getContextClassLoader().getResource("META-INF/maven/com.mycila.maven/maven-deployer/pom.properties"); Properties p = new Properties(); p.load(url.openStream()); version = " " + p.getProperty("version"); } catch (Exception ignored) { version = " x.y"; } JFrame frame = new JFrame("Maven Deployer" + version + " - By Mathieu Carbou (http://blog.mycila.com)"); frame.setContentPane(gui.formPanel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.setLocationByPlatform(true); frame.pack(); frame.setVisible(true); }
11
Code Sample 1: public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } Code Sample 2: public static void copy(String pstrFileFrom, String pstrFileTo) { try { FileChannel srcChannel = new FileInputStream(pstrFileFrom).getChannel(); FileChannel dstChannel = new FileOutputStream(pstrFileTo).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (Exception e) { throw new RuntimeException(e); } }
00
Code Sample 1: private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { jButton1.setEnabled(false); for (int i = 0; i < max; i++) { Card crd = WLP.getSelectedCard(WLP.jTable1.getSelectedRows()[i]); String s, s2; s = ""; s2 = ""; try { URL url = new URL("http://www.m-w.com/dictionary/" + crd.getWord()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { s = s + str; } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } Pattern pattern = Pattern.compile("popWin\\('/cgi-bin/(.+?)'", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher = pattern.matcher(s); if (matcher.find()) { String newurl = "http://m-w.com/cgi-bin/" + matcher.group(1); try { URL url2 = new URL(newurl); BufferedReader in2 = new BufferedReader(new InputStreamReader(url2.openStream())); String str; while ((str = in2.readLine()) != null) { s2 = s2 + str; } in2.close(); } catch (MalformedURLException e) { } catch (IOException e) { } Pattern pattern2 = Pattern.compile("<A HREF=\"http://(.+?)\">Click here to listen with your default audio player", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher2 = pattern2.matcher(s2); if (matcher2.find()) { getWave("http://" + matcher2.group(1), crd.getWord()); } int val = jProgressBar1.getValue(); val++; jProgressBar1.setValue(val); this.paintAll(this.getGraphics()); } } jButton1.setEnabled(true); } Code Sample 2: private InputStream open(String url) throws IOException { debug(url); if (!useCache) { return new URL(url).openStream(); } File f = new File(System.getProperty("java.io.tmpdir", "."), Digest.SHA1.encrypt(url) + ".xml"); debug("Cache : " + f); if (f.exists()) { return new FileInputStream(f); } InputStream in = new URL(url).openStream(); OutputStream out = new FileOutputStream(f); IOUtils.copyTo(in, out); out.flush(); out.close(); in.close(); return new FileInputStream(f); }
00
Code Sample 1: private boolean hasPackageInfo(URL url) { if (url == null) return false; BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = br.readLine()) != null) { if (line.startsWith("Specification-Title: ") || line.startsWith("Specification-Version: ") || line.startsWith("Specification-Vendor: ") || line.startsWith("Implementation-Title: ") || line.startsWith("Implementation-Version: ") || line.startsWith("Implementation-Vendor: ")) return true; } } catch (IOException ioe) { } finally { if (br != null) try { br.close(); } catch (IOException e) { } } return false; } Code Sample 2: public static void copyFile(File inputFile, File outputFile) throws IOException { BufferedInputStream fr = new BufferedInputStream(new FileInputStream(inputFile)); BufferedOutputStream fw = new BufferedOutputStream(new FileOutputStream(outputFile)); byte[] buf = new byte[8192]; int n; while ((n = fr.read(buf)) >= 0) fw.write(buf, 0, n); fr.close(); fw.close(); }
11
Code Sample 1: 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(); } Code Sample 2: public static void copyFile(File file, String pathExport) throws IOException { File out = new File(pathExport); FileChannel sourceChannel = new FileInputStream(file).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
11
Code Sample 1: protected void truncate(File file) { LogLog.debug("Compression of file: " + file.getAbsolutePath() + " started."); if (FileUtils.isFileOlder(file, ManagementFactory.getRuntimeMXBean().getStartTime())) { File backupRoot = new File(getBackupDir()); if (!backupRoot.exists() && !backupRoot.mkdirs()) { throw new AppenderInitializationError("Can't create backup dir for backup storage"); } SimpleDateFormat df; try { df = new SimpleDateFormat(getBackupDateFormat()); } catch (Exception e) { throw new AppenderInitializationError("Invalid date formate for backup files: " + getBackupDateFormat(), e); } String date = df.format(new Date(file.lastModified())); File zipFile = new File(backupRoot, file.getName() + "." + date + ".zip"); ZipOutputStream zos = null; FileInputStream fis = null; try { zos = new ZipOutputStream(new FileOutputStream(zipFile)); ZipEntry entry = new ZipEntry(file.getName()); entry.setMethod(ZipEntry.DEFLATED); entry.setCrc(FileUtils.checksumCRC32(file)); zos.putNextEntry(entry); fis = FileUtils.openInputStream(file); byte[] buffer = new byte[1024]; int readed; while ((readed = fis.read(buffer)) != -1) { zos.write(buffer, 0, readed); } } catch (Exception e) { throw new AppenderInitializationError("Can't create zip file", e); } finally { if (zos != null) { try { zos.close(); } catch (IOException e) { LogLog.warn("Can't close zip file", e); } } if (fis != null) { try { fis.close(); } catch (IOException e) { LogLog.warn("Can't close zipped file", e); } } } if (!file.delete()) { throw new AppenderInitializationError("Can't delete old log file " + file.getAbsolutePath()); } } } Code Sample 2: public static void CreateBackupOfDataFile(String _src, String _dest) { try { File src = new File(_src); File dest = new File(_dest); if (new File(_src).exists()) { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(src)); byte[] read = new byte[128]; int len = 128; while ((len = in.read(read)) > 0) out.write(read, 0, len); out.flush(); out.close(); in.close(); } } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public static void main(String[] args) throws Throwable { Options options = new Options(); options.addOption(new CommandLineOptionBuilder("cas", "cas file").isRequired(true).build()); options.addOption(new CommandLineOptionBuilder("o", "output directory").longName("outputDir").isRequired(true).build()); options.addOption(new CommandLineOptionBuilder("tempDir", "temp directory").build()); options.addOption(new CommandLineOptionBuilder("prefix", "file prefix for all generated files ( default " + DEFAULT_PREFIX + " )").build()); options.addOption(new CommandLineOptionBuilder("trim", "trim file in sfffile's tab delimmed trim format").build()); options.addOption(new CommandLineOptionBuilder("trimMap", "trim map file containing tab delimited trimmed fastX file to untrimmed counterpart").build()); options.addOption(new CommandLineOptionBuilder("chromat_dir", "directory of chromatograms to be converted into phd " + "(it is assumed the read data for these chromatograms are in a fasta file which the .cas file knows about").build()); options.addOption(new CommandLineOptionBuilder("s", "cache size ( default " + DEFAULT_CACHE_SIZE + " )").longName("cache_size").build()); options.addOption(new CommandLineOptionBuilder("useIllumina", "any FASTQ files in this assembly are encoded in Illumina 1.3+ format (default is Sanger)").isFlag(true).build()); options.addOption(new CommandLineOptionBuilder("useClosureTrimming", "apply additional contig trimming based on JCVI Closure rules").isFlag(true).build()); CommandLine commandLine; try { commandLine = CommandLineUtils.parseCommandLine(options, args); int cacheSize = commandLine.hasOption("s") ? Integer.parseInt(commandLine.getOptionValue("s")) : DEFAULT_CACHE_SIZE; File casFile = new File(commandLine.getOptionValue("cas")); File casWorkingDirectory = casFile.getParentFile(); ReadWriteDirectoryFileServer outputDir = DirectoryFileServer.createReadWriteDirectoryFileServer(commandLine.getOptionValue("o")); String prefix = commandLine.hasOption("prefix") ? commandLine.getOptionValue("prefix") : DEFAULT_PREFIX; TrimDataStore trimDatastore; if (commandLine.hasOption("trim")) { List<TrimDataStore> dataStores = new ArrayList<TrimDataStore>(); final String trimFiles = commandLine.getOptionValue("trim"); for (String trimFile : trimFiles.split(",")) { System.out.println("adding trim file " + trimFile); dataStores.add(new DefaultTrimFileDataStore(new File(trimFile))); } trimDatastore = MultipleDataStoreWrapper.createMultipleDataStoreWrapper(TrimDataStore.class, dataStores); } else { trimDatastore = TrimDataStoreUtil.EMPTY_DATASTORE; } CasTrimMap trimToUntrimmedMap; if (commandLine.hasOption("trimMap")) { trimToUntrimmedMap = new DefaultTrimFileCasTrimMap(new File(commandLine.getOptionValue("trimMap"))); } else { trimToUntrimmedMap = new UnTrimmedExtensionTrimMap(); } boolean useClosureTrimming = commandLine.hasOption("useClosureTrimming"); TraceDataStore<FileSangerTrace> sangerTraceDataStore = null; Map<String, File> sangerFileMap = null; ReadOnlyDirectoryFileServer sourceChromatogramFileServer = null; if (commandLine.hasOption("chromat_dir")) { sourceChromatogramFileServer = DirectoryFileServer.createReadOnlyDirectoryFileServer(new File(commandLine.getOptionValue("chromat_dir"))); sangerTraceDataStore = new SingleSangerTraceDirectoryFileDataStore(sourceChromatogramFileServer, ".scf"); sangerFileMap = new HashMap<String, File>(); Iterator<String> iter = sangerTraceDataStore.getIds(); while (iter.hasNext()) { String id = iter.next(); sangerFileMap.put(id, sangerTraceDataStore.get(id).getFile()); } } PrintWriter logOut = new PrintWriter(new FileOutputStream(outputDir.createNewFile(prefix + ".log")), true); PrintWriter consensusOut = new PrintWriter(new FileOutputStream(outputDir.createNewFile(prefix + ".consensus.fasta")), true); PrintWriter traceFilesOut = new PrintWriter(new FileOutputStream(outputDir.createNewFile(prefix + ".traceFiles.txt")), true); PrintWriter referenceFilesOut = new PrintWriter(new FileOutputStream(outputDir.createNewFile(prefix + ".referenceFiles.txt")), true); long startTime = System.currentTimeMillis(); logOut.println(System.getProperty("user.dir")); final ReadWriteDirectoryFileServer tempDir; if (!commandLine.hasOption("tempDir")) { tempDir = DirectoryFileServer.createTemporaryDirectoryFileServer(DEFAULT_TEMP_DIR); } else { File t = new File(commandLine.getOptionValue("tempDir")); IOUtil.mkdirs(t); tempDir = DirectoryFileServer.createTemporaryDirectoryFileServer(t); } try { if (!outputDir.contains("chromat_dir")) { outputDir.createNewDir("chromat_dir"); } if (sourceChromatogramFileServer != null) { for (File f : sourceChromatogramFileServer) { String name = f.getName(); OutputStream out = new FileOutputStream(outputDir.createNewFile("chromat_dir/" + name)); final FileInputStream fileInputStream = new FileInputStream(f); try { IOUtils.copy(fileInputStream, out); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(fileInputStream); } } } FastQQualityCodec qualityCodec = commandLine.hasOption("useIllumina") ? FastQQualityCodec.ILLUMINA : FastQQualityCodec.SANGER; CasDataStoreFactory casDataStoreFactory = new MultiCasDataStoreFactory(new H2SffCasDataStoreFactory(casWorkingDirectory, tempDir, EmptyDataStoreFilter.INSTANCE), new H2FastQCasDataStoreFactory(casWorkingDirectory, trimToUntrimmedMap, qualityCodec, tempDir.getRootDir()), new FastaCasDataStoreFactory(casWorkingDirectory, trimToUntrimmedMap, cacheSize)); final SliceMapFactory sliceMapFactory = new LargeNoQualitySliceMapFactory(); CasAssembly casAssembly = new DefaultCasAssembly.Builder(casFile, casDataStoreFactory, trimDatastore, trimToUntrimmedMap, casWorkingDirectory).build(); System.out.println("finished making casAssemblies"); for (File traceFile : casAssembly.getNuceotideFiles()) { traceFilesOut.println(traceFile.getAbsolutePath()); final String name = traceFile.getName(); String extension = FilenameUtils.getExtension(name); if (name.contains("fastq")) { if (!outputDir.contains("solexa_dir")) { outputDir.createNewDir("solexa_dir"); } if (outputDir.contains("solexa_dir/" + name)) { IOUtil.delete(outputDir.getFile("solexa_dir/" + name)); } outputDir.createNewSymLink(traceFile.getAbsolutePath(), "solexa_dir/" + name); } else if ("sff".equals(extension)) { if (!outputDir.contains("sff_dir")) { outputDir.createNewDir("sff_dir"); } if (outputDir.contains("sff_dir/" + name)) { IOUtil.delete(outputDir.getFile("sff_dir/" + name)); } outputDir.createNewSymLink(traceFile.getAbsolutePath(), "sff_dir/" + name); } } for (File traceFile : casAssembly.getReferenceFiles()) { referenceFilesOut.println(traceFile.getAbsolutePath()); } DataStore<CasContig> contigDatastore = casAssembly.getContigDataStore(); Map<String, AceContig> aceContigs = new HashMap<String, AceContig>(); CasIdLookup readIdLookup = sangerFileMap == null ? casAssembly.getReadIdLookup() : new DifferentFileCasIdLookupAdapter(casAssembly.getReadIdLookup(), sangerFileMap); Date phdDate = new Date(startTime); NextGenClosureAceContigTrimmer closureContigTrimmer = null; if (useClosureTrimming) { closureContigTrimmer = new NextGenClosureAceContigTrimmer(2, 5, 10); } for (CasContig casContig : contigDatastore) { final AceContigAdapter adpatedCasContig = new AceContigAdapter(casContig, phdDate, readIdLookup); CoverageMap<CoverageRegion<AcePlacedRead>> coverageMap = DefaultCoverageMap.buildCoverageMap(adpatedCasContig); for (AceContig aceContig : ConsedUtil.split0xContig(adpatedCasContig, coverageMap)) { if (useClosureTrimming) { AceContig trimmedAceContig = closureContigTrimmer.trimContig(aceContig); if (trimmedAceContig == null) { System.out.printf("%s was completely trimmed... skipping%n", aceContig.getId()); continue; } aceContig = trimmedAceContig; } aceContigs.put(aceContig.getId(), aceContig); consensusOut.print(new DefaultNucleotideEncodedSequenceFastaRecord(aceContig.getId(), NucleotideGlyph.convertToString(NucleotideGlyph.convertToUngapped(aceContig.getConsensus().decode())))); } } System.out.printf("finished adapting %d casAssemblies into %d ace contigs%n", contigDatastore.size(), aceContigs.size()); QualityDataStore qualityDataStore = sangerTraceDataStore == null ? casAssembly.getQualityDataStore() : MultipleDataStoreWrapper.createMultipleDataStoreWrapper(QualityDataStore.class, TraceQualityDataStoreAdapter.adapt(sangerTraceDataStore), casAssembly.getQualityDataStore()); final DateTime phdDateTime = new DateTime(phdDate); final PhdDataStore casPhdDataStore = CachedDataStore.createCachedDataStore(PhdDataStore.class, new ArtificalPhdDataStore(casAssembly.getNucleotideDataStore(), qualityDataStore, phdDateTime), cacheSize); final PhdDataStore phdDataStore = sangerTraceDataStore == null ? casPhdDataStore : MultipleDataStoreWrapper.createMultipleDataStoreWrapper(PhdDataStore.class, new PhdSangerTraceDataStoreAdapter<FileSangerTrace>(sangerTraceDataStore, phdDateTime), casPhdDataStore); WholeAssemblyAceTag pathToPhd = new DefaultWholeAssemblyAceTag("phdball", "cas2consed", new Date(DateTimeUtils.currentTimeMillis()), "../phd_dir/" + prefix + ".phd.ball"); AceAssembly aceAssembly = new DefaultAceAssembly<AceContig>(new SimpleDataStore<AceContig>(aceContigs), phdDataStore, Collections.<File>emptyList(), new DefaultAceTagMap(Collections.<ConsensusAceTag>emptyList(), Collections.<ReadAceTag>emptyList(), Arrays.asList(pathToPhd))); System.out.println("writing consed package..."); ConsedWriter.writeConsedPackage(aceAssembly, sliceMapFactory, outputDir.getRootDir(), prefix, false); } catch (Throwable t) { t.printStackTrace(logOut); throw t; } finally { long endTime = System.currentTimeMillis(); logOut.printf("took %s%n", new Period(endTime - startTime)); logOut.flush(); logOut.close(); outputDir.close(); consensusOut.close(); traceFilesOut.close(); referenceFilesOut.close(); trimDatastore.close(); } } catch (ParseException e) { printHelp(options); System.exit(1); } }
00
Code Sample 1: public void testExplicitHeaders() throws Exception { String headerString = "X-Foo=bar&X-Bar=baz%20foo"; HttpRequest expected = new HttpRequest(REQUEST_URL).addHeader("X-Foo", "bar").addHeader("X-Bar", "baz foo"); expect(pipeline.execute(expected)).andReturn(new HttpResponse(RESPONSE_BODY)); expect(request.getParameter(MakeRequestHandler.HEADERS_PARAM)).andReturn(headerString); replay(); handler.fetch(request, recorder); verify(); JSONObject results = extractJsonFromResponse(); assertEquals(HttpResponse.SC_OK, results.getInt("rc")); assertEquals(RESPONSE_BODY, results.get("body")); assertTrue(rewriter.responseWasRewritten()); } Code Sample 2: void bubbleSort(int[] a) { int i = 0; int j = a.length - 1; int aux = 0; int stop = 0; while (stop == 0) { stop = 1; i = 0; while (i < j) { if (a[i] > a[i + 1]) { aux = a[i]; a[i] = a[i + 1]; a[i + 1] = aux; stop = 0; } i = i + 1; } j = j - 1; } }
11
Code Sample 1: private void execute(String file, String[] ebms, String[] eems, String[] ims, String[] efms) throws BuildException { if (verbose) { System.out.println("Preprocessing file " + file + " (type: " + type + ")"); } try { File targetFile = new File(file); FileReader fr = new FileReader(targetFile); BufferedReader reader = new BufferedReader(fr); File preprocFile = File.createTempFile(targetFile.getName(), "tmp", targetFile.getParentFile()); FileWriter fw = new FileWriter(preprocFile); BufferedWriter writer = new BufferedWriter(fw); int result = preprocess(reader, writer, ebms, eems, ims, efms); reader.close(); writer.close(); switch(result) { case OVERWRITE: if (!targetFile.delete()) { System.out.println("Can't overwrite target file with preprocessed file"); throw new BuildException("Can't overwrite target file " + target + " with preprocessed file"); } preprocFile.renameTo(targetFile); if (verbose) { System.out.println("File " + preprocFile.getName() + " modified."); } modifiedCnt++; break; case REMOVE: if (!targetFile.delete()) { System.out.println("Can't delete target file"); throw new BuildException("Can't delete target file " + target); } if (!preprocFile.delete()) { System.out.println("Can't delete temporary preprocessed file " + preprocFile.getName()); throw new BuildException("Can't delete temporary preprocessed file " + preprocFile.getName()); } if (verbose) { System.out.println("File " + preprocFile.getName() + " removed."); } removedCnt++; break; case KEEP: if (!preprocFile.delete()) { System.out.println("Can't delete temporary preprocessed file " + preprocFile.getName()); throw new BuildException("Can't delete temporary preprocessed file " + preprocFile.getName()); } break; default: throw new BuildException("Unexpected preprocessing result for file " + preprocFile.getName()); } } catch (Exception e) { e.printStackTrace(); throw new BuildException(e.getMessage()); } } Code Sample 2: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: void loadPlaylist() { if (running_as_applet) { String s = null; for (int i = 0; i < 10; i++) { s = getParameter("jorbis.player.play." + i); if (s == null) break; playlist.addElement(s); } } if (playlistfile == null) { return; } try { InputStream is = null; try { URL url = null; if (running_as_applet) url = new URL(getCodeBase(), playlistfile); else url = new URL(playlistfile); URLConnection urlc = url.openConnection(); is = urlc.getInputStream(); } catch (Exception ee) { } if (is == null && !running_as_applet) { try { is = new FileInputStream(System.getProperty("user.dir") + System.getProperty("file.separator") + playlistfile); } catch (Exception ee) { } } if (is == null) return; while (true) { String line = readline(is); if (line == null) break; byte[] foo = line.getBytes(); for (int i = 0; i < foo.length; i++) { if (foo[i] == 0x0d) { line = new String(foo, 0, i); break; } } playlist.addElement(line); } } catch (Exception e) { System.out.println(e); } } Code Sample 2: public static void getGroupsImage(String username) { try { URL url = new URL("http://www.lastfm.de/user/" + username + "/groups/"); URLConnection con = url.openConnection(); HashMap hm = new HashMap(); Parser parser = new Parser(con); NodeList images = parser.parse(new TagNameFilter("IMG")); System.out.println(images.size()); for (int i = 0; i < images.size(); i++) { Node bild = images.elementAt(i); String bilder = bild.getText(); if (bilder.contains("http://panther1.last.fm/groupava")) { String bildurl = bilder.substring(9, 81); StringTokenizer st = new StringTokenizer(bilder.substring(88), "\""); String groupname = st.nextToken(); hm.put(groupname, bildurl); } } DB_Groups.addGroupImage(hm); System.out.println("log3"); } catch (ParserException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: private String fetchCompareContent() throws IOException { URL url = new URL(compareTo); StringWriter sw = new StringWriter(); IOUtils.copy(url.openStream(), sw); return sw.getBuffer().toString(); } Code Sample 2: public static void fastBackup(File file) { FileChannel in = null; FileChannel out = null; FileInputStream fin = null; FileOutputStream fout = null; try { in = (fin = new FileInputStream(file)).getChannel(); out = (fout = new FileOutputStream(file.getAbsolutePath() + ".bak")).getChannel(); in.transferTo(0, in.size(), out); } catch (IOException e) { Logging.getErrorLog().reportError("Fast backup failure (" + file.getAbsolutePath() + "): " + e.getMessage()); } finally { if (fin != null) { try { fin.close(); } catch (IOException e) { Logging.getErrorLog().reportException("Failed to close file input stream", e); } } if (fout != null) { try { fout.close(); } catch (IOException e) { Logging.getErrorLog().reportException("Failed to close file output stream", e); } } if (in != null) { try { in.close(); } catch (IOException e) { Logging.getErrorLog().reportException("Failed to close file channel", e); } } if (out != null) { try { out.close(); } catch (IOException e) { Logging.getErrorLog().reportException("Failed to close file channel", e); } } } }
00
Code Sample 1: public static void convertEncoding(File infile, File outfile, String from, String to) throws IOException, UnsupportedEncodingException { InputStream in; if (infile != null) in = new FileInputStream(infile); else in = System.in; OutputStream out; outfile.createNewFile(); if (outfile != null) out = new FileOutputStream(outfile); else out = System.out; if (from == null) from = System.getProperty("file.encoding"); if (to == null) to = "Unicode"; Reader r = new BufferedReader(new InputStreamReader(in, from)); Writer w = new BufferedWriter(new OutputStreamWriter(out, to)); char[] buffer = new char[4096]; int len; while ((len = r.read(buffer)) != -1) w.write(buffer, 0, len); r.close(); w.close(); } Code Sample 2: private void handleNodeUp(long eventID, long nodeID, String eventTime) { Category log = ThreadCategory.getInstance(OutageWriter.class); if (eventID == -1 || nodeID == -1) { log.warn(EventConstants.NODE_UP_EVENT_UEI + " ignored - info incomplete - eventid/nodeid: " + eventID + "/" + nodeID); return; } Connection dbConn = null; try { dbConn = DatabaseConnectionFactory.getInstance().getConnection(); int count = 0; if (openOutageExists(dbConn, nodeID)) { try { dbConn.setAutoCommit(false); } catch (SQLException sqle) { log.error("Unable to change database AutoCommit to FALSE", sqle); return; } PreparedStatement outageUpdater = dbConn.prepareStatement(OutageConstants.DB_UPDATE_OUTAGES_FOR_NODE); outageUpdater.setLong(1, eventID); outageUpdater.setTimestamp(2, convertEventTimeIntoTimestamp(eventTime)); outageUpdater.setLong(3, nodeID); count = outageUpdater.executeUpdate(); outageUpdater.close(); } else { log.warn("\'" + EventConstants.NODE_UP_EVENT_UEI + "\' for " + nodeID + " no open record."); } try { dbConn.commit(); if (log.isDebugEnabled()) log.debug("nodeUp closed " + count + " outages for nodeid " + nodeID + " in DB"); } catch (SQLException se) { log.warn("Rolling back transaction, nodeUp could not be recorded for nodeId: " + nodeID, se); try { dbConn.rollback(); } catch (SQLException sqle) { log.warn("SQL exception during rollback, reason", sqle); } } } catch (SQLException se) { log.warn("SQL exception while handling \'nodeRegainedService\'", se); } finally { try { if (dbConn != null) dbConn.close(); } catch (SQLException e) { log.warn("Exception closing JDBC connection", e); } } }
00
Code Sample 1: public static String md5Encode16(String s) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(s.getBytes("utf-8")); byte b[] = md.digest(); int i; StringBuilder buf = new StringBuilder(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } return buf.toString().substring(8, 24); } catch (Exception e) { throw new RuntimeException(e); } } Code Sample 2: public InputStream unZip(URL url) throws Exception { ZipInputStream zipped = new ZipInputStream(url.openStream()); System.out.println("unzipping: " + url.getFile()); ZipEntry zip = zipped.getNextEntry(); byte[] b = new byte[4096]; ByteArrayOutputStream bOut = new ByteArrayOutputStream(); for (int iRead = zipped.read(b); iRead != -1; iRead = zipped.read(b)) { bOut.write(b, 0, iRead); } zipped.close(); ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); return (InputStream) bIn; }
00
Code Sample 1: public static void copyFile(File in, File out) { try { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: JSONResponse execute() throws ServerException, RtmApiException, IOException { HttpClient httpclient = new DefaultHttpClient(); URI uri; try { uri = new URI(this.request.getUrl()); HttpPost httppost = new HttpPost(uri); HttpResponse response = httpclient.execute(httppost); InputStream is = response.getEntity().getContent(); try { StringBuilder sb = new StringBuilder(); BufferedReader r = new BufferedReader(new InputStreamReader(new DoneHandlerInputStream(is))); for (String line = r.readLine(); line != null; line = r.readLine()) { sb.append(line); } return new JSONResponse(sb.toString()); } finally { is.close(); } } catch (URISyntaxException e) { throw new RtmApiException(e.getMessage()); } catch (ClientProtocolException e) { throw new RtmApiException(e.getMessage()); } }
00
Code Sample 1: private static AtomContainer askForMovieSettings() throws IOException, QTException { final InputStream inputStream = QuickTimeFormatGenerator.class.getResourceAsStream(REFERENCE_MOVIE_RESOURCE); final ByteArrayOutputStream byteArray = new ByteArrayOutputStream(1024 * 100); IOUtils.copy(inputStream, byteArray); final byte[] movieBytes = byteArray.toByteArray(); final QTHandle qtHandle = new QTHandle(movieBytes); final DataRef dataRef = new DataRef(qtHandle, StdQTConstants.kDataRefFileExtensionTag, ".mov"); final Movie movie = Movie.fromDataRef(dataRef, StdQTConstants.newMovieActive | StdQTConstants4.newMovieAsyncOK); final MovieExporter exporter = new MovieExporter(StdQTConstants.kQTFileTypeMovie); exporter.doUserDialog(movie, null, 0, movie.getDuration()); return exporter.getExportSettingsFromAtomContainer(); } Code Sample 2: public boolean validateLogin(String username, String password) { boolean user_exists = false; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); String password_hash = hash.toString(16); statement = connect.prepareStatement("SELECT id from toepen.users WHERE username = ? AND password = ?"); statement.setString(1, username); statement.setString(2, password_hash); resultSet = statement.executeQuery(); while (resultSet.next()) { user_exists = true; } } catch (Exception ex) { System.out.println(ex); } finally { close(); return user_exists; } }
00
Code Sample 1: public Blowfish(String password) { MessageDigest digest = null; try { digest = MessageDigest.getInstance("SHA1"); digest.update(password.getBytes()); } catch (Exception e) { System.out.println(e); } m_bfish = new BlowfishCBC(digest.digest(), 0); digest.reset(); } Code Sample 2: public void submitReport() { String subject = m_Subject.getText(); String description = m_Description.getText(); String email = m_Email.getText(); if (subject.length() == 0) { Util.flashComponent(m_Subject, Color.RED); return; } if (description.length() == 0) { Util.flashComponent(m_Description, Color.RED); return; } DynamicLocalisation loc = m_MainFrame.getLocalisation(); if (email.length() == 0 || email.indexOf("@") == -1 || email.indexOf(".") == -1 || email.startsWith("@")) { email = "[email protected]"; } try { String data = URLEncoder.encode("mode", "UTF-8") + "=" + URLEncoder.encode("manual", "UTF-8"); data += "&" + URLEncoder.encode("from", "UTF-8") + "=" + URLEncoder.encode(email, "UTF-8"); data += "&" + URLEncoder.encode("subject", "UTF-8") + "=" + URLEncoder.encode(subject, "UTF-8"); data += "&" + URLEncoder.encode("body", "UTF-8") + "=" + URLEncoder.encode(description, "UTF-8"); data += "&" + URLEncoder.encode("jvm", "UTF-8") + "=" + URLEncoder.encode(System.getProperty("java.version"), "UTF-8"); data += "&" + URLEncoder.encode("ocdsver", "UTF-8") + "=" + URLEncoder.encode(Constants.OPENCDS_VERSION, "UTF-8"); data += "&" + URLEncoder.encode("os", "UTF-8") + "=" + URLEncoder.encode(Constants.OS_NAME + " " + System.getProperty("os.version") + " " + System.getProperty("os.arch"), "UTF-8"); URL url = new URL(Constants.BUGREPORT_SCRIPT); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { System.out.println(line); } wr.close(); rd.close(); JOptionPane.showMessageDialog(this, loc.getMessage("ReportBug.SentMessage")); } catch (Exception e) { Logger.getInstance().logException(e); } dispose(); }
00
Code Sample 1: private ArrayList<IdLocation> doGet(String identifier) throws IdLocatorException { String openurl = baseurl.toString() + "?url_ver=Z39.88-2004&rft_id=" + identifier; URL url; SRUSearchRetrieveResponse sru; try { url = new URL(openurl); HttpURLConnection huc = (HttpURLConnection) (url.openConnection()); int code = huc.getResponseCode(); if (code == 200) { sru = SRUSearchRetrieveResponse.read(huc.getInputStream()); } else throw new IdLocatorException("cannot get " + url.toString()); } catch (MalformedURLException e) { throw new IdLocatorException("A MalformedURLException occurred for " + openurl); } catch (IOException e) { throw new IdLocatorException("An IOException occurred attempting to connect to " + openurl); } catch (SRUException e) { throw new IdLocatorException("An SRUException occurred attempting to parse the response"); } ArrayList<IdLocation> ids = new ArrayList<IdLocation>(); for (SRUDC dc : sru.getRecords()) { IdLocation id = new IdLocation(); id.setId(dc.getKeys(SRUDC.Key.IDENTIFIER).firstElement()); id.setRepo(dc.getKeys(SRUDC.Key.SOURCE).firstElement()); id.setDate(dc.getKeys(SRUDC.Key.DATE).firstElement()); ids.add(id); } Collections.sort(ids); return ids; } Code Sample 2: public static void copyFile(File in, File outDir) throws IOException { FileChannel sourceChannel = null; FileChannel destinationChannel = null; try { sourceChannel = new FileInputStream(in).getChannel(); File out = new File(outDir, in.getName()); destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); } finally { try { if (sourceChannel != null) { sourceChannel.close(); } } finally { if (destinationChannel != null) { destinationChannel.close(); } } } }
00
Code Sample 1: public synchronized void receive(MessageEvent e) { switch(e.message.getType()) { case MessageTypes.QUIT: activeSessions--; break; case MessageTypes.SHUTDOWN_SERVER: activeSessions--; if (Options.password.trim().equals("")) { System.err.println("No default password set. Shutdown not allowed."); break; } if (e.message.get("pwhash") == null) { System.err.println("Shutdown message without password received. Shutdown not allowed."); break; } try { java.security.MessageDigest hash = java.security.MessageDigest.getInstance("SHA-1"); hash.update(Options.password.getBytes("UTF-8")); if (!java.security.MessageDigest.isEqual(hash.digest(), (byte[]) e.message.get("pwhash"))) { System.err.println("Wrong shutdown password. Shutdown not allowed."); break; } else { System.out.println("Valid shutdown password received."); } } catch (java.security.NoSuchAlgorithmException ex) { System.err.println("Password hash algorithm SHA-1 not supported by runtime."); break; } catch (UnsupportedEncodingException ex) { System.err.println("Password character encoding not supported."); break; } catch (Exception ex) { System.err.println("Unhandled exception occured. Shutdown aborted. Details:"); ex.printStackTrace(System.err); break; } if (activeSessions == 0) tStop(); else System.err.println("there are other active sessions - shutdown failed"); break; default: } } Code Sample 2: private static void fileUpload() throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(postURL); file = new File("h:\\Fantastic face.jpg"); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); ContentBody cbFile = new FileBody(file); mpEntity.addPart("MAX_FILE_SIZE", new StringBody("2147483647")); mpEntity.addPart("owner", new StringBody("")); mpEntity.addPart("pin", new StringBody(pin)); mpEntity.addPart("base", new StringBody(base)); mpEntity.addPart("host", new StringBody("letitbit.net")); mpEntity.addPart("file0", cbFile); httppost.setEntity(mpEntity); System.out.println("executing request " + httppost.getRequestLine()); System.out.println("Now uploading your file into letitbit.net"); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println(response.getStatusLine()); if (resEntity != null) { uploadresponse = EntityUtils.toString(resEntity); } System.out.println("Upload response : " + uploadresponse); }
00
Code Sample 1: public boolean save(String trxName) { if (m_value == null || (!(m_value instanceof String || m_value instanceof byte[])) || (m_value instanceof String && m_value.toString().length() == 0) || (m_value instanceof byte[] && ((byte[]) m_value).length == 0)) { StringBuffer sql = new StringBuffer("UPDATE ").append(m_tableName).append(" SET ").append(m_columnName).append("=null WHERE ").append(m_whereClause); int no = DB.executeUpdate(sql.toString(), trxName); log.fine("save [" + trxName + "] #" + no + " - no data - set to null - " + m_value); if (no == 0) log.warning("[" + trxName + "] - not updated - " + sql); return true; } StringBuffer sql = new StringBuffer("UPDATE ").append(m_tableName).append(" SET ").append(m_columnName).append("=? WHERE ").append(m_whereClause); boolean success = true; if (DB.isRemoteObjects()) { log.fine("[" + trxName + "] - Remote - " + m_value); Server server = CConnection.get().getServer(); try { if (server != null) { success = server.updateLOB(sql.toString(), m_displayType, m_value, trxName, SecurityToken.getInstance()); if (CLogMgt.isLevelFinest()) log.fine("server.updateLOB => " + success); return success; } log.log(Level.SEVERE, "AppsServer not found"); } catch (RemoteException ex) { log.log(Level.SEVERE, "AppsServer error", ex); } return false; } log.fine("[" + trxName + "] - Local - " + m_value); Trx trx = null; if (trxName != null) trx = Trx.get(trxName, false); Connection con = null; if (trx != null) con = trx.getConnection(); if (con == null) con = DB.createConnection(false, Connection.TRANSACTION_READ_COMMITTED); if (con == null) { log.log(Level.SEVERE, "Could not get Connection"); return false; } PreparedStatement pstmt = null; success = true; try { pstmt = con.prepareStatement(sql.toString()); if (m_displayType == DisplayType.TextLong) pstmt.setString(1, (String) m_value); else pstmt.setBytes(1, (byte[]) m_value); int no = pstmt.executeUpdate(); if (no != 1) { log.warning("[" + trxName + "] - Not updated #" + no + " - " + sql); success = false; } } catch (Throwable e) { log.log(Level.SEVERE, "[" + trxName + "] - " + sql, e); success = false; } finally { DB.close(pstmt); pstmt = null; } if (success) { if (trx != null) { trx = null; con = null; } else { try { con.commit(); } catch (Exception e) { log.log(Level.SEVERE, "[" + trxName + "] - commit ", e); success = false; } finally { try { con.close(); } catch (SQLException e) { } con = null; } } } if (!success) { log.severe("[" + trxName + "] - rollback"); if (trx != null) { trx.rollback(); trx = null; con = null; } else { try { con.rollback(); } catch (Exception ee) { log.log(Level.SEVERE, "[" + trxName + "] - rollback", ee); } finally { try { con.close(); } catch (SQLException e) { } con = null; } } } return success; } Code Sample 2: private static void initMagicRules() { InputStream in = null; try { String fname = System.getProperty("magic-mime"); if (fname != null && fname.length() != 0) { in = new FileInputStream(fname); if (in != null) { parse("-Dmagic-mime=" + fname, new InputStreamReader(in)); } } } catch (Exception e) { log.error("Failed to parse custom magic mime file defined by system property -Dmagic-mime [" + System.getProperty("magic-mime") + "]. File will be ignored.", e); } finally { in = closeStream(in); } try { Enumeration en = MimeUtil.class.getClassLoader().getResources("magic.mime"); while (en.hasMoreElements()) { URL url = (URL) en.nextElement(); in = url.openStream(); if (in != null) { try { parse("classpath:[" + url + "]", new InputStreamReader(in)); } catch (Exception ex) { log.error("Failed to parse magic.mime rule file [" + url + "] on the classpath. File will be ignored.", ex); } } } } catch (Exception e) { log.error("Problem while processing magic.mime files from classpath. Files will be ignored.", e); } finally { in = closeStream(in); } try { File f = new File(System.getProperty("user.home") + File.separator + ".magic.mime"); if (f.exists()) { in = new FileInputStream(f); if (in != null) { try { parse(f.getAbsolutePath(), new InputStreamReader(in)); } catch (Exception ex) { log.error("Failed to parse .magic.mime file from the users home directory. File will be ignored.", ex); } } } } catch (Exception e) { log.error("Problem while processing .magic.mime file from the users home directory. File will be ignored.", e); } finally { in = closeStream(in); } try { String name = System.getProperty("MAGIC"); if (name != null && name.length() != 0) { if (name.indexOf('.') < 0) { name = name + ".mime"; } else { name = name.substring(0, name.indexOf('.') - 1) + "mime"; } File f = new File(name); if (f.exists()) { in = new FileInputStream(f); if (in != null) { try { parse(f.getAbsolutePath(), new InputStreamReader(in)); } catch (Exception ex) { log.error("Failed to parse magic.mime file from directory located by environment variable MAGIC. File will be ignored.", ex); } } } } } catch (Exception e) { log.error("Problem while processing magic.mime file from directory located by environment variable MAGIC. File will be ignored.", e); } finally { in = closeStream(in); } int mMagicMimeEntriesSizeBeforeReadingOS = mMagicMimeEntries.size(); Iterator it = magicMimeFileLocations.iterator(); while (it.hasNext()) { parseMagicMimeFileLocation((String) it.next()); } if (mMagicMimeEntriesSizeBeforeReadingOS == mMagicMimeEntries.size()) { try { String resource = "eu/medsea/mimeutil/magic.mime"; in = MimeUtil.class.getClassLoader().getResourceAsStream(resource); if (in != null) { try { parse("resource:" + resource, new InputStreamReader(in)); } catch (Exception ex) { log.error("Failed to parse internal magic.mime file.", ex); } } } catch (Exception e) { log.error("Problem while processing internal magic.mime file.", e); } finally { in = closeStream(in); } } }
00
Code Sample 1: protected long getUrlSize(String location) { long returnValue = 0L; try { URL url = new URL(location); java.net.HttpURLConnection conn = (java.net.HttpURLConnection) url.openConnection(); conn.setRequestMethod("HEAD"); returnValue = conn.getContentLength(); } catch (IOException ioe) { logger.error("Failed to find proper size for entity at " + location, ioe); } return returnValue; } Code Sample 2: public void addForwardAddress(final List<NewUser> forwardAddresses) { try { final List<Integer> usersToRemoveFromCache = new ArrayList<Integer>(); connection.setAutoCommit(false); new ProcessEnvelope().executeNull(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public void executeProcessReturnNull() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty("userForwardAddresses.add")); Iterator<NewUser> iter = forwardAddresses.iterator(); Iterator<String> iter2; NewUser newUser; while (iter.hasNext()) { newUser = iter.next(); psImpl.setInt(1, newUser.userId); iter2 = newUser.forwardAddresses.iterator(); while (iter2.hasNext()) { psImpl.setString(2, iter2.next()); psImpl.executeUpdate(); } usersToRemoveFromCache.add(newUser.userId); } } }); connection.commit(); cmDB.removeUsers(usersToRemoveFromCache); } catch (SQLException sqle) { log.error(sqle); if (connection != null) { try { connection.rollback(); } catch (SQLException ex) { } } } finally { if (connection != null) { try { connection.setAutoCommit(true); } catch (SQLException ex) { } } } }
00
Code Sample 1: protected void innerProcess(CrawlURI curi) throws InterruptedException { if (!curi.isHttpTransaction()) { return; } if (!TextUtils.matches("^text.*$", curi.getContentType())) { return; } long maxsize = DEFAULT_MAX_SIZE_BYTES.longValue(); try { maxsize = ((Long) getAttribute(curi, ATTR_MAX_SIZE_BYTES)).longValue(); } catch (AttributeNotFoundException e) { logger.severe("Missing max-size-bytes attribute when processing " + curi.toString()); } if (maxsize < curi.getContentSize() && maxsize > -1) { return; } String regexpr = ""; try { regexpr = (String) getAttribute(curi, ATTR_STRIP_REG_EXPR); } catch (AttributeNotFoundException e2) { logger.severe("Missing strip-reg-exp when processing " + curi.toString()); return; } ReplayCharSequence cs = null; try { cs = curi.getHttpRecorder().getReplayCharSequence(); } catch (Exception e) { curi.addLocalizedError(this.getName(), e, "Failed get of replay char sequence " + curi.toString() + " " + e.getMessage()); logger.warning("Failed get of replay char sequence " + curi.toString() + " " + e.getMessage() + " " + Thread.currentThread().getName()); return; } MessageDigest digest = null; try { try { digest = MessageDigest.getInstance(SHA1); } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); return; } digest.reset(); String s = null; if (regexpr.length() == 0) { s = cs.toString(); } else { Matcher m = TextUtils.getMatcher(regexpr, cs); s = m.replaceAll(" "); TextUtils.recycleMatcher(m); } digest.update(s.getBytes()); byte[] newDigestValue = digest.digest(); if (logger.isLoggable(Level.FINEST)) { logger.finest("Recalculated content digest for " + curi.toString() + " old: " + Base32.encode((byte[]) curi.getContentDigest()) + ", new: " + Base32.encode(newDigestValue)); } curi.setContentDigest(SHA1, newDigestValue); } finally { if (cs != null) { try { cs.close(); } catch (IOException ioe) { logger.warning(TextUtils.exceptionToString("Failed close of ReplayCharSequence.", ioe)); } } } } Code Sample 2: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
00
Code Sample 1: public static void importDB(String input, String output) { try { Class.forName("org.sqlite.JDBC"); String fileName = output + File.separator + G.databaseName; File dataBase = new File(fileName); if (!dataBase.exists()) { G.conn = DriverManager.getConnection("jdbc:sqlite:" + fileName); createTablesDB(); } else G.conn = DriverManager.getConnection("jdbc:sqlite:" + fileName); long tiempoInicio = System.currentTimeMillis(); String directoryPath = input + File.separator; File myDirectory = new File(directoryPath); String[] list = myDirectory.list(); File fileXML = new File(input + File.separator + G.imagesName); if (!fileXML.exists()) { JOptionPane.showMessageDialog(null, "No se encuentra el fichero XML", "Error", JOptionPane.ERROR_MESSAGE); } else { SAXBuilder builder = new SAXBuilder(false); Document docXML = builder.build(fileXML); Element root = docXML.getRootElement(); List images = root.getChildren("image"); Iterator j = images.iterator(); List<Element> globalLanguages = root.getChild("languages").getChildren("language"); Iterator<Element> langsI = globalLanguages.iterator(); HashMap<String, Integer> languageIDs = new HashMap<String, Integer>(); HashMap<String, Integer> typeIDs = new HashMap<String, Integer>(); Element e; int i = 0; int contTypes = 0; int contImages = 0; while (langsI.hasNext()) { e = langsI.next(); languageIDs.put(e.getText(), i); PreparedStatement stmt = G.conn.prepareStatement("INSERT OR IGNORE INTO language (id,name) VALUES (?,?)"); stmt.setInt(1, i); stmt.setString(2, e.getText()); stmt.executeUpdate(); stmt.close(); i++; } G.conn.setAutoCommit(false); while (j.hasNext()) { Element image = (Element) j.next(); String id = image.getAttributeValue("id"); List languages = image.getChildren("language"); Iterator k = languages.iterator(); if (exists(list, id)) { String pathSrc = directoryPath.concat(id); String pathDst = output + File.separator + id.substring(0, 1).toUpperCase() + File.separator; String folder = output + File.separator + id.substring(0, 1).toUpperCase(); String pathDstTmp = pathDst.concat(id); String idTmp = id; File testFile = new File(pathDstTmp); int cont = 1; while (testFile.exists()) { idTmp = id.substring(0, id.lastIndexOf('.')) + '_' + cont + id.substring(id.lastIndexOf('.'), id.length()); pathDstTmp = pathDst + idTmp; testFile = new File(pathDstTmp); cont++; } pathDst = pathDstTmp; id = idTmp; File newDirectoryFolder = new File(folder); if (!newDirectoryFolder.exists()) { newDirectoryFolder.mkdirs(); } try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.toString()); } while (k.hasNext()) { Element languageElement = (Element) k.next(); String language = languageElement.getAttributeValue("id"); List words = languageElement.getChildren("word"); Iterator l = words.iterator(); while (l.hasNext()) { Element wordElement = (Element) l.next(); String type = wordElement.getAttributeValue("type"); if (!typeIDs.containsKey(type)) { typeIDs.put(type, contTypes); PreparedStatement stmt = G.conn.prepareStatement("INSERT OR IGNORE INTO type (id,name) VALUES (?,?)"); stmt.setInt(1, contTypes); stmt.setString(2, type); stmt.executeUpdate(); stmt.close(); contTypes++; } PreparedStatement stmt = G.conn.prepareStatement("INSERT OR IGNORE INTO main (word, idL, idT, name, nameNN) VALUES (?,?,?,?,?)"); stmt.setString(1, wordElement.getText().toLowerCase()); stmt.setInt(2, languageIDs.get(language)); stmt.setInt(3, typeIDs.get(type)); stmt.setString(4, id); stmt.setString(5, id); stmt.executeUpdate(); stmt.close(); if (contImages == 5000) { G.conn.commit(); contImages = 0; } else contImages++; } } } else { } } G.conn.setAutoCommit(true); G.conn.close(); long totalTiempo = System.currentTimeMillis() - tiempoInicio; System.out.println("El tiempo total es :" + totalTiempo / 1000 + " segundos"); } } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public Long processAddCompany(Company companyBean, String userLogin, Long holdingId, AuthSession authSession) { if (authSession == null) { return null; } PreparedStatement ps = null; DatabaseAdapter dbDyn = null; try { dbDyn = DatabaseAdapter.getInstance(); CustomSequenceType seq = new CustomSequenceType(); seq.setSequenceName("seq_WM_LIST_COMPANY"); seq.setTableName("WM_LIST_COMPANY"); seq.setColumnName("ID_FIRM"); Long sequenceValue = dbDyn.getSequenceNextValue(seq); ps = dbDyn.prepareStatement("insert into WM_LIST_COMPANY (" + " ID_FIRM, " + " full_name, " + " short_name, " + " address, " + " telefon_buh, " + " telefon_chief, " + " chief, " + " buh, " + " fax, " + " email, " + " icq, " + " short_client_info, " + " url, " + " short_info, " + "is_deleted" + ")" + (dbDyn.getIsNeedUpdateBracket() ? "(" : "") + " select " + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ?,0 from WM_AUTH_USER " + "where USER_LOGIN=? " + (dbDyn.getIsNeedUpdateBracket() ? ")" : "")); int num = 1; RsetTools.setLong(ps, num++, sequenceValue); ps.setString(num++, companyBean.getName()); ps.setString(num++, companyBean.getShortName()); ps.setString(num++, companyBean.getAddress()); ps.setString(num++, ""); ps.setString(num++, ""); ps.setString(num++, companyBean.getCeo()); ps.setString(num++, companyBean.getCfo()); ps.setString(num++, ""); ps.setString(num++, ""); RsetTools.setLong(ps, num++, null); ps.setString(num++, ""); ps.setString(num++, companyBean.getWebsite()); ps.setString(num++, companyBean.getInfo()); ps.setString(num++, userLogin); int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of inserted records - " + i1); if (holdingId != null) { InternalDaoFactory.getInternalHoldingDao().setRelateHoldingCompany(dbDyn, holdingId, sequenceValue); } dbDyn.commit(); return sequenceValue; } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error add new company"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } }
00
Code Sample 1: public ArrayList<Tweet> getTimeLine() { try { HttpGet get = new HttpGet("http://api.linkedin.com/v1/people/~/network/updates?scope=self"); consumer.sign(get); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(get); if (response != null) { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); return null; } StringBuffer sBuf = new StringBuffer(); String linea; BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); while ((linea = reader.readLine()) != null) { sBuf.append(linea); } reader.close(); response.getEntity().consumeContent(); get.abort(); SAXParserFactory spf = SAXParserFactory.newInstance(); StringReader XMLout = new StringReader(sBuf.toString()); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); xmlParserLinkedin gwh = new xmlParserLinkedin(); xr.setContentHandler(gwh); xr.parse(new InputSource(XMLout)); return gwh.getParsedData(); } } catch (UnsupportedEncodingException e) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); } catch (IOException e) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); } catch (OAuthMessageSignerException e) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); } catch (OAuthExpectationFailedException e) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); } catch (OAuthCommunicationException e) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); } catch (ParserConfigurationException e) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); } catch (SAXException e) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); } return null; } Code Sample 2: public void copyNIO(File in, File out) throws IOException { FileInputStream inStream = null; FileOutputStream outStream = null; FileChannel sourceChannel = null; FileChannel destinationChannel = null; try { inStream = new FileInputStream(in); outStream = new FileOutputStream(out); sourceChannel = inStream.getChannel(); destinationChannel = outStream.getChannel(); destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); } finally { if (sourceChannel != null) sourceChannel.close(); if (destinationChannel != null) destinationChannel.close(); if (inStream != null) inStream.close(); if (outStream != null) outStream.close(); } }
11
Code Sample 1: private void buildBundle() { if (targetProject == null) { MessageDialog.openError(getShell(), "Error", "No target SPAB project selected!"); return; } if (projectProcessDirSelector.getText().trim().length() == 0) { MessageDialog.openError(getShell(), "Error", "No process directory selected for project " + targetProject.getName() + "!"); return; } deleteBundleFile(); try { File projectDir = targetProject.getLocation().toFile(); File projectProcessesDir = new File(projectDir, projectProcessDirSelector.getText()); boolean bpmoCopied = IOUtils.copyProcessFilesSecure(getBPMOFile(), projectProcessesDir); boolean sbpelCopied = IOUtils.copyProcessFilesSecure(getSBPELFile(), projectProcessesDir); boolean xmlCopied = IOUtils.copyProcessFilesSecure(getBPEL4SWSFile(), projectProcessesDir); bundleFile = IOUtils.archiveBundle(projectDir, Activator.getDefault().getStateLocation().toFile()); if (bpmoCopied) { new File(projectProcessesDir, getBPMOFile().getName()).delete(); } if (sbpelCopied) { new File(projectProcessesDir, getSBPELFile().getName()).delete(); } if (xmlCopied) { new File(projectProcessesDir, getBPEL4SWSFile().getName()).delete(); } } catch (Throwable anyError) { LogManager.logError(anyError); MessageDialog.openError(getShell(), "Error", "Error building SPAB :\n" + anyError.getMessage()); updateBundleUI(); return; } bpmoFile = getBPMOFile(); sbpelFile = getSBPELFile(); xmlFile = getBPEL4SWSFile(); updateBundleUI(); getWizard().getContainer().updateButtons(); } Code Sample 2: public static void main(String[] argz) { int X, Y, Z; X = 256; Y = 256; Z = 256; try { String work_folder = "C:\\Documents and Settings\\Entheogen\\My Documents\\school\\jung\\vol_data\\CT_HEAD3"; FileOutputStream out_stream = new FileOutputStream(new File(work_folder + "\\converted.dat")); FileChannel out = out_stream.getChannel(); String f_name = "head256.raw"; File file = new File(work_folder + "\\" + f_name); FileChannel in = new FileInputStream(file).getChannel(); ByteBuffer buffa = BufferUtil.newByteBuffer((int) file.length()); in.read(buffa); in.close(); int N = 256; FloatBuffer output_data = BufferUtil.newFloatBuffer(N * N * N); float min = Float.MAX_VALUE; for (int i = 0, j = 0; i < buffa.capacity(); i++, j++) { byte c = buffa.get(i); min = Math.min(min, (float) (c)); output_data.put((float) (c)); } for (int i = 0; i < Y - X; ++i) { for (int j = 0; j < Y; ++j) { for (int k = 0; k < Z; ++k) { output_data.put(min); } } } output_data.rewind(); System.out.println("size of output_data = " + Integer.toString(output_data.capacity())); out.write(BufferUtil.copyFloatBufferAsByteBuffer(output_data)); ByteBuffer buffa2 = BufferUtil.newByteBuffer(2); buffa2.put((byte) '.'); out.close(); } catch (Exception exc) { exc.printStackTrace(); } }
11
Code Sample 1: private boolean getCached(Get g) throws IOException { boolean ret = false; File f = getCachedFile(g); if (f.exists()) { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(f); os = new FileOutputStream(getDestFile(g)); int read; byte[] buffer = new byte[4096]; while ((read = is.read(buffer)) > 0) { os.write(buffer, 0, read); } ret = true; } finally { if (is != null) is.close(); if (os != null) os.close(); is = null; os = null; } } return ret; } Code Sample 2: public static void copyFile(IPath fromFileName, IPath toFileName) throws IOException { File fromFile = fromFileName.toFile(); File toFile = toFileName.toFile(); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } InputStream from = null; OutputStream to = null; try { from = new BufferedInputStream(new FileInputStream(fromFile)); to = new BufferedOutputStream(new FileOutputStream(toFile)); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { } if (to != null) try { to.close(); } catch (IOException e) { } } }
11
Code Sample 1: private void createHomeTab() { Tabpanel homeTab = new Tabpanel(); windowContainer.addWindow(homeTab, Msg.getMsg(EnvWeb.getCtx(), "Home").replaceAll("&", ""), false); Portallayout portalLayout = new Portallayout(); portalLayout.setWidth("100%"); portalLayout.setHeight("100%"); portalLayout.setStyle("position: absolute; overflow: auto"); homeTab.appendChild(portalLayout); Portalchildren portalchildren = null; int currentColumnNo = 0; String sql = "SELECT COUNT(DISTINCT COLUMNNO) " + "FROM PA_DASHBOARDCONTENT " + "WHERE (AD_CLIENT_ID=0 OR AD_CLIENT_ID=?) AND ISACTIVE='Y'"; int noOfCols = DB.getSQLValue(null, sql, EnvWeb.getCtx().getAD_Client_ID()); int width = noOfCols <= 0 ? 100 : 100 / noOfCols; sql = "SELECT x.*, m.AD_MENU_ID " + "FROM PA_DASHBOARDCONTENT x " + "LEFT OUTER JOIN AD_MENU m ON x.AD_WINDOW_ID=m.AD_WINDOW_ID " + "WHERE (x.AD_CLIENT_ID=0 OR x.AD_CLIENT_ID=?) AND x.ISACTIVE='Y' " + "AND x.zulfilepath not in (?, ?, ?) " + "ORDER BY x.COLUMNNO, x.AD_CLIENT_ID, x.LINE "; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, null); pstmt.setInt(1, EnvWeb.getCtx().getAD_Client_ID()); pstmt.setString(2, ACTIVITIES_PATH); pstmt.setString(3, FAVOURITES_PATH); pstmt.setString(4, VIEWS_PATH); rs = pstmt.executeQuery(); while (rs.next()) { int columnNo = rs.getInt("ColumnNo"); if (portalchildren == null || currentColumnNo != columnNo) { portalchildren = new Portalchildren(); portalLayout.appendChild(portalchildren); portalchildren.setWidth(width + "%"); portalchildren.setStyle("padding: 5px"); currentColumnNo = columnNo; } Panel panel = new Panel(); panel.setStyle("margin-bottom:10px"); panel.setTitle(rs.getString("Name")); String description = rs.getString("Description"); if (description != null) panel.setTooltiptext(description); String collapsible = rs.getString("IsCollapsible"); panel.setCollapsible(collapsible.equals("Y")); panel.setBorder("normal"); portalchildren.appendChild(panel); Panelchildren content = new Panelchildren(); panel.appendChild(content); boolean panelEmpty = true; String htmlContent = rs.getString("HTML"); if (htmlContent != null) { StringBuffer result = new StringBuffer("<html><head>"); URL url = getClass().getClassLoader().getResource("org/compiere/images/PAPanel.css"); InputStreamReader ins; try { ins = new InputStreamReader(url.openStream()); BufferedReader bufferedReader = new BufferedReader(ins); String cssLine; while ((cssLine = bufferedReader.readLine()) != null) result.append(cssLine + "\n"); } catch (IOException e1) { logger.log(Level.SEVERE, e1.getLocalizedMessage(), e1); } result.append("</head><body><div class=\"content\">\n"); result.append(stripHtml(htmlContent, false) + "<br>\n"); result.append("</div>\n</body>\n</html>\n</html>"); Html html = new Html(); html.setContent(result.toString()); content.appendChild(html); panelEmpty = false; } int AD_Window_ID = rs.getInt("AD_Window_ID"); if (AD_Window_ID > 0) { int AD_Menu_ID = rs.getInt("AD_Menu_ID"); ToolBarButton btn = new ToolBarButton(String.valueOf(AD_Menu_ID)); MMenu menu = new MMenu(EnvWeb.getCtx(), AD_Menu_ID, null); btn.setLabel(menu.getName()); btn.addEventListener(Events.ON_CLICK, this); content.appendChild(btn); panelEmpty = false; } int PA_Goal_ID = rs.getInt("PA_Goal_ID"); if (PA_Goal_ID > 0) { StringBuffer result = new StringBuffer("<html><head>"); URL url = getClass().getClassLoader().getResource("org/compiere/images/PAPanel.css"); InputStreamReader ins; try { ins = new InputStreamReader(url.openStream()); BufferedReader bufferedReader = new BufferedReader(ins); String cssLine; while ((cssLine = bufferedReader.readLine()) != null) result.append(cssLine + "\n"); } catch (IOException e1) { logger.log(Level.SEVERE, e1.getLocalizedMessage(), e1); } result.append("</head><body><div class=\"content\">\n"); result.append(renderGoals(PA_Goal_ID, content)); result.append("</div>\n</body>\n</html>\n</html>"); Html html = new Html(); html.setContent(result.toString()); content.appendChild(html); panelEmpty = false; } String url = rs.getString("ZulFilePath"); if (url != null) { try { Component component = Executions.createComponents(url, content, null); if (component != null) { if (component instanceof DashboardPanel) { DashboardPanel dashboardPanel = (DashboardPanel) component; if (!dashboardPanel.getChildren().isEmpty()) { content.appendChild(dashboardPanel); dashboardRunnable.add(dashboardPanel); panelEmpty = false; } } else { content.appendChild(component); panelEmpty = false; } } } catch (Exception e) { logger.log(Level.WARNING, "Failed to create components. zul=" + url, e); } } if (panelEmpty) panel.detach(); } } catch (Exception e) { logger.log(Level.WARNING, "Failed to create dashboard content", e); } finally { Util.closeCursor(pstmt, rs); } registerWindow(homeTab); if (!portalLayout.getDesktop().isServerPushEnabled()) portalLayout.getDesktop().enableServerPush(true); dashboardRunnable.refreshDashboard(); dashboardThread = new Thread(dashboardRunnable, "UpdateInfo"); dashboardThread.setDaemon(true); dashboardThread.start(); } Code Sample 2: @Deprecated public static void getAndProcessContents(String videoPageURL, int bufsize, String charset, Closure<String> process) throws IOException { URL url = null; HttpURLConnection connection = null; InputStream is = null; InputStreamReader isr = null; BufferedReader br = null; try { url = new URL(videoPageURL); connection = (HttpURLConnection) url.openConnection(); is = connection.getInputStream(); isr = new InputStreamReader(is, charset); br = new BufferedReader(isr); for (String line = br.readLine(); line != null; line = br.readLine()) { process.exec(line); } } finally { Closeables.closeQuietly(br); Closeables.closeQuietly(isr); Closeables.closeQuietly(is); HttpUtils.disconnect(connection); } }
00
Code Sample 1: public boolean update(int idJugador, jugador jugadorModificado) { int intResult = 0; String sql = "UPDATE jugador " + "SET apellidoPaterno = ?, apellidoMaterno = ?, nombres = ?, fechaNacimiento = ?, " + " pais = ?, rating = ?, sexo = ? " + " WHERE idJugador = " + idJugador; try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); populatePreparedStatement(jugadorModificado); intResult = ps.executeUpdate(); connection.commit(); } catch (SQLException ex) { ex.printStackTrace(); try { connection.rollback(); } catch (SQLException exe) { exe.printStackTrace(); } } finally { conexionBD.close(ps); conexionBD.close(connection); } return (intResult > 0); } Code Sample 2: public static boolean isDicom(URL url) { assert url != null; boolean isDicom = false; BufferedInputStream is = null; try { is = new BufferedInputStream(url.openStream()); is.skip(DICOM_PREAMBLE_SIZE); byte[] buf = new byte[DICM.length]; is.read(buf); if (buf[0] == DICM[0] && buf[1] == DICM[1] && buf[2] == DICM[2] && buf[3] == DICM[3]) { isDicom = true; } } catch (Exception exc) { System.out.println("ImageFactory::isDicom(): exc=" + exc); } finally { if (is != null) { try { is.close(); } catch (Exception exc) { } } } return isDicom; }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public static 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) { logger.error(Logger.SECURITY_FAILURE, "Problem decoding file to file", exc); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: public void render(ServiceContext serviceContext) throws Exception { if (serviceContext.getTemplateName() == null) throw new Exception("no Template defined for service: " + serviceContext.getServiceInfo().getRefName()); File f = new File(serviceContext.getTemplateName()); serviceContext.getResponse().setContentLength((int) f.length()); InputStream in = new FileInputStream(f); IOUtils.copy(in, serviceContext.getResponse().getOutputStream(), 0, (int) f.length()); in.close(); } Code Sample 2: public DataRecord addRecord(InputStream input) throws DataStoreException { File temporary = null; try { temporary = newTemporaryFile(); DataIdentifier tempId = new DataIdentifier(temporary.getName()); usesIdentifier(tempId); long length = 0; MessageDigest digest = MessageDigest.getInstance(DIGEST); OutputStream output = new DigestOutputStream(new FileOutputStream(temporary), digest); try { length = IOUtils.copyLarge(input, output); } finally { output.close(); } DataIdentifier identifier = new DataIdentifier(digest.digest()); File file; synchronized (this) { usesIdentifier(identifier); file = getFile(identifier); System.out.println("new file name: " + file.getName()); File parent = file.getParentFile(); System.out.println("parent file: " + file.getParentFile().getName()); if (!parent.isDirectory()) { parent.mkdirs(); } if (!file.exists()) { temporary.renameTo(file); if (!file.exists()) { throw new IOException("Can not rename " + temporary.getAbsolutePath() + " to " + file.getAbsolutePath() + " (media read only?)"); } } else { long now = System.currentTimeMillis(); if (file.lastModified() < now) { file.setLastModified(now); } } if (!file.isFile()) { throw new IOException("Not a file: " + file); } if (file.length() != length) { throw new IOException(DIGEST + " collision: " + file); } } inUse.remove(tempId); return new FileDataRecord(identifier, file); } catch (NoSuchAlgorithmException e) { throw new DataStoreException(DIGEST + " not available", e); } catch (IOException e) { throw new DataStoreException("Could not add record", e); } finally { if (temporary != null) { temporary.delete(); } } }
00
Code Sample 1: private void copyFile(File in, File out) { try { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } catch (IOException ex) { ex.printStackTrace(); } } Code Sample 2: public String getMediaURL(String strLink) { try { String res = de.nomule.mediaproviders.KeepVid.getAnswer(strLink, "aa"); if (NoMuleRuntime.DEBUG) System.out.println(res); String regexp = "http:\\/\\/[^\"]+\\/get_video[^\"]+"; Pattern p = Pattern.compile(regexp); Matcher m = p.matcher(res); m.find(); String strRetUrl = res.substring(m.start(), m.end()); strRetUrl = URLDecoder.decode(strRetUrl, "UTF-8"); if (TRY_HIGH_QUALITY) { NoMuleRuntime.showDebug("HIGH_QUALITY"); strRetUrl += "&fmt=18"; try { URL url = new URL(strRetUrl); URLConnection conn = url.openConnection(); InputStream in = conn.getInputStream(); in.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { strRetUrl = strRetUrl.substring(0, strRetUrl.length() - 7); } } if (NoMuleRuntime.DEBUG) System.out.println(strRetUrl); return strRetUrl; } catch (UnsupportedEncodingException e) { System.out.println("Error in Youtube Media Provider. Encoding is not supported. (How would that happen?!)"); e.printStackTrace(); } return ""; }
11
Code Sample 1: public void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType(s_contentType); response.setHeader("Cache-control", "no-cache"); InputStream graphStream = getGraphStream(request); OutputStream out = getOutputStream(response); IOUtils.copy(graphStream, out); out.flush(); } Code Sample 2: public boolean restore(File directory) { log.debug("restore file from directory " + directory.getAbsolutePath()); try { if (!directory.exists()) return false; String[] operationFileNames = directory.list(); if (operationFileNames.length < 6) { log.error("Only " + operationFileNames.length + " files found in directory " + directory.getAbsolutePath()); return false; } int fileCount = 0; for (int i = 0; i < operationFileNames.length; i++) { if (!operationFileNames[i].toUpperCase().endsWith(".XML")) continue; log.debug("found file: " + operationFileNames[i]); fileCount++; File filein = new File(directory.getAbsolutePath() + File.separator + operationFileNames[i]); File fileout = new File(operationsDirectory + File.separator + operationFileNames[i]); FileReader in = new FileReader(filein); FileWriter out = new FileWriter(fileout); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } if (fileCount < 6) return false; return true; } catch (Exception e) { log.error("Exception while restoring operations files, may not be complete: " + e); return false; } }
00
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 void backupXML() { try { TimeStamp timeStamp = new TimeStamp(); String fnameIn = this.fnameXML(); String pathBackup = this.pathXML + "\\Backup\\"; String fnameOut = fnameIn.substring(fnameIn.indexOf(this.fname), fnameIn.length()); fnameOut = fnameOut.substring(0, fnameOut.indexOf("xml")); fnameOut = pathBackup + fnameOut + timeStamp.now("yyyyMMdd-kkmmss") + ".xml"; System.out.println("fnameIn: " + fnameIn); System.out.println("fnameOut: " + fnameOut); FileChannel in = new FileInputStream(fnameIn).getChannel(); FileChannel out = new FileOutputStream(fnameOut).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { central.inform("ORM.backupXML: " + e.toString()); } }
11
Code Sample 1: public static String encodeFromFile(String filename) throws java.io.IOException, URISyntaxException { String encodedData = null; Base641.InputStream bis = null; File file; try { URL url = new URL(filename); URLConnection conn = url.openConnection(); file = new File("myfile.doc"); java.io.InputStream inputStream = (java.io.InputStream) conn.getInputStream(); FileOutputStream out = new FileOutputStream(file); byte buf[] = new byte[1024]; int len; while ((len = inputStream.read(buf)) > 0) out.write(buf, 0, len); out.close(); inputStream.close(); byte[] buffer = new byte[Math.max((int) (file.length() * 1.4), 40)]; int length = 0; int numBytes = 0; bis = new Base641.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(file)), Base641.ENCODE); while ((numBytes = bis.read(buffer, length, 4096)) >= 0) { length += numBytes; } encodedData = new String(buffer, 0, length, Base641.PREFERRED_ENCODING); } catch (java.io.IOException e) { throw e; } finally { try { bis.close(); } catch (Exception e) { } } return encodedData; } Code Sample 2: public void doRender() throws IOException { File file = new File(fileName); if (!file.exists()) { logger.error("Static resource not found: " + fileName); isNotFound = true; return; } if (fileName.endsWith("xml") || fileName.endsWith("asp")) servletResponse.setContentType("text/xml"); else if (fileName.endsWith("css")) servletResponse.setContentType("text/css"); else if (fileName.endsWith("js")) servletResponse.setContentType("text/javascript"); InputStream in = null; try { in = new FileInputStream(file); IOUtils.copy(in, servletResponse.getOutputStream()); logger.debug("Static resource rendered: ".concat(fileName)); } catch (FileNotFoundException e) { logger.error("Static resource not found: " + fileName); isNotFound = true; } finally { IOUtils.closeQuietly(in); } }
11
Code Sample 1: public static void copier(final File pFichierSource, final File pFichierDest) { FileChannel vIn = null; FileChannel vOut = null; try { vIn = new FileInputStream(pFichierSource).getChannel(); vOut = new FileOutputStream(pFichierDest).getChannel(); vIn.transferTo(0, vIn.size(), vOut); } catch (Exception e) { e.printStackTrace(); } finally { if (vIn != null) { try { vIn.close(); } catch (IOException e) { } } if (vOut != null) { try { vOut.close(); } catch (IOException e) { } } } } Code Sample 2: private void sendData(HttpServletResponse response, MediaBean mediaBean) throws IOException { if (logger.isInfoEnabled()) logger.info("sendData[" + mediaBean + "]"); response.setContentLength(mediaBean.getContentLength()); response.setContentType(mediaBean.getContentType()); response.addHeader("Last-Modified", mediaBean.getLastMod()); response.addHeader("Cache-Control", "must-revalidate"); response.addHeader("content-disposition", "attachment, filename=" + (new Date()).getTime() + "_" + mediaBean.getFileName()); byte[] content = mediaBean.getContent(); InputStream is = null; OutputStream os = null; try { os = response.getOutputStream(); is = new ByteArrayInputStream(content); IOUtils.copy(is, os); } catch (IOException e) { logger.error(e, e); } finally { if (is != null) try { is.close(); } catch (IOException e) { } if (os != null) try { os.close(); } catch (IOException e) { } } }
00
Code Sample 1: private IMolecule readMolecule() throws Exception { String xpath = ""; if (index.equals("ichi")) { xpath = URLEncoder.encode("//molecule[./identifier/basic='" + query + "']", UTF8); } else if (index.equals("kegg")) { xpath = URLEncoder.encode("//molecule[./@name='" + query + "' and ./@dictRef='KEGG']", UTF8); } else if (index.equals("nist")) { xpath = URLEncoder.encode("//molecule[../@id='" + query + "']", UTF8); } else { logger.error("Did not recognize index type: " + index); return null; } String colname = URLEncoder.encode("/" + this.collection, UTF8); logger.info("Doing query: " + xpath + " in collection " + colname); URL url = new URL("http://" + server + "/Bob/QueryXindice"); logger.info("Connection to server: " + url.toString()); URLConnection connection = url.openConnection(); connection.setDoOutput(true); PrintWriter out = new PrintWriter(connection.getOutputStream()); out.print("detailed=on"); out.print("&"); out.print("xmlOnly=on"); out.print("&"); out.print("colName=" + colname); out.print("&"); out.print("xpathString=" + xpath); out.print("&"); out.println("query=Query"); out.close(); InputStream stream = connection.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(stream)); in.mark(1000000); in.readLine(); String comment = in.readLine(); logger.debug("The comment is: " + comment); Pattern p = Pattern.compile("<!-- There are (\\d{1,6}) results! -->"); Matcher match = p.matcher(comment); if (match.find()) { resultNum = match.group(1); } else { resultNum = "0"; } logger.debug("The number of result is " + resultNum); in.reset(); CMLReader reader = new CMLReader(stream); ChemFile cf = (ChemFile) reader.read((ChemObject) new ChemFile()); logger.debug("#sequences: " + cf.getChemSequenceCount()); IMolecule m = null; if (cf.getChemSequenceCount() > 0) { org.openscience.cdk.interfaces.IChemSequence chemSequence = cf.getChemSequence(0); logger.debug("#models in sequence: " + chemSequence.getChemModelCount()); if (chemSequence.getChemModelCount() > 0) { org.openscience.cdk.interfaces.IChemModel chemModel = chemSequence.getChemModel(0); org.openscience.cdk.interfaces.IMoleculeSet setOfMolecules = chemModel.getMoleculeSet(); logger.debug("#mols in model: " + setOfMolecules.getMoleculeCount()); if (setOfMolecules.getMoleculeCount() > 0) { m = setOfMolecules.getMolecule(0); } else { logger.warn("No molecules in the model"); } } else { logger.warn("No models in the sequence"); } } else { logger.warn("No sequences in the file"); } in.close(); return m; } Code Sample 2: public RawTableData(int selectedId) { selectedProjectId = selectedId; String urlString = dms_url + "/servlet/com.ufnasoft.dms.server.ServerGetProjectDocuments"; String rvalue = ""; String filename = dms_home + FS + "temp" + FS + username + "documents.xml"; try { String urldata = urlString + "?username=" + URLEncoder.encode(username, "UTF-8") + "&key=" + URLEncoder.encode(key, "UTF-8") + "&projectid=" + selectedProjectId + "&filename=" + URLEncoder.encode(username, "UTF-8") + "documents.xml"; ; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); URL u = new URL(urldata); DataInputStream is = new DataInputStream(u.openStream()); FileOutputStream os = new FileOutputStream(filename); int iBufSize = is.available(); byte inBuf[] = new byte[20000 * 1024]; int iNumRead; while ((iNumRead = is.read(inBuf, 0, iBufSize)) > 0) os.write(inBuf, 0, iNumRead); os.close(); is.close(); File f = new File(filename); InputStream inputstream = new FileInputStream(f); Document document = parser.parse(inputstream); NodeList nodelist = document.getElementsByTagName("doc"); int num = nodelist.getLength(); rawTableData = new String[num][11]; imageNames = new String[num]; for (int i = 0; i < num; i++) { rawTableData[i][0] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "did")); rawTableData[i][1] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "t")); rawTableData[i][2] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "f")); rawTableData[i][3] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "d")); rawTableData[i][4] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "l")); String firstname = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "fn")); String lastname = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "ln")); rawTableData[i][5] = firstname + " " + lastname; rawTableData[i][6] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "dln")); rawTableData[i][7] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "rsid")); rawTableData[i][8] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "img")); imageNames[i] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "img")); rawTableData[i][9] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "ucin")); rawTableData[i][10] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "dtid")); } } catch (MalformedURLException ex) { System.out.println(ex); } catch (ParserConfigurationException ex) { System.out.println(ex); } catch (NullPointerException e) { } catch (Exception ex) { System.out.println(ex); } }
11
Code Sample 1: private void anneal(final float maxGamma, final float gammaAccel, final float objectiveTolerance, final float objectiveAccel, final float scoreTolerance, final float paramTolerance, final float distanceLimit, final float randomLimit, final long randomSeed, final BufferedDocuments<Phrase> references, final int n, final int maxNbest, File stateFile, boolean keepState) { float gamma = 0; boolean annealObjective = true; double[] convergedScores = new double[n]; double[] totalLogScores = new double[n]; boolean[] isConverged = new boolean[n]; GradientPoint[] initPoints = new GradientPoint[n]; GradientPoint[] prevInitPoints = new GradientPoint[n]; GradientPoint[] bestInitPoints = new GradientPoint[n]; GradientPoint[] prevMinPoints = new GradientPoint[n]; Random rand = new Random(randomSeed); Time time = new Time(); if (stateFile != null && stateFile.length() > 0) { time.reset(); try { ObjectInputStream stream = new ObjectInputStream(new FileInputStream(stateFile)); gamma = stream.readFloat(); annealObjective = stream.readBoolean(); convergedScores = (double[]) stream.readObject(); totalLogScores = (double[]) stream.readObject(); isConverged = (boolean[]) stream.readObject(); initPoints = (GradientPoint[]) stream.readObject(); prevInitPoints = (GradientPoint[]) stream.readObject(); bestInitPoints = (GradientPoint[]) stream.readObject(); prevMinPoints = (GradientPoint[]) stream.readObject(); rand = (Random) stream.readObject(); int size = stream.readInt(); for (int id = 0; id < size; id++) { Feature feature = FEATURES.getRaw(CONFIG, stream.readUTF(), 0f); if (feature.getId() != id) throw new Exception("Features have changed"); } evaluation.read(stream); stream.close(); output.println("# Resuming from previous optimization state (" + time + ")"); output.println(); } catch (Exception e) { e.printStackTrace(); Log.getInstance().severe("Failed loading optimization state (" + stateFile + "): " + e.getMessage()); } } else { final int evaluations = ProjectedEvaluation.CFG_OPT_HISTORY_SIZE.getValue(); final GradientPoint[] randPoints = new GradientPoint[n * evaluations]; for (int i = 0; i < n; i++) { evaluation.setParallelId(i); for (int j = 0; j < evaluations; j++) { if (i != 0) randPoints[i * n + j] = getRandomPoint(rand, randPoints[0], distanceLimit, null); evaluate(references, i + ":" + j); if (i == 0) { randPoints[0] = new GradientPoint(evaluation, null); gamma = LogFeatureModel.FEAT_MODEL_GAMMA.getValue(); break; } } } for (int i = 0; i < randPoints.length; i++) if (randPoints[i] != null) randPoints[i] = new GradientPoint(evaluation, randPoints[i], output); for (int i = 0; i < n; i++) { prevInitPoints[i] = null; initPoints[i] = randPoints[i * n]; if (i != 0) for (int j = 1; j < evaluations; j++) if (randPoints[i * n + j].getScore() < initPoints[i].getScore()) initPoints[i] = randPoints[i * n + j]; bestInitPoints[i] = initPoints[i]; convergedScores[i] = Float.MAX_VALUE; } } for (int searchCount = 1; ; searchCount++) { boolean isFinished = true; for (int i = 0; i < n; i++) isFinished = isFinished && isConverged[i]; if (isFinished) { output.println("*** N-best list converged. Modifying annealing schedule. ***"); output.println(); if (annealObjective) { boolean objectiveConverged = true; for (int i = 0; objectiveConverged && i < n; i++) objectiveConverged = isConverged(bestInitPoints[i].getScore(), convergedScores[i], objectiveTolerance, SCORE_EPSILON); annealObjective = false; for (Metric<ProjectedSentenceEvaluation> metric : AbstractEvaluation.CFG_EVAL_METRICS.getValue()) if (metric.doAnnealing()) { float weight = metric.getWeight(); if (weight != 0) if (objectiveConverged) metric.setWeight(0); else { annealObjective = true; metric.setWeight(weight / objectiveAccel); } } } if (!annealObjective) { if (Math.abs(gamma) >= maxGamma) { GradientPoint bestPoint = bestInitPoints[0]; for (int i = 1; i < n; i++) if (bestInitPoints[i].getScore() < bestPoint.getScore()) bestPoint = bestInitPoints[i]; output.format("Best Score: %+.7g%n", bestPoint.getScore()); output.println(); bestPoint = new GradientPoint(evaluation, bestPoint, output); break; } gamma *= gammaAccel; if (Math.abs(gamma) + GAMMA_EPSILON >= maxGamma) gamma = gamma >= 0 ? maxGamma : -maxGamma; } for (int i = 0; i < n; i++) { convergedScores[i] = bestInitPoints[i].getScore(); initPoints[i] = new GradientPoint(evaluation, bestInitPoints[i], gamma, output); bestInitPoints[i] = initPoints[i]; prevInitPoints[i] = null; prevMinPoints[i] = null; isConverged[i] = false; } searchCount = 0; } for (int i = 0; i < n; i++) { if (isConverged[i]) continue; if (n > 1) output.println("Minimizing point " + i); Gradient gradient = initPoints[i].getGradient(); for (int id = 0; id < FEATURES.size(); id++) output.format("GRAD %-65s %-+13.7g%n", FEATURES.getName(id), gradient.get(id)); output.println(); time.reset(); GradientPoint minPoint = minimize(initPoints[i], prevInitPoints[i], bestInitPoints[i], scoreTolerance, paramTolerance, distanceLimit, randomLimit, rand); final float[] weights = minPoint.getWeights(); for (int j = 0; j < weights.length; j++) output.format("PARM %-65s %-+13.7g%n", FEATURES.getName(j), weights[j]); output.println(); output.format("Minimum Score: %+.7g (average distance of %.2f)%n", minPoint.getScore(), minPoint.getAverageDistance()); output.println(); output.println("# Minimized gradient (" + time + ")"); output.println(); output.flush(); isConverged[i] = weights == initPoints[i].getWeights(); prevInitPoints[i] = initPoints[i]; prevMinPoints[i] = minPoint; initPoints[i] = minPoint; } for (int i = 0; i < n; i++) { if (isConverged[i]) continue; isConverged[i] = isConvergedScore("minimum", prevMinPoints[i], prevInitPoints[i], scoreTolerance) && isConvergedWeights(prevMinPoints[i], prevInitPoints[i], paramTolerance); prevMinPoints[i].setWeightsAndRescore(evaluation); evaluation.setParallelId(i); evaluate(references, Integer.toString(i)); } Set<Point> prunePoints = new HashSet<Point>(); prunePoints.addAll(Arrays.asList(bestInitPoints)); prunePoints.addAll(Arrays.asList(prevInitPoints)); prunePoints.addAll(Arrays.asList(initPoints)); evaluation.prune(prunePoints, maxNbest, output); for (int i = 0; i < n; i++) { final boolean bestIsPrev = bestInitPoints[i] == prevInitPoints[i]; final boolean bestIsInit = bestInitPoints[i] == initPoints[i]; bestInitPoints[i] = new GradientPoint(evaluation, bestInitPoints[i], bestIsInit ? output : null); if (bestIsPrev) prevInitPoints[i] = bestInitPoints[i]; if (bestIsInit) initPoints[i] = bestInitPoints[i]; if (!bestIsPrev && prevInitPoints[i] != null) { prevInitPoints[i] = new GradientPoint(evaluation, prevInitPoints[i], null); if (prevInitPoints[i].getScore() <= bestInitPoints[i].getScore()) bestInitPoints[i] = prevInitPoints[i]; } if (!bestIsInit) { initPoints[i] = new GradientPoint(evaluation, initPoints[i], output); if (initPoints[i].getScore() <= bestInitPoints[i].getScore()) bestInitPoints[i] = initPoints[i]; } } for (int i = 0; i < n; i++) if (isConverged[i]) if (prevMinPoints[i] == null) { output.println("# Convergence failed: no previous minimum is defined"); output.println(); isConverged[i] = false; } else { isConverged[i] = isConvergedScore("best known", bestInitPoints[i], initPoints[i], scoreTolerance) && isConvergedScore("previous minimum", prevMinPoints[i], initPoints[i], scoreTolerance); } if (stateFile != null) { time.reset(); try { File dir = stateFile.getCanonicalFile().getParentFile(); File temp = File.createTempFile("cunei-opt-", ".tmp", dir); ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(temp)); stream.writeFloat(gamma); stream.writeBoolean(annealObjective); stream.writeObject(convergedScores); stream.writeObject(totalLogScores); stream.writeObject(isConverged); stream.writeObject(initPoints); stream.writeObject(prevInitPoints); stream.writeObject(bestInitPoints); stream.writeObject(prevMinPoints); stream.writeObject(rand); stream.writeInt(FEATURES.size()); for (int id = 0; id < FEATURES.size(); id++) stream.writeUTF(FEATURES.getName(id)); evaluation.write(stream); stream.close(); if (!temp.renameTo(stateFile)) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(temp).getChannel(); out = new FileOutputStream(stateFile).getChannel(); in.transferTo(0, in.size(), out); temp.delete(); } finally { if (in != null) in.close(); if (out != null) out.close(); } } output.println("# Saved optimization state (" + time + ")"); output.println(); } catch (IOException e) { Log.getInstance().severe("Failed writing optimization state: " + e.getMessage()); } } } if (stateFile != null && !keepState) stateFile.delete(); } Code Sample 2: public void process(String src, String dest) { try { KanjiDAO kanjiDAO = KanjiDAOFactory.getDAO(); MorphologicalAnalyzer mecab = MorphologicalAnalyzer.getInstance(); if (mecab.isActive()) { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(src), "UTF8")); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dest), "UTF8")); String line; bw.write("// // // \r\n$title=\r\n$singer=\r\n$id=\r\n\r\n + _______ // 0 0 0 0 0 0 0\r\n\r\n"); while ((line = br.readLine()) != null) { System.out.println(line); String segment[] = line.split("//"); String japanese = null; String english = null; if (segment.length > 1) english = segment[1].trim(); if (segment.length > 0) japanese = segment[0].trim().replaceAll(" ", "_"); boolean first = true; if (japanese != null) { ArrayList<ExtractedWord> wordList = mecab.extractWord(japanese); Iterator<ExtractedWord> iter = wordList.iterator(); while (iter.hasNext()) { ExtractedWord word = iter.next(); if (first) { first = false; bw.write("*"); } else bw.write(" "); if (word.isParticle) bw.write("- "); else bw.write("+ "); if (!word.original.equals(word.reading)) { System.out.println("--> " + JapaneseString.toRomaji(word.original) + " / " + JapaneseString.toRomaji(word.reading)); KReading[] kr = ReadingAnalyzer.analyzeReadingStub(word.original, word.reading, kanjiDAO); if (kr != null) { for (int i = 0; i < kr.length; i++) { if (i > 0) bw.write(" "); bw.write(kr[i].kanji); if (kr[i].type != KReading.KANA) { bw.write("|"); bw.write(kr[i].reading); } } } else { bw.write(word.original); bw.write("|"); bw.write(word.reading); } } else { bw.write(word.original); } bw.write(" // \r\n"); } if (english != null) { bw.write(english); bw.write("\r\n"); } bw.write("\r\n"); } } br.close(); bw.close(); } else { System.out.println("Mecab couldn't be initialized"); } } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: private void mergeOne(String level, char strand, String filename, Path outPath, FileSystem srcFS, FileSystem dstFS, Timer to) throws IOException { to.start(); final OutputStream outs = dstFS.create(new Path(outPath, filename)); final FileStatus[] parts = srcFS.globStatus(new Path(sorted ? getSortOutputDir(level, strand) : wrkDir, filename + "-[0-9][0-9][0-9][0-9][0-9][0-9]")); for (final FileStatus part : parts) { final InputStream ins = srcFS.open(part.getPath()); IOUtils.copyBytes(ins, outs, getConf(), false); ins.close(); } for (final FileStatus part : parts) srcFS.delete(part.getPath(), false); outs.write(BlockCompressedStreamConstants.EMPTY_GZIP_BLOCK); outs.close(); System.out.printf("summarize :: Merged %s%c in %d.%03d s.\n", level, strand, to.stopS(), to.fms()); } Code Sample 2: @Override public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException { if ((baseName == null) || (locale == null) || (format == null) || (loader == null)) { throw new NullPointerException(); } ResourceBundle bundle = null; if (format.equals(XML)) { String bundleName = toBundleName(baseName, locale); String resourceName = toResourceName(bundleName, format); URL url = loader.getResource(resourceName); if (url != null) { URLConnection connection = url.openConnection(); if (connection != null) { if (reload) { connection.setUseCaches(false); } InputStream stream = connection.getInputStream(); if (stream != null) { BufferedInputStream bis = new BufferedInputStream(stream); bundle = new XMLResourceBundle(bis); bis.close(); } } } } return bundle; }
11
Code Sample 1: 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; } Code Sample 2: public String encrypt(String pwd) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); System.out.println("Error"); } try { md5.update(pwd.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "That is not a valid encrpytion type"); } byte raw[] = md5.digest(); String empty = ""; String hash = ""; for (byte b : raw) { String tmp = empty + Integer.toHexString(b & 0xff); if (tmp.length() == 1) { tmp = 0 + tmp; } hash += tmp; } return hash; }
11
Code Sample 1: public void gzip(File from, File to) { OutputStream out_zip = null; ArchiveOutputStream os = null; try { try { out_zip = new FileOutputStream(to); os = new ArchiveStreamFactory().createArchiveOutputStream("zip", out_zip); os.putArchiveEntry(new ZipArchiveEntry(from.getName())); IOUtils.copy(new FileInputStream(from), os); os.closeArchiveEntry(); } finally { if (os != null) { os.close(); } } out_zip.close(); } catch (IOException ex) { fatal("IOException", ex); } catch (ArchiveException ex) { fatal("ArchiveException", ex); } } Code Sample 2: @Test public void testTrainingDefault() throws IOException { File temp = File.createTempFile("fannj_", ".tmp"); temp.deleteOnExit(); IOUtils.copy(this.getClass().getResourceAsStream("xor.data"), new FileOutputStream(temp)); List<Layer> layers = new ArrayList<Layer>(); layers.add(Layer.create(2)); layers.add(Layer.create(3, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); layers.add(Layer.create(1, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); Fann fann = new Fann(layers); Trainer trainer = new Trainer(fann); float desiredError = .001f; float mse = trainer.train(temp.getPath(), 500000, 1000, desiredError); assertTrue("" + mse, mse <= desiredError); }
11
Code Sample 1: public static synchronized BaseFont getL2BaseFont() { if (l2baseFont == null) { final ConfigProvider conf = ConfigProvider.getInstance(); try { final ByteArrayOutputStream tmpBaos = new ByteArrayOutputStream(); String fontPath = conf.getNotEmptyProperty("font.path", null); String fontName; String fontEncoding; InputStream tmpIs; if (fontPath != null) { fontName = conf.getNotEmptyProperty("font.name", null); if (fontName == null) { fontName = new File(fontPath).getName(); } fontEncoding = conf.getNotEmptyProperty("font.encoding", null); if (fontEncoding == null) { fontEncoding = BaseFont.WINANSI; } tmpIs = new FileInputStream(fontPath); } else { fontName = Constants.L2TEXT_FONT_NAME; fontEncoding = BaseFont.IDENTITY_H; tmpIs = FontUtils.class.getResourceAsStream(Constants.L2TEXT_FONT_PATH); } IOUtils.copy(tmpIs, tmpBaos); tmpIs.close(); tmpBaos.close(); l2baseFont = BaseFont.createFont(fontName, fontEncoding, BaseFont.EMBEDDED, BaseFont.CACHED, tmpBaos.toByteArray(), null); } catch (Exception e) { e.printStackTrace(); try { l2baseFont = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); } catch (Exception ex) { } } } return l2baseFont; } Code Sample 2: public void copy(File src, File dest) throws FileNotFoundException, IOException { FileInputStream srcStream = new FileInputStream(src); FileOutputStream destStream = new FileOutputStream(dest); FileChannel srcChannel = srcStream.getChannel(); FileChannel destChannel = destStream.getChannel(); srcChannel.transferTo(0, srcChannel.size(), destChannel); destChannel.close(); srcChannel.close(); destStream.close(); srcStream.close(); }
00
Code Sample 1: public static InputStream openURL(String url, ConnectData data) { try { URLConnection con = new URL(url).openConnection(); con.setConnectTimeout(TIMEOUT); con.setReadTimeout(TIMEOUT); con.setUseCaches(false); con.setRequestProperty("Accept-Charset", "utf-8"); setUA(con); if (data.cookie != null) con.setRequestProperty("Cookie", data.cookie); InputStream is = con.getInputStream(); parseCookie(con, data); return new BufferedInputStream(is); } catch (IOException ioe) { Log.except("failed to open URL " + url, ioe); } return null; } Code Sample 2: private static void checkClients() { try { sendMultiListEntry('l'); } catch (Exception e) { if (Util.getDebugLevel() > 90) e.printStackTrace(); } try { if (CANT_CHECK_CLIENTS != null) KeyboardHero.removeStatus(CANT_CHECK_CLIENTS); URL url = new URL(URL_STR + "?req=clients" + (server != null ? "&port=" + server.getLocalPort() : "")); URLConnection connection = url.openConnection(getProxy()); connection.setRequestProperty("User-Agent", USER_AGENT); BufferedReader bufferedRdr = new BufferedReader(new InputStreamReader(connection.getInputStream())); String ln; if (Util.getDebugLevel() > 30) Util.debug("URL: " + url); while ((ln = bufferedRdr.readLine()) != null) { String[] parts = ln.split(":", 2); if (parts.length < 2) { Util.debug(12, "Line read in checkClients: " + ln); continue; } try { InetSocketAddress address = new InetSocketAddress(parts[0], Integer.parseInt(parts[1])); boolean notFound = true; if (Util.getDebugLevel() > 25) Util.debug("NEW Address: " + address.toString()); synchronized (clients) { Iterator<Client> iterator = clients.iterator(); while (iterator.hasNext()) { final Client client = iterator.next(); if (client.socket.isClosed()) { iterator.remove(); continue; } if (Util.getDebugLevel() > 26 && client.address != null) Util.debug("Address: " + client.address.toString()); if (address.equals(client.address)) { notFound = false; break; } } } if (notFound) { connectClient(address); } } catch (NumberFormatException e) { } } bufferedRdr.close(); } catch (MalformedURLException e) { Util.conditionalError(PORT_IN_USE, "Err_PortInUse"); Util.error(Util.getMsg("Err_CantCheckClients")); } catch (FileNotFoundException e) { Util.error(Util.getMsg("Err_CantCheckClients_Proxy"), Util.getMsg("Err_FileNotFound")); } catch (SocketException e) { Util.error(Util.getMsg("Err_CantCheckClients_Proxy"), e.getLocalizedMessage()); } catch (Exception e) { CANT_CHECK_CLIENTS.setException(e.toString()); KeyboardHero.addStatus(CANT_CHECK_CLIENTS); } }
11
Code Sample 1: public ValidationReport validate(OriginalDeployUnitDescription unit) throws UnitValidationException { ValidationReport vr = new DefaultValidationReport(); errorHandler = new SimpleErrorHandler(vr); vr.setFileUri(unit.getAbsolutePath()); SAXParser parser; SAXReader reader = null; try { parser = factory.newSAXParser(); reader = new SAXReader(parser.getXMLReader()); reader.setValidation(false); reader.setErrorHandler(this.errorHandler); } catch (ParserConfigurationException e) { throw new UnitValidationException("The configuration of parser is illegal.", e); } catch (SAXException e) { String m = "Something is wrong when register schema"; logger.error(m, e); throw new UnitValidationException(m, e); } ZipInputStream zipInputStream; InputStream tempInput = null; try { tempInput = new FileInputStream(unit.getAbsolutePath()); } catch (FileNotFoundException e1) { String m = String.format("The file [%s] don't exist.", unit.getAbsolutePath()); logger.error(m, e1); throw new UnitValidationException(m, e1); } zipInputStream = new ZipInputStream(tempInput); ZipEntry zipEntry = null; try { zipEntry = zipInputStream.getNextEntry(); if (zipEntry == null) { String m = String.format("Error when get zipEntry. Maybe the [%s] is not zip file!", unit.getAbsolutePath()); logger.error(m); throw new UnitValidationException(m); } while (zipEntry != null) { if (configFiles.contains(zipEntry.getName())) { byte[] extra = new byte[(int) zipEntry.getSize()]; zipInputStream.read(extra); File file = File.createTempFile("temp", "extra"); file.deleteOnExit(); logger.info("[TempFile:]" + file.getAbsoluteFile()); ByteArrayInputStream byteInputStream = new ByteArrayInputStream(extra); FileOutputStream tempFileOutputStream = new FileOutputStream(file); IOUtils.copy(byteInputStream, tempFileOutputStream); tempFileOutputStream.flush(); IOUtils.closeQuietly(tempFileOutputStream); InputStream inputStream = new FileInputStream(file); reader.read(inputStream, unit.getAbsolutePath() + ":" + zipEntry.getName()); IOUtils.closeQuietly(inputStream); } zipEntry = zipInputStream.getNextEntry(); } } catch (IOException e) { ValidationMessage vm = new XMLValidationMessage("IOError", 0, 0, unit.getUrl() + ":" + zipEntry.getName(), e); vr.addValidationMessage(vm); } catch (DocumentException e) { ValidationMessage vm = new XMLValidationMessage("Document Error.", 0, 0, unit.getUrl() + ":" + zipEntry.getName(), e); vr.addValidationMessage(vm); } finally { IOUtils.closeQuietly(tempInput); IOUtils.closeQuietly(zipInputStream); } return vr; } Code Sample 2: @Override protected void copyContent(String filename) throws IOException { InputStream in = null; try { in = LOADER.getResourceAsStream(RES_PKG + filename); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); setResponseData(out.toByteArray()); } finally { if (in != null) { in.close(); } } }
11
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: public String getClass(EmeraldjbBean eb) throws EmeraldjbException { Entity entity = (Entity) eb; StringBuffer sb = new StringBuffer(); String myPackage = getPackageName(eb); sb.append("package " + myPackage + ";\n"); sb.append("\n"); DaoValuesGenerator valgen = new DaoValuesGenerator(); String values_class_name = valgen.getClassName(entity); sb.append("\n"); List importList = new Vector(); importList.add("java.io.FileOutputStream;"); importList.add("java.io.FileInputStream;"); importList.add("java.io.DataInputStream;"); importList.add("java.io.DataOutputStream;"); importList.add("java.io.IOException;"); importList.add("java.sql.Date;"); importList.add(valgen.getPackageName(eb) + "." + values_class_name + ";"); Iterator it = importList.iterator(); while (it.hasNext()) { String importName = (String) it.next(); sb.append("import " + importName + "\n"); } sb.append("\n"); String proto_version = entity.getPatternValue(GeneratorConst.PATTERN_STREAM_PROTO_VERSION, "1"); String streamer_class_name = getClassName(entity); sb.append("public class " + streamer_class_name + "\n"); sb.append("{" + "\n public static final int PROTO_VERSION=" + proto_version + ";"); sb.append("\n\n"); StringBuffer f_writer = new StringBuffer(); StringBuffer f_reader = new StringBuffer(); boolean has_times = false; boolean has_strings = false; it = entity.getMembers().iterator(); while (it.hasNext()) { Member member = (Member) it.next(); String nm = member.getName(); String getter = "obj." + methodGenerator.getMethodName(DaoGeneratorUtils.METHOD_GET, member); String setter = "obj." + methodGenerator.getMethodName(DaoGeneratorUtils.METHOD_SET, member); String pad = " "; JTypeBase gen_type = EmdFactory.getJTypeFactory().getJavaType(member.getType()); f_writer.append(gen_type.getToBinaryCode(pad, "dos", getter + "()")); f_reader.append(gen_type.getFromBinaryCode(pad, "din", setter)); } String reader_vars = ""; sb.append("\n public static void writeToFile(String file_nm, " + values_class_name + " obj) throws IOException" + "\n {" + "\n if (file_nm==null || file_nm.length()==0) throw new IOException(\"Bad file name (null or zero length)\");" + "\n if (obj==null) throw new IOException(\"Bad value object parameter, cannot write null object to file\");" + "\n FileOutputStream fos = new FileOutputStream(file_nm);" + "\n DataOutputStream dos = new DataOutputStream(fos);" + "\n writeStream(dos, obj);" + "\n fos.close();" + "\n } // end of writeToFile" + "\n" + "\n public static void readFromFile(String file_nm, " + values_class_name + " obj) throws IOException" + "\n {" + "\n if (file_nm==null || file_nm.length()==0) throw new IOException(\"Bad file name (null or zero length)\");" + "\n if (obj==null) throw new IOException(\"Bad value object parameter, cannot write null object to file\");" + "\n FileInputStream fis = new FileInputStream(file_nm);" + "\n DataInputStream dis = new DataInputStream(fis);" + "\n readStream(dis, obj);" + "\n fis.close();" + "\n } // end of readFromFile" + "\n" + "\n public static void writeStream(DataOutputStream dos, " + values_class_name + " obj) throws IOException" + "\n {" + "\n dos.writeByte(PROTO_VERSION);" + "\n " + f_writer + "\n } // end of writeStream" + "\n" + "\n public static void readStream(DataInputStream din, " + values_class_name + " obj) throws IOException" + "\n {" + "\n int proto_version = din.readByte();" + "\n if (proto_version==" + proto_version + ") readStreamV1(din,obj);" + "\n } // end of readStream" + "\n" + "\n public static void readStreamV1(DataInputStream din, " + values_class_name + " obj) throws IOException" + "\n {" + reader_vars + f_reader + "\n } // end of readStreamV1" + "\n" + "\n} // end of classs" + "\n\n" + "\n//**************" + "\n// End of file" + "\n//**************"); return sb.toString(); }
00
Code Sample 1: private String hash(String text) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(text.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); return hash.toString(16); } Code Sample 2: private boolean readRemoteFile() { InputStream inputstream; Concept concept = new Concept(); try { inputstream = url.openStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputstream); BufferedReader bufferedreader = new BufferedReader(inputStreamReader); String s4; while ((s4 = bufferedreader.readLine()) != null && s4.length() > 0) { if (!parseLine(s4, concept)) { return false; } } } catch (MalformedURLException e) { logger.fatal("malformed URL, trying to read local file"); return readLocalFile(); } catch (IOException e1) { logger.fatal("Error reading URL file, trying to read local file"); return readLocalFile(); } catch (Exception x) { logger.fatal("Failed to readRemoteFile " + x.getMessage() + ", trying to read local file"); return readLocalFile(); } return true; }
11
Code Sample 1: public DoSearch(String searchType, String searchString) { String urlString = dms_url + "/servlet/com.ufnasoft.dms.server.ServerDoSearch"; String rvalue = ""; String filename = dms_home + FS + "temp" + FS + username + "search.xml"; try { String urldata = urlString + "?username=" + URLEncoder.encode(username, "UTF-8") + "&key=" + key + "&search=" + URLEncoder.encode(searchString, "UTF-8") + "&searchtype=" + URLEncoder.encode(searchType, "UTF-8") + "&filename=" + URLEncoder.encode(username, "UTF-8") + "search.xml"; ; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); URL u = new URL(urldata); DataInputStream is = new DataInputStream(u.openStream()); FileOutputStream os = new FileOutputStream(filename); int iBufSize = is.available(); byte inBuf[] = new byte[20000 * 1024]; int iNumRead; while ((iNumRead = is.read(inBuf, 0, iBufSize)) > 0) os.write(inBuf, 0, iNumRead); os.close(); is.close(); File f = new File(filename); InputStream inputstream = new FileInputStream(f); Document document = parser.parse(inputstream); NodeList nodelist = document.getElementsByTagName("entry"); int num = nodelist.getLength(); searchDocs = new String[num][3]; searchDocImageName = new String[num]; searchDocsToolTip = new String[num]; for (int i = 0; i < num; i++) { searchDocs[i][0] = DOMUtil.getSimpleElementText((Element) nodelist.item(i), "filename"); searchDocs[i][1] = DOMUtil.getSimpleElementText((Element) nodelist.item(i), "project"); searchDocs[i][2] = DOMUtil.getSimpleElementText((Element) nodelist.item(i), "documentid"); searchDocImageName[i] = DOMUtil.getSimpleElementText((Element) nodelist.item(i), "imagename"); searchDocsToolTip[i] = DOMUtil.getSimpleElementText((Element) nodelist.item(i), "description"); } } catch (MalformedURLException ex) { System.out.println(ex); } catch (ParserConfigurationException ex) { System.out.println(ex); } catch (Exception ex) { System.out.println(ex); } System.out.println(rvalue); if (rvalue.equalsIgnoreCase("yes")) { } } Code Sample 2: public void verRecordatorio() { try { cantidadArchivos = obtenerCantidad() + 1; boolean existe = false; String filenametxt = ""; String filenamezip = ""; String hora = ""; String lugar = ""; String actividad = ""; String linea = ""; int dia = 0; int mes = 0; int ano = 0; for (int i = 1; i < cantidadArchivos; i++) { filenamezip = "recordatorio" + i + ".zip"; filenametxt = "recordatorio" + i + ".txt"; BufferedOutputStream dest = null; BufferedInputStream is = null; ZipEntry entry; ZipFile zipfile = new ZipFile(filenamezip); Enumeration e = zipfile.entries(); while (e.hasMoreElements()) { entry = (ZipEntry) e.nextElement(); is = new BufferedInputStream(zipfile.getInputStream(entry)); int count; byte data[] = new byte[buffer]; FileOutputStream fos = new FileOutputStream(entry.getName()); dest = new BufferedOutputStream(fos, buffer); while ((count = is.read(data, 0, buffer)) != -1) dest.write(data, 0, count); dest.flush(); dest.close(); is.close(); } DataInputStream input = new DataInputStream(new FileInputStream(filenametxt)); dia = Integer.parseInt(input.readLine()); mes = Integer.parseInt(input.readLine()); ano = Integer.parseInt(input.readLine()); if (dia == Integer.parseInt(identificarDato(datoSeleccionado))) { existe = true; hora = input.readLine(); lugar = input.readLine(); while ((linea = input.readLine()) != null) actividad += linea + "\n"; verRecordatorioInterfaz(hora, lugar, actividad); hora = ""; lugar = ""; actividad = ""; } input.close(); } if (!existe) JOptionPane.showMessageDialog(null, "No existe un recordatorio guardado\n" + "para el " + identificarDato(datoSeleccionado) + " de " + meses[mesTemporal].toLowerCase() + " del a�o " + anoTemporal, "No existe", JOptionPane.INFORMATION_MESSAGE); table.clearSelection(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error en: " + e.toString(), "Error", JOptionPane.ERROR_MESSAGE); } }
00
Code Sample 1: private static String getHashString(String text, String algorithm) throws NoSuchAlgorithmException, UnsupportedEncodingException { AssertUtility.notNull(text); AssertUtility.notNullAndNotSpace(algorithm); MessageDigest md; md = MessageDigest.getInstance(algorithm); md.update(text.getBytes("UTF-8"), 0, text.length()); byte[] hash = md.digest(); return convertToHex(hash); } Code Sample 2: protected void createValueListAnnotation(IProgressMonitor monitor, IPackageFragment pack, Map model) throws CoreException { IProject pj = pack.getJavaProject().getProject(); QualifiedName qn = new QualifiedName(JstActivator.PLUGIN_ID, JstActivator.PACKAGE_INFO_LOCATION); String location = pj.getPersistentProperty(qn); if (location != null) { IFolder javaFolder = pj.getFolder(new Path(NexOpenFacetInstallDataModelProvider.WEB_SRC_MAIN_JAVA)); IFolder packageInfo = javaFolder.getFolder(location); if (!packageInfo.exists()) { Logger.log(Logger.INFO, "package-info package [" + location + "] does not exists."); Logger.log(Logger.INFO, "ValueList annotation will not be added by this wizard. " + "You must add manually in your package-info class if exist " + "or create a new one at location " + location); return; } IFile pkginfo = packageInfo.getFile("package-info.java"); if (!pkginfo.exists()) { Logger.log(Logger.INFO, "package-info class at location [" + location + "] does not exists."); return; } InputStream in = pkginfo.getContents(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { IOUtils.copy(in, baos); String content = new String(baos.toByteArray()); VelocityEngine engine = VelocityEngineHolder.getEngine(); model.put("adapterType", getAdapterType()); model.put("packageInfo", location.replace('/', '.')); model.put("defaultNumberPerPage", "5"); model.put("defaultSortDirection", "asc"); if (isFacadeAdapter()) { model.put("facadeType", "true"); } if (content.indexOf("@ValueLists({})") > -1) { appendValueList(monitor, model, pkginfo, content, engine, true); return; } else if (content.indexOf("@ValueLists") > -1) { appendValueList(monitor, model, pkginfo, content, engine, false); return; } String vl = VelocityEngineUtils.mergeTemplateIntoString(engine, "ValueList.vm", model); ByteArrayInputStream bais = new ByteArrayInputStream(vl.getBytes()); try { pkginfo.setContents(bais, true, false, monitor); } finally { bais.close(); } return; } catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JeeServiceComponentUIPlugin.PLUGIN_ID, IStatus.OK, "I/O exception", e); throw new CoreException(status); } catch (VelocityException e) { IStatus status = new Status(IStatus.ERROR, JeeServiceComponentUIPlugin.PLUGIN_ID, IStatus.OK, "Velocity exception", e); throw new CoreException(status); } finally { try { baos.close(); in.close(); } catch (IOException e) { } } } Logger.log(Logger.INFO, "package-info location property does not exists."); }
11
Code Sample 1: public void testCodingFromFileSmaller() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); WritableByteChannel channel = newChannel(baos); HttpParams params = new BasicHttpParams(); SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 16); File tmpFile = File.createTempFile("testFile", "txt"); FileOutputStream fout = new FileOutputStream(tmpFile); OutputStreamWriter wrtout = new OutputStreamWriter(fout); wrtout.write("stuff;"); wrtout.write("more stuff;"); wrtout.flush(); wrtout.close(); FileChannel fchannel = new FileInputStream(tmpFile).getChannel(); encoder.transfer(fchannel, 0, 20); String s = baos.toString("US-ASCII"); assertTrue(encoder.isCompleted()); assertEquals("stuff;more stuff", s); tmpFile.delete(); } Code Sample 2: public static void main(String[] args) { try { boolean readExp = Utils.getFlag('l', args); final boolean writeExp = Utils.getFlag('s', args); final String expFile = Utils.getOption('f', args); if ((readExp || writeExp) && (expFile.length() == 0)) { throw new Exception("A filename must be given with the -f option"); } Experiment exp = null; if (readExp) { FileInputStream fi = new FileInputStream(expFile); ObjectInputStream oi = new ObjectInputStream(new BufferedInputStream(fi)); exp = (Experiment) oi.readObject(); oi.close(); } else { exp = new Experiment(); } System.err.println("Initial Experiment:\n" + exp.toString()); final JFrame jf = new JFrame("Weka Experiment Setup"); jf.getContentPane().setLayout(new BorderLayout()); final SetupPanel sp = new SetupPanel(); jf.getContentPane().add(sp, BorderLayout.CENTER); jf.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.err.println("\nFinal Experiment:\n" + sp.m_Exp.toString()); if (writeExp) { try { FileOutputStream fo = new FileOutputStream(expFile); ObjectOutputStream oo = new ObjectOutputStream(new BufferedOutputStream(fo)); oo.writeObject(sp.m_Exp); oo.close(); } catch (Exception ex) { ex.printStackTrace(); System.err.println("Couldn't write experiment to: " + expFile + '\n' + ex.getMessage()); } } jf.dispose(); System.exit(0); } }); jf.pack(); jf.setVisible(true); System.err.println("Short nap"); Thread.currentThread().sleep(3000); System.err.println("Done"); sp.setExperiment(exp); } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); } }
11
Code Sample 1: public static String encryptPassword(String password) { try { MessageDigest digest = java.security.MessageDigest.getInstance("SHA1"); digest.update(password.getBytes("UTF-8")); byte[] hash = digest.digest(); StringBuffer buf = new StringBuffer(); for (int i = 0; i < hash.length; i++) { int halfbyte = (hash[i] >>> 4) & 0x0F; int two_halfs = 0; do { if ((0 <= halfbyte) && (halfbyte <= 9)) { buf.append((char) ('0' + halfbyte)); } else { buf.append((char) ('a' + (halfbyte - 10))); } halfbyte = hash[i] & 0x0F; } while (two_halfs++ < 1); } return buf.toString(); } catch (Exception e) { } return null; } Code Sample 2: public static String calculate(String str) { MessageDigest md; try { md = MessageDigest.getInstance("SHA-256"); md.update(str.getBytes()); byte byteData[] = md.digest(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } return sb.toString(); } catch (NoSuchAlgorithmException ex) { return null; } }
11
Code Sample 1: private void packageDestZip(File tmpFile) throws FileNotFoundException, IOException { log("Creating launch profile package " + destfile); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(destfile))); ZipEntry e = new ZipEntry(RESOURCE_JAR_FILENAME); e.setMethod(ZipEntry.STORED); e.setSize(tmpFile.length()); e.setCompressedSize(tmpFile.length()); e.setCrc(calcChecksum(tmpFile, new CRC32())); out.putNextEntry(e); InputStream in = new BufferedInputStream(new FileInputStream(tmpFile)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.closeEntry(); out.finish(); out.close(); } Code Sample 2: private void transform(CommandLine commandLine) throws IOException { Reader reader; if (commandLine.hasOption('i')) { reader = createFileReader(commandLine.getOptionValue('i')); } else { reader = createStandardInputReader(); } Writer writer; if (commandLine.hasOption('o')) { writer = createFileWriter(commandLine.getOptionValue('o')); } else { writer = createStandardOutputWriter(); } String mapRule = commandLine.getOptionValue("m"); try { SrxTransformer transformer = new SrxAnyTransformer(); Map<String, Object> parameterMap = new HashMap<String, Object>(); if (mapRule != null) { parameterMap.put(Srx1Transformer.MAP_RULE_NAME, mapRule); } transformer.transform(reader, writer, parameterMap); } finally { cleanupReader(reader); cleanupWriter(writer); } }
11
Code Sample 1: @Override public void setContentAsStream(InputStream input) throws IOException { BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(htmlFile)); try { IOUtils.copy(input, output); } finally { output.close(); } if (this.getLastModified() != -1) { htmlFile.setLastModified(this.getLastModified()); } } Code Sample 2: public static void copyFile(File file, String pathExport) throws IOException { File out = new File(pathExport); FileChannel sourceChannel = new FileInputStream(file).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
00
Code Sample 1: public static void readAsFile(String fileName, String url) { BufferedInputStream in = null; BufferedOutputStream out = null; URLConnection conn = null; try { conn = new URL(url).openConnection(); conn.setDoInput(true); in = new BufferedInputStream(conn.getInputStream()); out = new BufferedOutputStream(new FileOutputStream(fileName)); int b; while ((b = in.read()) != -1) { out.write(b); } } catch (Exception ex) { log.error(ex.getMessage(), ex); } finally { if (null != in) { try { in.close(); } catch (IOException e) { } } if (null != out) { try { out.flush(); out.close(); } catch (IOException e) { } } } } Code Sample 2: public void copy(File s, File t) throws IOException { FileChannel in = (new FileInputStream(s)).getChannel(); FileChannel out = (new FileOutputStream(t)).getChannel(); in.transferTo(0, s.length(), out); in.close(); out.close(); }
00
Code Sample 1: public String fetchStockCompanyName(Stock stock) { String companyName = ""; String symbol = StockUtil.getStock(stock); if (isStockCached(symbol)) { return getStockFromCache(symbol); } String url = NbBundle.getMessage(MrSwingDataFeed.class, "MrSwingDataFeed.stockInfo.url", new String[] { symbol, register.get("username", ""), register.get("password", "") }); HttpContext context = new BasicHttpContext(); HttpGet method = new HttpGet(url); try { HttpResponse response = ProxyManager.httpClient.execute(method, context); HttpEntity entity = response.getEntity(); if (entity != null) { companyName = EntityUtils.toString(entity).split("\n")[1]; cacheStock(symbol, companyName); EntityUtils.consume(entity); } } catch (Exception ex) { companyName = ""; } finally { method.abort(); } return companyName; } Code Sample 2: public Reader transform(Reader reader, Map<String, Object> parameterMap) { try { File file = File.createTempFile("srx2", ".srx"); file.deleteOnExit(); Writer writer = getWriter(getFileOutputStream(file.getAbsolutePath())); transform(reader, writer, parameterMap); writer.close(); Reader resultReader = getReader(getFileInputStream(file.getAbsolutePath())); return resultReader; } catch (IOException e) { throw new IORuntimeException(e); } }