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:com.Uploader.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new ServletException("Content type is not multipart/form-data");
    }/*from  www .  j ava2  s .  c  o m*/

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.write("<html><head></head><body>");
    try {
        List<FileItem> fileItemsList = uploader.parseRequest(request);
        Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
        while (fileItemsIterator.hasNext()) {
            FileItem fileItem = fileItemsIterator.next();
            System.out.println("FieldName=" + fileItem.getFieldName());
            System.out.println("FileName=" + fileItem.getName());
            System.out.println("ContentType=" + fileItem.getContentType());
            System.out.println("Size in bytes=" + fileItem.getSize());
            File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator
                    + fileItem.getName());
            System.out.println("Absolute Path at server=" + file.getAbsolutePath());
            fileItem.write(file);
            out.write("File " + fileItem.getName() + " uploaded successfully.");
            out.write("<br>");
            out.write("<a href=\"Uploader?fileName=" + fileItem.getName() + "\">Download " + fileItem.getName()
                    + "</a>");
        }
    } catch (FileUploadException e) {
        out.write("Exception in uploading file.");
        e.printStackTrace();
    } catch (Exception e) {
        out.write("Exception in uploading file.");
        e.printStackTrace();
    }
    out.write("</body></html>");
}

From source file:io.hops.hopsworks.api.user.AuthService.java

@POST
@Path("login")
@Produces(MediaType.APPLICATION_JSON)/* w w w  .  j  a v  a2 s .c  o m*/
public Response login(@FormParam("email") String email, @FormParam("password") String password,
        @FormParam("otp") String otp, @Context HttpServletRequest req) throws UserException {
    logUserLogin(req);
    RESTApiJsonResponse json = new RESTApiJsonResponse();
    if (email == null || email.isEmpty()) {
        throw new IllegalArgumentException("Email was not provided");
    }
    Users user = userFacade.findByEmail(email);
    // Do pre cauth realm check
    String passwordWithSaltPlusOtp = authController.preCustomRealmLoginCheck(user, password, otp, req);

    // logout any user already loggedin if a new user tries to login 
    if (req.getRemoteUser() != null && !req.getRemoteUser().equals(email)) {
        logoutAndInvalidateSession(req);
    }
    //only login if not already logged...
    if (req.getRemoteUser() == null) {
        login(user, email, passwordWithSaltPlusOtp, req);
    } else {
        req.getServletContext().log("Skip logged because already logged in: " + email);
    }

    //read the user data from db and return to caller
    json.setSessionID(req.getSession().getId());

    return noCacheResponse.getNoCacheResponseBuilder(Response.Status.OK).entity(json).build();
}

From source file:cpabe.controladores.UploadDownloadFileAdvancedServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new ServletException("Content type is not multipart/form-data");
    }/*from  w w w.  j av a 2s  .co m*/

    // response.setContentType("text/html");
    //  PrintWriter out = response.getWriter();
    // out.write("<html><head></head><body>");
    try {
        List<FileItem> fileItemsList = uploader.parseRequest(request);
        Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
        while (fileItemsIterator.hasNext()) {
            FileItem fileItem = fileItemsIterator.next();

            System.out.println("FieldName=" + fileItem.getFieldName());
            System.out.println("FileName=" + fileItem.getName());
            System.out.println("ContentType=" + fileItem.getContentType());
            System.out.println("Size in bytes=" + fileItem.getSize());

            File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator
                    + fileItem.getName());
            //setar no objeto CaminhoArquivo os dados do arquivo anexado
            String caminho = file.getAbsolutePath();
            String nome = fileItem.getName();

            CaminhoArquivo c = new CaminhoArquivo();
            c.setNome(nome);
            c.setWay(caminho);

            request.setAttribute("caminho", c);
            System.out.println("caminho=" + caminho);
            System.out.println("nome=" + nome);

            System.out.println("Absolute Path at server=" + file.getAbsolutePath());
            fileItem.write(file);

            request.getRequestDispatcher("/avancado/encriptar/encriptar1.jsp").forward(request, response);

            // out.write("File " + fileItem.getName() + " uploaded successfully.");
            // out.write("<br>");
            // out.write("<a href=\"UploadDownloadFileServlet?fileName=" + fileItem.getName() + "\">Download " + fileItem.getName() + "</a>");
        }

    } catch (FileUploadException e) {
        //  out.write("Exception in uploading file.");
    } catch (Exception e) {
        //  out.write("Exception in uploading file.");
    }
    // out.write("</body></html>");
}

From source file:cpabe.controladores.UploadDownloadFileServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new ServletException("Content type is not multipart/form-data");
    }/*w w  w  . ja v a 2 s.  c o  m*/

    // response.setContentType("text/html");
    //  PrintWriter out = response.getWriter();
    // out.write("<html><head></head><body>");
    try {
        List<FileItem> fileItemsList = uploader.parseRequest(request);
        Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
        while (fileItemsIterator.hasNext()) {
            FileItem fileItem = fileItemsIterator.next();

            System.out.println("FieldName=" + fileItem.getFieldName());
            System.out.println("FileName=" + fileItem.getName());
            System.out.println("ContentType=" + fileItem.getContentType());
            System.out.println("Size in bytes=" + fileItem.getSize());

            File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator
                    + fileItem.getName());
            //setar no objeto CaminhoArquivo os dados do arquivo anexado
            String caminho = file.getAbsolutePath();
            String nome = fileItem.getName();

            CaminhoArquivo c = new CaminhoArquivo();
            c.setNome(nome);
            c.setWay(caminho);

            request.setAttribute("caminho", c);
            System.out.println("caminho=" + caminho);
            System.out.println("nome=" + nome);

            System.out.println("Absolute Path at server=" + file.getAbsolutePath());
            fileItem.write(file);

            request.getRequestDispatcher("/formularios/encriptar/encriptar1.jsp").forward(request, response);

            // out.write("File " + fileItem.getName() + " uploaded successfully.");
            // out.write("<br>");
            // out.write("<a href=\"UploadDownloadFileServlet?fileName=" + fileItem.getName() + "\">Download " + fileItem.getName() + "</a>");
        }

    } catch (FileUploadException e) {
        //  out.write("Exception in uploading file.");
    } catch (Exception e) {
        //  out.write("Exception in uploading file.");
    }
    // out.write("</body></html>");
}

From source file:utils.DBManager.java

public DBManager(HttpServletRequest request) throws SQLException {

    try {/*  w  w w. j a  v a2 s . co  m*/

        Class.forName("org.sqlite.JDBC", true, getClass().getClassLoader());
        String path = request.getServletContext().getRealPath("/");
        DBManager.con = DriverManager.getConnection(URL_PREFIX + path + DB_URL);
    } catch (ClassNotFoundException | SQLException e) {
        //throw new RuntimeException(e.toString(), e);
    }
}

From source file:servlets.GroupCreate.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from   w  ww. j  a va2 s.com*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        dbm = new DBManager(request);
    } catch (SQLException ex) {
        Logger.getLogger(GroupCreate.class.getName()).log(Level.SEVERE, null, ex);
    }
    HttpSession session = request.getSession();
    UserBean user = (UserBean) Support.getInSession(request, SessionUtils.USER);

    final String title = StringEscapeUtils.escapeHtml(request.getParameter(RequestUtils.GROUP_TITLE));
    String isPrivate = request.getParameter(RequestUtils.GROUP_PRIVATE);
    String[] usernames = request.getParameterValues(RequestUtils.USERCHECK);

    final List<Integer> users = new ArrayList<>();
    try {
        for (String username : usernames) {
            users.add(dbm.getIdFromUser(username));
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    final int groupId = addGroup(title, isPrivate, usernames, user);
    System.err.println(groupId);
    String path = request.getServletContext().getRealPath("/");
    File a = new File(path + "/files/" + groupId + "/");
    File b = new File(path + "/pdf/" + groupId + "/");
    a.mkdir();
    b.mkdir();

    new Thread(new Runnable() {

        @Override
        public void run() {
            MailUtils.sendMail(users, dbm, groupId, title);
        }
    }).start();

    Message msg = buildMessage(groupId, title);

    if (msg.getType() == Message.MessageType.ERROR) {
        setUsers(request);
        Support.forward(getServletContext(), request, response, "/creategroup.jsp", msg);
    } else {
        Support.forward(getServletContext(), request, response, "/home", msg);
    }
}

From source file:org.debux.webmotion.server.WebMotionServer.java

/**
 * Action management in the mapping/*from w w  w  .jav  a2  s .c  o m*/
 */
protected void doAction(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    long start = System.currentTimeMillis();

    // Create call context use in handler to get information on user request
    ServerContext serverContext = getServerContext(request);
    Call call = new Call(serverContext, request, response);

    // Apply config
    Mapping mapping = serverContext.getMapping();
    applyConfig(mapping, call);

    // Execute the main handler
    WebMotionHandler mainHandler = serverContext.getMainHandler();
    mainHandler.handle(mapping, call);

    // Register call in mbean
    ServerStats serverStats = serverContext.getServerStats();
    serverStats.registerCallTime(call, start);

    // Dispatch on servlet to manage websocket
    WebSocketInbound socket = (WebSocketInbound) request.getAttribute(WebSocketInbound.ATTRIBUTE_WEBSOCKET);
    if (socket != null) {
        ServletContext servletContext = request.getServletContext();
        RequestDispatcher dispatcher = servletContext.getNamedDispatcher(SERVLET_WEBSOCKET);
        dispatcher.forward(request, response);
    }
}

From source file:org.restcomm.connect.http.filters.FileCacheServlet.java

/**
 * Process the actual request.//from   w w  w . j a va  2  s. c o m
 *
 * @param request The request to be processed.
 * @param response The response to be created.
 * @param content Whether the request body should be written (GET) or not
 * (HEAD).
 * @throws IOException If something fails at I/O level.
 */
private void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content)
        throws IOException {
    // Validate the requested file ------------------------------------------------------------

    // Get requested file by path info.
    String requestedFile = request.getPathInfo();
    if (logger.isDebugEnabled()) {
        logger.debug("Requested path:" + requestedFile);
    }

    // Check if file is actually supplied to the request URL.
    if (requestedFile == null) {
        logger.debug("No file requested, return 404.");
        // Do your thing if the file is not supplied to the request URL.
        // Throw an exception, or send 404, or show default/warning page, or just ignore it.
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    Configuration rootConfiguration = (Configuration) request.getServletContext()
            .getAttribute(Configuration.class.getName());
    Configuration runtimeConfiguration = rootConfiguration.subset("runtime-settings");

    String basePath = runtimeConfiguration.getString("cache-path");
    int bufferSize = runtimeConfiguration.getInteger("cache-buffer-size", DEFAULT_BUFFER_SIZE);
    long expireTime = runtimeConfiguration.getLong("cache-expire-time", DEFAULT_EXPIRE_TIME);

    // URL-decode the file name (might contain spaces and on) and prepare file object.
    String fDecodedPath = URLDecoder.decode(requestedFile, "UTF-8");
    File file = new File(basePath, fDecodedPath);

    // Check if file actually exists in filesystem.
    if (!file.exists()) {
        logger.debug("Requested file not found, return 404.");
        // Do your thing if the file appears to be non-existing.
        // Throw an exception, or send 404, or show default/warning page, or just ignore it.
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Prepare some variables. The ETag is an unique identifier of the file.
    String fileName = file.getName();
    long length = file.length();
    long lastModified = file.lastModified();
    String eTag = fileName + "_" + length + "_" + lastModified;
    long expires = System.currentTimeMillis() + expireTime;

    // Validate request headers for caching ---------------------------------------------------
    // If-None-Match header should contain "*" or ETag. If so, then return 304.
    String ifNoneMatch = request.getHeader("If-None-Match");
    if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) {
        logger.debug("IfNoneMatch/Etag not matching, return 304.");
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        response.setHeader("ETag", eTag); // Required in 304.
        response.setDateHeader("Expires", expires); // Postpone cache with 1 week.
        return;
    }

    // If-Modified-Since header should be greater than LastModified. If so, then return 304.
    // This header is ignored if any If-None-Match header is specified.
    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) {
        logger.debug("IfModifiedSince not matching, return 304.");
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        response.setHeader("ETag", eTag); // Required in 304.
        response.setDateHeader("Expires", expires); // Postpone cache with 1 week.
        return;
    }

    // Validate request headers for resume ----------------------------------------------------
    // If-Match header should contain "*" or ETag. If not, then return 412.
    String ifMatch = request.getHeader("If-Match");
    if (ifMatch != null && !matches(ifMatch, eTag)) {
        logger.debug("ifMatch not matching, return 412.");
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // If-Unmodified-Since header should be greater than LastModified. If not, then return 412.
    long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
    if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) {
        logger.debug("ifUnmodifiedSince not matching, return 412.");
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // Prepare and initialize response --------------------------------------------------------
    // Get content type by file name and content disposition.
    String contentType = getServletContext().getMimeType(fileName);
    String disposition = "inline";

    // If content type is unknown, then set the default value.
    // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "application/octet-stream";
    }

    // If content type is text, expand content type with the one and right character encoding.
    if (contentType.startsWith("text")) {
        contentType += ";charset=UTF-8";
    } // Else, expect for images, determine content disposition. If content type is supported by
      // the browser, then set to inline, else attachment which will pop a 'save as' dialogue.
    else if (!contentType.startsWith("image")) {
        String accept = request.getHeader("Accept");
        disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment";
    }

    // Initialize response.
    response.reset();
    response.setBufferSize(bufferSize);
    response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
    response.setHeader("Accept-Ranges", "bytes");
    response.setHeader("ETag", eTag);
    response.setDateHeader("Last-Modified", lastModified);
    response.setDateHeader("Expires", expires);

    // Send requested file (part(s)) to client ------------------------------------------------
    // Prepare streams.
    FileInputStream input = null;
    OutputStream output = null;

    if (content) {
        logger.debug("Content requested,streaming.");
        // Open streams.
        input = new FileInputStream(file);
        output = response.getOutputStream();
        long streamed = stream(input, output, bufferSize);
        if (logger.isDebugEnabled()) {
            logger.debug("Bytes streamed:" + streamed);
        }
    }

}

From source file:com.github.cxt.Myjersey.jerseycore.FileResource.java

@Path("upload2")
@POST//from   www.j  ava 2  s. c  o m
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public String uploadFile(@Context HttpServletRequest request) throws IOException {
    //??,httpclent?
    System.out.println(request.getCharacterEncoding());
    ServletFileUpload upload = new ServletFileUpload();
    upload.setHeaderEncoding(CHARSET);
    try {
        FileItemIterator fileIterator = upload.getItemIterator(request);
        while (fileIterator.hasNext()) {
            FileItemStream item = fileIterator.next();
            InputStream is = item.openStream();
            try {
                if (!item.isFormField()) {
                    String fileName = item.getName();
                    if (fileName == null || fileName.trim().equals("")) {
                        continue;
                    }
                    String name = Calendar.getInstance().getTimeInMillis() + fileName;
                    String path = request.getServletContext().getRealPath("/");
                    path += File.separator + "data" + File.separator + name;
                    File file = new File(path);
                    FileUtils.copyInputStreamToFile(is, file);
                } else {
                    System.out.println(Streams.asString(is, CHARSET));
                }
            } finally {
                if (null != is) {
                    try {
                        is.close();
                    } catch (IOException ignore) {
                    }
                }
            }
        }
        return "{\"success\": true}";
    } catch (IOException | FileUploadException e) {
        return "{\"success\": false}";
    }
}

From source file:org.opensubsystems.core.util.servlet.WebParamUtils.java

/**
 * Parse multipart request and separate regular parameters and files. The
 * files names are also stored as values of the parameters that are used to 
 * upload them.//from  w  w  w.  j  a v a2  s. c o  m
 * 
 * @param strLogPrefix - log prefix used for all log output to tie together
 *                       the same invocations
 * @param request - request to get parameter from
 * @return TwoElementStruct<Map<String, String>, Map<String, FileItem>> - the
 *                  first element is map of parameter names and their values. 
 *                  For uploaded files the files names are also stored here as 
 *                  values of the parameters that are used to upload them.
 *                  If there is only one value of the parameter then the value
 *                  is stored directly as String. If there are multiple values
 *                  then the values are stored as List<String>.
 *                  The second element is map of parameter names and the files
 *                  that are uploaded as these parameters.
 * @throws FileUploadException - an error has occurred
 */
public static TwoElementStruct<Map<String, Object>, Map<String, FileItem>> parseMultipartRequest(
        String strLogPrefix, HttpServletRequest request) throws FileUploadException {
    if (GlobalConstants.ERROR_CHECKING) {
        assert ServletFileUpload.isMultipartContent(request) : "Specified request is not multipart";
    }

    TwoElementStruct<Map<String, Object>, Map<String, FileItem>> returnValue;
    FileCleaningTracker fileCleaningTracker;
    String strTempDir;
    DiskFileItemFactory factory;
    Properties prpSettings;
    int iMaxInMemorySize;
    int iMaxSize;
    ServletFileUpload upload;
    List<FileItem> items;

    // TODO: Improve: Consider calling 
    // FileUtils.createTemporarySubdirectory
    // as done in legacy Formature.DocumentTemplateServlet.getFormToProcess
    // to store the temporary files per session and request
    strTempDir = FileUtils.getTemporaryDirectory();

    prpSettings = Config.getInstance().getProperties();
    iMaxInMemorySize = PropertyUtils.getIntPropertyInRange(prpSettings, REQUEST_UPLOAD_MEMORY_THRESHOLD,
            REQUEST_UPLOAD_MEMORY_THRESHOLD_DEFAULT, "Maximal size of uploaded file that is kept in memory", 1, // 0 is allowed 
            Integer.MAX_VALUE);
    iMaxSize = PropertyUtils.getIntPropertyInRange(prpSettings, REQUEST_UPLOAD_MAX_SIZE,
            REQUEST_UPLOAD_MAX_SIZE_DEFAULT, "Maximal size of uploaded file", 1, // 0 is allowed 
            Integer.MAX_VALUE);

    fileCleaningTracker = FileCleanerCleanup.getFileCleaningTracker(request.getServletContext());

    // Create a factory for disk-based file items
    factory = new DiskFileItemFactory();
    factory.setFileCleaningTracker(fileCleaningTracker);
    // Set factory constraints
    factory.setSizeThreshold(iMaxInMemorySize);
    factory.setRepository(new File(strTempDir));

    // Create a new file upload handler
    upload = new ServletFileUpload(factory);
    // Set overall request size constraint
    upload.setSizeMax(iMaxSize);

    // Parse the request
    items = upload.parseRequest(request);
    if ((items != null) && (!items.isEmpty())) {
        Map mpParams;
        Map mpFiles;
        String strParamName;
        String strValue;
        Object temp;
        List<String> lstValues;

        mpParams = new HashMap(items.size());
        mpFiles = new HashMap();

        returnValue = new TwoElementStruct(mpParams, mpFiles);
        for (FileItem item : items) {
            strParamName = item.getFieldName();
            if (item.isFormField()) {
                strValue = item.getString();
            } else {
                strValue = item.getName();
                mpFiles.put(strParamName, item);
            }

            temp = mpParams.put(strParamName, strValue);
            if (temp != null) {
                // There was already an value so convert it to list of values
                if (temp instanceof String) {
                    // There are currently exactly two values
                    lstValues = new ArrayList<>();
                    lstValues.add((String) temp);
                    mpParams.put(strParamName, lstValues);
                } else {
                    // There are currently more than two values
                    lstValues = (List<String>) temp;
                }
                lstValues.add(strValue);
            }
        }
    } else {
        returnValue = new TwoElementStruct(Collections.emptyMap(), Collections.emptyMap());
    }

    return returnValue;
}