javax.ws.rs.Produces Java Examples

The following examples show how to use javax.ws.rs.Produces. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: VideosResource.java    From hmdm-server with Apache License 2.0 7 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 #2
Source File: SoapResource.java    From camel-quarkus with 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 #3
Source File: SettingsResource.java    From hmdm-server with 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 #4
Source File: FilesResource.java    From hmdm-server with 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 #5
Source File: MetricsResource.java    From metrics with 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 #6
Source File: ReactiveRestResourceTemplate.java    From kogito-runtimes with 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 #7
Source File: SetsResource.java    From cantor with 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 #8
Source File: ReactiveStreamsResource.java    From camel-quarkus with 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 #9
Source File: DeviceResource.java    From hmdm-server with 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 #10
Source File: ReactiveRestResourceTemplate.java    From kogito-runtimes with 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 #11
Source File: QueryStateInfoResource.java    From presto with 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 #12
Source File: SoapResource.java    From camel-quarkus with 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 #13
Source File: SettingsResource.java    From hmdm-server with 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
Source File: TaskResource.java    From presto with 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
Source File: DataDigestResource.java    From sofa-registry with 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
Source File: WebauthnService.java    From fido2 with 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
Source File: StorageResources.java    From Bats with 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
Source File: ProcessInstanceManagementResource.java    From kogito-runtimes with 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
Source File: StorageResources.java    From Bats with 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
Source File: CsvResource.java    From camel-quarkus with 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
Source File: MusicRestService.java    From micro-integrator with 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
Source File: RenewSwitchResource.java    From sofa-registry with 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
Source File: MusicRestService.java    From micro-integrator with 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
Source File: JtaResource.java    From camel-quarkus with 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
Source File: StramWebServices.java    From Bats with 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
Source File: XmlResource.java    From camel-quarkus with 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
Source File: Api.java    From apicurio-registry with 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
Source File: TestHttpRemoteTask.java    From presto with 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
Source File: BoardResource.java    From quarkus-coffeeshop-demo with 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
Source File: EntriesProxyResource.java    From browserup-proxy with 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));
}