Example usage for javax.servlet.http HttpServletRequest getPathInfo

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

Introduction

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

Prototype

public String getPathInfo();

Source Link

Document

Returns any extra path information associated with the URL the client sent when it made this request.

Usage

From source file:org.ocpsoft.rewrite.servlet.config.proxy.ProxyServlet.java

/**
 * For a redirect response from the target server, this translates {@code theUrl} to redirect to and translates it to
 * one the original client can use.//from  ww w  .j  ava 2  s .  c o m
 */
protected String rewriteUrlFromResponse(HttpServletRequest servletRequest, String theUrl) {
    /*
     * TODO document example paths
     */
    if (theUrl.startsWith(targetUri)) {
        String curUrl = servletRequest.getRequestURL().toString();// no query
        String pathInfo = servletRequest.getPathInfo();
        if (pathInfo != null) {
            assert curUrl.endsWith(pathInfo);
            curUrl = curUrl.substring(0, curUrl.length() - pathInfo.length());// take pathInfo off
        }
        theUrl = curUrl + theUrl.substring(targetUri.length());
    }
    return theUrl;
}

From source file:com.bosch.cr.integration.hello_world_ui.ProxyServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String auth = req.getHeader("Authorization");
    if (auth == null) {
        resp.setHeader("WWW-Authenticate", "BASIC realm=\"Proxy for CR\"");
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;//from  ww w  .  j  a  v a  2  s.com
    }

    try {
        long time = System.currentTimeMillis();
        CloseableHttpClient c = getHttpClient();

        String targetUrl = URL_PREFIX + req.getPathInfo()
                + (req.getQueryString() != null ? ("?" + req.getQueryString()) : "");
        BasicHttpRequest targetReq = new BasicHttpRequest(req.getMethod(), targetUrl);

        String user = "";
        if (auth.toUpperCase().startsWith("BASIC ")) {
            String userpassDecoded = new String(
                    new sun.misc.BASE64Decoder().decodeBuffer(auth.substring("BASIC ".length())));
            user = userpassDecoded.substring(0, userpassDecoded.indexOf(':'));
            String pass = userpassDecoded.substring(userpassDecoded.indexOf(':') + 1);
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass);
            targetReq.addHeader(new BasicScheme().authenticate(creds, targetReq, null));
        }

        targetReq.addHeader("x-cr-api-token", req.getHeader("x-cr-api-token"));
        CloseableHttpResponse targetResp = c.execute(targetHost, targetReq);

        System.out.println("Request: " + targetHost + targetUrl + ", user " + user + " -> "
                + (System.currentTimeMillis() - time) + " msec: " + targetResp.getStatusLine());

        resp.setStatus(targetResp.getStatusLine().getStatusCode());
        targetResp.getEntity().writeTo(resp.getOutputStream());
    } catch (IOException | AuthenticationException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.bosch.cr.examples.inventorybrowser.server.ProxyServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String auth = req.getHeader("Authorization");
    if (auth == null) {
        resp.setHeader("WWW-Authenticate", "BASIC realm=\"Proxy for Bosch IoT Things\"");
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;/*from w w w  . ja  va2 s  . c o m*/
    }

    try {
        long time = System.currentTimeMillis();
        CloseableHttpClient c = getHttpClient();

        String targetUrl = URL_PREFIX + req.getPathInfo()
                + (req.getQueryString() != null ? ("?" + req.getQueryString()) : "");
        BasicHttpRequest targetReq = new BasicHttpRequest(req.getMethod(), targetUrl);

        String user = "";
        if (auth.toUpperCase().startsWith("BASIC ")) {
            String userpassDecoded = new String(
                    new sun.misc.BASE64Decoder().decodeBuffer(auth.substring("BASIC ".length())));
            user = userpassDecoded.substring(0, userpassDecoded.indexOf(':'));
            String pass = userpassDecoded.substring(userpassDecoded.indexOf(':') + 1);
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass);
            targetReq.addHeader(new BasicScheme().authenticate(creds, targetReq, null));
        }

        targetReq.addHeader("x-cr-api-token", props.getProperty("apiToken"));
        CloseableHttpResponse targetResp = c.execute(targetHost, targetReq);

        System.out.println("Request: " + targetHost + targetUrl + ", user " + user + " -> "
                + (System.currentTimeMillis() - time) + " msec: " + targetResp.getStatusLine());

        resp.setStatus(targetResp.getStatusLine().getStatusCode());
        targetResp.getEntity().writeTo(resp.getOutputStream());

    } catch (IOException | AuthenticationException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:net.oneandone.jasmin.main.Servlet.java

/**
 * Called by the servlet engine to process get requests:
 * a) to set the Last-Modified header in the response
 * b) to check if 304 can be redurned if the "if-modified-since" request header is present
 * @return -1 for when unknown//from  ww  w. j a  v  a2 s.  c om
 */
@Override
public long getLastModified(HttpServletRequest request) {
    String path;
    int idx;
    long result;

    result = -1;
    try {
        path = request.getPathInfo();
        if (path != null && path.startsWith("/get/")) {
            lazyInit(request);
            path = path.substring(5);
            idx = path.indexOf('/');
            if (idx != -1) {
                path = path.substring(idx + 1);
                result = engine.getLastModified(path);
            }
        }
    } catch (IOException e) {
        error(request, "getLastModified", e);
        // fall-through
    } catch (RuntimeException | Error e) {
        error(request, "getLastModified", e);
        throw e;
    }
    LOG.debug("getLastModified(" + request.getPathInfo() + ") -> " + result);
    return result;
}

From source file:com.jd.survey.web.settings.DataSetController.java

/**
 * prepares the page to import a dataset from a csv file       
 * @param dataSetId//from w ww . j  av  a2s  . c o m
 * @param principal
 * @param uiModel
 * @param httpServletRequest
 * @return
 */
@Secured({ "ROLE_ADMIN" })
@RequestMapping(value = "/{id}", params = "import", produces = "text/html")
public String prepareForImport(@PathVariable("id") Long dataSetId, Principal principal, Model uiModel,
        HttpServletRequest httpServletRequest) {
    try {
        String login = principal.getName();
        User user = userService.user_findByLogin(login);
        if (!user.isAdmin()) {
            log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo()
                    + " attempted by user login:" + principal.getName() + "from IP:"
                    + httpServletRequest.getLocalAddr());
            return "accessDenied";
        }
        uiModel.addAttribute("dataSet", surveySettingsService.dataSet_findById(dataSetId));
        return "settings/datasets/upload";
    }

    catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:com.jd.survey.web.settings.DataSetController.java

@Secured({ "ROLE_ADMIN" })
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "text/html")
public String delete(@PathVariable("id") Long id, Principal principal, Model uiModel,
        HttpServletRequest httpServletRequest) {
    log.info("delete(): id=" + id);
    try {/*from   ww  w  .  j  av a2 s  . co m*/
        User user = userService.user_findByLogin(principal.getName());
        if (!user.isAdmin()) {
            log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo()
                    + " attempted by user login:" + principal.getName() + "from IP:"
                    + httpServletRequest.getLocalAddr());
            return "accessDenied";

        }
        surveySettingsService.dataSet_remove(id);
        return "redirect:/settings/datasets";
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:com.jd.survey.web.statistics.StatisticsController.java

/**
 * export the single Survey to a PDF /* w  ww .j a  v  a 2  s  .  c om*/
 * @param surveyId
 * @param principal
 * @param uiModel
 * @param httpServletRequest
 * @return
 */
@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/pdf/{id}", produces = "text/html")
public ModelAndView exportSurveyToPdf(@PathVariable("id") Long surveyDefinitionId, Principal principal,
        HttpServletRequest httpServletRequest, HttpServletResponse response) {

    try {

        User user = userService.user_findByLogin(principal.getName());
        if (!securityService.userIsAuthorizedToManageSurvey(surveyDefinitionId, user)) {
            log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo()
                    + " attempted by user login:" + principal.getName() + "from IP:"
                    + httpServletRequest.getLocalAddr());
            throw (new RuntimeException("Unauthorized access"));
        }
        ModelAndView modelAndView = new ModelAndView("statisticsPdf");

        Map<String, String> messages = new TreeMap<String, String>();

        messages.put("surveyLabel",
                messageSource.getMessage(SURVEY_LABEL, null, LocaleContextHolder.getLocale()));
        messages.put("totalLabel",
                messageSource.getMessage(TOTAL_LABEL, null, LocaleContextHolder.getLocale()));
        messages.put("completedLabel",
                messageSource.getMessage(COMPLETED_LABEL, null, LocaleContextHolder.getLocale()));
        messages.put("optionFrequencyLabel",
                messageSource.getMessage(OPTION_FREQUENCY_LABEL, null, LocaleContextHolder.getLocale()));
        messages.put("noStatstisticsMessage",
                messageSource.getMessage(NO_STATSTISTICS_MESSAGE, null, LocaleContextHolder.getLocale()));

        messages.put("pageLabel", messageSource.getMessage(PAGE_LABEL, null, LocaleContextHolder.getLocale()));
        messages.put("optionLabel",
                messageSource.getMessage(OPTION_LABEL, null, LocaleContextHolder.getLocale()));
        messages.put("minimumLabel",
                messageSource.getMessage(MINIMUM_LABEL, null, LocaleContextHolder.getLocale()));
        messages.put("maximumLabel",
                messageSource.getMessage(MAXIMUM_LABEL, null, LocaleContextHolder.getLocale()));

        messages.put("averageLabel",
                messageSource.getMessage(AVERAGE_LABEL, null, LocaleContextHolder.getLocale()));
        messages.put("standardDeviationLabel",
                messageSource.getMessage(STANDARD_DEVIATION_LABEL, null, LocaleContextHolder.getLocale()));
        messages.put("date_format",
                messageSource.getMessage(DATE_FORMAT, null, LocaleContextHolder.getLocale()));
        messages.put("falseLabel",
                messageSource.getMessage(FALSE_LABEL, null, LocaleContextHolder.getLocale()));
        messages.put("trueLabel", messageSource.getMessage(TRUE_LABEL, null, LocaleContextHolder.getLocale()));

        SurveyDefinition surveyDefinition = surveySettingsService.surveyDefinition_findById(surveyDefinitionId);
        SurveyStatistic surveyStatistic = surveyService.surveyStatistic_get(surveyDefinitionId);
        Long recordCount = surveyStatistic.getSubmittedCount();
        modelAndView.addObject("surveyDefinition", surveyDefinition);
        modelAndView.addObject("surveyStatistic", surveyStatistic);
        modelAndView.addObject("messages", messages);
        Map<String, List<QuestionStatistic>> allquestionStatistics = new TreeMap<String, List<QuestionStatistic>>();

        for (SurveyDefinitionPage page : surveyDefinition.getPages()) {
            for (Question question : page.getQuestions()) {
                List<QuestionStatistic> questionStatistics = surveyService
                        .questionStatistic_getStatistics(question, recordCount);
                allquestionStatistics.put("q" + question.getId().toString(), questionStatistics);
            }
        }
        modelAndView.addObject("allquestionStatistics", allquestionStatistics);
        return modelAndView;

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:org.apache.servicemix.http.HttpWsdlTest.java

public void testExternalNonStandaloneWsdl() throws Exception {

    //startup-jetty as mirror for 
    //http://www.ws-i.org/SampleApplications/SupplyChainManagement/2002-08/Retailer.wsdl
    int remoteHttpServerPort = getFreePortNumber();
    Server remoteServer = new Server(remoteHttpServerPort);
    Handler handler = new AbstractHandler() {

        public void handle(String arg0, HttpServletRequest req, HttpServletResponse res, int arg3)
                throws IOException, ServletException {

            res.setContentType("text/xml");
            PrintWriter writer = res.getWriter();
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    this.getClass().getClassLoader().getResourceAsStream("wsdls" + req.getPathInfo())));
            String line = br.readLine();
            while (line != null) {
                writer.write(line);//w  ww .ja  v  a 2  s.  c om
                line = br.readLine();
            }
            br.close();
            writer.close();
        }

    };

    remoteServer.addHandler(handler);
    remoteServer.start();

    try {
        int localHttpServerPort = getFreePortNumber();

        // HTTP Component
        HttpEndpoint ep = new HttpEndpoint();
        ep.setService(new QName("http://servicemix.apache.org/wsn/jaxws", "PullPointService"));
        ep.setEndpoint("JBI");
        ep.setRoleAsString("consumer");
        ep.setLocationURI("http://localhost:" + localHttpServerPort + "/Service/");
        ep.setDefaultMep(MessageExchangeSupport.IN_OUT);
        ep.setWsdlResource(new UrlResource("http://localhost:" + remoteHttpServerPort + "/wsn.wsdl"));
        HttpComponent http = new HttpComponent();
        http.setEndpoints(new HttpEndpoint[] { ep });
        container.activateComponent(http, "PullPointService");

        // Start container
        container.start();

        GetMethod get = new GetMethod("http://localhost:" + localHttpServerPort + "/Service/?wsdl");
        int state = new HttpClient().executeMethod(get);
        assertEquals(HttpServletResponse.SC_OK, state);
        Document doc = (Document) new SourceTransformer()
                .toDOMNode(new StringSource(get.getResponseBodyAsString()));
        get.releaseConnection();

        // Test WSDL
        WSDLFactory factory = WSDLFactory.newInstance();
        WSDLReader reader = factory.newWSDLReader();
        Definition def;

        def = reader.readWSDL("http://localhost:" + localHttpServerPort + "/Service/?wsdl", doc);
        assertNotNull(def);
        assertNotNull(def.getImports());
        assertEquals(1, def.getImports().size());

    } finally {
        remoteServer.stop();
    }

}

From source file:com.jd.survey.web.surveys.SurveyController.java

/**
 * Shows a list of Survey Entries for a Survey Definition, Supports Paging 
 * @param surveyId//from ww  w  . j  ava 2  s .c om
 * @param principal
 * @param uiModel
 * @param httpServletRequest
 * @return
 */
@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/list", produces = "text/html", method = RequestMethod.GET)
public String listSurveyEntries(@RequestParam(value = "id", required = true) Long surveyDefinitionId,
        @RequestParam(value = "page", required = false) Integer page,
        @RequestParam(value = "size", required = false) Integer size, Model uiModel, Principal principal,
        HttpServletRequest httpServletRequest) {
    try {
        User user = userService.user_findByLogin(principal.getName());
        Set<SurveyDefinition> surveyDefinitions = surveySettingsService
                .surveyDefinition_findAllCompletedInternal(user);

        if (!securityService.userIsAuthorizedToManageSurvey(surveyDefinitionId, user)) {
            log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo()
                    + " attempted by user login:" + principal.getName() + "from IP:"
                    + httpServletRequest.getLocalAddr());
            return "accessDenied";
        }

        uiModel.addAttribute("surveyDefinitions", surveyDefinitions);
        uiModel.addAttribute("surveyDefinition",
                surveySettingsService.surveyDefinition_findById(surveyDefinitionId));
        uiModel.addAttribute("surveyStatistic", surveyService.surveyStatistic_get(surveyDefinitionId));
        int sizeNo = size == null ? 25 : size.intValue();
        final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
        Set<SurveyEntry> surveyEntries = surveyService.surveyEntry_getAll(surveyDefinitionId, firstResult,
                sizeNo);
        float nrOfPages = (float) surveyService.surveyEntry_getCount(surveyDefinitionId) / sizeNo;
        int maxPages = (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages);
        uiModel.addAttribute("maxPages", maxPages);
        uiModel.addAttribute("surveyEntries", surveyEntries);
        return "surveys/entries";
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:net.ontopia.topicmaps.nav2.servlets.DataIntegrationServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("text/plain; charset=utf-8");

    // get topic map id
    String topicMapId = topicMapId = getInitParameter("topicMapId");
    if (topicMapId == null)
        throw new ServletException("Topic map identifier is not specified.");

    // parse path
    String path = request.getPathInfo();
    if (path == null)
        throw new ServletException("Path is missing.");
    path = path.substring(1);/*ww w .ja  va2 s.  c o  m*/

    String[] args = StringUtils.split(path, "/");
    String name = args[0];
    String action = args[1];

    // get topics query
    String topicsQuery = getInitParameter("topicsQuery");
    if (topicsQuery == null)
        throw new ServletException("Parameter 'topicsQuery' is not specified.");

    // get characteristcs query
    String characteristicsQuery = getInitParameter("characteristicsQuery");
    if (characteristicsQuery == null)
        throw new ServletException("Parameter 'characteristicsQuery' is not specified.");

    TopicMapStoreIF targetStore = TopicMaps.createStore(topicMapId, false);
    try {
        final TopicMapIF target = targetStore.getTopicMap();

        // transform input document to topic map
        final TopicMapIF source = transformRequest(name, request.getInputStream(),
                targetStore.getBaseAddress());

        // find topics to synchronize
        QueryProcessorIF qp = QueryUtils.getQueryProcessor(source);

        List candidates = new ArrayList();
        QueryResultIF qr = qp.execute(topicsQuery);
        try {
            while (qr.next()) {
                // synchronize topic
                candidates.add(qr.getValue(0));
            }
        } finally {
            qr.close();
        }

        if ("updated".equals(action) || "created".equals(action)) {

            DeciderIF tfilter = new DeciderIF() {
                @Override
                public boolean ok(Object o) {
                    return true;
                }
            };

            Iterator iter = candidates.iterator();
            while (iter.hasNext()) {
                TopicIF src = (TopicIF) iter.next();

                DeciderIF sfilter;
                if (characteristicsQuery == null) {
                    // let everything through
                    sfilter = tfilter;

                } else {
                    // let the characteristics query decide what gets synchronized
                    Collection characteristics = new HashSet();
                    QueryResultIF cqr = qp.execute(characteristicsQuery,
                            Collections.singletonMap("topic", src));
                    try {
                        while (cqr.next()) {
                            // synchronize topic
                            characteristics.add(cqr.getValue(0));
                        }
                    } finally {
                        cqr.close();
                    }
                    sfilter = new ContainmentDecider(characteristics);
                }
                // synchronize topic
                TopicMapSynchronizer.update(target, src, tfilter, sfilter);
            }
        } else if ("deleted".equals(action)) {

            Iterator iter = candidates.iterator();
            while (iter.hasNext()) {
                TopicIF src = (TopicIF) iter.next();
                Collection affectedTopics = IdentityUtils.findSameTopic(target, src);
                Iterator aiter = affectedTopics.iterator();
                while (aiter.hasNext()) {
                    TopicIF affectedTopic = (TopicIF) aiter.next();
                    affectedTopic.remove();
                }
            }
        } else {
            throw new ServletException("Unsupported action: " + action);
        }

        targetStore.commit();
    } catch (Exception e) {
        targetStore.abort();
        throw new ServletException(e);
    } finally {
        targetStore.close();
    }
}