List of usage examples for org.joda.time.format ISODateTimeFormat dateTime
public static DateTimeFormatter dateTime()
From source file:org.nuxeo.ecm.platform.audit.io.LogEntryJsonWriter.java
License:Apache License
protected void writeExtendedInfo(JsonGenerator jg, String key, Serializable value) throws IOException { Class<?> clazz = value.getClass(); if (Long.class.isAssignableFrom(clazz)) { jg.writeNumberField(key, (Long) value); } else if (Integer.class.isAssignableFrom(clazz)) { jg.writeNumberField(key, (Integer) value); } else if (Double.class.isAssignableFrom(clazz)) { jg.writeNumberField(key, (Double) value); } else if (Date.class.isAssignableFrom(clazz)) { jg.writeStringField(key, ISODateTimeFormat.dateTime().print(new DateTime(value))); } else if (String.class.isAssignableFrom(clazz)) { jg.writeStringField(key, (String) value); } else if (Boolean.class.isAssignableFrom(clazz)) { jg.writeBooleanField(key, (Boolean) value); } else {/*from www. j a va 2s. c om*/ jg.writeStringField(key, value.toString()); } }
From source file:org.nuxeo.ecm.platform.sync.server.webservices.WSSynchroServerModule.java
License:Open Source License
private ContextDataInfo[] getContextData(CoreSession documentManager, DocumentModel document, List<String> availableDocIds, DocumentModelList unrestrictedDocs) throws Exception { List<ContextDataInfo> listContextData = new ArrayList<ContextDataInfo>(); DocumentModel sourceDocument = null; DocumentRef ref = document.getRef(); // add needed context data if (document.isProxy()) { DocumentModel version = null;//from w w w . ja v a 2s . com String importProxyTargetId = null; String importProxyVersionableId = null; // first try to get the version from which the proxy was made version = documentManager.getSourceDocument(ref); if (version != null) { importProxyTargetId = version.getId(); // second try to get the source of the version from which // the proxy was made if (documentManager.hasPermission(version.getRef(), SecurityConstants.VERSION)) { if (version.getSourceId() != null) { // TODO: importProxyVersionableId = // version.getSourceId() sourceDocument = documentManager.getSourceDocument(version.getRef()); if (sourceDocument != null) { importProxyVersionableId = sourceDocument.getId(); } } } else { log.debug("Current logged user does not have Version security ..."); // an restricted user needs to get information about the // proxy sources DocumentSourceUnrestricted usr = new DocumentSourceUnrestricted(documentManager, ref); usr.runUnrestricted(); importProxyVersionableId = usr.sourceId; } } if (!availableDocIds.contains(importProxyTargetId)) { unrestrictedDocs.add(version); availableDocIds.add(importProxyTargetId); } // add proxy targetId listContextData.add(generateDataContextInfo(CoreSession.IMPORT_PROXY_TARGET_ID, importProxyTargetId)); // add proxy versionable id(source id) listContextData.add( generateDataContextInfo(CoreSession.IMPORT_PROXY_VERSIONABLE_ID, importProxyVersionableId)); } else if (document.isVersion()) { String importVersionVersionableId = null; List<VersionModel> versions = null; String minorVer = null; String majorVer = null; if (document.getSourceId() == null) { // add version description listContextData.add(generateDataContextInfo(CoreSession.IMPORT_VERSION_MAJOR, "1")); // add version description listContextData.add(generateDataContextInfo(CoreSession.IMPORT_VERSION_MINOR, "0")); listContextData .add(generateDataContextInfo(CoreSession.IMPORT_VERSION_VERSIONABLE_ID, document.getId())); // add version label listContextData .add(generateDataContextInfo(CoreSession.IMPORT_VERSION_LABEL, document.getVersionLabel())); } else { if (documentManager.hasPermission(new IdRef(document.getSourceId()), SecurityConstants.READ)) { sourceDocument = documentManager.getSourceDocument(ref); } else { log.debug("Current logged user does not have Version security ..."); DocumentSourceUnrestricted usr = new DocumentSourceUnrestricted(documentManager, ref); usr.runUnrestricted(); importVersionVersionableId = usr.sourceId; versions = usr.versionsForSourceDocument; minorVer = usr.minorVer; majorVer = usr.majorVer; } if (importVersionVersionableId == null) { importVersionVersionableId = sourceDocument.getId(); } // add versionable id(source id) listContextData.add(generateDataContextInfo(CoreSession.IMPORT_VERSION_VERSIONABLE_ID, importVersionVersionableId)); // add version label listContextData .add(generateDataContextInfo(CoreSession.IMPORT_VERSION_LABEL, document.getVersionLabel())); if (versions == null) { versions = documentManager.getVersionsForDocument(sourceDocument.getRef()); } for (VersionModel versionModel : versions) { if (versionModel.getLabel().equals(document.getVersionLabel())) { // add version description listContextData.add(generateDataContextInfo(CoreSession.IMPORT_VERSION_DESCRIPTION, versionModel.getDescription())); // add version creation date listContextData.add(generateDataContextInfo(CoreSession.IMPORT_VERSION_CREATED, new DateType().encode(versionModel.getCreated()))); break; } } if (minorVer == null || majorVer == null) { VersioningDocument docVer = document.getAdapter(VersioningDocument.class); minorVer = docVer.getMinorVersion().toString(); majorVer = docVer.getMajorVersion().toString(); } // add version description listContextData.add(generateDataContextInfo(CoreSession.IMPORT_VERSION_MAJOR, majorVer)); // add version description listContextData.add(generateDataContextInfo(CoreSession.IMPORT_VERSION_MINOR, minorVer)); } } else { // add lock status Lock lock = document.getLockInfo(); if (lock != null) { listContextData.add(generateDataContextInfo(CoreSession.IMPORT_LOCK_OWNER, lock.getOwner())); String createdString = ISODateTimeFormat.dateTime().print(new DateTime(lock.getCreated())); listContextData.add(generateDataContextInfo(CoreSession.IMPORT_LOCK_CREATED, createdString)); } if (document.isVersionable() && documentManager.hasPermission(ref, SecurityConstants.READ)) { listContextData .add(generateDataContextInfo(CoreSession.IMPORT_CHECKED_IN, Boolean.FALSE.toString())); // add the id of the last version, which represents the base // for // the current state of the document DocumentModel version = documentManager.getLastDocumentVersion(ref); if (version != null && version.getId().equals(document.getId())) { listContextData .add(generateDataContextInfo(CoreSession.IMPORT_BASE_VERSION_ID, version.getId())); } VersioningDocument docVer = document.getAdapter(VersioningDocument.class); String minorVer = docVer.getMinorVersion().toString(); String majorVer = docVer.getMajorVersion().toString(); // add major version listContextData.add(generateDataContextInfo(CoreSession.IMPORT_VERSION_MAJOR, majorVer)); // add minor version listContextData.add(generateDataContextInfo(CoreSession.IMPORT_VERSION_MINOR, minorVer)); } } // add current lifecycle state listContextData.add( generateDataContextInfo(CoreSession.IMPORT_LIFECYCLE_STATE, document.getCurrentLifeCycleState())); // add lifecycle policy listContextData .add(generateDataContextInfo(CoreSession.IMPORT_LIFECYCLE_POLICY, document.getLifeCyclePolicy())); return listContextData.toArray(new ContextDataInfo[0]); }
From source file:org.nuxeo.ecm.platform.ui.web.restAPI.LockingRestlet.java
License:Open Source License
@Override protected void doHandleStatelessRequest(Request req, Response res) { String repoId = (String) req.getAttributes().get("repo"); String docid = (String) req.getAttributes().get("docid"); DOMDocumentFactory domFactory = new DOMDocumentFactory(); DOMDocument result = (DOMDocument) domFactory.createDocument(); // init repo and document boolean initOk = initRepositoryAndTargetDocument(res, repoId, docid); if (!initOk) { return;/*from ww w . j a v a2 s . c o m*/ } String cUserName = getUserPrincipal(req).getName(); // get Action String action = STATUS; if (req.getResourceRef().getSegments().size() > 5) { action = req.getResourceRef().getSegments().get(5).toLowerCase(); } if (req.getMethod().equals(Method.LOCK)) { action = LOCK; } if (req.getMethod().equals(Method.UNLOCK)) { action = UNLOCK; } String response = ""; String code = ""; if (action.equals(LOCK)) { try { Lock lock = session.getLockInfo(targetDocRef); if (lock == null) { session.setLock(targetDocRef); session.save(); response = "lock acquired on document " + docid; code = SC_LOCKED_OK; } else if (lock.getOwner().equals(cUserName)) { response = "document " + docid + " is already locked by you"; code = SC_ALREADY_LOCKED_OK; } else { response = "document " + docid + " is already locked by " + lock.getOwner(); code = SC_ALREADY_LOCKED_KO; } } catch (ClientException e) { handleError(result, res, e); return; } } else if (action.equals(UNLOCK)) { try { Lock lock = session.getLockInfo(targetDocRef); if (lock == null) { response = "document " + docid + " is not locked"; code = SC_ALREADY_UNLOCKED_OK; } else if (lock.getOwner().equals(cUserName)) { session.removeLock(targetDocRef); session.save(); response = "document " + docid + " unlocked"; code = SC_UNLOCKED_OK; } else { response = "document " + docid + " is locked by " + lock.getOwner(); code = SC_ALREADY_LOCKED_KO; } } catch (ClientException e) { handleError(result, res, e); return; } } else if (action.equals(STATUS)) { try { Lock lock = session.getLockInfo(targetDocRef); response = session.getLock(targetDocRef); if (lock == null) { code = SC_LOCKINFO_NOT_LOCKED; } else { code = SC_LOCKINFO_LOCKED; } } catch (ClientException e) { handleError(result, res, e); return; } } else if (action.equals(STATE)) { try { Lock lock = session.getLockInfo(targetDocRef); if (lock == null) { code = SC_LOCKINFO_NOT_LOCKED; response = ""; } else { code = SC_LOCKINFO_LOCKED; response = lock.getOwner() + '/' + ISODateTimeFormat.dateTime().print(new DateTime(lock.getCreated())); } } catch (ClientException e) { handleError(result, res, e); return; } } else { handleError(result, res, "Unsupported operation"); return; } Element current = result.createElement("document"); current.setAttribute("code", code); current.setAttribute("message", response); result.setRootElement((org.dom4j.Element) current); res.setEntity(result.asXML(), MediaType.TEXT_XML); res.getEntity().setCharacterSet(CharacterSet.UTF_8); }
From source file:org.nuxeo.ecm.tokenauth.io.AuthenticationTokenWriter.java
License:Apache License
@Override public void write(AuthenticationToken token, JsonGenerator jg) throws IOException { jg.writeStartObject();// w w w. jav a2 s . c o m jg.writeStringField(ENTITY_FIELD_NAME, ENTITY_TYPE); jg.writeStringField("id", token.getToken()); jg.writeStringField("username", token.getUserName()); jg.writeStringField("application", token.getApplicationName()); jg.writeStringField("deviceId", token.getDeviceId()); jg.writeStringField("deviceDescription", token.getDeviceDescription()); jg.writeStringField("permission", token.getPermission()); DateTimeFormatter dateTime = ISODateTimeFormat.dateTime(); jg.writeStringField("creationDate", dateTime.print(new DateTime(token.getCreationDate()))); jg.writeEndObject(); }
From source file:org.nuxeo.elasticsearch.audit.ESAuditBackend.java
License:Open Source License
public String expandQueryVariables(String query, Map<String, Object> params) { if (params != null && params.size() > 0) { TextTemplate tmpl = new TextTemplate(); for (String key : params.keySet()) { Object val = params.get(key); if (val == null) { continue; } else if (val instanceof Calendar) { tmpl.setVariable(key, ISODateTimeFormat.dateTime().print(new DateTime((Calendar) val))); } else if (val instanceof Date) { tmpl.setVariable(key, ISODateTimeFormat.dateTime().print(new DateTime((Date) val))); } else { tmpl.setVariable(key, val.toString()); }//from www .j a va 2s . co m } query = tmpl.process(query); } return query; }
From source file:org.ohmage.domain.Audit.java
License:Apache License
/** * A JSONObject representing the available information from this audit. * /*from www . j a v a 2 s. c o m*/ * @return A JSONObject representing this object. If there is an error * building this object, null is returned. */ public JSONObject toJson() { try { JSONObject result = new JSONObject(); result.put(JSON_KEY_REQUEST_TYPE, requestType.toString()); result.put(JSON_KEY_URI, uri); result.put(JSON_KEY_CLIENT, client); result.put(JSON_KEY_DEVICE_ID, deviceId); result.put(JSON_KEY_RESPONSE, response); result.put(JSON_KEY_RECEIVED_MILLIS, receivedMillis); result.put(JSON_KEY_RESPONDED_MILLIS, respondedMillis); result.put(JSON_KEY_DB_TIMESTAMP, ISODateTimeFormat.dateTime().print(dbTimestamp.getTime())); result.put(JSON_KEY_PARAMETERS, parameters); result.put(JSON_KEY_EXTRAS, extras); return result; } catch (JSONException e) { LOGGER.error("Error building the JSONObject.", e); return null; } }
From source file:org.ohmage.prompts.TimestampPrompt.java
License:Apache License
@Override public Object getAnswer() { DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.dateTime().withOffsetParsed(); return dateTimeFormatter.print(value.getTimeInMillis()); }
From source file:org.ohmage.request.survey.SurveyResponseReadRequest.java
License:Apache License
@Override public void respond(final JsonGenerator generator, final ColumnNode<String> columns) throws JsonGenerationException, IOException, DomainException { for (SurveyResponse surveyResponse : getSurveyResponses()) { // Start the object. generator.writeStartObject();//from w w w . ja va2s . c o m // Write the data point's metadata. generator.writeObjectFieldStart("metadata"); // Write the unique identifier for this point. generator.writeStringField("id", surveyResponse.getSurveyResponseId().toString()); // Write the timestamp for this point. generator.writeStringField("timestamp", ISODateTimeFormat.dateTime() .print(new DateTime(surveyResponse.getTime(), surveyResponse.getTimezone()))); // Write the location for this point. Location location = surveyResponse.getLocation(); if (location != null) { generator.writeObjectFieldStart("location"); location.streamJson(generator, false, LocationColumnKey.ALL_COLUMNS); generator.writeEndObject(); } // End the metadata. generator.writeEndObject(); // Write the data point's data. generator.writeObjectFieldStart("data"); // Write the survey's ID. if ((columns == null) || columns.hasChild(SurveyResponse.JSON_KEY_SURVEY_ID)) { generator.writeStringField(SurveyResponse.JSON_KEY_SURVEY_ID, surveyResponse.getSurvey().getId()); } boolean allColumns = columns.isLeaf(); // Write the launch context. if (allColumns || columns.hasChild(SurveyResponse.JSON_KEY_SURVEY_LAUNCH_CONTEXT)) { generator.writeObjectFieldStart(SurveyResponse.JSON_KEY_SURVEY_LAUNCH_CONTEXT); ColumnNode<String> launchContextColumns = columns .getChild(SurveyResponse.JSON_KEY_SURVEY_LAUNCH_CONTEXT); boolean allLaunchContextColumns = (launchContextColumns == null) ? true : launchContextColumns.isLeaf(); // Write the launch context's time. if (allColumns || allLaunchContextColumns || launchContextColumns.hasChild(SurveyResponse.LaunchContext.JSON_KEY_LAUNCH_TIME)) { generator.writeNumberField(SurveyResponse.LaunchContext.JSON_KEY_LAUNCH_TIME, surveyResponse.getLaunchContext().getLaunchTime()); } // Write the launch context's time zone. if (allColumns || allLaunchContextColumns || launchContextColumns.hasChild(SurveyResponse.LaunchContext.JSON_KEY_LAUNCH_TIMEZONE)) { generator.writeStringField(SurveyResponse.LaunchContext.JSON_KEY_LAUNCH_TIMEZONE, surveyResponse.getLaunchContext().getTimeZone().getID()); } // Write the launch context's active triggers. if (allColumns || allLaunchContextColumns || launchContextColumns.hasChild(SurveyResponse.LaunchContext.JSON_KEY_ACTIVE_TRIGGERS)) { generator.writeArrayFieldStart(SurveyResponse.LaunchContext.JSON_KEY_ACTIVE_TRIGGERS); // Add all of the active triggers. JSONArray activeTriggers = surveyResponse.getLaunchContext().getActiveTriggers(); int numActiveTriggers = activeTriggers.length(); for (int i = 0; i < numActiveTriggers; i++) { try { generator.writeString(activeTriggers.getString(i)); } catch (JSONException e) { LOGGER.warn("Could not serialize one of the trigger names.", e); } } // End the launch context's active triggers array. generator.writeEndArray(); } // End the launch context. generator.writeEndObject(); } // Write the responses array. if (allColumns || columns.hasChild(SurveyResponse.JSON_KEY_RESPONSES)) { // Start the array of responses. generator.writeArrayFieldStart(SurveyResponse.JSON_KEY_RESPONSES); // Get the list of response columns. ColumnNode<String> responseColumns = columns.getChild(SurveyResponse.JSON_KEY_RESPONSES); // Process each response in its prompt's order in the survey. Map<Integer, Response> responses = surveyResponse.getResponses(); List<Integer> indices = new ArrayList<Integer>(responses.keySet()); Collections.sort(indices); // Add each prompt if it is in the column list. for (Integer index : indices) { // Get the response. Response response = responses.get(index); if (allColumns || responseColumns.isLeaf()) // Start the response. generator.writeStartObject(); // Write the response's ID. generator.writeStringField(PromptResponse.JSON_KEY_PROMPT_ID, response.getId()); // Remote activity prompt responses are JSONArray objects. // Jackson cannot readily parse them, so we will convert // them into their string representation, have Jackson // parse that string and then output it. Object responseValue = response.getResponse(); if ((responseValue instanceof JSONArray) || (responseValue instanceof JSONObject)) { responseValue = JSON_FACTORY.createJsonParser(responseValue.toString()).readValueAsTree(); } // Write the response. generator.writeObjectField(PromptResponse.JSON_KEY_RESPONSE, responseValue); // End the response. generator.writeEndObject(); } // End the array of responses. generator.writeEndArray(); } // End the data field. generator.writeEndObject(); // End the object. generator.writeEndObject(); } }
From source file:org.ohmage.streams.StreamPointBuilder.java
License:Apache License
/** * Set the time and timezone for this string. Time Zone is required for correct visualization of * the data point./* w w w.ja v a 2 s.c om*/ * * @param time * @param timeZone * @return */ public StreamPointBuilder withTime(Date time, TimeZone timeZone) { if (dateTimeFormatter == null) dateTimeFormatter = ISODateTimeFormat.dateTime().withOffsetParsed(); mTimestamp = dateTimeFormatter.print(new DateTime(time, DateTimeZone.forTimeZone(timeZone))); return this; }
From source file:org.ohmage.streams.StreamPointBuilder.java
License:Apache License
/** * Set the time for this point to the value of the {@link DateTime} * @param time/* w w w . j ava 2 s. c o m*/ * @return */ public StreamPointBuilder withTime(DateTime time) { if (dateTimeFormatter == null) dateTimeFormatter = ISODateTimeFormat.dateTime().withOffsetParsed(); mTimestamp = dateTimeFormatter.print(time); return this; }