Java Code Examples for javax.xml.bind.UnmarshalException

The following are top voted examples for showing how to use javax.xml.bind.UnmarshalException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: OpenJSharp   File: AbstractUnmarshallerImpl.java   View source code 7 votes vote down vote up
/**
 * Creates an UnmarshalException from a SAXException.
 *
 * This is an utility method provided for the derived classes.
 *
 * <p>
 * When a provider-implemented ContentHandler wants to throw a
 * JAXBException, it needs to wrap the exception by a SAXException.
 * If the unmarshaller implementation blindly wrap SAXException
 * by JAXBException, such an exception will be a JAXBException
 * wrapped by a SAXException wrapped by another JAXBException.
 * This is silly.
 *
 * <p>
 * This method checks the nested exception of SAXException
 * and reduce those excessive wrapping.
 *
 * @return the resulting UnmarshalException
 */
protected UnmarshalException createUnmarshalException( SAXException e ) {
    // check the nested exception to see if it's an UnmarshalException
    Exception nested = e.getException();
    if(nested instanceof UnmarshalException)
        return (UnmarshalException)nested;

    if(nested instanceof RuntimeException)
        // typically this is an unexpected exception,
        // just throw it rather than wrap it, so that the full stack
        // trace can be displayed.
        throw (RuntimeException)nested;


    // otherwise simply wrap it
    if(nested!=null)
        return new UnmarshalException(nested);
    else
        return new UnmarshalException(e);
}
 
Example 2
Project: openjdk-jdk10   File: AbstractUnmarshallerImpl.java   View source code 7 votes vote down vote up
/**
 * Creates an UnmarshalException from a SAXException.
 *
 * This is an utility method provided for the derived classes.
 *
 * <p>
 * When a provider-implemented ContentHandler wants to throw a
 * JAXBException, it needs to wrap the exception by a SAXException.
 * If the unmarshaller implementation blindly wrap SAXException
 * by JAXBException, such an exception will be a JAXBException
 * wrapped by a SAXException wrapped by another JAXBException.
 * This is silly.
 *
 * <p>
 * This method checks the nested exception of SAXException
 * and reduce those excessive wrapping.
 *
 * @return the resulting UnmarshalException
 */
protected UnmarshalException createUnmarshalException( SAXException e ) {
    // check the nested exception to see if it's an UnmarshalException
    Exception nested = e.getException();
    if(nested instanceof UnmarshalException)
        return (UnmarshalException)nested;

    if(nested instanceof RuntimeException)
        // typically this is an unexpected exception,
        // just throw it rather than wrap it, so that the full stack
        // trace can be displayed.
        throw (RuntimeException)nested;


    // otherwise simply wrap it
    if(nested!=null)
        return new UnmarshalException(nested);
    else
        return new UnmarshalException(e);
}
 
Example 3
Project: s3-proxy-chunk-upload   File: JAXBUtils.java   View source code 6 votes vote down vote up
public static  <T> T unmarshallUploadFromDocument(Document dom,
        String rootElement, Class<T> resultingClass)
        throws UnmarshalException {
    try {           
        String xmlString = getStringFromXML(dom, rootElement); 
        xmlString = xmlString.replaceAll(" xmlns(?:.*?)?=\".*?\"", "");            
        
        if (rootElement != null) {
            xmlString = "<" + rootElement + ">" + xmlString + "</"
                    + rootElement + ">";
        }

        return (T) unmarshallFromString(xmlString, resultingClass);
    } catch (Throwable e) {
        throw new UnmarshalException("Unable to unmarshal string", e);
    }
}
 
Example 4
Project: s3-proxy-chunk-upload   File: JAXBUtils.java   View source code 6 votes vote down vote up
public static final <T> T unmarshallUploadFromDocumentString(String xmlString,
                                                       String rootElement, Class<T> resultingClass)
        throws UnmarshalException {
    try {
        xmlString = xmlString.replaceAll(" xmlns(?:.*?)?=\".*?\"", "");

        if (rootElement != null) {
            xmlString = "<" + rootElement + ">" + xmlString + "</"
                    + rootElement + ">";
        }

        return (T) unmarshallFromString(xmlString, resultingClass);
    } catch (Throwable e) {
        throw new UnmarshalException("Unable to unmarshall string", e);
    }
}
 
Example 5
Project: s3-proxy-chunk-upload   File: JAXBUtils.java   View source code 6 votes vote down vote up
private static String getStringFromXML(Document dom,
        String rootElement) throws UnmarshalException {
    try {
        DOMSource domSource = new DOMSource(dom);
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty("omit-xml-declaration", "yes");
        transformer.transform(domSource, result);
        String xmlString = writer.toString();            
        
        if (rootElement != null) {
            xmlString = "<" + rootElement + ">" + xmlString + "</"
                    + rootElement + ">";
        }
        
        return xmlString;
    } catch (Throwable e) {
        throw new UnmarshalException("Unable to unmarshall string", e);
    }
}
 
Example 6
Project: hybris-integration-intellij-idea-plugin   File: DefaultBpJaxbService.java   View source code 6 votes vote down vote up
@Nonnull
@Override
public Process unmarshallBusinessProcessXml(@NotNull final File file) throws UnmarshalException {
    Validate.notNull(file);

    try {
        if (null == this.jaxbContext) {
            LOG.error(String.format(
                "Can not unmarshall '%s' because JAXBContext has not been created.", file.getAbsolutePath()
            ));

            return null;
        }

        final Unmarshaller jaxbUnmarshaller = this.jaxbContext.get().createUnmarshaller();

        return (Process) jaxbUnmarshaller.unmarshal(file);
    } catch (Exception e) {
        throw new UnmarshalException("Can not unmarshall " + file.getAbsolutePath(), e);
    }
}
 
Example 7
Project: OpenJSharp   File: UnmarshallingContext.java   View source code 6 votes vote down vote up
/**
 * Reports an error to the user, and asks if s/he wants
 * to recover. If the canRecover flag is false, regardless
 * of the client instruction, an exception will be thrown.
 *
 * Only if the flag is true and the user wants to recover from an error,
 * the method returns normally.
 *
 * The thrown exception will be catched by the unmarshaller.
 */
public void handleEvent(ValidationEvent event, boolean canRecover ) throws SAXException {
    ValidationEventHandler eventHandler = parent.getEventHandler();

    boolean recover = eventHandler.handleEvent(event);

    // if the handler says "abort", we will not return the object
    // from the unmarshaller.getResult()
    if(!recover)    aborted = true;

    if( !canRecover || !recover )
        throw new SAXParseException2( event.getMessage(), locator,
            new UnmarshalException(
                event.getMessage(),
                event.getLinkedException() ) );
}
 
Example 8
Project: OpenJSharp   File: UnmarshallerImpl.java   View source code 6 votes vote down vote up
private static JAXBException handleStreamException(XMLStreamException e) {
    // StAXStreamConnector wraps SAXException to XMLStreamException.
    // XMLStreamException doesn't print its nested stack trace when it prints
    // its stack trace, so if we wrap XMLStreamException in JAXBException,
    // it becomes harder to find out the real problem.
    // So we unwrap them here. But we don't want to unwrap too eagerly, because
    // that could throw away some meaningful exception information.
    Throwable ne = e.getNestedException();
    if(ne instanceof JAXBException) {
        return (JAXBException)ne;
    }
    if(ne instanceof SAXException) {
        return new UnmarshalException(ne);
    }
    return new UnmarshalException(e);
}
 
Example 9
Project: openjdk-jdk10   File: UnmarshallingContext.java   View source code 6 votes vote down vote up
/**
 * Reports an error to the user, and asks if s/he wants
 * to recover. If the canRecover flag is false, regardless
 * of the client instruction, an exception will be thrown.
 *
 * Only if the flag is true and the user wants to recover from an error,
 * the method returns normally.
 *
 * The thrown exception will be catched by the unmarshaller.
 */
public void handleEvent(ValidationEvent event, boolean canRecover ) throws SAXException {
    ValidationEventHandler eventHandler = parent.getEventHandler();

    boolean recover = eventHandler.handleEvent(event);

    // if the handler says "abort", we will not return the object
    // from the unmarshaller.getResult()
    if(!recover)    aborted = true;

    if( !canRecover || !recover )
        throw new SAXParseException2( event.getMessage(), locator,
            new UnmarshalException(
                event.getMessage(),
                event.getLinkedException() ) );
}
 
Example 10
Project: openjdk-jdk10   File: UnmarshallerImpl.java   View source code 6 votes vote down vote up
private static JAXBException handleStreamException(XMLStreamException e) {
    // StAXStreamConnector wraps SAXException to XMLStreamException.
    // XMLStreamException doesn't print its nested stack trace when it prints
    // its stack trace, so if we wrap XMLStreamException in JAXBException,
    // it becomes harder to find out the real problem.
    // So we unwrap them here. But we don't want to unwrap too eagerly, because
    // that could throw away some meaningful exception information.
    Throwable ne = e.getNestedException();
    if(ne instanceof JAXBException) {
        return (JAXBException)ne;
    }
    if(ne instanceof SAXException) {
        return new UnmarshalException(ne);
    }
    return new UnmarshalException(e);
}
 
Example 11
Project: openjdk9   File: UnmarshallingContext.java   View source code 6 votes vote down vote up
/**
 * Reports an error to the user, and asks if s/he wants
 * to recover. If the canRecover flag is false, regardless
 * of the client instruction, an exception will be thrown.
 *
 * Only if the flag is true and the user wants to recover from an error,
 * the method returns normally.
 *
 * The thrown exception will be catched by the unmarshaller.
 */
public void handleEvent(ValidationEvent event, boolean canRecover ) throws SAXException {
    ValidationEventHandler eventHandler = parent.getEventHandler();

    boolean recover = eventHandler.handleEvent(event);

    // if the handler says "abort", we will not return the object
    // from the unmarshaller.getResult()
    if(!recover)    aborted = true;

    if( !canRecover || !recover )
        throw new SAXParseException2( event.getMessage(), locator,
            new UnmarshalException(
                event.getMessage(),
                event.getLinkedException() ) );
}
 
Example 12
Project: openjdk9   File: UnmarshallerImpl.java   View source code 6 votes vote down vote up
private static JAXBException handleStreamException(XMLStreamException e) {
    // StAXStreamConnector wraps SAXException to XMLStreamException.
    // XMLStreamException doesn't print its nested stack trace when it prints
    // its stack trace, so if we wrap XMLStreamException in JAXBException,
    // it becomes harder to find out the real problem.
    // So we unwrap them here. But we don't want to unwrap too eagerly, because
    // that could throw away some meaningful exception information.
    Throwable ne = e.getNestedException();
    if(ne instanceof JAXBException) {
        return (JAXBException)ne;
    }
    if(ne instanceof SAXException) {
        return new UnmarshalException(ne);
    }
    return new UnmarshalException(e);
}
 
Example 13
Project: openjdk9   File: AbstractUnmarshallerImpl.java   View source code 6 votes vote down vote up
/**
 * Creates an UnmarshalException from a SAXException.
 *
 * This is an utility method provided for the derived classes.
 *
 * <p>
 * When a provider-implemented ContentHandler wants to throw a
 * JAXBException, it needs to wrap the exception by a SAXException.
 * If the unmarshaller implementation blindly wrap SAXException
 * by JAXBException, such an exception will be a JAXBException
 * wrapped by a SAXException wrapped by another JAXBException.
 * This is silly.
 *
 * <p>
 * This method checks the nested exception of SAXException
 * and reduce those excessive wrapping.
 *
 * @return the resulting UnmarshalException
 */
protected UnmarshalException createUnmarshalException( SAXException e ) {
    // check the nested exception to see if it's an UnmarshalException
    Exception nested = e.getException();
    if(nested instanceof UnmarshalException)
        return (UnmarshalException)nested;

    if(nested instanceof RuntimeException)
        // typically this is an unexpected exception,
        // just throw it rather than wrap it, so that the full stack
        // trace can be displayed.
        throw (RuntimeException)nested;


    // otherwise simply wrap it
    if(nested!=null)
        return new UnmarshalException(nested);
    else
        return new UnmarshalException(e);
}
 
Example 14
Project: Java8CN   File: AbstractUnmarshallerImpl.java   View source code 6 votes vote down vote up
/**
 * Creates an UnmarshalException from a SAXException.
 *
 * This is an utility method provided for the derived classes.
 *
 * <p>
 * When a provider-implemented ContentHandler wants to throw a
 * JAXBException, it needs to wrap the exception by a SAXException.
 * If the unmarshaller implementation blindly wrap SAXException
 * by JAXBException, such an exception will be a JAXBException
 * wrapped by a SAXException wrapped by another JAXBException.
 * This is silly.
 *
 * <p>
 * This method checks the nested exception of SAXException
 * and reduce those excessive wrapping.
 *
 * @return the resulting UnmarshalException
 */
protected UnmarshalException createUnmarshalException( SAXException e ) {
    // check the nested exception to see if it's an UnmarshalException
    Exception nested = e.getException();
    if(nested instanceof UnmarshalException)
        return (UnmarshalException)nested;

    if(nested instanceof RuntimeException)
        // typically this is an unexpected exception,
        // just throw it rather than wrap it, so that the full stack
        // trace can be displayed.
        throw (RuntimeException)nested;


    // otherwise simply wrap it
    if(nested!=null)
        return new UnmarshalException(nested);
    else
        return new UnmarshalException(e);
}
 
Example 15
Project: ubongo   File: Configuration.java   View source code 6 votes vote down vote up
static public Configuration loadConfiguration(String path) throws UnmarshalException {
    Configuration configuration;
    File file = new File(path);
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(Configuration.class);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        configuration = (Configuration) unmarshaller.unmarshal(file);
        if (configuration.debug == null) {
            configuration.debug = false;
        }
    } catch (JAXBException e) {
        logger.error("Failed to parse configuration file (file path: "
                + file.getAbsolutePath() + ").", e);
        configuration = null;
    }
    if (configuration == null) {
        throw new UnmarshalException("Failed to load configuration. Make sure that " + file.getAbsolutePath() + " exists and is configured correctly");
    }
    return configuration;
}
 
Example 16
Project: spring4-understanding   File: Jaxb2Marshaller.java   View source code 6 votes vote down vote up
/**
 * Convert the given {@code JAXBException} to an appropriate exception from the
 * {@code org.springframework.oxm} hierarchy.
 * @param ex {@code JAXBException} that occured
 * @return the corresponding {@code XmlMappingException}
 */
protected XmlMappingException convertJaxbException(JAXBException ex) {
	if (ex instanceof ValidationException) {
		return new ValidationFailureException("JAXB validation exception", ex);
	}
	else if (ex instanceof MarshalException) {
		return new MarshallingFailureException("JAXB marshalling exception", ex);
	}
	else if (ex instanceof UnmarshalException) {
		return new UnmarshallingFailureException("JAXB unmarshalling exception", ex);
	}
	else {
		// fallback
		return new UncategorizedMappingException("Unknown JAXB exception", ex);
	}
}
 
Example 17
Project: lookaside_java-1.8.0-openjdk   File: UnmarshallingContext.java   View source code 6 votes vote down vote up
/**
 * Reports an error to the user, and asks if s/he wants
 * to recover. If the canRecover flag is false, regardless
 * of the client instruction, an exception will be thrown.
 *
 * Only if the flag is true and the user wants to recover from an error,
 * the method returns normally.
 *
 * The thrown exception will be catched by the unmarshaller.
 */
public void handleEvent(ValidationEvent event, boolean canRecover ) throws SAXException {
    ValidationEventHandler eventHandler = parent.getEventHandler();

    boolean recover = eventHandler.handleEvent(event);

    // if the handler says "abort", we will not return the object
    // from the unmarshaller.getResult()
    if(!recover)    aborted = true;

    if( !canRecover || !recover )
        throw new SAXParseException2( event.getMessage(), locator,
            new UnmarshalException(
                event.getMessage(),
                event.getLinkedException() ) );
}
 
Example 18
Project: lookaside_java-1.8.0-openjdk   File: UnmarshallerImpl.java   View source code 6 votes vote down vote up
private static JAXBException handleStreamException(XMLStreamException e) {
    // StAXStreamConnector wraps SAXException to XMLStreamException.
    // XMLStreamException doesn't print its nested stack trace when it prints
    // its stack trace, so if we wrap XMLStreamException in JAXBException,
    // it becomes harder to find out the real problem.
    // So we unwrap them here. But we don't want to unwrap too eagerly, because
    // that could throw away some meaningful exception information.
    Throwable ne = e.getNestedException();
    if(ne instanceof JAXBException) {
        return (JAXBException)ne;
    }
    if(ne instanceof SAXException) {
        return new UnmarshalException(ne);
    }
    return new UnmarshalException(e);
}
 
Example 19
Project: lookaside_java-1.8.0-openjdk   File: AbstractUnmarshallerImpl.java   View source code 6 votes vote down vote up
/**
 * Creates an UnmarshalException from a SAXException.
 *
 * This is an utility method provided for the derived classes.
 *
 * <p>
 * When a provider-implemented ContentHandler wants to throw a
 * JAXBException, it needs to wrap the exception by a SAXException.
 * If the unmarshaller implementation blindly wrap SAXException
 * by JAXBException, such an exception will be a JAXBException
 * wrapped by a SAXException wrapped by another JAXBException.
 * This is silly.
 *
 * <p>
 * This method checks the nested exception of SAXException
 * and reduce those excessive wrapping.
 *
 * @return the resulting UnmarshalException
 */
protected UnmarshalException createUnmarshalException( SAXException e ) {
    // check the nested exception to see if it's an UnmarshalException
    Exception nested = e.getException();
    if(nested instanceof UnmarshalException)
        return (UnmarshalException)nested;

    if(nested instanceof RuntimeException)
        // typically this is an unexpected exception,
        // just throw it rather than wrap it, so that the full stack
        // trace can be displayed.
        throw (RuntimeException)nested;


    // otherwise simply wrap it
    if(nested!=null)
        return new UnmarshalException(nested);
    else
        return new UnmarshalException(e);
}
 
Example 20
Project: kc-rice   File: QualificationListAdapter.java   View source code 6 votes vote down vote up
/**
 * @see javax.xml.bind.annotation.adapters.XmlAdapter#unmarshal(java.lang.Object)
 */
@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;
}
 
Example 21
Project: kc-rice   File: PermissionDetailListAdapter.java   View source code 6 votes vote down vote up
/**
 * @see javax.xml.bind.annotation.adapters.XmlAdapter#unmarshal(java.lang.Object)
 */
@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;
}
 
Example 22
Project: kc-rice   File: RolesXmlDTO.java   View source code 6 votes vote down vote up
/**
 * @see org.kuali.rice.core.util.jaxb.RiceXmlListAdditionListener#newItemAdded(java.lang.Object)
 */
public void newItemAdded(RoleXmlDTO item) {
    // Persist the role if it has not already been persisted yet.
    if (!item.isAlreadyPersisted()) {
        try {
            RoleXmlUtil.validateAndPersistNewRole(item);
        } catch (UnmarshalException e) {
            throw new RuntimeException(e);
        }
    }
    
    // If a "roleMembers" element was present, remove any existing roles that do not match the new ones.
    Set<String> existingRoleMemberIds = item.getExistingRoleMemberIds();
    if (existingRoleMemberIds != null) {
        RoleXmlUtil.removeRoleMembers(item.getRoleId(), existingRoleMemberIds);
    }
    item.setExistingRoleMemberIds(null);
}
 
Example 23
Project: kc-rice   File: RoleXmlUtil.java   View source code 6 votes vote down vote up
/**
 * Performs the necessary validation on the new role, then saves it.
 * 
 * @param newRole The role to persist.
 * @return The ID of the persisted role.
 * @throws IllegalArgumentException if newRole is null.
 * @throws UnmarshalException if newRole contains invalid data.
 */
static String validateAndPersistNewRole(RoleXmlDTO newRole) throws UnmarshalException {
    if (newRole == null) {
        throw new IllegalArgumentException("Cannot persist a null role");
    }
    
    // Validate the role and (if applicable) retrieve the ID from an existing matching role.
    validateAndPrepareRole(newRole);

    Role.Builder builder = Role.Builder.create();
    builder.setActive(newRole.getActive());
    builder.setDescription(newRole.getRoleDescription());
    builder.setId(newRole.getRoleId());
    builder.setKimTypeId(newRole.getKimTypeId());
    builder.setName(newRole.getRoleName());
    builder.setNamespaceCode(newRole.getNamespaceCode());

    //save the role
    Role role = KimApiServiceLocator.getRoleService().createRole(builder.build());

    // Set a flag on the role to indicate that it has now been persisted so that the unmarshalling process will not save this role more than once.
    newRole.setAlreadyPersisted(true);
    
    return role.getId();
}
 
Example 24
Project: kc-rice   File: RoleXmlUtil.java   View source code 6 votes vote down vote up
/**
 * 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.
 */
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);
    }
}
 
Example 25
Project: kc-rice   File: PermissionXmlUtil.java   View source code 6 votes vote down vote up
/**
 * Validates a new permission and then saves it.
 * 
 * @param newPermission
 * @throws IllegalArgumentException if newPermission is null.
 * @throws UnmarshalException if newPermission contains invalid data.
 */
static void validateAndPersistNewPermission(PermissionXmlDTO newPermission) throws UnmarshalException {
    if (newPermission == null) {
        throw new IllegalArgumentException("Cannot persist a null permission");
    }
    
    // Validate the new permission.
    validatePermission(newPermission);
    
    // Save the permission.
    Permission.Builder builder = Permission.Builder.create(newPermission.getNamespaceCode(), newPermission.getPermissionName());
    builder.setDescription(newPermission.getPermissionDescription());
    builder.setActive(newPermission.getActive().booleanValue());
    builder.setAttributes(newPermission.getPermissionDetails());
    
    KimApiServiceLocator.getPermissionService().createPermission(builder.build());
}
 
Example 26
Project: kc-rice   File: PermissionXmlUtil.java   View source code 6 votes vote down vote up
/**
 * Validates a permission to ensure that the required fields have been filled.
 * 
 * @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());
    }
}
 
Example 27
Project: kc-rice   File: NameAndNamespacePairValidatingAdapter.java   View source code 6 votes vote down vote up
/**
 * @see javax.xml.bind.annotation.adapters.XmlAdapter#unmarshal(java.lang.Object)
 */
@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;
}
 
Example 28
Project: infobip-open-jdk-8   File: UnmarshallingContext.java   View source code 6 votes vote down vote up
/**
 * Reports an error to the user, and asks if s/he wants
 * to recover. If the canRecover flag is false, regardless
 * of the client instruction, an exception will be thrown.
 *
 * Only if the flag is true and the user wants to recover from an error,
 * the method returns normally.
 *
 * The thrown exception will be catched by the unmarshaller.
 */
public void handleEvent(ValidationEvent event, boolean canRecover ) throws SAXException {
    ValidationEventHandler eventHandler = parent.getEventHandler();

    boolean recover = eventHandler.handleEvent(event);

    // if the handler says "abort", we will not return the object
    // from the unmarshaller.getResult()
    if(!recover)    aborted = true;

    if( !canRecover || !recover )
        throw new SAXParseException2( event.getMessage(), locator,
            new UnmarshalException(
                event.getMessage(),
                event.getLinkedException() ) );
}
 
Example 29
Project: infobip-open-jdk-8   File: UnmarshallerImpl.java   View source code 6 votes vote down vote up
private static JAXBException handleStreamException(XMLStreamException e) {
    // StAXStreamConnector wraps SAXException to XMLStreamException.
    // XMLStreamException doesn't print its nested stack trace when it prints
    // its stack trace, so if we wrap XMLStreamException in JAXBException,
    // it becomes harder to find out the real problem.
    // So we unwrap them here. But we don't want to unwrap too eagerly, because
    // that could throw away some meaningful exception information.
    Throwable ne = e.getNestedException();
    if(ne instanceof JAXBException) {
        return (JAXBException)ne;
    }
    if(ne instanceof SAXException) {
        return new UnmarshalException(ne);
    }
    return new UnmarshalException(e);
}
 
Example 30
Project: infobip-open-jdk-8   File: AbstractUnmarshallerImpl.java   View source code 6 votes vote down vote up
/**
 * Creates an UnmarshalException from a SAXException.
 *
 * This is an utility method provided for the derived classes.
 *
 * <p>
 * When a provider-implemented ContentHandler wants to throw a
 * JAXBException, it needs to wrap the exception by a SAXException.
 * If the unmarshaller implementation blindly wrap SAXException
 * by JAXBException, such an exception will be a JAXBException
 * wrapped by a SAXException wrapped by another JAXBException.
 * This is silly.
 *
 * <p>
 * This method checks the nested exception of SAXException
 * and reduce those excessive wrapping.
 *
 * @return the resulting UnmarshalException
 */
protected UnmarshalException createUnmarshalException( SAXException e ) {
    // check the nested exception to see if it's an UnmarshalException
    Exception nested = e.getException();
    if(nested instanceof UnmarshalException)
        return (UnmarshalException)nested;

    if(nested instanceof RuntimeException)
        // typically this is an unexpected exception,
        // just throw it rather than wrap it, so that the full stack
        // trace can be displayed.
        throw (RuntimeException)nested;


    // otherwise simply wrap it
    if(nested!=null)
        return new UnmarshalException(nested);
    else
        return new UnmarshalException(e);
}
 
Example 31
Project: cxf-plus   File: UnmarshallingContext.java   View source code 6 votes vote down vote up
/**
 * Reports an error to the user, and asks if s/he wants
 * to recover. If the canRecover flag is false, regardless
 * of the client instruction, an exception will be thrown.
 *
 * Only if the flag is true and the user wants to recover from an error,
 * the method returns normally.
 *
 * The thrown exception will be catched by the unmarshaller.
 */
public void handleEvent(ValidationEvent event, boolean canRecover ) throws SAXException {
    ValidationEventHandler eventHandler = parent.getEventHandler();

    boolean recover = eventHandler.handleEvent(event);

    // if the handler says "abort", we will not return the object
    // from the unmarshaller.getResult()
    if(!recover)    aborted = true;

    if( !canRecover || !recover )
        throw new SAXParseException2( event.getMessage(), locator,
            new UnmarshalException(
                event.getMessage(),
                event.getLinkedException() ) );
}
 
Example 32
Project: modules   File: CSDController.java   View source code 6 votes vote down vote up
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public String handleException(Exception e) throws IOException {
    String message = e.getMessage();
    LOGGER.error(message, e);
    if (e.getCause() != null && e.getCause() instanceof UnmarshalException) {
        UnmarshalException cause = (UnmarshalException) e.getCause();
        if (cause.getLinkedException() != null && cause.getLinkedException() instanceof SAXParseException) {
            SAXParseException parseException = (SAXParseException) cause.getLinkedException();
            message += " -" + StringUtils.substringAfter(parseException.getMessage(), ":") +
                    " (line " + parseException.getLineNumber() + ")";
        }
    }
    return message;
}
 
Example 33
Project: hbase   File: TestXmlParsing.java   View source code 6 votes vote down vote up
@Test
public void testFailOnExternalEntities() throws Exception {
  final String externalEntitiesXml =
      "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
      + " <!DOCTYPE foo [ <!ENTITY xxe SYSTEM \"/tmp/foo\"> ] >"
      + " <ClusterVersion>&xee;</ClusterVersion>";
  Client client = mock(Client.class);
  RemoteAdmin admin = new RemoteAdmin(client, HBaseConfiguration.create(), null);
  Response resp = new Response(200, null, Bytes.toBytes(externalEntitiesXml));

  when(client.get("/version/cluster", Constants.MIMETYPE_XML)).thenReturn(resp);

  try {
    admin.getClusterVersion();
    fail("Expected getClusterVersion() to throw an exception");
  } catch (IOException e) {
    assertEquals("Cause of exception ought to be a failure to parse the stream due to our " +
        "invalid external entity. Make sure this isn't just a false positive due to " +
        "implementation. see HBASE-19020.", UnmarshalException.class, e.getCause().getClass());
    final String exceptionText = StringUtils.stringifyException(e);
    final String expectedText = "\"xee\"";
    LOG.debug("exception text: '" + exceptionText + "'", e);
    assertTrue("Exception does not contain expected text", exceptionText.contains(expectedText));
  }
}
 
Example 34
Project: OLE-INST   File: QualificationListAdapter.java   View source code 6 votes vote down vote up
/**
 * @see javax.xml.bind.annotation.adapters.XmlAdapter#unmarshal(java.lang.Object)
 */
@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;
}
 
Example 35
Project: OLE-INST   File: PermissionDetailListAdapter.java   View source code 6 votes vote down vote up
/**
 * @see javax.xml.bind.annotation.adapters.XmlAdapter#unmarshal(java.lang.Object)
 */
@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;
}
 
Example 36
Project: rice   File: RoleXmlUtil.java   View source code 6 votes vote down vote up
/**
 * 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.
 */
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);
    }
}
 
Example 37
Project: OLE-INST   File: RoleXmlUtil.java   View source code 6 votes vote down vote up
/**
 * Performs the necessary validation on the new role, then saves it.
 * 
 * @param newRole The role to persist.
 * @return The ID of the persisted role.
 * @throws IllegalArgumentException if newRole is null.
 * @throws UnmarshalException if newRole contains invalid data.
 */
static String validateAndPersistNewRole(RoleXmlDTO newRole) throws UnmarshalException {
    if (newRole == null) {
        throw new IllegalArgumentException("Cannot persist a null role");
    }
    
    // Validate the role and (if applicable) retrieve the ID from an existing matching role.
    validateAndPrepareRole(newRole);

    Role.Builder builder = Role.Builder.create();
    builder.setActive(newRole.getActive());
    builder.setDescription(newRole.getRoleDescription());
    builder.setId(newRole.getRoleId());
    builder.setKimTypeId(newRole.getKimTypeId());
    builder.setName(newRole.getRoleName());
    builder.setNamespaceCode(newRole.getNamespaceCode());

    //save the role
    Role role = KimApiServiceLocator.getRoleService().createRole(builder.build());

    // Set a flag on the role to indicate that it has now been persisted so that the unmarshalling process will not save this role more than once.
    newRole.setAlreadyPersisted(true);
    
    return role.getId();
}
 
Example 38
Project: OLE-INST   File: RoleXmlUtil.java   View source code 6 votes vote down vote up
/**
 * 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.
 */
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);
    }
}
 
Example 39
Project: rice   File: PermissionXmlUtil.java   View source code 6 votes vote down vote up
/**
 * Validates a new permission and then saves it.
 * 
 * @param newPermission
 * @throws IllegalArgumentException if newPermission is null.
 * @throws UnmarshalException if newPermission contains invalid data.
 */
static void validateAndPersistNewPermission(PermissionXmlDTO newPermission) throws UnmarshalException {
    if (newPermission == null) {
        throw new IllegalArgumentException("Cannot persist a null permission");
    }
    
    // Validate the new permission.
    validatePermission(newPermission);
    
    // Save the permission.
    Permission.Builder builder = Permission.Builder.create(newPermission.getNamespaceCode(), newPermission.getPermissionName());
    builder.setDescription(newPermission.getPermissionDescription());
    builder.setActive(newPermission.getActive().booleanValue());
    builder.setAttributes(newPermission.getPermissionDetails());
    
    KimApiServiceLocator.getPermissionService().createPermission(builder.build());
}
 
Example 40
Project: rice   File: PermissionXmlUtil.java   View source code 6 votes vote down vote up
/**
 * Validates a permission to ensure that the required fields have been filled.
 * 
 * @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());
    }
}