Example usage for java.io BufferedOutputStream close

List of usage examples for java.io BufferedOutputStream close

Introduction

In this page you can find the example usage for java.io BufferedOutputStream close.

Prototype

@Override
public void close() throws IOException 

Source Link

Document

Closes this output stream and releases any system resources associated with the stream.

Usage

From source file:eu.esdihumboldt.hale.io.geoserver.AbstractResource.java

/**
 * @see eu.esdihumboldt.hale.io.geoserver.Resource#write(java.io.OutputStream)
 *///  w ww  .  ja v  a  2 s  .c  om
@Override
public void write(OutputStream out) throws IOException {

    // unset unspecified variables by setting their value to null
    for (String var : this.allowedAttributes) {
        if (!this.attributes.containsKey(var)) {
            this.attributes.put(var, null);
        }
    }

    InputStream resourceStream = locateResource();
    if (resourceStream != null) {
        BufferedInputStream input = new BufferedInputStream(resourceStream);
        BufferedOutputStream output = new BufferedOutputStream(out);
        try {

            for (int b = input.read(); b >= 0; b = input.read()) {
                output.write(b);
            }
        } finally {
            try {
                input.close();
            } catch (IOException e) {
                // ignore exception on close
            }
            try {
                output.close();
            } catch (IOException e) {
                // ignore exception on close
            }
        }
    }

}

From source file:org.iti.agrimarket.service.OfferProductRestController.java

/**
 * is responsible to Get add offer//from   w  ww .j  a  v  a  2 s  .  c  o  m
 *
 * @author Muhammad
 * @param offer it's belongs to UserOfferProduct class mapping all its
 * properties
 * @return JSON Success word if added successfully or some of error codes
 */
@RequestMapping(value = ADD_OFFER_URL, method = RequestMethod.POST)
public Response addOffer(@RequestBody String offer) {

    //convert JSON parameter to Object
    UserOfferProductFixed offerProductFixed = paramExtractor.getParam(offer, UserOfferProductFixed.class);

    if (offerProductFixed != null && offerProductFixed.getProduct() != null
            && offerProductFixed.getUser() != null && offerProductFixed.getUser().getId() != 0
            && offerProductFixed.getUnitByUnitId() != null
            && offerProductFixed.getUnitByUnitId().getId() != null
            && offerProductFixed.getUnitByPricePerUnitId() != null
            && offerProductFixed.getUnitByPricePerUnitId().getId() != null
            && offerProductFixed.getStartDate() != null) {
        offerProductFixed.setRecommended(false);
        //check if product & user & unit are already exists! 
        User userObject = userService.getUser(offerProductFixed.getUser().getId());
        Product product = productServiceInterface.getProduct(offerProductFixed.getProduct().getId());
        Unit unit = unitService.getUnit(offerProductFixed.getUnitByUnitId().getId());

        if (userObject == null || product == null || unit == null) {
            logger.error(Constants.INVALID_PARAM);
            return Response.status(Constants.PARAM_ERROR).entity(Constants.INVALID_PARAM).build();
        }
        //            offerProductFixed.setImageUrl("images" + file.getName());
        int check = offerService.addOffer(offerProductFixed);
        if (check == -1) // if the object doesn't added
        {
            logger.error(Constants.DB_ERROR);
            return Response.status(Constants.DB_ERROR).build();
        }
        String name = offerProductFixed.getId() + String.valueOf(new Date().getTime());
        if (offerProductFixed.getImage() != null) {
            try {
                byte[] bytes = offerProductFixed.getImage();
                MagicMatch match = Magic.getMagicMatch(bytes);
                final String ext = "." + match.getExtension();

                File parentDir = new File(Constants.IMAGE_PATH + Constants.OFFER_PATH);
                if (!parentDir.isDirectory()) {
                    parentDir.mkdirs();
                }

                BufferedOutputStream stream = new BufferedOutputStream(
                        new FileOutputStream(new File(Constants.IMAGE_PATH + Constants.OFFER_PATH + name)));
                stream.write(bytes);

                stream.close();
                offerProductFixed.setImageUrl(Constants.IMAGE_PRE_URL + Constants.OFFER_PATH + name + ext);
                offerService.updateOffer(offerProductFixed);
            } catch (Exception e) {
                logger.error(e.getMessage());
                offerService.deleteOffer(check); // delete the offer if something goes wrong
                return Response.status(Constants.SERVER_ERROR).entity(Constants.IMAGE_UPLOAD_ERROR).build();
            }
        } else {
            logger.error(Constants.IMAGE_UPLOAD_ERROR);
            offerService.deleteOffer(check); // delete the offer if something goes wrong
            return Response.status(Constants.SERVER_ERROR).entity(Constants.IMAGE_UPLOAD_ERROR).build();
        }
        //if request happened successfully.
        return Response.ok(Constants.SUCCESS_JSON, MediaType.APPLICATION_JSON).build();
    } else {
        // if there are invalid or missing parameters
        logger.error(Constants.INVALID_PARAM);
        return Response.status(Constants.PARAM_ERROR).entity(Constants.INVALID_PARAM).build();
    }

}

From source file:ai.api.AIDataService.java

protected String doTextRequest(@NonNull final String endpoint, @NonNull final String requestJson,
        @Nullable final Map<String, String> additionalHeaders)
        throws MalformedURLException, AIServiceException {

    HttpURLConnection connection = null;

    try {// ww  w. j av  a 2  s.  com

        final URL url = new URL(endpoint);

        final String queryData = requestJson;

        Log.d(TAG, "Request json: " + queryData);

        if (config.getProxy() != null) {
            connection = (HttpURLConnection) url.openConnection(config.getProxy());
        } else {
            connection = (HttpURLConnection) url.openConnection();
        }

        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.addRequestProperty("Authorization", "Bearer " + config.getApiKey());
        connection.addRequestProperty("Content-Type", "application/json; charset=utf-8");
        connection.addRequestProperty("Accept", "application/json");

        if (additionalHeaders != null) {
            for (final Map.Entry<String, String> entry : additionalHeaders.entrySet()) {
                connection.addRequestProperty(entry.getKey(), entry.getValue());
            }
        }

        connection.connect();

        final BufferedOutputStream outputStream = new BufferedOutputStream(connection.getOutputStream());
        IOUtils.write(queryData, outputStream, Charsets.UTF_8);
        outputStream.close();

        final InputStream inputStream = new BufferedInputStream(connection.getInputStream());
        final String response = IOUtils.toString(inputStream, Charsets.UTF_8);
        inputStream.close();

        return response;
    } catch (final IOException e) {
        if (connection != null) {
            try {
                final InputStream errorStream = connection.getErrorStream();
                if (errorStream != null) {
                    final String errorString = IOUtils.toString(errorStream, Charsets.UTF_8);
                    Log.d(TAG, "" + errorString);
                    return errorString;
                } else {
                    throw new AIServiceException("Can't connect to the api.ai service.", e);
                }
            } catch (final IOException ex) {
                Log.w(TAG, "Can't read error response", ex);
            }
        }
        Log.e(TAG,
                "Can't make request to the API.AI service. Please, check connection settings and API access token.",
                e);
        throw new AIServiceException(
                "Can't make request to the API.AI service. Please, check connection settings and API access token.",
                e);

    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }

}

From source file:ca.licef.lompad.Classification.java

private String getQuery(String queryId, Object... params) throws java.io.IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    BufferedOutputStream bos = new BufferedOutputStream(baos);
    InputStream is = getClass().getResourceAsStream("/queries/" + queryId);

    BufferedInputStream bis = new BufferedInputStream(is);
    try {//w  w w. ja v a  2 s.c  om
        IOUtil.copy(bis, bos);
    } finally {
        bis.close();
        bos.close();
    }
    String rawQuery = baos.toString("UTF-8");
    if (params == null || params.length == 0)
        return (rawQuery);

    String query = MessageFormat.format(rawQuery, params);
    return (query);
}

From source file:com.twotoasters.android.horizontalimagescroller.io.ImageCacheManager.java

private void putBitmapToCaches(InputStream is, ImageUrlRequest imageUrlRequest) throws IOException {
    FlushedInputStream fis = new FlushedInputStream(is);
    Bitmap bitmap = null;/*from   ww  w  .j av  a 2  s. com*/
    try {
        bitmap = BitmapHelper.decodeSampledBitmapFromSteam(fis, imageUrlRequest.getReqWidth(),
                imageUrlRequest.getReqHeight());
        memoryCache.put(imageUrlRequest.getCacheKey(), bitmap);
    } catch (OutOfMemoryError e) {
        Log.v(TAG, "writeToExternalStorage - Out of memory");
        System.gc();
    }

    if (bitmap != null) {
        createFileIfNonexistent(imageUrlRequest);
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(openImageFileByUrl(imageUrlRequest)), 65535);
        bitmap.compress(Bitmap.CompressFormat.PNG, 0, bos);
        bos.flush();
        bos.close();
    }
    fis.close();
    is.close();
}

From source file:eu.scape_project.arc2warc.identification.PayloadContent.java

private byte[] inputStreamToByteArray() throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    BufferedInputStream buffis = new BufferedInputStream(inputStream);
    BufferedOutputStream buffos = new BufferedOutputStream(baos);
    byte[] tempBuffer = new byte[BUFFER_SIZE];
    int bytesRead;
    boolean firstByteArray = true;
    while ((bytesRead = buffis.read(tempBuffer)) != -1) {
        buffos.write(tempBuffer, 0, bytesRead);
        if (applyIdentification && firstByteArray && tempBuffer != null && bytesRead > 0) {
            identified = identifyPayloadType(tempBuffer);
        }//from ww  w. j  av  a2  s . c  om
        firstByteArray = false;
    }
    buffis.close();
    buffos.flush();
    buffos.close();

    return baos.toByteArray();
}

From source file:de.document.service.MedikamentService.java

public String transferToFile(MultipartFile file) throws Throwable {
    String filePath2 = Thread.currentThread().getContextClassLoader().getResource("medikament") + "\\"
            + file.getOriginalFilename();
    String filePath = filePath2.substring(6);

    if (!file.isEmpty()) {
        try {/*from  w w  w .java2  s .  c o  m*/
            byte[] bytes = file.getBytes();
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
            stream.write(bytes);
            stream.close();
            return filePath;

        } catch (Exception e) {
            System.out.println("You failed to upload " + file.getOriginalFilename() + " => " + e.getMessage());
        }
    } else {
        System.out
                .println("You failed to upload " + file.getOriginalFilename() + " because the file was empty.");
    }
    return null;
}

From source file:org.jboss.ejb3.packagemanager.retriever.impl.HttpPackageRetriever.java

/**
 * @see org.jboss.ejb3.packagemanager.retriever.PackageRetriever#retrievePackage(PackageManagerContext, URL)
 *///ww  w.  j  av a  2 s. c o m
@Override
public File retrievePackage(PackageManagerContext pkgMgrCtx, URL packagePath) throws PackageRetrievalException {
    if (!packagePath.getProtocol().equals("http")) {
        throw new PackageRetrievalException("Cannot handle " + packagePath);
    }
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(packagePath.toExternalForm());
    HttpResponse httpResponse = null;
    try {
        httpResponse = httpClient.execute(httpGet);
    } catch (Exception e) {
        throw new PackageRetrievalException("Exception while retrieving package " + packagePath, e);
    }
    if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new PackageRetrievalException("Http retrieval wasn't successful, returned status code  "
                + httpResponse.getStatusLine().getStatusCode());
    }
    HttpEntity httpEntity = httpResponse.getEntity();

    try {
        // TODO: should this tmp be deleted on exit?
        File tmpPkgFile = File.createTempFile("tmp", ".jar",
                pkgMgrCtx.getPackageManagerEnvironment().getPackageManagerTmpDir());
        FileOutputStream fos = new FileOutputStream(tmpPkgFile);
        BufferedOutputStream bos = null;
        BufferedInputStream bis = null;
        try {
            bos = new BufferedOutputStream(fos);
            InputStream is = httpEntity.getContent();
            bis = new BufferedInputStream(is);
            byte[] content = new byte[4096];
            int length;
            while ((length = bis.read(content)) != -1) {
                bos.write(content, 0, length);
            }
            bos.flush();
        } finally {
            if (bos != null) {
                bos.close();
            }
            if (bis != null) {
                bis.close();
            }
        }
        return tmpPkgFile;

    } catch (IOException ioe) {
        throw new PackageRetrievalException("Could not process the retrieved package", ioe);
    }
    // TODO: I need to read the HttpClient 4.x javadocs to figure out the API for closing the
    // Http connection

}

From source file:com.vtls.opensource.jhove.JHOVEDocumentFactory.java

/**
 * Get a JHOVE Document from a {@link URL} source
 * @param _uri  a resource URL/*w  w  w.j av  a  2 s.  co  m*/
 * @param _stream an input stream code
 * @return a JDOM Document
 * @throws IOException 
 * @throws JDOMException 
 */
public Document getDocument(InputStream _stream, String _uri) throws IOException, JDOMException {
    RepInfo representation = new RepInfo(_uri);

    File file = File.createTempFile("vtls-jhove-", "");
    file.deleteOnExit();

    BufferedOutputStream output_stream = new BufferedOutputStream(new FileOutputStream(file));
    BufferedInputStream input_stream = new BufferedInputStream(_stream);

    int stream_byte;
    while ((stream_byte = input_stream.read()) != -1) {
        output_stream.write(stream_byte);
    }

    output_stream.flush();
    output_stream.close();
    input_stream.close();

    representation.setSize(file.length());
    representation.setLastModified(new Date());
    populateRepresentation(representation, file);

    file.delete();

    return getDocumentFromRepresentation(representation);
}

From source file:org.fcrepo.localservices.imagemanip.ImageManipulation.java

/**
 * Method automatically called by browser to handle image manipulations.
 * // www  .j ava  2 s  .  c  om
 * @param req
 *        Browser request to servlet res Response sent back to browser after
 *        image manipulation
 * @throws IOException
 *         If an input or output exception occurred ServletException If a
 *         servlet exception occurred
 */
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    System.setProperty("java.awt.headless", "true");
    // collect all possible parameters for servlet
    String url = req.getParameter("url");
    String op = req.getParameter("op");
    String newWidth = req.getParameter("newWidth");
    String brightAmt = req.getParameter("brightAmt");
    String zoomAmt = req.getParameter("zoomAmt");
    String wmText = req.getParameter("wmText");
    String cropX = req.getParameter("cropX");
    String cropY = req.getParameter("cropY");
    String cropWidth = req.getParameter("cropWidth");
    String cropHeight = req.getParameter("cropHeight");
    String convertTo = req.getParameter("convertTo");
    if (convertTo != null) {
        convertTo = convertTo.toLowerCase();
    }
    try {
        if (op == null) {
            throw new ServletException("op parameter not specified.");
        }
        String outputMimeType;
        // get the image via url and put it into the ImagePlus processor.
        BufferedImage img = getImage(url);
        // do watermarking stuff
        if (op.equals("watermark")) {
            if (wmText == null) {
                throw new ServletException("Must specify wmText.");
            }
            Graphics g = img.getGraphics();
            int fontSize = img.getWidth() * 3 / 100;
            if (fontSize < 10) {
                fontSize = 10;
            }
            g.setFont(new Font("Lucida Sans", Font.BOLD, fontSize));
            FontMetrics fm = g.getFontMetrics();
            int stringWidth = (int) fm.getStringBounds(wmText, g).getWidth();
            int x = img.getWidth() / 2 - stringWidth / 2;
            int y = img.getHeight() - fm.getHeight();
            g.setColor(new Color(180, 180, 180));
            g.fill3DRect(x - 10, y - fm.getHeight() - 4, stringWidth + 20, fm.getHeight() + 12, true);
            g.setColor(new Color(100, 100, 100));
            g.drawString(wmText, x + 2, y + 2);
            g.setColor(new Color(240, 240, 240));
            g.drawString(wmText, x, y);
        }
        ImageProcessor ip = new ImagePlus("temp", img).getProcessor();
        // if the inputMimeType is image/gif, need to convert to RGB in any case
        if (inputMimeType.equals("image/gif")) {
            ip = ip.convertToRGB();
            alreadyConvertedToRGB = true;
        }
        // causes scale() and resize() to do bilinear interpolation
        ip.setInterpolate(true);
        if (!op.equals("convert")) {
            if (op.equals("resize")) {
                ip = resize(ip, newWidth);
            } else if (op.equals("zoom")) {
                ip = zoom(ip, zoomAmt);
            } else if (op.equals("brightness")) {
                ip = brightness(ip, brightAmt);
            } else if (op.equals("watermark")) {
                // this is now taken care of beforehand (see above)
            } else if (op.equals("grayscale")) {
                ip = grayscale(ip);
            } else if (op.equals("crop")) {
                ip = crop(ip, cropX, cropY, cropWidth, cropHeight);
            } else {
                throw new ServletException("Invalid operation: " + op);
            }
            outputMimeType = inputMimeType;
        } else {
            if (convertTo == null) {
                throw new ServletException("Neither op nor convertTo was specified.");
            }
            if (convertTo.equals("jpg") || convertTo.equals("jpeg")) {
                outputMimeType = "image/jpeg";
            } else if (convertTo.equals("gif")) {
                outputMimeType = "image/gif";
            } else if (convertTo.equals("tiff")) {
                outputMimeType = "image/tiff";
            } else if (convertTo.equals("bmp")) {
                outputMimeType = "image/bmp";
            } else if (convertTo.equals("png")) {
                outputMimeType = "image/png";
            } else {
                throw new ServletException("Invalid format: " + convertTo);
            }
        }
        res.setContentType(outputMimeType);
        BufferedOutputStream out = new BufferedOutputStream(res.getOutputStream());
        outputImage(ip, out, outputMimeType);
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
        res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                e.getClass().getName() + ": " + e.getMessage());
    }
}