List of usage examples for org.springframework.web.servlet.view InternalResourceView InternalResourceView
public InternalResourceView(String url)
From source file:com.asual.summer.core.ErrorResolver.java
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) {/*w w w. j a v a 2 s.c o m*/ if (e instanceof BindException) { BindException be = (BindException) e; Map<String, Map<String, Object>> errors = new HashMap<String, Map<String, Object>>(); for (FieldError fe : (List<FieldError>) be.getFieldErrors()) { Map<String, Object> error = new HashMap<String, Object>(); Object[] args = fe.getArguments(); String key = fe.isBindingFailure() ? fe.getCodes()[2].replaceFirst("typeMismatch", "conversion") : "validation." + fe.getCodes()[2]; String message = ResourceUtils.getMessage(key, args); if (message == null) { if (!fe.isBindingFailure()) { if (key.split("\\.").length > 3) { message = ResourceUtils .getMessage(key.substring(0, key.indexOf(".", key.indexOf(".") + 1)) + key.substring(key.lastIndexOf(".")), args); } if (message == null && key.split("\\.").length > 2) { message = ResourceUtils .getMessage(key.substring(0, key.indexOf(".", key.indexOf(".") + 1)), args); } } else if (fe.isBindingFailure() && key.split("\\.").length > 2) { message = ResourceUtils.getMessage( key.substring(0, key.indexOf(".")) + key.substring(key.lastIndexOf(".")), args); } else { message = fe.getDefaultMessage(); } } error.put("message", message != null ? message : "Error (" + key + ")"); error.put("value", fe.getRejectedValue()); errors.put(fe.getField(), error); } for (ObjectError oe : (List<ObjectError>) be.getGlobalErrors()) { Map<String, Object> error = new HashMap<String, Object>(); Object[] args = oe.getArguments(); String key = "global" + (oe.getCodes() != null ? "." + oe.getCodes()[2] : ""); String message = ResourceUtils.getMessage(key, args); if (message == null) { if (key.split("\\.").length > 3) { message = ResourceUtils.getMessage(key.substring(0, key.indexOf(".", key.indexOf(".") + 1)) + key.substring(key.lastIndexOf(".")), args); } if (message == null && key.split("\\.").length > 2) { message = ResourceUtils.getMessage(key.substring(0, key.indexOf(".", key.indexOf(".") + 1)), args); } if (message == null) { message = oe.getDefaultMessage(); } } error.put("message", message != null ? message : "Error (" + key + ")"); error.put("value", oe.getObjectName()); errors.put(oe.getObjectName(), error); } String form = (String) RequestUtils.getParameter("_form"); if (form != null) { if (request.getAttribute(ERRORS) == null) { request.setAttribute(ERRORS, errors); request.setAttribute(be.getObjectName(), be.getTarget()); return new ModelAndView(new InternalResourceView( form.concat(form.contains("?") ? "&" : "?").concat("_error=true"))); } } else { List<String> pairs = new ArrayList<String>(); for (String key : errors.keySet()) { pairs.add(key + "=" + errors.get(key).get("message")); } try { response.sendError(HttpServletResponse.SC_BAD_REQUEST, StringUtils.join(pairs, ";")); } catch (IOException ioe) { logger.error(ioe.getMessage(), ioe); } } } return null; }
From source file:me.bulat.jivr.webmin.web.defended.admin.ConsulControllerTest.java
@Test @WithMockUser(username = "alexb", roles = { "ADMIN" }) public void consulPage() throws Exception { List<String> nodeNames = nodes.stream().map(NodeKey::getNodeName).collect(Collectors.toList()); List<String> serviceNames = services.stream().map(ServiceKey::getServiceName).collect(Collectors.toList()); MockMvc mockMvc = standaloneSetup(controller) .setSingleView(new InternalResourceView("WEB-INF/jsp/admin/consul.jsp")).build(); mockMvc.perform(get("/admin/consul")).andExpect(view().name("admin/consul")) .andExpect(model().attributeExists("title", "message", "nodeForm", "services", "nodes", "nodeToDelete", "serviceToDelete", "serviceForm")) .andExpect(model().attribute("nodes", hasItems(nodeNames.toArray()))) .andExpect(model().attribute("services", hasItems(serviceNames.toArray()))); }
From source file:me.bulat.jivr.webmin.web.defended.admin.ConsulControllerTest.java
@Test @WithMockUser(username = "alexb", roles = { "ADMIN" }) public void addNodeSuccess() throws Exception { MockMvc mockMvc = standaloneSetup(controller) .setSingleView(new InternalResourceView("WEB-INF/jsp/admin/consul.jsp")).build(); mockMvc.perform(post("/admin/consul/addhost").param("nodeName", "test1").param("services", "service1")) .andExpect(status().isOk())/*ww w.ja v a 2s . co m*/ .andExpect(model().attribute("result", CoreMatchers.equalTo("Adding success!"))); }
From source file:org.toobsframework.pres.doit.controller.strategy.DefaultForwardStrategy.java
public AbstractUrlBasedView resolveSuccessForward(IRequest componentRequest, DoIt doIt, Map<String, Object> forwardParams) { AbstractUrlBasedView forwardView = null; String forwardName = getForwardName(FORWARD_NAME_PARAM, componentRequest.getParams()); if (forwardName == null) { forwardName = DEFAULT_SUCCESS_FORWARD_NAME; }/* ww w .ja v a 2 s.c o m*/ Forward toobsForwardDef = getForward(doIt, forwardName); if (toobsForwardDef != null) { String forwardTo = ParameterUtil.resoveForwardPath(componentRequest, toobsForwardDef, componentRequest.getHttpRequest().getParameterMap()); forwardView = new RedirectView(forwardTo, true); if (toobsForwardDef != null && toobsForwardDef.getParameters() != null) { // Create a clone of the input params Map<String, Object> allParams = new HashMap<String, Object>(componentRequest.getParams()); // Add the response params to it allParams.putAll(componentRequest.getResponseParams()); try { ParameterUtil.mapParameters(componentRequest, "Forward:" + toobsForwardDef.getUri(), toobsForwardDef.getParameters().getParameter(), allParams, forwardParams, doIt.getName()); } catch (ParameterException e) { log.error("Forward Parameter Mapping error " + e.getMessage(), e); componentRequest.getHttpResponse().setHeader(PresConstants.TOOBS_EXCEPTION_HEADER_NAME, "true"); forwardView = new InternalResourceView(this.getReferer(componentRequest.getHttpRequest())); } } } if (log.isDebugEnabled()) { log.debug("Success forward to: " + (toobsForwardDef != null ? toobsForwardDef.getName() : "null") + " URI: " + (forwardView != null ? forwardView.getUrl() : "null")); Iterator<Map.Entry<String, Object>> iter = forwardParams.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, Object> entry = iter.next(); log.debug("-->Forward Param - name: " + entry.getKey() + " value: " + entry.getValue()); } } return forwardView; }
From source file:me.bulat.jivr.webmin.web.defended.admin.ConsulControllerTest.java
@Test @WithMockUser(username = "alexb", roles = { "ADMIN" }) public void addNodeHasError() throws Exception { MockMvc mockMvc = standaloneSetup(controller) .setSingleView(new InternalResourceView("WEB-INF/jsp/admin/consul.jsp")).build(); mockMvc.perform(post("/admin/consul/addhost").param("services", "service1")).andExpect(status().isOk()) .andExpect(model().attribute("error", CoreMatchers.equalTo("Incorrect data!"))); }
From source file:me.bulat.jivr.webmin.web.defended.admin.ConsulControllerTest.java
@Test @WithMockUser(username = "alexb", roles = { "ADMIN" }) public void addNodeNodeExist() throws Exception { MockMvc mockMvc = standaloneSetup(controller) .setSingleView(new InternalResourceView("WEB-INF/jsp/admin/consul.jsp")).build(); mockMvc.perform(post("/admin/consul/addhost").param("nodeName", "agent1").param("services", "service1")) .andExpect(status().isOk())//from w w w. j a va 2 s . com .andExpect(model().attribute("error", CoreMatchers.equalTo("Node exist!"))); }
From source file:net.testdriven.psiprobe.controllers.deploy.UploadWarController.java
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { if (FileUpload.isMultipartContent(new ServletRequestContext(request))) { File tmpWar = null;// w ww . j a va 2 s . co m String contextName = null; boolean update = false; boolean compile = false; boolean discard = false; // // parse multipart request and extract the file // FileItemFactory factory = new DiskFileItemFactory(1048000, new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(-1); upload.setHeaderEncoding("UTF8"); try { for (Iterator it = upload.parseRequest(request).iterator(); it.hasNext();) { FileItem fi = (FileItem) it.next(); if (!fi.isFormField()) { if (fi.getName() != null && fi.getName().length() > 0) { tmpWar = new File(System.getProperty("java.io.tmpdir"), FilenameUtils.getName(fi.getName())); fi.write(tmpWar); } } else if ("context".equals(fi.getFieldName())) { contextName = fi.getString(); } else if ("update".equals(fi.getFieldName()) && "yes".equals(fi.getString())) { update = true; } else if ("compile".equals(fi.getFieldName()) && "yes".equals(fi.getString())) { compile = true; } else if ("discard".equals(fi.getFieldName()) && "yes".equals(fi.getString())) { discard = true; } } } catch (Exception e) { logger.fatal("Could not process file upload", e); request.setAttribute("errorMessage", getMessageSourceAccessor() .getMessage("probe.src.deploy.war.uploadfailure", new Object[] { e.getMessage() })); if (tmpWar != null && tmpWar.exists()) { tmpWar.delete(); } tmpWar = null; } String errMsg = null; if (tmpWar != null) { try { if (tmpWar.getName().endsWith(".war")) { if (contextName == null || contextName.length() == 0) { String warFileName = tmpWar.getName().replaceAll("\\.war$", ""); contextName = "/" + warFileName; } contextName = getContainerWrapper().getTomcatContainer().formatContextName(contextName); // // pass the name of the newly deployed context to the presentation layer // using this name the presentation layer can render a url to view compilation details // String visibleContextName = "".equals(contextName) ? "/" : contextName; request.setAttribute("contextName", visibleContextName); if (update && getContainerWrapper().getTomcatContainer().findContext(contextName) != null) { logger.debug("updating " + contextName + ": removing the old copy"); getContainerWrapper().getTomcatContainer().remove(contextName); } if (getContainerWrapper().getTomcatContainer().findContext(contextName) == null) { // // move the .war to tomcat application base dir // String destWarFilename = getContainerWrapper().getTomcatContainer() .formatContextFilename(contextName); File destWar = new File(getContainerWrapper().getTomcatContainer().getAppBase(), destWarFilename + ".war"); FileUtils.moveFile(tmpWar, destWar); // // let Tomcat know that the file is there // getContainerWrapper().getTomcatContainer().installWar(contextName, new URL("jar:file:" + destWar.getAbsolutePath() + "!/")); Context ctx = getContainerWrapper().getTomcatContainer().findContext(contextName); if (ctx == null) { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.notinstalled", new Object[] { visibleContextName }); } else { request.setAttribute("success", Boolean.TRUE); if (discard) { getContainerWrapper().getTomcatContainer().discardWorkDir(ctx); } if (compile) { Summary summary = new Summary(); summary.setName(ctx.getName()); getContainerWrapper().getTomcatContainer().listContextJsps(ctx, summary, true); request.getSession(true).setAttribute(DisplayJspController.SUMMARY_ATTRIBUTE, summary); request.setAttribute("compileSuccess", Boolean.TRUE); } } } else { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.alreadyExists", new Object[] { visibleContextName }); } } else { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.notWar.failure"); } } catch (Exception e) { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.failure", new Object[] { e.getMessage() }); logger.error("Tomcat throw an exception when trying to deploy", e); } finally { if (errMsg != null) { request.setAttribute("errorMessage", errMsg); } tmpWar.delete(); } } } return new ModelAndView(new InternalResourceView(getViewName())); }
From source file:com.googlecode.psiprobe.controllers.deploy.UploadWarController.java
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { if (FileUpload.isMultipartContent(new ServletRequestContext(request))) { File tmpWar = null;//from ww w . j a v a2s . c o m String contextName = null; boolean update = false; boolean compile = false; boolean discard = false; // // parse multipart request and extract the file // FileItemFactory factory = new DiskFileItemFactory(1048000, new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(-1); upload.setHeaderEncoding("UTF8"); try { for (Iterator it = upload.parseRequest(request).iterator(); it.hasNext();) { FileItem fi = (FileItem) it.next(); if (!fi.isFormField()) { if (fi.getName() != null && fi.getName().length() > 0) { tmpWar = new File(System.getProperty("java.io.tmpdir"), FilenameUtils.getName(fi.getName())); fi.write(tmpWar); } } else if ("context".equals(fi.getFieldName())) { contextName = fi.getString(); } else if ("update".equals(fi.getFieldName()) && "yes".equals(fi.getString())) { update = true; } else if ("compile".equals(fi.getFieldName()) && "yes".equals(fi.getString())) { compile = true; } else if ("discard".equals(fi.getFieldName()) && "yes".equals(fi.getString())) { discard = true; } } } catch (Exception e) { logger.fatal("Could not process file upload", e); request.setAttribute("errorMessage", getMessageSourceAccessor() .getMessage("probe.src.deploy.war.uploadfailure", new Object[] { e.getMessage() })); if (tmpWar != null && tmpWar.exists()) { tmpWar.delete(); } tmpWar = null; } String errMsg = null; if (tmpWar != null) { try { if (tmpWar.getName().endsWith(".war")) { if (contextName == null || contextName.length() == 0) { String warFileName = tmpWar.getName().replaceAll("\\.war$", ""); contextName = "/" + warFileName; } contextName = getContainerWrapper().getTomcatContainer().formatContextName(contextName); // // pass the name of the newly deployed context to the presentation layer // using this name the presentation layer can render a url to view compilation details // String visibleContextName = "".equals(contextName) ? "/" : contextName; request.setAttribute("contextName", visibleContextName); if (update && getContainerWrapper().getTomcatContainer().findContext(contextName) != null) { logger.debug("updating " + contextName + ": removing the old copy"); getContainerWrapper().getTomcatContainer().remove(contextName); } if (getContainerWrapper().getTomcatContainer().findContext(contextName) == null) { // // move the .war to tomcat application base dir // String destWarFilename = getContainerWrapper().getTomcatContainer() .formatContextFilename(contextName); File destWar = new File(getContainerWrapper().getTomcatContainer().getAppBase(), destWarFilename + ".war"); FileUtils.moveFile(tmpWar, destWar); // // let Tomcat know that the file is there // getContainerWrapper().getTomcatContainer().installWar(contextName, new URL("jar:" + destWar.toURI().toURL().toString() + "!/")); Context ctx = getContainerWrapper().getTomcatContainer().findContext(contextName); if (ctx == null) { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.notinstalled", new Object[] { visibleContextName }); } else { request.setAttribute("success", Boolean.TRUE); if (discard) { getContainerWrapper().getTomcatContainer().discardWorkDir(ctx); } if (compile) { Summary summary = new Summary(); summary.setName(ctx.getName()); getContainerWrapper().getTomcatContainer().listContextJsps(ctx, summary, true); request.getSession(true).setAttribute(DisplayJspController.SUMMARY_ATTRIBUTE, summary); request.setAttribute("compileSuccess", Boolean.TRUE); } } } else { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.alreadyExists", new Object[] { visibleContextName }); } } else { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.notWar.failure"); } } catch (Exception e) { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.failure", new Object[] { e.getMessage() }); logger.error("Tomcat throw an exception when trying to deploy", e); } finally { if (errMsg != null) { request.setAttribute("errorMessage", errMsg); } tmpWar.delete(); } } } return new ModelAndView(new InternalResourceView(getViewName())); }
From source file:me.bulat.jivr.webmin.web.defended.admin.ConsulControllerTest.java
@Test @WithMockUser(username = "alexb", roles = { "ADMIN" }) public void addServiceSuccess() throws Exception { MockMvc mockMvc = standaloneSetup(controller) .setSingleView(new InternalResourceView("WEB-INF/jsp/admin/consul.jsp")).build(); mockMvc.perform(post("/admin/consul/addservice").param("serviceName", "service3") .param("agiScriptClassName", "me.bulat.test.Example").param("active", "true") .param("host", "localhost").param("port", "15000")).andExpect(status().isOk()) .andExpect(model().attribute("result", CoreMatchers.equalTo("Adding success!"))); }
From source file:psiprobe.controllers.deploy.UploadWarController.java
@Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { if (FileUploadBase.isMultipartContent(new ServletRequestContext(request))) { File tmpWar = null;/* w w w . j ava 2 s . co m*/ String contextName = null; boolean update = false; boolean compile = false; boolean discard = false; // parse multipart request and extract the file FileItemFactory factory = new DiskFileItemFactory(1048000, new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(-1); upload.setHeaderEncoding(StandardCharsets.UTF_8.name()); try { List<FileItem> fileItems = upload.parseRequest(request); for (FileItem fi : fileItems) { if (!fi.isFormField()) { if (fi.getName() != null && fi.getName().length() > 0) { tmpWar = new File(System.getProperty("java.io.tmpdir"), FilenameUtils.getName(fi.getName())); fi.write(tmpWar); } } else if ("context".equals(fi.getFieldName())) { contextName = fi.getString(); } else if ("update".equals(fi.getFieldName()) && "yes".equals(fi.getString())) { update = true; } else if ("compile".equals(fi.getFieldName()) && "yes".equals(fi.getString())) { compile = true; } else if ("discard".equals(fi.getFieldName()) && "yes".equals(fi.getString())) { discard = true; } } } catch (Exception e) { logger.error("Could not process file upload", e); request.setAttribute("errorMessage", getMessageSourceAccessor() .getMessage("probe.src.deploy.war.uploadfailure", new Object[] { e.getMessage() })); if (tmpWar != null && tmpWar.exists() && !tmpWar.delete()) { logger.error("Unable to delete temp war file"); } tmpWar = null; } String errMsg = null; if (tmpWar != null) { try { if (tmpWar.getName().endsWith(".war")) { if (contextName == null || contextName.length() == 0) { String warFileName = tmpWar.getName().replaceAll("\\.war$", ""); contextName = "/" + warFileName; } contextName = getContainerWrapper().getTomcatContainer().formatContextName(contextName); /* * pass the name of the newly deployed context to the presentation layer using this name * the presentation layer can render a url to view compilation details */ String visibleContextName = "".equals(contextName) ? "/" : contextName; request.setAttribute("contextName", visibleContextName); if (update && getContainerWrapper().getTomcatContainer().findContext(contextName) != null) { logger.debug("updating {}: removing the old copy", contextName); getContainerWrapper().getTomcatContainer().remove(contextName); } if (getContainerWrapper().getTomcatContainer().findContext(contextName) == null) { // move the .war to tomcat application base dir String destWarFilename = getContainerWrapper().getTomcatContainer() .formatContextFilename(contextName); File destWar = new File(getContainerWrapper().getTomcatContainer().getAppBase(), destWarFilename + ".war"); FileUtils.moveFile(tmpWar, destWar); // let Tomcat know that the file is there getContainerWrapper().getTomcatContainer().installWar(contextName, new URL("jar:" + destWar.toURI().toURL().toString() + "!/")); Context ctx = getContainerWrapper().getTomcatContainer().findContext(contextName); if (ctx == null) { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.notinstalled", new Object[] { visibleContextName }); } else { request.setAttribute("success", Boolean.TRUE); // Logging action Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String name = auth.getName(); // get username logger logger.info(getMessageSourceAccessor().getMessage("probe.src.log.deploywar"), name, contextName); if (discard) { getContainerWrapper().getTomcatContainer().discardWorkDir(ctx); logger.info(getMessageSourceAccessor().getMessage("probe.src.log.discardwork"), name, contextName); } if (compile) { Summary summary = new Summary(); summary.setName(ctx.getName()); getContainerWrapper().getTomcatContainer().listContextJsps(ctx, summary, true); request.getSession(false).setAttribute(DisplayJspController.SUMMARY_ATTRIBUTE, summary); request.setAttribute("compileSuccess", Boolean.TRUE); } } } else { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.alreadyExists", new Object[] { visibleContextName }); } } else { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.notWar.failure"); } } catch (Exception e) { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.failure", new Object[] { e.getMessage() }); logger.error("Tomcat throw an exception when trying to deploy", e); } finally { if (errMsg != null) { request.setAttribute("errorMessage", errMsg); } if (tmpWar.exists() && !tmpWar.delete()) { logger.error("Unable to delete temp war file"); } } } } return new ModelAndView(new InternalResourceView(getViewName())); }