下面列出了org.json.simple.JSONAware#org.alfresco.util.ISO8601DateFormat 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public Boolean routeNode(int numShards, int shardInstance, Node node)
{
if(numShards <= 1)
{
return true;
}
String ISO8601Date = node.getShardPropertyValue();
Date date = ISO8601DateFormat.parse(ISO8601Date);
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(date);
int month = calendar.get(Calendar.MONTH);
int year = calendar.get(Calendar.YEAR);
// Avoid using Math.ceil with Integer
int countMonths = ((year * 12) + (month+1));
int grouping = 3;
int ceilGroupInstance = (countMonths + grouping - 1) / grouping;
return ceilGroupInstance % numShards == shardInstance;
}
public static Date getDate(JSONObject json) throws ParseException
{
if(json == null)
{
return null;
}
String dateTime = json.optString(DATE_TIME);
if(dateTime == null)
{
return null;
}
String format = json.optString(FORMAT);
if(format!= null && ISO8601.equals(format) == false)
{
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
return dateFormat.parse(dateTime);
}
return ISO8601DateFormat.parse(dateTime);
}
@SuppressWarnings("unchecked")
public static AuditEntry parseAuditEntry(JSONObject jsonObject)
{
Long id = (Long) jsonObject.get("id");
String auditApplicationId = (String) jsonObject.get("auditApplicationId");
Map<String, Serializable> values = (Map<String, Serializable>) jsonObject.get("values");
org.alfresco.rest.api.model.UserInfo createdByUser = null;
JSONObject createdByUserJson = (JSONObject) jsonObject.get("createdByUser");
if (createdByUserJson != null)
{
String userId = (String) createdByUserJson.get("id");
String displayName = (String) createdByUserJson.get("displayName");
createdByUser = new org.alfresco.rest.api.model.UserInfo(userId,displayName,displayName);
}
Date createdAt = ISO8601DateFormat.parse((String) jsonObject.get("createdAt"));
AuditEntry auditEntry = new AuditEntry(id, auditApplicationId, createdByUser, createdAt, values);
return auditEntry;
}
private PersonFavourite addFavouriteSite(String userName, NodeRef nodeRef)
{
PersonFavourite favourite = null;
SiteInfo siteInfo = siteService.getSite(nodeRef);
if(siteInfo != null)
{
favourite = getFavouriteSite(userName, siteInfo);
if(favourite == null)
{
Map<String, Serializable> preferences = new HashMap<String, Serializable>(1);
String siteFavouritedKey = siteFavouritedKey(siteInfo);
preferences.put(siteFavouritedKey, Boolean.TRUE);
// ISO8601 string format: PreferenceService works with strings only for dates it seems
String siteCreatedAtKey = siteCreatedAtKey(siteInfo);
Date createdAt = new Date();
String createdAtStr = ISO8601DateFormat.format(createdAt);
preferences.put(siteCreatedAtKey, createdAtStr);
preferenceService.setPreferences(userName, preferences);
favourite = new PersonFavourite(userName, siteInfo.getNodeRef(), Type.SITE, siteInfo.getTitle(), createdAt);
QName nodeClass = nodeService.getType(nodeRef);
OnAddFavouritePolicy policy = onAddFavouriteDelegate.get(nodeRef, nodeClass);
policy.onAddFavourite(userName, nodeRef);
}
}
else
{
// shouldn't happen, getType recognizes it as a site or subtype
logger.warn("Unable to get site for " + nodeRef);
}
return favourite;
}
private PersonFavourite getFavouriteSite(String userName, SiteInfo siteInfo)
{
PersonFavourite favourite = null;
String siteFavouritedKey = siteFavouritedKey(siteInfo);
String siteCreatedAtKey = siteCreatedAtKey(siteInfo);
Boolean isFavourited = false;
Serializable s = preferenceService.getPreference(userName, siteFavouritedKey);
if(s != null)
{
if(s instanceof String)
{
isFavourited = Boolean.valueOf((String)s);
}
else if(s instanceof Boolean)
{
isFavourited = (Boolean)s;
}
else
{
throw new AlfrescoRuntimeException("Unexpected favourites preference value");
}
}
if(isFavourited)
{
String createdAtStr = (String)preferenceService.getPreference(userName, siteCreatedAtKey);
Date createdAt = (createdAtStr == null ? null : ISO8601DateFormat.parse(createdAtStr));
favourite = new PersonFavourite(userName, siteInfo.getNodeRef(), Type.SITE, siteInfo.getTitle(), createdAt);
}
return favourite;
}
private void updateFavouriteNodes(String userName, Type type, Map<PersonFavouriteKey, PersonFavourite> favouriteNodes)
{
PrefKeys prefKeys = getPrefKeys(type);
Map<String, Serializable> preferences = new HashMap<String, Serializable>(1);
StringBuilder values = new StringBuilder();
for(PersonFavourite node : favouriteNodes.values())
{
NodeRef nodeRef = node.getNodeRef();
values.append(nodeRef.toString());
values.append(",");
// ISO8601 string format: PreferenceService works with strings only for dates it seems
StringBuilder sb = new StringBuilder(prefKeys.getAlfrescoPrefKey());
sb.append(nodeRef.toString());
sb.append(".createdAt");
String createdAtKey = sb.toString();
Date createdAt = node.getCreatedAt();
if(createdAt != null)
{
String createdAtStr = ISO8601DateFormat.format(createdAt);
preferences.put(createdAtKey, createdAtStr);
}
}
if(values.length() > 1)
{
values.delete(values.length() - 1, values.length());
}
preferences.put(prefKeys.getSharePrefKey(), values.toString());
preferenceService.setPreferences(userName, preferences);
}
private void extractFavouriteSite(String userName, Type type, Map<PersonFavouriteKey, PersonFavourite> sortedFavouriteNodes, Map<String, Serializable> preferences, String key)
{
// preference value indicates whether the site has been favourited
Serializable pref = preferences.get(key);
Boolean isFavourite = (Boolean)pref;
if(isFavourite)
{
PrefKeys sitePrefKeys = getPrefKeys(Type.SITE);
int length = sitePrefKeys.getSharePrefKey().length();
String siteId = key.substring(length);
try
{
SiteInfo siteInfo = siteService.getSite(siteId);
if(siteInfo != null)
{
StringBuilder builder = new StringBuilder(sitePrefKeys.getAlfrescoPrefKey());
builder.append(siteId);
builder.append(".createdAt");
String createdAtPrefKey = builder.toString();
String createdAtStr = (String)preferences.get(createdAtPrefKey);
Date createdAt = null;
if(createdAtStr != null)
{
createdAt = (createdAtStr != null ? ISO8601DateFormat.parse(createdAtStr): null);
}
PersonFavourite personFavourite = new PersonFavourite(userName, siteInfo.getNodeRef(), Type.SITE, siteId, createdAt);
sortedFavouriteNodes.put(personFavourite.getKey(), personFavourite);
}
}
catch(AccessDeniedException ex)
{
// the user no longer has access to this site, skip over the favourite
// TODO remove the favourite preference
return;
}
}
}
private Date getDate(Serializable value)
{
if(value instanceof Date)
{
return (Date) value;
}
else if(value instanceof String)
{
return ISO8601DateFormat.parse((String) value);
}
throw new AlfrescoRuntimeException("Parameter 'compareValue' must be of type java.util.Date!");
}
@Override
public Boolean routeNode(int numShards, int shardInstance, Node node)
{
if(numShards <= 1)
{
return true;
}
String ISO8601Date = node.getShardPropertyValue();
if(ISO8601Date == null)
{
return dbidRouter.routeNode(numShards, shardInstance, node);
}
try
{
Date date = ISO8601DateFormat.parse(ISO8601Date);
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(date);
int month = cal.get(Calendar.MONTH);
int year = cal.get(Calendar.YEAR);
return ((((year * 12) + month) / grouping) % numShards) == shardInstance;
}
catch (Exception exception)
{
return dbidRouter.routeNode(numShards, shardInstance, node);
}
}
/**
* Removes the time zone for a given date if the Calendar Entry is an all day event
*
* @return ISO 8601 formatted date String if datePattern is null
*/
protected String removeTimeZoneIfRequired(Date date, Boolean isAllDay, Boolean removeTimezone, String datePattern)
{
if (removeTimezone)
{
DateTime dateTime = new DateTime(date, DateTimeZone.UTC);
if (null == datePattern)
{
return dateTime.toString((isAllDay) ? (ALL_DAY_DATETIME_FORMATTER) : (ISODateTimeFormat.dateTime()));
}
else
{
// For Legacy Dates and Times.
return dateTime.toString(DateTimeFormat.forPattern(datePattern));
}
}
// This is for all other cases, including the case, when UTC time zone is configured
if (!isAllDay && (null == datePattern))
{
return ISO8601DateFormat.format(date);
}
DateFormat simpleDateFormat = new SimpleDateFormat((null != datePattern) ? (datePattern) : (ALL_DAY_DATETIME_PATTERN));
return simpleDateFormat.format(date);
}
private void updateRepeatingStartEnd(Date newStart, long duration, Map<String, Object> result)
{
Date newEnd = new Date(newStart.getTime() + duration);
result.put(RESULT_START, ISO8601DateFormat.format(newStart));
result.put(RESULT_END, ISO8601DateFormat.format(newEnd));
String legacyDateFormat = "yyyy-MM-dd";
SimpleDateFormat ldf = new SimpleDateFormat(legacyDateFormat);
String legacyTimeFormat ="HH:mm";
SimpleDateFormat ltf = new SimpleDateFormat(legacyTimeFormat);
result.put("legacyDateFrom", ldf.format(newStart));
result.put("legacyTimeFrom", ltf.format(newStart));
result.put("legacyDateTo", ldf.format(newEnd));
result.put("legacyTimeTo", ltf.format(newEnd));
}
@SuppressWarnings("unchecked")
protected JSONObject getUserDetails(String username)
{
NodeRef node = personService.getPerson(username);
JSONObject result = new JSONObject();
result.put("userName", username);
result.put("firstName", nodeService.getProperty(node, ContentModel.PROP_FIRSTNAME));
result.put("lastName", nodeService.getProperty(node, ContentModel.PROP_LASTNAME));
result.put("jobtitle", nodeService.getProperty(node, ContentModel.PROP_JOBTITLE));
result.put("organization", nodeService.getProperty(node, ContentModel.PROP_ORGANIZATION));
String status = (String) nodeService.getProperty(node, ContentModel.PROP_USER_STATUS);
if (status != null)
{
result.put("userStatus", status);
}
Date statusTime = (Date) nodeService.getProperty(node, ContentModel.PROP_USER_STATUS_TIME);
if (statusTime != null)
{
JSONObject statusTimeJson = new JSONObject();
statusTimeJson.put("iso8601", ISO8601DateFormat.format(statusTime));
result.put("userStatusTime", statusTimeJson);
}
// Get the avatar for the user id if one is available
List<AssociationRef> assocRefs = this.nodeService.getTargetAssocs(node, ContentModel.ASSOC_AVATAR);
if (!assocRefs.isEmpty())
{
NodeRef avatarNodeRef = assocRefs.get(0).getTargetRef();
result.put("avatar", avatarNodeRef.toString());
}
else
{
result.put("avatar", "avatar"); // This indicates to just use a placeholder
}
return result;
}
public static Map<String, Object> buildDateModel(Date dateTime)
{
String dateStr = ISO8601DateFormat.format(dateTime);
Map<String, Object> model = new HashMap<String, Object>();
model.put(DATE_TIME, dateStr);
model.put(FORMAT, ISO8601);
return model;
}
/**
* Build a model for a single action
*/
private Map<String,Object> buildModel(ExecutionSummary summary)
{
if(summary == null) {
return null;
}
// Get the details, if we can
ExecutionDetails details = actionTrackingService.getExecutionDetails(summary);
// Only record if still running - may have finished
// between getting the list and now
if(details != null) {
Map<String, Object> ram = new HashMap<String,Object>();
ram.put(ACTION_ID, summary.getActionId());
ram.put(ACTION_TYPE, summary.getActionType());
ram.put(ACTION_INSTANCE, summary.getExecutionInstance());
ram.put(ACTION_KEY, AbstractActionWebscript.getRunningId(summary));
ram.put(ACTION_NODE_REF, details.getPersistedActionRef());
ram.put(ACTION_RUNNING_ON, details.getRunningOn());
ram.put(ACTION_CANCEL_REQUESTED, details.isCancelRequested());
if(details.getStartedAt() != null) {
ram.put(ACTION_STARTED_AT, ISO8601DateFormat.format(details.getStartedAt()));
} else {
ram.put(ACTION_STARTED_AT, null);
}
return ram;
}
return null;
}
@SuppressWarnings("unchecked")
public void testBuildWorkflowInstance() throws Exception
{
WorkflowInstance workflowInstance = makeWorkflowInstance(null);
Map<String, Object> model = builder.buildSimple(workflowInstance);
assertEquals(workflowInstance.getId(), model.get(WorkflowModelBuilder.TASK_WORKFLOW_INSTANCE_ID));
assertTrue(model.containsKey(WorkflowModelBuilder.TASK_WORKFLOW_INSTANCE_URL));
assertEquals(workflowInstance.getDefinition().getName(), model.get(WorkflowModelBuilder.TASK_WORKFLOW_INSTANCE_NAME));
assertEquals(workflowInstance.getDefinition().getTitle(), model.get(WorkflowModelBuilder.TASK_WORKFLOW_INSTANCE_TITLE));
assertEquals(workflowInstance.getDefinition().getDescription(), model.get(WorkflowModelBuilder.TASK_WORKFLOW_INSTANCE_DESCRIPTION));
assertEquals(workflowInstance.getDescription(), model.get(WorkflowModelBuilder.TASK_WORKFLOW_INSTANCE_MESSAGE));
assertEquals(workflowInstance.isActive(), model.get(WorkflowModelBuilder.TASK_WORKFLOW_INSTANCE_IS_ACTIVE));
String startDate = ISO8601DateFormat.format(workflowInstance.getStartDate());
String endDate = ISO8601DateFormat.format(workflowInstance.getEndDate());
String startDateBuilder = ISO8601DateFormat.formatToZulu((String) model.get(WorkflowModelBuilder.TASK_WORKFLOW_INSTANCE_START_DATE));
String endDateBuilder = ISO8601DateFormat.formatToZulu((String) model.get(WorkflowModelBuilder.TASK_WORKFLOW_INSTANCE_END_DATE));
assertEquals(startDate, startDateBuilder);
assertEquals(endDate, endDateBuilder);
Map<String, Object> initiator = (Map<String, Object>) model.get(WorkflowModelBuilder.TASK_WORKFLOW_INSTANCE_INITIATOR);
if (initiator != null)
{
assertEquals(userName, initiator.get(WorkflowModelBuilder.PERSON_USER_NAME));
assertEquals(firstName, initiator.get(WorkflowModelBuilder.PERSON_FIRST_NAME));
assertEquals(lastName, initiator.get(WorkflowModelBuilder.PERSON_LAST_NAME));
}
assertTrue(model.containsKey(WorkflowModelBuilder.TASK_WORKFLOW_INSTANCE_DEFINITION_URL));
}
/**
* Start a review pooled process through the public REST-API.
*/
@SuppressWarnings("unchecked")
protected ProcessInfo startReviewPooledProcess(final RequestContext requestContext) throws PublicApiException {
org.activiti.engine.repository.ProcessDefinition processDefinition = activitiProcessEngine
.getRepositoryService()
.createProcessDefinitionQuery()
.processDefinitionKey("@" + requestContext.getNetworkId() + "@activitiReviewPooled")
.singleResult();
ProcessesClient processesClient = publicApiClient.processesClient();
final JSONObject createProcessObject = new JSONObject();
createProcessObject.put("processDefinitionId", processDefinition.getId());
final JSONObject variablesObject = new JSONObject();
variablesObject.put("bpm_priority", 1);
variablesObject.put("bpm_workflowDueDate", ISO8601DateFormat.format(new Date()));
variablesObject.put("wf_notifyMe", Boolean.FALSE);
TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>()
{
@Override
public Void doWork() throws Exception
{
List<MemberOfSite> memberships = getTestFixture().getNetwork(requestContext.getNetworkId()).getSiteMemberships(requestContext.getRunAsUser());
assertTrue(memberships.size() > 0);
MemberOfSite memberOfSite = memberships.get(0);
String group = "GROUP_site_" + memberOfSite.getSiteId() + "_" + memberOfSite.getRole().name();
variablesObject.put("bpm_groupAssignee", group);
return null;
}
}, requestContext.getRunAsUser(), requestContext.getNetworkId());
createProcessObject.put("variables", variablesObject);
return processesClient.createProcess(createProcessObject.toJSONString());
}
public Serializable getValue(Object value, PropertyDefinition propDef)
{
if (value == null)
{
return null;
}
// before persisting check data type of property
if (propDef.isMultiValued())
{
return processMultiValuedType(value);
}
if (isBooleanProperty(propDef))
{
return processBooleanValue(value);
}
else if (isLocaleProperty(propDef))
{
return processLocaleValue(value);
}
else if (value instanceof String)
{
String valStr = (String) value;
// make sure empty strings stay as empty strings, everything else
// should be represented as null
if (isTextProperty(propDef))
{
return valStr;
}
if(valStr.isEmpty())
{
return null;
}
if(isDateProperty(propDef) && !ISO8601DateFormat.isTimeComponentDefined(valStr))
{
// Special handling for day-only date storage (ALF-10243)
return ISO8601DateFormat.parseDayOnly(valStr, TimeZone.getDefault());
}
}
if (value instanceof Serializable)
{
return (Serializable) DefaultTypeConverter.INSTANCE.convert(propDef.getDataType(), value);
}
else
{
throw new FormException("Property values must be of a Serializable type! Value type: " + value.getClass());
}
}
@Override
public Object getValue(QName name, ContentModelItemData<?> data)
{
Serializable value = data.getPropertyValue(name);
if (value == null)
{
return getDefaultValue(name, data);
}
if (value instanceof Collection<?>)
{
// temporarily add repeating field data as a comma
// separated list, this will be changed to using
// a separate field for each value once we have full
// UI support in place.
Collection<?> values = (Collection<?>) value;
// if the non empty collection is a List of Date objects
// we need to convert each date to a ISO8601 format
if (value instanceof List<?> && !values.isEmpty())
{
List<?> list = (List<?>)values;
if (list.get(0) instanceof Date)
{
List<String> isoDates = new ArrayList<String>(list.size());
for (Object date : list)
{
isoDates.add(ISO8601DateFormat.format((Date)date));
}
// return the ISO formatted dates as a comma delimited string
return StringUtils.collectionToCommaDelimitedString(isoDates);
}
}
// return everything else using toString()
return StringUtils.collectionToCommaDelimitedString(values);
}
else if (value instanceof ContentData)
{
// for content properties retrieve the info URL rather than the
// the object value itself
ContentData contentData = (ContentData)value;
return contentData.getInfoUrl();
}
else if (value instanceof NodeRef)
{
return ((NodeRef)value).toString();
}
return value;
}
/**
* Handles the work of converting values to JSON.
*
* @param nodeRef NodeRef
* @param propertyName QName
* @param key String
* @param value Serializable
* @return the JSON value
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
protected Object propertyToJSON(final NodeRef nodeRef, final QName propertyName, final String key, final Serializable value)
{
if (value != null)
{
// Has a decorator has been registered for this property?
if (propertyDecorators.containsKey(propertyName))
{
JSONAware jsonAware = propertyDecorators.get(propertyName).decorate(propertyName, nodeRef, value);
if (jsonAware != null)
{
return jsonAware;
}
}
else
{
// Built-in data type processing
if (value instanceof Date)
{
JSONObject dateObj = new JSONObject();
dateObj.put("value", JSONObject.escape(value.toString()));
dateObj.put("iso8601", JSONObject.escape(ISO8601DateFormat.format((Date)value)));
return dateObj;
}
else if (value instanceof List)
{
// Convert the List to a JSON list by recursively calling propertyToJSON
List<Object> jsonList = new ArrayList<Object>(((List<Serializable>) value).size());
for (Serializable listItem : (List<Serializable>) value)
{
jsonList.add(propertyToJSON(nodeRef, propertyName, key, listItem));
}
return jsonList;
}
else if (value instanceof Double)
{
return (Double.isInfinite((Double)value) || Double.isNaN((Double)value) ? null : value.toString());
}
else if (value instanceof Float)
{
return (Float.isInfinite((Float)value) || Float.isNaN((Float)value) ? null : value.toString());
}
else
{
return value.toString();
}
}
}
return null;
}
private Map<PersonFavouriteKey, PersonFavourite> extractFavouriteNodes(String userName, Type type, String nodes)
{
PrefKeys prefKeys = getPrefKeys(type);
Map<PersonFavouriteKey, PersonFavourite> favouriteNodes = new HashMap<PersonFavouriteKey, PersonFavourite>();
StringTokenizer st = new StringTokenizer(nodes, ",");
while(st.hasMoreTokens())
{
String nodeRefStr = st.nextToken();
nodeRefStr = nodeRefStr.trim();
if(!NodeRef.isNodeRef((String)nodeRefStr))
{
continue;
}
NodeRef nodeRef = new NodeRef((String)nodeRefStr);
if(!nodeService.exists(nodeRef))
{
continue;
}
if(permissionService.hasPermission(nodeRef, PermissionService.READ_PROPERTIES) == AccessStatus.DENIED)
{
continue;
}
// get createdAt for this favourited node
// use ISO8601
StringBuilder builder = new StringBuilder(prefKeys.getAlfrescoPrefKey());
builder.append(nodeRef.toString());
builder.append(".createdAt");
String prefKey = builder.toString();
String createdAtStr = (String)preferenceService.getPreference(userName, prefKey);
Date createdAt = (createdAtStr != null ? ISO8601DateFormat.parse(createdAtStr): null);
String name = (String)nodeService.getProperty(nodeRef, ContentModel.PROP_NAME);
PersonFavourite personFavourite = new PersonFavourite(userName, nodeRef, type, name, createdAt);
PersonFavouriteKey key = personFavourite.getKey();
favouriteNodes.put(key, personFavourite);
}
return favouriteNodes;
}
@SuppressWarnings("unchecked")
private <T> T convertValueFromString(String value, PropertyType datatype)
{
if (value == null)
{
return null;
}
try
{
switch (datatype)
{
case BOOLEAN:
return (T) Boolean.valueOf(value);
case DATETIME:
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(ISO8601DateFormat.parse(value));
return (T) cal;
case DECIMAL:
return (T) new BigDecimal(value);
case HTML:
return (T) value;
case ID:
return (T) value;
case INTEGER:
return (T) new BigInteger(value);
case STRING:
return (T) value;
case URI:
return (T) value;
default: ;
}
}
catch (Exception e)
{
logger.error("Failed to convert value " + value + " to " + datatype, e);
return null;
}
throw new RuntimeException("Unknown datatype! Spec change?");
}
public void testToString()
{
assertEquals("true", DefaultTypeConverter.INSTANCE.convert(String.class, new Boolean(true)));
assertEquals("false", DefaultTypeConverter.INSTANCE.convert(String.class, new Boolean(false)));
assertEquals("v", DefaultTypeConverter.INSTANCE.convert(String.class, Character.valueOf('v')));
assertEquals("3", DefaultTypeConverter.INSTANCE.convert(String.class, Byte.valueOf("3")));
assertEquals("4", DefaultTypeConverter.INSTANCE.convert(String.class, Short.valueOf("4")));
assertEquals("5", DefaultTypeConverter.INSTANCE.convert(String.class, Integer.valueOf("5")));
assertEquals("6", DefaultTypeConverter.INSTANCE.convert(String.class, Long.valueOf("6")));
assertEquals("7.1", DefaultTypeConverter.INSTANCE.convert(String.class, Float.valueOf("7.1")));
assertEquals("NaN", DefaultTypeConverter.INSTANCE.convert(String.class, Float.NaN));
assertEquals("-Infinity", DefaultTypeConverter.INSTANCE.convert(String.class, Float.NEGATIVE_INFINITY));
assertEquals("Infinity", DefaultTypeConverter.INSTANCE.convert(String.class, Float.POSITIVE_INFINITY));
assertEquals("123.123", DefaultTypeConverter.INSTANCE.convert(String.class, Double.valueOf("123.123")));
assertEquals("NaN", DefaultTypeConverter.INSTANCE.convert(String.class, Double.NaN));
assertEquals("-Infinity", DefaultTypeConverter.INSTANCE.convert(String.class, Double.NEGATIVE_INFINITY));
assertEquals("Infinity", DefaultTypeConverter.INSTANCE.convert(String.class, Double.POSITIVE_INFINITY));
assertEquals("1234567890123456789", DefaultTypeConverter.INSTANCE.convert(String.class, new BigInteger("1234567890123456789")));
assertEquals("12345678901234567890.12345678901234567890", DefaultTypeConverter.INSTANCE.convert(String.class, new BigDecimal("12345678901234567890.12345678901234567890")));
Date date = new Date();
assertEquals(ISO8601DateFormat.format(date), DefaultTypeConverter.INSTANCE.convert(String.class, date));
assertEquals("P0Y25D", DefaultTypeConverter.INSTANCE.convert(String.class, new Duration("P0Y25D")));
assertEquals("woof", DefaultTypeConverter.INSTANCE.convert(String.class, "woof"));
// MLText
MLText mlText = new MLText("woof");
mlText.addValue(Locale.SIMPLIFIED_CHINESE, "缂");
assertEquals("woof", DefaultTypeConverter.INSTANCE.convert(String.class, mlText));
// Locale
assertEquals("fr_FR_", DefaultTypeConverter.INSTANCE.convert(String.class, Locale.FRANCE));
// VersionNumber
assertEquals("1.2.3", DefaultTypeConverter.INSTANCE.convert(String.class, new VersionNumber("1.2.3")));
// Period
assertEquals("period", DefaultTypeConverter.INSTANCE.convert(String.class, new Period("period")));
assertEquals("period|12", DefaultTypeConverter.INSTANCE.convert(String.class, new Period("period|12")));
Map<String,String> periodMap = new HashMap<>();
periodMap.put("periodType","month");
periodMap.put("expression","1");
assertEquals(new Period("month|1"), DefaultTypeConverter.INSTANCE.convert(Period.class, new Period(periodMap)));
// Java Class
assertEquals(this.getClass(), DefaultTypeConverter.INSTANCE.convert(Class.class, this.getClass().getName()));
}
public void testFromString()
{
assertEquals(Boolean.valueOf(true), DefaultTypeConverter.INSTANCE.convert(Boolean.class, "True"));
assertEquals(Boolean.valueOf(false), DefaultTypeConverter.INSTANCE.convert(Boolean.class, "woof"));
assertEquals(Character.valueOf('w'), DefaultTypeConverter.INSTANCE.convert(Character.class, "w"));
assertEquals(Byte.valueOf("3"), DefaultTypeConverter.INSTANCE.convert(Byte.class, "3"));
assertEquals(Short.valueOf("4"), DefaultTypeConverter.INSTANCE.convert(Short.class, "4"));
assertEquals(Integer.valueOf("5"), DefaultTypeConverter.INSTANCE.convert(Integer.class, "5"));
assertEquals(Long.valueOf("6"), DefaultTypeConverter.INSTANCE.convert(Long.class, "6"));
assertEquals(Float.valueOf("7.1"), DefaultTypeConverter.INSTANCE.convert(Float.class, "7.1"));
assertEquals(Float.NaN, DefaultTypeConverter.INSTANCE.convert(Float.class, "NaN"));
assertEquals(Float.NEGATIVE_INFINITY, DefaultTypeConverter.INSTANCE.convert(Float.class, "-Infinity"));
assertEquals(Float.POSITIVE_INFINITY, DefaultTypeConverter.INSTANCE.convert(Float.class, "Infinity"));
assertEquals(Double.valueOf("123.123"), DefaultTypeConverter.INSTANCE.convert(Double.class, "123.123"));
assertEquals(Double.NaN, DefaultTypeConverter.INSTANCE.convert(Double.class, "NaN"));
assertEquals(Double.NEGATIVE_INFINITY, DefaultTypeConverter.INSTANCE.convert(Double.class, "-Infinity"));
assertEquals(Double.POSITIVE_INFINITY, DefaultTypeConverter.INSTANCE.convert(Double.class, "Infinity"));
assertEquals(new BigInteger("1234567890123456789"), DefaultTypeConverter.INSTANCE.convert(BigInteger.class, "1234567890123456789"));
assertEquals(new BigDecimal("12345678901234567890.12345678901234567890"), DefaultTypeConverter.INSTANCE.convert(BigDecimal.class, "12345678901234567890.12345678901234567890"));
GregorianCalendar cal = new GregorianCalendar();
cal.set(Calendar.YEAR, 2004);
cal.set(Calendar.MONTH, 3);
cal.set(Calendar.DAY_OF_MONTH, 12);
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
String isoDate = ISO8601DateFormat.format(cal.getTime());
assertEquals(isoDate, ISO8601DateFormat.format(DefaultTypeConverter.INSTANCE.convert(Date.class, isoDate)));
assertEquals(new Duration("P25D"), DefaultTypeConverter.INSTANCE.convert(Duration.class, "P25D"));
assertEquals("woof", DefaultTypeConverter.INSTANCE.convert(String.class, "woof"));
MLText converted = DefaultTypeConverter.INSTANCE.convert(MLText.class, "woof");
assertEquals("woof", converted.getValue(Locale.getDefault()));
assertEquals(Locale.FRANCE, DefaultTypeConverter.INSTANCE.convert(Locale.class, "fr_FR"));
assertEquals(Locale.FRANCE, DefaultTypeConverter.INSTANCE.convert(Locale.class, "fr_FR_"));
assertEquals(new VersionNumber("1.2.3"), DefaultTypeConverter.INSTANCE.convert(VersionNumber.class, "1.2.3"));
assertEquals(new Period("period"), DefaultTypeConverter.INSTANCE.convert(Period.class, "period"));
assertEquals(new Period("period|12"), DefaultTypeConverter.INSTANCE.convert(Period.class, "period|12"));
Map<String,String> periodMap = new HashMap<String, String>();
periodMap.put("periodType","month");
periodMap.put("expression","1");
assertEquals(new Period(periodMap), DefaultTypeConverter.INSTANCE.convert(Period.class, periodMap));
// Java Class
assertEquals(this.getClass().getName(), DefaultTypeConverter.INSTANCE.convert(String.class, this.getClass()));
}
public void testQueryFolderProperties()
{
Session session = getSession("admin", "admin");
String folderName = getRootFolderName();
Folder root = session.getRootFolder();
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
properties.put(PropertyIds.NAME, folderName);
// create the folder
Folder newFolder = root.createFolder(properties);
ItemIterable<QueryResult> result = session.query("select * from cmis:folder where cmis:name = '"+folderName+"'", false);
assertEquals(1, result.getTotalNumItems());
String uniqueName = getUniqueName();
Map<String, Object> uProperties = new HashMap<String, Object>();
uProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
uProperties.put(PropertyIds.NAME, uniqueName);
Folder uniqueFolder = newFolder.createFolder(uProperties);
result = session.query("select * from cmis:folder where cmis:name = '"+uniqueName+"'", false);
assertEquals(1, result.getTotalNumItems());
result = session.query("select * from cmis:folder where cmis:name = '"+uniqueName+"' AND IN_FOLDER('"+ uniqueFolder.getParentId() + "')" , false);
assertEquals(1, result.getTotalNumItems());
result = session.query("select * from cmis:folder where IN_FOLDER('"+ uniqueFolder.getParentId() + "')" , false);
assertEquals(1, result.getTotalNumItems());
result = session.query("select * from cmis:folder where cmis:name = '"+uniqueName+"' AND cmis:createdBy = '"+ uniqueFolder.getCreatedBy()+"'" , false);
assertEquals(1, result.getTotalNumItems());
result = session.query("select * from cmis:folder where cmis:name = '"+uniqueName+"' AND cmis:objectId = '"+ uniqueFolder.getId()+"'" , false);
assertEquals(1, result.getTotalNumItems());
result = session.query("select * from cmis:folder where cmis:name = '"+uniqueName+"' AND cmis:lastModifiedBy = '"+ uniqueFolder.getLastModifiedBy()+"'" , false);
assertEquals(1, result.getTotalNumItems());
result = session.query("select * from cmis:folder where cmis:name = '"+ uniqueFolder.getName()+"'" , false);
assertEquals(1, result.getTotalNumItems());
String creationDate = ISO8601DateFormat.format(uniqueFolder.getCreationDate().getTime());
result = session.query("select * from cmis:folder where cmis:name = '"+uniqueName+"' AND cmis:creationDate = '"+ creationDate +"'" , false);
assertEquals(1, result.getTotalNumItems());
String modificationDate = ISO8601DateFormat.format(uniqueFolder.getLastModificationDate().getTime());
result = session.query("select * from cmis:folder where cmis:name = '"+uniqueName+"' AND cmis:lastModificationDate = '"+ modificationDate+"'" , false);
assertEquals(1, result.getTotalNumItems());
result = session.query("select * from cmis:folder where cmis:name = '"+uniqueName+"' AND cmis:objectTypeId = '"+ uniqueFolder.getType().getQueryName()+"'" , false);
assertEquals(1, result.getTotalNumItems());
result = session.query("select * from cmis:folder where cmis:name = '"+uniqueName+"' AND cmis:baseTypeId = '"+ uniqueFolder.getBaseType().getQueryName()+"'" , false);
assertEquals(1, result.getTotalNumItems());
}
public void testQueryDocumentProperties() throws Exception
{
Session session = getSession("admin", "admin");
String folderName = getRootFolderName();
Folder root = session.getRootFolder();
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
properties.put(PropertyIds.NAME, folderName);
// create the folder
Folder newFolder = root.createFolder(properties);
ItemIterable<QueryResult> result = session.query("select * from cmis:folder where cmis:name = '"+folderName+"'", false);
assertEquals(1, result.getTotalNumItems());
Document uniqueDocument = createUniqueDocument(newFolder);
result = session.query("select * from cmis:document where cmis:name = '"+uniqueDocument.getName()+"'", false);
assertEquals(1, result.getTotalNumItems());
result = session.query("select * from cmis:document where cmis:name = '"+uniqueDocument.getName()+"' AND IN_FOLDER('"+ newFolder.getId() + "')" , false);
assertEquals(1, result.getTotalNumItems());
result = session.query("select * from cmis:document where IN_FOLDER('"+ newFolder.getId() + "')" , false);
assertEquals(1, result.getTotalNumItems());
result = session.query("select * from cmis:document where cmis:name = '"+uniqueDocument.getName()+"' AND cmis:createdBy = '"+ uniqueDocument.getCreatedBy()+"'" , false);
assertEquals(1, result.getTotalNumItems());
result = session.query("select * from cmis:document where cmis:name = '"+uniqueDocument.getName()+"' AND cmis:objectId = '"+ uniqueDocument.getId()+"'" , false);
assertEquals(1, result.getTotalNumItems());
result = session.query("select * from cmis:document where cmis:name = '"+uniqueDocument.getName()+"' AND cmis:lastModifiedBy = '"+ uniqueDocument.getLastModifiedBy()+"'" , false);
assertEquals(1, result.getTotalNumItems());
result = session.query("select * from cmis:document where cmis:name = '"+ uniqueDocument.getName()+"'" , false);
assertEquals(1, result.getTotalNumItems());
String creationDate = ISO8601DateFormat.format(uniqueDocument.getCreationDate().getTime());
result = session.query("select * from cmis:document where cmis:name = '"+uniqueDocument.getName()+"' AND cmis:creationDate = '"+ creationDate +"'" , false);
assertEquals(1, result.getTotalNumItems());
String modificationDate = ISO8601DateFormat.format(uniqueDocument.getLastModificationDate().getTime());
result = session.query("select * from cmis:document where cmis:name = '"+uniqueDocument.getName()+"' AND cmis:lastModificationDate = '"+ modificationDate+"'" , false);
assertEquals(1, result.getTotalNumItems());
result = session.query("select * from cmis:document where cmis:name = '"+uniqueDocument.getName()+"' AND cmis:objectTypeId = '"+ uniqueDocument.getType().getQueryName()+"'" , false);
assertEquals(1, result.getTotalNumItems());
result = session.query("select * from cmis:document where cmis:name = '"+uniqueDocument.getName()+"' AND cmis:baseTypeId = '"+ uniqueDocument.getBaseType().getQueryName()+"'" , false);
assertEquals(1, result.getTotalNumItems());
result = session.query("select * from cmis:document where cmis:name = '"+uniqueDocument.getName()+"' AND cmis:contentStreamFileName = '"+ uniqueDocument.getContentStreamFileName()+"'" , false);
assertEquals(1, result.getTotalNumItems());
result = session.query("select * from cmis:document where cmis:name = '"+uniqueDocument.getName()+"' AND cmis:contentStreamLength = '"+ uniqueDocument.getContentStreamLength()+"'" , false);
assertEquals(1, result.getTotalNumItems());
result = session.query("select * from cmis:document where cmis:name = '"+uniqueDocument.getName()+"' AND cmis:contentStreamMimeType = '"+ uniqueDocument.getContentStreamMimeType()+"'" , false);
assertEquals(1, result.getTotalNumItems());
}
/**
* Updates properties on the definition, based on the JSON.
* Doesn't save the definition
* Doesn't change the name
*/
protected void updateDefinitionProperties(ReplicationDefinition replicationDefinition, JSONObject json)
throws JSONException
{
if(json.has("description")) {
String description = json.getString("description");
replicationDefinition.setDescription(description);
}
if(json.has("targetName")) {
String targetName = json.getString("targetName");
replicationDefinition.setTargetName(targetName);
}
if(json.has("enabled")) {
boolean enabled = json.getBoolean("enabled");
replicationDefinition.setEnabled(enabled);
}
if(json.has("payload")) {
replicationDefinition.getPayload().clear();
JSONArray payload = json.getJSONArray("payload");
for(int i=0; i<payload.length(); i++) {
String node = payload.getString(i);
replicationDefinition.getPayload().add(
new NodeRef(node)
);
}
}
// Now for the scheduling parts
if(json.has("schedule") && !json.isNull("schedule")) {
// Turn on scheduling, if not already enabled
replicationService.enableScheduling(replicationDefinition);
// Update the properties
JSONObject schedule = json.getJSONObject("schedule");
if(schedule.has("start") && !schedule.isNull("start")) {
// Look for start:.... or start:{"iso8601":....}
String startDate = schedule.getString("start");
if(schedule.get("start") instanceof JSONObject) {
startDate = schedule.getJSONObject("start").getString("iso8601");
}
replicationDefinition.setScheduleStart( ISO8601DateFormat.parse(startDate) );
} else {
replicationDefinition.setScheduleStart(null);
}
if(schedule.has("intervalPeriod") && !schedule.isNull("intervalPeriod")) {
replicationDefinition.setScheduleIntervalPeriod(
IntervalPeriod.valueOf(schedule.getString("intervalPeriod"))
);
} else {
replicationDefinition.setScheduleIntervalPeriod(null);
}
if(schedule.has("intervalCount") && !schedule.isNull("intervalCount")) {
replicationDefinition.setScheduleIntervalCount(
schedule.getInt("intervalCount")
);
} else {
replicationDefinition.setScheduleIntervalCount(null);
}
} else {
// Disable scheduling
replicationService.disableScheduling(replicationDefinition);
}
}
/**
* Build a model containing the full, detailed definition for the given
* Replication Definition.
*/
protected Map<String, Object> buildDetails(ReplicationDefinition rd) {
Map<String, Object> rdm = new HashMap<String,Object>();
// Set the core details
rdm.put(DEFINITION_NAME, rd.getReplicationName());
rdm.put(DEFINITION_DESCRIPTION, rd.getDescription());
rdm.put(DEFINITION_ENABLED, rd.isEnabled());
rdm.put(DEFINITION_TARGET_NAME, rd.getTargetName());
// Set the scheduling details
rdm.put(DEFINITION_SCHEDULE_ENABLED, rd.isSchedulingEnabled());
if(rd.isSchedulingEnabled())
{
rdm.put(DEFINITION_SCHEDULE_START, ISO8601DateFormat.format(rd.getScheduleStart()));
rdm.put(DEFINITION_SCHEDULE_COUNT, rd.getScheduleIntervalCount());
if(rd.getScheduleIntervalPeriod() != null) {
rdm.put(DEFINITION_SCHEDULE_PERIOD, rd.getScheduleIntervalPeriod().toString());
} else {
rdm.put(DEFINITION_SCHEDULE_PERIOD, null);
}
}
// Set the details of the previous run
// These will be null'd out later if replication is in progress
rdm.put(DEFINITION_FAILURE_MESSAGE, rd.getExecutionFailureMessage());
rdm.put(DEFINITION_TRANSFER_LOCAL_REPORT, rd.getLocalTransferReport());
rdm.put(DEFINITION_TRANSFER_REMOTE_REPORT, rd.getRemoteTransferReport());
// Do the status
// Includes start+end times, and running action details
setStatus(rd, rdm);
// Only include the payload entries that still exist
// Otherwise the freemarker layer gets upset about deleted nodes
List<NodeRef> payload = new ArrayList<NodeRef>();
for(NodeRef node : rd.getPayload()) {
if(nodeService.exists(node))
payload.add(node);
}
rdm.put(DEFINITION_PAYLOAD, payload);
// Save in the usual way
Map<String, Object> model = new HashMap<String,Object>();
model.put(MODEL_DATA_ITEM, rdm);
return model;
}
/**
* Figures out the status that's one of:
* New|Running|CancelRequested|Completed|Failed|Cancelled
* by merging data from the action tracking service.
* Will also set the start and end dates, from either the
* replication definition or action tracking data, depending
* on the status.
*/
protected void setStatus(ReplicationDefinition replicationDefinition,
ExecutionDetails details, Map<String, Object> model)
{
// Is it currently running?
if(details == null) {
// It isn't running, we can use the persisted details
model.put(DEFINITION_STATUS, replicationDefinition.getExecutionStatus().toString());
Date startDate = replicationDefinition.getExecutionStartDate();
if(startDate != null) {
model.put(DEFINITION_STARTED_AT, ISO8601DateFormat.format(startDate));
} else {
model.put(DEFINITION_STARTED_AT, null);
}
Date endDate = replicationDefinition.getExecutionEndDate();
if(endDate != null) {
model.put(DEFINITION_ENDED_AT, ISO8601DateFormat.format(endDate));
} else {
model.put(DEFINITION_ENDED_AT, null);
}
// It isn't running
model.put(DEFINITION_RUNNING_ACTION_ID, null);
return;
}
// As it is running / about to run, return the
// details of the running/pending version
if(details.isCancelRequested()) {
model.put(DEFINITION_STATUS, "CancelRequested");
} else if(details.getStartedAt() == null) {
model.put(DEFINITION_STATUS, "Pending");
} else {
model.put(DEFINITION_STATUS, "Running");
}
if(details.getStartedAt() != null) {
model.put(DEFINITION_STARTED_AT, ISO8601DateFormat.format(details.getStartedAt()));
} else {
model.put(DEFINITION_STARTED_AT, null);
}
model.put(DEFINITION_ENDED_AT, null);
model.put(DEFINITION_RUNNING_ACTION_ID,
AbstractActionWebscript.getRunningId(details.getExecutionSummary()));
// Since it's running / about to run, there shouldn't
// be failure messages or transfer reports
// If these currently exist on the model, remove them
if(model.containsKey(DEFINITION_FAILURE_MESSAGE))
model.put(DEFINITION_FAILURE_MESSAGE, null);
if(model.containsKey(DEFINITION_TRANSFER_LOCAL_REPORT))
model.put(DEFINITION_TRANSFER_LOCAL_REPORT, null);
if(model.containsKey(DEFINITION_TRANSFER_REMOTE_REPORT))
model.put(DEFINITION_TRANSFER_REMOTE_REPORT, null);
}
private static long getTime(String iso8601String)
{
return ISO8601DateFormat.parse(iso8601String.replace(" ", "+")).getTime();
}
protected void processVariable(String propertyName, String propertyValue, int type)
{
String localPropertyName = propertyName.replaceFirst("variables/", "");
Object actualValue = null;
DataTypeDefinition dataTypeDefinition = null;
// variable scope global is default
String scopeDef = "global";
// look for variable scope
if (localPropertyName.contains("local/"))
{
scopeDef = "local";
localPropertyName = localPropertyName.replaceFirst("local/", "");
}
if (localPropertyName.contains("global/"))
{
localPropertyName = localPropertyName.replaceFirst("global/", "");
}
// look for variable type definition
if ((propertyValue.contains("_") || propertyValue.contains(":")) && propertyValue.contains(" "))
{
int indexOfSpace = propertyValue.indexOf(' ');
if ((propertyValue.contains("_") && indexOfSpace > propertyValue.indexOf("_")) ||
(propertyValue.contains(":") && indexOfSpace > propertyValue.indexOf(":")))
{
String typeDef = propertyValue.substring(0, indexOfSpace);
try
{
QName dataType = QName.createQName(typeDef.replace('_', ':'), namespaceService);
dataTypeDefinition = dictionaryService.getDataType(dataType);
propertyValue = propertyValue.substring(indexOfSpace + 1);
}
catch (Exception e)
{
throw new ApiException("Error translating propertyName " + propertyName + " with value " + propertyValue);
}
}
}
if (dataTypeDefinition != null && "java.util.Date".equalsIgnoreCase(dataTypeDefinition.getJavaClassName()))
{
// fix for different ISO 8601 Date format classes in Alfresco (org.alfresco.util and Spring Surf)
actualValue = ISO8601DateFormat.parse(propertyValue);
}
else if (dataTypeDefinition != null)
{
actualValue = DefaultTypeConverter.INSTANCE.convert(dataTypeDefinition, propertyValue);
}
else
{
actualValue = propertyValue;
}
variableProperties.add(new QueryVariableHolder(localPropertyName, type, actualValue, scopeDef));
}