Search in sources :

Example 1 with Resource

use of javax.faces.application.Resource in project gdmatrix by gdmatrix.

the class UserSessionBean method getPrimefacesTheme.

public String getPrimefacesTheme() {
    String pfTheme;
    if (isEditViewSelected() || isRedirViewSelected()) {
        pfTheme = EDIT_PRIMEFACES_THEME;
    } else {
        pfTheme = getSelectedMenuItem().getProperty("primefacesTheme");
    }
    if (pfTheme != null) {
        try {
            String library = "primefaces-" + pfTheme;
            Resource resource = getFacesContext().getApplication().getResourceHandler().createResource("theme.css", library);
            if (resource != null)
                return pfTheme;
        } catch (Exception ex) {
            return DEFAULT_PRIMEFACES_THEME;
        }
    }
    return DEFAULT_PRIMEFACES_THEME;
}
Also used : Resource(javax.faces.application.Resource) IOException(java.io.IOException)

Example 2 with Resource

use of javax.faces.application.Resource in project org.ops4j.pax.web by ops4j.

the class OsgiResourceHandler method createResource.

@Override
public Resource createResource(final String resourceName, String libraryName, String contentType) {
    // first, use default ResourceHandler for lookup
    Resource standardResource = super.createResource(resourceName, libraryName, contentType);
    if (standardResource != null) {
        return standardResource;
    }
    String workResourceName = resourceName;
    // nothing found, continue with OsgiResourceHandler
    final FacesContext facesContext = FacesContext.getCurrentInstance();
    if (workResourceName.charAt(0) == PATH_SEPARATOR) {
        // If resourceName starts with '/', remove that character because it
        // does not have any meaning (with and without should point to the
        // same resource).
        workResourceName = workResourceName.substring(1);
    }
    if (!ResourceValidationUtils.isValidResourceName(workResourceName)) {
        logger.debug("Invalid resourceName '{}'", workResourceName);
        return null;
    }
    if (libraryName != null && !ResourceValidationUtils.isValidLibraryName(libraryName)) {
        logger.debug("Invalid libraryName '{}'", libraryName);
        return null;
    }
    final Optional<String> localePrefix = ResourceHandlerUtils.getLocalePrefixForLocateResource(facesContext);
    // Contract currently not supported: final List<String> contracts = facesContext.getResourceLibraryContracts();
    final JsfResourceQuery query = new JsfResourceQuery(localePrefix.orElse(null), libraryName, workResourceName, contentType);
    final Optional<JsfResourceQueryResult> matchedQueryResult = getServiceAndExecute(service -> matchResources(service, query));
    if (matchedQueryResult.isPresent()) {
        JsfResourceQueryResult queryResult = matchedQueryResult.get();
        return new OsgiResource(queryResult.getResourceInformation().getUrl(), queryResult.isMatchedLocalePrefix() ? localePrefix.orElseGet(null) : null, workResourceName, queryResult.getResourceVersion(), libraryName, queryResult.getLibraryVersion(), queryResult.getResourceInformation().getLastModified());
    } else {
        return null;
    }
// inspect final resource for contentType
// FIXME deal with content-type
// if (contentType == null)
// {
// try(InputStream is = resourceInfo.getUrl().openConnection().getInputStream()){
// contentType = URLConnection.guessContentTypeFromStream(is);
// }catch(IOException e){
// logger.error("Could not determine contentType from url-resource!", e);
// }
// }
}
Also used : FacesContext(javax.faces.context.FacesContext) Resource(javax.faces.application.Resource) ViewResource(javax.faces.application.ViewResource)

Example 3 with Resource

use of javax.faces.application.Resource 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 4 with Resource

use of javax.faces.application.Resource in project org.ops4j.pax.web by ops4j.

the class AbstractWarJsfResourcehandlerIntegrationTest method testJsfResourceHandler.

/**
 * Does multiple assertions in one test since container-startup is slow
 * <p/>
 * <ul>
 * 	<li>Check if pax-web-resources-jsf is started</li>
 * 	<li>Check if application under test (jsf-application-myfaces) is started
 * 	<li>Test actual resource-handler
 * 		<ul>
 * 			<li>Test for occurence of 'Hello JSF' (jsf-application-myfaces)</li>
 * 			<li>Test for occurence of 'Standard Header' (jsf-resourcebundle)</li>
 * 			<li>Test for occurence of 'iceland.jpg' from library 'default' in version '2_0' (jsf-resourcebundle)</li>
 * 			<li>Test for occurence of 'Customized Footer' (jsf-resourcebundle)</li>
 *          <li>Access a resource (image) via HTTP which gets loaded from a other bundle (jsf-resourcebundle)</li>
 * 		</ul>
 * 	</li>
 *  <li>Test localized resource
 * 	    <ul>
 * 			<li>Test for occurence of 'flag.png' from library 'layout' with default locale 'en' which resolves to 'iceland' (default in faces-config)</li>
 * 	        <li>Test for occurence of 'flag.png' from library 'layout' with default locale 'de' which resolves to 'germany'</li>
 * 	    </ul>
 * 	</li>
 * 	<li>Test resource-overide
 * 	    <ul>
 * 	        <li>Install another bundle (jsf-resourcebundle-override) which also serves  template/footer.xhtml</li>
 * 	        <li>Test for occurence of 'Overriden Footer' (jsf-resourcebundle-override)</li>
 * 			<li>Test for occurence of 'iceland.jpg' from library 'default' in version '3_0' (jsf-resourcebundle-override)</li>
 * 	        <li>Uninstall the previously installed bundle</li>
 * 	        <li>Test again, this time for occurence of 'Customized Footer' (jsf-resourcebundle)</li>
 * 	    </ul>
 * 	</li>
 * 	<li>
 * 	    Test {@link OsgiResource#userAgentNeedsUpdate(FacesContext)}
 * 	    with an If-Modified-Since header
 * 	</li>
 * 	<li>Test servletmapping with prefix (faces/*) rather than extension for both, page and image serving</li>
 * </ul>
 */
@Test
public void testJsfResourceHandler() throws Exception {
    final String pageUrl = "http://127.0.0.1:8181/osgi-resourcehandler-myfaces/index.xhtml";
    final String imageUrl = "http://127.0.0.1:8181/osgi-resourcehandler-myfaces/javax.faces.resource/images/iceland.jpg.xhtml?type=osgi&ln=default&lv=2_0";
    // prepare Bundle
    initWebListener();
    installAndStartBundle(mavenBundle().groupId("org.ops4j.pax.web.samples").artifactId("jsf-resourcehandler-myfaces").versionAsInProject().getURL());
    waitForWebListener();
    new WaitCondition2("pax-web-resources-extender done scanning for webresources-bundles", () -> {
        try {
            HttpTestClientFactory.createDefaultTestClient().doGETandExecuteTest(imageUrl);
            return true;
        } catch (AssertionError | Exception e) {
            return false;
        }
    }).waitForCondition(20000, 1000, () -> fail("Image not served in time. pax-web-resources-extender not finished"));
    // start testing
    BundleMatchers.isBundleActive("org.ops4j.pax.web.pax-web-resources-extender", bundleContext);
    BundleMatchers.isBundleActive("org.ops4j.pax.web.pax-web-resources-jsf", bundleContext);
    BundleMatchers.isBundleActive("jsf-resourcehandler-resourcebundle", bundleContext);
    BundleMatchers.isBundleActive("jsf-resourcehandler-myfaces", bundleContext);
    HttpTestClientFactory.createDefaultTestClient().withResponseAssertion("Some Content shall be included from the jsf-application-bundle to test internal view-resources", resp -> StringUtils.contains(resp, "Hello Included Content")).withResponseAssertion("Standard header shall be loaded from resourcebundle to test external view-resources", resp -> StringUtils.contains(resp, "Standard Header")).withResponseAssertion("Images shall be loaded from resourcebundle to test external resources", resp -> StringUtils.contains(resp, "iceland.jpg")).withResponseAssertion("Customized footer shall be loaded from resourcebundle to test external view-resources", resp -> StringUtils.contains(resp, "Customized Footer")).withResponseAssertion("Image-URL must be created from OsgiResource", resp -> StringUtils.contains(resp, "/osgi-resourcehandler-myfaces/javax.faces.resource/images/iceland.jpg.xhtml?type=osgi&amp;ln=default&amp;lv=2_0")).withResponseAssertion("Flag-URL must be served from iceland-folder", resp -> StringUtils.contains(resp, "/osgi-resourcehandler-myfaces/javax.faces.resource/flag.png.xhtml?type=osgi&amp;loc=iceland&amp;ln=layout")).doGETandExecuteTest(pageUrl);
    // Test German image
    HttpTestClientFactory.createDefaultTestClient().addRequestHeader("Accept-Language", "de").withReturnCode(200).withResponseAssertion("Flag-URL must be served from germany-folder", resp -> StringUtils.contains(resp, "/osgi-resourcehandler-myfaces/javax.faces.resource/flag.png.xhtml?type=osgi&amp;loc=germany&amp;ln=layout")).doGETandExecuteTest(pageUrl);
    // test resource serving for image
    HttpTestClientFactory.createDefaultTestClient().doGETandExecuteTest(imageUrl);
    // Install override bundle
    String bundlePath = mavenBundle().groupId("org.ops4j.pax.web.samples").artifactId("jsf-resourcehandler-resourcebundle-override").versionAsInProject().getURL();
    Bundle installedResourceBundle = installAndStartBundle(bundlePath);
    BundleMatchers.isBundleActive(installedResourceBundle.getSymbolicName(), bundleContext);
    HttpTestClientFactory.createDefaultTestClient().withResponseAssertion("Overriden footer shall be loaded from resourcebundle-override  to test external view-resources which are overriden", resp -> StringUtils.contains(resp, "Overriden Footer")).withResponseAssertion("Iceland-Picture shall be found in version 3.0 from resourcebunde-override", resp -> StringUtils.contains(resp, "javax.faces.resource/images/iceland.jpg.xhtml?type=osgi&amp;ln=default&amp;lv=2_0&amp;rv=3_0.jpg")).doGETandExecuteTest(pageUrl);
    // uninstall overriding bundle
    installedResourceBundle.stop();
    new WaitCondition2("Customized footer shall be loaded from resourcebundle", () -> {
        try {
            HttpTestClientFactory.createDefaultTestClient().withResponseAssertion("Customized footer shall be loaded from resourcebundle", resp -> StringUtils.contains(resp, "Customized Footer")).doGETandExecuteTest(pageUrl);
            return true;
        } catch (AssertionError | Exception e) {
            return false;
        }
    }).waitForCondition(5000, 1000, () -> fail("After uninstalling 'jsf-resourcehandler-resourcebundle-override' " + "the customized foot must be loaded again."));
    // Test If-Modified-Since
    ZonedDateTime now = ZonedDateTime.of(LocalDateTime.now(), ZoneId.of(ZoneId.SHORT_IDS.get("ECT")));
    // "Modified-Since should mark response with 304"
    HttpTestClientFactory.createDefaultTestClient().withReturnCode(304).addRequestHeader("If-Modified-Since", now.format(DateTimeFormatter.RFC_1123_DATE_TIME)).doGETandExecuteTest(imageUrl);
    // Test second faces-mapping which uses a prefix (faces/*)
    final String pageUrlWithPrefixMapping = "http://127.0.0.1:8181/osgi-resourcehandler-myfaces/faces/index.xhtml";
    final String imageUrlWithPrefixMapping = "http://127.0.0.1:8181/osgi-resourcehandler-myfaces/faces/javax.faces.resource/images/iceland.jpg?type=osgi&ln=default&lv=2_0";
    HttpTestClientFactory.createDefaultTestClient().doGETandExecuteTest(imageUrlWithPrefixMapping);
    HttpTestClientFactory.createDefaultTestClient().withResponseAssertion("Image-URL must be created from OsgiResource. This time the second servlet-mapping (faces/*) must be used.", resp -> StringUtils.contains(resp, "/osgi-resourcehandler-myfaces/faces/javax.faces.resource/images/iceland.jpg?type=osgi&amp;ln=default&amp;lv=2_0")).doGETandExecuteTest(pageUrlWithPrefixMapping);
}
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) WaitCondition2(org.ops4j.pax.web.itest.base.WaitCondition2) ZonedDateTime(java.time.ZonedDateTime) Bundle(org.osgi.framework.Bundle) CoreOptions.mavenBundle(org.ops4j.pax.exam.CoreOptions.mavenBundle) Test(org.junit.Test)

Example 5 with Resource

use of javax.faces.application.Resource in project liferay-faces-alloy by liferay.

the class VideoBacking method getEncodedMp4ResourceURL.

public String getEncodedMp4ResourceURL() throws UnsupportedEncodingException {
    if (encodedMp4ResourceURL == null) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        Application application = facesContext.getApplication();
        ResourceHandler resourceHandler = application.getResourceHandler();
        Resource mp3AudioResource = resourceHandler.createResource("over-the-rainbow.mp4", "videos");
        String requestPath = mp3AudioResource.getRequestPath();
        ExternalContext externalContext = facesContext.getExternalContext();
        String mp4ResourceURL = externalContext.encodeResourceURL(requestPath);
        encodedMp4ResourceURL = URLEncoder.encode(mp4ResourceURL, "UTF-8");
    }
    return encodedMp4ResourceURL;
}
Also used : FacesContext(javax.faces.context.FacesContext) ExternalContext(javax.faces.context.ExternalContext) Resource(javax.faces.application.Resource) FacesResource(com.liferay.faces.util.application.FacesResource) ResourceHandler(javax.faces.application.ResourceHandler) Application(javax.faces.application.Application)

Aggregations

Resource (javax.faces.application.Resource)27 ExternalContext (javax.faces.context.ExternalContext)10 ResourceHandler (javax.faces.application.ResourceHandler)9 FacesContext (javax.faces.context.FacesContext)7 FacesResource (com.liferay.faces.util.application.FacesResource)5 Application (javax.faces.application.Application)5 IOException (java.io.IOException)4 ResponseWriter (javax.faces.context.ResponseWriter)4 URL (java.net.URL)3 Collection (java.util.Collection)3 FacesException (javax.faces.FacesException)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 MalformedURLException (java.net.MalformedURLException)2 LocalDateTime (java.time.LocalDateTime)2 ZoneId (java.time.ZoneId)2 ZonedDateTime (java.time.ZonedDateTime)2 DateTimeFormatter (java.time.format.DateTimeFormatter)2 Arrays (java.util.Arrays)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2