Example usage for javax.xml.datatype DatatypeFactory newXMLGregorianCalendar

List of usage examples for javax.xml.datatype DatatypeFactory newXMLGregorianCalendar

Introduction

In this page you can find the example usage for javax.xml.datatype DatatypeFactory newXMLGregorianCalendar.

Prototype

public abstract XMLGregorianCalendar newXMLGregorianCalendar(final GregorianCalendar cal);

Source Link

Document

Create an XMLGregorianCalendar from a GregorianCalendar .

Usage

From source file:org.accada.epcis.repository.query.QuerySubscription.java

/**
 * Serializes and sends the given object back to the client. The Object must
 * be an instance of QueryResults, QueryTooLargeException, or
 * ImplementationException./*from  w w w. java2  s  . c  om*/
 * 
 * @param o
 *            The object to be sent back to the client. An instance of
 *            QueryResults, QueryTooLargeException, or
 *            ImplementationException.
 */
private void callbackObject(final Object o) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Callback " + o + " at " + new Date());
    }
    // create the EPCIS document
    EPCISQueryDocumentType epcisDoc = new EPCISQueryDocumentType();
    epcisDoc.setSchemaVersion(BigDecimal.valueOf(1.0));
    try {
        DatatypeFactory dataFactory = DatatypeFactory.newInstance();
        XMLGregorianCalendar now = dataFactory.newXMLGregorianCalendar(new GregorianCalendar());
        epcisDoc.setCreationDate(now);
    } catch (DatatypeConfigurationException e) {
        // oh well - don't care about setting the creation date
    }
    EPCISQueryBodyType epcisBody = new EPCISQueryBodyType();
    if (o instanceof QueryResults) {
        epcisBody.setQueryResults((QueryResults) o);
    } else if (o instanceof QueryTooLargeException) {
        epcisBody.setQueryTooLargeException((QueryTooLargeException) o);
    } else if (o instanceof ImplementationException) {
        epcisBody.setImplementationException((ImplementationException) o);
    } else {
        epcisBody = null;
    }
    epcisDoc.setEPCISBody(epcisBody);

    // serialize the response
    String data;
    try {
        data = marshalQueryDoc(epcisDoc);
    } catch (JAXBException e) {
        String msg = "An error serializing contents occurred: " + e.getMessage();
        LOG.error(msg, e);
        return;
    }

    // set up connection and send data to given destination
    try {
        URL serviceUrl = new URL(dest.toString());
        if (LOG.isDebugEnabled()) {
            LOG.debug("Sending results of subscribed query '" + subscriptionID + "' to '" + serviceUrl + "'");
            if (data.length() < 10 * 1024) {
                LOG.debug("Sending data:\n" + data);
            } else {
                LOG.debug("Sending data: [" + data.length() + " bytes]");
            }
        }
        int responseCode;
        try {
            responseCode = sendData(serviceUrl, data);
        } catch (Exception e) {
            LOG.warn("Unable to send results of subscribed query '" + subscriptionID + "' to '" + serviceUrl
                    + "', retrying in 3 sec ...");
            // wait 3 seconds and try again
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e1) {
                // never mind
            }
            try {
                responseCode = sendData(serviceUrl, data);
            } catch (Exception e2) {
                LOG.warn("Unable to send results of subscribed query '" + subscriptionID + "' to '" + serviceUrl
                        + "', retrying in 3 sec ...");
                // wait 3 seconds and try again
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e1) {
                    // never mind
                }
                responseCode = sendData(serviceUrl, data);
            }
        }
        LOG.debug("Response " + responseCode);
    } catch (IOException e) {
        String msg = "Unable to send results of subscribed query '" + subscriptionID + "' to '" + dest + "': "
                + e.getMessage();
        LOG.error(msg, e);
        return;
    }
}

From source file:org.alfresco.opencmis.CMISConnector.java

private String convertAspectPropertyValue(Object value) {
    if (value instanceof Date) {
        GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
        cal.setTime((Date) value);
        value = cal;//from   ww  w. ja v  a 2  s.  co m
    }

    if (value instanceof GregorianCalendar) {
        DatatypeFactory df;
        try {
            df = DatatypeFactory.newInstance();
        } catch (DatatypeConfigurationException e) {
            throw new IllegalArgumentException("Aspect conversation exception: " + e.getMessage(), e);
        }
        return df.newXMLGregorianCalendar((GregorianCalendar) value).toXMLFormat();
    }

    // MNT-12496 MNT-15044
    // Filter for AtomPub and Web services bindings only. Browser/json binding already encodes.
    if (AlfrescoCmisServiceCall.get() != null
            && (CallContext.BINDING_ATOMPUB.equals(AlfrescoCmisServiceCall.get().getBinding())
                    || CallContext.BINDING_WEBSERVICES.equals(AlfrescoCmisServiceCall.get().getBinding()))) {
        return filterXmlRestrictedCharacters(value.toString());
    } else {
        return value.toString();
    }
}

From source file:org.alfresco.opencmis.CMISConnector.java

private void setAspectProperties(NodeRef nodeRef, boolean isNameChanging,
        CmisExtensionElement aspectExtension) {
    if (aspectExtension.getChildren() == null) {
        return;/* w  w w.  j a va 2  s .co  m*/
    }

    List<String> aspectsToAdd = new ArrayList<String>();
    List<String> aspectsToRemove = new ArrayList<String>();
    Map<QName, List<Serializable>> aspectProperties = new HashMap<QName, List<Serializable>>();

    for (CmisExtensionElement extension : aspectExtension.getChildren()) {
        if (!ALFRESCO_EXTENSION_NAMESPACE.equals(extension.getNamespace())) {
            continue;
        }

        if (ASPECTS_TO_ADD.equals(extension.getName()) && (extension.getValue() != null)) {
            aspectsToAdd.add(extension.getValue());
        } else if (ASPECTS_TO_REMOVE.equals(extension.getName()) && (extension.getValue() != null)) {
            aspectsToRemove.add(extension.getValue());
        } else if (PROPERTIES.equals(extension.getName()) && (extension.getChildren() != null)) {
            for (CmisExtensionElement property : extension.getChildren()) {
                if (!property.getName().startsWith("property")) {
                    continue;
                }

                String propertyId = (property.getAttributes() == null ? null
                        : property.getAttributes().get("propertyDefinitionId"));
                if ((propertyId == null) || (property.getChildren() == null)) {
                    continue;
                }

                PropertyType propertyType = PropertyType.STRING;
                DatatypeFactory df = null;
                if (property.getName().equals("propertyBoolean")) {
                    propertyType = PropertyType.BOOLEAN;
                } else if (property.getName().equals("propertyInteger")) {
                    propertyType = PropertyType.INTEGER;
                } else if (property.getName().equals("propertyDateTime")) {
                    propertyType = PropertyType.DATETIME;
                    try {
                        df = DatatypeFactory.newInstance();
                    } catch (DatatypeConfigurationException e) {
                        throw new CmisRuntimeException("Aspect conversation exception: " + e.getMessage(), e);
                    }
                } else if (property.getName().equals("propertyDecimal")) {
                    propertyType = PropertyType.DECIMAL;
                }

                ArrayList<Serializable> values = new ArrayList<Serializable>();
                if (property.getChildren() != null) {
                    //                        try
                    //                        {
                    for (CmisExtensionElement valueElement : property.getChildren()) {
                        if ("value".equals(valueElement.getName())) {
                            switch (propertyType) {
                            case BOOLEAN:
                                try {
                                    values.add(Boolean.parseBoolean(valueElement.getValue()));
                                } catch (Exception e) {
                                    throw new CmisInvalidArgumentException(
                                            "Invalid property aspect value: " + propertyId, e);
                                }
                                break;
                            case DATETIME:
                                try {
                                    values.add(df.newXMLGregorianCalendar(valueElement.getValue())
                                            .toGregorianCalendar());
                                } catch (Exception e) {
                                    throw new CmisInvalidArgumentException(
                                            "Invalid property aspect value: " + propertyId, e);
                                }
                                break;
                            case INTEGER:
                                BigInteger value = null;
                                try {
                                    value = new BigInteger(valueElement.getValue());
                                } catch (Exception e) {
                                    throw new CmisInvalidArgumentException(
                                            "Invalid property aspect value: " + propertyId, e);
                                }

                                // overflow check
                                PropertyDefinitionWrapper propDef = getOpenCMISDictionaryService()
                                        .findProperty(propertyId);
                                if (propDef == null) {
                                    throw new CmisInvalidArgumentException(
                                            "Property " + propertyId + " is unknown!");
                                }

                                QName propertyQName = propDef.getPropertyAccessor().getMappedProperty();
                                if (propertyQName == null) {
                                    throw new CmisConstraintException(
                                            "Unable to set property " + propertyId + "!");
                                }

                                org.alfresco.service.cmr.dictionary.PropertyDefinition def = dictionaryService
                                        .getProperty(propertyQName);
                                QName dataDef = def.getDataType().getName();

                                if (dataDef.equals(DataTypeDefinition.INT)
                                        && (value.compareTo(maxInt) > 0 || value.compareTo(minInt) < 0)) {
                                    throw new CmisConstraintException(
                                            "Value is out of range for property " + propertyId);
                                }

                                if (dataDef.equals(DataTypeDefinition.LONG)
                                        && (value.compareTo(maxLong) > 0 || value.compareTo(minLong) < 0)) {
                                    throw new CmisConstraintException(
                                            "Value is out of range for property " + propertyId);
                                }

                                values.add(value);
                                break;
                            case DECIMAL:
                                try {
                                    values.add(new BigDecimal(valueElement.getValue()));
                                } catch (Exception e) {
                                    throw new CmisInvalidArgumentException(
                                            "Invalid property aspect value: " + propertyId, e);
                                }
                                break;
                            default:
                                values.add(valueElement.getValue());
                            }
                        }
                    }
                }

                aspectProperties.put(QName.createQName(propertyId, namespaceService), values);
            }
        }
    }

    // remove and add aspects
    String aspectType = null;
    try {
        for (String aspect : aspectsToRemove) {
            aspectType = aspect;

            TypeDefinitionWrapper type = getType(aspect);
            if (type == null) {
                throw new CmisInvalidArgumentException("Invalid aspect: " + aspectType);
            }

            QName typeName = type.getAlfrescoName();
            // if aspect is hidden aspect, remove only if hidden node is not client controlled
            if (typeName.equals(ContentModel.ASPECT_HIDDEN)) {
                if (hiddenAspect.isClientControlled(nodeRef)
                        || aspectProperties.containsKey(ContentModel.PROP_CLIENT_CONTROLLED)) {
                    // manipulate hidden aspect only if client controlled
                    nodeService.removeAspect(nodeRef, typeName);
                }

                //                   if(!isNameChanging && !hiddenAspect.isClientControlled(nodeRef) && !aspectProperties.containsKey(ContentModel.PROP_CLIENT_CONTROLLED))
                //                   {
                //                       nodeService.removeAspect(nodeRef, typeName);   
                //                   }
            } else {
                nodeService.removeAspect(nodeRef, typeName);
            }
        }

        for (String aspect : aspectsToAdd) {
            aspectType = aspect;

            TypeDefinitionWrapper type = getType(aspect);
            if (type == null) {
                throw new CmisInvalidArgumentException("Invalid aspect: " + aspectType);
            }

            QName typeName = type.getAlfrescoName();
            // if aspect is hidden aspect, remove only if hidden node is not client controlled
            if (typeName.equals(ContentModel.ASPECT_HIDDEN)) {
                if (hiddenAspect.isClientControlled(nodeRef)
                        || aspectProperties.containsKey(ContentModel.PROP_CLIENT_CONTROLLED)) {
                    // manipulate hidden aspect only if client controlled
                    nodeService.addAspect(nodeRef, type.getAlfrescoName(),
                            Collections.<QName, Serializable>emptyMap());
                }

                //                   if(!isNameChanging && !hiddenAspect.isClientControlled(nodeRef) && !aspectProperties.containsKey(ContentModel.PROP_CLIENT_CONTROLLED))
                //                   {
                //                      nodeService.addAspect(nodeRef, type.getAlfrescoName(),
                //                               Collections.<QName, Serializable> emptyMap());   
                //                   }
            } else {
                nodeService.addAspect(nodeRef, type.getAlfrescoName(),
                        Collections.<QName, Serializable>emptyMap());
            }
        }
    } catch (InvalidAspectException e) {
        throw new CmisInvalidArgumentException("Invalid aspect: " + aspectType);
    } catch (InvalidNodeRefException e) {
        throw new CmisInvalidArgumentException("Invalid node: " + nodeRef);
    }

    // set property
    for (Map.Entry<QName, List<Serializable>> property : aspectProperties.entrySet()) {
        QName propertyQName = property.getKey();

        if (property.getValue().isEmpty()) {
            if (HiddenAspect.HIDDEN_PROPERTIES.contains(property.getKey())) {
                if (hiddenAspect.isClientControlled(nodeRef)
                        || aspectProperties.containsKey(ContentModel.PROP_CLIENT_CONTROLLED)) {
                    // manipulate hidden aspect property only if client controlled
                    nodeService.removeProperty(nodeRef, propertyQName);
                }
            } else {
                nodeService.removeProperty(nodeRef, property.getKey());
            }
        } else {
            if (HiddenAspect.HIDDEN_PROPERTIES.contains(property.getKey())) {
                if (hiddenAspect.isClientControlled(nodeRef)
                        || aspectProperties.containsKey(ContentModel.PROP_CLIENT_CONTROLLED)) {
                    // manipulate hidden aspect property only if client controlled
                    nodeService.setProperty(nodeRef, property.getKey(),
                            property.getValue().size() == 1 ? property.getValue().get(0)
                                    : (Serializable) property.getValue());
                }
            } else {
                Serializable value = (Serializable) property.getValue();
                nodeService.setProperty(nodeRef, property.getKey(),
                        property.getValue().size() == 1 ? property.getValue().get(0) : value);
            }
        }
    }
}

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  v a 2 s . c o  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.api.impl.UDDICustodyTransferImpl.java

public void getTransferToken(String authInfo, KeyBag keyBag, Holder<String> nodeID,
        Holder<XMLGregorianCalendar> expirationTime, Holder<byte[]> opaqueToken)
        throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {/*from w  w  w .j a v a  2 s  .  c  o  m*/
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo);

        new ValidateCustodyTransfer(publisher).validateGetTransferToken(em, keyBag);

        int transferExpirationDays = DEFAULT_TRANSFEREXPIRATION_DAYS;
        try {
            transferExpirationDays = AppConfig.getConfiguration()
                    .getInt(Property.JUDDI_TRANSFER_EXPIRATION_DAYS);
            // For output
            nodeID.value = AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID);
        } catch (ConfigurationException ce) {
            throw new FatalErrorException(new ErrorMessage("errors.configuration.Retrieval"));
        }

        String transferKey = TRANSFER_TOKEN_PREFIX + UUID.randomUUID();
        org.apache.juddi.model.TransferToken transferToken = new org.apache.juddi.model.TransferToken();
        transferToken.setTransferToken(transferKey);
        // For output
        opaqueToken.value = transferKey.getBytes();

        GregorianCalendar gc = new GregorianCalendar();
        gc.add(GregorianCalendar.DAY_OF_MONTH, transferExpirationDays);

        transferToken.setExpirationDate(gc.getTime());

        try {
            DatatypeFactory df = DatatypeFactory.newInstance();
            // For output
            expirationTime.value = df.newXMLGregorianCalendar(gc);
        } catch (DatatypeConfigurationException ce) {
            throw new FatalErrorException(new ErrorMessage("errors.Unspecified"));
        }

        List<String> keyList = keyBag.getKey();
        for (String key : keyList) {
            TransferTokenKey tokenKey = new TransferTokenKey(transferToken, key);
            transferToken.getTransferKeys().add(tokenKey);
        }

        em.persist(transferToken);

        tx.commit();

        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(CustodyTransferQuery.GET_TRANSFERTOKEN, QueryStatus.SUCCESS, procTime);

    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

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

/**
 * Will add the expiration date to the provided subscription request.  Date is earlier of user provided date and the system default
 * /*from w w w  . j  a  v  a2  s. c  o m*/
 * @param apiSubscription
 * @throws DispositionReportFaultMessage
 */
private void doSubscriptionExpirationDate(org.uddi.sub_v3.Subscription apiSubscription)
        throws DispositionReportFaultMessage {

    int subscriptionExpirationDays = DEFAULT_SUBSCRIPTIONEXPIRATION_DAYS;
    try {
        subscriptionExpirationDays = AppConfig.getConfiguration()
                .getInt(Property.JUDDI_SUBSCRIPTION_EXPIRATION_DAYS);
    } catch (ConfigurationException ce) {
        throw new FatalErrorException(new ErrorMessage("errors.configuration.Retrieval"));
    }

    GregorianCalendar expirationDate = new GregorianCalendar();
    expirationDate.add(GregorianCalendar.DAY_OF_MONTH, subscriptionExpirationDays);

    // The expiration date is the earlier of the provided date and that specified by the parameter.
    if (apiSubscription.getExpiresAfter() != null) {
        GregorianCalendar userExpiration = apiSubscription.getExpiresAfter().toGregorianCalendar();
        if (userExpiration.getTimeInMillis() < expirationDate.getTimeInMillis())
            expirationDate.setTimeInMillis(userExpiration.getTimeInMillis());
    }

    try {
        DatatypeFactory df = DatatypeFactory.newInstance();
        apiSubscription.setExpiresAfter(df.newXMLGregorianCalendar(expirationDate));
    } catch (DatatypeConfigurationException ce) {
        throw new FatalErrorException(new ErrorMessage("errors.Unspecified"));
    }

}

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

public void TransferBusiness(String fromUser, String fromUserAuthToken, String toUser, String toUserAuthToken,
        String BusinessKey) throws Exception {

    System.out.println("Transfering business key " + BusinessKey);
    DatatypeFactory df = DatatypeFactory.newInstance();
    GregorianCalendar gcal = new GregorianCalendar();
    gcal.setTimeInMillis(System.currentTimeMillis());
    XMLGregorianCalendar xcal = df.newXMLGregorianCalendar(gcal);

    //Create a transfer token from fromUser to toUser
    KeyBag kb = new KeyBag();
    kb.getKey().add(BusinessKey);/*from w  w  w  .j  a v a2  s  .  c o m*/
    Holder<String> nodeidOUT = new Holder<String>();
    Holder<XMLGregorianCalendar> expiresOUT = new Holder<XMLGregorianCalendar>();
    Holder<byte[]> tokenOUT = new Holder<byte[]>();
    custodyTransferPortType.getTransferToken(fromUserAuthToken, kb, nodeidOUT, expiresOUT, tokenOUT);

    System.out.println("Transfer token obtained. Give this to user " + toUser);
    System.out.println("Expires " + expiresOUT.value.toXMLFormat());
    System.out.println("Node " + nodeidOUT.value);
    System.out.println("Token " + org.apache.commons.codec.binary.Base64.encodeBase64String(tokenOUT.value));

    if (toUser == null || toUser.length() == 0 || toUserAuthToken == null || toUserAuthToken.length() == 0) {
        System.out
                .println("The toUser parameters are either null or empty, I can't complete the transfer here");
        return;
    }

    //The magic part happens here, the user ROOT needs to give the user UDDI the token information out of band
    //in practice, all values must match exactly
    //UDDI now accepts the transfer
    TransferEntities te = new TransferEntities();
    te.setAuthInfo(toUserAuthToken);
    te.setKeyBag(kb);
    TransferToken tt = new TransferToken();
    tt.setExpirationTime(expiresOUT.value);
    tt.setNodeID(nodeidOUT.value);
    tt.setOpaqueToken(tokenOUT.value);
    te.setTransferToken(tt);
    System.out.println("Excuting transfer...");
    custodyTransferPortType.transferEntities(te);
    System.out.println("Complete! verifing ownership change...");

    //confirm the transfer
    GetOperationalInfo go = new GetOperationalInfo();
    go.setAuthInfo(fromUserAuthToken);
    go.getEntityKey().add(BusinessKey);
    OperationalInfos operationalInfo = uddiInquiryService.getOperationalInfo(go);
    boolean ok = false;
    boolean found = false;
    for (int i = 0; i < operationalInfo.getOperationalInfo().size(); i++) {
        if (operationalInfo.getOperationalInfo().get(i).getEntityKey().equalsIgnoreCase(BusinessKey)) {
            found = true;
            if (operationalInfo.getOperationalInfo().get(i).getAuthorizedName().equalsIgnoreCase(fromUser)) {
                System.out.println("Transfer unexpected failed");
            }
            if (operationalInfo.getOperationalInfo().get(i).getAuthorizedName().equalsIgnoreCase(toUser)) {
                ok = true;
            }

        }
    }
    if (!found) {
        System.out.println("Could get the operational info the transfed business");
    }
    System.out.println("Transfer " + (ok ? "success" : " failed"));
}

From source file:org.apache.juddi.v3.tck.UDDI_080_SubscriptionIntegrationTest.java

/**
 * invalid expiration time//w w w .  j a  v a  2  s.c o  m
 *
 * @throws DatatypeConfigurationException
 */
@Test
public void JUDDI_606_2() throws DatatypeConfigurationException {
    Assume.assumeTrue(TckPublisher.isEnabled());
    System.out.println("JUDDI_606_2");
    Assume.assumeTrue(TckPublisher.isSubscriptionEnabled());
    // invalid expiration time
    DatatypeFactory df = DatatypeFactory.newInstance();
    GregorianCalendar gcal = new GregorianCalendar();
    gcal.setTimeInMillis(System.currentTimeMillis());
    gcal.add(Calendar.DATE, -1);
    XMLGregorianCalendar newXMLGregorianCalendar = df.newXMLGregorianCalendar(gcal);

    Subscription sub = new Subscription();
    Holder<List<Subscription>> data = new Holder<List<Subscription>>();
    data.value = new ArrayList<Subscription>();
    sub.setBrief(true);
    sub.setExpiresAfter(newXMLGregorianCalendar);
    sub.setMaxEntities(1);
    sub.setNotificationInterval(null);
    sub.setBindingKey(null);
    sub.setSubscriptionFilter(new SubscriptionFilter());
    sub.getSubscriptionFilter().setFindService(new FindService());
    sub.getSubscriptionFilter().getFindService().setFindQualifiers(new FindQualifiers());
    sub.getSubscriptionFilter().getFindService().getFindQualifiers().getFindQualifier()
            .add(UDDIConstants.APPROXIMATE_MATCH);
    sub.getSubscriptionFilter().getFindService().getName().add(new Name("%", null));
    data.value.add(sub);
    try {
        tckSubscriptionJoe.subscription.saveSubscription(authInfoJoe, data);
        Assert.fail();
    } catch (Exception ex) {
        //HandleException(ex);
        logger.info("Expected exception: " + ex.getMessage());
    }
}

From source file:org.apache.juddi.v3.tck.UDDI_080_SubscriptionIntegrationTest.java

/**
 * set subscription, make a change as the same user, get subscription
 * results no key specified//from ww w  .j  a  va2 s.co  m
 *
 * @throws DatatypeConfigurationException
 */
@Test
public void JUDDI_606_11() throws DatatypeConfigurationException {
    Assume.assumeTrue(TckPublisher.isEnabled());
    System.out.println("JUDDI_606_11");
    Assume.assumeTrue(TckPublisher.isSubscriptionEnabled());

    String key = null;
    DatatypeFactory df = DatatypeFactory.newInstance();
    try {

        Holder<List<Subscription>> data = new Holder<List<Subscription>>();
        data.value = new ArrayList<Subscription>();
        Subscription sub = new Subscription();
        sub.setBrief(false);
        sub.setExpiresAfter(null);
        sub.setMaxEntities(null);
        sub.setNotificationInterval(null);
        sub.setBindingKey(null);
        sub.setSubscriptionFilter(new SubscriptionFilter());
        sub.getSubscriptionFilter().setFindBusiness(new FindBusiness());
        sub.getSubscriptionFilter().getFindBusiness().setFindQualifiers(new FindQualifiers());
        sub.getSubscriptionFilter().getFindBusiness().getFindQualifiers().getFindQualifier()
                .add(UDDIConstants.APPROXIMATE_MATCH);
        sub.getSubscriptionFilter().getFindBusiness().getName().add(new Name("%", null));
        data.value.add(sub);

        tckSubscriptionJoe.subscription.saveSubscription(authInfoJoe, data);
        SaveBusiness sb = new SaveBusiness();
        sb.setAuthInfo(authInfoJoe);
        BusinessEntity be = new BusinessEntity();
        be.getName().add(new Name("Test business", null));
        sb.getBusinessEntity().add(be);
        BusinessDetail saveBusiness = publicationJoe.saveBusiness(sb);

        key = saveBusiness.getBusinessEntity().get(0).getBusinessKey();

        GetSubscriptionResults gsr = new GetSubscriptionResults();
        gsr.setAuthInfo(authInfoJoe);
        gsr.setSubscriptionKey(null);
        gsr.setCoveragePeriod(new CoveragePeriod());
        GregorianCalendar gcal = new GregorianCalendar();
        gcal.setTimeInMillis(System.currentTimeMillis());
        gcal.add(Calendar.HOUR, -1);
        gsr.getCoveragePeriod().setStartPoint(df.newXMLGregorianCalendar(gcal));
        gcal = new GregorianCalendar();
        gcal.setTimeInMillis(System.currentTimeMillis());
        gsr.getCoveragePeriod().setEndPoint(df.newXMLGregorianCalendar(gcal));
        tckSubscriptionJoe.subscription.getSubscriptionResults(gsr);
        Assert.fail();
    } catch (Exception ex) {
        //HandleException(ex);
        //Assert.fail();
        logger.info("Expected exception: " + ex.getMessage());
    } finally {
        TckCommon.DeleteBusiness(key, authInfoJoe, publicationJoe);
    }
}

From source file:org.apache.juddi.v3.tck.UDDI_080_SubscriptionIntegrationTest.java

/**
 * set subscription, make a change as the same user, get subscription
 * results valid find_Business// w w w .j ava2s .c  om
 *
 * @throws DatatypeConfigurationException
 */
@Test
public void JUDDI_606_13() throws DatatypeConfigurationException {
    Assume.assumeTrue(TckPublisher.isEnabled());
    System.out.println("JUDDI_606_13");
    Assume.assumeTrue(TckPublisher.isSubscriptionEnabled());

    String key = null;
    DatatypeFactory df = DatatypeFactory.newInstance();
    try {

        Holder<List<Subscription>> data = new Holder<List<Subscription>>();
        data.value = new ArrayList<Subscription>();
        Subscription sub = new Subscription();
        sub.setBrief(false);
        sub.setExpiresAfter(null);
        sub.setMaxEntities(null);
        sub.setNotificationInterval(null);
        sub.setBindingKey(null);
        sub.setSubscriptionFilter(new SubscriptionFilter());
        sub.getSubscriptionFilter().setFindBusiness(new FindBusiness());
        sub.getSubscriptionFilter().getFindBusiness().setFindQualifiers(new FindQualifiers());
        sub.getSubscriptionFilter().getFindBusiness().getFindQualifiers().getFindQualifier()
                .add(UDDIConstants.APPROXIMATE_MATCH);
        sub.getSubscriptionFilter().getFindBusiness().getName().add(new Name("%", null));
        data.value.add(sub);

        tckSubscriptionJoe.subscription.saveSubscription(authInfoJoe, data);
        SaveBusiness sb = new SaveBusiness();
        sb.setAuthInfo(authInfoJoe);
        BusinessEntity be = new BusinessEntity();
        be.getName().add(new Name("Test business", null));
        sb.getBusinessEntity().add(be);
        BusinessDetail saveBusiness = publicationJoe.saveBusiness(sb);
        key = saveBusiness.getBusinessEntity().get(0).getBusinessKey();

        GetSubscriptionResults gsr = new GetSubscriptionResults();
        gsr.setAuthInfo(authInfoJoe);
        gsr.setSubscriptionKey(data.value.get(0).getSubscriptionKey());
        gsr.setCoveragePeriod(new CoveragePeriod());
        GregorianCalendar gcal = new GregorianCalendar();
        gcal.setTimeInMillis(System.currentTimeMillis());
        gcal.add(Calendar.HOUR, -1);
        gsr.getCoveragePeriod().setStartPoint(df.newXMLGregorianCalendar(gcal));
        gcal = new GregorianCalendar();
        gcal.setTimeInMillis(System.currentTimeMillis());
        gsr.getCoveragePeriod().setEndPoint(df.newXMLGregorianCalendar(gcal));
        SubscriptionResultsList subscriptionResults = tckSubscriptionJoe.subscription
                .getSubscriptionResults(gsr);
        Assert.assertNotNull(subscriptionResults);
        Assert.assertNotNull(subscriptionResults.getBusinessList());
        Assert.assertNotNull(subscriptionResults.getCoveragePeriod());
        Assert.assertNotNull(subscriptionResults.getBusinessList().getBusinessInfos());
        Assert.assertNotNull(subscriptionResults.getBusinessList().getBusinessInfos().getBusinessInfo().get(0));
        Assert.assertNotNull(subscriptionResults.getBusinessList().getBusinessInfos().getBusinessInfo().get(0)
                .getBusinessKey());
        Assert.assertNotNull(subscriptionResults.getBusinessList().getBusinessInfos().getBusinessInfo().get(0)
                .getName().get(0));

    } catch (Exception ex) {
        HandleException(ex);
        Assert.fail();
    } finally {
        TckCommon.DeleteBusiness(key, authInfoJoe, publicationJoe);
    }
}