use of javax.ws.rs.core.UriInfo in project indy by Commonjava.
the class DeprecatedFoloContentAccessResource method doHead.
@ApiOperation("Store and track file/artifact content under the given artifact store (type/name) and path.")
@ApiResponses({ @ApiResponse(code = 404, message = "Content is not available"), @ApiResponse(code = 200, message = "Header metadata for content (or rendered listing when path ends with '/index.html' or '/'") })
@HEAD
@Path("/{path: (.*)}")
public Response doHead(@ApiParam("User-assigned tracking session key") @PathParam("id") final String id, @ApiParam(allowableValues = "hosted,group,remote", required = true) @PathParam("type") final String type, @PathParam("name") final String name, @PathParam("path") final String path, @QueryParam(CHECK_CACHE_ONLY) final Boolean cacheOnly, @Context final HttpServletRequest request, @Context final UriInfo uriInfo) {
final TrackingKey tk = new TrackingKey(id);
final String baseUri = uriInfo.getBaseUriBuilder().path(BASE_PATH).path(id).build().toString();
EventMetadata metadata = new EventMetadata().set(TRACKING_KEY, tk).set(ACCESS_CHANNEL, AccessChannel.MAVEN_REPO);
final Consumer<Response.ResponseBuilder> deprecation = builder -> {
String alt = Paths.get("/api/folo/track/", id, MAVEN_PKG_KEY, type, name, path).toString();
markDeprecated(builder, alt);
};
return handler.doHead(MAVEN_PKG_KEY, type, name, path, cacheOnly, baseUri, request, metadata, deprecation);
}
use of javax.ws.rs.core.UriInfo in project indy by Commonjava.
the class DeprecatedFoloContentAccessResource method doGet.
@ApiOperation("Retrieve and track file/artifact content under the given artifact store (type/name) and path.")
@ApiResponses({ @ApiResponse(code = 404, message = "Content is not available"), @ApiResponse(code = 200, response = String.class, message = "Rendered content listing (when path ends with '/index.html' or '/')"), @ApiResponse(code = 200, response = StreamingOutput.class, message = "Content stream") })
@GET
@Path("/{path: (.*)}")
public Response doGet(@ApiParam("User-assigned tracking session key") @PathParam("id") final String id, @ApiParam(allowableValues = "hosted,group,remote", required = true) @PathParam("type") final String type, @PathParam("name") final String name, @PathParam("path") final String path, @Context final HttpServletRequest request, @Context final UriInfo uriInfo) {
final TrackingKey tk = new TrackingKey(id);
final String baseUri = uriInfo.getBaseUriBuilder().path(BASE_PATH).path(id).build().toString();
EventMetadata metadata = new EventMetadata().set(TRACKING_KEY, tk).set(ACCESS_CHANNEL, AccessChannel.MAVEN_REPO);
final Consumer<Response.ResponseBuilder> deprecation = builder -> {
String alt = Paths.get("/api/folo/track/", id, MAVEN_PKG_KEY, type, name, path).toString();
markDeprecated(builder, alt);
};
return handler.doGet(MAVEN_PKG_KEY, type, name, path, baseUri, request, metadata, deprecation);
}
use of javax.ws.rs.core.UriInfo in project tomee by apache.
the class Contexts method bind.
/**
* Using a set ensures we don't set the thread local twice or more,
* there may be super classes with injection points of identical types
* <p/>
* Also allows us to get context references from other sources such as interceptors
*
* @param exchange Exchange
* @param types Collection
*/
public static void bind(final Exchange exchange, final Collection<Class<?>> types) {
// used in lazy mode by RESTResourceFinder if cdi beans uses @Context, === initThreadLocal
EXCHANGE.set(exchange);
CdiAppContextsService.pushRequestReleasable(CleanUpThreadLocal.INSTANCE);
for (final Class<?> type : types) {
if (Request.class.equals(type)) {
final Request binding = JAXRSUtils.createContextValue(exchange.getInMessage(), null, Request.class);
ThreadLocalContextManager.REQUEST.set(binding);
} else if (UriInfo.class.equals(type)) {
final UriInfo binding = JAXRSUtils.createContextValue(exchange.getInMessage(), null, UriInfo.class);
ThreadLocalContextManager.URI_INFO.set(binding);
} else if (HttpHeaders.class.equals(type)) {
final HttpHeaders binding = JAXRSUtils.createContextValue(exchange.getInMessage(), null, HttpHeaders.class);
ThreadLocalContextManager.HTTP_HEADERS.set(binding);
} else if (SecurityContext.class.equals(type)) {
final SecurityContext binding = JAXRSUtils.createContextValue(exchange.getInMessage(), null, SecurityContext.class);
ThreadLocalContextManager.SECURITY_CONTEXT.set(binding);
} else if (ContextResolver.class.equals(type)) {
final ContextResolver<?> binding = JAXRSUtils.createContextValue(exchange.getInMessage(), type, ContextResolver.class);
ThreadLocalContextManager.CONTEXT_RESOLVER.set(binding);
} else if (Providers.class.equals(type)) {
final Providers providers = JAXRSUtils.createContextValue(exchange.getInMessage(), null, Providers.class);
ThreadLocalContextManager.PROVIDERS.set(providers);
} else if (ServletRequest.class.equals(type)) {
ServletRequest servletRequest = JAXRSUtils.createContextValue(exchange.getInMessage(), null, ServletRequest.class);
if (servletRequest == null) {
// probably the case with CXF
servletRequest = JAXRSUtils.createContextValue(exchange.getInMessage(), null, HttpServletRequest.class);
}
ThreadLocalContextManager.SERVLET_REQUEST.set(servletRequest);
} else if (HttpServletRequest.class.equals(type)) {
final HttpServletRequest httpServletRequest = JAXRSUtils.createContextValue(exchange.getInMessage(), null, HttpServletRequest.class);
ThreadLocalContextManager.HTTP_SERVLET_REQUEST.set(httpServletRequest);
} else if (HttpServletResponse.class.equals(type)) {
final HttpServletResponse httpServletResponse = JAXRSUtils.createContextValue(exchange.getInMessage(), null, HttpServletResponse.class);
ThreadLocalContextManager.HTTP_SERVLET_RESPONSE.set(httpServletResponse);
} else if (ServletConfig.class.equals(type)) {
final ServletConfig servletConfig = JAXRSUtils.createContextValue(exchange.getInMessage(), null, ServletConfig.class);
ThreadLocalContextManager.SERVLET_CONFIG.set(servletConfig);
} else if (Configuration.class.equals(type)) {
final Configuration config = JAXRSUtils.createContextValue(exchange.getInMessage(), null, Configuration.class);
ThreadLocalContextManager.CONFIGURATION.set(config);
} else if (ResourceInfo.class.equals(type)) {
final ResourceInfo config = JAXRSUtils.createContextValue(exchange.getInMessage(), null, ResourceInfo.class);
ThreadLocalContextManager.RESOURCE_INFO.set(config);
} else if (ResourceContext.class.equals(type)) {
final ResourceContext config = JAXRSUtils.createContextValue(exchange.getInMessage(), null, ResourceContext.class);
ThreadLocalContextManager.RESOURCE_CONTEXT.set(config);
} else {
final Message message = exchange.getInMessage();
final ContextProvider<?> provider = ProviderFactory.getInstance(message).createContextProvider(type, message);
if (provider != null) {
final Object value = provider.createContext(message);
Map<String, Object> map = ThreadLocalContextManager.OTHERS.get();
if (map == null) {
map = new HashMap<>();
ThreadLocalContextManager.OTHERS.set(map);
}
map.put(type.getName(), value);
}
}
}
}
use of javax.ws.rs.core.UriInfo in project ddf by codice.
the class TestRestEndpoint method testAddDocumentWithMetadataPositiveCase.
@Test
public void testAddDocumentWithMetadataPositiveCase() throws IOException, CatalogTransformerException, IngestException, SourceUnavailableException, URISyntaxException, InvalidSyntaxException, MimeTypeResolutionException {
CatalogFramework framework = givenCatalogFramework(SAMPLE_ID);
HttpHeaders headers = createHeaders(Arrays.asList(MediaType.APPLICATION_JSON));
BundleContext bundleContext = mock(BundleContext.class);
Collection<ServiceReference<InputTransformer>> serviceReferences = new ArrayList<>();
ServiceReference serviceReference = mock(ServiceReference.class);
InputTransformer inputTransformer = mock(InputTransformer.class);
when(inputTransformer.transform(any())).thenReturn(new MetacardImpl());
when(bundleContext.getService(serviceReference)).thenReturn(inputTransformer);
serviceReferences.add(serviceReference);
when(bundleContext.getServiceReferences(InputTransformer.class, "(id=xml)")).thenReturn(serviceReferences);
RESTEndpoint rest = new RESTEndpoint(framework) {
@Override
BundleContext getBundleContext() {
return bundleContext;
}
};
UuidGenerator uuidGenerator = mock(UuidGenerator.class);
when(uuidGenerator.generateUuid()).thenReturn(UUID.randomUUID().toString());
rest.setUuidGenerator(uuidGenerator);
rest.setMetacardTypes(Collections.singletonList(BasicTypes.BASIC_METACARD));
MimeTypeMapper mimeTypeMapper = mock(MimeTypeMapper.class);
when(mimeTypeMapper.getMimeTypeForFileExtension("txt")).thenReturn("text/plain");
when(mimeTypeMapper.getMimeTypeForFileExtension("xml")).thenReturn("text/xml");
rest.setMimeTypeMapper(mimeTypeMapper);
addMatchingService(rest, Arrays.asList(getSimpleTransformer()));
UriInfo info = givenUriInfo(SAMPLE_ID);
List<Attachment> attachments = new ArrayList<>();
ContentDisposition contentDisposition = new ContentDisposition("form-data; name=parse.resource; filename=C:\\DDF\\metacard.txt");
Attachment attachment = new Attachment("parse.resource", new ByteArrayInputStream("Some Text".getBytes()), contentDisposition);
attachments.add(attachment);
ContentDisposition contentDisposition1 = new ContentDisposition("form-data; name=parse.metadata; filename=C:\\DDF\\metacard.xml");
Attachment attachment1 = new Attachment("parse.metadata", new ByteArrayInputStream("Some Text Again".getBytes()), contentDisposition1);
attachments.add(attachment1);
ContentDisposition contentDisposition2 = new ContentDisposition("form-data; name=metadata; filename=C:\\DDF\\metacard.xml");
Attachment attachment2 = new Attachment("metadata", new ByteArrayInputStream("<meta>beta</meta>".getBytes()), contentDisposition2);
attachments.add(attachment2);
MultipartBody multipartBody = new MultipartBody(attachments);
Response response = rest.addDocument(headers, info, mock(HttpServletRequest.class), multipartBody, null, new ByteArrayInputStream("".getBytes()));
LOGGER.debug(ToStringBuilder.reflectionToString(response));
assertThat(response.getStatus(), equalTo(201));
assertThat(response.getMetadata(), notNullValue());
assertThat(response.getMetadata().get(Metacard.ID).get(0).toString(), equalTo(SAMPLE_ID));
}
use of javax.ws.rs.core.UriInfo in project ddf by codice.
the class TestRestEndpoint method testGetMetacardAsXml.
/**
* Tests that a geojson input has its InputTransformer invoked by the REST endpoint to create
* a metacard that is then converted to XML and returned from the REST endpoint.
*
* @throws Exception
*/
@Test
public void testGetMetacardAsXml() throws Exception {
String filename = "src/test/resources/ValidGeojson.json";
CatalogFramework framework = givenCatalogFramework(SAMPLE_ID);
String metacardXml = "<metacard ns2:id=\"assigned-when-ingested\">\r\n" + "<type>type.metacard</type>\r\n" + "<string name=\"title\">\r\n" + "<value>Title goes here ...</value>\r\n" + "</string>\r\n" + "<string name=\"metadata\">\r\n" + "<value>metadata goes here ...</value>\r\n" + "</metacard>";
// Mock XmlMetacardTransformer that CatalogFramework will call to convert generated
// metacard into XML to be returned from REST endpoint.
final BinaryContent content = mock(BinaryContent.class);
InputStream inputStream = new ByteArrayInputStream(metacardXml.getBytes(GET_OUTPUT_TYPE));
when(content.getInputStream()).thenReturn(inputStream);
when(content.getMimeTypeValue()).thenReturn("application/json;id=geojson");
when(framework.transform(isA(Metacard.class), anyString(), isNull(Map.class))).thenAnswer(new Answer<BinaryContent>() {
@Override
public BinaryContent answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
Metacard metacard = (Metacard) args[0];
return content;
}
});
RESTEndpoint restEndpoint = new RESTEndpoint(framework);
// Add a MimeTypeToINputTransformer that the REST endpoint will call to create the metacard
addMatchingService(restEndpoint, Arrays.asList(getSimpleTransformer()));
restEndpoint.setTikaMimeTypeResolver(new TikaMimeTypeResolver());
FilterBuilder filterBuilder = new GeotoolsFilterBuilder();
restEndpoint.setFilterBuilder(filterBuilder);
String json = "{\r\n" + " \"properties\": {\r\n" + " \"title\": \"myTitle\",\r\n" + " \"thumbnail\": \"CA==\",\r\n" + " \"resource-uri\": \"http://example.com\",\r\n" + " \"created\": \"2012-09-01T00:09:19.368+0000\",\r\n" + " \"metadata-content-type-version\": \"myVersion\",\r\n" + " \"metadata-content-type\": \"myType\",\r\n" + " \"metadata\": \"<xml>metadata goes here ...</xml>\",\r\n" + " \"modified\": \"2012-09-01T00:09:19.368+0000\"\r\n" + " },\r\n" + " \"type\": \"Feature\",\r\n" + " \"geometry\": {\r\n" + " \"type\": \"Point\",\r\n" + " \"coordinates\": [\r\n" + " 30.0,\r\n" + " 10.0\r\n" + " ]\r\n" + " }\r\n" + "} ";
// Sample headers for a multipart body specifying a geojson file to have a metacard created for:
// Content-Disposition: form-data; name="file"; filename="C:\DDF\geojson_valid.json"
// Content-Type: application/json;id=geojson
InputStream is = IOUtils.toInputStream(json);
List<Attachment> attachments = new ArrayList<>();
ContentDisposition contentDisposition = new ContentDisposition("form-data; name=file; filename=C:\\DDF\\geojson_valid.json");
Attachment attachment = new Attachment("file_part", is, contentDisposition);
attachments.add(attachment);
MediaType mediaType = new MediaType(MediaType.APPLICATION_JSON, "id=geojson");
MultipartBody multipartBody = new MultipartBody(attachments, mediaType, true);
UriInfo uriInfo = createSpecificUriInfo(LOCAL_RETRIEVE_ADDRESS);
Response response = restEndpoint.createMetacard(multipartBody, uriInfo, RESTEndpoint.DEFAULT_METACARD_TRANSFORMER);
assertEquals(OK, response.getStatus());
InputStream responseEntity = (InputStream) response.getEntity();
String responseXml = IOUtils.toString(responseEntity);
assertEquals(metacardXml, responseXml);
}
Aggregations