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: 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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #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: 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 #13
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 #14
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 #15
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 #16
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 #17
Source File: WebauthnService.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
@POST
@Path("/" + Constants.RP_PREAUTHENTICATE_PATH)
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response preauthenticate(JsonObject input){
    try {
        // Get user input + basic input checking
        String username = getValueFromInput(Constants.RP_JSON_KEY_USERNAME, input);

        // Verify user exists
        if(!userdatabase.doesUserExist(username)){
            POCLogger.logp(Level.SEVERE, CLASSNAME, "preauthenticate", "POC-WS-ERR-1002", username);
            return generateResponse(Response.Status.NOT_FOUND, POCLogger.getMessageProperty("POC-WS-ERR-1002"));
        }

        String preauth = SKFSClient.preauthenticate(username);
        HttpSession session = request.getSession(true);
        session.setAttribute(Constants.SESSION_USERNAME, username);
        session.setAttribute(Constants.SESSION_ISAUTHENTICATED, false);
        return generateResponse(Response.Status.OK, preauth);
    } catch (Exception ex) {
        ex.printStackTrace();
        POCLogger.logp(Level.SEVERE, CLASSNAME, "preauthenticate", "POC-WS-ERR-1000", ex.getLocalizedMessage());
        return generateResponse(Response.Status.INTERNAL_SERVER_ERROR,
                POCLogger.getMessageProperty("POC-WS-ERR-1000"));
    }
}
 
Example #18
Source File: JsonDataformatsResource.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Path("jacksonxml/marshal")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_XML)
public String jacksonXmlMarshal(PojoA pojo) {
    return producerTemplate.requestBody("direct:jacksonxml-marshal", pojo, String.class);
}
 
Example #19
Source File: ReactiveRestResourceTemplate.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@GET()
@Produces(MediaType.APPLICATION_JSON)
public CompletionStage<List<$Type$Output>> getResources_$name$() {
    return CompletableFuture.supplyAsync(() -> {
        return process.instances().values().stream()
                .map(pi -> mapOutput(new $Type$Output(), pi.variables()))
             .collect(Collectors.toList());
    });   
}
 
Example #20
Source File: WorkflowResource.java    From hop with Apache License 2.0 5 votes vote down vote up
@GET
@Path( "/status/{id : .+}" )
@Produces( { MediaType.APPLICATION_JSON } )
public WorkflowStatus getWorkflowStatus( @PathParam( "id" ) String id ) {
  WorkflowStatus status = new WorkflowStatus();
  // find workflow
  IWorkflowEngine<WorkflowMeta> workflow = HopServerResource.getWorkflow( id );
  HopServerObjectEntry entry = HopServerResource.getHopServerObjectEntry( id );

  status.setId( entry.getId() );
  status.setName( entry.getName() );
  status.setStatus( workflow.getStatusDescription() );

  return status;
}
 
Example #21
Source File: QueuedStatementResource.java    From presto with Apache License 2.0 5 votes vote down vote up
@ResourceSecurity(PUBLIC)
@GET
@Path("queued/{queryId}/{slug}/{token}")
@Produces(APPLICATION_JSON)
public void getStatus(
        @PathParam("queryId") QueryId queryId,
        @PathParam("slug") String slug,
        @PathParam("token") long token,
        @QueryParam("maxWait") Duration maxWait,
        @Context UriInfo uriInfo,
        @Suspended AsyncResponse asyncResponse)
{
    Query query = getQuery(queryId, slug, token);

    // wait for query to be dispatched, up to the wait timeout
    ListenableFuture<?> futureStateChange = addTimeout(
            query.waitForDispatched(),
            () -> null,
            WAIT_ORDERING.min(MAX_WAIT_TIME, maxWait),
            timeoutExecutor);

    // when state changes, fetch the next result
    ListenableFuture<QueryResults> queryResultsFuture = Futures.transform(
            futureStateChange,
            ignored -> query.getQueryResults(token, uriInfo),
            responseExecutor);

    // transform to Response
    ListenableFuture<Response> response = Futures.transform(
            queryResultsFuture,
            queryResults -> Response.ok(queryResults).build(),
            directExecutor());
    bindAsyncResponse(asyncResponse, response, responseExecutor);
}
 
Example #22
Source File: CompressionResource.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Path("/uncompress/{format}")
@POST
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response zipfileUncompress(@PathParam("format") String format, byte[] message) throws Exception {
    final byte[] response = producerTemplate.requestBody("direct:" + format + "-uncompress", message, byte[].class);
    return Response
            .created(new URI("https://camel.apache.org/"))
            .header("content-length", response.length)
            .entity(response)
            .build();
}
 
Example #23
Source File: CustomerResource.java    From hmdm-server with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/{id}/edit")
@Produces(MediaType.APPLICATION_JSON)
public Response getCustomerForUpdate(@PathParam("id") Integer id) {
    try {
        final Customer customer = this.customerDAO.findByIdForUpdate(id);
        return Response.OK(customer);
    } catch (Exception e) {
        log.error("Unexpected error when loading customer details for update: #{}", id, e);
        return Response.INTERNAL_ERROR();
    }
}
 
Example #24
Source File: DeviceLogResource.java    From hmdm-server with Apache License 2.0 5 votes vote down vote up
@ApiOperation(
        value = "Upload logs",
        notes = "Uploads the list of log records from device to server",
        response = Response.class
)
@POST
@Path("/list/{deviceNumber}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response uploadLogs(@PathParam("deviceNumber") String deviceNumber,
                           List<UploadedDeviceLogRecord> logs,
                           @Context HttpServletRequest httpRequest) {
    logger.debug("#uploadLogs: {} => {}", deviceNumber, logs);
    try {
        final Device dbDevice = this.unsecureDAO.getDeviceByNumber(deviceNumber);
        if (dbDevice == null) {
            logger.error("Device {} was not found", deviceNumber);
            return Response.DEVICE_NOT_FOUND_ERROR();
        }

        SecurityContext.init(dbDevice.getCustomerId());
        try {
            if (this.pluginStatusCache.isPluginDisabled(PLUGIN_ID)) {
                logger.error("Rejecting request from device {} due to disabled plugin", deviceNumber);
                return Response.PLUGIN_DISABLED();
            }

            this.executor.submit(
                    new InsertDeviceLogRecordsTask(deviceNumber, httpRequest.getRemoteAddr(), logs, this.deviceLogDAO)
            );
            return Response.OK();
        } finally {
            SecurityContext.release();
        }
    } catch (Exception e) {
        logger.error("Unexpected error when handling uploaded log records", e);
        return Response.INTERNAL_ERROR();
    }
}
 
Example #25
Source File: StramWebServices.java    From Bats with Apache License 2.0 5 votes vote down vote up
@GET
@Path(PATH_LOGICAL_PLAN + "/attributes")
@Produces(MediaType.APPLICATION_JSON)
public JSONObject getApplicationAttributes(@QueryParam("attributeName") String attributeName)
{
  init();
  HashMap<String, String> map = new HashMap<>();
  for (Map.Entry<Attribute<?>, Object> entry : dagManager.getApplicationAttributes().entrySet()) {
    if (attributeName == null || entry.getKey().getSimpleName().equals(attributeName)) {
      Map.Entry<Attribute<Object>, Object> entry1 = (Map.Entry<Attribute<Object>, Object>)(Map.Entry)entry;
      map.put(entry1.getKey().getSimpleName(), entry1.getKey().codec.toString(entry1.getValue()));
    }
  }
  return new JSONObject(map);
}
 
Example #26
Source File: CompressionResource.java    From camel-quarkus with 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();
}
 
Example #27
Source File: SessionDigestResource.java    From sofa-registry with 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 #28
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 #29
Source File: NitriteResource.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Path("/load/component/nitrite")
@GET
@Produces(MediaType.TEXT_PLAIN)
public Response loadComponentNitrite() throws Exception {
    /* This is an autogenerated test */
    if (context.getComponent(COMPONENT_NITRITE) != null) {
        return Response.ok().build();
    }
    LOG.warnf("Could not load [%s] from the Camel context", COMPONENT_NITRITE);
    return Response.status(500, COMPONENT_NITRITE + " could not be loaded from the Camel context").build();
}
 
Example #30
Source File: ProfileResources.java    From Bats with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/profiles")
@Produces(MediaType.TEXT_HTML)
public Viewable getProfiles(@Context UriInfo uriInfo) {
  QProfiles profiles = getProfilesJSON(uriInfo);
  return ViewableWithPermissions.create(authEnabled.get(), "/rest/profile/list.ftl", sc, profiles);
}