javax.portlet.PortletRequest Java Examples

The following examples show how to use javax.portlet.PortletRequest. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SimpleMappingExceptionResolver.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Actually resolve the given exception that got thrown during on handler execution,
 * returning a ModelAndView that represents a specific error page if appropriate.
 * @param request current portlet request
 * @param response current portlet response
 * @param handler the executed handler, or null if none chosen at the time of
 * the exception (for example, if multipart resolution failed)
 * @param ex the exception that got thrown during handler execution
 * @return a corresponding ModelAndView to forward to, or null for default processing
 */
@Override
protected ModelAndView doResolveException(
		PortletRequest request, MimeResponse response, Object handler, Exception ex) {

	// Log exception, both at debug log level and at warn level, if desired.
	if (logger.isDebugEnabled()) {
		logger.debug("Resolving exception from handler [" + handler + "]: " + ex);
	}
	logException(ex, request);

	// Expose ModelAndView for chosen error view.
	String viewName = determineViewName(ex, request);
	if (viewName != null) {
		return getModelAndView(viewName, ex, request);
	}
	else {
		return null;
	}
}
 
Example #2
Source File: PortletMimeResponseContextImpl.java    From portals-pluto with Apache License 2.0 6 votes vote down vote up
@Override
public void setContentType(String contentType) {
   // The content type is set by Pluto for the render & header phases
   if (!isClosed()) { 
      if (getLifecycle().equals(PortletRequest.RESOURCE_PHASE)) {
         getServletResponse().setContentType(contentType);
      } else {
         String type = getServletResponse().getContentType();
         if (type == null) {
            // default MIME type for Pluto
            type = "text/html";
         } else {
            // ignore charset parameter
            type = type.replaceAll("([^;]*).*", "$1");
         }
         if (!type.equals(contentType) && !contentType.matches("\\s*(?:\\*|\\*/\\s*\\*)\\s*")) {
            throw new IllegalArgumentException("Invalid content type: " + contentType);
         }
      }
   }
}
 
Example #3
Source File: PortletWebRequestTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecoratedNativeRequest() {
	MockRenderRequest portletRequest = new MockRenderRequest();
	MockRenderResponse portletResponse = new MockRenderResponse();
	PortletRequest decoratedRequest = new PortletRequestWrapper(portletRequest);
	PortletResponse decoratedResponse = new PortletResponseWrapper(portletResponse);
	PortletWebRequest request = new PortletWebRequest(decoratedRequest, decoratedResponse);
	assertSame(decoratedRequest, request.getNativeRequest());
	assertSame(decoratedRequest, request.getNativeRequest(PortletRequest.class));
	assertSame(portletRequest, request.getNativeRequest(RenderRequest.class));
	assertSame(portletRequest, request.getNativeRequest(MockRenderRequest.class));
	assertNull(request.getNativeRequest(MultipartRequest.class));
	assertSame(decoratedResponse, request.getNativeResponse());
	assertSame(decoratedResponse, request.getNativeResponse(PortletResponse.class));
	assertSame(portletResponse, request.getNativeResponse(RenderResponse.class));
	assertSame(portletResponse, request.getNativeResponse(MockRenderResponse.class));
	assertNull(request.getNativeResponse(MultipartRequest.class));
}
 
Example #4
Source File: SecurityMappingTest.java    From portals-pluto with Apache License 2.0 6 votes vote down vote up
protected TestResult checkIsUserInUnmappedRole(PortletRequest request) {
    TestResult result = isUserLoggedIn(request);
    result.setDescription("Test if user is in unmapped role");
    if (result.getReturnCode() == TestResult.WARNING) {
        return result;
    }

    ExpectedResults expectedResults = ExpectedResults.getInstance();
    String role = expectedResults.getUnmappedSecurityRole();
    if (request.isUserInRole(role)) {
    	result.setReturnCode(TestResult.PASSED);
    } else {
    	result.setReturnCode(TestResult.WARNING);
    	result.setResultMessage("User is not in the expected role: " + role
    			+ ". This may be due to misconfiuration.");
    }
    return result;
}
 
Example #5
Source File: PortalUser.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public String getFirstName(PortletRequest request) {
	fixPortalType(request);
	String firstName = null;
	Map userInfo = (Map) request.getAttribute(PortletRequest.USER_INFO);

	switch (portalType) {
		case GRIDSPHERE:
			String fullName = getGridsphereFullName(request);
			firstName = fullName.trim().substring(0, fullName.indexOf(" "));
			break;
		case PLUTO:
		case UPORTAL:
			if (userInfo != null) {
				firstName = (String) userInfo.get("user.name.given");
			}
			break;
	}
	log.debug("First Name={}", firstName);
	return firstName;
}
 
Example #6
Source File: PreferenceCommonTest.java    From portals-pluto with Apache License 2.0 6 votes vote down vote up
protected TestResult checkSetPreferencesReturnsFirst(PortletRequest request) {
    TestResult result = new TestResult();
    result.setDescription("Ensure the first value set to a given "
    		+ "preference is returned first by PortletPreferences.getValue().");
    result.setSpecPLT("14.1");

    PortletPreferences preferences = request.getPreferences();
    try {
        preferences.setValues("TEST", new String[] { "FIRST", "SECOND" });
    } catch (ReadOnlyException ex) {
    	TestUtils.failOnException("Unable to set preference values.", ex, result);
    	return result;
    }

    String value = preferences.getValue("TEST", DEF_VALUE);
    if (value != null && value.equals("FIRST")) {
    	result.setReturnCode(TestResult.PASSED);
    } else {
    	TestUtils.failOnAssertion("preference value", value, "FIRST", result);
    }
    return result;
}
 
Example #7
Source File: PortletHelper.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static String getEmail(PortletRequest request) {
	String email = null;
	Map<String,String> userInfo = (Map<String,String>) request.getAttribute(PortletRequest.USER_INFO);

	switch (lookupPortalType(request)) {
		case GRIDSPHERE:
			if (userInfo != null) {
				email = userInfo.get("user.email");
			}
			break;
		case PLUTO:
		case UPORTAL:
			if (userInfo != null) {
				email = userInfo.get("user.home-info.online.email");
			}
	}

	debugPrint(request,"EMail="+email);
	return email;
}
 
Example #8
Source File: HeaderPortlet.java    From portals-pluto with Apache License 2.0 6 votes vote down vote up
@Override
protected void doView(RenderRequest req, RenderResponse resp) throws PortletException, IOException {
   
   if (isDebug) {
      StringBuilder txt = new StringBuilder(128);
      txt.append("Rendering. ");
      txt.append("RENDER_PART: ");
      txt.append((String)req.getAttribute(PortletRequest.RENDER_PART));
      logger.debug(txt.toString());
   }

   resp.setContentType("text/html");

   PortletRequestDispatcher rd = getPortletContext().getRequestDispatcher("/WEB-INF/jsp/view-hdp.jsp");
   rd.include(req, resp);

}
 
Example #9
Source File: PortletHelper.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static String getEmail(PortletRequest request) {
	String email = null;
	Map<String,String> userInfo = (Map<String,String>) request.getAttribute(PortletRequest.USER_INFO);

	switch (lookupPortalType(request)) {
		case GRIDSPHERE:
			if (userInfo != null) {
				email = userInfo.get("user.email");
			}
			break;
		case PLUTO:
		case UPORTAL:
			if (userInfo != null) {
				email = userInfo.get("user.home-info.online.email");
			}
	}

	debugPrint(request,"EMail="+email);
	return email;
}
 
Example #10
Source File: PortletHelper.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public static void debugPrint(PortletRequest request, String line)
{
	if ( line == null ) return;
	line = line.replaceAll("<","&lt;").replaceAll(">","&gt;");

	PortletSession pSession = request.getPortletSession(true);
	String debugOut = null;
	try {
		debugOut = (String) pSession.getAttribute("debug.print");
	} catch (Throwable t) {
		debugOut = null;
	}
	if ( debugOut == null ) {
		debugOut = line;
	} else {
		debugOut = debugOut + "\n" + line;
	}
	pSession.setAttribute("debug.print",debugOut);
}
 
Example #11
Source File: AnnotationMethodHandlerAdapter.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
private String determineDefaultPhase(Method handlerMethod) {
	if (void.class != handlerMethod.getReturnType()) {
		return PortletRequest.RENDER_PHASE;
	}
	for (Class<?> argType : handlerMethod.getParameterTypes()) {
		if (ActionRequest.class.isAssignableFrom(argType) || ActionResponse.class.isAssignableFrom(argType) ||
				InputStream.class.isAssignableFrom(argType) || Reader.class.isAssignableFrom(argType)) {
			return PortletRequest.ACTION_PHASE;
		}
		else if (RenderRequest.class.isAssignableFrom(argType) || RenderResponse.class.isAssignableFrom(argType) ||
				OutputStream.class.isAssignableFrom(argType) || Writer.class.isAssignableFrom(argType)) {
			return PortletRequest.RENDER_PHASE;
		}
		else if (ResourceRequest.class.isAssignableFrom(argType) || ResourceResponse.class.isAssignableFrom(argType)) {
			return PortletRequest.RESOURCE_PHASE;
		}
		else if (EventRequest.class.isAssignableFrom(argType) || EventResponse.class.isAssignableFrom(argType)) {
			return PortletRequest.EVENT_PHASE;
		}
	}
	return "";
}
 
Example #12
Source File: DispatcherRenderParameterTest.java    From portals-pluto with Apache License 2.0 6 votes vote down vote up
protected TestResult checkParameters(PortletContext context,
                                     PortletRequest request,
                                     PortletResponse response)
throws IOException, PortletException {

	// Dispatch to the companion servlet: call checkParameters().
	StringBuffer buffer = new StringBuffer();
	buffer.append(SERVLET_PATH).append("?")
			.append(KEY_TARGET).append("=").append(TARGET_PARAMS)
			.append("&").append(KEY_A).append("=").append(VALUE_A)
			.append("&").append(KEY_B).append("=").append(VALUE_B);

	if (LOG.isDebugEnabled()) {
		LOG.debug("Dispatching to: " + buffer.toString());
	}
    PortletRequestDispatcher dispatcher = context.getRequestDispatcher(
    		buffer.toString());
    dispatcher.include((RenderRequest) request, (RenderResponse) response);

	// Retrieve test result returned by the companion servlet.
    TestResult result = (TestResult) request.getAttribute(RESULT_KEY);
	request.removeAttribute(RESULT_KEY);
    return result;
}
 
Example #13
Source File: PortletUtils.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Return a map containing all parameters with the given prefix.
 * Maps single values to String and multiple values to String array.
 * <p>For example, with a prefix of "spring_", "spring_param1" and
 * "spring_param2" result in a Map with "param1" and "param2" as keys.
 * <p>Similar to portlet
 * {@link javax.portlet.PortletRequest#getParameterMap()},
 * but more flexible.
 * @param request portlet request in which to look for parameters
 * @param prefix the beginning of parameter names
 * (if this is {@code null} or the empty string, all parameters will match)
 * @return map containing request parameters <b>without the prefix</b>,
 * containing either a String or a String array as values
 * @see javax.portlet.PortletRequest#getParameterNames
 * @see javax.portlet.PortletRequest#getParameterValues
 * @see javax.portlet.PortletRequest#getParameterMap
 */
public static Map<String, Object> getParametersStartingWith(PortletRequest request, String prefix) {
	Assert.notNull(request, "Request must not be null");
	Enumeration<String> paramNames = request.getParameterNames();
	Map<String, Object> params = new TreeMap<String, Object>();
	if (prefix == null) {
		prefix = "";
	}
	while (paramNames != null && paramNames.hasMoreElements()) {
		String paramName = paramNames.nextElement();
		if ("".equals(prefix) || paramName.startsWith(prefix)) {
			String unprefixed = paramName.substring(prefix.length());
			String[] values = request.getParameterValues(paramName);
			if (values == null || values.length == 0) {
				// Do nothing, no values found at all.
			}
			else if (values.length > 1) {
				params.put(unprefixed, values);
			}
			else {
				params.put(unprefixed, values[0]);
			}
		}
	}
	return params;
}
 
Example #14
Source File: BaseEventTest.java    From portals-pluto with Apache License 2.0 5 votes vote down vote up
@TestPhase(PortletRequest.ACTION_PHASE)
public TestResult checkFireEventsFromActionPhase(ActionRequest request,
        ActionResponse response) {
    tally(response);
    TestResult result = new TestResult();
    result.setReturnCode(TestResult.UNDEFINED);
    result.setDescription("Fire several events to test processing." +
            " Be sure to check to Companion portlet to make sure" +
            " that all tests are correctly run.");
    result.setSpecPLT("15.2.3");
    fireEvents(request, response);
    
    return result;
}
 
Example #15
Source File: PortletRequestUtils.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Get an array of boolean parameters, return an empty array if not found.
 * <p>Accepts "true", "on", "yes" (any case) and "1" as values for true;
 * treats every other non-empty value as false (i.e. parses leniently).
 * @param request current portlet request
 * @param name the name of the parameter with multiple possible values
 */
public static boolean[] getBooleanParameters(PortletRequest request, String name) {
	try {
		return getRequiredBooleanParameters(request, name);
	}
	catch (PortletRequestBindingException ex) {
		return new boolean[0];
	}
}
 
Example #16
Source File: ActionConfigIndexer.java    From opencps-v2 with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected Summary doGetSummary(Document document, Locale locale, String snippet, PortletRequest portletRequest,
		PortletResponse portletResponse) throws Exception {
	Summary summary = createSummary(document);

	summary.setMaxContentLength(QueryUtil.ALL_POS);

	return summary;
}
 
Example #17
Source File: MiscTest.java    From portals-pluto with Apache License 2.0 5 votes vote down vote up
protected TestResult checkPortalInfo(PortletRequest request) {
    TestResult result = new TestResult();
    result.setDescription("Ensure the expected portal info is returned.");

    String portalInfo = request.getPortalContext().getPortalInfo();
    ExpectedResults expectedResults = ExpectedResults.getInstance();
    String expected = expectedResults.getPortalInfo();
    if (portalInfo != null && portalInfo.equals(expected)) {
    	result.setReturnCode(TestResult.PASSED);
    } else {
    	TestUtils.failOnAssertion("portal info", portalInfo, expected, result);
    }
    return result;
}
 
Example #18
Source File: PortalUser.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public String getUsername(PortletRequest request) {
	fixPortalType(request);
	String username = null;
	Map userInfo = (Map) request.getAttribute(PortletRequest.USER_INFO);

	switch (portalType) {
		case GRIDSPHERE:
			if (userInfo != null) {
				username = (String) userInfo.get("user.name");
			}
			break;
		case ORACLEPORTAL:
			log.debug("userInfo {}", userInfo); // Changes by Venkatesh for Oracle Portal
			log.debug("Remote User={}", username); // Oracle portal is populating user name with [1] at the end
			// the following code will get rid of the unnecessary characters
			username = request.getRemoteUser();
			if(username != null && username.indexOf("[") != -1)
			{
				log.debug("Modifying user name for Oracle Portal={}", username);
				int corruptIndex = username.indexOf('[');
				username = username.substring(0,corruptIndex);
			}
			break;
		case PLUTO:  
		case UPORTAL:
			username = request.getRemoteUser();
			break;
	}
	log.debug("Remote User={}", username);
	return username;
}
 
Example #19
Source File: AnnotationMethodHandlerAdapter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected WebDataBinder createBinder(NativeWebRequest webRequest, Object target, String objectName)
		throws Exception {

	return AnnotationMethodHandlerAdapter.this.createBinder(
			webRequest.getNativeRequest(PortletRequest.class), target, objectName);
}
 
Example #20
Source File: PortletUtilsTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetSessionAttributeWithExistingSessionAndSpecificScope() throws Exception {
	PortletSession session = mock(PortletSession.class);
	PortletRequest request = mock(PortletRequest.class);
	given(request.getPortletSession()).willReturn(session); // must not create Session ...
	PortletUtils.setSessionAttribute(request, "foo", "foo", PortletSession.APPLICATION_SCOPE);
	verify(session).setAttribute("foo", "foo", PortletSession.APPLICATION_SCOPE);
}
 
Example #21
Source File: PortletArtifactProducer.java    From portals-pluto with Apache License 2.0 5 votes vote down vote up
/**
 * Producer method for the portlet request. 
 */
@Produces @PortletRequestScoped @Named("portletRequest")
public static PortletRequest producePortletRequest() {
   PortletArtifactProducer pap = producers.get();
   assert pap != null;
   return pap.req;
}
 
Example #22
Source File: PortletHelper.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public static Map getErrorMap(PortletRequest request)
{   
	PortletSession pSession = request.getPortletSession(true);
	try {
		return (Map) pSession.getAttribute("error.map");
	} catch (Throwable t) {
		return null;
	}
}
 
Example #23
Source File: AbstractReflectivePortletTest.java    From portals-pluto with Apache License 2.0 5 votes vote down vote up
/**
 * Returns check methods to run as tests using java reflection.
 * The following rules are applied to select check methods:
 * <ul>
 *   <li>methods declared in this class or inherited from super class</li>
 *   <li>methods with modifier 'public' or 'protected', but not 'abstract'</li>
 *   <li>methods that starts with <code>check</code></li>
 * </ul>
 * @return a list of check methods.
 */
private List<Method> getCheckMethods(PortletRequest request) {
    List<Method> checkMethods = new ArrayList<Method>();
    DefaultTestPhase dtp = getClass().getAnnotation(DefaultTestPhase.class);
    String defaultPhase = dtp != null ? dtp.value() 
                                      : PortletRequest.RENDER_PHASE;
    String lifecyclePhase = (String) 
            request.getAttribute(PortletRequest.LIFECYCLE_PHASE);
    debugWithName("Default phase: " + defaultPhase);
    debugWithName("Lifecycle Phase: " + lifecyclePhase);
    for (Class<?> clazz = getClass();
            clazz != null && AbstractReflectivePortletTest.class.isAssignableFrom(clazz);
            clazz = clazz.getSuperclass()) {
        // debugWithName("Checking class: " + clazz.getName());
        Method[] methods = clazz.getDeclaredMethods();
        String phase;
        TestPhase testPhase;
        for (int i = 0; i < methods.length; i++) {
            int mod = methods[i].getModifiers();
            testPhase = methods[i].getAnnotation(TestPhase.class);
            phase = testPhase != null ? testPhase.value() : defaultPhase;
            if ((Modifier.isPublic(mod) || Modifier.isProtected(mod))
                   && lifecyclePhase.equals(phase)
                   && !Modifier.isAbstract(mod)
                   && methods[i].getName().startsWith("check")) {
                // debugWithName(" - got check method: " + methods[i].getName());
                debugWithName(" - got check method: " + methods[i].getName());
                checkMethods.add(methods[i]);
            }
        }
    }
    return checkMethods;
}
 
Example #24
Source File: UserRoleAuthorizationInterceptor.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public final boolean preHandle(PortletRequest request, PortletResponse response, Object handler)
		throws PortletException, IOException {

	if (this.authorizedRoles != null) {
		for (String role : this.authorizedRoles) {
			if (request.isUserInRole(role)) {
				return true;
			}
		}
	}
	handleNotAuthorized(request, response, handler);
	return false;
}
 
Example #25
Source File: PortletHelper.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static String getGridsphereFullName(PortletRequest request) {
	String fullName = null;
	Map<String,String> userInfo = (Map<String,String>) request.getAttribute(PortletRequest.USER_INFO);
	if (userInfo != null) {
		fullName = userInfo.get("user.name.full");
	}
	return fullName;
}
 
Example #26
Source File: DispatcherTests3S_SPEC2_19_IncludeServletRender_servlet.java    From portals-pluto with Apache License 2.0 5 votes vote down vote up
protected void processTCKReq(HttpServletRequest request, HttpServletResponse response) throws ServletException,
      IOException {

   PortletRequest portletReq = (PortletRequest) request.getAttribute("javax.portlet.request");
   request.getAttribute("javax.portlet.response");
   request.getAttribute("javax.portlet.config");
   Thread.currentThread().getId();
   portletReq.getAttribute(THREADID_ATTR);

   new JSR286DispatcherTestCaseDetails();

   // Create result objects for the tests

}
 
Example #27
Source File: ViewEngineContextImpl.java    From portals-pluto with Apache License 2.0 5 votes vote down vote up
public ViewEngineContextImpl(Configuration configuration, PortletRequest portletRequest, MimeResponse mimeResponse,
	Models models, Locale locale) {
	this.configuration = configuration;
	this.portletRequest = portletRequest;
	this.mimeResponse = mimeResponse;
	this.models = models;
	this.locale = locale;
}
 
Example #28
Source File: PortletHelper.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public static int lookupPortalType(PortletRequest request)
{
	String portalInfo = request.getPortalContext().getPortalInfo();
	if ( portalInfo.toLowerCase().startsWith("sakai-charon") ) {
		return SAKAI;
	} else {
		return PLUTO;  // Assume a Pluto-based portal
	}
}
 
Example #29
Source File: WebContextProducer.java    From portals-pluto with Apache License 2.0 5 votes vote down vote up
@PortletRequestScoped
@Produces
public IWebContext getWebContext(BeanManager beanManager, VariableValidator variableValidator,
	MvcContext mvcContext, Models models, PortletRequest portletRequest, MimeResponse mimeResponse,
	ServletContext servletContext) {

	return new CDIPortletWebContext(beanManager, variableValidator, models,
			(String) portletRequest.getAttribute(PortletRequest.LIFECYCLE_PHASE),
			new HttpServletRequestAdapter(portletRequest), new HttpServletResponseAdapter(mimeResponse),
			servletContext, mvcContext.getLocale());
}
 
Example #30
Source File: AdapterPortlet.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Handle simple form.
 *
 * @param request
 *            the request
 * @param requestContext
 *            the request context
 *
 * @throws SourceBeanException
 *             the source bean exception
 */
private void handleSimpleForm(PortletRequest request, RequestContextIFace requestContext) throws SourceBeanException {
	SourceBean serviceRequest = requestContext.getServiceRequest();
	Enumeration names = request.getParameterNames();
	while (names.hasMoreElements()) {
		String parameterName = (String) names.nextElement();
		String[] parameterValues = request.getParameterValues(parameterName);
		if (parameterValues != null)
			for (int i = 0; i < parameterValues.length; i++)
				serviceRequest.setAttribute(parameterName, parameterValues[i]);
	} // while (names.hasMoreElements())
}