Example usage for javax.xml.datatype DatatypeFactory newInstance

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

Introduction

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

Prototype

public static DatatypeFactory newInstance() throws DatatypeConfigurationException 

Source Link

Document

Obtain a new instance of a DatatypeFactory .

Usage

From source file:nl.clockwork.mule.ebms.util.EbMSMessageUtils.java

public static MessageHeader createMessageHeader(CollaborationProtocolAgreement cpa, EbMSMessageContext context,
        String hostname) throws DatatypeConfigurationException {
    String uuid = UUID.getUUID();
    PartyInfo sendingPartyInfo = CPAUtils.getSendingPartyInfo(cpa, context.getFromRole(),
            context.getServiceType(), context.getService(), context.getAction());
    PartyInfo receivingPartyInfo = CPAUtils.getReceivingPartyInfo(cpa, context.getToRole(),
            context.getServiceType(), context.getService(), context.getAction());
    //PartyInfo receivingPartyInfo = CPAUtils.getOtherReceivingPartyInfo(cpa,context.getFromRole(),context.getServiceType(),context.getService(),context.getAction());

    MessageHeader messageHeader = new MessageHeader();

    messageHeader.setVersion(Constants.EBMS_VERSION);
    messageHeader.setMustUnderstand(true);

    messageHeader.setCPAId(cpa.getCpaid());
    messageHeader.setConversationId(context.getConversationId() != null ? context.getConversationId() : uuid);

    messageHeader.setFrom(new From());
    PartyId from = new PartyId();
    from.setType(sendingPartyInfo.getPartyId().get(0).getType());
    from.setValue(sendingPartyInfo.getPartyId().get(0).getValue());
    messageHeader.getFrom().getPartyId().add(from);
    messageHeader.getFrom().setRole(sendingPartyInfo.getCollaborationRole().get(0).getRole().getName());

    messageHeader.setTo(new To());
    PartyId to = new PartyId();
    to.setType(receivingPartyInfo.getPartyId().get(0).getType());
    to.setValue(receivingPartyInfo.getPartyId().get(0).getValue());
    messageHeader.getTo().getPartyId().add(to);
    messageHeader.getTo().setRole(receivingPartyInfo.getCollaborationRole().get(0).getRole().getName());

    messageHeader.setService(new Service());
    messageHeader.getService()//  w  w w . ja  v a 2s.c  o  m
            .setType(sendingPartyInfo.getCollaborationRole().get(0).getServiceBinding().getService().getType());
    messageHeader.getService().setValue(
            sendingPartyInfo.getCollaborationRole().get(0).getServiceBinding().getService().getValue());
    messageHeader.setAction(sendingPartyInfo.getCollaborationRole().get(0).getServiceBinding().getCanSend()
            .get(0).getThisPartyActionBinding().getAction());

    messageHeader.setMessageData(new MessageData());
    messageHeader.getMessageData().setMessageId(uuid + "@" + hostname);
    messageHeader.getMessageData().setRefToMessageId(context.getRefToMessageId());
    messageHeader.getMessageData()
            .setTimestamp(DatatypeFactory.newInstance().newXMLGregorianCalendar(new GregorianCalendar()));

    ReliableMessaging rm = CPAUtils.getReliableMessaging(cpa, messageHeader);
    if (rm != null) {
        GregorianCalendar timestamp = messageHeader.getMessageData().getTimestamp().toGregorianCalendar();
        Duration d = rm.getRetryInterval().multiply(rm.getRetries().add(new BigInteger("1")).intValue());
        d.addTo(timestamp);
        timestamp.add(Calendar.SECOND, 1);
        messageHeader.getMessageData()
                .setTimeToLive(DatatypeFactory.newInstance().newXMLGregorianCalendar(timestamp));
    }

    DeliveryChannel channel = CPAUtils.getDeliveryChannel(sendingPartyInfo.getCollaborationRole().get(0)
            .getServiceBinding().getCanSend().get(0).getThisPartyActionBinding());

    messageHeader.setDuplicateElimination(PerMessageCharacteristicsType.ALWAYS
            .equals(channel.getMessagingCharacteristics().getDuplicateElimination()) ? "" : null);

    return messageHeader;
}

From source file:nl.clockwork.mule.ebms.util.EbMSMessageUtils.java

public static MessageHeader createMessageHeader(MessageHeader messageHeader, String hostname,
        GregorianCalendar timestamp, EbMSAction action) throws DatatypeConfigurationException {
    messageHeader = (MessageHeader) XMLUtils.xmlToObject(XMLUtils.objectToXML(messageHeader)); //FIXME: replace by more efficient copy
    List<PartyId> partyIds = new ArrayList<PartyId>(messageHeader.getFrom().getPartyId());
    messageHeader.getFrom().getPartyId().clear();
    messageHeader.getFrom().getPartyId().addAll(messageHeader.getTo().getPartyId());
    messageHeader.getTo().getPartyId().clear();
    messageHeader.getTo().getPartyId().addAll(partyIds);

    messageHeader.getFrom().setRole(null);
    messageHeader.getTo().setRole(null);

    messageHeader.getMessageData().setRefToMessageId(messageHeader.getMessageData().getMessageId());
    messageHeader.getMessageData().setMessageId(UUID.getUUID() + "@" + hostname);
    messageHeader.getMessageData()/*from ww w  . j  a  v  a 2 s  .  com*/
            .setTimestamp(DatatypeFactory.newInstance().newXMLGregorianCalendar(timestamp));
    messageHeader.getMessageData().setTimeToLive(null);

    messageHeader.setService(action.getService());
    messageHeader.setAction(action.getAction());

    messageHeader.setDuplicateElimination(null);

    return messageHeader;
}

From source file:nl.clockwork.mule.ebms.util.EbMSMessageUtils.java

private static StatusResponse createStatusResponse(StatusRequest statusRequest, EbMSMessageStatus status,
        GregorianCalendar timestamp) throws DatatypeConfigurationException {
    StatusResponse response = new StatusResponse();
    response.setVersion(Constants.EBMS_VERSION);
    response.setRefToMessageId(statusRequest.getRefToMessageId());
    if (status != null) {
        response.setMessageStatus(status.statusCode());
        if (MessageStatusType.RECEIVED.equals(status.statusCode())
                || MessageStatusType.PROCESSED.equals(status.statusCode()))
            response.setTimestamp(DatatypeFactory.newInstance().newXMLGregorianCalendar(timestamp));
    }//ww w . j  a  v  a  2  s  .  c o  m
    return response;
}

From source file:nl.nn.adapterframework.extensions.idin.IdinSender.java

@Override
public String sendMessage(String correlationID, String message, ParameterResolutionContext prc)
        throws SenderException, TimeOutException {

    Element queryElement = null;/*from  ww  w .j  av a2  s . co  m*/
    try {
        if (XmlUtils.isWellFormed(message, "idin")) {
            queryElement = XmlUtils.buildElement(message);
        } else {
            queryElement = XmlUtils.buildElement("<idin/>");
        }
    } catch (DomBuilderException e) {
        throw new SenderException(e);
    }

    XmlBuilder result = new XmlBuilder("result");
    ErrorResponse error = null;

    if (getAction().equals("DIRECTORY")) {
        DirectoryResponse response = getCommunicator().getDirectory();

        if (response.getIsError()) {
            error = response.getErrorResponse();
        } else {
            XmlBuilder issuers = new XmlBuilder("issuers");

            if (XmlUtils.getChildTagAsBoolean(queryElement, "issuersByCountry")) {
                for (Entry<String, List<Issuer>> entry : response.getIssuersByCountry().entrySet()) {
                    XmlBuilder countryXml = new XmlBuilder("country");
                    String country = entry.getKey();
                    countryXml.addAttribute("name", country);

                    for (Issuer issuer : entry.getValue()) {
                        XmlBuilder issuerXml = new XmlBuilder("issuer");
                        issuerXml.setValue(issuer.getIssuerName());
                        issuerXml.addAttribute("id", issuer.getIssuerID());
                        countryXml.addSubElement(issuerXml);
                    }
                    issuers.addSubElement(countryXml);
                }
            } else {
                for (Issuer issuer : response.getIssuers()) {
                    XmlBuilder issuerXml = new XmlBuilder("issuer");
                    issuerXml.setValue(issuer.getIssuerName());
                    issuerXml.addAttribute("id", issuer.getIssuerID());
                    issuerXml.addAttribute("country", issuer.getIssuerCountry());
                    issuers.addSubElement(issuerXml);
                }
            }
            result.addSubElement(issuers);

            XmlBuilder timestamp = new XmlBuilder("timestamp");
            Date txDate = response.getDirectoryDateTimestamp().toGregorianCalendar().getTime();
            timestamp.setValue(DateUtils.format(txDate, "yyyy-MM-dd HH:mm:ss.SSS"), false);
            result.addSubElement(timestamp);
        }

        if (StringUtils.isNotEmpty(response.getRawMessage())) {
            log.debug(response.getRawMessage());
        }
    } else if (getAction().equals("RESPONSE")) {
        String transactionID = XmlUtils.getChildTagAsString(queryElement, "transactionID");
        if (StringUtils.isEmpty(transactionID))
            throw new SenderException("no transactionID was supplied");

        StatusRequest statusRequest = new StatusRequest();
        statusRequest.setTransactionID(transactionID);
        StatusResponse response = getCommunicator().getResponse(statusRequest);

        if (response.getIsError()) {
            error = response.getErrorResponse();
        } else {
            XmlBuilder status = new XmlBuilder("status");
            status.setValue(response.getStatus(), false);
            result.addSubElement(status);

            if (response.getStatus() == StatusResponse.Success) {
                SamlResponse saml = response.getSamlResponse();
                XmlBuilder samlXml = new XmlBuilder("saml");

                XmlBuilder acquirerId = new XmlBuilder("acquirerId");
                acquirerId.setValue(saml.getAcquirerID());
                samlXml.addSubElement(acquirerId);

                XmlBuilder attributes = new XmlBuilder("attributes");
                for (Entry<String, String> entry : saml.getAttributes().entrySet()) {
                    XmlBuilder attribute = new XmlBuilder("attribute");
                    attribute.addAttribute("name", entry.getKey());
                    attribute.setValue(entry.getValue());
                    attributes.addSubElement(attribute);
                }
                samlXml.addSubElement(attributes);

                XmlBuilder merchantReference = new XmlBuilder("merchantReference");
                merchantReference.setValue(saml.getMerchantReference());
                samlXml.addSubElement(merchantReference);

                XmlBuilder version = new XmlBuilder("version");
                version.setValue(saml.getAcquirerID());
                samlXml.addSubElement(version);

                result.addSubElement(samlXml);
            }

            XmlBuilder transactionIdXml = new XmlBuilder("transactionID");
            transactionIdXml.setValue(response.getTransactionID(), false);
            result.addSubElement(transactionIdXml);

            XmlBuilder timestamp = new XmlBuilder("timestamp");
            Date txDate = response.getStatusDateTimestamp().toGregorianCalendar().getTime();
            timestamp.setValue(DateUtils.format(txDate, "yyyy-MM-dd HH:mm:ss.SSS"), false);
            result.addSubElement(timestamp);
        }

        if (StringUtils.isNotEmpty(response.getRawMessage())) {
            log.debug(response.getRawMessage());
        }
    } else if (getAction().equals("AUTHENTICATE")) {
        AuthenticationRequest authRequest = new AuthenticationRequest();

        String issuerId = XmlUtils.getChildTagAsString(queryElement, "issuerId");
        if (StringUtils.isEmpty(issuerId))
            throw new SenderException("no issuerId was supplied");
        authRequest.setIssuerID(issuerId);

        String language = XmlUtils.getChildTagAsString(queryElement, "language");
        if (StringUtils.isNotEmpty(language))
            authRequest.setLanguage(language);

        String expirationPeriod = XmlUtils.getChildTagAsString(queryElement, "expirationPeriod");
        if (StringUtils.isNotEmpty(expirationPeriod)) {
            try {
                Duration duration = DatatypeFactory.newInstance().newDuration(expirationPeriod);
                authRequest.setExpirationPeriod(duration);
            } catch (DatatypeConfigurationException e) {
                throw new SenderException(e);
            }
        }

        String requestedServiceId = XmlUtils.getChildTagAsString(queryElement, "requestedServiceId");
        if (StringUtils.isNotEmpty(requestedServiceId)) {
            authRequest.setRequestedServiceID(new ServiceId(requestedServiceId));
        }

        String merchantReference = XmlUtils.getChildTagAsString(queryElement, "merchantReference");
        if (StringUtils.isNotEmpty(requestedServiceId))
            authRequest.setMerchantReference(merchantReference);

        AssuranceLevel assuranceLevel = AssuranceLevel.Loa3;
        String assurance = XmlUtils.getChildTagAsString(queryElement, "assuranceLevel");
        if (StringUtils.isNotEmpty(assurance))
            assuranceLevel = AssuranceLevel.valueOf(assurance);
        authRequest.setAssuranceLevel(assuranceLevel);

        String entranceCode = XmlUtils.getChildTagAsString(queryElement, "entranceCode");
        if (StringUtils.isNotEmpty(entranceCode))
            authRequest.setEntranceCode(entranceCode);

        AuthenticationResponse response = getCommunicator().newAuthenticationRequest(authRequest);
        if (response.getIsError()) {
            error = response.getErrorResponse();
        } else {
            XmlBuilder authenticationURL = new XmlBuilder("authenticationURL");
            authenticationURL.setValue(response.getIssuerAuthenticationURL(), false);
            result.addSubElement(authenticationURL);

            XmlBuilder transactionIdXml = new XmlBuilder("transactionID");
            transactionIdXml.setValue(response.getTransactionID(), false);
            result.addSubElement(transactionIdXml);

            XmlBuilder creationTime = new XmlBuilder("creationTime");
            Date txDate = response.getTransactionCreateDateTimestamp().toGregorianCalendar().getTime();
            creationTime.setValue(DateUtils.format(txDate, "yyyy-MM-dd HH:mm:ss.SSS"), false);
            result.addSubElement(creationTime);
        }

        if (StringUtils.isNotEmpty(response.getRawMessage())) {
            log.debug(response.getRawMessage());
        }
    }

    if (error != null) {
        XmlBuilder errorXml = new XmlBuilder("error");
        XmlBuilder statusCodeXml = new XmlBuilder("statusCode");
        statusCodeXml.setValue(error.getErrorCode());
        errorXml.addSubElement(statusCodeXml);

        XmlBuilder detailsXml = new XmlBuilder("details");
        detailsXml.setValue(error.getErrorDetails());
        errorXml.addSubElement(detailsXml);

        XmlBuilder messageXml = new XmlBuilder("message");
        messageXml.setValue(error.getErrorMessage());
        errorXml.addSubElement(messageXml);

        result.addSubElement(errorXml);
    }

    return result.toXML();
}

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

/**
 * Creates a new XMLGregorianCalendar from the given java.sql.Timestamp.
 * /* w  w  w  . j  ava2  s .c om*/
 * @param time
 *            The timestamp to convert.
 * @return The XML calendar object representing the given timestamp.
 * @throws ImplementationExceptionResponse
 *             If an error occurred when parsing the given timestamp into a
 *             calendar instance.
 */
private XMLGregorianCalendar timestampToXmlCalendar(Timestamp time) throws ImplementationExceptionResponse {
    try {
        DatatypeFactory factory = DatatypeFactory.newInstance();
        Calendar cal = TimeParser.convert(time);
        return factory.newXMLGregorianCalendar((GregorianCalendar) cal);
    } catch (DatatypeConfigurationException e) {
        String msg = "Unable to instantiate an XML representation for a date/time datatype.";
        ImplementationException iex = new ImplementationException();
        iex.setReason(msg);
        iex.setSeverity(ImplementationExceptionSeverity.SEVERE);
        throw new ImplementationExceptionResponse(msg, iex, e);
    }
}

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.//  w w w.  j ava  2s  .  c o m
 * 
 * @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;//w w w.ja va  2  s . c  o 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;/*from   w ww . ja va2  s  .  c  o  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.ambari.controller.Clusters.java

public List<Node> getClusterNodes(String clusterName, String roleName, String alive) throws Exception {

    List<Node> list = new ArrayList<Node>();
    Map<String, Node> nodeMap = nodes.getNodes();
    ClusterDefinition c = operational_clusters.get(clusterName).getClusterDefinition(-1);
    if (c.getNodes() == null || c.getNodes().equals("")
            || getClusterByName(clusterName).getClusterState().getState().equalsIgnoreCase("ATTIC")) {
        String msg = "No nodes are reserved for the cluster. Typically"
                + " cluster in ATTIC state does not have any nodes reserved";
        throw new WebApplicationException((new ExceptionResponse(msg, Response.Status.NO_CONTENT)).get());
    }/*from w  w w .j a  v a2  s .  co m*/
    List<String> hosts = getHostnamesFromRangeExpressions(c.getNodes());
    for (String host : hosts) {
        if (!nodeMap.containsKey(host)) {
            String msg = "Node [" + host + "] is expected to be registered w/ controller but not "
                    + "locatable";
            throw new WebApplicationException(
                    (new ExceptionResponse(msg, Response.Status.INTERNAL_SERVER_ERROR)).get());
        }
        Node n = nodeMap.get(host);
        if (roleName != null && !roleName.equals("")) {
            if (n.getNodeState().getNodeRoleNames("") == null) {
                continue;
            }
            if (!n.getNodeState().getNodeRoleNames("").contains(roleName)) {
                continue;
            }
        }

        // Heart beat is set to epoch during node initialization.
        GregorianCalendar cal = new GregorianCalendar();
        cal.setTime(new Date());
        XMLGregorianCalendar curTime = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
        if (alive.equals("")
                || (alive.equalsIgnoreCase("true") && Nodes.getTimeDiffInMillis(curTime,
                        n.getNodeState().getLastHeartbeatTime()) < Nodes.NODE_NOT_RESPONDING_DURATION)
                || (alive.equals("false") && Nodes.getTimeDiffInMillis(curTime,
                        n.getNodeState().getLastHeartbeatTime()) >= Nodes.NODE_NOT_RESPONDING_DURATION)) {
            list.add(nodeMap.get(host));
        }
    }
    return list;
}

From source file:org.apache.cxf.management.web.browser.bootstrapping.SimpleXMLSettingsStorage.java

private XMLGregorianCalendar getCurrentTime() {
    try {/*from  www.j a va  2s . co  m*/
        return DatatypeFactory.newInstance()
                .newXMLGregorianCalendar((GregorianCalendar) GregorianCalendar.getInstance());
    } catch (DatatypeConfigurationException e) {
        throw new RuntimeException(e);
    }
}