Example usage for java.io IOException initCause

List of usage examples for java.io IOException initCause

Introduction

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

Prototype

public synchronized Throwable initCause(Throwable cause) 

Source Link

Document

Initializes the cause of this throwable to the specified value.

Usage

From source file:gov.nasa.ensemble.common.io.FileUtilities.java

/**
 * This function will copy files or directories from one location to another. note that the source and the destination must be mutually exclusive. This function can not be used to copy a directory
 * to a sub directory of itself. The function will also have problems if the destination files already exist.
 * //from ww w  . java 2  s  .co m
 * @param src
 *            -- A File object that represents the source for the copy
 * @param dest
 *            -- A File object that represnts the destination for the copy.
 * @throws IOException
 *             if unable to copy.
 */
public static void copyFiles(File src, File dest) throws IOException {
    // Check to ensure that the source is valid...
    if (!src.exists()) {
        throw new IOException("copyFiles: Can not find source: " + src.getAbsolutePath() + ".");
    } else if (!src.canRead()) { // check to ensure we have rights to the source...
        throw new IOException("copyFiles: No right to source: " + src.getAbsolutePath() + ".");
    }
    // is this a directory copy?
    if (src.isDirectory()) {
        if (!dest.exists()) { // does the destination already exist?
            // if not we need to make it exist if possible (note this is mkdirs not mkdir)
            if (!dest.mkdirs()) {
                throw new IOException("copyFiles: Could not create direcotry: " + dest.getAbsolutePath() + ".");
            }
        }
        // get a listing of files...
        String list[] = src.list();
        // copy all the files in the list.
        for (int i = 0; i < list.length; i++) {
            File dest1 = new File(dest, list[i]);
            File src1 = new File(src, list[i]);
            copyFiles(src1, dest1);
        }
    } else {
        // This was not a directory, so lets just copy the file
        FileInputStream fin = null;
        FileOutputStream fout = null;
        byte[] buffer = new byte[4096]; // Buffer 4K at a time (you can change this).
        int bytesRead;
        try {
            // open the files for input and output
            fin = new FileInputStream(src);
            fout = new FileOutputStream(dest);
            // while bytesRead indicates a successful read, lets write...
            while ((bytesRead = fin.read(buffer)) >= 0) {
                fout.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) { // Error copying file...
            IOException wrapper = new IOException("copyFiles: Unable to copy file: " + src.getAbsolutePath()
                    + "to" + dest.getAbsolutePath() + ".");
            wrapper.initCause(e);
            wrapper.setStackTrace(e.getStackTrace());
            throw wrapper;
        } finally { // Ensure that the files are closed (if they were open).
            if (fin != null) {
                fin.close();
            }
            if (fout != null) {
                fout.close();
            }
        }
    }
}

From source file:org.kymjs.kjframe.http.httpclient.HttpRequestBuilder.java

private static KeyStore loadCertificates(Context context) throws IOException {
    try {//from  ww  w  .  j  a  v a 2 s  .c  om
        final KeyStore localTrustStore = KeyStore.getInstance("BKS");
        final InputStream in = context.getResources().openRawResource(R.raw.hc_keystore);
        try {
            localTrustStore.load(in, null);
        } finally {
            in.close();
        }

        return localTrustStore;
    } catch (Exception e) {
        final IOException ioe = new IOException("Failed to load SSL certificates");
        ioe.initCause(e);
        throw ioe;
    }
}

From source file:org.apache.hadoop.hdfs.server.datanode.CachingBlockSender.java

/**
 * Converts an IOExcpetion (not subclasses) to SocketException.
 * This is typically done to indicate to upper layers that the error
 * was a socket error rather than often more serious exceptions like
 * disk errors.//from   w ww.j  a v  a  2 s  . c  o m
 */
private static IOException ioeToSocketException(IOException ioe) {

    if (ioe.getClass().equals(IOException.class)) {
        // "se" could be a new class in stead of SocketException.
        final IOException se = new SocketException("Original Exception : " + ioe);
        se.initCause(ioe);
        /*
         * Change the stacktrace so that original trace is not truncated
         * when printed.
         */
        se.setStackTrace(ioe.getStackTrace());
        return se;
    }
    // otherwise just return the same exception.
    return ioe;
}

From source file:org.kymjs.kjframe.http.httpclient.HttpRequestBuilder.java

/**
 * Setup SSL connection./*from  w  ww  .  ja va2 s.  co m*/
 */
private static void setupSecureConnection(Context context, HttpsURLConnection conn) throws IOException {
    final SSLContext sslContext;
    try {
        // SSL certificates are provided by the Guardian Project:
        // https://github.com/guardianproject/cacert
        if (trustManagers == null) {
            // Load SSL certificates:
            // http://nelenkov.blogspot.com/2011/12/using-custom-certificate-trust-store-on.html
            // Earlier Android versions do not have updated root CA
            // certificates, resulting in connection errors.
            final KeyStore keyStore = loadCertificates(context);

            final CustomTrustManager customTrustManager = new CustomTrustManager(keyStore);
            trustManagers = new TrustManager[] { customTrustManager };
        }

        // Init SSL connection with custom certificates.
        // The same SecureRandom instance is used for every connection to
        // speed up initialization.
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagers, SECURE_RANDOM);
    } catch (GeneralSecurityException e) {
        final IOException ioe = new IOException("Failed to initialize SSL engine");
        ioe.initCause(e);
        throw ioe;
    }

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        // Fix slow read:
        // http://code.google.com/p/android/issues/detail?id=13117
        // Prior to ICS, the host name is still resolved even if we already
        // know its IP address, for each connection.
        final SSLSocketFactory delegate = sslContext.getSocketFactory();
        final SSLSocketFactory socketFactory = new SSLSocketFactory() {
            @Override
            public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
                InetAddress addr = InetAddress.getByName(host);
                injectHostname(addr, host);
                return delegate.createSocket(addr, port);
            }

            @Override
            public Socket createSocket(InetAddress host, int port) throws IOException {
                return delegate.createSocket(host, port);
            }

            @Override
            public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
                    throws IOException, UnknownHostException {
                return delegate.createSocket(host, port, localHost, localPort);
            }

            @Override
            public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort)
                    throws IOException {
                return delegate.createSocket(address, port, localAddress, localPort);
            }

            private void injectHostname(InetAddress address, String host) {
                try {
                    Field field = InetAddress.class.getDeclaredField("hostName");
                    field.setAccessible(true);
                    field.set(address, host);
                } catch (Exception ignored) {
                }
            }

            @Override
            public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
                injectHostname(s.getInetAddress(), host);
                return delegate.createSocket(s, host, port, autoClose);
            }

            @Override
            public String[] getDefaultCipherSuites() {
                return delegate.getDefaultCipherSuites();
            }

            @Override
            public String[] getSupportedCipherSuites() {
                return delegate.getSupportedCipherSuites();
            }
        };
        conn.setSSLSocketFactory(socketFactory);
    } else {
        conn.setSSLSocketFactory(sslContext.getSocketFactory());
    }

    conn.setHostnameVerifier(new BrowserCompatHostnameVerifier());
}

From source file:org.apache.hadoop.hbase.util.CommonFSUtils.java

/**
 * Verifies root directory path is a valid URI with a scheme
 *
 * @param root root directory path//  w  w  w .  j a v a2 s  .  c  om
 * @return Passed <code>root</code> argument.
 * @throws IOException if not a valid URI with a scheme
 */
public static Path validateRootPath(Path root) throws IOException {
    try {
        URI rootURI = new URI(root.toString());
        String scheme = rootURI.getScheme();
        if (scheme == null) {
            throw new IOException("Root directory does not have a scheme");
        }
        return root;
    } catch (URISyntaxException e) {
        IOException io = new IOException("Root directory path is not a valid " + "URI -- check your "
                + HConstants.HBASE_DIR + " configuration");
        io.initCause(e);
        throw io;
    }
}

From source file:org.apache.maven.doxia.siterenderer.DefaultSiteRenderer.java

private static ZipFile getZipFile(File file) throws IOException {
    if (file == null) {
        throw new IOException("Error opening ZipFile: null");
    }/* ww  w. j  a  v  a 2s. c o  m*/

    try {
        // TODO: plexus-archiver, if it could do the excludes
        return new ZipFile(file);
    } catch (ZipException ex) {
        IOException ioe = new IOException("Error opening ZipFile: " + file.getAbsolutePath());
        ioe.initCause(ex);
        throw ioe;
    }
}

From source file:com.google.android.feeds.JsonContentHandler.java

@Override
public Object getContent(URLConnection connection) throws IOException {
    String json = ContentHandlerUtils.toString(connection);
    try {/*  ww w  .j a  va  2s. com*/
        // Pass the JSON string to handler where it can be
        // interpreted as an object or an array.
        return getContent(json);
    } catch (JSONException e) {
        // Re-throw JSONException as IOException because
        // ContentHandler implementations are only allowed 
        // to throw IOExceptions.
        IOException ioe = new IOException();
        ioe.initCause(e);
        throw ioe;
    }
}

From source file:org.mule.transport.tcp.protocols.CustomClassLoadingLengthProtocol.java

@Override
public Object read(InputStream is) throws IOException {
    byte[] bytes = (byte[]) super.read(is);

    if (bytes == null) {
        return null;
    } else {//from   w w w  .  j  a  v  a2s. c  o m
        ClassLoaderObjectInputStream classLoaderIS = new ClassLoaderObjectInputStream(this.getClassLoader(),
                is);
        try {
            return classLoaderIS.readObject();
        } catch (ClassNotFoundException e) {
            logger.warn(e.getMessage());
            IOException iox = new IOException();
            iox.initCause(e);
            throw iox;
        } finally {
            classLoaderIS.close();
        }
    }
}

From source file:org.cloudata.core.client.scanner.ScannerFactory.java

private static TableScanner openSingleTabletScanner(CloudataConf conf, Row.Key targetRowKey,
        TabletInfo tabletInfo, RowFilter rowFilter) throws IOException {

    if (tabletInfo == null) {
        return null;
    }//from www . j a v a2  s.c  o m

    IOException exception = null;

    long txTimeout = conf.getInt("client.tx.timeout", 60) * 1000;
    long startTime = System.currentTimeMillis();

    String tableName = tabletInfo.getTableName();
    while (true) {
        try {
            SingleTabletScanner tableScanner = new SingleTabletScanner(conf, tabletInfo, rowFilter);
            return tableScanner;
        } catch (IOException e) {
            //LOG.warn("Scanner open error cause:" + e.getMessage() + " but retry, tablet:" + tabletInfo + ", error:" + e.getMessage());
            exception = e;
        } catch (Exception e) {
            LOG.error("Scanner open error cause:" + e.getMessage() + ", tablet:" + tabletInfo, e);
            exception = new IOException(e.getMessage());
            exception.initCause(e);
            throw exception;
        }

        if (tabletInfo != null) {
            TabletLocationCache.getInstance(conf).clearTabletCache(tabletInfo.getTableName(), targetRowKey,
                    tabletInfo);
        }
        try {
            tabletInfo = CTable.lookupTargetTablet(conf, tableName, targetRowKey);
        } catch (Exception err) {
            LOG.error("Scanner open error while lookupTargetTablet cause:" + err.getMessage() + " but retry:"
                    + tabletInfo.getTableName() + ",rowKey=" + targetRowKey);
        }

        if ((System.currentTimeMillis() - startTime) > txTimeout) {
            break;
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }
    }

    if (exception == null) {
        throw new IOException("fail open Scanner " + txTimeout + " ms tabletInfo=" + tabletInfo);
    } else {
        LOG.warn("Can't open scanner:" + tabletInfo + "," + exception.getMessage());
        throw CTableManager.makeIOException(exception);
    }
}

From source file:com.rabbitmq.client.test.performance.QosScaling.java

protected long drain(QueueingConsumer c) throws IOException {
    long start = System.nanoTime();
    try {/*from   w  ww .  jav  a2s . c  om*/
        for (int i = 0; i < params.messageCount; i++) {
            long tag = c.nextDelivery().getEnvelope().getDeliveryTag();
            channel.basicAck(tag, false);
        }
    } catch (InterruptedException e) {
        IOException ioe = new IOException();
        ioe.initCause(e);
        throw ioe;
    }
    long finish = System.nanoTime();
    return finish - start;
}