List of usage examples for java.io InputStream available
public int available() throws IOException
From source file:it.drwolf.ridire.session.JobCleaner.java
public void testScript(CrawledResource cr, String cleaningScript) { JSch jSch = new JSch(); String origFile = FilenameUtils.getFullPath(cr.getArcFile()).concat(JobMapperMonitor.RESOURCESDIR) .concat(cr.getDigest().concat(".txt")); String endFile = this.cleanerPath.concat(System.getProperty("file.separator")).concat(cr.getDigest()) .concat(".txt"); String command = "perl " + this.cleanerPath.concat(System.getProperty("file.separator")) + "testscript.pl " + endFile;/* ww w . j a v a 2s. c om*/ try { this.testBefore = this.ridirePlainTextCleaner.getCleanText(new File(origFile)); File script = File.createTempFile("cleaner", ".pl"); File origTemp = File.createTempFile("orig", ".temp"); FileUtils.writeStringToFile(origTemp, this.testBefore); FileUtils.writeStringToFile(script, cleaningScript); // transfer file to process com.jcraft.jsch.Session session = jSch.getSession(this.perlUser, "127.0.0.1"); java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.setPassword(this.perlPw); session.connect(); Channel channel = session.openChannel("sftp"); channel.connect(); ChannelSftp c = (ChannelSftp) channel; int mode = ChannelSftp.OVERWRITE; c.put(origTemp.getAbsolutePath(), endFile, mode); // transfer script c.put(script.getAbsolutePath(), this.cleanerPath.concat(System.getProperty("file.separator")).concat("testscript.pl")); c.disconnect(); FileUtils.deleteQuietly(script); // execute script channel = session.openChannel("exec"); ByteArrayOutputStream errorStream = new ByteArrayOutputStream(); ((ChannelExec) channel).setErrStream(errorStream); ((ChannelExec) channel).setCommand(command); channel.setInputStream(null); InputStream inputStream = channel.getInputStream(); channel.connect(); byte[] tmp = new byte[1024]; while (true) { while (inputStream.available() > 0) { int i = inputStream.read(tmp, 0, 1024); if (i < 0) { break; } } if (channel.isClosed()) { break; } try { Thread.sleep(200); } catch (Exception ee) { } } this.testOutput = errorStream.toString(); channel.disconnect(); // get new file channel = session.openChannel("sftp"); channel.connect(); c = (ChannelSftp) channel; File newFile = File.createTempFile("cleanedFile", null); c.get(endFile + ".tmp", newFile.getAbsolutePath()); c.disconnect(); // delete files from working directory channel = session.openChannel("exec"); command = "rm " + this.cleanerPath.concat(System.getProperty("file.separator")) + "testscript.pl " + endFile + " " + endFile + ".tmp"; ((ChannelExec) channel).setCommand(command); channel.setInputStream(null); inputStream = channel.getInputStream(); channel.connect(); StringBuffer testScriptOutputStringBuffer = new StringBuffer(); while (true) { while (inputStream.available() > 0) { int i = inputStream.read(tmp, 0, 1024); if (i < 0) { break; } testScriptOutputStringBuffer.append(tmp); } if (channel.isClosed()) { testScriptOutputStringBuffer.append("Exit status: " + channel.getExitStatus()); break; } try { Thread.sleep(200); } catch (Exception ee) { } } channel.disconnect(); session.disconnect(); this.testAfter = FileUtils.readFileToString(newFile); FileUtils.deleteQuietly(newFile); } catch (JSchException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SftpException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.golfmarin.golf.JsonParser.java
public JSONArray getJSONFromFile(Context ctx, String filename, String objects, String object) { // This could be a general parser that expects a file containing an objects/object hierarchy // This code uses names specific to golfcourses InputStream input; String jsonString = null;/*from w ww. j a v a 2 s. c o m*/ JSONObject golfcoursesJson = null; JSONObject golfcourseJson = null; JSONArray golfcourseJsonArray = null; Log.v("mytag", "Started getJSONFromFile:" + filename); // Read the file to a string try { input = ctx.getAssets().open(filename); int size = input.available(); byte[] buffer = new byte[size]; input.read(buffer); input.close(); jsonString = new String(buffer); } catch (Exception e) { Log.i("mytag", "Couldn't read json file " + e.toString()); } // Extract JSONArray from string try { golfcoursesJson = new JSONObject(jsonString); golfcourseJson = golfcoursesJson.getJSONObject(objects); golfcourseJsonArray = golfcourseJson.getJSONArray(object); } catch (JSONException e) { Log.i("mytag", "Couldn't parse JSON string." + e); } return golfcourseJsonArray; }
From source file:templates.commands.RemoteLauncherCommands.java
/** * Connect to a remote host via SSH and execute a command. * /*from ww w . j a v a 2s . c o m*/ * @param host * Host to connect to * @param user * User to login with * @param password * Password for the user * @param command * Command to execute * @return The result of the command execution */ private Result executeSshCommand(final String host, final String user, final String password, final String command) { StringBuilder result = new StringBuilder(); try { JSch jsch = new JSch(); Session session = jsch.getSession(user, host, 22); session.setUserInfo(createUserInfo(password)); session.connect(5000); ChannelExec channel = (ChannelExec) session.openChannel("exec"); channel.setCommand(command); channel.setInputStream(null); channel.setErrStream(System.err); InputStream in = channel.getInputStream(); channel.connect(); byte[] tmp = new byte[1024]; while (true) { while (in.available() > 0) { int i = in.read(tmp, 0, 1024); if (i < 0) break; result.append(new String(tmp, 0, i)); } if (channel.isClosed()) { break; } } channel.disconnect(); session.disconnect(); } catch (Exception jex) { return createResult(Result.Status.ERROR, jex.getMessage()); } return createResult(Result.Status.OK, result.toString()); }
From source file:com.ronnywu.browserview.client.Lv99JavascriptBridgeWebViewClient.java
/** * ?.//w w w .j a v a2s. c o m * ?APP,?. * ,?? JS . * <p/> * JS ?,???. * * @param view ?WebView * @param url URL?. */ @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); if (!openJSBridge) { return; } try { InputStream is = webView.getContext().getAssets().open("JavascriptBridge.js.txt"); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); String js = new String(buffer); executeJavascript(js); } catch (IOException e) { Toast.makeText(webView.getContext(), " JavascriptBridge.js ?/", Toast.LENGTH_LONG).show(); return; } if (startupMessageQueue != null) { for (int i = 0; i < startupMessageQueue.size(); i++) { dispatchMessage(startupMessageQueue.get(i)); } startupMessageQueue = null; } }
From source file:it.drwolf.ridire.session.JobCleaner.java
public void clean(List<String> arcFiles, List<String> digests) { try {//from www .j av a2 s . c o m List<String> origFiles = new ArrayList<String>(); List<String> endFiles = new ArrayList<String>(); for (int i = 0; i < arcFiles.size(); i++) { String origFile = FilenameUtils.getFullPath(arcFiles.get(i)).concat(JobMapperMonitor.RESOURCESDIR) .concat(digests.get(i).concat(".txt")); File cleanedFile = new File(origFile + ".2"); origFiles.add(cleanedFile.getAbsolutePath()); // duplicate orig file String cleanedText = this.ridirePlainTextCleaner.getCleanText(new File(origFile)); FileUtils.writeStringToFile(cleanedFile, cleanedText, "UTF-8"); String endFile = this.cleanerPath.concat(System.getProperty("file.separator")) .concat(digests.get(i)).concat(".txt.2"); endFiles.add(endFile); } // transfer file to process JSch jSch = new JSch(); com.jcraft.jsch.Session session = jSch.getSession(this.perlUser, "127.0.0.1"); java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.setPassword(this.perlPw); session.connect(); Channel channel = session.openChannel("sftp"); channel.connect(); ChannelSftp c = (ChannelSftp) channel; int mode = ChannelSftp.OVERWRITE; for (int i = 0; i < origFiles.size(); i++) { c.put(origFiles.get(i), endFiles.get(i), mode); } c.disconnect(); String command = null; // execute script for (String endFile : endFiles) { command = "perl " + this.cleanerPath.concat(System.getProperty("file.separator")) + "cleaner.pl "; channel = session.openChannel("exec"); ByteArrayOutputStream errorStream = new ByteArrayOutputStream(); ((ChannelExec) channel).setErrStream(errorStream); command += endFile; ((ChannelExec) channel).setCommand(command); channel.setInputStream(null); InputStream inputStream = channel.getInputStream(); channel.connect(); byte[] tmp = new byte[1024]; while (true) { while (inputStream.available() > 0) { int i = inputStream.read(tmp, 0, 1024); if (i < 0) { break; } } if (channel.isClosed()) { break; } try { Thread.sleep(200); } catch (Exception ee) { } } } channel.disconnect(); // get new files channel = session.openChannel("sftp"); channel.connect(); c = (ChannelSftp) channel; List<File> newFiles = new ArrayList<File>(); for (String endFile : endFiles) { File newFile = File.createTempFile("cleanedFile", null); newFiles.add(newFile); c.get(endFile + ".tmp", newFile.getAbsolutePath()); } c.disconnect(); // delete files from working directory channel = session.openChannel("exec"); command = "rm " + this.cleanerPath.concat(System.getProperty("file.separator")) + "*.2 " + this.cleanerPath.concat(System.getProperty("file.separator")) + "*.2.tmp"; ((ChannelExec) channel).setCommand(command); channel.setInputStream(null); channel.connect(); channel.disconnect(); session.disconnect(); for (int i = 0; i < origFiles.size(); i++) { File origF = new File(origFiles.get(i)); FileUtils.deleteQuietly(origF); FileUtils.moveFile(newFiles.get(i), origF); } for (int i = 0; i < origFiles.size(); i++) { this.ridireReTagger.retagFile(new File(origFiles.get(i))); } } catch (JSchException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SftpException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:importer.handler.post.ImporterPostHandler.java
/** * Parse the import params from the request * @param request the http request/*from w w w . j a v a 2s . c o m*/ */ void parseImportParams(HttpServletRequest request) throws AeseException { try { FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List items = upload.parseRequest(request); for (int i = 0; i < items.size(); i++) { FileItem item = (FileItem) items.get(i); if (item.isFormField()) { String fieldName = item.getFieldName(); if (fieldName != null) { String contents = item.getString(); if (fieldName.equals(Params.DOCID)) { if (contents.startsWith("/")) { contents = contents.substring(1); int pos = contents.indexOf("/"); if (pos != -1) { database = contents.substring(0, pos); contents = contents.substring(pos + 1); } } docid = contents; } else if (fieldName.startsWith(Params.SHORT_VERSION)) nameMap.put(fieldName.substring(Params.SHORT_VERSION.length()), item.getString()); else if (fieldName.equals(Params.LC_STYLE) || fieldName.equals(Params.STYLE) || fieldName.equals(Params.CORFORM)) { jsonKeys.put(fieldName.toLowerCase(), contents); style = contents; } else if (fieldName.equals(Params.DEMO)) { if (contents != null && contents.equals("brillig")) demo = false; else demo = true; } else if (fieldName.equals(Params.TITLE)) title = contents; else if (fieldName.equals(Params.FILTER)) filterName = contents.toLowerCase(); else if (fieldName.equals(Params.SIMILARITY)) similarityTest = contents != null && contents.equals("1"); else if (fieldName.equals(Params.SPLITTER)) splitterName = contents; else if (fieldName.equals(Params.STRIPPER)) stripperName = contents; else if (fieldName.equals(Params.TEXT)) textName = contents.toLowerCase(); else if (fieldName.equals(Params.DICT)) dict = contents; else if (fieldName.equals(Params.ENCODING)) encoding = contents; else if (fieldName.equals(Params.HH_EXCEPTIONS)) hhExceptions = contents; else jsonKeys.put(fieldName, contents); } } else if (item.getName().length() > 0) { try { // assuming that the contents are text //item.getName retrieves the ORIGINAL file name String type = item.getContentType(); if (type != null && type.startsWith("image/")) { InputStream is = item.getInputStream(); ByteHolder bh = new ByteHolder(); while (is.available() > 0) { byte[] b = new byte[is.available()]; is.read(b); bh.append(b); } ImageFile iFile = new ImageFile(item.getName(), item.getContentType(), bh.getData()); images.add(iFile); } else { byte[] rawData = item.get(); guessEncoding(rawData); //System.out.println(encoding); File f = new File(item.getName(), new String(rawData, encoding)); files.add(f); } } catch (Exception e) { throw new AeseException(e); } } } if (style == null) style = DEFAULT_STYLE; } catch (Exception e) { throw new AeseException(e); } }
From source file:com.concentricsky.android.khanacademy.data.KADataService.java
@Override public void onCreate() { Log.d(LOG_TAG, "onCreate"); helper = OpenHelperManager.getHelper(this, DatabaseHelper.class); InputStream is = getResources().openRawResource(R.raw.oauth_credentials); byte[] buffer; try {//from w w w . j a v a 2 s . c o m buffer = new byte[is.available()]; while (is.read(buffer) != -1) ; String jsontext = new String(buffer); JSONObject oauthCredentials = new JSONObject(jsontext); String key = oauthCredentials.getString("OAUTH_CONSUMER_KEY"); String secret = oauthCredentials.getString("OAUTH_CONSUMER_SECRET"); api = new KAAPIAdapter(this, key, secret); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } captionManager = new CaptionManager(this); offlineVideoManager = new OfflineVideoManager(this); thumbnailManager = ThumbnailManager.getSharedInstance(this); notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); setupResponseCache(); }
From source file:net.solarnetwork.node.io.serial.rxtx.SerialPortConnection.java
@Override public byte[] drainInputBuffer() throws IOException { InputStream in = getInputStream(); int avail = in.available(); if (avail < 1) { return new byte[0]; }/*from w ww.j a v a 2 s.c om*/ eventLog.trace("Attempting to drain {} bytes from serial port", avail); byte[] result = new byte[avail]; int count = 0; while (count < result.length) { count += in.read(result, count, result.length - count); } eventLog.trace("Drained {} bytes from serial port", result.length); return result; }
From source file:de.uni_luebeck.inb.knowarc.usecases.invocation.local.LocalUseCaseInvocation.java
private void copy_stream(InputStream read, OutputStream write) throws IOException { int a = read.available(); if (a > 0) { byte[] buf = new byte[a]; read.read(buf);/*from w w w .j a v a2 s .co m*/ write.write(buf); } }
From source file:ch.entwine.weblounge.preview.jai.JAIPreviewGenerator.java
/** * Resizes the given image to what is defined by the image style and writes * the result to the output stream./*from www.j a v a 2 s. c om*/ * * @param is * the input stream * @param os * the output stream * @param format * the image format * @param style * the style * @throws IllegalArgumentException * if the image is in an unsupported format * @throws IllegalArgumentException * if the input stream is empty * @throws IOException * if reading from or writing to the stream fails * @throws OutOfMemoryError * if the image is too large to be processed in memory */ private void style(InputStream is, OutputStream os, String format, ImageStyle style) throws IllegalArgumentException, IOException, OutOfMemoryError { // Does the input stream contain any data? if (is.available() == 0) throw new IllegalArgumentException("Empty input stream was passed to image styling"); // Do we need to do any work at all? if (style == null || ImageScalingMode.None.equals(style.getScalingMode())) { logger.trace("No scaling needed, performing a noop stream copy"); IOUtils.copy(is, os); return; } SeekableStream seekableInputStream = null; RenderedOp image = null; try { // Load the image from the given input stream seekableInputStream = new FileCacheSeekableStream(is); image = JAI.create("stream", seekableInputStream); if (image == null) throw new IOException("Error reading image from input stream"); // Get the original image size int imageWidth = image.getWidth(); int imageHeight = image.getHeight(); // Resizing float scale = ImageStyleUtils.getScale(imageWidth, imageHeight, style); RenderingHints scaleHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); scaleHints.put(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); scaleHints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); scaleHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); int scaledWidth = Math.round(scale * image.getWidth()); int scaledHeight = Math.round(scale * image.getHeight()); int cropX = 0; int cropY = 0; // If either one of scaledWidth or scaledHeight is < 1.0, then // the scale needs to be adapted to scale to 1.0 exactly and accomplish // the rest by cropping. if (scaledWidth < 1.0f) { scale = 1.0f / imageWidth; scaledWidth = 1; cropY = imageHeight - scaledHeight; scaledHeight = Math.round(imageHeight * scale); } else if (scaledHeight < 1.0f) { scale = 1.0f / imageHeight; scaledHeight = 1; cropX = imageWidth - scaledWidth; scaledWidth = Math.round(imageWidth * scale); } if (scale > 1.0) { ParameterBlock scaleParams = new ParameterBlock(); scaleParams.addSource(image); scaleParams.add(scale).add(scale).add(0.0f).add(0.0f); scaleParams.add(Interpolation.getInstance(Interpolation.INTERP_BICUBIC_2)); image = JAI.create("scale", scaleParams, scaleHints); } else if (scale < 1.0) { ParameterBlock subsampleAverageParams = new ParameterBlock(); subsampleAverageParams.addSource(image); subsampleAverageParams.add(Double.valueOf(scale)); subsampleAverageParams.add(Double.valueOf(scale)); image = JAI.create("subsampleaverage", subsampleAverageParams, scaleHints); } // Cropping cropX = (int) Math.max(cropX, (float) Math.ceil(ImageStyleUtils.getCropX(scaledWidth, scaledHeight, style))); cropY = (int) Math.max(cropY, (float) Math.ceil(ImageStyleUtils.getCropY(scaledWidth, scaledHeight, style))); if ((cropX > 0 && Math.floor(cropX / 2.0f) > 0) || (cropY > 0 && Math.floor(cropY / 2.0f) > 0)) { ParameterBlock cropTopLeftParams = new ParameterBlock(); cropTopLeftParams.addSource(image); cropTopLeftParams.add(cropX > 0 ? ((float) Math.floor(cropX / 2.0f)) : 0.0f); cropTopLeftParams.add(cropY > 0 ? ((float) Math.floor(cropY / 2.0f)) : 0.0f); cropTopLeftParams.add(scaledWidth - Math.max(cropX, 0.0f)); // width cropTopLeftParams.add(scaledHeight - Math.max(cropY, 0.0f)); // height RenderingHints croppingHints = new RenderingHints(JAI.KEY_BORDER_EXTENDER, BorderExtender.createInstance(BorderExtender.BORDER_COPY)); image = JAI.create("crop", cropTopLeftParams, croppingHints); } // Write resized/cropped image encoded as JPEG to the output stream ParameterBlock encodeParams = new ParameterBlock(); encodeParams.addSource(image); encodeParams.add(os); encodeParams.add("jpeg"); JAI.create("encode", encodeParams); } catch (Throwable t) { if (t.getClass().getName().contains("ImageFormat")) { throw new IllegalArgumentException(t.getMessage()); } } finally { IOUtils.closeQuietly(seekableInputStream); if (image != null) image.dispose(); } }