Example usage for javax.xml.bind JAXBException JAXBException

List of usage examples for javax.xml.bind JAXBException JAXBException

Introduction

In this page you can find the example usage for javax.xml.bind JAXBException JAXBException.

Prototype

public JAXBException(String message, Throwable exception) 

Source Link

Document

Construct a JAXBException with the specified detail message and linkedException.

Usage

From source file:Main.java

public static JAXBException convert(final JAXBException e) {
    return new JAXBException(getMessage(e), e.getLinkedException());
}

From source file:org.javelin.sws.ext.bind.SweJaxbMarshaller.java

@Override
public void marshal(Object jaxbElement, Result result) throws JAXBException {
    try {// www . j  av a2s. c  om
        XMLEventWriter writer = this.xmlOutputFactory.createXMLEventWriter(result);
        this.marshal(jaxbElement, writer);
        writer.flush();
    } catch (XMLStreamException e) {
        throw new JAXBException(e.getMessage(), e);
    }
}

From source file:cz.cas.lib.proarc.common.workflow.profile.WorkflowProfiles.java

private Unmarshaller getUnmarshaller() throws JAXBException {
    JAXBContext jctx = JAXBContext.newInstance(WorkflowDefinition.class);
    Unmarshaller unmarshaller = jctx.createUnmarshaller();
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URL schemaUrl = WorkflowDefinition.class.getResource("workflow.xsd");
    Schema schema = null;// w ww.  j  av  a2s .  c om
    try {
        schema = sf.newSchema(new StreamSource(schemaUrl.toExternalForm()));
    } catch (SAXException ex) {
        throw new JAXBException("Missing schema workflow.xsd!", ex);
    }
    unmarshaller.setSchema(schema);
    ValidationEventCollector errors = new ValidationEventCollector() {

        @Override
        public boolean handleEvent(ValidationEvent event) {
            super.handleEvent(event);
            return true;
        }

    };
    unmarshaller.setEventHandler(errors);
    return unmarshaller;
}

From source file:org.apache.nifi.authorization.FileAccessPolicyProvider.java

private Authorizations unmarshallAuthorizations() throws JAXBException {
    try {//w w w. ja  v  a  2s  .c  om
        final XMLStreamReader xsr = XmlUtils.createSafeReader(new StreamSource(authorizationsFile));
        final Unmarshaller unmarshaller = JAXB_AUTHORIZATIONS_CONTEXT.createUnmarshaller();
        unmarshaller.setSchema(authorizationsSchema);

        final JAXBElement<Authorizations> element = unmarshaller.unmarshal(xsr, Authorizations.class);
        return element.getValue();
    } catch (XMLStreamException e) {
        logger.error("Encountered an error reading authorizations file: ", e);
        throw new JAXBException("Error reading authorizations file", e);
    }
}

From source file:org.apache.nifi.authorization.FileAccessPolicyProvider.java

/**
 * Unmarshalls an existing authorized-users.xml and converts the object model to the new model.
 *
 * @param authorizations the current Authorizations instance that policies will be added to
 * @throws AuthorizerCreationException if the legacy authorized users file that was provided does not exist
 * @throws JAXBException if the legacy authorized users file that was provided could not be unmarshalled
 */// w  ww.j  a  v a 2 s .  c  om
private void convertLegacyAuthorizedUsers(final Authorizations authorizations)
        throws AuthorizerCreationException, JAXBException {
    final File authorizedUsersFile = new File(legacyAuthorizedUsersFile);
    if (!authorizedUsersFile.exists()) {
        throw new AuthorizerCreationException(
                "Legacy Authorized Users File '" + legacyAuthorizedUsersFile + "' does not exists");
    }

    final Unmarshaller unmarshaller = JAXB_USERS_CONTEXT.createUnmarshaller();
    unmarshaller.setSchema(usersSchema);

    final XMLStreamReader xsr;
    try {
        xsr = XmlUtils.createSafeReader(new StreamSource(authorizedUsersFile));
    } catch (XMLStreamException e) {
        logger.error("Encountered an error reading authorized users file: ", e);
        throw new JAXBException("Error reading authorized users file", e);
    }
    final JAXBElement<Users> element = unmarshaller.unmarshal(xsr, org.apache.nifi.user.generated.Users.class);

    final org.apache.nifi.user.generated.Users users = element.getValue();
    if (users.getUser().isEmpty()) {
        logger.info("Legacy Authorized Users File contained no users, nothing to convert");
        return;
    }

    // get all the user DNs into a list
    List<String> userIdentities = new ArrayList<>();
    for (org.apache.nifi.user.generated.User legacyUser : users.getUser()) {
        userIdentities.add(IdentityMappingUtil.mapIdentity(legacyUser.getDn(), identityMappings));
    }

    // sort the list and pull out the first identity
    Collections.sort(userIdentities);
    final String seedIdentity = userIdentities.get(0);

    // create mapping from Role to access policies
    final Map<Role, Set<RoleAccessPolicy>> roleAccessPolicies = RoleAccessPolicy.getMappings(rootGroupId);

    final List<Policy> allPolicies = new ArrayList<>();

    for (org.apache.nifi.user.generated.User legacyUser : users.getUser()) {
        // create the identifier of the new user based on the DN
        final String legacyUserDn = IdentityMappingUtil.mapIdentity(legacyUser.getDn(), identityMappings);
        final User user = userGroupProvider.getUserByIdentity(legacyUserDn);
        if (user == null) {
            throw new AuthorizerCreationException(
                    "Unable to locate legacy user " + legacyUserDn + " to seed policies.");
        }

        // create policies based on the given role
        for (org.apache.nifi.user.generated.Role jaxbRole : legacyUser.getRole()) {
            Role role = Role.valueOf(jaxbRole.getName());
            Set<RoleAccessPolicy> policies = roleAccessPolicies.get(role);

            for (RoleAccessPolicy roleAccessPolicy : policies) {

                // get the matching policy, or create a new one
                Policy policy = getOrCreatePolicy(allPolicies, seedIdentity, roleAccessPolicy.getResource(),
                        roleAccessPolicy.getAction());

                // add the user to the policy if it doesn't exist
                addUserToPolicy(user.getIdentifier(), policy);
            }
        }

    }

    // convert any access controls on ports to the appropriate policies
    for (PortDTO portDTO : ports) {
        final Resource resource;
        if (portDTO.getType() != null && portDTO.getType().equals("inputPort")) {
            resource = ResourceFactory.getDataTransferResource(ResourceFactory
                    .getComponentResource(ResourceType.InputPort, portDTO.getId(), portDTO.getName()));
        } else {
            resource = ResourceFactory.getDataTransferResource(ResourceFactory
                    .getComponentResource(ResourceType.OutputPort, portDTO.getId(), portDTO.getName()));
        }

        if (portDTO.getUserAccessControl() != null) {
            for (String userAccessControl : portDTO.getUserAccessControl()) {
                // need to perform the identity mapping on the access control so it matches the identities in the User objects
                final String mappedUserAccessControl = IdentityMappingUtil.mapIdentity(userAccessControl,
                        identityMappings);
                final User foundUser = userGroupProvider.getUserByIdentity(mappedUserAccessControl);

                // couldn't find the user matching the access control so log a warning and skip
                if (foundUser == null) {
                    logger.warn(
                            "Found port with user access control for {} but no user exists with this identity, skipping...",
                            new Object[] { mappedUserAccessControl });
                    continue;
                }

                // we found the user so create the appropriate policy and add the user to it
                Policy policy = getOrCreatePolicy(allPolicies, seedIdentity, resource.getIdentifier(),
                        WRITE_CODE);

                addUserToPolicy(foundUser.getIdentifier(), policy);
            }
        }

        if (portDTO.getGroupAccessControl() != null) {
            for (String groupAccessControl : portDTO.getGroupAccessControl()) {
                // find a group where the name is the groupAccessControl
                Group foundGroup = null;
                for (Group group : userGroupProvider.getGroups()) {
                    if (group.getName().equals(groupAccessControl)) {
                        foundGroup = group;
                        break;
                    }
                }

                // couldn't find the group matching the access control so log a warning and skip
                if (foundGroup == null) {
                    logger.warn(
                            "Found port with group access control for {} but no group exists with this name, skipping...",
                            new Object[] { groupAccessControl });
                    continue;
                }

                // we found the group so create the appropriate policy and add all the users to it
                Policy policy = getOrCreatePolicy(allPolicies, seedIdentity, resource.getIdentifier(),
                        WRITE_CODE);

                addGroupToPolicy(IdentifierUtil.getIdentifier(groupAccessControl), policy);
            }
        }
    }

    authorizations.getPolicies().getPolicy().addAll(allPolicies);
}

From source file:org.apache.nifi.authorization.FileUserGroupProvider.java

private Tenants unmarshallTenants() throws JAXBException {
    final Unmarshaller unmarshaller = JAXB_TENANTS_CONTEXT.createUnmarshaller();
    unmarshaller.setSchema(tenantsSchema);

    try {/*from  ww  w.j av a 2s.co m*/
        final XMLStreamReader xsr = XmlUtils.createSafeReader(new StreamSource(tenantsFile));
        final JAXBElement<Tenants> element = unmarshaller.unmarshal(xsr, Tenants.class);
        return element.getValue();
    } catch (XMLStreamException e) {
        throw new JAXBException("Error unmarshalling tenants", e);
    }
}

From source file:org.castor.jaxb.CastorJAXBUtils.java

/**
 * Coverts the passed exception into a new instance of {@link javax.xml.bind.JAXBException}.
 *
 * @param msg the error message//  w w  w .  j av  a 2  s  . c  o  m
 * @param e   the exception which was caused of the error
 *
 * @return JAXBException newly created {@link JAXBException} which wrapps the passed object
 */
public static JAXBException convertToJAXBException(String msg, Throwable e) {

    // returns the newly created exception
    return new JAXBException(msg, e);
}

From source file:org.docx4j.openpackaging.parts.JaxbXmlPart.java

/**
* Unmarshal XML data from the specified InputStream and return the
* resulting content tree. Validation event location information may be
* incomplete when using this form of the unmarshal API.
* 
* <p>/*from w w w.  j  a  v  a2s  . c  om*/
* Implements <a href="#unmarshalGlobal">Unmarshal Global Root Element</a>.
* 
* @param is
*            the InputStream to unmarshal XML data from
* @return the newly created root object of the java content tree
* 
* @throws JAXBException
*             If any unexpected errors occur while unmarshalling
*/
public E unmarshal(java.io.InputStream is) throws JAXBException {

    try {
        /* To avoid possible XML External Entity Injection attack,
         * we need to configure the processor.
         * 
         * We use STAX XMLInputFactory to do that.
         * 
         * createXMLStreamReader(is) is 40% slower than unmarshal(is).
         * 
         * But it seems to be the best we can do ... 
         * 
         *   org.w3c.dom.Document doc = XmlUtils.getNewDocumentBuilder().parse(is)
         *   unmarshal(doc)
         * 
         * ie DOM is 5x slower than unmarshal(is)
         * 
         */

        XMLInputFactory xif = XMLInputFactory.newInstance();
        xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
        xif.setProperty(XMLInputFactory.SUPPORT_DTD, false); // a DTD is merely ignored, its presence doesn't cause an exception
        XMLStreamReader xsr = xif.createXMLStreamReader(is);

        Unmarshaller u = jc.createUnmarshaller();

        JaxbValidationEventHandler eventHandler = new JaxbValidationEventHandler();
        if (is.markSupported()) {
            // Only fail hard if we know we can restart
            eventHandler.setContinue(false);
        }
        u.setEventHandler(eventHandler);

        try {
            jaxbElement = (E) XmlUtils.unwrap(u.unmarshal(xsr));
        } catch (UnmarshalException ue) {

            if (ue.getLinkedException() != null && ue.getLinkedException().getMessage().contains("entity")) {

                /*
                   Caused by: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[10,19]
                   Message: The entity "xxe" was referenced, but not declared.
                      at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(Unknown Source)
                      at com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXStreamConnector.bridge(Unknown Source)
                    */
                log.error(ue.getMessage(), ue);
                throw ue;
            }

            if (is.markSupported()) {
                // When reading from zip, we use a ByteArrayInputStream,
                // which does support this.

                log.info("encountered unexpected content; pre-processing");
                eventHandler.setContinue(true);

                try {
                    Templates mcPreprocessorXslt = JaxbValidationEventHandler.getMcPreprocessor();
                    is.reset();
                    JAXBResult result = XmlUtils.prepareJAXBResult(jc);
                    XmlUtils.transform(new StreamSource(is), mcPreprocessorXslt, null, result);
                    jaxbElement = (E) XmlUtils.unwrap(result.getResult());
                } catch (Exception e) {
                    throw new JAXBException("Preprocessing exception", e);
                }

            } else {
                log.error(ue.getMessage(), ue);
                log.error(".. and mark not supported");
                throw ue;
            }
        }

    } catch (XMLStreamException e1) {
        log.error(e1.getMessage(), e1);
        throw new JAXBException(e1);
    }

    return jaxbElement;

}

From source file:org.docx4j.openpackaging.parts.JaxbXmlPart.java

public E unmarshal(org.w3c.dom.Element el) throws JAXBException {

    try {/*from   w  w w  .  j  ava2  s .co m*/

        Unmarshaller u = jc.createUnmarshaller();
        JaxbValidationEventHandler eventHandler = new JaxbValidationEventHandler();
        eventHandler.setContinue(false);
        u.setEventHandler(eventHandler);

        try {
            jaxbElement = (E) XmlUtils.unwrap(u.unmarshal(el));
        } catch (UnmarshalException ue) {
            log.info("encountered unexpected content; pre-processing");
            try {
                org.w3c.dom.Document doc;
                if (el instanceof org.w3c.dom.Document) {
                    doc = (org.w3c.dom.Document) el;
                } else {
                    // Hope for the best. Dodgy though; what if this is
                    // being used on something deep in the tree?
                    // TODO: revisit
                    doc = el.getOwnerDocument();
                }
                eventHandler.setContinue(true);
                JAXBResult result = XmlUtils.prepareJAXBResult(jc);
                Templates mcPreprocessorXslt = JaxbValidationEventHandler.getMcPreprocessor();
                XmlUtils.transform(doc, mcPreprocessorXslt, null, result);
                jaxbElement = (E) XmlUtils.unwrap(result.getResult());
            } catch (Exception e) {
                throw new JAXBException("Preprocessing exception", e);
            }
        }
        return jaxbElement;

    } catch (JAXBException e) {
        log.error(e.getMessage(), e);
        throw e;
    }
}