List of usage examples for java.io InputStream available
public int available() throws IOException
From source file:net.sf.ginp.TestGinpModel.java
/** * JUnit setup helper method/*from w w w .ja v a 2s.c om*/ * *@throws IOException *@throws SetupException */ protected void setupTestJpeg() { // grab the test jpeg from the testing classpath InputStream picture = this.getClass().getResourceAsStream(File.separator + PICTURE_FILE_NAME); FileOutputStream outPic = null; int size = 0; try { size = picture.available(); if (size > 0) { byte[] buffer = new byte[size]; int i = picture.read(buffer); outPic = new FileOutputStream(PICTURE_FILE_LOCATION); outPic.write(buffer); outPic.flush(); } } catch (IOException ioe) { fail("cannot create test jpeg file:" + ioe); } finally { try { if (picture != null) { picture.close(); } if (outPic != null) { outPic.close(); } } catch (IOException ioe) { fail("error closing test jpeg file:" + ioe); } } }
From source file:com.theultimatelabs.scale.ScaleActivity.java
public JSONObject loadJsonResource(int id) { InputStream stream = getResources().openRawResource(id); byte[] buffer; try {/*from w w w.j av a2s . co m*/ buffer = new byte[stream.available()]; int bytesRead = stream.read(buffer); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } JSONObject json; try { json = new JSONObject(new String(buffer)); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } return json; }
From source file:ch.entwine.weblounge.preview.imagemagick.ImageMagickPreviewGenerator.java
/** * Resizes the given image to what is defined by the image style and writes * the result to the output stream./*from w w w.j a v a2 s. c o m*/ * * @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 */ @SuppressWarnings("cast") 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; } String uuid = UUID.randomUUID().toString(); File originalFile = new File(imageMagickDir, "image-" + uuid + "." + format); File scaledFile = new File(imageMagickDir, "image-scaled-" + uuid + "." + format); File croppedFile = new File(imageMagickDir, "image-cropped-" + uuid + "." + format); try { File finalFile = null; FileOutputStream fos = new FileOutputStream(originalFile); IOUtils.copy(is, fos); IOUtils.closeQuietly(fos); IOUtils.closeQuietly(is); // Load the image from the temporary file Info imageInfo = new Info(originalFile.getAbsolutePath(), true); // Get the original image size int imageWidth = imageInfo.getImageWidth(); int imageHeight = imageInfo.getImageHeight(); // Prepare for processing ConvertCmd imageMagick = new ConvertCmd(); // Resizing float scale = ImageStyleUtils.getScale(imageWidth, imageHeight, style); int scaledWidth = Math.round(scale * imageWidth); int scaledHeight = Math.round(scale * imageHeight); 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); } // Do the scaling IMOperation scaleOp = new IMOperation(); scaleOp.addImage(originalFile.getAbsolutePath()); scaleOp.resize((int) scaledWidth, (int) scaledHeight); scaleOp.addImage(scaledFile.getAbsolutePath()); imageMagick.run(scaleOp); finalFile = scaledFile; // Cropping cropX = (int) Math.max(cropX, Math.ceil(ImageStyleUtils.getCropX(scaledWidth, scaledHeight, style))); cropY = (int) Math.max(cropY, Math.ceil(ImageStyleUtils.getCropY(scaledWidth, scaledHeight, style))); if ((cropX > 0 && Math.floor(cropX / 2.0f) > 0) || (cropY > 0 && Math.floor(cropY / 2.0f) > 0)) { int croppedLeft = (int) (cropX > 0 ? ((float) Math.floor(cropX / 2.0f)) : 0.0f); int croppedTop = (int) (cropY > 0 ? ((float) Math.floor(cropY / 2.0f)) : 0.0f); int croppedWidth = (int) (scaledWidth - Math.max(cropX, 0.0f)); int croppedHeight = (int) (scaledHeight - Math.max(cropY, 0.0f)); // Do the cropping IMOperation cropOperation = new IMOperation(); cropOperation.addImage(scaledFile.getAbsolutePath()); cropOperation.crop(croppedWidth, croppedHeight, croppedLeft, croppedTop); cropOperation.p_repage(); // Reset the page canvas and position to match // the actual cropped image cropOperation.addImage(croppedFile.getAbsolutePath()); imageMagick.run(cropOperation); finalFile = croppedFile; } // Write resized/cropped image encoded as JPEG to the output stream FileInputStream fis = null; try { fis = new FileInputStream(finalFile); IOUtils.copy(fis, os); } finally { IOUtils.closeQuietly(fis); } } catch (Throwable t) { throw new IllegalArgumentException(t.getMessage()); } finally { FileUtils.deleteQuietly(originalFile); FileUtils.deleteQuietly(scaledFile); FileUtils.deleteQuietly(croppedFile); } }
From source file:it.cnr.icar.eric.server.interfaces.rest.URLHandler.java
void writeRepositoryItem(ExtrinsicObjectType eo) throws IOException, RegistryException, ObjectNotFoundException { String id = eo.getId();/* w ww. j ava 2s .c o m*/ ServerRequestContext context = new ServerRequestContext("URLHandler.writeRepositoryItem", null); try { RepositoryItem ri = QueryManagerFactory.getInstance().getQueryManager().getRepositoryItem(context, id); if (ri == null) { throw new ObjectNotFoundException(id, ServerResourceBundle.getInstance().getString("message.repositoryItem")); } else { response.setContentType(eo.getMimeType()); DataHandler dataHandler = ri.getDataHandler(); ServletOutputStream sout = response.getOutputStream(); InputStream fStream = dataHandler.getInputStream(); int bytesSize = fStream.available(); byte[] b = new byte[bytesSize]; fStream.read(b); sout.write(b); sout.close(); } context.commit(); context = null; } finally { if (context != null) { context.rollback(); } } }
From source file:com.datatorrent.lib.io.HttpInputOperator.java
@Override public void run() { while (super.isActive()) { try {//from w w w . j a v a 2s .c o m ClientResponse response = resource.header("x-stream", "rockon").accept(MediaType.APPLICATION_JSON) .get(ClientResponse.class); LOG.debug("Opening stream: " + resource); // media type check, if any, should be configuration based //if (!MediaType.APPLICATION_JSON_TYPE.equals(response.getType())) { // LOG.error("Unexpected response type " + response.getType()); // response.close(); //} else { InputStream is = response.getEntity(java.io.InputStream.class); while (true) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] bytes = new byte[255]; int bytesRead; while ((bytesRead = is.read(bytes)) != -1) { LOG.debug("read {} bytes", bytesRead); bos.write(bytes, 0, bytesRead); if (is.available() == 0 && bos.size() > 0) { // give chance to process what we have before blocking on read break; } } if (processBytes(bos.toByteArray())) { LOG.debug("End of chunked input stream."); response.close(); break; } if (bytesRead == -1) { LOG.error("Unexpected end of chunked input stream"); response.close(); break; } bos.reset(); } //} } catch (Exception e) { LOG.error("Error reading from " + resource.getURI(), e); } try { Thread.sleep(500); } catch (InterruptedException e) { LOG.info("Exiting IO loop {}.", e.toString()); break; } } }
From source file:com.ideabase.repository.test.webservice.RESTfulControllerTest.java
private String fixContent() throws IOException { final InputStream inputStream = getClass().getClassLoader().getResourceAsStream("save-format.xml"); byte[] data = new byte[inputStream.available()]; inputStream.read(data, 0, data.length); return new String(data); }
From source file:org.dataone.proto.trove.mn.rest.v1.ObjectController.java
/** * return the object requested//from ww w.j av a2s. c o m * * @param request * @param response * @param pid * @throws InvalidToken * @throws ServiceFailure * @throws IOException * @throws NotAuthorized * @throws NotFound * @throws NotImplemented */ @RequestMapping(value = "/v1/object/{pid}", method = RequestMethod.GET) public void get(HttpServletRequest request, HttpServletResponse response, @PathVariable String pid) throws InvalidToken, ServiceFailure, IOException, NotAuthorized, NotFound, NotImplemented, InvalidRequest, InsufficientResources { debugRequest(request); Identifier id = new Identifier(); try { id.setValue(urlCodec.decode(pid, "UTF-8")); } catch (DecoderException ex) { throw new ServiceFailure("20000", ex.getMessage()); } catch (UnsupportedEncodingException ex) { throw new ServiceFailure("20001", ex.getMessage()); } if (!logRequest(request, Event.READ, id)) { throw new ServiceFailure("20001", "unable to log request"); } Session session = new Session(); if (!this.logRequest(request, Event.READ, id)) { throw new ServiceFailure("20001", "unable to log request"); } InputStream in = mnRead.get(id); OutputStream out = response.getOutputStream(); try { byte[] buffer = null; int filesize = in.available(); if (filesize < 250000) { buffer = new byte[SMALL_BUFF_SIZE]; } else if (filesize >= 250000 && filesize <= 500000) { buffer = new byte[MED_BUFF_SIZE]; } else { buffer = new byte[LARGE_BUFF_SIZE]; } while (true) { int amountRead = in.read(buffer); if (amountRead == -1) { break; } out.write(buffer, 0, amountRead); out.flush(); } } finally { if (in != null) { in.close(); } if (out != null) { out.flush(); out.close(); } } }
From source file:com.esminis.server.mariadb.server.MariaDbServerLauncher.java
void initializeDataDirectory(Context context, File binary, File root) throws IOException { File[] files = root.listFiles(); if (files != null && files.length > 0) { return;/*from ww w . j av a 2 s. co m*/ } synchronized (lock) { final List<String> environment = getEnvironment(); final List<String> command = createCommandInternal(context, binary, root); Collections.addAll(command, "--bootstrap", "--log-warnings=0", "--max_allowed_packet=8M", "--net_buffer_length=16K"); final File dataMysqlDirectory = new File(root, "mysql"); if (dataMysqlDirectory.isDirectory()) { return; } if (!dataMysqlDirectory.mkdirs()) { throw new IOException("Cannot create directory: " + dataMysqlDirectory.getAbsolutePath()); } final Process process = Runtime.getRuntime().exec(command.toArray(new String[command.size()]), environment.toArray(new String[environment.size()]), root); final Object[] finishedWithError = { null }; try { final OutputStream stream = process.getOutputStream(); Observable.create(new Observable.OnSubscribe<Void>() { @Override public void call(Subscriber<? super Void> subscriber) { final InputStream inputStream = process.getErrorStream(); String data = ""; for (;;) { synchronized (finishedWithError) { if (finishedWithError[0] != null) { break; } } try { int available = inputStream.available(); if (available > 0) { for (int i = 0; i < available; i++) { data += (char) inputStream.read(); } if (getFreeSpace(dataMysqlDirectory) < 1024L * 1024L || data.contains("No space left on device")) { synchronized (finishedWithError) { finishedWithError[0] = new IOException("No space left on device"); } process.destroy(); break; } } } catch (Throwable ignored) { } Thread.yield(); } subscriber.onCompleted(); } }).subscribeOn(Schedulers.newThread()).subscribe(); writeToStream(stream, "use mysql;\n"); writeToStream(stream, context, "sql/mysql_system_tables.sql"); writeToStream(stream, context, "sql/mysql_performance_tables.sql"); writeToStream(stream, context, "sql/mysql_system_tables_data.sql"); writeToStream(stream, context, "sql/add_root_from_any_host.sql"); writeToStream(stream, context, "sql/fill_help_tables.sql"); writeToStream(stream, "exit;\n"); process.waitFor(); } catch (Throwable e) { FileUtils.deleteDirectory(root); //noinspection ResultOfMethodCallIgnored root.mkdirs(); synchronized (finishedWithError) { if (finishedWithError[0] != null && finishedWithError[0] instanceof IOException) { throw (IOException) finishedWithError[0]; } else { throw new IOException( e.toString() + "\n\nLog:\n" + IOUtils.toString(process.getErrorStream())); } } } finally { synchronized (finishedWithError) { if (finishedWithError[0] == null) { finishedWithError[0] = true; } } } } }
From source file:com.ideabase.repository.test.webservice.RESTfulControllerTest.java
private String fixUpdateRequest(final Integer pId) throws IOException { final InputStream inputStream = getClass().getClassLoader().getResourceAsStream("update-format.xml"); byte[] data = new byte[inputStream.available()]; inputStream.read(data, 0, data.length); final String text = new String(data); return text.replaceAll("#ID#", String.valueOf(pId)); }
From source file:com.persistent.cloudninja.scheduler.StorageUtility.java
/** * Retrieves a message from queue.//from ww w.j a va 2 s. co m * * @param queueName * @return : the message contents. * @throws InvalidKeyException * @throws URISyntaxException * @throws StorageException * @throws IOException */ public CloudQueueMessage getMessage(String queueName) throws InvalidKeyException, URISyntaxException, StorageException, IOException { //this queue will be different for diff tasks CloudQueue queue = queueClient.getQueueReference(queueName.toLowerCase()); CloudQueueMessage message = queue.retrieveMessage(VISIBILITY_TIMEOUT_SEC, null, null); //if dequeue count is greater than 3 then delete the message if (message != null && message.getDequeueCount() > MAX_DEQUEUE_COUNT) { // make the entry of the message as a poison message CloudBlobContainer container = blobClient.getContainerReference("poison-messages"); CloudBlob blob = container.getBlockBlobReference(message.getId()); InputStream stream = new ByteArrayInputStream(message.getMessageContentAsByte()); blob.upload(stream, stream.available()); // delete the message queue.deleteMessage(message); message = null; } return message; }