Example usage for java.io BufferedInputStream close

List of usage examples for java.io BufferedInputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

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

Usage

From source file:com.nabla.dc.server.ImageService.java

private boolean exportImage(final String imageId, final HttpServletResponse response)
        throws IOException, SQLException, InternalErrorException {
    final Connection conn = db.getConnection();
    try {/* ww w .  j  av  a2 s .  c o m*/
        final PreparedStatement stmt = StatementFormat.prepare(conn, "SELECT * FROM image WHERE id=?;",
                imageId);
        try {
            final ResultSet rs = stmt.executeQuery();
            try {
                if (!rs.next()) {
                    if (log.isDebugEnabled())
                        log.debug("failed to find report ID= " + imageId);
                    return false;
                }
                if (log.isTraceEnabled())
                    log.trace("exporting image " + imageId);
                response.reset();
                response.setBufferSize(DEFAULT_BUFFER_SIZE);
                response.setContentType(rs.getString("content_type"));
                response.setHeader("Content-Length", String.valueOf(rs.getInt("length")));
                response.setHeader("Content-Disposition",
                        MessageFormat.format("inline; filename=\"{0}\"", rs.getString("name")));
                // to prevent images to be downloaded every time user hovers one image
                final Calendar cal = Calendar.getInstance();
                cal.setTime(new Date());
                cal.add(Calendar.MONTH, 2);
                response.setDateHeader("Expires", cal.getTime().getTime());
                final BufferedInputStream input = new BufferedInputStream(rs.getBinaryStream("content"),
                        DEFAULT_BUFFER_SIZE);
                try {
                    final BufferedOutputStream output = new BufferedOutputStream(response.getOutputStream(),
                            DEFAULT_BUFFER_SIZE);
                    try {
                        final byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
                        int length;
                        while ((length = input.read(buffer)) > 0)
                            output.write(buffer, 0, length);
                    } finally {
                        output.close();
                    }
                } finally {
                    input.close();
                }
            } finally {
                rs.close();
            }
        } finally {
            stmt.close();
        }
    } finally {
        conn.close();
    }
    return true;
}

From source file:net.paissad.waqtsalat.utils.UncompressUtils.java

/**
 * Implements different methods for creating InputStream from the source
 * file./* w w  w.j av a 2  s  . c  om*/
 * 
 * @param method
 *            Method to use to uncompress the file to an InputStream.
 * @return InputStream of the 'source' file using the specified method.
 * @throws IOException
 */
private InputStream uncompressStream(final String method) throws IOException {
    try {
        logger.trace("Converting file '{}' to inputstream.", source.getAbsolutePath());
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(source));

        if (method.equals(GUNZIP_METHOD)) {
            return new GZIPInputStream(bis); // gzip
        }

        else if (method.equals(BUNZIP_METHOD)) {
            // Let's test the validity of the .bzip2 file.
            final char[] magic = new char[] { 'B', 'Z' };
            for (int i = 0; i < magic.length; i++) {
                if (bis.read() != magic[i]) {
                    bis.close();
                    throw new RuntimeException("Invalid bz2 file: " + source.getAbsolutePath());
                }
            } // End of validity check.
              // CBZip2InputStream documentation says that the 2 first
              // bytes 'B' and 'Z' must be read !!!
            return new CBZip2InputStream(bis); // bz2
        }

        else if (method.equals(TAR_METHOD)) {
            return new TarInputStream(bis); // tar
        }

        else {
            if (bis != null)
                bis.close();
            throw new RuntimeException("Unknown method '" + method + "'.");
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
        throw new IOException("Creating inputstream failed.");
    }
}

From source file:org.apache.ofbiz.base.util.UtilHttp.java

/**
 * Stream binary content from InputStream to OutputStream
 * This method does not close the streams passed
 *
 * @param out OutputStream content should go to
 * @param in InputStream of the actual content
 * @param length Size (in bytes) of the content
 * @throws IOException// ww w. j  a va 2s.c o m
 */
public static void streamContent(OutputStream out, InputStream in, int length) throws IOException {
    int bufferSize = 512; // same as the default buffer size; change as needed

    // make sure we have something to write to
    if (out == null) {
        throw new IOException("Attempt to write to null output stream");
    }

    // make sure we have something to read from
    if (in == null) {
        throw new IOException("Attempt to read from null input stream");
    }

    // make sure we have some content
    if (length == 0) {
        throw new IOException("Attempt to write 0 bytes of content to output stream");
    }

    // initialize the buffered streams
    BufferedOutputStream bos = new BufferedOutputStream(out, bufferSize);
    BufferedInputStream bis = new BufferedInputStream(in, bufferSize);

    byte[] buffer = new byte[length];
    int read = 0;
    try {
        while ((read = bis.read(buffer, 0, buffer.length)) != -1) {
            bos.write(buffer, 0, read);
        }
    } catch (IOException e) {
        Debug.logError(e, "Problem reading/writing buffers", module);
        bis.close();
        bos.close();
        throw e;
    } finally {
        if (bis != null) {
            bis.close();
        }
        if (bos != null) {
            bos.flush();
            bos.close();
        }
    }
}

From source file:com.neusou.bioroid.image.ImageLoader.java

public Bitmap loadImage(final String imageUri, boolean immediately) {
    if (imageUri == null || imageUri.equals("null")) {
        return null;
    }//from   w  ww  . j a v a  2s  . com

    final String url;
    url = imageUri;

    if (url == null || url.compareTo("null") == 0) {
        return null;
    }

    Bitmap dcached;
    dcached = mBitmapMap.get(url);

    if (dcached != null || immediately) {
        if (dcached == null) {
            mBitmapMap.remove(url);
        }
        return dcached;
    }

    URL imageUrl = null;

    try {
        imageUrl = new URL(imageUri);
    } catch (MalformedURLException e) {
        return null;
    }

    File imageDir = new File(mCacheDirectoryPath);
    String bigInt = computeDigest(url);
    File cachedImageFile = new File(imageDir, bigInt);
    String ess = Environment.getExternalStorageState();
    boolean canReadImageCacheDir = false;

    if (ess.equals(Environment.MEDIA_MOUNTED)) {
        if (!imageDir.canRead()) {
            boolean createSuccess = false;
            synchronized (imageDir) {
                createSuccess = imageDir.mkdirs();
            }
            canReadImageCacheDir = createSuccess && imageDir.canRead();
        }
        canReadImageCacheDir = imageDir.canRead();
        if (cachedImageFile.canRead()) {
            try {
                Bitmap cachedBitmap = getCachedBitmap(imageUrl, cachedImageFile);
                if (cachedBitmap != null) {
                    mBitmapMap.put(imageUri, cachedBitmap);
                    return cachedBitmap;
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    HttpGet httpRequest = null;
    try {
        httpRequest = new HttpGet(imageUrl.toURI());
    } catch (URISyntaxException e) {
        e.printStackTrace();
        return null;
    }

    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = null;
    try {
        response = (HttpResponse) httpclient.execute(httpRequest);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

    HttpEntity entity = response.getEntity();
    BufferedHttpEntity bufHttpEntity = null;
    try {
        bufHttpEntity = new BufferedHttpEntity(entity);
        final int bufferSize = 1024 * 50;
        BufferedInputStream imageBis = new BufferedInputStream(bufHttpEntity.getContent(), bufferSize);
        long contentLength = bufHttpEntity.getContentLength();
        Bitmap decodedBitmap = decode(imageBis);
        try {
            imageBis.close();
        } catch (IOException e1) {
        }
        encode(decodedBitmap, cachedImageFile.toURL(), CompressFormat.PNG, mImageCacheQuality);
        Calendar cal = Calendar.getInstance();
        long currentTime = cal.getTime().getTime();
        if (mUseCacheDatabase) {
            mCacheRecordDbHelper.insertCacheRecord(mDb, cachedImageFile.toURL(), currentTime, contentLength);
        }
        if (decodedBitmap != null) {
            mBitmapMap.put(url, decodedBitmap);
        }
        return decodedBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.servoy.extensions.plugins.http.HttpProvider.java

/**
 * @deprecated Obsolete method./*from   w w  w  .ja v  a2s  .  c om*/
 * 
 * @clonedesc js_getMediaData(String)
 * @sampleas js_getMediaData(String)
 *
 * @param url 
 * @param clientName 
 */
@Deprecated
public byte[] js_getMediaData(String url, String clientName) {
    if (url == null || clientName == null)
        return null;
    DefaultHttpClient client = httpClients.get(clientName);
    if (client == null) {
        return null;
    }
    ByteArrayOutputStream sb = new ByteArrayOutputStream();
    try {
        setHttpClientProxy(client, url, proxyUser, proxyPassword);

        HttpGet method = new HttpGet(url);

        //for some proxies
        method.addHeader("Cache-control", "no-cache");
        method.addHeader("Pragma", "no-cache");
        //maybe mod_deflate set and wrong configured
        method.addHeader("Accept-Encoding", "gzip");
        HttpResponse res = client.execute(method);
        int statusCode = res.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            return null;
        }

        InputStream is = null;
        Header contentEncoding = res.getFirstHeader("Content-Encoding");
        boolean gziped = contentEncoding == null ? false : "gzip".equalsIgnoreCase(contentEncoding.getValue());
        is = res.getEntity().getContent();
        if (gziped) {
            is = new GZIPInputStream(is);
        }
        BufferedInputStream bis = new BufferedInputStream(is);
        Utils.streamCopy(bis, sb);
        bis.close();
        is.close();
    } catch (IOException e) {
        Debug.error(e);
    }
    return sb.toByteArray();
}

From source file:org.dswarm.graph.xml.test.XMLResourceTest.java

private void readXMLFromDB(final String recordClassURI, final String dataModelURI,
        final Optional<String> optionalRootAttributePath, final Optional<String> optionalRecordTag,
        final Optional<Integer> optionalVersion, final Optional<String> optionalOriginalDataType,
        final String expectedFileName) throws IOException {

    final ObjectMapper objectMapper = Util.getJSONObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    final ObjectNode requestJson = objectMapper.createObjectNode();

    requestJson.put(DMPStatics.RECORD_CLASS_URI_IDENTIFIER, recordClassURI);
    requestJson.put(DMPStatics.DATA_MODEL_URI_IDENTIFIER, dataModelURI);

    if (optionalRootAttributePath.isPresent()) {

        requestJson.put(DMPStatics.ROOT_ATTRIBUTE_PATH_IDENTIFIER, optionalRootAttributePath.get());
    }//from w  w w  .  j ava  2 s .c  om

    if (optionalRecordTag.isPresent()) {

        requestJson.put(DMPStatics.RECORD_TAG_IDENTIFIER, optionalRecordTag.get());
    }

    if (optionalVersion.isPresent()) {

        requestJson.put(DMPStatics.VERSION_IDENTIFIER, optionalVersion.get());
    }

    if (optionalOriginalDataType.isPresent()) {

        requestJson.put(DMPStatics.ORIGINAL_DATA_TYPE_IDENTIFIER, optionalOriginalDataType.get());
    }

    final String requestJsonString = objectMapper.writeValueAsString(requestJson);

    // POST the request
    final ClientResponse response = target().path("/get").type(MediaType.APPLICATION_JSON_TYPE)
            .accept(MediaType.APPLICATION_XML_TYPE).post(ClientResponse.class, requestJsonString);

    Assert.assertEquals("expected 200", 200, response.getStatus());
    Assert.assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());

    final InputStream actualXMLStream = response.getEntity(InputStream.class);
    Assert.assertNotNull(actualXMLStream);

    // compare result with expected result
    final URL expectedFileURL = Resources.getResource(expectedFileName);
    final String expectedXML = Resources.toString(expectedFileURL, Charsets.UTF_8);

    final BufferedInputStream bis = new BufferedInputStream(actualXMLStream, 1024);

    // do comparison: check for XML similarity
    final Diff xmlDiff = DiffBuilder.compare(Input.fromString(expectedXML)).withTest(Input.fromStream(bis))
            .ignoreWhitespace().checkForSimilar().build();

    if (xmlDiff.hasDifferences()) {
        final StringBuilder sb = new StringBuilder("Oi chap, there seem to ba a mishap!");
        for (final Difference difference : xmlDiff.getDifferences()) {
            sb.append('\n').append(difference);
        }
        Assert.fail(sb.toString());
    }

    actualXMLStream.close();
    bis.close();
}

From source file:com.aimluck.eip.services.storage.impl.ALDefaultStorageHandler.java

protected int getFileSize(File file) {
    if (file == null) {
        return -1;
    }/* ww  w  .  ja  v  a 2  s.co  m*/

    FileInputStream fileInputStream = null;
    int size = -1;
    try {
        fileInputStream = new FileInputStream(file);
        BufferedInputStream input = new BufferedInputStream(fileInputStream);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] b = new byte[512];
        int len = -1;
        while ((len = input.read(b)) != -1) {
            output.write(b, 0, len);
            output.flush();
        }
        input.close();
        fileInputStream.close();

        byte[] fileArray = output.toByteArray();
        size = fileArray.length;
        output.close();
    } catch (FileNotFoundException e) {
        return -1;
    } catch (IOException ioe) {
        return -1;
    }
    return size;
}

From source file:com.webarch.common.net.http.HttpService.java

/**
 * /*ww  w  .ja  v a 2  s.  c  om*/
 *
 * @param media_id ?ID
 * @param identity 
 * @param filepath ?(????)
 * @return ?(???)error
 */
public static String downLoadMediaFile(String requestUrl, String media_id, String identity, String filepath) {
    String mediaLocalURL = "error";
    InputStream inputStream = null;
    FileOutputStream fileOutputStream = null;
    DataOutputStream dataOutputStream = null;
    try {
        URL downLoadURL = new URL(requestUrl);
        // URL
        HttpURLConnection connection = (HttpURLConnection) downLoadURL.openConnection();
        //?
        connection.setRequestMethod("GET");
        // 
        connection.connect();
        //?,?text,json
        if (connection.getContentType().equalsIgnoreCase("text/plain")) {
            // BufferedReader???URL?
            inputStream = connection.getInputStream();
            BufferedReader read = new BufferedReader(new InputStreamReader(inputStream, DEFAULT_CHARSET));
            String valueString = null;
            StringBuffer bufferRes = new StringBuffer();
            while ((valueString = read.readLine()) != null) {
                bufferRes.append(valueString);
            }
            inputStream.close();
            String errMsg = bufferRes.toString();
            JSONObject jsonObject = JSONObject.parseObject(errMsg);
            logger.error("???" + (jsonObject.getInteger("errcode")));
            mediaLocalURL = "error";
        } else {
            BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
            String ds = connection.getHeaderField("Content-disposition");
            //??
            String fullName = ds.substring(ds.indexOf("filename=\"") + 10, ds.length() - 1);
            //?--??
            String preffix = fullName.substring(0, fullName.lastIndexOf("."));
            //?
            String suffix = fullName.substring(preffix.length() + 1);
            //
            String length = connection.getHeaderField("Content-Length");
            //
            String type = connection.getHeaderField("Content-Type");
            //
            byte[] buffer = new byte[8192]; // 8k
            int count = 0;
            mediaLocalURL = filepath + File.separator;
            File file = new File(mediaLocalURL);
            if (!file.exists()) {
                file.mkdirs();
            }
            File mediaFile = new File(mediaLocalURL, fullName);
            fileOutputStream = new FileOutputStream(mediaFile);
            dataOutputStream = new DataOutputStream(fileOutputStream);
            while ((count = bis.read(buffer)) != -1) {
                dataOutputStream.write(buffer, 0, count);
            }
            //?
            mediaLocalURL += fullName;
            bis.close();
            dataOutputStream.close();
            fileOutputStream.close();
        }
    } catch (IOException e) {
        logger.error("?", e);
    }
    return mediaLocalURL;
}

From source file:net.mybox.mybox.Common.java

/**
 * Run a system command on the local machine
 * @param command/* w  w w .  ja  v  a2s  . c  o m*/
 * @return
 */
public static SysResult syscommand(String[] command) {
    Runtime r = Runtime.getRuntime();

    SysResult result = new SysResult();

    System.out.println("syscommand array: " + StringUtils.join(command, " "));

    try {

        Process p = r.exec(command);
        // should use a thread so it can be killed if it has not finished and another one needs to be started
        InputStream in = p.getInputStream();

        InputStream stderr = p.getErrorStream();
        InputStreamReader inreadErr = new InputStreamReader(stderr);
        BufferedReader brErr = new BufferedReader(inreadErr);

        BufferedInputStream buf = new BufferedInputStream(in);
        InputStreamReader inread = new InputStreamReader(buf);
        BufferedReader bufferedreader = new BufferedReader(inread);

        // Read the ls output
        String line;
        while ((line = bufferedreader.readLine()) != null) {
            result.output += line + "\n";
            System.err.print("  output> " + result.output);
            // should check for last line "Contacting server..." after 3 seconds, to restart unison command X times
        }

        result.worked = true;

        // Check for failure
        try {
            if (p.waitFor() != 0) {
                System.err.println("exit value = " + p.exitValue());
                System.err.println("command> " + command);
                System.err.println("output> " + result.output);
                System.err.print("error> ");

                while ((line = brErr.readLine()) != null)
                    System.err.println(line);

                result.worked = false;
            }
            result.returnCode = p.waitFor();
        } catch (InterruptedException e) {
            System.err.println(e);
            result.worked = false;
        } finally {
            // Close the InputStream
            bufferedreader.close();
            inread.close();
            buf.close();
            in.close();
        }
    } catch (IOException e) {
        System.err.println(e.getMessage());
        result.worked = false;
    }

    result.output = result.output.trim();

    return result;
}

From source file:facturacion.ftp.FtpServer.java

public static int sendImgFile(String fileNameServer, String hostDirServer, InputStream localFile) {
    FTPClient ftpClient = new FTPClient();
    boolean success = false;
    BufferedInputStream buffIn = null;
    try {//w  w w  . ja va2s. com
        ftpClient.connect(Config.getInstance().getProperty(Config.ServerFtpToken),
                Integer.parseInt(Config.getInstance().getProperty(Config.PortFtpToken)));
        ftpClient.login(Config.getInstance().getProperty(Config.UserFtpToken),
                Config.getInstance().getProperty(Config.PassFtpToken));
        ftpClient.enterLocalPassiveMode();
        /*ftpClient.connect("127.0.0.1", 21);
          ftpClient.login("erpftp", "Tribut@2014");*/
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        int reply = ftpClient.getReplyCode();

        System.out.println("Respuesta recibida de conexin FTP:" + reply);

        if (!FTPReply.isPositiveCompletion(reply)) {
            System.out.println("Imposible conectarse al servidor");
            return -1;
        }

        buffIn = new BufferedInputStream(localFile);//Ruta del archivo para enviar
        ftpClient.enterLocalPassiveMode();
        //crear directorio
        success = ftpClient.makeDirectory(hostDirServer);
        System.out.println("sucess 1 = " + success);
        success = ftpClient.makeDirectory(hostDirServer + "/img");
        System.out.println("sucess 233 = " + success);
        success = ftpClient.storeFile(hostDirServer + "/img/" + fileNameServer, buffIn);
        System.out.println("sucess 3 = " + success);
    } catch (IOException ex) {

    } finally {
        try {
            if (ftpClient.isConnected()) {
                buffIn.close(); //Cerrar envio de arcivos al FTP
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            return -1;
            //ex.printStackTrace();
        }
    }
    return (success) ? 1 : 0;
}