Example usage for javax.xml.bind UnmarshalException UnmarshalException

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

Introduction

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

Prototype

public UnmarshalException(Throwable exception) 

Source Link

Document

Construct an UnmarshalException with a linkedException.

Usage

From source file:gov.nih.nci.ncicb.tcga.dcc.common.jaxb.JAXBUtil.java

/**
 * This method unmarshals an XML file into a JAXB object element.
 * <p/>// ww w. j  av  a  2 s.c  o  m
 * <p/>
 * The underlying type of the JAXB object element returned by this method will correspond
 * to the JAXB object(s) referenced by the package namespace provided in the parameter list.
 * <p/>
 * <p/>
 * If the <code>filterMetaDataNamespaces</code> parameter is set to true, this method will use
 * the {@link MetaDataXMLNamespaceFilter} to filter the namespace URI of specific meta-data
 * elements during unmarshalling that correspond to the TCGA_BCR.Metadata XSD.
 * <p/>
 * <p/>
 * If the <code>validate</code> parameter is set to true, schema validation will be performed.
 * <p/>
 * <p/>
 * If both <code>filterMetaDataNamespaces</code> and <code>validate</code> are set to true,
 * only the meta-data elements will go through schema validation.
 *
 * @param xmlFile                  - a {@link File} object representing the XML file to unmarshalled
 * @param jaxbPackageName          - a string that represents package namespace of the JAXB context objects
 * @param filterMetaDataNamespaces - boolean that specifies whether or not to filter meta-data
 *                                 namespace URIs using the {@link MetaDataXMLNamespaceFilter}
 * @param validate                 - boolean indicating weather or not the XML should be validated against a schema
 * @return - an instance of {@link UnmarshalResult} representing the result of the unmarhsalling
 * @throws UnmarshalException if an error occurs during unmarshalling
 */
public static UnmarshalResult unmarshal(final File xmlFile, final String jaxbPackageName,
        final boolean filterMetaDataNamespaces, final boolean validate) throws UnmarshalException {

    Object jaxbObject = null;
    ValidationEventCollector validationEventCollector = (validate ? new ValidationEventCollector() : null);
    JAXBContext jaxbContext;
    Unmarshaller unmarshaller;

    if (xmlFile != null && jaxbPackageName != null) {
        FileReader xmlFileReader = null;
        try {
            // Get the JAXB context using the package name and create an unmarshaller
            jaxbContext = JAXBContext.newInstance(jaxbPackageName);
            unmarshaller = jaxbContext.createUnmarshaller();
            xmlFileReader = new FileReader(xmlFile);

            // Unmarshal the XML file
            if (filterMetaDataNamespaces) {
                final SAXSource source = applyMetaDataNamespaceFilter(unmarshaller, xmlFileReader);
                jaxbObject = unmarshaller.unmarshal(source);

                // Perform schema validation meta-data elements only
                if (validate) {
                    final String metaDataXML = getMetaDataXMLAsString(jaxbContext, jaxbObject);
                    jaxbObject = validate(unmarshaller, validationEventCollector, new StringReader(metaDataXML),
                            true);
                }
            } else {

                // Perform schema validation of all XML elements
                if (validate) {
                    jaxbObject = validate(unmarshaller, validationEventCollector, xmlFileReader, false);
                } else {
                    jaxbObject = unmarshaller.unmarshal(xmlFile);
                }
            }
        } catch (Exception e) {
            throw new UnmarshalException(e);
        } finally {
            IOUtils.closeQuietly(xmlFileReader);
        }
    } else {
        throw new UnmarshalException(new StringBuilder()
                .append("Unmarshalling failed because either the XML file '").append(xmlFile)
                .append("' or package namespace '").append(jaxbPackageName).append("' was null").toString());
    }

    // Return the result of the unmarshalling
    if (validationEventCollector != null) {
        return new UnmarshalResult(jaxbObject, Arrays.asList(validationEventCollector.getEvents()));
    } else {
        return new UnmarshalResult(jaxbObject, new ArrayList<ValidationEvent>());
    }
}

From source file:org.kuali.rice.core.util.jaxb.NameAndNamespacePairValidatingAdapter.java

/**
 * @see javax.xml.bind.annotation.adapters.XmlAdapter#unmarshal(java.lang.Object)
 *//*from w  w  w .  j a  va2  s .  co  m*/
@Override
public NameAndNamespacePair unmarshal(NameAndNamespacePair v) throws Exception {
    if (v != null) {

        if (StringUtils.isBlank(v.getName())) {
            throw new UnmarshalException("Cannot import a name-and-namespace pair with a blank name");
        } else if (StringUtils.isBlank(v.getNamespaceCode())) {
            throw new UnmarshalException("Cannot import a name-and-namespace pair with a blank namespace code");
        }
        if (CoreServiceApiServiceLocator.getNamespaceService().getNamespace(v.getNamespaceCode()) == null) {
            throw new UnmarshalException(
                    "Cannot import a name-and-namespace pair with invalid or unknown namespace \""
                            + v.getNamespaceCode() + "\"");
        }

        v.setName(new NormalizedStringAdapter().unmarshal(v.getName()));
        v.setNamespaceCode(v.getNamespaceCode());
    }
    return v;
}

From source file:org.kuali.rice.kim.api.jaxb.NameAndNamespacePairToKimTypeIdAdapter.java

/**
 * @see javax.xml.bind.annotation.adapters.XmlAdapter#unmarshal(java.lang.Object)
 *///from www .j  a  va  2  s. c  o  m
@Override
public String unmarshal(NameAndNamespacePair v) throws Exception {
    if (v != null) {
        KimTypeContract kimType = KimApiServiceLocator.getKimTypeInfoService().findKimTypeByNameAndNamespace(
                v.getNamespaceCode(), new NormalizedStringAdapter().unmarshal(v.getName()));
        if (kimType == null) {
            throw new UnmarshalException("Cannot find KIM Type with namespace \"" + v.getNamespaceCode()
                    + "\" and name \"" + v.getName() + "\"");
        }
        return kimType.getId();
    }
    return null;
}

From source file:org.kuali.rice.kim.api.jaxb.PermissionDetailListAdapter.java

/**
 * @see javax.xml.bind.annotation.adapters.XmlAdapter#unmarshal(java.lang.Object)
 *//*from  w w  w. j a  v  a2s . c o  m*/
@Override
public Map<String, String> unmarshal(PermissionDetailList v) throws Exception {
    if (v != null) {
        NormalizedStringAdapter normalizedStringAdapter = new NormalizedStringAdapter();
        Map<String, String> map = new HashMap<String, String>();
        for (MapStringStringAdapter.StringMapEntry stringMapEntry : v.getPermissionDetails()) {
            String tempKey = normalizedStringAdapter.unmarshal(stringMapEntry.getKey());
            if (StringUtils.isBlank(tempKey)) {
                throw new UnmarshalException("Cannot create a permission detail entry with a blank key");
            } else if (map.containsKey(tempKey)) {
                throw new UnmarshalException(
                        "Cannot create more than one permission detail entry with a key of \"" + tempKey
                                + "\"");
            }
            map.put(tempKey, normalizedStringAdapter.unmarshal(stringMapEntry.getValue()));
        }
    }
    return null;
}

From source file:org.kuali.rice.kim.api.jaxb.QualificationListAdapter.java

/**
 * @see javax.xml.bind.annotation.adapters.XmlAdapter#unmarshal(java.lang.Object)
 *///w w w  .j  a  va  2 s.  c om
@Override
public Map<String, String> unmarshal(QualificationList v) throws Exception {
    if (v != null) {
        NormalizedStringAdapter normalizedStringAdapter = new NormalizedStringAdapter();
        Map<String, String> map = new HashMap<String, String>();
        for (MapStringStringAdapter.StringMapEntry stringMapEntry : v.getQualifications()) {
            String tempKey = normalizedStringAdapter.unmarshal(stringMapEntry.getKey());
            if (StringUtils.isBlank(tempKey)) {
                throw new UnmarshalException("Cannot create a qualification entry with a blank key");
            } else if (map.containsKey(tempKey)) {
                throw new UnmarshalException(
                        "Cannot create more than one qualification entry with a key of \"" + tempKey + "\"");
            }
            map.put(tempKey, normalizedStringAdapter.unmarshal(stringMapEntry.getValue()));
        }
    }
    return null;
}

From source file:org.kuali.rice.kim.impl.jaxb.PermissionXmlUtil.java

/**
 * Validates a permission to ensure that the required fields have been filled.
 * // w w w. j a  va 2s .  c o m
 * @throws UnmarshalException if newPermission contains invalid data.
 */
private static void validatePermission(PermissionXmlDTO newPermission) throws UnmarshalException {
    // Ensure that the permission name, namespace, template, and description have been filled in.
    if (StringUtils.isBlank(newPermission.getPermissionName())
            || StringUtils.isBlank(newPermission.getNamespaceCode())) {
        throw new UnmarshalException("Cannot create a permission with a blank name or namespace");
    } else if (StringUtils.isBlank(newPermission.getPermissionTemplateId())) {
        throw new UnmarshalException("Cannot create a permission without specifying a permission template");
    } else if (StringUtils.isBlank(newPermission.getPermissionDescription())) {
        throw new UnmarshalException("Cannot create a permission with a blank description");
    }

    // If another permission with that name and namespace exists, use its ID on the new permission.
    PermissionContract permission = KimApiServiceLocator.getPermissionService().findPermByNamespaceCodeAndName(
            newPermission.getNamespaceCode(), newPermission.getPermissionName());
    if (permission != null) {
        newPermission.setPermissionId(permission.getId());
    }
}

From source file:org.kuali.rice.kim.impl.jaxb.RoleXmlUtil.java

/**
 * Performs the necessary validation on the new role member, then saves it.
 * //w w w .  j a  va  2 s  .c  o  m
 * @param newRoleMember The role member to save.
 * @return The ID of the persisted role member.
 * @throws IllegalArgumentException if newRoleMember is null.
 * @throws UnmarshalException if newRoleMember contains invalid data.
 */
static String validateAndPersistNewRoleMember(RoleMemberXmlDTO newRoleMember) throws UnmarshalException {

    if (newRoleMember == null) {
        throw new IllegalArgumentException("Cannot persist a null role member");
    }

    // Validate role ID and role name/namespace.
    validateRoleIdAndRoleNameForMember(newRoleMember);

    // Validate member type, member ID, and member name/namespace.
    validateMemberIdentity(newRoleMember);

    // Validate the from/to dates, if defined.
    if (newRoleMember.getActiveFromDate() != null && newRoleMember.getActiveToDate() != null
            && newRoleMember.getActiveFromDate().compareTo(newRoleMember.getActiveToDate()) > 0) {
        throw new UnmarshalException(
                "Cannot create a role member whose activeFromDate occurs after its activeToDate");
    }

    // Define defaults as needed.
    if (newRoleMember.getQualifications() == null) {
        newRoleMember.setQualifications(new HashMap<String, String>());
    }

    RoleMember.Builder builder = RoleMember.Builder.create(newRoleMember.getRoleId(),
            newRoleMember.getRoleIdAsMember(), newRoleMember.getMemberId(), newRoleMember.getMemberType(),
            newRoleMember.getActiveFromDate() == null ? null
                    : new DateTime(newRoleMember.getActiveFromDate().getMillis()),
            newRoleMember.getActiveToDate() == null ? null
                    : new DateTime(newRoleMember.getActiveToDate().getMillis()),
            newRoleMember.getQualifications(), newRoleMember.getMemberName(),
            newRoleMember.getMemberNamespaceCode());

    // Save the role member.
    RoleMemberContract newMember = KimApiServiceLocator.getRoleService().createRoleMember(builder.build());

    return newMember.getId();
}

From source file:org.kuali.rice.kim.impl.jaxb.RoleXmlUtil.java

/**
 * Validates a new role's name, namespace, KIM type, and description, and sets the role's ID if the name and namespace match an existing role.
 *///from www. j  a v a2  s.  c  o m
private static void validateAndPrepareRole(RoleXmlDTO newRole) throws UnmarshalException {
    // Ensure that the role name, role namespace, KIM type, and description have all been specified.
    if (StringUtils.isBlank(newRole.getRoleName()) || StringUtils.isBlank(newRole.getNamespaceCode())) {
        throw new UnmarshalException("Cannot create or override a role with a blank name or a blank namespace");
    } else if (StringUtils.isBlank(newRole.getKimTypeId())) {
        throw new UnmarshalException("Cannot create or override a role without specikfying a KIM type");
    } else if (StringUtils.isBlank(newRole.getRoleDescription())) {
        throw new UnmarshalException("Cannot create or override a role with a blank description");
    }

    // Attempt to find an existing matching role, and assign its ID to the validated role if it exists.
    String matchingId = KimApiServiceLocator.getRoleService()
            .getRoleIdByNamespaceCodeAndName(newRole.getNamespaceCode(), newRole.getRoleName());
    if (StringUtils.isNotBlank(matchingId)) {
        newRole.setRoleId(matchingId);
    }
}

From source file:org.kuali.rice.kim.impl.jaxb.RoleXmlUtil.java

/**
 * Validates a new role member's role ID, role name, and role namespace.
 *///from w  w  w . ja v a  2  s .  c o  m
private static void validateRoleIdAndRoleNameForMember(RoleMemberXmlDTO newRoleMember)
        throws UnmarshalException {
    // If the "roleMember" tag was not a descendant of a "role" tag, derive and validate its role information accordingly.
    if (newRoleMember instanceof RoleMemberXmlDTO.OutsideOfRole) {
        RoleMemberXmlDTO.OutsideOfRole standaloneMember = (RoleMemberXmlDTO.OutsideOfRole) newRoleMember;
        if (standaloneMember.getRoleNameAndNamespace() != null) {
            // If a name + namespace combo is given, verify that the combo maps to an existing role.
            String existingId = KimApiServiceLocator.getRoleService().getRoleIdByNamespaceCodeAndName(
                    standaloneMember.getRoleNamespaceCode(), standaloneMember.getRoleName());
            if (StringUtils.isBlank(existingId)) {
                throw new UnmarshalException("Cannot create role member for role with name \""
                        + standaloneMember.getRoleName() + "\" and namespace \""
                        + standaloneMember.getRoleNamespaceCode() + "\" because such a role does not exist");
            }

            // If the role member defines its own role ID, verify that it's the same as the one from the existing role; otherwise, assign the member's role ID.
            if (StringUtils.isBlank(standaloneMember.getRoleId())) {
                standaloneMember.setRoleId(existingId);
            } else if (!standaloneMember.getRoleId().equals(existingId)) {
                throw new UnmarshalException("Cannot create role member for role with ID \""
                        + standaloneMember.getRoleId() + "\", name \"" + standaloneMember.getRoleName()
                        + "\", and namespace \"" + standaloneMember.getRoleNamespaceCode()
                        + "\" because the existing role with the same name and namespace has an ID of \""
                        + existingId + "\" instead");
            }
        } else if (StringUtils.isBlank(standaloneMember.getRoleId())) {
            throw new UnmarshalException(
                    "Cannot create role member without providing the role ID or role name + namespace that the member belongs to");
        } else if (KimApiServiceLocator.getRoleService().getRole(standaloneMember.getRoleId()) == null) {
            throw new UnmarshalException("Cannot create role member for the role with ID \""
                    + standaloneMember.getRoleId() + "\" because that role does not exist");
        }
    }

    // Ensure that a role ID was explicitly defined or was derived from a name + namespace combo.
    if (StringUtils.isBlank(newRoleMember.getRoleId())) {
        throw new UnmarshalException(
                "Cannot create role member without providing the role ID or role name + namespace that the member belongs to");
    }
}

From source file:org.kuali.rice.kim.impl.jaxb.RoleXmlUtil.java

/**
 * Validates a new role member's member type, member ID, member name, and (if applicable) member namespace code.
 *//*from  w  w  w .j av  a  2 s .  c  o  m*/
private static void validateMemberIdentity(RoleMemberXmlDTO newRoleMember) throws UnmarshalException {
    // Ensure that sufficient and non-conflicting membership info has been set. (The getMemberTypeCode() method performs such validation.)
    MemberType memberType = newRoleMember.getMemberType();
    if (memberType == null) {
        throw new UnmarshalException(
                "Cannot create a role member with no member principal/group/role identification information specified");
    }

    // Ensure that a valid member ID was specified, if present.
    if (StringUtils.isNotBlank(newRoleMember.getMemberId())) {
        if (MemberType.PRINCIPAL.equals(memberType)) {
            // If the member is a principal, ensure that the principal exists.
            if (KimApiServiceLocator.getIdentityService()
                    .getPrincipal(newRoleMember.getPrincipalId()) == null) {
                throw new UnmarshalException("Cannot create principal role member with principal ID \""
                        + newRoleMember.getPrincipalId() + "\" because such a person does not exist");
            }
        } else if (MemberType.GROUP.equals(memberType)) {
            // If the member is a group, ensure that the group exists.
            if (KimApiServiceLocator.getGroupService().getGroup(newRoleMember.getGroupId()) == null) {
                throw new UnmarshalException("Cannot create group role member with group ID \""
                        + newRoleMember.getGroupId() + "\" because such a group does not exist");
            }
        } else if (MemberType.ROLE.equals(memberType)) {
            // If the member is another role, ensure that the role exists and that the role is not trying to become a member of itself.
            if (newRoleMember.getRoleId().equals(newRoleMember.getRoleIdAsMember())) {
                throw new UnmarshalException("The role with ID \"" + newRoleMember.getRoleIdAsMember()
                        + "\" cannot be made a member of itself");
            } else if (KimApiServiceLocator.getRoleService()
                    .getRole(newRoleMember.getRoleIdAsMember()) == null) {
                throw new UnmarshalException("Cannot use role with ID \"" + newRoleMember.getRoleIdAsMember()
                        + "\" as a role member because such a role does not exist");
            }
        }
    }

    // Ensure that a valid member name (and namespace, if applicable) was specified, if present.
    if (StringUtils.isNotBlank(newRoleMember.getMemberName())) {
        if (MemberType.PRINCIPAL.equals(memberType)) {
            //If the member is a principal, ensure that the principal exists and does not conflict with any existing principal ID information.
            PrincipalContract tempPrincipal = KimApiServiceLocator.getIdentityService()
                    .getPrincipalByPrincipalName(newRoleMember.getPrincipalName());
            if (tempPrincipal == null) {
                throw new UnmarshalException("Cannot create principal role member with principal name \""
                        + newRoleMember.getPrincipalName() + "\" because such a person does not exist");
            } else if (StringUtils.isBlank(newRoleMember.getPrincipalId())) {
                // If no principal ID was given, assign one from the retrieved principal.
                newRoleMember.setPrincipalId(tempPrincipal.getPrincipalId());
            } else if (!newRoleMember.getPrincipalId().equals(tempPrincipal.getPrincipalId())) {
                throw new UnmarshalException("Cannot create principal role member with principal ID \""
                        + newRoleMember.getPrincipalId() + "\" and principal name \""
                        + newRoleMember.getPrincipalName()
                        + "\" because the principal with that name has an ID of \""
                        + tempPrincipal.getPrincipalId() + "\" instead");
            }
        } else if (MemberType.GROUP.equals(memberType)) {
            // If the member is a group, ensure that the group exists and does not conflict with any existing group ID information.
            NameAndNamespacePair groupNameAndNamespace = newRoleMember.getGroupName();
            GroupContract tempGroup = KimApiServiceLocator.getGroupService().getGroupByNamespaceCodeAndName(
                    groupNameAndNamespace.getNamespaceCode(), groupNameAndNamespace.getName());
            if (tempGroup == null) {
                throw new UnmarshalException("Cannot create group role member with namespace \""
                        + groupNameAndNamespace.getNamespaceCode() + "\" and name \""
                        + groupNameAndNamespace.getName() + "\" because such a group does not exist");
            } else if (StringUtils.isBlank(newRoleMember.getGroupId())) {
                // If no group ID was given, assign one from the retrieved group.
                newRoleMember.setGroupId(tempGroup.getId());
            } else if (!newRoleMember.getGroupId().equals(tempGroup.getId())) {
                throw new UnmarshalException(
                        "Cannot create group role member with ID \"" + newRoleMember.getGroupId()
                                + "\", namespace \"" + groupNameAndNamespace.getNamespaceCode()
                                + "\", and name \"" + groupNameAndNamespace.getName()
                                + "\" because the group with that namespace and name has an ID of \""
                                + tempGroup.getId() + "\" instead");
            }
        } else if (MemberType.ROLE.equals(memberType)) {
            // If the member is another role, ensure that the role exists, does not conflict with any existing role ID information, and is not the member's role.
            NameAndNamespacePair roleNameAndNamespace = newRoleMember.getRoleNameAsMember();
            RoleContract tempRole = KimApiServiceLocator.getRoleService().getRoleByNamespaceCodeAndName(
                    roleNameAndNamespace.getNamespaceCode(), roleNameAndNamespace.getName());
            if (tempRole == null) {
                throw new UnmarshalException(
                        "Cannot use role with namespace \"" + roleNameAndNamespace.getNamespaceCode()
                                + "\" and name \"" + roleNameAndNamespace.getName()
                                + "\" as a role member because such a role does not exist");
            } else if (newRoleMember.getRoleId().equals(tempRole.getId())) {
                throw new UnmarshalException("The role with namespace \""
                        + roleNameAndNamespace.getNamespaceCode() + "\" and name \""
                        + roleNameAndNamespace.getName() + "\" cannot be made a member of itself");
            } else if (StringUtils.isBlank(newRoleMember.getRoleId())) {
                // If no role ID was given, assign one from the retrieved role.
                newRoleMember.setRoleIdAsMember(tempRole.getId());
            } else if (!newRoleMember.getRoleId().equals(tempRole.getId())) {
                throw new RuntimeException("Cannot use role with ID \"" + newRoleMember.getRoleId()
                        + "\", namespace \"" + roleNameAndNamespace.getNamespaceCode() + "\", and name \""
                        + roleNameAndNamespace.getName()
                        + "\" as a role member because the role with that namespace and name has an ID of \""
                        + tempRole.getId() + "\" instead");
            }
        }
    }

    // Ensure that a member ID was either explicitly defined or was derived from the member name (and namespace, if applicable).
    if (StringUtils.isBlank(newRoleMember.getMemberId())) {
        throw new RuntimeException(
                "Cannot create a role member with no member principal/group/role identification information specified");
    }

}