Example usage for java.io IOException getCause

List of usage examples for java.io IOException getCause

Introduction

In this page you can find the example usage for java.io IOException getCause.

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:org.apache.pdfbox.pdmodel.encryption.SecurityHandler.java

/**
 * Encrypt or decrypt data with AES256./*from   w ww.  j  a va2s  .c  o m*/
 *
 * @param data The data to encrypt.
 * @param output The output to write the encrypted data to.
 * @param decrypt true to decrypt the data, false to encrypt it.
 *
 * @throws IOException If there is an error reading the data.
 */
private void encryptDataAES256(InputStream data, OutputStream output, boolean decrypt) throws IOException {
    byte[] iv = new byte[16];

    if (decrypt) {
        // read IV from stream
        data.read(iv);
    } else {
        // generate random IV and write to stream
        SecureRandom rnd = new SecureRandom();
        rnd.nextBytes(iv);
        output.write(iv);
    }

    Cipher cipher;
    try {
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec keySpec = new SecretKeySpec(encryptionKey, "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(iv);
        cipher.init(decrypt ? Cipher.DECRYPT_MODE : Cipher.ENCRYPT_MODE, keySpec, ivSpec);
    } catch (GeneralSecurityException e) {
        throw new IOException(e);
    }

    CipherInputStream cis = new CipherInputStream(data, cipher);
    try {
        IOUtils.copy(cis, output);
    } catch (IOException exception) {
        // starting with java 8 the JVM wraps an IOException around a GeneralSecurityException
        // it should be safe to swallow a GeneralSecurityException
        if (!(exception.getCause() instanceof GeneralSecurityException)) {
            throw exception;
        }
        LOG.debug("A GeneralSecurityException occured when decrypting some stream data", exception);
    } finally {
        cis.close();
    }
}

From source file:org.bankinterface.util.HttpClient.java

private InputStream sendHttpRequestStream(String method, boolean overrideTrust) throws HttpClientException {

    String arguments = null;//from   w  ww . j  av a  2 s.  co  m
    InputStream in = null;

    if (url == null) {
        throw new HttpClientException("Cannot process a null URL.");
    }

    if (rawStream != null) {
        arguments = rawStream;
    } else if (parameters != null) {
        arguments = urlEncodeArgs(parameters);
    }

    // Append the arguments to the query string if GET.
    if (method.equalsIgnoreCase("get") && arguments != null) {
        if (url.contains("?")) {
            url = url + "&" + arguments;
        } else {
            url = url + "?" + arguments;
        }
    }

    // Create the URL and open the connection.
    try {
        requestUrl = new URL(url);
        if (overrideTrust) {
            con = URLConnector.openUntrustedConnection(requestUrl, timeout, clientCertAlias, hostVerification);
        } else {
            con = URLConnector.openConnection(requestUrl, timeout, clientCertAlias, hostVerification);
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Connection opened to : " + requestUrl.toExternalForm());
        }

        if ((con instanceof HttpURLConnection)) {
            ((HttpURLConnection) con).setInstanceFollowRedirects(followRedirects);
            if (logger.isDebugEnabled()) {
                logger.debug("Connection is of type HttpURLConnection, more specifically: "
                        + con.getClass().getName());
            }
        }

        // set the content type
        if (contentType != null) {
            con.setRequestProperty("Content-type", contentType);
        }

        // connection settings
        con.setDoOutput(true);
        con.setUseCaches(false);
        if (keepAlive) {
            con.setRequestProperty("Connection", "Keep-Alive");
        }

        if (method.equalsIgnoreCase("post")) {
            if (contentType == null) {
                con.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
            }
            con.setDoInput(true);
        }

        // if there is basicAuth info set the request property for it
        if (basicAuthUsername != null) {
            String token = basicAuthUsername + ":" + (basicAuthPassword == null ? "" : basicAuthPassword);
            String basicAuthString = "Basic " + Base64.encodeBase64String(token.getBytes());
            con.setRequestProperty("Authorization", basicAuthString);
            if (logger.isDebugEnabled()) {
                logger.debug("Header - Authorization: " + basicAuthString);
            }
        }

        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                String headerName = entry.getKey();
                String headerValue = entry.getValue();
                con.setRequestProperty(headerName, headerValue);
                if (logger.isDebugEnabled()) {
                    logger.debug("Header - " + headerName + ": " + headerValue);
                }
            }
        }

        if (method.equalsIgnoreCase("post")) {
            OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream(),
                    this.streamCharset != null ? this.streamCharset : "UTF-8");
            if (logger.isDebugEnabled()) {
                logger.debug("Opened output stream");
            }

            if (arguments != null) {
                out.write(arguments);
                if (logger.isDebugEnabled()) {
                    logger.debug("Wrote arguements (parameters) : " + arguments);
                }
            }

            out.flush();
            out.close();
            if (logger.isDebugEnabled()) {
                logger.debug("Flushed and closed buffer");
            }
        }

        if (logger.isDebugEnabled()) {
            Map<String, List<String>> headerFields = con.getHeaderFields();
            logger.debug("Header Fields : " + headerFields);
        }

        in = con.getInputStream();
    } catch (IOException ioe) {
        if ((trustAny && !overrideTrust) && (ioe.getCause() instanceof CertificateException)) {
            logger.warn("Try again override Trust");
            return sendHttpRequestStream(method, true);
        }
        throw new HttpClientException("IO Error processing request", ioe);
    } catch (Exception e) {
        throw new HttpClientException("Error processing request", e);
    }

    return in;
}

From source file:com.streamsets.pipeline.stage.destination.hdfs.HdfsTargetConfigBean.java

private FileSystem getFileSystemForInitDestroy() throws Exception {
    try {//from ww  w  .ja  v a2  s .  co m
        return getUGI().doAs(new PrivilegedExceptionAction<FileSystem>() {
            @Override
            public FileSystem run() throws Exception {
                return FileSystem.get(new URI(hdfsUri), hdfsConfiguration);
            }
        });
    } catch (IOException ex) {
        throw ex;
    } catch (RuntimeException ex) {
        Throwable cause = ex.getCause();
        if (cause instanceof Exception) {
            throw (Exception) cause;
        }
        throw ex;
    }
}

From source file:nl.strohalm.cyclos.http.BaseWebServiceTransactionFilter.java

@Override
protected void execute(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain chain) throws IOException, ServletException {
    // Run the request in a new transaction
    try {/*  www. j  a va 2  s .co  m*/
        transactionHelper.runInCurrentThread(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(final TransactionStatus status) {
                // When debug is enabled, log the transaction begin and add a listener for transaction end log
                prepareDebugLog();

                // Execute the workflow
                try {
                    onBeforeRunInTransaction(request, response);
                    doRunInTransaction(request, response, chain, status);
                } catch (final Throwable t) {
                    try {
                        onError(request, response, t);
                    } catch (final IOException e) {
                        throw new NestableRuntimeException(e);
                    }
                } finally {
                    try {
                        onTransactionEnd(request, response);
                    } catch (final IOException e) {
                        throw new NestableRuntimeException(e);
                    }
                }
            }
        });
    } catch (final NestableRuntimeException e) {
        final Throwable cause = e.getCause();
        if (cause instanceof IOException) {
            throw (IOException) cause;
        }
        if (cause instanceof ServletException) {
            throw (ServletException) cause;
        }
        throw e;
    } finally {
        // Cleanup the thread locals
        WebServiceContext.cleanup();
        LoggedUser.cleanup();
    }
}

From source file:org.apache.hadoop.hbase.regionserver.HMobStore.java

/**
 * Reads the cell from a mob file./*from  w ww .  j av  a  2s .  co  m*/
 * The mob file might be located in different directories.
 * 1. The working directory.
 * 2. The archive directory.
 * Reads the cell from the files located in both of the above directories.
 * @param locations The possible locations where the mob files are saved.
 * @param fileName The file to be read.
 * @param search The cell to be searched.
 * @param cacheMobBlocks Whether the scanner should cache blocks.
 * @param readPt the read point.
 * @param readEmptyValueOnMobCellMiss Whether return null value when the mob file is
 *        missing or corrupt.
 * @return The found cell. Null if there's no such a cell.
 * @throws IOException
 */
private Cell readCell(List<Path> locations, String fileName, Cell search, boolean cacheMobBlocks, long readPt,
        boolean readEmptyValueOnMobCellMiss) throws IOException {
    FileSystem fs = getFileSystem();
    Throwable throwable = null;
    for (Path location : locations) {
        MobFile file = null;
        Path path = new Path(location, fileName);
        try {
            file = mobCacheConfig.getMobFileCache().openFile(fs, path, mobCacheConfig);
            return readPt != -1 ? file.readCell(search, cacheMobBlocks, readPt)
                    : file.readCell(search, cacheMobBlocks);
        } catch (IOException e) {
            mobCacheConfig.getMobFileCache().evictFile(fileName);
            throwable = e;
            if ((e instanceof FileNotFoundException) || (e.getCause() instanceof FileNotFoundException)) {
                LOG.warn("Fail to read the cell, the mob file " + path + " doesn't exist", e);
            } else if (e instanceof CorruptHFileException) {
                LOG.error("The mob file " + path + " is corrupt", e);
                break;
            } else {
                throw e;
            }
        } catch (NullPointerException e) { // HDFS 1.x - DFSInputStream.getBlockAt()
            mobCacheConfig.getMobFileCache().evictFile(fileName);
            LOG.warn("Fail to read the cell", e);
            throwable = e;
        } catch (AssertionError e) { // assert in HDFS 1.x - DFSInputStream.getBlockAt()
            mobCacheConfig.getMobFileCache().evictFile(fileName);
            LOG.warn("Fail to read the cell", e);
            throwable = e;
        } finally {
            if (file != null) {
                mobCacheConfig.getMobFileCache().closeFile(file);
            }
        }
    }
    LOG.error("The mob file " + fileName + " could not be found in the locations " + locations
            + " or it is corrupt");
    if (readEmptyValueOnMobCellMiss) {
        return null;
    } else if (throwable instanceof IOException) {
        throw (IOException) throwable;
    } else {
        throw new IOException(throwable);
    }
}

From source file:org.osaf.cosmo.atom.provider.DetachedItemCollectionAdapter.java

@Override
public ResponseContext postEntry(RequestContext request) {
    DetachedItemTarget target = (DetachedItemTarget) request.getTarget();
    NoteItem master = target.getMaster();
    NoteItem occurrence = target.getOccurrence();

    if (log.isDebugEnabled())
        log.debug("detaching occurrence " + occurrence.getUid() + " from master " + master.getUid());

    ResponseContext frc = checkEntryWritePreconditions(request);
    if (frc != null)
        return frc;

    try {//from w  ww  .  j a v a  2 s  .co  m
        // XXX: does abdera automatically resolve external content?
        Entry entry = (Entry) request.getDocument().getRoot();
        ContentProcessor processor = createContentProcessor(entry);
        NoteItem detached = (NoteItem) master.copy();
        processor.processContent(entry.getContent(), detached);
        detached = detachOccurrence(master, detached, occurrence);

        ItemTarget itemTarget = new ItemTarget(request, detached, target.getProjection(), target.getFormat());
        ServiceLocator locator = createServiceLocator(request);
        ItemFeedGenerator generator = createItemFeedGenerator(itemTarget, locator);
        entry = generator.generateEntry(detached);

        return created(request, entry, detached, locator);
    } catch (IOException e) {
        String reason = "Unable to read request content: " + e.getMessage();
        log.error(reason, e);
        return ProviderHelper.servererror(request, reason, e);
    } catch (UnsupportedContentTypeException e) {
        return ProviderHelper.badrequest(request, "Entry content type must be one of "
                + StringUtils.join(getProcessorFactory().getSupportedContentTypes(), ", "));
    } catch (ParseException e) {
        String reason = "Unparseable content: ";
        if (e.getCause() != null)
            reason = reason + e.getCause().getMessage();
        else
            reason = reason + e.getMessage();
        return ProviderHelper.badrequest(request, reason);
    } catch (ValidationException e) {
        String reason = "Invalid content: ";
        if (e.getCause() != null)
            reason = reason + e.getCause().getMessage();
        else
            reason = reason + e.getMessage();
        return ProviderHelper.badrequest(request, reason);
    } catch (UidInUseException e) {
        return ProviderHelper.conflict(request, "Uid already in use");
    } catch (ProcessorException e) {
        String reason = "Unknown content processing error: " + e.getMessage();
        log.error(reason, e);
        return ProviderHelper.servererror(request, reason, e);
    } catch (CollectionLockedException e) {
        return locked(request);
    } catch (GeneratorException e) {
        String reason = "Unknown entry generation error: " + e.getMessage();
        log.error(reason, e);
        return ProviderHelper.servererror(request, reason, e);
    } catch (CosmoSecurityException e) {
        if (e instanceof ItemSecurityException)
            return insufficientPrivileges(request,
                    new InsufficientPrivilegesException((ItemSecurityException) e));
        else
            return ProviderHelper.forbidden(request, e.getMessage());
    }
}

From source file:org.alfresco.filesys.alfresco.AlfrescoTxDiskDriver.java

/**
 * Perform a retryable operation in a write transaction
 * <p>//ww w. java 2s  .  c o m
 * WARNING : side effect - that the current transaction, if any, is ended.
 * 
 * 
 * @param sess
 *            the server session
 * @param callback
 *            callback for the retryable operation
 * @return the result of the operation
 * @throws IOException
 */
public <T> T doInWriteTransaction(SrvSession sess, final CallableIO<T> callback) throws IOException {
    Boolean wasInRetryingTransaction = m_inRetryingTransaction.get();
    try {
        boolean hadTransaction = sess.hasTransaction();
        if (hadTransaction) {
            sess.endTransaction();
        }
        m_inRetryingTransaction.set(Boolean.TRUE);
        T result = m_transactionService.getRetryingTransactionHelper()
                .doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<T>() {
                    public T execute() throws Throwable {
                        try {
                            return callback.call();
                        } catch (IOException e) {
                            // Ensure original checked IOExceptions get propagated
                            throw new PropagatingException(e);
                        }
                    }
                });
        if (hadTransaction) {
            beginReadTransaction(sess);
        }
        return result;
    } catch (PropagatingException e) {
        // Unwrap checked exceptions
        throw (IOException) e.getCause();
    } finally {
        m_inRetryingTransaction.set(wasInRetryingTransaction);
    }
}

From source file:org.apache.hadoop.crypto.key.JavaKeyStoreProvider.java

private boolean isBadorWrongPassword(IOException ioe) {
    // As per documentation this is supposed to be the way to figure
    // if password was correct
    if (ioe.getCause() instanceof UnrecoverableKeyException) {
        return true;
    }/*from  w w  w .j  av  a  2  s .  c  om*/
    // Unfortunately that doesn't seem to work..
    // Workaround :
    if ((ioe.getCause() == null) && (ioe.getMessage() != null)
            && ((ioe.getMessage().contains("Keystore was tampered"))
                    || (ioe.getMessage().contains("password was incorrect")))) {
        return true;
    }
    return false;
}

From source file:de.comlineag.snc.webcrawler.fetcher.PageFetcher.java

public PageFetchResult fetchHeader(WebURL webUrl) {
    PageFetchResult fetchResult = new PageFetchResult();
    String toFetchURL = webUrl.getURL();
    HttpGet get = null;/*  ww w.  ja v a2  s. c o m*/
    try {
        get = new HttpGet(toFetchURL);
        synchronized (mutex) {
            long now = (new Date()).getTime();
            if (now - lastFetchTime < config.getPolitenessDelay()) {
                Thread.sleep(config.getPolitenessDelay() - (now - lastFetchTime));
            }
            lastFetchTime = (new Date()).getTime();
        }

        HttpResponse response = httpClient.execute(get);
        fetchResult.setEntity(response.getEntity());
        fetchResult.setResponseHeaders(response.getAllHeaders());

        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            if (statusCode != HttpStatus.SC_NOT_FOUND) {
                if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                        || statusCode == HttpStatus.SC_MOVED_TEMPORARILY
                        || statusCode == HttpStatus.SC_MULTIPLE_CHOICES || statusCode == HttpStatus.SC_SEE_OTHER
                        || statusCode == HttpStatus.SC_TEMPORARY_REDIRECT
                        || statusCode == CustomFetchStatus.SC_PERMANENT_REDIRECT) {
                    Header header = response.getFirstHeader("Location");
                    if (header != null) {
                        String movedToUrl = header.getValue();
                        movedToUrl = URLCanonicalizer.getCanonicalURL(movedToUrl, toFetchURL);
                        fetchResult.setMovedToUrl(movedToUrl);
                    }
                    fetchResult.setStatusCode(statusCode);
                    return fetchResult;
                }
                logger.info("Failed: {}, while fetching {}", response.getStatusLine().toString(), toFetchURL);
            }
            fetchResult.setStatusCode(response.getStatusLine().getStatusCode());
            return fetchResult;
        }

        fetchResult.setFetchedUrl(toFetchURL);
        String uri = get.getURI().toString();
        if (!uri.equals(toFetchURL)) {
            if (!URLCanonicalizer.getCanonicalURL(uri).equals(toFetchURL)) {
                fetchResult.setFetchedUrl(uri);
            }
        }

        if (fetchResult.getEntity() != null) {
            long size = fetchResult.getEntity().getContentLength();
            if (size == -1) {
                Header length = response.getLastHeader("Content-Length");
                if (length == null) {
                    length = response.getLastHeader("Content-length");
                }
                if (length != null) {
                    size = Integer.parseInt(length.getValue());
                } else {
                    size = -1;
                }
            }
            if (size > config.getMaxDownloadSize()) {
                fetchResult.setStatusCode(CustomFetchStatus.PageTooBig);
                get.abort();
                logger.warn("Failed: Page Size (" + size + ") exceeded max-download-size ("
                        + config.getMaxDownloadSize() + "), at URL: " + webUrl.getURL());
                return fetchResult;
            }

            fetchResult.setStatusCode(HttpStatus.SC_OK);
            return fetchResult;
        }

        get.abort();

    } catch (IOException e) {
        if (toFetchURL.toLowerCase().endsWith("robots.txt")) {
            // Ignoring this Exception as it just means that we tried to parse a robots.txt file which this site doesn't have
            // Which is ok, so no exception should be thrown
        } else {
            logger.error("Fatal transport error: " + e.getMessage() != null ? e.getMessage()
                    : e.getCause() + " while fetching " + toFetchURL + " (link found in doc #"
                            + webUrl.getParentDocid() + ")");
            logger.debug("Stacktrace: ", e);
            fetchResult.setStatusCode(CustomFetchStatus.FatalTransportError);
            return fetchResult;
        }
    } catch (IllegalStateException e) {
        // ignoring exceptions that occur because of not registering https
        // and other schemes
    } catch (Exception e) {
        logger.error("{} Error while fetching {}", e.getMessage() != null ? e.getMessage() : e.getCause(),
                webUrl.getURL());
        logger.debug("Stacktrace:", e);
    } finally {
        try {
            if (fetchResult.getEntity() == null && get != null) {
                get.abort();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    fetchResult.setStatusCode(CustomFetchStatus.UnknownError);
    logger.error("Failed: Unknown error occurred while fetching {}", webUrl.getURL());
    return fetchResult;
}

From source file:ch.entwine.weblounge.common.impl.request.RequestUtils.java

/**
 * Returns <code>true</code> if the exception was caused by the client closing
 * the connection.//from   w w w .  j  av  a2 s.com
 * 
 * @param e
 *          the exception
 * @return <code>true</code> if the client caused
 */
public static boolean isCausedByClient(IOException e) {
    Throwable cause = e.getCause();
    if (cause == null)
        return false;
    if ("Broken pipe".equals(cause.getMessage()))
        return true;
    if ("Connection reset by peer".equals(cause.getMessage()))
        return true;
    return false;
}