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:ch.cyberduck.core.dropbox.client.AbstractHttpDropboxClient.java

/**
 * Used internally to simplify making requests to the services, and handling an error, parsing
 * JSON, or returning a non-JSON body.  See executeRequest to see what's in the returned Map.
 *//*  w  ww . ja v a2 s  .  c om*/
protected HttpResponse request(HttpUriRequest req) throws IOException {
    if (null == auth) {
        throw new ConnectionCanceledException();
    }
    try {
        auth.sign(req);
    } catch (OAuthException e) {
        IOException failure = new IOException(e.getMessage());
        failure.initCause(e);
        throw failure;
    }
    return this.execute(req);
}

From source file:org.kuali.rice.core.impl.config.property.ConfigParserImpl.java

/**
 * Parses a single config location/* www . j  av a 2 s .c  om*/
 * @param params the current parameter map
 * @param location the location to parse
 * @param subs a StrSubstitutor used to substitute variable tokens
 * @throws IOException
 */
protected void parse(LinkedHashMap<String, Object> params, String location, StrSubstitutor subs, int depth)
        throws IOException {
    InputStream configStream = RiceUtilities.getResourceAsStream(location);
    if (configStream == null) {
        LOG.warn("###############################");
        LOG.warn("#");
        LOG.warn("# Configuration file '" + location + "' not found!");
        LOG.warn("#");
        LOG.warn("###############################");
        return;
    }

    final String prefix = StringUtils.repeat(INDENT, depth);
    LOG.info(prefix + "+ Parsing config: " + location);

    Document doc;
    try {
        doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(configStream);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Contents of config " + location + ": \n" + XmlJotter.jotNode(doc, true));
        }
    } catch (SAXException se) {
        IOException ioe = new IOException("Error parsing config resource: " + location);
        ioe.initCause(se);
        throw ioe;
    } catch (ParserConfigurationException pce) {
        IOException ioe = new IOException("Unable to obtain document builder");
        ioe.initCause(pce);
        throw ioe;
    } finally {
        configStream.close();
    }

    Element root = doc.getDocumentElement();
    // ignore the actual type of the document element for now
    // so that plugin descriptors can be parsed
    NodeList list = root.getChildNodes();
    StringBuilder content = new StringBuilder();
    for (int i = 0; i < list.getLength(); i++) {
        Node node = list.item(i);
        if (node.getNodeType() != Node.ELEMENT_NODE)
            continue;
        if (!PARAM_NAME.equals(node.getNodeName())) {
            LOG.warn("Encountered non-param config node: " + node.getNodeName());
            continue;
        }
        Element param = (Element) node;
        String name = param.getAttribute(NAME_ATTR);
        if (name == null) {
            LOG.error("Unnamed parameter in config resource '" + location + "': " + XmlJotter.jotNode(param));
            continue;
        }
        Boolean override = Boolean.TRUE;
        String overrideVal = param.getAttribute(OVERRIDE_ATTR);
        if (!StringUtils.isEmpty(overrideVal)) {
            override = Boolean.valueOf(overrideVal);
        }

        content.setLength(0);
        // accumulate all content (preserving any XML content)
        getNodeValue(name, location, param, content);
        String value = subs.replace(content);
        if (LOG.isDebugEnabled()) {
            LOG.debug(
                    prefix + INDENT + "* " + name + "=[" + ConfigLogger.getDisplaySafeValue(name, value) + "]");
        }

        if (IMPORT_NAME.equals(name)) {
            // what is this...we don't follow a string with this substring in it? i.e. if the value does not
            // resolve then don't try to follow it (it won't find it anyway; this is the case for any path
            // with unresolved params...)?
            if (!value.contains(ALTERNATE_BUILD_LOCATION_KEY)) {
                parse(params, value, subs, depth + 1);
            }
        } else {
            if (Boolean.valueOf(param.getAttribute(RANDOM_ATTR))) {
                // this is a special type of property whose value is a randomly generated number in the range specified
                value = String.valueOf(generateRandomInteger(value));
            }
            setParam(params, override, name, value, prefix + INDENT);
        }
    }
    LOG.info(prefix + "- Parsed config: " + location);
}

From source file:net.sbbi.upnp.jmx.UPNPMBeanService.java

protected UPNPMBeanService(String deviceUUID, String vendorDomain, String serviceId, String serviceType,
        int serviceVersion, MBeanInfo mbeanInfo, ObjectName mbeanName, MBeanServer targetServer)
        throws IOException {
    this.deviceUUID = deviceUUID;
    if (serviceId == null) {
        serviceId = generateServiceId(mbeanName);
    }/* w  ww. jav a2  s .  c  o  m*/
    this.serviceUUID = deviceUUID + "/" + serviceId;
    this.serviceType = "urn:" + vendorDomain + ":service:" + serviceType + ":" + serviceVersion;
    this.serviceId = "urn:" + vendorDomain + ":serviceId:" + serviceId;
    deviceSCDP = getDeviceSSDP(mbeanInfo);
    try {
        targetBeanClass = Class.forName(mbeanInfo.getClassName());
    } catch (ClassNotFoundException ex) {
        IOException ex2 = new IOException("Unable to find target MBean class " + mbeanInfo.getClassName());
        ex2.initCause(ex);
        throw ex2;
    }
    this.mbeanName = mbeanName;
    this.mbeanInfo = mbeanInfo;
    this.targetServer = targetServer;
}

From source file:ch.cyberduck.core.dropbox.client.AbstractHttpDropboxClient.java

/**
 * Used when we have to authenticate from scratch
 *
 * @param username// ww  w.  j a  v  a  2s  .  c  om
 * @param password
 * @return
 * @throws IOException
 * @throws OAuthException
 */
public void authenticate(String key, String secret, String username, String password) throws IOException {
    String[] params = { "email", username, "password", password };

    OAuthConsumer consumer = new CommonsHttpOAuthConsumer(key, secret);
    HttpGet request = new HttpGet(this.getUrl("/token", params, false));
    try {
        consumer.sign(request);
    } catch (OAuthException e) {
        IOException failure = new IOException(e.getMessage());
        failure.initCause(e);
        throw failure;
    }

    JSONObject credentials = this.parse(this.execute(request));

    String token_key = credentials.get("token").toString();
    String token_secret = credentials.get("secret").toString();
    log.info("Obtained Token Key:" + token_key);
    log.info("Obtained Token Secret:" + token_secret);

    auth = new Authenticator(key, secret, this.getRequestPath("/oauth/request_token"),
            this.getRequestPath("/oauth/access_token"), this.getRequestPath("/oauth/authorize"), token_key,
            token_secret);
}

From source file:org.hyperic.hq.bizapp.agent.client.SecureAgentConnection.java

@Override
protected Socket getSocket() throws IOException {
    SSLSocket socket;// ww w.j  a v a2 s  . co m

    log.debug("Creating secure socket");

    try {
        // Check for configured agent read timeout from System properties
        int readTimeout;

        try {
            readTimeout = Integer.parseInt(System.getProperty(PROP_READ_TIMEOUT));
        } catch (NumberFormatException e) {
            readTimeout = READ_TIMEOUT;
        }

        // Check for configured agent post handshake timeout
        // from System properties
        int postHandshakeTimeout;
        try {
            postHandshakeTimeout = Integer.parseInt(System.getProperty(PROP_POST_HANDSHAKE_TIMEOUT));
        } catch (NumberFormatException e) {
            postHandshakeTimeout = POST_HANDSHAKE_TIMEOUT;
        }

        SSLProvider sslProvider = new DefaultSSLProviderImpl(keystoreConfig, acceptUnverifiedCertificate);

        SSLSocketFactory factory = sslProvider.getSSLSocketFactory();

        // See the following links...
        // http://www.apache.org/dist/httpcomponents/httpcore/RELEASE_NOTES-4.1.x.txt
        // http://www-128.ibm.com/developerworks/forums/dw_thread.jsp?message=13695343&cat=10&thread=73546&treeDisplayType=threadmode1&forum=178#13695343
        // In any case, it would seem as though the bug has since been fixed in IBM's JRE, no need to work around it anymore...
        socket = (SSLSocket) factory.createSocket();

        // Make sure the InetAddress used to initialize the socket has a non-null hostname (empty string).
        // This prevents slow and unnecessary reverse DNS querying when the connection is opened.
        InetAddress withoutHost = InetAddress.getByName(this.agentAddress);
        InetAddress withHost = InetAddress.getByAddress("", withoutHost.getAddress());
        InetSocketAddress address = new InetSocketAddress(withHost, this.agentPort);

        socket.connect(address, readTimeout);

        // Set the socket timeout during the initial handshake to detect
        // connection issues with the agent.  
        socket.setSoTimeout(readTimeout);

        log.debug("Secure socket is connected to " + address + " - starting handshake.");

        socket.startHandshake();

        log.debug("SSL handshake complete");

        // [HHQ-3694] The timeout is set to a post handshake value.
        socket.setSoTimeout(postHandshakeTimeout);

    } catch (IOException exc) {
        IOException toThrow = new IOException(
                "Unable to connect to " + this.agentAddress + ":" + this.agentPort + ": " + exc.getMessage());
        // call initCause instead of constructor to be java 1.5 compat
        toThrow.initCause(exc);
        throw toThrow;
    }

    // Write our security settings
    try {
        DataOutputStream dOs;

        dOs = new DataOutputStream(socket.getOutputStream());
        dOs.writeUTF(this.authToken);
    } catch (IOException exc) {
        IOException toThrow = new IOException("Unable to write auth params to server");
        // call initCause instead of constructor to be java 1.5 compat
        toThrow.initCause(exc);
        throw toThrow;
    }

    return socket;
}

From source file:org.freedesktop.mime.MIMEEntry.java

void load(FileObject file) throws IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(false);//w ww. ja v  a2  s . co  m
    factory.setNamespaceAware(true);
    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputStream in = file.getContent().getInputStream();
        try {
            Document document = builder.parse(in);
            build(document);
        } finally {
            in.close();
        }
    } catch (IOException ioe) {
        throw ioe;
    } catch (Exception e) {
        IOException ioe = new IOException("Failed to parse XML.");
        ioe.initCause(e);
        throw ioe;
    }

}

From source file:org.dcm4chex.archive.hsm.TarRetrieverService.java

private File fetchHSMFile(String fsID, String tarPath) throws IOException {
    try {//from ww  w  . ja  v  a  2s.  c  o  m
        return (File) server.invoke(hsmModuleServicename, "fetchHSMFile", new Object[] { fsID, tarPath },
                new String[] { String.class.getName(), String.class.getName() });
    } catch (Exception x) {
        log.error("Fetch of HSMFile failed! fsID:" + fsID + " tarPath:" + tarPath, x);
        IOException iox = new IOException("Fetch of HSMFile failed!");
        iox.initCause(x);
        throw iox;
    }
}

From source file:org.ms123.common.git.FileHolder.java

/**
 * Load the configuration as a Git text style configuration file.
 * <p>//from  ww  w .j  a  v a 2 s.c  om
 * If the file does not exist, this configuration is cleared, and thus
 * behaves the same as though the file exists, but is empty.
 *
 * @throws IOException
 *             the file could not be read (but does exist).
 * @throws ConfigInvalidException
 *             the file is not a properly formatted configuration file.
 */
@Override
public void load() throws IOException, ConfigInvalidException {
    final FileSnapshot oldSnapshot = snapshot;
    final FileSnapshot newSnapshot = FileSnapshot.save(getFile());
    DelimiterInputStream dis = null;
    try {
        dis = new DelimiterInputStream(new BufferedInputStream(new FileInputStream(getFile())));
        byte[] array = new byte[] { 45, 45, 10 };
        byte[] in = dis.readTill(array);
        final ObjectId newHash = hash(in);
        if (hash.equals(newHash)) {
            if (oldSnapshot.equals(newSnapshot))
                oldSnapshot.setClean(newSnapshot);
            else
                snapshot = newSnapshot;
        } else {
            final String decoded;
            if (in.length >= 3 && in[0] == (byte) 0xEF && in[1] == (byte) 0xBB && in[2] == (byte) 0xBF) {
                decoded = RawParseUtils.decode(UTF8_CHARSET, in, 3, in.length);
                utf8Bom = true;
            } else {
                decoded = RawParseUtils.decode(in);
            }
            String content = null;
            try {
                fromText(decoded);
                content = getString("sw", null, "content");
            } catch (org.eclipse.jgit.errors.ConfigInvalidException c) {
                dis = new DelimiterInputStream(new FileInputStream(getFile()));
                m_isUnknown = true;
            }
            if (content != null) {
                m_content = content;
            } else {
                in = dis.readTill(null);
                m_content = RawParseUtils.decode(in);
            }
            snapshot = newSnapshot;
            hash = newHash;
        }
    } catch (FileNotFoundException noFile) {
        clear();
        snapshot = newSnapshot;
    } catch (IOException e) {
        final IOException e2 = new IOException(MessageFormat.format(JGitText.get().cannotReadFile, getFile()));
        e2.initCause(e);
        throw e2;
    } finally {
        if (dis != null)
            dis.close();
    }
}

From source file:com.chinamobile.bcbsp.pipes.Application.java

/**
 * Abort the application and wait for it to finish.
 * @param t/*from ww  w.j av a2s  .c  om*/
 *        the exception that signalled the problem
 * @throws IOException
 *         A wrapper around the exception that was passed in
 */
void abort(Throwable t) throws IOException {
    LOG.info("Aborting because of " + StringUtils.stringifyException(t));
    try {
        downlink.abort();
        downlink.flush();
    } catch (IOException e) {
        // IGNORE cleanup problems
    }
    try {
        handler.waitForFinish();
    } catch (Throwable ignored) {
        process.destroy();
    }
    IOException wrapper = new IOException("pipe child exception");
    wrapper.initCause(t);
    throw wrapper;
}

From source file:org.geotools.data.complex.config.XMLConfigDigester.java

/**
 * DOCUMENT ME!//from  ww  w. java2s.c  o m
 * 
 * @param dataStoreConfigUrl
 *            DOCUMENT ME!
 * 
 * @return DOCUMENT ME!
 * 
 * @throws IOException
 *             DOCUMENT ME!
 * @throws NullPointerException
 *             DOCUMENT ME!
 */
private AppSchemaDataAccessDTO digest(final URL dataStoreConfigUrl) throws IOException {
    if (dataStoreConfigUrl == null) {
        throw new NullPointerException("datastore config url");
    }

    // read mapping file into configString and interpolate properties
    InputStream configStream = null;
    String configString = null;
    try {
        configStream = dataStoreConfigUrl.openStream();
        if (configStream == null) {
            throw new IOException("Can't open datastore config file " + dataStoreConfigUrl);
        } else {
            configString = properties.interpolate(InterpolationProperties.readAll(configStream));
        }
    } finally {
        if (configStream != null) {
            configStream.close();
        }
    }

    XMLConfigDigester.LOGGER.fine("parsing complex datastore config: " + dataStoreConfigUrl.toExternalForm());

    Digester digester = new Digester();
    XMLConfigDigester.LOGGER.fine("digester created");
    // URL schema = getClass()
    // .getResource("../test-data/AppSchemaDataAccess.xsd");
    // digester.setSchema(schema.toExternalForm());
    digester.setValidating(false);
    digester.setNamespaceAware(true);
    digester.setRuleNamespaceURI(XMLConfigDigester.CONFIG_NS_URI);

    // digester.setRuleNamespaceURI(OGC_NS_URI);
    AppSchemaDataAccessDTO configDto = new AppSchemaDataAccessDTO();
    configDto.setBaseSchemasUrl(dataStoreConfigUrl.toExternalForm());

    digester.push(configDto);

    try {
        setNamespacesRules(digester);

        setIncludedTypesRules(digester);

        setSourceDataStoresRules(digester);

        setTargetSchemaUriRules(digester);

        setTypeMappingsRules(digester);

    } catch (Exception e) {
        e.printStackTrace();
        XMLConfigDigester.LOGGER.log(Level.SEVERE, "setting digester properties: ", e);
        throw new IOException("Error setting digester properties: " + e.getMessage());
    }

    try {
        digester.parse(new StringReader(configString));
    } catch (SAXException e) {
        e.printStackTrace();
        XMLConfigDigester.LOGGER.log(Level.SEVERE, "parsing " + dataStoreConfigUrl, e);

        IOException ioe = new IOException("Can't parse complex datastore config. ");
        ioe.initCause(e);
        throw ioe;
    }

    AppSchemaDataAccessDTO config = (AppSchemaDataAccessDTO) digester.getRoot();

    return config;
}