Example usage for java.util.zip InflaterInputStream InflaterInputStream

List of usage examples for java.util.zip InflaterInputStream InflaterInputStream

Introduction

In this page you can find the example usage for java.util.zip InflaterInputStream InflaterInputStream.

Prototype

public InflaterInputStream(InputStream in) 

Source Link

Document

Creates a new input stream with a default decompressor and buffer size.

Usage

From source file:org.openhab.action.telegram.internal.Telegram.java

@ActionDoc(text = "Sends a Telegram via Telegram REST API - direct message")
static public boolean sendTelegram(@ParamDoc(name = "group") String group,
        @ParamDoc(name = "message") String message) {

    if (groupTokens.get(group) == null) {
        logger.error("Bot '{}' not defined, action skipped", group);
        return false;
    }//from  w  w  w  . j ava 2s.c  o m

    String url = String.format(TELEGRAM_URL, groupTokens.get(group).getToken());

    HttpClient client = new HttpClient();

    PostMethod postMethod = new PostMethod(url);
    postMethod.getParams().setSoTimeout(HTTP_TIMEOUT);
    postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    NameValuePair[] data = { new NameValuePair("chat_id", groupTokens.get(group).getChatId()),
            new NameValuePair("text", message) };
    postMethod.setRequestBody(data);

    try {
        int statusCode = client.executeMethod(postMethod);

        if (statusCode == HttpStatus.SC_NO_CONTENT || statusCode == HttpStatus.SC_ACCEPTED) {
            return true;
        }

        if (statusCode != HttpStatus.SC_OK) {
            logger.warn("Method failed: {}", postMethod.getStatusLine());
            return false;
        }

        InputStream tmpResponseStream = postMethod.getResponseBodyAsStream();
        Header encodingHeader = postMethod.getResponseHeader("Content-Encoding");
        if (encodingHeader != null) {
            for (HeaderElement ehElem : encodingHeader.getElements()) {
                if (ehElem.toString().matches(".*gzip.*")) {
                    tmpResponseStream = new GZIPInputStream(tmpResponseStream);
                    logger.debug("GZipped InputStream from {}", url);
                } else if (ehElem.toString().matches(".*deflate.*")) {
                    tmpResponseStream = new InflaterInputStream(tmpResponseStream);
                    logger.debug("Deflated InputStream from {}", url);
                }
            }
        }

        String responseBody = IOUtils.toString(tmpResponseStream);
        if (!responseBody.isEmpty()) {
            logger.debug(responseBody);
        }

    } catch (HttpException e) {
        logger.error("Fatal protocol violation: {}", e.toString());
    } catch (IOException e) {
        logger.error("Fatal transport error: {}", e.toString());
    } finally {
        postMethod.releaseConnection();
    }

    return true;
}

From source file:eu.peppol.smp.SmpContentRetrieverImpl.java

/**
 * Gets the XML content of a given url, wrapped in an InputSource object.
 *//*from   w w  w .  ja va2s.c o  m*/
@Override
public InputSource getUrlContent(URL url) {

    HttpURLConnection httpURLConnection = null;
    try {
        httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.connect();
    } catch (IOException e) {
        throw new IllegalStateException("Unable to connect to " + url + " ; " + e.getMessage(), e);
    }

    try {
        if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_UNAVAILABLE)
            throw new TryAgainLaterException(url, httpURLConnection.getHeaderField("Retry-After"));
        if (httpURLConnection.getResponseCode() != HttpURLConnection.HTTP_OK)
            throw new ConnectionException(url, httpURLConnection.getResponseCode());
    } catch (IOException e) {
        throw new RuntimeException("Problem reading URL data at " + url.toExternalForm(), e);
    }

    try {

        String encoding = httpURLConnection.getContentEncoding();
        InputStream in = new BOMInputStream(httpURLConnection.getInputStream());
        InputStream result;

        if (encoding != null && encoding.equalsIgnoreCase(ENCODING_GZIP)) {
            result = new GZIPInputStream(in);
        } else if (encoding != null && encoding.equalsIgnoreCase(ENCODING_DEFLATE)) {
            result = new InflaterInputStream(in);
        } else {
            result = in;
        }

        String xml = readInputStreamIntoString(result);

        return new InputSource(new StringReader(xml));

    } catch (Exception e) {
        throw new RuntimeException("Problem reading URL data at " + url.toExternalForm(), e);
    }

}

From source file:com.uber.hoodie.common.HoodieJsonPayload.java

private String unCompressData(byte[] data) throws IOException {
    InflaterInputStream iis = new InflaterInputStream(new ByteArrayInputStream(data));
    try {// w ww  .j ava  2s .  c  o m
        StringWriter sw = new StringWriter(dataSize);
        IOUtils.copy(iis, sw);
        return sw.toString();
    } finally {
        iis.close();
    }
}

From source file:org.eclipse.gyrex.jobs.internal.worker.JobInfo.java

public static JobInfo parse(final IMessage message) throws IOException {
    final Properties properties = new Properties();
    try (InflaterInputStream in = new InflaterInputStream(new ByteArrayInputStream(message.getBody()))) {
        properties.load(in);/*from   w w w .j  a  v  a2s .c  o  m*/
    }

    // check version (remove key from properties)
    final Object versionValue = properties.remove(VERSION);
    if (!VERSION_VALUE.equals(versionValue))
        throw new IOException(String.format("invalid record data: version mismatch (expected %s, found %s)",
                VERSION_VALUE, String.valueOf(versionValue)));

    // get id (remove key from properties as well)
    final Object jobIdValue = properties.remove(ID);
    if ((null == jobIdValue) || !(jobIdValue instanceof String) || !IdHelper.isValidId(((String) jobIdValue)))
        throw new IOException(
                String.format("invalid record data: missing/invalid job id %s", String.valueOf(jobIdValue)));

    // get type (remove key from properties as well)
    final Object jobTypeValue = properties.remove(TYPE_ID);
    if ((null == jobTypeValue) || !(jobTypeValue instanceof String)
            || !IdHelper.isValidId(((String) jobTypeValue)))
        throw new IOException(
                String.format("invalid record data: missing/invalid job id %s", String.valueOf(jobTypeValue)));

    // get path (remove key from properties as well)
    final Object contextPathValue = properties.remove(CONTEXT_PATH);
    if ((null == contextPathValue) || !(contextPathValue instanceof String)
            || !Path.EMPTY.isValidPath(((String) contextPathValue)))
        throw new IOException(String.format("invalid record data: missing/invalid context path %s",
                String.valueOf(contextPathValue)));

    // get queue trigger (remove key from properties as well)
    final Object queueTrigger = properties.remove(QUEUE_TRIGGER);
    if ((null != queueTrigger) && !(queueTrigger instanceof String))
        throw new IOException(
                String.format("invalid record data: invalid queue trigger %s", String.valueOf(queueTrigger)));

    // get queue timestamp (remove key from properties as well)
    final Object queueTimestamp = properties.remove(QUEUE_TIMESTAMP);
    if ((null == queueTimestamp) || !(queueTimestamp instanceof String))
        throw new IOException(String.format("invalid record data: missing/invalid queue timestamp %s",
                String.valueOf(queueTimestamp)));

    // get schedule info (remove key from properties as well)
    final Object scheduleInfo = properties.remove(SCHEDULE_INFO);
    if ((null != scheduleInfo) && !(scheduleInfo instanceof String))
        throw new IOException(
                String.format("invalid record data: invalid schedule info %s", String.valueOf(scheduleInfo)));

    // get last successful finish timestamp (remove key from properties as well)
    final Object lastSuccessfulStart = properties.remove(LAST_SUCCESSFUL_START);
    if ((null == lastSuccessfulStart) || !(lastSuccessfulStart instanceof String))
        throw new IOException(
                String.format("invalid record data: missing/invalid last successful finish timestamp %s",
                        String.valueOf(lastSuccessfulStart)));

    // collect properties
    final Map<String, String> jobProperties = new HashMap<String, String>();
    for (final Iterator<?> stream = properties.keySet().iterator(); stream.hasNext();) {
        final String key = (String) stream.next();
        if (!key.startsWith(PREFIX)) {
            jobProperties.put(key, properties.getProperty(key));
        }
    }

    // create job info
    return new JobInfo((String) jobTypeValue, (String) jobIdValue, new Path((String) contextPathValue),
            jobProperties, (String) queueTrigger, NumberUtils.toLong((String) queueTimestamp),
            (String) scheduleInfo, NumberUtils.toLong((String) lastSuccessfulStart));
}

From source file:net.myrrix.common.io.IOUtils.java

/**
 * Opens an {@link InputStream} to the file. If it appears to be compressed, because its file name ends in
 * ".gz" or ".zip" or ".deflate", then it will be decompressed accordingly
 *
 * @param file file, possibly compressed, to open
 * @return {@link InputStream} on uncompressed contents
 * @throws IOException if the stream can't be opened or is invalid or can't be read
 *//*from w  w w . ja va 2  s  .com*/
public static InputStream openMaybeDecompressing(File file) throws IOException {
    String name = file.getName();
    InputStream in = new FileInputStream(file);
    if (name.endsWith(".gz")) {
        return new GZIPInputStream(in);
    }
    if (name.endsWith(".zip")) {
        return new ZipInputStream(in);
    }
    if (name.endsWith(".deflate")) {
        return new InflaterInputStream(in);
    }
    if (name.endsWith(".bz2") || name.endsWith(".bzip2")) {
        return new BZip2CompressorInputStream(in);
    }
    return in;
}

From source file:org.jbpm.bpel.persistence.db.type.ElementType.java

public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
    // retrieve stream from database
    String columnName = names[0];
    InputStream xmlStream = rs.getBinaryStream(columnName);

    // if SQL value is NULL, element is null as well
    if (xmlStream == null)
        return null;

    // introduce inflater, if requested
    Integer deflateLevel = getXmlDeflateLevel();
    if (deflateLevel != null)
        xmlStream = new InflaterInputStream(xmlStream);

    try {//from w  w  w.  j av a2  s . c o m
        // parse XML text
        Element element = XmlUtil.getDocumentBuilder().parse(xmlStream).getDocumentElement();
        xmlStream.close();

        if (log.isTraceEnabled())
            log.trace("returning '" + XmlUtil.toTraceString(element) + "' as column: " + columnName);
        return element;
    } catch (SAXException e) {
        throw new HibernateException("could not parse column: " + columnName, e);
    } catch (IOException e) {
        throw new HibernateException("could not read column: " + columnName, e);
    }
}

From source file:org.apache.tez.common.TezUtils.java

/**
 * Convert a byte string to a Configuration object
 *
 * @param byteString byteString representation of the conf created using {@link
 *                   #createByteStringFromConf(org.apache.hadoop.conf.Configuration)}
 * @return Configuration//from  w w  w.ja va 2 s. co  m
 * @throws java.io.IOException
 */
public static Configuration createConfFromByteString(ByteString byteString) throws IOException {
    Preconditions.checkNotNull(byteString, "ByteString must be specified");
    // SnappyInputStream uncompressIs = new
    // SnappyInputStream(byteString.newInput());
    InflaterInputStream uncompressIs = new InflaterInputStream(byteString.newInput());
    DAGProtos.ConfigurationProto confProto = DAGProtos.ConfigurationProto.parseFrom(uncompressIs);
    Configuration conf = new Configuration(false);
    readConfFromPB(confProto, conf);
    return conf;
}

From source file:org.owasp.dependencycheck.utils.Downloader.java

/**
 * Retrieves a file from a given URL and saves it to the outputPath.
 *
 * @param url the URL of the file to download
 * @param outputPath the path to the save the file to
 * @param useProxy whether to use the configured proxy when downloading files
 * @throws DownloadFailedException is thrown if there is an error downloading the file
 *///from  ww  w .  j a  v  a2  s . c  o m
public static void fetchFile(URL url, File outputPath, boolean useProxy) throws DownloadFailedException {
    if ("file".equalsIgnoreCase(url.getProtocol())) {
        File file;
        try {
            file = new File(url.toURI());
        } catch (URISyntaxException ex) {
            final String msg = String.format("Download failed, unable to locate '%s'", url.toString());
            throw new DownloadFailedException(msg);
        }
        if (file.exists()) {
            try {
                org.apache.commons.io.FileUtils.copyFile(file, outputPath);
            } catch (IOException ex) {
                final String msg = String.format("Download failed, unable to copy '%s'", url.toString());
                throw new DownloadFailedException(msg);
            }
        } else {
            final String msg = String.format("Download failed, file does not exist '%s'", url.toString());
            throw new DownloadFailedException(msg);
        }
    } else {
        HttpURLConnection conn = null;
        try {
            conn = URLConnectionFactory.createHttpURLConnection(url, useProxy);
            conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
            conn.connect();
        } catch (IOException ex) {
            try {
                if (conn != null) {
                    conn.disconnect();
                }
            } finally {
                conn = null;
            }
            throw new DownloadFailedException("Error downloading file.", ex);
        }
        final String encoding = conn.getContentEncoding();

        BufferedOutputStream writer = null;
        InputStream reader = null;
        try {
            if (encoding != null && "gzip".equalsIgnoreCase(encoding)) {
                reader = new GZIPInputStream(conn.getInputStream());
            } else if (encoding != null && "deflate".equalsIgnoreCase(encoding)) {
                reader = new InflaterInputStream(conn.getInputStream());
            } else {
                reader = conn.getInputStream();
            }

            writer = new BufferedOutputStream(new FileOutputStream(outputPath));
            final byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = reader.read(buffer)) > 0) {
                writer.write(buffer, 0, bytesRead);
            }
        } catch (Throwable ex) {
            throw new DownloadFailedException("Error saving downloaded file.", ex);
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (Throwable ex) {
                    LOGGER.log(Level.FINEST, "Error closing the writer in Downloader.", ex);
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (Throwable ex) {
                    LOGGER.log(Level.FINEST, "Error closing the reader in Downloader.", ex);
                }
            }
            try {
                conn.disconnect();
            } finally {
                conn = null;
            }
        }
    }
}

From source file:ubicrypt.core.provider.RemoteRepository.java

@Override
public Observable<InputStream> get(final UbiFile file) {
    return fileGetter.call(file, (rfile, is) -> monitor(new FileProvenience(file, this),
            new InflaterInputStream(AESGCM.decryptIs(rfile.getKey().getBytes(), is))));
}

From source file:org.nickelproject.util.IoUtil.java

/**
 * Uncompress the given byte array using the delfate algorithm and return
 * the uncompressed byte array./*  www  .  j a v  a 2  s. c o  m*/
 */
public static byte[] inflate(final byte[] pInput) throws IOException {
    final ByteArrayInputStream vByteArrayStream = new ByteArrayInputStream(pInput);
    final ByteArrayOutputStream vByteArrayOutputStream = new ByteArrayOutputStream(pInput.length);
    final InputStream vInflaterStream = new InflaterInputStream(vByteArrayStream);
    ByteStreams.copy(vInflaterStream, vByteArrayOutputStream);
    vInflaterStream.close();
    final byte[] vUnCompressedBytes = vByteArrayOutputStream.toByteArray();
    return vUnCompressedBytes;
}