Example #1
0
  @Security.Authenticated(SecuriteAPI.class)
  public static Result labelsUtilisateurs() {
    if (Securite.utilisateur().getRole() != Utilisateur.Role.ADMIN) {
      return unauthorized();
    }

    ObjectNode json =
        JsonUtils.genererReponseJson(JsonUtils.JsonStatut.OK, "Récupération des labels effectuée");

    UtilisateurService.LabelsResult labelsResult = UtilisateurService.getLabels();
    ArrayNode auth = new ArrayNode(JsonNodeFactory.instance);
    for (String s : labelsResult.types_auth) {
      auth.add(s);
    }

    ArrayNode roles = new ArrayNode(JsonNodeFactory.instance);
    for (String s : labelsResult.roles) {
      roles.add(s);
    }

    json.put("services", auth);
    json.put("roles", roles);

    // attendu: msg.statut, msg.services, msg.roles
    return ok(json);
  }
  @Test
  public void testGroupByWithSum1()
      throws JsonGenerationException, JsonMappingException, IOException, InterruptedException {
    Object[][] rows1 = {{0}, {2}, {2}, {5}, {10}, {100}};
    Block block = new ArrayBlock(Arrays.asList(rows1), new String[] {"a"}, 1);

    TupleOperator operator = new GroupByOperator();
    Map<String, Block> input = new HashMap<String, Block>();
    input.put("first", block);

    ObjectMapper mapper = new ObjectMapper();
    ObjectNode json = mapper.createObjectNode();
    json.put("input", "first");
    ArrayNode anode = mapper.createArrayNode();
    anode.add("a");
    json.put("groupBy", anode);
    anode = mapper.createArrayNode();
    ObjectNode onode = mapper.createObjectNode();
    onode.put("type", "SUM");
    onode.put("input", "a");
    onode.put("output", "sum");
    anode.add(onode);
    json.put("aggregates", anode);

    BlockProperties props =
        new BlockProperties(null, new BlockSchema("INT a, INT sum"), (BlockProperties) null);
    operator.setInput(input, json, props);

    Block output = new TupleOperatorBlock(operator, props);

    ArrayBlock.assertData(
        output,
        new Object[][] {{0, 0}, {2, 4}, {5, 5}, {10, 10}, {100, 100}},
        new String[] {"a", "sum"});
  }
  public static String getSerializedJSON(List<SearchResult> searchResults) {
    ArrayNode resultArray = JsonNodeFactory.instance.arrayNode();
    for (SearchResult result : searchResults) {
      ObjectNode resultNode = JsonNodeFactory.instance.objectNode();
      resultNode.put("metric", result.getMetricName());

      String unit = result.getUnit();
      if (unit != null) {
        // Preaggreated metrics do not have units. Do not want to return null units in query
        // results.
        resultNode.put("unit", unit);
      }

      // get enum values and add if applicable
      List<String> enumValues = result.getEnumValues();
      if (enumValues != null) {
        // sort for consistent result ordering
        Collections.sort(enumValues);
        ArrayNode enumValuesArray = JsonNodeFactory.instance.arrayNode();
        for (String val : enumValues) {
          enumValuesArray.add(val);
        }
        resultNode.put("enum_values", enumValuesArray);
      }

      resultArray.add(resultNode);
    }
    return resultArray.toString();
  }
Example #4
0
  /**
   * Generates the JSON code for the raw log entry collection.
   *
   * @param model the model data to output
   * @param locale the locale indicating the language in which localizable data should be shown
   * @return a string containing the JSON code for the raw log entry collection
   * @throws MonitorInterfaceException
   *     <ul>
   *       <li>the model data is invalid
   *       <li>an error occurred while converting the raw log entry collection to JSON
   *     </ul>
   */
  @SuppressWarnings("unchecked")
  @Override
  protected JsonNode getResponseData(Map<String, ?> model, Locale locale)
      throws MonitorInterfaceException {

    if (model.containsKey("rawLogsCollection") && model.containsKey("addQueryId")) {

      if (model.containsKey("getExport")
          && model.containsKey("Slaname")
          && model.containsKey("Jobname")
          && model.containsKey("Queryname")) {
        final Set<RawLogEntry> logsCollection = (Set<RawLogEntry>) model.get("rawLogsCollection");
        final Boolean addQueryId = (Boolean) model.get("addQueryId");
        final Boolean getExport = (Boolean) model.get("getExport");
        final Boolean isSummary = (Boolean) model.get("isSummary");
        final String slaName = (String) model.get("Slaname");
        final String jobName = (String) model.get("Jobname");
        final String queryName = (String) model.get("Queryname");
        final ObjectMapper mapper = this.getObjectMapper();
        final ArrayNode rowsCollection = mapper.createArrayNode();
        List<RawLogEntry> sortLogs = new ArrayList<RawLogEntry>(logsCollection);
        Collections.sort(sortLogs, new MyLogComparable());

        for (RawLogEntry logEntry : sortLogs) {
          rowsCollection.add(
              RawLogSerializer.serialize(
                  logEntry,
                  addQueryId,
                  getExport,
                  slaName,
                  jobName,
                  queryName,
                  locale,
                  mapper,
                  isSummary,
                  null));
        }
        return rowsCollection;
      } else {
        final Set<RawLogEntry> logsCollection = (Set<RawLogEntry>) model.get("rawLogsCollection");
        final Boolean addQueryId = (Boolean) model.get("addQueryId");
        final Boolean isSummary = (Boolean) model.get("isSummary");
        final Long noPagingCount = (Long) model.get("noPagingCount");
        final ObjectMapper mapper = this.getObjectMapper();
        this.getRootObjectNode().put("noPagingCount", noPagingCount);
        final ArrayNode rowsCollection = mapper.createArrayNode();
        for (RawLogEntry logEntry : logsCollection) {
          rowsCollection.add(
              RawLogSerializer.serialize(logEntry, addQueryId, locale, mapper, isSummary));
        }
        return rowsCollection;
      }
    }
    throw new MonitorInterfaceException("An internal error occurred", "internal.error");
  }
Example #5
0
  public static void main(String args[]) {

    JacksonTester tester = new JacksonTester();

    try {
      ObjectMapper mapper = new ObjectMapper();

      JsonNode rootNode = mapper.createObjectNode();
      JsonNode marksNode = mapper.createArrayNode();

      ((ArrayNode) marksNode).add(100);
      ((ArrayNode) marksNode).add(90);
      ((ArrayNode) marksNode).add(85);

      ((ObjectNode) rootNode).put("name", "Mahesh Kumar");
      ((ObjectNode) rootNode).put("age", 21);
      ((ObjectNode) rootNode).put("verified", false);
      ((ObjectNode) rootNode).put("marks", marksNode);

      mapper.writeValue(new File("student.json"), rootNode);

      rootNode = mapper.readTree(new File("student.json"));

      JsonNode nameNode = rootNode.path("name");
      System.out.println("Name: " + nameNode.getTextValue());

      JsonNode ageNode = rootNode.path("age");
      System.out.println("Age: " + ageNode.getIntValue());

      JsonNode verifiedNode = rootNode.path("verified");
      System.out.println("Verified: " + (verifiedNode.getBooleanValue() ? "Yes" : "No"));

      JsonNode marksNode1 = rootNode.path("marks");
      Iterator<JsonNode> iterator = marksNode1.getElements();
      System.out.print("Marks: [ ");

      while (iterator.hasNext()) {
        JsonNode marks = iterator.next();
        System.out.print(marks.getIntValue() + " ");
      }

      System.out.println("]");
    } catch (JsonParseException e) {
      e.printStackTrace();
    } catch (JsonMappingException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Example #6
0
 private ArrayNode createSerializedTimestamp(int[] vector, ObjectMapper mapper) {
   ArrayNode ret = mapper.createArrayNode();
   for (int val : vector) {
     ret.add(val);
   }
   return ret;
 }
  private void addJsonParameters(
      String propertyName, List<IOParameter> parameterList, ObjectNode propertiesNode) {
    ObjectNode parametersNode = objectMapper.createObjectNode();
    ArrayNode itemsNode = objectMapper.createArrayNode();
    for (IOParameter parameter : parameterList) {
      ObjectNode parameterItemNode = objectMapper.createObjectNode();
      if (StringUtils.isNotEmpty(parameter.getSource())) {
        parameterItemNode.put(PROPERTY_IOPARAMETER_SOURCE, parameter.getSource());
      } else {
        parameterItemNode.putNull(PROPERTY_IOPARAMETER_SOURCE);
      }
      if (StringUtils.isNotEmpty(parameter.getTarget())) {
        parameterItemNode.put(PROPERTY_IOPARAMETER_TARGET, parameter.getTarget());
      } else {
        parameterItemNode.putNull(PROPERTY_IOPARAMETER_TARGET);
      }
      if (StringUtils.isNotEmpty(parameter.getSourceExpression())) {
        parameterItemNode.put(
            PROPERTY_IOPARAMETER_SOURCE_EXPRESSION, parameter.getSourceExpression());
      } else {
        parameterItemNode.putNull(PROPERTY_IOPARAMETER_SOURCE_EXPRESSION);
      }

      itemsNode.add(parameterItemNode);
    }

    parametersNode.put("totalCount", itemsNode.size());
    parametersNode.put(EDITOR_PROPERTIES_GENERAL_ITEMS, itemsNode);
    propertiesNode.put(propertyName, parametersNode);
  }
Example #8
0
  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String thisUsersId = req.getParameter("userId");
    if ("true".equals(req.getParameter("pingAlive"))) {
      updateLastAliveTime(thisUsersId);
    } else {
      ObjectMapper mapper = new ObjectMapper();

      ArrayNode usersArray = mapper.createArrayNode();

      for (Map.Entry<String, User> userEntry : users.entrySet()) {
        if (!thisUsersId.equals(userEntry.getKey())) {
          User user = userEntry.getValue();
          Date now = new Date();
          if ((now.getTime() - user.getLastAliveTime().getTime()) / 1000 <= 10) {
            ObjectNode userJson = mapper.createObjectNode();
            userJson.put("user_id", userEntry.getKey());
            userJson.put("user_name", user.getName());
            usersArray.add(userJson);
          }
        }
      }

      ObjectNode usersJson = mapper.createObjectNode();
      usersJson.put("opponents", usersArray);

      resp.setContentType("application/json; charset=UTF-8");
      mapper.writeValue(resp.getWriter(), usersJson);
    }
  }
  ObjectNode createNamespaceNode(ArrayNode container) {
    ObjectNode ns = container.objectNode();
    ns.put(Constants.EJS_NS_KEYWORD, ns.objectNode());
    container.add(ns);

    return ns;
  }
  @Test
  public void testSortOperator()
      throws JsonGenerationException, JsonMappingException, IOException, InterruptedException {
    System.out.println("Testing SORT operator");

    Object[][] rows1 = {{0, 10, 0}, {2, 5, 2}, {2, 8, 5}, {5, 9, 6}, {10, 11, 1}, {100, 6, 10}};
    Block block = new ArrayBlock(Arrays.asList(rows1), new String[] {"a", "b", "c"}, 1);

    TupleOperator operator = new SortOperator();
    Map<String, Block> input = new HashMap<String, Block>();
    input.put("unsorted", block);

    ObjectMapper mapper = new ObjectMapper();

    ObjectNode json = mapper.createObjectNode();
    json.put("input", "unsorted");
    ArrayNode anode = mapper.createArrayNode();
    anode.add("b");
    anode.add("c");
    json.put("sortBy", anode);

    BlockProperties props =
        new BlockProperties(null, new BlockSchema("INT a, INT b, INT c"), (BlockProperties) null);
    operator.setInput(input, json, props);

    Block output = new TupleOperatorBlock(operator, props);

    System.out.println("output is " + output);
    ArrayBlock.assertData(
        output,
        new Object[][] {{2, 5, 2}, {100, 6, 10}, {2, 8, 5}, {5, 9, 6}, {0, 10, 0}, {10, 11, 1}},
        new String[] {"a", "b", "c"});
  }
    // jquery-validation call
    @RequestMapping(value = "/validate", method = RequestMethod.GET)
    @ResponseBody
    public Object validateField(String fieldId, String fieldValue, String _) {

        ObjectMapper mapper = new ObjectMapper();
        ArrayNode arrayNode = mapper.createArrayNode();

        boolean result;

        if (fieldId.equals("email")) {
            arrayNode.add(fieldId);
            result = mAccountService.validateEmail(fieldValue);
            arrayNode.add(result);
        }

        return arrayNode;
    }
 /**
  * @deprecated since 0.6.0 use {@link #fetch(String)} (with slightly different, but better
  *     semantics)
  */
 @Deprecated
 @Override
 public JsonNode applicationTree() {
   ArrayNode apps = mapper().createArrayNode();
   for (Application application : mgmt().getApplications())
     apps.add(recursiveTreeFromEntity(application));
   return apps;
 }
 private static ArrayNode createJSONList(
     final List list, final List<String> propertyKeys, final boolean showTypes) {
   final ArrayNode jsonList = jsonNodeFactory.arrayNode();
   for (Object item : list) {
     if (item instanceof Element) {
       jsonList.add(createJSONElementAsObjectNode((Element) item, propertyKeys, showTypes));
     } else if (item instanceof List) {
       jsonList.add(createJSONList((List) item, propertyKeys, showTypes));
     } else if (item instanceof Map) {
       jsonList.add(createJSONMap((Map) item, propertyKeys, showTypes));
     } else if (item != null && item.getClass().isArray()) {
       jsonList.add(createJSONList(convertArrayToList(item), propertyKeys, showTypes));
     } else {
       addObject(jsonList, item);
     }
   }
   return jsonList;
 }
 private ArrayNode childEntitiesRecursiveAsArray(Entity entity) {
   ArrayNode node = mapper().createArrayNode();
   for (Entity e : entity.getChildren()) {
     if (Entitlements.isEntitled(
         mgmt().getEntitlementManager(), Entitlements.SEE_ENTITY, entity)) {
       node.add(recursiveTreeFromEntity(e));
     }
   }
   return node;
 }
Example #15
0
  public static ObjectNode entityListToJson(List<Entity> entityList) throws LeanException {
    ObjectNode json = getObjectMapper().createObjectNode();
    ArrayNode array = getObjectMapper().createArrayNode();

    for (Entity entity : entityList) {
      array.add(entityToJson(entity));
    }
    json.put("result", array);
    return json;
  }
 private ArrayNode entitiesIdAsArray(Iterable<? extends Entity> entities) {
   ArrayNode node = mapper().createArrayNode();
   for (Entity entity : entities) {
     if (Entitlements.isEntitled(
         mgmt().getEntitlementManager(), Entitlements.SEE_ENTITY, entity)) {
       node.add(entity.getId());
     }
   }
   return node;
 }
  private ArrayNode createJsonForGenerate(Object vectorIdentifier) {
    ArrayNode outputTupleJson = JsonUtils.createArrayNode();

    // + First duplicate existing schema
    for (String s : inputBlock.getProperties().getSchema().getColumnNames()) {
      outputTupleJson.add(RewriteUtils.createProjectionExpressionNode(s, s));
    }

    // + Add the new generated column
    JsonNode constNode;
    if (vectorIdentifier instanceof String)
      constNode = RewriteUtils.createStringConstant((String) vectorIdentifier);
    else constNode = RewriteUtils.createIntegerConstant((Integer) vectorIdentifier);

    String outColName = metaRelationName + "___" + identifierColumnName;
    outputTupleJson.add(
        JsonUtils.createObjectNode("col_name", outColName, "expression", constNode));
    return outputTupleJson;
  }
Example #18
0
  public ObjectNode toJson() {
    try {
      JsonNodeFactory nf = JsonNodeFactory.instance;
      ObjectNode all = nf.objectNode();
      all.put("allconvs", mAllConvs);
      all.put("convs", mConvs);
      all.put("clicks", mClicks);
      all.put("imps", mImps);
      all.put("bids", mBids);
      all.put("aucs", mAucs);
      all.put("uniques", mUniques);
      ArrayNode winNodes = new ArrayNode(nf);
      Iterator<Double> winIter = mPercentKey.iterator();
      while (winIter.hasNext()) {
        Double winPercent = winIter.next();
        Integer winCount = mWinPercent.get(winPercent);
        ObjectNode winCountN = nf.objectNode();
        winCountN.put("winPercent", winPercent);
        winCountN.put("winCount", winCount);
        winNodes.add(winCountN);
      }
      Iterator<Double> bidIter = mPercentKey.iterator();
      while (bidIter.hasNext()) {
        Double bidPercent = bidIter.next();
        Integer bidCount = mBidPercent.get(bidPercent);
        ObjectNode bidCountN = nf.objectNode();
        bidCountN.put("bidPercent", bidPercent);
        bidCountN.put("bidCount", bidCount);
        winNodes.add(bidCountN);
      }
      all.put("WinBidPercent", winNodes);
      if (mShwhr != null && mShwhr.length() > 0) {
        all.put("shwhr", mShwhr);
      }

      return all;
    } catch (Exception ex) {
      System.out.println(ex.getMessage());
      return null;
    }
  }
  @GET
  @Produces(MediaType.APPLICATION_JSON)
  @Path("/attribute")
  public String getAttributes() {
    ArrayNode noAttributes = JsonNodeFactory.instance.arrayNode();

    for (Attribute attribute : LomBusinessFacade.getInstance().getAllAttributes()) {
      noAttributes.add(attribute.getJson());
    }

    return noAttributes.toString();
  }
  @GET
  @Produces(MediaType.APPLICATION_JSON)
  @Path("/class")
  public String getClasses() {
    ArrayNode noClasses = JsonNodeFactory.instance.arrayNode();

    for (Clazz clazz : LomBusinessFacade.getInstance().getAllClasses()) {
      noClasses.add(clazz.getJson());
    }

    return noClasses.toString();
  }
  /**
   * Calculate the results graph data. The graph includes final rank graph and final vs provisional
   * score graph.
   *
   * @param resultInfos the results
   */
  private void calculateResultsGraphData(List<ResultInfo> resultInfos) {
    // Sort the results info by final score.
    Collections.sort(
        resultInfos,
        new Comparator<ResultInfo>() {
          public int compare(ResultInfo resultInfo, ResultInfo resultInfo2) {
            if (resultInfo.getFinalRank() < resultInfo2.getFinalRank()) {
              return 0;
            }
            if (resultInfo.getFinalRank() == resultInfo2.getFinalRank()) {
              return String.CASE_INSENSITIVE_ORDER.compare(
                  resultInfo.getHandle(), resultInfo2.getHandle());
            }
            return 1;
          }
        });
    ObjectMapper objectMapper = new ObjectMapper();
    ObjectNode finalScoreRankingData = objectMapper.createObjectNode();
    ObjectNode finalVsProvisionalScoreData = objectMapper.createObjectNode();
    ArrayNode rating = objectMapper.createArrayNode();
    ArrayNode score = objectMapper.createArrayNode();
    for (ResultInfo result : resultInfos) {
      ObjectNode finalScoreNode = objectMapper.createObjectNode();
      finalScoreNode.put("handle", result.getHandle());
      finalScoreNode.put("number", result.getFinalScore());
      finalScoreNode.put("rank", result.getFinalRank());
      rating.add(finalScoreNode);

      ObjectNode finalProvisionalScoreNode = objectMapper.createObjectNode();
      finalProvisionalScoreNode.put("handle", result.getHandle());
      finalProvisionalScoreNode.put("finalScore", result.getFinalScore());
      finalProvisionalScoreNode.put("provisionalScore", result.getProvisionalScore());
      score.add(finalProvisionalScoreNode);
    }
    finalScoreRankingData.put("rating", rating);
    finalVsProvisionalScoreData.put("score", score);

    viewData.setFinalScoreRankingData(finalScoreRankingData.toString());
    viewData.setFinalVsProvisionalScoreData(finalVsProvisionalScoreData.toString());
  }
  @Test
  // testing multiple join keys
  public void testMergeJoinMultipleJoinKeys()
      throws JsonGenerationException, JsonMappingException, IOException, InterruptedException {
    Object[][] rows1 = {{0, 1}, {2, 1}, {2, 2}, {5, 1}, {10, 1}, {100, 1}};
    Object[][] rows2 = {{1, 1}, {2, 0}, {2, 1}, {5, 1}, {100, 2}, {100, 3}};
    Object[][] expected = {{2, 1, 2, 1}, {5, 1, 5, 1}};

    Block block1 = new ArrayBlock(Arrays.asList(rows1), new String[] {"a", "b"});
    Block block2 = new ArrayBlock(Arrays.asList(rows2), new String[] {"c", "a"});

    TupleOperator operator = new MergeJoinOperator();
    Map<String, Block> input = new HashMap<String, Block>();
    input.put("block1", block1);
    input.put("block2", block2);

    ObjectMapper mapper = new ObjectMapper();
    ObjectNode node = mapper.createObjectNode();
    ArrayNode lkeys = mapper.createArrayNode();
    lkeys.add("a");
    lkeys.add("b");
    node.put("leftCubeColumns", lkeys);
    ArrayNode rkeys = mapper.createArrayNode();
    rkeys.add("c");
    rkeys.add("a");
    node.put("rightCubeColumns", rkeys);
    node.put("leftBlock", "block1");

    BlockProperties props =
        new BlockProperties(
            null,
            new BlockSchema("INT block1___a, INT block1___b, INT block2___c, INT block2___a"),
            (BlockProperties) null);
    operator.setInput(input, node, props);

    Block output = new TupleOperatorBlock(operator, props);

    ArrayBlock.assertData(output, expected, new String[] {"block1.a", "block2.a"});
  }
 private ArrayNode entitiesIdAndNameAsArray(Collection<? extends Entity> entities) {
   ArrayNode node = mapper().createArrayNode();
   for (Entity entity : entities) {
     if (Entitlements.isEntitled(
         mgmt().getEntitlementManager(), Entitlements.SEE_ENTITY, entity)) {
       ObjectNode holder = mapper().createObjectNode();
       holder.put("id", entity.getId());
       holder.put("name", entity.getDisplayName());
       node.add(holder);
     }
   }
   return node;
 }
  protected void convertElementToJson(ObjectNode propertiesNode, FlowElement flowElement) {
    BoundaryEvent boundaryEvent = (BoundaryEvent) flowElement;
    ArrayNode dockersArrayNode = objectMapper.createArrayNode();
    ObjectNode dockNode = objectMapper.createObjectNode();
    GraphicInfo graphicInfo = model.getGraphicInfo(boundaryEvent.getId());
    GraphicInfo parentGraphicInfo = model.getGraphicInfo(boundaryEvent.getAttachedToRef().getId());
    dockNode.put(EDITOR_BOUNDS_X, graphicInfo.x + graphicInfo.width - parentGraphicInfo.x);
    dockNode.put(EDITOR_BOUNDS_Y, graphicInfo.y - parentGraphicInfo.y);
    dockersArrayNode.add(dockNode);
    flowElementNode.put("dockers", dockersArrayNode);

    addEventProperties(boundaryEvent, propertiesNode);
  }
 private static void addObject(final ArrayNode jsonList, final Object value) {
   if (value == null) {
     jsonList.add((JsonNode) null);
   } else if (value instanceof Boolean) {
     jsonList.add((Boolean) value);
   } else if (value instanceof Long) {
     jsonList.add((Long) value);
   } else if (value instanceof Integer) {
     jsonList.add((Integer) value);
   } else if (value instanceof Float) {
     jsonList.add((Float) value);
   } else if (value instanceof Double) {
     jsonList.add((Double) value);
   } else if (value instanceof String) {
     jsonList.add((String) value);
   } else if (value instanceof ObjectNode) {
     jsonList.add((ObjectNode) value);
   } else if (value instanceof ArrayNode) {
     jsonList.add((ArrayNode) value);
   } else {
     jsonList.add(value.toString());
   }
 }
 @GET
 @Produces(MediaType.APPLICATION_JSON)
 @Path("/class/{fullName}/attributes")
 public String getAttributesFromClass(@PathParam("fullName") String fullName) {
   Clazz clazz = LomBusinessFacade.getInstance().getClass(fullName);
   ArrayNode attributesNode = JsonNodeFactory.instance.arrayNode();
   if (clazz != null) {
     List<Attribute> attributes =
         LomBusinessFacade.getInstance().getAttributesByClassID(clazz.getId());
     for (Attribute attribute : attributes) {
       attributesNode.add(attribute.getJson());
     }
   }
   return attributesNode.toString();
 }
  /**
   * Generates the JSON code for the query collection.
   *
   * @param model the model data to output
   * @param locale the locale indicating the language in which localizable data should be shown
   * @return a string containing the JSON code for the query collection
   * @throws MonitorInterfaceException
   *     <ul>
   *       <li>the model data is invalid
   *       <li>an error occurred while converting the query collection to JSON
   *     </ul>
   */
  @SuppressWarnings("unchecked")
  @Override
  protected JsonNode getResponseData(Map<String, ?> model, Locale locale)
      throws MonitorInterfaceException {

    if (model.containsKey("queryCollection")) {
      final ObjectMapper mapper = this.getObjectMapper();
      final ArrayNode queriesList = mapper.createArrayNode();

      for (Query query : (Collection<Query>) model.get("queryCollection")) {

        queriesList.add(QuerySerializer.serialize(query, true, locale, mapper));
      }

      return queriesList;
    }

    throw new MonitorInterfaceException("An internal error occurred", "internal.error");
  }
Example #28
0
  @Security.Authenticated(SecuriteAPI.class)
  public static Result listeUtilisateurs() {
    if (SecuriteAPI.utilisateur().getRole() != Utilisateur.Role.ADMIN) {
      return unauthorized();
    }

    List<Utilisateur> utilisateurs = UtilisateurService.utilisateurs();
    ObjectNode json =
        JsonUtils.genererReponseJson(
            JsonUtils.JsonStatut.OK, utilisateurs.size() + " utilisateur(s) trouvés.");
    ArrayNode jsonUtilisateurs = new ArrayNode(JsonNodeFactory.instance);
    for (Utilisateur u : utilisateurs) {
      jsonUtilisateurs.add(u.toJsonMinimal());
    }
    json.put(Constantes.JSON_UTILISATEURS, jsonUtilisateurs);

    // attendu: msg.statut, msg.utilisateurs = [{id, login, service, type, nom, prenom}]
    return ok(json);
  }
Example #29
0
 private static void addTypedValueToArray(ArrayNode node, Object value) {
   if (value instanceof Long) {
     node.add((Long) value);
   } else if (value instanceof Double) {
     node.add((Double) value);
   } else if (value instanceof String) {
     node.add((String) value);
   } else if (value instanceof Boolean) {
     node.add((Boolean) value);
   } else if (value instanceof Date) {
     node.add(getDateNode((Date) value));
   } else if (value instanceof Text) {
     node.add(getTextNode((Text) value));
   }
 }
  @Override
  public JsonNode fetch(String entityIds) {
    Map<String, JsonNode> jsonEntitiesById = MutableMap.of();
    for (Application application : mgmt().getApplications())
      jsonEntitiesById.put(application.getId(), fromEntity(application));
    if (entityIds != null) {
      for (String entityId : entityIds.split(",")) {
        Entity entity = mgmt().getEntityManager().getEntity(entityId.trim());
        while (entity != null && entity.getParent() != null) {
          if (Entitlements.isEntitled(
              mgmt().getEntitlementManager(), Entitlements.SEE_ENTITY, entity)) {
            jsonEntitiesById.put(entity.getId(), fromEntity(entity));
          }
          entity = entity.getParent();
        }
      }
    }

    ArrayNode result = mapper().createArrayNode();
    for (JsonNode n : jsonEntitiesById.values()) result.add(n);
    return result;
  }