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:com.wfreitas.camelsoap.SoapClient.java

private WsdlInterface[] getWsdlInterfaces(String wsdl, Properties httpClientProps) throws IOException {
    try {/*from   w  ww  .j  ava  2  s  .c o m*/
        WsdlInterface[] wsdlInterfaces = wsdls.get(wsdl);
        if (wsdlInterfaces == null) {
            WsdlProject wsdlProject = new WsdlProject();
            wsdlInterfaces = wsdlProject.importWsdl(wsdl, true, createWsdlLoader(wsdl, httpClientProps));
            wsdls.put(wsdl, wsdlInterfaces);
        }
        return wsdlInterfaces;
    } catch (Exception e) {
        IOException ioe = new IOException("Failed to import WSDL '" + wsdl + "'.");
        ioe.initCause(e);
        throw ioe;
    }
}

From source file:org.paxle.crawler.impl.CrawlerTools.java

/**
 * Copies all data from the given {@link InputStream} to the given {@link ICrawlerDocument crawler-document}.<br />
 * Additionally this function ...//from w  ww. j  a v a2s. c om
 * <ul>
 *    <li>detects the charset-encoding of the content using an {@link ICharsetDetector}</li>
 *  <li>detects the mime-type of the content using an {@link IMimeTypeDetector}</li>
 *  <li>generates a MD5 checksum of the content using an {@link ICryptManager}</li>
 * </ul>
 * 
 * @see #copy(InputStream, OutputStream, long) for details
 * @param doc the crawler-document the content belongs to
 * @param is the stream to read from
 * @param lrc the {@link LimitedRateCopier} to use to copy the data, if any, otherwise <code>null</code>
 * @param maxFileSize max allowed content-size to copy in bytes or <code>-1</code>
 * @return the number of copied bytes
 * 
 * @throws IOException if an I/O-error occures
 * @throws ContentLengthLimitExceededException if the content-length read via the input stream exceeds the
 *    limit defined via maxFileSize
 */
public long saveInto(ICrawlerDocument doc, InputStream is, final ILimitedRateCopier lrc, final int maxFileSize)
        throws IOException, ContentLengthLimitExceededException {
    if (doc == null)
        throw new NullPointerException("The crawler-document is null.");
    if (is == null)
        throw new NullPointerException("The content inputstream is null.");

    // testing if the charset is supported by java
    if (doc.getCharset() != null && isUnsupportedCharset(doc.getCharset())) {
        logger.warn(String.format("The resource '%s' has an unsupported charset '%s'. Resetting charset ...",
                doc.getLocation(), doc.getCharset()));
        doc.setCharset(null);
    }

    File file = null;
    OutputStream os = null;
    try {
        // init file output-stream
        file = this.tfm.createTempFile();
        os = new BufferedOutputStream(new FileOutputStream(file));

        // limit file size
        ContentLengthLimitOutputStream tos = null;
        if (maxFileSize != -1) {
            tos = new ContentLengthLimitOutputStream(maxFileSize, os);
            os = tos;
        }

        // init charset detection stream
        ACharsetDetectorOutputStream chardetos = null;
        if (this.chardet != null) {
            chardetos = this.chardet.createOutputStream(os);
            os = chardetos;
        }

        // init md5-calculation stream
        ACryptOutputStream md5os = null;
        final ICrypt md5 = (cryptManager == null) ? null : cryptManager.getCrypt("md5");
        if (md5 != null) {
            md5os = md5.createOutputStream(os);
            os = md5os;
        }

        /* ================================================================
         * COPY DATA
         * ================================================================ */
        final long copied = (lrc == null) ? ioTools.copy(is, os) : lrc.copy(is, os, -1);

        /* ================================================================
         * CHARSET DETECTION
         * ================================================================ */
        if (chardetos != null) {
            final String charset = chardetos.getCharset();
            if (charset == null || charset.length() == 0) {
                logger.debug(String.format(
                        "The CharsetDetector was unable to determine the charset for resource '%s'.",
                        doc.getLocation()));
            } else if (isUnsupportedCharset(charset)) {
                logger.warn(String.format(
                        "The CharsetDetector detected an unsupported charset '%s' for resource '%s'.", charset,
                        doc.getLocation()));
            } else {
                doc.setCharset(charset);
                logger.debug(String.format("The CharsetDetector detected charset '%s' for resource '%s'.",
                        charset, doc.getLocation()));
            }
        }

        /* ================================================================
         * MD5-HASH
         * ================================================================ */
        if (md5os != null) {
            final byte[] md5sum = md5os.getHash();
            if (md5sum != null)
                doc.setMD5Sum(md5sum);
        }

        /* ================================================================
         * MIME-TYPE DETECTION
         * ================================================================ */
        if (doc.getMimeType() == null) {
            if (mimeTypeDetector != null) {
                String mimeType = null;
                try {
                    mimeType = mimeTypeDetector.getMimeType(file);
                } catch (Exception e) {
                    logger.warn(String.format(
                            "Unexpected '%s' while trying to determine the mime-type of resource '%s'.",
                            e.getClass().getName(), doc.getLocation()), e);
                }
                logger.debug(String.format("MimeType of resource '%s' was detected as '%s'", doc.getLocation(),
                        mimeType));
                if (mimeType != null)
                    doc.setMimeType(mimeType);
            }
        }

        doc.setContent(file);
        return copied;
    } catch (Throwable e) {
        if (file != null) {
            // closing stream
            try {
                os.close();
            } catch (Exception e2) {
                /* ignore this */
            } finally {
                os = null;
            }

            // releasing temp file
            this.tfm.releaseTempFile(file);
        }

        // re-throw IO-Exceptions
        if (e instanceof IOException)
            throw (IOException) e;

        // convert other exceptions
        IOException ioe = new IOException(e.getMessage());
        ioe.initCause(e);
        throw ioe;
    } finally {
        if (os != null)
            os.close();
    }
}

From source file:org.wso2.andes.server.management.JMXManagedObjectRegistry.java

public void start() throws IOException, ConfigurationException {

    CurrentActor.get().message(ManagementConsoleMessages.STARTUP());

    //check if system properties are set to use the JVM's out-of-the-box JMXAgent
    if (areOutOfTheBoxJMXOptionsSet()) {
        CurrentActor.get().message(ManagementConsoleMessages.READY(true));
        return;/* w w w  .ja  v a  2  s  . c  o  m*/
    }

    IApplicationRegistry appRegistry = ApplicationRegistry.getInstance();
    int port = appRegistry.getConfiguration().getJMXManagementPort();

    //Socket factories for the RMIConnectorServer, either default or SLL depending on configuration
    RMIClientSocketFactory csf;
    RMIServerSocketFactory ssf;

    //check ssl enabled option in config, default to true if option is not set
    boolean sslEnabled = appRegistry.getConfiguration().getManagementSSLEnabled();

    if (sslEnabled) {
        //set the SSL related system properties used by the SSL RMI socket factories to the values
        //given in the configuration file, unless command line settings have already been specified
        String keyStorePath;

        if (System.getProperty("javax.net.ssl.keyStore") != null) {
            keyStorePath = System.getProperty("javax.net.ssl.keyStore");
        } else {
            keyStorePath = appRegistry.getConfiguration().getManagementKeyStorePath();
        }

        //check the keystore path value is valid
        if (keyStorePath == null) {
            throw new ConfigurationException("JMX management SSL keystore path not defined, "
                    + "unable to start SSL protected JMX ConnectorServer");
        } else {
            //ensure the system property is set
            System.setProperty("javax.net.ssl.keyStore", keyStorePath);

            //check the file is usable
            File ksf = new File(keyStorePath);

            if (!ksf.exists()) {
                throw new FileNotFoundException("Cannot find JMX management SSL keystore file " + ksf + "\n"
                        + "Check broker configuration, or see create-example-ssl-stores script"
                        + "in the bin/ directory if you need to generate an example store.");
            }
            if (!ksf.canRead()) {
                throw new FileNotFoundException(
                        "Cannot read JMX management SSL keystore file: " + ksf + ". Check permissions.");
            }

            CurrentActor.get().message(ManagementConsoleMessages.SSL_KEYSTORE(ksf.getAbsolutePath()));
        }

        //check the key store password is set
        if (System.getProperty("javax.net.ssl.keyStorePassword") == null) {

            if (appRegistry.getConfiguration().getManagementKeyStorePassword() == null) {
                throw new ConfigurationException("JMX management SSL keystore password not defined, "
                        + "unable to start requested SSL protected JMX server");
            } else {
                System.setProperty("javax.net.ssl.keyStorePassword",
                        appRegistry.getConfiguration().getManagementKeyStorePassword());
            }
        }

        //create the SSL RMI socket factories
        csf = new SslRMIClientSocketFactory();
        ssf = new SslRMIServerSocketFactory();
    } else {
        //Do not specify any specific RMI socket factories, resulting in use of the defaults.
        csf = null;
        ssf = null;
    }

    //add a JMXAuthenticator implementation the env map to authenticate the RMI based JMX connector server
    RMIPasswordAuthenticator rmipa = new RMIPasswordAuthenticator();
    rmipa.setAuthenticationManager(appRegistry.getAuthenticationManager());
    HashMap<String, Object> env = new HashMap<String, Object>();
    env.put(JMXConnectorServer.AUTHENTICATOR, rmipa);

    /*
     * Start a RMI registry on the management port, to hold the JMX RMI ConnectorServer stub. 
     * Using custom socket factory to prevent anyone (including us unfortunately) binding to the registry using RMI.
     * As a result, only binds made using the object reference will succeed, thus securing it from external change. 
     */
    System.setProperty("java.rmi.server.randomIDs", "true");
    if (_useCustomSocketFactory) {
        _rmiRegistry = LocateRegistry.createRegistry(port, null, new CustomRMIServerSocketFactory());
    } else {
        _rmiRegistry = LocateRegistry.createRegistry(port, null, null);
    }

    CurrentActor.get().message(ManagementConsoleMessages.LISTENING("RMI Registry", port));

    /*
     * We must now create the RMI ConnectorServer manually, as the JMX Factory methods use RMI calls 
     * to bind the ConnectorServer to the registry, which will now fail as for security we have
     * locked it from any RMI based modifications, including our own. Instead, we will manually bind 
     * the RMIConnectorServer stub to the registry using its object reference, which will still succeed.
     * 
     * The registry is exported on the defined management port 'port'. We will export the RMIConnectorServer
     * on 'port +1'. Use of these two well-defined ports will ease any navigation through firewall's. 
     */
    final RMIServerImpl rmiConnectorServerStub = new RMIJRMPServerImpl(port + PORT_EXPORT_OFFSET, csf, ssf,
            env);
    String localHost;
    try {
        localHost = InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException ex) {
        localHost = "127.0.0.1";
    }
    final String hostname = localHost;
    final JMXServiceURL externalUrl = new JMXServiceURL("service:jmx:rmi://" + hostname + ":"
            + (port + PORT_EXPORT_OFFSET) + "/jndi/rmi://" + hostname + ":" + port + "/jmxrmi");

    final JMXServiceURL internalUrl = new JMXServiceURL("rmi", hostname, port + PORT_EXPORT_OFFSET);
    _cs = new RMIConnectorServer(internalUrl, env, rmiConnectorServerStub, _mbeanServer) {
        @Override
        public synchronized void start() throws IOException {
            try {
                //manually bind the connector server to the registry at key 'jmxrmi', like the out-of-the-box agent                        
                _rmiRegistry.bind("jmxrmi", rmiConnectorServerStub);
            } catch (AlreadyBoundException abe) {
                //key was already in use. shouldnt happen here as its a new registry, unbindable by normal means.

                //IOExceptions are the only checked type throwable by the method, wrap and rethrow
                IOException ioe = new IOException(abe.getMessage());
                ioe.initCause(abe);
                throw ioe;
            }

            //now do the normal tasks
            super.start();
        }

        @Override
        public synchronized void stop() throws IOException {
            try {
                if (_rmiRegistry != null) {
                    _rmiRegistry.unbind("jmxrmi");
                }
            } catch (NotBoundException nbe) {
                //ignore
            }

            //now do the normal tasks
            super.stop();
        }

        @Override
        public JMXServiceURL getAddress() {
            //must return our pre-crafted url that includes the full details, inc JNDI details
            return externalUrl;
        }

    };

    //Add the custom invoker as an MBeanServerForwarder, and start the RMIConnectorServer.
    MBeanServerForwarder mbsf = MBeanInvocationHandlerImpl.newProxyInstance();
    _cs.setMBeanServerForwarder(mbsf);

    NotificationFilterSupport filter = new NotificationFilterSupport();
    filter.enableType(JMXConnectionNotification.OPENED);
    filter.enableType(JMXConnectionNotification.CLOSED);
    filter.enableType(JMXConnectionNotification.FAILED);
    // Get the handler that is used by the above MBInvocationHandler Proxy.
    // which is the MBeanInvocationHandlerImpl and so also a NotificationListener
    _cs.addNotificationListener((NotificationListener) Proxy.getInvocationHandler(mbsf), filter, null);

    _cs.start();

    String connectorServer = (sslEnabled ? "SSL " : "") + "JMX RMIConnectorServer";
    CurrentActor.get().message(ManagementConsoleMessages.LISTENING(connectorServer, port + PORT_EXPORT_OFFSET));

    CurrentActor.get().message(ManagementConsoleMessages.READY(false));
}

From source file:org.eclipse.smarthome.binding.homematic.internal.communicator.client.RpcClient.java

/**
 * Returns the remaining time of <i>install_mode==true</i>
 *
 * @param hmInterface specifies the interface on which install mode status is requested
 * @return current duration in seconds that the controller will remain in install mode,
 *         value of 0 means that the install mode is disabled
 * @throws IOException if RpcClient fails to propagate command
 *//*from w w  w. java  2 s. co m*/
public int getInstallMode(HmInterface hmInterface) throws IOException {
    RpcRequest<T> request = createRpcRequest("getInstallMode");
    Object[] result = sendMessage(config.getRpcPort(hmInterface), request);
    if (logger.isTraceEnabled()) {
        logger.trace(
                "Checking InstallMode: getInstallMode() request returned {} (remaining seconds in InstallMode=true)",
                result);
    }
    try {
        return (int) result[0];
    } catch (Exception cause) {
        IOException wrappedException = new IOException(
                "Failed to request install mode from interface " + hmInterface);
        wrappedException.initCause(cause);
        throw wrappedException;
    }
}

From source file:org.fusesource.meshkeeper.distribution.PluginClassLoader.java

/**
 * @param key/*www  . j  av  a  2  s.  c  om*/
 */
public Class<?> loadPlugin(String path, String key) throws IOException, ClassNotFoundException {

    String uri = path + key;

    try {
        //Possible that the plugin properties are already on the classpath
        //try loading there first: 
        Properties properties = loadProperties(this, uri);
        if (properties == null) {
            loadPlugin(key);
            properties = loadProperties(this, uri);
        }

        if (properties == null) {
            throw new IOException("Could not find factory properties: " + uri);
        }

        String className = properties.getProperty("class");
        if (className == null) {
            throw new IOException("Expected property is missing: class");
        }

        // The properties file can point us to the artifact to use...
        String mavenArtifact = properties.getProperty("maven.artifact");
        if (mavenArtifact != null) {
            loadArtifact(mavenArtifact);
        }

        //See if we can load it (either from system or the recently
        //loaded plugin classloader:
        return loadClass(className);

    } catch (IOException ioe) {
        throw ioe;
    } catch (ClassNotFoundException cnfe) {
        throw cnfe;
    } catch (Exception e) {
        IOException ioe = new IOException();
        ioe.initCause(e);
        throw ioe;
    }

}

From source file:ch.cyberduck.core.azure.AzureSession.java

@Override
protected void login(LoginController controller, Credentials credentials) throws IOException {
    // http://*.blob.core.windows.net
    try {/* www . ja v  a  2 s.  co m*/
        client = new BlobStorageRest(new URI(host.getProtocol().getScheme() + "://" + host.getHostname()),
                false, credentials.getUsername(), credentials.getPassword());
    } catch (URISyntaxException e) {
        log.error("Failure parsing URI:" + e.getMessage());
        IOException failure = new IOException(e.getMessage());
        failure.initCause(e);
        throw failure;
    }
    client.setTimeout(TimeSpan.fromMilliseconds(this.timeout()));
    try {
        this.getContainers(true);
    } catch (StorageServerException e) {
        if (this.isLoginFailure(e)) {
            this.message(Locale.localizedString("Login failed", "Credentials"));
            controller.fail(host.getProtocol(), credentials);
            this.login();
        } else {
            IOException failure = new IOException(e.getCause().getMessage());
            failure.initCause(e);
            throw failure;
        }
    }
}

From source file:dk.deck.remoteconsole.SshRemoteConsole.java

/**
 * Opens a shell channel to the server/*from  w w  w  .ja v  a 2s. com*/
 *
 * @return The ChannelShell object
 * @throws IOException
 */
@Override
public ChannelShell openShell() throws IOException {
    try {
        Channel channel = session.openChannel("shell"); // shell
        ChannelShell shell = (ChannelShell) channel;
        return shell;
    } catch (JSchException ex) {
        IOException ioe = new IOException();
        ioe.initCause(ex);
        throw ioe;
    }
}

From source file:com.icesoft.faces.webapp.parser.TagToComponentMap.java

/**
 * Same as addTags but this one has more info such as attributes/descriptions
 *
 * @param tldInput The TLD to process/*  ww  w.  j a v  a 2 s.  co  m*/
 * @throws IOException If digester barfs.
 */
public void addTagAttrib(InputStream tldInput) throws IOException {

    Digester digester = new Digester();
    digester.setNamespaceAware(true);
    digester.setValidating(false);
    digester.setEntityResolver(ParserUtils.entityResolver);
    digester.setUseContextClassLoader(false);

    /* Need to set the class loader to work.  Not sure why.
       May need to change when we move behind servlet container or Tomcat */
    digester.setClassLoader(loader);

    // This rule creates an element we can use to populate the map;
    digester.addObjectCreate("taglib/tag", "com.icesoft.faces.webapp.parser.TagToTagClassElement");
    digester.addObjectCreate("taglib/uri", "java.lang.StringBuffer");

    // This rule pushes everything into the hash table;
    NameRule nRule = new NameRule(tagToComponentMap, faceletsTaglibXmlWriter);
    digester.addRule("taglib/tag", nRule);
    digester.addRule("taglib/uri", nRule);

    // These rules scoop the values from <name> and <tag-class> elements;
    digester.addCallMethod("taglib/tag/name", "setTagName", 0);
    digester.addCallMethod("taglib/tag/tag-class", "setTagClass", 0);
    digester.addCallMethod("taglib/tag/description", "setDescription", 0);
    digester.addCallMethod("taglib/uri", "append", 0);

    digester.addObjectCreate("taglib/tag/attribute", "com.icesoft.faces.webapp.parser.AttributeElement");

    digester.addCallMethod("taglib/tag/attribute/name", "setName", 0);
    digester.addCallMethod("taglib/tag/attribute/required", "setRequired", 0);
    digester.addCallMethod("taglib/tag/attribute/description", "setDescription", 0);
    digester.addSetNext("taglib/tag/attribute", "addAttribute");

    try {
        digester.parse(tldInput);
    } catch (Throwable e) {
        IOException ioe = new IOException("Can't parse tld " + tldInput.toString());
        ioe.initCause(e);
        throw ioe;
    } finally {
        tldInput.close();
    }
}

From source file:com.googlecode.ddom.frontend.saaj.impl.AbstractSOAPPartImpl.java

public final void writeTo(OutputStream out) throws IOException {
    // TODO: there is some code duplication here
    if (source instanceof StreamSource) {
        // We need to copy the content of the StreamSource so that the SOAP part can still
        // be accessed later.
        // TODO: repeated calls to getContent() will created multiple copies; this is unnecessary
        // TODO: this will not work for StreamSources containing a Reader
        // TODO: need to close the input stream?
        // TODO: depending on the type of input stream, there may be smarter ways to clone the stream
        byte[] content = IOUtils.toByteArray(((StreamSource) source).getInputStream());
        source = new StreamSource(new ByteArrayInputStream(content));
        out.write(content);//from  ww  w . jav a 2s .c o m
    } else {
        // Make sure that the document is initialized and has an envelope
        try {
            getEnvelope();
        } catch (SOAPException ex) {
            throw new RuntimeException(ex); // TODO
        }
        try {
            XmlInput input = document.coreGetInput(true);
            input.addFilter(new NamespaceRepairingFilter());
            // TODO: set encoding?
            XmlOutput output = streamFactory.getOutput(out, new Options());
            new Stream(input, output).flush();
        } catch (StreamException ex) {
            // TODO: maybe we can extract an existing IOException??
            IOException ex2 = new IOException();
            ex2.initCause(ex);
            throw ex2;
        }
    }
}

From source file:dk.deck.remoteconsole.SshRemoteConsole.java

/**
 * Creates a tcp connection with a ssh session. This is where the
 * authentication occours. From here you can execute commands or open a
 * shell, via channels.//from w ww.ja  va2 s .  co m
 *
 * This method is using the credentials added on the setter methods.
 *
 * @throws IOException
 */
@Override
public void connect() throws IOException {
    try {
        if (isConnected()) {
            throw new IllegalStateException("Already connected");
        }
        session = createSession();
        log.debug("Connecting to " + getUser() + "@" + getHost());
        session.connect();
    } catch (JSchException ex) {
        IOException ioe = new IOException(ex.getMessage());
        ioe.initCause(ex);
        throw ioe;
    }
}