Example usage for org.joda.time.format DateTimeFormat forPattern

List of usage examples for org.joda.time.format DateTimeFormat forPattern

Introduction

In this page you can find the example usage for org.joda.time.format DateTimeFormat forPattern.

Prototype

public static DateTimeFormatter forPattern(String pattern) 

Source Link

Document

Factory to create a formatter from a pattern string.

Usage

From source file:com.inbravo.scribe.rest.service.crm.CRMMessageFormatUtils.java

License:Open Source License

/**
 * //  w w  w.  j ava  2  s.co  m
 * @param finishDate
 * @return
 * @throws Exception
 */
public static final DateTime validateInputDate(final String date, final String permittedDateFormats)
        throws Exception {

    logger.debug(
            "----Inside validateInputDate, date: " + date + " & permittedDateFormats: " + permittedDateFormats);

    /* Seperate all the formats */
    final String[] defaultDateFormats = permittedDateFormats.split(",");

    /* Create array for all date parsing formats */
    final DateTimeParser[] dateTimeParser = new DateTimeParser[defaultDateFormats.length];

    /* Parse with individual formats */
    for (int i = 0; i < defaultDateFormats.length; i++) {

        /* If format is valid */
        if (defaultDateFormats[i] != null && !"".equals(defaultDateFormats[i])) {

            /* Create new parser for each format */
            dateTimeParser[i] = DateTimeFormat.forPattern(defaultDateFormats[i].trim()).getParser();
        }
    }

    /* Final date formater builder */
    final DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder().append(null, dateTimeParser)
            .toFormatter();

    /* Parse user supplied date */
    final DateTime updatedDate = dateTimeFormatter.parseDateTime(date);

    logger.debug("----Inside validateInputDate, updated date: " + updatedDate);

    /* Return updated date */
    return updatedDate;
}

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   ww  w. ja va 2  s.  c om*/
    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 w  w  w.j av a  2 s  .  co 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");
    }
}

From source file:com.inbravo.scribe.rest.service.crm.zh.ZHCRMMessageFormatUtils.java

License:Open Source License

/**
 * //from  ww w. ja v  a 2  s. c  o  m
 * @param zHObjectType
 * @param iFieldName
 * @param iFieldValue
 * @param permittedDateFormats
 * @param zHInputDateFormat
 * @return
 * @throws Exception
 */
private static final String changeToZHDateFormat(final String iFieldValue, final String permittedDateFormats,
        final String zHInputDateFormat) {

    /* Change to ZOHO specific date format */
    try {
        final DateTime iDT = validateInputDate(iFieldValue, permittedDateFormats);

        /* Create ZH specific date formatter */
        final DateTimeFormatter zhDateTimeFormatter = DateTimeFormat.forPattern(zHInputDateFormat);

        /* Format the date to ZH specific */
        return zhDateTimeFormatter.print(iDT);

    } catch (final Exception e) {
        throw new ScribeException(ScribeResponseCodes._1003 + "Following date input: " + iFieldValue
                + " is not acceptable at Scribe", e);
    }
}

From source file:com.inbravo.scribe.rest.service.crm.zh.ZHCRMMessageFormatUtils.java

License:Open Source License

public static void main(String[] args) {

    final DateTimeFormatter zhDateTimeFormatter = DateTimeFormat.forPattern("yyyy/MM/dd HH:mm:ss Z");

    System.out.println(zhDateTimeFormatter.parseDateTime("2012/11/02 01:00:19 -0700"));

}

From source file:com.inspireon.dragonfly.common.logging.ExtendedDailyRollingFileAppender.java

License:Apache License

public void activateOptions() {
    super.activateOptions();

    if ((datePattern != null) && (fileName != null)) {
        //          lastCheck.setTime(System.currentTimeMillis());
        lastCheck = new DateTime();
        datePatternFormat = new SimpleDateFormat(datePattern);

        int type = computeCheckPeriod();
        printPeriodicity(type);/*from  w  w  w  .j  a  va2 s. co m*/
        rollingCalendar.setType(type);

        File file = new File(fileName);
        DateTime lastModifiedDate = new DateTime(file.lastModified());
        scheduledFilename = fileName + lastModifiedDate.toString(DateTimeFormat.forPattern(datePattern));
        //                datePatternFormat.format(new Date(file.lastModified()));
    } else {
        LogLog.error("Either File or DatePattern options are not set for appender [" + name + "].");
    }
}

From source file:com.inspireon.dragonfly.common.logging.ExtendedDailyRollingFileAppender.java

License:Apache License

int computeCheckPeriod() {
    RollingCalendar rollingCalendar = new RollingCalendar(GMT, Locale.ENGLISH);

    // set sate to 1970-01-01 00:00:00 GMT
    DateTime epoch = new DateTime(0);

    if (datePattern != null) {
        for (int i = TOP_OF_MINUTE; i <= TOP_OF_MONTH; i++) {
            //                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(datePattern);
            //                simpleDateFormat.setTimeZone(GMT); // do all date
            // formatting in GMT
            epoch = epoch.withZone(DateTimeZone.forID(Constants.TIME_ZONE_GMT));
            String r0 = epoch.toString(DateTimeFormat.forPattern(datePattern));
            //                String r0 = simpleDateFormat.format(epoch);
            rollingCalendar.setType(i);//from  w  w  w  . j av a2 s .  c  om

            DateTime next = new DateTime(rollingCalendar.getNextCheckMillis(epoch.toDate()));
            next = next.withZone(DateTimeZone.forID(Constants.TIME_ZONE_GMT));
            String r1 = next.toString(DateTimeFormat.forPattern(datePattern));
            //                String r1 = simpleDateFormat.format(next);

            if ((r0 != null) && (r1 != null) && !r0.equals(r1)) {
                return i;
            }
        }
    }

    return TOP_OF_TROUBLE; // Deliberately head for trouble...
}

From source file:com.inspireon.dragonfly.common.logging.ExtendedDailyRollingFileAppender.java

License:Apache License

/**
 * Rollover the current file to a new file.
 *///from   w  w w .j  a v  a  2 s .c  o m
void rollOver() throws IOException {
    /* Compute filename, but only if datePattern is specified */
    if (datePattern == null) {
        errorHandler.error("Missing DatePattern option in rollOver().");

        return;
    }

    String datedFilename = fileName + lastCheck.toString(DateTimeFormat.forPattern(datePattern));

    // It is too early to roll over because we are still within the
    // bounds of the current interval. Rollover will occur once the
    // next interval is reached.
    if (scheduledFilename.equals(datedFilename)) {
        return;
    }

    // close current file, and rename it to datedFilename
    this.closeFile();

    File target = new File(scheduledFilename);

    if (target.exists()) {
        target.delete();
    }

    File file = new File(fileName);
    boolean result = file.renameTo(target);

    if (result) {
        LogLog.debug(fileName + " -> " + scheduledFilename);
    } else {
        LogLog.error("Failed to rename [" + fileName + "] to [" + scheduledFilename + "].");
    }

    try {
        // This will also close the file. This is OK since multiple
        // close operations are safe.
        this.setFile(fileName, false, this.bufferedIO, this.bufferSize);
    } catch (IOException e) {
        errorHandler.error("setFile(" + fileName + ", false) call failed.");
    }

    scheduledFilename = datedFilename;
}

From source file:com.jay.pea.mhealthapp2.presenter.CustomCardViewMeds.java

License:Open Source License

/**
 * method to set up each card's views/*from www. j a va 2  s. c  o  m*/
 *
 * @param med
 */
public void setCard(Medication med) {
    //set the content for Text views of the card
    if (med.getImageRes().equals("photo")) {
        pdb = new PhotoDatabase(context);
        imageBitmap = DbBitmapUtility.getImage(pdb.getBitmapImage(med.getMedName()));
        medImage.setImageBitmap(imageBitmap);
        medImage.setBackground(null);
    } else {
        medImage.setImageResource(
                getResources().getIdentifier(med.getImageRes(), "drawable", "com.jay.pea.mhealthapp2"));
    }
    medText.setText(med.getMedString());
    if (med.getFreq() == 1) {
        doseText.setText(med.getDose() + "   Once a day");
    } else {
        doseText.setText(med.getDose() + "   " + med.getFreq() + " x a day");
    }
    DateTime start = new DateTime(med.getMedStart() * 1000l);
    DateTime end = new DateTime(med.getMedEnd() * 1000l);

    // Format for date output
    DateTimeFormatter dtf = DateTimeFormat.forPattern("dd-MMM-yy");
    String date = start.toString(dtf) + " to " + end.toString(dtf);
    dateText.setText(date);

}

From source file:com.jay.pea.mhealthapp2.presenter.MainActivity.java

License:Open Source License

/**
 * update Listview method for updating the list when the data set changes.
 *//*from   w w w.  ja va 2  s  .c om*/
public void updateListView() {
    medList = new ArrayList<>();
    medList.clear();
    dbHelper = new MedDBOpenHelper(this);
    db = dbHelper.getReadableDatabase();
    medList = dbHelper.getAllMeds();
    doseList = new ArrayList<>();
    todaysDoseList = new ArrayList<>();
    doseList.clear();
    todaysDoseList.clear();

    //get all doses and add to doseList
    for (Medication med : medList) {
        HashMap<DateTime, DateTime> doseMap1 = med.getDoseMap1();
        HashMap<DateTime, Integer> doseMap2 = med.getDoseMap2();

        for (DateTime doseDate : doseMap1.keySet()) {
            //get takenDate and alertOn
            DateTime takenDate = doseMap1.get(doseDate);
            int alertOn = doseMap2.get(doseDate);
            Dose dose = new Dose(med, doseDate, takenDate, alertOn);
            doseList.add(dose);
        }
    }

    //get today's doses
    for (Dose dose : doseList) {
        DateTimeFormatter dayFormat = DateTimeFormat.forPattern("dd MMM yyyy");
        if (dose.getDoseTime().toString(dayFormat).equals(today.toString(dayFormat))) {
            todaysDoseList.add(dose);
        }
        //sort collect, add to adaptor
        Collections.sort(todaysDoseList, new DoseComparator());
        doseListViewAdaptor = new CustomCardViewAdaptor(this, todaysDoseList);
        listView.setAdapter(doseListViewAdaptor);
    }

    //clear the alert count and dose count prefs
    alertCount = context.getSharedPreferences(PREFS_NAME_1, 0);
    editor = alertCount.edit();
    for (Medication med : medList) {
        editor.putInt(med.getMedName(), 0);
        editor.putStringSet(med.getDose(), null);
        editor.apply();
    }

    //clear the alert time prefs
    alertTimes = context.getSharedPreferences(PREFS_NAME_2, 0);
    editorTimes = alertTimes.edit();
    editorTimes.clear();
    editorTimes.apply();

    //set today's dose alerts
    for (Dose dose : todaysDoseList) {

        String doseMedName = dose.getMedication().getMedName();
        AlertManager am = new AlertManager();
        Log.d("AlertManagerMain", dose.getMedication().getMedName() + "  "
                + dose.getDoseTime().toString(dtfDate) + "  " + dose.getDoseTime().toString(dtfTime));
        am.setAlerts(context, dose);

        //record the number of alerts and save to preferences to allow safety monitor to check the number of alerts fired.
        if (alertCount.contains(doseMedName)) {
            editor.putInt(doseMedName, alertCount.getInt(doseMedName, 0) + 1);
        } else {
            editor.putInt(doseMedName, 1);
        }
        editor.apply();
        Log.d(TAG, alertCount.getInt(doseMedName, 0) + " " + doseMedName + " "
                + dose.getDoseTime().toString(dtfTime));

        String doseTime = dose.getDoseTime().toString(dtfTime);
        String doseName = dose.getMedication().getDose();

        alertTimes = context.getSharedPreferences(PREFS_NAME_2, 0);

        SharedPreferences ss = getSharedPreferences("db", 0);
        Set<String> hs = ss.getStringSet("set", new HashSet<String>());
        Set<String> in = new HashSet<String>(hs);
        in.add(String.valueOf(hs.size() + 1));
        ss.edit().putStringSet("set", in).apply(); // brevity

        //record the times of alerts and save to preferences to allow safety monitor to check the times of alerts fired.
        if (alertTimes.contains(doseName)) {
            Set<String> alertTimesHS = alertTimes.getStringSet(doseName, new HashSet<String>()); //get the existing
            Set<String> inAlertTimesHS = new HashSet<String>(alertTimesHS); //create a new set with the preferences set as the constructor
            inAlertTimesHS.add(dose.getDoseTime().toString(dtfTime)); // add to the new set this dose time
            alertTimes.edit().putStringSet(doseName, inAlertTimesHS).apply(); //save the addition to the Stringset and commit
        } else {
            Set<String> inAlertTimesHS = new HashSet<String>();
            inAlertTimesHS.add(dose.getDoseTime().toString(dtfTime));
            alertTimes.edit().putStringSet(doseName, inAlertTimesHS).apply();
        }
        editor.apply();
        Log.d(TAG, " " + doseName);
    }
}