Search in sources :

Example 1 with ResourceInfo

use of org.ops4j.pax.web.resources.api.ResourceInfo in project org.ops4j.pax.web by ops4j.

the class AbstractWarJsfResourcehandlerIntegrationTest method testResourceUnavailble.

/**
 * After a JSF thread received a resource, the bundle with the resource might be uninstalled
 * anyway. This can happen before the actual bytes are served.
 * <p>
 * <ol>
 * <li>createResource</li>
 * <li>resourcebundle uninstalled</li>
 * <li>resource.getInputStream</li>
 * </ol>
 * <p>
 * According to the spec, IOException is the only one catched later on.
 */
@Test(expected = IOException.class)
public void testResourceUnavailble() throws Exception {
    ServiceReference<OsgiResourceLocator> sr = bundleContext.getServiceReference(OsgiResourceLocator.class);
    OsgiResourceLocator resourceLocator = bundleContext.getService(sr);
    ResourceInfo resourceInfo = resourceLocator.locateResource("default/2_0/images/iceland.jpg");
    Resource resource = new OsgiResource(resourceInfo.getUrl(), null, "iceland.jpg", null, "default", "2_0", resourceInfo.getLastModified());
    // uninstall bundle
    Arrays.stream(bundleContext.getBundles()).filter(bundle -> bundle.getSymbolicName().equals("jsf-resourcehandler-resourcebundle")).findFirst().orElseThrow(() -> new AssertionError("Bundle 'jsf-resourcehandler-resourcebundle' not found")).uninstall();
    // to fast for tests, resource isn't fully gone yet
    Thread.sleep(1000);
    try {
        resource.getInputStream();
        fail("IOException expected due to missing resource!");
    } finally {
        bundleContext.ungetService(sr);
    }
}
Also used : Arrays(java.util.Arrays) Constants(org.osgi.framework.Constants) URL(java.net.URL) ResourceQueryResult(org.ops4j.pax.web.resources.api.query.ResourceQueryResult) ZonedDateTime(java.time.ZonedDateTime) LocalDateTime(java.time.LocalDateTime) IndexedOsgiResourceLocator(org.ops4j.pax.web.resources.extender.internal.IndexedOsgiResourceLocator) StringUtils(org.apache.commons.lang3.StringUtils) ResourceInfo(org.ops4j.pax.web.resources.api.ResourceInfo) Resource(javax.faces.application.Resource) FacesContext(javax.faces.context.FacesContext) OsgiResource(org.ops4j.pax.web.resources.jsf.OsgiResource) HttpTestClientFactory(org.ops4j.pax.web.itest.base.client.HttpTestClientFactory) Assert.fail(org.junit.Assert.fail) Bundle(org.osgi.framework.Bundle) BundleMatchers(org.ops4j.pax.web.itest.base.assertion.BundleMatchers) ServiceReference(org.osgi.framework.ServiceReference) MalformedURLException(java.net.MalformedURLException) Collection(java.util.Collection) Test(org.junit.Test) IOException(java.io.IOException) Assert.assertThat(org.ops4j.pax.web.itest.base.assertion.Assert.assertThat) OsgiResourceLocator(org.ops4j.pax.web.resources.api.OsgiResourceLocator) ZoneId(java.time.ZoneId) CoreOptions.mavenBundle(org.ops4j.pax.exam.CoreOptions.mavenBundle) WaitCondition2(org.ops4j.pax.web.itest.base.WaitCondition2) ResourceQueryMatcher(org.ops4j.pax.web.resources.api.query.ResourceQueryMatcher) DateTimeFormatter(java.time.format.DateTimeFormatter) FrameworkUtil(org.osgi.framework.FrameworkUtil) ResourceInfo(org.ops4j.pax.web.resources.api.ResourceInfo) IndexedOsgiResourceLocator(org.ops4j.pax.web.resources.extender.internal.IndexedOsgiResourceLocator) OsgiResourceLocator(org.ops4j.pax.web.resources.api.OsgiResourceLocator) OsgiResource(org.ops4j.pax.web.resources.jsf.OsgiResource) Resource(javax.faces.application.Resource) OsgiResource(org.ops4j.pax.web.resources.jsf.OsgiResource) Test(org.junit.Test)

Example 2 with ResourceInfo

use of org.ops4j.pax.web.resources.api.ResourceInfo in project org.ops4j.pax.web by ops4j.

the class OsgiResourceHandler method handleResourceRequest.

@Override
public void handleResourceRequest(FacesContext facesContext) throws IOException {
    final Map<String, String> requestParameterMap = facesContext.getExternalContext().getRequestParameterMap();
    if (!"osgi".equals(requestParameterMap.get(OsgiResource.REQUEST_PARAM_TYPE))) {
        // no OsgiResource...proceed with default ResourceHandler
        super.handleResourceRequest(facesContext);
    }
    String localePrefix = requestParameterMap.get(OsgiResource.REQUEST_PARAM_LOCALE);
    String libraryName = requestParameterMap.get(OsgiResource.REQUEST_PARAM_LIBRARY);
    String libraryVersion = requestParameterMap.get(OsgiResource.REQUEST_PARAM_LIBRARY_VERSION);
    String resourceVersion = requestParameterMap.get(OsgiResource.REQUEST_PARAM_RESOURCE_VERSION);
    String resourceBasePath = ResourceHandlerUtils.calculateResourceBasePath(facesContext);
    if (resourceBasePath == null) {
        // resource base name
        return;
    }
    // We neet to get an instance of HttpServletResponse, but sometimes
    // the response object is wrapped by several instances of
    // ServletResponseWrapper (like ResponseSwitch).
    // Since we are handling a resource, we can expect to get an
    // HttpServletResponse.
    HttpServletResponse httpServletResponse = ResourceHandlerUtils.getHttpServletResponse(facesContext.getExternalContext().getResponse());
    if (httpServletResponse == null) {
        throw new IllegalStateException("Could not obtain an instance of HttpServletResponse.");
    }
    if (ResourceHandlerUtils.isResourceIdentifierExcluded(facesContext, resourceBasePath, excludedResourceExtensions)) {
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    // extract resourceName. if none was found set Response to 404
    String resourceName;
    if (resourceBasePath.startsWith(ResourceHandler.RESOURCE_IDENTIFIER)) {
        resourceName = resourceBasePath.substring(ResourceHandler.RESOURCE_IDENTIFIER.length() + 1);
        if (!ResourceValidationUtils.isValidResourceName(resourceName)) {
            httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
    } else {
        // Does not have the conditions for be a resource call
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    if (libraryName != null && !ResourceValidationUtils.isValidLibraryName(libraryName)) {
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    String resourceIdentifier = createResourceIdentifier(localePrefix, resourceName, resourceVersion, libraryName, libraryVersion);
    OsgiResource resource;
    // in this case we have the full path to the resource, no version-magic needed
    ResourceInfo resourceInfo = getServiceAndExecute(service -> service.locateResource(resourceIdentifier));
    if (resourceInfo == null) {
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    resource = new OsgiResource(resourceInfo.getUrl(), localePrefix, resourceName, resourceVersion, libraryName, libraryVersion, resourceInfo.getLastModified());
    // Resource has not changed, return 304
    if (!resource.userAgentNeedsUpdate(facesContext)) {
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }
    // serve
    httpServletResponse.setContentType(ResourceHandlerUtils.getContentType(resource, facesContext.getExternalContext()));
    Map<String, String> headers = resource.getResponseHeaders();
    for (Map.Entry<String, String> entry : headers.entrySet()) {
        httpServletResponse.setHeader(entry.getKey(), entry.getValue());
    }
    // Sets the preferred buffer size for the body of the response
    facesContext.getExternalContext().setResponseBufferSize(this.resourceBufferSize);
    // serve up the bytes (taken from trinidad ResourceServlet)
    try {
        // byte[] buffer = new byte[_BUFFER_SIZE];
        byte[] buffer = new byte[this.resourceBufferSize];
        try (InputStream in = resource.getInputStream();
            OutputStream out = httpServletResponse.getOutputStream()) {
            int count = ResourceHandlerUtils.pipeBytes(in, out, buffer);
            // set the content length
            if (!httpServletResponse.isCommitted()) {
                httpServletResponse.setContentLength(count);
            }
        }
    } catch (IOException e) {
        if (logger.isErrorEnabled()) {
            logger.error("Error trying to load resource '{}' with library '{}' : {}", new Object[] { resourceName, libraryName, e.getMessage(), e });
        }
        // return 404
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
    }
}
Also used : ResourceInfo(org.ops4j.pax.web.resources.api.ResourceInfo) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) Map(java.util.Map)

Aggregations

IOException (java.io.IOException)2 ResourceInfo (org.ops4j.pax.web.resources.api.ResourceInfo)2 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 MalformedURLException (java.net.MalformedURLException)1 URL (java.net.URL)1 LocalDateTime (java.time.LocalDateTime)1 ZoneId (java.time.ZoneId)1 ZonedDateTime (java.time.ZonedDateTime)1 DateTimeFormatter (java.time.format.DateTimeFormatter)1 Arrays (java.util.Arrays)1 Collection (java.util.Collection)1 Map (java.util.Map)1 Resource (javax.faces.application.Resource)1 FacesContext (javax.faces.context.FacesContext)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 StringUtils (org.apache.commons.lang3.StringUtils)1 Assert.fail (org.junit.Assert.fail)1 Test (org.junit.Test)1 CoreOptions.mavenBundle (org.ops4j.pax.exam.CoreOptions.mavenBundle)1