Example usage for javax.xml.bind JAXB marshal

List of usage examples for javax.xml.bind JAXB marshal

Introduction

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

Prototype

public static void marshal(Object jaxbObject, Result xml) 

Source Link

Document

Writes a Java object tree to XML and store it to the specified location.

Usage

From source file:ddf.security.realm.sts.StsRealm.java

/**
 * Creates a binary security token based on the provided credential.
 *//* ww w  .  j  a v a2  s  . c o m*/
private String getBinarySecurityToken(String credential) {
    BinarySecurityTokenType binarySecurityTokenType = new BinarySecurityTokenType();
    binarySecurityTokenType.setValueType("#CAS");
    binarySecurityTokenType.setEncodingType(WSConstants.SOAPMESSAGE_NS + "#Base64Binary");
    binarySecurityTokenType.setId("CAS");
    binarySecurityTokenType.setValue(Base64.encode(credential.getBytes()));
    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);
    Writer writer = new StringWriter();
    JAXB.marshal(binarySecurityTokenElement, writer);

    String binarySecurityToken = writer.toString();

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

    return binarySecurityToken;
}

From source file:org.apache.juddi.adminconsole.hub.JUDDIRequestsAsXML.java

public static String getSampleXML(String method) {
    StringWriter sw = new StringWriter();

    if (method.equalsIgnoreCase("save_ClientSubscriptionInfo")) {
        SaveClientSubscriptionInfo obj = new SaveClientSubscriptionInfo();
        obj.getClientSubscriptionInfo().add(new ClientSubscriptionInfo());
        obj.getClientSubscriptionInfo().get(0).setFromClerk(new Clerk());
        obj.getClientSubscriptionInfo().get(0).setToClerk(new Clerk());
        obj.getClientSubscriptionInfo().get(0).setSubscriptionKey("key");

        JAXB.marshal(obj, sw);
    }/*from   www .j  a va2  s  .  co  m*/
    if (method.equalsIgnoreCase("invoke_SyncSubscription")) {
        SyncSubscription obj = new SyncSubscription();
        obj.getGetSubscriptionResultsList().add(new GetSubscriptionResults());
        obj.getGetSubscriptionResultsList().get(0).setSubscriptionKey("key");
        obj.getGetSubscriptionResultsList().get(0).setCoveragePeriod(new CoveragePeriod());
        DatatypeFactory newInstance;
        try {
            newInstance = DatatypeFactory.newInstance();
            obj.getGetSubscriptionResultsList().get(0).getCoveragePeriod()
                    .setEndPoint(newInstance.newXMLGregorianCalendar(new GregorianCalendar()));
            obj.getGetSubscriptionResultsList().get(0).getCoveragePeriod()
                    .setStartPoint(newInstance.newXMLGregorianCalendar(new GregorianCalendar()));

        } catch (DatatypeConfigurationException ex) {
            Logger.getLogger(JUDDIRequestsAsXML.class.getName()).log(Level.SEVERE, null, ex);
        }
        JAXB.marshal(obj, sw);
    }
    if (method.equalsIgnoreCase("admin_SaveBusiness")) {
        AdminSaveBusiness obj = new AdminSaveBusiness();
        obj.getValues().add(new AdminSaveBusinessWrapper());
        obj.getValues().get(0).setPublisherID("username");
        obj.getValues().get(0).getBusinessEntity().add(new BusinessEntity());
        obj.getValues().get(0).getBusinessEntity().get(0).getName().add(new Name("Business Name", "en"));
        JAXB.marshal(obj, sw);
    }
    if (method.equalsIgnoreCase("admin_SaveTModel")) {
        AdminSaveTModel obj = new AdminSaveTModel();
        obj.getValues().add(new AdminSaveTModelWrapper());
        obj.getValues().get(0).setPublisherID("username");
        obj.getValues().get(0).getTModel().add(new TModel());
        obj.getValues().get(0).getTModel().get(0).setName(new Name("TModel Name", "en"));
        JAXB.marshal(obj, sw);
    }

    if (method.equalsIgnoreCase("admin_SaveSubscription")) {
        AdminSaveSubscriptionRequest obj = new AdminSaveSubscriptionRequest();
        obj.setPublisherOrUsername("username");
        obj.getSubscriptions().add(new Subscription());
        obj.getSubscriptions().get(0).setSubscriptionFilter(new SubscriptionFilter());
        obj.getSubscriptions().get(0).setBrief(Boolean.TRUE);
        obj.getSubscriptions().get(0).getSubscriptionFilter().setFindBusiness(new FindBusiness());
        obj.getSubscriptions().get(0).getSubscriptionFilter().getFindBusiness().getName()
                .add(new Name(UDDIConstants.WILDCARD, null));
        obj.getSubscriptions().get(0).getSubscriptionFilter().getFindBusiness()
                .setFindQualifiers(new FindQualifiers());
        obj.getSubscriptions().get(0).getSubscriptionFilter().getFindBusiness().getFindQualifiers()
                .getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH);
        obj.getSubscriptions().get(0).getSubscriptionFilter().getFindBusiness().getFindQualifiers()
                .getFindQualifier().add(UDDIConstants.CASE_INSENSITIVE_MATCH);
        //obj.getSubscriptions().get(0).getSubscriptionFilter().getFindBusiness()
        JAXB.marshal(obj, sw);
    }

    if (method.equalsIgnoreCase("set_ReplicationNodes")) {
        ReplicationConfiguration replicationConfiguration = new ReplicationConfiguration();
        replicationConfiguration.setCommunicationGraph(new CommunicationGraph());
        String thisnode = "NODEID";
        try {
            thisnode = AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID);
        } catch (ConfigurationException ex) {
            Logger.getLogger(JUDDIRequestsAsXML.class.getName()).log(Level.SEVERE, null, ex);
        }

        replicationConfiguration.getCommunicationGraph().getNode().add(thisnode);
        Operator op = new Operator();
        op.setOperatorNodeID(thisnode);

        op.setOperatorStatus(OperatorStatusType.NORMAL);
        String url = "http://localhost:8080/juddiv3/services/replication";
        try {
            url = AppConfig.getConfiguration().getString(Property.DEFAULT_BASE_URL_SECURE)
                    + "/services/replication";
        } catch (ConfigurationException ex) {
            Logger.getLogger(JUDDIRequestsAsXML.class.getName()).log(Level.SEVERE, null, ex);
        }
        op.setSoapReplicationURL(url);

        replicationConfiguration.getOperator().add(op);
        replicationConfiguration.setRegistryContact(new ReplicationConfiguration.RegistryContact());
        replicationConfiguration.getRegistryContact().setContact(new Contact());
        replicationConfiguration.getRegistryContact().getContact().getPersonName()
                .add(new PersonName("UNKNOWN", "en"));

        JAXB.marshal(replicationConfiguration, sw);
    }

    return PrettyPrintXML(sw.toString());
}

From source file:org.apache.juddi.adminconsole.hub.UddiAdminHub.java

private String invoke_SyncSubscription(HttpServletRequest parameters) {
    StringBuilder ret = new StringBuilder();
    SyncSubscription sb = new SyncSubscription();

    SyncSubscriptionDetail d = null;/* www . j a va  2 s. co  m*/
    try {
        StringReader sr = new StringReader(parameters.getParameter("invokeSyncSubscriptionXML").trim());
        sb = (JAXB.unmarshal(sr, SyncSubscription.class));
        sb.setAuthInfo(GetToken());
        d = juddi.invokeSyncSubscription(sb);
    } catch (Exception ex) {
        if (isExceptionExpiration(ex)) {
            token = null;
            sb.setAuthInfo(GetToken());
            try {
                d = juddi.invokeSyncSubscription(sb);
            } catch (Exception ex1) {
                return HandleException(ex);
            }

        } else {
            return HandleException(ex);
        }
    }
    if (d != null) {
        ret.append("<pre>");
        StringWriter sw = new StringWriter();
        JAXB.marshal(d, sw);
        sw.append(PrettyPrintXML(sw.toString()));
        ret.append("</pre>");
    } else {
        ret.append("No data returned");
    }
    return ret.toString();
}

From source file:org.apache.juddi.adminconsole.hub.UddiAdminHub.java

public static String getSampleSave_ClientSubscriptionInfo() {
    SaveClientSubscriptionInfo x = new SaveClientSubscriptionInfo();
    x.setAuthInfo("");
    x.getClientSubscriptionInfo().add(new ClientSubscriptionInfo());
    x.getClientSubscriptionInfo().get(0).setFromClerk(new Clerk());
    x.getClientSubscriptionInfo().get(0).setToClerk(new Clerk());
    x.getClientSubscriptionInfo().get(0).setSubscriptionKey("subscription key");
    x.getClientSubscriptionInfo().get(0).setLastModified(null);
    x.getClientSubscriptionInfo().get(0).setLastNotified(null);
    x.getClientSubscriptionInfo().get(0).getFromClerk().setName("ClerkName");
    x.getClientSubscriptionInfo().get(0).getFromClerk().setPublisher("username");
    x.getClientSubscriptionInfo().get(0).getFromClerk().setPassword("password");
    x.getClientSubscriptionInfo().get(0).getFromClerk().setNode(new Node());
    x.getClientSubscriptionInfo().get(0).getFromClerk().getNode().setClientName("clientname");
    x.getClientSubscriptionInfo().get(0).getFromClerk().getNode().setName("nodename");
    x.getClientSubscriptionInfo().get(0).getFromClerk().getNode().setDescription("description");
    x.getClientSubscriptionInfo().get(0).getFromClerk().getNode()
            .setInquiryUrl("http://localhost:8080/juddiv3/services/inquiry");
    x.getClientSubscriptionInfo().get(0).getFromClerk().getNode()
            .setPublishUrl("http://localhost:8080/juddiv3/services/publish");
    x.getClientSubscriptionInfo().get(0).getFromClerk().getNode()
            .setCustodyTransferUrl("http://localhost:8080/juddiv3/services/custody-transfer");
    x.getClientSubscriptionInfo().get(0).getFromClerk().getNode()
            .setSubscriptionUrl("http://localhost:8080/juddiv3/services/subscription");
    x.getClientSubscriptionInfo().get(0).getFromClerk().getNode()
            .setSubscriptionListenerUrl("http://localhost:8080/juddiv3/services/subscription-listener");
    x.getClientSubscriptionInfo().get(0).getFromClerk().getNode()
            .setJuddiApiUrl("http://localhost:8080/juddiv3/services/juddi-api");
    x.getClientSubscriptionInfo().get(0).getFromClerk().getNode()
            .setReplicationUrl("http://localhost:8080/juddiv3/services/replication");

    x.getClientSubscriptionInfo().get(0).getToClerk().setName("ClerkName");
    x.getClientSubscriptionInfo().get(0).getToClerk().setPublisher("username");
    x.getClientSubscriptionInfo().get(0).getToClerk().setPassword("password");
    x.getClientSubscriptionInfo().get(0).getToClerk().setNode(new Node());
    x.getClientSubscriptionInfo().get(0).getToClerk().getNode().setClientName("clientname");
    x.getClientSubscriptionInfo().get(0).getToClerk().getNode().setName("nodename");
    x.getClientSubscriptionInfo().get(0).getToClerk().getNode().setDescription("description");
    x.getClientSubscriptionInfo().get(0).getToClerk().getNode()
            .setInquiryUrl("http://localhost:8080/juddiv3/services/inquiry");
    x.getClientSubscriptionInfo().get(0).getToClerk().getNode()
            .setPublishUrl("http://localhost:8080/juddiv3/services/publish");
    x.getClientSubscriptionInfo().get(0).getToClerk().getNode()
            .setCustodyTransferUrl("http://localhost:8080/juddiv3/services/custody-transfer");
    x.getClientSubscriptionInfo().get(0).getToClerk().getNode()
            .setSubscriptionUrl("http://localhost:8080/juddiv3/services/subscription");
    x.getClientSubscriptionInfo().get(0).getToClerk().getNode()
            .setSubscriptionListenerUrl("http://localhost:8080/juddiv3/services/subscription-listener");
    x.getClientSubscriptionInfo().get(0).getToClerk().getNode()
            .setJuddiApiUrl("http://localhost:8080/juddiv3/services/juddi-api");
    x.getClientSubscriptionInfo().get(0).getToClerk().getNode()
            .setReplicationUrl("http://localhost:8080/juddiv3/services/replication");
    StringWriter sw = new StringWriter();
    JAXB.marshal(x, sw);
    return sw.toString();
}

From source file:org.apache.juddi.adminconsole.hub.UddiAdminHub.java

private String save_ClientSubscriptionInfo(HttpServletRequest parameters) {
    StringBuilder ret = new StringBuilder();
    SaveClientSubscriptionInfo sb = new SaveClientSubscriptionInfo();

    if (parameters.getParameter("ClientSubscriptionInfoDetailXML") == null)
        return "No input!";
    ClientSubscriptionInfoDetail d = null;
    try {/*from   w  w w . j a  va 2  s .  co m*/
        StringReader sr = new StringReader(parameters.getParameter("ClientSubscriptionInfoDetailXML").trim());
        sb = (JAXB.unmarshal(sr, SaveClientSubscriptionInfo.class));
        sb.setAuthInfo(GetToken());
        d = juddi.saveClientSubscriptionInfo(sb);
    } catch (Exception ex) {
        if (ex instanceof DispositionReportFaultMessage) {
            DispositionReportFaultMessage f = (DispositionReportFaultMessage) ex;
            if (f.getFaultInfo().countainsErrorCode(DispositionReport.E_AUTH_TOKEN_EXPIRED)) {
                token = null;
                sb.setAuthInfo(GetToken());
                try {
                    d = juddi.saveClientSubscriptionInfo(sb);
                } catch (Exception ex1) {
                    return HandleException(ex);
                }
            }
        } else {
            return HandleException(ex);
        }
    }
    if (d != null) {
        ret.append("<pre>");
        StringWriter sw = new StringWriter();
        JAXB.marshal(d, sw);
        sw.append(PrettyPrintXML(sw.toString()));
        ret.append("</pre>");
    } else {
        ret.append("No data returned");
    }
    return ret.toString();
}

From source file:org.apache.juddi.api.impl.API_160_ReplicationTest.java

@Test
public void setReplicationConfig() throws Exception {

    ReplicationConfiguration r = new ReplicationConfiguration();
    Operator op = new Operator();
    op.setOperatorNodeID("test_node");
    op.setSoapReplicationURL("http://localhost");
    op.setOperatorStatus(OperatorStatusType.NORMAL);

    r.getOperator().add(op);//from   w w w.  j av a2  s  .c  om
    r.setCommunicationGraph(new CommunicationGraph());
    r.setRegistryContact(new ReplicationConfiguration.RegistryContact());
    r.getRegistryContact().setContact(new Contact());
    r.getRegistryContact().getContact().getPersonName().add(new PersonName("test", null));
    //  r.getCommunicationGraph().getEdge().add(new CommunicationGraph.Edge());
    r.getCommunicationGraph().getNode().add("test_node");

    JAXB.marshal(r, System.out);
    DispositionReport setReplicationNodes = juddi.setReplicationNodes(authInfoRoot, r);

    ReplicationConfiguration replicationNodes = juddi.getReplicationNodes(authInfoRoot);
    Assert.assertNotNull(replicationNodes.getCommunicationGraph());
    Assert.assertNotNull(replicationNodes.getCommunicationGraph().getNode());
    Assert.assertEquals("test_node", replicationNodes.getCommunicationGraph().getNode().get(0));
    Assert.assertNotNull(replicationNodes.getMaximumTimeToGetChanges());
    Assert.assertNotNull(replicationNodes.getMaximumTimeToSyncRegistry());
    Assert.assertNotNull(replicationNodes.getTimeOfConfigurationUpdate());
    Assert.assertNotNull(replicationNodes.getSerialNumber());
    long firstcommit = replicationNodes.getSerialNumber();

    r = new ReplicationConfiguration();
    r.getOperator().add(op);
    r.setCommunicationGraph(new CommunicationGraph());
    r.setRegistryContact(new ReplicationConfiguration.RegistryContact());
    r.getRegistryContact().setContact(new Contact());
    r.getRegistryContact().getContact().getPersonName().add(new PersonName("test", null));
    //  r.getCommunicationGraph().getEdge().add(new CommunicationGraph.Edge());
    r.getCommunicationGraph().getNode().add("test_node");

    JAXB.marshal(r, System.out);
    setReplicationNodes = juddi.setReplicationNodes(authInfoRoot, r);

    replicationNodes = juddi.getReplicationNodes(authInfoRoot);
    Assert.assertNotNull(replicationNodes.getCommunicationGraph());
    Assert.assertNotNull(replicationNodes.getCommunicationGraph().getNode());
    Assert.assertEquals("test_node", replicationNodes.getCommunicationGraph().getNode().get(0));
    Assert.assertNotNull(replicationNodes.getMaximumTimeToGetChanges());
    Assert.assertNotNull(replicationNodes.getMaximumTimeToSyncRegistry());
    Assert.assertNotNull(replicationNodes.getTimeOfConfigurationUpdate());
    Assert.assertNotNull(replicationNodes.getSerialNumber());
    Assert.assertTrue(firstcommit < replicationNodes.getSerialNumber());

}

From source file:org.apache.juddi.config.InstallTest.java

/**
 * Test of applyReplicationTokenChanges method, of class Install.
 *//*from  w ww. j a va  2 s . c  o  m*/
@Test
public void testApplyReplicationTokenChanges() throws Exception {
    System.out.println("applyReplicationTokenChanges");
    InputStream fis = getClass().getClassLoader()
            .getResourceAsStream("juddi_install_data/root_replicationConfiguration.xml");

    ReplicationConfiguration replicationCfg = JAXB.unmarshal(fis, ReplicationConfiguration.class);
    Properties props = new Properties();
    props.put(Property.JUDDI_NODE_ID, "uddi:a_custom_node");
    props.put(Property.JUDDI_BASE_URL, "http://juddi.apache.org");
    props.put(Property.JUDDI_BASE_URL_SECURE, "https://juddi.apache.org");

    Configuration config = new MapConfiguration(props);
    String thisnode = "uddi:a_custom_node";

    ReplicationConfiguration result = Install.applyReplicationTokenChanges(replicationCfg, config, thisnode);
    StringWriter sw = new StringWriter();
    JAXB.marshal(result, sw);
    Assert.assertFalse(sw.toString().contains("${juddi.nodeId}"));
    Assert.assertFalse(sw.toString().contains("${juddi.server.baseurlsecure}"));
    Assert.assertFalse(sw.toString().contains("${juddi.server.baseurl}"));

}

From source file:org.apache.juddi.mapping.MappingApiToModel.java

private static SignatureTransformDataValue mapSignatureTransformDataValue(Object xform) {
    SignatureTransformDataValue sdv = new SignatureTransformDataValue();
    if (xform instanceof String) {
        sdv.setContentType(String.class.getSimpleName());
        String xformStr = xform.toString();
        byte[] xformBytes = xformStr.getBytes();
        sdv.setContentBytes(xformBytes);
    } else if (xform instanceof Element) {
        sdv.setContentType(Element.class.getCanonicalName());
        Element xformEl = (Element) xform;
        String str = serializeTransformElement(xformEl);
        try {//ww w. j ava 2s  .  c  o m
            sdv.setContentBytes(str.getBytes("UTF-8"));
        } catch (Exception e) {
            throw new RuntimeException("Failed to encode string due to: " + e.getMessage(), e);
        }
    } else if (xform instanceof byte[]) {
        sdv.setContentType(byte[].class.getSimpleName());
        sdv.setContentBytes((byte[]) xform);
    } else if (xform instanceof JAXBElement) {
        sdv.setContentType(Element.class.getCanonicalName());
        JAXBElement xformJAXB = (JAXBElement) xform;
        DOMResult domResult = new DOMResult();
        JAXB.marshal(xformJAXB, domResult);
        Element xformEl = ((Document) domResult.getNode()).getDocumentElement();
        String str = serializeTransformElement(xformEl);
        try {
            sdv.setContentBytes(str.getBytes("UTF-8"));
        } catch (Exception e) {
            throw new RuntimeException("Failed to encode string due to: " + e.getMessage(), e);
        }
    } else {
        throw new RuntimeException("Unrecognized type: " + xform.getClass().getCanonicalName());
    }
    return sdv;
}

From source file:org.apache.juddi.replication.ReplicationNotifier.java

/**
 * Note: this is for locally originated changes only, see null null null         {@link org.apache.juddi.api.impl.UDDIReplicationImpl.PullTimerTask#PersistChangeRecord PersistChangeRecord
 * } for how remote changes are processed
 *
 * @param j must be one of the UDDI save APIs
 *
 *///from   ww  w .  java2  s . co m
protected void ProcessChangeRecord(org.apache.juddi.model.ChangeRecord j) {
    //store and convert the changes to database model

    //TODO need a switch to send the notification without persisting the record
    //this is to support multihop notifications
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = null;
    try {
        tx = em.getTransaction();
        tx.begin();
        j.setIsAppliedLocally(true);
        em.persist(j);
        j.setOriginatingUSN(j.getId());
        em.merge(j);
        log.info("CR saved locally, it was from " + j.getNodeID() + " USN:" + j.getOriginatingUSN() + " Type:"
                + j.getRecordType().name() + " Key:" + j.getEntityKey() + " Local id:" + j.getId());
        tx.commit();
    } catch (Exception ex) {
        log.fatal("unable to store local change record locally!!", ex);
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        JAXB.marshal(MappingModelToApi.mapChangeRecord(j), System.out);
    } finally {
        em.close();
    }

    log.debug("ChangeRecord: " + j.getId() + "," + j.getEntityKey() + "," + j.getNodeID() + ","
            + j.getOriginatingUSN() + "," + j.getRecordType().toString());
    SendNotifications(j.getId(), j.getNodeID(), false);

}

From source file:org.apache.juddi.samples.JuddiAdminService.java

void registerLocalNodeToRemoteNode(String authtoken, Node cfg, Node publishTo) throws Exception {

    Transport transport = clerkManager.getTransport(publishTo.getName());

    UDDISecurityPortType security2 = transport.getUDDISecurityService();
    System.out.print("username: ");
    String uname = System.console().readLine();
    char passwordArray[] = System.console().readPassword("password: ");
    GetAuthToken getAuthTokenRoot = new GetAuthToken();
    getAuthTokenRoot.setUserID(uname);/*from   w ww  .  jav  a2 s  . com*/
    getAuthTokenRoot.setCred(new String(passwordArray));
    authtoken = security2.getAuthToken(getAuthTokenRoot).getAuthInfo();
    System.out.println("Success!");

    JUDDIApiPortType juddiApiService = transport.getJUDDIApiService();
    SaveNode sn = new SaveNode();
    sn.setAuthInfo(authtoken);
    sn.getNode().add(cfg);
    NodeDetail saveNode = juddiApiService.saveNode(sn);
    JAXB.marshal(saveNode, System.out);
    System.out.println("Success.");

}