Search in sources :

Example 91 with TypeReference

use of com.fasterxml.jackson.core.type.TypeReference in project thingsboard by thingsboard.

the class BaseWidgetsBundleControllerTest method testFindSystemAndTenantWidgetsBundles.

@Test
public void testFindSystemAndTenantWidgetsBundles() throws Exception {
    loginSysAdmin();
    List<WidgetsBundle> sysWidgetsBundles = doGetTyped("/api/widgetsBundles?", new TypeReference<List<WidgetsBundle>>() {
    });
    List<WidgetsBundle> createdSystemWidgetsBundles = new ArrayList<>();
    for (int i = 0; i < 82; i++) {
        WidgetsBundle widgetsBundle = new WidgetsBundle();
        widgetsBundle.setTitle("Sys widgets bundle" + i);
        createdSystemWidgetsBundles.add(doPost("/api/widgetsBundle", widgetsBundle, WidgetsBundle.class));
    }
    List<WidgetsBundle> systemWidgetsBundles = new ArrayList<>(createdSystemWidgetsBundles);
    systemWidgetsBundles.addAll(sysWidgetsBundles);
    List<WidgetsBundle> widgetsBundles = new ArrayList<>();
    widgetsBundles.addAll(systemWidgetsBundles);
    login(tenantAdmin.getEmail(), "testPassword1");
    for (int i = 0; i < 127; i++) {
        WidgetsBundle widgetsBundle = new WidgetsBundle();
        widgetsBundle.setTitle("Tenant widgets bundle" + i);
        widgetsBundles.add(doPost("/api/widgetsBundle", widgetsBundle, WidgetsBundle.class));
    }
    List<WidgetsBundle> loadedWidgetsBundles = doGetTyped("/api/widgetsBundles?", new TypeReference<List<WidgetsBundle>>() {
    });
    Collections.sort(widgetsBundles, idComparator);
    Collections.sort(loadedWidgetsBundles, idComparator);
    Assert.assertEquals(widgetsBundles, loadedWidgetsBundles);
    loginSysAdmin();
    loadedWidgetsBundles = doGetTyped("/api/widgetsBundles?", new TypeReference<List<WidgetsBundle>>() {
    });
    Collections.sort(systemWidgetsBundles, idComparator);
    Collections.sort(loadedWidgetsBundles, idComparator);
    Assert.assertEquals(systemWidgetsBundles, loadedWidgetsBundles);
    for (WidgetsBundle widgetsBundle : createdSystemWidgetsBundles) {
        doDelete("/api/widgetsBundle/" + widgetsBundle.getId().getId().toString()).andExpect(status().isOk());
    }
    loadedWidgetsBundles = doGetTyped("/api/widgetsBundles?", new TypeReference<List<WidgetsBundle>>() {
    });
    Collections.sort(sysWidgetsBundles, idComparator);
    Collections.sort(loadedWidgetsBundles, idComparator);
    Assert.assertEquals(sysWidgetsBundles, loadedWidgetsBundles);
}
Also used : ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) TypeReference(com.fasterxml.jackson.core.type.TypeReference) WidgetsBundle(org.thingsboard.server.common.data.widget.WidgetsBundle) Test(org.junit.Test)

Example 92 with TypeReference

use of com.fasterxml.jackson.core.type.TypeReference in project thingsboard by thingsboard.

the class BaseWidgetsBundleControllerTest method testFindSystemWidgetsBundlesByPageLink.

@Test
public void testFindSystemWidgetsBundlesByPageLink() throws Exception {
    loginSysAdmin();
    List<WidgetsBundle> sysWidgetsBundles = doGetTyped("/api/widgetsBundles?", new TypeReference<List<WidgetsBundle>>() {
    });
    List<WidgetsBundle> createdWidgetsBundles = new ArrayList<>();
    for (int i = 0; i < 120; i++) {
        WidgetsBundle widgetsBundle = new WidgetsBundle();
        widgetsBundle.setTitle("Widgets bundle" + i);
        createdWidgetsBundles.add(doPost("/api/widgetsBundle", widgetsBundle, WidgetsBundle.class));
    }
    List<WidgetsBundle> widgetsBundles = new ArrayList<>(createdWidgetsBundles);
    widgetsBundles.addAll(sysWidgetsBundles);
    List<WidgetsBundle> loadedWidgetsBundles = new ArrayList<>();
    TextPageLink pageLink = new TextPageLink(14);
    TextPageData<WidgetsBundle> pageData;
    do {
        pageData = doGetTypedWithPageLink("/api/widgetsBundles?", new TypeReference<TextPageData<WidgetsBundle>>() {
        }, pageLink);
        loadedWidgetsBundles.addAll(pageData.getData());
        if (pageData.hasNext()) {
            pageLink = pageData.getNextPageLink();
        }
    } while (pageData.hasNext());
    Collections.sort(widgetsBundles, idComparator);
    Collections.sort(loadedWidgetsBundles, idComparator);
    Assert.assertEquals(widgetsBundles, loadedWidgetsBundles);
    for (WidgetsBundle widgetsBundle : createdWidgetsBundles) {
        doDelete("/api/widgetsBundle/" + widgetsBundle.getId().getId().toString()).andExpect(status().isOk());
    }
    pageLink = new TextPageLink(17);
    loadedWidgetsBundles.clear();
    do {
        pageData = doGetTypedWithPageLink("/api/widgetsBundles?", new TypeReference<TextPageData<WidgetsBundle>>() {
        }, pageLink);
        loadedWidgetsBundles.addAll(pageData.getData());
        if (pageData.hasNext()) {
            pageLink = pageData.getNextPageLink();
        }
    } while (pageData.hasNext());
    Collections.sort(sysWidgetsBundles, idComparator);
    Collections.sort(loadedWidgetsBundles, idComparator);
    Assert.assertEquals(sysWidgetsBundles, loadedWidgetsBundles);
}
Also used : TextPageLink(org.thingsboard.server.common.data.page.TextPageLink) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) TypeReference(com.fasterxml.jackson.core.type.TypeReference) WidgetsBundle(org.thingsboard.server.common.data.widget.WidgetsBundle) Test(org.junit.Test)

Example 93 with TypeReference

use of com.fasterxml.jackson.core.type.TypeReference in project nextprot-api by calipho-sib.

the class StatementExtractorBase method deserialize.

protected Set<Statement> deserialize(InputStream content) {
    ObjectMapper mapper = new ObjectMapper();
    Set<Statement> obj = null;
    try {
        obj = mapper.readValue(content, new TypeReference<Set<Statement>>() {
        });
    } catch (IOException e) {
        throw new NextProtException(e);
    }
    return obj;
}
Also used : NextProtException(org.nextprot.api.commons.exception.NextProtException) Statement(org.nextprot.commons.statements.Statement) TypeReference(com.fasterxml.jackson.core.type.TypeReference) IOException(java.io.IOException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 94 with TypeReference

use of com.fasterxml.jackson.core.type.TypeReference in project OpenTripPlanner by opentripplanner.

the class BrokerHttpHandler method service.

@Override
public void service(Request request, Response response) throws Exception {
    response.setContentType("application/json");
    // request.getRequestURI(); // without protocol or server, only request path
    // request.getPathInfo(); // without handler base path
    String[] pathComponents = request.getPathInfo().split("/");
    // Path component 0 is empty since the path always starts with a slash.
    if (pathComponents.length < 2) {
        response.setStatus(HttpStatus.BAD_REQUEST_400);
        response.setDetailMessage("path should have at least one part");
    }
    try {
        if (request.getMethod() == Method.HEAD) {
            /* Let the client know server is alive and URI + request are valid. */
            mapper.readTree(request.getInputStream());
            response.setStatus(HttpStatus.OK_200);
            return;
        } else if (request.getMethod() == Method.GET && "status".equals(pathComponents[1])) {
            /* fetch job status */
            String[] jobIds = pathComponents[2].split(",");
            List<JobStatus> ret = Arrays.asList(jobIds).stream().map(id -> broker.findJob(id)).filter(job -> job != null).map(job -> new JobStatus(job)).collect(Collectors.toList());
            if (ret.isEmpty()) {
                response.setStatus(HttpStatus.NOT_FOUND_404);
                response.setDetailMessage("no job IDs were found");
            } else {
                response.setStatus(HttpStatus.OK_200);
                OutputStream os = response.getOutputStream();
                mapper.writeValue(os, ret);
                os.close();
            }
            return;
        } else if (request.getMethod() == Method.POST) {
            /* dequeue messages. */
            String command = pathComponents[1];
            if ("dequeue".equals(command)) {
                String graphAffinity = pathComponents[2];
                request.getRequest().getConnection().addCloseListener((closeable, iCloseType) -> {
                    broker.removeSuspendedResponse(graphAffinity, response);
                });
                // The request should survive after the handler function exits.
                response.suspend();
                broker.registerSuspendedResponse(graphAffinity, response);
            } else /* not dequeueing, enqueuing */
            if ("enqueue".equals(command)) {
                String context = pathComponents[2];
                if ("priority".equals(context)) {
                    // Enqueue a single priority task
                    AnalystClusterRequest task = mapper.readValue(request.getInputStream(), AnalystClusterRequest.class);
                    broker.enqueuePriorityTask(task, response);
                    // Enqueueing the priority task has set its internal taskId.
                    // TODO move all removal listener registration into the broker functions.
                    request.getRequest().getConnection().addCloseListener((closeable, iCloseType) -> {
                        broker.deletePriorityTask(task.taskId);
                    });
                    // The request should survive after the handler function exits.
                    response.suspend();
                    return;
                } else if ("jobs".equals(context)) {
                    // Enqueue a list of tasks that belong to jobs
                    List<AnalystClusterRequest> tasks = mapper.readValue(request.getInputStream(), new TypeReference<List<AnalystClusterRequest>>() {
                    });
                    // Pre-validate tasks checking that they are all on the same job
                    AnalystClusterRequest exemplar = tasks.get(0);
                    for (AnalystClusterRequest task : tasks) {
                        if (task.jobId != exemplar.jobId || task.graphId != exemplar.graphId) {
                            response.setStatus(HttpStatus.BAD_REQUEST_400);
                            response.setDetailMessage("All tasks must be for the same graph and job.");
                        }
                    }
                    broker.enqueueTasks(tasks);
                    response.setStatus(HttpStatus.ACCEPTED_202);
                } else {
                    response.setStatus(HttpStatus.NOT_FOUND_404);
                    response.setDetailMessage("Context not found; should be either 'jobs' or 'priority'");
                }
            } else if ("complete".equals(command)) {
                // Mark a specific high-priority task as completed, and record its result.
                // We were originally planning to do this with a DELETE request that has a body,
                // but that is nonstandard enough to anger many libraries including Grizzly.
                int taskId = Integer.parseInt(pathComponents[3]);
                Response suspendedProducerResponse = broker.deletePriorityTask(taskId);
                if (suspendedProducerResponse == null) {
                    response.setStatus(HttpStatus.NOT_FOUND_404);
                    return;
                }
                // Copy the result back to the connection that was the source of the task.
                try {
                    ByteStreams.copy(request.getInputStream(), suspendedProducerResponse.getOutputStream());
                } catch (IOException ioex) {
                // Apparently the task producer did not wait to retrieve its result. Priority task result delivery
                // is not guaranteed, we don't need to retry, this is not considered an error by the worker.
                }
                response.setStatus(HttpStatus.OK_200);
                suspendedProducerResponse.setStatus(HttpStatus.OK_200);
                suspendedProducerResponse.resume();
                return;
            } else if ("single".equals(command)) {
                // await single point responses
                String graphAffinity = pathComponents[2];
                Broker.WrappedResponse wr = new Broker.WrappedResponse(request, response);
                request.getRequest().getConnection().addCloseListener((c, i) -> {
                    broker.removeSinglePointChannel(graphAffinity, wr);
                });
                response.suspend();
                broker.registerSinglePointChannel(graphAffinity, wr);
            }
        } else if (request.getMethod() == Method.DELETE) {
            /* Acknowledge completion of a task and remove it from queues, avoiding re-delivery. */
            if ("tasks".equalsIgnoreCase(pathComponents[1])) {
                int taskId = Integer.parseInt(pathComponents[2]);
                // This must not have been a priority task. Try to delete it as a normal job task.
                if (broker.markTaskCompleted(taskId)) {
                    response.setStatus(HttpStatus.OK_200);
                } else {
                    response.setStatus(HttpStatus.NOT_FOUND_404);
                }
            } else if ("jobs".equals((pathComponents[1]))) {
                if (broker.deleteJob(pathComponents[2])) {
                    response.setStatus(HttpStatus.OK_200);
                    response.setDetailMessage("job deleted");
                } else {
                    response.setStatus(HttpStatus.NOT_FOUND_404);
                    response.setDetailMessage("job not found");
                }
            } else {
                response.setStatus(HttpStatus.BAD_REQUEST_400);
                response.setDetailMessage("Delete is only allowed for tasks and jobs.");
            }
        } else {
            response.setStatus(HttpStatus.BAD_REQUEST_400);
            response.setDetailMessage("Unrecognized HTTP method.");
        }
    } catch (JsonProcessingException jpex) {
        response.setStatus(HttpStatus.BAD_REQUEST_400);
        response.setDetailMessage("Could not decode/encode JSON payload. " + jpex.getMessage());
        LOG.info("Error processing JSON from client", jpex);
    } catch (Exception ex) {
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR_500);
        response.setDetailMessage(ex.toString());
        LOG.info("Error processing client request", ex);
    }
}
Also used : OutputStream(java.io.OutputStream) Arrays(java.util.Arrays) Request(org.glassfish.grizzly.http.server.Request) Logger(org.slf4j.Logger) Method(org.glassfish.grizzly.http.Method) JodaLocalDateSerializer(org.opentripplanner.api.model.JodaLocalDateSerializer) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HttpHandler(org.glassfish.grizzly.http.server.HttpHandler) AgencyAndIdSerializer(org.opentripplanner.api.model.AgencyAndIdSerializer) LoggerFactory(org.slf4j.LoggerFactory) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) Response(org.glassfish.grizzly.http.server.Response) Collectors(java.util.stream.Collectors) List(java.util.List) GeoJsonModule(com.conveyal.geojson.GeoJsonModule) ByteStreams(com.google.common.io.ByteStreams) JsonInclude(com.fasterxml.jackson.annotation.JsonInclude) AnalystClusterRequest(org.opentripplanner.analyst.cluster.AnalystClusterRequest) TypeReference(com.fasterxml.jackson.core.type.TypeReference) HttpStatus(org.glassfish.grizzly.http.util.HttpStatus) OutputStream(java.io.OutputStream) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) Response(org.glassfish.grizzly.http.server.Response) List(java.util.List) AnalystClusterRequest(org.opentripplanner.analyst.cluster.AnalystClusterRequest) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 95 with TypeReference

use of com.fasterxml.jackson.core.type.TypeReference in project streamline by hortonworks.

the class AclEntry method toMap.

@Override
public Map<String, Object> toMap() {
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> map = super.toMap();
    map.put(SID_TYPE, sidType != null ? sidType.toString() : "");
    try {
        map.put(PERMISSIONS, permissions != null ? mapper.writerFor(new TypeReference<EnumSet<Permission>>() {
        }).writeValueAsString(permissions) : "");
    } catch (JsonProcessingException ex) {
        throw new RuntimeException(ex);
    }
    return map;
}
Also used : Permission(com.hortonworks.streamline.streams.security.Permission) TypeReference(com.fasterxml.jackson.core.type.TypeReference) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Aggregations

TypeReference (com.fasterxml.jackson.core.type.TypeReference)316 IOException (java.io.IOException)130 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)113 Test (org.junit.Test)95 ArrayList (java.util.ArrayList)74 Map (java.util.Map)74 List (java.util.List)60 HashMap (java.util.HashMap)58 File (java.io.File)34 TextPageLink (org.thingsboard.server.common.data.page.TextPageLink)27 Collectors (java.util.stream.Collectors)25 InputStream (java.io.InputStream)23 JsonNode (com.fasterxml.jackson.databind.JsonNode)19 ImmutableMap (com.google.common.collect.ImmutableMap)19 lombok.val (lombok.val)18 Matchers.containsString (org.hamcrest.Matchers.containsString)17 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)14 Collections (java.util.Collections)13 ISE (org.apache.druid.java.util.common.ISE)12 URL (java.net.URL)10