Example usage for org.joda.time.format ISODateTimeFormat dateTime

List of usage examples for org.joda.time.format ISODateTimeFormat dateTime

Introduction

In this page you can find the example usage for org.joda.time.format ISODateTimeFormat dateTime.

Prototype

public static DateTimeFormatter dateTime() 

Source Link

Document

Returns a formatter that combines a full date and time, separated by a 'T' (yyyy-MM-dd'T'HH:mm:ss.SSSZZ).

Usage

From source file:org.phenotips.vocabulary.internal.GeneNomenclature.java

License:Open Source License

private void addMetaInfo(Collection<SolrInputDocument> data) {
    SolrInputDocument metaTerm = new SolrInputDocument();
    metaTerm.addField(ID_FIELD_NAME, "HEADER_INFO");
    metaTerm.addField(VERSION_FIELD_NAME, ISODateTimeFormat.dateTime().withZoneUTC().print(new DateTime()));
    data.add(metaTerm);//from  w w  w  . java 2s.  co  m
}

From source file:org.phenotips.vocabulary.internal.solr.MendelianInheritanceInMan.java

License:Open Source License

private void loadVersion() {
    SolrInputDocument metaTerm = new SolrInputDocument();
    metaTerm.addField(ID_FIELD, "HEADER_INFO");
    metaTerm.addField("version", ISODateTimeFormat.dateTime().withZoneUTC().print(new DateTime()));
    this.data.put("VERSION", metaTerm);
}

From source file:org.projectbuendia.client.net.OpenMrsXformsConnection.java

License:Apache License

/**
 * Send a single Xform to the OpenMRS server.
 *
 * @param patientUuid null if this is to add a new patient, non-null for observation on existing
 *                  patient//  w  ww  .ja  v  a 2  s  .c  o  m
 * @param resultListener the listener to be informed of the form asynchronously
 * @param errorListener a listener to be informed of any errors
 */
public void postXformInstance(@Nullable String patientUuid, String xform,
        final Response.Listener<JSONObject> resultListener, Response.ErrorListener errorListener) {

    // The JsonObject members in the API as written at the moment.
    // int "patient_id"
    // int "enterer_id"
    // String "date_entered" in ISO8601 format (1977-01-10T
    // String "xml" the form.
    JsonObject post = new JsonObject();
    post.addProperty("xml", xform);
    // Don't add patient property for create new patient
    if (patientUuid != null) {
        post.addProperty("patient_uuid", patientUuid);
    }
    // TODO: get the enterer from the user login
    post.addProperty("enterer_id", 1);

    post.addProperty("date_entered", ISODateTimeFormat.dateTime().print(new DateTime()));
    JSONObject postBody = null;
    try {
        postBody = new JSONObject(post.toString());
    } catch (JSONException e) {
        LOG.e(e, "This should never happen converting one JSON object to another. " + post);
        errorListener.onErrorResponse(new VolleyError("failed to convert to JSON", e));
    }
    OpenMrsJsonRequest request = new OpenMrsJsonRequest(mConnectionDetails, "/xforminstance", postBody, // non-null implies POST
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    resultListener.onResponse(response);
                }
            }, errorListener);
    // Set a permissive timeout.
    request.setRetryPolicy(new DefaultRetryPolicy(Common.REQUEST_TIMEOUT_MS_MEDIUM, 1, 1f));
    mConnectionDetails.getVolley().addToRequestQueue(request);
}

From source file:org.projectbuendia.client.ui.OdkActivityLauncher.java

License:Apache License

private static void updateClientCache(String patientUuid, TreeElement savedRoot, ContentResolver resolver) {
    // id, fill in auto
    // patient uuid: context
    // encounter uuid: make one up
    // encounter time:
    //   <encounter>
    //     <encounter.encounter_datetime>2014-12-15T13:33:00.000Z</encounter.encounter_datetime>
    // concept uuid:
    //   <vitals>
    //     <!-- Concept UUID is 5088 -->
    //     <temperature_c openmrs_concept="5088^Temperature (C)^99DCT" openmrs_datatype="NM">
    // value://from   w  ww . j a v a  2s .c  o  m
    //   <vitals>
    //     <temperature_c openmrs_concept="5088^Temperature (C)^99DCT" openmrs_datatype="NM">
    //       <value>36.0</value>
    // temp_cache: true

    // or for coded
    // <symptoms_abinaryinvisible>
    //   <weakness multiple="0" openmrs_concept="5226^WEAKNESS^99DCT" openmrs_datatype="CWE">
    //      <value>1066^NO^99DCT</value>

    ContentValues common = new ContentValues();
    common.put(Contracts.Observations.PATIENT_UUID, patientUuid);

    TreeElement encounter = savedRoot.getChild("encounter", 0);
    if (encounter == null) {
        LOG.e("No encounter found in instance");
        return;
    }

    TreeElement encounterDatetime = encounter.getChild("encounter.encounter_datetime", 0);
    if (encounterDatetime == null) {
        LOG.e("No encounter date time found in instance");
        return;
    }
    IAnswerData dateTimeValue = encounterDatetime.getValue();
    try {

        DateTime encounterTime = ISODateTimeFormat.dateTime().parseDateTime((String) dateTimeValue.getValue());
        long secondsSinceEpoch = encounterTime.getMillis() / 1000L;
        common.put(Contracts.Observations.ENCOUNTER_TIME, secondsSinceEpoch);
        common.put(Contracts.Observations.ENCOUNTER_UUID, UUID.randomUUID().toString());
        common.put(Contracts.Observations.TEMP_CACHE, 1);
    } catch (IllegalArgumentException e) {
        LOG.e("Could not parse datetime" + dateTimeValue.getValue());
        return;
    }

    ArrayList<ContentValues> toInsert = new ArrayList<>();
    HashSet<Integer> xformConceptIds = new HashSet<>();
    for (int i = 0; i < savedRoot.getNumChildren(); i++) {
        TreeElement group = savedRoot.getChildAt(i);
        if (group.getNumChildren() == 0) {
            continue;
        }
        for (int j = 0; j < group.getNumChildren(); j++) {
            TreeElement question = group.getChildAt(j);
            TreeElement openmrsConcept = question.getAttribute(null, "openmrs_concept");
            TreeElement openmrsDatatype = question.getAttribute(null, "openmrs_datatype");
            if (openmrsConcept == null || openmrsDatatype == null) {
                continue;
            }
            // Get the concept for the question.
            // eg "5088^Temperature (C)^99DCT"
            String encodedConcept = (String) openmrsConcept.getValue().getValue();
            Integer id = getConceptId(xformConceptIds, encodedConcept);
            if (id == null) {
                continue;
            }
            // Also get for the answer if a coded question
            String value;
            TreeElement valueChild = question.getChild("value", 0);
            IAnswerData answer = valueChild.getValue();
            if (answer == null) {
                continue;
            }
            Object answerObject = answer.getValue();
            if (answerObject == null) {
                continue;
            }
            if ("CWE".equals(openmrsDatatype.getValue().getValue())) {
                value = getConceptId(xformConceptIds, answerObject.toString()).toString();
            } else {
                value = answerObject.toString();
            }

            ContentValues observation = new ContentValues(common);
            // Set to the id for now, we'll replace with uuid later
            observation.put(Contracts.Observations.CONCEPT_UUID, id.toString());
            observation.put(Contracts.Observations.VALUE, value);
            toInsert.add(observation);
        }
    }

    String inClause = Joiner.on(",").join(xformConceptIds);
    // Get a map from client ids to UUIDs from our local concept database.
    HashMap<String, String> idToUuid = new HashMap<>();
    Cursor cursor = resolver.query(Contracts.Concepts.CONTENT_URI,
            new String[] { Contracts.Concepts._ID, Contracts.Concepts.XFORM_ID },
            Contracts.Concepts.XFORM_ID + " IN (" + inClause + ")", null, null);
    try {
        while (cursor.moveToNext()) {
            idToUuid.put(cursor.getString(cursor.getColumnIndex(Contracts.Concepts.XFORM_ID)),
                    cursor.getString(cursor.getColumnIndex(Contracts.Concepts._ID)));
        }
    } finally {
        cursor.close();
    }

    // Remap concept ids to uuids, skipping anything we can't remap.
    for (Iterator<ContentValues> i = toInsert.iterator(); i.hasNext();) {
        ContentValues values = i.next();
        if (!mapIdToUuid(idToUuid, values, Contracts.Observations.CONCEPT_UUID)) {
            i.remove();
        }
        mapIdToUuid(idToUuid, values, Contracts.Observations.VALUE);
    }
    resolver.bulkInsert(Contracts.Observations.CONTENT_URI,
            toInsert.toArray(new ContentValues[toInsert.size()]));
}

From source file:org.projecthdata.social.api.Root.java

License:Apache License

/**
 * Gets the value of the created property.
 * //from  www. j  ava 2s .  c o  m
 * @return possible object is {@link java.util.Date }
 * 
 */
@Element
public String getCreated() {
    return created.toString(ISODateTimeFormat.dateTime());
}

From source file:org.projecthdata.social.api.Root.java

License:Apache License

/**
 * Gets the value of the lastModified property.
 * //from w ww .  j a v a2s .c o m
 * @return possible object is {@link java.util.Date }
 * 
 */
@Element
public String getLastModified() {
    return lastModified.toString(ISODateTimeFormat.dateTime());
}

From source file:org.sakaiproject.accountvalidator.tool.otp.AcountValidationLocator.java

License:Educational Community License

public String validateAccount() {
    log.debug("Validate Account");

    List<String> userReferences = new ArrayList<String>();

    for (Iterator<String> it = delivered.keySet().iterator(); it.hasNext();) {

        String key = (String) it.next();

        ValidationAccount item = (ValidationAccount) delivered.get(key);
        if (ValidationAccount.STATUS_CONFIRMED.equals(item.getStatus())
                || ValidationAccount.STATUS_EXPIRED.equals(item.getStatus())) {
            return "error";
        }/*from   ww w. j  a v  a2  s  .  com*/
        log.debug("Validating Item: " + item.getId() + " for user: " + item.getUserId());
        String firstName = item.getFirstName();
        String surname = item.getSurname();
        if (firstName != null) {
            firstName = firstName.trim();
        }
        if (surname != null) {
            surname = surname.trim();
        }

        int accountStatus = item.getAccountStatus();
        //names are required in all cases except password resets
        if (ValidationAccount.ACCOUNT_STATUS_NEW == accountStatus
                || ValidationAccount.ACCOUNT_STATUS_LEGACY_NOPASS == accountStatus
                || ValidationAccount.ACCOUNT_STATUS_REQUEST_ACCOUNT == accountStatus) {
            if (firstName == null || firstName.isEmpty()) {
                tml.addMessage(new TargettedMessage("firstname.required", new Object[] {},
                        TargettedMessage.SEVERITY_ERROR));
                return "error";
            }
            if (surname == null || surname.isEmpty()) {
                tml.addMessage(new TargettedMessage("lastname.required", new Object[] {},
                        TargettedMessage.SEVERITY_ERROR));
                return "error";
            }
        }

        log.debug(firstName + " " + surname);
        log.debug("this is an new item?: " + item.getAccountStatus());
        try {
            String userId = EntityReference.getIdFromRef(item.getUserId());
            //we need permission to edit this user

            //if this is an existing user did the password match?
            if (ValidationAccount.ACCOUNT_STATUS_EXISITING == item.getAccountStatus()
                    && !validateLogin(userId, item.getPassword())) {
                tml.addMessage(new TargettedMessage("validate.invalidPassword", new Object[] {},
                        TargettedMessage.SEVERITY_ERROR));
                return "error";
            }
            securityService.pushAdvisor(new SecurityAdvisor() {
                public SecurityAdvice isAllowed(String userId, String function, String reference) {
                    if (function.equals(UserDirectoryService.SECURE_UPDATE_USER_ANY)) {
                        return SecurityAdvice.ALLOWED;
                    } else {
                        return SecurityAdvice.NOT_ALLOWED;
                    }
                }
            });

            if (validationLogic.isTokenExpired(item)) {
                // A TargettedMessage will be displayed by ValidationProducer
                return "error!";
            }

            UserEdit u = userDirectoryService.editUser(userId);
            if (isLegacyLinksEnabled() || ValidationAccount.ACCOUNT_STATUS_PASSWORD_RESET != accountStatus) {
                //We always can change names if legacy links is enabled. Otherwise in the new forms, we can't change names during password resets
                u.setFirstName(firstName);
                u.setLastName(surname);
            }
            ResourcePropertiesEdit rp = u.getPropertiesEdit();
            DateTime dt = new DateTime();
            DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
            rp.addProperty("AccountValidated", fmt.print(dt));

            //if this is a new account set the password
            if (ValidationAccount.ACCOUNT_STATUS_NEW == accountStatus
                    || ValidationAccount.ACCOUNT_STATUS_LEGACY_NOPASS == accountStatus
                    || ValidationAccount.ACCOUNT_STATUS_PASSWORD_RESET == accountStatus
                    || ValidationAccount.ACCOUNT_STATUS_REQUEST_ACCOUNT == accountStatus) {
                if (item.getPassword() == null || !item.getPassword().equals(item.getPassword2())) {
                    //Abandon the edit
                    userDirectoryService.cancelEdit(u);
                    tml.addMessage(new TargettedMessage("validate.passNotMatch", new Object[] {},
                            TargettedMessage.SEVERITY_ERROR));
                    return "error!";
                }

                // bbailla2, bjones86 - SAK-22427
                if (userDirectoryService.getPasswordPolicy() != null) {
                    PasswordRating rating = userDirectoryService.validatePassword(item.getPassword(), u);
                    if (PasswordRating.FAILED.equals(rating)) {
                        userDirectoryService.cancelEdit(u);
                        tml.addMessage(new TargettedMessage("validate.password.fail", new Object[] {},
                                TargettedMessage.SEVERITY_ERROR));
                        return "error!";
                    }
                }

                u.setPassword(item.getPassword());

                // Do they have to accept terms and conditions.
                if (!"".equals(serverConfigurationService.getString("account-validator.terms"))) {
                    //terms and conditions are only relevant for new accounts (unless we're using the legacy links)
                    boolean checkTerms = ValidationAccount.ACCOUNT_STATUS_NEW == accountStatus
                            || isLegacyLinksEnabled();
                    if (checkTerms) {
                        // Check they accepted the terms.
                        if (item.getTerms().booleanValue()) {
                            u.getPropertiesEdit().addProperty("TermsAccepted", "true");
                        } else {
                            userDirectoryService.cancelEdit(u);
                            tml.addMessage(new TargettedMessage("validate.acceptTerms", new Object[] {},
                                    TargettedMessage.SEVERITY_ERROR));
                            return "error!";
                        }
                    }
                }
            }

            userDirectoryService.commitEdit(u);

            //update the Validation object
            item.setvalidationReceived(new Date());
            item.setStatus(ValidationAccount.STATUS_CONFIRMED);
            log.debug("Saving now ...");

            //post an event
            developerHelperService.fireEvent("accountvalidation.validated", u.getReference());

            validationLogic.save(item);

            userReferences.add(userDirectoryService.userReference(item.getUserId()));

            //log the user in
            Evidence e = new ExternalTrustedEvidence(u.getEid());
            try {
                Authentication a = authenticationManager.authenticate(e);
                log.debug("authenticated " + a.getEid() + "(" + a.getUid() + ")");
                log.debug("reg: " + httpServletRequest.getRemoteAddr());
                log.debug("user agent: " + httpServletRequest.getHeader("user-agent"));
                usageSessionService.login(a, httpServletRequest);
            } catch (AuthenticationException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

        } catch (UserNotDefinedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UserPermissionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UserLockedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UserAlreadyDefinedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            securityService.popAdvisor();
        }

        //validationLogic.

        // Send password reset acknowledgement email for password reset scenarios
        if (ValidationAccount.ACCOUNT_STATUS_PASSWORD_RESET == accountStatus) {
            String supportEmail = serverConfigurationService.getString("support.email");
            Map<String, String> replacementValues = new HashMap<String, String>();
            replacementValues.put("emailSupport", supportEmail);
            emailTemplateService.sendRenderedMessages(TEMPLATE_KEY_ACKNOWLEDGE_PASSWORD_RESET, userReferences,
                    replacementValues, supportEmail, supportEmail);
        }
    }

    return "success";
}

From source file:org.sakaiproject.tool.assessment.ui.bean.delivery.SectionContentsBean.java

License:Educational Community License

public void setMetaData(SectionDataIfc section) {

    if (section.getSectionMetaDataByLabel(SectionDataIfc.AUTHOR_TYPE) != null) {
        Integer authortype = new Integer(section.getSectionMetaDataByLabel(SectionDataIfc.AUTHOR_TYPE));
        setSectionAuthorType(authortype);

        if (section.getSectionMetaDataByLabel(SectionDataIfc.AUTHOR_TYPE)
                .equals(SectionDataIfc.RANDOM_DRAW_FROM_QUESTIONPOOL.toString())) {
            if (section.getSectionMetaDataByLabel(SectionDataIfc.NUM_QUESTIONS_DRAWN) != null) {
                Integer numberdrawn = new Integer(
                        section.getSectionMetaDataByLabel(SectionDataIfc.NUM_QUESTIONS_DRAWN));
                setNumberToBeDrawn(numberdrawn);
            }/*ww  w  . j a  v a2  s  . com*/

            if (section.getSectionMetaDataByLabel(SectionDataIfc.POOLID_FOR_RANDOM_DRAW) != null) {
                Long poolid = new Long(
                        section.getSectionMetaDataByLabel(SectionDataIfc.POOLID_FOR_RANDOM_DRAW));
                setPoolIdToBeDrawn(poolid);
            }
            if (section.getSectionMetaDataByLabel(SectionDataIfc.POOLNAME_FOR_RANDOM_DRAW) != null) {
                String poolname = section.getSectionMetaDataByLabel(SectionDataIfc.POOLNAME_FOR_RANDOM_DRAW);
                setPoolNameToBeDrawn(poolname);

                String randomDrawDate = section
                        .getSectionMetaDataByLabel(SectionDataIfc.QUESTIONS_RANDOM_DRAW_DATE);
                if (randomDrawDate != null && !"".equals(randomDrawDate)) {

                    try {

                        // bjones86 - SAM-1604
                        DateTime drawDate;
                        DateTimeFormatter fmt = ISODateTimeFormat.dateTime(); //The Date Time is in ISO format
                        try {
                            drawDate = fmt.parseDateTime(randomDrawDate);
                        } catch (Exception ex) {
                            Date date = null;
                            try {
                                // Old code produced dates that appeard like java.util.Date.toString() in the database
                                // This means it's possible that the database contains dates in multiple formats
                                // We'll try parsing Date.toString()'s format first.
                                // Date.toString is locale independent. So this SimpleDateFormat using Locale.US should guarantee that this works on all machines:
                                DateFormat df = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
                                // parse can either throw an exception or return null
                                date = df.parse(randomDrawDate);
                            } catch (Exception e) {
                                // failed to parse. Not worth logging yet because we will try again with another format
                            }

                            if (date == null) {
                                DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZ");
                                // If this throws an exception, it's caught below. This is appropriate.
                                date = df.parse(randomDrawDate);
                            }

                            if (date == null) {
                                // Nothing has worked
                                throw new IllegalArgumentException("Unable to parse date " + randomDrawDate);
                            } else {
                                drawDate = new DateTime(date);
                            }
                        }

                        //We need the locale to localize the output string
                        Locale loc = new ResourceLoader().getLocale();
                        String drawDateString = DateTimeFormat.fullDate().withLocale(loc).print(drawDate);
                        String drawTimeString = DateTimeFormat.fullTime().withLocale(loc).print(drawDate);
                        setRandomQuestionsDrawDate(drawDateString);
                        setRandomQuestionsDrawTime(drawTimeString);

                    } catch (Exception e) {
                        log.error("Unable to parse date text: " + randomDrawDate, e);
                    }
                }
            }
        }

    } else {

        setSectionAuthorType(SectionDataIfc.QUESTIONS_AUTHORED_ONE_BY_ONE);
    }
    if (section.getSectionMetaDataByLabel(SectionDataIfc.QUESTIONS_ORDERING) != null) {
        Integer questionorder = new Integer(
                section.getSectionMetaDataByLabel(SectionDataIfc.QUESTIONS_ORDERING));
        setQuestionOrdering(questionorder);
    } else {
        setQuestionOrdering(SectionDataIfc.AS_LISTED_ON_ASSESSMENT_PAGE);
    }

}

From source file:org.samcrow.ridgesurvey.data.ObservationDatabase.java

License:Open Source License

private static ContentValues createContentValues(@NonNull Observation observation) {
    final ContentValues values = new ContentValues();
    values.put("uploaded", observation.isUploaded() ? 1 : 0);
    values.put("site", observation.getSiteId());
    values.put("route", observation.getRouteName());

    final DateTimeFormatter formatter = ISODateTimeFormat.dateTime();
    values.put("time", formatter.print(observation.getTime()));

    // Convert species to JSON
    final JSONObject species = new JSONObject();
    try {//from ww w.  j a  v  a2s .co m
        for (Map.Entry<String, Boolean> entry : observation.getSpecies().entrySet()) {
            species.put(entry.getKey(), entry.getValue().booleanValue());
        }
        values.put("species", species.toString(0));
    } catch (JSONException e) {
        final SQLException e1 = new SQLException("JSON problem", e);
        throw e1;
    }

    values.put("notes", observation.getNotes());
    return values;
}

From source file:org.samcrow.ridgesurvey.data.ObservationDatabase.java

License:Open Source License

private static IdentifiedObservation createObservation(Cursor result) throws SQLException {
    final int idIndex = result.getColumnIndexOrThrow("id");
    final int uploadedIndex = result.getColumnIndexOrThrow("uploaded");
    final int siteIndex = result.getColumnIndexOrThrow("site");
    final int routeIndex = result.getColumnIndexOrThrow("route");
    final int timeIndex = result.getColumnIndexOrThrow("time");
    final int speciesIndex = result.getColumnIndexOrThrow("species");
    final int notesIndex = result.getColumnIndexOrThrow("notes");

    final int id = result.getInt(idIndex);
    final boolean uploaded = result.getInt(uploadedIndex) == 1;

    final int site = result.getInt(siteIndex);
    final String route = result.getString(routeIndex);

    final DateTimeFormatter formatter = ISODateTimeFormat.dateTime();
    final String timeString = result.getString(timeIndex);
    DateTime time;//  w  ww.j a  va 2 s .  c  om
    try {
        time = formatter.parseDateTime(timeString);
    } catch (IllegalArgumentException e) {
        final SQLException e1 = new SQLException("Invalid date/time value: " + timeString);
        //noinspection UnnecessaryInitCause
        e1.initCause(e);
        throw e1;
    }

    final String speciesJson = result.getString(speciesIndex);

    final Map<String, Boolean> speciesPresent = new HashMap<>();
    // Try to parse
    try {
        final JSONObject species = new JSONObject(speciesJson);
        for (Iterator<String> iter = species.keys(); iter.hasNext();) {
            final String speciesName = iter.next();
            final boolean present = species.getBoolean(speciesName);
            speciesPresent.put(speciesName, present);
        }
    } catch (JSONException e) {
        final SQLException e1 = new SQLException("Species JSON could not be parsed", e);
        throw e1;
    }

    final String notes = result.getString(notesIndex);

    return new IdentifiedObservation(time, uploaded, site, route, speciesPresent, notes, id);
}