Example usage for javax.servlet ServletRequestEvent ServletRequestEvent

List of usage examples for javax.servlet ServletRequestEvent ServletRequestEvent

Introduction

In this page you can find the example usage for javax.servlet ServletRequestEvent ServletRequestEvent.

Prototype

public ServletRequestEvent(ServletContext sc, ServletRequest request) 

Source Link

Document

Construct a ServletRequestEvent for the given ServletContext and ServletRequest.

Usage

From source file:io.mapzone.arena.geocode.GeocodeServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {//w w w  . ja  va  2s.  c o  m

        EventManager.instance().publish(new ServletRequestEvent(getServletContext(), req));

        if (req.getParameterMap().isEmpty()) {
            resp.sendError(400, "No parameters found! Please specify at least 'text'.");
            return;
        }

        GeocodeQuery query = extractQuery(req);

        // perform search
        List<Address> addresses = service.geocode(query);

        resp.setStatus(HttpStatus.SC_OK);
        resp.setContentType("application/json;charset=utf-8");
        handleCors(req, resp);

        // convert addresses to result json
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(resp.getOutputStream());
        JSONWriter writer = new JSONWriter(outputStreamWriter);
        writer.object();
        writer.key("results");
        writer.array();
        for (Address address : addresses) {
            writer.value(toJSON(address));
        }
        writer.endArray();
        writer.endObject();
        outputStreamWriter.flush();
        outputStreamWriter.close();
    } catch (Exception e) {
        e.printStackTrace();
        resp.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }
}

From source file:br.com.caelum.vraptor.ioc.spring.SpringProvider.java

/**
 * Provides request scope support for Spring IoC Container when
 * org.springframework.web.context.request.RequestContextListener has not
 * been called.//from   w w  w  .ja va  2 s. com
 */
public <T> T provideForRequest(RequestInfo request, Execution<T> execution) {
    if (springListenerAlreadyCalled()) {
        return execution.insideRequest(getContainer());
    }
    VRaptorRequestHolder.setRequestForCurrentThread(request);
    T result;
    try {
        ServletContext context = request.getServletContext();
        HttpServletRequest webRequest = request.getRequest();
        requestListener.requestInitialized(new ServletRequestEvent(context, webRequest));
        try {
            result = execution.insideRequest(getContainer());
        } finally {
            requestListener.requestDestroyed(new ServletRequestEvent(context, webRequest));
        }
    } finally {
        VRaptorRequestHolder.resetRequestForCurrentThread();
    }
    return result;
}

From source file:br.com.caelum.vraptor.ioc.spring.SpringProviderRegisteringComponentsTest.java

@Override
protected <T> T executeInsideRequest(final WhatToDo<T> execution) {
    Callable<T> task = new Callable<T>() {
        public T call() throws Exception {
            T result = null;//from   w  ww  .  ja  va2 s  . c  o m
            HttpSessionMock session = new HttpSessionMock(context, "session" + ++counter);
            HttpServletRequestMock httpRequest = new HttpServletRequestMock(session,
                    mock(MutableRequest.class, "request" + counter));
            MutableResponse response = mock(MutableResponse.class, "response" + counter);

            RequestInfo request = new RequestInfo(context, null, httpRequest, response);
            VRaptorRequestHolder.setRequestForCurrentThread(request);

            RequestContextListener contextListener = new RequestContextListener();
            contextListener.requestInitialized(new ServletRequestEvent(context, httpRequest));
            result = execution.execute(request, counter);
            contextListener.requestDestroyed(new ServletRequestEvent(context, httpRequest));

            VRaptorRequestHolder.resetRequestForCurrentThread();
            return result;
        }
    };

    Future<T> future = Executors.newSingleThreadExecutor().submit(task);

    try {
        return future.get(60, TimeUnit.SECONDS);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:nl.surfnet.coin.shared.log.ApiCallLogServiceImplTest.java

@Before
public void init() {
    service = new ApiCallLogServiceImpl(super.getJdbcTemplate());
    ApiCallLogContextListener listener = new ApiCallLogContextListener();
    ServletRequestEvent requestEvent = new ServletRequestEvent(new MockServletContext(),
            new MockHttpServletRequest("GET", "http://127.0.0.1/social/people/test"));
    listener.requestInitialized(requestEvent);
}

From source file:pt.webdetails.cns.notifications.sparkl.kettle.baserver.web.utils.HttpConnectionHelper.java

protected static Response invokePlatformEndpoint(final String endpointPath, final String httpMethod,
        final Map<String, String> queryParameters) {

    Response response = new Response();

    // get servlet context and request dispatcher
    ServletContext servletContext = null;
    RequestDispatcher requestDispatcher = null;
    try {/* w ww .  j a v  a2  s  .  c o m*/
        Object context = PentahoSystem.getApplicationContext().getContext();
        if (context instanceof ServletContext) {
            servletContext = (ServletContext) context;
            requestDispatcher = servletContext.getRequestDispatcher("/api" + endpointPath);
        }
    } catch (NoClassDefFoundError ex) {
        logger.error("Failed to get application servlet context", ex);
        return response;
    }

    if (requestDispatcher != null) {

        // create servlet request
        final InternalHttpServletRequest servletRequest = new InternalHttpServletRequest(httpMethod, "/pentaho",
                "/api", endpointPath);
        servletRequest.setAttribute("org.apache.catalina.core.DISPATCHER_TYPE", 2); // FORWARD = 2

        for (Map.Entry<String, String> entry : queryParameters.entrySet()) {
            servletRequest.setParameter(entry.getKey(), entry.getValue());
        }

        ServletRequestEvent servletRequestEvent = new ServletRequestEvent(servletContext, servletRequest);
        RequestContextListener requestContextListener = new RequestContextListener();
        requestContextListener.requestInitialized(servletRequestEvent);

        // create servlet response
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        final InternalHttpServletResponse servletResponse = new InternalHttpServletResponse(outputStream);

        try {
            // used for calculating the response time
            long startTime = System.currentTimeMillis();

            requestDispatcher.forward(servletRequest, servletResponse);

            // get response time
            long responseTime = System.currentTimeMillis() - startTime;

            response.setStatusCode(servletResponse.getStatus());
            response.setResult(servletResponse.getContentAsString());
            response.setResponseTime(responseTime);
        } catch (ServletException ex) {
            logger.error("Failed ", ex);
            return response;
        } catch (IOException ex) {
            logger.error("Failed ", ex);
            return response;
        } finally {
            requestContextListener.requestDestroyed(servletRequestEvent);
        }

    }

    return response;
}

From source file:org.dbflute.utflute.spring.web.WebContainerTestCase.java

protected void xdoListenRequestInitialized() {
    final MockletHttpServletRequest request = getMockRequest();
    if (request != null) {
        ServletRequestEvent event = new ServletRequestEvent(request.getServletContext(), request);
        _xmockListener = new RequestContextListener();
        _xmockListener.requestInitialized(event);
    }//from   w  w  w  .  j ava 2s  .  co m
}

From source file:org.pentaho.di.baserver.utils.web.HttpConnectionHelper.java

protected Response invokePlatformEndpoint(final String endpointPath, final String httpMethod,
        final Map<String, String> queryParameters) {

    Response response = new Response();

    // get servlet context and request dispatcher
    ServletContext servletContext = null;
    RequestDispatcher requestDispatcher = null;
    try {//from ww  w.  jav a  2  s  .co  m
        Object context = getContext();
        if (context instanceof ServletContext) {
            servletContext = (ServletContext) context;
            requestDispatcher = servletContext.getRequestDispatcher("/api" + endpointPath);
        }
    } catch (NoClassDefFoundError ex) {
        logger.error("Failed to get application servlet context", ex);
        return response;
    }

    if (requestDispatcher != null) {
        // create servlet request
        URL fullyQualifiedServerURL;
        try {
            fullyQualifiedServerURL = getUrl();
        } catch (MalformedURLException e) {
            logger.error("FullyQualifiedServerURL is incorrect");
            return response;
        }

        final InternalHttpServletRequest servletRequest = new InternalHttpServletRequest(httpMethod,
                fullyQualifiedServerURL, "/api", endpointPath);
        servletRequest.setAttribute("org.apache.catalina.core.DISPATCHER_TYPE", DispatcherType.FORWARD); //FORWARD = 2

        try {
            insertParameters(httpMethod, queryParameters, servletRequest);
        } catch (UnsupportedEncodingException e) {
            logger.error("Can't encode parameters");
            return response;
        }

        ServletRequestEvent servletRequestEvent = new ServletRequestEvent(servletContext, servletRequest);
        RequestContextListener requestContextListener = new RequestContextListener();
        requestContextListener.requestInitialized(servletRequestEvent);

        // create servlet response
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        final InternalHttpServletResponse servletResponse = new InternalHttpServletResponse(outputStream);

        try {
            // used for calculating the response time
            long startTime = System.currentTimeMillis();

            requestDispatcher.forward(servletRequest, servletResponse);

            // get response time
            long responseTime = System.currentTimeMillis() - startTime;

            response.setStatusCode(servletResponse.getStatus());
            response.setResult(servletResponse.getContentAsString());
            response.setResponseTime(responseTime);
        } catch (ServletException ex) {
            logger.error("Failed ", ex);
            return response;
        } catch (IOException ex) {
            logger.error("Failed ", ex);
            return response;
        } finally {
            requestContextListener.requestDestroyed(servletRequestEvent);
        }

    }

    return response;
}

From source file:org.dbflute.utflute.spring.web.WebContainerTestCase.java

protected void xdoListenRequestDestroyed() {
    if (_xmockListener != null) {
        final MockletHttpServletRequest request = getMockRequest();
        if (request != null) { // just in case
            ServletRequestEvent event = new ServletRequestEvent(request.getServletContext(), request);
            _xmockListener.requestDestroyed(event);
            _xmockListener = null;/*from  w w w .j av  a  2 s  .c o  m*/
        }
    }
}

From source file:io.mapzone.arena.share.ShareInfoServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {/*from   w  w  w . j a v a 2  s. co  m*/
        // log.info( "QueryString: " + req.getQueryString() );
        // Enumeration<String> headerNames = req.getHeaderNames();
        // while (headerNames.hasMoreElements()) {
        // String header = headerNames.nextElement();
        // log.info( "HEADER '" + header + "': '" + req.getHeader( header ) + "'"
        // );
        // }

        if (req.getParameterMap().isEmpty() || StringUtils.isBlank(req.getParameter(PARAMETER_LAYERS))
                || StringUtils.isBlank(req.getParameter(PARAMETER_BBOX))) {
            resp.sendError(400, "No parameters found! Please specify at least '" + PARAMETER_LAYERS + "' and '"
                    + PARAMETER_BBOX + "'.");
            return;
        }

        final String layers = req.getParameter(PARAMETER_LAYERS);
        final String bbox = req.getParameter(PARAMETER_BBOX);
        final String authToken = req.getParameter(PARAMETER_AUTHTOKEN);

        resp.setStatus(HttpStatus.SC_OK);
        resp.setContentType("text/html;charset=utf-8");

        final String projectName = ArenaConfig.getAppTitle();
        // FIXME add the project description here
        final String description = ArenaConfig.getAppTitle();
        final String arenaUrl = ArenaPlugin.instance().config().getProxyUrl() + ArenaPlugin.ALIAS;
        final StringBuilder imageUrl = new StringBuilder(ArenaPlugin.instance().config().getProxyUrl());
        imageUrl.append(GeoServerStarter.ALIAS);
        imageUrl.append(
                "?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&FORMAT=image%2Fpng&CRS=EPSG%3A3857&STYLES=&WIDTH=1200&HEIGHT=630");
        imageUrl.append("&LAYERS=").append(URLEncoder.encode(layers, "utf-8"));
        imageUrl.append("&BBOX=").append(URLEncoder.encode(bbox, "utf-8"));
        if (!StringUtils.isBlank(authToken)) {
            imageUrl.append("&authToken=").append(URLEncoder.encode(authToken, "utf-8"));
        }

        //            log.info( "IMGURL" + imageUrl.toString() );
        // convert addresses to result json
        OutputStreamWriter writer = new OutputStreamWriter(resp.getOutputStream());
        writer.write("<html>\n");
        writer.write(" <head>\n");
        writer.write("  <title>mapzone - " + projectName + "</title>\n");
        writer.write("  <meta name='author' content='mapzone' />\n");
        writer.write("  <meta name='description' content='" + description + "' />\n");
        writer.write(
                "  <meta name='keywords' content='location, geo, web, osm, map, maps, styling, wms, csv, xls, georeference, geofence, geocode' />\n");
        writer.write("  <meta name='robots' content='index,follow' />\n");
        writer.write("  <meta name='audience' content='all' />\n");
        // writer.write( " <meta name='revisit-after' content='5 days' />\n");
        // facebook/opengraph
        writer.write("  <meta property='og:locality' content='Leipzig'/>\n");
        writer.write("  <meta property='og:country-name' content='Germany'/>\n");
        writer.write("  <meta property='og:latitude' content='51.32794'/>\n");
        writer.write("  <meta property='og:longitude' content='12.33126'/>\n");
        writer.write("  <meta property='og:image:url' content='" + imageUrl.toString() + "' />\n");
        writer.write("  <meta property='og:image:type' content='image/png' />\n");
        writer.write("  <meta property='og:image:width' content='1200' />\n");
        writer.write("  <meta property='og:image:height' content='630' />\n");
        writer.write("  <meta property='og:type' content='article' />\n");
        writer.write("  <meta property='og:site_name' content='mapzone - " + projectName + "' />\n");
        // wird grad nicht von Facebook untersttzt
        // writer.write( " <meta property='fb:app_id' content='1754931524765083'
        // />\n");
        // writer.write( " <meta property='fb:admins' content='739545402735248'
        // />\n");
        writer.write(
                "  <meta property='article:publisher' content='https://www.facebook.com/mapzoneio-1401853630109662' />\n");
        writer.write("  <meta property='article:author' content='https://www.facebook.com/stundzig' />\n");

        // writer.write( " <meta property='og:url' content='" + arenaUrl + "'
        // />\n");

        // perform a redirect after 10ms
        writer.write("  <script type='text/javascript'>window.setTimeout(function(){window.location.href = '"
                + arenaUrl + "'; },10);</script>\n");
        writer.write(" </head>\n");
        writer.write(" <body>\n");
        // writer.write( " <iframe src='" + arenaUrl
        // + "' width='100%' height='520' frameborder='0'
        // allowfullscreen='allowfullscreen'></iframe>\n");
        writer.write(" </body>\n");
        writer.write("<head>\n");
        writer.flush();
        writer.close();

        EventManager.instance().publish(new ServletRequestEvent(getServletContext(), req));
    } catch (Exception e) {
        e.printStackTrace();
        resp.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }
}