Example usage for com.fasterxml.jackson.databind ObjectMapper convertValue

List of usage examples for com.fasterxml.jackson.databind ObjectMapper convertValue

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper convertValue.

Prototype

@SuppressWarnings("unchecked")
    public <T> T convertValue(Object fromValue, JavaType toValueType) throws IllegalArgumentException 

Source Link

Usage

From source file:it.sayservice.platform.smartplanner.otp.OTPHandler.java

public List<StopTime> getTimes(String router, String agencyId, String routeId, String stopId, long from,
        long to) throws Exception {
    List<StopTime> result = new ArrayList<StopTime>();

    try {//from   w  w w.j a  v a2  s. c  o m
        Long timeInterval = Math.abs(to - from) / 1000; // otp expect
        // seconds since
        // midnight.

        String stopIdOTP = agencyId + ":" + stopId;
        String res = HTTPConnector.doGet(otpURL + Constants.OP_STOPS + "/" + stopIdOTP + Constants.OP_STOPTIMES,
                "startTime=" + from / 1000 + "&timeRange=" + timeInterval + "&numberOfDepartures=100", null,
                MediaType.APPLICATION_JSON);

        com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();

        JsonNode root = mapper.readTree(res);

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

        ArrayNode rootList = mapper.convertValue(root, ArrayNode.class);

        for (JsonNode pattern : rootList) {
            ArrayNode times = mapper.convertValue(pattern.get("times"), ArrayNode.class);
            for (JsonNode timeNode : times) {
                String[] ids = timeNode.get("tripId").asText().split(":");
                //               long time = SmartPlannerUtils.addSecondsToTimeStamp(from, timeNode.get("scheduledDeparture").asInt());
                long time = SmartPlannerUtils.computeDate(timeNode.get("scheduledDeparture").asInt(),
                        timeNode.get("serviceDay").asLong() * 1000);
                Id id = new Id();
                id.setAgency(agencyId);
                id.setId(ids[1]);
                String u = time + "_" + id.getId() + id.getAgency();
                if (used.contains(u)) {
                    continue;
                }

                String tripId = id.getId();
                String tripRouteId = routerTripsMap.get(router).get(agencyId + "_" + tripId);

                StopTime stopTime = new StopTime();
                stopTime.setTime(time);
                stopTime.setTrip(id);

                if (routeId == null || tripRouteId != null && tripRouteId.equals(routeId)) {
                    result.add(stopTime);
                    used.add(u);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    Collections.sort(result);
    return result;
}

From source file:it.sayservice.platform.smartplanner.otp.OTPHandler.java

public List<Route> getRoutes(String router) {
    List<Route> result = new ArrayList<Route>();

    try {/*w w w . j  a  v a 2 s .  c  om*/
        String res = HTTPConnector.doGet(otpURL + Constants.OP_ROUTES, "", null, MediaType.APPLICATION_JSON);

        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        ArrayList list = mapper.readValue(res, ArrayList.class);

        for (Object o : list) {
            Map<String, Object> tmpMap = mapper.convertValue(o, Map.class);
            // Route route = mapper.convertValue(tmpMap.get("RouteType"),
            // Route.class);
            // new version.
            String[] ids = tmpMap.get("id").toString().split(":");
            String agencyId = ids[0];
            String routeId = ids[1];

            Route route = new Route();
            Id id = new Id();
            id.setAgency(agencyId);
            id.setId(routeId);
            route.setId(id);
            if (tmpMap.containsKey("longName"))
                route.setRouteLongName(tmpMap.get("longName").toString());
            if (tmpMap.containsKey("shortName"))
                route.setRouteShortName(tmpMap.get("shortName").toString());

            result.add(route);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return result;
}

From source file:com.derpgroup.quip.bots.insultibot.resource.InsultiBotAlexaResource.java

/**
 * Generates a welcome message.//w ww .  j a v  a 2 s.  co  m
 *
 * @return The message, never null
 */
@POST
public SpeechletResponseEnvelope doAlexaRequest(SpeechletRequestEnvelope request,
        @HeaderParam("SignatureCertChainUrl") String signatureCertChainUrl,
        @HeaderParam("Signature") String signature, @QueryParam("testFlag") Boolean testFlag) {

    ObjectMapper mapper = new ObjectMapper().registerModule(new MixInModule());
    CommonMetadata outputMetadata = null;
    try {
        if (request.getRequest() == null) {
            throw new DerpwizardException(DerpwizardExceptionReasons.MISSING_INFO.getSsml(),
                    "Missing request body.");
        }
        if (testFlag == null || testFlag == false) {
            AlexaUtils.validateAlexaRequest(request, signatureCertChainUrl, signature);
        }

        Map<String, Object> sessionAttributes = request.getSession().getAttributes();
        sessionAttributes.put("bot", "insultibot");
        User user = request.getSession().getUser();
        if (user == null) {
            throw new DerpwizardException(DerpwizardExceptionReasons.MISSING_INFO.getSsml(),
                    "No user included as part of request body.");
        }
        sessionAttributes.put("userId", user.getUserId());

        // Build the Metadata objects here
        CommonMetadata inputMetadata = mapper.convertValue(sessionAttributes,
                new TypeReference<QuipMetadata>() {
                });
        outputMetadata = mapper.convertValue(sessionAttributes, new TypeReference<QuipMetadata>() {
        });

        ///////////////////////////////////
        // Build the ServiceInput object //
        ///////////////////////////////////
        ServiceInput serviceInput = new ServiceInput();
        serviceInput.setMetadata(inputMetadata);
        Map<String, String> messageAsMap = AlexaUtils.getMessageAsMap(request.getRequest());
        serviceInput.setMessageAsMap(messageAsMap);

        SpeechletRequest speechletRequest = (SpeechletRequest) request.getRequest();
        String intent = QuipUtil.getMessageSubject(speechletRequest);
        serviceInput.setSubject(intent);

        ////////////////////////////////////
        // Build the ServiceOutput object //
        ////////////////////////////////////
        ServiceOutput serviceOutput = new ServiceOutput();
        serviceOutput.setMetadata(outputMetadata);
        serviceOutput.setConversationEnded(false);
        ConversationHistoryUtils.registerRequestInConversationHistory(intent, messageAsMap, outputMetadata,
                outputMetadata.getConversationHistory());

        // Perform the service request
        QuipLogger.log(serviceInput);
        manager.handleRequest(serviceInput, serviceOutput);

        // Build the response
        SpeechletResponseEnvelope responseEnvelope = new SpeechletResponseEnvelope();
        Map<String, Object> sessionAttributesOutput = mapper.convertValue(outputMetadata,
                new TypeReference<Map<String, Object>>() {
                });
        responseEnvelope.setSessionAttributes(sessionAttributesOutput);

        SpeechletResponse speechletResponse = new SpeechletResponse();
        SimpleCard card;
        Reprompt reprompt = null;
        SsmlOutputSpeech outputSpeech;

        switch (serviceInput.getSubject()) {
        case "END_OF_CONVERSATION":
        case "STOP":
        case "CANCEL":
            outputSpeech = null;
            card = null;
            speechletResponse.setShouldEndSession(true);
            break;
        default:
            if (StringUtils.isNotEmpty(serviceOutput.getVisualOutput().getTitle())
                    && StringUtils.isNotEmpty(serviceOutput.getVisualOutput().getText())) {
                card = new SimpleCard();
                card.setTitle(serviceOutput.getVisualOutput().getTitle());
                card.setContent(serviceOutput.getVisualOutput().getText());
            } else {
                card = null;
            }
            if (serviceOutput.getDelayedVoiceOutput() != null
                    && StringUtils.isNotEmpty(serviceOutput.getDelayedVoiceOutput().getSsmltext())) {
                reprompt = new Reprompt();
                SsmlOutputSpeech repromptSpeech = new SsmlOutputSpeech();
                repromptSpeech
                        .setSsml("<speak>" + serviceOutput.getDelayedVoiceOutput().getSsmltext() + "</speak>");
                reprompt.setOutputSpeech(repromptSpeech);
            }

            outputSpeech = new SsmlOutputSpeech();
            outputSpeech.setSsml("<speak>" + serviceOutput.getVoiceOutput().getSsmltext() + "</speak>");
            speechletResponse.setShouldEndSession(serviceOutput.isConversationEnded());
            break;
        }

        speechletResponse.setOutputSpeech(outputSpeech);
        speechletResponse.setCard(card);
        speechletResponse.setReprompt(reprompt);
        responseEnvelope.setResponse(speechletResponse);
        responseEnvelope.setVersion(ALEXA_VERSION);

        return responseEnvelope;
    } catch (DerpwizardException e) {
        LOG.debug(e.getMessage());
        return new DerpwizardExceptionAlexaWrapper(e, ALEXA_VERSION,
                mapper.convertValue(outputMetadata, new TypeReference<Map<String, Object>>() {
                }));
    } catch (Throwable t) {
        LOG.debug(t.getMessage());
        return new DerpwizardExceptionAlexaWrapper(new DerpwizardException(t.getMessage()), ALEXA_VERSION,
                mapper.convertValue(outputMetadata, new TypeReference<Map<String, Object>>() {
                }));
    }
}

From source file:com.derpgroup.quip.bots.complibot.resource.CompliBotAlexaResource.java

/**
 * Generates a welcome message.//  w  w w.  ja v a 2  s .c  o  m
 *
 * @return The message, never null
 */
@POST
public SpeechletResponseEnvelope doAlexaRequest(
        @NotNull @Valid SpeechletRequestEnvelope<? extends CoreSpeechletRequest> request,
        @HeaderParam("SignatureCertChainUrl") String signatureCertChainUrl,
        @HeaderParam("Signature") String signature, @QueryParam("testFlag") Boolean testFlag) {

    ObjectMapper mapper = new ObjectMapper().registerModule(new MixInModule());
    QuipMetadata outputMetadata = null;
    try {
        if (request.getRequest() == null) {
            throw new DerpwizardException(DerpwizardExceptionReasons.MISSING_INFO.getSsml(),
                    "Missing request body."); //TODO: create AlexaException
        }
        if (testFlag == null || testFlag == false) {
            AlexaUtils.validateAlexaRequest(request, signatureCertChainUrl, signature);
        }

        Map<String, Object> sessionAttributes = request.getSession().getAttributes();
        sessionAttributes.put("bot", "complibot");
        User user = request.getSession().getUser();
        if (user == null) {
            throw new DerpwizardException(DerpwizardExceptionReasons.MISSING_INFO.getSsml(),
                    "No user included as part of request body.");
        }
        sessionAttributes.put("userId", user.getUserId());

        // Build the Metadata objects here
        CommonMetadata inputMetadata = mapper.convertValue(sessionAttributes,
                new TypeReference<QuipMetadata>() {
                });
        outputMetadata = mapper.convertValue(sessionAttributes, new TypeReference<QuipMetadata>() {
        });

        ///////////////////////////////////
        // Build the ServiceInput object //
        ///////////////////////////////////
        ServiceInput serviceInput = new ServiceInput();
        serviceInput.setMetadata(inputMetadata);
        Map<String, String> messageAsMap = AlexaUtils.getMessageAsMap(request.getRequest());
        serviceInput.setMessageAsMap(messageAsMap);

        SpeechletRequest speechletRequest = (SpeechletRequest) request.getRequest();
        String intent = QuipUtil.getMessageSubject(speechletRequest);
        serviceInput.setSubject(intent);

        ////////////////////////////////////
        // Build the ServiceOutput object //
        ////////////////////////////////////
        ServiceOutput serviceOutput = new ServiceOutput();
        serviceOutput.setMetadata(outputMetadata);
        serviceOutput.setConversationEnded(false);
        ConversationHistoryUtils.registerRequestInConversationHistory(intent, messageAsMap, outputMetadata,
                outputMetadata.getConversationHistory());

        // Perform the service request
        QuipLogger.log(serviceInput);
        manager.handleRequest(serviceInput, serviceOutput);

        // Build the response
        SpeechletResponseEnvelope responseEnvelope = new SpeechletResponseEnvelope();
        Map<String, Object> sessionAttributesOutput = mapper.convertValue(outputMetadata,
                new TypeReference<Map<String, Object>>() {
                });
        responseEnvelope.setSessionAttributes(sessionAttributesOutput);

        SpeechletResponse speechletResponse = new SpeechletResponse();
        SimpleCard card;
        SsmlOutputSpeech outputSpeech;
        Reprompt reprompt = null;

        switch (serviceInput.getSubject()) {
        case "END_OF_CONVERSATION":
        case "STOP":
        case "CANCEL":
            outputSpeech = null;
            card = null;
            speechletResponse.setShouldEndSession(true);
            break;
        default:
            if (StringUtils.isNotEmpty(serviceOutput.getVisualOutput().getTitle())
                    && StringUtils.isNotEmpty(serviceOutput.getVisualOutput().getText())) {
                card = new SimpleCard();
                card.setTitle(serviceOutput.getVisualOutput().getTitle());
                card.setContent(serviceOutput.getVisualOutput().getText());
            } else {
                card = null;
            }
            if (serviceOutput.getDelayedVoiceOutput() != null
                    && StringUtils.isNotEmpty(serviceOutput.getDelayedVoiceOutput().getSsmltext())) {
                reprompt = new Reprompt();
                SsmlOutputSpeech repromptSpeech = new SsmlOutputSpeech();
                repromptSpeech
                        .setSsml("<speak>" + serviceOutput.getDelayedVoiceOutput().getSsmltext() + "</speak>");
                reprompt.setOutputSpeech(repromptSpeech);
            }

            outputSpeech = new SsmlOutputSpeech();
            outputSpeech.setSsml("<speak>" + serviceOutput.getVoiceOutput().getSsmltext() + "</speak>");
            speechletResponse.setShouldEndSession(serviceOutput.isConversationEnded());
            break;
        }

        speechletResponse.setOutputSpeech(outputSpeech);
        speechletResponse.setCard(card);
        speechletResponse.setReprompt(reprompt);
        responseEnvelope.setResponse(speechletResponse);
        responseEnvelope.setVersion(ALEXA_VERSION);

        return responseEnvelope;
    } catch (DerpwizardException e) {
        LOG.debug(e.getMessage());
        return new DerpwizardExceptionAlexaWrapper(e, ALEXA_VERSION,
                mapper.convertValue(outputMetadata, new TypeReference<Map<String, Object>>() {
                }));
    } catch (Throwable t) {
        LOG.debug(t.getMessage());
        return new DerpwizardExceptionAlexaWrapper(new DerpwizardException(t.getMessage()), ALEXA_VERSION,
                mapper.convertValue(outputMetadata, new TypeReference<Map<String, Object>>() {
                }));
    }
}

From source file:io.fabric8.core.jmx.FabricManager.java

@Override
public void changeCreateOptionsField(String containerId, String field, Object value) {
    CreateContainerMetadata<? extends CreateContainerOptions> metadata = getContainerMetaData(containerId);
    if (metadata == null) {
        return;/* www.ja va 2 s .  c  o  m*/
    }
    CreateContainerOptions options = metadata.getCreateOptions();
    if (options == null) {
        return;
    }

    ObjectMapper mapper = getObjectMapper();
    JsonNode optionsJson = mapper.convertValue(options, JsonNode.class);
    JsonNode valueJson = mapper.convertValue(value, JsonNode.class);
    ((ObjectNode) optionsJson).put(field, valueJson);

    Object builder = null;

    try {
        builder = options.getClass().getMethod("builder").invoke(null);
    } catch (Exception e) {
        LOG.warn("Failed to get builder when setting " + field + " on container " + containerId, e);
        throw new RuntimeException(
                "Failed to get builder when setting " + field + " on container " + containerId, e);
    }

    builder = mapper.convertValue(optionsJson, builder.getClass());

    CreateContainerOptions newOptions = null;
    try {
        newOptions = (CreateContainerOptions) builder.getClass().getMethod("build").invoke(builder);
    } catch (Exception e) {
        LOG.warn(
                "Failed to build CreatecontainerOptions when setting " + field + " on container " + containerId,
                e);
        throw new RuntimeException(
                "Failed to build CreatecontainerOptions when setting " + field + " on container " + containerId,
                e);
    }
    metadata.setCreateOptions(newOptions);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Create container metadata: " + metadata);
    }
    getFabricService().getDataStore().setContainerMetadata(metadata);
}

From source file:io.fabric8.core.jmx.FabricManager.java

@Override
public Map<String, String> createContainers(Map<String, Object> options) {

    if (LOG.isDebugEnabled()) {
        LOG.debug("Creating containers from JSON data: " + options);
    }//from w w w  . j  a va  2  s.  co  m

    String providerType = (String) options.get("providerType");

    if (providerType == null) {
        throw new RuntimeException("No providerType provided");
    }

    CreateContainerBasicOptions.Builder builder = null;

    Class clazz = fabricService.getProviders().get(providerType).getOptionsType();
    try {
        builder = (CreateContainerBasicOptions.Builder) clazz.getMethod("builder").invoke(null);
    } catch (Exception e) {
        LOG.warn("Failed to find builder type", e);
    }

    if (builder == null) {
        throw new RuntimeException("Unknown provider type : " + providerType);
    }

    ObjectMapper mapper = getObjectMapper();

    builder = mapper.convertValue(options, builder.getClass());

    builder.zookeeperPassword(getFabricService().getZookeeperPassword());
    builder.zookeeperUrl(getFabricService().getZookeeperUrl());

    Object profileObject = options.get("profiles");

    if (profileObject != null) {
        List profiles = mapper.convertValue(profileObject, List.class);
        builder.profiles(profiles);
    }

    CreateContainerOptions build = builder.build();

    if (LOG.isDebugEnabled()) {
        LOG.debug("Created container options: " + build + " with profiles " + build.getProfiles());
    }

    CreateContainerMetadata<?> metadatas[] = getFabricService().createContainers(build);

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

    for (CreateContainerMetadata<?> metadata : metadatas) {
        if (!metadata.isSuccess()) {
            LOG.warn("Failed to create container {}: ", metadata.getContainerName(), metadata.getFailure());
            rc.put(metadata.getContainerName(), metadata.getFailure().getMessage());
        }
    }

    return rc;
}

From source file:com.ikanow.aleph2.v1.document_db.utils.TestJsonNodeBsonUtils.java

@Test
public void test_mapWritableWrapper() {
    final ObjectMapper mapper = BeanTemplateUtils.configureMapper(Optional.empty());

    final BasicDBObject m1 = new BasicDBObject();

    m1.put("test1", true);

    final BasicDBObject m2 = new BasicDBObject();
    m2.put("nested", m1);
    m2.put("test2", "test2");

    final BasicDBList a1 = new BasicDBList();
    a1.add(4);//  ww w .  j av a  2s .c o  m
    a1.add(5);

    final BasicDBList a2 = new BasicDBList();
    a2.add(m1);
    a2.add(m1);

    m2.put("array", a2);
    m1.put("array", a1);

    final JsonNode j2 = JsonNodeBsonUtils.from(m2);

    assertEquals(3, j2.size());

    // Check j's contents
    assertEquals(Stream.of("nested", "test2", "array").sorted().collect(Collectors.toList()),
            Optionals.streamOf(j2.fieldNames(), false).sorted().collect(Collectors.toList()));
    assertEquals("test2", j2.get("test2").asText());

    final JsonNode j1 = j2.get("nested");
    assertEquals(2, j1.size());
    final JsonNode j1b = JsonNodeBsonUtils.from(m1);
    assertTrue("entrySet wrong: " + j1b.toString(), "{\"test1\":true,\"array\":[4,5]}".equals(j1b.toString())
            || "{\"array\":[4,5],\"test1\":true}".equals(j1b.toString())); //(tests entrySet)
    final ArrayNode an = mapper.createArrayNode();
    an.add(mapper.convertValue(4, JsonNode.class));
    an.add(mapper.convertValue(5, JsonNode.class));
    assertEquals(Arrays.asList(mapper.convertValue(true, JsonNode.class), an),
            Optionals.streamOf(((ObjectNode) j1).elements(), false).collect(Collectors.toList()));

    // OK, now test adding:

    assertEquals(2, j1.size());

    final ObjectNode o1 = (ObjectNode) j1;
    o1.put("added", "added_this");

    final ObjectNodeWrapper o1c = (ObjectNodeWrapper) o1;
    assertFalse(o1c.containsKey("not_present"));
    assertTrue(o1c.containsKey("added"));
    assertTrue(o1c.containsKey("test1"));

    assertEquals(Stream.of("test1", "array", "added").sorted().collect(Collectors.toList()),
            Optionals.streamOf(j1.fieldNames(), false).sorted().collect(Collectors.toList()));
    assertEquals(
            Arrays.asList(mapper.convertValue(true, JsonNode.class), an,
                    mapper.convertValue("added_this", JsonNode.class)),
            Optionals.streamOf(((ObjectNode) j1).elements(), false).collect(Collectors.toList()));
    assertTrue(j1.toString().contains("added_this"));
    assertTrue(j1.toString().contains("4,5"));

    assertEquals(mapper.convertValue("added_this", JsonNode.class), j1.get("added"));

    assertEquals(3, j1.size());

    // OK now test removing:

    assertEquals(null, o1.remove("not_present"));
    assertEquals(mapper.convertValue(true, JsonNode.class), o1.remove("test1"));
    assertEquals(2, o1.size());
    ObjectNode o1b = o1.remove(Arrays.asList("added", "array"));
    assertEquals(0, o1.size());
    assertEquals(0, o1b.size());

    o1.setAll(JsonNodeBsonUtils.from(m1)); // will be minus one object
    assertEquals(2, o1.size());
    assertTrue(o1c.containsValue(mapper.convertValue(true, JsonNode.class)));
    assertFalse(o1c.containsValue("banana"));

    final ObjectNodeWrapper o2 = (ObjectNodeWrapper) JsonNodeBsonUtils.from(m2);
    assertFalse(o2.isEmpty());
    assertTrue(o2.containsKey("array"));
    assertFalse(o2.containsValue("array"));
    assertTrue(o2.containsValue(mapper.convertValue("test2", JsonNode.class)));
    assertEquals(TextNode.class, o2.remove("test2").getClass());
    assertEquals(2, o2.size());
    o2.removeAll();
    assertEquals(0, o2.size());
}

From source file:com.ikanow.aleph2.search_service.elasticsearch.utils.TestJsonNodeWritableUtils.java

@SuppressWarnings("deprecation")
@Test/*w  ww  . j  av a  2s  .co  m*/
public void test_mapWritableWrapper() {
    final ObjectMapper mapper = BeanTemplateUtils.configureMapper(Optional.empty());

    final MapWritable m1 = new MapWritable();

    m1.put(new Text("test1"), new BooleanWritable(true));

    final MapWritable m2 = new MapWritable();
    m2.put(new Text("nested"), m1);
    m2.put(new Text("test2"), new Text("test2"));

    final ArrayWritable a1 = new ArrayWritable(IntWritable.class);
    a1.set(new Writable[] { new IntWritable(4), new IntWritable(5) });

    final ArrayWritable a2 = new ArrayWritable(MapWritable.class);
    a2.set(new Writable[] { m1, m1 });

    m2.put(new Text("array"), a2);
    m1.put(new Text("array"), a1);

    final JsonNode j2 = JsonNodeWritableUtils.from(m2);

    assertEquals(3, j2.size());

    // Check j's contents
    assertEquals(Stream.of("nested", "test2", "array").sorted().collect(Collectors.toList()),
            Optionals.streamOf(j2.fieldNames(), false).sorted().collect(Collectors.toList()));
    assertEquals("test2", j2.get("test2").asText());

    final JsonNode j1 = j2.get("nested");
    assertEquals(2, j1.size());
    final JsonNode j1b = JsonNodeWritableUtils.from(m1);
    assertTrue("{\"test1\":true,\"array\":[4,5]}".equals(j1b.toString())
            || "{\"array\":[4,5],\"test1\":true}".equals(j1b.toString())); //(tests entrySet)
    final ArrayNode an = mapper.createArrayNode();
    an.add(mapper.convertValue(4, JsonNode.class));
    an.add(mapper.convertValue(5, JsonNode.class));
    assertEquals(Arrays.asList(mapper.convertValue(true, JsonNode.class), an),
            Optionals.streamOf(((ObjectNode) j1).elements(), false).collect(Collectors.toList()));

    // OK, now test adding:

    assertEquals(2, j1.size());

    final ObjectNode o1 = (ObjectNode) j1;
    o1.put("added", "added_this");

    final ObjectNodeWrapper o1c = (ObjectNodeWrapper) o1;
    assertFalse(o1c.containsKey("not_present"));
    assertTrue(o1c.containsKey("added"));
    assertTrue(o1c.containsKey("test1"));

    assertEquals(Stream.of("test1", "array", "added").sorted().collect(Collectors.toList()),
            Optionals.streamOf(j1.fieldNames(), false).sorted().collect(Collectors.toList()));
    assertEquals(
            Arrays.asList(mapper.convertValue(true, JsonNode.class), an,
                    mapper.convertValue("added_this", JsonNode.class)),
            Optionals.streamOf(((ObjectNode) j1).elements(), false).collect(Collectors.toList()));
    assertTrue(j1.toString().contains("added_this"));
    assertTrue(j1.toString().contains("4,5"));

    assertEquals(mapper.convertValue("added_this", JsonNode.class), j1.get("added"));

    assertEquals(3, j1.size());

    // OK now test removing:

    assertEquals(null, o1.remove("not_present"));
    assertEquals(mapper.convertValue(true, JsonNode.class), o1.remove("test1"));
    assertEquals(2, o1.size());
    ObjectNode o1b = o1.remove(Arrays.asList("added", "array"));
    assertEquals(0, o1.size());
    assertEquals(0, o1b.size());

    o1.putAll(JsonNodeWritableUtils.from(m1)); // will be minus one object
    assertEquals(2, o1.size());
    assertTrue(o1c.containsValue(mapper.convertValue(true, JsonNode.class)));
    assertFalse(o1c.containsValue("banana"));

    final ObjectNodeWrapper o2 = (ObjectNodeWrapper) JsonNodeWritableUtils.from(m2);
    assertFalse(o2.isEmpty());
    assertTrue(o2.containsKey("array"));
    assertFalse(o2.containsValue("array"));
    assertTrue(o2.containsValue(mapper.convertValue("test2", JsonNode.class)));
    assertEquals(TextNode.class, o2.remove("test2").getClass());
    assertEquals(2, o2.size());
    o2.removeAll();
    assertEquals(0, o2.size());
}

From source file:com.yahoo.elide.graphql.GraphQLEndpoint.java

private Response executeGraphQLRequest(ObjectMapper mapper, SecurityContext securityContext,
        String graphQLDocument, JsonNode jsonDocument) {
    boolean isVerbose = false;
    try (DataStoreTransaction tx = elide.getDataStore().beginTransaction()) {
        final User user = tx.accessUser(getUser.apply(securityContext));
        GraphQLRequestScope requestScope = new GraphQLRequestScope(tx, user, elide.getElideSettings());
        isVerbose = requestScope.getPermissionExecutor().isVerbose();

        if (!jsonDocument.has(QUERY)) {
            return Response.status(400).entity("A `query` key is required.").build();
        }/*from   ww w .j a v  a2  s .  com*/

        String query = jsonDocument.get(QUERY).asText();

        // Logging all queries. It is recommended to put any private information that shouldn't be logged into
        // the "variables" section of your query. Variable values are not logged.
        log.info("Processing GraphQL query:\n{}", query);

        ExecutionInput.Builder executionInput = new ExecutionInput.Builder().context(requestScope).query(query);

        if (jsonDocument.has(OPERATION_NAME) && !jsonDocument.get(OPERATION_NAME).isNull()) {
            executionInput.operationName(jsonDocument.get(OPERATION_NAME).asText());
        }

        if (jsonDocument.has(VARIABLES) && !jsonDocument.get(VARIABLES).isNull()) {
            Map<String, Object> variables = mapper.convertValue(jsonDocument.get(VARIABLES), Map.class);
            executionInput.variables(variables);
        }

        ExecutionResult result = api.execute(executionInput);

        tx.preCommit();
        requestScope.runQueuedPreSecurityTriggers();
        requestScope.getPermissionExecutor().executeCommitChecks();
        if (query.trim().startsWith(MUTATION)) {
            if (!result.getErrors().isEmpty()) {
                HashMap<String, Object> abortedResponseObject = new HashMap<String, Object>() {
                    {
                        put("errors", result.getErrors());
                        put("data", null);
                    }
                };
                // Do not commit. Throw OK response to process tx.close correctly.
                throw new WebApplicationException(
                        Response.ok(mapper.writeValueAsString(abortedResponseObject)).build());
            }
            requestScope.saveOrCreateObjects();
        }
        tx.flush(requestScope);

        requestScope.runQueuedPreCommitTriggers();
        elide.getAuditLogger().commit(requestScope);
        tx.commit(requestScope);
        requestScope.runQueuedPostCommitTriggers();

        if (log.isTraceEnabled()) {
            requestScope.getPermissionExecutor().printCheckStats();
        }

        return Response.ok(mapper.writeValueAsString(result.toSpecification())).build();
    } catch (WebApplicationException e) {
        log.debug("WebApplicationException", e);
        return e.getResponse();
    } catch (JsonProcessingException e) {
        log.debug("Invalid json body provided to GraphQL", e);
        return buildErrorResponse(new InvalidEntityBodyException(graphQLDocument), isVerbose);
    } catch (IOException e) {
        log.error("Uncaught IO Exception by Elide in GraphQL", e);
        return buildErrorResponse(new TransactionException(e), isVerbose);
    } catch (HttpStatusException e) {
        log.debug("Caught HTTP status exception {}", e.getStatus(), e);
        return buildErrorResponse(new HttpStatusException(200, "") {
            @Override
            public int getStatus() {
                return 200;
            }

            @Override
            public Pair<Integer, JsonNode> getErrorResponse() {
                return e.getErrorResponse();
            }

            @Override
            public Pair<Integer, JsonNode> getVerboseErrorResponse() {
                return e.getVerboseErrorResponse();
            }

            @Override
            public String getVerboseMessage() {
                return e.getVerboseMessage();
            }

            @Override
            public String toString() {
                return e.toString();
            }
        }, isVerbose);
    } catch (Exception | Error e) {
        log.debug("Unhandled error or exception.", e);
        throw e;
    } finally {
        elide.getAuditLogger().clear();
    }
}

From source file:org.wso2.carbon.bpmn.rest.service.runtime.ProcessInstanceService.java

protected Response createExecutionVariable(Execution execution, boolean override, int variableType,
        HttpServletRequest httpServletRequest) throws IOException, ServletException {

    boolean debugEnabled = log.isDebugEnabled();
    if (debugEnabled) {
        log.debug("httpServletRequest.getContentType():" + httpServletRequest.getContentType());
    }/*from w  ww .jav  a 2 s. co  m*/
    Response.ResponseBuilder responseBuilder = Response.ok();

    if (debugEnabled) {
        log.debug("Processing non binary variable");
    }

    List<RestVariable> inputVariables = new ArrayList<>();
    List<RestVariable> resultVariables = new ArrayList<>();

    try {
        if (Utils.isApplicationJsonRequest(httpServletRequest)) {
            ObjectMapper objectMapper = new ObjectMapper();
            @SuppressWarnings("unchecked")
            List<Object> variableObjects = (List<Object>) objectMapper
                    .readValue(httpServletRequest.getInputStream(), List.class);
            for (Object restObject : variableObjects) {
                RestVariable restVariable = objectMapper.convertValue(restObject, RestVariable.class);
                inputVariables.add(restVariable);
            }
        } else if (Utils.isApplicationXmlRequest(httpServletRequest)) {
            JAXBContext jaxbContext;
            try {
                jaxbContext = JAXBContext.newInstance(RestVariableCollection.class);
                Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
                RestVariableCollection restVariableCollection = (RestVariableCollection) jaxbUnmarshaller
                        .unmarshal(httpServletRequest.getInputStream());
                if (restVariableCollection == null) {
                    throw new ActivitiIllegalArgumentException("xml request body could not be transformed to a "
                            + "RestVariable Collection instance.");
                }
                List<RestVariable> restVariableList = restVariableCollection.getRestVariables();

                if (restVariableList.size() == 0) {
                    throw new ActivitiIllegalArgumentException(
                            "xml request body could not identify any rest " + "variables to be updated");
                }
                for (RestVariable restVariable : restVariableList) {
                    inputVariables.add(restVariable);
                }

            } catch (JAXBException | IOException e) {
                throw new ActivitiIllegalArgumentException(
                        "xml request body could not be transformed to a " + "RestVariable instance.", e);
            }
        }
    } catch (Exception e) {
        throw new ActivitiIllegalArgumentException("Failed to serialize to a RestVariable instance", e);
    }

    if (inputVariables.size() == 0) {
        throw new ActivitiIllegalArgumentException("Request didn't contain a list of variables to create.");
    }

    RestVariable.RestVariableScope sharedScope = null;
    RestVariable.RestVariableScope varScope;
    Map<String, Object> variablesToSet = new HashMap<>();

    for (RestVariable var : inputVariables) {
        // Validate if scopes match
        varScope = var.getVariableScope();
        if (var.getName() == null) {
            throw new ActivitiIllegalArgumentException("Variable name is required");
        }

        if (varScope == null) {
            varScope = RestVariable.RestVariableScope.LOCAL;
        }
        if (sharedScope == null) {
            sharedScope = varScope;
        }
        if (varScope != sharedScope) {
            throw new ActivitiIllegalArgumentException(
                    "Only allowed to update multiple variables in the same scope.");
        }

        if (!override && hasVariableOnScope(execution, var.getName(), varScope)) {
            throw new BPMNConflictException("Variable '" + var.getName() + "' is already present on execution '"
                    + execution.getId() + "'.");
        }

        RestResponseFactory restResponseFactory = new RestResponseFactory();
        Object actualVariableValue = restResponseFactory.getVariableValue(var);
        variablesToSet.put(var.getName(), actualVariableValue);
        resultVariables.add(restResponseFactory.createRestVariable(var.getName(), actualVariableValue, varScope,
                execution.getId(), variableType, false, uriInfo.getBaseUri().toString()));
    }

    if (!variablesToSet.isEmpty()) {
        RuntimeService runtimeService = BPMNOSGIService.getRuntimeService();

        if (sharedScope == RestVariable.RestVariableScope.LOCAL) {
            runtimeService.setVariablesLocal(execution.getId(), variablesToSet);
        } else {
            if (execution.getParentId() != null) {
                // Explicitly set on parent, setting non-local variables on execution itself will override local-variables if exists
                runtimeService.setVariables(execution.getParentId(), variablesToSet);
            } else {
                // Standalone task, no global variables possible
                throw new ActivitiIllegalArgumentException("Cannot set global variables on execution '"
                        + execution.getId() + "', task is not part of process.");
            }
        }
    }

    RestVariableCollection restVariableCollection = new RestVariableCollection();
    restVariableCollection.setRestVariables(resultVariables);
    responseBuilder.entity(restVariableCollection);
    // }
    return responseBuilder.status(Response.Status.CREATED).build();
}