Java Code Examples for play.libs.Json#newObject()

The following examples show how to use play.libs.Json#newObject() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RMSE.java    From samantha with MIT License 6 votes vote down vote up
public MetricResult getResults() {
    ObjectNode result = Json.newObject();
    result.put(ConfigKey.EVALUATOR_METRIC_NAME.get(), "RMSE");
    ObjectNode para = Json.newObject();
    result.set(ConfigKey.EVALUATOR_METRIC_PARA.get(), para);
    double value = 0.0;
    if (n > 0) {
        value = Math.sqrt(errorSquared / n);
    }
    result.put(ConfigKey.EVALUATOR_METRIC_VALUE.get(), value);
    result.put(ConfigKey.EVALUATOR_METRIC_SUPPORT.get(), n);
    List<ObjectNode> results = new ArrayList<>(1);
    results.add(result);
    boolean pass = true;
    if (value > maxValue) {
        pass = false;
    }
    return new MetricResult(results, pass);
}
 
Example 2
Source File: ProfileController.java    From htwplus with MIT License 6 votes vote down vote up
/**
 * Get the temporary avatar image
 *
 * @param id
 * @return
 */
public Result getTempAvatar(Long id) {

    ObjectNode result = Json.newObject();
    Account account = accountManager.findById(id);

    if (account == null) {
        return notFound();
    }

    if (!Secured.editAccount(account)) {
        result.put("error", "Not allowed.");
        return forbidden(result);
    }

    File tempAvatar = avatarManager.getTempAvatar(account.id);
    if (tempAvatar != null) {
        return ok(tempAvatar);
    } else {
        return notFound();
    }
}
 
Example 3
Source File: RetrieverBasedExpander.java    From samantha with MIT License 6 votes vote down vote up
public List<ObjectNode> expand(List<ObjectNode> initialResult,
                               RequestContext requestContext) {
    List<ObjectNode> expanded = new ArrayList<>();
    for (ObjectNode entity : initialResult) {
        ObjectNode reqBody = Json.newObject();
        IOUtilities.parseEntityFromJsonNode(requestContext.getRequestBody(), reqBody);
        IOUtilities.parseEntityFromJsonNode(entity, reqBody);
        RequestContext pseudoReq = new RequestContext(reqBody, requestContext.getEngineName());
        RetrievedResult retrievedResult = retriever.retrieve(pseudoReq);
        for (ObjectNode one : retrievedResult.getEntityList()) {
            IOUtilities.parseEntityFromJsonNode(entity, one);
        }
        expanded.addAll(retrievedResult.getEntityList());
    }
    return expanded;
}
 
Example 4
Source File: AbstractModelManager.java    From samantha with MIT License 6 votes vote down vote up
public boolean passModel(Object model, RequestContext requestContext) {
    if (evaluatorNames == null || evaluatorNames.size() == 0) {
        return true;
    }
    String engineName = requestContext.getEngineName();
    boolean pass = true;
    SamanthaConfigService configService = injector.instanceOf(SamanthaConfigService.class);
    ObjectNode pseudoReqBody = Json.newObject();
    IOUtilities.parseEntityFromJsonNode(requestContext.getRequestBody(), pseudoReqBody);
    pseudoReqBody.put(ConfigKey.MODEL_OPERATION.get(), ModelOperation.EVALUATE.get());
    RequestContext pseudoReq = new RequestContext(pseudoReqBody, engineName);
    for (String name : evaluatorNames) {
        Evaluator evaluator = configService.getEvaluator(name, pseudoReq);
        if (!evaluator.evaluate(pseudoReq).getPass()) {
            pass = false;
        }
    }
    return pass;
}
 
Example 5
Source File: CSVFileIndexer.java    From samantha with MIT License 6 votes vote down vote up
public ObjectNode getIndexedDataDAOConfig(RequestContext requestContext) {
    JsonNode reqBody = requestContext.getRequestBody();
    String start = JsonHelpers.getOptionalString(reqBody, beginTimeKey,
            beginTime);
    String end = JsonHelpers.getOptionalString(reqBody, endTimeKey,
            endTime);
    int startStamp = IndexerUtilities.parseTime(start);
    int endStamp = IndexerUtilities.parseTime(end);
    List<String> files = dataService.getFiles(indexType, startStamp, endStamp);
    ObjectNode sub = Json.newObject();
    sub.set(filesKey, Json.toJson(files));
    sub.put(separatorKey, dataService.getSeparator());
    sub.put(daoNameKey, subDaoName);

    ObjectNode ret = Json.newObject();
    ret.put(daoNameKey, daoName);
    ret.put(beginTimeKey, Integer.valueOf(startStamp).toString());
    ret.put(endTimeKey, Integer.valueOf(endStamp).toString());
    ret.set(subDaoConfigKey, sub);
    return ret;
}
 
Example 6
Source File: TodoControllerTest.java    From play-rest-security with MIT License 6 votes vote down vote up
@Test
public void addTodo() {
    DemoData demoData = app.injector().instanceOf(DemoData.class);
    String authToken = demoData.user1.createToken();

    ObjectNode todoJson = Json.newObject();
    todoJson.put("value", "make it work");

    Http.RequestBuilder fakeRequest = fakeRequest(controllers.routes.TodoController.createTodo())
            .header(SecurityController.AUTH_TOKEN_HEADER, authToken)
            .bodyJson(todoJson);

    Result result = route(fakeRequest);

    assertEquals(OK, result.status());

    Todo todo = Json.fromJson(Json.parse(contentAsString(result)), Todo.class);
    assertNotNull(todo.id);
    assertEquals("make it work", todo.value);
    assertNull(todo.user); // this should not be serialized
}
 
Example 7
Source File: ResponsePacker.java    From samantha with MIT License 5 votes vote down vote up
public JsonNode packRecommendation(Recommender recommender, RankedResult rankedResult,
                                   RequestContext requestContext) {
    ObjectNode result = Json.newObject();
    result.set("recommendations", rankedResult.toJson());
    result.set("configuration", Json.toJson(recommender.getConfig().asMap()));
    result.put("engine", requestContext.getEngineName());
    return result;
}
 
Example 8
Source File: SecurityControllerTest.java    From play-rest-security with MIT License 5 votes vote down vote up
@Test
public void loginWithDifferentCaseUsername() {
    DemoData demoData = app.injector().instanceOf(DemoData.class);
    ObjectNode loginJson = Json.newObject();
    loginJson.put("emailAddress", demoData.user1.getEmailAddress().toUpperCase());
    loginJson.put("password", demoData.user1.getPassword());

    Result result = route(fakeRequest(controllers.routes.SecurityController.login()).bodyJson(loginJson));

    assertEquals(OK, result.status());
}
 
Example 9
Source File: ESRetrieverUtilities.java    From samantha with MIT License 5 votes vote down vote up
static public RetrievedResult parse(String elasticSearchScoreName, RequestContext requestContext,
                                    SearchResponse searchResponse, List<EntityExpander> expanders,
                                    List<String> retrieveFields) {
    List<ObjectNode> entityList = new ArrayList<>(searchResponse.getHits().getHits().length);
    for (SearchHit hit : searchResponse.getHits().getHits()) {
        ObjectNode entity = Json.newObject();
        ExpanderUtilities.parseEntityFromSearchHit(retrieveFields, elasticSearchScoreName,
                hit, entity);
        entityList.add(entity);
    }
    entityList = ExpanderUtilities.expand(entityList, expanders, requestContext);
    long totalHits = searchResponse.getHits().getTotalHits();
    return new RetrievedResult(entityList, totalHits);
}
 
Example 10
Source File: KnnModelTrigger.java    From samantha with MIT License 5 votes vote down vote up
public List<ObjectNode> getTriggeredFeatures(List<ObjectNode> bases) {
    Object2DoubleMap<String> item2score = new Object2DoubleOpenHashMap<>();
    int numInter = 0;
    for (ObjectNode inter : bases) {
        double weight = 1.0;
        if (inter.has(weightAttr)) {
            weight = inter.get(weightAttr).asDouble();
        }
        String key = FeatureExtractorUtilities.composeConcatenatedKey(inter, feaAttrs);
        if (weight >= 0.5 && featureKnnModel != null) {
            getNeighbors(item2score, featureKnnModel, key, weight);
        }
        if (weight < 0.5 && featureKdnModel != null) {
            getNeighbors(item2score, featureKdnModel, key, weight);
        }
        numInter++;
        if (numInter >= maxInter) {
            break;
        }
    }
    List<ObjectNode> results = new ArrayList<>();
    for (Map.Entry<String, Double> entry : item2score.entrySet()) {
        ObjectNode entity = Json.newObject();
        Map<String, String> attrVals = FeatureExtractorUtilities.decomposeKey(entry.getKey());
        for (Map.Entry<String, String> ent : attrVals.entrySet()) {
            entity.put(ent.getKey(), ent.getValue());
        }
        entity.put(scoreAttr, entry.getValue());
        results.add(entity);
    }
    results.sort(SortingUtilities.jsonFieldReverseComparator(scoreAttr));
    return results;
}
 
Example 11
Source File: CatIndexer.java    From samantha with MIT License 5 votes vote down vote up
public ObjectNode getIndexedDataDAOConfig(RequestContext requestContext) {
    ObjectNode ret = Json.newObject();
    ArrayNode daos = Json.newArray();
    ret.set(indexersDaoConfigKey, daos);
    for (String indexerName: indexerNames) {
        Indexer indexer = configService.getIndexer(indexerName, requestContext);
        daos.add(indexer.getIndexedDataDAOConfig(requestContext));
    }
    ret.put(daoNameKey, daoName);
    return ret;
}
 
Example 12
Source File: RedisVariableSpace.java    From samantha with MIT License 5 votes vote down vote up
public void ensureScalarVar(String name, int size, double initial, boolean randomize) {
    String varName = "S_" + name;
    ObjectNode obj = Json.newObject();
    obj.put("name", name);
    obj.put("initial", initial);
    obj.put("randomize", randomize);
    ensureVar(obj, varName, size);
}
 
Example 13
Source File: GroundUtils.java    From ground with Apache License 2.0 5 votes vote down vote up
private static ObjectNode getServerError(final Request request, final Throwable e) {
  Logger.error("Error! Request Path: {}\nError Message: {}\n Stack Trace: {}", request.path(), e.getMessage(), e.getStackTrace());

  ObjectNode result = Json.newObject();
  result.put("Error", "Unexpected error while processing request.");
  result.put("Request Path", request.path());

  StringWriter sw = new StringWriter();
  e.printStackTrace(new PrintWriter(sw));
  result.put("Stack Trace", sw.toString());
  return result;
}
 
Example 14
Source File: SQLBasedDAOConfig.java    From samantha with MIT License 5 votes vote down vote up
public EntityDAO getEntityDAO(RequestContext requestContext, JsonNode daoConfig) {
    SamanthaConfigService configService = injector
            .instanceOf(SamanthaConfigService.class);
    ObjectNode req = Json.newObject();
    IOUtilities.parseEntityFromJsonNode(daoConfig, req);
    String retrieverName = JsonHelpers.getOptionalString(daoConfig, retrieverNameKey, this.retrieverName);
    req.put(setCursorKey, true);
    RequestContext pseudoReq = new RequestContext(req, requestContext.getEngineName());
    Retriever retriever = configService.getRetriever(retrieverName, pseudoReq);
    if (!(retriever instanceof SQLBasedRetriever)) {
        throw new ConfigurationException(retrieverName + " must be of type " + SQLBasedRetriever.class);
    }
    return new RetrieverBasedDAO(retrieverName, configService, pseudoReq);
}
 
Example 15
Source File: ESBasedDAOConfig.java    From samantha with MIT License 5 votes vote down vote up
public EntityDAO getEntityDAO(RequestContext requestContext, JsonNode daoConfig) {
    SamanthaConfigService configService = injector
            .instanceOf(SamanthaConfigService.class);
    ObjectNode req = Json.newObject();
    IOUtilities.parseEntityFromJsonNode(daoConfig, req);
    String retrieverName = JsonHelpers.getOptionalString(daoConfig, retrieverNameKey, this.retrieverName);
    req.put(setScrollKey, true);
    RequestContext pseudoReq = new RequestContext(req, requestContext.getEngineName());
    Retriever retriever = configService.getRetriever(retrieverName, pseudoReq);
    if (!(retriever instanceof ESQueryBasedRetriever)) {
        throw new ConfigurationException(retrieverName + " must be of type " + ESQueryBasedRetriever.class);
    }
    return new RetrieverBasedDAO(retrieverName, configService, pseudoReq);
}
 
Example 16
Source File: CategoriesWithProductCountQuery.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public JsonNode getVariables() {
    final ObjectNode objectNode = Json.newObject();
    objectNode.put("limit", limit);
    objectNode.put("offset", offset);
    final ArrayNode sortArrayNode = Json.newArray();
    sort.forEach(querySort -> sortArrayNode.add(querySort.toSphereSort()));
    objectNode.set("sort", sortArrayNode);
    predicates.stream()
            .reduce(QueryPredicate::and)
            .ifPresent(joinedPredicates -> objectNode.put("where", joinedPredicates.toSphereQuery()));
    return objectNode;
}
 
Example 17
Source File: GroupController.java    From htwplus with MIT License 5 votes vote down vote up
/**
 * Create the real avatar with the given dimensions
 *
 * @param id
 * @return
 */
public Result createAvatar(long id) {
    ObjectNode result = Json.newObject();

    Group group = groupManager.findById(id);

    if (group == null) {
        return notFound();
    }

    if (!Secured.editGroup(group)) {
        result.put("error", "Not allowed.");
        return forbidden(result);
    }

    Form<Avatar> form = formFactory.form(Avatar.class).bindFromRequest();

    if (form.hasErrors()) {
        result.set("error", form.errorsAsJson());
        return badRequest(result);
    }

    try {
        groupManager.saveAvatar(form.get(), group);
        result.put("success", "saved");
        return ok(result);
    } catch (FileOperationException e) {
        result.put("error", "Unexpected Error while saving avatar.");
        return internalServerError(result);
    }
}
 
Example 18
Source File: CSVFileDAO.java    From samantha with MIT License 5 votes vote down vote up
public ObjectNode getNextEntity() {
    Map<String, Object> rowAsMap;
    try {
        rowAsMap = it.next();
    } catch (Exception e) {
        rowAsMap = new HashMap<>();
    }
    ObjectNode entity = Json.newObject();
    IOUtilities.parseEntityFromMap(entity, rowAsMap);
    cnt++;
    if (cnt % 1000000 == 0) {
        logger.info("Read {} entities.", cnt);
    }
    return entity;
}
 
Example 19
Source File: MockJsonSerializable.java    From htwplus with MIT License 5 votes vote down vote up
@Override
public ObjectNode getAsJson() {
    ObjectNode node = Json.newObject();
    node.put("class_name", this.getClass().getSimpleName());
    node.put("time", (new Date()).getTime());
    node.put("random", (new Random()).nextInt(100));

    return node;
}
 
Example 20
Source File: TensorFlowBatchIndexerTest.java    From samantha with MIT License 4 votes vote down vote up
@Test
public void testTensorFlowBatchIndex() {
    SamanthaConfigService configService = injector.instanceOf(SamanthaConfigService.class);
    MockIndexer mockIndexer = new MockIndexer(
            config, configService, injector, "daoConfig", config);
    SpaceProducer spaceProducer = injector.instanceOf(SpaceProducer.class);
    List<FeatureExtractor> featureExtractors = new ArrayList<>();
    FeatureExtractor itemExtractor = new SeparatedStringExtractor(
            "ITEM", "item", "item", "\\|",
            false, null, null
    );
    featureExtractors.add(itemExtractor);
    FeatureExtractor attrExtractor = new SeparatedStringExtractor(
            "ATTR", "attr", "attr", "\\|",
            false, "null", null
    );
    featureExtractors.add(attrExtractor);
    FeatureExtractor sizeExtractor = new SeparatedStringSizeExtractor(
            "SEQ_LEN", "item", "sequence_length",
            "|", null
    );
    featureExtractors.add(sizeExtractor);
    TensorFlowModel model = new TensorFlowModelProducer(spaceProducer)
            .createTensorFlowModelModelFromGraphDef(
                    "name", SpaceMode.DEFAULT, "shouldNotExist.graph",
                    null, new ArrayList<>(), null,
                    Lists.newArrayList("ITEM", "ATTR", "SEQ_LEN"),
                    featureExtractors, "loss", "update",
                    "output", "init", "top_k",
                    "topKId", "topKValue", "ITEM");
    TensorFlowBatchIndexer batchIndexer = new TensorFlowBatchIndexer(
            configService, config, injector, config, "daoConfig", mockIndexer,
            model, 1, "tstamp");
    ArrayNode batch = Json.newArray();
    ObjectNode user1 = Json.newObject();
    user1.put("item", "20|49|10|2|4");
    user1.put("attr", "jid|cjk|je|je|cjk");
    batch.add(user1);
    ObjectNode user2 = Json.newObject();
    user2.put("item", "14|19|2|5|20|15|2");
    user2.put("attr", "cjk|mn|je|lk|jid|null|je");
    batch.add(user2);
    RequestContext requestContext = new RequestContext(Json.newObject(), "test");
    batchIndexer.index(batch, requestContext);
    ArrayNode indexed = mockIndexer.getIndexed();
    assertEquals("1,2,3,4,5,6,7,4,8,1,9,4", indexed.get(0).get("item_idx").asText());
    assertEquals("1,2,3,3,2,2,4,3,5,1,6,3", indexed.get(0).get("attr_idx").asText());
    assertEquals("5.0,7.0", indexed.get(0).get("sequence_length_val").asText());
    batch.removeAll();
    indexed.removeAll();
    ObjectNode item1 = Json.newObject();
    item1.put("item", "20");
    item1.put("attr", "jid");
    batch.add(item1);
    ObjectNode item2 = Json.newObject();
    item2.put("item", "15");
    batch.add(item2);
    ObjectNode item3 = Json.newObject();
    item3.put("item", "40");
    item3.put("attr", "cjk");
    batch.add(item3);
    ObjectNode item4 = Json.newObject();
    item4.put("item", "41");
    item4.put("attr", "djkfds");
    batch.add(item4);
    batchIndexer.index(batch, requestContext);
    assertEquals("1,9,10,11", indexed.get(0).get("item_idx").asText());
    assertEquals("1,6,2,7", indexed.get(0).get("attr_idx").asText());
}