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();
}
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())));
}
}
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;
}
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);
}
}
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();
}
Aggregations