Example usage for com.fasterxml.jackson.databind JsonNode toString

List of usage examples for com.fasterxml.jackson.databind JsonNode toString

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind JsonNode toString.

Prototype

public abstract String toString();

Source Link

Usage

From source file:com.microsoft.rest.serializer.FlatteningDeserializer.java

@SuppressWarnings("unchecked")
@Override/*from  w w w .  jav a 2 s .  co m*/
public Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    JsonNode root = mapper.readTree(jp);
    final Class<?> tClass = this.defaultDeserializer.handledType();
    for (Field field : tClass.getDeclaredFields()) {
        JsonNode node = root;
        JsonProperty property = field.getAnnotation(JsonProperty.class);
        if (property != null) {
            String value = property.value();
            if (value.matches(".+[^\\\\]\\..+")) {
                String[] values = value.split("((?<!\\\\))\\.");
                for (String val : values) {
                    val = val.replace("\\.", ".");
                    node = node.get(val);
                    if (node == null) {
                        break;
                    }
                }
                ((ObjectNode) root).put(value, node);
            }
        }
    }
    JsonParser parser = new JsonFactory().createParser(root.toString());
    parser.nextToken();
    return defaultDeserializer.deserialize(parser, ctxt);
}

From source file:info.bonjean.quinkana.Main.java

private static void run(String[] args) throws QuinkanaException {
    Properties properties = new Properties();
    InputStream inputstream = Main.class.getResourceAsStream("/config.properties");

    try {/*ww w  .  j  a va  2  s.  com*/
        properties.load(inputstream);
        inputstream.close();
    } catch (IOException e) {
        throw new QuinkanaException("cannot load internal properties", e);
    }

    String name = (String) properties.get("name");
    String description = (String) properties.get("description");
    String url = (String) properties.get("url");
    String version = (String) properties.get("version");
    String usage = (String) properties.get("help.usage");
    String defaultHost = (String) properties.get("default.host");
    int defaultPort = Integer.valueOf(properties.getProperty("default.port"));

    ArgumentParser parser = ArgumentParsers.newArgumentParser(name).description(description)
            .epilog("For more information, go to " + url).version("${prog} " + version).usage(usage);
    parser.addArgument("ACTION").type(Action.class).choices(Action.tail, Action.list).dest("action");
    parser.addArgument("-H", "--host").setDefault(defaultHost)
            .help(String.format("logstash host (default: %s)", defaultHost));
    parser.addArgument("-P", "--port").type(Integer.class).setDefault(defaultPort)
            .help(String.format("logstash TCP port (default: %d)", defaultPort));
    parser.addArgument("-f", "--fields").nargs("+").help("fields to display");
    parser.addArgument("-i", "--include").nargs("+").help("include filter (OR), example host=example.com")
            .metavar("FILTER").type(Filter.class);
    parser.addArgument("-x", "--exclude").nargs("+")
            .help("exclude filter (OR, applied after include), example: severity=debug").metavar("FILTER")
            .type(Filter.class);
    parser.addArgument("-s", "--single").action(Arguments.storeTrue()).help("display single result and exit");
    parser.addArgument("--version").action(Arguments.version()).help("output version information and exit");

    Namespace ns = parser.parseArgsOrFail(args);

    Action action = ns.get("action");
    List<String> fields = ns.getList("fields");
    List<Filter> includes = ns.getList("include");
    List<Filter> excludes = ns.getList("exclude");
    boolean single = ns.getBoolean("single");
    String host = ns.getString("host");
    int port = ns.getInt("port");

    final Socket clientSocket;
    final InputStream is;
    try {
        clientSocket = new Socket(host, port);
        is = clientSocket.getInputStream();
    } catch (IOException e) {
        throw new QuinkanaException("cannot connect to the server " + host + ":" + port, e);
    }

    // add a hook to ensure we clean the resources when leaving
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });

    // prepare JSON parser
    ObjectMapper mapper = new ObjectMapper();
    JsonFactory jsonFactory = mapper.getFactory();
    JsonParser jp;
    try {
        jp = jsonFactory.createParser(is);
    } catch (IOException e) {
        throw new QuinkanaException("error during JSON parser creation", e);
    }

    JsonToken token;

    // action=list
    if (action.equals(Action.list)) {
        try {
            // do this in a separate loop to not pollute the main loop
            while ((token = jp.nextToken()) != null) {
                if (token != JsonToken.START_OBJECT)
                    continue;

                // parse object
                JsonNode node = jp.readValueAsTree();

                // print fields
                Iterator<String> fieldNames = node.fieldNames();
                while (fieldNames.hasNext())
                    System.out.println(fieldNames.next());

                System.exit(0);
            }
        } catch (IOException e) {
            throw new QuinkanaException("error during JSON parsing", e);
        }
    }

    // action=tail
    try {
        while ((token = jp.nextToken()) != null) {
            if (token != JsonToken.START_OBJECT)
                continue;

            // parse object
            JsonNode node = jp.readValueAsTree();

            // filtering (includes)
            if (includes != null) {
                boolean skip = true;
                for (Filter include : includes) {
                    if (include.match(node)) {
                        skip = false;
                        break;
                    }
                }
                if (skip)
                    continue;
            }

            // filtering (excludes)
            if (excludes != null) {
                boolean skip = false;
                for (Filter exclude : excludes) {
                    if (exclude.match(node)) {
                        skip = true;
                        break;
                    }
                }
                if (skip)
                    continue;
            }

            // if no field specified, print raw output (JSON)
            if (fields == null) {
                System.out.println(node.toString());
                if (single)
                    break;
                continue;
            }

            // formatted output, build and print the string
            StringBuilder sb = new StringBuilder(128);
            for (String field : fields) {
                if (sb.length() > 0)
                    sb.append(" ");

                if (node.get(field) != null && node.get(field).textValue() != null)
                    sb.append(node.get(field).textValue());
            }
            System.out.println(sb.toString());

            if (single)
                break;
        }
    } catch (IOException e) {
        throw new QuinkanaException("error during JSON parsing", e);
    }
}

From source file:com.networknt.light.server.handler.RestHandler.java

@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    if (exchange.isInIoThread()) {
        exchange.dispatch(this);
        return;/*from  w w w  .  ja v  a2 s.  co m*/
    }

    exchange.startBlocking();
    // check if it is get or post
    String json = null;
    Map<String, Object> jsonMap = null;
    if (Methods.GET.equals(exchange.getRequestMethod())) {
        Map params = exchange.getQueryParameters();
        String cmd = ((Deque<String>) params.get("cmd")).getFirst();
        json = URLDecoder.decode(cmd, "UTF8");
    } else if (Methods.POST.equals(exchange.getRequestMethod())) {
        json = new Scanner(exchange.getInputStream(), "UTF-8").useDelimiter("\\A").next();
    } else {
        logger.error("Invalid Request Method");
        exchange.setResponseCode(400);
        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
        exchange.getResponseSender().send((ByteBuffer.wrap("Invalid Request Method".getBytes("utf-8"))));
        return;
    }
    //logger.debug("json = {}", json);

    // convert json string to map here. It it cannot be converted, then it is invalid command.
    try {
        jsonMap = ServiceLocator.getInstance().getMapper().readValue(json,
                new TypeReference<HashMap<String, Object>>() {
                });
    } catch (Exception e) {
        exchange.setResponseCode(400);
        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
        exchange.getResponseSender().send((ByteBuffer.wrap("invalid_command".getBytes("utf-8"))));
        return;
    }

    // TODO validate with json schema to make sure the input json is valid. return an error message otherwise.
    // you need to get the schema from db again for the one sent from browser might be modified.
    String cmdRuleClass = Util.getCommandRuleId(jsonMap);
    boolean readOnly = (boolean) jsonMap.get("readOnly");
    if (!readOnly) {
        JsonSchema schema = AbstractValidationRule.getSchema(cmdRuleClass);
        if (schema != null) {
            // validate only if schema is not null.
            JsonNode jsonNode = mapper.valueToTree(jsonMap);
            ProcessingReport report = schema.validate(jsonNode.get("data"));
            logger.debug("report" + report);
            if (!report.isSuccess()) {
                exchange.setResponseCode(400);
                exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                JsonNode messages = ((ListProcessingReport) report).asJson();
                exchange.getResponseSender().send((ByteBuffer.wrap(messages.toString().getBytes("utf-8"))));
                return;
            }
        }
    }

    HeaderMap headerMap = exchange.getRequestHeaders();
    Map<String, Object> payload = null;
    try {
        payload = getTokenPayload(headerMap);
    } catch (IllegalStateException e) {
        //e.printStackTrace();
        String msg = e.getMessage();
        if (msg != null && msg.startsWith(JwtUtil.TOKEN_EXPIRED_MESSAGE)) {
            // return 401 status and let client to refresh the token.
            exchange.setResponseCode(401);
            exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
            exchange.getResponseSender().send((ByteBuffer.wrap("token_expired".getBytes("utf-8"))));
            return;
        } else {
            // invalid token, return 401 status and let client to discard the token.
            exchange.setResponseCode(401);
            exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
            exchange.getResponseSender().send((ByteBuffer.wrap("invalid_token".getBytes("utf-8"))));
            return;
        }
    }

    GetAccessRule rule = new GetAccessRule();
    Map<String, Object> access = rule.getAccessByRuleClass(cmdRuleClass);
    if (access != null) {
        // authorization rule available, check it.
        String accessLevel = (String) access.get("accessLevel");
        switch (accessLevel) {
        case "A":
            // Access by anyone.
            break;
        case "N":
            // Not accessible
            exchange.setResponseCode(400);
            exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
            exchange.getResponseSender().send((ByteBuffer.wrap("Not accessible".getBytes("utf-8"))));
            return;
        case "C":
            // client id is in the jwt token like userId and roles.
            if (payload == null) {
                exchange.setResponseCode(401);
                exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                exchange.getResponseSender().send((ByteBuffer.wrap("Login is required".getBytes("utf-8"))));
                return;
            } else {
                Map<String, Object> user = (Map<String, Object>) payload.get("user");
                String clientId = (String) user.get("clientId");
                List<String> clients = (List) access.get("clients");
                if (!clients.contains(clientId)) {
                    exchange.setResponseCode(403);
                    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                    exchange.getResponseSender()
                            .send((ByteBuffer.wrap("Client permission denied".getBytes("utf-8"))));
                    return;
                }
            }
            break;
        case "R":
            // role only
            if (payload == null) {
                exchange.setResponseCode(401);
                exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                exchange.getResponseSender().send((ByteBuffer.wrap("Login is required".getBytes("utf-8"))));
                return;
            } else {
                Map<String, Object> user = (Map<String, Object>) payload.get("user");
                List userRoles = (List) user.get("roles");
                List<String> accessRoles = (List) access.get("roles");
                boolean found = false;
                for (String role : accessRoles) {
                    if (userRoles.contains(role)) {
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    exchange.setResponseCode(403);
                    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                    exchange.getResponseSender()
                            .send((ByteBuffer.wrap("Role permission denied".getBytes("utf-8"))));
                    return;
                }
            }
            break;
        case "U":
            //user only
            if (payload == null) {
                exchange.setResponseCode(401);
                exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                exchange.getResponseSender().send((ByteBuffer.wrap("Login is required".getBytes("utf-8"))));
                return;
            } else {
                Map<String, Object> user = (Map<String, Object>) payload.get("user");
                String userId = (String) user.get("userId");
                List<String> users = (List) access.get("users");
                if (!users.contains(userId)) {
                    exchange.setResponseCode(403);
                    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                    exchange.getResponseSender()
                            .send((ByteBuffer.wrap("User permission denied".getBytes("utf-8"))));
                    return;
                }
            }
            break;
        case "CR":
            // client and role
            if (payload == null) {
                exchange.setResponseCode(401);
                exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                exchange.getResponseSender().send((ByteBuffer.wrap("Login is required".getBytes("utf-8"))));
                return;
            } else {
                Map<String, Object> user = (Map<String, Object>) payload.get("user");
                String clientId = (String) user.get("clientId");
                List<String> clients = (List) access.get("clients");
                if (!clients.contains(clientId)) {
                    exchange.setResponseCode(403);
                    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                    exchange.getResponseSender()
                            .send((ByteBuffer.wrap("Client permission denied".getBytes("utf-8"))));
                    return;
                }
                // client is ok, check roles
                List userRoles = (List) user.get("roles");
                List<String> accessRoles = (List) access.get("roles");
                boolean found = false;
                for (String role : accessRoles) {
                    if (userRoles.contains(role)) {
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    exchange.setResponseCode(403);
                    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                    exchange.getResponseSender()
                            .send((ByteBuffer.wrap("Role permission denied".getBytes("utf-8"))));
                    return;
                }
            }
            break;
        case "CU":
            // client and user
            if (payload == null) {
                exchange.setResponseCode(401);
                exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                exchange.getResponseSender().send((ByteBuffer.wrap("Login is required".getBytes("utf-8"))));
                return;
            } else {
                Map<String, Object> user = (Map<String, Object>) payload.get("user");
                String clientId = (String) user.get("clientId");
                List<String> clients = (List) access.get("clients");
                if (!clients.contains(clientId)) {
                    exchange.setResponseCode(403);
                    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                    exchange.getResponseSender()
                            .send((ByteBuffer.wrap("Client permission denied".getBytes("utf-8"))));
                    return;
                }
                // client is ok, check user
                String userId = (String) user.get("userId");
                List<String> users = (List) access.get("users");
                if (!users.contains(userId)) {
                    exchange.setResponseCode(403);
                    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                    exchange.getResponseSender()
                            .send((ByteBuffer.wrap("User permission denied".getBytes("utf-8"))));
                    return;
                }
            }
            break;
        case "RU":
            // role and user
            if (payload == null) {
                exchange.setResponseCode(401);
                exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                exchange.getResponseSender().send((ByteBuffer.wrap("Login is required".getBytes("utf-8"))));
                return;
            } else {
                Map<String, Object> user = (Map<String, Object>) payload.get("user");
                List userRoles = (List) user.get("roles");
                List<String> accessRoles = (List) access.get("roles");
                boolean found = false;
                for (String role : accessRoles) {
                    if (userRoles.contains(role)) {
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    exchange.setResponseCode(403);
                    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                    exchange.getResponseSender()
                            .send((ByteBuffer.wrap("Role permission denied".getBytes("utf-8"))));
                    return;
                }
                // role is OK, now check userId
                String userId = (String) user.get("userId");
                List<String> users = (List) access.get("users");
                if (!users.contains(userId)) {
                    exchange.setResponseCode(403);
                    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                    exchange.getResponseSender()
                            .send((ByteBuffer.wrap("User permission denied".getBytes("utf-8"))));
                    return;
                }
            }
            break;
        case "CRU":
            // client, role and user
            if (payload == null) {
                exchange.setResponseCode(401);
                exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                exchange.getResponseSender().send((ByteBuffer.wrap("Login is required".getBytes("utf-8"))));
                return;
            } else {
                Map<String, Object> user = (Map<String, Object>) payload.get("user");
                String clientId = (String) user.get("clientId");
                List<String> clients = (List) access.get("clients");
                if (!clients.contains(clientId)) {
                    exchange.setResponseCode(403);
                    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                    exchange.getResponseSender()
                            .send((ByteBuffer.wrap("Client permission denied".getBytes("utf-8"))));
                    return;
                }
                // client is ok, check roles
                List userRoles = (List) user.get("roles");
                List<String> accessRoles = (List) access.get("roles");
                boolean found = false;
                for (String role : accessRoles) {
                    if (userRoles.contains(role)) {
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    exchange.setResponseCode(403);
                    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                    exchange.getResponseSender()
                            .send((ByteBuffer.wrap("Role permission denied".getBytes("utf-8"))));
                    return;
                }
                // role is OK, now check userId
                String userId = (String) user.get("userId");
                List<String> users = (List) access.get("users");
                if (!users.contains(userId)) {
                    exchange.setResponseCode(403);
                    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                    exchange.getResponseSender()
                            .send((ByteBuffer.wrap("User permission denied".getBytes("utf-8"))));
                    return;
                }
            }
            break;
        default:
            logger.error("Invalid Access Level: " + accessLevel);
        }
    }

    if (payload != null) {
        // put payload as part of the map
        jsonMap.put("payload", payload);
    }

    // TODO should I remove the port number here?
    // inject host into the data in command if there is no host in the json map.
    // that means the rules to be accessed are common and host should be part of the data.
    // if there is host in the command, then the corresponding rule should be host specific
    // and table(s) to be accessed should be host specific as well.
    if (jsonMap.get("host") == null) {
        String host = headerMap.getFirst("host");
        if (host.indexOf(':') != -1) {
            host = host.substring(0, host.indexOf(":"));
        }
        Map<String, Object> data = (Map<String, Object>) jsonMap.get("data");
        if (data == null) {
            data = new HashMap<String, Object>();
            jsonMap.put("data", data);
            data.put("host", host);
        } else {
            // do not replace host as it might be owner doing something for one host from another.
            if (data.get("host") == null) {
                data.put("host", host);
            }
        }
    }

    // inject ip address into the command here and saved as part of event in order to  identify
    // users that are not logged in.
    jsonMap.put("ipAddress", getIpAddress(exchange));

    // TODO Apply request transform rules. For example routing here for A/B testing.

    GetTransformRequestRule transformRule = new GetTransformRequestRule();
    List<Map<String, Object>> transforms = transformRule.getTransformRequest(cmdRuleClass);
    for (Map<String, Object> transform : transforms) {
        jsonMap.put("transformData", transform.get("transformData"));
        RuleEngine.getInstance().executeRule((String) transform.get("transformRule"), jsonMap);
    }

    // two types of rules (Command Rule and Event Rule)
    // Command Rule is responsible for validation and return result to client and enrich the command to event that
    // can be replayed at anytime without side effect.Once this is done, return to client. Also, it there are any
    // calls to the outside system, they should be performed here in order to avoid side effects.
    //
    // Event rule is responsible to update domain model based on the event enriched by Command Rule.

    if (readOnly) {
        // get data from memory and return it, it call a command rule to get the data and result will be in the jsonMap as "result" key
        // call the right rule to execute the command, return error code and message if validation fails.
        RuleEngine.getInstance().executeRule(Util.getCommandRuleId(jsonMap), jsonMap);
    } else {
        // this is a update command or impacting to external system.
        // TODO validate version number in itself and dependencies to make sure the event is valid. Reject it back if not.
        // TODO This is the command that need to be executed, and it should be done only once to eliminate side effect.
        // Once this is done, the jsonMap is enriched so that the event is created and can be replayed.
        // It is very possible that something needs to be returned, put it in "result" key in jsonMap.
        boolean valid = RuleEngine.getInstance().executeRule(Util.getCommandRuleId(jsonMap), jsonMap);
        if (valid) {
            // persist event into event store.
            Map<String, Object> eventMap = (Map<String, Object>) jsonMap.get("eventMap");
            DbService.persistEvent(eventMap);

            // Publish the event to subscribers here to update snapshot and cache and etags.

            // This is the async call to update domain model after the fact. Nothing should be returned from here.
            // Basically, this is to apply event generated by the Command Rule
            RuleEngine.getInstance().executeRuleAsync(Util.getEventRuleId(eventMap), eventMap);
        }
    }
    // orientdb most likely return ODocument and ODocument collection, convert to json string by rules
    String result = null;
    Integer responseCode = (Integer) jsonMap.get("responseCode");
    if (responseCode != null) {
        // there is an error
        exchange.setResponseCode(responseCode);
        result = (String) jsonMap.get("error");
        logger.debug("response error: {}", result);
        // TODO should I log the response error here or in the response interceptor?
        // do I have all the info here?

    } else {
        //  no error
        result = (String) jsonMap.get("result");

        // TODO apply response transform rule. Not supported currently yet.

        logger.debug("response success: {} ", result);
    }
    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
    if (result != null) {
        exchange.getResponseSender().send(ByteBuffer.wrap(result.getBytes("utf-8")));
    }
}

From source file:org.createnet.raptor.cli.command.IndexCommand.java

private List<Indexer.IndexRecord> getData(int offset, int limit) {
    try {/*from  w ww. ja v a2  s .  c  o m*/

        BaseQuery query = new BaseQuery();
        query.offset = offset;
        query.limit = limit;

        logger.debug("Loading {} data records from offset {}", limit, offset);

        List<JsonNode> objList = storage.getDataConnection().list(query);
        List<Indexer.IndexRecord> list = new ArrayList();

        for (JsonNode rawobj : objList) {

            Indexer.IndexRecord indexRecord = indexer.getIndexRecord(IndexerService.IndexNames.data);

            try {

                String timestamp = "" + System.currentTimeMillis();
                if (rawobj.has("timestamp")) {
                    timestamp = rawobj.get("timestamp").asText();
                } else if (rawobj.has("lastUpdate")) {
                    timestamp = rawobj.get("lastUpdate").asText();
                }

                indexRecord.id = rawobj.get("objectId").asText() + "-" + rawobj.get("streamId").asText() + "-"
                        + timestamp;
            } catch (NullPointerException ex) {
                logger.warn("NPE on record {}", rawobj.toString());
                continue;
            }

            indexRecord.body = rawobj.toString();
            indexRecord.isNew(true);

            list.add(indexRecord);
        }

        return list;
    } catch (ConfigurationException | Storage.StorageException ex) {
        logger.debug("Exception while loading data records", ex);
        throw new ObjectIndexerException(ex);
    }
}

From source file:org.openmhealth.reference.domain.Schema.java

/**
 * Creates a new schema (registry entry).
 * /*  w w  w.  j  a v a 2  s.co  m*/
 * @param id
 *        The ID for this schema.
 * 
 * @param version
 *        The version of this schema.
 * 
 * @param schema
 *        The specific schema.
 *        
 * @param controller
 *        The controller used to validate this schema and to validate any
 *        data when using the
 *        {@link #validateData(String, MetaData, JsonNode)} method.
 * 
 * @throws OmhException
 *         A parameter was invalid.
 *
 * @see #validateData(String, MetaData, JsonNode)
 */
@JsonCreator
public Schema(@JsonProperty(JSON_KEY_ID) final String id, @JsonProperty(JSON_KEY_VERSION) final long version,
        @JsonProperty(JSON_KEY_SCHEMA) final JsonNode schema,
        @JacksonInject(JSON_KEY_VALIDATION_CONTROLLER) final ValidationController controller)
        throws OmhException {

    // Validate the ID.
    if (id == null) {
        throw new OmhException("The ID is null.");
    } else if (id.trim().length() == 0) {
        throw new OmhException("The ID is empty.");
    } else {
        this.id = validateId(id);
    }

    // Validate the version.
    this.version = validateVersion(version);

    // Make sure the schema is not null.
    if (schema == null) {
        throw new OmhException("The schema is null.");
    }
    try {
        this.schema = new Concordia(new ByteArrayInputStream(schema.toString().getBytes()), controller);
    } catch (IllegalArgumentException e) {
        throw new OmhException("The schema is missing.", e);
    } catch (ConcordiaException e) {
        throw new OmhException("The schema is invalid.", e);
    } catch (IOException e) {
        throw new OmhException("The schema cannot be read.", e);
    }
}

From source file:com.infinities.keystone4j.admin.v3.group.GroupResourceTest.java

@Test
public void testCreateGroup() throws JsonProcessingException, IOException {
    Group group = new Group();
    group.setName("test");
    group.setDescription("description");
    group.setDomainId("default");
    GroupWrapper wrapper = new GroupWrapper(group);
    String json = JsonUtils.toJson(wrapper, Views.Advance.class);
    JsonNode node = JsonUtils.convertToJsonNode(json);
    JsonNode groupJ = node.get("group");
    assertEquals(group.getName(), groupJ.get("name").asText());
    assertEquals(group.getDescription(), groupJ.get("description").asText());
    assertEquals(group.getDomain().getId(), groupJ.get("domain_id").asText());
    Response response = target("/v3/groups").register(JacksonFeature.class).register(ObjectMapperResolver.class)
            .request()/*ww w .  j a  va 2s. co m*/
            .header("X-Auth-Token", Config.Instance.getOpt(Config.Type.DEFAULT, "admin_token").asText())
            .post(Entity.entity(wrapper, MediaType.APPLICATION_JSON_TYPE));
    assertEquals(201, response.getStatus());
    node = JsonUtils.convertToJsonNode(response.readEntity(String.class));
    System.err.println(node.toString());
    groupJ = node.get("group");
    assertNotNull(groupJ.get("id").asText());
    assertEquals(group.getName(), groupJ.get("name").asText());
    assertEquals(group.getDescription(), groupJ.get("description").asText());
    assertEquals(group.getDomain().getId(), groupJ.get("domain_id").asText());
    assertNotNull(groupJ.get("links"));
    assertNotNull(groupJ.get("links").get("self").asText());
}

From source file:org.jboss.aerogear.sync.server.gcm.GcmDiffSyncHandler.java

protected void messageReceived(JsonNode json) throws Exception {

    JsonNode syncMessage = JsonMapper.asJsonNode(json.get("data").get("message").asText());
    logger.info("Doc:" + json);
    final String googleRegistrationId = json.get("from").asText();
    final String diffsyncClientId = clientIdFromJson(syncMessage);
    switch (MessageType.from(syncMessage.get("msgType").asText())) {
    case ADD:// www .ja va2s  . c om
        final Document<T> doc = syncEngine.documentFromJson(syncMessage);
        final PatchMessage<S> patchMessage = addSubscriber(doc, diffsyncClientId, googleRegistrationId);
        send(GcmMessages.createJsonMessage(googleRegistrationId, "m-" + UUID.randomUUID(),
                patchMessage.asJson()));
        break;
    case PATCH:
        final PatchMessage<S> clientPatchMessage = syncEngine.patchMessageFromJson(syncMessage.toString());
        logger.info("Client Edits=" + clientPatchMessage);
        checkForReconnect(clientPatchMessage.documentId(), googleRegistrationId, diffsyncClientId);
        patch(clientPatchMessage);
        break;
    case DETACH:
        // detach the client from a specific document.
        break;
    case UNKNOWN:
        //unknownMessageType(ctx, json);
        break;
    }
}

From source file:com.blackberry.bdp.common.versioned.ZkVersioned.java

public synchronized void save(String role) throws Exception {
    JsonNode roleBasedJsonNode = toJsonNode(role);
    LOG.info("Role based json node : {}", roleBasedJsonNode);
    String jsonToWriteToZk;//from  w ww .  ja va2 s .c o m
    try {
        JsonNode existingJsonNode = get(this.getClass(), this.curator, this.zkPath).toJsonNode();
        LOG.info("existing json node from zk : {}", existingJsonNode);
        jsonToWriteToZk = merge(existingJsonNode, roleBasedJsonNode).toString();
        LOG.info("saving existing object with role {} yields JSON {}", role, jsonToWriteToZk);
    } catch (MissingConfigurationException mce) {
        jsonToWriteToZk = roleBasedJsonNode.toString();
        LOG.info("saving with role {} yields JSON {}", role, jsonToWriteToZk);
    }
    writeJsonToZooKeeper(jsonToWriteToZk);
}

From source file:com.hollowsoft.library.utility.request.HttpRequest.java

/**
 *
 * @param url//from   ww w. jav a 2  s.c om
 * @param jsonNode
 * @param headerArray
 * @return
 * @throws RequestException
 */
public JsonNode doPut(final String url, final JsonNode jsonNode, final Header... headerArray)
        throws RequestException {

    if (url == null || url.isEmpty()) {
        throw new IllegalArgumentException("The url cannot be null or empty.");
    }

    if (jsonNode == null || jsonNode.isNull()) {
        throw new IllegalArgumentException("The jsonNode cannot be null or empty.");
    }

    try {

        final HttpPut httpPut = new HttpPut(url);

        httpPut.setHeaders(headerArray);
        httpPut.setEntity(new StringEntity(jsonNode.toString(), Constants.DEFAULT_CHARSET.name()));

        final HttpEntity httpEntity = httpClient.execute(httpPut).getEntity();

        return new ObjectMapper().reader().readTree(httpEntity.getContent());

    } catch (final ClientProtocolException e) {
        throw new RequestException(e);

    } catch (final JsonProcessingException e) {
        throw new RequestException(e);

    } catch (final IllegalStateException e) {
        throw new RequestException(e);

    } catch (final IOException e) {
        throw new RequestException(e);
    }
}

From source file:com.hollowsoft.library.utility.request.HttpRequest.java

/**
 *
 * @param url/*  w  w w  .  ja va2s. c o  m*/
 * @param jsonNode
 * @param headerArray
 * @return
 * @throws RequestException
 */
public JsonNode doPost(final String url, final JsonNode jsonNode, final Header... headerArray)
        throws RequestException {

    if (url == null || url.isEmpty()) {
        throw new IllegalArgumentException("The url cannot be null or empty.");
    }

    if (jsonNode == null || jsonNode.isNull()) {
        throw new IllegalArgumentException("The jsonNode cannot be null or empty.");
    }

    try {

        final HttpPost httpPost = new HttpPost(url);

        httpPost.setHeaders(headerArray);
        httpPost.setEntity(new StringEntity(jsonNode.toString(), Constants.DEFAULT_CHARSET.name()));

        final HttpEntity httpEntity = httpClient.execute(httpPost).getEntity();

        return new ObjectMapper().reader().readTree(httpEntity.getContent());

    } catch (final ClientProtocolException e) {
        throw new RequestException(e);

    } catch (final JsonProcessingException e) {
        throw new RequestException(e);

    } catch (final IllegalStateException e) {
        throw new RequestException(e);

    } catch (final IOException e) {
        throw new RequestException(e);
    }
}