Skip to content

Instantly share code, notes, and snippets.

@dav-rob
Created July 20, 2011 09:27
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save dav-rob/1094650 to your computer and use it in GitHub Desktop.
public class MyLatestActivitySorterFactory implements NativeScriptFactory{
protected ObjectMapper mapper;
//2011-02-12 18:11:00.0
private DateFormat myDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
private final static Log LOG = LogFactory.getLog(MyLatestActivitySorterFactory.class);
@Override
public ExecutableScript newScript(Map<String, Object> params) {
if (mapper == null){
mapper = new ObjectMapper();
mapper.getDeserializationConfig().setDateFormat(myDateFormat);
//mapper.getSerializationConfig().setDateFormat(myDateFormat);
}
return new MyLatestActivitySortScript(params);
}
class MyLatestActivitySortScript extends AbstractFloatSearchScript {
private Map<String, Object> params;
public MyLatestActivitySortScript(Map<String, Object> params) {
this.params = params;
}
@Override
public float runAsFloat() {
DocLookup doc = doc();
StringDocFieldData myLatestActivitiesField = doc.field("myLatestActivitiesJson");
String myLatestActivityJSON = myLatestActivitiesField.getStringValue();
LOG.info("MyLatest JSON\n" + myLatestActivityJSON);
if (myLatestActivityJSON == null || myLatestActivityJSON.trim().equals("")){
return 0;
}
Map<Integer, Date> myLatestActivitiesMap = unMarshallMyLatestActivityMap(myLatestActivityJSON);
//String indexFieldName = (String)params.get("indexFieldName");
Integer userId = (Integer)params.get("userId");
Float score = getScore(myLatestActivitiesMap, userId);
LOG.info("MyLastActivity JSON[" + myLatestActivityJSON + "], gives score " + score);
String sortDirection = (String)params.get("sortDirection");
LOG.info("Sort Direction[" + sortDirection + "]");
if (sortDirection == null || (sortDirection != null && !sortDirection.toUpperCase().trim().equals("DESC"))){
LOG.info("Applying ASC sort order!");
score = 0- score;
}
return score;
}
}
public Float getScore(Map<Integer, Date> myLatestActivitiesMap, Integer userId){
Date date = myLatestActivitiesMap.get(userId);
Long time = date.getTime();
Float score = time.floatValue();
return score;
}
protected Map<Integer, Date> unMarshallMyLatestActivityMap(String myLatestActivityJSON) {
Map<Integer, Date> myLatestActivitiesMap = null;
try {
myLatestActivitiesMap = (Map<Integer, Date>)mapper.readValue(myLatestActivityJSON, new TypeReference<HashMap<Integer, Date>>(){});
} catch (Exception e){
LOG.error("Error unmarshalling myLastestActivities JSON", e);
return null;
}
return myLatestActivitiesMap;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment