Search in sources :

Example 1 with JsonObject

use of org.apache.camel.util.json.JsonObject in project camel-quarkus by apache.

the class GraphQLResource method multipleQueries.

@Path("/query")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response multipleQueries(@QueryParam("testPort") int port, @QueryParam("bookId") String bookId) {
    JsonObject variables = new JsonObject();
    variables.put("id", bookId);
    producerTemplate.getCamelContext().getRegistry().bind("bookByIdQueryVariables", variables);
    final String result = producerTemplate.requestBody("graphql://http://localhost:" + port + "/graphql/server?queryFile=graphql/bookQuery.graphql&operationName=BookById&variables=#bookByIdQueryVariables", null, String.class);
    return Response.ok().entity(result).build();
}
Also used : JsonObject(org.apache.camel.util.json.JsonObject) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 2 with JsonObject

use of org.apache.camel.util.json.JsonObject in project camel-idea-plugin by camel-tooling.

the class CamelDocumentationProvider method generateCamelComponentDocumentation.

private String generateCamelComponentDocumentation(String componentName, String val, int wrapLength, Project project) {
    // it is a known Camel component
    CamelCatalog camelCatalog = ServiceManager.getService(project, CamelCatalogService.class).get();
    String json = camelCatalog.componentJSonSchema(componentName);
    if (json == null) {
        return null;
    }
    ComponentModel component = JsonMapper.generateComponentModel(json);
    // camel catalog expects & as & when it parses so replace all & as &
    String camelQuery = val;
    camelQuery = camelQuery.replaceAll("&", "&");
    // strip up ending incomplete parameter
    if (camelQuery.endsWith("&") || camelQuery.endsWith("?")) {
        camelQuery = camelQuery.substring(0, camelQuery.length() - 1);
    }
    Map<String, String> existing = null;
    try {
        existing = camelCatalog.endpointProperties(camelQuery);
    } catch (Throwable e) {
        LOG.warn("Error parsing Camel endpoint properties with url: " + camelQuery, e);
    }
    StringBuilder options = new StringBuilder();
    if (existing != null && !existing.isEmpty()) {
        JsonObject jsonObject;
        try {
            jsonObject = (JsonObject) Jsoner.deserialize(json);
        } catch (DeserializationException e) {
            throw new RuntimeException(e);
        }
        Map<String, JsonObject> properties = jsonObject.getMap("properties");
        for (Map.Entry<String, String> entry : existing.entrySet()) {
            String name = entry.getKey();
            String value = entry.getValue();
            JsonObject row = properties.get(name);
            if (row != null) {
                String kind = row.getString("kind");
                String deprecated = row.getString("deprecated");
                String line;
                if ("path".equals(kind)) {
                    line = value + "<br/>";
                } else {
                    if ("true".equals(deprecated)) {
                        line = "<s>" + name + "</s>=" + value + "<br/>";
                    } else {
                        line = name + "=" + value + "<br/>";
                    }
                }
                options.append("<br/>");
                options.append("<b>").append(line).append("</b>");
                String summary = row.getString("description");
                // the text looks a bit weird when using single /
                summary = summary.replace('/', ' ');
                options.append(wrapText(summary, wrapLength)).append("<br/>");
            }
        }
    }
    // append any lenient options as well
    Map<String, String> extra = null;
    try {
        extra = camelCatalog.endpointLenientProperties(camelQuery);
    } catch (Throwable e) {
        LOG.warn("Error parsing Camel endpoint properties with url: " + camelQuery, e);
    }
    if (extra != null && !extra.isEmpty()) {
        for (Map.Entry<String, String> entry : extra.entrySet()) {
            String name = entry.getKey();
            String value = entry.getValue();
            String line = name + "=" + value + "<br/>";
            options.append("<br/>");
            options.append("<b>").append(line).append("</b>");
            String summary = "This option is a custom option that is not part of the Camel component";
            options.append(wrapText(summary, wrapLength)).append("<br/>");
        }
    }
    StringBuilder sb = new StringBuilder();
    if (component.isDeprecated()) {
        sb.append("<b><s>").append(component.getTitle()).append(" Component (deprecated)</s></b><br/>");
    } else {
        sb.append("<b>").append(component.getTitle()).append(" Component</b><br/>");
    }
    sb.append(wrapText(component.getDescription(), wrapLength)).append("<br/><br/>");
    if (component.getDeprecatedSince() != null) {
        sb.append("<b>Deprecated Since:</b> <tt>").append(component.getDeprecatedSince()).append("</tt><br/>");
    }
    sb.append("<b>Since:</b> <tt>").append(component.getFirstVersionShort()).append("</tt><br/>");
    if (component.getSupportLevel() != null) {
        sb.append("<b>Support Level:</b> <tt>").append(component.getSupportLevel()).append("</tt><br/>");
    }
    String g = component.getGroupId();
    String a = component.getArtifactId();
    String v = component.getVersion();
    if (g != null && a != null && v != null) {
        sb.append("<b>Maven:</b> <tt>").append(g).append(":").append(a).append(":").append(v).append("</tt><br/>");
    }
    sb.append("<b>Syntax:</b> <tt>").append(component.getSyntax()).append("?options</tt><br/>");
    sb.append("<p/>");
    sb.append("<br/>");
    // indent the endpoint url with 5 spaces and wrap it by url separator
    String wrapped = wrapSeparator(val, "&", "<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;", 100);
    sb.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>").append(wrapped).append("</b><br/>");
    if (options.length() > 0) {
        sb.append(options);
    }
    return sb.toString();
}
Also used : CamelCatalog(org.apache.camel.catalog.CamelCatalog) JsonObject(org.apache.camel.util.json.JsonObject) DeserializationException(org.apache.camel.util.json.DeserializationException) CamelCatalogService(com.github.cameltooling.idea.service.CamelCatalogService) ComponentModel(org.apache.camel.tooling.model.ComponentModel) Map(java.util.Map)

Example 3 with JsonObject

use of org.apache.camel.util.json.JsonObject in project ph-ee-connector-mpesa by openMF.

the class TransactionResponseProcessor method getErrorCode.

/**
 * Sample Error Json payload
 * {
 *    "requestId":"22749-38515563-2",
 *    "errorCode":"404.001.03",
 *    "errorMessage":"Invalid Access Token"
 * }
 * @param errorJson
 * @return errorCode
 */
private String getErrorCode(String errorJson) {
    String errorCode;
    JsonObject jsonObject = (new Gson()).fromJson(errorJson, JsonObject.class);
    errorCode = jsonObject.getString("errorCode");
    return errorCode;
}
Also used : JsonObject(org.apache.camel.util.json.JsonObject) Gson(com.google.gson.Gson)

Example 4 with JsonObject

use of org.apache.camel.util.json.JsonObject in project ph-ee-connector-mpesa by openMF.

the class CollectionResponseProcessor method process.

@Override
public void process(Exchange exchange) throws JsonProcessingException {
    Map<String, Object> variables = new HashMap<>();
    Object updatedRetryCount = exchange.getProperty(SERVER_TRANSACTION_STATUS_RETRY_COUNT);
    if (updatedRetryCount != null) {
        variables.put(SERVER_TRANSACTION_STATUS_RETRY_COUNT, updatedRetryCount);
        Boolean isRetryExceeded = (Boolean) exchange.getProperty(IS_RETRY_EXCEEDED);
        if (isRetryExceeded == null || !isRetryExceeded) {
            String body = exchange.getProperty(LAST_RESPONSE_BODY, String.class);
            Object statusCode = exchange.getIn().getHeader(Exchange.HTTP_RESPONSE_CODE);
            if (body == null) {
                body = exchange.getIn().getHeader(Exchange.HTTP_RESPONSE_TEXT, String.class);
            }
            if (statusCode == null) {
                Exception e = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);
                if (null != e && e instanceof HttpOperationFailedException) {
                    HttpOperationFailedException httpOperationFailedException = (HttpOperationFailedException) e;
                    statusCode = httpOperationFailedException.getStatusCode();
                }
            }
            variables.put(GET_TRANSACTION_STATUS_RESPONSE, body);
            variables.put(GET_TRANSACTION_STATUS_RESPONSE_CODE, exchange.getIn().getHeader(Exchange.HTTP_RESPONSE_CODE));
        }
    }
    Boolean isRetryExceeded = (Boolean) exchange.getProperty(IS_RETRY_EXCEEDED);
    Object isTransactionPending = exchange.getProperty(IS_TRANSACTION_PENDING);
    if (isTransactionPending != null && (boolean) isTransactionPending && (isRetryExceeded == null || !isRetryExceeded)) {
        String newTimer = getNextTimer(exchange.getProperty(TIMER, String.class));
        logger.info("Updating retry count to " + updatedRetryCount);
        logger.info("Updating timer value to " + newTimer);
        variables.put(TIMER, newTimer);
        Long elementInstanceKey = (Long) exchange.getProperty(ZEEBE_ELEMENT_INSTANCE_KEY);
        zeebeClient.newSetVariablesCommand(elementInstanceKey).variables(variables).send().join();
        return;
    }
    Object hasTransferFailed = exchange.getProperty(TRANSACTION_FAILED);
    if (hasTransferFailed != null && (boolean) hasTransferFailed) {
        String body = exchange.getProperty(ERROR_INFORMATION, String.class);
        variables.put(TRANSACTION_FAILED, true);
        variables.put(TRANSFER_CREATE_FAILED, true);
        if (isRetryExceeded == null || !isRetryExceeded) {
            variables.put(ERROR_INFORMATION, body);
            variables.put(ERROR_CODE, exchange.getProperty(ERROR_CODE, String.class));
            variables.put(ERROR_DESCRIPTION, exchange.getProperty(ERROR_DESCRIPTION, String.class));
        }
    } else {
        variables.put(TRANSACTION_FAILED, false);
        variables.put(TRANSFER_CREATE_FAILED, false);
        variables.put(SERVER_TRANSACTION_ID, exchange.getProperty(SERVER_TRANSACTION_ID));
        Object receiptNumber = exchange.getProperty(SERVER_TRANSACTION_RECEIPT_NUMBER);
        if (receiptNumber != null) {
            variables.put(SERVER_TRANSACTION_RECEIPT_NUMBER, receiptNumber);
        }
    }
    variables.put(TRANSFER_RESPONSE_CREATE, ZeebeUtils.getTransferResponseCreateJson());
    String clientCorrelationId = exchange.getProperty(TRANSACTION_ID, String.class);
    if (clientCorrelationId == null) {
        JsonObject response = new JsonObject();
        response.put("developerMessage", "Can't find the correlation ID for the provided callback, with server id " + exchange.getProperty(SERVER_TRANSACTION_ID) + "It might be possible that either transaction doesn't " + "exist or this is test hit");
        response.put("zeebeVariables", objectMapper.writeValueAsString(variables));
        exchange.getIn().setBody(response.toJson());
        return;
    }
    logger.info("Publishing transaction message variables: " + variables);
    zeebeClient.newPublishMessageCommand().messageName(TRANSFER_MESSAGE).correlationKey(clientCorrelationId).timeToLive(Duration.ofMillis(timeToLive)).variables(variables).send().join();
}
Also used : HashMap(java.util.HashMap) HttpOperationFailedException(org.apache.camel.http.base.HttpOperationFailedException) JsonObject(org.apache.camel.util.json.JsonObject) JsonObject(org.apache.camel.util.json.JsonObject) HttpOperationFailedException(org.apache.camel.http.base.HttpOperationFailedException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 5 with JsonObject

use of org.apache.camel.util.json.JsonObject in project ph-ee-connector-mpesa by openMF.

the class ZeebeUtils method getTransferResponseCreateJson.

public static JsonObject getTransferResponseCreateJson() {
    JsonObject jsonObject = new JsonObject();
    jsonObject.put("completedTimestamp", "" + System.currentTimeMillis());
    return jsonObject;
}
Also used : JsonObject(org.apache.camel.util.json.JsonObject)

Aggregations

JsonObject (org.apache.camel.util.json.JsonObject)15 CamelKafkaConnectorModel (org.apache.camel.kafkaconnector.model.CamelKafkaConnectorModel)3 Gson (com.google.gson.Gson)2 File (java.io.File)2 StkCallback (org.mifos.connector.mpesa.dto.StkCallback)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 CamelCatalogService (com.github.cameltooling.idea.service.CamelCatalogService)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 LinkedHashMap (java.util.LinkedHashMap)1 Map (java.util.Map)1 GET (javax.ws.rs.GET)1 Path (javax.ws.rs.Path)1 Produces (javax.ws.rs.Produces)1 Exchange (org.apache.camel.Exchange)1 LoggingLevel (org.apache.camel.LoggingLevel)1 RouteBuilder (org.apache.camel.builder.RouteBuilder)1 CamelCatalog (org.apache.camel.catalog.CamelCatalog)1 HttpOperationFailedException (org.apache.camel.http.base.HttpOperationFailedException)1