Example usage for java.time ZonedDateTime format

List of usage examples for java.time ZonedDateTime format

Introduction

In this page you can find the example usage for java.time ZonedDateTime format.

Prototype

@Override 
public String format(DateTimeFormatter formatter) 

Source Link

Document

Formats this date-time using the specified formatter.

Usage

From source file:org.cgiar.ccafs.marlo.action.center.summaries.ImpactPathwayOutcomesSummaryAction.java

/**
 * Get the main information of the report
 * /*ww w .j a  v a  2s .  c  o m*/
 * @return
 */
private TypedTableModel getMasterTableModel() {
    // Initialization of Model
    TypedTableModel model = new TypedTableModel(
            new String[] { "title", "current_date", "imageUrl", "research_program_id" },
            new Class[] { String.class, String.class, String.class, Long.class });
    String title = "Impact Pathway Full Report";
    String currentDate = "";

    // Get title
    title = researchProgram.getResearchArea().getAcronym() + ", " + researchProgram.getComposedName()
            + ", Organized by Impact";

    // Get datetime
    ZonedDateTime timezone = ZonedDateTime.now();
    DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-d 'at' HH:mm ");
    currentDate = timezone.format(format) + this.getTimeZone();

    // Get CIAT imgage URL from repo
    String imageUrl = this.getBaseUrl() + "/global/images/centers/CIAT.png";

    model.addRow(new Object[] { title, currentDate, imageUrl, researchProgram.getId() });
    return model;
}

From source file:org.elasticsearch.multi_node.RollupIT.java

public void testBigRollup() throws Exception {
    final int numDocs = 200;
    String dateFormat = "strict_date_optional_time";

    // create the test-index index
    try (XContentBuilder builder = jsonBuilder()) {
        builder.startObject();/*www  . j a  v  a  2s .  co m*/
        {
            builder.startObject("mappings").startObject("_doc").startObject("properties")
                    .startObject("timestamp").field("type", "date").field("format", dateFormat).endObject()
                    .startObject("value").field("type", "integer").endObject().endObject().endObject()
                    .endObject();
        }
        builder.endObject();
        final StringEntity entity = new StringEntity(Strings.toString(builder), ContentType.APPLICATION_JSON);
        Request req = new Request("PUT", "rollup-docs");
        req.setEntity(entity);
        client().performRequest(req);
    }

    // index documents for the rollup job
    final StringBuilder bulk = new StringBuilder();
    for (int i = 0; i < numDocs; i++) {
        bulk.append("{\"index\":{\"_index\":\"rollup-docs\",\"_type\":\"_doc\"}}\n");
        ZonedDateTime zdt = ZonedDateTime.ofInstant(Instant.ofEpochSecond(1531221196 + (60 * i)),
                ZoneId.of("UTC"));
        String date = zdt.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
        bulk.append("{\"timestamp\":\"").append(date).append("\",\"value\":").append(i).append("}\n");
    }
    bulk.append("\r\n");

    final Request bulkRequest = new Request("POST", "/_bulk");
    bulkRequest.addParameter("refresh", "true");
    bulkRequest.setJsonEntity(bulk.toString());
    client().performRequest(bulkRequest);

    // create the rollup job
    final Request createRollupJobRequest = new Request("PUT", "/_xpack/rollup/job/rollup-job-test");
    int pageSize = randomIntBetween(2, 50);
    createRollupJobRequest.setJsonEntity("{" + "\"index_pattern\":\"rollup-*\","
            + "\"rollup_index\":\"results-rollup\"," + "\"cron\":\"*/1 * * * * ?\"," // fast cron so test runs quickly
            + "\"page_size\":" + pageSize + "," + "\"groups\":{" + "    \"date_histogram\":{"
            + "        \"field\":\"timestamp\"," + "        \"interval\":\"5m\"" + "      }" + "},"
            + "\"metrics\":[" + "    {\"field\":\"value\",\"metrics\":[\"min\",\"max\",\"sum\"]}" + "]" + "}");

    Map<String, Object> createRollupJobResponse = toMap(client().performRequest(createRollupJobRequest));
    assertThat(createRollupJobResponse.get("acknowledged"), equalTo(Boolean.TRUE));

    // start the rollup job
    final Request startRollupJobRequest = new Request("POST", "_xpack/rollup/job/rollup-job-test/_start");
    Map<String, Object> startRollupJobResponse = toMap(client().performRequest(startRollupJobRequest));
    assertThat(startRollupJobResponse.get("started"), equalTo(Boolean.TRUE));

    assertRollUpJob("rollup-job-test");

    // Wait for the job to finish, by watching how many rollup docs we've indexed
    assertBusy(() -> {
        final Request getRollupJobRequest = new Request("GET", "_xpack/rollup/job/rollup-job-test");
        Response getRollupJobResponse = client().performRequest(getRollupJobRequest);
        assertThat(getRollupJobResponse.getStatusLine().getStatusCode(), equalTo(RestStatus.OK.getStatus()));

        Map<String, Object> job = getJob(getRollupJobResponse, "rollup-job-test");
        if (job != null) {
            assertThat(ObjectPath.eval("status.job_state", job), equalTo("started"));
            assertThat(ObjectPath.eval("stats.rollups_indexed", job), equalTo(41));
        }
    }, 30L, TimeUnit.SECONDS);

    // Refresh the rollup index to make sure all newly indexed docs are searchable
    final Request refreshRollupIndex = new Request("POST", "results-rollup/_refresh");
    toMap(client().performRequest(refreshRollupIndex));

    String jsonRequestBody = "{\n" + "  \"size\": 0,\n" + "  \"query\": {\n" + "    \"match_all\": {}\n"
            + "  },\n" + "  \"aggs\": {\n" + "    \"date_histo\": {\n" + "      \"date_histogram\": {\n"
            + "        \"field\": \"timestamp\",\n" + "        \"interval\": \"1h\",\n"
            + "        \"format\": \"date_time\"\n" + "      },\n" + "      \"aggs\": {\n"
            + "        \"the_max\": {\n" + "          \"max\": {\n" + "            \"field\": \"value\"\n"
            + "          }\n" + "        }\n" + "      }\n" + "    }\n" + "  }\n" + "}";

    Request request = new Request("GET", "rollup-docs/_search");
    request.setJsonEntity(jsonRequestBody);
    Response liveResponse = client().performRequest(request);
    Map<String, Object> liveBody = toMap(liveResponse);

    request = new Request("GET", "results-rollup/_rollup_search");
    request.setJsonEntity(jsonRequestBody);
    Response rollupResponse = client().performRequest(request);
    Map<String, Object> rollupBody = toMap(rollupResponse);

    // Do the live agg results match the rollup agg results?
    assertThat(ObjectPath.eval("aggregations.date_histo.buckets", liveBody),
            equalTo(ObjectPath.eval("aggregations.date_histo.buckets", rollupBody)));

    request = new Request("GET", "rollup-docs/_rollup_search");
    request.setJsonEntity(jsonRequestBody);
    Response liveRollupResponse = client().performRequest(request);
    Map<String, Object> liveRollupBody = toMap(liveRollupResponse);

    // Does searching the live index via rollup_search work match the live search?
    assertThat(ObjectPath.eval("aggregations.date_histo.buckets", liveBody),
            equalTo(ObjectPath.eval("aggregations.date_histo.buckets", liveRollupBody)));

}

From source file:org.cgiar.ccafs.marlo.action.center.summaries.IPOutcomesSummaryAction.java

/**
 * Get the main information of the report
 * //from  ww w . ja  v  a2s .  c o  m
 * @return
 */
private TypedTableModel getMasterTableModel() {
    // Initialization of Model
    TypedTableModel model = new TypedTableModel(new String[] { "currentDate", "center", "researchProgram" },
            new Class[] { String.class, String.class, String.class });
    String currentDate = "";

    // Get datetime
    ZonedDateTime timezone = ZonedDateTime.now();
    DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-d 'at' HH:mm ");
    currentDate = timezone.format(format) + this.getTimeZone();

    // Get CIAT imgage URL from repo
    String center = this.getCenterSession();

    model.addRow(new Object[] { currentDate, center, researchProgram.getName() });
    return model;
}

From source file:org.ng200.openolympus.ContestTest.java

public Contest createContestUsingAPI(int duration) throws Exception {
    // @formatter:off
    final ZonedDateTime now = ZonedDateTime.now();

    final String result = this.mockMvc
            .perform(MockMvcRequestBuilders.post("/api/contests/create")
                    .param("name", "TestContest_" + ContestTest.id++)
                    .param("startTime", now.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME))
                    .param("duration", Integer.toString(duration)))
            .andDo(MockMvcResultHandlers.print()).andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.content().contentType(this.contentType))
            .andExpect(MockMvcResultMatchers.jsonPath("$.status").value("OK"))
            .andExpect(MockMvcResultMatchers.jsonPath("$.data.id").exists()).andReturn().getResponse()
            .getContentAsString();/*  w  w  w . ja v  a  2 s.  c  o m*/
    return this.contestRepository.findOne(Long.valueOf(JsonPath.read(result, "$.data.id").toString()));
    // @formatter:on
}

From source file:com.sumzerotrading.broker.ib.InteractiveBrokersBroker.java

@Override
public String getFormattedDate(ZonedDateTime date) {
    return date.format(zonedDateFormatter);
}

From source file:org.cgiar.ccafs.marlo.action.center.summaries.OutcomesContributionsSummaryAction.java

/**
 * Get the main information of the report
 * /*from   w ww  .j  a  v a2 s . c  o m*/
 * @return
 */
private TypedTableModel getMasterTableModel() {
    // Initialization of Model
    TypedTableModel model = new TypedTableModel(
            new String[] { "current_date", "imageUrl", "research_program_id", "center",
                    "researchProgramTitle" },
            new Class[] { String.class, String.class, Long.class, String.class, String.class });
    String currentDate = "";
    // Get datetime
    ZonedDateTime timezone = ZonedDateTime.now();
    DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-d 'at' HH:mm ");
    currentDate = timezone.format(format) + this.getTimeZone();

    // Get CIAT imgage URL from repo
    String imageUrl = this.getBaseUrl() + "/global/images/centers/CIAT.png";

    String center = null;
    center = researchProgram.getResearchArea().getResearchCenter().getName();

    String researchProgramTitle = null;
    if (researchProgram.getName() != null && !researchProgram.getName().trim().isEmpty()) {
        researchProgramTitle = researchProgram.getName();
    }

    model.addRow(new Object[] { currentDate, imageUrl, researchProgram.getId(), center, researchProgramTitle });
    return model;
}

From source file:org.cgiar.ccafs.marlo.action.center.summaries.DeliverablesSummaryAction.java

/**
 * Get the main information of the report
 * /*from ww  w  .  j  a v  a2  s .c o m*/
 * @return
 */
private TypedTableModel getMasterTableModel() {
    // Initialization of Model
    final TypedTableModel model = new TypedTableModel(
            new String[] { "currentDate", "center", "researchProgram" },
            new Class[] { String.class, String.class, String.class });
    String currentDate = "";

    // Get datetime
    final ZonedDateTime timezone = ZonedDateTime.now();
    final DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-d 'at' HH:mm ");
    currentDate = timezone.format(format) + this.getTimeZone();
    final String center = this.getCenterSession();

    model.addRow(new Object[] { currentDate, center, researchProgram.getName() });
    return model;
}

From source file:org.ops4j.pax.web.itest.undertow.WarJsfResourcehandlerIntegrationTest.java

/**
 * Does multiple assertions in one test since container-startup is slow
 * <p>/*from   w w w .  ja v  a2 s. c  o  m*/
 * <pre>
 * <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>
 * </pre>
 */
@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()
            // set header for german-locale in JSF
            .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);
}

From source file:org.ops4j.pax.web.itest.jetty.WarJsfResourcehandlerIntegrationTest.java

/**
 * Does multiple assertions in one test since container-startup is slow
 * <p>//from   ww  w .jav a2s  . c om
 * <pre>
 * <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>
 * </pre>
 */
@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()
            // set header for german-locale in JSF
            .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);
}

From source file:org.ops4j.pax.web.itest.tomcat.WarJsfResourcehandlerIntegrationTest.java

/**
 * Does multiple assertions in one test since container-startup is slow
 * <p>/*from  w  w w  . j  ava  2 s .  com*/
 * <pre>
 * <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>
 * </pre>
 */
@Test
public void testJsfResourceHandler() throws Exception {
    final String pageUrl = "http://127.0.0.1:8282/osgi-resourcehandler-myfaces/index.xhtml";
    final String imageUrl = "http://127.0.0.1:8282/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()
            // set header for german-locale in JSF
            .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:8282/osgi-resourcehandler-myfaces/faces/index.xhtml";
    final String imageUrlWithPrefixMapping = "http://127.0.0.1:8282/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);
}