Java Code Examples for javax.ws.rs.Produces

The following examples show how to use javax.ws.rs.Produces. These examples are extracted from open source projects.
Example 1
Project: camel-quarkus   File: SoapResource.java    License: Apache License 2.0 6 votes vote down vote up
@Path("/round")
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public Response round(String message) throws Exception {
    LOG.infof("Sending to soap: %s", message);
    GetCustomersByName request = new GetCustomersByName();
    request.setName(message);
    final String xml = producerTemplate.requestBody("direct:marshal", request, String.class);
    LOG.infof("Got response from marshal: %s", xml);

    GetCustomersByName response = producerTemplate.requestBody("direct:unmarshal", xml, GetCustomersByName.class);
    LOG.infof("Got response from unmarshal: %s", response);

    return Response
            .created(new URI("https://camel.apache.org/"))
            .entity(response.getName())
            .build();
}
 
Example 2
Project: hmdm-server   File: SettingsResource.java    License: Apache License 2.0 6 votes vote down vote up
@ApiOperation(
        value = "Save misc settings",
        notes = "Save the misc settings for MDM web application",
        response = Settings.class
)
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/misc")
public Response updateMiscSettings(Settings settings) {
    try {
        if (!unsecureDAO.isSingleCustomer()) {
            // These settings are not allowed to setup in multi-tenant mode
            settings.setCreateNewDevices(false);
            settings.setNewDeviceGroupId(null);
            settings.setNewDeviceConfigurationId(null);
        }
        this.commonDAO.saveMiscSettings(settings);
        return Response.OK();
    } catch (Exception e) {
        log.error("Unexpected error when saving misc settings", e);
        return Response.INTERNAL_ERROR();
    }
}
 
Example 3
Project: hmdm-server   File: FilesResource.java    License: Apache License 2.0 6 votes vote down vote up
@ApiOperation(
        value = "Get applications",
        notes = "Gets the list of applications using the file",
        response = Application.class,
        responseContainer = "List"
)
@GET
@Path("/apps/{url}")
@Produces(MediaType.APPLICATION_JSON)
public Response getApplicationsForFile(@PathParam("url") @ApiParam("An URL referencing the file") String url) {
    try {
        String decodedUrl = URLDecoder.decode(url, "UTF-8");
        return Response.OK(this.applicationDAO.getAllApplicationsByUrl(decodedUrl));
    } catch (Exception e) {
        logger.error("Unexpected error when getting the list of applications by URL", e);
        return Response.INTERNAL_ERROR();
    }
}
 
Example 4
Project: metrics   File: MetricsResource.java    License: Apache License 2.0 6 votes vote down vote up
@Path("/list")
@GET
@Produces({Constants.PRODUCE_JSON_WITH_QUALITY_SOURCE, MediaType.TEXT_HTML})
public Response listMetrics() {
    if (manager.isEnabled()) {
        Map<String, Set<MetricObject>> metrics = new LinkedHashMap<String, Set<MetricObject>>();
        for (String groupName : manager.listMetricGroups()) {
            MetricRegistry registry = manager.getMetricRegistryByGroup(groupName);
            Set<MetricObject> metricsPerRegistry = new LinkedHashSet<MetricObject>();
            metricsPerRegistry.addAll(buildMetricRegistry(registry));
            metrics.put(groupName, metricsPerRegistry);
        }
        try {
            String data = JSON.toJSONString(buildResultPojo(metrics, true, ""), filter);
            return Response.ok(data).build();
        } catch (Exception e) {
            return buildResult(null, false, e.toString());
        }
    } else {
        return buildResult(null, false, "Metrics has been disabled explicitly!");
    }
}
 
Example 5
Project: kogito-runtimes   File: ReactiveRestResourceTemplate.java    License: Apache License 2.0 6 votes vote down vote up
@POST()
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)    
public CompletionStage<$Type$Output> createResource_$name$(@Context HttpHeaders httpHeaders, @QueryParam("businessKey") String businessKey, $Type$Input resource) {
    if (resource == null) {
        resource = new $Type$Input();
    }
    final $Type$Input value = resource;
    return CompletableFuture.supplyAsync(() -> {
        return org.kie.kogito.services.uow.UnitOfWorkExecutor.executeInUnitOfWork(application.unitOfWorkManager(), () -> {
            ProcessInstance<$Type$> pi = process.createInstance(businessKey, mapInput(value, new $Type$()));
            String startFromNode = httpHeaders.getHeaderString("X-KOGITO-StartFromNode");
            
            if (startFromNode != null) {
                pi.startFrom(startFromNode);
            } else {
            
                pi.start();
            }
            return getModel(pi);
        });
    });
}
 
Example 6
Project: cantor   File: SetsResource.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@GET
@Path("/{namespace}/{set}")
@Produces(MediaType.APPLICATION_JSON)
@Operation(summary = "Get entries from a set")
@ApiResponses(value = {
    @ApiResponse(responseCode = "200",
                 description = "Provides entry names and weights matching query parameters as properties in a json",
                 content = @Content(schema = @Schema(implementation = Map.class))),
    @ApiResponse(responseCode = "400", description = "One of the query parameters has a bad value"),
    @ApiResponse(responseCode = "500", description = serverErrorMessage)
})
public Response get(@Parameter(description = "Namespace identifier") @PathParam("namespace") final String namespace,
                    @Parameter(description = "Name of the set") @PathParam("set") final String set,
                    @BeanParam final SetsDataSourceBean bean) throws IOException {
    logger.info("received request for values in set/namespace {}/{}", set, namespace);
    logger.debug("request parameters: {}", bean);
    final Map<String, Long> entries = this.cantor.sets().get(
            namespace,
            set,
            bean.getMin(),
            bean.getMax(),
            bean.getStart(),
            bean.getCount(),
            bean.isAscending());
    return Response.ok(parser.toJson(entries)).build();
}
 
Example 7
Project: camel-quarkus   File: ReactiveStreamsResource.java    License: Apache License 2.0 6 votes vote down vote up
@Path("/to-upper")
@POST
@Produces(MediaType.TEXT_PLAIN)
public String toUpper(String payload) throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<String> result = new AtomicReference<>();

    TestSubscriber<String> subscriber = TestSubscriber.onNext(data -> {
        result.set(data);
        latch.countDown();
    });

    subscriber.setInitiallyRequested(1);
    reactiveStreamsService.fromStream("toUpper", String.class).subscribe(subscriber);

    producerTemplate.to("direct:toUpper").withBody(payload).send();

    latch.await(5, TimeUnit.SECONDS);

    return result.get();
}
 
Example 8
Project: hmdm-server   File: DeviceResource.java    License: Apache License 2.0 6 votes vote down vote up
@ApiOperation(
        value = "Delete device",
        notes = "Delete an existing device"
)
@DELETE
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response removeDevice(@PathParam("id") @ApiParam("Device ID") Integer id) {
    final boolean canEditDevices = SecurityContext.get().hasPermission("edit_devices");

    if (!(canEditDevices)) {
        log.error("Unauthorized attempt to delete device",
                SecurityException.onCustomerDataAccessViolation(id, "device"));
        return Response.PERMISSION_DENIED();
    }

    this.deviceDAO.removeDeviceById(id);
    return Response.OK();
}
 
Example 9
Project: kogito-runtimes   File: ReactiveRestResourceTemplate.java    License: Apache License 2.0 6 votes vote down vote up
@POST()
@Path("/{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public CompletionStage<$Type$Output> updateModel_$name$(@PathParam("id") String id, $Type$ resource) {
    return CompletableFuture.supplyAsync(() -> {
        return org.kie.kogito.services.uow.UnitOfWorkExecutor.executeInUnitOfWork(application.unitOfWorkManager(), () -> {
            ProcessInstance<$Type$> pi = process.instances()
                    .findById(id)
                    .orElse(null);
            if (pi == null) {
                return null;
            } else {
                pi.updateVariables(resource);
                return mapOutput(new $Type$Output(), pi.variables());
            }
        });
    });
}
 
Example 10
Project: presto   File: QueryStateInfoResource.java    License: Apache License 2.0 6 votes vote down vote up
@ResourceSecurity(AUTHENTICATED_USER)
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<QueryStateInfo> getQueryStateInfos(@QueryParam("user") String user, @Context HttpServletRequest servletRequest, @Context HttpHeaders httpHeaders)
{
    List<BasicQueryInfo> queryInfos = dispatchManager.getQueries();
    queryInfos = filterQueries(extractAuthorizedIdentity(servletRequest, httpHeaders, accessControl, groupProvider), queryInfos, accessControl);

    if (!isNullOrEmpty(user)) {
        queryInfos = queryInfos.stream()
                .filter(queryInfo -> Pattern.matches(user, queryInfo.getSession().getUser()))
                .collect(toImmutableList());
    }

    return queryInfos.stream()
            .filter(queryInfo -> !queryInfo.getState().isDone())
            .map(this::getQueryStateInfo)
            .collect(toImmutableList());
}
 
Example 11
Project: camel-quarkus   File: SoapResource.java    License: Apache License 2.0 6 votes vote down vote up
@Path("/marshal/{soapVersion}")
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_XML)
public Response marshall(@PathParam("soapVersion") String soapVersion, String message) throws Exception {
    LOG.infof("Sending to soap: %s", message);
    GetCustomersByName request = new GetCustomersByName();
    request.setName(message);

    final String endpointUri = "direct:marshal" + (soapVersion.equals("1.2") ? "-soap12" : "");
    final String response = producerTemplate.requestBody(endpointUri, request, String.class);

    return Response
            .created(new URI("https://camel.apache.org/"))
            .entity(response)
            .build();
}
 
Example 12
Project: hmdm-server   File: VideosResource.java    License: Apache License 2.0 6 votes vote down vote up
@GET
@Path("/{fileName}")
@Produces({"application/octet-stream"})
public javax.ws.rs.core.Response downloadVideo(@PathParam("fileName") String fileName) throws Exception {
    File videoDir = new File(this.videoDirectory);
    if (!videoDir.exists()) {
        videoDir.mkdirs();
    }

    File videoFile = new File(videoDir, URLDecoder.decode(fileName, "UTF8"));
    if (!videoFile.exists()) {
        return javax.ws.rs.core.Response.status(404).build();
    } else {
        ContentDisposition contentDisposition = ContentDisposition.type("attachment").fileName(videoFile.getName()).creationDate(new Date()).build();
        return javax.ws.rs.core.Response.ok( ( StreamingOutput ) output -> {
            try {
                InputStream input = new FileInputStream( videoFile );
                IOUtils.copy(input, output);
                output.flush();
            } catch ( Exception e ) { e.printStackTrace(); }
        } ).header( "Content-Disposition", contentDisposition ).build();

    }
}
 
Example 13
Project: hmdm-server   File: SettingsResource.java    License: Apache License 2.0 6 votes vote down vote up
@ApiOperation(
        value = "Get user role settings",
        notes = "Gets the current settings for role of the current user",
        response = UserRoleSettings.class
)
@GET
@Path("/userRole/{roleId}")
@Produces(MediaType.APPLICATION_JSON)
public Response getUserRoleSettings(@PathParam("roleId") int roleId) {
    try {
        UserRoleSettings settings = this.userRoleSettingsDAO.getUserRoleSettings(roleId);
        if (settings == null) {
            final UserRoleSettings defaultSettings = new UserRoleSettings();
            defaultSettings.setRoleId(roleId);

            settings = defaultSettings;
        }
        return Response.OK(settings);
    } catch (Exception e) {
        log.error("Unexpected error when getting the user role settings for current user", e);
        return Response.INTERNAL_ERROR();
    }
}
 
Example 14
Project: presto   File: TaskResource.java    License: Apache License 2.0 6 votes vote down vote up
@ResourceSecurity(INTERNAL_ONLY)
@POST
@Path("{taskId}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createOrUpdateTask(@PathParam("taskId") TaskId taskId, TaskUpdateRequest taskUpdateRequest, @Context UriInfo uriInfo)
{
    requireNonNull(taskUpdateRequest, "taskUpdateRequest is null");

    Session session = taskUpdateRequest.getSession().toSession(sessionPropertyManager, taskUpdateRequest.getExtraCredentials());
    TaskInfo taskInfo = taskManager.updateTask(session,
            taskId,
            taskUpdateRequest.getFragment(),
            taskUpdateRequest.getSources(),
            taskUpdateRequest.getOutputIds(),
            taskUpdateRequest.getTotalPartitions());

    if (shouldSummarize(uriInfo)) {
        taskInfo = taskInfo.summarize();
    }

    return Response.ok().entity(taskInfo).build();
}
 
Example 15
Project: sofa-registry   File: DataDigestResource.java    License: Apache License 2.0 6 votes vote down vote up
@POST
@Path("connect/query")
@Produces(MediaType.APPLICATION_JSON)
public Map<String, Map<String, Publisher>> getPublishersByConnectId(Map<String, String> map) {
    Map<String, Map<String, Publisher>> ret = new HashMap<>();
    if (map != null && !map.isEmpty()) {
        map.forEach((ip, port) -> {
            String connectId = NetUtil.genHost(ip, Integer.valueOf(port));
            if (!connectId.isEmpty()) {
                Map<String, Publisher> publisherMap = datumCache.getByConnectId(connectId);
                if (publisherMap != null && !publisherMap.isEmpty()) {
                    ret.put(connectId, publisherMap);
                }
            }
        });
    }
    return ret;
}
 
Example 16
Project: fido2   File: WebauthnService.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
@POST
@Path("/" + Constants.RP_ISLOGGEDIN_PATH)
@Produces({MediaType.APPLICATION_JSON})
public Response isLoggedIn() {
    try {
        HttpSession session = request.getSession(false);
        if (session == null) {
            return generateResponse(Response.Status.OK, "");
        }
        String username = (String) session.getAttribute(Constants.SESSION_USERNAME);
        Boolean isAuthenticated = (Boolean) session.getAttribute(Constants.SESSION_ISAUTHENTICATED);
        if(username == null || isAuthenticated == null || !isAuthenticated){
            return generateResponse(Response.Status.OK, "");
        }
        return generateResponse(Response.Status.OK, username);
    } catch (Exception ex) {
        ex.printStackTrace();
        WebauthnTutorialLogger.logp(Level.SEVERE, CLASSNAME, "isLoggedIn", "WEBAUTHN-WS-ERR-1000", ex.getLocalizedMessage());
        return generateResponse(Response.Status.INTERNAL_SERVER_ERROR,
                WebauthnTutorialLogger.getMessageProperty("WEBAUTHN-WS-ERR-1000"));
    }
}
 
Example 17
Project: Bats   File: StorageResources.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Regex allows the following paths:
 * /storage/{name}/export
 * "/storage/{name}/export/{format}
 * Note: for the second case the format involves the leading slash, therefore it should be removed then
 */
@GET
@Path("/storage/{name}/export{format: (/[^/]+?)*}")
@Produces(MediaType.APPLICATION_JSON)
public Response exportPlugin(@PathParam("name") String name, @PathParam("format") String format) {
  format = StringUtils.isNotEmpty(format) ? format.replace("/", "") : JSON_FORMAT;
  return isSupported(format)
      ? Response.ok(getPluginConfig(name))
          .header(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment;filename=\"%s.%s\"", name, format))
          .build()
      : Response.status(Response.Status.NOT_FOUND.getStatusCode())
          .entity(String.format("Unknown \"%s\" file format for \"%s\" Storage Plugin config", format, name))
          .build();
}
 
Example 18
Project: kogito-runtimes   File: ProcessInstanceManagementResource.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@DELETE
@Path("{processId}/instances/{processInstanceId}")
@Produces(MediaType.APPLICATION_JSON)
public Response cancelProcessInstanceId(@PathParam("processId") String processId, @PathParam("processInstanceId") String processInstanceId) {
    return doCancelProcessInstanceId(processId, processInstanceId);
}
 
Example 19
Project: Bats   File: StorageResources.java    License: Apache License 2.0 5 votes vote down vote up
@GET
@Path("/storage/{name}.json")
@Produces(MediaType.APPLICATION_JSON)
public PluginConfigWrapper getPluginConfig(@PathParam("name") String name) {
  try {
    // TODO: DRILL-6412: No need to get StoragePlugin. It is enough to have plugin name and config here
    StoragePlugin plugin = storage.getPlugin(name);
    if (plugin != null) {
      return new PluginConfigWrapper(name, plugin.getConfig());
    }
  } catch (Exception e) {
    logger.error("Failure while trying to access storage config: {}", name, e);
  }
  return new PluginConfigWrapper(name, null);
}
 
Example 20
Project: camel-quarkus   File: CsvResource.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Path("/csv-to-json")
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON)
public List<List<Object>> csv2json(String csv) throws Exception {
    return producerTemplate.requestBody("direct:csv-to-json", csv, List.class);
}
 
Example 21
Project: micro-integrator   File: MusicRestService.java    License: Apache License 2.0 5 votes vote down vote up
@GET
@Path("/get")
@Produces(MediaType.APPLICATION_JSON)
public Music getMusicInJSON(@QueryParam("album") final String albumName) {
    /*            Music music = new Music();
   music.setAlbum("Beat It !!!");
   music.setSinger("Micheal Jackson");*/

    return musicService.getByAlbum(albumName);
    //return musicService.musicCollection.get("Dimuthu");

}
 
Example 22
Project: sofa-registry   File: RenewSwitchResource.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * enable session
 */
@GET
@Path("session/enable")
@Produces(MediaType.APPLICATION_JSON)
public Result enableSessionRenew() {
    invokeSession("true");

    Result result = new Result();
    result.setSuccess(true);
    return result;
}
 
Example 23
Project: micro-integrator   File: MusicRestService.java    License: Apache License 2.0 5 votes vote down vote up
@POST
@Path("/post")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response createMusicInJSONPOST(
        Music music /*@PathParam("album") String album, @PathParam("singer") String singer*/) {

    musicService.setMusic(music);

    String result = "Album Added in POST : " + music;
    return Response.status(201).entity(result).build();
    //return music.getAlbum();

}
 
Example 24
Project: camel-quarkus   File: JtaResource.java    License: Apache License 2.0 5 votes vote down vote up
@Path("/{policy}")
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public Response post(@PathParam("policy") String policy, String message) throws Exception {
    LOG.infof("Sending to jta policy %s: %s", policy, message);
    final String response = producerTemplate.requestBody("direct:" + policy, message, String.class);
    LOG.infof("Got response from jta: %s", response);
    return Response
            .created(new URI("https://camel.apache.org/"))
            .entity(response)
            .build();
}
 
Example 25
Project: Bats   File: StramWebServices.java    License: Apache License 2.0 5 votes vote down vote up
@GET
@Path(PATH_LOGICAL_PLAN_OPERATORS)
@Produces(MediaType.APPLICATION_JSON)
public JSONObject getLogicalOperators() throws Exception
{
  init();
  LogicalOperatorsInfo nodeList = new LogicalOperatorsInfo();
  nodeList.operators = dagManager.getLogicalOperatorInfoList();
  return new JSONObject(objectMapper.writeValueAsString(nodeList));
}
 
Example 26
Project: camel-quarkus   File: XmlResource.java    License: Apache License 2.0 5 votes vote down vote up
@Path("/html-to-text")
@POST
@Consumes(MediaType.TEXT_HTML)
@Produces(MediaType.TEXT_PLAIN)
public String htmlToText(String html) {
    LOG.debugf("Parsing HTML %s", html);
    return producerTemplate.requestBody(
            XmlRouteBuilder.DIRECT_HTML_TO_TEXT,
            html,
            String.class);
}
 
Example 27
Project: apicurio-registry   File: Api.java    License: Apache License 2.0 5 votes vote down vote up
@PATCH
@Path("/schemas/{schemaid}")
@Consumes({"application/json"})
@Produces({"application/json"})
public Response apiSchemasSchemaidPatch(@PathParam("schemaid") String schemaid, @NotNull @Valid List<AnyOfStateModificationEnabledModification> anyOfStateModificationEnabledModification)
throws ArtifactNotFoundException {
    return service.apiSchemasSchemaidPatch(schemaid, anyOfStateModificationEnabledModification);
}
 
Example 28
Project: presto   File: TestHttpRemoteTask.java    License: Apache License 2.0 5 votes vote down vote up
@GET
@Path("{taskId}")
@Produces(MediaType.APPLICATION_JSON)
public synchronized TaskInfo getTaskInfo(
        @PathParam("taskId") final TaskId taskId,
        @HeaderParam(PRESTO_CURRENT_STATE) TaskState currentState,
        @HeaderParam(PRESTO_MAX_WAIT) Duration maxWait,
        @Context UriInfo uriInfo)
{
    lastActivityNanos.set(System.nanoTime());
    return buildTaskInfo();
}
 
Example 29
Project: quarkus-coffeeshop-demo   File: BoardResource.java    License: Apache License 2.0 5 votes vote down vote up
@GET
@Produces(MediaType.SERVER_SENT_EVENTS)
public Publisher<String> getQueue() {
    return Multi.createBy().merging()
            .streams(
                    queue.map(b -> json.toJson(b)),
                    getPingStream()
            );
}
 
Example 30
Project: browserup-proxy   File: EntriesProxyResource.java    License: Apache License 2.0 5 votes vote down vote up
@GET
@Path("/assertResponseTimeLessThanOrEqual")
@Produces(MediaType.APPLICATION_JSON)
@Operation(
        description = "Assert that the response times for all requests " +
                "found by a given URL pattern are less than or equal to a given number of milliseconds.",
        responses = {
                @ApiResponse(
                        description = "Assertion result",
                        content = @Content(
                                mediaType = MediaType.APPLICATION_JSON,
                                schema = @Schema(implementation = AssertionResult.class)))})
public AssertionResult responseTimeLessThanOrEqual(
        @PathParam(PORT)
        @NotNullConstraint(paramName = PORT)
        @PortWithExistingProxyConstraint
        @Parameter(required = true, in = ParameterIn.PATH, description = DocConstants.PORT_DESCRIPTION) int port,

        @QueryParam(URL_PATTERN)
        @NotBlankConstraint(paramName = URL_PATTERN)
        @PatternConstraint(paramName = URL_PATTERN)
        @Parameter(required = true, description = DocConstants.URL_PATTERN_DESCRIPTION) String urlPattern,

        @QueryParam(MILLISECONDS)
        @LongPositiveConstraint(value = 0, paramName = MILLISECONDS)
        @Parameter(required = true, description = DocConstants.MILLISECONDS_DESCRIPTION) String milliseconds) {

    return proxyManager.get(port).assertResponseTimeLessThanOrEqual(
            Pattern.compile(urlPattern),
            Long.parseLong(milliseconds));
}
 
Example 31
Project: presto   File: TaskResource.java    License: Apache License 2.0 5 votes vote down vote up
@ResourceSecurity(INTERNAL_ONLY)
@GET
@Path("{taskId}")
@Produces(MediaType.APPLICATION_JSON)
public void getTaskInfo(
        @PathParam("taskId") final TaskId taskId,
        @HeaderParam(PRESTO_CURRENT_STATE) TaskState currentState,
        @HeaderParam(PRESTO_MAX_WAIT) Duration maxWait,
        @Context UriInfo uriInfo,
        @Suspended AsyncResponse asyncResponse)
{
    requireNonNull(taskId, "taskId is null");

    if (currentState == null || maxWait == null) {
        TaskInfo taskInfo = taskManager.getTaskInfo(taskId);
        if (shouldSummarize(uriInfo)) {
            taskInfo = taskInfo.summarize();
        }
        asyncResponse.resume(taskInfo);
        return;
    }

    Duration waitTime = randomizeWaitTime(maxWait);
    ListenableFuture<TaskInfo> futureTaskInfo = addTimeout(
            taskManager.getTaskInfo(taskId, currentState),
            () -> taskManager.getTaskInfo(taskId),
            waitTime,
            timeoutExecutor);

    if (shouldSummarize(uriInfo)) {
        futureTaskInfo = Futures.transform(futureTaskInfo, TaskInfo::summarize, directExecutor());
    }

    // For hard timeout, add an additional time to max wait for thread scheduling contention and GC
    Duration timeout = new Duration(waitTime.toMillis() + ADDITIONAL_WAIT_TIME.toMillis(), MILLISECONDS);
    bindAsyncResponse(asyncResponse, futureTaskInfo, responseExecutor)
            .withTimeout(timeout);
}
 
Example 32
Project: Hands-On-Enterprise-Java-Microservices-with-Eclipse-MicroProfile   File: SecureEndpoint.java    License: MIT License 5 votes vote down vote up
@GET
@Path("/openHello")
@Produces(MediaType.TEXT_PLAIN)
@PermitAll
public String openHello() {
    String user = jwt == null ? "anonymous" : jwt.getName();
    String upnClaim = upn == null ? "no-upn" : upn;
    return String.format("Hello[open] user=%s, upn=%s", user, upnClaim);
}
 
Example 33
Project: browserup-proxy   File: MostRecentEntryProxyResource.java    License: Apache License 2.0 5 votes vote down vote up
@GET
@Path("/assertContentContains")
@Produces(MediaType.APPLICATION_JSON)
@Operation(
        description = "Assert that response content for the most recent request found by a given URL pattern contains specified value.",
        responses = {@ApiResponse(
                description = "Assertion result",
                content = @Content(
                        mediaType = MediaType.APPLICATION_JSON,
                        schema = @Schema(implementation = AssertionResult.class)))})
public AssertionResult contentContains(
        @PathParam(PORT)
        @NotNullConstraint(paramName = PORT)
        @PortWithExistingProxyConstraint
        @Parameter(required = true, in = ParameterIn.PATH, description = PORT_DESCRIPTION) int port,

        @QueryParam(URL_PATTERN)
        @NotBlankConstraint(paramName = URL_PATTERN)
        @PatternConstraint(paramName = URL_PATTERN)
        @Parameter(required = true, description = URL_PATTERN_DESCRIPTION) String urlPattern,

        @QueryParam(CONTENT_TEXT)
        @NotBlankConstraint(paramName = CONTENT_TEXT)
        @Parameter(required = true, description = CONTENT_TEXT_DESCRIPTION) String contentText) {

    return proxyManager.get(port).assertMostRecentResponseContentContains(Pattern.compile(urlPattern), contentText);
}
 
Example 34
Project: browserup-proxy   File: EntriesProxyResource.java    License: Apache License 2.0 5 votes vote down vote up
@GET
@Path("/assertStatusEquals")
@Produces(MediaType.APPLICATION_JSON)
@Operation(description = "In case url pattern is provided assert that all responses found by url pattern have specified http status, " +
        "otherwise assert that all responses of current step have specified status.",
        responses = {@ApiResponse(
                description = "Assertion result",
                content = @Content(
                        mediaType = MediaType.APPLICATION_JSON,
                        schema = @Schema(implementation = AssertionResult.class)))})
public AssertionResult statusEquals(
        @PathParam(PORT)
        @NotNullConstraint(paramName = PORT)
        @PortWithExistingProxyConstraint
        @Parameter(required = true, in = ParameterIn.PATH, description = DocConstants.PORT_DESCRIPTION) int port,

        @QueryParam(URL_PATTERN)
        @PatternConstraint(paramName = URL_PATTERN)
        @Parameter(description = DocConstants.URL_PATTERN_DESCRIPTION) String urlPattern,

        @QueryParam(STATUS)
        @NotNullConstraint(paramName = STATUS)
        @HttpStatusCodeConstraint(paramName = STATUS)
        @Parameter(required = true, description = STATUS_DESCRIPTION) String status) {

    MitmProxyServer proxyServer = proxyManager.get(port);
    int intStatus = Integer.parseInt(status);

    return StringUtils.isEmpty(urlPattern) ?
            proxyServer.assertResponseStatusCode(intStatus) :
            proxyServer.assertResponseStatusCode(Pattern.compile(urlPattern), intStatus);
}
 
Example 35
Project: camel-quarkus   File: DataformatResource.java    License: Apache License 2.0 5 votes vote down vote up
@Path("/ical/marshal")
@GET
@Produces("text/calendar")
public String icalmarshal(
        @QueryParam("start") String start,
        @QueryParam("end") String end,
        @QueryParam("summary") String summary,
        @QueryParam("attendee") String attendee) {
    Calendar cal = ICalUtils.createTestCalendar(ZonedDateTime.parse(start), ZonedDateTime.parse(end), summary, attendee);
    return producerTemplate.requestBody("direct:ical-marshal", cal, String.class);
}
 
Example 36
Project: cantor   File: ObjectsResource.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON)
@Operation(summary = "Get all objects namespaces")
@ApiResponses(value = {
        @ApiResponse(responseCode = "200",
                description = "Provides the list of all namespaces",
                content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
        @ApiResponse(responseCode = "500", description = serverErrorMessage)
})
public Response getNamespaces() throws IOException {
    logger.info("received request for all objects namespaces");
    return Response.ok(parser.toJson(this.cantor.objects().namespaces())).build();
}
 
Example 37
Project: camel-quarkus   File: JsonValidatorResource.java    License: Apache License 2.0 5 votes vote down vote up
@Path("/validate-from-header")
@GET
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public String validateFromHeader(String json) {
    LOG.infof("Calling validateFromHeader with: %s", json);
    return producerTemplate.requestBodyAndHeader("direct:validate-json-from-header", null, "headerToValidate",
            json, String.class);
}
 
Example 38
Project: Hands-On-Enterprise-Java-Microservices-with-Eclipse-MicroProfile   File: Endpoint.java    License: MIT License 5 votes vote down vote up
@GET
@Path("/hello")
@Produces(MediaType.TEXT_PLAIN)
public String hello(@HeaderParam("user-agent") String userAgent) {
    tracer.activeSpan().setTag("user-agent", userAgent);
    return "hello";
}
 
Example 39
Project: sofa-registry   File: SessionDigestResource.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * return true mean push switch on
 */
@GET
@Path("pushSwitch")
@Produces(MediaType.APPLICATION_JSON)
public Map<String, Object> getPushSwitch() {
    Map<String, Object> resultMap = new HashMap<>(1);
    resultMap.put("pushSwitch", !sessionServerConfig.isStopPushSwitch() ? "open" : "closed");
    return resultMap;
}
 
Example 40
Project: camel-quarkus   File: CompressionResource.java    License: Apache License 2.0 5 votes vote down vote up
@Path("/compress/{format}")
@POST
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response zipfileCompress(@PathParam("format") String format, byte[] message) throws Exception {
    final byte[] response = producerTemplate.requestBody("direct:" + format + "-compress", message, byte[].class);
    return Response
            .created(new URI("https://camel.apache.org/"))
            .header("content-length", response.length)
            .entity(response)
            .build();
}