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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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: java-ml-projects   File: DataSetResource.java   Source Code and License 6 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 8
Project: wechat-mall   File: IndexResource.java   Source Code and License 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 9
Project: comms-router   File: PlanResource.java   Source Code and License 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 10
Project: dust-api   File: DeviceSlackResource.java   Source Code and License 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 11
Project: opencps-v2   File: RegistrationManagement.java   Source Code and License 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 12
Project: presto-manager   File: ControllerPackageAPI.java   Source Code and License 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 13
Project: athena   File: FlowsWebResource.java   Source Code and License 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 14
Project: athena   File: TenantWebResource.java   Source Code and License 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 15
Project: plugin-prov   File: ProvQuoteInstanceResource.java   Source Code and License 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 16
Project: MaximoForgeViewerPlugin   File: ForgeRS.java   Source Code and License 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 17
Project: verify-service-provider   File: TranslateSamlResponseResource.java   Source Code and License 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 18
Project: acmeair-modular   File: BookingsREST.java   Source Code and License 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 19
Project: plugin-bt-jira   File: JiraImportPluginResource.java   Source Code and License 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 20
Project: sierra   File: GraphQLService.java   Source Code and License 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 21
Project: athena   File: PolicyWebResource.java   Source Code and License 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 22
Project: uavstack   File: TestRestService.java   Source Code and License 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 23
Project: Info-Portal   File: UserResource.java   Source Code and License 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 24
Project: camunda-bpm-swagger   File: JaxRsAnnotationStep.java   Source Code and License 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 25
Project: opencps-v2   File: RegistrationTemplatesManagement.java   Source Code and License 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 26
Project: athena   File: ApplicationResource.java   Source Code and License 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 27
Project: diax-dialect   File: TokenVerificationAPI.java   Source Code and License 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 28
Project: microservices-transactions-tcc   File: CompositeController.java   Source Code and License 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 29
Project: diax-dialect   File: TokenVerificationAPI.java   Source Code and License 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 30
Project: vc   File: ProductResource.java   Source Code and License 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 31
Project: Equella   File: TaxonomyResource.java   Source Code and License 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 32
Project: athena   File: DhcpWebResource.java   Source Code and License 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 33
Project: athena   File: FlowObjectiveWebResource.java   Source Code and License 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 34
Project: opencps-v2   File: EmployeeManagement.java   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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;
}
 
Example 41
Project: Celebino   File: GardenStatusController.java   Source Code and License 5 votes vote down vote up
/**
 * Cadastra GardenStatus
 * 
 * @param GardenStatus
 * @return Response
 */
@PermitAll
@POST
@Path("/")
@Consumes("application/json")
@Produces("application/json")
public Response insert(GardenStatus gardenstatus) {
	ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST);
	builder.expires(new Date());

	Timestamp time = new Timestamp(System.currentTimeMillis());
	gardenstatus.setTime(time);

	try {
		Garden garden = GardenDao.getInstance().getById(gardenstatus.getGarden().getId());

		if (garden.getId().equals(null)) {
			GardenDao.getInstance().insertU(gardenstatus.getGarden());
		} else {
			gardenstatus.setGarden(garden);
		}
		
		Long id = GardenStatusDao.getInstance().insertU(gardenstatus);
		gardenstatus.setId(id);

		System.out.println(new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(time.getTime()));
		System.out.println(time.getTime());
		builder.status(Response.Status.OK).entity(gardenstatus);

	} catch (SQLException e) {
		builder.status(Response.Status.INTERNAL_SERVER_ERROR);
	}

	return builder.build();
}
 
Example 42
Project: vc   File: Operation_StateResource.java   Source Code and License 5 votes vote down vote up
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Operation_State createAddress(Operation_State Loc) {
    Operation_State Operation_StateResponse = Operation_State_Service.CreateOperation_State(Loc);
    return Operation_StateResponse;
}
 
Example 43
Project: DBus   File: AvroSchemaResource.java   Source Code and License 5 votes vote down vote up
@POST
@Path("/search")
public Response search(Map<String, Object> map) {
    try {
        AvroSchemaService service = AvroSchemaService.getService();
        PageInfo<AvroSchema> result = service.search(getInt(map, "pageNum"), getInt(map, "pageSize"), map);
        return Response.ok().entity(result).build();
    } catch (Exception e) {
        logger.error("Error encountered while search avro schema with parameter:{}", JSON.toJSONString(map), e);
        return Response.status(200).entity(new Result(-1, e.getMessage())).build();
    }
}
 
Example 44
Project: soapbox-race-core   File: DriverPersona.java   Source Code and License 5 votes vote down vote up
@POST
@Secured
@Path("/ReserveName")
@Produces(MediaType.APPLICATION_XML)
public ArrayOfString reserveName(@QueryParam("name") String name) {
	return bo.reserveName(name);
}
 
Example 45
Project: rebase-server   File: CategoryResource.java   Source Code and License 5 votes vote down vote up
@POST @Path("{owner}")
@Consumes(MediaType.APPLICATION_JSON)
public Response newCategory(@Valid Category cat, @Username @PathParam("owner") String owner) {
    Authorizations.verify(owner, auth);
    Document category = new Document(KEY, cat.key)
        .append(NAME, cat.name)
        .append(RANK, cat.rank)
        .append(OWNER, owner)
        .append(CREATED_AT, new Date());
    MongoDBs.categories().insertOne(category);
    return Response.created(URIs.create("categories", owner, cat.key))
        .entity(category)
        .build();
}
 
Example 46
Project: uavstack   File: TestRestService.java   Source Code and License 5 votes vote down vote up
@POST
@Path("methodPath3")
@Consumes("applicatino/json")
@Produces("plain/text")
public String[] testPosthMethod2(String jsonString) {

    return new String[0];
}
 
Example 47
Project: app-ms   File: AuthnResource.java   Source Code and License 5 votes vote down vote up
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(@ApiResponse(code = 401,
    message = "Unauthorized Response",
    response = ErrorResponse.class))
public Response json(final UsernamePassword usernamePassword,
    @HeaderParam(HttpHeaders.AUTHORIZATION) final String authorization) {

    if (!"password".equals(usernamePassword.getPassword())) {
        throw ErrorResponses.unauthorized(ErrorCodes.UNAUTHORIZED_CLIENT, "invalid username/password combination", "FORM");
    }

    final JwtClaims claims = new JwtClaims();
    claims.setSubject(usernamePassword.getUsername());
    claims.setAudience(HttpAuthorizationHeaders.parseBasicAuthorization(authorization)[0]);

    final Form form = new Form();
    form.param("grant_type", GrantTypes.JWT_ASSERTION);
    form.param("assertion", cryptoOps.sign(claims));

    return Response.ok(client.target(authorizationEndpoint).request(MediaType.APPLICATION_JSON_TYPE)
        .header(HttpHeaders.AUTHORIZATION, authorization)
        .post(Entity.form(form), OAuthTokenResponse.class))
        .build();

}
 
Example 48
Project: osc-core   File: NsmMgrApis.java   Source Code and License 5 votes vote down vote up
@Path("/queryVmInfo")
@POST
public Response queryVMInfo(@Context HttpHeaders headers, QueryVmInfoRequest queryVmInfo) {

    log.info("Query VM info request: " + queryVmInfo);
    this.userContext.setUser(OscAuthFilter.getUsername(headers));

    return this.apiUtil.getResponse(this.queryVmInfoService, queryVmInfo);
}
 
Example 49
Project: E-Clinic   File: ContactRestEndPoint.java   Source Code and License 5 votes vote down vote up
@POST
@Path("create")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response create(@Valid Contact value) {
    try {
        contactService.create(value);
    } catch (Exception ex) {
        return Response.ok().header("Exception", ex.getMessage()).build();
    }
    return Response.ok().entity("Data is saved").build();
}
 
Example 50
Project: Java-9-Programming-Blueprints   File: DeskDroidResource.java   Source Code and License 5 votes vote down vote up
@POST
@Path("conversations")
@Secure
public Response sendMessage(Message message) throws InterruptedException {
    final SmsManager sms = SmsManager.getDefault();
    final ArrayList<String> parts = sms.divideMessage(message.getBody());
    final CountDownLatch sentLatch = new CountDownLatch(parts.size());
    final AtomicInteger statusCode =
            new AtomicInteger(Response.Status.CREATED.getStatusCode());
    final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (getResultCode() != Activity.RESULT_OK) {
                statusCode.set(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
            }
            sentLatch.countDown();
        }
    };
    deskDroidService.registerReceiver(receiver, new IntentFilter("com.steeplesoft.deskdroid.SMS_SENT"));
    ArrayList<PendingIntent> sentPIs = new ArrayList<>();
    for (int i = 0; i < parts.size(); i++) {
        sentPIs.add(PendingIntent.getBroadcast(deskDroidService.getApplicationContext(), 0,
                new Intent("com.steeplesoft.deskdroid.SMS_SENT"), 0));
    }
    sms.sendMultipartTextMessage(message.getAddress(), null, parts, sentPIs, null);

    sentLatch.await(5, TimeUnit.SECONDS);
    deskDroidService.unregisterReceiver(receiver);
    return Response.status(statusCode.get()).build();

}
 
Example 51
Project: redpipe   File: BaseSecurityResource.java   Source Code and License 5 votes vote down vote up
@POST
@Path("/loginAuth")
public Single<Response> loginAuth(@FormParam("username") String username, @FormParam("password") String password,
		@FormParam("return_url") String returnUrl, @Context Session session, @Context RoutingContext ctx,
		@Context AuthProvider auth) throws URISyntaxException {
	if (username == null || username.isEmpty() || password == null || password.isEmpty())
		return Single.just(Response.status(Status.BAD_REQUEST).build());

	JsonObject authInfo = new JsonObject().put("username", username).put("password", password);
	return auth.rxAuthenticate(authInfo).map(user -> {
		ctx.setUser(user);
		if (session != null) {
			// the user has upgraded from unauthenticated to authenticated
			// session should be upgraded as recommended by owasp
			session.regenerateId();
		}
		String redirectUrl = session.remove(REDIRECT_KEY);
		if (redirectUrl == null)
			redirectUrl = returnUrl;
		if (redirectUrl == null)
			redirectUrl = "/";

		try {
			return Response.status(Status.FOUND).location(new URI(redirectUrl)).build();
		} catch (URISyntaxException e) {
			throw new RuntimeException(e);
		}
	}).onErrorReturn(t -> {
		t.printStackTrace();
		return Response.status(Status.FORBIDDEN).build();
	});
}
 
Example 52
Project: launcher-backend   File: LaunchResource.java   Source Code and License 5 votes vote down vote up
@POST
@javax.ws.rs.Path("/commands/{commandName}/next")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public JsonObject nextStep(JsonObject content,
                           @PathParam("commandName") @DefaultValue(DEFAULT_COMMAND_NAME) String commandName,
                           @Context HttpHeaders headers)
        throws Exception {
    validateCommand(commandName);
    int stepIndex = content.getInt("stepIndex", 1);
    JsonObjectBuilder builder = createObjectBuilder();
    try (CommandController controller = getCommand(commandName, ForgeInitializer.getRoot(), headers)) {
        if (!(controller instanceof WizardCommandController)) {
            throw new WebApplicationException("Controller is not a wizard", Status.BAD_REQUEST);
        }
        controller.getContext().getAttributeMap().put("action", "next");
        WizardCommandController wizardController = (WizardCommandController) controller;
        helper.populateController(content, controller);
        for (int i = 0; i < stepIndex; i++) {
            wizardController.next().initialize();
            helper.populateController(content, wizardController);
        }
        helper.describeMetadata(builder, controller);
        helper.describeInputs(builder, controller);
        helper.describeCurrentState(builder, controller);
    }
    return builder.build();
}
 
Example 53
Project: verify-hub   File: RpAuthnResponseGeneratorResource.java   Source Code and License 5 votes vote down vote up
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Timed
public Response generate(ResponseFromHubDto responseFromHub) throws JsonProcessingException {
    return Response.ok().entity(service.generate(responseFromHub)).type(MediaType.APPLICATION_JSON_TYPE).build();
}
 
Example 54
Project: opencps-v2   File: DossierTemplateManagement.java   Source Code and License 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 DossierTemplate", response = DossierTemplateInputModel.class)
@ApiResponses(value = {
		@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the DossierTemplate was created", response = DossierTemplateInputModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal error", response = ExceptionModel.class) })

public Response addDossierTemplate(@Context HttpServletRequest request, @Context HttpHeaders header,
		@Context Company company, @Context Locale locale, @Context User user,
		@Context ServiceContext serviceContext, @BeanParam DossierTemplateInputModel input);
 
Example 55
Project: elastic-job-cloud   File: CloudAppRestfulApi.java   Source Code and License 5 votes vote down vote up
/**
 * 注册应用配置.
 * 
 * @param appConfig 应用配置
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
public void register(final CloudAppConfiguration appConfig) {
    Optional<CloudAppConfiguration> appConfigFromZk = appConfigService.load(appConfig.getAppName());
    if (appConfigFromZk.isPresent()) {
        throw new AppConfigurationException("app '%s' already existed.", appConfig.getAppName());
    }
    appConfigService.add(appConfig);
}
 
Example 56
Project: comms-router   File: AgentResource.java   Source Code and License 5 votes vote down vote up
@POST
@Path("{resourceId}")
@ApiOperation(
    value = "Update an existing Agent",
    notes = "Update some properties of an existing Agent")
@ApiResponses({
    @ApiResponse(code = 204, message = "Successful operation"),
    @ApiResponse(code = 400, message = "Invalid ID supplied",
        response = ExceptionPresentation.class),
    @ApiResponse(code = 404, message = "Agent not found",
        response = ExceptionPresentation.class),
    @ApiResponse(code = 405, message = "Validation exception",
        response = ExceptionPresentation.class)})
public void update(
    @ApiParam(value = "ID of the agent to be updated")
    @PathParam("resourceId")
        String resourceId,
    @ApiParam(
        value = "UpdateAgentArg object representing parameters of the Agent to be updated",
        required = true)
        UpdateAgentArg agentArg)
    throws CommsRouterException {

  LOGGER.debug("Updating agent {}", agentArg);

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

  agentService.update(agentArg, objectId);
}
 
Example 57
Project: dremio-oss   File: HomeResource.java   Source Code and License 5 votes vote down vote up
@POST
@Path("upload_start/{path: .*}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public File uploadFile(@PathParam("path") String path,
                       @FormDataParam("file") InputStream fileInputStream,
                       @FormDataParam("file") FormDataContentDisposition contentDispositionHeader,
                       @FormDataParam("fileName") FileName fileName,
                       @QueryParam("extension") String extension) throws Exception {
  // add some validation
  InputValidation inputValidation = new InputValidation();
  inputValidation.validate(fileName);

  List<String> pathList = PathUtils.toPathComponents(path);
  pathList.add(SqlUtils.quoteIdentifier(fileName.getName()));

  final FilePath filePath = FilePath.fromURLPath(homeName, PathUtils.toFSPathString(pathList));

  final FileConfig config = new FileConfig();
  try {
    // upload file to staging area
    final org.apache.hadoop.fs.Path stagingLocation = fileStore.stageFile(filePath, extension, fileInputStream);
    config.setLocation(stagingLocation.toString());
    config.setName(filePath.getLeaf().getName());
    config.setCtime(System.currentTimeMillis());
    config.setFullPathList(filePath.toPathList());
    config.setOwner(securityContext.getUserPrincipal().getName());
    config.setType(FileFormat.getFileFormatType(Collections.singletonList(extension)));
  } catch (IOException ioe) {
    throw new DACException("Error writing to file at " + filePath, ioe);
  }
  final File file = newFile(filePath.toUrlPath(),
      filePath, FileFormat.getForFile(config), 0, 0, true, true, true,
      DatasetType.PHYSICAL_DATASET_HOME_FILE
  );
  return file;
}
 
Example 58
Project: xsharing-services-router   File: IVRouterService.java   Source Code and License 5 votes vote down vote up
@POST
@Path(IVRouterConfig.SHORTEST_PATHS)
IVRouterResponse getShortestPaths(@FormParam(IVRouterConfig.MODE) String mode,
                                  @FormParam(IVRouterConfig.VEHICLE_ID) String vehicleId,
                                  @FormParam(IVRouterConfig.DISTANCE_TIME_WEIGHTING) Double distanceTimeWeighting,
                                  @FormParam(IVRouterConfig.CREATE_ROUTES) Boolean createRoutes,
                                  @FormParam(IVRouterConfig.POINTS) String point);
 
Example 59
Project: sample-acmegifts   File: NotificationResource.java   Source Code and License 5 votes vote down vote up
@POST
@Path("/")
@Consumes("application/json")
public Response notify(JsonObject payload) {
  // Validate the JWT. At this point, anyone can submit a notification if they
  // have a valid JWT.
  try {
    validateJWT();
  } catch (JWTException jwte) {
    return Response.status(Status.UNAUTHORIZED)
        .type(MediaType.TEXT_PLAIN)
        .entity(jwte.getMessage())
        .build();
  }

  JsonObject notification = payload.getJsonObject(JSON_KEY_NOTIFICATION);
  String twitterHandle = notification.getString(JSON_KEY_TWITTER_HANDLE);
  String message = notification.getString(JSON_KEY_MESSAGE);

  try {
    log(message);
    tweet(twitterHandle, message);
  } catch (Exception e) {
    throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR);
  }

  return Response.ok().build();
}
 
Example 60
Project: uavstack   File: XRobotRestService.java   Source Code and License 5 votes vote down vote up
@POST
@Path("command")
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public void doCommand(String data, @Suspended AsyncResponse response) {

    UAVHttpMessage msg = new UAVHttpMessage(data);

    this.doHttpPost("uav.app.xrobot.http.addr", "/hit/xrobot", msg, new CmdCallback(response));
}