Java Code Examples for javax.servlet.ServletContext#getRequestDispatcher()

The following examples show how to use javax.servlet.ServletContext#getRequestDispatcher() . These examples are extracted from open source projects. 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
public static void forwardRequestRelativeToGivenContext(String fwdPath, ServletContext targetContext,
    HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
  if (fwdPath == null || targetContext == null || request == null || response == null) {
    String msg = "Path, context, request, and response may not be null";
    log.error(
        "forwardRequestRelativeToGivenContext() ERROR: " + msg + (fwdPath == null ? ": " : "[" + fwdPath + "]: "));
    throw new IllegalArgumentException(msg + ".");
  }

  Escaper urlPathEscaper = UrlEscapers.urlPathSegmentEscaper();
  String encodedPath = urlPathEscaper.escape(fwdPath); // LOOK path vs query
  RequestDispatcher dispatcher = targetContext.getRequestDispatcher(encodedPath);

  if (dispatcherWasFound(encodedPath, dispatcher, response))
    dispatcher.forward(request, response);
}
 
Example 2
Source Project: Jinx   File: NettyAsyncContext.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void dispatch(ServletContext context, String path) {
    final HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
    httpRequest.setAttribute(ASYNC_CONTEXT_PATH, httpRequest.getContextPath());
    httpRequest.setAttribute(ASYNC_PATH_INFO, httpRequest.getPathInfo());
    httpRequest.setAttribute(ASYNC_QUERY_STRING, httpRequest.getQueryString());
    httpRequest.setAttribute(ASYNC_REQUEST_URI, httpRequest.getRequestURI());
    httpRequest.setAttribute(ASYNC_SERVLET_PATH, httpRequest.getServletPath());
    final NettyRequestDispatcher dispatcher = (NettyRequestDispatcher) context.getRequestDispatcher(path);
    ctx.executor().submit(() -> {
        try {
            dispatcher.dispatch(httpRequest, servletResponse);
            // TODO is this right?
            for (AsyncListener listener : ImmutableList.copyOf(listeners)) {
                listener.onComplete(new AsyncEvent(NettyAsyncContext.this));
            }
        } catch (ServletException | IOException e) {
            // TODO notify listeners
            e.printStackTrace();
        }
    });
}
 
Example 3
Source Project: joynr   File: TestRequestDispatcher.java    License: Apache License 2.0 6 votes vote down vote up
private void forwardToUrl(final String targetContextPath,
                          Request baseRequest,
                          HttpServletResponse response) throws ServletException, IOException {

    logger.info("Forward request {} to context {}", baseRequest.toString(), targetContextPath);

    synchronized (contextForwardCounts) {
        int currentContextForwardCount = 0;
        if (contextForwardCounts.containsKey(targetContextPath)) {
            currentContextForwardCount = contextForwardCounts.get(targetContextPath);
        }
        contextForwardCounts.put(targetContextPath, currentContextForwardCount + 1);
    }

    ServletContext currentContext = baseRequest.getServletContext();
    String currentContextPath = currentContext.getContextPath();

    String forwardContextPath = currentContextPath.replace(ClusteredBounceProxyWithDispatcher.CONTEXT_DISPATCHER,
                                                           targetContextPath);

    ServletContext forwardContext = currentContext.getContext(forwardContextPath);
    String forwardPath = baseRequest.getPathInfo();
    RequestDispatcher requestDispatcher = forwardContext.getRequestDispatcher(forwardPath);

    requestDispatcher.forward(baseRequest, response);
}
 
Example 4
protected void redirect(HttpServletRequest request, HttpServletResponse response, String pathInfo) throws ServletException {

		String theServletPath = dispatcherServletPath == null ? "/" : dispatcherServletPath;

		ServletContext sc = super.getServletContext();
		RequestDispatcher rd = dispatcherServletName != null ? sc.getNamedDispatcher(dispatcherServletName) : sc.getRequestDispatcher(theServletPath + pathInfo);
		if (rd == null) {
			throw new ServletException("No RequestDispatcher can be created for path " + pathInfo);
		}
		try {
			HttpServletRequestFilter servletRequest = new HttpServletRequestFilter(request, pathInfo, theServletPath);
			rd.forward(servletRequest, response);
		} catch (Throwable ex) {
			throw new ServletException("RequestDispatcher for path " + pathInfo + " has failed");
		}
	}
 
Example 5
Source Project: Tomcat8-Source-Read   File: AsyncContextImpl.java    License: MIT License 5 votes vote down vote up
@Override
public void dispatch(ServletContext servletContext, String path) {
    synchronized (asyncContextLock) {
        if (log.isDebugEnabled()) {
            logDebug("dispatch   ");
        }
        check();
        if (dispatch != null) {
            throw new IllegalStateException(
                    sm.getString("asyncContextImpl.dispatchingStarted"));
        }
        if (request.getAttribute(ASYNC_REQUEST_URI)==null) {
            request.setAttribute(ASYNC_REQUEST_URI, request.getRequestURI());
            request.setAttribute(ASYNC_CONTEXT_PATH, request.getContextPath());
            request.setAttribute(ASYNC_SERVLET_PATH, request.getServletPath());
            request.setAttribute(ASYNC_PATH_INFO, request.getPathInfo());
            request.setAttribute(ASYNC_QUERY_STRING, request.getQueryString());
        }
        final RequestDispatcher requestDispatcher = servletContext.getRequestDispatcher(path);
        if (!(requestDispatcher instanceof AsyncDispatcher)) {
            throw new UnsupportedOperationException(
                    sm.getString("asyncContextImpl.noAsyncDispatcher"));
        }
        final AsyncDispatcher applicationDispatcher =
                (AsyncDispatcher) requestDispatcher;
        final ServletRequest servletRequest = getRequest();
        final ServletResponse servletResponse = getResponse();
        // https://bz.apache.org/bugzilla/show_bug.cgi?id=63246
        // Take a local copy as the dispatch may complete the
        // request/response and that in turn may trigger recycling of this
        // object before the in-progress count can be decremented
        final Context context = this.context;
        this.dispatch = new AsyncRunnable(
                request, applicationDispatcher, servletRequest, servletResponse);
        this.request.getCoyoteRequest().action(ActionCode.ASYNC_DISPATCH, null);
        clearServletRequestResponse();
        context.decrementInProgressAsyncCount();
    }
}
 
Example 6
Source Project: atlas   File: AtlasHttpServlet.java    License: Apache License 2.0 5 votes vote down vote up
protected void includeResponse(HttpServletRequest request, HttpServletResponse response, String template) {
    try {
        response.setContentType(TEXT_HTML);
        response.setHeader(XFRAME_OPTION, DENY);
        ServletContext context = getServletContext();
        RequestDispatcher rd = context.getRequestDispatcher(template);
        rd.include(request, response);
    } catch (Exception e) {
        LOG.error("Error in AtlasHttpServlet", template, e);
    }
}
 
Example 7
@Override
public void handleSubmission(ServletContext context, MCRServletJob job, MCREditorSession session,
    String servletNameOrPath)
    throws Exception {
    session.getSubmission().setSubmittedValues(job.getRequest().getParameterMap());
    Document result = session.getEditedXML();

    if (session.getValidator().isValid()) {
        result = MCRChangeTracker.removeChangeTracking(result);
        result = session.getXMLCleaner().clean(result);
        result = session.getPostProcessor().process(result);

        RequestDispatcher dispatcher = context.getNamedDispatcher(servletNameOrPath);
        if (dispatcher == null) {
            dispatcher = context.getRequestDispatcher(servletNameOrPath);
        }

        job.getRequest().setAttribute("MCRXEditorSubmission", result);

        session.setBreakpoint("After handling target servlet " + servletNameOrPath);

        dispatcher.forward(job.getRequest(), job.getResponse());
    } else {
        session.setBreakpoint("After validation failed, target servlet " + servletNameOrPath);
        job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(session.getRedirectURL(null)));
    }
}
 
Example 8
Source Project: cxf   File: RequestDispatcherProvider.java    License: Apache License 2.0 5 votes vote down vote up
protected RequestDispatcher getRequestDispatcher(ServletContext sc, Class<?> clazz, String path) {

        RequestDispatcher rd = dispatcherName != null ? sc.getNamedDispatcher(dispatcherName)
                                                      : sc.getRequestDispatcher(path);
        if (rd == null) {
            String message =
                new org.apache.cxf.common.i18n.Message("RESOURCE_PATH_NOT_FOUND",
                                                       BUNDLE, path).toString();
            LOG.severe(message);
            throw ExceptionUtils.toInternalServerErrorException(null, null);
        }
        return rd;
    }
 
Example 9
@Override
protected void service(final HttpServletRequest req, final HttpServletResponse resp)
    throws ServletException, IOException
{
  try {
    final String matchingRoute = findMatchingRoute(req);
    ServletContext context = getServletContext();
    RequestDispatcher rd = context.getRequestDispatcher(matchingRoute);
    rd.forward(req, resp);
  }
  catch (Exception e) {
    Throwables.propagateIfPossible(e, ServletException.class, IOException.class);
  }
}
 
Example 10
Source Project: cxf   File: AbstractHTTPServlet.java    License: Apache License 2.0 5 votes vote down vote up
protected void redirect(HttpServletRequest request, HttpServletResponse response, String pathInfo)
    throws ServletException {
    boolean customServletPath = dispatcherServletPath != null;
    String theServletPath = customServletPath ? dispatcherServletPath : "/";

    ServletContext sc = super.getServletContext();
    RequestDispatcher rd = dispatcherServletName != null
        ? sc.getNamedDispatcher(dispatcherServletName)
        : sc.getRequestDispatcher((theServletPath + pathInfo).replace("//", "/"));
    if (rd == null) {
        String errorMessage = "No RequestDispatcher can be created for path " + pathInfo;
        if (dispatcherServletName != null) {
            errorMessage += ", dispatcher name: " + dispatcherServletName;
        }
        throw new ServletException(errorMessage);
    }
    try {
        for (Map.Entry<String, String> entry : redirectAttributes.entrySet()) {
            request.setAttribute(entry.getKey(), entry.getValue());
        }
        HttpServletRequest servletRequest =
            new HttpServletRequestRedirectFilter(request, pathInfo, theServletPath, customServletPath);
        if (PropertyUtils.isTrue(getServletConfig().getInitParameter(REDIRECT_WITH_INCLUDE_PARAMETER))) {
            rd.include(servletRequest, response);
        } else {
            rd.forward(servletRequest, response);
        }
    } catch (Throwable ex) {
        throw new ServletException("RequestDispatcher for path " + pathInfo + " has failed", ex);
    }
}
 
Example 11
@Override
public String getFileText(String originalPath, boolean virtual)
        throws IOException {
    try {
        ServletContextAndPath csAndP = getServletContextAndPath(
                originalPath, virtual);
        ServletContext context = csAndP.getServletContext();
        String path = csAndP.getPath();
        RequestDispatcher rd = context.getRequestDispatcher(path);
        if (rd == null) {
            throw new IOException(
                    "Couldn't get request dispatcher for path: " + path);
        }
        ByteArrayServletOutputStream basos = new ByteArrayServletOutputStream();
        ResponseIncludeWrapper responseIncludeWrapper = new ResponseIncludeWrapper(res, basos);
        rd.include(req, responseIncludeWrapper);
        //We can't assume the included servlet flushed its output
        responseIncludeWrapper.flushOutputStreamOrWriter();
        byte[] bytes = basos.toByteArray();

        //Assume platform default encoding unless otherwise specified
        String retVal;
        if (inputEncoding == null) {
            retVal = new String( bytes );
        } else {
            retVal = new String (bytes,
                    B2CConverter.getCharset(inputEncoding));
        }

        //make an assumption that an empty response is a failure. This is
        // a problem
        // if a truly empty file
        //were included, but not sure how else to tell.
        if (retVal.equals("") && !req.getMethod().equalsIgnoreCase("HEAD")) {
            throw new IOException("Couldn't find file: " + path);
        }
        return retVal;
    } catch (ServletException e) {
        throw new IOException("Couldn't include file: " + originalPath
                + " because of ServletException: " + e.getMessage());
    }
}
 
Example 12
Source Project: Tomcat8-Source-Read   File: StandardHostValve.java    License: MIT License 4 votes vote down vote up
/**
 * Handle an HTTP status code or Java exception by forwarding control
 * to the location included in the specified errorPage object.  It is
 * assumed that the caller has already recorded any request attributes
 * that are to be forwarded to this page.  Return <code>true</code> if
 * we successfully utilized the specified error page location, or
 * <code>false</code> if the default error report should be rendered.
 *
 * @param request The request being processed
 * @param response The response being generated
 * @param errorPage The errorPage directive we are obeying
 */
private boolean custom(Request request, Response response,
                         ErrorPage errorPage) {

    if (container.getLogger().isDebugEnabled()) {
        container.getLogger().debug("Processing " + errorPage);
    }

    try {
        // Forward control to the specified location
        ServletContext servletContext =
            request.getContext().getServletContext();
        RequestDispatcher rd =
            servletContext.getRequestDispatcher(errorPage.getLocation());

        if (rd == null) {
            container.getLogger().error(
                sm.getString("standardHostValue.customStatusFailed", errorPage.getLocation()));
            return false;
        }

        if (response.isCommitted()) {
            // Response is committed - including the error page is the
            // best we can do
            rd.include(request.getRequest(), response.getResponse());
        } else {
            // Reset the response (keeping the real error code and message)
            response.resetBuffer(true);
            response.setContentLength(-1);

            rd.forward(request.getRequest(), response.getResponse());

            // If we forward, the response is suspended again
            response.setSuspended(false);
        }

        // Indicate that we have successfully processed this custom page
        return true;

    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
        // Report our failure to process this custom page
        container.getLogger().error("Exception Processing " + errorPage, t);
        return false;
    }
}
 
Example 13
Source Project: Tomcat7.0.67   File: StandardHostValve.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Handle an HTTP status code or Java exception by forwarding control
 * to the location included in the specified errorPage object.  It is
 * assumed that the caller has already recorded any request attributes
 * that are to be forwarded to this page.  Return <code>true</code> if
 * we successfully utilized the specified error page location, or
 * <code>false</code> if the default error report should be rendered.
 *
 * @param request The request being processed
 * @param response The response being generated
 * @param errorPage The errorPage directive we are obeying
 */
private boolean custom(Request request, Response response,
                         ErrorPage errorPage) {

    if (container.getLogger().isDebugEnabled())
        container.getLogger().debug("Processing " + errorPage);

    try {
        // Forward control to the specified location
        ServletContext servletContext =
            request.getContext().getServletContext();
        RequestDispatcher rd =
            servletContext.getRequestDispatcher(errorPage.getLocation());

        if (rd == null) {
            container.getLogger().error(
                sm.getString("standardHostValue.customStatusFailed", errorPage.getLocation()));
            return false;
        }

        if (response.isCommitted()) {
            // Response is committed - including the error page is the
            // best we can do 
            rd.include(request.getRequest(), response.getResponse());
        } else {
            // Reset the response (keeping the real error code and message)
            response.resetBuffer(true);
            response.setContentLength(-1);

            rd.forward(request.getRequest(), response.getResponse());

            // If we forward, the response is suspended again
            response.setSuspended(false);
        }

        // Indicate that we have successfully processed this custom page
        return (true);

    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
        // Report our failure to process this custom page
        container.getLogger().error("Exception Processing " + errorPage, t);
        return (false);

    }
}
 
Example 14
Source Project: Tomcat7.0.67   File: AsyncContextImpl.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void dispatch(ServletContext context, String path) {
    synchronized (asyncContextLock) {
        if (log.isDebugEnabled()) {
            logDebug("dispatch   ");
        }
        check();
        if (dispatch != null) {
            throw new IllegalStateException(
                    sm.getString("asyncContextImpl.dispatchingStarted"));
        }
        if (request.getAttribute(ASYNC_REQUEST_URI)==null) {
            request.setAttribute(ASYNC_REQUEST_URI, request.getRequestURI());
            request.setAttribute(ASYNC_CONTEXT_PATH, request.getContextPath());
            request.setAttribute(ASYNC_SERVLET_PATH, request.getServletPath());
            request.setAttribute(ASYNC_PATH_INFO, request.getPathInfo());
            request.setAttribute(ASYNC_QUERY_STRING, request.getQueryString());
        }
        final RequestDispatcher requestDispatcher = context.getRequestDispatcher(path);
        if (!(requestDispatcher instanceof AsyncDispatcher)) {
            throw new UnsupportedOperationException(
                    sm.getString("asyncContextImpl.noAsyncDispatcher"));
        }
        final AsyncDispatcher applicationDispatcher =
                (AsyncDispatcher) requestDispatcher;
        final ServletRequest servletRequest = getRequest();
        final ServletResponse servletResponse = getResponse();
        Runnable run = new Runnable() {
            @Override
            public void run() {
                request.getCoyoteRequest().action(ActionCode.ASYNC_DISPATCHED, null);
                try {
                    applicationDispatcher.dispatch(servletRequest, servletResponse);
                }catch (Exception x) {
                    //log.error("Async.dispatch",x);
                    throw new RuntimeException(x);
                }
            }
        };

        this.dispatch = run;
        this.request.getCoyoteRequest().action(ActionCode.ASYNC_DISPATCH, null);
        clearServletRequestResponse();
    }
}
 
Example 15
Source Project: docx4j-template   File: JspTemplateImpl.java    License: Apache License 2.0 4 votes vote down vote up
private void doInterpret(String requestURL,Map<String, Object> variables, OutputStream output) throws IOException, ServletException {
 	/**
      * 创建ServletContext对象,用于获取RequestDispatcher对象
      */
     ServletContext sc = request.getSession().getServletContext();
     /**
      * 根据传过来的相对文件路径,生成一个reqeustDispatcher的包装类
      */
     RequestDispatcher rd = sc.getRequestDispatcher(requestURL);
     /**
      * 创建一个ByteArrayOutputStream的字节数组输出流,用来存放输出的信息
      */
     final ByteArrayOutputStream baos = new ByteArrayOutputStream();
      
     /**
      * ServletOutputStream是抽象类,必须实现write的方法
      */
     final ServletOutputStream outputStream = new ServletOutputStream(){
         
         public void write(int b) throws IOException {
             /**
              * 将指定的字节写入此字节输出流
              */
             baos.write(b);
         }

	@SuppressWarnings("unused")
public boolean isReady() {
		return false;
	}

     }; 
     /**
      * 通过现有的 OutputStream 创建新的 PrintWriter
      * OutputStreamWriter 是字符流通向字节流的桥梁:可使用指定的 charset 将要写入流中的字符编码成字节
      */
     final PrintWriter pw = new PrintWriter(new OutputStreamWriter(baos, config.getOutputEncoding() ),true);
     /**
      * 生成HttpServletResponse的适配器,用来包装response
      */
     HttpServletResponse resp = new HttpServletResponseWrapper(response){
         /**
          * 调用getOutputStream的方法(此方法是ServletResponse中已有的)返回ServletOutputStream的对象
          * 用来在response中返回一个二进制输出对象
          * 此方法目的是把源文件写入byteArrayOutputStream
          */
         public ServletOutputStream getOutputStream(){
             return outputStream;
         }
          
         /**
          * 再调用getWriter的方法(此方法是ServletResponse中已有)返回PrintWriter的对象
          * 此方法用来发送字符文本到客户端
          */
         public PrintWriter getWriter(){
             return pw;
         }
     }; 
     /**
      * 在不跳转下访问目标jsp。 就是利用RequestDispatcher.include(ServletRequest request,
      * ServletResponse response)。 该方法把RequestDispatcher指向的目标页面写到response中。
      */
     rd.include(request, resp);
     pw.flush();
     /**
      * 使用ByteArrayOutputStream的writeTo方法来向文本输出流写入数据,这也是为什么要使用ByteArray的一个原因
      */
     baos.writeTo(output);
 }
 
Example 16
public void route(
    ServletContext servletContext,
    HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException {
    TracerSingleton.log(
        Constants.NOME_MODULO,
        TracerSingleton.DEBUG,
        "Router::route: request.getContextPath() ["
            + request.getContextPath()
            + "]");
    TracerSingleton.log(
        Constants.NOME_MODULO,
        TracerSingleton.DEBUG,
        "Router::Router: _publisher [" + _publisher + "]");
    TracerSingleton.log(
        Constants.NOME_MODULO,
        TracerSingleton.DEBUG,
        "Router::Router: _isForward [" + _isForward + "]");
    String publishingParameters = "";
    Enumeration parameterNames = _parameters.keys();
    while (parameterNames.hasMoreElements()) {
        String parameterName = (String) parameterNames.nextElement();
        String parameterValue =
            String.valueOf(_parameters.get(parameterName));
        if (_publisher.indexOf(parameterName) == -1)
            publishingParameters += JavaScript.escape(parameterName)
                + "="
                + JavaScript.escape(parameterValue)
                + "&";
    } // while (parameterNames.hasMoreElements())
    TracerSingleton.log(
        Constants.NOME_MODULO,
        TracerSingleton.DEBUG,
        "Router::route: publishingParameters ["
            + publishingParameters
            + "]");
    String publishingURL = _publisher;
    ConfigSingleton configure = ConfigSingleton.getInstance();
    String appendContextRoot =
        (String) configure.getAttribute("PUBLISHING.APPEND_CONTEXT_ROOT");
    if ((appendContextRoot == null)
        || (appendContextRoot.equalsIgnoreCase("TRUE")))
        if (_publisher.startsWith("/")) {
            TracerSingleton.log(
                Constants.NOME_MODULO,
                TracerSingleton.DEBUG,
                "Router::route: publisher assoluto");
            if (_isForward)
                publishingURL = _publisher;
            else
                publishingURL = request.getContextPath() + _publisher;
        } // if (_publisher.startsWith("/"))
    else {
        TracerSingleton.log(
            Constants.NOME_MODULO,
            TracerSingleton.DEBUG,
            "Router::route: publisher relativo");
        publishingURL = _publisher;
    } // if (_publisher.startsWith("/")) else
    if (publishingParameters!=null && publishingParameters.length()>0) {
        if (_publisher.indexOf('?') == -1)
            publishingURL += "?" + publishingParameters;
        else
            publishingURL += "&" + publishingParameters;
    }
    TracerSingleton.log(
        Constants.NOME_MODULO,
        TracerSingleton.DEBUG,
        "Router::route: publishingURL [" + publishingURL + "]");
    if (_isForward) {
        RequestDispatcher requestDispatcher =
            servletContext.getRequestDispatcher(publishingURL);
        requestDispatcher.forward(request, response);
    } // if (_isForward)
    else {
        response.sendRedirect(response.encodeRedirectURL(publishingURL));
    } // if (_isForward) else
}
 
Example 17
private void handleContentItem(HttpServletRequest request, HttpServletResponse response, Map payload)
	throws ServletException, IOException
{

	String allowedToolsConfig = ServerConfigurationService.getString("basiclti.provider.allowedtools", "");
	String[] allowedTools = allowedToolsConfig.split(":");
	List<String> allowedToolsList = Arrays.asList(allowedTools);

	String tool_id = (String) request.getParameter("install");
	if ( tool_id == null ) {
		ArrayList<Tool> tools = new ArrayList<Tool>();
		for (String toolId : allowedToolsList) {
			Tool theTool = ToolManager.getTool(toolId);
			if ( theTool == null ) continue;
			tools.add(theTool);
		}
		request.setAttribute("tools",tools);
	} else {
		if ( !allowedToolsList.contains(tool_id)) {
			doError(request, response, "launch.tool.notallowed", tool_id, null);
			return;
		}
		final Tool toolCheck = ToolManager.getTool(tool_id);
		if ( toolCheck == null) {
			doError(request, response, "launch.tool.notfound", tool_id, null);
			return;
		}

		String content_item_return_url = (String) payload.get("content_item_return_url");
		if ( content_item_return_url == null) {
			doError(request, response, "content_item.return_url.notfound", tool_id, null);
			return;
		}

		ContentItemResponse resp = SakaiContentItemUtil.getContentItemResponse(tool_id);
		if ( resp == null) {
			doError(request, response, "launch.tool.notfound", tool_id, null);
			return;
		}
		String content_items = resp.prettyPrintLog();

		// Set up the return
		Map<String, String> ltiMap = new HashMap<String, String> ();
		Map<String, String> extra = new HashMap<String, String> ();
		ltiMap.put(BasicLTIConstants.LTI_MESSAGE_TYPE, BasicLTIConstants.LTI_MESSAGE_TYPE_CONTENTITEMSELECTION);
		ltiMap.put(BasicLTIConstants.LTI_VERSION, BasicLTIConstants.LTI_VERSION_1);
		ltiMap.put("content_items", content_items);
		String data = (String) payload.get("data");
		if ( data != null ) ltiMap.put("data", data);
		log.debug("ltiMap={}", ltiMap);

		boolean dodebug = log.isDebugEnabled();
		boolean autosubmit = false;
		String launchtext = rb.getString("content_item.install.button");
		String back_to_store = rb.getString("content_item.back.to.store");
		extra.put("button_html","<input type=\"submit\" value=\""+back_to_store+"\"onclick=\"location.href='content.item'; return false;\">");
		String launch_html = BasicLTIUtil.postLaunchHTML(ltiMap, content_item_return_url, launchtext, autosubmit, dodebug, extra);

		request.setAttribute("back_to_store", rb.getString("content_item.back.to.store"));
		request.setAttribute("install",tool_id);
		request.setAttribute("launch_html",launch_html);
		request.setAttribute("tool",toolCheck);
	}

	// Forward to the JSP
	ServletContext sc = this.getServletContext();
	RequestDispatcher rd = sc.getRequestDispatcher("/contentitem.jsp");
	try {
		rd.forward(request, response);
	}
	catch (Exception e) {
		log.error(e.getMessage(), e);
	}
}
 
Example 18
private void buildSurveyHtml() throws Exception{
		HttpServletRequest request=Struts2Utils.getRequest();
		HttpServletResponse response=Struts2Utils.getResponse();
		String url = "";
		String name = "";
		ServletContext sc = ServletActionContext.getServletContext();

		String file_name = request.getParameter("file_name");
		url = "/design/my-collect.action?surveyId=402880ea4675ac62014675ac7b3a0000";
		// 这是生成的html文件名,如index.htm.
		name = "/survey.htm";
		name = sc.getRealPath(name);
		
		RequestDispatcher rd = sc.getRequestDispatcher(url);
		final ByteArrayOutputStream os = new ByteArrayOutputStream();

		final ServletOutputStream stream = new ServletOutputStream() {
			public void write(byte[] data, int offset, int length) {
				os.write(data, offset, length);
			}

			public void write(int b) throws IOException {
				os.write(b);
			}
		};
		
		final PrintWriter pw = new PrintWriter(new OutputStreamWriter(os,"utf-8"));

		HttpServletResponse rep = new HttpServletResponseWrapper(response) {
			public ServletOutputStream getOutputStream() {
				return stream;
			}

			public PrintWriter getWriter() {
				return pw;
			}
		};

//		rd.include(request, rep);
		rd.forward(request,rep);
		pw.flush();
		
		// 把jsp输出的内容写到xxx.htm
		File file = new File(name);
		if (!file.exists()) {
			file.createNewFile();
		}
		FileOutputStream fos = new FileOutputStream(file);
		
		os.writeTo(fos);
		fos.close();
	}
 
Example 19
public void jspWriteToHtml(String url, String filePath,String fileName) throws Exception {
	HttpServletRequest request = Struts2Utils.getRequest();
	HttpServletResponse response = Struts2Utils.getResponse();
	ServletContext sc = ServletActionContext.getServletContext();
	url = "/my-survey-design!previewDev.action?surveyId=402880ea4675ac62014675ac7b3a0000";
	// 这是生成的html文件名,如index.htm
	filePath = filePath.replace("/", File.separator);
	filePath = filePath.replace("\\", File.separator);
	String fileRealPath = sc.getRealPath("/") + filePath;
	RequestDispatcher rd = sc.getRequestDispatcher(url);
	final ByteArrayOutputStream os = new ByteArrayOutputStream();

	final ServletOutputStream stream = new ServletOutputStream() {
		public void write(byte[] data, int offset, int length) {
			os.write(data, offset, length);
		}

		public void write(int b) throws IOException {
			os.write(b);
		}
	};

	final PrintWriter pw = new PrintWriter(new OutputStreamWriter(os,
			"UTF-8"));

	HttpServletResponse rep = new HttpServletResponseWrapper(response) {
		public ServletOutputStream getOutputStream() {
			return stream;
		}

		public PrintWriter getWriter() {
			return pw;
		}
	};

	rd.forward(request, response);
	pw.flush();

	File file2 = new File(fileRealPath);
	if (!file2.exists() || !file2.isDirectory()) {
		file2.mkdirs();
	}
	File file = new File(fileRealPath + fileName);
	if (!file.exists()) {
		file.createNewFile();
	}
	FileOutputStream fos = new FileOutputStream(file);
	os.writeTo(fos);
	fos.close();
}
 
Example 20
Source Project: tomcatsrc   File: AsyncContextImpl.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void dispatch(ServletContext context, String path) {
    synchronized (asyncContextLock) {
        if (log.isDebugEnabled()) {
            logDebug("dispatch   ");
        }
        check();
        if (dispatch != null) {
            throw new IllegalStateException(
                    sm.getString("asyncContextImpl.dispatchingStarted"));
        }
        if (request.getAttribute(ASYNC_REQUEST_URI)==null) {
            request.setAttribute(ASYNC_REQUEST_URI, request.getRequestURI());
            request.setAttribute(ASYNC_CONTEXT_PATH, request.getContextPath());
            request.setAttribute(ASYNC_SERVLET_PATH, request.getServletPath());
            request.setAttribute(ASYNC_PATH_INFO, request.getPathInfo());
            request.setAttribute(ASYNC_QUERY_STRING, request.getQueryString());
        }
        final RequestDispatcher requestDispatcher = context.getRequestDispatcher(path);
        if (!(requestDispatcher instanceof AsyncDispatcher)) {
            throw new UnsupportedOperationException(
                    sm.getString("asyncContextImpl.noAsyncDispatcher"));
        }
        final AsyncDispatcher applicationDispatcher =
                (AsyncDispatcher) requestDispatcher;
        final ServletRequest servletRequest = getRequest();
        final ServletResponse servletResponse = getResponse();
        Runnable run = new Runnable() {
            @Override
            public void run() {
                request.getCoyoteRequest().action(ActionCode.ASYNC_DISPATCHED, null);
                try {
                    applicationDispatcher.dispatch(servletRequest, servletResponse);
                }catch (Exception x) {
                    //log.error("Async.dispatch",x);
                    throw new RuntimeException(x);
                }
            }
        };

        this.dispatch = run;
        this.request.getCoyoteRequest().action(ActionCode.ASYNC_DISPATCH, null);
        clearServletRequestResponse();
    }
}