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.eclipsetrader.internal.brokers.paper.PaperBroker.java

public void save(File file) throws JAXBException, IOException {
    if (file.exists()) {
        file.delete();/*from w  ww  .  ja  v a2s  . c  om*/
    }

    JAXBContext jaxbContext = JAXBContext.newInstance(OrderMonitor[].class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setEventHandler(new ValidationEventHandler() {

        @Override
        public boolean handleEvent(ValidationEvent event) {
            Status status = new Status(IStatus.WARNING, Activator.PLUGIN_ID, 0,
                    "Error validating XML: " + event.getMessage(), null); //$NON-NLS-1$
            Activator.log(status);
            return true;
        }
    });
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    marshaller.setProperty(Marshaller.JAXB_ENCODING, System.getProperty("file.encoding")); //$NON-NLS-1$

    OrderMonitor[] elements = pendingOrders.toArray(new OrderMonitor[pendingOrders.size()]);
    JAXBElement<OrderMonitor[]> element = new JAXBElement<OrderMonitor[]>(new QName("list"),
            OrderMonitor[].class, elements);
    marshaller.marshal(element, new FileWriter(file));
}

From source file:org.eclipsetrader.yahoo.internal.news.NewsProvider.java

protected void save() throws JAXBException, IOException {
    File file = YahooActivator.getDefault().getStateLocation().append(HEADLINES_FILE).toFile();
    if (file.exists()) {
        file.delete();/*from w  w  w  .ja va  2s .c  om*/
    }

    JAXBContext jaxbContext = JAXBContext.newInstance(HeadLine[].class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setEventHandler(new ValidationEventHandler() {

        @Override
        public boolean handleEvent(ValidationEvent event) {
            Status status = new Status(IStatus.WARNING, YahooActivator.PLUGIN_ID, 0,
                    "Error validating XML: " + event.getMessage(), null); //$NON-NLS-1$
            YahooActivator.getDefault().getLog().log(status);
            return true;
        }
    });
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    marshaller.setProperty(Marshaller.JAXB_ENCODING, System.getProperty("file.encoding")); //$NON-NLS-1$

    JAXBElement<HeadLine[]> element = new JAXBElement<HeadLine[]>(new QName("list"), HeadLine[].class,
            oldItems.toArray(new HeadLine[oldItems.size()]));
    marshaller.marshal(element, new FileWriter(file));
}

From source file:org.eclipsetrader.yahoojapan.internal.news.NewsProvider.java

protected void save() throws JAXBException, IOException {
    File file = YahooJapanActivator.getDefault().getStateLocation().append(HEADLINES_FILE).toFile();
    if (file.exists()) {
        file.delete();//  ww w.j  a va  2  s .co m
    }

    JAXBContext jaxbContext = JAXBContext.newInstance(HeadLine[].class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setEventHandler(new ValidationEventHandler() {

        @Override
        public boolean handleEvent(ValidationEvent event) {
            Status status = new Status(IStatus.WARNING, YahooJapanActivator.PLUGIN_ID, 0,
                    "Error validating XML: " + event.getMessage(), null); //$NON-NLS-1$
            YahooJapanActivator.getDefault().getLog().log(status);
            return true;
        }
    });
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    marshaller.setProperty(Marshaller.JAXB_ENCODING, System.getProperty("file.encoding")); //$NON-NLS-1$

    JAXBElement<HeadLine[]> element = new JAXBElement<HeadLine[]>(new QName("list"), HeadLine[].class,
            oldItems.toArray(new HeadLine[oldItems.size()]));
    marshaller.marshal(element, new FileWriter(file));
}

From source file:org.emergya.backtrackTSP.DistanceMatrix.java

@SuppressWarnings("restriction")
private WayPointType getWayPoint(Point position) {
    WayPointType point = new WayPointType();
    point.setStop(Boolean.TRUE);//from w  w w .  ja v  a 2s. c  om

    PositionType postype = new PositionType();
    PointType pointtype = new PointType();
    DirectPositionType directPosition = new DirectPositionType();

    directPosition.setSrsName("EPSG:" + position.getSRID());
    directPosition.getValue().add(position.getX());
    directPosition.getValue().add(position.getY());

    pointtype.setPos(directPosition);
    postype.setPoint(pointtype);
    JAXBElement<? extends AbstractLocationType> value = new JAXBElement<PositionType>(
            new QName("http://www.opengis.net/gml", "pos", "gml"), PositionType.class, postype);
    point.setLocation(value);

    return point;
}

From source file:org.energy_home.jemma.javagal.rest.util.Util.java

/**
 * Marshal class.//from   ww  w.j  a  v a2  s .c o m
 * 
 * @param o
 *            the object to marshall.
 * 
 * @return the marshalled representation.
 */
@SuppressWarnings("unchecked")
synchronized public static <T> String marshal(Object o) {

    StringWriter stringWriter = new StringWriter();
    try {
        JAXBContext jc = JAXBContext.newInstance(o.getClass());
        Marshaller m = jc.createMarshaller();
        QName _qname = new QName("http://www.zigbee.org/GWGRESTSchema", o.getClass().getSimpleName());
        JAXBElement<T> je = new JAXBElement<T>(_qname, (Class<T>) o.getClass(), ((T) o));
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.FALSE);
        m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        m.setProperty("com.sun.xml.internal.bind.namespacePrefixMapper", new NamespacePrefixMapperImpl());
        m.setProperty("com.sun.xml.internal.bind.xmlDeclaration", Boolean.FALSE);
        m.marshal(je, stringWriter);
        String _tores = stringWriter.toString();

        return _tores;
    } catch (JAXBException e) {
        logger.error("Exception on marshal : " + e.getMessage());
        return EMPTY_STRING;
    }
}

From source file:org.fcrepo.oai.service.OAIProviderService.java

public JAXBElement<OAIPMHtype> getRecord(final Session session, final UriInfo uriInfo, final String identifier,
        final String metadataPrefix) throws RepositoryException {
    final HttpIdentifierTranslator translator = new HttpIdentifierTranslator(session, FedoraNodes.class,
            uriInfo);// ww w  .  j  av  a 2 s.  c o  m
    final MetadataFormat format = metadataFormats.get(metadataPrefix);
    if (format == null) {
        return error(VerbType.GET_RECORD, identifier, metadataPrefix,
                OAIPMHerrorcodeType.CANNOT_DISSEMINATE_FORMAT, "The metadata format is not available");
    }
    final Resource subject = translator.getSubject("/" + identifier);
    final String path = translator.getPathFromSubject(subject);
    if (!this.objectService.exists(session, path)) {
        return error(VerbType.GET_RECORD, identifier, metadataPrefix, OAIPMHerrorcodeType.ID_DOES_NOT_EXIST,
                "The requested identifier does not exist");
    }
    final FedoraObject obj = this.objectService.getObject(session, path);
    final Model model = obj.getPropertiesDataset(translator).getDefaultModel();
    final StmtIterator it = model.listStatements(subject, model.createProperty(format.getPropertyName()),
            (RDFNode) null);
    if (!it.hasNext()) {
        return error(VerbType.GET_RECORD, identifier, metadataPrefix, OAIPMHerrorcodeType.NO_RECORDS_MATCH,
                "The record does not have a oai meta data object associated");
    }

    final String dsPath = translator.getPathFromSubject(it.next().getObject().asResource());
    if (!this.datastreamService.exists(session, dsPath)) {
        return error(VerbType.GET_RECORD, identifier, metadataPrefix, OAIPMHerrorcodeType.BAD_ARGUMENT,
                "The referenced datastream for the meta data can not be found");
    }

    final Datastream mdDs = this.datastreamService.getDatastream(session, dsPath);
    final OAIPMHtype oai = oaiFactory.createOAIPMHtype();
    final RequestType req = oaiFactory.createRequestType();
    req.setVerb(VerbType.GET_RECORD);
    req.setValue(uriInfo.getRequestUri().toASCIIString());

    final GetRecordType getRecord = oaiFactory.createGetRecordType();
    final RecordType record = oaiFactory.createRecordType();
    getRecord.setRecord(record);

    final HeaderType header = oaiFactory.createHeaderType();
    header.setIdentifier(identifier);
    header.setDatestamp(dateFormat.print(new Date().getTime()));
    final StmtIterator itSets = model.listStatements(translator.getSubject("/" + identifier),
            model.createProperty(propertyIsPartOfSet), (RDFNode) null);
    if (itSets.hasNext()) {
        header.getSetSpec().add(itSets.next().getObject().asLiteral().getString());
    }
    record.setHeader(header);
    // TODO: add set specs

    final MetadataType md = oaiFactory.createMetadataType();
    try {
        String content = IOUtils.toString(mdDs.getContent());
        md.setAny(new JAXBElement<String>(new QName(format.getPrefix()), String.class, content));
    } catch (IOException e) {
        throw new RepositoryException(e);
    } finally {
        IOUtils.closeQuietly(mdDs.getContent());
    }
    record.setMetadata(md);

    oai.setGetRecord(getRecord);
    return oaiFactory.createOAIPMH(oai);
}

From source file:org.fcrepo.oai.service.OAIProviderService.java

public JAXBElement<OAIPMHtype> listRecords(Session session, UriInfo uriInfo, String metadataPrefix, String from,
        String until, String set, int offset) throws RepositoryException {

    final HttpIdentifierTranslator translator = new HttpIdentifierTranslator(session, FedoraNodes.class,
            uriInfo);/*  w  ww. ja  v  a2  s  .  c  o  m*/

    if (metadataPrefix == null) {
        return error(VerbType.LIST_RECORDS, null, null, OAIPMHerrorcodeType.BAD_ARGUMENT,
                "metadataprefix is invalid");
    }
    final MetadataFormat mdf = metadataFormats.get(metadataPrefix);
    if (mdf == null) {
        return error(VerbType.LIST_RECORDS, null, metadataPrefix, OAIPMHerrorcodeType.CANNOT_DISSEMINATE_FORMAT,
                "Unavailable metadata format");
    }
    DateTime fromDateTime = null;
    DateTime untilDateTime = null;
    try {
        fromDateTime = (from != null && !from.isEmpty()) ? dateFormat.parseDateTime(from) : null;
        untilDateTime = (until != null && !until.isEmpty()) ? dateFormat.parseDateTime(until) : null;
    } catch (IllegalArgumentException e) {
        return error(VerbType.LIST_RECORDS, null, metadataPrefix, OAIPMHerrorcodeType.BAD_ARGUMENT,
                e.getMessage());
    }

    final StringBuilder sparql = new StringBuilder("PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> ")
            .append("SELECT ?sub ?obj WHERE { ").append("?sub <").append(mdf.getPropertyName())
            .append("> ?obj . ");

    final List<String> filters = new ArrayList<>();

    if (fromDateTime != null || untilDateTime != null) {
        sparql.append("?sub <").append(RdfLexicon.LAST_MODIFIED_DATE).append("> ?date . ");
        if (fromDateTime != null) {
            filters.add("?date >='" + from + "'^^xsd:dateTime ");
        }
        if (untilDateTime != null) {
            filters.add("?date <='" + until + "'^^xsd:dateTime ");
        }
    }

    if (set != null && !set.isEmpty()) {
        if (!setsEnabled) {
            return error(VerbType.LIST_RECORDS, null, metadataPrefix, OAIPMHerrorcodeType.NO_SET_HIERARCHY,
                    "Sets are not enabled");
        }
        sparql.append("?sub <").append(propertyIsPartOfSet).append("> ?set . ");
        filters.add("?set = '" + set + "'");
    }

    int filterCount = 0;
    for (String filter : filters) {
        if (filterCount++ == 0) {
            sparql.append("FILTER (");
        }
        sparql.append(filter).append(filterCount == filters.size() ? ")" : " && ");
    }
    sparql.append("}").append(" OFFSET ").append(offset).append(" LIMIT ").append(maxListSize);
    try {
        final JQLConverter jql = new JQLConverter(session, translator, sparql.toString());
        final ResultSet result = jql.execute();
        final OAIPMHtype oai = oaiFactory.createOAIPMHtype();
        final ListRecordsType records = oaiFactory.createListRecordsType();
        if (!result.hasNext()) {
            return error(VerbType.LIST_RECORDS, null, metadataPrefix, OAIPMHerrorcodeType.NO_RECORDS_MATCH,
                    "No record found");
        }
        while (result.hasNext()) {
            // check if the records exists
            final RecordType record = oaiFactory.createRecordType();
            final HeaderType h = oaiFactory.createHeaderType();
            final QuerySolution solution = result.next();
            final Resource subjectUri = solution.get("sub").asResource();
            final Resource oaiRecordUri = solution.get("obj").asResource();
            if (!this.datastreamService.exists(session, translator.getPathFromSubject(oaiRecordUri))) {
                continue;
            }
            h.setIdentifier(subjectUri.getURI());
            final FedoraObject obj = this.objectService.getObject(session,
                    translator.getPathFromSubject(subjectUri));
            h.setDatestamp(dateFormat.print(obj.getLastModifiedDate().getTime()));
            // get set names this object is part of
            final Model objModel = obj.getPropertiesDataset(translator).getDefaultModel();
            final StmtIterator setNames = objModel.listStatements(translator.getSubject(obj.getPath()),
                    objModel.createProperty(propertyIsPartOfSet), (RDFNode) null);
            while (setNames.hasNext()) {
                final FedoraObject setObject = this.objectService.getObject(session,
                        setsRootPath + "/" + setNames.next().getObject().asLiteral().getString());
                final Model setObjectModel = setObject.getPropertiesDataset(translator).getDefaultModel();
                final StmtIterator setSpec = setObjectModel.listStatements(
                        translator.getSubject(setObject.getPath()), objModel.createProperty(propertyHasSetSpec),
                        (RDFNode) null);
                if (setSpec.hasNext()) {
                    h.getSetSpec().add(setSpec.next().getObject().asLiteral().getString());
                }
            }
            // get the metadata record from fcrepo
            final MetadataType md = oaiFactory.createMetadataType();
            final Datastream mdDs = this.datastreamService.getDatastream(session,
                    translator.getPathFromSubject(oaiRecordUri));
            try {
                String content = IOUtils.toString(mdDs.getContent());
                md.setAny(new JAXBElement<String>(new QName(mdf.getPrefix()), String.class, content));
            } catch (IOException e) {
                throw new RepositoryException(e);
            } finally {
                IOUtils.closeQuietly(mdDs.getContent());
            }
            record.setMetadata(md);
            record.setHeader(h);
            records.getRecord().add(record);
        }

        final RequestType req = oaiFactory.createRequestType();
        if (records.getRecord().size() == maxListSize) {
            req.setResumptionToken(encodeResumptionToken(VerbType.LIST_RECORDS.value(), metadataPrefix, from,
                    until, set, offset + maxListSize));
        }
        req.setVerb(VerbType.LIST_RECORDS);
        req.setMetadataPrefix(metadataPrefix);
        oai.setRequest(req);
        oai.setListRecords(records);
        return oaiFactory.createOAIPMH(oai);
    } catch (Exception e) {
        e.printStackTrace();
        throw new RepositoryException(e);
    }
}

From source file:org.gofleet.openLS.util.Utils.java

/**
 * Envelops an {@link AbstractResponseParametersType} response inside the
 * {@link XLSType}//  ww w . j  av  a2s. c om
 * 
 * @param element
 * @return
 * @throws AxisFault
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static JAXBElement<XLSType> envelop(List<List<AbstractResponseParametersType>> params) {
    XLSType xlsType = new XLSType();
    xlsType.setVersion(BigDecimal.ONE);

    ResponseType responseType = new ResponseType();

    for (List<AbstractResponseParametersType> element : params) {
        for (AbstractResponseParametersType e : element) {
            String responseClass = e.getClass().getSimpleName().toString();
            responseClass = responseClass.substring(0, responseClass.length() - 4);

            JAXBElement<? extends AbstractResponseParametersType> body_ = new JAXBElement(
                    new QName("http://www.opengis.net/xls", responseClass, ""), e.getClass(), e);
            responseType.setResponseParameters(body_);
        }
        responseType.setNumberOfResponses(new BigInteger((new Integer(element.size())).toString()));
        responseType.setRequestID("-1");
        responseType.setVersion("0.9");
        xlsType.getBody().add(new JAXBElement(new QName("http://www.opengis.net/xls", "Response"),
                responseType.getClass(), responseType));
    }

    ResponseHeaderType header = new ResponseHeaderType();
    header.setSessionID("none");

    xlsType.setHeader(new JAXBElement<ResponseHeaderType>(
            new QName("http://www.opengis.net/xls", "ResponseHeader"), ResponseHeaderType.class, header));

    JAXBElement<XLSType> res = new JAXBElement<XLSType>(new QName("http://www.opengis.net/xls", "xls"),
            XLSType.class, xlsType);

    return res;
}

From source file:org.jasig.portlet.attachment.util.ImportExport.java

private void export(String directoryName) {
    boolean operationSucceeded = true;
    File dir = checkIfDirExists(directoryName, true);

    int offset = 0;
    List<Attachment> attachments;
    do {//from w  w w  . jav  a 2  s .co  m
        attachments = attachmentService.findAll(offset, batchFetchSize);
        if (attachments.size() > 0) {
            try {
                JAXBContext jc = JAXBContext.newInstance(Attachment.class);
                Marshaller marshaller = jc.createMarshaller();
                marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                for (Attachment attachment : attachments) {
                    File entityFile = new File(dir, attachment.getGuid() + FILENAME_SUFFIX);

                    if (attachment.getData() == null) {
                        log.error(
                                "File {}, guid {} has no data.  This typically occurs if you are running export"
                                        + " against a SimpleContentPortlet database prior to v2.0.0. You probably want"
                                        + " to delete this file before running import and instead run export using"
                                        + " a version prior to 2.0.0",
                                entityFile.getAbsolutePath(), attachment.getGuid());
                        operationSucceeded = false;
                    } else {
                        log.info("Creating file {}", entityFile.getAbsolutePath());
                    }
                    try {
                        JAXBElement<Attachment> je2 = new JAXBElement<>(new QName("Attachment"),
                                Attachment.class, attachment);
                        marshaller.marshal(je2, new FileWriter(entityFile));
                    } catch (IOException e) {
                        log.error("Unable to write to file {}", entityFile.getAbsolutePath(), e);
                        operationSucceeded = false;
                    }
                }

            } catch (JAXBException e) {
                log.error("Unable to create XML file", e);
                System.exit(1);
            }
        }
        offset += attachments.size();

    } while (attachments.size() == batchFetchSize);

    if (attachments.size() == 0 && offset == 0) {
        log.info("No attachments found in the database.");
    }

    if (!operationSucceeded) {
        System.exit(1);
    }
}

From source file:org.jboss.as.test.integration.security.xacml.JBossPDPInteroperabilityTestCase.java

/**
 * Creates a {@link JBossPDP} instance filled with policies from Medical example (loaded from a directory in the
 * filesystem)./*from  w ww.j a  v  a  2s. co  m*/
 *
 * @param policyDir
 * @return
 * @throws IOException
 */
private JBossPDP createPDPForMed(final File policyDir) throws IOException {
    final File policySetFile = new File(policyDir, XACMLTestUtils.MED_EXAMPLE_POLICY_SET);
    final File policySetFile2 = new File(policyDir, XACMLTestUtils.MED_EXAMPLE_POLICY_SET2);

    //copy policy files to the temporary folder
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Copying policies to the " + policyDir.getAbsolutePath());
    }
    FileUtils.copyInputStreamToFile(
            getClass().getResourceAsStream(
                    XACMLTestUtils.TESTOBJECTS_POLICIES + "/" + XACMLTestUtils.MED_EXAMPLE_POLICY_SET),
            policySetFile);
    FileUtils.copyInputStreamToFile(
            getClass().getResourceAsStream(
                    XACMLTestUtils.TESTOBJECTS_POLICIES + "/" + XACMLTestUtils.MED_EXAMPLE_POLICY_SET2),
            policySetFile2);

    //create XML configuration for the PDP
    final PDP pdp = new PDP();
    final PoliciesType policies = new PoliciesType();
    final PolicySetType policySet = new PolicySetType();
    policySet.setLocation(policyDir.toURI().getPath());
    policies.getPolicySet().add(policySet);
    pdp.setPolicies(policies);
    final LocatorType locator = new LocatorType();
    locator.setName(JBossPolicySetLocator.class.getName());
    final LocatorsType locators = new LocatorsType();
    locators.getLocator().add(locator);
    pdp.setLocators(locators);

    return new JBossPDP(new JAXBElement<PDP>(new QName("urn:jboss:xacml:2.0", "jbosspdp"), PDP.class, pdp));
}