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:edu.caltech.ipac.firefly.server.query.IpacTablePartProcessor.java

protected static IOException makeException(Exception e, String reason) {
    IOException eio = new IOException(reason);
    eio.initCause(e);
    return eio;/*w  ww  . j a v a2  s  . co  m*/
}

From source file:org.jboss.bpm.console.server.util.DOMUtils.java

public static Element sourceToElement(Source source) throws IOException {
    Element retElement = null;/*from ww w .  ja va 2  s . c o  m*/

    try {
        if (source instanceof StreamSource) {
            StreamSource streamSource = (StreamSource) source;

            InputStream ins = streamSource.getInputStream();
            if (ins != null) {
                retElement = DOMUtils.parse(ins);
            } else {
                Reader reader = streamSource.getReader();
                retElement = DOMUtils.parse(new InputSource(reader));
            }
        } else if (source instanceof DOMSource) {
            DOMSource domSource = (DOMSource) source;
            Node node = domSource.getNode();
            if (node instanceof Element) {
                retElement = (Element) node;
            } else if (node instanceof Document) {
                retElement = ((Document) node).getDocumentElement();
            } else {
                throw new RuntimeException("Unsupported Node type: " + node.getClass().getName());
            }
        } else if (source instanceof SAXSource) {
            // The fact that JAXBSource derives from SAXSource is an implementation detail.
            // Thus in general applications are strongly discouraged from accessing methods defined on SAXSource.
            // The XMLReader object obtained by the getXMLReader method shall be used only for parsing the InputSource object returned by the getInputSource method.

            TransformerFactory tf = TransformerFactory.newInstance();
            ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
            Transformer transformer = tf.newTransformer();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.setOutputProperty(OutputKeys.METHOD, "xml");
            transformer.transform(source, new StreamResult(baos));
            retElement = DOMUtils.parse(new ByteArrayInputStream(baos.toByteArray()));
        } else {
            throw new RuntimeException("Source type not implemented: " + source.getClass().getName());
        }

    } catch (TransformerException ex) {
        IOException ioex = new IOException();
        ioex.initCause(ex);
        throw ioex;
    }

    return retElement;
}

From source file:com.jpeterson.littles3.bo.Acp.java

/**
 * Decode an Acp as XML./*from w  w  w  .  ja v a2 s .  c  om*/
 * 
 * @param xml
 *            The Acp encoded as XML.
 * @return The Acp decoded from the XML.
 */
public static Acp decode(InputStream xml) throws IOException {
    Acp acp;
    SAXBuilder builder;
    Document document;
    Element accessControlPolicyElement;
    Element ownerElement;
    Element idElement, displayNameElement;
    Element accessControlListElement;
    Element grantElement;
    Element granteeElement, permissionElement;
    Element uriElement;
    Attribute typeAttribute;
    CanonicalUser user;
    Namespace defaultNamespace;

    acp = new Acp();

    builder = new SAXBuilder();

    try {
        document = builder.build(xml);

        accessControlPolicyElement = document.getRootElement();

        if (!(ELEMENT_ACCESS_CONTROL_POLICY.equals(accessControlPolicyElement.getName()))) {
            // TODO: indicate error

            System.out.println("Constant ELEMENT_ACCESS_CONTROL_POLICY: " + ELEMENT_ACCESS_CONTROL_POLICY);
            System.out.println("accessControlPolicyElement.getName(): " + accessControlPolicyElement.getName());

            throw new IOException("Invalid root element: " + accessControlPolicyElement);
        }

        defaultNamespace = accessControlPolicyElement.getNamespace();

        if ((ownerElement = accessControlPolicyElement.getChild(ELEMENT_OWNER, defaultNamespace)) == null) {
            throw new IOException("Invalid XML. Should have 'Owner' element");
        }

        if ((idElement = ownerElement.getChild(ELEMENT_ID, defaultNamespace)) == null) {
            throw new IOException("Invalid XML. Should have 'ID' element");
        }

        user = new CanonicalUser(idElement.getText());

        if ((displayNameElement = ownerElement.getChild(ELEMENT_DISPLAY_NAME, defaultNamespace)) != null) {
            user.setDisplayName(displayNameElement.getText());
        }

        acp.setOwner(user);

        if ((accessControlListElement = accessControlPolicyElement.getChild(ELEMENT_ACCESS_CONTROL_LIST,
                defaultNamespace)) == null) {
            throw new IOException("Invalid XML. Should have 'AccessControlList' element");
        }

        for (Iterator grants = accessControlListElement.getChildren(ELEMENT_GRANT, defaultNamespace)
                .iterator(); grants.hasNext();) {
            Grantee grantee;

            grantElement = (Element) grants.next();
            if ((granteeElement = grantElement.getChild(ELEMENT_GRANTEE, defaultNamespace)) == null) {
                throw new IOException("Invalid XML. Should have 'Grantee' element");
            }
            if ((permissionElement = grantElement.getChild(ELEMENT_PERMISSION, defaultNamespace)) == null) {
                throw new IOException("Invalid XML. Should have 'Permission' element");
            }

            if ((typeAttribute = granteeElement.getAttribute(ATTRIBUTE_TYPE, NAMESPACE_XSI)) == null) {
                throw new IOException("Invalid XML. Should have 'type' attribute");
            }
            String typeValue = typeAttribute.getValue();
            if (ATTRIBUTE_TYPE_VALUE_CANONICAL_USER.equals(typeValue)) {
                if ((idElement = granteeElement.getChild(ELEMENT_ID, defaultNamespace)) == null) {
                    throw new IOException("Invalid XML. Should have 'ID' element");
                }

                user = new CanonicalUser(idElement.getText());

                if ((displayNameElement = granteeElement.getChild(ELEMENT_DISPLAY_NAME,
                        defaultNamespace)) != null) {
                    user.setDisplayName(displayNameElement.getText());
                }

                grantee = user;
            } else if (ATTRIBUTE_TYPE_VALUE_GROUP.equals(typeValue)) {
                if ((uriElement = granteeElement.getChild(ELEMENT_URI, defaultNamespace)) == null) {
                    throw new IOException("Invalid XML. Should have 'URI' element");
                }

                String uriValue = uriElement.getValue();
                if (AllUsersGroup.URI_STRING.equals(uriValue)) {
                    grantee = AllUsersGroup.getInstance();
                } else if (AuthenticatedUsersGroup.URI_STRING.equals(uriValue)) {
                    grantee = AuthenticatedUsersGroup.getInstance();
                } else {
                    throw new IOException("Unknown group uri: " + uriValue);
                }
            } else {
                throw new IOException("Unknown type: " + typeValue);
            }

            try {
                acp.grant(grantee, permissionElement.getValue());
            } catch (IllegalArgumentException e) {
                IOException ex = new IOException("Invalid permission: " + permissionElement.getValue());
                ex.initCause(e);
                throw ex;
            }
        }
    } catch (JDOMException e) {
        IOException ex = new IOException(e.getMessage());
        ex.initCause(e);
        throw ex;
    }

    return acp;
}

From source file:org.rioproject.impl.util.DownloadManager.java

private static void removeExtractedTarFiles(File root, File tarFile) throws IOException {
    InputStream is = new FileInputStream(tarFile);
    ArchiveInputStream in;/*from  w  w  w.  ja v a  2s.c o m*/
    try {
        in = new ArchiveStreamFactory().createArchiveInputStream("tar", is);
    } catch (ArchiveException e) {
        IOException ioe = new IOException("Removing " + tarFile.getName());
        ioe.initCause(e);
        throw ioe;
    }
    File parent = null;
    try {
        TarArchiveEntry entry;
        while ((entry = (TarArchiveEntry) in.getNextEntry()) != null) {
            File f = new File(root, entry.getName());
            if (parent == null) {
                parent = new File(getExtractedToPath(f, root));
            }
            FileUtils.remove(f);

        }
    } finally {
        in.close();
    }
    FileUtils.remove(parent);
}

From source file:com.hipu.bdb.util.FileUtils.java

/**
  * Copy up to extent bytes of the source file to the destination
  *//from  w  w  w  .ja v a  2 s.  co m
  * @param src
  * @param dest
  * @param extent Maximum number of bytes to copy
 * @param overwrite If target file already exits, and this parameter is
  * true, overwrite target file (We do this by first deleting the target
  * file before we begin the copy).
 * @return True if the extent was greater than actual bytes copied.
  * @throws FileNotFoundException
  * @throws IOException
  */
public static boolean copyFile(final File src, final File dest, long extent, final boolean overwrite)
        throws FileNotFoundException, IOException {
    boolean result = false;
    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("Copying file " + src + " to " + dest + " extent " + extent + " exists " + dest.exists());
    }
    if (dest.exists()) {
        if (overwrite) {
            dest.delete();
            LOGGER.finer(dest.getAbsolutePath() + " removed before copy.");
        } else {
            // Already in place and we're not to overwrite.  Return.
            return result;
        }
    }
    FileInputStream fis = null;
    FileOutputStream fos = null;
    FileChannel fcin = null;
    FileChannel fcout = null;
    try {
        // Get channels
        fis = new FileInputStream(src);
        fos = new FileOutputStream(dest);
        fcin = fis.getChannel();
        fcout = fos.getChannel();
        if (extent < 0) {
            extent = fcin.size();
        }

        // Do the file copy
        long trans = fcin.transferTo(0, extent, fcout);
        if (trans < extent) {
            result = false;
        }
        result = true;
    } catch (IOException e) {
        // Add more info to the exception. Preserve old stacktrace.
        // We get 'Invalid argument' on some file copies. See
        // http://intellij.net/forums/thread.jsp?forum=13&thread=63027&message=853123
        // for related issue.
        String message = "Copying " + src.getAbsolutePath() + " to " + dest.getAbsolutePath() + " with extent "
                + extent + " got IOE: " + e.getMessage();
        if ((e instanceof ClosedByInterruptException)
                || ((e.getMessage() != null) && e.getMessage().equals("Invalid argument"))) {
            LOGGER.severe("Failed copy, trying workaround: " + message);
            workaroundCopyFile(src, dest);
        } else {
            IOException newE = new IOException(message);
            newE.initCause(e);
            throw newE;
        }
    } finally {
        // finish up
        if (fcin != null) {
            fcin.close();
        }
        if (fcout != null) {
            fcout.close();
        }
        if (fis != null) {
            fis.close();
        }
        if (fos != null) {
            fos.close();
        }
    }
    return result;
}

From source file:com.granule.json.utils.XML.java

/**
 * Method to take an input stream to an XML document and return a String of the JSON format.  Note that the xmlStream is not closed when read is complete.  This is left up to the caller, who may wish to do more with it.
 * @param xmlStream The InputStream to an XML document to transform to JSON.
 * @param verbose Boolean flag denoting whther or not to write the JSON in verbose (formatted), or compact form (no whitespace)
 * @return A string of the JSON representation of the XML file
 * //from  w w  w. ja va  2  s.c o  m
 * @throws SAXException Thrown if an error occurs during parse.
 * @throws IOException Thrown if an IOError occurs.
 */
public static String toJson(InputStream xmlStream, boolean verbose) throws SAXException, IOException {
    if (logger.isLoggable(Level.FINER)) {
        logger.exiting(className, "toJson(InputStream, boolean)");
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    String result = null;

    try {
        toJson(xmlStream, baos, verbose);
        result = baos.toString("UTF-8");
        baos.close();
    } catch (UnsupportedEncodingException uec) {
        IOException iox = new IOException(uec.toString());
        iox.initCause(uec);
        throw iox;
    }

    if (logger.isLoggable(Level.FINER)) {
        logger.exiting(className, "toJson(InputStream, boolean)");
    }

    return result;
}

From source file:com.granule.json.utils.XML.java

/**
 * Method to take an input stream to an JSON document and return a String of the XML format.  Note that the JSONStream is not closed when read is complete.  This is left up to the caller, who may wish to do more with it.
 * @param xmlStream The InputStream to an JSON document to transform to XML.
 * @param verbose Boolean flag denoting whther or not to write the XML in verbose (formatted), or compact form (no whitespace)
 * @return A string of the JSON representation of the XML file
 * //from  w ww  .  ja v a2 s  .c o m
 * @throws IOException Thrown if an IOError occurs.
 */
public static String toXml(InputStream JSONStream, boolean verbose) throws IOException {
    if (logger.isLoggable(Level.FINER)) {
        logger.exiting(className, "toXml(InputStream, boolean)");
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    String result = null;

    try {
        toXml(JSONStream, baos, verbose);
        result = baos.toString("UTF-8");
        baos.close();
    } catch (UnsupportedEncodingException uec) {
        IOException iox = new IOException(uec.toString());
        iox.initCause(uec);
        throw iox;
    }

    if (logger.isLoggable(Level.FINER)) {
        logger.exiting(className, "toXml(InputStream, boolean)");
    }

    return result;
}

From source file:org.rioproject.impl.util.DownloadManager.java

private static void unTar(File tarFile, File target) throws IOException {
    InputStream is = new FileInputStream(tarFile);
    ArchiveInputStream in;/*from   w  w w .  jav  a2s . com*/
    try {
        in = new ArchiveStreamFactory().createArchiveInputStream("tar", is);
    } catch (ArchiveException e) {
        IOException ioe = new IOException("Unarchving " + tarFile.getName());
        ioe.initCause(e);
        throw ioe;
    }
    try {
        TarArchiveEntry entry;
        while ((entry = (TarArchiveEntry) in.getNextEntry()) != null) {
            File f = new File(target, entry.getName());
            if (entry.isDirectory()) {
                if (f.mkdirs()) {
                    logger.trace("Created directory {}", f.getPath());
                }
            } else {
                if (!f.getParentFile().exists()) {
                    if (f.getParentFile().mkdirs()) {
                        logger.trace("Created {}", f.getParentFile().getPath());
                    }
                }
                if (f.createNewFile()) {
                    logger.trace("Created {}", f.getName());
                }
                OutputStream out = new FileOutputStream(f);
                IOUtils.copy(in, out);
                out.close();
            }
            setPerms(f, entry.getMode());
        }
    } finally {
        in.close();
    }
}

From source file:biz.varkon.shelvesom.server.ServerInfo.java

/**
 * Parses a valid XML response from the specified input stream. This method
 * must invoke parse/*from  w ww  .ja  v a2  s .c om*/
 * {@link ResponseParser#parseResponse(org.xmlpull.v1.XmlPullParser)} if the
 * XML response is valid, or throw an exception if it is not.
 * 
 * @param in
 *            The input stream containing the response sent by the web
 *            service.
 * @param responseParser
 *            The parser to use when the response is valid.
 * 
 * @throws java.io.IOException
 */
public static void parseResponse(InputStream in, ResponseParser responseParser,
        IOUtilities.inputTypes inputType) throws IOException {
    final XmlPullParser parser = Xml.newPullParser();
    try {
        parser.setInput(new InputStreamReader(in));

        int type;
        while ((type = parser.next()) != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT) {
            // Empty
        }

        if (type != XmlPullParser.START_TAG) {
            throw new InflateException(parser.getPositionDescription() + ": No start tag found!");
        }

        String name;
        boolean valid = false;
        final int topDepth = parser.getDepth();

        while (((type = parser.next()) != XmlPullParser.END_TAG || parser.getDepth() > topDepth)
                && type != XmlPullParser.END_DOCUMENT) {

            if (type != XmlPullParser.START_TAG) {
                continue;
            }

            name = parser.getName();

            if (RESPONSE_TAG_REQUEST.equals(name)) {
                valid = isRequestValid(parser);
                break;
            }
        }

        if (valid)
            responseParser.parseResponse(parser);

    } catch (XmlPullParserException e) {
        final IOException ioe = new IOException("Could not parse the response");
        ioe.initCause(e);
        throw ioe;
    }
}

From source file:com.granule.json.utils.XML.java

/**
 * Method to do the transform from an JSON input stream to a XML stream.
 * Neither input nor output streams are closed.  Closure is left up to the caller.
 *
 * @param JSONStream The XML stream to convert to JSON
 * @param XMLStream The stream to write out JSON to.  The contents written to this stream are always in UTF-8 format.
 * @param verbose Flag to denote whether or not to render the XML text in verbose (indented easy to read), or compact (not so easy to read, but smaller), format.
 *
 * @throws IOException Thrown if an IO error occurs.
 *//*from   w  w  w. jav  a 2  s  .  c o  m*/
public static void toXml(InputStream JSONStream, OutputStream XMLStream, boolean verbose) throws IOException {
    if (logger.isLoggable(Level.FINER)) {
        logger.entering(className, "toXml(InputStream, OutputStream)");
    }

    if (XMLStream == null) {
        throw new NullPointerException("XMLStream cannot be null");
    } else if (JSONStream == null) {
        throw new NullPointerException("JSONStream cannot be null");
    } else {

        if (logger.isLoggable(Level.FINEST)) {
            logger.logp(Level.FINEST, className, "transform", "Parsing the JSON and a DOM builder.");
        }

        try {
            //Get the JSON from the stream.
            JSONObject jObject = new JSONObject(JSONStream);

            //Create a new document

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbf.newDocumentBuilder();
            Document doc = dBuilder.newDocument();

            if (logger.isLoggable(Level.FINEST)) {
                logger.logp(Level.FINEST, className, "transform", "Parsing the JSON content to XML");
            }

            convertJSONObject(doc, doc.getDocumentElement(), jObject, "jsonObject");

            //Serialize it.
            TransformerFactory tfactory = TransformerFactory.newInstance();
            Transformer serializer = null;
            if (verbose) {
                serializer = tfactory.newTransformer(new StreamSource(new StringReader(styleSheet)));
                ;
            } else {
                serializer = tfactory.newTransformer();
            }
            Properties oprops = new Properties();
            oprops.put(OutputKeys.METHOD, "xml");
            oprops.put(OutputKeys.OMIT_XML_DECLARATION, "yes");
            oprops.put(OutputKeys.VERSION, "1.0");
            oprops.put(OutputKeys.INDENT, "true");
            serializer.setOutputProperties(oprops);
            serializer.transform(new DOMSource(doc), new StreamResult(XMLStream));

        } catch (Exception ex) {
            IOException iox = new IOException("Problem during conversion");
            iox.initCause(ex);
            throw iox;
        }
    }

    if (logger.isLoggable(Level.FINER)) {
        logger.exiting(className, "toXml(InputStream, OutputStream)");
    }
}