Example usage for org.apache.commons.io.input CountingInputStream CountingInputStream

List of usage examples for org.apache.commons.io.input CountingInputStream CountingInputStream

Introduction

In this page you can find the example usage for org.apache.commons.io.input CountingInputStream CountingInputStream.

Prototype

public CountingInputStream(InputStream in) 

Source Link

Document

Constructs a new CountingInputStream.

Usage

From source file:acmi.l2.clientmod.xdat.Controller.java

@FXML
private void open() {
    FileChooser fileChooser = new FileChooser();
    fileChooser.setTitle("Open interface.xdat");
    fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("XDAT (*.xdat)", "*.xdat"),
            new FileChooser.ExtensionFilter("All files", "*.*"));

    if (initialDirectory.getValue() != null && initialDirectory.getValue().exists()
            && initialDirectory.getValue().isDirectory())
        fileChooser.setInitialDirectory(initialDirectory.getValue());

    File selected = fileChooser.showOpenDialog(editor.getStage());
    if (selected == null)
        return;//w ww.j av a2s .co m

    xdatFile.setValue(selected);
    initialDirectory.setValue(selected.getParentFile());

    try {
        IOEntity xdat = editor.getXdatClass().getConstructor().newInstance();

        editor.execute(() -> {
            CountingInputStream cis = new CountingInputStream(
                    new BufferedInputStream(new FileInputStream(selected)));
            try (InputStream is = cis) {
                xdat.read(is);

                Platform.runLater(() -> editor.setXdatObject(xdat));
            } catch (Exception e) {
                log.log(Level.WARNING, String.format("Read error before offset 0x%x", cis.getCount()), e);
                throw e;
            }
            return null;
        }, e -> Platform.runLater(() -> Dialogs.show(Alert.AlertType.ERROR, "Read error", null,
                "Try to choose another version")));
    } catch (ReflectiveOperationException e) {
        log.log(Level.WARNING, "XDAT class should have empty public constructor", e);
        Dialogs.show(Alert.AlertType.ERROR, "ReflectiveOperationException", null,
                "XDAT class should have empty public constructor");
    }
}

From source file:com.constellio.app.services.appManagement.AppManagementService.java

public void getWarFromServer(ProgressInfo progressInfo)
        throws AppManagementServiceRuntimeException.CannotConnectToServer {
    String URL_WAR = getWarURLFromServer();

    System.out.println("URL FOR WAR => " + URL_WAR);

    try {/*from   w  w w  .  j av a 2  s  .c  om*/
        progressInfo.reset();
        progressInfo.setTask("Getting WAR from server");
        progressInfo.setEnd(1);

        progressInfo.setProgressMessage("Downloading WAR");
        InputStream input = getInputForPost(URL_WAR, getLicenseInfo().getSignature());
        if (input == null) {
            throw new AppManagementServiceRuntimeException.CannotConnectToServer(URL_WAR);
        }
        CountingInputStream countingInputStream = new CountingInputStream(input);

        progressInfo.setProgressMessage("Creating WAR file");
        OutputStream warFileOutput = getWarFileDestination().create("war upload");

        try {
            progressInfo.setProgressMessage("Copying downloaded WAR");

            byte[] buffer = new byte[8 * 1024];
            int bytesRead;
            while ((bytesRead = countingInputStream.read(buffer)) != -1) {
                warFileOutput.write(buffer, 0, bytesRead);
                long totalBytesRead = countingInputStream.getByteCount();
                String progressMessage = FileUtils.byteCountToDisplaySize(totalBytesRead);
                progressInfo.setProgressMessage(progressMessage);
            }
        } finally {
            IOUtils.closeQuietly(countingInputStream);
            IOUtils.closeQuietly(warFileOutput);
        }
        progressInfo.setCurrentState(1);

    } catch (IOException ioe) {
        throw new AppManagementServiceRuntimeException.CannotConnectToServer(URL_WAR, ioe);
    }
}

From source file:de.burlov.amazon.s3.dirsync.DirSync.java

private Object downloadObject(String s3key, byte[] encKey) throws IOException {
    InputStream in = downloadData(s3key);
    if (in == null) {
        return null;
    }//ww  w . ja  va2  s. co m
    CountingInputStream cin = new CountingInputStream(
            new InflaterInputStream(new CryptInputStream(in, cipher, encKey)));
    ObjectInputStream oin = new ObjectInputStream(cin);
    try {
        Object o = oin.readObject();
        transferredData += cin.getByteCount();
        return o;
    } catch (ClassNotFoundException e) {
        /*
         * sollte eigentlich nie vorkommen
         */
        throw new IOException(e.getLocalizedMessage());
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:nl.b3p.kaartenbalie.service.requesthandler.WFSRequestHandler.java

public void writeResponse(DataWrapper data, User user) throws Exception {
    OGCResponse ogcresponse = getNewOGCResponse();
    OGCRequest ogcrequest = data.getOgcrequest();

    String version = ogcrequest.getFinalVersion();
    String spInUrl = ogcrequest.getServiceProviderName();

    Integer[] orgIds = user.getOrganizationIds();
    OutputStream os = data.getOutputStream();

    Object identity = null;/* ww  w.  j  a  v a 2s  .co m*/
    try {
        identity = MyEMFDatabase.createEntityManager(MyEMFDatabase.MAIN_EM);

        boolean forAdmin = isConfigInUrlAndAdmin(data, user);
        // zet layers uit request in een list
        List<LayerSummary> layerSummaryList = prepareRequestLayers(ogcrequest);
        if (layerSummaryList == null) {
            // als geen layers meegegeven, dan alle layers gebruiken
            // alleen bij getcapabilities
            EntityManager em = MyEMFDatabase.getEntityManager(MyEMFDatabase.MAIN_EM);
            String[] al = getOrganisationLayers(em, orgIds, version, forAdmin);
            layerSummaryList = LayerSummary.createLayerSummaryList(Arrays.asList(al), spInUrl, true);
        }

        // maak lijst waarin de layers per sp zijn verzameld
        // boolean om volgorde van de lagen te bewaren
        List<SpLayerSummary> spLayerSummaries = null;
        if (forAdmin) {
            spLayerSummaries = getLayerSummaries(layerSummaryList, spInUrl);
        } else {
            spLayerSummaries = getServiceProviderURLS(layerSummaryList, orgIds, false, data, false);
        }
        if (spLayerSummaries == null || spLayerSummaries.isEmpty()) {
            throw new UnsupportedOperationException(
                    "No Serviceprovider available! User might not have rights to any Serviceprovider!");
        }
        if (spLayerSummaries.size() > 1 && version.equals(OGCConstants.WFS_VERSION_UNSPECIFIED)) {
            // forceren dat alle sp dezelfde versie retourneren, indien meer dan 1
            ogcrequest.addOrReplaceParameter(OGCConstants.VERSION, OGCConstants.WFS_VERSION_110);
        }

        DataMonitoring rr = data.getRequestReporting();
        long startprocestime = System.currentTimeMillis();
        String xmlEncoding = "UTF-8";

        for (SpLayerSummary sp : spLayerSummaries) {
            if (spInUrl != null && !spInUrl.equals(sp.getSpAbbr())) {
                // sp in url en dit is een andere sp
                continue;
            }
            sp.setSpInUrl(spInUrl);

            // zet de juiste layers voor deze sp
            OGCRequest sprequest = (OGCRequest) ogcrequest.clone();
            prepareRequest4Sp(sprequest, sp);

            String lurl = sp.getSpUrl();
            if (lurl.length() == 0) {
                throw new UnsupportedOperationException("No Serviceprovider for this service available!");
            }
            ServiceProviderRequest wfsRequest = this.createServiceProviderRequest(data, lurl,
                    sp.getServiceproviderId(), 0l);

            B3PCredentials credentials = new B3PCredentials();
            credentials.setUserName(sp.getUsername());
            credentials.setPassword(sp.getPassword());
            credentials.setUrl(lurl);
            HttpClientConfigured hcc = new HttpClientConfigured(credentials);

            HttpUriRequest method = null;
            if (sprequest.getHttpMethod().equalsIgnoreCase("POST")) {
                method = createPostMethod(sprequest, sp, wfsRequest);
            } else { // get
                method = createGetMethod(sprequest, sp, wfsRequest);
            }

            try {
                HttpResponse response = hcc.execute(method);

                try {

                    int statusCode = response.getStatusLine().getStatusCode();
                    wfsRequest.setResponseStatus(statusCode);
                    HttpEntity entity = response.getEntity();

                    if (statusCode != 200) {
                        log.error("Failed to connect with " + method.getURI() + " Using body: "
                                + sprequest.getXMLBody());
                        throw new UnsupportedOperationException("Failed to connect with " + method.getURI()
                                + " Using body: " + sprequest.getXMLBody());
                    }

                    wfsRequest.setRequestResponseTime(System.currentTimeMillis() - startprocestime);

                    data.setContentType("text/xml");
                    InputStream is = entity.getContent();

                    InputStream isx = null;
                    byte[] bytes = null;
                    int rsl = 0;
                    try {
                        rsl = new Integer(KBConfiguration.RESPONSE_SIZE_LIMIT);
                    } catch (NumberFormatException nfe) {
                        log.debug("KBConfiguration.RESPONSE_SIZE_LIMIT not properly configured: "
                                + nfe.getLocalizedMessage());
                    }
                    if (KBConfiguration.SAVE_MESSAGES) {
                        int len = 1;
                        byte[] buffer = new byte[2024];
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        while ((len = is.read(buffer, 0, buffer.length)) > 0) {
                            bos.write(buffer, 0, len);
                            if (buffer.length > rsl && rsl > 0) {
                                throw new ProviderException(
                                        "Response size exceeds maximum set in configuration:" + buffer.length
                                                + ", max is: " + rsl);
                            }
                        }
                        bytes = bos.toByteArray();
                        isx = new ByteArrayInputStream(bytes);
                    } else {
                        isx = new CountingInputStream(is);
                    }

                    if (KBConfiguration.SAVE_MESSAGES || spInUrl == null || !mayDirectWrite()) {
                        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                        dbf.setNamespaceAware(true);
                        DocumentBuilder builder = dbf.newDocumentBuilder();
                        Document doc = builder.parse(isx);
                        // indien meerdere sp met verschillende encodings
                        // dan wint de laatste!
                        String docEncoding = doc.getXmlEncoding();
                        if (docEncoding != null) {
                            xmlEncoding = docEncoding;
                        }

                        int len = 0;
                        if (KBConfiguration.SAVE_MESSAGES) {
                            wfsRequest.setMessageReceived(new String(bytes));
                        } else {
                            len = new Integer(((CountingInputStream) isx).getCount());
                            wfsRequest.setBytesReceived(new Long(len));
                        }
                        if (len > rsl && rsl > 0) {
                            throw new ProviderException("Response size exceeds maximum set in configuration:"
                                    + len + ", max is: " + rsl);
                        }

                        String prefix = sp.getSpAbbr();
                        if (spInUrl != null && !spInUrl.isEmpty()) {
                            // sp in url dus geen prefix toevoegen
                            prefix = null;
                        }

                        if (OGCResponse.isWfsV100ErrorResponse(doc.getDocumentElement())) {
                            // wfs 1.0.0 error
                            ogcresponse.rebuildWfsV100ErrorResponse(doc, sprequest, prefix);
                        } else if (OGCResponse.isOwsV100ErrorResponse(doc.getDocumentElement())) {
                            // wfs 1.1.0 error
                            ogcresponse.rebuildOwsV100ErrorResponse(doc, sprequest, prefix);
                        } else {
                            // normale response
                            ogcresponse.rebuildResponse(doc, sprequest, prefix);
                        }
                    } else {
                        /**
                         * Deze methode kan alleen aangeroepen worden als
                         * aan de volgende voorwaarden is voldaan:
                         * <li> slechts n sp nodig voor aanroep
                         * <li> spabbr zit in de url en niet als prefix in
                         * de layer name
                         * <li> KBConfiguration.SAVE_MESSAGES is false Als
                         * aan voorwaarden is voldaan dat wordt direct
                         * doorgestreamd indien er geen fout is opgetreden.
                         * <li> de aanroep methode mayDirectWrite is true.
                         */
                        // direct write possible
                        byte[] h = prepareDirectWrite(isx);
                        if (h != null) {
                            os.write(h);
                        }
                        // write rest
                        IOUtils.copy(isx, os);
                        wfsRequest.setBytesReceived(new Long(((CountingInputStream) isx).getCount()));
                        ogcresponse.setAlreadyDirectWritten(true);
                        break;
                    }
                } finally {
                    hcc.close(response);
                    hcc.close();
                }

            } catch (Exception e) {
                wfsRequest.setExceptionMessage("Failed to send bytes to client: " + e.getMessage());
                wfsRequest.setExceptionClass(e.getClass());

                throw e;
            } finally {
                rr.addServiceProviderRequest(wfsRequest);
            }
        }

        // only write when not already direct written
        if (!ogcresponse.isAlreadyDirectWritten()) {
            String responseBody = ogcresponse.getResponseBody(spLayerSummaries, ogcrequest, xmlEncoding);
            if (responseBody != null && !responseBody.equals("")) {
                byte[] buffer = responseBody.getBytes(xmlEncoding);
                os.write(buffer);
            } else {
                throw new UnsupportedOperationException("XMLbody empty!");
            }
        }
        doAccounting(user.getMainOrganizationId(), data, user);

    } finally {
        log.debug("Closing entity manager .....");
        MyEMFDatabase.closeEntityManager(identity, MyEMFDatabase.MAIN_EM);
    }
}

From source file:org.amanzi.neo.loader.core.parser.impl.internal.AbstractStreamParser.java

protected CountingInputStream initializeStream(final C configuration) {
    try {/*from w  w w. j  a v a2 s . co  m*/
        return new CountingInputStream(new FileInputStream(configuration.getFile()));
    } catch (java.io.FileNotFoundException e) {
        throw new FileNotFoundException(configuration.getFile(), e);
    }
}

From source file:org.apache.axiom.om.OMDocumentTestBase.java

public void testBuild() throws Exception {
    CountingInputStream in = new CountingInputStream(getTestResource(TestConstants.REALLY_BIG_MESSAGE));
    OMDocument doc = OMXMLBuilderFactory.createOMBuilder(omMetaFactory.getOMFactory(), in).getDocument();
    assertFalse(doc.isComplete());//from  ww  w .  j av  a  2  s .  com
    int countBeforeBuild = in.getCount();
    doc.build();
    assertTrue(doc.isComplete());
    int countAfterBuild = in.getCount();
    assertTrue(countAfterBuild > countBeforeBuild);
    OMNode node = doc.getFirstOMChild();
    while (node != null) {
        node = node.getNextOMSibling();
    }
    assertEquals(countAfterBuild, in.getCount());
}

From source file:org.apache.jackrabbit.core.data.db.DbDataStore.java

public DataRecord addRecord(InputStream stream) throws DataStoreException {
    InputStream fileInput = null;
    String tempId = null;/*from  ww  w.j  a va 2  s.  c  o  m*/
    ResultSet rs = null;
    try {
        long tempModified;
        while (true) {
            try {
                tempModified = System.currentTimeMillis();
                String id = UUID.randomUUID().toString();
                tempId = TEMP_PREFIX + id;
                temporaryInUse.add(tempId);
                // SELECT LENGTH, LAST_MODIFIED FROM DATASTORE WHERE ID=?
                rs = conHelper.query(selectMetaSQL, tempId);
                boolean hasNext = rs.next();
                DbUtility.close(rs);
                rs = null;
                if (hasNext) {
                    // re-try in the very, very unlikely event that the row already exists
                    continue;
                }
                // INSERT INTO DATASTORE VALUES(?, 0, ?, NULL)
                conHelper.exec(insertTempSQL, tempId, tempModified);
                break;
            } catch (Exception e) {
                throw convert("Can not insert new record", e);
            } finally {
                DbUtility.close(rs);
                // prevent that rs.close() is called again
                rs = null;
            }
        }
        MessageDigest digest = getDigest();
        DigestInputStream dIn = new DigestInputStream(stream, digest);
        CountingInputStream in = new CountingInputStream(dIn);
        StreamWrapper wrapper;
        if (STORE_SIZE_MINUS_ONE.equals(storeStream)) {
            wrapper = new StreamWrapper(in, -1);
        } else if (STORE_SIZE_MAX.equals(storeStream)) {
            wrapper = new StreamWrapper(in, Integer.MAX_VALUE);
        } else if (STORE_TEMP_FILE.equals(storeStream)) {
            File temp = moveToTempFile(in);
            long length = temp.length();
            wrapper = new StreamWrapper(new ResettableTempFileInputStream(temp), length);
        } else {
            throw new DataStoreException("Unsupported stream store algorithm: " + storeStream);
        }
        // UPDATE DATASTORE SET DATA=? WHERE ID=?
        conHelper.exec(updateDataSQL, wrapper, tempId);
        long length = in.getByteCount();
        DataIdentifier identifier = new DataIdentifier(encodeHexString(digest.digest()));
        usesIdentifier(identifier);
        String id = identifier.toString();
        long newModified;
        while (true) {
            newModified = System.currentTimeMillis();
            if (checkExisting(tempId, length, identifier)) {
                touch(identifier, newModified);
                conHelper.exec(deleteSQL, tempId);
                break;
            }
            try {
                // UPDATE DATASTORE SET ID=?, LENGTH=?, LAST_MODIFIED=?
                // WHERE ID=? AND LAST_MODIFIED=?
                int count = conHelper.update(updateSQL, id, length, newModified, tempId, tempModified);
                // If update count is 0, the last modified time of the
                // temporary row was changed - which means we need to
                // re-try using a new last modified date (a later one)
                // because we need to ensure the new last modified date
                // is _newer_ than the old (otherwise the garbage
                // collection could delete rows)
                if (count != 0) {
                    // update was successful
                    break;
                }
            } catch (SQLException e) {
                // duplicate key (the row already exists) - repeat
                // we use exception handling for flow control here, which is bad,
                // but the alternative is to use UPDATE ... WHERE ... (SELECT ...)
                // which could cause a deadlock in some databases - also,
                // duplicate key will only occur if somebody else concurrently
                // added the same record (which is very unlikely)
            }
            // SELECT LENGTH, LAST_MODIFIED FROM DATASTORE WHERE ID=?
            rs = conHelper.query(selectMetaSQL, tempId);
            if (!rs.next()) {
                // the row was deleted, which is unexpected / not allowed
                String msg = DIGEST + " temporary entry deleted: " + " id=" + tempId + " length=" + length;
                log.error(msg);
                throw new DataStoreException(msg);
            }
            tempModified = rs.getLong(2);
            DbUtility.close(rs);
            rs = null;
        }
        usesIdentifier(identifier);
        DbDataRecord record = new DbDataRecord(this, identifier, length, newModified);
        return record;
    } catch (Exception e) {
        throw convert("Can not insert new record", e);
    } finally {
        if (tempId != null) {
            temporaryInUse.remove(tempId);
        }
        DbUtility.close(rs);
        if (fileInput != null) {
            try {
                fileInput.close();
            } catch (IOException e) {
                throw convert("Can not close temporary file", e);
            }
        }
    }
}

From source file:org.apache.jackrabbit.core.persistence.util.BundleReader.java

/**
 * Creates a new bundle deserializer./*from w  w  w .  j  av a2  s  .  c o  m*/
 *
 * @param binding bundle binding
 * @param stream stream from which the bundle is read
 * @throws IOException if an I/O error occurs.
 */
public BundleReader(BundleBinding binding, InputStream stream) throws IOException {
    this.binding = binding;
    this.cin = new CountingInputStream(stream);
    this.in = new DataInputStream(cin);
    this.version = in.readUnsignedByte();
}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC3Impl.java

/**
 * Samples the URL passed in and stores the result in
 * <code>HTTPSampleResult</code>, following redirects and downloading
 * page resources as appropriate.//w  w  w.ja v a2  s .  c o m
 * <p>
 * When getting a redirect target, redirects are not followed and resources
 * are not downloaded. The caller will take care of this.
 *
 * @param url
 *            URL to sample
 * @param method
 *            HTTP method: GET, POST,...
 * @param areFollowingRedirect
 *            whether we're getting a redirect target
 * @param frameDepth
 *            Depth of this target in the frame structure. Used only to
 *            prevent infinite recursion.
 * @return results of the sampling
 */
@Override
protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) {

    String urlStr = url.toString();

    if (log.isDebugEnabled()) {
        log.debug("Start : sample " + urlStr);
        log.debug("method " + method + " followingRedirect " + areFollowingRedirect + " depth " + frameDepth);
    }

    HttpMethodBase httpMethod = null;

    HTTPSampleResult res = new HTTPSampleResult();
    res.setMonitor(isMonitor());

    res.setSampleLabel(urlStr); // May be replaced later
    res.setHTTPMethod(method);
    res.setURL(url);

    res.sampleStart(); // Count the retries as well in the time
    try {
        // May generate IllegalArgumentException
        if (method.equals(HTTPConstants.POST)) {
            httpMethod = new PostMethod(urlStr);
        } else if (method.equals(HTTPConstants.GET)) {
            httpMethod = new GetMethod(urlStr);
        } else if (method.equals(HTTPConstants.PUT)) {
            httpMethod = new PutMethod(urlStr);
        } else if (method.equals(HTTPConstants.HEAD)) {
            httpMethod = new HeadMethod(urlStr);
        } else if (method.equals(HTTPConstants.TRACE)) {
            httpMethod = new TraceMethod(urlStr);
        } else if (method.equals(HTTPConstants.OPTIONS)) {
            httpMethod = new OptionsMethod(urlStr);
        } else if (method.equals(HTTPConstants.DELETE)) {
            httpMethod = new EntityEnclosingMethod(urlStr) {
                @Override
                public String getName() { // HC3.1 does not have the method
                    return HTTPConstants.DELETE;
                }
            };
        } else if (method.equals(HTTPConstants.PATCH)) {
            httpMethod = new EntityEnclosingMethod(urlStr) {
                @Override
                public String getName() { // HC3.1 does not have the method
                    return HTTPConstants.PATCH;
                }
            };
        } else {
            throw new IllegalArgumentException("Unexpected method: '" + method + "'");
        }

        final CacheManager cacheManager = getCacheManager();
        if (cacheManager != null && HTTPConstants.GET.equalsIgnoreCase(method)) {
            if (cacheManager.inCache(url)) {
                return updateSampleResultForResourceInCache(res);
            }
        }

        // Set any default request headers
        setDefaultRequestHeaders(httpMethod);

        // Setup connection
        HttpClient client = setupConnection(url, httpMethod, res);
        savedClient = client;

        // Handle the various methods
        if (method.equals(HTTPConstants.POST)) {
            String postBody = sendPostData((PostMethod) httpMethod);
            res.setQueryString(postBody);
        } else if (method.equals(HTTPConstants.PUT) || method.equals(HTTPConstants.PATCH)
                || method.equals(HTTPConstants.DELETE)) {
            String putBody = sendEntityData((EntityEnclosingMethod) httpMethod);
            res.setQueryString(putBody);
        }

        int statusCode = client.executeMethod(httpMethod);

        // We've finished with the request, so we can add the LocalAddress to it for display
        final InetAddress localAddr = client.getHostConfiguration().getLocalAddress();
        if (localAddr != null) {
            httpMethod.addRequestHeader(HEADER_LOCAL_ADDRESS, localAddr.toString());
        }
        // Needs to be done after execute to pick up all the headers
        res.setRequestHeaders(getConnectionHeaders(httpMethod));

        // Request sent. Now get the response:
        InputStream instream = httpMethod.getResponseBodyAsStream();

        if (instream != null) {// will be null for HEAD
            instream = new CountingInputStream(instream);
            try {
                Header responseHeader = httpMethod.getResponseHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
                if (responseHeader != null && HTTPConstants.ENCODING_GZIP.equals(responseHeader.getValue())) {
                    InputStream tmpInput = new GZIPInputStream(instream); // tmp inputstream needs to have a good counting
                    res.setResponseData(
                            readResponse(res, tmpInput, (int) httpMethod.getResponseContentLength()));
                } else {
                    res.setResponseData(
                            readResponse(res, instream, (int) httpMethod.getResponseContentLength()));
                }
            } finally {
                JOrphanUtils.closeQuietly(instream);
            }
        }

        res.sampleEnd();
        // Done with the sampling proper.

        // Now collect the results into the HTTPSampleResult:

        res.setSampleLabel(httpMethod.getURI().toString());
        // Pick up Actual path (after redirects)

        res.setResponseCode(Integer.toString(statusCode));
        res.setSuccessful(isSuccessCode(statusCode));

        res.setResponseMessage(httpMethod.getStatusText());

        String ct = null;
        Header h = httpMethod.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE);
        if (h != null)// Can be missing, e.g. on redirect
        {
            ct = h.getValue();
            res.setContentType(ct);// e.g. text/html; charset=ISO-8859-1
            res.setEncodingAndType(ct);
        }

        res.setResponseHeaders(getResponseHeaders(httpMethod));
        if (res.isRedirect()) {
            final Header headerLocation = httpMethod.getResponseHeader(HTTPConstants.HEADER_LOCATION);
            if (headerLocation == null) { // HTTP protocol violation, but avoids NPE
                throw new IllegalArgumentException("Missing location header");
            }
            String redirectLocation = headerLocation.getValue();
            res.setRedirectLocation(redirectLocation); // in case sanitising fails
        }

        // record some sizes to allow HTTPSampleResult.getBytes() with different options
        if (instream != null) {
            res.setBodySize(((CountingInputStream) instream).getCount());
        }
        res.setHeadersSize(calculateHeadersSize(httpMethod));
        if (log.isDebugEnabled()) {
            log.debug("Response headersSize=" + res.getHeadersSize() + " bodySize=" + res.getBodySize()
                    + " Total=" + (res.getHeadersSize() + res.getBodySize()));
        }

        // If we redirected automatically, the URL may have changed
        if (getAutoRedirects()) {
            res.setURL(new URL(httpMethod.getURI().toString()));
        }

        // Store any cookies received in the cookie manager:
        saveConnectionCookies(httpMethod, res.getURL(), getCookieManager());

        // Save cache information
        if (cacheManager != null) {
            cacheManager.saveDetails(httpMethod, res);
        }

        // Follow redirects and download page resources if appropriate:
        res = resultProcessing(areFollowingRedirect, frameDepth, res);

        log.debug("End : sample");
        return res;
    } catch (IllegalArgumentException e) { // e.g. some kinds of invalid URL
        res.sampleEnd();
        // pick up headers if failed to execute the request
        // httpMethod can be null if method is unexpected
        if (httpMethod != null) {
            res.setRequestHeaders(getConnectionHeaders(httpMethod));
        }
        errorResult(e, res);
        return res;
    } catch (IOException e) {
        res.sampleEnd();
        // pick up headers if failed to execute the request
        // httpMethod cannot be null here, otherwise 
        // it would have been caught in the previous catch block
        res.setRequestHeaders(getConnectionHeaders(httpMethod));
        errorResult(e, res);
        return res;
    } finally {
        savedClient = null;
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }
}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPJavaImpl.java

/**
 * Reads the response from the URL connection.
 *
 * @param conn//from   ww w . j a  v  a2s  .  co m
 *            URL from which to read response
 * @param res
 *            {@link SampleResult} to read response into
 * @return response content
 * @exception IOException
 *                if an I/O exception occurs
 */
protected byte[] readResponse(HttpURLConnection conn, SampleResult res) throws IOException {
    BufferedInputStream in;

    final int contentLength = conn.getContentLength();
    if ((contentLength == 0) && OBEY_CONTENT_LENGTH) {
        log.info("Content-Length: 0, not reading http-body");
        res.setResponseHeaders(getResponseHeaders(conn));
        res.latencyEnd();
        return NULL_BA;
    }

    // works OK even if ContentEncoding is null
    boolean gzipped = HTTPConstants.ENCODING_GZIP.equals(conn.getContentEncoding());
    InputStream instream = null;
    try {
        instream = new CountingInputStream(conn.getInputStream());
        if (gzipped) {
            in = new BufferedInputStream(new GZIPInputStream(instream));
        } else {
            in = new BufferedInputStream(instream);
        }
    } catch (IOException e) {
        if (!(e.getCause() instanceof FileNotFoundException)) {
            log.error("readResponse: " + e.toString());
            Throwable cause = e.getCause();
            if (cause != null) {
                log.error("Cause: " + cause);
                if (cause instanceof Error) {
                    throw (Error) cause;
                }
            }
        }
        // Normal InputStream is not available
        InputStream errorStream = conn.getErrorStream();
        if (errorStream == null) {
            log.info("Error Response Code: " + conn.getResponseCode() + ", Server sent no Errorpage");
            res.setResponseHeaders(getResponseHeaders(conn));
            res.latencyEnd();
            return NULL_BA;
        }

        log.info("Error Response Code: " + conn.getResponseCode());

        if (gzipped) {
            in = new BufferedInputStream(new GZIPInputStream(errorStream));
        } else {
            in = new BufferedInputStream(errorStream);
        }
    } catch (Exception e) {
        log.error("readResponse: " + e.toString());
        Throwable cause = e.getCause();
        if (cause != null) {
            log.error("Cause: " + cause);
            if (cause instanceof Error) {
                throw (Error) cause;
            }
        }
        in = new BufferedInputStream(conn.getErrorStream());
    }
    // N.B. this closes 'in'
    byte[] responseData = readResponse(res, in, contentLength);
    if (instream != null) {
        res.setBodySize(((CountingInputStream) instream).getCount());
        instream.close();
    }
    return responseData;
}