Example usage for javax.xml.bind JAXBElement JAXBElement

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

Introduction

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

Prototype

public JAXBElement(QName name, Class<T> declaredType, T value) 

Source Link

Document

Construct an xml element instance.

Usage

From source file:org.atricore.idbus.kernel.main.mediation.camel.AbstractCamelProducer.java

@Deprecated
protected String marshal(Class endpointInterface, Object msg, String msgQName, String msgLocalName,
        String[] userPackages) throws Exception {
    WebService ws = getWebServiceAnnotation(endpointInterface);
    JAXBContext jaxbContext = createJAXBContext(endpointInterface, userPackages);
    JAXBElement jaxbRequest = new JAXBElement(new QName(msgQName, msgLocalName), msg.getClass(), msg);
    StringWriter writer = new StringWriter();
    jaxbContext.createMarshaller().marshal(jaxbRequest, writer);

    return writer.toString();
}

From source file:org.atricore.idbus.kernel.main.mediation.camel.AbstractCamelProducer.java

@Deprecated
protected String marshal(Object msg, String msgQName, String msgLocalName, String[] userPackages)
        throws Exception {
    JAXBContext jaxbContext = createJAXBContext(userPackages);
    JAXBElement jaxbRequest = new JAXBElement(new QName(msgQName, msgLocalName), msg.getClass(), msg);
    StringWriter writer = new StringWriter();
    jaxbContext.createMarshaller().marshal(jaxbRequest, writer);

    return writer.toString();
}

From source file:org.atricore.idbus.kernel.main.mediation.camel.component.binding.AbstractMediationHttpBinding.java

protected String marshal(Object obj, String msgQName, String msgLocalName, String[] userPackages)
        throws Exception {

    JAXBContext jaxbContext = createJAXBContext(obj, userPackages);
    JAXBElement jaxbRequest = new JAXBElement(new QName(msgQName, msgLocalName), obj.getClass(), obj);
    Writer writer = new StringWriter();

    // Support XMLDsig
    jaxbContext.createMarshaller().marshal(jaxbRequest, writer);

    return writer.toString();
}

From source file:org.codehaus.enunciate.modules.xfire.EnunciatedJAXWSOperationBinding.java

public void writeMessage(OutMessage message, XMLStreamWriter writer, MessageContext context) throws XFireFault {
    if (this.responseInfo == null) {
        throw new XFireFault("Unable to write message: no response info was found!", XFireFault.SENDER);
    }//  w w w. ja va2s  .  c o m

    Class beanClass = this.responseInfo.getBeanClass();
    Object[] params = (Object[]) message.getBody();
    Object bean;
    if (this.responseInfo.isBare()) {
        //bare response.  we don't need to wrap it up.
        bean = new JAXBElement(this.responseInfo.getMessageInfo().getName(), this.responseInfo.getBeanClass(),
                params[0]);
    } else {
        try {
            bean = beanClass.newInstance();
        } catch (Exception e) {
            throw new XFireFault("Problem instantiating response wrapper " + beanClass.getName() + ".", e,
                    XFireFault.RECEIVER);
        }

        PropertyDescriptor[] properties = this.responseInfo.getPropertyOrder();
        if (properties.length > 0) { //no properties implies a void method...
            if (properties.length != params.length) {
                throw new XFireFault("There are " + params.length + " parameters to the out message but "
                        + properties.length + " properties on " + beanClass.getName(), XFireFault.RECEIVER);
            }

            for (int i = 0; i < properties.length; i++) {
                PropertyDescriptor descriptor = properties[i];
                try {
                    descriptor.getWriteMethod().invoke(bean, params[i]);
                } catch (IllegalAccessException e) {
                    throw new XFireFault("Problem with property " + descriptor.getName() + " on "
                            + beanClass.getName() + ".", e, XFireFault.RECEIVER);
                } catch (InvocationTargetException e) {
                    throw new XFireFault("Problem with property " + descriptor.getName() + " on "
                            + beanClass.getName() + ".", e, XFireFault.RECEIVER);
                }
            }
        }
    }

    try {
        Marshaller marshaller = this.jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        marshaller.setAttachmentMarshaller(new AttachmentMarshaller(context));
        marshaller.marshal(bean, writer);
    } catch (JAXBException e) {
        throw new XFireRuntimeException("Unable to marshal type.", e);
    }
}

From source file:org.codice.ddf.security.handler.anonymous.AnonymousHandler.java

/**
 * Returns the UsernameToken marshalled as a String so that it can be attached to the
 * {@link org.codice.ddf.security.handler.api.HandlerResult} object.
 *
 * @param usernameTokenType/* w w  w.  j av a2  s  .c o  m*/
 * @return String
 */
private synchronized String getUsernameTokenElement(UsernameTokenType usernameTokenType) {
    Writer writer = new StringWriter();
    Marshaller marshaller = null;
    if (utContext != null) {
        try {
            marshaller = utContext.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        } catch (JAXBException e) {
            LOGGER.error("Exception while creating UsernameToken marshaller.", e);
        }

        JAXBElement<UsernameTokenType> usernameTokenElement = new JAXBElement<UsernameTokenType>(
                new QName("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
                        "UsernameToken"),
                UsernameTokenType.class, usernameTokenType);

        if (marshaller != null) {
            try {
                marshaller.marshal(usernameTokenElement, writer);
            } catch (JAXBException e) {
                LOGGER.error("Exception while writing username token.", e);
            }
        }
    }

    return writer.toString();
}

From source file:org.codice.ddf.security.handler.anonymous.AnonymousHandler.java

/**
 * This method uses the data passed in the HttpServletRequest to generate
 * and return UsernameTokenType./*from   w w w . j  a  v  a  2s.  c  o  m*/
 *
 * @param request http request to obtain attributes from and to pass into any local filter chains required
 * @return UsernameTokenType
 */
private UsernameTokenType setAuthenticationInfo(HttpServletRequest request) {
    HttpServletRequest httpRequest = request;

    String username = "guest";
    String password = "guest";

    /**
     * Parse the header data and extract the username and password.
     *
     * Change the username and password if request contains values.
     */
    String header = httpRequest.getHeader("Authorization");
    if (!StringUtils.isEmpty(header)) {
        String headerData[] = header.split(" ");
        if (headerData.length == 2) {
            String decodedHeader = new String(Base64.decodeBase64(headerData[1].getBytes()));
            String decodedHeaderData[] = decodedHeader.split(":");
            if (decodedHeaderData.length == 2) {
                username = decodedHeaderData[0];
                password = decodedHeaderData[1];
            }
        }
    }

    /**
     * Use the collected information to set the username and password and
     * generate UsernameTokenType to return.
     */
    UsernameTokenType usernameTokenType = new UsernameTokenType();
    AttributedString user = new AttributedString();
    user.setValue(username);
    usernameTokenType.setUsername(user);
    PasswordString passwordString = new PasswordString();
    passwordString.setValue(password);
    passwordString.setType(WSConstants.PASSWORD_TEXT);
    JAXBElement<PasswordString> passwordType = new JAXBElement<PasswordString>(QNameConstants.PASSWORD,
            PasswordString.class, passwordString);
    usernameTokenType.getAny().add(passwordType);

    return usernameTokenType;
}

From source file:org.codice.ddf.security.handler.api.BSTAuthenticationToken.java

/**
 * Creates a binary security token based on the provided credential.
 *//*  w  w w  .  jav a  2  s.c o m*/
private synchronized String getBinarySecurityToken(String credential) {
    Writer writer = new StringWriter();

    Marshaller marshaller = null;

    BinarySecurityTokenType binarySecurityTokenType = createBinarySecurityTokenType(credential);
    JAXBElement<BinarySecurityTokenType> binarySecurityTokenElement = new JAXBElement<BinarySecurityTokenType>(
            new QName("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
                    "BinarySecurityToken"),
            BinarySecurityTokenType.class, binarySecurityTokenType);

    if (BINARY_TOKEN_CONTEXT != null) {
        try {
            marshaller = BINARY_TOKEN_CONTEXT.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        } catch (JAXBException e) {
            LOGGER.error("Exception while creating UsernameToken marshaller.", e);
        }

        if (marshaller != null) {
            try {
                marshaller.marshal(binarySecurityTokenElement, writer);
            } catch (JAXBException e) {
                LOGGER.error("Exception while writing username token.", e);
            }
        }
    }

    String binarySecurityToken = writer.toString();

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Binary Security Token: " + binarySecurityToken);
    }

    return binarySecurityToken;
}

From source file:org.codice.ddf.spatial.ogc.csw.catalog.common.GetRecordsRequest.java

/**
 * Convert the KVP values into a GetRecordsType, validates format of fields and enumeration
 * constraints required to meet the schema requirements of the GetRecordsType. No further
 * validation is done at this point//  w ww . ja  v a2 s  .  c o m
 *
 * @return GetRecordsType representation of this key-value representation
 * @throws CswException
 *             An exception when some field cannot be converted to the equivalent GetRecordsType
 *             value
 */
public GetRecordsType get202RecordsType() throws CswException {
    GetRecordsType getRecords = new GetRecordsType();

    getRecords.setOutputSchema(getOutputSchema());
    getRecords.setRequestId(getRequestId());

    if (getMaxRecords() != null) {
        getRecords.setMaxRecords(getMaxRecords());
    }
    if (getStartPosition() != null) {
        getRecords.setStartPosition(getStartPosition());
    }
    if (getOutputFormat() != null) {
        getRecords.setOutputFormat(getOutputFormat());
    }
    if (getResponseHandler() != null) {
        getRecords.setResponseHandler(Arrays.asList(getResponseHandler()));
    }
    if (getResultType() != null) {
        try {
            getRecords.setResultType(ResultType.fromValue(getResultType()));
        } catch (IllegalArgumentException iae) {
            LOGGER.warn("Failed to find \"{}\" as a valid ResultType, Exception {}", getResultType(), iae);
            throw new CswException(
                    "A CSW getRecords request ResultType must be \"hits\", \"results\", or \"validate\"");
        }
    }
    if (getDistributedSearch() != null && getDistributedSearch()) {
        DistributedSearchType disSearch = new DistributedSearchType();
        disSearch.setHopCount(getHopCount());
        getRecords.setDistributedSearch(disSearch);
    }

    QueryType query = new QueryType();

    Map<String, String> namespaces = parseNamespaces(getNamespace());
    List<QName> typeNames = typeStringToQNames(getTypeNames(), namespaces);
    query.setTypeNames(typeNames);

    if (getElementName() != null && getElementSetName() != null) {
        LOGGER.warn(
                "CSW getRecords request received with mutually exclusive ElementName and SetElementName set");
        throw new CswException(
                "A CSW getRecords request can only have an \"ElementName\" or an \"ElementSetName\"");
    }

    if (getElementName() != null) {
        query.setElementName(typeStringToQNames(getElementName(), namespaces));
    }

    if (getElementSetName() != null) {
        try {
            ElementSetNameType eleSetName = new ElementSetNameType();
            eleSetName.setTypeNames(typeNames);
            eleSetName.setValue(ElementSetType.fromValue(getElementSetName()));
            query.setElementSetName(eleSetName);
        } catch (IllegalArgumentException iae) {
            LOGGER.warn("Failed to find \"{}\" as a valid elementSetType, Exception {}", getElementSetName(),
                    iae);
            throw new CswException(
                    "A CSW getRecords request ElementSetType must be \"brief\", \"summary\", or \"full\"");
        }

    }

    if (getSortBy() != null) {
        SortByType sort = new SortByType();

        List<SortPropertyType> sortProps = new LinkedList<SortPropertyType>();

        String[] sortOptions = getSortBy().split(",");

        for (String sortOption : sortOptions) {
            if (sortOption.lastIndexOf(':') < 1) {
                throw new CswException("Invalid Sort Order format: " + getSortBy());
            }
            SortPropertyType sortProperty = new SortPropertyType();
            PropertyNameType propertyName = new PropertyNameType();

            String propName = StringUtils.substringBeforeLast(sortOption, ":");
            String direction = StringUtils.substringAfterLast(sortOption, ":");
            propertyName.setContent(Arrays.asList((Object) propName));
            SortOrderType sortOrder;

            if (direction.equals("A")) {
                sortOrder = SortOrderType.ASC;
            } else if (direction.equals("D")) {
                sortOrder = SortOrderType.DESC;
            } else {
                throw new CswException("Invalid Sort Order format: " + getSortBy());
            }

            sortProperty.setPropertyName(propertyName);
            sortProperty.setSortOrder(sortOrder);

            sortProps.add(sortProperty);
        }

        sort.setSortProperty(sortProps);

        query.setElementName(typeStringToQNames(getElementName(), namespaces));
        query.setSortBy(sort);
    }

    if (getConstraint() != null) {
        QueryConstraintType queryConstraint = new QueryConstraintType();

        if (getConstraintLanguage().equalsIgnoreCase(CswConstants.CONSTRAINT_LANGUAGE_CQL)) {
            queryConstraint.setCqlText(getConstraint());
        } else if (getConstraintLanguage().equalsIgnoreCase(CswConstants.CONSTRAINT_LANGUAGE_FILTER)) {
            try {
                XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
                xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
                xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
                XMLStreamReader xmlStreamReader = xmlInputFactory
                        .createXMLStreamReader(new StringReader(constraint));

                Unmarshaller unmarshaller = JAX_BCONTEXT.createUnmarshaller();
                @SuppressWarnings("unchecked")
                JAXBElement<FilterType> jaxbFilter = (JAXBElement<FilterType>) unmarshaller
                        .unmarshal(xmlStreamReader);
                queryConstraint.setFilter(jaxbFilter.getValue());
            } catch (JAXBException e) {
                throw new CswException("JAXBException parsing OGC Filter:" + getConstraint(), e);
            } catch (Exception e) {
                throw new CswException("Unable to parse OGC Filter:" + getConstraint(), e);
            }
        } else {
            throw new CswException("Invalid Constraint Language defined: " + getConstraintLanguage());
        }
        query.setConstraint(queryConstraint);
    }

    JAXBElement<QueryType> jaxbQuery = new JAXBElement<QueryType>(new QName(CswConstants.CSW_OUTPUT_SCHEMA),
            QueryType.class, query);

    getRecords.setAbstractQuery(jaxbQuery);

    return getRecords;
}

From source file:org.codice.ddf.spatial.ogc.csw.catalog.common.source.AbstractCswSource.java

private String getGetRecordsTypeAsXml(GetRecordsType getRecordsType) {
    Writer writer = new StringWriter();
    try {//from   w w  w  .  j  a v  a2  s.co m
        Marshaller marshaller = JAXB_CONTEXT.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        JAXBElement<GetRecordsType> jaxbElement = new JAXBElement<GetRecordsType>(
                new QName(CswConstants.CSW_OUTPUT_SCHEMA, CswConstants.GET_RECORDS), GetRecordsType.class,
                getRecordsType);
        marshaller.marshal(jaxbElement, writer);
    } catch (JAXBException e) {
        LOGGER.error("{}: Unable to marshall {} to XML.", cswSourceConfiguration.getId(), GetRecordsType.class,
                e);
    }
    return writer.toString();
}

From source file:org.codice.ddf.spatial.ogc.csw.catalog.common.source.CswFilterDelegateTest.java

private JAXBElement<FilterType> getFilterTypeJaxbElement(FilterType filterType) {
    JAXBElement<FilterType> filterTypeJaxbElement = new JAXBElement<>(
            new QName("http://www.opengis.net/ogc", FILTER_QNAME_LOCAL_PART), FilterType.class, filterType);
    return filterTypeJaxbElement;
}