下面列出了org.springframework.core.io.ResourceEditor#javax.portlet.PortletException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void processAction(
ActionRequest request,
ActionResponse response)
throws PortletException, IOException {
PortletTracer.info(Constants.NOME_MODULO, "AdapterPortlet", "action", "Invocato");
// set into threadLocal variables the jsr 168 portlet object
PortletAccess.setPortletConfig(getPortletConfig());
PortletAccess.setPortletRequest(request);
PortletAccess.setPortletResponse(response);
PortletSession portletSession = request.getPortletSession();
portletSession.setAttribute("BrowserLocale", request.getLocale());
processService(request, response);
}
public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {
response.getWriter().println("<html>"
+ "<head>"
+ "<script>"
+ "var "+response.getNamespace()+"message = 'Handle Submit, Portlet Two';"
+ "function "+response.getNamespace()+"handleSubmit(){"
+ " alert('Handle Submit, The Portlet Is '+"+response.getNamespace()+"message);"
+ "}"
+ "</script>"
+ "</head>"
+ "<form action="+response.createActionURL()+">"
+ " <input type='button' value='Click On Me' onclick='"+response.getNamespace()+"handleSubmit()'/>"
+ "</form>"
+ "</html>");
}
@Override
public void validate(PortletRequest request) throws PortletException {
if (!PortletAnnotationMappingUtils.checkHeaders(this.headers, request)) {
throw new PortletRequestBindingException("Header conditions \"" +
StringUtils.arrayToDelimitedString(this.headers, ", ") +
"\" not met for actual request");
}
if (!this.methods.isEmpty()) {
if (!(request instanceof ClientDataRequest)) {
throw new PortletRequestMethodNotSupportedException(StringUtils.toStringArray(this.methods));
}
String method = ((ClientDataRequest) request).getMethod();
if (!this.methods.contains(method)) {
throw new PortletRequestMethodNotSupportedException(method, StringUtils.toStringArray(this.methods));
}
}
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof Portlet) {
PortletConfig config = this.portletConfig;
if (config == null || !this.useSharedPortletConfig) {
config = new DelegatingPortletConfig(beanName, this.portletContext, this.portletConfig);
}
try {
((Portlet) bean).init(config);
}
catch (PortletException ex) {
throw new BeanInitializationException("Portlet.init threw exception", ex);
}
}
return bean;
}
/**
* Create new PortletConfigPropertyValues.
* @param config PortletConfig we'll use to take PropertyValues from
* @param requiredProperties set of property names we need, where
* we can't accept default values
* @throws PortletException if any required properties are missing
*/
private PortletConfigPropertyValues(PortletConfig config, Set<String> requiredProperties)
throws PortletException {
Set<String> missingProps = (requiredProperties != null && !requiredProperties.isEmpty()) ?
new HashSet<String>(requiredProperties) : null;
Enumeration<String> en = config.getInitParameterNames();
while (en.hasMoreElements()) {
String property = en.nextElement();
Object value = config.getInitParameter(property);
addPropertyValue(new PropertyValue(property, value));
if (missingProps != null) {
missingProps.remove(property);
}
}
// fail if we are still missing properties
if (missingProps != null && missingProps.size() > 0) {
throw new PortletException(
"Initialization from PortletConfig for portlet '" + config.getPortletName() +
"' failed; the following required properties were missing: " +
StringUtils.collectionToDelimitedString(missingProps, ", "));
}
}
/**
* Serve the resource as specified in the given request to the given response,
* using the PortletContext's request dispatcher.
* <p>This is roughly equivalent to Portlet 2.0 GenericPortlet.
* @param request the current resource request
* @param response the current resource response
* @param context the current Portlet's PortletContext
* @throws PortletException propagated from Portlet API's forward method
* @throws IOException propagated from Portlet API's forward method
*/
public static void serveResource(ResourceRequest request, ResourceResponse response, PortletContext context)
throws PortletException, IOException {
String id = request.getResourceID();
if (id != null) {
if (!PortletUtils.isProtectedResource(id)) {
PortletRequestDispatcher rd = context.getRequestDispatcher(id);
if (rd != null) {
rd.forward(request, response);
return;
}
}
response.setProperty(ResourceResponse.HTTP_STATUS_CODE, "404");
}
}
@Test
public void unknownRequiredInitParameter() throws Exception {
String testParam = "testParam";
String testValue = "testValue";
portletConfig.addInitParameter(testParam, testValue);
TestPortletBean portletBean = new TestPortletBean();
portletBean.addRequiredProperty("unknownParam");
assertNull(portletBean.getTestParam());
try {
portletBean.init(portletConfig);
fail("should have thrown PortletException");
}
catch (PortletException ex) {
// expected
}
assertNull(portletBean.getTestParam());
}
public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {
response.getWriter().println("<html>"
+ "<head>"
+ "<script>"
+ "var "+response.getNamespace()+"message = 'Handle Submit, Portlet One';"
+ "function "+response.getNamespace()+"handleSubmit(){"
+ " alert('Handle Submit, The Portlet Is '+"+response.getNamespace()+"message);"
+ "}"
+ "</script>"
+ "</head>"
+ "<form action="+response.createActionURL()+">"
+ " <input type='button' value='Click On Me' onclick='"+response.getNamespace()+"handleSubmit()'/>"
+ "</form>"
+ "</html>");
}
public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException {
// Handle default MIME type request
if(request.getContentType().equals("application/x-www-form-urlencoded")){
String message = request.getParameter("message");
System.out.println(message);
}
// Handle multipart request
else if(request.getContentType().contains("multipart/form-data")){
// Create FileItemFactory
FileItemFactory factory = new DiskFileItemFactory();
// Create PortletFileUpload instance
PortletFileUpload fileUpload = new PortletFileUpload(factory);
try {
// Instead of parsing the request ourselves, let Apache PortletFileUpload do that
List<FileItem> files = fileUpload.parseRequest(request);
// Iterate over files
for(FileItem item : files){
// Print out some of information
System.out.println("File Uploaded Name Is : "+item.getName()+" , Its Size Is :: "+item.getSize());
}
} catch (FileUploadException e) {
e.printStackTrace();
}
System.out.println(response.encodeURL("/index.html"));
}
}
public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException{
// Create request dispatcher
PortletRequestDispatcher dispatcher = this.getPortletContext().getNamedDispatcher("RegisterEmployeeServlet");
try {
// Include
dispatcher.include(request, response);
// Set render parameter
response.setRenderParameter("status", "success");
}
catch(Exception ex){
// Set render parameter
response.setRenderParameter("status", "failed");
response.setRenderParameter("exception", ex.getMessage());
}
}
@Override
public void render(
RenderRequest renderRequest, RenderResponse renderResponse)
throws IOException, PortletException {
ThemeDisplay themeDisplay =
(ThemeDisplay) renderRequest.getAttribute(WebKeys.THEME_DISPLAY);
PortletDisplay portletDisplay = themeDisplay.getPortletDisplay();
String portletId = portletDisplay.getId();
JSONObject urlObject = JSONFactoryUtil.createJSONObject();
JSONObject apiObject = JSONFactoryUtil.createJSONObject();
// url
PortletURL registerResultURL = PortletURLFactoryUtil.create(
renderRequest, portletId, themeDisplay.getPlid(),
PortletRequest.RENDER_PHASE);
registerResultURL.setPortletMode(PortletMode.VIEW);
registerResultURL.setWindowState(LiferayWindowState.EXCLUSIVE);
registerResultURL.setParameter(
"mvcPath", "/templates/applicant_bvh/register_result.ftl");
urlObject.put("register_result", registerResultURL.toString());
// api
apiObject.put("server", themeDisplay.getPortalURL() + "/o/rest/v2");
apiObject.put(
"portletNamespace",
themeDisplay.getPortletDisplay().getNamespace());
// set varible
renderRequest.setAttribute("ajax", urlObject);
renderRequest.setAttribute("api", apiObject);
super.render(renderRequest, renderResponse);
}
@Override
public void render(
RenderRequest renderRequest, RenderResponse renderResponse)
throws IOException, PortletException {
ThemeDisplay themeDisplay =
(ThemeDisplay) renderRequest.getAttribute(WebKeys.THEME_DISPLAY);
PortletDisplay portletDisplay = themeDisplay.getPortletDisplay();
String portletId = portletDisplay.getId();
JSONObject urlObject = JSONFactoryUtil.createJSONObject();
JSONObject apiObject = JSONFactoryUtil.createJSONObject();
// url
PortletURL confirmPasswordURL = PortletURLFactoryUtil.create(
renderRequest, portletId, themeDisplay.getPlid(),
PortletRequest.RENDER_PHASE);
confirmPasswordURL.setPortletMode(PortletMode.VIEW);
confirmPasswordURL.setWindowState(LiferayWindowState.EXCLUSIVE);
confirmPasswordURL.setParameter(
"mvcPath", "/templates/applicant/confirm_password.ftl");
urlObject.put("confirm_password", confirmPasswordURL.toString());
// api
apiObject.put("server", themeDisplay.getPortalURL() + "/o/rest/v2");
apiObject.put(
"portletNamespace",
themeDisplay.getPortletDisplay().getNamespace());
// set varible
renderRequest.setAttribute("ajax", urlObject);
renderRequest.setAttribute("api", apiObject);
super.render(renderRequest, renderResponse);
}
@Override
public void render(
RenderRequest renderRequest, RenderResponse renderResponse)
throws IOException, PortletException {
ThemeDisplay themeDisplay =
(ThemeDisplay) renderRequest.getAttribute(WebKeys.THEME_DISPLAY);
PortletDisplay portletDisplay = themeDisplay.getPortletDisplay();
String portletId = portletDisplay.getId();
JSONObject urlObject = JSONFactoryUtil.createJSONObject();
JSONObject apiObject = JSONFactoryUtil.createJSONObject();
// url
PortletURL registerResultURL = PortletURLFactoryUtil.create(
renderRequest, portletId, themeDisplay.getPlid(),
PortletRequest.RENDER_PHASE);
registerResultURL.setPortletMode(PortletMode.VIEW);
registerResultURL.setWindowState(LiferayWindowState.EXCLUSIVE);
registerResultURL.setParameter(
"mvcPath", "/templates/applicant/register_result.ftl");
urlObject.put("register_result", registerResultURL.toString());
// api
apiObject.put("server", themeDisplay.getPortalURL() + "/o/rest/v2");
apiObject.put(
"portletNamespace",
themeDisplay.getPortletDisplay().getNamespace());
// set varible
renderRequest.setAttribute("ajax", urlObject);
renderRequest.setAttribute("api", apiObject);
super.render(renderRequest, renderResponse);
}
@Override
protected void doView(
RenderRequest renderRequest, RenderResponse renderResponse)
throws IOException, PortletException {
PrintWriter printWriter = renderResponse.getWriter();
printWriter.print("opencps-lang Portlet - Hello World!");
}
@Override
public void init() throws PortletException {
super.init();
PortletTracer.info(Constants.NOME_MODULO, "AdapterPortlet", "init", "Invocato");
String serializeSessionStr = (String) ConfigSingleton.getInstance().getAttribute(SERIALIZE_SESSION_ATTRIBUTE);
if ((serializeSessionStr != null) && (serializeSessionStr.equalsIgnoreCase("TRUE"))) {
serializeSession = true;
}
PortletInitializerManager.init();
}
@Override
public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException {
PortletTracer.info(Constants.NOME_MODULO, "AdapterPortlet", "action", "Invocato");
// set into threadLocal variables the jsr 168 portlet object
PortletAccess.setPortletConfig(getPortletConfig());
PortletAccess.setPortletRequest(request);
PortletAccess.setPortletResponse(response);
PortletSession portletSession = request.getPortletSession();
portletSession.setAttribute("BrowserLocale", request.getLocale());
processService(request, response);
}
public void init() throws PortletException {
super.init();
PortletTracer.info(Constants.NOME_MODULO, "AdapterPortlet", "init", "Invocato");
String serializeSessionStr = (String) ConfigSingleton.getInstance().getAttribute(SERIALIZE_SESSION_ATTRIBUTE);
if ((serializeSessionStr != null) && (serializeSessionStr.equalsIgnoreCase("TRUE"))) {
serializeSession = true;
}
PortletInitializerManager.init();
}
@Override
public void init() throws PortletException {
super.init();
ConfigSingleton.setConfigFileName("/WEB-INF/conf/master.xml");
ConfigSingleton.setRootPath(getPortletContext().getRealPath(""));
ConfigSingleton.setConfigurationCreation(new StreamCreatorConfiguration());
PortletTracer.info(Constants.NOME_MODULO, "AdapterPortlet", "init", "Invocato");
String serializeSessionStr = (String) ConfigSingleton.getInstance().getAttribute(SERIALIZE_SESSION_ATTRIBUTE);
if ((serializeSessionStr != null) && (serializeSessionStr.equalsIgnoreCase("TRUE"))) {
serializeSession = true;
}
PortletInitializerManager.init();
}
@Override
public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException {
PortletTracer.info(Constants.NOME_MODULO, "AdapterPortlet", "action", "Invocato");
// set into threadLocal variables the jsr 168 portlet object
PortletAccess.setPortletConfig(getPortletConfig());
PortletAccess.setPortletRequest(request);
PortletAccess.setPortletResponse(response);
PortletSession portletSession = request.getPortletSession();
portletSession.setAttribute("BrowserLocale", request.getLocale());
processService(request, response);
}
public void doView(RenderRequest request, RenderResponse response)
throws PortletException, IOException
{
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
String user = request.getParameter("user");
writer.println("<h1>Hello "+user+"!</h1>");
}
public Method resolveHandlerMethod(PortletRequest request) throws PortletException {
Map<RequestMappingInfo, Method> targetHandlerMethods = new LinkedHashMap<RequestMappingInfo, Method>();
for (Method handlerMethod : getHandlerMethods()) {
RequestMappingInfo mappingInfo = this.mappings.get(handlerMethod);
if (mappingInfo.match(request)) {
Method oldMappedMethod = targetHandlerMethods.put(mappingInfo, handlerMethod);
if (oldMappedMethod != null && oldMappedMethod != handlerMethod) {
throw new IllegalStateException("Ambiguous handler methods mapped for portlet mode '" +
request.getPortletMode() + "': {" + oldMappedMethod + ", " + handlerMethod +
"}. If you intend to handle the same mode in multiple methods, then factor " +
"them out into a dedicated handler class with that mode mapped at the type level!");
}
}
}
if (!targetHandlerMethods.isEmpty()) {
if (targetHandlerMethods.size() == 1) {
return targetHandlerMethods.values().iterator().next();
}
else {
RequestMappingInfo bestMappingMatch = null;
for (RequestMappingInfo mapping : targetHandlerMethods.keySet()) {
if (bestMappingMatch == null) {
bestMappingMatch = mapping;
}
else {
if (mapping.isBetterMatchThan(bestMappingMatch)) {
bestMappingMatch = mapping;
}
}
}
return targetHandlerMethods.get(bestMappingMatch);
}
}
else {
throw new NoHandlerFoundException("No matching handler method found for portlet request", request);
}
}
public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException{
// Create request dispatcher
PortletRequestDispatcher dispatcher = this.getPortletContext().getNamedDispatcher("RegisterEmployeeServlet");
try {
// Include
dispatcher.include(request, response);
// Set render parameter
response.setRenderParameter("status", "success");
}
catch(Exception ex){
// Set render parameter
response.setRenderParameter("status", "failed");
response.setRenderParameter("exception", ex.getMessage());
}
}
/**
* Return the HandlerAdapter for this handler object.
* @param handler the handler object to find an adapter for
* @throws PortletException if no HandlerAdapter can be found for the handler.
* This is a fatal error.
*/
protected HandlerAdapter getHandlerAdapter(Object handler) throws PortletException {
for (HandlerAdapter ha : this.handlerAdapters) {
if (logger.isDebugEnabled()) {
logger.debug("Testing handler adapter [" + ha + "]");
}
if (ha.supports(handler)) {
return ha;
}
}
throw new PortletException("No adapter for handler [" + handler +
"]: Does your handler implement a supported interface like Controller?");
}
@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;
}
/**
* Map config parameters onto bean properties of this portlet, and
* invoke subclass initialization.
* @throws PortletException if bean properties are invalid (or required
* properties are missing), or if subclass initialization fails.
*/
@Override
public final void init() throws PortletException {
if (logger.isInfoEnabled()) {
logger.info("Initializing portlet '" + getPortletName() + "'");
}
// Set bean properties from init parameters.
try {
PropertyValues pvs = new PortletConfigPropertyValues(getPortletConfig(), this.requiredProperties);
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
ResourceLoader resourceLoader = new PortletContextResourceLoader(getPortletContext());
bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));
initBeanWrapper(bw);
bw.setPropertyValues(pvs, true);
}
catch (BeansException ex) {
logger.error("Failed to set bean properties on portlet '" + getPortletName() + "'", ex);
throw ex;
}
// let subclasses do whatever initialization they like
initPortletBean();
if (logger.isInfoEnabled()) {
logger.info("Portlet '" + getPortletName() + "' configured successfully");
}
}
/**
* Delegate action requests to processRequest/doActionService.
*/
@Override
public final void processAction(ActionRequest request, ActionResponse response)
throws PortletException, IOException {
processRequest(request, response);
}
/**
* Delegate render requests to processRequest/doRenderService.
*/
@Override
protected final void doDispatch(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
processRequest(request, response);
}
@Override
public ModelAndView handleRenderRequest(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
if (!Locale.CANADA.equals(request.getLocale())) {
throw new PortletException("Incorrect Locale in RenderRequest");
}
response.getWriter().write("locale-ok");
return null;
}
@Override
public ModelAndView handleRenderRequest(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
if (!Locale.CANADA.equals(LocaleContextHolder.getLocale())) {
throw new PortletException("Incorrect Locale in LocaleContextHolder");
}
response.getWriter().write("locale-ok");
return null;
}
@Override
public void render(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
synchronized(this){
renderCount++;
}
response.getWriter().print("<form action="+response.createActionURL()+">"
+ "<p> The number of initiated Portlets by the container is :: "+initCount+"</p>"
+ "<p> The number of processed actions by the container is :: "+actionCount+"</p>"
+ "<p> The number of achieved render by the container is :: "+renderCount+"</p>"
+"<input value='Submit' type='submit'/><br/>"
+ "<a href='"+response.createRenderURL()+"'>Render Again</a>"
+ "</form>");
}