label
class label 2
classes | source_code
stringlengths 398
72.9k
|
---|---|
11
| Code Sample 1:
private String sendMessage(HttpURLConnection connection, String reqMessage) throws IOException { if (msgLog.isTraceEnabled()) msgLog.trace("Outgoing SOAPMessage\n" + reqMessage); BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream()); out.write(reqMessage.getBytes("UTF-8")); out.close(); InputStream inputStream = null; if (connection.getResponseCode() < 400) inputStream = connection.getInputStream(); else inputStream = connection.getErrorStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); IOUtils.copyStream(baos, inputStream); inputStream.close(); String response = new String(baos.toByteArray(), "UTF-8"); if (msgLog.isTraceEnabled()) msgLog.trace("Incoming Response SOAPMessage\n" + response); return response; }
Code Sample 2:
private void forcedCopy(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(); } } } |
00
| Code Sample 1:
protected static void copyOrMove(File sourceLocation, File targetLocation, boolean move) throws IOException { String[] children; int i; InputStream in; OutputStream out; byte[] buf; int len; if (sourceLocation.isDirectory()) { if (!targetLocation.exists()) targetLocation.mkdir(); children = sourceLocation.list(); for (i = 0; i < children.length; i++) { copyOrMove(new File(sourceLocation, children[i]), new File(targetLocation, children[i]), move); } if (move) sourceLocation.delete(); } else { in = new FileInputStream(sourceLocation); if (targetLocation.isDirectory()) out = new FileOutputStream(targetLocation.getAbsolutePath() + File.separator + sourceLocation.getName()); else out = new FileOutputStream(targetLocation); buf = new byte[1024]; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); if (move) sourceLocation.delete(); } }
Code Sample 2:
public void runTask(HashMap pjobParms) throws Exception { FTPClient lftpClient = null; FileInputStream lfisSourceFile = null; JBJFPluginDefinition lpluginCipher = null; IJBJFPluginCipher theCipher = null; try { JBJFFTPDefinition lxmlFTP = null; if (getFTPDefinition() != null) { lxmlFTP = getFTPDefinition(); this.mstrSourceDirectory = lxmlFTP.getSourceDirectory(); this.mstrTargetDirectory = lxmlFTP.getTargetDirectory(); this.mstrFilename = lxmlFTP.getFilename(); this.mstrRemoteServer = lxmlFTP.getServer(); if (getResources().containsKey("plugin-cipher")) { lpluginCipher = (JBJFPluginDefinition) getResources().get("plugin-cipher"); } if (lpluginCipher != null) { theCipher = getTaskPlugins().getCipherPlugin(lpluginCipher.getPluginId()); } if (theCipher != null) { this.mstrServerUsr = theCipher.decryptString(lxmlFTP.getUser()); this.mstrServerPwd = theCipher.decryptString(lxmlFTP.getPass()); } else { this.mstrServerUsr = lxmlFTP.getUser(); this.mstrServerPwd = lxmlFTP.getPass(); } } else { throw new Exception("Work unit [ " + SHORT_NAME + " ] is missing an FTP Definition. Please check" + " your JBJF Batch Definition file an make sure" + " this work unit has a <resource> element added" + " within the <task> element."); } lfisSourceFile = new FileInputStream(mstrSourceDirectory + File.separator + mstrFilename); lftpClient = new FTPClient(); lftpClient.connect(mstrRemoteServer); lftpClient.setFileType(lxmlFTP.getFileTransferType()); if (!FTPReply.isPositiveCompletion(lftpClient.getReplyCode())) { throw new Exception("FTP server [ " + mstrRemoteServer + " ] refused connection."); } if (!lftpClient.login(mstrServerUsr, mstrServerPwd)) { throw new Exception("Unable to login to server [ " + mstrTargetDirectory + " ]."); } if (!lftpClient.changeWorkingDirectory(mstrTargetDirectory)) { throw new Exception("Unable to change to remote directory [ " + mstrTargetDirectory + "]"); } lftpClient.enterLocalPassiveMode(); if (!lftpClient.storeFile(mstrFilename, lfisSourceFile)) { throw new Exception("Unable to upload [ " + mstrSourceDirectory + "/" + mstrFilename + " ]" + " to " + mstrTargetDirectory + File.separator + mstrFilename + " to " + mstrRemoteServer); } lfisSourceFile.close(); lftpClient.logout(); } catch (Exception e) { throw e; } finally { if (lftpClient != null && lftpClient.isConnected()) { try { lftpClient.disconnect(); } catch (IOException ioe) { } } if (lfisSourceFile != null) { try { lfisSourceFile.close(); } catch (Exception e) { } } } } |
11
| Code Sample 1:
public static Photo createPhoto(String title, String userLogin, String pathToPhoto, String basePathImage) throws NoSuchAlgorithmException, IOException { String id = CryptSHA1.genPhotoID(userLogin, title); String extension = pathToPhoto.substring(pathToPhoto.lastIndexOf(".")); String destination = basePathImage + id + extension; FileInputStream fis = new FileInputStream(pathToPhoto); FileOutputStream fos = new FileOutputStream(destination); FileChannel fci = fis.getChannel(); FileChannel fco = fos.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (true) { int read = fci.read(buffer); if (read == -1) break; buffer.flip(); fco.write(buffer); buffer.clear(); } fci.close(); fco.close(); fos.close(); fis.close(); ImageIcon image; ImageIcon thumb; String destinationThumb = basePathImage + "thumb/" + id + extension; image = new ImageIcon(destination); int maxSize = 150; int origWidth = image.getIconWidth(); int origHeight = image.getIconHeight(); if (origWidth > origHeight) { thumb = new ImageIcon(image.getImage().getScaledInstance(maxSize, -1, Image.SCALE_SMOOTH)); } else { thumb = new ImageIcon(image.getImage().getScaledInstance(-1, maxSize, Image.SCALE_SMOOTH)); } BufferedImage bi = new BufferedImage(thumb.getIconWidth(), thumb.getIconHeight(), BufferedImage.TYPE_INT_RGB); Graphics g = bi.getGraphics(); g.drawImage(thumb.getImage(), 0, 0, null); try { ImageIO.write(bi, "JPG", new File(destinationThumb)); } catch (IOException ioe) { System.out.println("Error occured saving thumbnail"); } Photo photo = new Photo(id); photo.setTitle(title); photo.basePathImage = basePathImage; return photo; }
Code Sample 2:
public static void main(String[] args) throws MalformedURLException, IOException { InputStream in = null; try { in = new URL("hdfs://localhost:8020/user/leeing/maxtemp/sample.txt").openStream(); IOUtils.copyBytes(in, System.out, 8192, false); } finally { IOUtils.closeStream(in); System.out.println("\nend."); } } |
00
| Code Sample 1:
public static void writeFullImageToStream(Image scaledImage, String javaFormat, OutputStream os) throws IOException { BufferedImage bufImage = new BufferedImage(scaledImage.getWidth(null), scaledImage.getHeight(null), BufferedImage.TYPE_BYTE_BINARY); Graphics gr = bufImage.getGraphics(); gr.drawImage(scaledImage, 0, 0, null); gr.dispose(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ImageIO.write(bufImage, javaFormat, bos); IOUtils.copyStreams(new ByteArrayInputStream(bos.toByteArray()), os); }
Code Sample 2:
public int subclass(int objectId, String description) throws FidoDatabaseException, ObjectNotFoundException { try { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { String sql = "insert into Objects (Description) " + "values ('" + description + "')"; conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); if (contains(stmt, objectId) == false) throw new ObjectNotFoundException(objectId); stmt.executeUpdate(sql); int id; sql = "select currval('objects_objectid_seq')"; rs = stmt.executeQuery(sql); if (rs.next() == false) throw new SQLException("No rows returned from select currval() query"); else id = rs.getInt(1); ObjectLinkTable objectLinkList = new ObjectLinkTable(); objectLinkList.linkObjects(stmt, id, "isa", objectId); conn.commit(); return id; } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } } |
11
| Code Sample 1:
@Override public void actionPerformed(ActionEvent e) { if (copiedFiles_ != null) { File[] tmpFiles = new File[copiedFiles_.length]; File tmpDir = new File(Settings.getPropertyString(ConstantKeys.project_dir), "tmp/"); tmpDir.mkdirs(); for (int i = copiedFiles_.length - 1; i >= 0; i--) { Frame f = FrameManager.getInstance().getFrameAtIndex(i); try { File in = f.getFile(); File out = new File(tmpDir, f.getFile().getName()); FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); tmpFiles[i] = out; } catch (IOException e1) { e1.printStackTrace(); } } try { FrameManager.getInstance().insertFrames(getTable().getSelectedRow(), FrameManager.INSERT_TYPE.MOVE, tmpFiles); } catch (IOException e1) { e1.printStackTrace(); } } }
Code Sample 2:
private void writeInputStreamToFile(InputStream stream, File file) { try { FileOutputStream fOut = new FileOutputStream(file); IOUtils.copy(stream, fOut); fOut.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } |
00
| Code Sample 1:
private boolean connect() { try { this.ftpClient.connect(this.server, this.port); this.ftpClient.login(this.username, this.password); return true; } catch (IOException iOException) { return false; } }
Code Sample 2:
protected void initializeFromURL(URL url, AVList params) throws IOException { URLConnection connection = url.openConnection(); String message = this.validateURLConnection(connection, SHAPE_CONTENT_TYPES); if (message != null) { throw new IOException(message); } this.shpChannel = Channels.newChannel(WWIO.getBufferedInputStream(connection.getInputStream())); URLConnection shxConnection = this.getURLConnection(WWIO.replaceSuffix(url.toString(), INDEX_FILE_SUFFIX)); if (shxConnection != null) { message = this.validateURLConnection(shxConnection, INDEX_CONTENT_TYPES); if (message != null) Logging.logger().warning(message); else { InputStream shxStream = this.getURLStream(shxConnection); if (shxStream != null) this.shxChannel = Channels.newChannel(WWIO.getBufferedInputStream(shxStream)); } } URLConnection prjConnection = this.getURLConnection(WWIO.replaceSuffix(url.toString(), PROJECTION_FILE_SUFFIX)); if (prjConnection != null) { message = this.validateURLConnection(prjConnection, PROJECTION_CONTENT_TYPES); if (message != null) Logging.logger().warning(message); else { InputStream prjStream = this.getURLStream(prjConnection); if (prjStream != null) this.prjChannel = Channels.newChannel(WWIO.getBufferedInputStream(prjStream)); } } this.setValue(AVKey.DISPLAY_NAME, url.toString()); this.initialize(params); URL dbfURL = WWIO.makeURL(WWIO.replaceSuffix(url.toString(), ATTRIBUTE_FILE_SUFFIX)); if (dbfURL != null) { try { this.attributeFile = new DBaseFile(dbfURL); } catch (Exception e) { } } } |
00
| Code Sample 1:
public String encodePassword(String password, byte[] salt) throws Exception { if (salt == null) { salt = new byte[12]; secureRandom.nextBytes(salt); } MessageDigest md = MessageDigest.getInstance("MD5"); md.update(salt); md.update(password.getBytes("UTF8")); byte[] digest = md.digest(); byte[] storedPassword = new byte[digest.length + 12]; System.arraycopy(salt, 0, storedPassword, 0, 12); System.arraycopy(digest, 0, storedPassword, 12, digest.length); return new String(Base64.encode(storedPassword)); }
Code Sample 2:
public static String doPostWithBasicAuthentication(URL url, String username, String password, String parameters, Map<String, String> headers) throws IOException { HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setDoInput(true); con.setDoOutput(true); byte[] encodedPassword = (username + ":" + password).getBytes(); BASE64Encoder encoder = new BASE64Encoder(); con.setRequestProperty("Authorization", "Basic " + encoder.encode(encodedPassword)); con.setConnectTimeout(2000); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); if (parameters != null) con.setRequestProperty("Content-Length", "" + Integer.toString(parameters.getBytes().length)); if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { con.setRequestProperty(header.getKey(), header.getValue()); } } DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(parameters); wr.flush(); wr.close(); InputStream is = con.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\n'); } rd.close(); is.close(); con.disconnect(); return response.toString(); } |
00
| Code Sample 1:
public void sendFile(File file, String filename, String contentType) throws SearchLibException { response.setContentType(contentType); response.addHeader("Content-Disposition", "attachment; filename=" + filename); FileInputStream inputStream = null; try { inputStream = new FileInputStream(file); ServletOutputStream outputStream = getOutputStream(); IOUtils.copy(inputStream, outputStream); outputStream.close(); } catch (FileNotFoundException e) { throw new SearchLibException(e); } catch (IOException e) { throw new SearchLibException(e); } finally { if (inputStream != null) IOUtils.closeQuietly(inputStream); } }
Code Sample 2:
public static String readURL(String urlStr, boolean debug) { if (debug) System.out.print(" trying: " + urlStr + "\n"); URL url = null; try { url = new URL(urlStr); } catch (java.net.MalformedURLException e) { System.out.print("test failed: using URL: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } HttpURLConnection huc = null; try { huc = (HttpURLConnection) url.openConnection(); } catch (IOException e) { System.out.print("test failed: using URL: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } String contentType = huc.getContentType(); if (contentType == null || contentType.indexOf("text/xml") < 0) { System.out.print("*** Warning *** Content-Type not set to text/xml"); System.out.print('\n'); System.out.print(" Content-type: "); System.out.print(contentType); System.out.print('\n'); } InputStream urlStream = null; try { urlStream = huc.getInputStream(); } catch (java.io.IOException e) { System.out.print("test failed: opening URL: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } BufferedReader in = new BufferedReader(new InputStreamReader(urlStream)); boolean xml = true; String href = null, inputLine = null; StringBuffer content = new StringBuffer(), stylesheet = null; Transformer transformer = null; try { inputLine = in.readLine(); } catch (java.io.IOException e) { System.out.print("test failed: reading first line of response: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } if (inputLine == null) { System.out.print("test failed: No input read from URL"); System.out.print('\n'); return null; } if (!inputLine.startsWith("<?xml ")) { xml = false; content.append(inputLine); } if (xml) { int offset = inputLine.indexOf('>'); if (offset + 2 < inputLine.length()) { inputLine = inputLine.substring(offset + 1); offset = inputLine.indexOf('<'); if (offset > 0) inputLine = inputLine.substring(offset); } else try { inputLine = in.readLine(); } catch (java.io.IOException e) { System.out.print("test failed: reading response: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } content.append(inputLine); } try { while ((inputLine = in.readLine()) != null) content.append(inputLine); } catch (java.io.IOException e) { System.out.print("test failed: reading response: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } String contentStr = content.toString(); if (transformer != null) { StreamSource streamXMLRecord = new StreamSource(new StringReader(contentStr)); StringWriter xmlRecordWriter = new StringWriter(); try { transformer.transform(streamXMLRecord, new StreamResult(xmlRecordWriter)); System.out.print(" successfully applied stylesheet '"); System.out.print(href); System.out.print("'"); System.out.print('\n'); } catch (javax.xml.transform.TransformerException e) { System.out.print("unable to apply stylesheet '"); System.out.print(href); System.out.print("'to response: "); System.out.print(e.getMessage()); System.out.print('\n'); e.printStackTrace(); } } return contentStr; } |
00
| Code Sample 1:
public static String convertStringToMD5(String toEnc) { try { MessageDigest mdEnc = MessageDigest.getInstance("MD5"); mdEnc.update(toEnc.getBytes(), 0, toEnc.length()); return new BigInteger(1, mdEnc.digest()).toString(16); } catch (Exception e) { return null; } }
Code Sample 2:
public static void copyFile(File source, File target) { try { target.getParentFile().mkdirs(); byte[] buffer = new byte[4096]; int len = 0; FileInputStream in = new FileInputStream(source); FileOutputStream out = new FileOutputStream(target); while ((len = in.read(buffer)) != -1) out.write(buffer, 0, len); in.close(); out.close(); } catch (Exception e) { System.out.println(e); } } |
11
| Code Sample 1:
public static void streamCopyFile(File srcFile, File destFile) { try { FileInputStream fi = new FileInputStream(srcFile); FileOutputStream fo = new FileOutputStream(destFile); byte[] buf = new byte[1024]; int readLength = 0; while (readLength != -1) { readLength = fi.read(buf); if (readLength != -1) { fo.write(buf, 0, readLength); } } fo.close(); fi.close(); } catch (Exception e) { } }
Code Sample 2:
public static void main(String[] args) throws Exception { if (args.length != 2) { System.out.println("arguments: sourcefile destfile"); System.exit(1); } FileChannel in = new FileInputStream(args[0]).getChannel(), out = new FileOutputStream(args[1]).getChannel(); in.transferTo(0, in.size(), out); } |
11
| Code Sample 1:
public static void copyFile(String oldPathFile, String newPathFile) { try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPathFile); if (oldfile.exists()) { InputStream inStream = new FileInputStream(oldPathFile); FileOutputStream fs = new FileOutputStream(newPathFile); byte[] buffer = new byte[2048]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; fs.write(buffer, 0, byteread); } inStream.close(); } else { System.err.println(FileUtil.class.toString() + ":不存在file" + oldPathFile); } } catch (Exception e) { System.err.println(FileUtil.class.toString() + ":复制file" + oldPathFile + "到" + newPathFile + "出错!"); } }
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:
private void getRandomGUID(boolean secure, Object o) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(o.getClass().getName()); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } }
Code Sample 2:
public void createVendorSignature() { byte b; try { _vendorMessageDigest = MessageDigest.getInstance("MD5"); _vendorSig = Signature.getInstance("MD5/RSA/PKCS#1"); _vendorSig.initSign((PrivateKey) _vendorPrivateKey); _vendorMessageDigest.update(getBankString().getBytes()); _vendorMessageDigestBytes = _vendorMessageDigest.digest(); _vendorSig.update(_vendorMessageDigestBytes); _vendorSignatureBytes = _vendorSig.sign(); } catch (Exception e) { } ; } |
00
| Code Sample 1:
@Override public void doExecute(String[] args) { if (args.length != 2) { printUsage(); } else { int fileNo = 0; try { fileNo = Integer.parseInt(args[1]) - 1; } catch (NumberFormatException e) { printUsage(); return; } if (fileNo < 0) { printUsage(); return; } StorageFile[] files = (StorageFile[]) ctx.getRemoteDir().listFiles(); try { StorageFile file = files[fileNo]; File outFile = getOutFile(file); FileOutputStream out = new FileOutputStream(outFile); InputStream in = file.openStream(); IOUtils.copy(in, out); IOUtils.closeQuietly(out); afterSave(outFile); if (outFile.exists()) { print("File written to: " + outFile.getAbsolutePath()); } } catch (IOException e) { printError("Failed to load file. " + e.getMessage()); } catch (Exception e) { printUsage(); return; } } }
Code Sample 2:
public boolean load() { if (getFilename() != null && getFilename().length() > 0) { try { File file = new File(PreferencesManager.loadDirectoryLocation("macros") + File.separator + getFilename()); URL url = file.toURL(); InputStreamReader isr = new InputStreamReader(url.openStream()); BufferedReader br = new BufferedReader(isr); String line = br.readLine(); String macro_text = ""; while (line != null) { macro_text = macro_text.concat(line); line = br.readLine(); if (line != null) { macro_text = macro_text.concat(System.getProperty("line.separator")); } } code = macro_text; } catch (Exception e) { System.err.println("Exception at StoredMacro.load(): " + e.toString()); return false; } } return true; } |
00
| Code Sample 1:
public void render(Map map, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(OUTPUT_BYTE_ARRAY_INITIAL_SIZE); File file = (File) map.get("targetFile"); IOUtils.copy(new FileInputStream(file), baos); httpServletResponse.setContentType(getContentType()); httpServletResponse.setContentLength(baos.size()); httpServletResponse.addHeader("Content-disposition", "attachment; filename=" + file.getName()); ServletOutputStream out = httpServletResponse.getOutputStream(); baos.writeTo(out); out.flush(); }
Code Sample 2:
private String getRandomGUID(final boolean secure) { MessageDigest md5 = null; final StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } try { final long time = System.currentTimeMillis(); final long rand; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(id); sbValueBeforeMD5.append(SEMI_COLON); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(SEMI_COLON); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); final byte[] array = md5.digest(); final StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { final int bufferIndex = array[j] & SHIFT_SPACE; if (ZERO_TEST > bufferIndex) sb.append(CHAR_ZERO); sb.append(Integer.toHexString(bufferIndex)); } return sb.toString(); } catch (Exception e) { throw new RuntimeException(e); } } |
11
| Code Sample 1:
private static List retrieveQuotes(Report report, Symbol symbol, String prefix, TradingDate startDate, TradingDate endDate) throws ImportExportException { List quotes = new ArrayList(); String URLString = constructURL(symbol, prefix, startDate, endDate); EODQuoteFilter filter = new GoogleEODQuoteFilter(symbol); PreferencesManager.ProxyPreferences proxyPreferences = PreferencesManager.getProxySettings(); try { URL url = new URL(URLString); InputStreamReader input = new InputStreamReader(url.openStream()); BufferedReader bufferedInput = new BufferedReader(input); String line = bufferedInput.readLine(); while (line != null) { line = bufferedInput.readLine(); if (line != null) { try { EODQuote quote = filter.toEODQuote(line); quotes.add(quote); verify(report, quote); } catch (QuoteFormatException e) { report.addError(Locale.getString("GOOGLE_DISPLAY_URL") + ":" + symbol + ":" + Locale.getString("ERROR") + ": " + e.getMessage()); } } } bufferedInput.close(); } catch (BindException e) { throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); } catch (ConnectException e) { throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); } catch (UnknownHostException e) { throw new ImportExportException(Locale.getString("UNKNOWN_HOST_ERROR", e.getMessage())); } catch (NoRouteToHostException e) { throw new ImportExportException(Locale.getString("DESTINATION_UNREACHABLE_ERROR", e.getMessage())); } catch (MalformedURLException e) { throw new ImportExportException(Locale.getString("INVALID_PROXY_ERROR", proxyPreferences.host, proxyPreferences.port)); } catch (FileNotFoundException e) { } catch (IOException e) { throw new ImportExportException(Locale.getString("ERROR_DOWNLOADING_QUOTES")); } return quotes; }
Code Sample 2:
private void sendMessages() { Configuration conf = Configuration.getInstance(); for (int i = 0; i < errors.size(); i++) { String msg = null; synchronized (this) { msg = errors.get(i); if (DEBUG) System.out.println(msg); errors.remove(i); } if (!conf.getCustomerFeedback()) continue; if (conf.getApproveCustomerFeedback()) { ConfirmCustomerFeedback dialog = new ConfirmCustomerFeedback(JOptionPane.getFrameForComponent(SqlTablet.getInstance()), msg); if (dialog.getResult() == ConfirmCustomerFeedback.Result.NO) continue; } try { URL url = new URL("http://www.sqltablet.com/beta/bug.php"); URLConnection urlc = url.openConnection(); urlc.setDoOutput(true); urlc.setDoOutput(true); urlc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); DataOutputStream out = new DataOutputStream(urlc.getOutputStream()); String lines[] = msg.split("\n"); for (int l = 0; l < lines.length; l++) { String line = (l > 0 ? "&line" : "line") + l + "="; line += URLEncoder.encode(lines[l], "UTF-8"); out.write(line.getBytes()); } out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(urlc.getInputStream())); String line; while ((line = in.readLine()) != null) { if (DEBUG) System.out.println("RemoteLogger : " + line + "\n"); } in.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } |
00
| Code Sample 1:
private void enumeratePathArchive(final String archive) throws IOException { final boolean trace1 = m_trace1; final File fullArchive = new File(m_currentPathDir, archive); JarInputStream in = null; try { in = new JarInputStream(new BufferedInputStream(new FileInputStream(fullArchive), 32 * 1024)); final IPathHandler handler = m_handler; Manifest manifest = in.getManifest(); if (manifest == null) manifest = readManifestViaJarFile(fullArchive); handler.handleArchiveStart(m_currentPathDir, new File(archive), manifest); for (ZipEntry entry; (entry = in.getNextEntry()) != null; ) { if (trace1) m_log.trace1("enumeratePathArchive", "processing archive entry [" + entry.getName() + "] ..."); handler.handleArchiveEntry(in, entry); in.closeEntry(); } if (m_processManifest) { if (manifest == null) manifest = in.getManifest(); if (manifest != null) { final Attributes attributes = manifest.getMainAttributes(); if (attributes != null) { final String jarClassPath = attributes.getValue(Attributes.Name.CLASS_PATH); if (jarClassPath != null) { final StringTokenizer tokenizer = new StringTokenizer(jarClassPath); for (int p = 1; tokenizer.hasMoreTokens(); ) { final String relPath = tokenizer.nextToken(); final File archiveParent = fullArchive.getParentFile(); final File path = archiveParent != null ? new File(archiveParent, relPath) : new File(relPath); final String fullPath = m_canonical ? Files.canonicalizePathname(path.getPath()) : path.getPath(); if (m_pathSet.add(fullPath)) { if (m_verbose) m_log.verbose(" added manifest Class-Path entry [" + path + "]"); m_path.add(m_pathIndex + (p++), path); } } } } } } } catch (FileNotFoundException fnfe) { if ($assert.ENABLED) throw fnfe; } finally { if (in != null) try { in.close(); } catch (Exception ignore) { } } }
Code Sample 2:
public void run() { String s; s = ""; try { URL url = new URL("http://www.m-w.com/dictionary/" + word); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while (((str = in.readLine()) != null) && (!stopped)) { s = s + str; } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } Pattern pattern = Pattern.compile("Main Entry:.+?<br>(.+?)</td>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher = pattern.matcher(s); java.io.StringWriter wr = new java.io.StringWriter(); HTMLDocument doc = null; HTMLEditorKit kit = (HTMLEditorKit) editor.getEditorKit(); try { doc = (HTMLDocument) editor.getDocument(); } catch (Exception e) { } System.out.println(wr); editor.setContentType("text/html"); if (matcher.find()) try { kit.insertHTML(doc, editor.getCaretPosition(), "<HR>" + matcher.group(1) + "<HR>", 0, 0, null); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } else try { kit.insertHTML(doc, editor.getCaretPosition(), "<HR><FONT COLOR='RED'>NOT FOUND!!</FONT><HR>", 0, 0, null); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } button.setEnabled(true); } |
00
| Code Sample 1:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String zOntoJsonApiUrl = getInitParameter("zOntoJsonApiServletUrl"); URL url = new URL(zOntoJsonApiUrl + "?" + req.getQueryString()); resp.setContentType("text/html"); InputStreamReader bf = new InputStreamReader(url.openStream()); BufferedReader bbf = new BufferedReader(bf); String response = ""; String line = bbf.readLine(); PrintWriter out = resp.getWriter(); while (line != null) { response += line; line = bbf.readLine(); } out.print(response); out.close(); }
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); } |
11
| Code Sample 1:
private LinkedList<Datum> processDatum(Datum dataset) { ArrayList<Object[]> markerTestResults = new ArrayList<Object[]>(); ArrayList<Object[]> alleleEstimateResults = new ArrayList<Object[]>(); boolean hasAlleleNames = false; String blank = new String(""); MarkerPhenotypeAdapter theAdapter; if (dataset.getDataType().equals(MarkerPhenotype.class)) { theAdapter = new MarkerPhenotypeAdapter((MarkerPhenotype) dataset.getData()); } else theAdapter = new MarkerPhenotypeAdapter((Phenotype) dataset.getData()); int numberOfMarkers = theAdapter.getNumberOfMarkers(); if (numberOfMarkers == 0) { return calculateBLUEsFromPhenotypes(theAdapter, dataset.getName()); } int numberOfCovariates = theAdapter.getNumberOfCovariates(); int numberOfFactors = theAdapter.getNumberOfFactors(); int numberOfPhenotypes = theAdapter.getNumberOfPhenotypes(); int expectedIterations = numberOfPhenotypes * numberOfMarkers; int iterationsSofar = 0; int percentFinished = 0; File tempFile = null; File ftestFile = null; File blueFile = null; BufferedWriter ftestWriter = null; BufferedWriter BLUEWriter = null; String ftestHeader = "Trait\tMarker\tLocus\tLocus_pos\tChr\tChr_pos\tmarker_F\tmarker_p\tperm_p\tmarkerR2\tmarkerDF\tmarkerMS\terrorDF\terrorMS\tmodelDF\tmodelMS"; String BLUEHeader = "Trait\tMarker\tObs\tLocus\tLocus_pos\tChr\tChr_pos\tAllele\tEstimate"; if (writeOutputToFile) { String outputbase = outputName; if (outputbase.endsWith(".txt")) { int index = outputbase.lastIndexOf("."); outputbase = outputbase.substring(0, index); } String datasetNameNoSpace = dataset.getName().trim().replaceAll("\\ ", "_"); ftestFile = new File(outputbase + "_" + datasetNameNoSpace + "_ftest.txt"); int count = 0; while (ftestFile.exists()) { count++; ftestFile = new File(outputbase + "_" + datasetNameNoSpace + "_ftest" + count + ".txt"); } blueFile = new File(outputbase + "_" + datasetNameNoSpace + "_BLUEs.txt"); count = 0; while (blueFile.exists()) { count++; blueFile = new File(outputbase + "_" + datasetNameNoSpace + "_BLUEs" + count + ".txt"); } tempFile = new File(outputbase + "_" + datasetNameNoSpace + "_ftest.tmp"); try { if (permute) { ftestWriter = new BufferedWriter(new FileWriter(tempFile)); ftestWriter.write(ftestHeader); ftestWriter.newLine(); } else { ftestWriter = new BufferedWriter(new FileWriter(ftestFile)); ftestWriter.write(ftestHeader); ftestWriter.newLine(); } if (reportBLUEs) { BLUEWriter = new BufferedWriter(new FileWriter(blueFile)); BLUEWriter.write(BLUEHeader); BLUEWriter.newLine(); } } catch (IOException e) { myLogger.error("Failed to open file for output"); myLogger.error(e); return null; } } if (permute) { minP = new double[numberOfPhenotypes][numberOfPermutations]; for (int i = 0; i < numberOfPermutations; i++) { for (int j = 0; j < numberOfPhenotypes; j++) { minP[j][i] = 1; } } } for (int ph = 0; ph < numberOfPhenotypes; ph++) { double[] phenotypeData = theAdapter.getPhenotypeValues(ph); boolean[] missing = theAdapter.getMissingPhenotypes(ph); ArrayList<String[]> factorList = MarkerPhenotypeAdapterUtils.getFactorList(theAdapter, ph, missing); ArrayList<double[]> covariateList = MarkerPhenotypeAdapterUtils.getCovariateList(theAdapter, ph, missing); double[][] permutedData = null; if (permute) { permutedData = permuteData(phenotypeData, missing, factorList, covariateList, theAdapter); } for (int m = 0; m < numberOfMarkers; m++) { Object[] markerData = theAdapter.getMarkerValue(ph, m); boolean[] finalMissing = new boolean[missing.length]; System.arraycopy(missing, 0, finalMissing, 0, missing.length); MarkerPhenotypeAdapterUtils.updateMissing(finalMissing, theAdapter.getMissingMarkers(ph, m)); int[] nonmissingRows = MarkerPhenotypeAdapterUtils.getNonMissingIndex(finalMissing); int numberOfObs = nonmissingRows.length; double[] y = new double[numberOfObs]; for (int i = 0; i < numberOfObs; i++) y[i] = phenotypeData[nonmissingRows[i]]; int firstMarkerAlleleEstimate = 1; ArrayList<ModelEffect> modelEffects = new ArrayList<ModelEffect>(); FactorModelEffect meanEffect = new FactorModelEffect(new int[numberOfObs], false); meanEffect.setID("mean"); modelEffects.add(meanEffect); if (numberOfFactors > 0) { for (int f = 0; f < numberOfFactors; f++) { String[] afactor = factorList.get(f); String[] factorLabels = new String[numberOfObs]; for (int i = 0; i < numberOfObs; i++) factorLabels[i] = afactor[nonmissingRows[i]]; FactorModelEffect fme = new FactorModelEffect(ModelEffectUtils.getIntegerLevels(factorLabels), true, theAdapter.getFactorName(f)); modelEffects.add(fme); firstMarkerAlleleEstimate += fme.getNumberOfLevels() - 1; } } if (numberOfCovariates > 0) { for (int c = 0; c < numberOfCovariates; c++) { double[] covar = new double[numberOfObs]; double[] covariateData = covariateList.get(c); for (int i = 0; i < numberOfObs; i++) covar[i] = covariateData[nonmissingRows[i]]; modelEffects.add(new CovariateModelEffect(covar, theAdapter.getCovariateName(c))); firstMarkerAlleleEstimate++; } } ModelEffect markerEffect; boolean markerIsDiscrete = theAdapter.isMarkerDiscrete(m); ArrayList<Object> alleleNames = new ArrayList<Object>(); if (markerIsDiscrete) { Object[] markers = new Object[numberOfObs]; for (int i = 0; i < numberOfObs; i++) markers[i] = markerData[nonmissingRows[i]]; int[] markerLevels = ModelEffectUtils.getIntegerLevels(markers, alleleNames); markerEffect = new FactorModelEffect(markerLevels, true, theAdapter.getMarkerName(m)); hasAlleleNames = true; } else { double[] markerdbl = new double[numberOfObs]; for (int i = 0; i < numberOfObs; i++) markerdbl[i] = ((Double) markerData[nonmissingRows[i]]).doubleValue(); markerEffect = new CovariateModelEffect(markerdbl, theAdapter.getMarkerName(m)); } int[] alleleCounts = markerEffect.getLevelCounts(); modelEffects.add(markerEffect); int markerEffectNumber = modelEffects.size() - 1; Identifier[] taxaSublist = new Identifier[numberOfObs]; Identifier[] taxa = theAdapter.getTaxa(ph); for (int i = 0; i < numberOfObs; i++) taxaSublist[i] = taxa[nonmissingRows[i]]; boolean areTaxaReplicated = containsDuplicates(taxaSublist); double[] markerSSdf = null, errorSSdf = null, modelSSdf = null; double F, p; double[] beta = null; if (areTaxaReplicated && markerIsDiscrete) { ModelEffect taxaEffect = new FactorModelEffect(ModelEffectUtils.getIntegerLevels(taxaSublist), true); modelEffects.add(taxaEffect); SweepFastNestedModel sfnm = new SweepFastNestedModel(modelEffects, y); double[] taxaSSdf = sfnm.getTaxaInMarkerSSdf(); double[] residualSSdf = sfnm.getErrorSSdf(); markerSSdf = sfnm.getMarkerSSdf(); errorSSdf = sfnm.getErrorSSdf(); modelSSdf = sfnm.getModelcfmSSdf(); F = markerSSdf[0] / markerSSdf[1] / taxaSSdf[0] * taxaSSdf[1]; try { p = LinearModelUtils.Ftest(F, markerSSdf[1], taxaSSdf[1]); } catch (Exception e) { p = Double.NaN; } beta = sfnm.getBeta(); int markerdf = (int) markerSSdf[1]; if (permute && markerdf > 0) { updatePermutationPValues(ph, permutedData, nonMissingIndex(missing, finalMissing), getXfromModelEffects(modelEffects), sfnm.getInverseOfXtX(), markerdf); } } else { SweepFastLinearModel sflm = new SweepFastLinearModel(modelEffects, y); modelSSdf = sflm.getModelcfmSSdf(); markerSSdf = sflm.getMarginalSSdf(markerEffectNumber); errorSSdf = sflm.getResidualSSdf(); F = markerSSdf[0] / markerSSdf[1] / errorSSdf[0] * errorSSdf[1]; try { p = LinearModelUtils.Ftest(F, markerSSdf[1], errorSSdf[1]); } catch (Exception e) { p = Double.NaN; } beta = sflm.getBeta(); int markerdf = (int) markerSSdf[1]; if (permute && markerdf > 0) { updatePermutationPValues(ph, permutedData, nonMissingIndex(missing, finalMissing), getXfromModelEffects(modelEffects), sflm.getInverseOfXtX(), markerdf); } } if (!filterOutput || p < maxp) { String traitname = theAdapter.getPhenotypeName(ph); if (traitname == null) traitname = blank; String marker = theAdapter.getMarkerName(m); if (marker == null) marker = blank; String locus = theAdapter.getLocusName(m); Integer site = new Integer(theAdapter.getLocusPosition(m)); String chrname = ""; Double chrpos = Double.NaN; if (hasMap) { int ndx = -1; ndx = myMap.getMarkerIndex(marker); if (ndx > -1) { chrname = myMap.getChromosome(ndx); chrpos = myMap.getGeneticPosition(ndx); } } Object[] result = new Object[16]; int col = 0; result[col++] = traitname; result[col++] = marker; result[col++] = locus; result[col++] = site; result[col++] = chrname; result[col++] = chrpos; result[col++] = new Double(F); result[col++] = new Double(p); result[col++] = Double.NaN; result[col++] = new Double(markerSSdf[0] / (modelSSdf[0] + errorSSdf[0])); result[col++] = new Double(markerSSdf[1]); result[col++] = new Double(markerSSdf[0] / markerSSdf[1]); result[col++] = new Double(errorSSdf[1]); result[col++] = new Double(errorSSdf[0] / errorSSdf[1]); result[col++] = new Double(modelSSdf[1]); result[col++] = new Double(modelSSdf[0] / modelSSdf[1]); if (writeOutputToFile) { StringBuilder sb = new StringBuilder(); sb.append(result[0]); for (int i = 1; i < 16; i++) sb.append("\t").append(result[i]); try { ftestWriter.write(sb.toString()); ftestWriter.newLine(); } catch (IOException e) { myLogger.error("Failed to write output to ftest file. Ending prematurely"); try { ftestWriter.flush(); BLUEWriter.flush(); } catch (Exception e1) { } myLogger.error(e); return null; } } else { markerTestResults.add(result); } int numberOfMarkerAlleles = alleleNames.size(); if (numberOfMarkerAlleles == 0) numberOfMarkerAlleles++; for (int i = 0; i < numberOfMarkerAlleles; i++) { result = new Object[9]; result[0] = traitname; result[1] = marker; result[2] = new Integer(alleleCounts[i]); result[3] = locus; result[4] = site; result[5] = chrname; result[6] = chrpos; if (numberOfMarkerAlleles == 1) result[7] = ""; else result[7] = alleleNames.get(i); if (i == numberOfMarkerAlleles - 1) result[8] = 0.0; else result[8] = beta[firstMarkerAlleleEstimate + i]; if (writeOutputToFile) { StringBuilder sb = new StringBuilder(); sb.append(result[0]); for (int j = 1; j < 9; j++) sb.append("\t").append(result[j]); try { BLUEWriter.write(sb.toString()); BLUEWriter.newLine(); } catch (IOException e) { myLogger.error("Failed to write output to ftest file. Ending prematurely"); try { ftestWriter.flush(); BLUEWriter.flush(); } catch (Exception e1) { } myLogger.error(e); return null; } } else { alleleEstimateResults.add(result); } } } int tmpPercent = ++iterationsSofar * 100 / expectedIterations; if (tmpPercent > percentFinished) { percentFinished = tmpPercent; fireProgress(percentFinished); } } } fireProgress(0); if (writeOutputToFile) { try { ftestWriter.close(); BLUEWriter.close(); } catch (IOException e) { e.printStackTrace(); } } HashMap<String, Integer> traitnameMap = new HashMap<String, Integer>(); if (permute) { for (int ph = 0; ph < numberOfPhenotypes; ph++) { Arrays.sort(minP[ph]); traitnameMap.put(theAdapter.getPhenotypeName(ph), ph); } if (writeOutputToFile) { try { BufferedReader tempReader = new BufferedReader(new FileReader(tempFile)); ftestWriter = new BufferedWriter(new FileWriter(ftestFile)); ftestWriter.write(tempReader.readLine()); ftestWriter.newLine(); String input; String[] data; Pattern tab = Pattern.compile("\t"); while ((input = tempReader.readLine()) != null) { data = tab.split(input); String trait = data[0]; double pval = Double.parseDouble(data[7]); int ph = traitnameMap.get(trait); int ndx = Arrays.binarySearch(minP[ph], pval); if (ndx < 0) ndx = -ndx - 1; if (ndx == 0) ndx = 1; data[8] = Double.toString((double) ndx / (double) numberOfPermutations); ftestWriter.write(data[0]); for (int i = 1; i < data.length; i++) { ftestWriter.write("\t"); ftestWriter.write(data[i]); } ftestWriter.newLine(); } tempReader.close(); ftestWriter.close(); tempFile.delete(); } catch (IOException e) { myLogger.error(e); } } else { for (Object[] result : markerTestResults) { String trait = result[0].toString(); double pval = (Double) result[7]; int ph = traitnameMap.get(trait); int ndx = Arrays.binarySearch(minP[ph], pval); if (ndx < 0) ndx = -ndx - 1; if (ndx == 0) ndx = 1; result[8] = new Double((double) ndx / (double) numberOfPermutations); } } } String[] columnLabels = new String[] { "Trait", "Marker", "Locus", "Locus_pos", "Chr", "Chr_pos", "marker_F", "marker_p", "perm_p", "markerR2", "markerDF", "markerMS", "errorDF", "errorMS", "modelDF", "modelMS" }; boolean hasMarkerNames = theAdapter.hasMarkerNames(); LinkedList<Integer> outputList = new LinkedList<Integer>(); outputList.add(0); if (hasMarkerNames) outputList.add(1); outputList.add(2); outputList.add(3); if (hasMap) { outputList.add(4); outputList.add(5); } outputList.add(6); outputList.add(7); if (permute) outputList.add(8); for (int i = 9; i < 16; i++) outputList.add(i); LinkedList<Datum> resultset = new LinkedList<Datum>(); int nrows = markerTestResults.size(); Object[][] table = new Object[nrows][]; int numberOfColumns = outputList.size(); String[] colnames = new String[numberOfColumns]; int count = 0; for (Integer ndx : outputList) colnames[count++] = columnLabels[ndx]; for (int i = 0; i < nrows; i++) { table[i] = new Object[numberOfColumns]; Object[] result = markerTestResults.get(i); count = 0; for (Integer ndx : outputList) table[i][count++] = result[ndx]; } StringBuilder tableName = new StringBuilder("GLM_marker_test_"); tableName.append(dataset.getName()); StringBuilder comments = new StringBuilder("Tests of Marker-Phenotype Association"); comments.append("GLM: fixed effect linear model\n"); comments.append("Data set: ").append(dataset.getName()); comments.append("\nmodel: trait = mean"); for (int i = 0; i < theAdapter.getNumberOfFactors(); i++) { comments.append(" + "); comments.append(theAdapter.getFactorName(i)); } for (int i = 0; i < theAdapter.getNumberOfCovariates(); i++) { comments.append(" + "); comments.append(theAdapter.getCovariateName(i)); } comments.append(" + marker"); if (writeOutputToFile) { comments.append("\nOutput written to " + ftestFile.getPath()); } TableReport markerTestReport = new SimpleTableReport("Marker Test", colnames, table); resultset.add(new Datum(tableName.toString(), markerTestReport, comments.toString())); int[] outputIndex; columnLabels = new String[] { "Trait", "Marker", "Obs", "Locus", "Locus_pos", "Chr", "Chr_pos", "Allele", "Estimate" }; if (hasAlleleNames) { if (hasMarkerNames && hasMap) { outputIndex = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 }; } else if (hasMarkerNames) { outputIndex = new int[] { 0, 1, 2, 3, 4, 7, 8 }; } else if (hasMap) { outputIndex = new int[] { 0, 2, 3, 4, 5, 6, 7, 8 }; } else { outputIndex = new int[] { 0, 2, 3, 4, 7, 8 }; } } else { if (hasMarkerNames && hasMap) { outputIndex = new int[] { 0, 1, 2, 3, 4, 5, 6, 8 }; } else if (hasMarkerNames) { outputIndex = new int[] { 0, 1, 2, 3, 4, 8 }; } else if (hasMap) { outputIndex = new int[] { 0, 2, 3, 4, 5, 6, 8 }; } else { outputIndex = new int[] { 0, 2, 3, 4, 8 }; } } nrows = alleleEstimateResults.size(); table = new Object[nrows][]; numberOfColumns = outputIndex.length; colnames = new String[numberOfColumns]; for (int j = 0; j < numberOfColumns; j++) { colnames[j] = columnLabels[outputIndex[j]]; } for (int i = 0; i < nrows; i++) { table[i] = new Object[numberOfColumns]; Object[] result = alleleEstimateResults.get(i); for (int j = 0; j < numberOfColumns; j++) { table[i][j] = result[outputIndex[j]]; } } tableName = new StringBuilder("GLM allele estimates for "); tableName.append(dataset.getName()); comments = new StringBuilder("Marker allele effect estimates\n"); comments.append("GLM: fixed effect linear model\n"); comments.append("Data set: ").append(dataset.getName()); comments.append("\nmodel: trait = mean"); for (int i = 0; i < theAdapter.getNumberOfFactors(); i++) { comments.append(" + "); comments.append(theAdapter.getFactorName(i)); } for (int i = 0; i < theAdapter.getNumberOfCovariates(); i++) { comments.append(" + "); comments.append(theAdapter.getCovariateName(i)); } comments.append(" + marker"); if (writeOutputToFile) { comments.append("\nOutput written to " + blueFile.getPath()); } TableReport alleleEstimateReport = new SimpleTableReport("Allele Estimates", colnames, table); resultset.add(new Datum(tableName.toString(), alleleEstimateReport, comments.toString())); fireProgress(0); return resultset; }
Code Sample 2:
public void unpack(File destDirectory, boolean delete) { if (delete) delete(destDirectory); if (destDirectory.exists()) throw new ContentPackageException("Destination directory already exists."); this.destDirectory = destDirectory; this.manifestFile = new File(destDirectory, MANIFEST_FILE_NAME); try { if (zipInputStream == null) zipInputStream = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry zipEntry; while ((zipEntry = zipInputStream.getNextEntry()) != null) { File destFile = new File(destDirectory, zipEntry.getName()); destFile.getParentFile().mkdirs(); if (!zipEntry.isDirectory()) { BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(destFile), BUFFER_SIZE); byte[] buffer = new byte[BUFFER_SIZE]; int length; while ((length = zipInputStream.read(buffer, 0, BUFFER_SIZE)) != -1) output.write(buffer, 0, length); output.close(); zipInputStream.closeEntry(); } } zipInputStream.close(); } catch (IOException ex) { throw new ContentPackageException(ex); } } |
11
| Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public static void main(String[] args) { JFileChooser askDir = new JFileChooser(); askDir.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); askDir.setMultiSelectionEnabled(false); int returnVal = askDir.showOpenDialog(null); if (returnVal == JFileChooser.CANCEL_OPTION) { System.exit(returnVal); } File startDir = askDir.getSelectedFile(); ArrayList<File> files = new ArrayList<File>(); goThrough(startDir, files); SearchClient client = new SearchClient("VZFo5W5i"); MyID3 singleton = new MyID3(); for (File song : files) { try { MusicMetadataSet set = singleton.read(song); IMusicMetadata meta = set.getSimplified(); String qu = song.getName(); if (meta.getAlbum() != null) { qu = meta.getAlbum(); } else if (meta.getArtist() != null) { qu = meta.getArtist(); } if (qu.length() > 2) { ImageSearchRequest req = new ImageSearchRequest(qu); ImageSearchResults res = client.imageSearch(req); if (res.getTotalResultsAvailable().doubleValue() > 1) { System.out.println("Downloading " + res.listResults()[0].getUrl()); URL url = new URL(res.listResults()[0].getUrl()); URLConnection con = url.openConnection(); con.setConnectTimeout(10000); int realSize = con.getContentLength(); if (realSize > 0) { String mime = con.getContentType(); InputStream stream = con.getInputStream(); byte[] realData = new byte[realSize]; for (int i = 0; i < realSize; i++) { stream.read(realData, i, 1); } stream.close(); ImageData imgData = new ImageData(realData, mime, qu, 0); meta.addPicture(imgData); File temp = File.createTempFile("tempsong", "mp3"); singleton.write(song, temp, set, meta); FileChannel inChannel = new FileInputStream(temp).getChannel(); FileChannel outChannel = new FileOutputStream(song).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } temp.delete(); } } } } catch (ID3ReadException e) { } catch (MalformedURLException e) { } catch (UnsupportedEncodingException e) { } catch (ID3WriteException e) { } catch (IOException e) { } catch (SearchException e) { } } } |
11
| Code Sample 1:
private void sendFile(File file, HttpExchange response) throws IOException { response.getResponseHeaders().add(FileUploadBase.CONTENT_LENGTH, Long.toString(file.length())); InputStream inputStream = null; try { inputStream = new FileInputStream(file); IOUtils.copy(inputStream, response.getResponseBody()); } catch (Exception exception) { throw new IOException("error sending file", exception); } finally { IOUtils.closeQuietly(inputStream); } }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } |
00
| Code Sample 1:
private 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 ObjectInputStream getObjectInputStreamFromServlet(String strUrl) throws Exception { if (headList.size() == 0) { return null; } String starter = "-----------------------------"; String returnChar = "\r\n"; String lineEnd = "--"; String urlString = strUrl; String input = null; List txtList = new ArrayList(); List fileList = new ArrayList(); String targetFile = null; String actionStatus = null; StringBuffer returnMessage = new StringBuffer(); List head = new ArrayList(); final String boundary = String.valueOf(System.currentTimeMillis()); URL url = null; URLConnection conn = null; DataOutputStream dos = null; ObjectInputStream inputFromServlet = null; try { url = new URL(baseURL, "/" + projectName + strUrl); conn = url.openConnection(); ((HttpURLConnection) conn).setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestProperty("Content-Type", "multipart/form-data, boundary=" + "---------------------------" + boundary); conn.setRequestProperty("Cookie", (String) headList.get(0)); if (input != null) { String auth = "Basic " + new sun.misc.BASE64Encoder().encode(input.getBytes()); conn.setRequestProperty("Authorization", auth); } dos = new DataOutputStream(conn.getOutputStream()); dos.flush(); inputFromServlet = new ObjectInputStream(conn.getInputStream()); txtList.clear(); fileList.clear(); } catch (EOFException e) { workflowEditor.getEditor().outputMessage("Session Expired!", false); throw e; } catch (Exception e) { e.printStackTrace(); return null; } finally { try { dos.close(); } catch (Exception e) { } } return inputFromServlet; } |
11
| Code Sample 1:
@Override protected void loadInternals(final File internDir, final ExecutionMonitor exec) throws IOException, CanceledExecutionException { List<String> taxa = new Vector<String>(); String domain = m_domain.getStringValue(); String id = ""; if (domain.equalsIgnoreCase("Eukaryota")) id = "eukaryota"; try { URL url = new URL("http://www.ebi.ac.uk/genomes/" + id + ".details.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String link = ""; String key = ""; String name = ""; int counter = 0; String line = ""; while ((line = reader.readLine()) != null) { String[] st = line.split("\t"); ena_details ena = new ena_details(st[0], st[1], st[2], st[3], st[4]); ENADataHolder.instance().put(ena.desc, ena); taxa.add(ena.desc); } reader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
public void sendMessage(Message msg) { if (!blackList.contains(msg.getTo())) { Hashtable<String, String> content = msg.getContent(); Enumeration<String> keys = content.keys(); String key; String data = "to=" + msg.getTo() + "&from=" + msg.getFrom() + "&"; while (keys.hasMoreElements()) { key = (String) keys.nextElement(); data += key + "=" + content.get(key) + "&"; } URL url = null; try { logger.log(this, Level.FINER, "sending " + data + " to " + msg.getTo()); url = new URL("http://" + msg.getTo() + ":8080/webmsgservice?" + data); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); in.readLine(); in.close(); logger.log(this, Level.FINER, "message sent to " + msg.getTo()); } catch (MalformedURLException e) { blackList.add(msg.getTo()); logger.log(this, Level.WARNING, "an error occured during message sending (" + msg.getTo() + ") : " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { logger.log(this, Level.WARNING, "an error occured during message sending (" + msg.getTo() + ") : " + e.getMessage()); blackList.add(msg.getTo()); } } else { logger.log(this, Level.FINE, "will not send message to " + msg.getTo() + " because black listed IP"); } } |
00
| Code Sample 1:
private static InputStream getResourceAsStream(String pResourcePath, Object pResourceLoader, boolean pThrow) { URL url = getResource(pResourcePath, pResourceLoader, pThrow); InputStream stream = null; if (url != null) { try { stream = url.openStream(); } catch (IOException e) { LOGGER.warn(null, e); } } return stream; }
Code Sample 2:
private String getTextResponse(String address) throws Exception { URL url = new URL(address); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setUseCaches(false); BufferedReader in = null; try { con.connect(); assertEquals(HttpURLConnection.HTTP_OK, con.getResponseCode()); in = new BufferedReader(new InputStreamReader(con.getInputStream())); StringBuilder builder = new StringBuilder(); String inputLine = null; while ((inputLine = in.readLine()) != null) { builder.append(inputLine); } return builder.toString(); } finally { if (in != null) { in.close(); } con.disconnect(); } } |
00
| Code Sample 1:
private void doDissemTest(String what, boolean redirectOK) throws Exception { final int num = 30; System.out.println("Getting " + what + " " + num + " times..."); int i = 0; try { URL url = new URL(BASE_URL + "/get/" + what); for (i = 0; i < num; i++) { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); InputStream in = conn.getInputStream(); in.read(); in.close(); conn.disconnect(); } } catch (Exception e) { fail("Dissemination of " + what + " failed on iter " + i + ": " + e.getMessage()); } }
Code Sample 2:
public FlashExObj get(String s, int page) { FlashExObj retVal = new FlashExObj(); s = s.replaceAll("[^a-z0-9_]", ""); ArrayList list = new ArrayList(); retVal.list = list; try { String result = null; URL url = new URL("http://www.flashcardexchange.com/flashcards/list/" + URLEncoder.encode(s, "UTF-8") + "?page=" + page); URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"); connection.setDoOutput(false); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); String inputLine; int state = 2; StringBuilder sb = new StringBuilder(); while ((inputLine = in.readLine()) != null) { if (state == 0) { int textPos = inputLine.indexOf("Number of Card"); if (textPos >= 0) { state = 1; } } else if (state == 1) { int s1 = inputLine.indexOf(">"); int s2 = inputLine.indexOf("<", 1); if (s1 >= 0 && s1 < s2) { String numOfCardStr = inputLine.substring(s1 + 1, s2); try { } catch (Exception e) { } state = 2; } } else if (state == 2) { int textPos = inputLine.indexOf("tbody class=\"shaded\""); if (textPos >= 0) { state = 3; } } else if (state == 3) { int textPos = inputLine.indexOf("tbody"); if (textPos >= 0) { break; } sb.append(inputLine); sb.append(" "); } } in.close(); Pattern myPattern = Pattern.compile("<td>(.*?)</td>"); Matcher myMatcher = myPattern.matcher(sb); String str; int counter = 0; String buff[] = new String[4]; while (myMatcher.find()) { int tt = counter % 4; buff[tt] = myMatcher.group(1); if (tt == 3) { String toAdd[] = new String[2]; toAdd[0] = buff[1]; toAdd[1] = buff[2]; list.add(toAdd); } counter++; } } catch (Exception e) { e.printStackTrace(); } return retVal; } |
00
| Code Sample 1:
public static String hashJopl(String password, String algorithm, String prefixKey, boolean useDefaultEncoding) { try { MessageDigest digest = MessageDigest.getInstance(algorithm); if (useDefaultEncoding) { digest.update(password.getBytes()); } else { for (char c : password.toCharArray()) { digest.update((byte) (c >> 8)); digest.update((byte) c); } } byte[] digestedPassword = digest.digest(); BASE64Encoder encoder = new BASE64Encoder(); String encodedDigestedStr = encoder.encode(digestedPassword); return prefixKey + encodedDigestedStr; } catch (NoSuchAlgorithmException ne) { return password; } }
Code Sample 2:
public APIResponse delete(String id) throws Exception { APIResponse response = new APIResponse(); connection = (HttpURLConnection) new URL(url + "/api/transaction/delete/" + id).openConnection(); connection.setRequestMethod("DELETE"); connection.setConnectTimeout(TIMEOUT); connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { response.setDone(true); response.setMessage("Transaction Deleted!"); } else { response.setDone(false); response.setMessage("Delete Transaction Error Code: Http (" + connection.getResponseCode() + ")"); } connection.disconnect(); return response; } |
00
| Code Sample 1:
public SequenceIterator call(SequenceIterator[] arguments, XPathContext context) throws XPathException { try { String encodedString = ((StringValue) arguments[0].next()).getStringValue(); byte[] decodedBytes = Base64.decode(encodedString); if (arguments.length > 1 && ((BooleanValue) arguments[1].next()).getBooleanValue()) { ByteArrayInputStream bis = new ByteArrayInputStream(decodedBytes); GZIPInputStream zis = new GZIPInputStream(bis); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(zis, baos); decodedBytes = baos.toByteArray(); } Document doc = XmlUtils.stringToDocument(new String(decodedBytes, "UTF-8")); Source source = new DOMSource(doc.getDocumentElement()); XPathEvaluator evaluator = new XPathEvaluator(context.getConfiguration()); NodeInfo[] infos = new NodeInfo[] { evaluator.setSource(source) }; return new ArrayIterator(infos); } catch (Exception e) { throw new XPathException("Could not base64 decode string", e); } }
Code Sample 2:
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) { } } } } |
11
| Code Sample 1:
public static void copyFile(final File sourceFile, final File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileInputStream inStream = null; FileOutputStream outStream = null; FileChannel source = null; FileChannel destination = null; try { source = (inStream = new FileInputStream(sourceFile)).getChannel(); destination = (outStream = new FileOutputStream(destFile)).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { closeIO(source); closeIO(inStream); closeIO(destination); closeIO(outStream); } }
Code Sample 2:
private String getResourceAsString(final String name) throws IOException { final InputStream is = JiBXTestCase.class.getResourceAsStream(name); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copyAndClose(is, baos); return baos.toString(); } |
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:
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.addHeader("Cache-Control", "max-age=" + Constants.HTTP_CACHE_SECONDS); String uuid = req.getRequestURI().substring(req.getRequestURI().indexOf(Constants.SERVLET_FULL_PREFIX) + Constants.SERVLET_FULL_PREFIX.length() + 1); boolean notScale = ClientUtils.toBoolean(req.getParameter(Constants.URL_PARAM_NOT_SCALE)); ServletOutputStream os = resp.getOutputStream(); if (uuid != null && !"".equals(uuid)) { try { String mimetype = fedoraAccess.getMimeTypeForStream(uuid, FedoraUtils.IMG_FULL_STREAM); if (mimetype == null) { mimetype = "image/jpeg"; } ImageMimeType loadFromMimeType = ImageMimeType.loadFromMimeType(mimetype); if (loadFromMimeType == ImageMimeType.JPEG || loadFromMimeType == ImageMimeType.PNG) { StringBuffer sb = new StringBuffer(); sb.append(config.getFedoraHost()).append("/objects/").append(uuid).append("/datastreams/IMG_FULL/content"); InputStream is = RESTHelper.get(sb.toString(), config.getFedoraLogin(), config.getFedoraPassword(), false); if (is == null) { return; } try { IOUtils.copyStreams(is, os); } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Unable to open full image.", e); } finally { os.flush(); if (is != null) { try { is.close(); } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Unable to close stream.", e); } finally { is = null; } } } } else { Image rawImg = KrameriusImageSupport.readImage(uuid, FedoraUtils.IMG_FULL_STREAM, this.fedoraAccess, 0, loadFromMimeType); BufferedImage scaled = null; if (!notScale) { scaled = KrameriusImageSupport.getSmallerImage(rawImg, 1250, 1000); } else { scaled = KrameriusImageSupport.getSmallerImage(rawImg, 2500, 2000); } KrameriusImageSupport.writeImageToStream(scaled, "JPG", os); resp.setContentType(ImageMimeType.JPEG.getValue()); resp.setStatus(HttpURLConnection.HTTP_OK); } } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Unable to open full image.", e); } catch (XPathExpressionException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Unable to create XPath expression.", e); } finally { os.flush(); } } } |
11
| Code Sample 1:
public static void cpdir(File src, File dest) throws BrutException { dest.mkdirs(); File[] files = src.listFiles(); for (int i = 0; i < files.length; i++) { File file = files[i]; File destFile = new File(dest.getPath() + File.separatorChar + file.getName()); if (file.isDirectory()) { cpdir(file, destFile); continue; } try { InputStream in = new FileInputStream(file); OutputStream out = new FileOutputStream(destFile); IOUtils.copy(in, out); in.close(); out.close(); } catch (IOException ex) { throw new BrutException("Could not copy file: " + file, ex); } } }
Code Sample 2:
public 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:
public static final String getUniqueId() { String digest = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); String timeVal = "" + (System.currentTimeMillis() + 1); String localHost = ""; try { localHost = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { throw new RuntimeException("Error trying to get localhost" + e.getMessage()); } String randVal = "" + new Random().nextInt(); String val = timeVal + localHost + randVal; md.reset(); md.update(val.getBytes()); digest = toHexString(md.digest()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("NoSuchAlgorithmException : " + e.getMessage()); } return digest; }
Code Sample 2:
public static String generateMessageId(String plain) { byte[] cipher = new byte[35]; String messageId = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(plain.getBytes()); cipher = md5.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < cipher.length; i++) { String hex = Integer.toHexString(0xff & cipher[i]); if (hex.length() == 1) sb.append('0'); sb.append(hex); } StringBuffer pass = new StringBuffer(); pass.append(sb.substring(0, 6)); pass.append("H"); pass.append(sb.substring(6, 11)); pass.append("H"); pass.append(sb.substring(11, 21)); pass.append("H"); pass.append(sb.substring(21)); messageId = new String(pass); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return messageId; } |
00
| Code Sample 1:
private void copyFile(File f) throws IOException { File newFile = new File(destdir + "/" + f.getName()); newFile.createNewFile(); FileInputStream fin = new FileInputStream(f); FileOutputStream fout = new FileOutputStream(newFile); int c; while ((c = fin.read()) != -1) fout.write(c); fin.close(); fout.close(); }
Code Sample 2:
private void RotaDraw(GeoPoint orig, GeoPoint dest, int color, MapView mapa) { StringBuilder urlString = new StringBuilder(); urlString.append("http://maps.google.com/maps?f=d&hl=en"); urlString.append("&saddr="); urlString.append(Double.toString((double) orig.getLatitudeE6() / 1.0E6)); urlString.append(","); urlString.append(Double.toString((double) orig.getLongitudeE6() / 1.0E6)); urlString.append("&daddr="); urlString.append(Double.toString((double) dest.getLatitudeE6() / 1.0E6)); urlString.append(","); urlString.append(Double.toString((double) dest.getLongitudeE6() / 1.0E6)); urlString.append("&ie=UTF8&0&om=0&output=kml"); Document doc = null; HttpURLConnection urlConnection = null; URL url = null; try { url = new URL(urlString.toString()); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.connect(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); doc = db.parse(urlConnection.getInputStream()); if (doc.getElementsByTagName("GeometryCollection").getLength() > 0) { String path = doc.getElementsByTagName("GeometryCollection").item(0).getFirstChild().getFirstChild().getFirstChild().getNodeValue(); Log.d("xxx", "path=" + path); String[] pairs = path.split(" "); String[] lngLat = pairs[0].split(","); GeoPoint startGP = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double.parseDouble(lngLat[0]) * 1E6)); mapa.getOverlays().add(new CamadaGS(startGP, startGP, 1)); GeoPoint gp1; GeoPoint gp2 = startGP; for (int i = 1; i < pairs.length; i++) { lngLat = pairs[i].split(","); gp1 = gp2; gp2 = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double.parseDouble(lngLat[0]) * 1E6)); mapa.getOverlays().add(new CamadaGS(gp1, gp2, 2, color)); Log.d("xxx", "pair:" + pairs[i]); } mapa.getOverlays().add(new CamadaGS(dest, dest, 3)); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } } |
11
| Code Sample 1:
public void processDeleteHolding(Holding holdingBean, AuthSession authSession) { if (authSession == null) { return; } DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); if (holdingBean.getId() == null) throw new IllegalArgumentException("holdingId is null"); processDeleteRelatedCompany(dbDyn, holdingBean, authSession); String sql = "delete from WM_LIST_HOLDING " + "where ID_HOLDING=? and ID_HOLDING in "; switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: String idList = authSession.getGrantedHoldingId(); sql += " (" + idList + ") "; break; default: sql += "(select z1.ID_ROAD from v$_read_list_road z1 where z1.user_login = ?)"; break; } ps = dbDyn.prepareStatement(sql); RsetTools.setLong(ps, 1, holdingBean.getId()); switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: break; default: ps.setString(2, authSession.getUserLogin()); break; } int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of deleted records - " + i1); dbDyn.commit(); } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error delete holding"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } }
Code Sample 2:
@Override public synchronized void deleteCallStatistics(Integer elementId, String contextName, String category, String project, String name, Date dateFrom, Date dateTo, Boolean extractException, String principal) throws DatabaseException { final Connection connection = this.getConnection(); try { connection.setAutoCommit(false); String queryString = "DELETE " + this.getCallInvocationsSchemaAndTableName() + " FROM " + this.getCallInvocationsSchemaAndTableName() + " INNER JOIN " + this.getCallElementsSchemaAndTableName() + " ON " + this.getCallElementsSchemaAndTableName() + ".element_id = " + this.getCallInvocationsSchemaAndTableName() + ".element_id "; if (principal != null) { queryString = queryString + "LEFT JOIN " + this.getCallPrincipalsSchemaAndTableName() + " ON " + this.getCallInvocationsSchemaAndTableName() + ".principal_id = " + this.getCallPrincipalsSchemaAndTableName() + ".principal_id "; } queryString = queryString + "WHERE "; if (elementId != null) { queryString = queryString + this.getCallElementsSchemaAndTableName() + ".elementId = ? AND "; } if (contextName != null) { queryString = queryString + this.getCallElementsSchemaAndTableName() + ".context_name LIKE ? AND "; } if ((category != null)) { queryString = queryString + this.getCallElementsSchemaAndTableName() + ".category LIKE ? AND "; } if ((project != null)) { queryString = queryString + this.getCallElementsSchemaAndTableName() + ".project LIKE ? AND "; } if ((name != null)) { queryString = queryString + this.getCallElementsSchemaAndTableName() + ".name LIKE ? AND "; } if (dateFrom != null) { queryString = queryString + this.getCallInvocationsSchemaAndTableName() + ".start_timestamp >= ? AND "; } if (dateTo != null) { queryString = queryString + this.getCallInvocationsSchemaAndTableName() + ".start_timestamp <= ? AND "; } if (principal != null) { queryString = queryString + this.getCallPrincipalsSchemaAndTableName() + ".principal_name LIKE ? AND "; } if (extractException != null) { if (extractException.booleanValue()) { queryString = queryString + this.getCallInvocationsSchemaAndTableName() + ".exception_id IS NOT NULL AND "; } else { queryString = queryString + this.getCallInvocationsSchemaAndTableName() + ".exception_id IS NULL AND "; } } queryString = DefaultDatabaseHandler.removeOrphanWhereAndAndFromSelect(queryString); final PreparedStatement preparedStatement = DebugPreparedStatement.prepareStatement(connection, queryString); int indexCounter = 1; if (elementId != null) { preparedStatement.setLong(indexCounter, elementId.longValue()); indexCounter = indexCounter + 1; } if (contextName != null) { preparedStatement.setString(indexCounter, contextName); indexCounter = indexCounter + 1; } if ((category != null)) { preparedStatement.setString(indexCounter, category); indexCounter = indexCounter + 1; } if ((project != null)) { preparedStatement.setString(indexCounter, project); indexCounter = indexCounter + 1; } if ((name != null)) { preparedStatement.setString(indexCounter, name); indexCounter = indexCounter + 1; } if (dateFrom != null) { preparedStatement.setTimestamp(indexCounter, new Timestamp(dateFrom.getTime())); indexCounter = indexCounter + 1; } if (dateTo != null) { preparedStatement.setTimestamp(indexCounter, new Timestamp(dateTo.getTime())); indexCounter = indexCounter + 1; } if (principal != null) { preparedStatement.setString(indexCounter, principal); indexCounter = indexCounter + 1; } preparedStatement.executeUpdate(); preparedStatement.close(); connection.commit(); } catch (final SQLException e) { try { connection.rollback(); } catch (final SQLException ex) { JeeObserverServerContext.logger.log(Level.SEVERE, "Transaction rollback error.", ex); } JeeObserverServerContext.logger.log(Level.SEVERE, e.getMessage()); throw new DatabaseException("Error deleting call statistics.", e); } finally { this.releaseConnection(connection); } } |
00
| Code Sample 1:
public FlashExObj get(String s, int page) { FlashExObj retVal = new FlashExObj(); s = s.replaceAll("[^a-z0-9_]", ""); ArrayList list = new ArrayList(); retVal.list = list; try { String result = null; URL url = new URL("http://www.flashcardexchange.com/flashcards/list/" + URLEncoder.encode(s, "UTF-8") + "?page=" + page); URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"); connection.setDoOutput(false); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); String inputLine; int state = 2; StringBuilder sb = new StringBuilder(); while ((inputLine = in.readLine()) != null) { if (state == 0) { int textPos = inputLine.indexOf("Number of Card"); if (textPos >= 0) { state = 1; } } else if (state == 1) { int s1 = inputLine.indexOf(">"); int s2 = inputLine.indexOf("<", 1); if (s1 >= 0 && s1 < s2) { String numOfCardStr = inputLine.substring(s1 + 1, s2); try { } catch (Exception e) { } state = 2; } } else if (state == 2) { int textPos = inputLine.indexOf("tbody class=\"shaded\""); if (textPos >= 0) { state = 3; } } else if (state == 3) { int textPos = inputLine.indexOf("tbody"); if (textPos >= 0) { break; } sb.append(inputLine); sb.append(" "); } } in.close(); Pattern myPattern = Pattern.compile("<td>(.*?)</td>"); Matcher myMatcher = myPattern.matcher(sb); String str; int counter = 0; String buff[] = new String[4]; while (myMatcher.find()) { int tt = counter % 4; buff[tt] = myMatcher.group(1); if (tt == 3) { String toAdd[] = new String[2]; toAdd[0] = buff[1]; toAdd[1] = buff[2]; list.add(toAdd); } counter++; } } catch (Exception e) { e.printStackTrace(); } return retVal; }
Code Sample 2:
public static int copyFile(File src, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(src).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) in.close(); if (out != null) out.close(); } return 1; } |
00
| Code Sample 1:
@Override public boolean exists() { if (local_file.exists()) { return true; } else { try { URLConnection c = remote_url.openConnection(); try { c.setConnectTimeout(CIO.getLoadingTimeOut()); c.connect(); return c.getContentLength() > 0; } catch (Exception err) { err.printStackTrace(); return false; } finally { if (c instanceof HttpURLConnection) { ((HttpURLConnection) c).disconnect(); } } } catch (IOException e) { e.printStackTrace(); return false; } } }
Code Sample 2:
public void sendTemplate(String filename, TemplateValues values) throws IOException { Checker.checkEmpty(filename, "filename"); Checker.checkNull(values, "values"); URL url = _getFile(filename); boolean writeSpaces = Context.getRootContext().getRunMode() == RUN_MODE.DEV ? true : false; Template t = new Template(url.openStream(), writeSpaces); try { t.write(getWriter(), values); } catch (ErrorListException ele) { Context.getRootContext().getLogger().error(ele); } } |
11
| Code Sample 1:
@Test public void testCopy_inputStreamToWriter_Encoding_nullEncoding() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStreamTest out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); IOUtils.copy(in, writer, null); out.off(); writer.flush(); assertTrue("Not all bytes were read", in.available() == 0); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); }
Code Sample 2:
void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); } |
11
| Code Sample 1:
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 he3Decode(String in_file) { try { File out = new File(in_file + extension); File in = new File(in_file); int file_size = (int) in.length(); FileInputStream in_stream = new FileInputStream(in_file); out.createNewFile(); FileOutputStream out_stream = new FileOutputStream(out.getName()); ByteArrayOutputStream os = new ByteArrayOutputStream(file_size); byte byte_arr[] = new byte[8]; int buff_size = byte_arr.length; int _fetched = 0; int _chars_read = 0; System.out.println(appname + ".\n" + "decoding: " + in_file + "\n" + "decoding to: " + in_file + extension + "\n" + "\nreading: "); while (_fetched < file_size) { _chars_read = in_stream.read(byte_arr, 0, buff_size); if (_chars_read == -1) break; os.write(byte_arr, 0, _chars_read); _fetched += _chars_read; System.out.print("*"); } System.out.print("\ndecoding: "); out_stream.write(_decode((ByteArrayOutputStream) os)); System.out.print("complete\n\n"); } catch (java.io.FileNotFoundException fnfEx) { System.err.println("Exception: " + fnfEx.getMessage()); } catch (java.io.IOException ioEx) { System.err.println("Exception: " + ioEx.getMessage()); } } |
00
| Code Sample 1:
private static void testTidy() { try { String url = "http://groups.google.com/group/dengues/files"; java.io.InputStream is = new java.net.URL(url).openStream(); org.w3c.dom.Document doc = dengues.system.HTMLWebHelper.parseDOM(is); org.w3c.dom.NodeList list = doc.getElementsByTagName("td"); org.w3c.dom.Element stockTypeElement = null; for (int i = 0; i < list.getLength(); i++) { org.w3c.dom.Node item = list.item(i); String content = dengues.system.HTMLWebHelper.getContent(item); String convert = dengues.system.HTMLWebHelper.convert(content); if (convert.equals("zDevil")) { stockTypeElement = (org.w3c.dom.Element) item.getParentNode().getParentNode(); break; } } if (stockTypeElement != null) { org.w3c.dom.NodeList trList = stockTypeElement.getElementsByTagName("tr"); for (int i = 0; i < trList.getLength(); i++) { org.w3c.dom.NodeList trListChildren = trList.item(i).getChildNodes(); if (trListChildren.getLength() > 2) { org.w3c.dom.Node node_0 = trListChildren.item(0); org.w3c.dom.Node node_1 = trListChildren.item(1); String content = dengues.system.HTMLWebHelper.getContent(node_0); String convert_0 = dengues.system.HTMLWebHelper.convert(content); content = dengues.system.HTMLWebHelper.getContent(node_1); String convert_1 = dengues.system.HTMLWebHelper.convert(content); if (!"".equals(convert_0)) { System.out.println(convert_0 + " => " + convert_1); } } } } is.close(); } catch (java.net.MalformedURLException ex) { ex.printStackTrace(); } catch (java.io.IOException ex) { ex.printStackTrace(); } }
Code Sample 2:
static synchronized Person lookup(PhoneNumber number, String siteName) { Vector<Person> foundPersons = new Vector<Person>(5); if (number.isFreeCall()) { Person p = new Person("", "FreeCall"); p.addNumber(number); foundPersons.add(p); } else if (number.isSIPNumber() || number.isQuickDial()) { Person p = new Person(); p.addNumber(number); foundPersons.add(p); } else if (ReverseLookup.rlsMap.containsKey(number.getCountryCode())) { nummer = number.getAreaNumber(); rls_list = ReverseLookup.rlsMap.get(number.getCountryCode()); Debug.info("Begin reverselookup for: " + nummer); if (nummer.startsWith(number.getCountryCode())) nummer = nummer.substring(number.getCountryCode().length()); city = ""; for (int i = 0; i < rls_list.size(); i++) { yield(); rls = rls_list.get(i); if (!siteName.equals("") && !siteName.equals(rls.getName())) { Debug.warning("This lookup should be done using a specific site, skipping"); continue; } prefix = rls.getPrefix(); ac_length = rls.getAreaCodeLength(); if (!nummer.startsWith(prefix)) nummer = prefix + nummer; urlstr = rls.getURL(); if (urlstr.contains("$AREACODE")) { urlstr = urlstr.replaceAll("\\$AREACODE", nummer.substring(prefix.length(), ac_length + prefix.length())); urlstr = urlstr.replaceAll("\\$NUMBER", nummer.substring(prefix.length() + ac_length)); } else if (urlstr.contains("$PFXAREACODE")) { urlstr = urlstr.replaceAll("\\$PFXAREACODE", nummer.substring(0, prefix.length() + ac_length)); urlstr = urlstr.replaceAll("\\$NUMBER", nummer.substring(prefix.length() + ac_length)); } else urlstr = urlstr.replaceAll("\\$NUMBER", nummer); Debug.info("Reverse lookup using: " + urlstr); url = null; data = new String[dataLength]; try { url = new URL(urlstr); if (url != null) { try { con = url.openConnection(); con.setConnectTimeout(5000); con.setReadTimeout(15000); con.addRequestProperty("User-Agent", userAgent); con.connect(); header = ""; charSet = ""; for (int j = 0; ; j++) { String headerName = con.getHeaderFieldKey(j); String headerValue = con.getHeaderField(j); if (headerName == null && headerValue == null) { break; } if ("content-type".equalsIgnoreCase(headerName)) { String[] split = headerValue.split(";", 2); for (int k = 0; k < split.length; k++) { if (split[k].trim().toLowerCase().startsWith("charset=")) { String[] charsetSplit = split[k].split("="); charSet = charsetSplit[1].trim(); } } } header += headerName + ": " + headerValue + " | "; } Debug.debug("Header of " + rls.getName() + ":" + header); Debug.debug("CHARSET : " + charSet); BufferedReader d; if (charSet.equals("")) { d = new BufferedReader(new InputStreamReader(con.getInputStream(), "ISO-8859-1")); } else { d = new BufferedReader(new InputStreamReader(con.getInputStream(), charSet)); } int lines = 0; while (null != ((str = d.readLine()))) { data[lines] = str; yield(); if (lines >= dataLength) { System.err.println("Result > " + dataLength + " Lines"); break; } lines++; } d.close(); Debug.info("Begin processing response from " + rls.getName()); for (int j = 0; j < rls.size(); j++) { yield(); firstname = ""; lastname = ""; company = ""; street = ""; zipcode = ""; city = ""; Person p = null; patterns = rls.getEntry(j); Pattern namePattern = null; Pattern streetPattern = null; Pattern cityPattern = null; Pattern zipcodePattern = null; Pattern firstnamePattern = null; Pattern lastnamePattern = null; Matcher nameMatcher = null; Matcher streetMatcher = null; Matcher cityMatcher = null; Matcher zipcodeMatcher = null; Matcher firstnameMatcher = null; Matcher lastnameMatcher = null; if (!patterns[ReverseLookupSite.NAME].equals("") && (patterns[ReverseLookupSite.FIRSTNAME].equals("") && patterns[ReverseLookupSite.LASTNAME].equals(""))) { namePattern = Pattern.compile(patterns[ReverseLookupSite.NAME]); } if (!patterns[ReverseLookupSite.STREET].equals("")) { streetPattern = Pattern.compile(patterns[ReverseLookupSite.STREET]); } if (!patterns[ReverseLookupSite.CITY].equals("")) { cityPattern = Pattern.compile(patterns[ReverseLookupSite.CITY]); } if (!patterns[ReverseLookupSite.ZIPCODE].equals("")) { zipcodePattern = Pattern.compile(patterns[ReverseLookupSite.ZIPCODE]); } if (!patterns[ReverseLookupSite.FIRSTNAME].equals("")) { firstnamePattern = Pattern.compile(patterns[ReverseLookupSite.FIRSTNAME]); } if (!patterns[ReverseLookupSite.LASTNAME].equals("")) { lastnamePattern = Pattern.compile(patterns[ReverseLookupSite.LASTNAME]); } for (int line = 0; line < dataLength; line++) { if (data[line] != null) { int spaceAlternative = 160; data[line] = data[line].replaceAll(new Character((char) spaceAlternative).toString(), " "); if (lastnamePattern != null) { lastnameMatcher = lastnamePattern.matcher(data[line]); if (lastnameMatcher.find()) { str = ""; for (int k = 1; k <= lastnameMatcher.groupCount(); k++) { if (lastnameMatcher.group(k) != null) str = str + lastnameMatcher.group(k).trim() + " "; } lastname = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(str)); lastname = lastname.trim(); lastname = lastname.replaceAll(",", ""); lastname = lastname.replaceAll("%20", " "); lastname = JFritzUtils.replaceSpecialCharsUTF(lastname); lastname = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(lastname)); lastname = JFritzUtils.removeDuplicateWhitespace(lastname); if ("lastname".equals(patterns[ReverseLookupSite.FIRSTOCCURANCE])) { p = new Person(); p.addNumber(number.getIntNumber(), "home"); foundPersons.add(p); } if (p != null) { p.setLastName(lastname); } } } yield(); if (firstnamePattern != null) { firstnameMatcher = firstnamePattern.matcher(data[line]); if (firstnameMatcher.find()) { str = ""; for (int k = 1; k <= firstnameMatcher.groupCount(); k++) { if (firstnameMatcher.group(k) != null) str = str + firstnameMatcher.group(k).trim() + " "; } firstname = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(str)); firstname = firstname.trim(); firstname = firstname.replaceAll(",", ""); firstname = firstname.replaceAll("%20", " "); firstname = JFritzUtils.replaceSpecialCharsUTF(firstname); firstname = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(firstname)); firstname = JFritzUtils.removeDuplicateWhitespace(firstname); if ("firstname".equals(patterns[ReverseLookupSite.FIRSTOCCURANCE])) { p = new Person(); p.addNumber(number.getIntNumber(), "home"); foundPersons.add(p); } if (p != null) { p.setFirstName(firstname); } } } yield(); if (namePattern != null) { nameMatcher = namePattern.matcher(data[line]); if (nameMatcher.find()) { str = ""; for (int k = 1; k <= nameMatcher.groupCount(); k++) { if (nameMatcher.group(k) != null) str = str + nameMatcher.group(k).trim() + " "; } String[] split; split = str.split(" ", 2); lastname = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(split[0])); lastname = lastname.trim(); lastname = lastname.replaceAll(",", ""); lastname = lastname.replaceAll("%20", " "); lastname = JFritzUtils.replaceSpecialCharsUTF(lastname); lastname = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(lastname)); lastname = JFritzUtils.removeDuplicateWhitespace(lastname); if (split[1].length() > 0) { firstname = HTMLUtil.stripEntities(split[1]); if ((firstname.indexOf(" ") > -1) && (firstname.indexOf(" u.") == -1)) { company = JFritzUtils.removeLeadingSpaces(firstname.substring(firstname.indexOf(" ")).trim()); firstname = JFritzUtils.removeLeadingSpaces(firstname.substring(0, firstname.indexOf(" ")).trim()); } else { firstname = JFritzUtils.removeLeadingSpaces(firstname.replaceAll(" u. ", " und ")); } } firstname = firstname.replaceAll("%20", " "); firstname = JFritzUtils.replaceSpecialCharsUTF(firstname); firstname = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(firstname)); firstname = JFritzUtils.removeDuplicateWhitespace(firstname); firstname = firstname.trim(); company = company.replaceAll("%20", " "); company = JFritzUtils.replaceSpecialCharsUTF(company); company = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(company)); company = JFritzUtils.removeDuplicateWhitespace(company); company = company.trim(); if ("name".equals(patterns[ReverseLookupSite.FIRSTOCCURANCE])) { p = new Person(); if (company.length() > 0) { p.addNumber(number.getIntNumber(), "business"); } else { p.addNumber(number.getIntNumber(), "home"); } foundPersons.add(p); } if (p != null) { p.setFirstName(firstname); p.setLastName(lastname); p.setCompany(company); } } } yield(); if (streetPattern != null) { streetMatcher = streetPattern.matcher(data[line]); if (streetMatcher.find()) { str = ""; for (int k = 1; k <= streetMatcher.groupCount(); k++) { if (streetMatcher.group(k) != null) str = str + streetMatcher.group(k).trim() + " "; } street = str.replaceAll("%20", " "); street = JFritzUtils.replaceSpecialCharsUTF(street); street = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(street)); street = JFritzUtils.removeDuplicateWhitespace(street); street = street.trim(); if ("street".equals(patterns[ReverseLookupSite.FIRSTOCCURANCE])) { p = new Person(); p.addNumber(number.getIntNumber(), "home"); foundPersons.add(p); } if (p != null) { p.setStreet(street); } } } yield(); if (cityPattern != null) { cityMatcher = cityPattern.matcher(data[line]); if (cityMatcher.find()) { str = ""; for (int k = 1; k <= cityMatcher.groupCount(); k++) { if (cityMatcher.group(k) != null) str = str + cityMatcher.group(k).trim() + " "; } city = str.replaceAll("%20", " "); city = JFritzUtils.replaceSpecialCharsUTF(city); city = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(city)); city = JFritzUtils.removeDuplicateWhitespace(city); city = city.trim(); if ("city".equals(patterns[ReverseLookupSite.FIRSTOCCURANCE])) { p = new Person(); p.addNumber(number.getIntNumber(), "home"); foundPersons.add(p); } if (p != null) { p.setCity(city); } } } yield(); if (zipcodePattern != null) { zipcodeMatcher = zipcodePattern.matcher(data[line]); if (zipcodeMatcher.find()) { str = ""; for (int k = 1; k <= zipcodeMatcher.groupCount(); k++) { if (zipcodeMatcher.group(k) != null) str = str + zipcodeMatcher.group(k).trim() + " "; } zipcode = str.replaceAll("%20", " "); zipcode = JFritzUtils.replaceSpecialCharsUTF(zipcode); zipcode = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(zipcode)); zipcode = JFritzUtils.removeDuplicateWhitespace(zipcode); zipcode = zipcode.trim(); if ("zipcode".equals(patterns[ReverseLookupSite.FIRSTOCCURANCE])) { p = new Person(); p.addNumber(number.getIntNumber(), "home"); foundPersons.add(p); } if (p != null) { p.setPostalCode(zipcode); } } } } } if (!firstname.equals("") || !lastname.equals("") || !company.equals("")) break; } yield(); if (!firstname.equals("") || !lastname.equals("") || !company.equals("")) { if (city.equals("")) { if (number.getCountryCode().equals(ReverseLookup.GERMANY_CODE)) city = ReverseLookupGermany.getCity(nummer); else if (number.getCountryCode().equals(ReverseLookup.AUSTRIA_CODE)) city = ReverseLookupAustria.getCity(nummer); else if (number.getCountryCode().startsWith(ReverseLookup.USA_CODE)) city = ReverseLookupUnitedStates.getCity(nummer); else if (number.getCountryCode().startsWith(ReverseLookup.TURKEY_CODE)) city = ReverseLookupTurkey.getCity(nummer); } return foundPersons.get(0); } } catch (IOException e1) { Debug.error("Error while retrieving " + urlstr); } } } catch (MalformedURLException e) { Debug.error("URL invalid: " + urlstr); } } yield(); Debug.warning("No match for " + nummer + " found"); if (city.equals("")) { if (number.getCountryCode().equals(ReverseLookup.GERMANY_CODE)) city = ReverseLookupGermany.getCity(nummer); else if (number.getCountryCode().equals(ReverseLookup.AUSTRIA_CODE)) city = ReverseLookupAustria.getCity(nummer); else if (number.getCountryCode().startsWith(ReverseLookup.USA_CODE)) city = ReverseLookupUnitedStates.getCity(nummer); else if (number.getCountryCode().startsWith(ReverseLookup.TURKEY_CODE)) city = ReverseLookupTurkey.getCity(nummer); } Person p = new Person("", "", "", "", "", city, "", ""); p.addNumber(number.getAreaNumber(), "home"); return p; } else { Debug.warning("No reverse lookup sites for: " + number.getCountryCode()); Person p = new Person(); p.addNumber(number.getAreaNumber(), "home"); if (number.getCountryCode().equals(ReverseLookup.GERMANY_CODE)) city = ReverseLookupGermany.getCity(number.getIntNumber()); else if (number.getCountryCode().equals(ReverseLookup.AUSTRIA_CODE)) city = ReverseLookupAustria.getCity(number.getIntNumber()); else if (number.getCountryCode().startsWith(ReverseLookup.USA_CODE)) city = ReverseLookupUnitedStates.getCity(number.getIntNumber()); else if (number.getCountryCode().startsWith(ReverseLookup.TURKEY_CODE)) city = ReverseLookupTurkey.getCity(number.getIntNumber()); p.setCity(city); return p; } return new Person("not found", "Person"); } |
11
| Code Sample 1:
public static String[] putFECSplitFile(String uri, File file, int htl, boolean mode) { FcpFECUtils fecutils = null; Vector segmentHeaders = null; Vector segmentFileMaps = new Vector(); Vector checkFileMaps = new Vector(); Vector segmentKeyMaps = new Vector(); Vector checkKeyMaps = new Vector(); int fileLength = (int) file.length(); String output = new String(); int maxThreads = frame1.frostSettings.getIntValue("splitfileUploadThreads"); Thread[] chunkThreads = null; String[][] chunkResults = null; Thread[] checkThreads = null; String[][] checkResults = null; int threadCount = 0; String board = getBoard(file); { fecutils = new FcpFECUtils(frame1.frostSettings.getValue("nodeAddress"), frame1.frostSettings.getIntValue("nodePort")); synchronized (fecutils.getClass()) { try { segmentHeaders = fecutils.FECSegmentFile("OnionFEC_a_1_2", fileLength); } catch (Exception e) { } } int chunkCnt = 0; int checkCnt = 0; synchronized (fecutils.getClass()) { try { Socket fcpSock; BufferedInputStream fcpIn; PrintStream fcpOut; for (int i = 0; i < segmentHeaders.size(); i++) { int blockCount = (int) ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).BlockCount; int blockNo = 0; fcpSock = new Socket(InetAddress.getByName(frame1.frostSettings.getValue("nodeAddress")), frame1.frostSettings.getIntValue("nodePort")); fcpSock.setSoTimeout(1800000); fcpOut = new PrintStream(fcpSock.getOutputStream()); fcpIn = new BufferedInputStream(fcpSock.getInputStream()); FileInputStream fileIn = new FileInputStream(file); File[] chunkFiles = new File[blockCount]; { System.out.println("Processing segment " + i); fileIn.skip(((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).Offset); long segLength = ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).BlockCount * ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).BlockSize; System.out.println("segLength = " + Long.toHexString(segLength)); String headerString = "SegmentHeader\n" + ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).reconstruct() + "EndMessage\n"; String dataHeaderString = "\0\0\0\2FECEncodeSegment\nMetadataLength=" + Long.toHexString(headerString.length()) + "\nDataLength=" + Long.toHexString(headerString.length() + segLength) + "\nData\n" + headerString; System.out.print(dataHeaderString); fcpOut.print(dataHeaderString); long count = 0; while (count < segLength) { byte[] buffer = new byte[(int) ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).BlockSize]; System.out.println(Long.toHexString(((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).Offset + count)); int inbytes = fileIn.read(buffer); if (inbytes < 0) { System.out.println("End of input file - no data"); for (int j = 0; j < buffer.length; j++) buffer[j] = 0; inbytes = buffer.length; } if (inbytes < buffer.length) { System.out.println("End of input file - not enough data"); for (int j = inbytes; j < buffer.length; j++) buffer[j] = 0; inbytes = buffer.length; } if (inbytes > segLength - count) inbytes = (int) (segLength - count); fcpOut.write(buffer); File uploadMe = new File(frame1.keypool + String.valueOf(System.currentTimeMillis()) + "-" + chunkCnt + ".tmp"); chunkFiles[blockNo] = uploadMe; uploadMe.deleteOnExit(); FileOutputStream fileOut = new FileOutputStream(uploadMe); fileOut.write(buffer, 0, (int) inbytes); fileOut.close(); count += inbytes; chunkCnt++; ; blockNo++; if (blockNo >= blockCount) break; } segmentFileMaps.add(chunkFiles); fcpOut.flush(); fileIn.close(); } int checkNo = 0; int checkBlockCount = (int) ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).CheckBlockCount; File[] checkFiles = new File[checkBlockCount]; File uploadMe = null; FileOutputStream outFile = null; { String currentLine; long checkBlockSize = ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).CheckBlockSize; int checkPtr = 0; int length = 0; do { boolean started = false; currentLine = fecutils.getLine(fcpIn).trim(); if (currentLine.equals("DataChunk")) { started = true; } if (currentLine.startsWith("Length=")) { length = Integer.parseInt((currentLine.split("="))[1], 16); } if (currentLine.equals("Data")) { int currentRead; byte[] buffer = new byte[(int) length]; if (uploadMe == null) { uploadMe = new File(frame1.keypool + String.valueOf(System.currentTimeMillis()) + "-chk-" + checkCnt + ".tmp"); uploadMe.deleteOnExit(); outFile = new FileOutputStream(uploadMe); } currentRead = fcpIn.read(buffer); while (currentRead < length) { currentRead += fcpIn.read(buffer, currentRead, length - currentRead); } outFile.write(buffer); checkPtr += currentRead; if (checkPtr == checkBlockSize) { outFile.close(); checkFiles[checkNo] = uploadMe; uploadMe = null; checkNo++; checkCnt++; checkPtr = 0; } } } while (currentLine.length() > 0); checkFileMaps.add(checkFiles); } fcpOut.close(); fcpIn.close(); fcpSock.close(); } } catch (Exception e) { System.out.println("putFECSplitFile NOT GOOD " + e.toString()); } } int chunkNo = 0; int uploadedBytes = 0; for (int i = 0; i < segmentFileMaps.size(); i++) { File[] currentFileMap = (File[]) segmentFileMaps.get(i); chunkThreads = new Thread[currentFileMap.length]; chunkResults = new String[currentFileMap.length][2]; threadCount = 0; for (int j = 0; j < currentFileMap.length; j++) { if (DEBUG) System.out.println("Chunk: " + chunkNo); while (getActiveThreads(chunkThreads) >= maxThreads) mixed.wait(5000); chunkThreads[threadCount] = new putKeyThread("CHK@", currentFileMap[j], htl, chunkResults, threadCount, mode); chunkThreads[threadCount].start(); threadCount++; uploadedBytes += currentFileMap[j].length(); updateUploadTable(file, uploadedBytes, mode); mixed.wait(1000); chunkNo++; } while (getActiveThreads(chunkThreads) > 0) { if (DEBUG) System.out.println("Active Splitfile inserts remaining: " + getActiveThreads(chunkThreads)); mixed.wait(3000); } segmentKeyMaps.add(chunkResults); } int checkNo = 0; for (int i = 0; i < checkFileMaps.size(); i++) { File[] currentFileMap = (File[]) checkFileMaps.get(i); checkThreads = new Thread[currentFileMap.length]; checkResults = new String[currentFileMap.length][2]; threadCount = 0; for (int j = 0; j < currentFileMap.length; j++) { if (DEBUG) System.out.println("Check: " + checkNo); while (getActiveThreads(checkThreads) >= maxThreads) mixed.wait(5000); checkThreads[threadCount] = new putKeyThread("CHK@", currentFileMap[j], htl, checkResults, threadCount, mode); checkThreads[threadCount].start(); threadCount++; uploadedBytes += currentFileMap[j].length(); updateUploadTable(file, uploadedBytes, mode); mixed.wait(1000); checkNo++; } while (getActiveThreads(checkThreads) > 0) { if (DEBUG) System.out.println("Active Checkblock inserts remaining: " + getActiveThreads(checkThreads)); mixed.wait(3000); } checkKeyMaps.add(checkResults); } checkThreads = null; } String redirect = null; { synchronized (fecutils.getClass()) { try { redirect = fecutils.FECMakeMetadata(segmentHeaders, segmentKeyMaps, checkKeyMaps, "Frost"); } catch (Exception e) { System.out.println("putFECSplitFile NOT GOOD " + e.toString()); } } String[] sortedRedirect = redirect.split("\n"); for (int z = 0; z < sortedRedirect.length; z++) System.out.println(sortedRedirect[z]); int sortStart = -1; int sortEnd = -1; for (int line = 0; line < sortedRedirect.length; line++) { if (sortedRedirect[line].equals("Document")) { sortStart = line + 1; break; } } for (int line = sortStart; line < sortedRedirect.length; line++) { if (sortedRedirect[line].equals("End")) { sortEnd = line; break; } } System.out.println("sortStart " + sortStart + " sortEnd " + sortEnd); if (sortStart < sortEnd) Arrays.sort(sortedRedirect, sortStart, sortEnd); redirect = new String(); for (int line = 0; line < sortedRedirect.length; line++) redirect += sortedRedirect[line] + "\n"; System.out.println(redirect); } int tries = 0; String[] result = { "Error", "Error" }; while (!result[0].equals("Success") && !result[0].equals("KeyCollision") && tries < 8) { tries++; try { FcpConnection connection = new FcpConnection(frame1.frostSettings.getValue("nodeAddress"), frame1.frostSettings.getValue("nodePort")); output = connection.putKeyFromFile(uri, null, redirect.getBytes(), htl, mode); } catch (FcpToolsException e) { if (DEBUG) System.out.println("FcpToolsException " + e); frame1.displayWarning(e.toString()); } catch (UnknownHostException e) { if (DEBUG) System.out.println("UnknownHostException"); frame1.displayWarning(e.toString()); } catch (IOException e) { if (DEBUG) System.out.println("IOException"); frame1.displayWarning(e.toString()); } result = result(output); mixed.wait(3000); if (DEBUG) System.out.println("*****" + result[0] + " " + result[1] + " "); } if ((result[0].equals("Success") || result[0].equals("KeyCollision")) && mode) { try { GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("GMT")); String dirdate = cal.get(Calendar.YEAR) + "."; dirdate += cal.get(Calendar.MONTH) + 1 + "."; dirdate += cal.get(Calendar.DATE); String fileSeparator = System.getProperty("file.separator"); String destination = frame1.keypool + board + fileSeparator + dirdate + fileSeparator; FcpConnection connection = new FcpConnection(frame1.frostSettings.getValue("nodeAddress"), frame1.frostSettings.getValue("nodePort")); String contentKey = result(connection.putKeyFromFile(uri, null, redirect.getBytes(), htl, false))[1]; String prefix = new String("freenet:"); if (contentKey.startsWith(prefix)) contentKey = contentKey.substring(prefix.length()); FileAccess.writeFile("Already uploaded today", destination + contentKey + ".lck"); } catch (Exception e) { } } return result; }
Code Sample 2:
private void addMaintainerScripts(TarOutputStream tar, PackageInfo info) throws IOException, ScriptDataTooLargeException { for (final MaintainerScript script : info.getMaintainerScripts().values()) { if (script.getSize() > Integer.MAX_VALUE) { throw new ScriptDataTooLargeException("The script data is too large for the tar file. script=[" + script.getType().getFilename() + "]."); } final TarEntry entry = standardEntry(script.getType().getFilename(), UnixStandardPermissions.EXECUTABLE_FILE_MODE, (int) script.getSize()); tar.putNextEntry(entry); IOUtils.copy(script.getStream(), tar); tar.closeEntry(); } } |
00
| 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:
private Datastream addManagedDatastreamVersion(Entry entry) throws StreamIOException, ObjectIntegrityException { Datastream ds = new DatastreamManagedContent(); setDSCommonProperties(ds, entry); ds.DSLocationType = "INTERNAL_ID"; ds.DSMIME = getDSMimeType(entry); IRI contentLocation = entry.getContentSrc(); if (contentLocation != null) { if (m_obj.isNew()) { ValidationUtility.validateURL(contentLocation.toString(), ds.DSControlGrp); } if (m_format.equals(ATOM_ZIP1_1)) { if (!contentLocation.isAbsolute() && !contentLocation.isPathAbsolute()) { File f = getContentSrcAsFile(contentLocation); contentLocation = new IRI(DatastreamManagedContent.TEMP_SCHEME + f.getAbsolutePath()); } } ds.DSLocation = contentLocation.toString(); ds.DSLocation = (DOTranslationUtility.normalizeDSLocationURLs(m_obj.getPid(), ds, m_transContext)).DSLocation; return ds; } try { File temp = File.createTempFile("binary-datastream", null); OutputStream out = new FileOutputStream(temp); if (MimeTypeHelper.isText(ds.DSMIME) || MimeTypeHelper.isXml(ds.DSMIME)) { IOUtils.copy(new StringReader(entry.getContent()), out, m_encoding); } else { IOUtils.copy(entry.getContentStream(), out); } ds.DSLocation = DatastreamManagedContent.TEMP_SCHEME + temp.getAbsolutePath(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } return ds; } |
00
| Code Sample 1:
byte[] loadUrlByteArray(String szName, int offset, int size) { byte[] baBuffer = new byte[size]; try { URL url = new URL(waba.applet.Applet.currentApplet.getCodeBase(), szName); try { InputStream file = url.openStream(); if (size == 0) { int n = file.available(); baBuffer = new byte[n - offset]; } DataInputStream dataFile = new DataInputStream(file); try { dataFile.skip(offset); dataFile.readFully(baBuffer); } catch (EOFException e) { System.err.print(e.getMessage()); } file.close(); } catch (IOException e) { System.err.print(e.getMessage()); } } catch (MalformedURLException e) { System.err.print(e.getMessage()); } return baBuffer; }
Code Sample 2:
private String unzip(TupleInput input) { boolean zipped = input.readBoolean(); if (!zipped) { return input.readString(); } int len = input.readInt(); try { byte array[] = new byte[len]; input.read(array); GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(array)); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copyTo(in, out); in.close(); out.close(); return new String(out.toByteArray()); } catch (IOException err) { throw new RuntimeException(err); } } |
11
| Code Sample 1:
private void unzipResource(final String resourceName, final File targetDirectory) throws IOException { final URL resource = this.getClass().getResource(resourceName); assertNotNull("Expected '" + resourceName + "' not found.", resource); assertTrue(targetDirectory.isAbsolute()); FileUtils.deleteDirectory(targetDirectory); assertTrue(targetDirectory.mkdirs()); ZipInputStream in = null; boolean suppressExceptionOnClose = true; try { in = new ZipInputStream(resource.openStream()); ZipEntry e; while ((e = in.getNextEntry()) != null) { if (e.isDirectory()) { continue; } final File dest = new File(targetDirectory, e.getName()); assertTrue(dest.isAbsolute()); OutputStream out = null; try { out = FileUtils.openOutputStream(dest); IOUtils.copy(in, out); suppressExceptionOnClose = false; } finally { try { if (out != null) { out.close(); } suppressExceptionOnClose = true; } catch (final IOException ex) { if (!suppressExceptionOnClose) { throw ex; } } } in.closeEntry(); } suppressExceptionOnClose = false; } finally { try { if (in != null) { in.close(); } } catch (final IOException e) { if (!suppressExceptionOnClose) { throw e; } } } }
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 ResourceMigrator getCompletedResourceMigrator() { return new ResourceMigrator() { public void migrate(InputMetadata meta, InputStream inputStream, OutputCreator outputCreator) throws IOException, ResourceMigrationException { OutputStream outputStream = outputCreator.createOutputStream(); IOUtils.copy(inputStream, outputStream); } }; }
Code Sample 2:
public void testConvert() throws IOException, ConverterException { InputStreamReader reader = new InputStreamReader(new FileInputStream("test" + File.separator + "input" + File.separator + "A0851ohneex.dat"), CharsetUtil.forName("x-PICA")); FileWriter writer = new FileWriter("test" + File.separator + "output" + File.separator + "ddbInterToMarcxmlTest.out"); Converter c = context.getConverter("ddb-intern", "MARC21-xml", "x-PICA", "UTF-8"); ConversionParameters params = new ConversionParameters(); params.setSourceCharset("x-PICA"); params.setTargetCharset("UTF-8"); params.setAddCollectionHeader(true); params.setAddCollectionFooter(true); c.convert(reader, writer, params); } |
11
| Code Sample 1:
@Override public DownloadingItem download(Playlist playlist, String title, File folder, StopDownloadCondition condition, String uuid) throws IOException, StoreStateException { boolean firstIteration = true; Iterator<PlaylistEntry> entries = playlist.getEntries().iterator(); DownloadingItem prevItem = null; File[] previousDownloadedFiles = new File[0]; while (entries.hasNext()) { PlaylistEntry entry = entries.next(); DownloadingItem item = null; LOGGER.info("Downloading from '" + entry.getTitle() + "'"); InputStream is = RESTHelper.inputStream(entry.getUrl()); boolean stopped = false; File nfile = null; try { nfile = createFileStream(folder, entry); item = new DownloadingItem(nfile, uuid.toString(), title, entry, new Date(), getPID(), condition); if (previousDownloadedFiles.length > 0) { item.setPreviousFiles(previousDownloadedFiles); } addItem(item); if (prevItem != null) deletePrevItem(prevItem); prevItem = item; stopped = IOUtils.copyStreams(is, new FileOutputStream(nfile), condition); } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); radioScheduler.fireException(e); if (!condition.isStopped()) { File[] nfiles = new File[previousDownloadedFiles.length + 1]; System.arraycopy(previousDownloadedFiles, 0, nfiles, 0, previousDownloadedFiles.length); nfiles[nfiles.length - 1] = item.getFile(); previousDownloadedFiles = nfiles; if ((!entries.hasNext()) && (firstIteration)) { firstIteration = false; entries = playlist.getEntries().iterator(); } continue; } } if (stopped) { item.setState(ProcessStates.STOPPED); this.radioScheduler.fireStopDownloading(item); return item; } } return null; }
Code Sample 2:
public BasePolicy(String flaskPath) throws Exception { SWIGTYPE_p_p_policy p_p_pol = apol.new_policy_t_p_p(); if (!flaskPath.endsWith("/")) flaskPath += "/"; File tmpPolConf = File.createTempFile("tmpBasePolicy", ".conf"); BufferedWriter tmpPolFile = new BufferedWriter(new FileWriter(tmpPolConf)); BufferedReader secClassFile = new BufferedReader(new FileReader(flaskPath + "security_classes")); int bufSize = 1024; char[] buffer = new char[bufSize]; int read; while ((read = secClassFile.read(buffer)) > 0) { tmpPolFile.write(buffer, 0, read); } secClassFile.close(); BufferedReader sidsFile = new BufferedReader(new FileReader(flaskPath + "initial_sids")); while ((read = sidsFile.read(buffer)) > 0) { tmpPolFile.write(buffer, 0, read); } sidsFile.close(); BufferedReader axxVecFile = new BufferedReader(new FileReader(flaskPath + "access_vectors")); while ((read = axxVecFile.read(buffer)) > 0) { tmpPolFile.write(buffer, 0, read); } axxVecFile.close(); tmpPolFile.write("attribute ricka; \ntype rick_t; \nrole rick_r types rick_t; \nuser rick_u roles rick_r;\nsid kernel rick_u:rick_r:rick_t\nfs_use_xattr ext3 rick_u:rick_r:rick_t;\ngenfscon proc / rick_u:rick_r:rick_t\n"); tmpPolFile.flush(); tmpPolFile.close(); if (apol.open_policy(tmpPolConf.getAbsolutePath(), p_p_pol) == 0) { Policy = apol.policy_t_p_p_value(p_p_pol); if (Policy == null) { throw new Exception("Failed to allocate memory for policy_t struct."); } tmpPolConf.delete(); } else { throw new IOException("Failed to open/parse base policy file: " + tmpPolConf.getAbsolutePath()); } } |
11
| Code Sample 1:
public static String SHA1(String string) throws XLWrapException { MessageDigest md; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new XLWrapException("SHA-1 message digest is not available."); } byte[] data = new byte[40]; md.update(string.getBytes()); data = md.digest(); StringBuffer buf = new StringBuffer(); for (int i = 0; i < data.length; i++) { int halfbyte = (data[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 = data[i] & 0x0F; } while (two_halfs++ < 1); } return buf.toString(); }
Code Sample 2:
public static String getHash(String password, String salt) throws NoSuchAlgorithmException, UnsupportedEncodingException { logger.debug("Entering getHash with password = " + password + "\n and salt = " + salt); MessageDigest digest = MessageDigest.getInstance("SHA-512"); digest.reset(); digest.update(salt.getBytes()); byte[] input = digest.digest(password.getBytes("UTF-8")); String hashResult = String.valueOf(input); logger.debug("Exiting getHash with hasResult of " + hashResult); return hashResult; } |
00
| Code Sample 1:
public JspBaseTestCase(String name) { super(name); String propertyFile = "bugbase.properties"; Properties properties = new Properties(); setProperties(properties); try { URL url = this.getClass().getResource("/" + propertyFile); if (url != null) { InputStream is = url.openStream(); properties.load(is); is.close(); getLog().debug("Cactus LogService successfully instantiated."); getLog().debug("Log4J successfully instantiated."); } } catch (IOException e) { System.err.println("ERROR: cannot load " + propertyFile + "!"); } setDefault("openfuture.bugbase.test.host", "localhost:8080"); setDefault("openfuture.bugbase.test.context", "bugbase"); setDefault("openfuture.bugbase.test.userid", "admin"); setDefault("openfuture.bugbase.test.password", "bugbase"); setDefault("openfuture.bugbase.test.project", "BugBase Test"); }
Code Sample 2:
private void downloadFile(String name, URL url, File file) throws IOException { InputStream in = null; FileOutputStream out = null; try { URLConnection conn = url.openConnection(); conn.setConnectTimeout(10000); conn.setReadTimeout(10000); int expectedSize = conn.getContentLength(); progressPanel.downloadStarting(name, expectedSize == -1); int downloaded = 0; byte[] buf = new byte[1024]; int length; in = conn.getInputStream(); out = new FileOutputStream(file); while ((in != null) && ((length = in.read(buf)) != -1)) { downloaded += length; out.write(buf, 0, length); if (expectedSize != -1) progressPanel.downloadProgress((downloaded * 100) / expectedSize); } out.flush(); } finally { progressPanel.downloadFinished(); if (out != null) out.close(); if (in != null) in.close(); } } |
11
| Code Sample 1:
private static void readAndWriteFile(File source, File target) { try { FileInputStream in = new FileInputStream(source); FileOutputStream out = new FileOutputStream(target); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception e) { } }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } |
00
| Code Sample 1:
@Override public TDSScene loadScene(URL url) throws IOException, IncorrectFormatException, ParsingErrorException { boolean baseURLWasNull = setBaseURLFromModelURL(url); TDSScene scene = loadScene(url.openStream()); if (baseURLWasNull) { popBaseURL(); } return (scene); }
Code Sample 2:
public static String getFileContents(String path) { BufferedReader buffReader = null; InputStream stream = null; if (path.indexOf("://") != -1) { URL url = null; try { url = new URL(path); } catch (MalformedURLException e) { LOGGER.warn(String.format("Malformed URL: \"%s\"", path)); } if (url == null) { throw new DeveloperError(String.format("Cannot create URL from path: \"%s\"", path), new NullPointerException()); } try { String encoding = Characters.getDeclaredXMLEncoding(url); stream = url.openStream(); buffReader = new BufferedReader(new InputStreamReader(stream, encoding)); } catch (IOException e) { LOGGER.warn(String.format("I/O error trying to read \"%s\"", path)); } } else { File toRead = null; try { toRead = getExistingFile(path); } catch (FileNotFoundException e) { throw new UserError(new FileNotFoundException(path)); } if (toRead.isAbsolute()) { String parent = toRead.getParent(); try { workingDirectory.push(URLTools.createValidURL(parent)); } catch (FileNotFoundException e) { throw new DeveloperError(String.format("Created an invalid parent file: \"%s\".", parent), e); } } if (toRead.exists() && !toRead.isDirectory()) { String _path = toRead.getAbsolutePath(); try { String encoding = Characters.getDeclaredXMLEncoding(URLTools.createValidURL(_path)); stream = new FileInputStream(_path); buffReader = new BufferedReader(new InputStreamReader(stream, encoding)); } catch (IOException e) { LOGGER.warn(String.format("I/O error trying to read \"%s\"", _path)); return null; } } else { assert toRead.exists() : "getExistingFile() returned a non-existent file"; if (toRead.isDirectory()) { throw new UserError(new FileAlreadyExistsAsDirectoryException(toRead)); } } } StringBuilder result = new StringBuilder(); String line; if (buffReader != null && stream != null) { try { while ((line = buffReader.readLine()) != null) { result.append(line); } buffReader.close(); stream.close(); } catch (IOException e) { LOGGER.warn(String.format("I/O error trying to read \"%s\"", path)); return null; } } return result.toString(); } |
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 sourceName, String destName) throws IOException { File src = new File(sourceName); File dest = new File(destName); BufferedInputStream source = null; BufferedOutputStream destination = null; byte[] buffer; int bytes_read; long byteCount = 0; if (!src.exists()) throw new IOException("Source not found: " + src); if (!src.canRead()) throw new IOException("Source is unreadable: " + src); if (src.isFile()) { if (!dest.exists()) { File parentdir = parent(dest); if (!parentdir.exists()) parentdir.mkdir(); } else if (dest.isDirectory()) { if (src.isDirectory()) dest = new File(dest + File.separator + src); else dest = new File(dest + File.separator + src.getName()); } } else if (src.isDirectory()) { if (dest.isFile()) throw new IOException("Cannot copy directory " + src + " to file " + dest); if (!dest.exists()) dest.mkdir(); } if ((!dest.canWrite()) && (dest.exists())) throw new IOException("Destination is unwriteable: " + dest); if (src.isFile()) { try { source = new BufferedInputStream(new FileInputStream(src)); destination = new BufferedOutputStream(new FileOutputStream(dest)); buffer = new byte[4096]; byteCount = 0; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); byteCount = byteCount + bytes_read; } } finally { if (source != null) source.close(); if (destination != null) destination.close(); } } else if (src.isDirectory()) { String targetfile, target, targetdest; String[] files = src.list(); for (int i = 0; i < files.length; i++) { targetfile = files[i]; target = src + File.separator + targetfile; targetdest = dest + File.separator + targetfile; if ((new File(target)).isDirectory()) { copy(new File(target).getCanonicalPath(), new File(targetdest).getCanonicalPath()); } else { try { byteCount = 0; source = new BufferedInputStream(new FileInputStream(target)); destination = new BufferedOutputStream(new FileOutputStream(targetdest)); buffer = new byte[4096]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); byteCount = byteCount + bytes_read; } } finally { if (source != null) source.close(); if (destination != null) destination.close(); } } } } } |
11
| Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
private void setInlineXML(Entry entry, DatastreamXMLMetadata ds) throws UnsupportedEncodingException, StreamIOException { String content; if (m_obj.hasContentModel(Models.SERVICE_DEPLOYMENT_3_0) && (ds.DatastreamID.equals("SERVICE-PROFILE") || ds.DatastreamID.equals("WSDL"))) { content = DOTranslationUtility.normalizeInlineXML(new String(ds.xmlContent, m_encoding), m_transContext); } else { content = new String(ds.xmlContent, m_encoding); } if (m_format.equals(ATOM_ZIP1_1)) { String name = ds.DSVersionID + ".xml"; try { m_zout.putNextEntry(new ZipEntry(name)); InputStream is = new ByteArrayInputStream(content.getBytes(m_encoding)); IOUtils.copy(is, m_zout); m_zout.closeEntry(); is.close(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } IRI iri = new IRI(name); entry.setSummary(ds.DSVersionID); entry.setContent(iri, ds.DSMIME); } else { entry.setContent(content, ds.DSMIME); } } |
00
| Code Sample 1:
public String sendSMS(String host, String port, String username, String password, String from, String to, String text, String uhd, String charset, String coding, String validity, String deferred, String dlrmask, String dlrurl, String pid, String mclass, String mwi) throws SMSPushRequestException, Exception { StringBuffer res = new StringBuffer(); if (!Utils.checkNonEmptyStringAttribute(coding) || coding.equals("0")) text = Utils.convertTextForGSMEncodingURLEncoded(text); else if (coding.equals("1")) text = Utils.convertTextForUTFEncodingURLEncoded(text, "UTF-8"); else text = Utils.convertTextForUTFEncodingURLEncoded(text, "UCS-2"); String directives = "username=" + username; directives += "&password=" + password; directives += "&from=" + URLEncoder.encode(from, "UTF-8"); directives += "&to=" + to; directives += "&text=" + text; if (Utils.checkNonEmptyStringAttribute(uhd)) directives += "&uhd=" + uhd; if (Utils.checkNonEmptyStringAttribute(charset)) directives += "&charset=" + charset; if (Utils.checkNonEmptyStringAttribute(coding)) directives += "&coding=" + coding; if (Utils.checkNonEmptyStringAttribute(validity)) directives += "&validity=" + validity; if (Utils.checkNonEmptyStringAttribute(deferred)) directives += "&deferred=" + deferred; if (Utils.checkNonEmptyStringAttribute(dlrmask)) directives += "&dlrmask=" + dlrmask; if (Utils.checkNonEmptyStringAttribute(dlrurl)) directives += "&dlrurl=" + dlrurl; if (Utils.checkNonEmptyStringAttribute(pid)) directives += "&pid=" + pid; if (Utils.checkNonEmptyStringAttribute(mclass)) directives += "&mclass=" + mclass; if (Utils.checkNonEmptyStringAttribute(mwi)) directives += "&mwi=" + mwi; URL url = new URL("http://" + host + ":" + port + "/cgi-bin/sendsms?" + directives); URLConnection conn = url.openConnection(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String response; while ((response = rd.readLine()) != null) res.append(response); rd.close(); String resultCode = res.substring(0, res.indexOf(":")); if (!resultCode.equals(SMS_PUSH_RESPONSE_SUCCESS_CODE)) throw new SMSPushRequestException(resultCode); return res.toString(); }
Code Sample 2:
private static List<String> getContent(URL url) throws IOException { final HttpURLConnection http = (HttpURLConnection) url.openConnection(); try { http.connect(); final int code = http.getResponseCode(); if (code != 200) throw new IOException("IP Locator failed to get the location. Http Status code : " + code + " [" + url + "]"); return getContent(http); } finally { http.disconnect(); } } |
11
| Code Sample 1:
public static final long copyFile(final File srcFile, final File dstFile, final long cpySize) throws IOException { if ((null == srcFile) || (null == dstFile)) return (-1L); final File dstFolder = dstFile.getParentFile(); if ((!dstFolder.exists()) && (!dstFolder.mkdirs())) throw new IOException("Failed to created destination folder(s)"); FileChannel srcChannel = null, dstChannel = null; try { srcChannel = new FileInputStream(srcFile).getChannel(); dstChannel = new FileOutputStream(dstFile).getChannel(); final long srcLen = srcFile.length(), copyLen = dstChannel.transferFrom(srcChannel, 0, (cpySize < 0L) ? srcLen : cpySize); if ((cpySize < 0L) && (copyLen != srcLen)) return (-2L); return copyLen; } finally { FileUtil.closeAll(srcChannel, dstChannel); } }
Code Sample 2:
private void outputSignedOpenDocument(byte[] signatureData) throws IOException { LOG.debug("output signed open document"); OutputStream signedOdfOutputStream = getSignedOpenDocumentOutputStream(); if (null == signedOdfOutputStream) { throw new NullPointerException("signedOpenDocumentOutputStream is null"); } ZipOutputStream zipOutputStream = new ZipOutputStream(signedOdfOutputStream); ZipInputStream zipInputStream = new ZipInputStream(this.getOpenDocumentURL().openStream()); ZipEntry zipEntry; while (null != (zipEntry = zipInputStream.getNextEntry())) { if (!zipEntry.getName().equals(ODFUtil.SIGNATURE_FILE)) { zipOutputStream.putNextEntry(zipEntry); IOUtils.copy(zipInputStream, zipOutputStream); } } zipInputStream.close(); zipEntry = new ZipEntry(ODFUtil.SIGNATURE_FILE); zipOutputStream.putNextEntry(zipEntry); IOUtils.write(signatureData, zipOutputStream); zipOutputStream.close(); } |
11
| Code Sample 1:
public static boolean copy(File source, File target, boolean owrite) { if (!source.exists()) { log.error("Invalid input to copy: source " + source + "doesn't exist"); return false; } else if (!source.isFile()) { log.error("Invalid input to copy: source " + source + "isn't a file."); return false; } else if (target.exists() && !owrite) { log.error("Invalid input to copy: target " + target + " exists."); return false; } try { BufferedInputStream in = new BufferedInputStream(new FileInputStream(source)); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(target)); byte buffer[] = new byte[1024]; int read = -1; while ((read = in.read(buffer, 0, 1024)) != -1) out.write(buffer, 0, read); out.flush(); out.close(); in.close(); return true; } catch (IOException e) { log.error("Copy failed: ", e); return false; } }
Code Sample 2:
private String getResourceAsString(final String name) throws IOException { final InputStream is = JiBXTestCase.class.getResourceAsStream(name); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copyAndClose(is, baos); return baos.toString(); } |
00
| Code Sample 1:
public String getNextObjectId() throws SQLException { long nextserial = 1; String s0 = "lock table serials in exclusive mode"; String s1 = "SELECT nextserial FROM serials WHERE tablename = 'SERVER_OIDS'"; String s2; try { Statement stmt = dbconnect.connection.createStatement(); stmt.executeUpdate(s0); ResultSet rs = stmt.executeQuery(s1); if (!rs.next()) { s2 = "insert into serials (tablename,nextserial) values ('SERVER_OIDS', " + (nextserial) + ")"; } else { nextserial = rs.getLong(1) + 1; s2 = "update serials set nextserial=" + (nextserial) + " where tablename='SERVER_OIDS'"; } stmt.executeUpdate(s2); dbconnect.connection.commit(); rs.close(); stmt.close(); return "" + nextserial; } catch (SQLException e) { dbconnect.connection.rollback(); throw e; } }
Code Sample 2:
private File copyFromURL(URL url, String dir) throws IOException { File urlFile = new File(url.getFile()); File dest = new File(dir, urlFile.getName()); logger.log("Extracting " + urlFile.getName() + " to " + dir + "..."); FileOutputStream os = new FileOutputStream(dest); InputStream is = url.openStream(); byte data[] = new byte[4096]; int ct; while ((ct = is.read(data)) >= 0) os.write(data, 0, ct); is.close(); os.close(); logger.log("ok\n"); return dest; } |
00
| Code Sample 1:
public void excluir(Cliente cliente) throws Exception { Connection connection = criaConexao(false); String sql = "delete from cliente where cod_cliente = ?"; PreparedStatement stmt = null; try { stmt = connection.prepareStatement(sql); stmt.setLong(1, cliente.getId()); int retorno = stmt.executeUpdate(); if (retorno == 0) { connection.rollback(); throw new SQLException("Ocorreu um erro inesperado no momento de remover dados de cliente no banco!"); } connection.commit(); } catch (SQLException e) { connection.rollback(); throw e; } finally { try { stmt.close(); this.fechaConexao(); } catch (SQLException e) { throw e; } } }
Code Sample 2:
public void run() { if (currentNode == null || currentNode.equals("")) { JOptionPane.showMessageDialog(null, "Please select a genome to download first", "Error", JOptionPane.ERROR_MESSAGE); return; } String localFile = parameter.getTemporaryFilesPath() + currentNode; String remotePath = NCBI_FTP_PATH + currentPath; String remoteFile = remotePath + "/" + currentNode; try { ftp.connect(NCBI_FTP_HOST); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); JOptionPane.showMessageDialog(null, "FTP server refused connection", "Error", JOptionPane.ERROR_MESSAGE); } ftp.login("anonymous", "[email protected]"); inProgress = true; ftp.setFileType(FTPClient.BINARY_FILE_TYPE); long size = getFileSize(remotePath, currentNode); if (size == -1) throw new FileNotFoundException(); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(localFile)); BufferedInputStream in = new BufferedInputStream(ftp.retrieveFileStream(remoteFile), ftp.getBufferSize()); byte[] b = new byte[1024]; long bytesTransferred = 0; int tick = 0; int oldTick = 0; int len; while ((len = in.read(b)) != -1) { out.write(b, 0, len); bytesTransferred += 1024; if ((tick = new Long(bytesTransferred * 100 / size).intValue()) > oldTick) { progressBar.setValue(tick < 100 ? tick : 99); oldTick = tick; } } in.close(); out.close(); ftp.completePendingCommand(); progressBar.setValue(100); fileDownloaded = localFile; JOptionPane.showMessageDialog(null, "File successfully downloaded", "Congratulation!", JOptionPane.INFORMATION_MESSAGE); ftp.logout(); } catch (SocketException ex) { JOptionPane.showMessageDialog(null, "Error occurs while trying to connect server", "Error", JOptionPane.ERROR_MESSAGE); } catch (FileNotFoundException ex) { JOptionPane.showMessageDialog(null, "This file is not found on the server", "Error", JOptionPane.ERROR_MESSAGE); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Error occurs while fetching data", "Error", JOptionPane.ERROR_MESSAGE); } finally { inProgress = false; if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } } |
00
| Code Sample 1:
private void processBasicContent() { String[] packageNames = sourceCollector.getPackageNames(); for (int i = 0; i < packageNames.length; i++) { XdcSource[] sources = sourceCollector.getXdcSources(packageNames[i]); File dir = new File(outputDir, packageNames[i]); dir.mkdirs(); Set pkgDirs = new HashSet(); for (int j = 0; j < sources.length; j++) { XdcSource source = sources[j]; Properties patterns = source.getPatterns(); if (patterns != null) { tables.put("patterns", patterns); } pkgDirs.add(source.getFile().getParentFile()); DialectHandler dialectHandler = source.getDialectHandler(); Writer out = null; try { String sourceFilePath = source.getFile().getAbsolutePath(); source.setProcessingProperties(baseProperties, j > 0 ? sources[j - 1].getFileName() : null, j < sources.length - 1 ? sources[j + 1].getFileName() : null); String rootComment = XslUtils.transformToString(sourceFilePath, XSL_PKG + "/source-header.xsl", tables); source.setRootComment(rootComment); Document htmlDoc = XslUtils.transform(sourceFilePath, encoding, dialectHandler.getXslResourcePath(), tables); if (LOG.isInfoEnabled()) { LOG.info("Processing source file " + sourceFilePath); } out = IOUtils.getWriter(new File(dir, source.getFile().getName() + ".html"), docencoding); XmlUtils.printHtml(out, htmlDoc); if (sourceProcessor != null) { sourceProcessor.processSource(source, encoding, docencoding); } XdcSource.clearProcessingProperties(baseProperties); } catch (XmlException e) { LOG.error(e.getMessage(), e); } catch (IOException e) { LOG.error(e.getMessage(), e); } finally { if (out != null) { try { out.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } } for (Iterator iter = pkgDirs.iterator(); iter.hasNext(); ) { File docFilesDir = new File((File) iter.next(), "xdc-doc-files"); if (docFilesDir.exists() && docFilesDir.isDirectory()) { File targetDir = new File(dir, "xdc-doc-files"); targetDir.mkdirs(); try { IOUtils.copyTree(docFilesDir, targetDir); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } } }
Code Sample 2:
public static void updateTableData(Connection dest, TableMetaData tableMetaData) throws Exception { PreparedStatement ps = null; try { dest.setAutoCommit(false); String sql = "UPDATE " + tableMetaData.getSchema() + "." + tableMetaData.getTableName() + " SET "; for (String columnName : tableMetaData.getColumnsNames()) { sql += columnName + " = ? ,"; } sql = sql.substring(0, sql.length() - 1); sql += " WHERE "; for (String pkColumnName : tableMetaData.getPkColumns()) { sql += pkColumnName + " = ? AND "; } sql = sql.substring(0, sql.length() - 4); ps = dest.prepareStatement(sql); for (Row r : tableMetaData.getData()) { int param = 1; for (String columnName : tableMetaData.getColumnsNames()) { if (dest instanceof OracleConnection) { if (tableMetaData.getColumnsTypes().get(columnName).equalsIgnoreCase("BLOB")) { BLOB blob = new BLOB((OracleConnection) dest, (byte[]) r.getRowData().get(columnName)); ((OraclePreparedStatement) ps).setBLOB(param, blob); } else if (tableMetaData.getColumnsTypes().get(columnName).equalsIgnoreCase("CLOB")) { ((OraclePreparedStatement) ps).setStringForClob(param, (String) r.getRowData().get(columnName)); } else if (tableMetaData.getColumnsTypes().get(columnName).equalsIgnoreCase("LONG")) { ps.setBytes(param, (byte[]) r.getRowData().get(columnName)); } } else { ps.setObject(param, r.getRowData().get(columnName)); } param++; } for (String pkColumnName : tableMetaData.getPkColumns()) { ps.setObject(param, r.getRowData().get(pkColumnName)); param++; } if (ps.executeUpdate() != 1) { dest.rollback(); throw new Exception(); } ps.clearParameters(); } dest.commit(); dest.setAutoCommit(true); } finally { if (ps != null) ps.close(); } } |
00
| Code Sample 1:
public void imagesParserAssesmentItem(int file, int currentquestion, Resource resTemp) { NodeList nl = null; Node n = null; NamedNodeMap nnp = null; Node nsrc = null; URL url = null; String sFilename = ""; String sNewPath = ""; int index; String sOldPath = ""; try { if (file == 1) { nl = doc.getElementsByTagName("img"); } else { nl = doc_[currentquestion].getElementsByTagName("img"); } for (int i = 0; i < nl.getLength(); i++) { n = nl.item(i); nnp = n.getAttributes(); nsrc = nnp.getNamedItem("src"); String sTemp = nsrc.getTextContent(); url = new URL("file", "localhost", sTemp); sOldPath = url.getPath(); sOldPath = sOldPath.replace('/', File.separatorChar); int indexFirstSlash = sOldPath.indexOf(File.separatorChar); String sSourcePath = sOldPath.substring(indexFirstSlash + 1); index = sOldPath.lastIndexOf(File.separatorChar); sFilename = sOldPath.substring(index + 1); sNewPath = this.sTempLocation + sFilename; FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(sSourcePath).getChannel(); out = new FileOutputStream(sNewPath).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } if (file == 1) { sXml = sXml.replace(nsrc.getTextContent(), sFilename); } else { sXml_[currentquestion] = sXml_[currentquestion].replace(nsrc.getTextContent(), sFilename); } lsImages.add(sFilename); resTemp.addFile(sFilename); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
protected int getResponseCode(String address) throws Exception { URL url = new URL(address); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setUseCaches(false); try { con.connect(); return con.getResponseCode(); } finally { con.disconnect(); } } |
11
| Code Sample 1:
@SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { PositionParser pp; Database.init("XIDResult"); pp = new PositionParser("01:33:50.904+30:39:35.79"); String url = "http://simbad.u-strasbg.fr/simbad/sim-script?submit=submit+script&script="; String script = "format object \"%IDLIST[%-30*]|-%COO(A)|%COO(D)|%OTYPELIST(S)\"\n"; String tmp = ""; script += pp.getPosition() + " radius=1m"; url += URLEncoder.encode(script, "ISO-8859-1"); URL simurl = new URL(url); BufferedReader in = new BufferedReader(new InputStreamReader(simurl.openStream())); String boeuf; boolean data_found = false; JSONObject retour = new JSONObject(); JSONArray dataarray = new JSONArray(); JSONArray colarray = new JSONArray(); JSONObject jsloc = new JSONObject(); jsloc.put("sTitle", "ID"); colarray.add(jsloc); jsloc = new JSONObject(); jsloc.put("sTitle", "Position"); colarray.add(jsloc); jsloc = new JSONObject(); jsloc.put("sTitle", "Type"); colarray.add(jsloc); retour.put("aoColumns", colarray); int datasize = 0; while ((boeuf = in.readLine()) != null) { if (data_found) { String[] fields = boeuf.trim().split("\\|", -1); int pos = fields.length - 1; if (pos >= 3) { String type = fields[pos]; pos--; String dec = fields[pos]; pos--; String ra = fields[pos]; String id = ""; for (int i = 0; i < pos; i++) { id += fields[i]; if (i < (pos - 1)) { id += "|"; } } if (id.length() <= 30) { JSONArray darray = new JSONArray(); darray.add(id.trim()); darray.add(ra + " " + dec); darray.add(type.trim()); dataarray.add(darray); datasize++; } } } else if (boeuf.startsWith("::data")) { data_found = true; } } retour.put("aaData", dataarray); retour.put("iTotalRecords", datasize); retour.put("iTotalDisplayRecords", datasize); System.out.println(retour.toJSONString()); in.close(); }
Code Sample 2:
protected InputStream callApiGet(String apiUrl, int expected) { try { URL url = new URL(apiUrl); HttpURLConnection request = (HttpURLConnection) url.openConnection(); if (ApplicationConstants.CONNECT_TIMEOUT > -1) { request.setConnectTimeout(ApplicationConstants.CONNECT_TIMEOUT); } if (ApplicationConstants.READ_TIMEOUT > -1) { request.setReadTimeout(ApplicationConstants.READ_TIMEOUT); } for (String headerName : requestHeaders.keySet()) { request.setRequestProperty(headerName, requestHeaders.get(headerName)); } request.connect(); if (request.getResponseCode() != expected) { throw new BingMapsException(convertStreamToString(request.getErrorStream())); } else { return getWrappedInputStream(request.getInputStream(), GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding())); } } catch (IOException e) { throw new BingMapsException(e); } } |
00
| Code Sample 1:
public static HttpResponse query(DefaultHttpClient httpclient, Request request, Proxy proxy, Log log) throws ClientProtocolException, IOException, MojoExecutionException { log.debug("preparing " + request); if (proxy != null) { log.info("setting up " + proxy + " for request " + request); proxy.prepare(httpclient); } HttpRequestBase httpRequest = request.buildHttpRequestBase(httpclient, log); HttpHost targetHost = request.buildHttpHost(log); log.debug("HTTP " + request.getMethod() + " url=" + request.getFinalUrl()); long responseTime = System.currentTimeMillis(); HttpResponse response = httpclient.execute(targetHost, httpRequest); log.debug("received response (time=" + (System.currentTimeMillis() - responseTime) + "ms) for request [" + "HTTP " + request.getMethod() + " url=" + request.getFinalUrl() + "]"); return response; }
Code Sample 2:
public Parameters getParameters(HttpExchange http) throws IOException { ParametersImpl params = new ParametersImpl(); String query = null; if (http.getRequestMethod().equalsIgnoreCase("GET")) { query = http.getRequestURI().getRawQuery(); } else if (http.getRequestMethod().equalsIgnoreCase("POST")) { InputStream in = new MaxInputStream(http.getRequestBody()); if (in != null) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); IOUtils.copyTo(in, bytes); query = new String(bytes.toByteArray()); in.close(); } } else { throw new IOException("Method not supported " + http.getRequestMethod()); } if (query != null) { for (String s : query.split("[&]")) { s = s.replace('+', ' '); int eq = s.indexOf('='); if (eq > 0) { params.add(URLDecoder.decode(s.substring(0, eq), "UTF-8"), URLDecoder.decode(s.substring(eq + 1), "UTF-8")); } } } return params; } |
11
| Code Sample 1:
public boolean executeUpdate(String strSql, HashMap<Integer, Object> prams) throws SQLException, ClassNotFoundException { getConnection(); boolean flag = false; try { pstmt = con.prepareStatement(strSql); setParamet(pstmt, prams); logger.info("###############::执行SQL语句操作(更新数据 有参数):" + strSql); if (0 < pstmt.executeUpdate()) { close_DB_Object(); flag = true; con.commit(); } } catch (SQLException ex) { logger.info("###############Error DBManager Line121::执行SQL语句操作(更新数据 无参数):" + strSql + "失败!"); flag = false; con.rollback(); throw ex; } catch (ClassNotFoundException ex) { logger.info("###############Error DBManager Line152::执行SQL语句操作(更新数据 无参数):" + strSql + "失败! 参数设置类型错误!"); con.rollback(); throw ex; } return flag; }
Code Sample 2:
@Override public void run() { Shell currentShell = Display.getCurrent().getActiveShell(); if (DMManager.getInstance().getOntology() == null) return; DataRecordSet data = DMManager.getInstance().getOntology().getDataView().dataset(); InputDialog input = new InputDialog(currentShell, Resources.I18N.getString("vikamine.dtp.title"), Resources.I18N.getString("vikamine.dtp.export.tablename"), data.getRelationName(), null); input.open(); String tablename = input.getValue(); if (tablename == null) return; super.getProfile().connect(); IManagedConnection mc = super.getProfile().getManagedConnection("java.sql.Connection"); java.sql.Connection sql = (java.sql.Connection) mc.getConnection().getRawConnection(); try { sql.setAutoCommit(false); DatabaseMetaData dbmd = sql.getMetaData(); ResultSet tables = dbmd.getTables(null, null, tablename, new String[] { "TABLE" }); if (tables.next()) { if (!MessageDialog.openConfirm(currentShell, Resources.I18N.getString("vikamine.dtp.title"), Resources.I18N.getString("vikamine.dtp.export.overwriteTable"))) return; Statement statement = sql.createStatement(); statement.executeUpdate("DROP TABLE " + tablename); statement.close(); } String createTableQuery = null; for (int i = 0; i < data.getNumAttributes(); i++) { if (DMManager.getInstance().getOntology().isIDAttribute(data.getAttribute(i))) continue; if (createTableQuery == null) createTableQuery = ""; else createTableQuery += ","; createTableQuery += getColumnDefinition(data.getAttribute(i)); } Statement statement = sql.createStatement(); statement.executeUpdate("CREATE TABLE " + tablename + "(" + createTableQuery + ")"); statement.close(); exportRecordSet(data, sql, tablename); sql.commit(); sql.setAutoCommit(true); MessageDialog.openInformation(currentShell, Resources.I18N.getString("vikamine.dtp.title"), Resources.I18N.getString("vikamine.dtp.export.successful")); } catch (SQLException e) { try { sql.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } MessageDialog.openError(currentShell, Resources.I18N.getString("vikamine.dtp.title"), Resources.I18N.getString("vikamine.dtp.export.failed")); e.printStackTrace(); } } |
00
| Code Sample 1:
public int procesar() { int mas = 0; String uriOntologia = "", source = "", uri = ""; String fichOrigenHTML = "", fichOrigenLN = ""; String ficheroOutOWL = ""; md5 firma = null; StringTokenV2 entra = null, entra2 = null, entra3 = null; FileInputStream lengNat = null; BufferedInputStream lengNat2 = null; DataInputStream entradaLenguajeNatural = null; FileWriter salOWL = null; BufferedWriter salOWL2 = null; PrintWriter salidaOWL = null; String sujeto = "", verbo = "", CD = "", CI = "", fraseOrigen = ""; StringTokenV2 token2; boolean bandera = false; OntClass c = null; OntClass cBak = null; String claseTrabajo = ""; String nombreClase = "", nombrePropiedad = "", variasPalabras = ""; int incre = 0, emergencia = 0; String lineaSalida = ""; String[] ontologia = new String[5]; ontologia[0] = "http://www.criado.info/owl/vertebrados_es.owl#"; ontologia[1] = "http://www.w3.org/2001/sw/WebOnt/guide-src/wine#"; ontologia[2] = "http://www.co-ode.org/ontologies/pizza/2005/10/18/pizza.owl#"; ontologia[3] = "http://www.w3.org/2001/sw/WebOnt/guide-src/food#"; ontologia[4] = "http://www.daml.org/2001/01/gedcom/gedcom#"; String[] ontologiaSource = new String[5]; ontologiaSource[0] = this.directorioMapeo + "\\" + "mapeo_vertebrados_es.xml"; ontologiaSource[1] = this.directorioMapeo + "\\" + "mapeo_wine_es.xml"; ontologiaSource[2] = this.directorioMapeo + "\\" + "mapeo_pizza_es.xml"; ontologiaSource[3] = this.directorioMapeo + "\\" + "mapeo_food_es.xml"; ontologiaSource[4] = this.directorioMapeo + "\\" + "mapeo_parentesco_es.xml"; mapeoIdiomas clasesOntologias; try { if ((entrada = entradaFichero.readLine()) != null) { if (entrada.trim().length() > 10) { entrada2 = new StringTokenV2(entrada.trim(), "\""); if (entrada2.isIncluidaSubcadena("<fichero ontologia=")) { ontologiaOrigen = entrada2.getToken(2); fichOrigenHTML = entrada2.getToken(4); fichOrigenLN = entrada2.getToken(6); if (ontologiaOrigen.equals("VERTEBRADOS")) { source = ontologiaSource[0]; uriOntologia = ontologia[0]; } if (ontologiaOrigen.equals("WINE")) { source = ontologiaSource[1]; uriOntologia = ontologia[1]; } if (ontologiaOrigen.equals("PIZZA")) { source = ontologiaSource[2]; uriOntologia = ontologia[2]; } if (ontologiaOrigen.equals("FOOD")) { source = ontologiaSource[3]; uriOntologia = ontologia[3]; } if (ontologiaOrigen.equals("PARENTESCOS")) { source = ontologiaSource[4]; uriOntologia = ontologia[4]; } firma = new md5(uriOntologia, false); clasesOntologias = new mapeoIdiomas(source); uri = ""; ficheroOutOWL = ""; entra2 = new StringTokenV2(fichOrigenHTML, "\\"); int numToken = entra2.getNumeroTokenTotales(); entra = new StringTokenV2(fichOrigenHTML, " "); if (entra.isIncluidaSubcadena(directorioLocal)) { entra = new StringTokenV2(entra.getQuitar(directorioLocal) + "", " "); uri = entra.getCambiar("\\", "/"); uri = entra.getQuitar(entra2.getToken(numToken)) + ""; entra3 = new StringTokenV2(entra2.getToken(numToken), "."); ficheroOutOWL = entra3.getToken(1) + "_" + firma.toString() + ".owl"; uri = urlPatron + uri + ficheroOutOWL; } entra3 = new StringTokenV2(fichOrigenHTML, "."); ficheroOutOWL = entra3.getToken(1) + "_" + firma.toString() + ".owl"; lineaSalida = "<vistasemantica origen=\"" + fichOrigenLN + "\" destino=\"" + uri + "\" />"; lengNat = new FileInputStream(fichOrigenLN); lengNat2 = new BufferedInputStream(lengNat); entradaLenguajeNatural = new DataInputStream(lengNat2); salOWL = new FileWriter(ficheroOutOWL); salOWL2 = new BufferedWriter(salOWL); salidaOWL = new PrintWriter(salOWL2); while ((entradaInstancias = entradaLenguajeNatural.readLine()) != null) { sujeto = ""; verbo = ""; CD = ""; CI = ""; fraseOrigen = ""; if (entradaInstancias.trim().length() > 10) { entrada2 = new StringTokenV2(entradaInstancias.trim(), "\""); if (entrada2.isIncluidaSubcadena("<oracion sujeto=")) { sujeto = entrada2.getToken(2).trim(); verbo = entrada2.getToken(4).trim(); CD = entrada2.getToken(6).trim(); CI = entrada2.getToken(8).trim(); fraseOrigen = entrada2.getToken(10).trim(); if (sujeto.length() > 0 & verbo.length() > 0 & CD.length() > 0) { bandera = false; c = null; cBak = null; nombreClase = clasesOntologias.getClaseInstancia(CD); if (nombreClase.length() > 0) { bandera = true; } if (bandera) { if (incre == 0) { salidaOWL.write(" <rdf:RDF " + "\n"); salidaOWL.write(" xmlns:j.0=\"" + uriOntologia + "\"" + "\n"); salidaOWL.write(" xmlns:protege=\"http://protege.stanford.edu/plugins/owl/protege#\"" + "\n"); salidaOWL.write(" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"" + "\n"); salidaOWL.write(" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema#\"" + "\n"); salidaOWL.write(" xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\"" + "\n"); salidaOWL.write(" xmlns:owl=\"http://www.w3.org/2002/07/owl#\" " + "\n"); salidaOWL.write(" xmlns=\"" + uri + "#\"" + "\n"); salidaOWL.write(" xml:base=\"" + uri + "\">" + "\n"); salidaOWL.write(" <owl:Ontology rdf:about=\"\">" + "\n"); salidaOWL.write(" <owl:imports rdf:resource=\"" + uriOntologia + "\"/>" + "\n"); salidaOWL.write(" </owl:Ontology>" + "\n"); salidaOWL.flush(); salida.write(lineaSalida + "\n"); salida.flush(); incre = 1; } salidaOWL.write(" <j.0:" + nombreClase + " rdf:ID=\"" + sujeto.toUpperCase() + "\"/>" + "\n"); salidaOWL.write(" <owl:AllDifferent>" + "\n"); salidaOWL.write(" <owl:distinctMembers rdf:parseType=\"Collection\">" + "\n"); salidaOWL.write(" <" + nombreClase + " rdf:about=\"#" + sujeto.toUpperCase() + "\"/>" + "\n"); salidaOWL.write(" </owl:distinctMembers>" + "\n"); salidaOWL.write(" </owl:AllDifferent>" + "\n"); salidaOWL.flush(); bandera = false; } } } } } salidaOWL.write(" </rdf:RDF>" + "\n" + "\n"); salidaOWL.write("<!-- Creado por [html2ws] http://www.luis.criado.org -->" + "\n"); salidaOWL.flush(); } } mas = 1; } else { salida.write("</listaVistasSemanticas>\n"); salida.flush(); salida.close(); bw2.close(); fw2.close(); salidaOWL.close(); entradaFichero.close(); ent2.close(); ent1.close(); mas = -1; } } catch (Exception e) { mas = -2; salida.write("No se encuentra: " + fichOrigen + "\n"); salida.flush(); } return mas; }
Code Sample 2:
@Override public Directory directory() { HttpURLConnection urlConnection = null; InputStream in = null; try { URL url = new URL(DIRECTORY_URL); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("Accept-Encoding", "gzip, deflate"); String encoding = urlConnection.getContentEncoding(); if ("gzip".equalsIgnoreCase(encoding)) { in = new GZIPInputStream(urlConnection.getInputStream()); } else if ("deflate".equalsIgnoreCase(encoding)) { in = new InflaterInputStream(urlConnection.getInputStream(), new Inflater(true)); } else { in = urlConnection.getInputStream(); } return persister.read(IcecastDirectory.class, in); } catch (Exception e) { throw new RuntimeException("Failed to get directory", e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (urlConnection != null) { urlConnection.disconnect(); } } } |
00
| Code Sample 1:
public static String hash(String str) { if (str == null || str.length() == 0) { throw new CaptureSecurityException("String to encript cannot be null or zero length"); } StringBuilder hexString = new StringBuilder(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] hash = md.digest(); for (byte element : hash) { if ((0xff & element) < 0x10) { hexString.append('0').append(Integer.toHexString((0xFF & element))); } else { hexString.append(Integer.toHexString(0xFF & element)); } } } catch (NoSuchAlgorithmException e) { throw new CaptureSecurityException(e); } return hexString.toString(); }
Code Sample 2:
public static JSONObject update(String name, String uid, double lat, double lon, boolean online) throws ClientProtocolException, IOException, JSONException { HttpClient client = new DefaultHttpClient(params); HttpPost post = new HttpPost(UPDATE_URI); List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("name", name)); parameters.add(new BasicNameValuePair("uid", uid)); parameters.add(new BasicNameValuePair("latitude", Double.toString(lat))); parameters.add(new BasicNameValuePair("longitude", Double.toString(lon))); parameters.add(new BasicNameValuePair("online", Boolean.toString(online))); post.setEntity(new UrlEncodedFormEntity(parameters, HTTP.UTF_8)); HttpResponse response = client.execute(post); if (response.getStatusLine().getStatusCode() == 200) { String res = EntityUtils.toString(response.getEntity()); return new JSONObject(res); } throw new IOException("bad http response:" + response.getStatusLine().getReasonPhrase()); } |
00
| Code Sample 1:
public void atualizarLivro(LivroBean livro) { PreparedStatement pstmt = null; String sql = "update livro " + "set " + "isbn = ?, " + "autor = ?, " + "editora = ?, " + "edicao = ?, " + "titulo = ? " + "where " + "isbn = ?"; try { pstmt = connection.prepareStatement(sql); pstmt.setString(1, livro.getISBN()); pstmt.setString(2, livro.getAutor()); pstmt.setString(3, livro.getEditora()); pstmt.setString(4, livro.getEdicao()); pstmt.setString(5, livro.getTitulo()); pstmt.executeUpdate(); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (SQLException ex1) { throw new RuntimeException("Erro ao tentar atualizar livro.", ex1); } throw new RuntimeException("Erro ao tentar atualizar livro.", ex); } finally { try { if (pstmt != null) { pstmt.close(); } if (connection != null) { connection.close(); } } catch (SQLException ex) { throw new RuntimeException("Erro ao tentar atualizar livro.", ex); } } }
Code Sample 2:
private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } |
00
| Code Sample 1:
public XmldbURI createFile(String newName, InputStream is, Long length, String contentType) throws IOException, PermissionDeniedException, CollectionDoesNotExistException { if (LOG.isDebugEnabled()) LOG.debug("Create '" + newName + "' in '" + xmldbUri + "'"); XmldbURI newNameUri = XmldbURI.create(newName); MimeType mime = MimeTable.getInstance().getContentTypeFor(newName); if (mime == null) { mime = MimeType.BINARY_TYPE; } DBBroker broker = null; Collection collection = null; BufferedInputStream bis = new BufferedInputStream(is); VirtualTempFile vtf = new VirtualTempFile(); BufferedOutputStream bos = new BufferedOutputStream(vtf); IOUtils.copy(bis, bos); bis.close(); bos.close(); vtf.close(); if (mime.isXMLType() && vtf.length() == 0L) { if (LOG.isDebugEnabled()) LOG.debug("Creating dummy XML file for null resource lock '" + newNameUri + "'"); vtf = new VirtualTempFile(); IOUtils.write("<null_resource/>", vtf); vtf.close(); } TransactionManager transact = brokerPool.getTransactionManager(); Txn txn = transact.beginTransaction(); try { broker = brokerPool.get(subject); collection = broker.openCollection(xmldbUri, Lock.WRITE_LOCK); if (collection == null) { LOG.debug("Collection " + xmldbUri + " does not exist"); transact.abort(txn); throw new CollectionDoesNotExistException(xmldbUri + ""); } if (mime.isXMLType()) { if (LOG.isDebugEnabled()) LOG.debug("Inserting XML document '" + mime.getName() + "'"); VirtualTempFileInputSource vtfis = new VirtualTempFileInputSource(vtf); IndexInfo info = collection.validateXMLResource(txn, broker, newNameUri, vtfis); DocumentImpl doc = info.getDocument(); doc.getMetadata().setMimeType(mime.getName()); collection.store(txn, broker, info, vtfis, false); } else { if (LOG.isDebugEnabled()) LOG.debug("Inserting BINARY document '" + mime.getName() + "'"); InputStream fis = vtf.getByteStream(); bis = new BufferedInputStream(fis); DocumentImpl doc = collection.addBinaryResource(txn, broker, newNameUri, bis, mime.getName(), length.longValue()); bis.close(); } transact.commit(txn); if (LOG.isDebugEnabled()) LOG.debug("Document created sucessfully"); } catch (EXistException e) { LOG.error(e); transact.abort(txn); throw new IOException(e); } catch (TriggerException e) { LOG.error(e); transact.abort(txn); throw new IOException(e); } catch (SAXException e) { LOG.error(e); transact.abort(txn); throw new IOException(e); } catch (LockException e) { LOG.error(e); transact.abort(txn); throw new PermissionDeniedException(xmldbUri + ""); } catch (IOException e) { LOG.error(e); transact.abort(txn); throw e; } catch (PermissionDeniedException e) { LOG.error(e); transact.abort(txn); throw e; } finally { if (vtf != null) { vtf.delete(); } if (collection != null) { collection.release(Lock.WRITE_LOCK); } brokerPool.release(broker); if (LOG.isDebugEnabled()) LOG.debug("Finished creation"); } XmldbURI newResource = xmldbUri.append(newName); return newResource; }
Code Sample 2:
public RTUser getUserInfo(final String username) { getSession(); Map<String, String> attributes = Collections.emptyMap(); final HttpGet get = new HttpGet(m_baseURL + "/REST/1.0/user/" + username); try { final HttpResponse response = getClient().execute(get); int responseCode = response.getStatusLine().getStatusCode(); if (responseCode != HttpStatus.SC_OK) { throw new RequestTrackerException("Received a non-200 response code from the server: " + responseCode); } else { if (response.getEntity() != null) { attributes = parseResponseStream(response.getEntity().getContent()); } } } catch (final Exception e) { LogUtils.errorf(this, e, "An exception occurred while getting user info for " + username); return null; } final String id = attributes.get("id"); final String realname = attributes.get("realname"); final String email = attributes.get("emailaddress"); if (id == null || "".equals(id)) { LogUtils.errorf(this, "Unable to retrieve ID from user info."); return null; } return new RTUser(Long.parseLong(id.replace("user/", "")), username, realname, email); } |
11
| Code Sample 1:
private void copyFile(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
Code Sample 2:
public static void copyFileStreams(File fromFile, File toFile) throws IOException { if (!fromFile.exists()) { return; } FileInputStream fis = new FileInputStream(fromFile); FileOutputStream fos = new FileOutputStream(toFile); int read = 0; byte[] buf = new byte[1024]; while (-1 != read) { read = fis.read(buf); if (read >= 0) { fos.write(buf, 0, read); } } fos.close(); fis.close(); } |
11
| Code Sample 1:
public static void main(String[] args) throws NoSuchAlgorithmException { String password = "root"; MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(password.getBytes()); final byte[] digest = messageDigest.digest(); final StringBuilder buf = new StringBuilder(digest.length * 2); for (int j = 0; j < digest.length; j++) { buf.append(HEX_DIGITS[(digest[j] >> 4) & 0x0f]); buf.append(HEX_DIGITS[digest[j] & 0x0f]); } String pwd = buf.toString(); System.out.println(pwd); }
Code Sample 2:
public Blowfish(String password) { MessageDigest digest = null; try { digest = MessageDigest.getInstance("SHA1"); digest.update(password.getBytes()); } catch (Exception e) { Log.error(e.getMessage(), e); } m_bfish = new BlowfishCBC(digest.digest(), 0); digest.reset(); } |
00
| Code Sample 1:
@Test public void parse() throws Exception { URL url = new URL("http://www.oki.com"); HtmlParser parser = new HtmlParser(); byte[] bytes = FileUtilities.getContents(url.openStream(), Integer.MAX_VALUE).toByteArray(); OutputStream parsed = parser.parse(new ByteArrayInputStream(bytes), new ByteArrayOutputStream()); assertTrue(parsed.toString().indexOf("Oki") > -1); }
Code Sample 2:
public void readData() throws IOException { i = 0; j = 0; URL url = getClass().getResource("resources/Chrom_623_620.dat"); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); s = br.readLine(); StringTokenizer st = new StringTokenizer(s); s = br.readLine(); st = new StringTokenizer(s); chrom_x[i][j] = Double.parseDouble(st.nextToken()); temp_prev = chrom_x[i][j]; chrom_y[i][j] = Double.parseDouble(st.nextToken()); gridmin = chrom_x[i][j]; gridmax = chrom_x[i][j]; sext1[i][j] = Double.parseDouble(st.nextToken()); sext2[i][j] = Double.parseDouble(st.nextToken()); sext3[i][j] = Double.parseDouble(st.nextToken()); sext4[i][j] = Double.parseDouble(st.nextToken()); j++; while ((s = br.readLine()) != null) { st = new StringTokenizer(s); temp_new = Double.parseDouble(st.nextToken()); if (temp_new != temp_prev) { temp_prev = temp_new; i++; j = 0; } chrom_x[i][j] = temp_new; chrom_y[i][j] = Double.parseDouble(st.nextToken()); sext1[i][j] = Double.parseDouble(st.nextToken()); sext2[i][j] = Double.parseDouble(st.nextToken()); sext3[i][j] = Double.parseDouble(st.nextToken()); sext4[i][j] = Double.parseDouble(st.nextToken()); imax = i; jmax = j; j++; if (chrom_x[i][j] <= gridmin) gridmin = chrom_x[i][j]; if (chrom_x[i][j] >= gridmax) gridmax = chrom_x[i][j]; } } |
11
| Code Sample 1:
private static void unpackEntry(File destinationFile, ZipInputStream zin, ZipEntry entry) throws Exception { if (!entry.isDirectory()) { createFolders(destinationFile.getParentFile()); FileOutputStream fis = new FileOutputStream(destinationFile); try { IOUtils.copy(zin, fis); } finally { zin.closeEntry(); fis.close(); } } else { createFolders(destinationFile); } }
Code Sample 2:
public void download(RequestContext ctx) throws IOException { if (ctx.isRobot()) { ctx.forbidden(); return; } long id = ctx.id(); File bean = File.INSTANCE.Get(id); if (bean == null) { ctx.not_found(); return; } String f_ident = ctx.param("fn", ""); if (id >= 100 && !StringUtils.equals(f_ident, bean.getIdent())) { ctx.not_found(); return; } if (bean.IsLoginRequired() && ctx.user() == null) { StringBuilder login = new StringBuilder(LinkTool.home("home/login?goto_page=")); ctx.redirect(login.toString()); return; } FileInputStream fis = null; try { java.io.File file = StorageService.FILES.readFile(bean.getPath()); fis = new FileInputStream(file); ctx.response().setContentLength((int) file.length()); String ext = FilenameUtils.getExtension(bean.getPath()); String mine_type = Multimedia.mime_types.get(ext); if (mine_type != null) ctx.response().setContentType(mine_type); String ua = ctx.header("user-agent"); if (ua != null && ua.indexOf("Firefox") >= 0) ctx.header("Content-Disposition", "attachment; filename*=\"utf8''" + LinkTool.encode_url(bean.getName()) + "." + ext + "\""); else ctx.header("Content-Disposition", "attachment; filename=" + LinkTool.encode_url(bean.getName() + "." + ext)); IOUtils.copy(fis, ctx.response().getOutputStream()); bean.IncDownloadCount(1); } finally { IOUtils.closeQuietly(fis); } } |
11
| Code Sample 1:
public String download(String urlStr) { StringBuffer sb = new StringBuffer(); String line = null; BufferedReader buffer = null; try { url = new URL(urlStr); HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); System.out.println(buffer); while ((line = buffer.readLine()) != null) { sb.append(line); } } catch (Exception e) { e.printStackTrace(); } finally { try { buffer.close(); } catch (Exception e) { e.printStackTrace(); } } return sb.toString(); }
Code Sample 2:
@Test public void unacceptableMimeTypeTest() throws IOException { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://localhost:8080/alfresco/sword/deposit/company_home"); File file = new File("/Library/Application Support/Apple/iChat Icons/Planets/Mars.gif"); FileEntity entity = new FileEntity(file, "text/xml"); entity.setChunked(true); httppost.setEntity(entity); Date date = new Date(); Long time = date.getTime(); httppost.addHeader("content-disposition", "filename=x" + time + "x.gif"); System.out.println("Executing request...." + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { InputStream is = resEntity.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = ""; while ((line = br.readLine()) != null) { if (!line.isEmpty()) System.out.println(line); } } if (resEntity != null) { resEntity.consumeContent(); } httpclient.getConnectionManager().shutdown(); } |
00
| Code Sample 1:
protected StringBuffer readURL(java.net.URL url) throws IOException { StringBuffer result = new StringBuffer(4096); InputStreamReader reader = new InputStreamReader(url.openStream()); for (; ; ) { char portion[] = new char[4096]; int numRead = reader.read(portion, 0, portion.length); if (numRead < 0) break; result.append(portion, 0, numRead); } dout("Read " + result.length() + " bytes."); return result; }
Code Sample 2:
@Override public void close() throws IOException { super.close(); byte[] signatureData = toByteArray(); ZipOutputStream zipOutputStream = new ZipOutputStream(this.targetOutputStream); ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(this.originalZipFile)); ZipEntry zipEntry; while (null != (zipEntry = zipInputStream.getNextEntry())) { if (!zipEntry.getName().equals(ODFUtil.SIGNATURE_FILE)) { ZipEntry newZipEntry = new ZipEntry(zipEntry.getName()); zipOutputStream.putNextEntry(newZipEntry); LOG.debug("copying " + zipEntry.getName()); IOUtils.copy(zipInputStream, zipOutputStream); } } zipInputStream.close(); zipEntry = new ZipEntry(ODFUtil.SIGNATURE_FILE); LOG.debug("writing " + zipEntry.getName()); zipOutputStream.putNextEntry(zipEntry); IOUtils.write(signatureData, zipOutputStream); zipOutputStream.close(); } |
00
| Code Sample 1:
public static String descripta(String senha) throws GCIException { LOGGER.debug(INICIANDO_METODO + "descripta(String)"); try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(senha.getBytes()); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(digest.digest()); } catch (NoSuchAlgorithmException e) { LOGGER.fatal(e.getMessage(), e); throw new GCIException(e); } finally { LOGGER.debug(FINALIZANDO_METODO + "descripta(String)"); } }
Code Sample 2:
public static void copy(String from_name, String to_name) throws IOException { File from_file = new File(from_name); File to_file = new File(to_name); if (!from_file.exists()) abort("FileCopy: no such source file: " + from_name); if (!from_file.isFile()) abort("FileCopy: can't copy directory: " + from_name); if (!from_file.canRead()) abort("FileCopy: source file is unreadable: " + from_name); if (to_file.isDirectory()) to_file = new File(to_file, from_file.getName()); String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("FileCopy: destination directory doesn't exist: " + parent); if (dir.isFile()) abort("FileCopy: destination is not a directory: " + parent); if (!dir.canWrite()) abort("FileCopy: destination directory is unwriteable: " + parent); FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } |
00
| Code Sample 1:
public static String[] parseM3U(String strURL, Context c) { URL url; URLConnection urlConn = null; String TAG = "parseM3U"; Vector<String> radio = new Vector<String>(); final String filetoken = "http"; try { url = new URL(strURL); urlConn = url.openConnection(); Log.d(TAG, "Got data"); } catch (IOException ioe) { Log.e(TAG, "Could not connect to " + strURL); } try { DataInputStream in = new DataInputStream(urlConn.getInputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { String temp = strLine.toLowerCase(); Log.d(TAG, strLine); if (temp.startsWith(filetoken)) { radio.add(temp); Log.d(TAG, "Found audio " + temp); } } br.close(); in.close(); } catch (Exception e) { Log.e(TAG, "Trouble reading file: " + e.getMessage()); } String[] t = new String[0]; String[] r = null; if (radio.size() != 0) { r = (String[]) radio.toArray(t); Log.d(TAG, "Found total: " + String.valueOf(r.length)); } return r; }
Code Sample 2:
Object onSuccess() { this.mErrorExist = true; this.mErrorMdp = true; if (this.mNewMail.equals(mClient.getEmail()) || !this.mNewMail.equals(mClient.getEmail()) && !mClientManager.exists(this.mNewMail)) { this.mErrorExist = false; if (mNewMdp != null && mNewMdpConfirm != null) { if (this.mNewMdp.equals(this.mNewMdpConfirm)) { this.mErrorMdp = false; MessageDigest sha1Instance; try { sha1Instance = MessageDigest.getInstance("SHA1"); sha1Instance.reset(); sha1Instance.update(this.mNewMdp.getBytes()); byte[] digest = sha1Instance.digest(); BigInteger bigInt = new BigInteger(1, digest); String vHashPassword = bigInt.toString(16); mClient.setMdp(vHashPassword); } catch (NoSuchAlgorithmException e) { mLogger.error(e.getMessage(), e); } } } else { this.mErrorMdp = false; } if (!this.mErrorMdp) { mClient.setAdresse(this.mNewAdresse); mClient.setEmail(this.mNewMail); mClient.setNom(this.mNewNom); mClient.setPrenom((this.mNewPrenom != null ? this.mNewPrenom : "")); Client vClient = new Client(mClient); mClientManager.save(vClient); mComponentResources.discardPersistentFieldChanges(); return "Client/List"; } } return errorZone.getBody(); } |
00
| Code Sample 1:
public static void main(String[] args) { try { FTPClient p = new FTPClient(); p.connect("url"); p.login("login", "pass"); int sendCommand = p.sendCommand("SYST"); System.out.println("TryMe.main() - " + sendCommand + " (sendCommand)"); sendCommand = p.sendCommand("PWD"); System.out.println("TryMe.main() - " + sendCommand + " (sendCommand)"); sendCommand = p.sendCommand("NOOP"); System.out.println("TryMe.main() - " + sendCommand + " (sendCommand)"); sendCommand = p.sendCommand("PASV"); System.out.println("TryMe.main() - " + sendCommand + " (sendCommand)"); p.changeWorkingDirectory("/"); try { printDir(p, "/"); } catch (Exception e) { e.printStackTrace(); } p.logout(); p.disconnect(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
public boolean download(String url) { HttpGet httpGet = new HttpGet(url); String filename = FileUtils.replaceNonAlphanumericCharacters(url); String completePath = directory + File.separatorChar + filename; int retriesLeft = MAX_RETRIES; while (retriesLeft > 0) { try { HttpResponse response = httpClient.execute(httpGet); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { logger.info("Downloading file from " + url + " -> " + completePath); IOUtils.copy(resEntity.getContent(), new FileOutputStream(completePath)); logger.info("File " + filename + " was downloaded successfully."); setFileSize(new File(completePath).length()); setFilename(filename); return true; } else { logger.warn("Trouble downloading file from " + url + ". Status was: " + response.getStatusLine()); } } catch (ClientProtocolException e) { logger.error("Protocol error. This is probably serious, and there's no need " + "to continue trying to download this file.", e); return false; } catch (IOException e) { logger.warn("IO trouble: " + e.getMessage() + ". Retries left: " + retriesLeft); } retriesLeft--; } return false; } |
00
| Code Sample 1:
protected Drawing loadDrawing(ProgressIndicator progress) throws IOException { Drawing drawing = createDrawing(); if (getParameter("datafile") != null) { URL url = new URL(getDocumentBase(), getParameter("datafile")); URLConnection uc = url.openConnection(); if (uc instanceof HttpURLConnection) { ((HttpURLConnection) uc).setUseCaches(false); } int contentLength = uc.getContentLength(); InputStream in = uc.getInputStream(); try { if (contentLength != -1) { in = new BoundedRangeInputStream(in); ((BoundedRangeInputStream) in).setMaximum(contentLength + 1); progress.setProgressModel((BoundedRangeModel) in); progress.setIndeterminate(false); } BufferedInputStream bin = new BufferedInputStream(in); bin.mark(512); IOException formatException = null; for (InputFormat format : drawing.getInputFormats()) { try { bin.reset(); } catch (IOException e) { uc = url.openConnection(); in = uc.getInputStream(); in = new BoundedRangeInputStream(in); ((BoundedRangeInputStream) in).setMaximum(contentLength + 1); progress.setProgressModel((BoundedRangeModel) in); bin = new BufferedInputStream(in); bin.mark(512); } try { bin.reset(); format.read(bin, drawing, true); formatException = null; break; } catch (IOException e) { formatException = e; } } if (formatException != null) { throw formatException; } } finally { in.close(); } } return drawing; }
Code Sample 2:
protected static StringBuffer doRESTOp(String urlString) throws Exception { StringBuffer result = new StringBuffer(); String restUrl = urlString; int p = restUrl.indexOf("://"); if (p < 0) restUrl = System.getProperty("fedoragsearch.protocol") + "://" + System.getProperty("fedoragsearch.hostport") + "/" + System.getProperty("fedoragsearch.path") + restUrl; URL url = null; url = new URL(restUrl); URLConnection conn = null; conn = url.openConnection(); conn.setRequestProperty("Authorization", "Basic " + (new BASE64Encoder()).encode((System.getProperty("fedoragsearch.fgsUserName") + ":" + System.getProperty("fedoragsearch.fgsPassword")).getBytes())); conn.connect(); content = null; content = conn.getContent(); String line; BufferedReader br = new BufferedReader(new InputStreamReader((InputStream) content)); while ((line = br.readLine()) != null) result.append(line); return result; } |
00
| Code Sample 1:
public ValidEPoint[] split(EPoint o, EPoint e1, long v1, EPoint e2) throws MalformedURLException, IOException, NoSuchAlgorithmException, InvalidEPointCertificateException, InvalidKeyException, SignatureException { URLConnection u = new URL(url, "action").openConnection(); OutputStream os; InputStream is; ValidEPoint[] v = new ValidEPoint[2]; u.setDoOutput(true); u.setDoInput(true); u.setAllowUserInteraction(false); os = u.getOutputStream(); os.write(("B=" + URLEncoder.encode(o.toString(), "UTF-8") + "&D=" + Base16.encode(e1.getMD()) + "&F=" + Long.toString(v1) + "&C=" + Base16.encode(e2.getMD())).getBytes()); os.close(); is = u.getInputStream(); v[1] = new ValidEPoint(this, e2, is); is.close(); v[0] = validate(e1); return v; }
Code Sample 2:
public void login() { if (email.isEmpty() || pass.isEmpty()) { NotifyUtil.warn("Acount Data", "You need to specify and account e-mail and password.", false); return; } final ProgressHandle handle = ProgressHandleFactory.createHandle("Connecting to Facebook ..."); final Runnable task = new Runnable() { @Override public void run() { handle.start(); handle.switchToIndeterminate(); FacebookJsonRestClient client = new FacebookJsonRestClient(API_KEY, SECRET); client.setIsDesktop(true); HttpURLConnection connection; List<String> cookies; try { String token = client.auth_createToken(); String post_url = "http://www.facebook.com/login.php"; String get_url = "http://www.facebook.com/login.php" + "?api_key=" + API_KEY + "&v=1.0" + "&auth_token=" + token; HttpURLConnection.setFollowRedirects(true); connection = (HttpURLConnection) new URL(get_url).openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401"); connection.setRequestProperty("Host", "www.facebook.com"); connection.setRequestProperty("Accept-Charset", "UFT-8"); connection.connect(); cookies = connection.getHeaderFields().get("Set-Cookie"); connection = (HttpURLConnection) new URL(post_url).openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401"); connection.setRequestProperty("Host", "www.facebook.com"); connection.setRequestProperty("Accept-Charset", "UFT-8"); if (cookies != null) { for (String cookie : cookies) { connection.addRequestProperty("Cookie", cookie.split(";", 2)[0]); } } String params = "api_key=" + API_KEY + "&auth_token=" + token + "&email=" + URLEncoder.encode(email, "UTF-8") + "&pass=" + URLEncoder.encode(pass, "UTF-8") + "&v=1.0"; connection.setRequestProperty("Content-Length", Integer.toString(params.length())); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setDoOutput(true); connection.connect(); connection.getOutputStream().write(params.toString().getBytes("UTF-8")); connection.getOutputStream().close(); cookies = connection.getHeaderFields().get("Set-Cookie"); if (cookies == null) { ActionListener listener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String url = "http://www.chartsy.org/facebook/"; DesktopUtil.browseAndWarn(url, null); } }; NotifyUtil.show("Application Permission", "You need to grant permission first.", MessageType.WARNING, listener, false); connection.disconnect(); loggedIn = false; } else { sessionKey = client.auth_getSession(token); sessionSecret = client.getSessionSecret(); loggedIn = true; } connection.disconnect(); handle.finish(); } catch (FacebookException fex) { handle.finish(); NotifyUtil.error("Login Error", fex.getMessage(), fex, false); } catch (IOException ioex) { handle.finish(); NotifyUtil.error("Login Error", ioex.getMessage(), ioex, false); } } }; WindowManager.getDefault().invokeWhenUIReady(task); } |
00
| Code Sample 1:
private void initURL() { try { log.fine("Checking: " + locator); URLConnection conn = URIFactory.url(locator).openConnection(); conn.setUseCaches(false); log.info(conn.getHeaderFields().toString()); String header = conn.getHeaderField(null); if (header.contains("404")) { log.info("404 file not found: " + locator); return; } if (header.contains("500")) { log.info("500 server error: " + locator); return; } if (conn.getContentLength() > 0) { byte[] buffer = new byte[50]; conn.getInputStream().read(buffer); if (new String(buffer).trim().startsWith("<!DOCTYPE")) return; } else if (conn.getContentLength() == 0) { exists = true; return; } exists = true; length = conn.getContentLength(); } catch (Exception ioe) { System.err.println(ioe); } }
Code Sample 2:
public void register(URL codeBase, String filePath) throws Exception { Properties properties = new Properties(); URL url = new URL(codeBase + filePath); properties.load(url.openStream()); initializeContext(codeBase, properties); } |
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 Exception { String uri = args[0]; Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(URI.create(uri), conf); FSDataInputStream in = null; try { in = fs.open(new Path(uri)); IOUtils.copyBytes(in, System.out, 4096, false); in.seek(0); IOUtils.copyBytes(in, System.out, 4096, false); } finally { IOUtils.closeStream(in); } } |
11
| Code Sample 1:
public static void transfer(FileInputStream fileInStream, FileOutputStream fileOutStream) throws IOException { FileChannel fileInChannel = fileInStream.getChannel(); FileChannel fileOutChannel = fileOutStream.getChannel(); long fileInSize = fileInChannel.size(); try { long transferred = fileInChannel.transferTo(0, fileInSize, fileOutChannel); if (transferred != fileInSize) { throw new IOException("transfer() did not complete"); } } finally { ensureClose(fileInChannel, fileOutChannel); } }
Code Sample 2:
private void exportJar(File root, List<File> list, Manifest manifest) throws Exception { JarOutputStream jarOut = null; FileInputStream fin = null; try { jarOut = new JarOutputStream(new FileOutputStream(jarFile), manifest); for (int i = 0; i < list.size(); i++) { String filename = list.get(i).getAbsolutePath(); filename = filename.substring(root.getAbsolutePath().length() + 1); fin = new FileInputStream(list.get(i)); JarEntry entry = new JarEntry(filename.replace('\\', '/')); jarOut.putNextEntry(entry); byte[] buf = new byte[4096]; int read; while ((read = fin.read(buf)) != -1) { jarOut.write(buf, 0, read); } jarOut.closeEntry(); jarOut.flush(); } } finally { if (fin != null) { try { fin.close(); } catch (Exception e) { ExceptionOperation.operate(e); } } if (jarOut != null) { try { jarOut.close(); } catch (Exception e) { } } } } |
00
| Code Sample 1:
public static String getStringHash(String fileName) { try { MessageDigest digest = MessageDigest.getInstance("md5"); digest.reset(); digest.update(fileName.getBytes()); byte messageDigest[] = digest.digest(); StringBuilder builder = new StringBuilder(); for (int i = 0; i < messageDigest.length; i++) builder.append(Integer.toHexString(0xFF & messageDigest[i])); String result = builder.toString(); return result; } catch (NoSuchAlgorithmException ex) { return fileName; } }
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 void run(IAction action) { int style = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().getStyle(); Shell shell = new Shell((style & SWT.MIRRORED) != 0 ? SWT.RIGHT_TO_LEFT : SWT.NONE); GraphicalViewer viewer = new ScrollingGraphicalViewer(); viewer.createControl(shell); viewer.setEditDomain(new DefaultEditDomain(null)); viewer.setRootEditPart(new ScalableFreeformRootEditPart()); viewer.setEditPartFactory(new ProjectEditPartFactory()); viewer.setContents(getContents()); viewer.flush(); int printMode = new PrintModeDialog(shell).open(); if (printMode == -1) return; PrintDialog dialog = new PrintDialog(shell, SWT.NULL); PrinterData data = dialog.open(); if (data != null) { PrintGraphicalViewerOperation op = new PrintGraphicalViewerOperation(new Printer(data), viewer); op.setPrintMode(printMode); op.run(selectedFile.getName()); } }
Code Sample 2:
public static InputStream getRequest(String path) throws Exception { HttpGet httpGet = new HttpGet(path); HttpResponse httpResponse = sClient.execute(httpGet); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(httpResponse.getEntity()); return bufHttpEntity.getContent(); } else { return null; } } |
11
| Code Sample 1:
protected String encrypt(final String data, final String key) throws CryptographicFailureException { Validate.notNull(data, "Provided data cannot be null."); Validate.notNull(key, "Provided key name cannot be null."); final PublicKey pk = getPublicKey(key); if (pk == null) { throw new CryptographicFailureException("PublicKeyNotFound", String.format("Cannot find public key '%s'", key)); } try { final Cipher cipher = Cipher.getInstance(pk.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, pk); final ByteArrayInputStream bin = new ByteArrayInputStream(data.getBytes()); final CipherInputStream cin = new CipherInputStream(bin, cipher); final ByteArrayOutputStream bout = new ByteArrayOutputStream(); IOUtils.copy(cin, bout); return new String(Base64.encodeBase64(bout.toByteArray())); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(String.format("Cannot find instance of algorithm '%s'", pk.getAlgorithm()), e); } catch (NoSuchPaddingException e) { throw new IllegalStateException(String.format("Cannot build instance of algorithm '%s'", pk.getAlgorithm()), e); } catch (InvalidKeyException e) { throw new IllegalStateException(String.format("Cannot build instance of algorithm '%s'", pk.getAlgorithm()), e); } catch (IOException e) { throw new IllegalStateException("Cannot build in-memory cipher copy", e); } }
Code Sample 2:
public static void buildPerMovieDiffBinary(String completePath, String slopeOneDataFolderName, String slopeOneDataFileName) { try { File inFile = new File(completePath + fSep + "SmartGRAPE" + fSep + slopeOneDataFolderName + fSep + slopeOneDataFileName); FileChannel inC = new FileInputStream(inFile).getChannel(); for (int i = 1; i <= 17770; i++) { File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + slopeOneDataFolderName + fSep + "Movie-" + i + "-SlopeOneData.txt"); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf = ByteBuffer.allocate(17770 * 10); for (int j = 1; j < i; j++) { ByteBuffer bbuf = ByteBuffer.allocate(12); inC.position((17769 * 17770 * 6) - ((17769 - (j - 1)) * (17770 - (j - 1)) * 6) + (i - j - 1) * 12); inC.read(bbuf); bbuf.flip(); buf.putShort(bbuf.getShort()); bbuf.getShort(); buf.putInt(bbuf.getInt()); buf.putFloat(-bbuf.getFloat()); } buf.putShort(new Integer(i).shortValue()); buf.putInt(0); buf.putFloat(0.0f); ByteBuffer remainingBuf = inC.map(FileChannel.MapMode.READ_ONLY, (17769 * 17770 * 6) - ((17769 - (i - 1)) * (17770 - (i - 1)) * 6), (17770 - i) * 12); while (remainingBuf.hasRemaining()) { remainingBuf.getShort(); buf.putShort(remainingBuf.getShort()); buf.putInt(remainingBuf.getInt()); buf.putFloat(remainingBuf.getFloat()); } buf.flip(); outC.write(buf); buf.clear(); outC.close(); } } catch (Exception e) { e.printStackTrace(); } } |
11
| Code Sample 1:
protected File downloadUpdate(String resource) throws AgentException { RESTCall call = makeRESTCall(resource); call.invoke(); File tmpFile; try { tmpFile = File.createTempFile("controller-update-", ".war", new File(tmpPath)); } catch (IOException e) { throw new AgentException("Failed to create temporary file", e); } InputStream is; try { is = call.getInputStream(); } catch (IOException e) { throw new AgentException("Failed to open input stream", e); } try { FileOutputStream os; try { os = new FileOutputStream(tmpFile); } catch (FileNotFoundException e) { throw new AgentException("Failed to open temporary file for writing", e); } boolean success = false; try { IOUtils.copy(is, os); success = true; } catch (IOException e) { throw new AgentException("Failed to download update", e); } finally { try { os.flush(); os.close(); } catch (IOException e) { if (!success) throw new AgentException("Failed to flush to disk", e); } } } finally { try { is.close(); } catch (IOException e) { log.error("Failed to close input stream", e); } call.disconnect(); } return tmpFile; }
Code Sample 2:
public void doCompress(File[] files, File out, List<String> excludedKeys) { Map<String, File> map = new HashMap<String, File>(); String parent = FilenameUtils.getBaseName(out.getName()); for (File f : files) { CompressionUtil.list(f, parent, map, excludedKeys); } if (!map.isEmpty()) { FileOutputStream fos = null; ArchiveOutputStream aos = null; InputStream is = null; try { fos = new FileOutputStream(out); aos = getArchiveOutputStream(fos); for (Map.Entry<String, File> entry : map.entrySet()) { File file = entry.getValue(); ArchiveEntry ae = getArchiveEntry(file, entry.getKey()); aos.putArchiveEntry(ae); if (file.isFile()) { IOUtils.copy(is = new FileInputStream(file), aos); IOUtils.closeQuietly(is); is = null; } aos.closeArchiveEntry(); } aos.finish(); } catch (IOException ex) { ex.printStackTrace(); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(aos); IOUtils.closeQuietly(fos); } } } |
00
| Code Sample 1:
static String fetchURLComposeExternPackageList(String urlpath, String pkglisturlpath) { String link = pkglisturlpath + "package-list"; try { boolean relative = isRelativePath(urlpath); readPackageList((new URL(link)).openStream(), urlpath, relative); } catch (MalformedURLException exc) { return getText("doclet.MalformedURL", link); } catch (IOException exc) { return getText("doclet.URL_error", link); } return null; }
Code Sample 2:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } |
00
| Code Sample 1:
public T_Result unmarshall(URL url) throws SAXException, ParserConfigurationException, IOException { XMLReader parser = getParserFactory().newSAXParser().getXMLReader(); parser.setContentHandler(getContentHandler()); parser.setDTDHandler(getContentHandler()); parser.setEntityResolver(getContentHandler()); parser.setErrorHandler(getContentHandler()); InputSource inputSource = new InputSource(url.openStream()); inputSource.setSystemId(url.toString()); parser.parse(inputSource); return contentHandler.getRootObject(); }
Code Sample 2:
public static void getResponseAsStream(String _url, Object _stringOrStream, OutputStream _stream, Map _headers, Map _params, String _contentType, int _timeout) throws IOException { if (_url == null || _url.length() <= 0) throw new IllegalArgumentException("Url can not be null."); String temp = _url.toLowerCase(); if (!temp.startsWith("http://") && !temp.startsWith("https://")) _url = "http://" + _url; HttpMethod method = null; if (_stringOrStream == null && (_params == null || _params.size() <= 0)) method = new GetMethod(_url); else method = new PostMethod(_url); HttpMethodParams params = ((HttpMethodBase) method).getParams(); if (params == null) { params = new HttpMethodParams(); ((HttpMethodBase) method).setParams(params); } if (_timeout < 0) params.setSoTimeout(0); else params.setSoTimeout(_timeout); if (_contentType != null && _contentType.length() > 0) { if (_headers == null) _headers = new HashMap(); _headers.put("Content-Type", _contentType); } if (_headers != null) { Iterator iter = _headers.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); method.setRequestHeader((String) entry.getKey(), (String) entry.getValue()); } } if (method instanceof PostMethod && (_params != null && _params.size() > 0)) { Iterator iter = _params.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); ((PostMethod) method).addParameter((String) entry.getKey(), (String) entry.getValue()); } } if (method instanceof EntityEnclosingMethod && _stringOrStream != null) { if (_stringOrStream instanceof InputStream) { RequestEntity entity = new InputStreamRequestEntity((InputStream) _stringOrStream); ((EntityEnclosingMethod) method).setRequestEntity(entity); } else { RequestEntity entity = new StringRequestEntity(_stringOrStream.toString(), _contentType, null); ((EntityEnclosingMethod) method).setRequestEntity(entity); } } HttpClient httpClient = new HttpClient(new org.apache.commons.httpclient.SimpleHttpConnectionManager()); try { int status = httpClient.executeMethod(method); if (status != HttpStatus.SC_OK) { if (status >= 500 && status < 600) throw new IOException("Remote service<" + _url + "> respose a error, status:" + status); } InputStream instream = method.getResponseBodyAsStream(); IOUtils.copy(instream, _stream); instream.close(); } catch (IOException err) { throw err; } finally { if (method != null) method.releaseConnection(); } } |
00
| Code Sample 1:
private void buildCache() { cache = new HashMap<String, byte[]>(); JarInputStream jis = null; BufferedInputStream bis = null; URL[] urls = getURLs(); for (URL url : urls) { try { if (url.getPath().endsWith(".jar")) { jis = new JarInputStream(url.openStream()); bis = new BufferedInputStream(jis); JarEntry jarEntry = null; while ((jarEntry = jis.getNextJarEntry()) != null) { String name = jarEntry.getName(); if (!jarEntry.isDirectory() && name.toLowerCase().endsWith(".class")) { String className = name.replaceAll("/", ".").substring(0, name.length() - 6); if (isClassLoaderConditonVerified(className)) { ByteArrayOutputStream baos = null; BufferedOutputStream bos = null; try { baos = new ByteArrayOutputStream(); bos = new BufferedOutputStream(baos); int i = -1; while ((i = bis.read()) != -1) { bos.write(i); } bos.flush(); cache.put(className, baos.toByteArray()); } finally { if (baos != null) { try { baos.close(); } catch (IOException ignore) { } } if (bos != null) { try { bos.close(); } catch (IOException ex) { } } } jis.closeEntry(); } } } try { jis.close(); } catch (IOException ignore) { } } else { File file = new File(url.getFile()); buildCacheFromFile(file, null); } } catch (IOException ex) { continue; } } }
Code Sample 2:
public ViewProperties(String basePath, String baseFile) throws Exception { FileInputStream input = null; String file = basePath + "/" + baseFile + ".properties"; properties = new Properties(); try { URL url = MapViewer.class.getResource(file); properties.load(url.openStream()); viewName = (String) properties.get("view.name"); viewShape = (String) properties.get("view.shape"); path = basePath + "/" + (String) properties.get("icon.path"); iconHeight = getIntProperty("icon.height", 96); iconWidth = getIntProperty("icon.width", 96); fontSizeSmall = getIntProperty("font.small.size", 10); fontSizeMedium = getIntProperty("font.medium.size", 12); fontSizeLarge = getIntProperty("font.large.size", 16); fontSizeHuge = getIntProperty("font.huge.size", 20); if (viewShape.equals("Hexagonal")) { tileHeight = (int) (Math.sqrt(3.0) / 2.0 * iconWidth); tileWidth = (int) (iconWidth * 3.0 / 4.0); tileOffset = (int) (tileHeight / 2.0); } else { tileHeight = iconHeight; tileWidth = iconWidth; tileOffset = 0; } } catch (Exception e) { error("Cannot load properties from file [" + file + "]"); throw e; } } |
00
| Code Sample 1:
public static Dictionary getDefaultConfig(BundleContext bc) { final Dictionary config = new Hashtable(); config.put(HttpConfig.HTTP_ENABLED_KEY, getPropertyAsBoolean(bc, "org.knopflerfish.http.enabled", "true")); config.put(HttpConfig.HTTPS_ENABLED_KEY, getPropertyAsBoolean(bc, "org.knopflerfish.http.secure.enabled", "true")); config.put(HttpConfig.HTTP_PORT_KEY, getPropertyAsInteger(bc, "org.osgi.service.http.port", HTTP_PORT_DEFAULT)); config.put(HttpConfig.HTTPS_PORT_KEY, getPropertyAsInteger(bc, "org.osgi.service.http.secure.port", HTTPS_PORT_DEFAULT)); config.put(HttpConfig.HOST_KEY, getPropertyAsString(bc, "org.osgi.service.http.hostname", "")); Properties mimeProps = new Properties(); try { mimeProps.load(HttpConfig.class.getResourceAsStream("/mime.default")); String propurl = getPropertyAsString(bc, "org.knopflerfish.http.mime.props", ""); if (propurl.length() > 0) { URL url = new URL(propurl); Properties userMimeProps = new Properties(); userMimeProps.load(url.openStream()); Enumeration e = userMimeProps.keys(); while (e.hasMoreElements()) { String key = (String) e.nextElement(); mimeProps.put(key, userMimeProps.getProperty(key)); } } } catch (MalformedURLException ignore) { } catch (IOException ignore) { } Vector mimeVector = new Vector(mimeProps.size()); Enumeration e = mimeProps.keys(); while (e.hasMoreElements()) { String key = (String) e.nextElement(); mimeVector.addElement(new String[] { key, mimeProps.getProperty(key) }); } config.put(HttpConfig.MIME_PROPS_KEY, mimeVector); config.put(HttpConfig.SESSION_TIMEOUT_KEY, getPropertyAsInteger(bc, "org.knopflerfish.http.session.timeout.default", 1200)); config.put(HttpConfig.CONNECTION_TIMEOUT_KEY, getPropertyAsInteger(bc, "org.knopflerfish.http.connection.timeout", 30)); config.put(HttpConfig.CONNECTION_MAX_KEY, getPropertyAsInteger(bc, "org.knopflerfish.http.connection.max", 50)); config.put(HttpConfig.DNS_LOOKUP_KEY, getPropertyAsBoolean(bc, "org.knopflerfish.http.dnslookup", "false")); config.put(HttpConfig.RESPONSE_BUFFER_SIZE_DEFAULT_KEY, getPropertyAsInteger(bc, "org.knopflerfish.http.response.buffer.size.default", 16384)); config.put(HttpConfig.DEFAULT_CHAR_ENCODING_KEY, getPropertyAsString(bc, HttpConfig.DEFAULT_CHAR_ENCODING_KEY, "ISO-8859-1")); config.put(HttpConfig.REQ_CLIENT_AUTH_KEY, getPropertyAsBoolean(bc, "org.knopflerfish.http.req.client.auth", "false")); return config; }
Code Sample 2:
public static void unzipAndRemove(final String file) { String destination = file.substring(0, file.length() - 3); InputStream is = null; OutputStream os = null; try { is = new GZIPInputStream(new FileInputStream(file)); os = new FileOutputStream(destination); byte[] buffer = new byte[8192]; for (int length; (length = is.read(buffer)) != -1; ) os.write(buffer, 0, length); } catch (IOException e) { System.err.println("Fehler: Kann nicht entpacken " + file); } finally { if (os != null) try { os.close(); } catch (IOException e) { } if (is != null) try { is.close(); } catch (IOException e) { } } deleteFile(file); } |
11
| Code Sample 1:
private byte[] _generate() throws NoSuchAlgorithmException { if (host == null) { try { seed = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { seed = "localhost/127.0.0.1"; } catch (SecurityException e) { seed = "localhost/127.0.0.1"; } host = seed; } else { seed = host; } seed = seed + new Date().toString(); seed = seed + Long.toString(rnd.nextLong()); md = MessageDigest.getInstance(algorithm); md.update(seed.getBytes()); return md.digest(); }
Code Sample 2:
private static String digest(String myinfo) { try { MessageDigest alga = MessageDigest.getInstance("SHA"); alga.update(myinfo.getBytes()); byte[] digesta = alga.digest(); return byte2hex(digesta); } catch (Exception ex) { return myinfo; } } |
00
| Code Sample 1:
public static String md5(String word) { MessageDigest alg = null; try { alg = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(ServletUtils.class.getName()).log(Level.SEVERE, null, ex); } alg.reset(); alg.update(word.getBytes()); byte[] digest = alg.digest(); StringBuilder hashedWord = new StringBuilder(); String hx; for (int i = 0; i < digest.length; i++) { hx = Integer.toHexString(0xFF & digest[i]); if (hx.length() == 1) { hx = "0" + hx; } hashedWord.append(hx); } return hashedWord.toString(); }
Code Sample 2:
public FlickrObject perform(boolean chkResponse) throws FlickrException { validate(); String data = getRequestData(); OutputStream os = null; InputStream is = null; try { URL url = null; try { url = new URL(m_url); } catch (MalformedURLException mux) { IllegalStateException iax = new IllegalStateException(); iax.initCause(mux); throw iax; } HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoOutput(true); con.setRequestMethod("POST"); os = con.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os); osw.write(data); osw.flush(); is = con.getInputStream(); return processRespons(is, chkResponse); } catch (FlickrException fx) { throw fx; } catch (IOException iox) { throw new FlickrException(iox); } finally { if (os != null) try { os.close(); } catch (IOException _) { } if (is != null) try { is.close(); } catch (IOException _) { } } } |
00
| Code Sample 1:
@Override public Class<?> loadClass(final String name) throws ClassNotFoundException { final String baseName = StringUtils.substringBefore(name, "$"); if (baseName.startsWith("java") && !whitelist.contains(baseName) && !additionalWhitelist.contains(baseName)) { throw new NoClassDefFoundError(name + " is a restricted class for GAE"); } if (!name.startsWith("com.gargoylesoftware")) { return super.loadClass(name); } super.loadClass(name); final InputStream is = getResourceAsStream(name.replaceAll("\\.", "/") + ".class"); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { IOUtils.copy(is, bos); final byte[] bytes = bos.toByteArray(); return defineClass(name, bytes, 0, bytes.length); } catch (final IOException e) { throw new RuntimeException(e); } }
Code Sample 2:
@Override public DataTable generateDataTable(Query query, HttpServletRequest request) throws DataSourceException { String url = request.getParameter(URL_PARAM_NAME); if (StringUtils.isEmpty(url)) { log.error("url parameter not provided."); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url parameter not provided"); } Reader reader; try { reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); } catch (MalformedURLException e) { log.error("url is malformed: " + url); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url is malformed: " + url); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } DataTable dataTable = null; ULocale requestLocale = DataSourceHelper.getLocaleFromRequest(request); try { dataTable = CsvDataSourceHelper.read(reader, null, true, requestLocale); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } return dataTable; } |
00
| Code Sample 1:
private String loadStatusResult() { try { URL url = new URL(getServerUrl()); InputStream input = url.openStream(); InputStreamReader is = new InputStreamReader(input, "utf-8"); BufferedReader reader = new BufferedReader(is); StringBuffer buffer = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { buffer.append(line); } return buffer.toString(); } catch (MalformedURLException e1) { e1.printStackTrace(); return null; } catch (IOException e2) { e2.printStackTrace(); return null; } }
Code Sample 2:
@SuppressWarnings("unchecked") private Map<String, Object> _request(String method, String path, Map<String, Object> body, JSONRecognizer... recognizers) throws IOException, TwinException { String uri = url + path; HttpRequest request; if (body == null) { BasicHttpRequest r = new BasicHttpRequest(method, uri); request = r; } else { BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest(method, uri); StringEntity entity; try { entity = new StringEntity(JSON.encode(body), "utf-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } entity.setContentType("application/json; charset=utf-8"); r.setEntity(entity); request = r; } HttpClient client = getClient(); try { HttpResponse response = client.execute(new HttpHost(url.getHost(), url.getPort()), request); HttpEntity entity = response.getEntity(); if (entity == null) return null; String contentType = entity.getContentType().getValue(); boolean isJson = (contentType != null) && ("application/json".equals(contentType) || contentType.startsWith("application/json;")); String result = null; InputStream in = entity.getContent(); try { Reader r = new InputStreamReader(in, "UTF-8"); StringBuilder sb = new StringBuilder(); char[] buf = new char[256]; int read; while ((read = r.read(buf, 0, buf.length)) >= 0) sb.append(buf, 0, read); r.close(); result = sb.toString(); } finally { try { in.close(); } catch (Exception e) { } } int code = response.getStatusLine().getStatusCode(); if (code >= 400) { if (isJson) { try { throw deserializeException((Map<String, Object>) JSON.decode(result)); } catch (IllegalArgumentException e) { throw TwinError.UnknownError.create("Couldn't parse error response: \n" + result, e); } } if (code == 404) throw TwinError.UnknownCommand.create("Got server response " + code + " for request " + uri); else throw TwinError.UnknownError.create("Got server response " + code + " for request " + uri + "\nBody is " + result); } if (!isJson) throw TwinError.UnknownError.create("Got wrong content type " + contentType + " for request " + uri + "\nBody is " + result); try { return (Map<String, Object>) JSON.decode(result, recognizers); } catch (Exception e) { throw TwinError.UnknownError.create("Malformed JSON result for request " + uri + ": \nBody is " + result, e); } } catch (ClientProtocolException e) { throw new IOException(e); } } |
00
| Code Sample 1:
protected Icon newIcon(String iconName) { URL url = Utils.getResource(getFullPath(iconName, "/"), getClass()); if (url == null) { if (getParent() != null) return getParent().getIcon(iconName); return null; } try { MethodCall getImage = new MethodCaller("org.apache.sanselan.Sanselan", null, "getBufferedImage", new Object[] { InputStream.class }).getMethodCall(); getImage.setArgumentValue(0, url.openStream()); return new ImageIcon((BufferedImage) getImage.call()); } catch (Throwable e) { return new ImageIcon(url); } }
Code Sample 2:
public static void assertEquals(String xmlpath, Object actualObject) throws Exception { InputStreamReader isr; try { isr = new FileReader(xmlpath); } catch (FileNotFoundException e) { URL url = AssertHelper.class.getClassLoader().getResource(xmlpath); if (null != url) { try { isr = new InputStreamReader(url.openStream()); } catch (Exception e1) { throw new AssertionFailedError("Unable to find output xml : " + xmlpath); } } else { throw new AssertionFailedError("Could not read output xml : " + xmlpath); } } DOMParser parser = new DOMParser(); parser.parse(new InputSource(isr)); Document document = parser.getDocument(); try { assertEqual(document.getDocumentElement(), actualObject); } catch (AssertionFailedError e) { String message = null; if (null != e.getCause()) { message = e.getCause().getMessage(); } else { message = e.getMessage(); } StringBuffer sbf = new StringBuffer(message + " \n " + xmlpath); Iterator iter = nodestack.iterator(); while (iter.hasNext()) { sbf.append(" -> " + ((Object[]) iter.next())[0]); iter.remove(); } AssertionFailedError a = new AssertionFailedError(sbf.toString()); a.setStackTrace(e.getStackTrace()); throw a; } catch (Exception e) { String message = null; if (null != e.getCause()) { message = e.getCause().getMessage(); } else { message = e.getMessage(); } StringBuffer sbf = new StringBuffer(message + " \n " + xmlpath); Iterator iter = nodestack.iterator(); while (iter.hasNext()) { sbf.append(" -> " + ((Object[]) iter.next())[0]); iter.remove(); } Exception ex = new Exception(sbf.toString()); ex.setStackTrace(e.getStackTrace()); throw ex; } } |
11
| Code Sample 1:
public static String SHA1(String string) throws XLWrapException { MessageDigest md; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new XLWrapException("SHA-1 message digest is not available."); } byte[] data = new byte[40]; md.update(string.getBytes()); data = md.digest(); StringBuffer buf = new StringBuffer(); for (int i = 0; i < data.length; i++) { int halfbyte = (data[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 = data[i] & 0x0F; } while (two_halfs++ < 1); } return buf.toString(); }
Code Sample 2:
private String getMD5Password(String plainText) throws NoSuchAlgorithmException { MessageDigest mdAlgorithm; StringBuffer hexString = new StringBuffer(); String md5Password = ""; mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(plainText.getBytes()); byte[] digest = mdAlgorithm.digest(); for (int i = 0; i < digest.length; i++) { plainText = Integer.toHexString(0xFF & digest[i]); if (plainText.length() < 2) { plainText = "0" + plainText; } hexString.append(plainText); } md5Password = hexString.toString(); return md5Password; } |
11
| Code Sample 1:
public void copyFile(File sourceFile, File destFile) throws IOException { Log.level3("Copying " + sourceFile.getPath() + " to " + destFile.getPath()); 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:
@Override public void download(String remoteFilePath, String localFilePath) { InputStream remoteStream = null; try { remoteStream = client.get(remoteFilePath); } catch (IOException e) { e.printStackTrace(); } OutputStream localStream = null; try { localStream = new FileOutputStream(new File(localFilePath)); } catch (FileNotFoundException e1) { e1.printStackTrace(); } try { IOUtils.copy(remoteStream, localStream); } catch (IOException e) { e.printStackTrace(); } } |
00
| Code Sample 1:
public byte[] loadResource(String name) throws IOException { ClassPathResource cpr = new ClassPathResource(name); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(cpr.getInputStream(), baos); return baos.toByteArray(); }
Code Sample 2:
public AudioFileFormat getAudioFileFormat(URL url) throws UnsupportedAudioFileException, IOException { InputStream urlStream = url.openStream(); AudioFileFormat fileFormat = null; try { fileFormat = getFMT(urlStream, false); } finally { urlStream.close(); } return fileFormat; } |
00
| Code Sample 1:
private static InputStream stream(String input) { try { if (input.startsWith("http://")) return URIFactory.url(input).openStream(); else return stream(new File(input)); } catch (IOException e) { throw new RuntimeException(e); } catch (URISyntaxException e) { throw new RuntimeException(e); } }
Code Sample 2:
private InputStream getInputStream() throws URISyntaxException, MalformedURLException, IOException { InputStream inStream = null; try { URL url = new URI(wsdlFile).toURL(); URLConnection connection = url.openConnection(); connection.connect(); inStream = connection.getInputStream(); } catch (IllegalArgumentException ex) { inStream = new FileInputStream(wsdlFile); } return inStream; } |
11
| Code Sample 1:
public String getMD5(String data) { try { MessageDigest md5Algorithm = MessageDigest.getInstance("MD5"); md5Algorithm.update(data.getBytes(), 0, data.length()); byte[] digest = md5Algorithm.digest(); StringBuffer hexString = new StringBuffer(); String hexDigit = null; for (int i = 0; i < digest.length; i++) { hexDigit = Integer.toHexString(0xFF & digest[i]); if (hexDigit.length() < 2) { hexDigit = "0" + hexDigit; } hexString.append(hexDigit); } return hexString.toString(); } catch (NoSuchAlgorithmException ne) { return data; } }
Code Sample 2:
public static boolean verify(final String password, final String encryptedPassword) { MessageDigest digest = null; int size = 0; String base64 = null; if (encryptedPassword.regionMatches(true, 0, "{CRYPT}", 0, 7)) { throw new InternalError("Not implemented"); } else if (encryptedPassword.regionMatches(true, 0, "{SHA}", 0, 5)) { size = 20; base64 = encryptedPassword.substring(5); try { digest = MessageDigest.getInstance("SHA-1"); } catch (final NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{SSHA}", 0, 6)) { size = 20; base64 = encryptedPassword.substring(6); try { digest = MessageDigest.getInstance("SHA-1"); } catch (final NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{MD5}", 0, 5)) { size = 16; base64 = encryptedPassword.substring(5); try { digest = MessageDigest.getInstance("MD5"); } catch (final NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{SMD5}", 0, 6)) { size = 16; base64 = encryptedPassword.substring(6); try { digest = MessageDigest.getInstance("MD5"); } catch (final NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else { return false; } final byte[] data = Base64.decode(base64.toCharArray()); final byte[] orig = new byte[size]; System.arraycopy(data, 0, orig, 0, size); digest.reset(); digest.update(password.getBytes()); if (data.length > size) { digest.update(data, size, data.length - size); } return MessageDigest.isEqual(digest.digest(), orig); } |
11
| Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public void run() { Vector<Update> updates = new Vector<Update>(); if (dic != null) updates.add(dic); if (gen != null) updates.add(gen); if (res != null) updates.add(res); if (help != null) updates.add(help); for (Iterator iterator = updates.iterator(); iterator.hasNext(); ) { Update update = (Update) iterator.next(); try { File temp = File.createTempFile("fm_" + update.getType(), ".jar"); temp.deleteOnExit(); FileOutputStream out = new FileOutputStream(temp); URL url = new URL(update.getAction()); URLConnection conn = url.openConnection(); com.diccionarioderimas.Utils.setupProxy(conn); InputStream in = conn.getInputStream(); byte[] buffer = new byte[1024]; int read = 0; int total = 0; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); total += read; if (total > 10000) { progressBar.setValue(progressBar.getValue() + total); total = 0; } } out.close(); in.close(); String fileTo = basePath + "diccionariorimas.jar"; if (update.getType() == Update.GENERATOR) fileTo = basePath + "generador.jar"; else if (update.getType() == Update.RESBC) fileTo = basePath + "resbc.me"; else if (update.getType() == Update.HELP) fileTo = basePath + "help.html"; if (update.getType() == Update.RESBC) { Utils.unzip(temp, new File(fileTo)); } else { Utils.copyFile(new FileInputStream(temp), new File(fileTo)); } } catch (Exception e) { e.printStackTrace(); } } setVisible(false); if (gen != null || res != null) { try { new Main(null, basePath, false); } catch (Exception e) { new ErrorDialog(frame, e); } } String restart = ""; if (dic != null) restart += "\nAlgunas de ellas s�lo estar�n disponibles despu�s de reiniciar el diccionario."; JOptionPane.showMessageDialog(frame, "Se han terminado de realizar las actualizaciones." + restart, "Actualizaciones", JOptionPane.INFORMATION_MESSAGE); } |
00
| Code Sample 1:
public void sorter() { String inputLine1, inputLine2; String epiNames[] = new String[1000]; String epiEpisodes[] = new String[1000]; int lineCounter = 0; try { String pluginDir = pluginInterface.getPluginDirectoryName(); String eplist_file = pluginDir + System.getProperty("file.separator") + "EpisodeList.txt"; File episodeList = new File(eplist_file); if (!episodeList.isFile()) { episodeList.createNewFile(); } final BufferedReader in = new BufferedReader(new FileReader(episodeList)); while ((inputLine1 = in.readLine()) != null) { if ((inputLine2 = in.readLine()) != null) { epiNames[lineCounter] = inputLine1; epiEpisodes[lineCounter] = inputLine2; lineCounter++; } } in.close(); int epiLength = epiNames.length; for (int i = 0; i < (lineCounter); i++) { for (int j = 0; j < (lineCounter - 1); j++) { if (epiNames[j].compareToIgnoreCase(epiNames[j + 1]) > 0) { String temp = epiNames[j]; epiNames[j] = epiNames[j + 1]; epiNames[j + 1] = temp; String temp2 = epiEpisodes[j]; epiEpisodes[j] = epiEpisodes[j + 1]; epiEpisodes[j + 1] = temp2; } } } File episodeList2 = new File(eplist_file); BufferedWriter bufWriter = new BufferedWriter(new FileWriter(episodeList2)); for (int i = 0; i <= lineCounter; i++) { if (epiNames[i] == null) { break; } bufWriter.write(epiNames[i] + "\n"); bufWriter.write(epiEpisodes[i] + "\n"); } bufWriter.close(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
public static void copyFile(File src, File dst) throws ResourceNotFoundException, ParseErrorException, Exception { if (src.getAbsolutePath().endsWith(".vm")) { copyVMFile(src, dst.getAbsolutePath().substring(0, dst.getAbsolutePath().lastIndexOf(".vm"))); } else { FileInputStream fIn; FileOutputStream fOut; FileChannel fIChan, fOChan; long fSize; MappedByteBuffer mBuf; fIn = new FileInputStream(src); fOut = new FileOutputStream(dst); fIChan = fIn.getChannel(); fOChan = fOut.getChannel(); fSize = fIChan.size(); mBuf = fIChan.map(FileChannel.MapMode.READ_ONLY, 0, fSize); fOChan.write(mBuf); fIChan.close(); fIn.close(); fOChan.close(); fOut.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:
public static void main(final String[] args) { final Runnable startDerby = new Runnable() { public void run() { try { final NetworkServerControl control = new NetworkServerControl(InetAddress.getByName("localhost"), 1527); control.start(new PrintWriter(System.out)); } catch (final Exception ex) { throw new RuntimeException(ex); } } }; new Thread(startDerby).start(); final Runnable startActiveMq = new Runnable() { public void run() { Main.main(new String[] { "start", "xbean:file:active-mq-config.xml" }); } }; new Thread(startActiveMq).start(); final Runnable startMailServer = new Runnable() { public void run() { final SimpleMessageListener listener = new SimpleMessageListener() { public final boolean accept(final String from, final String recipient) { return true; } public final void deliver(final String from, final String recipient, final InputStream data) throws TooMuchDataException, IOException { System.out.println("FROM: " + from); System.out.println("TO: " + recipient); final File tmpDir = new File(System.getProperty("java.io.tmpdir")); final File file = new File(tmpDir, recipient); final FileWriter fw = new FileWriter(file); try { IOUtils.copy(data, fw); } finally { fw.close(); } } }; final SMTPServer smtpServer = new SMTPServer(new SimpleMessageListenerAdapter(listener)); smtpServer.start(); System.out.println("Started SMTP Server"); } }; new Thread(startMailServer).start(); } |
00
| Code Sample 1:
public boolean isValid(WizardContext context) { if (serviceSelection < 0) { return false; } ServiceReference selection = (ServiceReference) serviceList.getElementAt(serviceSelection); if (selection == null) { return false; } String function = (String) context.getAttribute(ServiceWizard.ATTRIBUTE_FUNCTION); context.setAttribute(ServiceWizard.ATTRIBUTE_SERVICE_REFERENCE, selection); URL url = selection.getResourceURL(); InputStream inputStream = null; try { inputStream = url.openStream(); InputSource inputSource = new InputSource(inputStream); JdbcService service = ServiceDigester.parseService(inputSource, IsqlToolkit.getSharedEntityResolver()); context.setAttribute(ServiceWizard.ATTRIBUTE_SERVICE, service); return true; } catch (IOException error) { if (!ServiceWizard.FUNCTION_DELETE.equals(function)) { String loc = url.toExternalForm(); String message = messages.format("SelectServiceStep.failed_to_load_service_from_url", loc); context.showErrorDialog(error, message); } else { return true; } } catch (Exception error) { String message = messages.format("SelectServiceStep.service_load_error", url.toExternalForm()); context.showErrorDialog(error, message); } return false; }
Code Sample 2:
public boolean searchEntity(String login, String password, String searcheId, OutputStream os) throws SynchronizationException { HttpClient client = new SSLHttpClient(); try { StringBuilder builder = new StringBuilder(url).append("?" + CMD_PARAM + "=" + CMD_SEARCH).append("&" + LOGIN_PARAM + "=" + URLEncoder.encode(login, "UTF-8")).append("&" + PASSWD_PARAM + "=" + URLEncoder.encode(password, "UTF-8")).append("&" + SEARCH_PARAM + "=" + searcheId); HttpGet method = httpGetMethod(builder.toString()); HttpResponse response = client.execute(method); Header header = response.getFirstHeader(HEADER_NAME); if (header != null && HEADER_VALUE.equals(HEADER_VALUE)) { int code = response.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { long expectedLength = response.getEntity().getContentLength(); InputStream is = response.getEntity().getContent(); FileUtils.writeInFile(is, os, expectedLength); return true; } else { throw new SynchronizationException("Command 'search' : HTTP error code returned." + code, SynchronizationException.ERROR_SEARCH); } } else { throw new SynchronizationException("HTTP header is invalid", SynchronizationException.ERROR_SEARCH); } } catch (Exception e) { throw new SynchronizationException("Command 'search' -> ", e, SynchronizationException.ERROR_SEARCH); } } |
11
| Code Sample 1:
public void access() { Authenticator.setDefault(new MyAuthenticator()); try { URL url = new URL("http://localhost/ws/test"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } }
Code Sample 2:
public static LinkedList Import(String url) throws Exception { LinkedList data = new LinkedList(); BufferedReader in = new BufferedReader(new InputStreamReader((new URL(url)).openStream())); String csvLine; while ((csvLine = in.readLine()) != null) { StringTokenizer st = new StringTokenizer(csvLine, ","); CSVData cd = new CSVData(); st.nextToken(); st.nextToken(); cd.matrNumber = Integer.parseInt(st.nextToken().trim()); cd.fName = st.nextToken().trim(); cd.lName = st.nextToken().trim(); cd.email = st.nextToken().trim(); cd.stdyPath = st.nextToken().trim(); cd.sem = Integer.parseInt(st.nextToken().trim()); data.add(cd); } in.close(); return data; } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.