Search in sources :

Example 71 with PathParam

use of javax.ws.rs.PathParam in project solr-document-store by DBCDK.

the class BiliographicRecordAPIBean method getBibliographicKeysByRepositoryIdWithSupersedeId.

@GET
@Path("bibliographic-records/repository-id/{repositoryId}")
@Produces({ MediaType.APPLICATION_JSON })
@Timed
public Response getBibliographicKeysByRepositoryIdWithSupersedeId(@PathParam("repositoryId") String repositoryID, @DefaultValue("1") @QueryParam("page") int page, @DefaultValue("10") @QueryParam("page_size") int pageSize, @DefaultValue("agencyId") @QueryParam("order_by") String orderBy, @DefaultValue("false") @QueryParam("desc") boolean desc) throws JsonProcessingException {
    log.info("Requesting bibliographic record with repository id: {}", repositoryID);
    log.info("Query parameters - page: {}, page_size: {}, order_by: {}", page, pageSize, orderBy);
    // Checking for valid  query parameters
    if (!BibliographicEntity.sortableColumns.contains(orderBy)) {
        return Response.status(400).entity("{\"error\":\"order_by parameter not acceptable\"}").build();
    }
    String direction = (desc) ? "DESC" : "ASC";
    Query frontendQuery = entityManager.createNativeQuery("SELECT b.*,b2b.livebibliographicrecordid as supersede_id " + "FROM bibliographicsolrkeys b " + "LEFT OUTER JOIN bibliographictobibliographic b2b ON b.bibliographicrecordid=b2b.deadbibliographicrecordid " + "WHERE b.repositoryId = ? ORDER BY b." + orderBy + " " + direction, "BibliographicEntityWithSupersedeId").setParameter(1, repositoryID).setParameter(2, orderBy).setFirstResult((page - 1) * pageSize).setMaxResults(pageSize);
    List<BibliographicFrontendEntity> res = ((List<Object[]>) frontendQuery.getResultList()).stream().map((record) -> {
        BibliographicEntity b = (BibliographicEntity) record[0];
        return new BibliographicFrontendEntity(b, (String) record[1]);
    }).collect(Collectors.toList());
    Query queryTotal = entityManager.createNativeQuery("SELECT COUNT(b.bibliographicRecordId) FROM bibliographicsolrkeys b WHERE b.repositoryId = ?").setParameter(1, repositoryID);
    long count = (long) queryTotal.getSingleResult();
    return Response.ok(new FrontendReturnListType<>(res, pageCount(count, pageSize)), MediaType.APPLICATION_JSON).build();
}
Also used : Stateless(javax.ejb.Stateless) PathParam(javax.ws.rs.PathParam) Logger(org.slf4j.Logger) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) LoggerFactory(org.slf4j.LoggerFactory) Path(javax.ws.rs.Path) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) EntityManager(javax.persistence.EntityManager) PersistenceContext(javax.persistence.PersistenceContext) Collectors(java.util.stream.Collectors) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) Timed(dk.dbc.search.solrdocstore.monitor.Timed) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) Inject(javax.inject.Inject) Query(javax.persistence.Query) MediaType(javax.ws.rs.core.MediaType) List(java.util.List) QueryParam(javax.ws.rs.QueryParam) Response(javax.ws.rs.core.Response) DefaultValue(javax.ws.rs.DefaultValue) Query(javax.persistence.Query) List(java.util.List) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) Timed(dk.dbc.search.solrdocstore.monitor.Timed) GET(javax.ws.rs.GET)

Example 72 with PathParam

use of javax.ws.rs.PathParam in project mod-inventory-storage by folio-org.

the class ItemStorageAPI method putItemStorageItemsByItemId.

@Validate
@Override
public void putItemStorageItemsByItemId(@PathParam("itemId") @NotNull String itemId, @QueryParam("lang") @DefaultValue("en") @Pattern(regexp = "[a-zA-Z]{2}") String lang, Item entity, java.util.Map<String, String> okapiHeaders, io.vertx.core.Handler<io.vertx.core.AsyncResult<Response>> asyncResultHandler, Context vertxContext) throws Exception {
    String tenantId = okapiHeaders.get(TENANT_HEADER);
    try {
        PostgresClient postgresClient = PostgresClient.getInstance(vertxContext.owner(), TenantTool.calculateTenantId(tenantId));
        vertxContext.runOnContext(v -> {
            try {
                getMaterialType(vertxContext.owner(), tenantId, entity, replyHandler -> {
                    int res = replyHandler.result();
                    if (res == 0) {
                        String message = "Can not add " + entity.getMaterialTypeId() + ". Material type not found";
                        log.error(message);
                        asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(PutItemStorageItemsByItemIdResponse.withPlainBadRequest(message)));
                    } else if (res == -1) {
                        asyncResultHandler.handle(Future.succeededFuture(ItemStorageResource.PostItemStorageItemsResponse.withPlainInternalServerError("")));
                    } else {
                        try {
                            String[] fieldList = { "*" };
                            String query = String.format("id==%s", itemId);
                            CQLWrapper cql = getCQL(query, 1, 0);
                            log.info(String.format("SQL generated from CQL: %s", cql.toString()));
                            postgresClient.get(getTableName(query), Item.class, fieldList, cql, true, false, reply -> {
                                if (reply.succeeded()) {
                                    List<Item> itemList = (List<Item>) reply.result().getResults();
                                    if (itemList.size() == 1) {
                                        try {
                                            postgresClient.update("item", entity, entity.getId(), update -> {
                                                try {
                                                    if (update.succeeded()) {
                                                        OutStream stream = new OutStream();
                                                        stream.setData(entity);
                                                        asyncResultHandler.handle(Future.succeededFuture(PutItemStorageItemsByItemIdResponse.withNoContent()));
                                                    } else {
                                                        String message = PgExceptionUtil.badRequestMessage(update.cause());
                                                        if (message != null) {
                                                            asyncResultHandler.handle(Future.succeededFuture(PutItemStorageItemsByItemIdResponse.withPlainBadRequest(message)));
                                                        } else {
                                                            asyncResultHandler.handle(Future.succeededFuture(PutItemStorageItemsByItemIdResponse.withPlainInternalServerError(update.cause().getMessage())));
                                                        }
                                                    }
                                                } catch (Exception e) {
                                                    asyncResultHandler.handle(Future.succeededFuture(PostItemStorageItemsResponse.withPlainInternalServerError(e.getMessage())));
                                                }
                                            });
                                        } catch (Exception e) {
                                            asyncResultHandler.handle(Future.succeededFuture(PutItemStorageItemsByItemIdResponse.withPlainInternalServerError(e.getMessage())));
                                        }
                                    } else {
                                        try {
                                            postgresClient.save("item", entity.getId(), entity, save -> {
                                                try {
                                                    if (save.succeeded()) {
                                                        OutStream stream = new OutStream();
                                                        stream.setData(entity);
                                                        asyncResultHandler.handle(Future.succeededFuture(PutItemStorageItemsByItemIdResponse.withNoContent()));
                                                    } else {
                                                        asyncResultHandler.handle(Future.succeededFuture(PutItemStorageItemsByItemIdResponse.withPlainInternalServerError(save.cause().getMessage())));
                                                    }
                                                } catch (Exception e) {
                                                    asyncResultHandler.handle(Future.succeededFuture(PostItemStorageItemsResponse.withPlainInternalServerError(e.getMessage())));
                                                }
                                            });
                                        } catch (Exception e) {
                                            asyncResultHandler.handle(Future.succeededFuture(PutItemStorageItemsByItemIdResponse.withPlainInternalServerError(e.getMessage())));
                                        }
                                    }
                                } else {
                                    asyncResultHandler.handle(Future.succeededFuture(PutItemStorageItemsByItemIdResponse.withPlainInternalServerError(reply.cause().getMessage())));
                                }
                            });
                        } catch (Exception e) {
                            asyncResultHandler.handle(Future.succeededFuture(ItemStorageResource.PostItemStorageItemsResponse.withPlainInternalServerError(e.getMessage())));
                        }
                    }
                });
            } catch (Exception e) {
                asyncResultHandler.handle(Future.succeededFuture(ItemStorageResource.PostItemStorageItemsResponse.withPlainInternalServerError(e.getMessage())));
            }
        });
    } catch (Exception e) {
        asyncResultHandler.handle(Future.succeededFuture(ItemStorageResource.PostItemStorageItemsResponse.withPlainInternalServerError(e.getMessage())));
    }
}
Also used : PathParam(javax.ws.rs.PathParam) Arrays(java.util.Arrays) CQLWrapper(org.folio.rest.persist.cql.CQLWrapper) io.vertx.core(io.vertx.core) Criteria(org.folio.rest.persist.Criteria.Criteria) LoggerFactory(io.vertx.core.logging.LoggerFactory) QueryParam(javax.ws.rs.QueryParam) Limit(org.folio.rest.persist.Criteria.Limit) PgExceptionUtil(org.folio.rest.persist.PgExceptionUtil) Map(java.util.Map) DefaultValue(javax.ws.rs.DefaultValue) FieldException(org.z3950.zing.cql.cql2pgjson.FieldException) Offset(org.folio.rest.persist.Criteria.Offset) Logger(io.vertx.core.logging.Logger) ItemStorageResource(org.folio.rest.jaxrs.resource.ItemStorageResource) UUID(java.util.UUID) NotNull(javax.validation.constraints.NotNull) Validate(org.folio.rest.annotations.Validate) TenantTool(org.folio.rest.tools.utils.TenantTool) PostgresClient(org.folio.rest.persist.PostgresClient) org.folio.rest.jaxrs.model(org.folio.rest.jaxrs.model) OutStream(org.folio.rest.tools.utils.OutStream) List(java.util.List) Criterion(org.folio.rest.persist.Criteria.Criterion) Response(javax.ws.rs.core.Response) Pattern(javax.validation.constraints.Pattern) CQL2PgJSON(org.z3950.zing.cql.cql2pgjson.CQL2PgJSON) PostgresClient(org.folio.rest.persist.PostgresClient) List(java.util.List) OutStream(org.folio.rest.tools.utils.OutStream) CQLWrapper(org.folio.rest.persist.cql.CQLWrapper) FieldException(org.z3950.zing.cql.cql2pgjson.FieldException) Validate(org.folio.rest.annotations.Validate)

Example 73 with PathParam

use of javax.ws.rs.PathParam in project raml-module-builder by folio-org.

the class AnnotationGrabber method getParameterNames.

public static JsonObject getParameterNames(Method method) throws Exception {
    // need to handle default values
    JsonObject retObject = new JsonObject();
    Parameter[] nonAnnotationParams = method.getParameters();
    Annotation[][] annotations = method.getParameterAnnotations();
    Class[] parameterTypes = method.getParameterTypes();
    int k = 0;
    for (Annotation[] annotation : annotations) {
        Class parameterType = parameterTypes[k++];
        if (annotation.length == 0) {
            // we are here because - there is a param but it is not annotated - this
            // will occur for post / put
            // requests - the entity to save/update will not be annotated
            JsonObject obj = null;
            obj = new JsonObject();
            // this will be
            obj.put("value", nonAnnotationParams[k - 1].getName());
            // a generic
            // name - unless
            // debug info
            // turned on for
            // javac (store
            // information
            // about method
            // parameters)
            obj.put("type", parameterType.getCanonicalName());
            obj.put("order", k - 1);
            obj.put("param_type", NON_ANNOTATED_PARAM);
            retObject.put("" + (k - 1), obj);
        }
        JsonObject prevObjForDefaultVal = null;
        for (Annotation a : annotation) {
            JsonObject obj = null;
            if (a instanceof HeaderParam) {
                obj = new JsonObject();
                obj.put("value", ((HeaderParam) a).value());
                obj.put("type", parameterType.getCanonicalName());
                obj.put("order", k - 1);
                obj.put("param_type", HEADER_PARAM);
            } else if (a instanceof PathParam) {
                obj = new JsonObject();
                obj.put("value", ((PathParam) a).value());
                obj.put("type", parameterType.getCanonicalName());
                obj.put("order", k - 1);
                obj.put("param_type", PATH_PARAM);
            } else if (a instanceof QueryParam) {
                obj = new JsonObject();
                obj.put("value", ((QueryParam) a).value());
                obj.put("type", parameterType.getCanonicalName());
                obj.put("order", k - 1);
                obj.put("param_type", QUERY_PARAM);
            } else if (a instanceof DefaultValue && prevObjForDefaultVal != null) {
                // default values originate in the raml and appear after the parameter
                // they are to be applied to
                String defaultValue = ((DefaultValue) a).value();
                // push it into the previously scanned parameter
                prevObjForDefaultVal.put("default_value", defaultValue);
                prevObjForDefaultVal = null;
            }
            if (obj != null) {
                prevObjForDefaultVal = obj;
                // obj may be null in case of @DefaultValue annotation which i am
                // currently ignoring
                retObject.put("" + (k - 1), obj);
            }
        }
    }
    return retObject;
}
Also used : HeaderParam(javax.ws.rs.HeaderParam) JsonObject(io.vertx.core.json.JsonObject) Annotation(java.lang.annotation.Annotation) DefaultValue(javax.ws.rs.DefaultValue) QueryParam(javax.ws.rs.QueryParam) Parameter(java.lang.reflect.Parameter) PathParam(javax.ws.rs.PathParam)

Example 74 with PathParam

use of javax.ws.rs.PathParam in project candlepin by candlepin.

the class ResourceLocatorMap method logLocators.

/**
 * Log what resources have been detected and warn about missing media types.
 *
 * Not having a @Produces annotation on a method can have subtle effects on the way Resteasy
 * resolves which method to dispatch a request to.
 *
 * Resource resolution order is detailed in the JAX-RS 2.0 specification in section 3.7.2.
 * Consider the following
 *
 *   @PUT
 *   @Path("/foo")
 *   public String methodOne() {
 *       ...
 *   }
 *
 *   @PUT
 *   @Path("/{id}")
 *   @Produces(MediaType.APPLICATION_JSON)
 *   public String methodTwo(@PathParam("id") String id) {
 *       ....
 *   }
 *
 *   With a cursory reading of the specification, it appears that a request to
 *
 *   PUT /foo
 *
 *   should result in methodOne being selected since methodOne's Path has more
 *   literal characters than methodTwo.  However, methodTwo has a specific media
 *   type defined and methodOne does not (thus using the wildcard type as a default),
 *   methodTwo is actually the resource selected.
 *
 *   The same rules apply for @Consumes annotations.
 */
protected void logLocators() {
    StringBuffer registered = new StringBuffer("Registered the following RESTful methods:\n");
    StringBuffer missingProduces = new StringBuffer();
    StringBuffer missingConsumes = new StringBuffer();
    for (Method m : keySet()) {
        String name = m.getDeclaringClass() + "." + m.getName();
        registered.append("\t" + name + "\n");
        if (!m.isAnnotationPresent(Produces.class)) {
            missingProduces.append("\t" + name + "\n");
        }
        if (m.isAnnotationPresent(GET.class) || m.isAnnotationPresent(HEAD.class) || m.isAnnotationPresent(DELETE.class) || m.isAnnotationPresent(Deprecated.class)) {
            /* Technically GET, HEAD, and DELETE are allowed to have bodies (and therefore would
                 * need a Consumes annotation, but the HTTP 1.1 spec states in section 4.3 that any
                 * such body should be ignored.  See http://stackoverflow.com/a/983458/6124862
                 *
                 * Therefore, we won't print warnings on unannotated GET, HEAD, and DELETE methods.
                 *
                 * Deprecated methods are not expected to be updated.
                 */
            continue;
        }
        if (!m.isAnnotationPresent(Consumes.class)) {
            missingConsumes.append("\t" + name + "\n");
        } else {
            /* The purpose of all the ridiculousness below is to find methods that
                 * bind objects from the HTTP request body but that are marked as consuming
                 * the star slash star wildcard mediatype.  Candlepin only consumes JSON
                 * at the moment but even if that changes we still want to be explicit
                 * about what we accept.
                 */
            Consumes consumes = m.getAnnotation(Consumes.class);
            List<String> mediaTypes = Arrays.asList(consumes.value());
            if (mediaTypes.contains(MediaType.WILDCARD)) {
                Annotation[][] allParamAnnotations = m.getParameterAnnotations();
                boolean bindsBody = false;
                for (Annotation[] paramAnnotations : allParamAnnotations) {
                    boolean boundObjectFromBody = true;
                    for (Annotation a : paramAnnotations) {
                        Class<? extends Annotation> clazz = a.annotationType();
                        if (QueryParam.class.isAssignableFrom(clazz) || PathParam.class.isAssignableFrom(clazz) || MatrixParam.class.isAssignableFrom(clazz) || HeaderParam.class.isAssignableFrom(clazz) || FormParam.class.isAssignableFrom(clazz) || CookieParam.class.isAssignableFrom(clazz)) {
                            boundObjectFromBody = false;
                            continue;
                        }
                    }
                    bindsBody = bindsBody || boundObjectFromBody;
                }
                if (bindsBody) {
                    log.warn("{} consumes a wildcard media type but binds an object from" + " the request body.  Define specific media types consumed instead.", name);
                }
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.trace(registered.toString());
    }
    if (missingProduces.length() != 0) {
        log.warn("The following methods are missing a Produces annotation:\n{}", missingProduces);
    }
    if (missingConsumes.length() != 0) {
        log.warn("The following methods are missing a Consumes annotation:\n{}", missingConsumes);
    }
}
Also used : HEAD(javax.ws.rs.HEAD) HeaderParam(javax.ws.rs.HeaderParam) ResourceMethod(org.jboss.resteasy.spi.metadata.ResourceMethod) Method(java.lang.reflect.Method) Annotation(java.lang.annotation.Annotation) CookieParam(javax.ws.rs.CookieParam) Produces(javax.ws.rs.Produces) Consumes(javax.ws.rs.Consumes) QueryParam(javax.ws.rs.QueryParam) GET(javax.ws.rs.GET) PathParam(javax.ws.rs.PathParam)

Example 75 with PathParam

use of javax.ws.rs.PathParam in project plugin-prov by ligoj.

the class TerraformResource method getTerraformLog.

/**
 * Get the log of the current or last Terraform execution of a given subscription.
 *
 * @param subscription
 *            The related subscription.
 * @return the streaming {@link Response} with output.
 * @throws IOException
 *             When Terraform content cannot be written.
 */
@GET
@Produces(MediaType.TEXT_HTML)
@Path("{subscription:\\d+}/terraform.log")
public Response getTerraformLog(@PathParam("subscription") final int subscription) throws IOException {
    final Subscription entity = subscriptionResource.checkVisibleSubscription(subscription);
    final File log = toFile(entity, MAIN_LOG);
    // Check there is a log file
    if (log.exists()) {
        final StreamingOutput so = o -> FileUtils.copyFile(toFile(entity, MAIN_LOG), o);
        return Response.ok().entity(so).build();
    }
    // No log file for now
    return Response.status(Status.NOT_FOUND).build();
}
Also used : PathParam(javax.ws.rs.PathParam) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Produces(javax.ws.rs.Produces) CacheRemoveAll(javax.cache.annotation.CacheRemoveAll) GET(javax.ws.rs.GET) Path(javax.ws.rs.Path) Autowired(org.springframework.beans.factory.annotation.Autowired) ArrayUtils(org.apache.commons.lang3.ArrayUtils) AbstractToolPluginResource(org.ligoj.app.resource.plugin.AbstractToolPluginResource) MediaType(javax.ws.rs.core.MediaType) Matcher(java.util.regex.Matcher) ServicePluginLocator(org.ligoj.app.resource.ServicePluginLocator) NodeResource(org.ligoj.app.resource.node.NodeResource) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Service(org.springframework.stereotype.Service) Subscription(org.ligoj.app.model.Subscription) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) Status(javax.ws.rs.core.Response.Status) PrintWriter(java.io.PrintWriter) POST(javax.ws.rs.POST) Node(org.ligoj.app.model.Node) Transactional(javax.transaction.Transactional) QuoteVo(org.ligoj.app.plugin.prov.QuoteVo) FileWriter(java.io.FileWriter) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) StreamingOutput(javax.ws.rs.core.StreamingOutput) FileUtils(org.apache.commons.io.FileUtils) BusinessException(org.ligoj.bootstrap.core.resource.BusinessException) SubscriptionResource(org.ligoj.app.resource.subscription.SubscriptionResource) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) Executors(java.util.concurrent.Executors) CacheResult(javax.cache.annotation.CacheResult) IOUtils(org.apache.commons.io.IOUtils) Slf4j(lombok.extern.slf4j.Slf4j) Response(javax.ws.rs.core.Response) SecurityContext(org.springframework.security.core.context.SecurityContext) Writer(java.io.Writer) Optional(java.util.Optional) ProvResource(org.ligoj.app.plugin.prov.ProvResource) Pattern(java.util.regex.Pattern) PluginsClassLoader(org.ligoj.app.resource.plugin.PluginsClassLoader) StreamingOutput(javax.ws.rs.core.StreamingOutput) Subscription(org.ligoj.app.model.Subscription) File(java.io.File) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Aggregations

PathParam (javax.ws.rs.PathParam)127 Path (javax.ws.rs.Path)105 GET (javax.ws.rs.GET)96 Produces (javax.ws.rs.Produces)96 Response (javax.ws.rs.core.Response)93 QueryParam (javax.ws.rs.QueryParam)82 List (java.util.List)72 MediaType (javax.ws.rs.core.MediaType)72 POST (javax.ws.rs.POST)71 DELETE (javax.ws.rs.DELETE)70 Consumes (javax.ws.rs.Consumes)66 Inject (javax.inject.Inject)62 Api (io.swagger.annotations.Api)60 ApiOperation (io.swagger.annotations.ApiOperation)59 Map (java.util.Map)59 ApiResponse (io.swagger.annotations.ApiResponse)58 ApiResponses (io.swagger.annotations.ApiResponses)57 Collectors (java.util.stream.Collectors)57 Logger (org.slf4j.Logger)52 LoggerFactory (org.slf4j.LoggerFactory)52