Example usage for org.springframework.web.context.request WebRequest getContextPath

List of usage examples for org.springframework.web.context.request WebRequest getContextPath

Introduction

In this page you can find the example usage for org.springframework.web.context.request WebRequest getContextPath.

Prototype

String getContextPath();

Source Link

Document

Return the context path for this request (usually the base path that the current web application is mapped to).

Usage

From source file:org.openbaton.marketplace.api.exceptions.GlobalExceptionHandler.java

@ExceptionHandler({ PackageIntegrityException.class })
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
protected @ResponseBody ResponseEntity<Object> handleInvalidRequest(Exception e, WebRequest request) {
    if (log.isDebugEnabled()) {
        log.error("Exception was thrown -> Return message: " + e.getMessage(), e);
    } else {/*from   ww w.j a  va  2  s. c o m*/
        log.error("Exception was thrown -> Return message: " + e.getMessage());
    }
    ExceptionResource exc = new ExceptionResource("Bad Request", e.getMessage());
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    Map body = new HashMap<>();
    body.put("error", "Upload Error");
    body.put("exception", e.getClass().toString());
    body.put("message", e.getMessage());
    body.put("path", request.getContextPath());
    body.put("status", HttpStatus.BAD_REQUEST.value());
    body.put("timestamp", new Date().getTime());
    ResponseEntity responseEntity = new ResponseEntity(body, headers, HttpStatus.BAD_REQUEST);
    return responseEntity;
}

From source file:org.openbaton.marketplace.api.exceptions.GlobalExceptionHandler.java

@ExceptionHandler({ FailedToUploadException.class })
@ResponseStatus(value = HttpStatus.I_AM_A_TEAPOT)
protected @ResponseBody ResponseEntity<Object> handleErrorRequest(Exception e, WebRequest request) {
    if (log.isDebugEnabled()) {
        log.error("Exception was thrown -> Return message: " + e.getMessage(), e);
    } else {/*  ww w.j  a  va  2  s  . c om*/
        log.error("Exception was thrown -> Return message: " + e.getMessage());
    }
    ExceptionResource exc = new ExceptionResource("Bad Request", e.getMessage());
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    Map body = new HashMap<>();
    body.put("error", "Upload Error");
    body.put("exception", e.getClass().toString());
    body.put("message", e.getMessage());
    body.put("path", request.getContextPath());
    body.put("status", HttpStatus.I_AM_A_TEAPOT.value());
    body.put("timestamp", new Date().getTime());
    ResponseEntity responseEntity = new ResponseEntity(body, headers, HttpStatus.I_AM_A_TEAPOT);
    return responseEntity;
}

From source file:edu.jhuapl.openessence.controller.ReportController.java

@RequestMapping("/chartJson")
public @ResponseBody Map<String, Object> chartJson(WebRequest request, HttpServletRequest servletRequest,
        @RequestParam("dsId") JdbcOeDataSource ds, ChartModel chartModel) throws ErrorMessageException {

    log.info(LogStatements.GRAPHING.getLoggingStmt() + request.getUserPrincipal().getName());

    final List<Filter> filters = new Filters().getFilters(request.getParameterMap(), ds, null, 0, null, 0);
    final List<Dimension> results = ControllerUtils.getResultDimensionsByIds(ds,
            request.getParameterValues("results"));

    Dimension filterDimension = null;
    if (results.get(0).getFilterBeanId() != null && results.get(0).getFilterBeanId().length() > 0) {
        filterDimension = ds.getFilterDimension(results.get(0).getFilterBeanId());
    }/*from  w w w .  j  a v  a 2s. c o m*/
    // if not provided, use the result dimension
    // it means name and id columns are same...
    if (filterDimension != null) {
        results.add(results.size(), filterDimension);
    }

    // Subset of results, should check
    final List<Dimension> charts = ControllerUtils.getResultDimensionsByIds(ds,
            request.getParameterValues("charts"));

    final List<Dimension> accumulations = ControllerUtils.getAccumulationsByIds(ds,
            request.getParameterValues("accumId"));

    final List<OrderByFilter> sorts = new ArrayList<OrderByFilter>();
    try {
        sorts.addAll(Sorters.getSorters(request.getParameterMap()));
    } catch (Exception e) {
        log.warn("Unable to get sorters, using default ordering");
    }

    // TODO put this on ChartModel
    //default to white allows clean copy paste of charts from browser
    Color backgroundColor = Color.WHITE;

    String bgParam = request.getParameter("backgroundColor");
    if (bgParam != null && !"".equals(bgParam)) {
        if ("transparent".equalsIgnoreCase(bgParam)) {
            backgroundColor = new Color(255, 255, 255, 0);
        } else {
            backgroundColor = ControllerUtils.getColorsFromHex(Color.WHITE, bgParam)[0];
        }
    }

    String graphBarUrl = request.getContextPath() + servletRequest.getServletPath() + "/report/graphBar";
    graphBarUrl = appendGraphFontParam(ds, graphBarUrl);

    String graphPieUrl = request.getContextPath() + servletRequest.getServletPath() + "/report/graphPie";
    graphPieUrl = appendGraphFontParam(ds, graphPieUrl);

    // TODO eliminate all the nesting in response and just use accumulation and chartID properties
    Map<String, Object> response = new HashMap<String, Object>();
    Map<String, Object> graphs = new HashMap<String, Object>();
    response.put("graphs", graphs);

    String clientTimezone = null;
    String timezoneEnabledString = messageSource.getMessage(TIMEZONE_ENABLED, "false");
    if (timezoneEnabledString.equalsIgnoreCase("true")) {
        clientTimezone = ControllerUtils.getRequestTimezoneAsHourMinuteString(request);
    }
    Collection<Record> records = new DetailsQuery().performDetailsQuery(ds, results, accumulations, filters,
            sorts, false, clientTimezone);
    final List<Filter> graphFilters = new Filters().getFilters(request.getParameterMap(), ds, null, 0, null, 0,
            false);
    //for each requested accumulation go through each requested result and create a chart
    for (Dimension accumulation : accumulations) {
        Map<String, Object> accumulationMap = new HashMap<String, Object>();
        // Create charts for dimensions (subset of results)
        for (Dimension chart : charts) {
            DefaultGraphData data = new DefaultGraphData();
            data.setGraphTitle(chartModel.getTitle());
            data.setGraphHeight(chartModel.getHeight());
            data.setGraphWidth(chartModel.getWidth());
            data.setShowLegend(chartModel.isLegend());
            data.setBackgroundColor(backgroundColor);
            data.setShowGraphLabels(chartModel.isShowGraphLabels());
            data.setLabelBackgroundColor(backgroundColor);
            data.setPlotHorizontal(chartModel.isPlotHorizontal());
            data.setNoDataMessage(chartModel.getNoDataMessage());
            data.setTitleFont(new Font("Arial", Font.BOLD, 12));

            GraphObject graph = createGraph(ds, request.getUserPrincipal().getName(), records, chart,
                    filterDimension, accumulation, data, chartModel, graphFilters);
            String graphURL = "";
            if (BAR.equalsIgnoreCase(chartModel.getType())) {
                graphURL = graphBarUrl;
            } else if (PIE.equalsIgnoreCase(chartModel.getType())) {
                graphURL = graphPieUrl;
            }
            graphURL = appendUrlParameter(graphURL, "graphDataId", graph.getGraphDataId());

            chartModel.setImageUrl(graphURL);
            chartModel.setImageMap(graph.getImageMap());
            chartModel.setImageMapName(graph.getImageMapName());

            accumulationMap.put(chart.getId(), chartModel);
        }
        graphs.put(accumulation.getId(), accumulationMap);
    }

    log.info(String.format("Chart JSON Details query for %s", request.getUserPrincipal().getName()));

    return response;
}

From source file:edu.jhuapl.openessence.controller.ReportController.java

@RequestMapping("/timeSeriesJson")
public @ResponseBody Map<String, Object> timeSeriesJson(@RequestParam("dsId") JdbcOeDataSource ds,
        TimeSeriesModel model, Principal principal, WebRequest request, HttpServletRequest servletRequest)
        throws ErrorMessageException {

    Map<String, Object> result = new HashMap<String, Object>();

    DataSeriesSource dss = null;//ww  w  .jav a2 s  . co  m
    if (ds instanceof DataSeriesSource) {
        dss = (DataSeriesSource) ds;

    }

    String groupId = "";
    String resolution = "";

    // TODO put this logic in a custom HandlerMethodArgumentResolver
    if (model.getTimeseriesGroupResolution() != null) {
        String[] parts = model.getTimeseriesGroupResolution().split(":");
        if (parts.length == 2 && !parts[0].trim().isEmpty() && !parts[1].trim().isEmpty()) {
            groupId = parts[0];
            resolution = parts[1];
        }
    }

    if (groupId == null || groupId.isEmpty()) {
        throw new OeDataSourceException("No Grouping Dimension ID specified");
    }

    GroupingDimension groupingDim = dss.getGroupingDimension(groupId);
    // find resolution handlers as appropriate for groupings
    if (resolution == null || "".equals(groupId)) {
        String[] res = groupingDim.getResolutions().toArray(new String[groupingDim.getResolutions().size()]);
        if (res.length > 0) {
            resolution = res[0];
        }
    }

    if (ds.getDimensionJoiner() != null) {
        ds.getDimensionJoiner().joinDimensions();
    }

    List<Dimension> accumulations = ControllerUtils.getAccumulationsByIds(ds, model.getAccumId());
    List<Dimension> timeseriesDenominators = ControllerUtils.getAccumulationsByIds(ds,
            model.getTimeseriesDenominator(), false);

    final List<OrderByFilter> sorts = new ArrayList<OrderByFilter>();
    GroupingImpl group = new GroupingImpl(groupId, resolution);

    if (resolution.equals(DAILY) && model.getPrepull() < 0) {
        model.setPrepull(DEFAULT_DAILY_PREPULL);
    }

    if (model.getPrepull() < 0) {
        model.setPrepull(0);
    }

    //union accumulations to get all results
    List<Dimension> dimensions = new ArrayList<Dimension>(
            ControllerUtils.unionDimensions(accumulations, timeseriesDenominators));
    List<Grouping> groupings = new ArrayList<Grouping>();
    groupings.add(groupingDim.makeGrouping(resolution));

    //create results group dimension + all dimensions
    final List<Dimension> results = new ArrayList<Dimension>();
    for (Dimension d : dimensions) {
        results.add(ds.getResultDimension(d.getId()));
    }

    Map<String, ResolutionHandler> resolutionHandlers = dss.getGroupingDimension(group.getId())
            .getResolutionsMap();
    List<Filter> filters = new Filters().getFilters(request.getParameterMap(), dss, group.getId(),
            model.getPrepull(), resolution, getCalWeekStartDay(resolutionHandlers));

    String clientTimezone = null;
    String timezoneEnabledString = messageSource.getMessage(TIMEZONE_ENABLED, "false");
    if (timezoneEnabledString.equalsIgnoreCase("true")) {
        clientTimezone = ControllerUtils.getRequestTimezoneAsHourMinuteString(request);
    }
    //details query for all records
    Collection<Record> records = new DetailsQuery().performDetailsQuery(ds, results, dimensions, filters, sorts,
            groupings, false, clientTimezone);

    //create graph data and set known configuration
    DefaultGraphData graphData = new DefaultGraphData();
    graphData.setShowSingleSeverityLegends(false);
    graphData.setGraphTitle(model.getTimeseriesTitle());
    graphData.setGraphWidth(model.getWidth());
    graphData.setGraphHeight(model.getHeight());
    graphData.setShowLegend(true);
    graphData.setBackgroundColor(new Color(255, 255, 255, 0));

    // only set an array if they provided one
    if (model.getGraphBaseColors() != null && model.getGraphBaseColors().length > 0) {
        // TODO leverage Spring to convert colors
        graphData.setGraphBaseColors(ControllerUtils.getColorsFromHex(Color.BLACK, model.getGraphBaseColors()));
    }

    String graphTimeSeriesUrl = request.getContextPath() + servletRequest.getServletPath()
            + "/report/graphTimeSeries";
    graphTimeSeriesUrl = appendGraphFontParam(ds, graphTimeSeriesUrl);

    //TODO, this still uses the html method from the graph module and then wraps in json...move to a pure json method
    Map<String, Object> timeseriesResult = createTimeseries(principal.getName(), dss, filters, group,
            resolution, model.getPrepull(), graphTimeSeriesUrl, records, accumulations, timeseriesDenominators,
            model.getTimeseriesDetectorClass(), model.isIncludeDetails(), model.isDisplayIntervalEndDate(),
            graphData, ControllerUtils.getRequestTimezone(request));

    result.putAll(timeseriesResult);

    return result;
}

From source file:org.jtalks.jcommune.web.controller.migration.PhpbbRedirectionController.java

/**
 * http://www.javatalks.ru/ftopic2036-0.php
 * http://www.javatalks.ru/ftopic2036-0.php/topicname
 * @param topicParams example ftopic2036-0, where the last number is page, which is ignored in our case
 * @param response http response object to set headers on
 * @param request http request to figure out the context path
 *///from  ww  w .j  ava 2  s.c  o m
@RequestMapping({ "/ftopic{topicParams}", "/ftopic{topicParams}.php", "/ftopic{topicParams}/**",
        "/ftopic{topicParams}.php/**" })
public void showFtopicWithAdditionalParams(@PathVariable String topicParams, HttpServletResponse response,
        WebRequest request) {
    String id = StringUtils.substringBefore(topicParams, "-");
    String redirectUrl = request.getContextPath() + "/topics/" + id;
    setHttp301Headers(response, redirectUrl);
}

From source file:org.jtalks.jcommune.web.controller.migration.PhpbbRedirectionController.java

/**
 * Redirect topic URLs to, assumes that topic ids
 * haven't been changed during migration. 
 * /* www  .  j a v  a 2s .  c om*/
 * @param topicParams contains topic id and additional info(it will be ignored)
 * @param response http response object to set headers on
 * @param request http request to figure out the context path
 */
@RequestMapping("/topics/{topicParams}.php")
public void showTopicWithAdditionalParams(@PathVariable String topicParams, HttpServletResponse response,
        WebRequest request) {
    String id = StringUtils.substringBefore(topicParams, "-");
    String redirectUrl = request.getContextPath() + "/topics/" + id;
    setHttp301Headers(response, redirectUrl);
}

From source file:org.jtalks.jcommune.web.controller.migration.PhpbbRedirectionController.java

/**
 * Redirects post URLs, assumes that post ids
 * haven't been changed during data migration
 *
 * @param id post identifier from url/*from  w  ww . j  a  v a2s. c om*/
 * @param response http response object to set headers on
 * @param request http request to figure out the context path
 */
@RequestMapping({ "/sutra{id}.php", "/sutra{id}" })
public void showPost(@PathVariable String id, HttpServletResponse response, WebRequest request) {
    String redirectUrl = request.getContextPath() + "/posts/" + id;
    setHttp301Headers(response, redirectUrl);
}

From source file:org.jtalks.jcommune.web.controller.migration.PhpbbRedirectionController.java

/**
 * Redirects branch URL's, assumes that bramch ids
 * haven't been changed during data migration
 *
 * @param id branch identifier from url/*w ww  . j a  v a  2s . c  o  m*/
 * @param response http response object to set headers on
 * @param request http request to figure out the context path
 */
@RequestMapping("/forum{id}.php")
public void showBranch(@PathVariable String id, HttpServletResponse response, WebRequest request) {
    String redirectUrl = request.getContextPath() + "/branches/" + id;
    setHttp301Headers(response, redirectUrl);
}

From source file:org.jtalks.jcommune.web.controller.migration.PhpbbRedirectionController.java

/**
 * Redirects branch URL's, assumes that branch ids haven't been changed during data migration. Redirects always to
 * the first page of the branch even if page was specified in params.
 *
 * @param id branch identifier from url, but also may contain the page number which will be ignored
 * @param response http response object to set headers on
 * @param request http request to figure out the context path
 *//* w w w.  jav  a  2 s. co m*/
@RequestMapping("/viewforum{branchParams}.php")
public void showBranchWithViewPrefix(@PathVariable String branchParams, HttpServletResponse response,
        WebRequest request) {
    String id = StringUtils.substringBefore(branchParams, "-");
    String redirectUrl = request.getContextPath() + "/branches/" + id;
    setHttp301Headers(response, redirectUrl);
}

From source file:org.jtalks.jcommune.web.controller.migration.PhpbbRedirectionController.java

/**
 * Redirects search URL's to default search page
 *
 * @param response http response object to set headers on
 * @param request http request to figure out the context path
 *//*from w ww. j a  v a 2 s. co m*/
@RequestMapping("/search.php")
public void showSearch(HttpServletResponse response, WebRequest request) {
    String redirectUrl = request.getContextPath() + "/search/?searchText=";
    setHttp301Headers(response, redirectUrl);
}