public Geometry decodeGeometry(JsonNode node) throws GeoJSONException {
   if (node == null || node.isNull() || node.isMissingNode()) {
     return null;
   } else {
     return decodeGeometry(node, DEFAULT_GEOMETRY_FACTORY);
   }
 }
Example #2
0
 public List<String> getRevisions() {
   List<String> revisions = new ArrayList<String>();
   for (JsonNode changesNode : node.get(CHANGES_FIELD_NAME)) {
     revisions.add(nodeAsString(changesNode.get(REV_FIELD_NAME)));
   }
   return Collections.unmodifiableList(revisions);
 }
  @RequestMapping(value = "/run/input", method = RequestMethod.POST)
  public BigInteger runInputFlow(@RequestBody JsonNode json) throws IOException, JSONException {

    final String entityName = json.get("flow").get("entityName").asText();
    final String flowName = json.get("flow").get("flowName").asText();

    environmentConfiguration.saveOrUpdateFlowMlcpOptionsToFile(
        entityName, flowName, json.get("mlcp").toString());

    CancellableTask task =
        new CancellableTask() {

          @Override
          public void cancel(BasicFuture<?> resultFuture) {
            // TODO: stop MLCP. We don't have a way to do this yet.
          }

          @Override
          public void run(BasicFuture<?> resultFuture) {
            try {
              flowManagerService.loadData(json.get("mlcp"));

              resultFuture.completed(null);
            } catch (IOException e) {
              LOGGER.error(e.toString());
              resultFuture.failed(e);
            }
          }
        };

    return taskManagerService.addTask(task);
  }
  @Test
  public void testCreateDocument() {
    running(
        fakeApplication(),
        () -> {
          try {
            DbHelper.open("1234567890", TEST_USER, TEST_USER);
            ObjectNode params = MAPPER.createObjectNode();
            ObjectNode doc = MAPPER.createObjectNode();
            doc.put("fresh", "fresh");
            params.put("collection", TEST_COLLECTION);
            params.put("data", doc);
            ObjectNode cmd = ScriptCommands.createCommand("documents", "post", params);

            JsonNode exec = CommandRegistry.execute(cmd, null);
            assertNotNull(exec);
            assertTrue(exec.isObject());
            assertNotNull(exec.get("id"));
            assertEquals(TEST_COLLECTION, exec.get("@class").asText());

          } catch (Throwable t) {
            fail(ExceptionUtils.getFullStackTrace(t));
          } finally {
            DbHelper.close(DbHelper.getConnection());
          }
        });
  }
  @Override
  public void validate(
      final Processor<FullData, FullData> processor,
      final ProcessingReport report,
      final MessageBundle bundle,
      final FullData data)
      throws ProcessingException {
    final SchemaTree tree = data.getSchema();
    final JsonPointer schemaPointer = tree.getPointer();
    final JsonNode schemas = tree.getNode().get(keyword);
    final int size = schemas.size();
    final ObjectNode fullReport = FACTORY.objectNode();

    int nrSuccess = 0;
    ListProcessingReport subReport;
    JsonPointer ptr;
    FullData newData;

    for (int index = 0; index < size; index++) {
      subReport = new ListProcessingReport(report.getLogLevel(), LogLevel.FATAL);
      ptr = schemaPointer.append(JsonPointer.of(keyword, index));
      newData = data.withSchema(tree.setPointer(ptr));
      processor.process(subReport, newData);
      fullReport.put(ptr.toString(), subReport.asJson());
      if (subReport.isSuccess()) nrSuccess++;
    }

    if (nrSuccess == 0)
      report.error(
          newMsg(data, bundle, "err.common.schema.noMatch")
              .putArgument("nrSchemas", size)
              .put("reports", fullReport));
  }
  /**
   * Matches the contents of a push header instruction.
   *
   * @param instructionJson JSON instruction to match
   * @param description Description object used for recording errors
   * @return true if contents match, false otherwise
   */
  private boolean matchModMplsHeaderInstruction(JsonNode instructionJson, Description description) {
    ModMplsHeaderInstruction instructionToMatch = (ModMplsHeaderInstruction) instruction;
    final String jsonSubtype = instructionJson.get("subtype").textValue();
    if (!instructionToMatch.subtype().name().equals(jsonSubtype)) {
      description.appendText("subtype was " + jsonSubtype);
      return false;
    }

    final String jsonType = instructionJson.get("type").textValue();
    if (!instructionToMatch.type().name().equals(jsonType)) {
      description.appendText("type was " + jsonType);
      return false;
    }

    final JsonNode ethJson = instructionJson.get("ethernetType");
    if (ethJson == null) {
      description.appendText("ethernetType was not null");
      return false;
    }

    if (instructionToMatch.ethernetType().toShort() != ethJson.asInt()) {
      description.appendText("ethernetType was " + ethJson);
      return false;
    }

    return true;
  }
  public static <T> T process(
      RequestMethod method,
      String path,
      Class<T> clazz,
      String className,
      Resource classObj,
      GenericParams params)
      throws ZSAPIException {
    Response response = handleRequest(method, path, classObj, clazz, params);
    if (method == RequestMethod.DELETE) {
      // No body
      return null;
    }

    try {
      Object body = response.getBody();
      if (!(body instanceof String)) {
        return (T) response;
      }
      ObjectMapper mapper = RequestUtil.getMapper();
      JsonNode root = mapper.readTree((String) body);
      JsonNode dataNode =
          root.get(className != null ? className : clazz.getSimpleName().toLowerCase());
      if (dataNode == null) {
        return null;
      }
      return mapper.readValue(dataNode.toString(), clazz);
    } catch (Exception e) {
      throw new ZSAPIException(e);
    }
  }
  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;
  }
 @Test
 public void unclosedObject_AutoClosesOnClose() throws IOException {
   jsonGenerator.writeStartObject();
   jsonGenerator.writeFieldName("stringProp").writeValue("stringVal");
   JsonNode node = toJsonNode();
   assertTrue(node.isObject());
 }
Example #10
0
  /**
   * ERP推送订单
   *
   * @return shopOrderNo 订单编号
   * @throws ApiException
   */
  public Result shopOrderPush() throws ApiException, ParseException {
    JsonNode json = request().body().asJson();
    //        List<String> shopOrderCodeList = new ArrayList<>();
    for (int i = 0; i < json.size(); i++) {
      Long orderId = (json.get(i)).asLong();
      // 推送之前先查询,先从ERP查询该订单若已存在则不推送
      //            String shopOrderNo = "";
      List<Object> salesOrderList = shopOrderMiddle.salesOrderQuery(orderId.toString());
      if ((null == salesOrderList) || salesOrderList.size() == 0) {
        // 调用推送订单Actor
        system.actorSelection(SysParCom.ERP_ORDER_PUSH).tell(orderId, ActorRef.noSender());

        //                shopOrderNo = shopOrderMiddle.shopOrderPush(orderId);
        //                Logger.error("推送结果:"+shopOrderNo);
        //                shopOrderCodeList.add(shopOrderNo);
        //                //推送成功的订单再创建schedule
        //                if (Json.parse(shopOrderNo).has("ShopOrderNo")) {
        //                    shopOrderNo =
        // Json.parse(shopOrderNo).findValue("ShopOrderNo").asText();
        //                    Logger.error("订单"+shopOrderNo+":push to ERP");
        //                    //启动scheduler从erp查询订单,海关审核通过,更新物流信息
        //                    scheduler.schedule(Duration.create(SysParCom.ORDER_QUERY_DELAY,
        // TimeUnit.MILLISECONDS),Duration.create(SysParCom.ORDER_QUERY_INTERVAL,
        // TimeUnit.MILLISECONDS),salesOrderQueryActor,orderId);
        //                }
      }
    }
    //        return ok(shopOrderCodeList.toString());
    return ok();
  }
  @Override
  public SchemaAndValue toConnectData(String topic, byte[] value) {
    JsonNode jsonValue;
    try {
      jsonValue = deserializer.deserialize(topic, value);
    } catch (SerializationException e) {
      throw new DataException(
          "Converting byte[] to Kafka Connect data failed due to serialization error: ", e);
    }

    if (enableSchemas
        && (jsonValue == null
            || !jsonValue.isObject()
            || jsonValue.size() != 2
            || !jsonValue.has("schema")
            || !jsonValue.has("payload")))
      throw new DataException(
          "JsonDeserializer with schemas.enable requires \"schema\" and \"payload\" fields and may not contain additional fields");

    // The deserialized data should either be an envelope object containing the schema and the
    // payload or the schema
    // was stripped during serialization and we need to fill in an all-encompassing schema.
    if (!enableSchemas) {
      ObjectNode envelope = JsonNodeFactory.instance.objectNode();
      envelope.set("schema", null);
      envelope.set("payload", jsonValue);
      jsonValue = envelope;
    }

    return jsonToConnect(jsonValue);
  }
Example #12
0
  /** Deserialize from the cursor as json nodes */
  private Map<Integer, JsonNode> fromCursor(final String cursor) throws CursorParseException {

    Preconditions.checkArgument(cursor != null, "Cursor cannot be null");

    Preconditions.checkArgument(
        cursor.length() <= MAX_SIZE,
        "Your cursor must be less than " + MAX_SIZE + " chars in length");

    Preconditions.checkArgument(!cursor.isEmpty(), "Cursor cannot have an empty value");

    try {
      JsonNode jsonNode = CursorSerializerUtil.fromString(cursor);

      Preconditions.checkArgument(
          jsonNode.size() <= MAX_CURSOR_COUNT,
          " You cannot have more than " + MAX_CURSOR_COUNT + " cursors");

      Map<Integer, JsonNode> cursors = new HashMap<>();

      final Iterable<Map.Entry<String, JsonNode>> iterable = () -> jsonNode.fields();

      for (final Map.Entry<String, JsonNode> node : iterable) {
        cursors.put(Integer.parseInt(node.getKey()), node.getValue());
      }

      return cursors;
    } catch (IllegalArgumentException ie) {
      throw new IllegalArgumentException(
          "Provided cursor has an invalid format and cannot be parsed.");
    } catch (Exception e) {
      throw new CursorParseException("Unable to deserialize cursor", e);
    }
  }
Example #13
0
 public BooleanField(JsonNode node) {
   super(node);
   if (node.has("format")) {
     String formatString = node.get("format").asText();
     booleanValues = formatString.split(":");
   }
 }
Example #14
0
  @Test
  @SuppressWarnings("rawtypes")
  public void wordDelimitersCausesCamelCase()
      throws ClassNotFoundException, IntrospectionException, InstantiationException,
          IllegalAccessException, InvocationTargetException {

    ClassLoader resultsClassLoader =
        generateAndCompile(
            "/schema/properties/propertiesWithWordDelimiters.json",
            "com.example",
            config("usePrimitives", true, "propertyWordDelimiters", "_ -"));

    Class generatedType = resultsClassLoader.loadClass("com.example.WordDelimit");

    Object instance = generatedType.newInstance();

    new PropertyDescriptor("propertyWithUnderscores", generatedType)
        .getWriteMethod()
        .invoke(instance, "a_b_c");
    new PropertyDescriptor("propertyWithHyphens", generatedType)
        .getWriteMethod()
        .invoke(instance, "a-b-c");
    new PropertyDescriptor("propertyWithMixedDelimiters", generatedType)
        .getWriteMethod()
        .invoke(instance, "a b_c-d");

    JsonNode jsonified = mapper.valueToTree(instance);

    assertThat(jsonified.has("property_with_underscores"), is(true));
    assertThat(jsonified.has("property-with-hyphens"), is(true));
    assertThat(jsonified.has("property_with mixed-delimiters"), is(true));
  }
 /*
  * (non-Javadoc)
  *
  * @see
  * com.ssachtleben.play.plugin.auth.providers.BaseProvider#handle(play.mvc
  * .Http.Context)
  */
 @Override
 protected AuthUser handle(Context context) {
   String contentType = context.request().getHeader("content-type");
   if ("application/json".equals(contentType)) {
     JsonNode node = context.request().body().asJson();
     return new PasswordEmailAuthUser(
         node.get(RequestParameter.EMAIL).asText(),
         node.get(RequestParameter.PASSWORD).asText(),
         node);
   } else {
     Map<String, String[]> params = context.request().body().asFormUrlEncoded();
     if (params != null
         && params.containsKey(RequestParameter.EMAIL)
         && params.containsKey(RequestParameter.PASSWORD)) {
       ObjectMapper mapper = new ObjectMapper();
       JsonNode data;
       try {
         data = mapper.readTree(mapper.writeValueAsString(params));
       } catch (IOException e) {
         logger().error("Failed to serialize params to json", e);
         data = mapper.createObjectNode();
       }
       return new PasswordEmailAuthUser(
           params.get(RequestParameter.EMAIL)[0], params.get(RequestParameter.PASSWORD)[0], data);
     }
   }
   return null;
 }
Example #16
0
  @Test
  public void testSaveMap() throws IOException {
    Resource resource = resourceSet.createResource(URI.createURI("test"));

    ETypes types = ModelFactory.eINSTANCE.createETypes();
    {
      Type t = ModelFactory.eINSTANCE.createType();
      t.setName("t1");
      Value v = ModelFactory.eINSTANCE.createValue();
      v.setValue(1);
      types.getValues().put(t, v);
    }
    resource.getContents().add(types);

    JsonNode actual = mapper.valueToTree(resource);

    assertThat(actual.get("values"))
        .hasSize(1)
        .contains(
            ((ObjectNode)
                    mapper
                        .createObjectNode()
                        .set(
                            "key",
                            mapper
                                .createObjectNode()
                                .put("eClass", "http://www.emfjson.org/jackson/model#//Type")
                                .put("name", "t1")))
                .set(
                    "value",
                    mapper
                        .createObjectNode()
                        .put("eClass", "http://www.emfjson.org/jackson/model#//Value")
                        .put("value", 1)));
  }
 public static String dumpConfigurationAsJson() {
   ImmutableCollection<String> keys = CONFIGURATION_SECTIONS.keySet();
   ObjectMapper mapper = new ObjectMapper();
   JsonFactory jfactory = mapper.getJsonFactory();
   StringWriter sw = new StringWriter();
   try {
     JsonGenerator gen = jfactory.createJsonGenerator(sw);
     gen.writeStartArray();
     for (String v : keys) {
       String st = dumpConfigurationAsJson(v);
       ObjectMapper op = new ObjectMapper();
       JsonNode p = op.readTree(st);
       Logger.debug("OBJECT:" + p.toString());
       Logger.debug("STRING:" + st);
       // JsonParser jp = jfactory.createJsonParser(st);
       gen.writeTree(p);
     }
     gen.writeEndArray();
     gen.close();
     return sw.toString();
   } catch (Exception e) {
     Logger.error("Cannot generate a json for the configuration", e);
   }
   return "[]";
 } // dumpConfigurationAsJson()
  @Test
  public void givenANode_whenRemovingFromATree_thenCorrect() throws IOException {
    final JsonNode rootNode = ExampleStructure.getExampleRoot();
    ((ObjectNode) rootNode).remove("company");

    assertTrue(rootNode.path("company").isMissingNode());
  }
Example #19
0
 @Override
 public boolean equals(Object obj) {
   if (obj == null) return false;
   JsonNode a = new ObjectMapper().valueToTree(this);
   JsonNode b = new ObjectMapper().valueToTree(obj);
   return a.equals(b);
 };
  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;
  }
  @Test
  public void testCommandGetFilteredCollection() {
    running(
        fakeApplication(),
        () -> {
          try {
            DbHelper.open("1234567890", TEST_USER, TEST_USER);
            ObjectNode cmd = MAPPER.createObjectNode();
            ObjectNode p = MAPPER.createObjectNode();
            ObjectNode q = MAPPER.createObjectNode();
            q.put("where", "idx < ?");
            ArrayNode params = MAPPER.createArrayNode();
            params.add("5");
            q.put("params", params);
            p.put("collection", TEST_COLLECTION);
            p.put("query", q);

            cmd.put(ScriptCommand.RESOURCE, "documents");
            cmd.put(ScriptCommand.NAME, "list");
            cmd.put(ScriptCommand.PARAMS, p);

            JsonNode node = CommandRegistry.execute(cmd, null);
            assertNotNull(node);
            assertTrue(node.isArray());
            assertEquals(5, node.size());
          } catch (Throwable t) {
            fail(ExceptionUtils.getFullStackTrace(t));
          } finally {
            DbHelper.close(DbHelper.getConnection());
          }
        });
  }
    @Override
    public AckArgs deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
      List<Object> args = new ArrayList<Object>();
      AckArgs result = new AckArgs(args);

      ObjectMapper mapper = (ObjectMapper) jp.getCodec();
      JsonNode root = mapper.readTree(jp);
      AckCallback<?> callback = currentAckClass.get();
      Iterator<JsonNode> iter = root.iterator();
      int i = 0;
      while (iter.hasNext()) {
        Object val;

        Class<?> clazz = callback.getResultClass();
        if (callback instanceof MultiTypeAckCallback) {
          MultiTypeAckCallback multiTypeAckCallback = (MultiTypeAckCallback) callback;
          clazz = multiTypeAckCallback.getResultClasses()[i];
        }

        JsonNode arg = iter.next();
        if (arg.isTextual() || arg.isBoolean()) {
          clazz = Object.class;
        }

        val = mapper.treeToValue(arg, clazz);
        args.add(val);
        i++;
      }
      return result;
    }
Example #23
0
 public static Result updateGift(String giftId) {
   if (!Utils.checkCredentials(request())) {
     return unauthorized();
   }
   if (!Utils.checkJsonInput(request())) {
     Logger.info("Bad request data for Invite Code " + request().body());
     return generateBadRequest("Bad input json" + request().body());
   }
   Logger.info("Updating Gift Card. GiftId" + giftId);
   Gift gift;
   String giftStatus = "";
   try {
     gift = GiftDAO.getInstance().findGiftById(giftId);
     JsonNode jsonReq = request().body().asJson();
     giftStatus = jsonReq.get("giftStatus").asText();
     gift.setGiftStatus(Gift.GiftStatus.valueOf(giftStatus));
     GiftDAO.getInstance().updateGift(gift);
     Logger.info("Gift Card Updated. GiftId" + giftId);
   } catch (Exception e) {
     Logger.info("Gift Card Update Failed. GiftId" + giftId);
     return generateBadRequest("Invalid Gift Status. Details:" + e);
   }
   // send email to merchant who has challenge with this gift card.
   try {
     if (giftStatus.equals("FUNDED")) {
       EmailService.sendMail(giftId);
     }
   } catch (Exception e) {
     Logger.error("Failed to send Email. GiftId" + giftId);
   }
   return ok(gift.toJson());
 }
  public void onReceive(Object message) throws Exception {

    System.out.println("----------------------------------------------------------");
    if (getSender().equals(getContext().parent())) {
      System.out.println("-A-" + getSender()); // == getContext().parent()
      System.out.println("-A-" + getSelf());
      System.out.println("-A-" + getContext().self());
      System.out.println("-A-" + getContext().parent());
      if (message instanceof JsonNode) {
        System.out.println("-A-" + "GO!");
        JsonNode event = (JsonNode) message;
        models.ChatRoom.defaultRoom.tell(
            new Talk(username, event.get("text").asText()), getSender());
      } else {
        unhandled(message);
      }
    } else {
      System.out.println("-B-" + getSender());
      System.out.println("-B-" + getSelf());
      System.out.println("-B-" + getContext().self());
      System.out.println("-B-" + getContext().parent());
      if (message instanceof ObjectNode) {
        System.out.println("-B-" + "GO!");
        // JsonNode event = (JsonNode)message;
        out.tell(message, ActorRef.noSender());
      } else {
        unhandled(message);
      }
    }
  }
 private boolean validateJsonConf() throws IOException, ProcessingException {
   JsonNode schemaNode =
       JsonLoader.fromFile(new File("src/main/resources/ConfigurationSchema.json"));
   JsonSchemaFactory schemaFactory = JsonSchemaFactory.byDefault();
   /*
   Here we consume the original jsonConfigReader in the process of validation and recreate a Reader from JsonNode
   then assign it back to the jsonConfigReader, if the validation succeed.
   Can we improve this logic?
    */
   if (schemaFactory.getSyntaxValidator().schemaIsValid(schemaNode)) {
     JsonSchema jsonSchema = schemaFactory.getJsonSchema(schemaNode);
     JsonNode topologyConfig = JsonLoader.fromReader(jsonConfigReader);
     ProcessingReport report = jsonSchema.validate(topologyConfig);
     if (report.isSuccess()) {
       log.info("Validation succeeded... ");
       log.info(report.toString());
       jsonConfigReader =
           new InputStreamReader(new ByteArrayInputStream(topologyConfig.toString().getBytes()));
       return true;
     } else {
       log.error("Validation failed...");
       log.error(report.toString());
       throw new RuntimeException(
           "Configuration file validation failed, Please recheck configuration file and try again");
     }
   } else {
     log.error("Json configuration schema is not valid ");
     log.error("Terminate the process .....");
     throw new RuntimeException("Json Configuration schema is not valid");
   }
 }
 public String parseData(JsonNode node, String f)
     throws JsonProcessingException, IOException, JSONException {
   System.out.println("---");
   ObjectNode json = factory.objectNode();
   type.push(f);
   Iterator<String> fieldNames = node.fieldNames();
   String uri = type.toString().replaceAll(", ", ".").replaceAll("[\\[\\]]", "");
   json.put("type_uri", uri);
   ObjectNode object = factory.objectNode();
   while (fieldNames.hasNext()) {
     String fieldName = fieldNames.next();
     JsonNode fieldValue = node.get(fieldName);
     // if (node.findParent("description").get("description") != null)
     // json.set("value", node.findParent("description").get("description"));
     if (fieldValue.isObject()) {
       ObjectNode assoc = factory.objectNode();
       assoc.set(uri + "." + parseData(fieldValue, fieldName).replaceAll("\n", ""), fieldValue);
       json.set("composite", assoc);
     } else {
       json.set(fieldName, fieldValue);
     }
   }
   // json.append("}");
   System.out.println("xxx");
   System.out.println(m.writerWithDefaultPrettyPrinter().writeValueAsString(json));
   TopicModel t = new TopicModel(new JSONObject(json.toString()));
   System.err.println(t.getUri());
   System.err.println(t.getChildTopicsModel());
   return type.pop();
 }
 @RequestMapping("/drug/enforcements")
 @ResponseBody
 public JsonNode getDrugRecallsForUnii(
     @RequestParam(value = "unii", defaultValue = "") String unii,
     @RequestParam(value = "limit", defaultValue = "0") int limit)
     throws Exception {
   JsonNode node;
   HttpHeaders headers = new HttpHeaders();
   ObjectMapper mapper = new ObjectMapper();
   headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
   UriComponentsBuilder builder =
       UriComponentsBuilder.fromHttpUrl(searchDrugEnfrcmntUrl)
           .queryParam("limit", uniiRecallsLimit);
   this.apiKey.addToUriComponentsBuilder(builder);
   if (unii != null && unii.trim().length() > 0) {
     builder.queryParam("search", "openfda.unii:" + unii);
     try {
       node = mapper.readTree(rest.getForObject(builder.build().toUri(), String.class));
       ((ObjectNode) node).set("results", getSortedResults(node.get("results"), limit));
     } catch (HttpClientErrorException ex) {
       if (ex.getStatusCode().value() == 404) {
         node =
             new ObjectMapper()
                 .readTree(
                     "{\"error\":{\"code\":\"NOT_FOUND\", \"message\":\"No matches found!\"}}");
       } else {
         throw ex;
       }
     }
   } else {
     node = getDrugRecalls(limit == 0 ? 10 : limit, null, null);
   }
   return node;
 }
  /**
   * Parse a JSON response to extract an entity document.
   *
   * <p>TODO This method currently contains code to work around Wikibase issue
   * https://phabricator.wikimedia.org/T73349. This should be removed once the issue is fixed.
   *
   * @param entityNode the JSON node that should contain the entity document data
   * @return the entitiy document, or null if there were unrecoverable errors
   * @throws IOException
   * @throws JsonProcessingException
   */
  private EntityDocument parseJsonResponse(JsonNode entityNode)
      throws JsonProcessingException, IOException {
    try {
      JacksonTermedStatementDocument ed =
          mapper.treeToValue(entityNode, JacksonTermedStatementDocument.class);
      ed.setSiteIri(this.siteIri);

      return ed;
    } catch (JsonProcessingException e) {
      logger.warn(
          "Error when reading JSON for entity "
              + entityNode.path("id").asText("UNKNOWN")
              + ": "
              + e.toString()
              + "\nTrying to manually fix issue https://phabricator.wikimedia.org/T73349.");
      String jsonString = entityNode.toString();
      jsonString =
          jsonString
              .replace("\"sitelinks\":[]", "\"sitelinks\":{}")
              .replace("\"labels\":[]", "\"labels\":{}")
              .replace("\"aliases\":[]", "\"aliases\":{}")
              .replace("\"claims\":[]", "\"claims\":{}")
              .replace("\"descriptions\":[]", "\"descriptions\":{}");

      ObjectReader documentReader = this.mapper.reader(JacksonTermedStatementDocument.class);

      JacksonTermedStatementDocument ed;
      ed = documentReader.readValue(jsonString);
      ed.setSiteIri(this.siteIri);
      return ed;
    }
  }
 private void verifyAuthentication(ClientDetails config, HttpStatus finalStatus) {
   String baseUrl = "http://localhost:" + this.context.getEmbeddedServletContainer().getPort();
   RestTemplate rest = new TestRestTemplate();
   // First, verify the web endpoint can't be reached
   assertEndpointUnauthorized(baseUrl, rest);
   // Since we can't reach it, need to collect an authorization token
   HttpHeaders headers = getHeaders(config);
   String url = baseUrl + "/oauth/token";
   JsonNode tokenResponse =
       rest.postForObject(
           url, new HttpEntity<MultiValueMap<String, Object>>(getBody(), headers), JsonNode.class);
   String authorizationToken = tokenResponse.findValue("access_token").asText();
   String tokenType = tokenResponse.findValue("token_type").asText();
   String scope = tokenResponse.findValues("scope").get(0).toString();
   assertThat(tokenType, equalTo("bearer"));
   assertThat(scope, equalTo("\"read\""));
   // Now we should be able to see that endpoint.
   headers.set("Authorization", "BEARER " + authorizationToken);
   ResponseEntity<String> securedResponse =
       rest.exchange(
           new RequestEntity<Void>(headers, HttpMethod.GET, URI.create(baseUrl + "/securedFind")),
           String.class);
   assertThat(securedResponse.getStatusCode(), equalTo(HttpStatus.OK));
   assertThat(
       securedResponse.getBody(),
       equalTo("You reached an endpoint " + "secured by Spring Security OAuth2"));
   ResponseEntity<String> entity =
       rest.exchange(
           new RequestEntity<Void>(headers, HttpMethod.POST, URI.create(baseUrl + "/securedSave")),
           String.class);
   assertThat(entity.getStatusCode(), equalTo(finalStatus));
 }
  protected void assertResultsPresentInPostDataResponseWithStatusCheck(
      String url, ObjectNode body, int expectedStatusCode, String... expectedResourceIds)
      throws JsonProcessingException, IOException {
    int numberOfResultsExpected = 0;
    if (expectedResourceIds != null) {
      numberOfResultsExpected = expectedResourceIds.length;
    }

    // Do the actual call
    HttpPost post = new HttpPost(SERVER_URL_PREFIX + url);
    post.setEntity(new StringEntity(body.toString()));
    HttpResponse response = executeHttpRequest(post, expectedStatusCode);

    if (expectedStatusCode == HttpStatus.SC_OK) {
      // Check status and size
      JsonNode rootNode = objectMapper.readTree(response.getEntity().getContent());
      JsonNode dataNode = rootNode.get("data");
      assertEquals(numberOfResultsExpected, dataNode.size());

      // Check presence of ID's
      if (expectedResourceIds != null) {
        List<String> toBeFound = new ArrayList<String>(Arrays.asList(expectedResourceIds));
        Iterator<JsonNode> it = dataNode.iterator();
        while (it.hasNext()) {
          String id = it.next().get("id").textValue();
          toBeFound.remove(id);
        }
        assertTrue(
            "Not all entries have been found in result, missing: "
                + StringUtils.join(toBeFound, ", "),
            toBeFound.isEmpty());
      }
    }
  }