Search in sources :

Example 96 with POST

use of javax.ws.rs.POST in project killbill by killbill.

the class AccountResource method payAllInvoices.

@TimedResource
@POST
@Produces(APPLICATION_JSON)
@Consumes(APPLICATION_JSON)
@Path("/{accountId:" + UUID_PATTERN + "}/" + INVOICE_PAYMENTS)
@ApiOperation(value = "Trigger a payment for all unpaid invoices")
@ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid account id supplied"), @ApiResponse(code = 404, message = "Account not found") })
public Response payAllInvoices(@PathParam("accountId") final String accountId, @QueryParam(QUERY_PAYMENT_EXTERNAL) @DefaultValue("false") final Boolean externalPayment, @QueryParam(QUERY_PAYMENT_AMOUNT) final BigDecimal paymentAmount, @QueryParam(QUERY_PLUGIN_PROPERTY) final List<String> pluginPropertiesString, @HeaderParam(HDR_CREATED_BY) final String createdBy, @HeaderParam(HDR_REASON) final String reason, @HeaderParam(HDR_COMMENT) final String comment, @javax.ws.rs.core.Context final HttpServletRequest request) throws AccountApiException, PaymentApiException, InvoiceApiException {
    final Iterable<PluginProperty> pluginProperties = extractPluginProperties(pluginPropertiesString);
    final CallContext callContext = context.createContext(createdBy, reason, comment, request);
    final Account account = accountUserApi.getAccountById(UUID.fromString(accountId), callContext);
    final Collection<Invoice> unpaidInvoices = invoiceApi.getUnpaidInvoicesByAccountId(account.getId(), clock.getUTCToday(), callContext);
    BigDecimal remainingRequestPayment = paymentAmount;
    if (remainingRequestPayment == null) {
        remainingRequestPayment = BigDecimal.ZERO;
        for (final Invoice invoice : unpaidInvoices) {
            remainingRequestPayment = remainingRequestPayment.add(invoice.getBalance());
        }
    }
    for (final Invoice invoice : unpaidInvoices) {
        final BigDecimal amountToPay = (remainingRequestPayment.compareTo(invoice.getBalance()) >= 0) ? invoice.getBalance() : remainingRequestPayment;
        if (amountToPay.compareTo(BigDecimal.ZERO) > 0) {
            final UUID paymentMethodId = externalPayment ? null : account.getPaymentMethodId();
            createPurchaseForInvoice(account, invoice.getId(), amountToPay, paymentMethodId, externalPayment, null, null, pluginProperties, callContext);
        }
        remainingRequestPayment = remainingRequestPayment.subtract(amountToPay);
        if (remainingRequestPayment.compareTo(BigDecimal.ZERO) == 0) {
            break;
        }
    }
    //
    if (externalPayment && remainingRequestPayment.compareTo(BigDecimal.ZERO) > 0) {
        invoiceApi.insertCredit(account.getId(), remainingRequestPayment, clock.getUTCToday(), account.getCurrency(), true, "pay all invoices", callContext);
    }
    return Response.status(Status.OK).build();
}
Also used : PluginProperty(org.killbill.billing.payment.api.PluginProperty) Account(org.killbill.billing.account.api.Account) Invoice(org.killbill.billing.invoice.api.Invoice) UUID(java.util.UUID) CallContext(org.killbill.billing.util.callcontext.CallContext) BigDecimal(java.math.BigDecimal) Path(javax.ws.rs.Path) TimedResource(org.killbill.commons.metrics.TimedResource) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) Consumes(javax.ws.rs.Consumes) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 97 with POST

use of javax.ws.rs.POST in project neo4j by neo4j.

the class CypherService method cypher.

@POST
@SuppressWarnings({ "unchecked", "ParameterCanBeLocal" })
public Response cypher(String body, @Context HttpServletRequest request, @QueryParam(INCLUDE_STATS_PARAM) boolean includeStats, @QueryParam(INCLUDE_PLAN_PARAM) boolean includePlan, @QueryParam(PROFILE_PARAM) boolean profile) throws BadInputException {
    usage.get(features).flag(http_cypher_endpoint);
    Map<String, Object> command = input.readMap(body);
    if (!command.containsKey(QUERY_KEY)) {
        return output.badRequest(new InvalidArgumentsException("You have to provide the 'query' parameter."));
    }
    String query = (String) command.get(QUERY_KEY);
    Map<String, Object> params;
    try {
        params = (Map<String, Object>) (command.containsKey(PARAMS_KEY) && command.get(PARAMS_KEY) != null ? command.get(PARAMS_KEY) : new HashMap<String, Object>());
    } catch (ClassCastException e) {
        return output.badRequest(new IllegalArgumentException("Parameters must be a JSON map"));
    }
    try {
        QueryExecutionEngine executionEngine = cypherExecutor.getExecutionEngine();
        boolean periodicCommitQuery = executionEngine.isPeriodicCommit(query);
        CommitOnSuccessfulStatusCodeRepresentationWriteHandler handler = (CommitOnSuccessfulStatusCodeRepresentationWriteHandler) output.getRepresentationWriteHandler();
        if (periodicCommitQuery) {
            handler.closeTransaction();
        }
        TransactionalContext tc = cypherExecutor.createTransactionContext(query, params, request);
        Result result;
        if (profile) {
            result = executionEngine.profileQuery(query, params, tc);
            includePlan = true;
        } else {
            result = executionEngine.executeQuery(query, params, tc);
            includePlan = result.getQueryExecutionType().requestedExecutionPlanDescription();
        }
        if (periodicCommitQuery) {
            handler.setTransaction(database.beginTx());
        }
        return output.ok(new CypherResultRepresentation(result, includeStats, includePlan));
    } catch (Throwable e) {
        if (e.getCause() instanceof CypherException) {
            return output.badRequest(e.getCause());
        } else {
            return output.badRequest(e);
        }
    }
}
Also used : CypherResultRepresentation(org.neo4j.server.rest.repr.CypherResultRepresentation) HashMap(java.util.HashMap) Result(org.neo4j.graphdb.Result) QueryExecutionEngine(org.neo4j.kernel.impl.query.QueryExecutionEngine) CommitOnSuccessfulStatusCodeRepresentationWriteHandler(org.neo4j.server.rest.transactional.CommitOnSuccessfulStatusCodeRepresentationWriteHandler) TransactionalContext(org.neo4j.kernel.impl.query.TransactionalContext) CypherException(org.neo4j.cypher.CypherException) InvalidArgumentsException(org.neo4j.server.rest.repr.InvalidArgumentsException) POST(javax.ws.rs.POST)

Example 98 with POST

use of javax.ws.rs.POST in project neo4j by neo4j.

the class RestfulGraphDatabase method createPagedTraverser.

@POST
@Path(PATH_TO_CREATE_PAGED_TRAVERSERS)
public Response createPagedTraverser(@PathParam("nodeId") long startNode, @PathParam("returnType") TraverserReturnType returnType, @QueryParam("pageSize") @DefaultValue(FIFTY_ENTRIES) int pageSize, @QueryParam("leaseTime") @DefaultValue(SIXTY_SECONDS) int leaseTimeInSeconds, String body) {
    try {
        validatePageSize(pageSize);
        validateLeaseTime(leaseTimeInSeconds);
        String traverserId = actions.createPagedTraverser(startNode, input.readMap(body), pageSize, leaseTimeInSeconds);
        URI uri = new URI("node/" + startNode + "/paged/traverse/" + returnType + "/" + traverserId);
        return output.created(new ListEntityRepresentation(actions.pagedTraverse(traverserId, returnType), uri.normalize()));
    } catch (EvaluationException e) {
        return output.badRequest(e);
    } catch (BadInputException e) {
        return output.badRequest(e);
    } catch (NotFoundException e) {
        return output.notFound(e);
    } catch (URISyntaxException e) {
        return output.serverError(e);
    }
}
Also used : BadInputException(org.neo4j.server.rest.repr.BadInputException) StartNodeNotFoundException(org.neo4j.server.rest.domain.StartNodeNotFoundException) NotFoundException(org.neo4j.graphdb.NotFoundException) EndNodeNotFoundException(org.neo4j.server.rest.domain.EndNodeNotFoundException) EvaluationException(org.neo4j.server.rest.domain.EvaluationException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) ListEntityRepresentation(org.neo4j.server.rest.repr.ListEntityRepresentation) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 99 with POST

use of javax.ws.rs.POST in project neo4j by neo4j.

the class ConsoleService method exec.

@POST
public Response exec(@Context InputFormat input, String data) {
    Map<String, Object> args;
    try {
        args = input.readMap(data);
    } catch (BadInputException e) {
        return output.badRequest(e);
    }
    if (!args.containsKey("command")) {
        return Response.status(Status.BAD_REQUEST).entity("Expected command argument not present.").build();
    }
    ScriptSession scriptSession;
    try {
        scriptSession = getSession(args);
    } catch (IllegalArgumentException e) {
        return output.badRequest(e);
    }
    log.debug(scriptSession.toString());
    try {
        Pair<String, String> result = scriptSession.evaluate((String) args.get("command"));
        List<Representation> list = new ArrayList<Representation>(asList(ValueRepresentation.string(result.first()), ValueRepresentation.string(result.other())));
        return output.ok(new ListRepresentation(RepresentationType.STRING, list));
    } catch (Exception e) {
        List<Representation> list = new ArrayList<Representation>(asList(ValueRepresentation.string(e.getClass() + " : " + e.getMessage() + "\n"), ValueRepresentation.string(null)));
        return output.ok(new ListRepresentation(RepresentationType.STRING, list));
    }
}
Also used : ArrayList(java.util.ArrayList) ValueRepresentation(org.neo4j.server.rest.repr.ValueRepresentation) ListRepresentation(org.neo4j.server.rest.repr.ListRepresentation) ConsoleServiceRepresentation(org.neo4j.server.rest.management.repr.ConsoleServiceRepresentation) Representation(org.neo4j.server.rest.repr.Representation) BadInputException(org.neo4j.server.rest.repr.BadInputException) BadInputException(org.neo4j.server.rest.repr.BadInputException) ArrayList(java.util.ArrayList) Arrays.asList(java.util.Arrays.asList) List(java.util.List) ListRepresentation(org.neo4j.server.rest.repr.ListRepresentation) POST(javax.ws.rs.POST)

Example 100 with POST

use of javax.ws.rs.POST in project platformlayer by platformlayer.

the class KeychainResource method authorizeCertificateChain.

@POST
public ValidateTokenResponse authorizeCertificateChain(@QueryParam("project") String project, CertificateChainInfo chain) {
    try {
        requireSystemAccess();
    } catch (AuthenticatorException e) {
        log.warn("Error while checking system token", e);
        throwInternalError();
    }
    UserEntity userEntity = null;
    try {
        boolean unlock = false;
        userEntity = userAuthenticator.findUserFromKeychain(chain, unlock);
    } catch (AuthenticatorException e) {
        log.warn("Error while fetching user", e);
        throwInternalError();
    }
    if (userEntity == null) {
        throw404NotFound();
    }
    ValidateTokenResponse response = new ValidateTokenResponse();
    response.access = new ValidateAccess();
    response.access.user = Mapping.mapToUserValidation(userEntity);
    // response.access.token = new Token();
    // response.access.token.expires = checkTokenInfo.expiration;
    // response.access.token.id = checkToken;
    String checkProject = project;
    if (checkProject != null) {
        ProjectEntity projectEntity = null;
        try {
            projectEntity = userAuthenticator.findProject(checkProject);
        } catch (AuthenticatorException e) {
            log.warn("Error while fetching project", e);
            throwInternalError();
        }
        if (projectEntity == null) {
            throw404NotFound();
        }
        // Note that we do not unlock the user / project; we don't have any secret material
        // TODO: We could return stuff encrypted with the user's public key
        // projectEntity.unlockWithUser(userEntity);
        //
        // if (!projectEntity.isSecretValid()) {
        // throw404NotFound();
        // }
        UserProjectEntity userProject = null;
        try {
            userProject = userAuthenticator.findUserProject(userEntity, projectEntity);
        } catch (AuthenticatorException e) {
            log.warn("Error while fetching project", e);
            throwInternalError();
        }
        if (userProject == null) {
            // Not a member of project
            throw404NotFound();
        }
        response.access.project = Mapping.mapToProject(projectEntity);
        response.access.project.roles = Mapping.mapToRoles(userProject.getRoles());
    }
    return response;
}
Also used : ValidateTokenResponse(org.platformlayer.auth.model.ValidateTokenResponse) ValidateAccess(org.platformlayer.auth.model.ValidateAccess) UserProjectEntity(org.platformlayer.auth.UserProjectEntity) ProjectEntity(org.platformlayer.auth.ProjectEntity) AuthenticatorException(org.platformlayer.auth.AuthenticatorException) UserProjectEntity(org.platformlayer.auth.UserProjectEntity) UserEntity(org.platformlayer.auth.UserEntity) POST(javax.ws.rs.POST)

Aggregations

POST (javax.ws.rs.POST)513 Path (javax.ws.rs.Path)360 Consumes (javax.ws.rs.Consumes)242 Produces (javax.ws.rs.Produces)222 ApiOperation (io.swagger.annotations.ApiOperation)133 ApiResponses (io.swagger.annotations.ApiResponses)107 IOException (java.io.IOException)74 URI (java.net.URI)63 WebApplicationException (javax.ws.rs.WebApplicationException)62 Timed (com.codahale.metrics.annotation.Timed)55 Response (javax.ws.rs.core.Response)50 TimedResource (org.killbill.commons.metrics.TimedResource)36 CallContext (org.killbill.billing.util.callcontext.CallContext)35 AuditEvent (org.graylog2.audit.jersey.AuditEvent)33 HashMap (java.util.HashMap)32 BadRequestException (co.cask.cdap.common.BadRequestException)24 AuditPolicy (co.cask.cdap.common.security.AuditPolicy)24 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)23 Account (org.killbill.billing.account.api.Account)22 ExceptionMetered (com.codahale.metrics.annotation.ExceptionMetered)20