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:org.opendatakit.api.forms.FormService.java

@POST
@ApiOperation(value = "Upload a zipped form definition as multipart/form-data.", response = FormUploadResult.class)
@Consumes({ MediaType.MULTIPART_FORM_DATA })
@Produces({ MediaType.APPLICATION_JSON, ApiConstants.MEDIA_TEXT_XML_UTF8,
        ApiConstants.MEDIA_APPLICATION_XML_UTF8 })
@Path("{appId}/{odkClientVersion}")
public Response doPost(@Context HttpServletRequest req, @Context HttpServletResponse resp,
        @PathParam("odkClientVersion") String odkClientVersion, @PathParam("appId") String appId,
        @Context UriInfo info) throws IOException {
    logger.debug("Uploading...");
    ServiceUtils.examineRequest(req.getServletContext(), req);

    req.getContentLength();//  w w  w.  ja  v a2 s.co  m
    if (!ServletFileUpload.isMultipartContent(req)) {
        throw new WebApplicationException(ErrorConsts.NO_MULTI_PART_CONTENT,
                HttpServletResponse.SC_BAD_REQUEST);
    }

    try {
        TablesUserPermissions userPermissions = ContextUtils.getTablesUserPermissions(callingContext);
        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(req);
        Map<String, byte[]> files = null;
        String tableId = null;
        List<String> regionalOffices = new ArrayList<>();

        // unzipping files

        for (FileItem item : items) {

            // Retrieve all Regional Office IDs to which a form definition
            // is going to be assigned to
            if (item.getFieldName().equals(WebConsts.OFFICE_ID)) {
                regionalOffices.add(item.getString());
            }

            String fieldName = item.getFieldName();
            String fileName = FilenameUtils.getName(item.getName());

            if (fieldName.equals(WebConsts.ZIP_FILE)) {
                if (fileName == null || !(fileName.endsWith(".zip"))) {
                    throw new WebApplicationException(ErrorConsts.NO_ZIP_FILE,
                            HttpServletResponse.SC_BAD_REQUEST);
                }

                InputStream fileStream = item.getInputStream();
                ZipInputStream zipStream = new ZipInputStream(fileStream);
                files = processZipInputStream(zipStream);
            }
        }

        tableId = getTableIdFromFiles(files);

        FormUploadResult formUploadResult = uploadFiles(odkClientVersion, appId, tableId, userPermissions,
                files, regionalOffices);

        FileManifestManager manifestManager = new FileManifestManager(appId, odkClientVersion, callingContext);
        OdkTablesFileManifest manifest = manifestManager.getManifestForTable(tableId);
        FileManifestService.fixDownloadUrls(info, appId, odkClientVersion, manifest);

        formUploadResult.setManifest(manifest);
        String eTag = Integer.toHexString(manifest.hashCode()); // Is this
                                                                // right?

        return Response.status(Status.CREATED).entity(formUploadResult).header(HttpHeaders.ETAG, eTag)
                .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
                .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true")
                .build();

    } catch (FileUploadException | ODKDatastoreException | ODKTaskLockException | PermissionDeniedException
            | TableAlreadyExistsException e) {
        logger.error("Error uploading zip", e);
        throw new WebApplicationException(ErrorConsts.PERSISTENCE_LAYER_PROBLEM + "\n" + e.toString(),
                HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

    }
}

From source file:com.cpjit.swagger4j.DefaultConfigResolver.java

private Properties loadConfig(HttpServletRequest request) throws IOException {
    Properties props = new Properties();
    InputStream is = ResourceUtil.getResourceAsStream(configFile);
    props.load(is);//ww w.ja  va2 s  . c  o  m
    String path = request.getContextPath();
    String host = request.getServerName() + ":" + request.getServerPort() + path;
    props.setProperty("apiHost", host);
    String apiFile = props.getProperty("apiFile");
    if (StringUtils.isBlank(apiFile)) {
        apiFile = Constants.DEFAULT_API_FILE;
    }
    String apiFilePath = request.getServletContext().getRealPath(apiFile);
    props.setProperty("apiFile", apiFilePath);
    String suffix = props.getProperty("suffix");
    if (StringUtils.isBlank(suffix)) {
        suffix = "";
    }
    props.put("suffix", suffix);
    return props;
}

From source file:pages.NewClaim.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w  w  w.jav a 2 s.  c o  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    HttpSession session = request.getSession(false);

    String[] query = new String[3];

    query[0] = (String) request.getParameter("rationale").trim();
    query[1] = (String) request.getParameter("amount");
    query[2] = (String) request.getParameter("UserID");

    Jdbc jdbc = new Jdbc();

    jdbc.connect((Connection) request.getServletContext().getAttribute("connection"));
    session.setAttribute("dbbean", jdbc);

    if (jdbc == null)
        request.getRequestDispatcher("/WEB-INF/conErr.jsp").forward(request, response);

    else {
        jdbc.insertNewClaim(query);
        request.setAttribute("message", "A claim has been made: " + query[0] + " The amount is: " + query[1]);
    }

    request.getRequestDispatcher("/WEB-INF/user.jsp").forward(request, response);
}

From source file:io.lavagna.web.support.ResourceController.java

@RequestMapping(value = "/css/all-{version:.+}.css", method = RequestMethod.GET)
public void handleCss(HttpServletRequest request, HttpServletResponse response) throws IOException {

    if (contains(env.getActiveProfiles(), "dev") || cssCache.get() == null) {
        ByteArrayOutputStream cssOs = new ByteArrayOutputStream();
        ServletContext context = request.getServletContext();
        BeforeAfter ba = new BeforeAfter();

        //make sure we add the css in the right order
        concatenateResourcesWithExtension(context, "/css/", ".css", cssOs, ba);
        concatenateResourcesWithExtension(context, "/app/ui/", ".css", cssOs, ba);
        concatenateResourcesWithExtension(context, "/app/components/", ".css", cssOs, ba);

        cssCache.set(cssOs.toByteArray());
    }/*from  www . java 2s  .c o m*/

    try (OutputStream os = response.getOutputStream()) {
        response.setContentType("text/css");
        StreamUtils.copy(cssCache.get(), os);
    }
}

From source file:com.cpjit.swagger4j.support.struts2.ApiAction.java

private Properties loadSettings(HttpServletRequest request) throws IOException {
    Properties props = new Properties();
    InputStream is = ResourceUtil.getResourceAsStream("swagger.properties");
    props.load(is);//from   w  w w .  ja  v  a2s . co m
    String path = request.getContextPath();
    String host = request.getServerName() + ":" + request.getServerPort() + path;
    props.setProperty("apiHost", host);
    String apiFile = props.getProperty("apiFile");
    if (StringUtils.isBlank(apiFile)) {
        apiFile = DEFAULT_API_FILE;
    }
    String apiFilePath = request.getServletContext().getRealPath(apiFile);
    props.setProperty("apiFile", apiFilePath);
    if (StringUtils.isBlank(props.getProperty("devMode"))) {
        props.setProperty("devMode", devMode);
    }
    String suffix = props.getProperty("suffix");
    if (StringUtils.isBlank(suffix)) {
        suffix = "";
    }
    props.put("suffix", suffix);
    return props;
}

From source file:app.controller.ResourceController.java

@GetMapping(value = "/download/{resourceType:.*}")
public void download(HttpServletRequest request, HttpServletResponse response, @RequestParam String filename,
        @PathVariable int resourceType) throws IOException {
    logger.info("---------------download resource-----------------");
    FileResource resource = new FileResource();
    int result = resourceService.download(filename, resourceType, resource);
    if (result != BaseResponse.COMMON_SUCCESS) {
        throw new ResourceNotFoundException();
    }/*from  ww  w  .j a v  a 2 s.co  m*/
    File file = resource.file;

    // get MIME type of the file
    ServletContext context = request.getServletContext();
    String mimeType = context.getMimeType(filename);
    if (mimeType == null) {
        mimeType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
    }

    response.setContentType(mimeType);
    response.setContentLength((int) file.length());
    response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename);

    BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
    FileCopyUtils.copy(new BufferedInputStream(new FileInputStream(file)), out);
}

From source file:io.lavagna.web.api.SetupController.java

@RequestMapping(value = "/setup/api/import", method = RequestMethod.POST)
public void importLavagna(@RequestParam("file") MultipartFile file, HttpServletRequest req,
        HttpServletResponse res) throws IOException {

    // TODO: move to a helper, as it has the same code as the one in the ExportImportController
    Path tempFile = Files.createTempFile(null, null);
    try {//from  w w w. j  a  va 2 s .  co m
        try (InputStream is = file.getInputStream(); OutputStream os = Files.newOutputStream(tempFile)) {
            StreamUtils.copy(is, os);
        }
        exportImportService2.importData(true, tempFile);
    } finally {
        Files.delete(tempFile);
    }
    //

    res.sendRedirect(req.getServletContext().getContextPath());
}

From source file:se.inera.certificate.proxy.mappings.local.LocalDispatcher.java

@Override
public void dispatch(HttpServletRequest request, HttpServletResponse response) {
    // Request path without servlet context path.
    String requestPath = getPath(request);

    // The new path to forward to including the new servlet context path.
    String newUri = joinFragments(localMapping.getMappedPath(),
            substringAfter(requestPath, localMapping.getContext()));

    // The context path of the 'forwarded to' servlet.
    String servletContextPath = getFirstSegment(newUri);

    // Servlet context of the 'forwarded to' servlet.
    ServletContext context = request.getServletContext().getContext(servletContextPath);

    // Get a request dispatcher for the new URL.
    RequestDispatcher requestDispatcher = context
            .getRequestDispatcher(StringUtils.substringAfter(newUri, servletContextPath));

    LocalRequestWrapper w = new LocalRequestWrapper(request);

    for (Map.Entry<String, String> header : getRequestContext().getHeaders(request).entrySet()) {
        w.addHeader(header.getKey(), header.getValue());
    }/*from  w  w w.  ja  v  a  2 s. co  m*/

    try {
        requestDispatcher.forward(w, response);
    } catch (ServletException e) {
        Throwables.propagate(e);
    } catch (IOException e) {
        Throwables.propagate(e);
    }
}

From source file:eu.europa.ec.fisheries.uvms.reporting.rest.resources.ReportingResource.java

/**
 * lazy loading of the app name from the web.xml
 *
 * @param request/*from  w ww .ja  v a 2s  .  c o m*/
 * @return
 */
private String getApplicationName(HttpServletRequest request) {
    if (applicationName == null) {
        applicationName = request.getServletContext().getInitParameter(USM_APPLICATION);
    }
    return applicationName;
}

From source file:alpine.servlets.FileSystemResourceServlet.java

@Override
protected StaticResource getStaticResource(HttpServletRequest request) throws IllegalArgumentException {
    final String pathInfo = request.getPathInfo();

    if (pathInfo == null || pathInfo.isEmpty() || "/".equals(pathInfo)) {
        throw new IllegalArgumentException();
    }//from   w w w  .  j a v  a  2 s .  c  o m

    String name = "";
    try {
        name = URLDecoder.decode(pathInfo.substring(1), StandardCharsets.UTF_8.name());
    } catch (UnsupportedEncodingException e) {
        LOGGER.error(e.getMessage());
    }

    final ServletContext context = request.getServletContext();
    final File file = (absolute) ? new File(directory, name)
            : new File(context.getRealPath("/"), name).getAbsoluteFile();

    return !file.exists() ? null : new StaticResource() {
        @Override
        public long getLastModified() {
            return file.lastModified();
        }

        @Override
        public InputStream getInputStream() throws IOException {
            return new FileInputStream(file);
        }

        @Override
        public String getFileName() {
            return file.getName();
        }

        @Override
        public long getContentLength() {
            return file.length();
        }
    };
}