Search in sources :

Example 11 with ResourceURL

use of javax.portlet.ResourceURL in project gatein-portal by Meeds-io.

the class NavigationUtils method addJsonNodes.

private static StringBuffer addJsonNodes(Iterator<UserNode> children) throws Exception {
    StringBuffer sbJsonTree = new StringBuffer();
    sbJsonTree.append("[");
    boolean first = true;
    while (children.hasNext()) {
        UserNode child = children.next();
        if (!first) {
            sbJsonTree.append(",");
        }
        first = false;
        sbJsonTree.append("{");
        sbJsonTree.append("\"icon\":").append(child.getIcon() != null ? "\"" + child.getIcon() + "\"" : "null").append(",");
        sbJsonTree.append("\"label\":\"").append(child.getLabel()).append("\",");
        sbJsonTree.append("\"name\":\"").append(child.getName()).append("\",");
        sbJsonTree.append("\"resolvedLabel\":\"").append(child.getResolvedLabel()).append("\",");
        String childURI = "";
        if (child.getPageRef() != null) {
            childURI = child.getURI();
        }
        sbJsonTree.append("\"uri\":\"").append(childURI).append("\",");
        WebuiRequestContext context = WebuiRequestContext.getCurrentInstance();
        MimeResponse res = context.getResponse();
        ResourceURL resourceURL = res.createResourceURL();
        resourceURL.setResourceID(res.encodeURL(child.getURI()));
        Writer w = new StringWriter();
        resourceURL.write(w, true);
        sbJsonTree.append("\"getNodeURL\":\"").append(w.toString()).append("\",");
        sbJsonTree.append("\"nodes\":").append(addJsonNodes(child.getChildren().iterator()));
        sbJsonTree.append("}");
    }
    sbJsonTree.append("]");
    return sbJsonTree;
}
Also used : StringWriter(java.io.StringWriter) MimeResponse(javax.portlet.MimeResponse) WebuiRequestContext(org.exoplatform.webui.application.WebuiRequestContext) ResourceURL(javax.portlet.ResourceURL) StringWriter(java.io.StringWriter) Writer(java.io.Writer)

Example 12 with ResourceURL

use of javax.portlet.ResourceURL in project gatein-portal by Meeds-io.

the class UINavigationPortlet method toJSON.

private JSONObject toJSON(UserNode node, MimeResponse res) throws Exception {
    JSONObject json = new JSONObject();
    String nodeId = node.getId();
    json.put("label", node.getEncodedResolvedLabel());
    json.put("hasChild", node.getChildrenCount() > 0);
    UserNode selectedNode = Util.getUIPortal().getNavPath();
    json.put("isSelected", nodeId.equals(selectedNode.getId()));
    json.put("icon", node.getIcon());
    ResourceURL rsURL = res.createResourceURL();
    rsURL.setResourceID(node.getURI());
    json.put("getNodeURL", rsURL.toString());
    if (node.getPageRef() != null) {
        NavigationResource resource = new NavigationResource(node);
        NodeURL url = Util.getPortalRequestContext().createURL(NodeURL.TYPE, resource);
        url.setAjax(isUseAjax());
        json.put("actionLink", url.toString());
    }
    JSONArray childs = new JSONArray();
    for (UserNode child : node.getChildren()) {
        childs.put(toJSON(child, res));
    }
    json.put("childs", childs);
    return json;
}
Also used : JSONObject(org.json.JSONObject) UserNode(org.exoplatform.portal.mop.user.UserNode) JSONArray(org.json.JSONArray) NavigationResource(org.exoplatform.web.url.navigation.NavigationResource) NodeURL(org.exoplatform.web.url.navigation.NodeURL) ResourceURL(javax.portlet.ResourceURL)

Example 13 with ResourceURL

use of javax.portlet.ResourceURL in project liferay-faces-bridge-impl by liferay.

the class BridgeURLBase method createResourceURL.

private ResourceURL createResourceURL(FacesContext facesContext, List<URIParameter> uriParameters) throws MalformedURLException {
    try {
        logger.debug("createResourceURL uriParameters=[{0}]", uriParameters);
        // Ask the portlet container to create a portlet resource URL.
        ExternalContext externalContext = facesContext.getExternalContext();
        MimeResponse mimeResponse = (MimeResponse) externalContext.getResponse();
        ResourceURL resourceURL = mimeResponse.createResourceURL();
        // If the "javax.faces.resource" token is found in the URL, then
        String bridgeURIAsString = bridgeURI.toString();
        int tokenPos = bridgeURIAsString.indexOf("javax.faces.resource");
        if (tokenPos >= 0) {
            // Parse-out the resourceId
            String resourceId = bridgeURIAsString.substring(tokenPos);
            // Parse-out the resourceName and convert it to a URL parameter on the portlet resource URL.
            int queryStringPos = resourceId.indexOf('?');
            String resourceName = resourceId;
            if (queryStringPos > 0) {
                resourceName = resourceName.substring(0, queryStringPos);
            }
            int slashPos = resourceName.indexOf('/');
            if (slashPos > 0) {
                resourceName = resourceName.substring(slashPos + 1);
            } else {
                logger.debug("There is no slash after the [{0}] token in resourceURL=[{1}]", "javax.faces.resource", uriParameters);
            }
            resourceURL.setParameter("javax.faces.resource", resourceName);
            logger.debug("Added parameter to portletURL name=[{0}] value=[{1}]", "javax.faces.resource", resourceName);
        }
        // Copy the request parameters to the portlet resource URL.
        if (uriParameters != null) {
            copyURIParametersToBaseURL(uriParameters, resourceURL);
        }
        return resourceURL;
    } catch (ClassCastException e) {
        throw new MalformedURLException(e.getMessage());
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) ExternalContext(javax.faces.context.ExternalContext) MimeResponse(javax.portlet.MimeResponse) ResourceURL(javax.portlet.ResourceURL)

Example 14 with ResourceURL

use of javax.portlet.ResourceURL in project liferay-faces-bridge-impl by liferay.

the class BridgeURLResourceImpl method toBaseURL.

@Override
public BaseURL toBaseURL(FacesContext facesContext) throws MalformedURLException {
    BaseURL baseURL;
    String uri = bridgeURI.toString();
    // doesn't have the double-forward-slash like "http://" does, then
    if (bridgeURI.isOpaque()) {
        // parameters. This will be a URL that represents navigation to a different viewId.
        if (bridgeURI.isPortletScheme()) {
            // TCK: modeViewIDTest
            // TCK: requestRenderIgnoresScopeViaCreateViewTest
            // TCK: requestRenderRedisplayTest
            // TCK: requestRedisplayOutOfScopeTest
            // TCK: renderRedirectTest
            // TCK: ignoreCurrentViewIdModeChangeTest
            // TCK: exceptionThrownWhenNoDefaultViewIdTest
            String portletMode = getParameter(Bridge.PORTLET_MODE_PARAMETER);
            boolean modeChanged = ((portletMode != null) && (portletMode.length() > 0));
            Bridge.PortletPhase urlPortletPhase = bridgeURI.getPortletPhase();
            if (urlPortletPhase == Bridge.PortletPhase.ACTION_PHASE) {
                baseURL = createActionURL(facesContext, modeChanged);
            } else if (urlPortletPhase == Bridge.PortletPhase.RENDER_PHASE) {
                baseURL = createRenderURL(facesContext, modeChanged);
            } else {
                baseURL = createResourceURL(facesContext, modeChanged);
            }
            // user clicks on the link (invokes the BaseURL).
            if (selfReferencing) {
                ExternalContext externalContext = facesContext.getExternalContext();
                PortletRequest portletRequest = (PortletRequest) externalContext.getRequest();
                copyRenderParameters(portletRequest, baseURL, externalContext.encodeNamespace(""), UINamingContainer.getSeparatorChar(facesContext));
            }
            // PortletURL.
            if (baseURL instanceof PortletURL) {
                PortletURL portletURL = (PortletURL) baseURL;
                ExternalContext externalContext = facesContext.getExternalContext();
                PortletRequest portletRequest = (PortletRequest) externalContext.getRequest();
                PortletURLHelper.setPortletMode(portletURL, portletMode, portletRequest);
                String windowState = getParameter(Bridge.PORTLET_WINDOWSTATE_PARAMETER);
                PortletURLHelper.setWindowState(portletURL, windowState, portletRequest);
            }
            // Apply the security.
            String secure = getParameter(Bridge.PORTLET_SECURE_PARAMETER);
            PortletURLHelper.setSecure(baseURL, secure);
            // According to the Bridge Spec, the "javax.portlet.faces.Secure" parameter must not be "carried
            // forward to the generated reference." According to a clarification in the Portlet 3.0 JavaDoc for
            // BaseURL#setProperty(String,String), setting the parameter to null will remove it.
            baseURL.setParameter(Bridge.PORTLET_SECURE_PARAMETER, (String) null);
        } else // Otherwise, return the a BaseURL string representation (unmodified value) as required by the Bridge Spec.
        {
            // TCK: encodeResourceURLOpaqueTest
            baseURL = new BaseURLNonEncodedImpl(bridgeURI, encoding);
        }
    } else // Otherwise, if the URL is a JSF2 portlet resource URL, then
    if (PortletResourceUtilCompat.isPortletResourceURL(uri)) {
        // FACES-63 Return the URI unmodified to prevent double-encoding of resource URLs.
        baseURL = new BaseURLBridgeURIAdapterImpl(bridgeURI);
    } else // resource URL identifier, then return a ResourceURL that can retrieve the JSF2 resource.
    if ((uri != null) && uri.contains("javax.faces.resource")) {
        baseURL = createResourceURL(facesContext, bridgeURI.getParameterMap());
    } else // of the URL that contains the context-path.
    if (bridgeURI.isPathRelative()) {
        // TCK: encodeResourceURLRelativeURLTest
        // TCK: encodeResourceURLRelativeURLBackLinkTest
        ExternalContext externalContext = facesContext.getExternalContext();
        String contextPath = externalContext.getRequestContextPath();
        baseURL = new BaseURLRelativeImpl(bridgeURI, contextPath);
    } else // Otherwise, if the URL is external, then return an encoded BaseURL string representation of the URL.
    if (bridgeURI.isExternal(contextPath)) {
        // TCK: encodeResourceURLForeignExternalURLBackLinkTest
        ExternalContext externalContext = facesContext.getExternalContext();
        PortletResponse portletResponse = (PortletResponse) externalContext.getResponse();
        baseURL = new BaseURLPortletResponseEncodedImpl(bridgeURI, portletResponse);
    } else // to a different Faces view, then
    if (viewLink) {
        String portletMode = getParameter(Bridge.PORTLET_MODE_PARAMETER);
        String windowState = getParameter(Bridge.PORTLET_WINDOWSTATE_PARAMETER);
        boolean secure = BooleanHelper.toBoolean(getParameter(Bridge.PORTLET_SECURE_PARAMETER));
        // JavaDoc comments for {@link Bridge#VIEW_LINK}.
        if (getViewId() != null) {
            // TCK: encodeResourceURLViewLinkTest
            // TCK: encodeResourceURLViewLinkWithBackLinkTest
            ExternalContext externalContext = facesContext.getExternalContext();
            PortletRequest portletRequest = (PortletRequest) externalContext.getRequest();
            PortletURL actionURL = createActionURL(facesContext, PortletURLHelper.EXCLUDED_PARAMETER_NAMES);
            PortletURLHelper.setPortletMode(actionURL, portletMode, portletRequest);
            PortletURLHelper.setWindowState(actionURL, windowState, portletRequest);
            PortletURLHelper.setSecure(actionURL, secure);
            // According to the Bridge Spec, the "javax.portlet.faces.Secure" parameter must not be "carried
            // forward to the generated reference." According to a clarification in the Portlet 3.0 JavaDoc for
            // BaseURL#setProperty(String,String), setting the parameter to null will remove it.
            actionURL.setParameter(Bridge.PORTLET_SECURE_PARAMETER, (String) null);
            baseURL = actionURL;
        } else // Otherwise, return a PortletURL (Render URL) that contains the "_jsfBridgeNonFacesView" render parameter,
        // which is a signal to the GenericFacesPortlet to dispatch to this non-Faces target when the URL is
        // requested. Note that this seems to be a use-case that is contradictory with the JavaDoc for
        // Brige#VIEW_LINK which claims navigation to a different view. But there are a number of tests in the TCK
        // that utilize this (see below).
        {
            Bridge.PortletPhase portletRequestPhase = BridgeUtil.getPortletRequestPhase(facesContext);
            if (isHeaderOrRenderOrResourcePhase(portletRequestPhase)) {
                // TCK: encodeActionURLNonJSFViewRenderTest
                // TCK: encodeActionURLNonJSFViewWithParamRenderTest
                // TCK: encodeActionURLNonJSFViewWithModeRenderTest
                // TCK: encodeActionURLNonJSFViewWithInvalidModeRenderTest
                // TCK: encodeActionURLNonJSFViewWithWindowStateRenderTest
                // TCK: encodeActionURLNonJSFViewWithInvalidWindowStateRenderTest
                // TCK: encodeActionURLNonJSFViewResourceTest
                // TCK: encodeActionURLNonJSFViewWithParamResourceTest
                // TCK: encodeActionURLNonJSFViewWithModeResourceTest
                // TCK: encodeActionURLNonJSFViewWithInvalidModeResourceTest
                // TCK: encodeActionURLNonJSFViewWithWindowStateResourceTest
                // TCK: encodeActionURLNonJSFViewWithInvalidWindowStateResourceTest
                ExternalContext externalContext = facesContext.getExternalContext();
                PortletRequest portletRequest = (PortletRequest) externalContext.getRequest();
                PortletURL renderURL = createRenderURL(facesContext, PortletURLHelper.EXCLUDED_PARAMETER_NAMES);
                renderURL.setParameter(Bridge.NONFACES_TARGET_PATH_PARAMETER, bridgeURI.getPath());
                PortletURLHelper.setPortletMode(renderURL, portletMode, portletRequest);
                PortletURLHelper.setWindowState(renderURL, windowState, portletRequest);
                PortletURLHelper.setSecure(renderURL, secure);
                // According to the Bridge Spec, the "javax.portlet.faces.Secure" parameter must not be "carried
                // forward to the generated reference." According to a clarification in the Portlet 3.0 JavaDoc for
                // BaseURL#setProperty(String,String), setting the parameter to null will remove it.
                renderURL.setParameter(Bridge.PORTLET_SECURE_PARAMETER, (String) null);
                baseURL = renderURL;
            } else {
                throw new IllegalStateException("Unable to encode a URL for a non-Faces view in the " + portletRequestPhase + " of the portlet lifecycle.");
            }
        }
    } else // Otherwise, if the URL targets a Faces viewId, then return a ResourceURL that targets the view.
    if (getViewId() != null) {
        // TCK: resourceAttrRetainedAfterRedisplayPPRTest
        // TCK: encodeActionURLJSFViewResourceTest
        // TCK: encodeActionURLWithParamResourceTest
        // TCK: encodeActionURLWithModeResourceTest
        // TCK: encodeActionURLWithInvalidModeResourceTest
        // TCK: encodeActionURLWithWindowStateResourceTest
        // TCK: encodeActionURLWithInvalidWindowStateResourceTest
        // TCK: encodeURLEscapingTest
        // TCK: encodeResourceURLWithModeTest
        baseURL = createResourceURL(facesContext, PortletURLHelper.EXCLUDED_PARAMETER_NAMES);
    } else // an appropriate ResourceURL.
    if (inProtocol) {
        // TCK: nonFacesResourceTest
        ResourceURL resourceURL = createResourceURL(facesContext);
        resourceURL.setResourceID(bridgeURI.getContextRelativePath(contextPath));
        baseURL = resourceURL;
    } else // Otherwise, assume that the URL is for an resource external to the portlet context like
    // "/portalcontext/resources/foo.png" and return a BaseURL string representation of it.
    {
        // TCK: encodeResourceURLTest
        // TCK: encodeResourceURLBackLinkTest
        baseURL = new BaseURLBridgeURIAdapterImpl(bridgeURI);
    }
    return baseURL;
}
Also used : PortletResponse(javax.portlet.PortletResponse) PortletRequest(javax.portlet.PortletRequest) ExternalContext(javax.faces.context.ExternalContext) BaseURL(javax.portlet.BaseURL) PortletURL(javax.portlet.PortletURL) Bridge(javax.portlet.faces.Bridge) ResourceURL(javax.portlet.ResourceURL)

Example 15 with ResourceURL

use of javax.portlet.ResourceURL in project struts by apache.

the class StrutsSpringPortletMockObjectsTest method testMockMimeResponse.

public void testMockMimeResponse() {
    final String TEST_CONTENT_TYPE = "text/html";
    final int TEST_BUFFERSIZE = 8192;
    final String TEST_INCLUDED_URL = "localhost:8080/fakeincludedurl";
    final String TEST_FORWARDED_URL = "localhost:8080/fakeforwardedurl";
    final String TEST_FAKECONTENT = "Some fake content for the test.";
    final byte[] TEST_FAKECONTENT_ASBYTES = TEST_FAKECONTENT.getBytes(StandardCharsets.UTF_8);
    // Call each constructor in sequence, do some basic checks
    MockMimeResponse mockMimeResponse = new MockMimeResponse();
    assertEquals("Default character encoding not as expected ?", WebUtils.DEFAULT_CHARACTER_ENCODING, mockMimeResponse.getCharacterEncoding());
    assertEquals("Default locale not as expected ?", Locale.getDefault(), mockMimeResponse.getLocale());
    assertTrue("Default buffersize not as expected ?", mockMimeResponse.getBufferSize() >= 4096);
    assertFalse("Mock response already committed ?", mockMimeResponse.isCommitted());
    final MockPortalContext mockPortalContext = new MockPortalContext();
    final MockPortletContext mockPortletContext = new MockPortletContext();
    final MockPortletRequest mockPortletRequest = new MockPortletRequest(mockPortalContext, mockPortletContext);
    mockMimeResponse = new MockMimeResponse(mockPortalContext);
    assertEquals("Portal context does not match constructor-set value ?", mockPortalContext, mockMimeResponse.getPortalContext());
    mockMimeResponse = new MockMimeResponse(mockPortalContext, mockPortletRequest);
    assertEquals("Portal context does not match constructor-set value ?", mockPortalContext, mockMimeResponse.getPortalContext());
    mockMimeResponse.setContentType(TEST_CONTENT_TYPE);
    assertEquals("Content-type not as expected ?", TEST_CONTENT_TYPE, mockMimeResponse.getContentType());
    mockMimeResponse.setCharacterEncoding(StandardCharsets.UTF_8.name());
    assertEquals("Charset not as expected ?", StandardCharsets.UTF_8.name(), mockMimeResponse.getCharacterEncoding());
    mockMimeResponse.setBufferSize(TEST_BUFFERSIZE);
    assertEquals("Buffersize not as expected ?", TEST_BUFFERSIZE, mockMimeResponse.getBufferSize());
    mockMimeResponse.setCommitted(true);
    assertTrue("Response not committed ?", mockMimeResponse.isCommitted());
    mockMimeResponse.setCommitted(false);
    assertFalse("Response still committed ?", mockMimeResponse.isCommitted());
    mockMimeResponse.setIncludedUrl(TEST_INCLUDED_URL);
    assertEquals("Included URL not as expected ?", TEST_INCLUDED_URL, mockMimeResponse.getIncludedUrl());
    mockMimeResponse.setForwardedUrl(TEST_FORWARDED_URL);
    assertEquals("Forwarded URL not as expected ?", TEST_FORWARDED_URL, mockMimeResponse.getForwardedUrl());
    try {
        assertNotNull("OutputStream null ?", mockMimeResponse.getPortletOutputStream());
    } catch (Exception ex) {
        fail("MockMimeResponse get outputstream failed.  Exception: " + ex);
    }
    PortletURL portletUrl = mockMimeResponse.createRenderURL();
    assertNotNull("RenderURL null ?", portletUrl);
    portletUrl = mockMimeResponse.createActionURL();
    assertNotNull("ActionURL null ?", portletUrl);
    ResourceURL resourceURL = mockMimeResponse.createResourceURL();
    assertNotNull("ResourceURL null ?", resourceURL);
    assertNotNull("CacheControl null ?", mockMimeResponse.getCacheControl());
    try {
        OutputStream outputStream = mockMimeResponse.getPortletOutputStream();
        assertNotNull("OutputStream null ?", outputStream);
        outputStream.write(TEST_FAKECONTENT_ASBYTES);
        final byte[] writeResult = mockMimeResponse.getContentAsByteArray();
        assertArrayEquals("Written byte array does not match original ?", TEST_FAKECONTENT_ASBYTES, writeResult);
        assertTrue("Buffer not committed after processing ?", mockMimeResponse.isCommitted());
    } catch (Exception ex) {
        fail("MockMimeResponse get/process outputstream failed.  Exception: " + ex);
    }
    try {
        mockMimeResponse.resetBuffer();
    } catch (IllegalStateException ise) {
    // Expected failure
    }
    mockMimeResponse.setCommitted(false);
    mockMimeResponse.resetBuffer();
    try {
        PrintWriter printWriter = mockMimeResponse.getWriter();
        assertNotNull("PrintWriter null ?", printWriter);
        printWriter.print(TEST_FAKECONTENT);
        mockMimeResponse.flushBuffer();
        final byte[] writeResult = mockMimeResponse.getContentAsByteArray();
        assertArrayEquals("Written byte array does not match original ?", TEST_FAKECONTENT_ASBYTES, writeResult);
        assertTrue("Buffer not committed after processing ?", mockMimeResponse.isCommitted());
        final String writeResultAsString = mockMimeResponse.getContentAsString();
        assertEquals("Written result does not match original ?", TEST_FAKECONTENT, writeResultAsString);
    } catch (Exception ex) {
        fail("MockMimeResponse get/process printwriter failed.  Exception: " + ex);
    }
    try {
        mockMimeResponse.reset();
    } catch (IllegalStateException ise) {
    // Expected failure
    }
    mockMimeResponse.setCommitted(false);
    mockMimeResponse.reset();
    assertNull("After reset, character encoding not null ?", mockMimeResponse.getCharacterEncoding());
    assertNull("After reset, content-type not null ?", mockMimeResponse.getContentType());
    assertNull("After reset, locale not null ?", mockMimeResponse.getLocale());
}
Also used : MockPortalContext(org.apache.struts2.mock.web.portlet.MockPortalContext) MockMimeResponse(org.apache.struts2.mock.web.portlet.MockMimeResponse) OutputStream(java.io.OutputStream) MockPortletContext(org.apache.struts2.mock.web.portlet.MockPortletContext) ReadOnlyException(javax.portlet.ReadOnlyException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) MockPortletRequest(org.apache.struts2.mock.web.portlet.MockPortletRequest) PortletURL(javax.portlet.PortletURL) MockPortletURL(org.apache.struts2.mock.web.portlet.MockPortletURL) MockResourceURL(org.apache.struts2.mock.web.portlet.MockResourceURL) ResourceURL(javax.portlet.ResourceURL) PrintWriter(java.io.PrintWriter)

Aggregations

ResourceURL (javax.portlet.ResourceURL)17 MimeResponse (javax.portlet.MimeResponse)6 UserNode (org.exoplatform.portal.mop.user.UserNode)5 JSONArray (org.json.JSONArray)5 JSONObject (org.json.JSONObject)5 ExternalContext (javax.faces.context.ExternalContext)3 NavigationResource (org.exoplatform.web.url.navigation.NavigationResource)3 NodeURL (org.exoplatform.web.url.navigation.NodeURL)3 IOException (java.io.IOException)2 StringWriter (java.io.StringWriter)2 MalformedURLException (java.net.MalformedURLException)2 PortletResponse (javax.portlet.PortletResponse)2 PortletURL (javax.portlet.PortletURL)2 WebuiRequestContext (org.exoplatform.webui.application.WebuiRequestContext)2 BridgeTest (com.liferay.faces.bridge.tck.annotation.BridgeTest)1 SystemException (com.liferay.portal.kernel.exception.SystemException)1 FileEntry (com.liferay.portal.kernel.repository.model.FileEntry)1 OutputStream (java.io.OutputStream)1 PrintWriter (java.io.PrintWriter)1 Writer (java.io.Writer)1