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:controladores.DepartamentosController.java

@Override
public ModelAndView handleRequest(HttpServletRequest hsr, HttpServletResponse hsr1) throws Exception {
    ModelAndView mv = new ModelAndView("departamentos");
    DriverManagerDataSource dataSource;//from  ww w  .  j  a va  2 s .com
    dataSource = (DriverManagerDataSource) this.getBean("dataSource", hsr.getServletContext());
    this.cn = dataSource.getConnection();

    mv.addObject("listadepartamentos", this.getDepartamentos());

    return mv;
}

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

/**
 * forgot./*w w w .ja v  a 2 s  .  c  o  m*/
 *
 * @throws Exception exception
 */
@Test(dependsOnMethods = "init")
public void forgot() throws Exception {
    final HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getServletContext()).thenReturn(mock(ServletContext.class));
    when(request.getRequestURI()).thenReturn("/forgot");
    when(request.getMethod()).thenReturn("POST");

    final JSONObject requestJSON = new JSONObject();
    requestJSON.put(User.USER_EMAIL, "test@gmail.com");

    final BufferedReader reader = new BufferedReader(new StringReader(requestJSON.toString()));
    when(request.getReader()).thenReturn(reader);

    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, "succeed\":true"));
}

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

/**
 * login./*www .j  av a2s  . c o m*/
 *
 * @throws Exception exception
 */
@Test(dependsOnMethods = "init")
public void login() throws Exception {
    final HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getServletContext()).thenReturn(mock(ServletContext.class));
    when(request.getRequestURI()).thenReturn("/login");
    when(request.getMethod()).thenReturn("POST");

    final JSONObject requestJSON = new JSONObject();
    requestJSON.put(User.USER_EMAIL, "test@gmail.com");
    requestJSON.put(User.USER_PASSWORD, "pass");

    final BufferedReader reader = new BufferedReader(new StringReader(requestJSON.toString()));
    when(request.getReader()).thenReturn(reader);

    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, "isLoggedIn\":true"));
}

From source file:org.debux.webmotion.server.WebMotionServer.java

/**
 * @param request request to found servlet context
 * @return server context in servlet context
 *///from   w  w  w  .j  a  v  a 2  s  . co  m
protected ServerContext getServerContext(HttpServletRequest request) {
    ServletContext servletContext = request.getServletContext();
    ServerContext serverContext = (ServerContext) servletContext
            .getAttribute(ServerContext.ATTRIBUTE_SERVER_CONTEXT);
    return serverContext;
}

From source file:org.apache.syncope.ext.saml2lsp.agent.Login.java

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

    String idp = request.getParameter(Constants.PARAM_IDP);

    SyncopeClient anonymous = (SyncopeClient) request.getServletContext()
            .getAttribute(Constants.SYNCOPE_ANONYMOUS_CLIENT);
    try {//w  w  w.j a  v  a 2  s. co m
        SAML2RequestTO requestTO = anonymous.getService(SAML2SPService.class).createLoginRequest(
                StringUtils.substringBefore(request.getRequestURL().toString(), "/saml2sp"), idp);

        prepare(response, requestTO);
    } catch (Exception e) {
        LOG.error("While preparing authentication request to IdP", e);

        String errorURL = getServletContext().getInitParameter(Constants.CONTEXT_PARAM_LOGIN_ERROR_URL);
        if (errorURL == null) {
            request.setAttribute("exception", e);
            request.getRequestDispatcher("loginError.jsp").forward(request, response);

            e.printStackTrace(response.getWriter());
        } else {
            response.sendRedirect(errorURL + "?errorMessage="
                    + URLEncoder.encode(e.getMessage(), StandardCharsets.UTF_8.name()));
        }
    }
}

From source file:com.mycompany.bankinterface.service.GetUserData.java

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

    servletContext = request.getServletContext();

    response.setContentType("application/json;charset=UTF-8");
    response.setHeader("Access-Control-Allow-Origin", "*");

    try (PrintWriter out = response.getWriter()) {

        String userId = request.getParameter("userId");

        if (StringUtil.isBlank(userId)) {
            writeJsonError("Required parameter -->userId<-- not found", out);
            return;
        }/*from  ww w .j a  v a2 s .  co  m*/

        User user = getUserById(userId);

        if (user == null) {
            writeJsonError("User " + userId + " not found", out);
            return;
        }

        /*
         JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder();
                
         for (EidRecord eidRecord : user.getEidRecords()) {
         jsonArrayBuilder.add(
         Json.createObjectBuilder()
         .add("eid", eidRecord.getEid())
         .add("dataType", eidRecord.getDataType())
         .add("data", eidRecord.getData())
         );
         }
                
         JsonArray ediRecordsJson = jsonArrayBuilder.build();
         */
        JSONObject hash = new JSONObject();

        for (EidRecord eidRecord : user.getEidRecords()) {
            JSONObject jo = new JSONObject();
            jo.put("data", eidRecord.getData());
            jo.put("eid", eidRecord.getEid());
            jo.put("signature", eidRecord.getSignature());
            jo.put("verifierPubKey", eidRecord.getVerifierPublicKey());
            hash.put(eidRecord.getDataType(), jo);
        }

        out.write(hash.toString());
    }
}

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

/**
 * rpc/*from  www. j  ava  2 s . co m*/
 *
 * @throws Exception exception
 */
@Test(dependsOnMethods = "init")
public void metaWeblog() throws Exception {
    final HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getServletContext()).thenReturn(mock(ServletContext.class));
    when(request.getRequestURI()).thenReturn("/apis/metaweblog");
    when(request.getMethod()).thenReturn("POST");

    //        Date date = (Date) DateFormatUtils.ISO_DATETIME_FORMAT.parseObject("2004-05-03T17:30:08");
    Date date = DateUtils.parseDate("20040503T17:30:08",
            new String[] { "yyyyMMdd'T'HH:mm:ss", "yyyyMMdd'T'HH:mm:ss'Z'" });

    final class MockServletInputStream extends ServletInputStream {

        private ByteArrayInputStream stream;

        public MockServletInputStream(byte[] data) {
            stream = new ByteArrayInputStream(data);
        }

        public int read() throws IOException {
            return stream.read();
        }

        @Override
        public boolean isFinished() {
            return false;
        }

        @Override
        public boolean isReady() {
            return false;
        }

        @Override
        public void setReadListener(ReadListener readListener) {
        }
    }
    StringBuilder sb = new StringBuilder();
    sb.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>").append("<methodCall>")
            .append("<methodName>metaWeblog.newPost</methodName>").append("<params>").append("<param>")
            .append("<value><int>11</int></value>").append("</param>").append("<param>")
            .append("<value><string>test@gmail.com</string></value>").append("</param>").append("<param>")
            .append("<value><string>pass</string></value>").append("</param>").append("<param>")
            .append("<value>").append("<struct>").append("<member>").append("<name>dateCreated</name>")
            .append("<value><dateTime.iso8601>20040503T17:30:08</dateTime.iso8601></value>").append("</member>")
            .append("<member>").append("<name>title</name>").append("<value><string>title</string></value>")
            .append("</member>").append("<member>").append("<name>description</name>")
            .append("<value><string>description</string></value>").append("</member>").append("</struct>")
            .append("</value>").append("</param>").append("<param>")
            .append("<value><boolean>1</boolean></value>").append("</param>").append("</params>")
            .append("</methodCall>");
    when(request.getInputStream()).thenReturn(new MockServletInputStream(sb.toString().getBytes()));

    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();
    System.out.println("xxxxxcontent:" + content);
    Assert.assertTrue(StringUtils.startsWith(content, "<?xml version=\"1.0\""));
}

From source file:com.denimgroup.threadfix.webapp.controller.ToolsDownloadController.java

private String doDownload(HttpServletRequest request, HttpServletResponse response, String jarName) {

    String jarResource = JAR_DOWNLOAD_DIR + jarName;

    InputStream in = request.getServletContext().getResourceAsStream(jarResource);
    if (in == null) {
        exceptionLogService.storeExceptionLog(
                new ExceptionLog(new FileNotFoundException("File not found for download: " + jarResource)));
        return index();
    }//from ww w  .j  av a  2 s .c  o  m

    try {
        ServletOutputStream out = response.getOutputStream();
        int jarSize = request.getServletContext().getResource(jarResource).openConnection().getContentLength();

        if (jarName.endsWith(".jar"))
            response.setContentType("application/java-archive");
        else
            response.setContentType("application/octet-stream");
        ;
        response.setContentLength(jarSize);
        response.addHeader("Content-Disposition", "attachment; filename=\"" + jarName + "\"");

        IOUtils.copy(in, out);
        in.close();
        out.flush();
        out.close();
    } catch (IOException ioe) {
        exceptionLogService.storeExceptionLog(new ExceptionLog(ioe));
        return index();
    }
    return null;
}

From source file:edu.pucp.igc.piscosemanticsearch.Indexador.java

public Indexador(HttpServletRequest req, HttpServletResponse resp) {
    piscoOntology = new PiscoOntology(req, resp);
    String path = req.getServletContext().getRealPath("/");
    fileCarpetaIndice = new File(path + "indice");
    rmRuta = path + "resources/corpus/";
}

From source file:com.manydesigns.portofino.stripes.AuthenticationRequiredResolution.java

public void execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    if (request.getParameter("__portofino_quiet_auth_failure") != null) {
        return;//from www . j a v a  2s.  c o m
    }
    ServletContext servletContext = request.getServletContext();
    Configuration configuration = (Configuration) servletContext
            .getAttribute(BaseModule.PORTOFINO_CONFIGURATION);
    String loginPage = configuration.getString(PortofinoProperties.LOGIN_PAGE);
    if (response.getContentType() == null || response.getContentType().contains("text/html")) {
        ElementsActionBeanContext context = new ElementsActionBeanContext();
        context.setRequest(request);
        String originalPath = context.getActionPath();
        UrlBuilder urlBuilder = new UrlBuilder(Locale.getDefault(), originalPath, false);
        Map<?, ?> parameters = request.getParameterMap();
        urlBuilder.addParameters(parameters);
        String returnUrl = urlBuilder.toString();
        logger.info("Anonymous user not allowed to see {}. Redirecting to login.", originalPath);
        RedirectResolution redirectResolution = new RedirectResolution(loginPage, true);
        redirectResolution.addParameter("returnUrl", returnUrl);
        redirectResolution.execute(request, response);
    } else {
        logger.debug("AJAX call while user disconnected");
        UrlBuilder loginUrlBuilder = new UrlBuilder(request.getLocale(), loginPage, false);
        response.setHeader(LOGIN_PAGE_HEADER, loginUrlBuilder.toString());
        new ErrorResolution(STATUS, errorMessage).execute(request, response);
    }
}