Beispiel #1
1
  /**
   * Create job arguments that are used by CrowdClient to build a POST request for a new job on
   * Crowdflower
   */
  void createArgumentMaps() {
    argumentMap = new LinkedMultiValueMap<String, String>();
    includedCountries = new Vector<String>();
    excludedCountries = new Vector<String>();

    Iterator<Map.Entry<String, JsonNode>> jsonRootIt = template.fields();

    for (Map.Entry<String, JsonNode> elt; jsonRootIt.hasNext(); ) {
      elt = jsonRootIt.next();

      JsonNode currentNode = elt.getValue();
      String currentKey = elt.getKey();

      if (currentNode.isContainerNode()) {
        // special processing for these arrays:
        if (currentKey.equals(includedCountriesKey) || currentKey.equals(excludedCountriesKey)) {
          Iterator<JsonNode> jsonSubNodeIt = currentNode.elements();
          for (JsonNode subElt; jsonSubNodeIt.hasNext(); ) {
            subElt = jsonSubNodeIt.next();
            (currentKey.equals(includedCountriesKey) ? includedCountries : excludedCountries)
                .addElement(subElt.path(countryCodeKey).asText());
          }
        }
      } else if (!currentNode.isNull() && argumentFilterSet.contains(currentKey)) {
        argumentMap.add(jobKey + "[" + currentKey + "]", currentNode.asText());
      }
      if (currentKey == idKey) {
        this.id = currentNode.asText();
      }
    }
  }
Beispiel #2
0
  @SuppressWarnings({"rawtypes", "unchecked"})
  private final ContinuousMapping parseContinuous(
      String columnName,
      Class<?> type,
      VisualProperty<?> vp,
      VisualMappingFunctionFactory factory,
      JsonNode mappingNode) {

    final ContinuousMapping mapping =
        (ContinuousMapping) factory.createVisualMappingFunction(columnName, type, vp);
    for (JsonNode point : mappingNode.get("points")) {
      JsonNode val = point.get("value");
      JsonNode lesser = point.get("lesser");
      JsonNode equal = point.get("equal");
      JsonNode greater = point.get("greater");

      final BoundaryRangeValues newPoint =
          new BoundaryRangeValues(
              vp.parseSerializableString(lesser.asText()),
              vp.parseSerializableString(equal.asText()),
              vp.parseSerializableString(greater.asText()));
      mapping.addPoint(val.asDouble(), newPoint);
    }

    return mapping;
  }
  protected void localize(ProcessInstance processInstance) {
    ExecutionEntity processInstanceExecution = (ExecutionEntity) processInstance;
    processInstanceExecution.setLocalizedName(null);
    processInstanceExecution.setLocalizedDescription(null);

    if (locale != null) {
      String processDefinitionId = processInstanceExecution.getProcessDefinitionId();
      if (processDefinitionId != null) {
        ObjectNode languageNode =
            Context.getLocalizationElementProperties(
                locale,
                processInstanceExecution.getProcessDefinitionKey(),
                processDefinitionId,
                withLocalizationFallback);
        if (languageNode != null) {
          JsonNode languageNameNode = languageNode.get(DynamicBpmnConstants.LOCALIZATION_NAME);
          if (languageNameNode != null && languageNameNode.isNull() == false) {
            processInstanceExecution.setLocalizedName(languageNameNode.asText());
          }

          JsonNode languageDescriptionNode =
              languageNode.get(DynamicBpmnConstants.LOCALIZATION_DESCRIPTION);
          if (languageDescriptionNode != null && languageDescriptionNode.isNull() == false) {
            processInstanceExecution.setLocalizedDescription(languageDescriptionNode.asText());
          }
        }
      }
    }
  }
  public List<ConcreteEvent> fetchEvents() {
    ObjectMapper o = new ObjectMapper();
    try {
      JsonNode node = HttpResponse(eventUrl);
      JsonNode refArray = node.get("next");
      JsonNode refNode = refArray.get("$ref");
      String ref = refNode.asText();
      JsonNode itemArray = node.get("items");
      eventContainer = new ArrayList<ConcreteEvent>();

      int j = itemArray.size();
      for (int i = 0; i < j; i++) {
        ConcreteEvent event = new ConcreteEvent();
        JsonNode item = itemArray.get(i);

        JsonNode status = item.get("status");

        event.setId(item.get("id").asLong());
        event.setName(item.get("name").asText());
        event.setLength(item.get("laenge").asDouble());
        event.setWidth(item.get("breite").asDouble());
        event.setDate(item.get("datum").asText());
        event.setDescription(item.get("beschreibung").asText());

        if (status != null && status.asText().equals("D".toString())) {
          deletedEventContainer.addBean(event);
        } else {
          eventContainer.add(event);
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
    return eventContainer;
  }
 @Override
 public void create(Record record, JsonNode json, Class clazz, String dir) throws Exception {
   for (Field f : clazz.getFields()) {
     if (!json.has(f.getName())) return;
     JsonNode j = json.get(f.getName());
     JsonField field = f.getAnnotation(JsonField.class);
     JsonStruc struc = f.getAnnotation(JsonStruc.class);
     if (field != null) {
       SubRecordData sub = record.get(field.value()[0]);
       if (f.getType() == String.class) ((SubZString) sub).value = j.asText();
       else if (f.getType() == JsonFile.class)
         ((SubZString) sub).value =
             (j.asText().startsWith("/") ? j.asText().substring(1) : dir + "/" + j.asText())
                 .replace("/", "\\");
       else if (f.getType() == int[].class)
         for (int i = 0; i < sub.size(); i++) ((SubIntArray) sub).value[i] = j.get(i).intValue();
       else if (f.getType() == JsonFormID[].class) {
         if (field.value()[1] != null) record.get(field.value()[1]);
         ((SubFormIDList) sub).value.clear();
         for (int i = 0; i < sub.size(); i++)
           ((SubFormIDList) sub).value.add(getFormId(j.get(i), field.value(), 2));
       }
     }
     if (struc != null) {
       SubRecordData sub = record.get(struc.value()[0]);
       Field subf = sub.getClass().getField(struc.value()[1]);
       if (f.getType() == int.class) subf.setInt(sub, j.asInt());
       else if (f.getType() == float.class) subf.setFloat(sub, (float) j.asDouble());
     }
   }
 }
 public Optional<Integer> parseOptionalIntValue(String description, JsonNode node) {
   try {
     return Optional.of(Integer.parseInt(node.asText()));
   } catch (NumberFormatException e) {
     LOGGER.warn("Failed to parse {} value {} to int", description, node.asText());
     return Optional.empty();
   }
 }
  protected FlowElement convertJsonToElement(
      JsonNode elementNode, JsonNode modelNode, Map<String, JsonNode> shapeMap) {
    ServiceTask task = new ServiceTask();
    if (StringUtils.isNotEmpty(getPropertyValueAsString(PROPERTY_SERVICETASK_CLASS, elementNode))) {
      task.setImplementationType(ImplementationType.IMPLEMENTATION_TYPE_CLASS);
      task.setImplementation(getPropertyValueAsString(PROPERTY_SERVICETASK_CLASS, elementNode));

    } else if (StringUtils.isNotEmpty(
        getPropertyValueAsString(PROPERTY_SERVICETASK_EXPRESSION, elementNode))) {
      task.setImplementationType(ImplementationType.IMPLEMENTATION_TYPE_EXPRESSION);
      task.setImplementation(
          getPropertyValueAsString(PROPERTY_SERVICETASK_EXPRESSION, elementNode));

    } else if (StringUtils.isNotEmpty(
        getPropertyValueAsString(PROPERTY_SERVICETASK_DELEGATE_EXPRESSION, elementNode))) {
      task.setImplementationType(ImplementationType.IMPLEMENTATION_TYPE_DELEGATEEXPRESSION);
      task.setImplementation(
          getPropertyValueAsString(PROPERTY_SERVICETASK_DELEGATE_EXPRESSION, elementNode));
    }

    if (StringUtils.isNotEmpty(
        getPropertyValueAsString(PROPERTY_SERVICETASK_RESULT_VARIABLE, elementNode))) {
      task.setResultVariableName(
          getPropertyValueAsString(PROPERTY_SERVICETASK_RESULT_VARIABLE, elementNode));
    }

    JsonNode fieldsNode = getProperty(PROPERTY_SERVICETASK_FIELDS, elementNode);
    if (fieldsNode != null) {
      JsonNode itemsArrayNode = fieldsNode.get(EDITOR_PROPERTIES_GENERAL_ITEMS);
      if (itemsArrayNode != null) {
        for (JsonNode itemNode : itemsArrayNode) {
          JsonNode nameNode = itemNode.get(PROPERTY_SERVICETASK_FIELD_NAME);
          if (nameNode != null && StringUtils.isNotEmpty(nameNode.asText())) {

            FieldExtension field = new FieldExtension();
            field.setFieldName(nameNode.asText());
            if (StringUtils.isNotEmpty(
                getValueAsString(PROPERTY_SERVICETASK_FIELD_VALUE, itemNode))) {
              field.setStringValue(getValueAsString(PROPERTY_SERVICETASK_FIELD_VALUE, itemNode));
            } else if (StringUtils.isNotEmpty(
                getValueAsString(PROPERTY_SERVICETASK_FIELD_EXPRESSION, itemNode))) {
              field.setExpression(
                  getValueAsString(PROPERTY_SERVICETASK_FIELD_EXPRESSION, itemNode));
            }
            task.getFieldExtensions().add(field);
          }
        }
      }
    }

    return task;
  }
  @Override
  public List<JsonNode> apply(final Scope scope, final List<JsonQuery> args, final JsonNode in)
      throws JsonQueryException {
    Preconditions.checkInputType("endswith", in, JsonNodeType.STRING);

    final String text = in.asText();

    final List<JsonNode> out = new ArrayList<>();
    for (final JsonNode suffix : args.get(0).apply(scope, in)) {
      if (!suffix.isTextual())
        throw new JsonQueryException("1st argument of endswith() must evaluate to string");
      out.add(BooleanNode.valueOf(text.endsWith(suffix.asText())));
    }
    return out;
  }
Beispiel #9
0
    @Override
    public AtomicColumnType fromJsonNode(JsonNode json) {
      if (json.isObject() && json.has("value")) {
        return null;
      }
      BaseType baseType = BaseType.fromJson(json, "key");

      if (baseType != null) {

        AtomicColumnType atomicColumnType = new AtomicColumnType(baseType);

        JsonNode node = null;
        if ((node = json.get("min")) != null) {
          atomicColumnType.setMin(node.asLong());
        }

        if ((node = json.get("max")) != null) {
          if (node.isNumber()) {
            atomicColumnType.setMax(node.asLong());
          } else if ("unlimited".equals(node.asText())) {
            atomicColumnType.setMax(Long.MAX_VALUE);
          }
        }
        return atomicColumnType;
      }

      return null;
    }
  @Override
  public Tuple convert(String source) {
    TupleBuilder builder = TupleBuilder.tuple();
    try {

      JsonNode root = mapper.readTree(source);
      for (Iterator<Entry<String, JsonNode>> it = root.fields(); it.hasNext(); ) {
        Entry<String, JsonNode> entry = it.next();
        String name = entry.getKey();
        JsonNode node = entry.getValue();
        if (node.isObject()) {
          // tuple
          builder.addEntry(name, convert(node.toString()));
        } else if (node.isArray()) {
          builder.addEntry(name, nodeToList(node));
        } else {
          if (name.equals("id")) {
            // TODO how should this be handled?
          } else if (name.equals("timestamp")) {
            // TODO how should this be handled?
          } else {
            builder.addEntry(name, node.asText());
          }
        }
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
    return builder.build();
  }
Beispiel #11
0
 /** Parses the entity, client identification and execution options from the given json object */
 protected void parse(ObjectNode node) {
   entityVersion = new EntityVersion();
   JsonNode x = node.get("entity");
   if (x != null && !(x instanceof NullNode)) {
     entityVersion.setEntity(x.asText());
   }
   x = node.get("entityVersion");
   if (x != null && !(x instanceof NullNode)) {
     entityVersion.setVersion(x.asText());
   }
   // TODO: clientIdentification
   x = node.get("execution");
   if (x != null) {
     execution = ExecutionOptions.fromJson((ObjectNode) x);
   }
 }
  public List<SecurityRequirement> securityRequirements(
      ArrayNode node, String location, ParseResult result) {
    if (node == null) return null;

    List<SecurityRequirement> output = new ArrayList<SecurityRequirement>();

    for (JsonNode item : node) {
      SecurityRequirement security = new SecurityRequirement();
      if (item.getNodeType().equals(JsonNodeType.OBJECT)) {
        ObjectNode on = (ObjectNode) item;
        Set<String> keys = getKeys(on);

        for (String key : keys) {
          List<String> scopes = new ArrayList<>();
          ArrayNode obj = getArray(key, on, false, location + ".security", result);
          if (obj != null) {
            for (JsonNode n : obj) {
              if (n.getNodeType().equals(JsonNodeType.STRING)) {
                scopes.add(n.asText());
              } else {
                result.invalidType(location, key, "string", n);
              }
            }
          }
          security.requirement(key, scopes);
        }
      }
      output.add(security);
    }

    return output;
  }
  protected UIEntity fieldsToUIEntity(Iterator<Map.Entry<String, JsonNode>> fields) {
    UIEntity entity = new UIEntity();

    while (fields.hasNext()) {
      Map.Entry<String, JsonNode> field = fields.next();
      JsonNode fieldValue = field.getValue();

      if (fieldValue instanceof ObjectNode) {
        entity.put(field.getKey(), fieldsToUIEntity(field.getValue().fields()));
      } else if (fieldValue instanceof ArrayNode) {
        Iterator<JsonNode> elements = fieldValue.elements();
        List<Object> listValues = new ArrayList<>();

        while (elements.hasNext()) {
          JsonNode nextNode = elements.next();

          if (nextNode instanceof ObjectNode) {
            listValues.add(fieldsToUIEntity(nextNode.fields()));
          } else {
            listValues.add(nextNode.asText());
          }
        }

        entity.put(field.getKey(), listValues);
      } else if (!(field.getValue() instanceof NullNode)) {
        entity.put(field.getKey(), field.getValue().asText());
      }
    }

    return entity;
  }
Beispiel #14
0
  private void a(JsonNode jsonnode) {
    if (jsonnode.has("songs")) {
      JsonNode jsonnode1;
      for (Iterator iterator = jsonnode.get("songs").iterator();
          iterator.hasNext();
          b.add(jsonnode1.asText())) {
        jsonnode1 = (JsonNode) iterator.next();
      }

    } else {
      aa.b(a, "no songs specified for object!");
    }
    if (jsonnode.has("day")) {
      jsonnode = jsonnode.get("day").asText().split(",");
      if (jsonnode.length == 0) {
        aa.b(a, "no days specified for object");
      } else {
        int j = jsonnode.length;
        int i = 0;
        while (i < j) {
          String s = jsonnode[i];
          c.add(new b(this, s));
          i++;
        }
      }
      return;
    } else {
      aa.b(a, "no days specified for object");
      return;
    }
  }
  public Object unwrap(Object o) {

    if (o == null) {
      return null;
    }
    if (!(o instanceof JsonNode)) {
      return o;
    }

    JsonNode e = (JsonNode) o;

    if (e.isValueNode()) {

      if (e.isTextual()) {
        return e.asText();
      } else if (e.isBoolean()) {
        return e.asBoolean();
      } else if (e.isInt()) {
        return e.asInt();
      } else if (e.isLong()) {
        return e.asLong();
      } else if (e.isBigDecimal()) {
        return e.decimalValue();
      } else if (e.isDouble()) {
        return e.doubleValue();
      } else if (e.isFloat()) {
        return e.floatValue();
      } else if (e.isBigDecimal()) {
        return e.decimalValue();
      } else if (e.isNull()) {
        return null;
      }
    }
    return o;
  }
  public Map<Long, List<Long>> fetchRelations() {
    List<Long> array;
    ObjectMapper o = new ObjectMapper();
    try {

      JsonNode node = HttpResponse(matchUrl);
      JsonNode refArray = node.get("next");
      JsonNode refNode = refArray.get("$ref");
      String ref = refNode.asText();
      JsonNode itemArray = node.get("items");

      participants = new HashMap<Long, List<Long>>();

      for (int i = 0; i < itemArray.size(); i++) {
        JsonNode item = itemArray.get(i);

        Long u_id = item.get("ntz_id").asLong();
        Long e_id = item.get("eve_id").asLong();

        if (!participants.containsKey(e_id)) {
          array = new LinkedList<Long>();
          participants.put(e_id, array);
        }
        participants.get(e_id).add(u_id);
      }

    } catch (IOException e) {
      e.printStackTrace();
    }
    return participants;
  }
  /**
   * Validates the deviceId that is contained in json string against the input deviceId.
   *
   * @param deviceId device identifier
   * @param node object node
   * @return validity
   */
  private boolean validateDeviceId(String deviceId, ObjectNode node) {
    JsonNode specifiedDeviceId = node.get("deviceId");

    if (specifiedDeviceId != null && !specifiedDeviceId.asText().equals(deviceId)) {
      throw new IllegalArgumentException(DEVICE_INVALID);
    }
    return true;
  }
 private boolean doesClusterExist(String clusterName, User user) throws InternalServerException {
   JsonNode statusNode = new helpers.Carina().getCluster(clusterName, user);
   if (statusNode != null) {
     return statusNode.asText().equals("active");
   } else {
     return false;
   }
 }
 protected String getValueAsString(String name, JsonNode objectNode) {
   String propertyValue = null;
   JsonNode propertyNode = objectNode.get(name);
   if (propertyNode != null && propertyNode.isNull() == false) {
     propertyValue = propertyNode.asText();
   }
   return propertyValue;
 }
 public Object extension(JsonNode jsonNode) {
   if (jsonNode.getNodeType().equals(JsonNodeType.BOOLEAN)) {
     return jsonNode.asBoolean();
   }
   if (jsonNode.getNodeType().equals(JsonNodeType.STRING)) {
     return jsonNode.asText();
   }
   if (jsonNode.getNodeType().equals(JsonNodeType.NUMBER)) {
     NumericNode n = (NumericNode) jsonNode;
     if (n.isLong()) {
       return jsonNode.asLong();
     }
     if (n.isInt()) {
       return jsonNode.asInt();
     }
     if (n.isBigDecimal()) {
       return jsonNode.textValue();
     }
     if (n.isBoolean()) {
       return jsonNode.asBoolean();
     }
     if (n.isFloat()) {
       return jsonNode.floatValue();
     }
     if (n.isDouble()) {
       return jsonNode.doubleValue();
     }
     if (n.isShort()) {
       return jsonNode.intValue();
     }
     return jsonNode.asText();
   }
   if (jsonNode.getNodeType().equals(JsonNodeType.ARRAY)) {
     ArrayNode an = (ArrayNode) jsonNode;
     List<Object> o = new ArrayList<Object>();
     for (JsonNode i : an) {
       Object obj = extension(i);
       if (obj != null) {
         o.add(obj);
       }
     }
     return o;
   }
   return jsonNode;
 }
  /**
   * This operation accepts an object in the JavaScript Object Notation format (JSON) and returns a
   * value for the specified key.
   *
   * @param object The string representation of a JSON object. Objects in JSON are a collection of
   *     name value pairs, separated by a colon and surrounded with curly brackets {}. The name must
   *     be a string value, and the value can be a single string or any valid JSON object or array.
   *     Examples: {"one":1, "two":2}, {"one":{"a":"a","B":"B"}, "two":"two", "three":[1,2,3.4]}
   * @param key The key in the object to get the value of. Examples: city, location[0].city
   * @return a map containing the output of the operation. Keys present in the map are:
   *     <p><br>
   *     <br>
   *     <b>returnResult</b> - This will contain the value for the specified key in the object. <br>
   *     <b>exception</b> - In case of success response, this result is empty. In case of failure
   *     response, this result contains the java stack trace of the runtime exception. <br>
   *     <br>
   *     <b>returnCode</b> - The returnCode of the operation: 0 for success, -1 for failure.
   */
  @Action(
      name = "Get Value from Object",
      outputs = {
        @Output(Constants.OutputNames.RETURN_RESULT),
        @Output(Constants.OutputNames.RETURN_CODE),
        @Output(Constants.OutputNames.EXCEPTION)
      },
      responses = {
        @Response(
            text = Constants.ResponseNames.SUCCESS,
            field = Constants.OutputNames.RETURN_CODE,
            value = Constants.ReturnCodes.RETURN_CODE_SUCCESS,
            matchType = MatchType.COMPARE_EQUAL,
            responseType = ResponseType.RESOLVED),
        @Response(
            text = Constants.ResponseNames.FAILURE,
            field = Constants.OutputNames.RETURN_CODE,
            value = Constants.ReturnCodes.RETURN_CODE_FAILURE,
            matchType = MatchType.COMPARE_EQUAL,
            responseType = ResponseType.ERROR,
            isOnFail = true)
      })
  public Map<String, String> execute(
      @Param(value = Constants.InputNames.OBJECT, required = true) String object,
      @Param(value = Constants.InputNames.KEY, required = true) String key) {

    Map<String, String> returnResult = new HashMap<>();

    if (isBlank(object)) {
      return populateResult(returnResult, new Exception("Empty object provided!"));
    }
    if (key == null) {
      return populateResult(returnResult, new Exception("Null key provided!"));
    }

    final JsonNode jsonRoot;
    ObjectMapper objectMapper = new ObjectMapper();
    try {
      jsonRoot = objectMapper.readTree(object);
    } catch (Exception exception) {
      final String value = "Invalid object provided! " + exception.getMessage();
      return populateResult(returnResult, value, exception);
    }

    int startIndex = 0;
    final JsonNode valueFromObject;
    try {
      valueFromObject = getObject(jsonRoot, key.split(ESCAPED_SLASH + "."), startIndex);
    } catch (Exception exception) {
      return populateResult(returnResult, exception);
    }
    if (valueFromObject.isValueNode()) {
      return populateResult(returnResult, valueFromObject.asText(), null);
    } else {
      return populateResult(returnResult, valueFromObject.toString(), null);
    }
  }
  /**
   * Installs the filtering rules onto the specified device.
   *
   * @param stream filtering rule JSON
   * @return 200 OK
   * @onos.rsModel ObjectivePolicy
   */
  @POST
  @Path("policy")
  @Consumes(MediaType.APPLICATION_JSON)
  public Response initPolicy(InputStream stream) {

    try {
      ObjectNode jsonTree = (ObjectNode) mapper().readTree(stream);
      JsonNode policyJson = jsonTree.get("policy");

      if (policyJson == null || policyJson.asText().isEmpty()) {
        throw new IllegalArgumentException(POLICY_INVALID);
      }

      flowObjectiveService.initPolicy(policyJson.asText());
      return Response.ok().build();
    } catch (IOException e) {
      throw new IllegalArgumentException(e);
    }
  }
  public boolean createCluster(String clusterName, User user)
      throws InternalServerException, InterruptedException {
    Logger.info("Create cluster " + clusterName + " with " + user.token);
    CarinaRequest carinaRequest = new CarinaRequest(clusterName, false, user.username);

    F.Promise<String> statusPromise =
        WS.url("https://app.getcarina.com/clusters/" + user.username)
            .setHeader("x-auth-token", user.token)
            .setHeader("x-content-type", "application/json")
            .post(Json.toJson(carinaRequest))
            .map(
                new F.Function<WSResponse, String>() {
                  @Override
                  public String apply(WSResponse wsResponse) throws Throwable {
                    Logger.debug(
                        "response from cluster create: "
                            + wsResponse.getStatus()
                            + " "
                            + wsResponse.getStatusText());

                    Logger.debug("response body: " + wsResponse.getBody());
                    Logger.debug("Keep checking until we get to success (or error) state");

                    return wsResponse.asJson().get("status").asText();
                  }
                })
            .recover(
                new F.Function<Throwable, String>() {
                  // Everything is down!
                  @Override
                  public String apply(Throwable throwable) throws Throwable {
                    throw new InternalServerException(
                        "{'message': 'We are currently experiencing difficulties.  "
                            + "Please try again later.'}");
                    // return internalServerError(
                    //        Helpers.buildJsonResponse("message", "We are currently experiencing
                    // difficulties.  Please try again later."));
                  }
                });

    String status = statusPromise.get(30000);
    while (!status.equals("active") && !status.equals("error")) {
      JsonNode statusNode = new helpers.Carina().getCluster(clusterName, user);
      if (statusNode != null) {
        status = statusNode.asText();
      } else if (status.equals("error")) {
        throw new InternalServerException("Cluster ended up in error state");
      } else {
        throw new InternalServerException("Unable to get status");
      }
      Thread.sleep(1000);
    }
    return true;
  }
Beispiel #24
0
 protected boolean isEqualToCurrentLocalizationValue(
     String language, String id, String propertyName, String propertyValue, ObjectNode infoNode) {
   boolean isEqual = false;
   JsonNode localizationNode =
       infoNode.path("localization").path(language).path(id).path(propertyName);
   if (localizationNode.isMissingNode() == false
       && localizationNode.isNull() == false
       && localizationNode.asText().equals(propertyValue)) {
     isEqual = true;
   }
   return isEqual;
 }
  public List<ConcreteUser> fetchUsers() {
    JsonNode node = null;
    try {
      node = HttpResponse(usersUrl);
    } catch (JsonProcessingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    JsonNode refArray = node.get("next");
    JsonNode refNode = refArray.get("$ref");
    String ref = refNode.asText();
    JsonNode itemArray = node.get("items");

    userContainer = new ArrayList<ConcreteUser>();

    for (int i = 0; i < itemArray.size(); i++) {
      ConcreteUser user = new ConcreteUser();
      JsonNode item = itemArray.get(i);

      JsonNode status = item.get("status");

      user.setId(item.get("id").asLong());
      user.setFirstName(item.get("vorname").asText());
      user.setName(item.get("name").asText());
      user.setLength(item.get("laenge").asDouble());
      user.setWidth(item.get("breite").asDouble());
      user.setWeblogin(item.get("weblogin").toString());
      user.setPassword(item.get("passwort").toString());
      user.setBirthDate(item.get("geburtsdatum").toString());

      if (status != null && status.asText().equals("D")) {
      } else {
        userContainer.add(user);
      }
    }
    return userContainer;
  }
 public String getString(
     String key, ObjectNode node, boolean required, String location, ParseResult result) {
   String value = null;
   JsonNode v = node.get(key);
   if (node == null || v == null) {
     if (required) {
       result.missing(location, key);
       result.invalid();
     }
   } else {
     value = v.asText();
   }
   return value;
 }
 private List<Object> nodeToList(JsonNode node) {
   List<Object> list = new ArrayList<Object>(node.size());
   for (int i = 0; i < node.size(); i++) {
     JsonNode item = node.get(i);
     if (item.isObject()) {
       list.add(convert(item.toString()));
     } else if (item.isArray()) {
       list.add(nodeToList(item));
     } else {
       list.add(item.asText());
     }
   }
   return list;
 }
 private JsonNode createProduct(JsonNode node, String userName) throws Exception {
   ObjectMapper om = new ObjectMapper();
   ArrayNode anode = om.createArrayNode();
   if (node.isArray()) {
     Iterator<JsonNode> nodeiterator = node.iterator();
     while (nodeiterator.hasNext()) {
       ProductBack cbase = om.convertValue(nodeiterator.next(), ProductBack.class);
       anode.add(createProductToDb(om, cbase, userName));
     }
   } else {
     ProductBack cbase = JSON.parseObject(node.asText(), ProductBack.class);
     anode.add(createProductToDb(om, cbase, userName));
   }
   return anode;
 }
Beispiel #29
0
  /** Fetches the credentials from the endpoint. */
  private synchronized void fetchCredentials() {
    if (!needsToLoadCredentials()) return;

    JsonNode accessKey;
    JsonNode secretKey;
    JsonNode node;
    JsonNode token;
    try {
      lastInstanceProfileCheck = new Date();

      String credentialsResponse =
          EC2CredentialsUtils.readResource(credentailsEndpointProvider.getCredentialsEndpoint());

      node = Jackson.jsonNodeOf(credentialsResponse);
      accessKey = node.get(ACCESS_KEY_ID);
      secretKey = node.get(SECRET_ACCESS_KEY);
      token = node.get(TOKEN);

      if (null == accessKey || null == secretKey) {
        throw new AmazonClientException("Unable to load credentials.");
      }

      if (null != token) {
        credentials =
            new BasicSessionCredentials(accessKey.asText(), secretKey.asText(), token.asText());
      } else {
        credentials = new BasicAWSCredentials(accessKey.asText(), secretKey.asText());
      }

      JsonNode expirationJsonNode = node.get("Expiration");
      if (null != expirationJsonNode) {
        /*
         * TODO: The expiration string comes in a different format
         * than what we deal with in other parts of the SDK, so we
         * have to convert it to the ISO8601 syntax we expect.
         */
        String expiration = expirationJsonNode.asText();
        expiration = expiration.replaceAll("\\+0000$", "Z");

        try {
          credentialsExpiration = DateUtils.parseISO8601Date(expiration);
        } catch (Exception ex) {
          handleError("Unable to parse credentials expiration date from Amazon EC2 instance", ex);
        }
      }
    } catch (JsonMappingException e) {
      handleError("Unable to parse response returned from service endpoint", e);
    } catch (IOException e) {
      handleError("Unable to load credentials from service endpoint", e);
    } catch (URISyntaxException e) {
      handleError("Unable to load credentials from service endpoint", e);
    }
  }
Beispiel #30
0
 /**
  * Parses an ID.
  *
  * @param node
  * @return
  */
 protected Object parseId(JsonNode node) {
   if (node == null || node.isNull()) {
     return null;
   } else if (node.isDouble()) {
     return node.asDouble();
   } else if (node.isFloatingPointNumber()) {
     return node.asDouble();
   } else if (node.isInt()) {
     return node.asInt();
   } else if (node.isIntegralNumber()) {
     return node.asInt();
   } else if (node.isLong()) {
     return node.asLong();
   } else if (node.isTextual()) {
     return node.asText();
   }
   throw new IllegalArgumentException("Unknown id type");
 }