Example usage for org.joda.time DateTime now

List of usage examples for org.joda.time DateTime now

Introduction

In this page you can find the example usage for org.joda.time DateTime now.

Prototype

public static DateTime now(Chronology chronology) 

Source Link

Document

Obtains a DateTime set to the current system millisecond time using the specified chronology.

Usage

From source file:com.inbravo.scribe.rest.service.crm.ms.auth.MSOffice365AuthManager.java

License:Open Source License

@Override
public final String[] getCRMAuthToken(final ScribeCacheObject cacheObject) throws Exception {

    String stsEndpoint = null;/*from   w  w  w. ja v  a 2s  .com*/
    String urnAddress = null;
    String userName = null;
    String password = null;
    String crmServiceURL = null;
    String crmServiceProtocal = null;

    logger.debug("----Inside getCRMAuthToken for agent: " + cacheObject.getScribeMetaObject().getCrmUserId());

    /* Check if additonal info is present */
    if (cacheObject.getAdditionalInfo() != null) {

        /* Parse the reponse */
        stsEndpoint = cacheObject.getAdditionalInfo().get("STSEnpoint");
        urnAddress = cacheObject.getAdditionalInfo().get("URNAddress");
    }

    /* get CRM credentials */
    userName = cacheObject.getScribeMetaObject().getCrmUserId();
    password = cacheObject.getScribeMetaObject().getCrmPassword();
    crmServiceURL = cacheObject.getScribeMetaObject().getCrmServiceURL();
    crmServiceProtocal = cacheObject.getScribeMetaObject().getCrmServiceProtocol();

    logger.debug("----Inside getCRMAuthToken userName: " + userName + " & password: " + password
            + " & stsEndpoint: " + stsEndpoint + " & urnAddress: " + urnAddress + " & crmServiceURL: "
            + crmServiceURL + " & crmServiceProtocal: " + crmServiceProtocal);

    final URL fileURL = CRMMessageFormatUtils.getFileURL(loginFileName);

    String msg = null;
    try {

        /* Get SAML from login */
        if (samlForMSLogin == null) {

            logger.debug("----Inside getCRMAuthToken reading security template from file");

            /* This logic is for reading the file once in lifetime only */
            samlForMSLogin = MSCRMMessageFormatUtils.readStringFromFile(fileURL.getPath());

            /* Convert for local usage */
            msg = samlForMSLogin;
        } else {
            logger.debug("----Inside getCRMAuthToken reading security template from memory");

            /* Convert for local usage */
            msg = samlForMSLogin;
        }

        /* This is a trick to avoid error if password contains '$' */
        userName = Matcher.quoteReplacement(userName);
        password = Matcher.quoteReplacement(password);

        logger.debug("----Inside getCRMAuthToken userName: " + userName + " & password: " + password
                + " & stsEndpoint: " + stsEndpoint);

        /* Get DB specific formatter */
        final DateTimeFormatter isoDateFormat = DateTimeFormat.forPattern(msOffice365RequestDateFormat);

        /* Get current time */
        final String currentDateTime = isoDateFormat
                .print(DateTime.now(DateTimeZone.forID((msOffice365RequestTimeZone))));

        /* Add 5 minutes expiry time from now */
        final String expireDateTime = isoDateFormat.print(DateTime
                .now(DateTimeZone.forID((msOffice365RequestTimeZone))).plusMinutes(loginExpirationInMinutes));

        /* The final customer specific security header */
        msg = String.format(msg, UUID.randomUUID().toString(), "ACQA", stsEndpoint, currentDateTime,
                expireDateTime, userName, password, urnAddress);

        logger.debug("----Inside getCRMAuthToken, login request: " + msg);

        /* Send SOAP message */
        final String response = sOAPExecutor.getSOAPResponse(stsEndpoint, msg);

        logger.debug("----Inside getCRMAuthToken, login response: " + response);

        /* If a valid response */
        if (response != null && !response.contains("internalerror")) {

            /* Extract all the values from response */
            final String securityToken0 = MSCRMMessageFormatUtils.getValueFromXML(response,
                    "//*[local-name()='CipherValue']/text()");
            final String securityToken1 = MSCRMMessageFormatUtils.getValueFromXML(response,
                    "//*[local-name()='CipherValue']/text()", 1);
            final String keyIdentifier = MSCRMMessageFormatUtils.getValueFromXML(response,
                    "//*[local-name()='KeyIdentifier']/text()");

            logger.debug("----Inside getCRMAuthToken securityToken0: " + securityToken0 + " & securityToken1: "
                    + securityToken1 + " & keyIdentifier: " + keyIdentifier);
            return new String[] { securityToken0, securityToken1, keyIdentifier };
        } else {

            /* Extract all the values from response */
            final String error = MSCRMMessageFormatUtils.getValueFromXML(response,
                    "//*[local-name()='Reason' and namespace-uri()='http://www.w3.org/2003/05/soap-envelope']/*[local-name()='Text' and namespace-uri()='http://www.w3.org/2003/05/soap-envelope']/text()");

            throw new ScribeException(ScribeResponseCodes._1012 + " MS Login request failed : " + error);
        }

    } catch (final IOException e) {
        throw new ScribeException(
                ScribeResponseCodes._1015 + " Not able to connect to office 365 login server: " + stsEndpoint);
    }
}

From source file:com.inbravo.scribe.rest.service.crm.ms.v5.MSCRMOffice365basedServiceManager.java

License:Open Source License

/**
 * //from www  .  ja va  2  s. c  o m
 * @param securityTokens
 * @return
 */
private final SOAPHeaderBlock[] createCRMOptionsHeaderBlock(final String organizationServiceURL,
        final String[] securityTokens, final String msCRMOperationType) {

    /* Get DB specific formatter */
    final DateTimeFormatter isoDateFormat = DateTimeFormat.forPattern(msOffice365RequestDateFormat);

    /* Get current time */
    final String currentDateTime = isoDateFormat
            .print(DateTime.now(DateTimeZone.forID((msOffice365RequestTimeZone))));

    /* Add 5 minutes expiry time from now */
    final String expireDateTime = isoDateFormat.print(DateTime
            .now(DateTimeZone.forID((msOffice365RequestTimeZone))).plusMinutes(loginExpirationInMinutes));

    /* The final customer specific security header */
    final String securityHeader = String.format(MSCRMSchemaConstants.securityHeaderTemplate, securityTokens[2],
            securityTokens[0], securityTokens[1]);

    try {

        /* Create new factory */
        final OMFactory factory = OMAbstractFactory.getOMFactory();

        /* Create security/addressing headers */
        final OMNamespace addressingNS = factory.createOMNamespace(MSCRM_SAML_Constants._ADDRESSING, "a");
        final OMNamespace securityNS = factory.createOMNamespace(MSCRM_SAML_Constants._WSSSecurity, "o");
        final OMNamespace utitlityNS = factory.createOMNamespace(MSCRM_SAML_Constants._WSSSecurityUtility, "u");

        final OMElement timeStamp = factory.createOMElement("Timestamp", utitlityNS);
        timeStamp.addAttribute("Id", "_0", utitlityNS);

        /* Add created timestamp information */
        final OMElement created = factory.createOMElement("Created", utitlityNS);
        final OMText createdTime = factory.createOMText(currentDateTime + "Z");
        created.addChild(createdTime);

        /* Add expires timestamp information */
        final OMElement expires = factory.createOMElement("Expires", utitlityNS);
        final OMText expiresTime = factory.createOMText(expireDateTime + "Z");
        expires.addChild(expiresTime);

        timeStamp.addChild(created);
        timeStamp.addChild(expires);

        /* Create security header block */
        final SOAPHeaderBlock wsseHeader = OMAbstractFactory.getSOAP12Factory()
                .createSOAPHeaderBlock("Security", securityNS);
        wsseHeader.setMustUnderstand(true);

        /* Add time validity information */
        wsseHeader.addChild(timeStamp);
        wsseHeader.addChild(AXIOMUtil.stringToOM(factory, securityHeader));

        /* Create action header block for action */
        final SOAPHeaderBlock actionHeader = OMAbstractFactory.getSOAP12Factory()
                .createSOAPHeaderBlock("Action", addressingNS);
        actionHeader.setMustUnderstand(true);
        final OMText actionText = factory
                .createOMText(MSCRM_2011_Schema_Constants._IORGANIZATIONSERVICE + msCRMOperationType);
        actionHeader.addChild(actionText);

        /* Create messageId header block for action */
        final SOAPHeaderBlock messageIdHeader = OMAbstractFactory.getSOAP12Factory()
                .createSOAPHeaderBlock("MessageID", addressingNS);
        final OMText messageIdText = factory.createOMText(UUID.randomUUID().toString());
        messageIdHeader.addChild(messageIdText);

        /* Create replyTo header block for action */
        final SOAPHeaderBlock replyToHeader = OMAbstractFactory.getSOAP12Factory()
                .createSOAPHeaderBlock("ReplyTo", addressingNS);
        final OMElement address = factory.createOMElement("Address", addressingNS);
        final OMText addressText = factory.createOMText("http://www.w3.org/2005/08/addressing/anonymous");
        address.addChild(addressText);
        replyToHeader.addChild(address);

        /* Create To header block for action */
        final SOAPHeaderBlock toHeader = OMAbstractFactory.getSOAP12Factory().createSOAPHeaderBlock("To",
                addressingNS);
        toHeader.setMustUnderstand(true);
        final OMText toText = factory.createOMText(organizationServiceURL);
        toHeader.addChild(toText);

        return new SOAPHeaderBlock[] { actionHeader, messageIdHeader, replyToHeader, toHeader, wsseHeader };

    } catch (final XMLStreamException e) {
        throw new ScribeException(ScribeResponseCodes._1015
                + "Problem in adding security information to SOAP request to MS office 365 login server");
    }
}