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

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

Introduction

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

Prototype

@Nullable
String getHeader(String headerName);

Source Link

Document

Return the request header of the given name, or null if none.

Usage

From source file:br.com.mv.modulo.utils.AjaxUtils.java

public static boolean isAjaxRequest(WebRequest webRequest) {
    String requestedWith = webRequest.getHeader("X-Requested-With");
    return requestedWith != null ? "XMLHttpRequest".equals(requestedWith) : false;
}

From source file:org.mytms.common.web.util.RequestUtil.java

/**
 * Get header or url parameter.    Will obtain the parameter from a header variable or a URL parameter, preferring
 * header values if they are set.// w w w . ja  v  a 2s  .c o m
 */
public static String getURLorHeaderParameter(WebRequest request, String varName) {
    String returnValue = request.getHeader(varName);
    if (returnValue == null) {
        returnValue = request.getParameter(varName);
    }
    return returnValue;
}

From source file:net.noday.core.web.BaseController.java

@ExceptionHandler
public ModelAndView resolveException(Exception e, WebRequest req) {
    log.error(e.getMessage(), e);/*  ww  w.j av  a2  s.c om*/
    ModelAndView m = new ModelAndView("error/500");
    m.addObject("href", req.getHeader("referer"));
    responseMsg(m, false, e.getMessage());
    return m;
}

From source file:org.openmrs.module.dhisreport.web.controller.LocationMappingController.java

@RequestMapping(value = "/module/dhisreport/mapLocations", method = RequestMethod.POST)
public String mapLocations(ModelMap model,
        @RequestParam(value = "DHIS2OrgUnits", required = true) String dhis2OrgUnitCode,
        @RequestParam(value = "openmrsLocations", required = true) String openmrsLocationName,
        WebRequest webRequest) {
    System.out.println("org unit does not  exits and it is : " + dhis2OrgUnitCode);
    String referer = webRequest.getHeader("Referer");

    if (dhis2OrgUnitCode.equals("")) {
        System.out.println("org unit does not  exits");
        webRequest.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                Context.getMessageSourceService().getMessage("dhisreport.orgUnitCodeDoesNotExist"),
                WebRequest.SCOPE_SESSION);
        return "redirect:" + referer;
    }// w  w w .  j  a va2  s. c  o m
    List<Location> locationList = new ArrayList<Location>();
    locationList.addAll(Context.getLocationService().getAllLocations());
    Location loc = Context.getLocationService().getLocation(openmrsLocationName);
    if (loc == null) {
        webRequest.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                Context.getMessageSourceService().getMessage("dhisreport.openMRSLocationDoesNotExist"),
                WebRequest.SCOPE_SESSION);
        return "redirect:" + referer;
    }

    List<LocationAttributeType> attributeTypes = Context.getLocationService().getAllLocationAttributeTypes();
    for (LocationAttributeType lat : attributeTypes) {
        if (lat.getName().equals("CODE")) {
            LocationAttribute locationAttribute = new LocationAttribute();
            locationAttribute.setAttributeType(lat);
            locationAttribute.setValue(dhis2OrgUnitCode);
            loc.setAttribute(locationAttribute);
            Context.getLocationService().saveLocation(loc);
            webRequest.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                    Context.getMessageSourceService().getMessage("dhisreport.openMRSLocationMapped"),
                    WebRequest.SCOPE_SESSION);
            return "redirect:" + referer;
        }
    }
    LocationAttributeType attributetype = new LocationAttributeType();
    attributetype.setName("CODE");
    attributetype.setDescription("Corresponding Value of ORG UNITS for DHIS");
    attributetype.setMinOccurs(0);
    attributetype.setMaxOccurs(1);
    attributetype.setDatatypeClassname("org.openmrs.customdatatype.datatype.FreeTextDatatype");
    Context.getLocationService().saveLocationAttributeType(attributetype);

    LocationAttribute locationAttribute = new LocationAttribute();
    locationAttribute.setAttributeType(attributetype);
    locationAttribute.setValue(dhis2OrgUnitCode);
    loc.setAttribute(locationAttribute);
    Context.getLocationService().saveLocation(loc);
    webRequest.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
            Context.getMessageSourceService().getMessage("dhisreport.openMRSLocationMapped"),
            WebRequest.SCOPE_SESSION);
    return "redirect:" + referer;

}

From source file:org.openmrs.module.dhisreport.web.controller.ReportDefinitionController.java

@RequestMapping(value = "/module/dhisreport/getReportDefinitions", method = RequestMethod.POST)
public String getReportDefinitions(WebRequest webRequest, HttpServletRequest request) {
    String username = Context.getAdministrationService().getGlobalProperty("dhisreport.dhis2UserName");
    String password = Context.getAdministrationService().getGlobalProperty("dhisreport.dhis2Password");
    String dhisurl = Context.getAdministrationService().getGlobalProperty("dhisreport.dhis2URL");
    String url = dhisurl + "/api/dataSets";
    //String url = "https://play.dhis2.org/demo/api/dataSets";
    String referer = webRequest.getHeader("Referer");
    HttpSession session = request.getSession();

    try {// w  ww.  j  a v a 2  s.  co m
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet getRequest = new HttpGet(url);
        getRequest.addHeader("accept", "application/dsd+xml");
        getRequest.addHeader(
                BasicScheme.authenticate(new UsernamePasswordCredentials(username, password), "UTF-8", false));
        HttpResponse response = httpClient.execute(getRequest);

        if (response.getStatusLine().getStatusCode() != 200) {
            log.error("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }

        InputStream is = response.getEntity().getContent();
        try {
            DHIS2ReportingService service = Context.getService(DHIS2ReportingService.class);
            service.unMarshallandSaveReportTemplates(is);
            session.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                    Context.getMessageSourceService().getMessage("dhisreport.uploadSuccess"));
        } catch (Exception ex) {
            log.error("Error loading file: " + ex);
            session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                    Context.getMessageSourceService().getMessage("dhisreport.uploadError"));
        } finally {
            is.close();
        }
        httpClient.getConnectionManager().shutdown();
        return "redirect:" + referer;
    } catch (ClientProtocolException ee) {
        log.debug("An error occured in the HTTP protocol." + ee.toString());
        ee.printStackTrace();
    } catch (IOException ee) {
        log.debug("Problem accessing DHIS2 server: " + ee.toString());
        session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                Context.getMessageSourceService().getMessage("dhisreport.checkConnectionWithDHIS2"));
    }
    return "redirect:" + referer;
}

From source file:kz.supershiny.web.wicket.TiresApplication.java

protected WebResponse newWebResponse(final WebRequest webRequest,
        final HttpServletResponse httpServletResponse) {
    return new ServletWebResponse((ServletWebRequest) webRequest, httpServletResponse) {

        @Override/*from w ww . j  a  va2 s.c o  m*/
        public String encodeURL(CharSequence url) {
            return isRobot(webRequest) ? url.toString() : super.encodeURL(url);
        }

        @Override
        public String encodeRedirectURL(CharSequence url) {
            return isRobot(webRequest) ? url.toString() : super.encodeRedirectURL(url);
        }

        private boolean isRobot(WebRequest request) {
            final String agent = webRequest.getHeader("User-Agent");
            return isAgent(agent);
        }
    };
}

From source file:bjerne.gallery.controller.GalleryController.java

/**
 * Method used to return the binary of a gallery file (
 * {@link GalleryFile#getActualFile()} ). This method handles 304 redirects
 * (if file has not changed) and range headers if requested by browser. The
 * range parts is particularly important for videos. The correct response
 * status is set depending on the circumstances.
 * <p>//w  ww . j  av a 2 s.  c  o  m
 * NOTE: the range logic should NOT be considered a complete implementation
 * - it's a bare minimum for making requests for byte ranges work.
 * 
 * @param request
 *            Request
 * @param galleryFile
 *            Gallery file
 * @return The binary of the gallery file, or a 304 redirect, or a part of
 *         the file.
 * @throws IOException
 *             If there is an issue accessing the binary file.
 */
private ResponseEntity<InputStreamResource> returnResource(WebRequest request, GalleryFile galleryFile)
        throws IOException {
    LOG.debug("Entering returnResource()");
    if (request.checkNotModified(galleryFile.getActualFile().lastModified())) {
        return null;
    }
    File file = galleryFile.getActualFile();
    String contentType = galleryFile.getContentType();
    String rangeHeader = request.getHeader(HttpHeaders.RANGE);
    long[] ranges = getRangesFromHeader(rangeHeader);
    long startPosition = ranges[0];
    long fileTotalSize = file.length();
    long endPosition = ranges[1] != 0 ? ranges[1] : fileTotalSize - 1;
    long contentLength = endPosition - startPosition + 1;
    LOG.debug("contentLength: {}, file length: {}", contentLength, fileTotalSize);

    LOG.debug("Returning resource {} as inputstream. Start position: {}", file.getCanonicalPath(),
            startPosition);
    InputStream boundedInputStream = new BoundedInputStream(new FileInputStream(file), endPosition + 1);

    InputStream is = new BufferedInputStream(boundedInputStream, 65536);
    InputStreamResource inputStreamResource = new InputStreamResource(is);
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentLength(contentLength);
    responseHeaders.setContentType(MediaType.valueOf(contentType));
    responseHeaders.add(HttpHeaders.ACCEPT_RANGES, "bytes");
    if (StringUtils.isNotBlank(rangeHeader)) {
        is.skip(startPosition);
        String contentRangeResponseHeader = "bytes " + startPosition + "-" + endPosition + "/" + fileTotalSize;
        responseHeaders.add(HttpHeaders.CONTENT_RANGE, contentRangeResponseHeader);
        LOG.debug("{} was not null but {}. Adding header {} to response: {}", HttpHeaders.RANGE, rangeHeader,
                HttpHeaders.CONTENT_RANGE, contentRangeResponseHeader);
    }
    HttpStatus status = (startPosition == 0 && contentLength == fileTotalSize) ? HttpStatus.OK
            : HttpStatus.PARTIAL_CONTENT;
    LOG.debug("Returning {}. Status: {}, content-type: {}, {}: {}, contentLength: {}", file, status,
            contentType, HttpHeaders.CONTENT_RANGE, responseHeaders.get(HttpHeaders.CONTENT_RANGE),
            contentLength);
    return new ResponseEntity<InputStreamResource>(inputStreamResource, responseHeaders, status);
}

From source file:org.openmrs.module.dhisreport.web.controller.Dhis2ServerController.java

@RequestMapping(value = "/module/dhisreport/testconnection", method = RequestMethod.POST)
public String CheckConnectionWithDHIS2(ModelMap model, WebRequest webRequest) {
    DHIS2ReportingService service = Context.getService(DHIS2ReportingService.class);
    HttpDhis2Server server = service.getDhis2Server();
    String dhisurl = Context.getAdministrationService().getGlobalProperty("dhisreport.dhis2URL");
    String dhisusername = Context.getAdministrationService().getGlobalProperty("dhisreport.dhis2UserName");
    String dhispassword = Context.getAdministrationService().getGlobalProperty("dhisreport.dhis2Password");

    URL url = null;/*from  w ww.  j  a  v  a2s . com*/
    try {
        url = new URL(dhisurl);
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    boolean val = testConnection(url, dhisusername, dhispassword, server, webRequest, model);

    String referer = webRequest.getHeader("Referer");

    if (val == false) {
        webRequest.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                Context.getMessageSourceService().getMessage("dhisreport.dhis2ConnectionFailure"),
                WebRequest.SCOPE_SESSION);
        return "redirect:" + referer;
    }
    webRequest.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
            Context.getMessageSourceService().getMessage("dhisreport.dhis2ConnectionSuccess"),
            WebRequest.SCOPE_SESSION);
    return "redirect:" + referer;
}

From source file:org.openmrs.module.dhisreport.web.controller.ReportController.java

@RequestMapping(value = "/module/dhisreport/executeReport", method = RequestMethod.POST)
public String executeReport(ModelMap model,
        @RequestParam(value = "reportDefinition_id", required = true) Integer reportDefinition_id,
        @RequestParam(value = "location", required = false) String OU_Code,
        @RequestParam(value = "resultDestination", required = true) String destination,
        @RequestParam(value = "date", required = true) String dateStr,
        @RequestParam(value = "frequency", required = true) String freq,
        @RequestParam(value = "prior", required = true) String prior, WebRequest webRequest,
        HttpServletRequest request) throws Exception {
    DHIS2ReportingService service = Context.getService(DHIS2ReportingService.class);
    Period period = null;//from w w  w  .  j a  va  2s.c om
    //System.out.println( "freeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee" + freq );
    //System.out.println( "dasdasssssssssssssssssssss" + dateStr );

    if (freq.equalsIgnoreCase("monthly")) {
        if (dateStr.length() > 7)
            dateStr = replacedateStrMonth(dateStr);
        dateStr = dateStr.concat("-01");
        try {
            //System.out.println( "helloooooooooo1=====" + dateStr );
            period = new MonthlyPeriod(new SimpleDateFormat("yyyy-MM-dd").parse(dateStr));
            // System.out.println( "helloooooooooo2=====" + period );
        } catch (ParseException pex) {
            log.error("Cannot convert passed string to date... Please check dateFormat", pex);
            webRequest.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                    Context.getMessageSourceService().getMessage("Date Parsing Error"),
                    WebRequest.SCOPE_SESSION);
            return null;
        }
    }
    if (freq.equalsIgnoreCase("weekly")) {
        try {
            String finalweek = "";
            String[] modify_week = dateStr.split("W");
            Integer weekvalue = Integer.parseInt(dateStr.substring(dateStr.indexOf('W') + 1)) + 1;
            if (weekvalue > 9) {
                weekvalue = weekvalue == 54 ? 53 : weekvalue;
                finalweek = modify_week[0].concat("W" + weekvalue.toString());
            } else {
                finalweek = modify_week[0].concat("W0" + weekvalue.toString());
            }

            period = new WeeklyPeriod(new SimpleDateFormat("yyyy-'W'ww").parse(finalweek));
        } catch (ParseException ex) {
            log.error("Cannot convert passed string to date... Please check dateFormat", ex);
            webRequest.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                    Context.getMessageSourceService().getMessage("Date Parsing Error"),
                    WebRequest.SCOPE_SESSION);
            return null;
        }
    }
    if (freq.equalsIgnoreCase("daily")) {

        webRequest.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                Context.getMessageSourceService().getMessage("dhisreport.dateFormatError"),
                WebRequest.SCOPE_SESSION);
        return null;

    }

    // Get Location by OrgUnit Code
    //Location location = service.getLocationByOU_Code( OU_Code );
    // System.out.println( "helloooooooooo3=====" + period );
    List<DataValueSet> dvsList = new ArrayList<DataValueSet>();
    List<Location> locationList = new ArrayList<Location>();
    List<Location> locationListFinal = new ArrayList<Location>();
    //locationList.add( location );
    //locationList.add( service.getLocationByOU_Code( "Gahombo" ) );
    locationList.addAll(Context.getLocationService().getAllLocations());

    //remove locations without Organization Unit codes
    for (Location l : locationList) {
        for (LocationAttribute la : l.getActiveAttributes()) {
            if (la.getAttributeType().getName().equals("CODE")) {
                //System.out.println( "Name-----" + la.getAttributeType().getName() + "Value---" + la.getValue() );
                if (!la.getValue().toString().isEmpty() && la.getValue().toString() != null) {
                    locationListFinal.add(l);
                    break;
                }

            }

        }
    }

    Map<String, Map> desetList = new HashMap<String, Map>();
    List<AggregatedResultSet> aggregatedList = new ArrayList<AggregatedResultSet>();
    if (locationListFinal.isEmpty() && !locationList.isEmpty()) {
        log.error("Location attribute CODE not set");
        request.getSession().setAttribute("errorMessage",
                "Please set location attribute CODE to generate results.");
        String referer = webRequest.getHeader("Referer");
        return "redirect:" + referer;
    }

    boolean priority = false;
    if (prior.equals("report")) {
        priority = true;
    }

    for (Location l : locationListFinal) {
        AggregatedResultSet agrs = new AggregatedResultSet();
        DataValueSet dvs = service.evaluateReportDefinition(service.getReportDefinition(reportDefinition_id),
                period, l, priority);
        for (LocationAttribute la : l.getActiveAttributes()) {
            if (la.getAttributeType().getName().equals("CODE"))
                dvs.setOrgUnit(la.getValue().toString());
        }
        // Set OrgUnit code into DataValueSet

        List<DataValue> datavalue = dvs.getDataValues();
        Map<DataElement, String> deset = new HashMap<DataElement, String>();
        for (DataValue dv : datavalue) {

            DataElement detrmp = service.getDataElementByCode(dv.getDataElement());
            // System.out.println( detrmp.getName() + detrmp.getCode() );
            deset.put(detrmp, dv.getValue());
        }
        agrs.setDataValueSet(dvs);
        agrs.setDataElementMap(deset);
        AdxType adxType = getAdxType(dvs, dateStr);

        if (destination.equals("post")) {
            ImportSummaries importSummaries = Context.getService(DHIS2ReportingService.class)
                    .postAdxReport(adxType);
            agrs.setImportSummaries(importSummaries);
        }
        aggregatedList.add(agrs);
    }

    org.openmrs.module.reporting.report.definition.ReportDefinition rrd = Context
            .getService(ReportDefinitionService.class)
            .getDefinitionByUuid(service.getReportDefinition(reportDefinition_id).getReportingReportId());

    Map<String, Object> param = new HashMap<String, Object>();
    param.put("startDate", period.getStartDate());
    param.put("endDate", period.getEndDate());
    if (rrd != null) {
        ReportRequest rq = new ReportRequest();
        rq.setReportDefinition(
                new Mapped<org.openmrs.module.reporting.report.definition.ReportDefinition>(rrd, param));
        rq.setRenderingMode(new RenderingMode(new DefaultWebRenderer(), "Web", null, 100));
        Report report = Context.getService(ReportService.class).runReport(rq);
        model.addAttribute("resultUuid", rq.getUuid());
    } else {
        model.addAttribute("resultUuid", null);
    }
    model.addAttribute("user", Context.getAuthenticatedUser());
    model.addAttribute("aggregatedList", aggregatedList);
    return null;
}