Exemplo n.º 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();
      }
    }
  }
  private void setupObjectNodes(final JsonNode schema) {
    JsonNode node = schema.path("properties");

    if (node.isObject()) properties.putAll(CollectionUtils.toMap(node.fields()));

    node = schema.path("patternProperties");

    if (node.isObject()) patternProperties.putAll(CollectionUtils.toMap(node.fields()));

    node = schema.path("additionalProperties");

    if (node.isObject()) additionalProperties = node;
  }
  @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 (node.isNull()) {
          builder.addEntry(name, null);
        } else if (node.isBoolean()) {
          builder.addEntry(name, node.booleanValue());
        } else if (node.isNumber()) {
          builder.addEntry(name, node.numberValue());
        } else {
          builder.addEntry(name, mapper.treeToValue(node, Object.class));
        }
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
    return builder.build();
  }
Exemplo n.º 4
0
 public static void flashMsg(JsonNode jsonNode) {
   Iterator<Entry<String, JsonNode>> it = jsonNode.fields();
   while (it.hasNext()) {
     Entry<String, JsonNode> field = it.next();
     flash(field.getKey(), field.getValue().asText());
   }
 }
  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;
  }
Exemplo n.º 6
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);
    }
  }
  @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();
  }
Exemplo n.º 8
0
 private void writeData(HttpURLConnection conn) throws IOException {
   conn.setRequestProperty("Content-Type", contentType);
   try (OutputStream os = conn.getOutputStream()) {
     switch (contentType) {
       case "application/json":
         Jackson.defaultMapper().writeValue(os, data);
         break;
       case "application/x-www-form-urlencoded":
         {
           Escaper escaper = UrlEscapers.urlFormParameterEscaper();
           StringBuilder content = new StringBuilder();
           Iterator<Map.Entry<String, JsonNode>> fields = data.fields();
           while (fields.hasNext()) {
             Map.Entry<String, JsonNode> field = fields.next();
             content.append(escaper.escape(field.getKey()));
             content.append("=");
             content.append(escaper.escape(field.getValue().asText()));
             if (fields.hasNext()) {
               content.append("&");
             }
           }
           String contentString = content.toString();
           log.info(
               "First {} characters of POST body are {}",
               LOG_TRUNCATE_CHARS,
               LessStrings.trunc(contentString, LOG_TRUNCATE_CHARS));
           os.write(contentString.getBytes());
           break;
         }
       default:
         throw new IllegalStateException("Unknown content type " + contentType);
     }
     os.flush();
   }
 }
Exemplo n.º 9
0
  public void initDataFromMDSD(JsonNode mdsdNode, JsonNode fmdBeanRoot, String language)
      throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {

    LANG = language;
    this.mdsd = mdsdNode;
    JsonNode fmdBean = fmdBeanRoot.get(0);

    Iterator<Map.Entry<String, JsonNode>> properties = mdsdNode.get(PROPERTIES_FIELD).fields();

    this.metaDataCleaned = new TreeMap<String, Object>();

    if (fmdBean != null) {
      while (properties.hasNext()) {

        Map.Entry<String, JsonNode> mapDsdTmp = properties.next();
        String key = mapDsdTmp.getKey();

        FMDProperty objectProperty =
            fillObjectProperty(Lists.newArrayList(mapDsdTmp.getValue().fields()).listIterator());
        Object returnedValue = getReturnedValueFromObject(objectProperty, fmdBean, key);

        if (returnedValue != null) {

          if (objectProperty.getTitleToVisualize() != null) {

            // 1) IF THERE IS A TYPE
            if (mapDsdTmp.getValue().get(TYPE_FIELD) != null) {

              FMDescriptor value =
                  new FMDescriptor(
                      key, objectProperty.getTitleToVisualize(), objectProperty.getDescription());
              String order = getOrderFromEntity(mapDsdTmp.getValue());

              // simple case: string type or number type
              if (isReadyToPut(objectProperty)) {
                this.metaDataCleaned.put(
                    order, value.setValue(((TextNode) returnedValue).asText()));
              } else {
                this.metaDataCleaned.put(
                    order,
                    value.setValue(fillRecursive2(mapDsdTmp.getValue().fields(), returnedValue)));
              }
            }
            // 2) REF TYPE
            else if (mapDsdTmp.getValue().get(REF_FIELD) != null) {

              JsonNode msdRef =
                  getMdsdObjectFromReference(mapDsdTmp.getValue().get(REF_FIELD).asText());
              String order = getOrderFromEntity(mapDsdTmp.getValue());

              FMDescriptor tempVal = initDtoMDSD(mapDsdTmp.getValue(), key);
              this.metaDataCleaned.put(
                  order, tempVal.setValue(fillRecursive2(msdRef.fields(), returnedValue)));
            }
          }
        }
      }
    }
  }
  @Override
  public void validate(final ValidationReport report, final JsonNode instance) {
    final JsonNode oldParent = report.getSchema();

    report.setSchema(parent);

    for (final KeywordValidator validator : validators)
      validator.validateInstance(report, instance);

    if (!(instance.isContainerNode() || report.isSuccess())) {
      report.setSchema(oldParent);
      return;
    }

    final JsonPointer ptr = report.getPath();

    JsonPointer current;

    if (instance.isArray()) {
      JsonNode subSchema;
      int i = 0;
      for (final JsonNode element : instance) {
        current = ptr.append(i);
        report.setPath(current);
        subSchema = arrayPath(i);
        JsonSchema.fromNode(parent, subSchema).validate(report, element);
        i++;
      }
      report.setSchema(oldParent);
      report.setPath(ptr);
      return;
    }

    // Can only be an object now
    final Map<String, JsonNode> map = CollectionUtils.toMap(instance.fields());

    String key;
    JsonNode value;

    for (final Map.Entry<String, JsonNode> entry : map.entrySet()) {
      key = entry.getKey();
      value = entry.getValue();
      current = ptr.append(key);
      report.setPath(current);
      for (final JsonNode subSchema : objectPath(key))
        JsonSchema.fromNode(parent, subSchema).validate(report, value);
    }

    report.setSchema(oldParent);
    report.setPath(ptr);
  }
Exemplo n.º 11
0
 private static Map<String, String> payloadToMap(String payload) {
   Map<String, String> data = new HashMap<String, String>();
   JsonNode payloadJson = JsonMapper.asJsonNode(payload);
   Iterator<Entry<String, JsonNode>> fields = payloadJson.fields();
   while (fields.hasNext()) {
     Map.Entry<String, JsonNode> field = fields.next();
     if (field.getValue().isValueNode()) {
       data.put(field.getKey(), field.getValue().asText());
     } else {
       data.put(field.getKey(), JsonMapper.toString(field.getValue()));
     }
   }
   return data;
 }
 // Override needed to support legacy JSON Schema generator
 @Override
 protected void _depositSchemaProperty(ObjectNode propertiesNode, JsonNode schemaNode) {
   JsonNode props = schemaNode.get("properties");
   if (props != null) {
     Iterator<Entry<String, JsonNode>> it = props.fields();
     while (it.hasNext()) {
       Entry<String, JsonNode> entry = it.next();
       String name = entry.getKey();
       if (_nameTransformer != null) {
         name = _nameTransformer.transform(name);
       }
       propertiesNode.set(name, entry.getValue());
     }
   }
 }
Exemplo n.º 13
0
  /**
   * Return a map out of an object's members
   *
   * <p>If the node given as an argument is not a map, an empty map is returned.
   *
   * @param node the node
   * @return a map
   */
  public static Map<String, JsonNode> asMap(final JsonNode node) {
    if (!node.isObject()) return Collections.emptyMap();

    final Iterator<Map.Entry<String, JsonNode>> iterator = node.fields();
    final Map<String, JsonNode> ret = Maps.newHashMap();

    Map.Entry<String, JsonNode> entry;

    while (iterator.hasNext()) {
      entry = iterator.next();
      ret.put(entry.getKey(), entry.getValue());
    }

    return ret;
  }
  @RequestMapping(value = "create", method = RequestMethod.POST)
  public Movie create(@RequestBody JsonNode jsonNode) {
    Map<Locale, String> translations = new HashMap<>();

    jsonNode
        .fields()
        .forEachRemaining(
            field -> {
              if (field.getKey().startsWith(Movie.TITLE + "-")) {
                String[] fieldName = field.getKey().split("-");
                translations.put(new Locale(fieldName[1]), field.getValue().asText());
              }
            });

    return moviesService.create(
        jsonNode.get(Movie.TITLE).asText(), jsonNode.get(Movie.YEAR).asInt(), translations);
  }
 private Task getTaskFromJson(JsonNode node) throws JsonProcessingException {
   if (node.isObject()) {
     ObjectNode onode = (ObjectNode) node;
     final JsonNode type = onode.remove("type");
     final JsonNode attributes = onode.remove("attributes");
     final JsonNode relationships = onode.remove("relationships");
     final JsonNode links = onode.remove("links");
     Iterator<Map.Entry<String, JsonNode>> fields = attributes.fields();
     while (fields.hasNext()) {
       Map.Entry<String, JsonNode> f = fields.next();
       onode.put(f.getKey(), f.getValue().textValue());
     }
     return mapper.treeToValue(onode, Task.class);
   } else {
     throw new JsonMappingException("Not an object: " + node);
   }
 }
  private void parse(
      final JsonNode jsonNode,
      final Set<String> contextIds,
      final List<ConfigurationEntity> entities) {

    final Iterator<Map.Entry<String, JsonNode>> it = jsonNode.fields();

    while (it.hasNext()) {
      final Map.Entry<String, JsonNode> next = it.next();
      if (next.getValue().isContainerNode()) {
        contextIds.add(next.getKey());
        parse(next.getValue(), contextIds, entities);
      } else {
        entities.add(
            new ConfigurationEntity("test1", contextIds, next.getKey(), next.getValue().asText()));
      }
    }
  }
Exemplo n.º 17
0
    @Override
    public Volumes deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
        throws IOException, JsonProcessingException {

      List<Volume> volumes = new ArrayList<Volume>();
      ObjectCodec oc = jsonParser.getCodec();
      JsonNode node = oc.readTree(jsonParser);
      for (Iterator<Map.Entry<String, JsonNode>> it = node.fields(); it.hasNext(); ) {

        Map.Entry<String, JsonNode> field = it.next();
        if (!field.getValue().equals(NullNode.getInstance())) {
          String path = field.getKey();
          Volume volume = new Volume(path);
          volumes.add(volume);
        }
      }
      return new Volumes(volumes.toArray(new Volume[0]));
    }
Exemplo n.º 18
0
  /**
   * read properties from disk
   *
   * @return success True if successfully read
   * @throws ClassNotFoundException
   * @throws IOException
   */
  private void read() throws IOException, ClassNotFoundException {
    try {
      if (channel != null) {
        channel.position(0);
      }
      properties.clear();
      JsonNode data = om.readTree(fis);
      Iterator<Entry<String, JsonNode>> fieldIter = data.fields();

      while (fieldIter.hasNext()) {
        Entry<String, JsonNode> item = fieldIter.next();
        properties.put(item.getKey(), item.getValue());
      }
    } catch (EOFException eof) {
      // empty file, new agent?
    } catch (JsonMappingException jme) {
      // empty file, new agent?
    }
  }
  @BeforeClass
  public void setUp() throws IOException, JsonSchemaException {
    final JsonNode schemaList = JsonLoader.fromResource("/ref/jsonresolver-schemas.json");
    testData = JsonLoader.fromResource("/ref/jsonresolver-testdata.json");

    manager = mock(URIManager.class);
    registry = new SchemaRegistry(manager);

    final Map<String, JsonNode> map = CollectionUtils.toMap(schemaList.fields());

    URI uri;
    JsonNode schema;

    for (final Map.Entry<String, JsonNode> entry : map.entrySet()) {
      uri = URI.create(entry.getKey());
      schema = entry.getValue();
      when(manager.getContent(uri)).thenReturn(schema);
    }

    resolver = new JsonResolver(registry);
  }
  @Test
  public void testModuleWithMethods() throws Exception {
    JavaScriptModulesConfig jsModulesConfig =
        new JavaScriptModulesConfig.Builder().add(SomeModule.class).build();

    String json = getModuleDescriptions(jsModulesConfig);
    JsonNode node = parse(json);
    assertThat(node).hasSize(1);

    JsonNode module = node.fields().next().getValue();
    assertThat(module).isNotNull();

    JsonNode methods = module.get("methods");
    assertThat(methods).isNotNull().hasSize(2);

    JsonNode intMethodNode = methods.get("intMethod");
    assertThat(intMethodNode).isNotNull();
    assertThat(intMethodNode.get("methodID").asInt()).isEqualTo(0);

    JsonNode stringMethod = methods.get("stringMethod");
    assertThat(stringMethod).isNotNull();
    assertThat(stringMethod.get("methodID").asInt()).isEqualTo(1);
  }
  /** Test getting the engine properties. */
  public void testGetProperties() throws Exception {
    CloseableHttpResponse response =
        executeRequest(
            new HttpGet(
                SERVER_URL_PREFIX
                    + RestUrls.createRelativeResourceUrl(RestUrls.URL_PROPERTIES_COLLECTION)),
            HttpStatus.SC_OK);

    Map<String, String> properties = managementService.getProperties();

    JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);
    assertNotNull(responseNode);
    assertEquals(properties.size(), responseNode.size());

    Iterator<Map.Entry<String, JsonNode>> nodes = responseNode.fields();
    Map.Entry<String, JsonNode> node = null;
    while (nodes.hasNext()) {
      node = nodes.next();
      String propValue = properties.get(node.getKey());
      assertNotNull(propValue);
      assertEquals(propValue, node.getValue().textValue());
    }
  }
  @Override
  protected void doHandleResponse(HttpResponse httpResponse) throws Exception {

    final Session session = SessionManager.getSession(getSyncAccountId());

    Header tokenHeader = httpResponse.getFirstHeader("Sync-JWT");

    if (tokenHeader != null) {
      session.setToken(tokenHeader.getValue());
    }

    Map<String, DownloadFileHandler> handlers =
        (Map<String, DownloadFileHandler>) getParameterValue("handlers");

    InputStream inputStream = null;

    try {
      HttpEntity httpEntity = httpResponse.getEntity();

      inputStream =
          new CountingInputStream(httpEntity.getContent()) {

            @Override
            protected synchronized void afterRead(int n) {
              session.incrementDownloadedBytes(n);

              super.afterRead(n);
            }
          };

      ZipInputStream zipInputStream = new ZipInputStream(inputStream);

      ZipEntry zipEntry = null;

      while ((zipEntry = zipInputStream.getNextEntry()) != null) {
        String zipEntryName = zipEntry.getName();

        if (zipEntryName.equals("errors.json")) {
          JsonNode rootJsonNode = JSONUtil.readTree(zipInputStream);

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

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

            Handler<Void> handler = handlers.get(field.getKey());

            JsonNode valueJsonNode = field.getValue();

            JsonNode exceptionJsonNode = valueJsonNode.get("exception");

            handler.handlePortalException(exceptionJsonNode.textValue());
          }

          break;
        }

        DownloadFileHandler downloadFileHandler = handlers.get(zipEntryName);

        SyncFile syncFile = (SyncFile) downloadFileHandler.getParameterValue("syncFile");

        if (downloadFileHandler.isUnsynced(syncFile)) {
          continue;
        }

        if (_logger.isTraceEnabled()) {
          _logger.trace(
              "Handling response {} file path {}",
              DownloadFileHandler.class.getSimpleName(),
              syncFile.getFilePathName());
        }

        try {
          downloadFileHandler.copyFile(
              syncFile,
              Paths.get(syncFile.getFilePathName()),
              new CloseShieldInputStream(zipInputStream),
              false);
        } catch (Exception e) {
          if (!isEventCancelled()) {
            _logger.error(e.getMessage(), e);
          }
        } finally {
          downloadFileHandler.removeEvent();
        }
      }
    } catch (Exception e) {
      if (!isEventCancelled() && _logger.isDebugEnabled()) {
        _logger.debug(e.getMessage(), e);
      }
    } finally {
      StreamUtil.cleanUp(inputStream);
    }
  }
Exemplo n.º 23
0
 public HalRepresentationBuilder addProperties(JsonNode jax) {
   require(jax.isObject());
   jax.fields().forEachRemaining(e -> addProperty(e.getKey(), e.getValue()));
   return this;
 }
Exemplo n.º 24
0
  private Schema asConnectSchema(JsonNode jsonSchema) {
    if (jsonSchema.isNull()) return null;

    Schema cached = toConnectSchemaCache.get(jsonSchema);
    if (cached != null) return cached;

    JsonNode schemaTypeNode = jsonSchema.get(JsonSchema.SCHEMA_TYPE_FIELD_NAME);
    if (schemaTypeNode == null || !schemaTypeNode.isTextual())
      throw new DataException("Schema must contain 'type' field");

    final SchemaBuilder builder;
    switch (schemaTypeNode.textValue()) {
      case JsonSchema.BOOLEAN_TYPE_NAME:
        builder = SchemaBuilder.bool();
        break;
      case JsonSchema.INT8_TYPE_NAME:
        builder = SchemaBuilder.int8();
        break;
      case JsonSchema.INT16_TYPE_NAME:
        builder = SchemaBuilder.int16();
        break;
      case JsonSchema.INT32_TYPE_NAME:
        builder = SchemaBuilder.int32();
        break;
      case JsonSchema.INT64_TYPE_NAME:
        builder = SchemaBuilder.int64();
        break;
      case JsonSchema.FLOAT_TYPE_NAME:
        builder = SchemaBuilder.float32();
        break;
      case JsonSchema.DOUBLE_TYPE_NAME:
        builder = SchemaBuilder.float64();
        break;
      case JsonSchema.BYTES_TYPE_NAME:
        builder = SchemaBuilder.bytes();
        break;
      case JsonSchema.STRING_TYPE_NAME:
        builder = SchemaBuilder.string();
        break;
      case JsonSchema.ARRAY_TYPE_NAME:
        JsonNode elemSchema = jsonSchema.get(JsonSchema.ARRAY_ITEMS_FIELD_NAME);
        if (elemSchema == null)
          throw new DataException("Array schema did not specify the element type");
        builder = SchemaBuilder.array(asConnectSchema(elemSchema));
        break;
      case JsonSchema.MAP_TYPE_NAME:
        JsonNode keySchema = jsonSchema.get(JsonSchema.MAP_KEY_FIELD_NAME);
        if (keySchema == null) throw new DataException("Map schema did not specify the key type");
        JsonNode valueSchema = jsonSchema.get(JsonSchema.MAP_VALUE_FIELD_NAME);
        if (valueSchema == null)
          throw new DataException("Map schema did not specify the value type");
        builder = SchemaBuilder.map(asConnectSchema(keySchema), asConnectSchema(valueSchema));
        break;
      case JsonSchema.STRUCT_TYPE_NAME:
        builder = SchemaBuilder.struct();
        JsonNode fields = jsonSchema.get(JsonSchema.STRUCT_FIELDS_FIELD_NAME);
        if (fields == null || !fields.isArray())
          throw new DataException("Struct schema's \"fields\" argument is not an array.");
        for (JsonNode field : fields) {
          JsonNode jsonFieldName = field.get(JsonSchema.STRUCT_FIELD_NAME_FIELD_NAME);
          if (jsonFieldName == null || !jsonFieldName.isTextual())
            throw new DataException("Struct schema's field name not specified properly");
          builder.field(jsonFieldName.asText(), asConnectSchema(field));
        }
        break;
      default:
        throw new DataException("Unknown schema type: " + schemaTypeNode.textValue());
    }

    JsonNode schemaOptionalNode = jsonSchema.get(JsonSchema.SCHEMA_OPTIONAL_FIELD_NAME);
    if (schemaOptionalNode != null
        && schemaOptionalNode.isBoolean()
        && schemaOptionalNode.booleanValue()) builder.optional();
    else builder.required();

    JsonNode schemaNameNode = jsonSchema.get(JsonSchema.SCHEMA_NAME_FIELD_NAME);
    if (schemaNameNode != null && schemaNameNode.isTextual())
      builder.name(schemaNameNode.textValue());

    JsonNode schemaVersionNode = jsonSchema.get(JsonSchema.SCHEMA_VERSION_FIELD_NAME);
    if (schemaVersionNode != null && schemaVersionNode.isIntegralNumber()) {
      builder.version(schemaVersionNode.intValue());
    }

    JsonNode schemaDocNode = jsonSchema.get(JsonSchema.SCHEMA_DOC_FIELD_NAME);
    if (schemaDocNode != null && schemaDocNode.isTextual()) builder.doc(schemaDocNode.textValue());

    JsonNode schemaParamsNode = jsonSchema.get(JsonSchema.SCHEMA_PARAMETERS_FIELD_NAME);
    if (schemaParamsNode != null && schemaParamsNode.isObject()) {
      Iterator<Map.Entry<String, JsonNode>> paramsIt = schemaParamsNode.fields();
      while (paramsIt.hasNext()) {
        Map.Entry<String, JsonNode> entry = paramsIt.next();
        JsonNode paramValue = entry.getValue();
        if (!paramValue.isTextual())
          throw new DataException("Schema parameters must have string values.");
        builder.parameter(entry.getKey(), paramValue.textValue());
      }
    }

    JsonNode schemaDefaultNode = jsonSchema.get(JsonSchema.SCHEMA_DEFAULT_FIELD_NAME);
    if (schemaDefaultNode != null)
      builder.defaultValue(convertToConnect(builder, schemaDefaultNode));

    Schema result = builder.build();
    toConnectSchemaCache.put(jsonSchema, result);
    return result;
  }
Exemplo n.º 25
0
  /**
   * * Login the user. parameters: username password appcode: the App Code (API KEY) login_data:
   * json serialized string containing info related to the device used by the user. In particular,
   * for push notification, must by supplied: deviceId os: (android|ios)
   *
   * @return
   * @throws SqlInjectionException
   * @throws IOException
   * @throws JsonProcessingException
   */
  @With({NoUserCredentialWrapFilter.class})
  public static Result login() throws SqlInjectionException, JsonProcessingException, IOException {
    String username = "";
    String password = "";
    String appcode = "";
    String loginData = null;

    RequestBody body = request().body();
    // BaasBoxLogger.debug ("Login called. The body is: {}", body);
    if (body == null)
      return badRequest(
          "missing data: is the body x-www-form-urlencoded or application/json? Detected: "
              + request().getHeader(CONTENT_TYPE));
    Map<String, String[]> bodyUrlEncoded = body.asFormUrlEncoded();
    if (bodyUrlEncoded != null) {
      if (bodyUrlEncoded.get("username") == null)
        return badRequest("The 'username' field is missing");
      else username = bodyUrlEncoded.get("username")[0];
      if (bodyUrlEncoded.get("password") == null)
        return badRequest("The 'password' field is missing");
      else password = bodyUrlEncoded.get("password")[0];
      if (bodyUrlEncoded.get("appcode") == null)
        return badRequest("The 'appcode' field is missing");
      else appcode = bodyUrlEncoded.get("appcode")[0];
      if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("Username " + username);
      if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("Password " + password);
      if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("Appcode " + appcode);
      if (username.equalsIgnoreCase(BBConfiguration.getBaasBoxAdminUsername())
          || username.equalsIgnoreCase(BBConfiguration.getBaasBoxUsername()))
        return forbidden(username + " cannot login");

      if (bodyUrlEncoded.get("login_data") != null) loginData = bodyUrlEncoded.get("login_data")[0];
      if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("LoginData" + loginData);
    } else {
      JsonNode bodyJson = body.asJson();
      if (bodyJson == null)
        return badRequest(
            "missing data : is the body x-www-form-urlencoded or application/json? Detected: "
                + request().getHeader(CONTENT_TYPE));
      if (bodyJson.get("username") == null) return badRequest("The 'username' field is missing");
      else username = bodyJson.get("username").asText();
      if (bodyJson.get("password") == null) return badRequest("The 'password' field is missing");
      else password = bodyJson.get("password").asText();
      if (bodyJson.get("appcode") == null) return badRequest("The 'appcode' field is missing");
      else appcode = bodyJson.get("appcode").asText();
      if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("Username " + username);
      if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("Password " + password);
      if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("Appcode " + appcode);
      if (username.equalsIgnoreCase(BBConfiguration.getBaasBoxAdminUsername())
          || username.equalsIgnoreCase(BBConfiguration.getBaasBoxUsername()))
        return forbidden(username + " cannot login");

      if (bodyJson.get("login_data") != null) loginData = bodyJson.get("login_data").asText();
      if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("LoginData" + loginData);
    }
    /* other useful parameter to receive and to store...*/
    // validate user credentials
    ODatabaseRecordTx db = null;
    String user = null;
    try {
      db = DbHelper.open(appcode, username, password);
      user = prepareResponseToJson(UserService.getCurrentUser());

      if (loginData != null) {
        JsonNode loginInfo = null;
        try {
          loginInfo = Json.parse(loginData);
        } catch (Exception e) {
          if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("Error parsong login_data field");
          if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug(ExceptionUtils.getFullStackTrace(e));
          return badRequest("login_data field is not a valid json string");
        }
        Iterator<Entry<String, JsonNode>> it = loginInfo.fields();
        HashMap<String, Object> data = new HashMap<String, Object>();
        while (it.hasNext()) {
          Entry<String, JsonNode> element = it.next();
          String key = element.getKey();
          Object value = element.getValue().asText();
          data.put(key, value);
        }
        UserService.registerDevice(data);
      }
    } catch (OSecurityAccessException e) {
      if (BaasBoxLogger.isDebugEnabled())
        BaasBoxLogger.debug("UserLogin: "******"user " + username + " unauthorized");
    } catch (InvalidAppCodeException e) {
      if (BaasBoxLogger.isDebugEnabled())
        BaasBoxLogger.debug("UserLogin: "******"user " + username + " unauthorized");
    } finally {
      if (db != null && !db.isClosed()) db.close();
    }
    ImmutableMap<SessionKeys, ? extends Object> sessionObject =
        SessionTokenProvider.getSessionTokenProvider().setSession(appcode, username, password);
    response()
        .setHeader(SessionKeys.TOKEN.toString(), (String) sessionObject.get(SessionKeys.TOKEN));

    ObjectMapper mapper = new ObjectMapper();
    user =
        user.substring(0, user.lastIndexOf("}"))
            + ",\""
            + SessionKeys.TOKEN.toString()
            + "\":\""
            + (String) sessionObject.get(SessionKeys.TOKEN)
            + "\"}";
    JsonNode jn = mapper.readTree(user);

    return ok(jn);
  }