Esempio n. 1
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;
    }
  }
  @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);
  }
Esempio n. 3
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));
  }
Esempio n. 4
0
 private boolean checkSignedRequest(HttpServletRequest request, HttpServletResponse response)
     throws IOException {
   String param = request.getParameter(SIGNED_REQUEST);
   if (param != null) {
     log.debug("Signed request: " + param);
     String[] split = param.split("\\.", 2);
     Base64 base64 = new Base64(true);
     byte[] sig = base64.decode(split[0].getBytes(UTF_8));
     JsonNode data = mapper.readTree(new String(base64.decode(split[1].getBytes(UTF_8)), UTF_8));
     log.trace("Signature: " + split[0]);
     log.trace("JSON: " + data);
     if (!data.get("algorithm").asText().equals(HMAC_SHA256)) {
       log.error("Dropping auth attempt; unknown algorithm: " + data.get("algorithm").asText());
       return false;
     }
     byte[] hmac = hmac(split[1], appSecret);
     if (!Arrays.equals(hmac, sig)) {
       log.error(
           "Dropping auth attempt; incorrect sig; expected: "
               + new String(base64.encode(hmac), UTF_8)
               + "; was: "
               + split[0]);
       return false;
     }
     if (!data.has("user_id") || !data.has("oauth_token")) {
       log.debug("Attempting OAuth");
       String url = getDialogUrl();
       redirect(response, url, true);
       return false;
     } else {
       // this is authorized user, get their info from Graph API using received access token
       String token = data.get("oauth_token").asText();
       String exp = data.get("expires").asText();
       log.debug("Found token: " + token);
       log.trace("Found expiry date: " + exp + " (" + new Date(Long.parseLong(exp) * 1000L) + ")");
       AuthToken tok = new AuthToken(token, Long.parseLong(exp) * 1000L);
       createUserSessionDetails(request, tok);
       setFirstAccess(request);
       return true;
     }
   } else {
     /*if(log.isTraceEnabled()) {
     	Map<?, ?> map = request.getParameterMap();
     	for(Entry<?, ?> e : map.entrySet()) {
     		log.trace("Param: " + e.getKey() + " = " + e.getValue());
     	}
     }*/
     if (isOathResponse(request)) {
       log.trace(
           "This is a facebook canvas request, but without signed request, redirecting to facebook uri");
       redirect(response, fbFinalredirectUri, false);
       return false;
     } else if (checkLocalSignIn(request)) {
       return true;
     } else {
       return getSessionAttribute(request, USER_ATTR) != null;
     }
   }
 }
 public static boolean is_me(@Nonnull JsonNode json) {
   assert json != null;
   return json.has("action")
       && json.get("action").asText().equals("created")
       && json.has("issue")
       && json.has("comment")
       && json.has("repository")
       && json.has("sender")
       && json.size() == 5
       && (json.get("issue").has("pull_request"));
 }
  private SchemaAndValue jsonToConnect(JsonNode jsonValue) {
    if (jsonValue == null) return SchemaAndValue.NULL;

    if (!jsonValue.isObject()
        || jsonValue.size() != 2
        || !jsonValue.has(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME)
        || !jsonValue.has(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME))
      throw new DataException(
          "JSON value converted to Kafka Connect must be in envelope containing schema");

    Schema schema = asConnectSchema(jsonValue.get(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME));
    return new SchemaAndValue(
        schema, convertToConnect(schema, jsonValue.get(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME)));
  }
Esempio n. 7
0
  /**
   * Hack for URN support
   *
   * @param currentPackage
   * @param node
   * @param schema
   * @return
   */
  public String deriveClassQualifiedName(JPackage currentPackage, JsonNode node, Schema schema) {
    String qualifiedName = null;
    if (node.has("id")) {
      String idStr = node.get("id").asText();
      URI nodeId = URI.create(idStr);
      String scheme = nodeId.getScheme();
      if (idStr.indexOf('?') < 0
          && (scheme.equalsIgnoreCase("urn")
              || (idStr.charAt(scheme.length() + 1) == '/'
                  && idStr.charAt(scheme.length() + 2) == '/'))) {
        char delimiter = idStr.charAt(scheme.length());
        String idWoScheme = idStr.substring(scheme.length() + 1);
        String authority = idWoScheme.substring(0, idWoScheme.indexOf(delimiter));
        String qualifiedNameTemplate = idWoScheme;
        if (authority.equalsIgnoreCase("jsonschema") || authority.equalsIgnoreCase("schema")) {
          qualifiedNameTemplate = idWoScheme.substring(authority.length());
        }
        // System.out.println("package-template before-cleanup "+qualifiedNameTemplate);
        qualifiedNameTemplate =
            qualifiedNameTemplate.replaceAll("\\" + delimiter, ".").replaceAll("#", ".");
        if (qualifiedNameTemplate.charAt(0) == '.') {
          qualifiedNameTemplate = qualifiedNameTemplate.substring(1);
        }
        qualifiedName = qualifiedNameTemplate;
        // System.out.println("package-template after-cleanup "+qualifiedNameTemplate);
      } else {
        return qualifiedName;
      }

      // extra hacks for urn:jsonschema
    } else {
    }
    return qualifiedName;
  }
Esempio n. 8
0
  @With({UserCredentialWrapFilter.class, ConnectToDBFilter.class})
  @BodyParser.Of(BodyParser.Json.class)
  public static Result changePassword() {
    if (BaasBoxLogger.isTraceEnabled()) BaasBoxLogger.trace("Method Start");
    Http.RequestBody body = request().body();

    JsonNode bodyJson = body.asJson();
    if (BaasBoxLogger.isTraceEnabled()) BaasBoxLogger.trace("changePassword bodyJson: " + bodyJson);
    if (bodyJson == null)
      return badRequest(
          "The body payload cannot be empty. Hint: put in the request header Content-Type: application/json");

    // check and validate input
    if (!bodyJson.has("old")) return badRequest("The 'old' field is missing");
    if (!bodyJson.has("new")) return badRequest("The 'new' field is missing");

    String currentPassword = DbHelper.getCurrentHTTPPassword();
    String oldPassword = (String) bodyJson.findValuesAsText("old").get(0);
    String newPassword = (String) bodyJson.findValuesAsText("new").get(0);

    if (!oldPassword.equals(currentPassword)) {
      return badRequest("The old password does not match with the current one");
    }

    try {
      UserService.changePasswordCurrentUser(newPassword);
    } catch (OpenTransactionException e) {
      BaasBoxLogger.error(ExceptionUtils.getFullStackTrace(e));
      throw new RuntimeException(e);
    }
    if (BaasBoxLogger.isTraceEnabled()) BaasBoxLogger.trace("Method End");
    return ok();
  }
 @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());
     }
   }
 }
Esempio n. 10
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;
    }
Esempio n. 11
0
 public BooleanField(JsonNode node) {
   super(node);
   if (node.has("format")) {
     String formatString = node.get("format").asText();
     booleanValues = formatString.split(":");
   }
 }
  @Override
  public void propertyField(
      JFieldVar field, JDefinedClass clazz, String propertyName, JsonNode propertyNode) {
    field.annotate(JsonProperty.class).param("value", propertyName);
    if (field.type().erasure().equals(field.type().owner().ref(Set.class))) {
      field.annotate(JsonDeserialize.class).param("as", LinkedHashSet.class);
    }

    if (propertyNode.has("javaJsonView")) {
      field
          .annotate(JsonView.class)
          .param("value", field.type().owner().ref(propertyNode.get("javaJsonView").asText()));
    }

    if (propertyNode.has("description")) {
      field.annotate(JsonPropertyDescription.class).param("value", propertyNode.asText());
    }
  }
Esempio n. 13
0
 protected String getType(final JsonNode node) throws GeoJSONException {
   if (!node.has(TYPE)) {
     throw new GeoJSONException("Can not determine geometry type (missing 'type' field)");
   }
   if (!node.path(TYPE).isTextual()) {
     throw new GeoJSONException("'type' field has to be a string");
   }
   return node.path(TYPE).textValue();
 }
Esempio n. 14
0
  private static JsonNode extractAuthJson(final Path configPath) throws IOException {
    final JsonNode config = MAPPER.readTree(configPath.toFile());

    if (config.has("auths")) {
      return config.get("auths");
    }

    return config;
  }
Esempio n. 15
0
  /**
   * Creates a new Java class that will be generated.
   *
   * @param nodeName the node name which may be used to dictate the new class name
   * @param node the node representing the schema that caused the need for a new class. This node
   *     may include a 'javaType' property which if present will override the fully qualified name
   *     of the newly generated class.
   * @param _package the package which may contain a new class after this method call
   * @return a reference to a newly created class
   * @throws ClassAlreadyExistsException if the given arguments cause an attempt to create a class
   *     that already exists, either on the classpath or in the current map of classes to be
   *     generated.
   */
  private JDefinedClass createClass(String nodeName, JsonNode node, JPackage _package)
      throws ClassAlreadyExistsException {

    JDefinedClass newType;

    try {
      boolean usePolymorphicDeserialization = usesPolymorphicDeserialization(node);
      if (node.has("javaType")) {
        String fqn = substringBefore(node.get("javaType").asText(), "<");

        if (isPrimitive(fqn, _package.owner())) {
          throw new ClassAlreadyExistsException(primitiveType(fqn, _package.owner()));
        }

        int index = fqn.lastIndexOf(".") + 1;
        if (index >= 0 && index < fqn.length()) {
          fqn =
              fqn.substring(0, index)
                  + ruleFactory.getGenerationConfig().getClassNamePrefix()
                  + fqn.substring(index)
                  + ruleFactory.getGenerationConfig().getClassNameSuffix();
        }

        try {
          _package.owner().ref(Thread.currentThread().getContextClassLoader().loadClass(fqn));
          JClass existingClass =
              TypeUtil.resolveType(
                  _package,
                  fqn
                      + (node.get("javaType").asText().contains("<")
                          ? "<" + substringAfter(node.get("javaType").asText(), "<")
                          : ""));

          throw new ClassAlreadyExistsException(existingClass);
        } catch (ClassNotFoundException e) {
          if (usePolymorphicDeserialization) {
            newType = _package.owner()._class(JMod.PUBLIC, fqn, ClassType.CLASS);
          } else {
            newType = _package.owner()._class(fqn);
          }
        }
      } else {
        if (usePolymorphicDeserialization) {
          newType = _package._class(JMod.PUBLIC, getClassName(nodeName, _package), ClassType.CLASS);
        } else {
          newType = _package._class(getClassName(nodeName, _package));
        }
      }
    } catch (JClassAlreadyExistsException e) {
      throw new ClassAlreadyExistsException(e.getExistingClass());
    }

    ruleFactory.getAnnotator().propertyInclusion(newType, node);

    return newType;
  }
Esempio n. 16
0
  private static AuthConfig.Builder parseDockerConfig(final Path configPath, String serverAddress)
      throws IOException {
    checkNotNull(configPath);
    final AuthConfig.Builder authBuilder = AuthConfig.builder();
    final JsonNode authJson = extractAuthJson(configPath);

    if (isNullOrEmpty(serverAddress)) {
      final Iterator<String> servers = authJson.fieldNames();
      if (servers.hasNext()) {
        serverAddress = servers.next();
      }
    } else {
      if (!authJson.has(serverAddress)) {
        log.error("Could not find auth config for {}. Returning empty builder", serverAddress);
        return AuthConfig.builder().serverAddress(serverAddress);
      }
    }

    final JsonNode serverAuth = authJson.get(serverAddress);
    if (serverAuth != null && serverAuth.has("auth")) {
      authBuilder.serverAddress(serverAddress);
      final String authString = serverAuth.get("auth").asText();
      final String[] authParams = Base64.decodeAsString(authString).split(":");

      if (authParams.length == 2) {
        authBuilder.username(authParams[0].trim());
        authBuilder.password(authParams[1].trim());
      } else {
        log.warn("Failed to parse auth string for {}", serverAddress);
        return authBuilder;
      }
    } else {
      log.warn("Could not find auth field for {}", serverAddress);
      return authBuilder;
    }

    if (serverAuth.has("email")) {
      authBuilder.email(serverAuth.get("email").asText());
    }

    return authBuilder;
  }
Esempio n. 17
0
 private JType getSuperType(
     String nodeName, JsonNode node, JClassContainer jClassContainer, Schema schema) {
   JType superType = jClassContainer.owner().ref(Object.class);
   if (node.has("extends")) {
     superType =
         ruleFactory
             .getSchemaRule()
             .apply(nodeName + "Parent", node.get("extends"), jClassContainer, schema);
   }
   return superType;
 }
Esempio n. 18
0
  /**
   * Map path segments to tree nodes, each segment to a set of nodes of a same level from the root
   *
   * @param pathSegments
   * @param treeRoot
   * @return
   * @throws PathException
   */
  public static Map<String, List<JsonNode>> mapPath2Tree(
      List<String> pathSegments, JsonNode treeRoot) throws PathException {

    if (treeRoot == null || !treeRoot.has(pathSegments.get(0))) {
      // Failed from root
      return null;
    }
    Map<String, List<JsonNode>> queryMap = new HashMap<String, List<JsonNode>>();
    for (String s : pathSegments) {
      queryMap.put(s, new ArrayList<JsonNode>());
    }

    for (int i = 0; i < pathSegments.size(); i++) {
      String nodeName = pathSegments.get(i);
      List<JsonNode> ret = new ArrayList<JsonNode>();
      if (i == 0) {
        JsonNode childs = treeRoot.get(nodeName);
        if (childs != null) {
          if (childs.isArray()) {
            Iterator<JsonNode> iter = childs.iterator();
            while (iter.hasNext()) {
              ret.add(iter.next());
            }
          } else {
            ret.add(childs);
          }
        }
      } else {
        // parent node
        List<JsonNode> parents = queryMap.get(pathSegments.get(i - 1));
        for (JsonNode parent : parents) {
          JsonNode childs = parent.get(nodeName);
          if (childs != null) {
            if (childs.isArray()) {
              Iterator<JsonNode> iter = childs.iterator();
              while (iter.hasNext()) {
                ret.add(iter.next());
              }
            } else {
              ret.add(childs);
            }
          }
        }
      }
      if (ret.size() > 0) {
        queryMap.get(nodeName).addAll(ret);
      } else if (i < pathSegments.size() - 1) {
        // not found in the middle of the path
        return null;
      }
    }

    return queryMap;
  }
  @Override
  public String deserialize(JsonParser jp, DeserializationContext ctxt)
      throws IOException, JsonProcessingException {
    if (jp.hasCurrentToken() && jp.getCurrentToken().equals(JsonToken.START_OBJECT)) {
      ObjectMapper mapper = new ObjectMapper();
      JsonNode node = mapper.reader(JsonNode.class).readValue(jp);
      return node.has(VALUE) ? node.get(VALUE).textValue() : null;
    }

    throw ctxt.mappingException("Expected JSON object");
  }
Esempio n. 20
0
 // Parses the given JSON and provides links as configured.
 private void parseLinks() {
   JsonNode nodes = cfg.get("links");
   if (nodes != null) {
     for (JsonNode node : nodes) {
       parseLink(node, false);
       if (!node.has("halfplex")) {
         parseLink(node, true);
       }
     }
   }
 }
Esempio n. 21
0
 // [Issue#232]
 public void testBigDecimalAsPlainStringTreeConversion() throws Exception {
   ObjectMapper mapper = new ObjectMapper();
   mapper.enable(SerializationFeature.WRITE_BIGDECIMAL_AS_PLAIN);
   Map<String, Object> map = new HashMap<String, Object>();
   String PI_STR = "3.00000000";
   map.put("pi", new BigDecimal(PI_STR));
   JsonNode tree = mapper.valueToTree(map);
   assertNotNull(tree);
   assertEquals(1, tree.size());
   assertTrue(tree.has("pi"));
 }
  private <T> void assertEndpointReturns400(String endpoint, T entity) {
    Response response =
        target(String.format("/json/%s", endpoint))
            .request(MediaType.APPLICATION_JSON)
            .post(Entity.entity(entity, MediaType.APPLICATION_JSON));
    assertThat(response.getStatus()).isEqualTo(400);

    JsonNode errorMessage = response.readEntity(JsonNode.class);
    assertThat(errorMessage.get("code").asInt()).isEqualTo(400);
    assertThat(errorMessage.get("message").asText()).isEqualTo("Unable to process JSON");
    assertThat(errorMessage.has("details")).isFalse();
  }
 // This test is to verify extract-document-data & extract-path with  selected=exclude option query
 @Test
 public void testExtractDocumentData2() throws Exception {
   this.loadJSONDocuments();
   this.loadXMLDocuments();
   String head = "<search:search xmlns:search=\"http://marklogic.com/appservices/search\">";
   String tail = "</search:search>";
   String qtext4 = "<search:qtext>71 OR dog14</search:qtext>";
   DocumentManager docMgr = client.newDocumentManager();
   QueryManager queryMgr = client.newQueryManager();
   String options =
       "<search:options>"
           + "<search:extract-document-data selected=\"exclude\">"
           + "<search:extract-path>//foo</search:extract-path>"
           + "<search:extract-path>//says</search:extract-path>"
           + "</search:extract-document-data>"
           + "</search:options>";
   // test XML response with extracted XML and JSON matches
   String combinedSearch = head + qtext4 + options + tail;
   RawCombinedQueryDefinition rawCombinedQueryDefinition =
       queryMgr.newRawCombinedQueryDefinition(
           new StringHandle(combinedSearch).withMimetype("application/xml"));
   SearchHandle results = queryMgr.search(rawCombinedQueryDefinition, new SearchHandle());
   MatchDocumentSummary[] summaries = results.getMatchResults();
   assertNotNull(summaries);
   assertEquals(2, summaries.length);
   for (MatchDocumentSummary summary : summaries) {
     ExtractedResult extracted = summary.getExtracted();
     if (Format.XML == summary.getFormat()) {
       // we don't test for kind because it isn't sent in this case
       System.out.println("EXTRACTED Size ==" + extracted.size());
       // TODO:: Bug 33921 also add test to include-with-ancestors
       assertEquals(0, extracted.size());
       //			Document item1 = extracted.next().getAs(Document.class);
       //			assertEquals("This is so foo with a bar 71", item1.getFirstChild().getTextContent());
       continue;
     } else if (Format.JSON == summary.getFormat()) {
       // we don't test for kind because it isn't sent in this case
       assertEquals(1, extracted.size());
       for (ExtractedItem item : extracted) {
         String stringJsonItem = item.getAs(String.class);
         JsonNode nodeJsonItem = item.getAs(JsonNode.class);
         if (nodeJsonItem.has("animal")) {
           assertEquals("{\"animal\":\"dog14\"}", stringJsonItem);
           continue;
         }
         fail("unexpected extracted item:" + stringJsonItem);
       }
       continue;
     }
     fail("unexpected search result:" + summary.getUri());
   }
 }
  /**
   * Executes a call to wbeditentity. Minimal error handling.
   *
   * @param parameters the parameters to be used in the call
   * @return the entity document that is returned, or null in case of errors
   * @throws IOException if there were IO errors
   * @throws MediaWikiApiErrorException if the API returned an error
   */
  private EntityDocument doWbEditEntity(Map<String, String> parameters)
      throws IOException, MediaWikiApiErrorException {

    try (InputStream response = this.connection.sendRequest("POST", parameters)) {

      JsonNode root = this.mapper.readTree(response);

      this.connection.checkErrors(root);
      this.connection.logWarnings(root);

      if (root.has("item")) {
        return parseJsonResponse(root.path("item"));
      } else if (root.has("property")) {
        // TODO: not tested because of missing
        // permissions
        return parseJsonResponse(root.path("property"));
      } else if (root.has("entity")) {
        return parseJsonResponse(root.path("entity"));
      } else {
        throw new JsonMappingException("No entity document found in API response.");
      }
    }
  }
Esempio n. 25
0
  /**
   * Retrieve the list of properties to go in the constructor from node. This is all properties
   * listed in node["properties"] if ! onlyRequired, and only required properties if onlyRequired.
   *
   * @param node
   * @return
   */
  private List<String> getConstructorProperties(JsonNode node, boolean onlyRequired) {

    if (!node.has("properties")) {
      return new ArrayList<String>();
    }

    List<String> rtn = new ArrayList<String>();

    NameHelper nameHelper = ruleFactory.getNameHelper();
    for (Iterator<Map.Entry<String, JsonNode>> properties = node.get("properties").fields();
        properties.hasNext(); ) {
      Map.Entry<String, JsonNode> property = properties.next();

      JsonNode propertyObj = property.getValue();
      if (onlyRequired) {
        if (propertyObj.has("required") && propertyObj.get("required").asBoolean()) {
          rtn.add(nameHelper.getPropertyName(property.getKey()));
        }
      } else {
        rtn.add((nameHelper.getPropertyName(property.getKey())));
      }
    }
    return rtn;
  }
  /** tests getting serializer/deserializer instances. */
  public void testSerializeDeserializeWithJaxbAnnotations() throws Exception {
    ObjectMapper mapper = getJaxbMapper();
    // test expects that wrapper name be used...
    mapper.enable(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME);

    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    JaxbExample ex = new JaxbExample();
    QName qname = new QName("urn:hi", "hello");
    ex.setQname(qname);
    QName qname1 = new QName("urn:hi", "hello1");
    ex.setQname1(qname1);
    ex.setAttributeProperty("attributeValue");
    ex.setElementProperty("elementValue");
    ex.setWrappedElementProperty(Arrays.asList("wrappedElementValue"));
    ex.setEnumProperty(EnumExample.VALUE1);
    ex.setPropertyToIgnore("ignored");
    String json = mapper.writeValueAsString(ex);

    // uncomment to see what the JSON looks like.
    // System.out.println(json);

    // make sure the json is written out correctly.
    JsonNode node = mapper.readValue(json, JsonNode.class);
    assertEquals(qname.toString(), node.get("qname").asText());
    JsonNode attr = node.get("myattribute");
    assertNotNull(attr);
    assertEquals("attributeValue", attr.asText());
    assertEquals("elementValue", node.get("myelement").asText());
    assertTrue(node.has("mywrapped"));
    assertEquals(1, node.get("mywrapped").size());
    assertEquals("wrappedElementValue", node.get("mywrapped").get(0).asText());
    assertEquals("Value One", node.get("enumProperty").asText());
    assertNull(node.get("propertyToIgnore"));

    // now make sure it gets deserialized correctly.
    JaxbExample readEx = mapper.readValue(json, JaxbExample.class);
    assertEquals(ex.qname, readEx.qname);
    assertEquals(ex.qname1, readEx.qname1);
    assertEquals(ex.attributeProperty, readEx.attributeProperty);
    assertEquals(ex.elementProperty, readEx.elementProperty);
    assertEquals(ex.wrappedElementProperty, readEx.wrappedElementProperty);
    assertEquals(ex.enumProperty, readEx.enumProperty);
    assertNull(readEx.propertyToIgnore);
  }
Esempio n. 27
0
  @With({UserCredentialWrapFilter.class, ConnectToDBFilter.class})
  @BodyParser.Of(BodyParser.Json.class)
  public static Result updateProfile() {
    if (BaasBoxLogger.isTraceEnabled()) BaasBoxLogger.trace("Method Start");
    Http.RequestBody body = request().body();

    JsonNode bodyJson = body.asJson();
    if (BaasBoxLogger.isTraceEnabled()) BaasBoxLogger.trace("updateProfile bodyJson: " + bodyJson);
    if (bodyJson == null)
      return badRequest(
          "The body payload cannot be empty. Hint: put in the request header Content-Type: application/json");

    // extract the profile	 fields
    JsonNode nonAppUserAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_BY_ANONYMOUS_USER);
    JsonNode privateAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_ONLY_BY_THE_USER);
    JsonNode friendsAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_BY_FRIENDS_USER);
    JsonNode appUsersAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_BY_REGISTERED_USER);

    if (privateAttributes != null && privateAttributes.has("email")) {
      // check if email address is valid
      if (!Util.validateEmail((String) privateAttributes.findValuesAsText("email").get(0)))
        return badRequest("The email address must be valid.");
    }

    ODocument profile;
    try {
      profile =
          UserService.updateCurrentProfile(
              nonAppUserAttributes, privateAttributes, friendsAttributes, appUsersAttributes);
    } catch (Throwable e) {
      BaasBoxLogger.warn("updateProfile", e);
      if (Play.isDev()) return internalServerError(ExceptionUtils.getFullStackTrace(e));
      else return internalServerError(ExceptionUtils.getMessage(e));
    }
    if (BaasBoxLogger.isTraceEnabled()) BaasBoxLogger.trace("Method End");

    return ok(prepareResponseToJson(profile));
  } // updateProfile
 private static ImportSummary getImportSummary(Response response) {
   // because the web api almost randomly gives the responses in different forms, this
   // method checks which one it is that is being returned, and parses accordingly.
   try {
     JsonNode node =
         DhisController.getInstance()
             .getObjectMapper()
             .readTree(new StringConverter().fromBody(response.getBody(), String.class));
     if (node == null) {
       return null;
     }
     if (node.has("response")) {
       return getPutImportSummary(response);
     } else {
       return getPostImportSummary(response);
     }
   } catch (IOException e) {
     e.printStackTrace();
   } catch (ConversionException e) {
     e.printStackTrace();
   }
   return null;
 }
Esempio n. 29
0
    @Override
    public KeyValuedColumnType fromJsonNode(JsonNode json) {
      if (json.isValueNode() || !json.has("value")) {
        return null;
      }
      BaseType keyType = BaseType.fromJson(json, "key");
      BaseType valueType = BaseType.fromJson(json, "value");

      KeyValuedColumnType keyValueColumnType = new KeyValuedColumnType(keyType, valueType);
      JsonNode node = null;
      if ((node = json.get("min")) != null) {
        keyValueColumnType.setMin(node.asLong());
      }

      if ((node = json.get("max")) != null) {
        if (node.isLong()) {
          keyValueColumnType.setMax(node.asLong());
        } else if (node.isTextual() && "unlimited".equals(node.asText())) {
          keyValueColumnType.setMax(Long.MAX_VALUE);
        }
      }

      return keyValueColumnType;
    }
  protected void handleEvent(JsonNode event) { // obslug eventow z websocketa

    if (!event.has("request")) {
      return;
    }

    String request = event.get("request").asText();

    if (request.equals("geolocation")) {
      handleGeolocation(event);
      return;
    } else if (request.equals("search")) {

      // get request data
      String pattern = event.get("pattern").asText();
      Boolean limit = event.get("limit").asText().equals("true");
      List<String> tagList = ctxEx.extractTags(pattern);
      String searchPattern = ctxEx.stripTags(pattern);

      Logger.info("searching for:" + pattern + " with" + (limit ? "out" : "") + " limit");
      Logger.info("search:" + searchPattern + "\ntags:" + tagList.toString());

      ArrayList<ArrayList<String>> searchResult = search(searchPattern, limit);

      if (!tagList.isEmpty()) searchResult = filterOutByTags(searchResult, tagList);

      if (searchResult == null) {
        sendEmptyResults();
      } else {
        Logger.info(String.valueOf(searchResult.size()) + " found");

        ObjectNode message = Json.newObject(); // create message

        ArrayNode results = message.putArray("result"); // results array in message
        Set<String> tagsSet = new HashSet<>();

        for (ArrayList<String> result : searchResult) {
          ObjectNode innerMsg = Json.newObject(); // inner message (file info)
          innerMsg.put("file", result.get(0));
          innerMsg.put("link", result.get(1));
          innerMsg.put("size", result.get(2));

          ArrayNode tags = innerMsg.putArray("tags"); // tags array in innerMsg (for this file)
          // odejmujemy 4 ze wzgledu na to ze na poczatku sa 4 elementy ktore nie sa tagami
          int tagcount = result.size() - 4;
          for (int tagnr = 0; tagnr < tagcount - 2; tagnr++) {
            tags.add(result.get(4 + tagnr));
            tagsSet.add("\"" + result.get(4 + tagnr) + "\"");
          }
          String tempCont = ctxEx.getContext(result.get(3), searchPattern);
          innerMsg.put("context", tempCont);
          innerMsg.put("lat", result.get(result.size() - 2));
          innerMsg.put("lng", result.get(result.size() - 1));
          results.add(innerMsg);
        }
        int temp = searchResult.size();
        String temp2 = "" + temp;
        message.put("resultsCount", temp2);
        message.put("tagList", tagsSet.toString());
        socketOut.write(message);
      }
    }
  }