Example usage for javax.servlet.http HttpServletRequest getServletContext

List of usage examples for javax.servlet.http HttpServletRequest getServletContext

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getServletContext.

Prototype

public ServletContext getServletContext();

Source Link

Document

Gets the servlet context to which this ServletRequest was last dispatched.

Usage

From source file:org.b3log.solo.processor.ArticleProcessorTestCase.java

/**
 * getAuthorsArticlesByPage.//from  w  w  w  . ja v  a2 s .  co  m
 *
 * @throws Exception exception
 */
@Test(dependsOnMethods = "init")
public void getAuthorsArticlesByPage() throws Exception {
    final JSONObject admin = getUserRepository().getAdmin();
    final String userId = admin.optString(Keys.OBJECT_ID);

    final HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getServletContext()).thenReturn(mock(ServletContext.class));
    when(request.getRequestURI()).thenReturn("/articles/authors/" + userId + "/1");
    when(request.getMethod()).thenReturn("GET");
    when(request.getAttribute(Keys.TEMAPLTE_DIR_NAME)).thenReturn("next");
    when(request.getAttribute(Keys.HttpRequest.START_TIME_MILLIS)).thenReturn(System.currentTimeMillis());

    final MockDispatcherServlet dispatcherServlet = new MockDispatcherServlet();
    dispatcherServlet.init();

    final StringWriter stringWriter = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(stringWriter);

    final HttpServletResponse response = mock(HttpServletResponse.class);
    when(response.getWriter()).thenReturn(printWriter);

    dispatcherServlet.service(request, response);

    final String content = stringWriter.toString();
    Assert.assertTrue(StringUtils.contains(content, "{\"sc\":true"));
}

From source file:org.b3log.solo.processor.ArticleProcessorTestCase.java

/**
 * showAuthorArticles./*  w  w w. j ava 2  s .co m*/
 *
 * @throws Exception exception
 */
@Test(dependsOnMethods = "init")
public void showAuthorArticles() throws Exception {
    final JSONObject admin = getUserRepository().getAdmin();
    final String userId = admin.optString(Keys.OBJECT_ID);

    final HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getServletContext()).thenReturn(mock(ServletContext.class));
    when(request.getRequestURI()).thenReturn("/authors/" + userId + "/1");
    when(request.getMethod()).thenReturn("GET");
    when(request.getAttribute(Keys.TEMAPLTE_DIR_NAME)).thenReturn("next");
    when(request.getAttribute(Keys.HttpRequest.START_TIME_MILLIS)).thenReturn(System.currentTimeMillis());

    final MockDispatcherServlet dispatcherServlet = new MockDispatcherServlet();
    dispatcherServlet.init();

    final StringWriter stringWriter = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(stringWriter);

    final HttpServletResponse response = mock(HttpServletResponse.class);
    when(response.getWriter()).thenReturn(printWriter);

    dispatcherServlet.service(request, response);

    final String content = stringWriter.toString();
    // Assert.assertTrue(StringUtils.contains(content, "Solo "));
}

From source file:org.egov.egf.web.controller.expensebill.CreateExpenseBillController.java

@RequestMapping(value = "/downloadBillDoc", method = RequestMethod.GET)
public void getBillDoc(final HttpServletRequest request, final HttpServletResponse response)
        throws IOException {
    final ServletContext context = request.getServletContext();
    final String fileStoreId = request.getParameter("fileStoreId");
    String fileName = "";
    final File downloadFile = fileStoreService.fetch(fileStoreId, FinancialConstants.FILESTORE_MODULECODE);
    final FileInputStream inputStream = new FileInputStream(downloadFile);
    EgBillregister egBillregister = expenseBillService
            .getById(Long.parseLong(request.getParameter("egBillRegisterId")));
    egBillregister = getBillDocuments(egBillregister);

    for (final DocumentUpload doc : egBillregister.getDocumentDetail())
        if (doc.getFileStore().getFileStoreId().equalsIgnoreCase(fileStoreId))
            fileName = doc.getFileStore().getFileName();

    // get MIME type of the file
    String mimeType = context.getMimeType(downloadFile.getAbsolutePath());
    if (mimeType == null)
        // set to binary type if MIME mapping not found
        mimeType = "application/octet-stream";

    // set content attributes for the response
    response.setContentType(mimeType);//from www. ja  v a 2s .co  m
    response.setContentLength((int) downloadFile.length());

    // set headers for the response
    final String headerKey = "Content-Disposition";
    final String headerValue = String.format("attachment; filename=\"%s\"", fileName);
    response.setHeader(headerKey, headerValue);

    // get output stream of the response
    final OutputStream outStream = response.getOutputStream();

    final byte[] buffer = new byte[BUFFER_SIZE];
    int bytesRead = -1;

    // write bytes read from the input stream into the output stream
    while ((bytesRead = inputStream.read(buffer)) != -1)
        outStream.write(buffer, 0, bytesRead);

    inputStream.close();
    outStream.close();
}

From source file:org.b3log.solo.processor.ArticleProcessorTestCase.java

/**
 * getRelevantArticles.//from   ww  w.  ja  v a  2  s  .c  o m
 *
 * @throws Exception exception
 */
@Test(dependsOnMethods = "init")
public void getRelevantArticles() throws Exception {
    final JSONObject article = getArticleRepository().get(new Query()).optJSONArray(Keys.RESULTS)
            .optJSONObject(0);
    final String articleId = article.optString(Keys.OBJECT_ID);

    final HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getServletContext()).thenReturn(mock(ServletContext.class));
    when(request.getRequestURI()).thenReturn("/article/id/" + articleId + "/relevant/articles");
    when(request.getMethod()).thenReturn("GET");
    when(request.getAttribute(Keys.TEMAPLTE_DIR_NAME)).thenReturn("next");
    when(request.getAttribute(Keys.HttpRequest.START_TIME_MILLIS)).thenReturn(System.currentTimeMillis());

    final MockDispatcherServlet dispatcherServlet = new MockDispatcherServlet();
    dispatcherServlet.init();

    final StringWriter stringWriter = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(stringWriter);

    final HttpServletResponse response = mock(HttpServletResponse.class);
    when(response.getWriter()).thenReturn(printWriter);

    dispatcherServlet.service(request, response);

    final String content = stringWriter.toString();
    Assert.assertTrue(StringUtils.contains(content, "{\"relevantArticles\""));
}

From source file:org.b3log.solo.processor.ArticleProcessorTestCase.java

/**
 * getArticleContent./*from  w  w  w.  ja va  2s . c o  m*/
 *
 * @throws Exception exception
 */
@Test(dependsOnMethods = "init")
public void getArticleContent() throws Exception {
    final JSONObject article = getArticleRepository().get(new Query()).optJSONArray(Keys.RESULTS)
            .optJSONObject(0);
    final String articleId = article.optString(Keys.OBJECT_ID);

    final HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getServletContext()).thenReturn(mock(ServletContext.class));
    when(request.getRequestURI()).thenReturn("/get-article-content");
    when(request.getParameter("id")).thenReturn(articleId);
    when(request.getMethod()).thenReturn("GET");
    when(request.getAttribute(Keys.TEMAPLTE_DIR_NAME)).thenReturn("next");
    when(request.getAttribute(Keys.HttpRequest.START_TIME_MILLIS)).thenReturn(System.currentTimeMillis());

    final MockDispatcherServlet dispatcherServlet = new MockDispatcherServlet();
    dispatcherServlet.init();

    final StringWriter stringWriter = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(stringWriter);

    final HttpServletResponse response = mock(HttpServletResponse.class);
    when(response.getWriter()).thenReturn(printWriter);

    dispatcherServlet.service(request, response);

    final String content = stringWriter.toString();
    Assert.assertTrue(StringUtils.contains(content, "<p>"));
}

From source file:org.b3log.solo.processor.ArticleProcessorTestCase.java

/**
 * showArticlePwdForm.//  www .jav a2 s  .co  m
 *
 * @throws Exception exception
 */
@Test(dependsOnMethods = "init")
public void showArticlePwdForm() throws Exception {
    final JSONObject article = getArticleRepository().get(new Query()).optJSONArray(Keys.RESULTS)
            .optJSONObject(0);
    final String articleId = article.optString(Keys.OBJECT_ID);

    final HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getServletContext()).thenReturn(mock(ServletContext.class));
    when(request.getRequestURI()).thenReturn("/console/article-pwd");
    when(request.getMethod()).thenReturn("GET");
    when(request.getParameter("articleId")).thenReturn(articleId);
    when(request.getAttribute(Keys.TEMAPLTE_DIR_NAME)).thenReturn("next");
    when(request.getAttribute(Keys.HttpRequest.START_TIME_MILLIS)).thenReturn(System.currentTimeMillis());

    final MockDispatcherServlet dispatcherServlet = new MockDispatcherServlet();
    dispatcherServlet.init();

    final StringWriter stringWriter = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(stringWriter);

    final HttpServletResponse response = mock(HttpServletResponse.class);
    when(response.getWriter()).thenReturn(printWriter);

    dispatcherServlet.service(request, response);

    final String content = stringWriter.toString();
    Assert.assertTrue(StringUtils.contains(content, "<title>?</title>"));
}

From source file:org.b3log.solo.processor.ArticleProcessorTestCase.java

/**
 * showArticle.// w  w w .  ja  v  a2 s .  co  m
 *
 * @throws Exception exception
 */
@Test(dependsOnMethods = "init")
public void showArticle() throws Exception {
    final JSONObject article = getArticleRepository().get(new Query()).optJSONArray(Keys.RESULTS)
            .optJSONObject(0);

    final HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getServletContext()).thenReturn(mock(ServletContext.class));
    when(request.getRequestURI()).thenReturn("/pagepermalink");
    when(request.getMethod()).thenReturn("GET");
    when(request.getAttribute(Keys.TEMAPLTE_DIR_NAME)).thenReturn("next");
    when(request.getAttribute(Keys.HttpRequest.START_TIME_MILLIS)).thenReturn(System.currentTimeMillis());
    when(request.getAttribute(Article.ARTICLE)).thenReturn(article);

    final StringWriter stringWriter = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(stringWriter);

    final HttpServletResponse response = mock(HttpServletResponse.class);
    when(response.getWriter()).thenReturn(printWriter);

    final HTTPRequestContext httpRequestContext = new HTTPRequestContext();
    httpRequestContext.setRequest(request);
    httpRequestContext.setResponse(response);

    final ArticleProcessor articleProcessor = Lifecycle.getBeanManager().getReference(ArticleProcessor.class);
    articleProcessor.showArticle(httpRequestContext, request, response);

    final Map<String, Object> dataModel = httpRequestContext.getRenderer().getRenderDataModel();
    final JSONObject handledArticle = (JSONObject) dataModel.get(Article.ARTICLE);
    Assert.assertTrue(
            StringUtils.contains(handledArticle.optString(Keys.OBJECT_ID), article.optString(Keys.OBJECT_ID)));
}

From source file:com.sonicle.webtop.core.app.WebTopApp.java

/**
 * Gets WebTopApp object stored as context's attribute.
 * @param request The http request/*from www.  j ava  2 s . c o m*/
 * @return WebTopApp object
 * @throws javax.servlet.ServletException
 */
public static WebTopApp get(HttpServletRequest request) throws ServletException {
    try {
        return get(request.getServletContext());
    } catch (IllegalStateException ex) {
        throw new ServletException(ex.getMessage());
    }
}

From source file:cpabe.controladores.UploadDecriptacaoServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String fileName = request.getParameter("fileName");
    if (fileName == null || fileName.equals("")) {
        throw new ServletException("O nome do arquivo no pode ser null ou vazio.");
    }/*from   ww  w .  ja va  2s .  c o  m*/
    File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator + fileName);
    if (!file.exists()) {
        throw new ServletException("O arquivo desejado no existe no Servidor.");
    }
    System.out.println("File location on server::" + file.getAbsolutePath());
    ServletContext ctx = getServletContext();
    InputStream fis = new FileInputStream(file);
    String mimeType = ctx.getMimeType(file.getAbsolutePath());
    response.setContentType(mimeType != null ? mimeType : "application/octet-stream");
    response.setContentLength((int) file.length());
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

    ServletOutputStream os = response.getOutputStream();
    byte[] bufferData = new byte[1024];
    int read = 0;
    while ((read = fis.read(bufferData)) != -1) {
        os.write(bufferData, 0, read);
    }
    os.flush();
    os.close();
    fis.close();
    System.out.println("File downloaded at client successfully");
}

From source file:ro.fils.angularspring.controller.ProjectsController.java

@RequestMapping(method = RequestMethod.GET, value = "/downloadXSLT")
public void downloadXSLT(HttpServletRequest request, HttpServletResponse response)
        throws FileNotFoundException, IOException, BadElementException {
    ServletContext context = request.getServletContext();
    String appPath = context.getRealPath("");
    String fullPath = appPath + "Projects.xsl";
    PDFCreator creator = new PDFCreator();
    creator.saveAsXSLT(XSLTFile.xsltString, fullPath);
    System.out.println("appPath = " + appPath);

    File downloadFile = new File(fullPath);
    FileInputStream inputStream = new FileInputStream(downloadFile);

    // get MIME type of the file
    String mimeType = context.getMimeType(fullPath);
    if (mimeType == null) {
        // set to binary type if MIME mapping not found
        mimeType = "application/octet-stream";
    }//from  ww w.  j  a  v a 2  s .c  o m
    System.out.println("MIME type: " + mimeType);

    // set content attributes for the response
    response.setContentType(mimeType);
    response.setContentLength((int) downloadFile.length());

    // set headers for the response
    String headerKey = "Content-Disposition";
    String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
    response.setHeader(headerKey, headerValue);

    // get output stream of the response
    OutputStream outStream = response.getOutputStream();

    byte[] buffer = new byte[BUFFER_SIZE];
    int bytesRead = -1;

    // write bytes read from the input stream into the output stream
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outStream.write(buffer, 0, bytesRead);
    }

    inputStream.close();
    outStream.close();

}