Java Code Examples for javax.ws.rs.POST

The following are top voted examples for showing how to use javax.ws.rs.POST. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: syndesis   File: Validating.java   View source code 7 votes vote down vote up
@POST
@Path(value = "/validation")
@Consumes("application/json")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses({//
    @ApiResponse(code = 204, message = "All validations pass"), //
    @ApiResponse(code = 400, message = "Found violations in validation", responseContainer = "Set",
        response = Violation.class)//
})
default Response validate(@NotNull final T obj) {
    final Set<ConstraintViolation<T>> constraintViolations = getValidator().validate(obj, AllValidations.class);

    if (constraintViolations.isEmpty()) {
        return Response.noContent().build();
    }

    throw new ConstraintViolationException(constraintViolations);
}
 
Example 2
Project: osc-core   File: ManagerConnectorApis.java   View source code 6 votes vote down vote up
@ApiOperation(value = "Creates an Manager Connector",
        notes = "Creates an Manager Connector and sync's it immediately.<br/> "
                + "If we are unable to connect to the manager using the credentials provided, this call will fail.<br/>"
                + "To skip validation of IP and credentials 'skipRemoteValidation' flag can be used.",
        response = BaseJobResponse.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Successful operation"), @ApiResponse(code = 400,
        message = "In case of any error validating the information",
        response = ErrorCodeDto.class) })
@POST
public Response createApplianceManagerConnector(@Context HttpHeaders headers,
                                                @ApiParam(required = true) ApplianceManagerConnectorRequest amcRequest) {

    logger.info("Creating Appliance Manager Connector...");
    this.userContext.setUser(OscAuthFilter.getUsername(headers));
    Response responseForBaseRequest = this.apiUtil.getResponseForBaseRequest(this.addService,
                new DryRunRequest<>(amcRequest, amcRequest.isSkipRemoteValidation()));
    return responseForBaseRequest;
}
 
Example 3
Project: dremio-oss   File: UserResource.java   View source code 6 votes vote down vote up
@RolesAllowed({"admin", "user"})
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public UserUI updateUser(UserForm userForm, @PathParam("userName") UserName userName)
  throws IOException, IllegalArgumentException, NamespaceException, UserNotFoundException, DACUnauthorizedException {
  checkUser(userName, "update");
  User userConfig = userForm.getUserConfig();
  if (userConfig != null && userConfig.getUserName() != null && !userConfig.getUserName().equals(userName.getName())) {
    final UserName newUserName = new UserName(userForm.getUserConfig().getUserName());
    userConfig = userService.updateUserName(userName.getName(),
      newUserName.getName(),
      userConfig, userForm.getPassword());
    // TODO: rename home space and all uploaded files along with it
    // new username
    return new UserUI(new UserResourcePath(newUserName), newUserName, userConfig);
  } else {
    User newUser = SimpleUser.newBuilder(userForm.getUserConfig()).setUserName(userName.getName()).build();
    newUser = userService.updateUser(newUser, userForm.getPassword());
    return new UserUI(new UserResourcePath(userName), userName, newUser);
  }
}
 
Example 4
Project: plugin-prov   File: ImportCatalogResource.java   View source code 6 votes vote down vote up
/**
 * Update the catalog prices of related provider. Asynchronous operation.
 * 
 * @param node
 *            The node (provider) to update.
 * @return The catalog status.
 */
@POST
@Path("catalog/{node:service:prov:.+}")
public ImportCatalogStatus updateCatalog(@PathParam("node") final String node) {
	final Node entity = nodeResource.checkWritableNode(node).getTool();
	final ImportCatalogService catalogService = locator.getResource(entity.getId(), ImportCatalogService.class);
	final ImportCatalogStatus task = startTask(entity.getId(), t -> {
		t.setLocation(null);
		t.setNbInstancePrices(null);
		t.setNbInstanceTypes(null);
		t.setNbStorageTypes(null);
		t.setWorkload(0);
		t.setDone(0);
		t.setPhase(null);
	});
	final String user = securityHelper.getLogin();
	// The import execution will done into another thread
	Executors.newSingleThreadExecutor().submit(() -> {
		Thread.sleep(50);
		securityHelper.setUserName(user);
		updateCatalog(catalogService, entity.getId());
		return null;
	});
	return task;
}
 
Example 5
Project: jersey-jwt-springsecurity   File: AuthenticationResource.java   View source code 6 votes vote down vote up
/**
 * Validate user credentials and issue a token for the user.
 *
 * @param credentials
 * @return
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response authenticate(UserCredentials credentials) {

    Authentication authenticationRequest =
            new UsernamePasswordAuthenticationToken(credentials.getUsername(), credentials.getPassword());
    Authentication authenticationResult = authenticationManager.authenticate(authenticationRequest);
    SecurityContextHolder.getContext().setAuthentication(authenticationResult);

    String username = SecurityContextHolder.getContext().getAuthentication().getName();
    Set<Authority> authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities().stream()
            .map(grantedAuthority -> Authority.valueOf(grantedAuthority.toString()))
            .collect(Collectors.toSet());

    String token = authenticationTokenService.issueToken(username, authorities);
    AuthenticationToken authenticationToken = new AuthenticationToken();
    authenticationToken.setToken(token);

    return Response.ok(authenticationToken).build();
}
 
Example 6
Project: lemon   File: AndroidDeviceResource.java   View source code 6 votes vote down vote up
@POST
@Path("checkLogin")
@Produces(MediaType.APPLICATION_JSON)
public BaseDTO checkLogin(@HeaderParam("sessionId") String sessionId) {
    logger.info("sessionId : {}", sessionId);

    PimDevice pimDevice = pimDeviceManager.findUniqueBy("sessionId",
            sessionId);
    logger.info("pimDevice : {}", pimDevice);

    if (pimDevice == null) {
        return null;
    }

    BaseDTO result = new BaseDTO();

    result.setCode(200);

    return result;
}
 
Example 7
Project: wechat-mall   File: IndexResource.java   View source code 6 votes vote down vote up
@POST
@Path("register")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String register(@FormParam("userName") String userName,
		@FormParam("password") String password,
		@FormParam("phone") Long phone, @FormParam("email") String email,
		@FormParam("nick") String nick, @FormParam("addr") String addr,
		@FormParam("gender") String gender) {
	// check not null
	User u = new User();// dao 应该查询
	u.setAddr(addr);
	u.setEmail(email);
	u.setGender(gender);
	u.setNick(nick);
	u.setPassword(password);
	u.setPhone(phone);
	u.setUsername(userName);
	return JsonUtil.bean2Json(u);
}
 
Example 8
Project: comms-router   File: PlanResource.java   View source code 6 votes vote down vote up
@POST
@Path("{resourceId}")
@ApiOperation(
    value = "Update an existing Plan",
    notes = "Update some properties of an existing Plan")
@ApiResponses({
    @ApiResponse(code = 204, message = "Successful operation"),
    @ApiResponse(code = 400, message = "Invalid ID supplied",
        response = ExceptionPresentation.class),
    @ApiResponse(code = 404, message = "Plan not found",
        response = ExceptionPresentation.class),
    @ApiResponse(code = 405, message = "Validation exception",
        response = ExceptionPresentation.class)})
public void update(
    @ApiParam(value = "ID of the plan to be updated") @PathParam("resourceId") String resourceId,
    @ApiParam(value = "UpdatePlanArg object representing parameters of the Plan to be updated",
        required = true) UpdatePlanArg planArg)
    throws CommsRouterException {

  LOGGER.debug("Updating plan {}", planArg);

  RouterObjectRef objectId =
      RouterObjectRef.builder().setRef(resourceId).setRouterRef(routerRef).build();

  planService.update(planArg, objectId);
}
 
Example 9
Project: dust-api   File: DeviceSlackResource.java   View source code 6 votes vote down vote up
/**
 * Slack command endpoint. This is where the application is receiving slash commands from Slack
 * and returning synchronous responses to them.
 *
 * @param params parameters posted from Slack
 * @return synchronous response for the command
 */
@Path("/command")
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public SlackCommandResponse receiveSlackCommand(final MultivaluedMap<String, String> params) {
    LOGGER.debug("Received Slack command: {}", params);
    final String token = params.getFirst("token");
    if (slackConfig().getCommandVerificationTokens().contains(token)) {
        final String command = params.getFirst("command");
        switch (command) {
            case LIST_COMMAND:
                return listDevices();
            case SHOW_COMMAND:
                return showDevice(params);
            case CLAIM_COMMAND:
                return claim(params);
            case UNCLAIM_COMMAND:
                return unclaim(params);
            default:
                throw new IllegalArgumentException("Unknown command: " + command);
        }
    } else {
        throw new IllegalStateException("Token error");
    }
}
 
Example 10
Project: opencps-v2   File: RegistrationManagement.java   View source code 6 votes vote down vote up
@POST
@Path("/registrations/applicant/{applicantNo}/agency/{agencyNo}/forms/{formNo}")
@Consumes({ MediaType.APPLICATION_FORM_URLENCODED })
@Produces({ MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN })
@ApiOperation(value = "Get list dataform by applicantNo, agencyNo and formNo")
@ApiResponses(value = {
		@ApiResponse (code = HttpURLConnection.HTTP_OK, message = "Return a list dataform"),
		@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not Found", response = ExceptionModel.class),
		@ApiResponse (code = HttpURLConnection.HTTP_FORBIDDEN, message = "Accsess denied", response = ExceptionModel.class) })
public Response getDataFormByFormNo (@Context HttpServletRequest request, @Context HttpHeaders header, @Context Company company,
		@Context Locale locale, @Context User user, @Context ServiceContext serviceContext,
		@ApiParam(value = "id for applicant", required = true) @PathParam("applicantNo") String applicantNo,
		@ApiParam(value = "id for agency", required = true) @PathParam("agencyNo") String agencyNo,
		@ApiParam(value = "id for forms", required = true) @PathParam("formNo") String formNo, 
		@FormParam("keyword") String keyword);
 
Example 11
Project: presto-manager   File: ControllerPackageAPI.java   View source code 6 votes vote down vote up
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
@ApiOperation(value = "Upgrade Presto")
@ApiResponses(value = {
        @ApiResponse(code = 207, message = "Multiple responses available"),
        @ApiResponse(code = 400, message = "Request contains invalid parameters")})
public Response upgrade(String urlToFetchPackage,
        @QueryParam("checkDependencies") @DefaultValue("true") boolean checkDependencies,
        @QueryParam("forceUpgrade") @DefaultValue("false") boolean forceUpgrade,
        @QueryParam("preserveConfig") @DefaultValue("true") boolean preserveConfig,
        @QueryParam("scope") String scope,
        @QueryParam("nodeId") List<String> nodeId)
{
    ApiRequester.Builder apiRequester = requesterBuilder(ControllerPackageAPI.class)
            .httpMethod(POST)
            .accept(MediaType.TEXT_PLAIN)
            .entity(Entity.entity(urlToFetchPackage, MediaType.TEXT_PLAIN));

    optionalQueryParam(apiRequester, "checkDependencies", checkDependencies);
    optionalQueryParam(apiRequester, "preserveConfig", preserveConfig);
    optionalQueryParam(apiRequester, "forceUpgrade", forceUpgrade);

    return forwardRequest(scope, apiRequester.build(), nodeId);
}
 
Example 12
Project: athena   File: FlowsWebResource.java   View source code 6 votes vote down vote up
/**
 * Creates new flow rules. Creates and installs a new flow rules.<br>
 * Instructions description:
 * https://wiki.onosproject.org/display/ONOS/Flow+Rule+Instructions
 * <br>
 * Criteria description:
 * https://wiki.onosproject.org/display/ONOS/Flow+Rule+Criteria
 *
 * @param stream flow rules JSON
 * @return status of the request - CREATED if the JSON is correct,
 * BAD_REQUEST if the JSON is invalid
 * @onos.rsModel FlowsBatchPost
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createFlows(@QueryParam("appId") String appId, InputStream stream) {
    try {
        ObjectNode jsonTree = (ObjectNode) mapper().readTree(stream);
        ArrayNode flowsArray = (ArrayNode) jsonTree.get(FLOWS);

        if (appId != null) {
            flowsArray.forEach(flowJson -> ((ObjectNode) flowJson).put("appId", appId));
        }

        List<FlowRule> rules = codec(FlowRule.class).decode(flowsArray, this);
        service.applyFlowRules(rules.toArray(new FlowRule[rules.size()]));
        rules.forEach(flowRule -> {
            ObjectNode flowNode = mapper().createObjectNode();
            flowNode.put(DEVICE_ID, flowRule.deviceId().toString())
                    .put(FLOW_ID, flowRule.id().value());
            flowsNode.add(flowNode);
        });
    } catch (IOException ex) {
        throw new IllegalArgumentException(ex);
    }
    return Response.ok(root).build();
}
 
Example 13
Project: athena   File: TenantWebResource.java   View source code 6 votes vote down vote up
/**
 * Creates a tenant with the given tenant identifier.
 *
 * @param stream TenantId JSON stream
 * @return status of the request - CREATED if the JSON is correct,
 * BAD_REQUEST if the JSON is invalid
 * @onos.rsModel TenantId
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response addTenantId(InputStream stream) {
    try {
        final TenantId tid = getTenantIdFromJsonStream(stream);
        vnetAdminService.registerTenantId(tid);
        final TenantId resultTid = getExistingTenantId(vnetAdminService, tid);
        UriBuilder locationBuilder = uriInfo.getBaseUriBuilder()
                .path("tenants")
                .path(resultTid.id());
        return Response
                .created(locationBuilder.build())
                .build();
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example 14
Project: plugin-prov   File: ProvQuoteInstanceResource.java   View source code 6 votes vote down vote up
/**
 * Upload a file of quote in add mode.
 * 
 * @param subscription
 *            The subscription identifier, will be used to filter the locations
 *            from the associated provider.
 * @param uploadedFile
 *            Instance entries files to import. Currently support only CSV
 *            format.
 * @param columns
 *            the CSV header names.
 * @param term
 *            The default {@link ProvInstancePriceTerm} used when no one is
 *            defined in the CSV line
 * @param ramMultiplier
 *            The multiplier for imported RAM values. Default is 1.
 * @param encoding
 *            CSV encoding. Default is UTF-8.
 * @throws IOException
 *             When the CSV stream cannot be written.
 */
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("{subscription:\\d+}/upload")
public void upload(@PathParam("subscription") final int subscription, @Multipart(value = "csv-file") final InputStream uploadedFile,
		@Multipart(value = "columns", required = false) final String[] columns,
		@Multipart(value = "term", required = false) final String term,
		@Multipart(value = "memoryUnit", required = false) final Integer ramMultiplier,
		@Multipart(value = "encoding", required = false) final String encoding) throws IOException {
	subscriptionResource.checkVisibleSubscription(subscription).getNode().getId();

	// Check column's name validity
	final String[] sanitizeColumns = ArrayUtils.isEmpty(columns) ? DEFAULT_COLUMNS : columns;
	checkHeaders(ACCEPTED_COLUMNS, sanitizeColumns);

	// Build CSV header from array
	final String csvHeaders = StringUtils.chop(ArrayUtils.toString(sanitizeColumns)).substring(1).replace(',', ';') + "\n";

	// Build entries
	final String safeEncoding = ObjectUtils.defaultIfNull(encoding, StandardCharsets.UTF_8.name());
	csvForBean
			.toBean(InstanceUpload.class, new InputStreamReader(
					new SequenceInputStream(new ByteArrayInputStream(csvHeaders.getBytes(safeEncoding)), uploadedFile), safeEncoding))
			.stream().filter(Objects::nonNull).forEach(i -> persist(i, subscription, term, ramMultiplier));
}
 
Example 15
Project: MaximoForgeViewerPlugin   File: ForgeRS.java   View source code 6 votes vote down vote up
@POST
   @Produces(MediaType.APPLICATION_JSON)
   @Path("bubble")
   @Consumes("*/*") 
   public Response bubbleDetails(
   	@Context HttpServletRequest request,
   	InputStream is
) 
	throws IOException, 
	       URISyntaxException 
   {
   	APIImpl impl = getAPIImpl( request );
   	if( impl == null )
   	{
           return Response.status( Response.Status.UNAUTHORIZED ).build();     
   	}
   	String urn = stream2string( is );
   	Result result = impl.viewableQuery( urn );
   	return formatReturn( result );
   }
 
Example 16
Project: verify-service-provider   File: TranslateSamlResponseResource.java   View source code 6 votes vote down vote up
@POST
public Response translateResponse(@NotNull @Valid TranslateSamlResponseBody translateSamlResponseBody) throws IOException {
    String entityId = entityIdService.getEntityId(translateSamlResponseBody);
    try {
        TranslatedResponseBody translatedResponseBody = responseService.convertTranslatedResponseBody(
            translateSamlResponseBody.getSamlResponse(),
            translateSamlResponseBody.getRequestId(),
            translateSamlResponseBody.getLevelOfAssurance(),
            entityId
        );

        LOG.info(String.format("Translated response for entityId: %s, requestId: %s, got Scenario: %s",
                entityId,
                translateSamlResponseBody.getRequestId(),
                translatedResponseBody.getScenario()));

        return Response.ok(translatedResponseBody).build();
    } catch (SamlResponseValidationException | SamlTransformationErrorException e) {
        LOG.warn(String.format("Error translating saml response for entityId: %s, requestId: %s, got Message: %s", entityId, translateSamlResponseBody.getRequestId(), e.getMessage()));
        return Response
            .status(BAD_REQUEST)
            .entity(new ErrorMessage(BAD_REQUEST.getStatusCode(), e.getMessage()))
            .build();
    }
}
 
Example 17
Project: acmeair-modular   File: BookingsREST.java   View source code 6 votes vote down vote up
@POST
@Consumes({"application/x-www-form-urlencoded"})
@Path("/cancelbooking")
@Produces("text/plain")
public Response cancelBookingsByNumber(
		@FormParam("number") String number,
		@FormParam("userid") String userid) {
	try {
		bs.cancelBooking(userid, number);
		return Response.ok("booking " + number + " deleted.").build();
				
	}
	catch (Exception e) {
		e.printStackTrace();
		return Response.status(Status.INTERNAL_SERVER_ERROR).build();
	}
}
 
Example 18
Project: plugin-bt-jira   File: JiraImportPluginResource.java   View source code 6 votes vote down vote up
/**
 * Clear JIRA Cache.
 * 
 * @see "http://localhost:6080/plugins/servlet/scriptrunner/builtin?section=builtin_scripts#"
 * @see "https://marketplace.atlassian.com/plugins/com.onresolve.jira.groovy.groovyrunner"
 */
protected boolean clearJiraCache(final ImportContext context, final ImportStatus result, final CurlProcessor processor) {
	if (result.getScriptRunner()) {
		final List<CurlRequest> requests = new ArrayList<>();
		final String url = context.parameters.get(PARAMETER_URL) + "/secure/admin/groovy/CannedScriptRunner.jspa";
		requests.add(new CurlRequest(HttpMethod.POST, url,
				"cannedScript=com.onresolve.jira.groovy.canned.admin.ClearCaches" + "&cannedScriptArgs_FIELD_WHICH_CACHE=jira"
						+ "&cannedScriptArgs_Hidden_FIELD_WHICH_CACHE=jira" + "&cannedScriptArgs_Hidden_output=Cache+cleared."
						+ "&cannedScript=com.onresolve.jira.groovy.canned.admin.ClearCaches&id="
						+ "&atl_token=B3WY-Y7OK-4J8S-4GH4%7Ca2a4f45ffb53fcf8fbb12453e587949470377ec7%7Clin" + "&RunCanned=Run"
						+ "&webSudoIsPost=true&os_cookie=true",
				"Accept:application/json, text/javascript, */*; q=0.01"));
		return processor.process(requests);
	}
	return false;
}
 
Example 19
Project: sierra   File: GraphQLService.java   View source code 6 votes vote down vote up
@POST
public Response execute(String x) {
	GraphQLRequest request = Json.loads(x, GraphQLRequest.class);
	String query = request.query;
	Object context = null;
	Map<String, Object> arguments = request.variables;
	if (query == null) { query = ""; }
	if (arguments == null) {arguments = Collections.emptyMap(); }
	ExecutionResult result = graphql
		.execute(query, context, arguments);
	List<Object> errors = handleErrors(result);
	Map<String, Object> output = new LinkedHashMap<>();
	Status status = Status.OK;
	if (!errors.isEmpty()) {
		// react-relay rejected when
		// key "errors" presented even it's empty
		output.put("errors", errors);
		status = Status.BAD_REQUEST;
	}
	output.put("data", result.getData());
	return Response
		.status(status)
		.type(MediaType.APPLICATION_JSON)
		.entity(Json.dumps(output))
		.build();
}
 
Example 20
Project: athena   File: PolicyWebResource.java   View source code 6 votes vote down vote up
/**
 * Create a new segment routing policy.
 *
 * @param input JSON stream for policy to create
 * @return status of the request - OK if the policy is created,
 * @throws IOException if JSON processing fails
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response createPolicy(InputStream input) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode policyJson = (ObjectNode) mapper.readTree(input);
    SegmentRoutingService srService = get(SegmentRoutingService.class);
    Policy policyInfo = POLICY_CODEC.decode(policyJson, this);

    if (policyInfo.type() == Policy.Type.TUNNEL_FLOW) {
        srService.createPolicy(policyInfo);
        return Response.ok().build();
    } else {
        return Response.serverError().build();
    }
}
 
Example 21
Project: uavstack   File: TestRestService.java   View source code 5 votes vote down vote up
@POST
@Path("testAredis")
public void testAredis(String jsonString) {

    SystemLogger.init("DEBUG", true, 0);
    CacheManager cm = CacheManagerFactory.build("localhost:6379", 1, 5, 5);
    cm.put("TEST", "foo", "bar");

    cm.get("TEST", "foo");

    cm.lpush("TEST", "lll", "a");
    cm.lpush("TEST", "lll", "b");
    cm.lpush("TEST", "lll", "c");
    cm.lpop("TEST", "lll");
    cm.lpop("TEST", "lll");
    cm.lpop("TEST", "lll");

    cm.putHash("TEST", "mmm", "abc", "123");
    cm.putHash("TEST", "mmm", "def", "456");
    cm.getHashAll("TEST", "mmm");

    cm.del("TEST", "foo");
    cm.del("TEST", "lll");
    cm.del("TEST", "mmm");

    cm.shutdown();
}
 
Example 22
Project: Info-Portal   File: UserResource.java   View source code 5 votes vote down vote up
@POST
@Path("/fname/{fname}/lname/{lname}")
public Response addUser(@PathParam("fname") String fname,
                        @PathParam("lname") String lname) {
    User user = new User(fname, lname);
    users.createUser(user);
    return Response.accepted().build();
}
 
Example 23
Project: camunda-bpm-swagger   File: JaxRsAnnotationStep.java   View source code 5 votes vote down vote up
static Optional<Class<? extends Annotation>> javaxRsAnnotation(final Method method) {
  for (final Class<? extends Annotation> a : Arrays.asList(POST.class, GET.class, PUT.class, DELETE.class, OPTIONS.class)) {
    if (method.getAnnotation(a) != null) {
      return Optional.of(a);
    }
  }

  return Optional.empty();
}
 
Example 24
Project: opencps-v2   File: RegistrationTemplatesManagement.java   View source code 5 votes vote down vote up
@POST
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@ApiOperation(value = "Add a RegistrationTemplate", response = RegistrationTemplateDetailModel.class)
@ApiResponses(value = {
		@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a RegistrationTemplate was created", response = RegistrationTemplateDetailModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal error", response = ExceptionModel.class) })
public Response addRegistrationTemplate(@Context HttpServletRequest request, @Context HttpHeaders header,
		@Context Company company, @Context Locale locale, @Context User user,
		@Context ServiceContext serviceContext, @BeanParam RegistrationTemplateInputModel input);
 
Example 25
Project: athena   File: ApplicationResource.java   View source code 5 votes vote down vote up
@Path("upload")
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response upload(@QueryParam("activate") @DefaultValue("false") String activate,
                       @FormDataParam("file") InputStream stream) throws IOException {
    ApplicationAdminService service = get(ApplicationAdminService.class);
    Application app = service.install(stream);
    lastInstalledAppName = app.id().name();
    if (Objects.equals(activate, "true")) {
        service.activate(app.id());
    }
    return Response.ok().build();
}
 
Example 26
Project: diax-dialect   File: TokenVerificationAPI.java   View source code 5 votes vote down vote up
@Path("/checktrainer")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String checkTrainer(String JSONRequest, @Context ServletContext context) {
	JSONObject tokenObject = new JSONObject(JSONRequest);
	DatabaseOperations databaseOps = (DatabaseOperations) context.getAttribute("databaseOps");
	boolean trainer = databaseOps.isTokenTrainable(tokenObject.getString("token"));
	String out = trainer ? "1" : "0";
	return new JSONObject().put("response", out).toString();
}
 
Example 27
Project: microservices-transactions-tcc   File: CompositeController.java   View source code 5 votes vote down vote up
@POST
@Path("files")
@Produces ( "application/json" )
   @ApiOperation(
   		code = 201,
           value = "Save new content while creating its discussion board",
           notes = "Both operations (new content and forum) must succeed within a given time interval, otherwise both will be canceled or rolled back. "
           		+ "The newly created resource(s) can be referenced by the URI(s) returned in the entity of the response, with the URI for the "
           		+ "distributed transaction given by the Location header field",
           response = String.class,
           responseContainer = "List",
           responseHeaders = {
   			 @ResponseHeader(name = "Location", description = "The distributed transaction URI", response = String.class)
   		}
       )
@ApiResponses(value = {
		@ApiResponse(code=500, message="Error processing request", response = ErrorDetails.class)
})
public Response save(@Context UriInfo uriInfo, 
		@ApiParam(value = "Data to pass to server", required = true) CompositeData data
		) throws CompositeTransactionException {
	
	Entry<String, List<String>> txEntities = service.saveAllEntities(data);
	
	URI location = uriInfo.getAbsolutePathBuilder().path("{id}")
			.resolveTemplate("id", txEntities.getKey()).build();
	
	return Response.created(location).entity(txEntities.getValue()).build();
}
 
Example 28
Project: diax-dialect   File: TokenVerificationAPI.java   View source code 5 votes vote down vote up
@Path("/verifytoken")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String verifyToken(String JSONRequest, @Context ServletContext context) {
	JSONObject tokenObject = new JSONObject(JSONRequest);
	DatabaseOperations databaseOps = (DatabaseOperations) context.getAttribute("databaseOps");
	boolean verified = databaseOps.checkToken(tokenObject.getString("token"));
	boolean banned = databaseOps.isTokenBanned(tokenObject.getString("token"));
	String out = verified && !banned ? "1" : "0";
	return new JSONObject().put("response", out).toString();
}
 
Example 29
Project: vc   File: ProductResource.java   View source code 5 votes vote down vote up
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Product createAddress(Product Per) {
    Product ProductResponse = Product_Service.CreateProduct(Per);
    return ProductResponse;
}
 
Example 30
Project: Equella   File: TaxonomyResource.java   View source code 5 votes vote down vote up
/**
 * Insert new term
 * 
 * @param uuid
 * @param termBean
 * @return
 */
@POST
@Path("/{uuid}/term")
@Produces("application/json")
@ApiOperation(value = "Create taxonomy term")
public Response createTaxonomyTerm(
	@ApiParam(value = "Taxonomy uuid", required = true) @PathParam("uuid") String taxonomyUuid,
	@ApiParam(value = "Taxonomy term") TermBean termBean)
{
	if( taxonomyService.isTaxonomyReadonly(taxonomyUuid) )
	{
		throw new WebException(Status.METHOD_NOT_ALLOWED.getStatusCode(),
			Status.METHOD_NOT_ALLOWED.getReasonPhrase(), "Taxonomy is readonly");
	}

	final Taxonomy taxonomy = ensureTaxonomy(taxonomyUuid, PrivCheck.EDIT);

	TermResult parentTerm = taxonomyService.getTermResultByUuid(taxonomyUuid, termBean.getParentUuid());
	int index = termBean.getIndex();

	if( index < 0 )
	{
		index = 0;
	}

	try
	{
		TermResult termResult = termService.insertTerm(taxonomy, parentTerm, termBean.getTerm(), index);
		return Response.created(getTermUrl(taxonomyUuid, termResult.getUuid())).build();
	}
	catch( Exception e )
	{
		throw new WebException(Status.NOT_ACCEPTABLE.getStatusCode(), Status.NOT_ACCEPTABLE.getReasonPhrase(),
			e.getMessage());
	}

}
 
Example 31
Project: athena   File: DhcpWebResource.java   View source code 5 votes vote down vote up
/**
 * Post a new static MAC/IP binding.
 * Registers a static binding to the DHCP server, and displays the current set of bindings.
 *
 * @onos.rsModel DhcpConfigPut
 * @param stream JSON stream
 * @return 200 OK
 */
@POST
@Path("mappings")
@Consumes(MediaType.APPLICATION_JSON)
public Response setMapping(InputStream stream) {
    ObjectNode root = mapper().createObjectNode();
    try {
        ObjectNode jsonTree = (ObjectNode) mapper().readTree(stream);
        JsonNode macID = jsonTree.get("mac");
        JsonNode ip = jsonTree.get("ip");
        if (macID != null && ip != null) {
            IpAssignment ipAssignment = IpAssignment.builder()
                    .ipAddress(Ip4Address.valueOf(ip.asText()))
                    .leasePeriod(service.getLeaseTime())
                    .timestamp(new Date())
                    .assignmentStatus(Option_Requested)
                    .build();

            if (!service.setStaticMapping(MacAddress.valueOf(macID.asText()),
                                          ipAssignment)) {
                throw new IllegalArgumentException("Static Mapping Failed. " +
                                                           "The IP maybe unavailable.");
            }
        }

        final Map<HostId, IpAssignment> intents = service.listMapping();
        ArrayNode arrayNode = root.putArray("mappings");
        intents.entrySet().forEach(i -> arrayNode.add(mapper().createObjectNode()
                                                              .put("host", i.getKey().toString())
                                                              .put("ip", i.getValue().ipAddress().toString())));
    } catch (IOException e) {
        throw new IllegalArgumentException(e.getMessage());
    }
    return ok(root).build();
}
 
Example 32
Project: athena   File: FlowObjectiveWebResource.java   View source code 5 votes vote down vote up
/**
 * Creates and installs a new next objective for the specified device.
 *
 * @param deviceId device identifier
 * @param stream   next objective JSON
 * @return status of the request - CREATED if the JSON is correct,
 * BAD_REQUEST if the JSON is invalid
 * @onos.rsModel NextObjective
 */
@POST
@Path("{deviceId}/next")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createNextObjective(@PathParam("deviceId") String deviceId,
                                    InputStream stream) {
    try {
        UriBuilder locationBuilder = null;
        ObjectNode jsonTree = (ObjectNode) mapper().readTree(stream);
        if (validateDeviceId(deviceId, jsonTree)) {
            DeviceId did = DeviceId.deviceId(deviceId);
            NextObjective nextObjective =
                    codec(NextObjective.class).decode(jsonTree, this);
            flowObjectiveService.next(did, nextObjective);
            locationBuilder = uriInfo.getBaseUriBuilder()
                    .path("flowobjectives")
                    .path(did.toString())
                    .path("next")
                    .path(Integer.toString(nextObjective.id()));
        }
        return Response
                .created(locationBuilder.build())
                .build();
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example 33
Project: java-ml-projects   File: DataSetResource.java   View source code 5 votes vote down vote up
@POST
@Path("{label}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void receiveFile(MultipartInput input, @PathParam("label") String label) {
	List<InputPart> parts = input.getParts();
	parts.stream().filter(p -> p.getMediaType().getType().startsWith("image"))
			.forEach(p -> this.saveImage(p, label));
	input.close();
}
 
Example 34
Project: opencps-v2   File: EmployeeManagement.java   View source code 5 votes vote down vote up
@POST
@Path("/{id}/account")
@Consumes({ MediaType.APPLICATION_FORM_URLENCODED })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response createEmployeeAccount(@Context HttpServletRequest request, @Context HttpHeaders header,
		@Context Company company, @Context Locale locale, @Context User user,
		@Context ServiceContext serviceContext, @PathParam("id") long id,
		@BeanParam EmployeeAccountInputModel input);
 
Example 35
Project: vc   File: IndividualResource.java   View source code 5 votes vote down vote up
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Individual createAddress(Individual Per) {
    Individual IndividualResponse = Individual_Service.CreateIndividual(Per);
    return IndividualResponse;
}
 
Example 36
Project: ats-framework   File: MonitoringServiceImpl.java   View source code 5 votes vote down vote up
/**
 * Initialize Monitoring context Must be called before calling any
 * scheduleXYZMonitoring REST method
 */
@POST
@Path( "initializeMonitoring")
@Consumes( MediaType.APPLICATION_JSON)
@Produces( MediaType.APPLICATION_JSON)
public Response initializeMonitoring(
                                      @Context HttpServletRequest request,
                                      BasePojo basePojo ) {

    final String caller = getCaller(request, basePojo, false);
    ThreadsPerCaller.registerThread(caller);

    try {

        SessionData sd = getSessionData(request, basePojo);

        RestSystemMonitor restSystemMonitor = sd.getSystemMonitor();

        String agent = request.getLocalAddr() + ":" + request.getLocalPort();

        restSystemMonitor.initializeMonitoringContext(agent);

        return Response.ok("{\"status\":\"monitoring context initialized.\"}").build();

    } catch (Exception e) {
        return Response.serverError().entity(new ErrorPojo(e)).build();
    } finally {
        ThreadsPerCaller.unregisterThread();
    }

}
 
Example 37
Project: uavstack   File: GodEyeRestService.java   View source code 5 votes vote down vote up
@SuppressWarnings("unchecked")
@POST
@Path("notify/up/stgy/hm")
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public void noitifyStrategyUpdate(String dataParam, @Suspended AsyncResponse response) throws Exception {

    // 添加操作字段
    Map<String, Object> stgyMap = JSONHelper.toObject(dataParam, Map.class);
    for (Entry<String, Object> objecMap : stgyMap.entrySet()) {
        String key = objecMap.getKey();
        Object value = stgyMap.get(key);
        if (null != value) {
            Map<String, Object> idMap = JSONHelper.toObject(String.valueOf(value), Map.class);
            idMap.put("uptime", new Date().getTime());

            stgyMap.put(key, idMap);
            break;
        }
    }

    final String stgyData = JSONHelper.toString(stgyMap);

    // 封装http请求数据
    UAVHttpMessage message = new UAVHttpMessage();
    message.putRequest("body", stgyData);
    message.setIntent("strategy.update");

    NoitifyStrategyUpdateCB callback = new NoitifyStrategyUpdateCB();
    callback.setResponse(response);
    callback.setStgyData(stgyData);

    doHttpPost("uav.app.godeye.notify.strategy.http.addr", "/rtntf/oper", message, callback);

}
 
Example 38
Project: opencps-v2   File: DataManagement.java   View source code 5 votes vote down vote up
@POST
@Path("/{code}/dictgroups/{groupCode}/dictitems")
@Consumes({ MediaType.APPLICATION_FORM_URLENCODED })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response addDictgroupsDictItems(@Context HttpServletRequest request, @Context HttpHeaders header,
		@Context Company company, @Context Locale locale, @Context User user, @Context ServiceContext serviceContext,
		@PathParam("code") String code, @PathParam("groupCode") String groupCode, @FormParam("itemCode") String itemCode);
 
Example 39
Project: soapbox-race-core   File: Event.java   View source code 5 votes vote down vote up
@POST
@Secured
@Path("/bust")
@Produces(MediaType.APPLICATION_XML)
public PursuitEventResult bust(InputStream bustXml, @HeaderParam("securityToken") String securityToken, @QueryParam("eventSessionId") Long eventSessionId) {
	PursuitArbitrationPacket pursuitArbitrationPacket = (PursuitArbitrationPacket) UnmarshalXML.unMarshal(bustXml, PursuitArbitrationPacket.class);
	PursuitEventResult pursuitEventResult = new PursuitEventResult();
	Long activePersonaId = tokenBO.getActivePersonaId(securityToken);
	pursuitEventResult = eventBO.getPursitEnd(eventSessionId, activePersonaId, pursuitArbitrationPacket, true);
	return pursuitEventResult;
}
 
Example 40
Project: syndesis   File: VerifierEndpoint.java   View source code 5 votes vote down vote up
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/{id}")
public List<VerifierResponse> verify(@PathParam("id") String connectorId, Map<String, Object> parameters) {
    List<VerifierResponse> answer;
    Verifier verifier;

    try {
        // First find try to lookup the verifier from the application context
        verifier = applicationContext.getBean(connectorId, Verifier.class);
    } catch (NoSuchBeanDefinitionException|NoSuchBeanException ignored) {
        LOGGER.debug("No bean of type: {} with id: {} found in application context, switch to factory finder", Verifier.class.getName(), connectorId);

        verifier = null;

        try {
            // Then fallback to camel's factory finder
            final FactoryFinder finder = camelContext.getFactoryFinder(RESOURCE_PATH);
            final Class<?> type = finder.findClass(connectorId);

            verifier = (Verifier) camelContext.getInjector().newInstance(type);
        } catch (Exception e) {
            LOGGER.warn("No factory finder of type: {} for id: {}", Verifier.class.getName(), connectorId, e);
        }
    }


    if (verifier != null) {
        answer = verifier.verify(camelContext, connectorId, parameters);
        answer = filterExceptions(answer);
    } else {
        answer = Collections.singletonList(createUnsupportedResponse(connectorId));
    }


    return answer;
}