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:ro.fils.angularspring.controller.ProjectsController.java

@RequestMapping(method = RequestMethod.GET, value = "/downloadXML")
public void downloadXML(HttpServletRequest request, HttpServletResponse response)
        throws FileNotFoundException, IOException, BadElementException {
    ServletContext context = request.getServletContext();
    String appPath = context.getRealPath("");
    String fullPath = appPath + "Projects.xml";
    PDFCreator creator = new PDFCreator();
    creator.saveAsXML(projectsDocumentRepository.findOne(ConnectionUtils.PROJECTS_COLLECTION).getContent(),
            fullPath);// w ww.  java 2s. c  o  m
    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";
    }
    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();

}

From source file:io.lavagna.web.support.ResourceController.java

@RequestMapping(value = { "/", //
        "user/{provider}/{username}", "user/{provider}/{username}/projects/",
        "user/{provider}/{username}/activity/", //
        "about", "about/third-party", //
        "search", //
        "search/" + PROJ_SHORT_NAME + "/" + BOARD_SHORT_NAME + "-" + CARD_SEQ, //
        PROJ_SHORT_NAME + "", //
        PROJ_SHORT_NAME + "/search", //
        PROJ_SHORT_NAME + "/search/" + BOARD_SHORT_NAME + "-" + CARD_SEQ, // /
        PROJ_SHORT_NAME + "/" + BOARD_SHORT_NAME, //
        PROJ_SHORT_NAME + "/statistics", //
        PROJ_SHORT_NAME + "/milestones", //
        PROJ_SHORT_NAME + "/milestones/" + BOARD_SHORT_NAME + "-" + CARD_SEQ, //
        PROJ_SHORT_NAME + "/" + BOARD_SHORT_NAME + "-" + CARD_SEQ }, method = RequestMethod.GET)
public void handleIndex(HttpServletRequest request, HttpServletResponse response) throws IOException {

    ServletContext context = request.getServletContext();

    if (contains(env.getActiveProfiles(), "dev") || indexTopTemplate.get() == null) {
        ByteArrayOutputStream indexTop = new ByteArrayOutputStream();
        try (InputStream is = context.getResourceAsStream("/WEB-INF/views/index-top.html")) {
            StreamUtils.copy(is, indexTop);
        }//from   w  w  w .j  av a2s. com
        indexTopTemplate.set(Mustache.compiler().escapeHTML(false)
                .compile(indexTop.toString(StandardCharsets.UTF_8.name())));
    }

    if (contains(env.getActiveProfiles(), "dev") || indexCache.get() == null) {
        ByteArrayOutputStream index = new ByteArrayOutputStream();
        output("/WEB-INF/views/index.html", context, index, new BeforeAfter());

        Map<String, Object> data = new HashMap<>();
        data.put("contextPath", request.getServletContext().getContextPath() + "/");

        data.put("version", version);

        List<String> inlineTemplates = prepareTemplates(context, "/app/");
        inlineTemplates.addAll(prepareTemplates(context, "/partials/"));
        data.put("inlineTemplates", inlineTemplates);

        indexCache.set(
                Mustache.compiler().escapeHTML(false).compile(index.toString(StandardCharsets.UTF_8.name()))
                        .execute(data).getBytes(StandardCharsets.UTF_8));
    }

    try (OutputStream os = response.getOutputStream()) {
        response.setContentType("text/html; charset=UTF-8");

        Map<String, Object> localizationData = new HashMap<>();
        Locale currentLocale = ObjectUtils.firstNonNull(request.getLocale(), Locale.ENGLISH);
        localizationData.put("firstDayOfWeek", Calendar.getInstance(currentLocale).getFirstDayOfWeek());

        StreamUtils.copy(indexTopTemplate.get().execute(localizationData).getBytes(StandardCharsets.UTF_8), os);
        StreamUtils.copy(indexCache.get(), os);
    }
}

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

@RequestMapping(method = RequestMethod.GET, value = "/downloadPDF")
public void downloadPDF(HttpServletRequest request, HttpServletResponse response)
        throws FileNotFoundException, IOException, BadElementException {
    ServletContext context = request.getServletContext();
    String appPath = context.getRealPath("");
    String fullPath = appPath + "Projects.pdf";
    PDFCreator creator = new PDFCreator();
    projectConverter = new ProjectConverter();
    creator.saveAsPDF(/*w w  w.j  av a 2s  .c  o m*/
            projectConverter.readAll(
                    projectsDocumentRepository.findOne(ConnectionUtils.PROJECTS_COLLECTION).getContent()),
            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";
    }
    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();

}

From source file:org.apache.hadoop.gateway.dispatch.DefaultDispatchTest.java

@Test
public void testCallToNonSecureClusterWithoutDelegationToken() throws URISyntaxException, IOException {
    DefaultDispatch defaultDispatch = new DefaultDispatch();
    ServletContext servletContext = EasyMock.createNiceMock(ServletContext.class);
    GatewayConfig gatewayConfig = EasyMock.createNiceMock(GatewayConfig.class);
    EasyMock.expect(gatewayConfig.isHadoopKerberosSecured()).andReturn(false).anyTimes();
    EasyMock.expect(servletContext.getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE))
            .andReturn(gatewayConfig).anyTimes();
    ServletInputStream inputStream = EasyMock.createNiceMock(ServletInputStream.class);
    HttpServletRequest inboundRequest = EasyMock.createNiceMock(HttpServletRequest.class);
    EasyMock.expect(inboundRequest.getInputStream()).andReturn(inputStream).anyTimes();
    EasyMock.expect(inboundRequest.getQueryString()).andReturn("a=123").anyTimes();
    EasyMock.expect(inboundRequest.getServletContext()).andReturn(servletContext).anyTimes();
    EasyMock.replay(gatewayConfig, servletContext, inboundRequest);
    HttpEntity httpEntity = defaultDispatch.createRequestEntity(inboundRequest);
    assertFalse("buffering in non secure cluster", (httpEntity instanceof PartiallyRepeatableHttpEntity));
}

From source file:org.apache.hadoop.gateway.dispatch.DefaultDispatchTest.java

@Test
public void testCallToSecureClusterWithoutDelegationToken() throws URISyntaxException, IOException {
    DefaultDispatch defaultDispatch = new DefaultDispatch();
    defaultDispatch.setReplayBufferSize(10);
    ServletContext servletContext = EasyMock.createNiceMock(ServletContext.class);
    GatewayConfig gatewayConfig = EasyMock.createNiceMock(GatewayConfig.class);
    EasyMock.expect(gatewayConfig.isHadoopKerberosSecured()).andReturn(Boolean.TRUE).anyTimes();
    EasyMock.expect(servletContext.getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE))
            .andReturn(gatewayConfig).anyTimes();
    ServletInputStream inputStream = EasyMock.createNiceMock(ServletInputStream.class);
    HttpServletRequest inboundRequest = EasyMock.createNiceMock(HttpServletRequest.class);
    EasyMock.expect(inboundRequest.getQueryString()).andReturn("a=123").anyTimes();
    EasyMock.expect(inboundRequest.getInputStream()).andReturn(inputStream).anyTimes();
    EasyMock.expect(inboundRequest.getServletContext()).andReturn(servletContext).anyTimes();
    EasyMock.replay(gatewayConfig, servletContext, inboundRequest);
    HttpEntity httpEntity = defaultDispatch.createRequestEntity(inboundRequest);
    assertTrue("not buffering in the absence of delegation token",
            (httpEntity instanceof PartiallyRepeatableHttpEntity));
}

From source file:dijalmasilva.controllers.LugarController.java

@RequestMapping("/new")
public String newLugar(LugarForm l, HttpServletRequest req) {

    if (l == null) {
        req.setAttribute("result", "Algum dado inserido est invlido.");
    } else {//ww  w .j a  va2  s . c  o m
        Usuario usuarioLogado = (Usuario) req.getSession().getAttribute("usuarioLogado");
        Lugar newPlace = service.salvar(l.convertToLugar(), usuarioLogado);
        if (newPlace != null) {
            List<Lugar> todasOcorrencias = service.buscarTodos();
            req.getServletContext().setAttribute("todasOcorrencias", todasOcorrencias);
            req.setAttribute("result", "Ocorrncia registrada com sucesso!");
        } else {
            req.setAttribute("result",
                    "No foi possvel registrar a ocorrncia. \n Tente novamente mais tarde.!");
        }
    }

    return "home";
}

From source file:org.adeptnet.atlassian.common.Common.java

public void doSAMLRedirect(final HttpServletRequest request, final HttpServletResponse response,
        final String relayState) throws SAMLException, MessageEncodingException {
    if (!samlEnabled) {
        throw new SAMLException("SAML is not enabled");
    }/*from w ww.  ja v a2s.c om*/

    final SAMLClient client = getSAMLClient(request.getServletContext());
    client.doSAMLRedirect(response, relayState);
}

From source file:org.apache.hadoop.gateway.dispatch.DefaultDispatchTest.java

@Test
public void testCallToSecureClusterWithDelegationToken() throws URISyntaxException, IOException {
    DefaultDispatch defaultDispatch = new DefaultDispatch();
    ServletContext servletContext = EasyMock.createNiceMock(ServletContext.class);
    GatewayConfig gatewayConfig = EasyMock.createNiceMock(GatewayConfig.class);
    EasyMock.expect(gatewayConfig.isHadoopKerberosSecured()).andReturn(true).anyTimes();
    EasyMock.expect(servletContext.getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE))
            .andReturn(gatewayConfig).anyTimes();
    ServletInputStream inputStream = EasyMock.createNiceMock(ServletInputStream.class);
    HttpServletRequest inboundRequest = EasyMock.createNiceMock(HttpServletRequest.class);
    EasyMock.expect(inboundRequest.getQueryString()).andReturn("delegation=123").anyTimes();
    EasyMock.expect(inboundRequest.getInputStream()).andReturn(inputStream).anyTimes();
    EasyMock.expect(inboundRequest.getServletContext()).andReturn(servletContext).anyTimes();
    EasyMock.replay(gatewayConfig, servletContext, inboundRequest);
    HttpEntity httpEntity = defaultDispatch.createRequestEntity(inboundRequest);
    assertFalse("buffering in the presence of delegation token",
            (httpEntity instanceof PartiallyRepeatableHttpEntity));
}

From source file:org.siphon.d2js.D2jsRunner.java

public void run(HttpServletRequest request, HttpServletResponse response, String method)
        throws ServletException, IOException {

    String requestPath = getServletPath(request);
    String jsfile = request.getServletContext().getRealPath(requestPath);
    ScriptObjectMirror d2js = null;//from  w  ww . j  a  v  a 2  s .  c o  m
    try {
        d2js = d2jsManager.getD2js(jsfile, requestPath);
        if (d2js == null) {
            response.setStatus(404);
            PrintWriter out = response.getWriter();
            out.print(request.getServletPath() + " not found");
            out.flush();
            return;
        }
    } catch (Exception e3) {
        logger.error("", e3);
        throw new ServletException(e3);
    }

    JsspRequest jsspRequest = new JsspRequest(request, engine);

    String params;
    try {
        params = getParams(jsspRequest);
    } catch (Exception e3) {
        response.setStatus(500);
        PrintWriter out = response.getWriter();
        out.print("{\"error\":{\"message\" : \"params must be json\"}}");
        out.flush();
        return;
    }

    formatter.writeHttpHeader(response);

    JsspWriter out = null;
    //Task task = null;
    MutableObject<Task> taskDocker = new MutableObject<>();
    try {
        out = new JsspWriter(response, engine);
        JsspSession session = new JsspSession(request.getSession());

        // ? native ? JO  ScrpiteObjectMirror ???
        ((Invocable) engine).invokeFunction("processRequest", jsfile, method, params, jsspRequest, response,
                session, out, taskDocker);
        //         d2js = (ScriptObjectMirror) d2js.callMember("clone");
        //         d2js.put("request", jsspRequest);
        //         d2js.put("response", response);
        //         d2js.put("session", session);
        //         d2js.put("out", out);
        //         d2js.put("task", task);
        //         Object result = d2js.callMember(method, params);
        //         if(JsTypeUtil.isNull(result)){
        //            out.print("{\"success\":true}");
        //         } else {
        //            out.print(this.json.stringify(result));
        //         }
        //
        Task task = taskDocker.getValue();
        if (task != null && task.getCallbacker() != null) {
            this.completeTask(taskDocker.getValue(), null);
        }
    } catch (Exception e) {
        try {
            Task task = taskDocker.getValue();
            if (task != null && task.getCallbacker() != null) {
                this.completeTask(taskDocker.getValue(), e);
            }
        } catch (Exception e2) {
            logger.error("", e2);
        }

        Object ex = JsEngineUtil.parseJsException(e);
        if (ex instanceof Throwable == false) {
            boolean ignore = false;
            if (ex instanceof ScriptObjectMirror) {
                ScriptObjectMirror mex = (ScriptObjectMirror) ex;
                CharSequence name = (CharSequence) mex.get("name");
                if ("ValidationError".equals(name) || "MultiError".equals(name)) {
                    ignore = true;
                }
            } else if (ex instanceof ScriptObject) {
                ScriptObject oex = (ScriptObject) ex;
                CharSequence name = (CharSequence) oex.get("name");
                if ("ValidationError".equals(name) || "MultiError".equals(name)) {
                    ignore = true;
                }
            }
            if (!ignore)
                logger.error(json.tryStringify(ex), e);
        } else {
            logger.error("", (Throwable) ex);
        }

        try {
            out.print(formatter.formatException(ex, this.engine));
            out.flush();
        } catch (Exception e1) {
            logger.error("", e1);
        }
    } finally {
        out.flush();
    }
}

From source file:org.apache.hadoop.gateway.dispatch.DefaultDispatchTest.java

@Test
public void testUsingDefaultBufferSize() throws URISyntaxException, IOException {
    DefaultDispatch defaultDispatch = new DefaultDispatch();
    ServletContext servletContext = EasyMock.createNiceMock(ServletContext.class);
    GatewayConfig gatewayConfig = EasyMock.createNiceMock(GatewayConfig.class);
    EasyMock.expect(gatewayConfig.isHadoopKerberosSecured()).andReturn(Boolean.TRUE).anyTimes();
    EasyMock.expect(gatewayConfig.getHttpServerRequestBuffer()).andReturn(16384).anyTimes();
    EasyMock.expect(servletContext.getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE))
            .andReturn(gatewayConfig).anyTimes();
    ServletInputStream inputStream = EasyMock.createNiceMock(ServletInputStream.class);
    HttpServletRequest inboundRequest = EasyMock.createNiceMock(HttpServletRequest.class);
    EasyMock.expect(inboundRequest.getQueryString()).andReturn("a=123").anyTimes();
    EasyMock.expect(inboundRequest.getInputStream()).andReturn(inputStream).anyTimes();
    EasyMock.expect(inboundRequest.getServletContext()).andReturn(servletContext).anyTimes();
    EasyMock.replay(gatewayConfig, servletContext, inboundRequest);
    HttpEntity httpEntity = defaultDispatch.createRequestEntity(inboundRequest);
    assertTrue("not buffering in the absence of delegation token",
            (httpEntity instanceof PartiallyRepeatableHttpEntity));
    assertEquals(defaultDispatch.getReplayBufferSize(), 16);
    assertEquals(defaultDispatch.getReplayBufferSizeInBytes(), 16384);

    //also test normal setter and getters
    defaultDispatch.setReplayBufferSize(-1);
    assertEquals(defaultDispatch.getReplayBufferSizeInBytes(), -1);
    assertEquals(defaultDispatch.getReplayBufferSize(), -1);

    defaultDispatch.setReplayBufferSize(16);
    assertEquals(defaultDispatch.getReplayBufferSizeInBytes(), 16384);
    assertEquals(defaultDispatch.getReplayBufferSize(), 16);

}