Example usage for org.apache.commons.io.output NullOutputStream nullOutputStream

List of usage examples for org.apache.commons.io.output NullOutputStream nullOutputStream

Introduction

In this page you can find the example usage for org.apache.commons.io.output NullOutputStream nullOutputStream.

Prototype

public static OutputStream nullOutputStream() 

Source Link

Document

Returns a new OutputStream which discards all bytes.

Usage

From source file:password.pwm.http.servlet.resource.ResourceServletService.java

private String makeResourcePathNonce() throws PwmUnrecoverableException, IOException {
    final boolean enablePathNonce = Boolean.parseBoolean(
            pwmApplication.getConfig().readAppProperty(AppProperty.HTTP_RESOURCES_ENABLE_PATH_NONCE));
    if (!enablePathNonce) {
        return "";
    }//from  w w w . j ava 2s.  com

    final Instant startTime = Instant.now();
    final ChecksumOutputStream checksumOs = new ChecksumOutputStream(PwmHashAlgorithm.MD5,
            new NullOutputStream());

    if (pwmApplication.getPwmEnvironment().getContextManager() != null) {
        try {
            final File webInfPath = pwmApplication.getPwmEnvironment().getContextManager()
                    .locateWebInfFilePath();
            if (webInfPath != null && webInfPath.exists()) {
                final File basePath = webInfPath.getParentFile();
                if (basePath != null && basePath.exists()) {
                    final File resourcePath = new File(basePath.getAbsolutePath() + File.separator + "public"
                            + File.separator + "resources");
                    if (resourcePath.exists()) {
                        final List<FileSystemUtility.FileSummaryInformation> fileSummaryInformations = new ArrayList<>();
                        fileSummaryInformations.addAll(FileSystemUtility.readFileInformation(resourcePath));
                        for (final FileSystemUtility.FileSummaryInformation fileSummaryInformation : fileSummaryInformations) {
                            checksumOs.write((fileSummaryInformation.getSha1sum())
                                    .getBytes(PwmConstants.DEFAULT_CHARSET));
                        }
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error("unable to generate resource path nonce: " + e.getMessage());
        }
    }

    for (final FileResource fileResource : getResourceServletConfiguration().getCustomFileBundle().values()) {
        JavaHelper.copyWhilePredicate(fileResource.getInputStream(), checksumOs, o -> true);
    }

    if (getResourceServletConfiguration().getZipResources() != null) {
        for (final String key : getResourceServletConfiguration().getZipResources().keySet()) {
            final ZipFile value = getResourceServletConfiguration().getZipResources().get(key);
            checksumOs.write(key.getBytes(PwmConstants.DEFAULT_CHARSET));
            for (Enumeration<? extends ZipEntry> zipEnum = value.entries(); zipEnum.hasMoreElements();) {
                final ZipEntry entry = zipEnum.nextElement();
                checksumOs.write(Long.toHexString(entry.getSize()).getBytes(PwmConstants.DEFAULT_CHARSET));
            }
        }
    }

    final String nonce = JavaHelper.byteArrayToHexString(checksumOs.getInProgressChecksum()).toLowerCase();
    LOGGER.debug("completed generation of nonce '" + nonce + "' in "
            + TimeDuration.fromCurrent(startTime).asCompactString());

    final String noncePrefix = pwmApplication.getConfig()
            .readAppProperty(AppProperty.HTTP_RESOURCES_NONCE_PATH_PREFIX);
    return "/" + noncePrefix + nonce;
}

From source file:pt.ist.vaadinframework.codegeneration.NonOverridingCodeWriter.java

@Override
public Writer openSource(JPackage pkg, String fileName) throws IOException {
    File wannaBeFile = new File(srcDir, pkg.name().replaceAll("\\.", "/") + File.separator + fileName);
    if (wannaBeFile.exists()) {
        return new OutputStreamWriter(new NullOutputStream());
    }//from w  ww.  ja  v a 2 s.c o  m
    System.out.println("Creating Data Layer Class: " + wannaBeFile.getAbsolutePath());
    return super.openSource(pkg, fileName);
}

From source file:pt.webdetails.cda.cache.Query.java

protected void executeQuery() throws Exception {

    final CdaSettings cdaSettings = SettingsManager.getInstance().parseSettingsFile(getCdaFile());

    final QueryOptions queryOptions = new QueryOptions();
    queryOptions.setDataAccessId(getDataAccessId());
    // force query to be refreshed
    queryOptions.setCacheBypass(true);/*from  w  w w.ja  va  2  s  .  com*/

    for (Object o : getParameters()) {
        CachedParam param = (CachedParam) o;
        queryOptions.addParameter(param.getName(), param.getValue());
    }

    OutputStream nullOut = new NullOutputStream();
    Date d = new Date();
    CdaEngine.getInstance().doQuery(nullOut, cdaSettings, queryOptions);
    setTimeElapsed(new Date().getTime() - d.getTime());
    CacheScheduleManager.logger
            .debug("Time elapsed: " + Double.toString(new Double(getTimeElapsed()) / 1000) + "s");
}

From source file:tds.itemscoringengine.web.server.ItemScoringEngineHttpWebHelper.java

public void sendXml(String url, ItemScoreResponse inputData) {
    sendXml(url, inputData, new NullOutputStream());
}

From source file:uk.ac.gate.cloud.client.RestClient.java

/**
 * Make an API request and return the raw data from the response as an
 * InputStream.//from www .j  av  a2s.  c  o  m
 * 
 * @param target the URL to request (relative URLs will resolve
 *          against the {@link #getBaseUrl() base URL}).
 * @param method the request method (GET, POST, DELETE, etc.)
 * @param requestBody the value to send as the request body. If
 *          <code>null</code>, no request body is sent. If an
 *          <code>InputStream</code> or a <code>StreamWriteable</code>
 *          then its content will be sent as-is and an appropriate
 *          <code>Content-Type</code> should be given in the
 *          <code>extraHeaders</code> (note that the input stream will
 *          <em>not</em> be closed by this method, that is the
 *          responsibility of the caller). Otherwise the provided
 *          object will be serialized to JSON and sent with the
 *          default <code>application/json</code> MIME type.
 * @param gzipThreshold size threshold above which the request body
 *          should be GZIP compressed. If negative, the request will
 *          never be compressed.
 * @param extraHeaders any additional HTTP headers, specified as an
 *          alternating sequence of header names and values
 * @return for a successful response, the response stream, or
 *         <code>null</code> for a 201 response
 * @throws RestClientException if an exception occurs during
 *           processing, or the server returns a 4xx or 5xx error
 *           response (in which case the response JSON message will be
 *           available as a {@link JsonNode} in the exception).
 */
public InputStream requestForStream(String target, String method, Object requestBody, int gzipThreshold,
        String... extraHeaders) throws RestClientException {
    try {
        HttpURLConnection connection = sendRequest(target, method, requestBody, gzipThreshold, extraHeaders);
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
            // successful response with no content
            return null;
        } else if (responseCode >= 400) {
            readError(connection);
            return null; // not reachable, readError always throws exception
        } else if (responseCode >= 300) {
            // redirect - all redirects we care about from the GATE Cloud
            // APIs are 303. We have to follow them manually to make
            // authentication work properly.
            String location = connection.getHeaderField("Location");
            // consume body
            InputStream stream = connection.getInputStream();
            IOUtils.copy(stream, new NullOutputStream());
            IOUtils.closeQuietly(stream);
            // follow the redirect
            return requestForStream(location, method, requestBody, gzipThreshold, extraHeaders);
        } else {
            storeHeaders(connection);
            if ("gzip".equals(connection.getHeaderField("Content-Encoding"))) {
                return new GZIPInputStream(connection.getInputStream());
            } else {
                return connection.getInputStream();
            }
        }
    } catch (IOException e) {
        throw new RestClientException(e);
    }

}

From source file:uk.ac.gate.cloud.client.RestClient.java

/**
 * Read a response or error message from the given connection,
 * handling any 303 redirect responses if <code>followRedirects</code>
 * is true./*w  ww.ja v a  2s.c  o m*/
 */
private <T> T readResponseOrError(HttpURLConnection connection, TypeReference<T> responseType,
        boolean followRedirects) throws RestClientException {
    InputStream stream = null;
    try {
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
            // successful response with no content
            storeHeaders(connection);
            return null;
        }
        String encoding = connection.getContentEncoding();
        if ("gzip".equalsIgnoreCase(encoding)) {
            stream = new GZIPInputStream(connection.getInputStream());
        } else {
            stream = connection.getInputStream();
        }

        if (responseCode < 300 || responseCode >= 400 || !followRedirects) {
            try {
                return MAPPER.readValue(stream, responseType);
            } finally {
                storeHeaders(connection);
                stream.close();
            }
        } else {
            // redirect - all redirects we care about from the GATE Cloud
            // APIs are 303. We have to follow them manually to make
            // authentication work properly.
            String location = connection.getHeaderField("Location");
            // consume body
            IOUtils.copy(stream, new NullOutputStream());
            IOUtils.closeQuietly(stream);
            // follow the redirect
            return get(location, responseType);
        }
    } catch (Exception e) {
        readError(connection);
        return null; // unreachable, as readError always throws exception
    }
}