javax.ws.rs.POST Java Examples

The following examples show how to use javax.ws.rs.POST. 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: XmlResource.java    From camel-quarkus with Apache License 2.0 7 votes vote down vote up
@Path("/html-transform")
@POST
@Consumes(MediaType.TEXT_HTML)
@Produces(MediaType.TEXT_PLAIN)
public String htmlTransform(String html) {
    LOG.debugf("Parsing HTML %s", html);
    return producerTemplate.requestBody(
            XmlRouteBuilder.DIRECT_HTML_TRANSFORM,
            html,
            String.class);
}
 
Example #2
Source File: PluginResource.java    From hmdm-server with Apache License 2.0 6 votes vote down vote up
/**
 * <p>Disables the specified plugins from usage for customer account associated with the current user.</p>
 *
 * @param pluginIds a list of IDs of plugins to be disabled.
 * @return empty response.
 */
@POST
@Path("/private/disabled")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response saveUsedPlugins(Integer[] pluginIds) {
    try {
        if (!SecurityContext.get().hasPermission("plugins_customer_access_management")) {
            logger.error("The user is not granted the 'plugins_customer_access_management' permission");
            return Response.PERMISSION_DENIED();
        }
        
        this.pluginDAO.saveDisabledPlugins(pluginIds);
        this.pluginStatusCache.setCustomerDisabledPlugins(SecurityContext.get().getCurrentUser().get().getCustomerId(), pluginIds);
        return Response.OK();
    } catch (Exception e) {
        logger.error("Unexpected error when disabling plugins", e);
        return Response.INTERNAL_ERROR();
    }
}
 
Example #3
Source File: GoogleSheetsResource.java    From camel-quarkus with Apache License 2.0 6 votes vote down vote up
@Path("/create")
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public Response createSheet(String title) throws Exception {
    SpreadsheetProperties sheetProperties = new SpreadsheetProperties();
    sheetProperties.setTitle(title);

    Spreadsheet sheet = new Spreadsheet();
    sheet.setProperties(sheetProperties);

    Spreadsheet response = producerTemplate.requestBody("google-sheets://spreadsheets/create?inBody=content", sheet,
            Spreadsheet.class);
    return Response
            .created(new URI("https://camel.apache.org/"))
            .entity(response.getSpreadsheetId())
            .build();
}
 
Example #4
Source File: QueryResources.java    From Bats with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/query")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_HTML)
public Viewable submitQuery(@FormParam("query") String query,
                            @FormParam("queryType") String queryType,
                            @FormParam("autoLimit") String autoLimit) throws Exception {
  try {
    final String trimmedQueryString = CharMatcher.is(';').trimTrailingFrom(query.trim());
    final QueryResult result = submitQueryJSON(new QueryWrapper(trimmedQueryString, queryType, autoLimit));
    List<Integer> rowsPerPageValues = work.getContext().getConfig().getIntList(ExecConstants.HTTP_WEB_CLIENT_RESULTSET_ROWS_PER_PAGE_VALUES);
    Collections.sort(rowsPerPageValues);
    final String rowsPerPageValuesAsStr = Joiner.on(",").join(rowsPerPageValues);
    return ViewableWithPermissions.create(authEnabled.get(), "/rest/query/result.ftl", sc, new TabularResult(result, rowsPerPageValuesAsStr));
  } catch (Exception | Error e) {
    logger.error("Query from Web UI Failed: {}", e);
    return ViewableWithPermissions.create(authEnabled.get(), "/rest/errorMessage.ftl", sc, e);
  }
}
 
Example #5
Source File: SqlResource.java    From camel-quarkus with Apache License 2.0 6 votes vote down vote up
@Path("/post")
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public Response createCamel(String species) throws Exception {
    Map<String, Object> params = new HashMap<>();
    params.put("species", species);

    producerTemplate.requestBodyAndHeaders(
            "sql:INSERT INTO camel (species) VALUES (:#species)", null,
            params);

    return Response
            .created(new URI("https://camel.apache.org/"))
            .build();
}
 
Example #6
Source File: DeviceLogResource.java    From hmdm-server with Apache License 2.0 6 votes vote down vote up
/**
 * <p>Gets the list of device log records matching the specified filter.</p>
 *
 * @param filter a filter to be used for filtering the records.
 * @return a response with list of device log records matching the specified filter.
 */
@ApiOperation(
        value = "Search logs",
        notes = "Gets the list of log records matching the specified filter",
        response = PaginatedData.class,
        authorizations = {@Authorization("Bearer Token")}
)
@POST
@Path("/private/search")
@Produces(MediaType.APPLICATION_JSON)
public Response getLogs(DeviceLogFilter filter) {
    try {
        List<DeviceLogRecord> records = this.deviceLogDAO.findAll(filter);
        long count = this.deviceLogDAO.countAll(filter);

        return Response.OK(new PaginatedData<>(records, count));
    } catch (Exception e) {
        logger.error("Failed to search the log records due to unexpected error. Filter: {}", filter, e);
        return Response.INTERNAL_ERROR();
    }
}
 
Example #7
Source File: PersistentDataResource.java    From sofa-registry with Apache License 2.0 6 votes vote down vote up
@POST
@Path("remove")
@Produces(MediaType.APPLICATION_JSON)
public Result remove(PersistenceData data) {

    checkObj(data, "PersistenceData");
    checkObj(data.getVersion(), "version");

    String dataInfoId = DataInfo.toDataInfoId(data.getDataId(), data.getInstanceId(),
        data.getGroup());

    try {
        boolean ret = persistenceDataDBService.remove(dataInfoId);
        DB_LOGGER.info("remove Persistence Data {} from DB result {}!", data, ret);
    } catch (Exception e) {
        DB_LOGGER.error("error remove Persistence Data {} from DB!", data);
        throw new RuntimeException("Remove Persistence Data " + data + " from DB error!");
    }

    fireDataChangeNotify(data.getVersion(), dataInfoId, DataOperator.REMOVE);

    Result result = new Result();
    result.setSuccess(true);
    return result;
}
 
Example #8
Source File: RuleQueryController.java    From Qualitis with Apache License 2.0 6 votes vote down vote up
@POST
@Path("query")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public GeneralResponse<?> query(RuleQueryRequest param, @Context HttpServletRequest request) {
  if (param == null) {
    param = new RuleQueryRequest();
  }
  // Get login user
  param.setUser(HttpUtils.getUserName(request));
  try {
    List<RuleQueryProject> results = ruleQueryService.query(param);
    LOG.info("[My DataSource] Query successfully. The number of results:{}", results == null ? 0 : results.size());
    return new GeneralResponse<>("200", "{&QUERY_SUCCESSFULLY}", results);
  } catch (Exception e) {
    LOG.error("[My DataSource] Query failed, internal error.", e);
    return new GeneralResponse<>("500", e.getMessage(), null);
  }
}
 
Example #9
Source File: AuthenticateResource.java    From clouditor with Apache License 2.0 6 votes vote down vote up
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response login(LoginRequest request) {
  var payload = new LoginResponse();

  if (!service.verifyLogin(request)) {
    throw new NotAuthorizedException("Invalid user and/or password");
  }

  var user = PersistenceManager.getInstance().getById(User.class, request.getUsername());

  payload.setToken(service.createToken(user));

  // TODO: max age, etc.
  return Response.ok(payload).cookie(new NewCookie("authorization", payload.getToken())).build();
}
 
Example #10
Source File: ClientsOpenResource.java    From sofa-registry with Apache License 2.0 6 votes vote down vote up
/**
 * Client off common response.
 *
 * @param request the request  
 * @return the common response
 */
@POST
@Path("/off")
public CommonResponse clientOff(CancelAddressRequest request) {

    if (null == request) {
        return CommonResponse.buildFailedResponse("Request can not be null.");
    }

    if (CollectionUtils.isEmpty(request.getConnectIds())) {
        return CommonResponse.buildFailedResponse("ConnectIds can not be null.");
    }

    final List<String> connectIds = request.getConnectIds();
    sessionRegistry.cancel(connectIds);
    return CommonResponse.buildSuccessResponse();
}
 
Example #11
Source File: AuditResource.java    From hmdm-server with Apache License 2.0 6 votes vote down vote up
/**
 * <p>Gets the list of audit log records matching the specified filter.</p>
 *
 * @param filter a filter to be used for filtering the records.
 * @return a response with list of audit log records matching the specified filter.
 */
@ApiOperation(
        value = "Search logs",
        notes = "Gets the list of audit log records matching the specified filter",
        response = PaginatedData.class,
        authorizations = {@Authorization("Bearer Token")}
)
@POST
@Path("/private/log/search")
@Produces(MediaType.APPLICATION_JSON)
public Response getLogs(AuditLogFilter filter) {
    try {
        List<AuditLogRecord> records = this.auditDAO.findAll(filter);
        long count = this.auditDAO.countAll(filter);

        return Response.OK(new PaginatedData<>(records, count));
    } catch (Exception e) {
        logger.error("Failed to search the audit log records due to unexpected error. Filter: {}", filter, e);
        return Response.INTERNAL_ERROR();
    }
}
 
Example #12
Source File: ProtobufResource.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Path("/unmarshal")
@POST
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
@Produces(MediaType.APPLICATION_JSON)
public String unmarshal(byte[] body) {
    final Person person = producerTemplate.requestBody("direct:protobuf-unmarshal", body, Person.class);
    return "{\"name\": \"" + person.getName() + "\",\"id\": " + person.getId() + "}";
}
 
Example #13
Source File: AzureBlobResource.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Path("/blob/create")
@POST
@Consumes(MediaType.TEXT_PLAIN)
public Response createBlob(String message) throws Exception {
    BlobBlock blob = new BlobBlock(new ByteArrayInputStream(message.getBytes(StandardCharsets.UTF_8)));
    producerTemplate.sendBody(
            "azure-blob://devstoreaccount1/camel-test/test?operation=uploadBlobBlocks&azureBlobClient=#azureBlobClient&validateClientURI=false",
            blob);
    return Response.created(new URI("https://camel.apache.org/")).build();
}
 
Example #14
Source File: JaxbResource.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Path("/marshal-lastname")
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_XML)
public Response marshallLastName(String name) throws Exception {
    Person p = new Person();
    p.setLastName(name);

    String response = producerTemplate.requestBody("direct:marshal-2", p, String.class);
    LOG.infof("Got response from jaxb=>: %s", response);
    return Response
            .created(new URI("https://camel.apache.org/"))
            .entity(response)
            .build();
}
 
Example #15
Source File: SftpResource.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Path("/create/{fileName}")
@POST
@Consumes(MediaType.TEXT_PLAIN)
public Response createFile(@PathParam("fileName") String fileName, String fileContent)
        throws Exception {
    producerTemplate.sendBodyAndHeader("sftp://admin@localhost:{{camel.sftp.test-port}}/sftp?password=admin", fileContent,
            Exchange.FILE_NAME, fileName);
    return Response
            .created(new URI("https://camel.apache.org/"))
            .build();
}
 
Example #16
Source File: WebauthnService.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
@POST
@Path("/" + Constants.RP_PREGISTER_PATH)
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response preregister(JsonObject input){
    try{
        //Get user input + basic input checking
        String username = getValueFromInput(Constants.RP_JSON_KEY_USERNAME, input);
        String displayName = getValueFromInput(Constants.RP_JSON_KEY_DISPLAYNAME, input);

        //Verify User does not already exist
        if (!doesAccountExists(username)){
            String prereg = SKFSClient.preregister(username, displayName);
            HttpSession session = request.getSession(true);
            session.setAttribute(Constants.SESSION_USERNAME, username);
            session.setAttribute(Constants.SESSION_ISAUTHENTICATED, false);
            session.setMaxInactiveInterval(Constants.SESSION_TIMEOUT_VALUE);
            return generateResponse(Response.Status.OK, prereg);
        }
        else{
            //If the user already exists, throw an error
            WebauthnTutorialLogger.logp(Level.SEVERE, CLASSNAME, "preregister", "WEBAUTHN-WS-ERR-1001", username);
            return generateResponse(Response.Status.CONFLICT,
                    WebauthnTutorialLogger.getMessageProperty("WEBAUTHN-WS-ERR-1001"));
        }
    }
    catch(Exception ex){
        ex.printStackTrace();
        WebauthnTutorialLogger.logp(Level.SEVERE, CLASSNAME, "preregister", "WEBAUTHN-WS-ERR-1000", ex.getLocalizedMessage());
        return generateResponse(Response.Status.INTERNAL_SERVER_ERROR,
                WebauthnTutorialLogger.getMessageProperty("WEBAUTHN-WS-ERR-1000"));
    }
}
 
Example #17
Source File: JsonDataformatsResource.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Path("/out-a")
@POST
@Produces(MediaType.TEXT_PLAIN)
public String testPojoA(@QueryParam("json-component") String jsonComponent) {
    LOG.infof("Invoking testPojoA(%s)", jsonComponent);
    return consumerTemplate.receive("vm:" + jsonComponent + "-out-a").getMessage().getBody().toString();
}
 
Example #18
Source File: MusicRestService.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
@POST
@Path("/add_singer_details")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response addSingerDetailsInJSONPOST(Singer singer) {

    musicService.setSinger(singer);

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

}
 
Example #19
Source File: CafeResource.java    From jakartaee-azure with MIT License 5 votes vote down vote up
@POST
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response createCoffee(Coffee coffee) {
	try {
		coffee = this.cafeRepository.persistCoffee(coffee);
		return Response.created(URI.create("/" + coffee.getId())).build();
	} catch (PersistenceException e) {
		logger.log(Level.SEVERE, "Error creating coffee {0}: {1}.", new Object[] { coffee, e });
		throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR);
	}
}
 
Example #20
Source File: MustacheResource.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Path("/templateFromRegistry")
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public String templateFromRegistry(String message) {
    LOG.infof("Calling templateFromRegistry with %s", message);
    return template.requestBody("mustache://ref:templateFromRegistry", message, String.class);
}
 
Example #21
Source File: WebUiStaticResource.java    From presto with Apache License 2.0 5 votes vote down vote up
@ResourceSecurity(WEB_UI)
@POST
@Path("/ui/{path: .*}")
public Response postFile(@PathParam("path") String path)
{
    // The "getFile" resource method matches all GET requests, and without a
    // resource for POST requests, a METHOD_NOT_ALLOWED error will be returned
    // instead of a NOT_FOUND error
    return Response.status(NOT_FOUND).build();
}
 
Example #22
Source File: JmsResource.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Path("/paho-ws/{queueName}")
@POST
@Consumes(MediaType.TEXT_PLAIN)
public Response producePahoMessageWs(@PathParam("queueName") String queueName, String message) throws Exception {
    producerTemplate.sendBody("paho:" + queueName + "?retained=true&brokerUrl={{broker-url.ws}}", message);
    return Response.created(new URI("https://camel.apache.org/")).build();
}
 
Example #23
Source File: FhirR5Resource.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Path("/fhir2json")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response fhir2json(String patient) throws Exception {
    try (InputStream response = producerTemplate.requestBody("direct:json-to-r5", patient, InputStream.class)) {
        return Response
                .created(new URI("https://camel.apache.org/"))
                .entity(response)
                .build();
    }
}
 
Example #24
Source File: WebauthnService.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
@POST
@Path("/" + Constants.RP_AUTHENTICATE_PATH)
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response authenticate(JsonObject input){
    try {
        HttpSession session = request.getSession(false);
        if (session == null) {
            POCLogger.logp(Level.SEVERE, CLASSNAME, "authenticate", "POC-WS-ERR-1003", "");
            return generateResponse(Response.Status.FORBIDDEN, POCLogger.getMessageProperty("POC-WS-ERR-1003"));
        }

        String username = (String) session.getAttribute(Constants.SESSION_USERNAME);
        if (doesAccountExist(username)) {
            String authresponse = SKFSClient.authenticate(username, getOrigin(), input);
            session.setAttribute("username", username);
            session.setAttribute("isAuthenticated", true);
            return generateResponse(Response.Status.OK, getResponseFromSKFSResponse(authresponse));
        } else {
            POCLogger.logp(Level.SEVERE, CLASSNAME, "authenticate", "POC-WS-ERR-1002", username);
            return generateResponse(Response.Status.CONFLICT, POCLogger.getMessageProperty("POC-WS-ERR-1002"));
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        POCLogger.logp(Level.SEVERE, CLASSNAME, "authenticate", "POC-WS-ERR-1000", ex.getLocalizedMessage());
        return generateResponse(Response.Status.INTERNAL_SERVER_ERROR,
                POCLogger.getMessageProperty("POC-WS-ERR-1000"));
    }
}
 
Example #25
Source File: CafeResource.java    From jakartaee-azure with MIT License 5 votes vote down vote up
@POST
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public Coffee createCoffee(Coffee coffee) {
	try {
		return this.cafeRepository.persistCoffee(coffee);
	} catch (PersistenceException e) {
		logger.log(Level.SEVERE, "Error creating coffee {0}: {1}.", new Object[] { coffee, e });
		throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR);
	}
}
 
Example #26
Source File: AccountsResource.java    From clouditor with Apache License 2.0 5 votes vote down vote up
@POST
@Path("discover/{provider}")
public CloudAccount discover(@PathParam("provider") String provider) {
  provider = sanitize(provider);

  var account = this.service.discover(provider);

  if (account == null) {
    throw new NotFoundException();
  }

  return account;
}
 
Example #27
Source File: TelegramResource.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Path("/stop-location")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response stopLocation(StopMessageLiveLocationMessage message) throws Exception {
    producerTemplate.requestBody(String.format("telegram://bots?chatId=%s", chatId), message);
    log.infof("Sent a message to telegram %s", message);
    return Response
            .created(new URI(String.format("https://telegram.org/")))
            .build();
}
 
Example #28
Source File: DrillRoot.java    From Bats with Apache License 2.0 5 votes vote down vote up
@POST
@Path("/shutdown")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed(ADMIN_ROLE)
public Response shutdownForcefully() throws Exception {
  drillbit.setForcefulShutdown(true);
  String resp = "Forceful shutdown request is triggered";
  return shutdown(resp);
}
 
Example #29
Source File: JsonDataformatsResource.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Path("/unmarshal/{direct-id}")
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON)
public String testXmlUnmarshalDefinition(@PathParam("direct-id") String directId, String statement) {
    LOG.infof("Invoking testXmlUnmarshalDefinition(%s, %s)", directId, statement);
    Object object = producerTemplate.requestBody("direct:" + directId, statement);
    String answer = JsonbBuilder.create().toJson(object);

    return answer;
}
 
Example #30
Source File: GoogleCalendarResource.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Path("/create")
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public Response createCalendar(String summary) throws Exception {
    Calendar calendar = new Calendar();
    calendar.setSummary(summary);
    calendar.setTimeZone("Europe/London");
    Calendar response = producerTemplate.requestBody("google-calendar://calendars/insert?inBody=content", calendar,
            Calendar.class);
    return Response
            .created(new URI("https://camel.apache.org/"))
            .entity(response.getId())
            .build();
}