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.jbpm.designer.repository.VFSRepositoryGitFileSystemTest.java

@Test
public void testCreateGlobalDirOnNewProjectWithSpaces() throws Exception {
    ServletContext servletContext = mock(ServletContext.class);
    when(servletContext.getRealPath(anyString())).thenReturn(getClass().getResource("default.json").getFile());

    HttpServletRequest servletRequest = mock(HttpServletRequest.class);
    when(servletRequest.getServletContext()).thenReturn(servletContext);

    VFSRepository repository = new VFSRepository(producer.getIoService());
    repository.setDescriptor(descriptor);
    repository.setServletRequest(servletRequest);

    Directory testProjectDir = repository.createDirectory("/my test project");

    final KieModule mockProject = mock(KieModule.class);
    when(mockProject.getRootPath()).thenReturn(Paths
            .convert(producer.getIoService().get(URI.create(decodeUniqueId(testProjectDir.getUniqueId())))));

    NewModuleEvent event = mock(NewModuleEvent.class);
    when(event.getModule()).thenReturn(mockProject);

    repository.createGlobalDirOnNewProject(event);

    boolean globalDirectoryExists = repository.directoryExists("/my test project/global");
    assertTrue(globalDirectoryExists);/* ww w  .j  av  a 2  s  .co  m*/

    Collection<Asset> foundFormTemplates = repository.listAssets("/my test project/global",
            new FilterByExtension("fw"));
    assertNotNull(foundFormTemplates);
    assertEquals(0, foundFormTemplates.size());

    Collection<Asset> foundJSONAssets = repository.listAssets("/my test project/global",
            new FilterByExtension("json"));
    assertNotNull(foundJSONAssets);
    assertEquals(3, foundJSONAssets.size());

    Collection<Asset> foundWidAssets = repository.listAssets("/my test project", new FilterByExtension("wid"));
    assertNotNull(foundWidAssets);
    assertEquals(0, foundWidAssets.size());

    // call again to try to trigger FileAlreadyExistsException
    repository.createGlobalDirOnNewProject(event);

    boolean globalDirectoryStillExists = repository.directoryExists("/my test project/global");
    assertTrue(globalDirectoryStillExists);

    // no new files or copies were added
    Collection<Asset> foundFormTemplatesAfterSecondCall = repository.listAssets("/my test project/global",
            new FilterByExtension("fw"));
    assertNotNull(foundFormTemplatesAfterSecondCall);
    assertEquals(0, foundFormTemplatesAfterSecondCall.size());

    Collection<Asset> foundJSONAssetsAfterSecondCall = repository.listAssets("/my test project/global",
            new FilterByExtension("json"));
    assertNotNull(foundJSONAssetsAfterSecondCall);
    assertEquals(3, foundJSONAssetsAfterSecondCall.size());

    Collection<Asset> foundWidAssetsAfterSecondCall = repository.listAssets("/my test project",
            new FilterByExtension("wid"));
    assertNotNull(foundWidAssetsAfterSecondCall);
    assertEquals(0, foundWidAssetsAfterSecondCall.size());
}

From source file:pt.ist.bennu.core.presentationTier.actions.ConfigurationAction.java

public ActionForward viewSystemConfig(final ActionMapping mapping, final ActionForm form,
        final HttpServletRequest request, final HttpServletResponse response) {

    ArrayList<String> modulesList = new ArrayList<String>();
    for (Project artifact : FenixFramework.getProject().getProjects()) {
        modulesList.add(artifact.getName());
    }//from w w w  .  jav  a2 s . co  m
    //       Properties projectProperties = new Properties();
    //       projectProperties.load(getClass().getResourceAsStream(propertiesLocation));

    //       final String[] modules = projectProperties.getProperty("depends").split(",");
    final String[] modules = modulesList.toArray(new String[0]);

    File[] listModulesFiles = new File(request.getServletContext().getRealPath("/WEB-INF/lib"))
            .listFiles(new FilenameFilter() {

                @Override
                public boolean accept(File dir, String name) {
                    return name.endsWith("jar") && StringUtils.indexOfAny(name, modules) >= 0;
                }
            });

    List<File> modulesFileList = new ArrayList<File>(Arrays.asList(listModulesFiles));

    File[] listFiles = new File(request.getServletContext().getRealPath("/WEB-INF/lib"))
            .listFiles(new FilenameFilter() {

                @Override
                public boolean accept(File dir, String name) {
                    return name.endsWith("jar");
                }
            });

    List<File> listFilesList = new ArrayList<File>(Arrays.asList(listFiles));
    listFilesList.removeAll(modulesFileList);

    Collections.sort(modulesFileList);
    Collections.sort(listFilesList);

    setAttribute(request, "AllOtherJars", listFilesList);
    setAttribute(request, "AllModuleJars", modulesFileList);
    return getContext(request).forward("/bennu-core/systemInfo.jsp");
}

From source file:com.askme.controller.app.AppController.java

@RequestMapping(value = "/user/changeProfile", method = RequestMethod.POST)
public String postChangeProfile(@Valid User user, BindingResult result, ModelMap model,
        RedirectAttributes redirect, HttpServletRequest request,
        @RequestParam(value = "file", required = false) MultipartFile file) {
    passwordValidator.validate(user, result);
    if (result.hasErrors()) {
        System.out.println(result.getAllErrors());
        return "change_profile";
    }/*from w  w w  .j a  v a  2 s .co m*/

    // Upload avatar
    if (file != null) {
        try {
            InputStream inputStream = file.getInputStream();
            if (inputStream == null) {
                System.out.println("File inputstream is null");
            }
            String path = request.getServletContext().getRealPath("/") + "public/avatar/";
            FileUtils.forceMkdir(new File(path));
            File upload = new File(path + file.getOriginalFilename());
            file.transferTo(upload);
            user.setAvatar(file.getOriginalFilename());
            IOUtils.closeQuietly(inputStream);
        } catch (IOException ex) {
            System.out.println("Error saving uploaded file");
        }
    }

    userService.update(user);

    redirect.addFlashAttribute("success", "Cp nht profile thnh cng");
    return "redirect:/login";
}

From source file:controller.CommercialController.java

@RequestMapping(value = "regub/commercial/contrats/facturecom", method = RequestMethod.POST)
//public @ResponseBody
String factureAction(HttpServletRequest request, HttpServletResponse response, HttpSession session, Model model)
        throws IOException {

    int idvideo = Integer.parseInt(request.getParameter("idvideo"));
    Facture facture = new Facture();
    facture.Consulter(VidBDD.VideoPrec(idvideo).get(0).getClient(), VidBDD.VideoPrec(idvideo).get(0),
            request.getServletContext());
    //if(request.getSession()){
    //int test = Integer.parseInt(request.getParameter("select")) ;
    //request.setAttribute("Modify", this.modif.modifcontrat(id));
    //}//  ww  w  .  j  a  va2 s  .  c o  m
    //session.setAttribute("Modify", this.modif.modifcontrat(id));
    int BUFFER_SIZE = 4096;
    ServletContext context = request.getServletContext();
    String appPath = context.getRealPath("");
    System.out.println(appPath);

    try {

        File downloadFile = new File(appPath + "\\resources\\reports\\facture.pdf");
        FileInputStream fis = new FileInputStream(downloadFile);
        // get MIME type of the file
        String mimeType = context.getMimeType(appPath + "\\resources\\reports\\facture.pdf");
        if (mimeType == null) {
            // set to binary type if MIME mapping not found
            mimeType = "application/octet-stream";
        }
        System.out.println("MIME type: " + mimeType);

        // set content attributes for the response
        response.setContentType(mimeType);
        response.setContentLength((int) downloadFile.length());

        // set headers for the response
        String headerKey = "Content-Disposition";
        String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
        response.setHeader(headerKey, headerValue);

        // get output stream of the response
        OutputStream outStream = response.getOutputStream();

        byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead = -1;

        // write bytes read from the input stream into the output stream
        while ((bytesRead = fis.read(buffer)) != -1) {
            outStream.write(buffer, 0, bytesRead);
        }

        fis.close();
        outStream.close();

    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return "redirect:/regub/commercial/contrats/" + VidBDD.VideoPrec(idvideo).get(0).getClient().getIdClient();
}

From source file:controller.CommercialController.java

@RequestMapping(value = "regub/commercial/facturecom", method = RequestMethod.POST)
//public @ResponseBody
String facture2Action(HttpServletRequest request, HttpServletResponse response, HttpSession session,
        Model model) throws IOException {

    int idvideo = Integer.parseInt(request.getParameter("idvideo"));
    Facture facture = new Facture();
    facture.Consulter(VidBDD.VideoPrec(idvideo).get(0).getClient(), VidBDD.VideoPrec(idvideo).get(0),
            request.getServletContext());
    //if(request.getSession()){
    //int test = Integer.parseInt(request.getParameter("select")) ;
    //request.setAttribute("Modify", this.modif.modifcontrat(id));
    //}/*from w w  w  .ja v  a2  s  .co m*/
    //session.setAttribute("Modify", this.modif.modifcontrat(id));
    int BUFFER_SIZE = 4096;
    ServletContext context = request.getServletContext();
    String appPath = context.getRealPath("");
    System.out.println(appPath);

    try {

        File downloadFile = new File(appPath + "\\resources\\reports\\facture.pdf");
        FileInputStream fis = new FileInputStream(downloadFile);
        // get MIME type of the file
        String mimeType = context.getMimeType(appPath + "\\resources\\reports\\facture.pdf");
        if (mimeType == null) {
            // set to binary type if MIME mapping not found
            mimeType = "application/octet-stream";
        }
        System.out.println("MIME type: " + mimeType);

        // set content attributes for the response
        response.setContentType(mimeType);
        response.setContentLength((int) downloadFile.length());

        // set headers for the response
        String headerKey = "Content-Disposition";
        String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
        response.setHeader(headerKey, headerValue);

        // get output stream of the response
        OutputStream outStream = response.getOutputStream();

        byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead = -1;

        // write bytes read from the input stream into the output stream
        while ((bytesRead = fis.read(buffer)) != -1) {
            outStream.write(buffer, 0, bytesRead);
        }

        fis.close();
        outStream.close();

    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return "redirect:/regub/commercial/contrats/derniercontrats";
}

From source file:sos.Sos.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// w w  w.  ja v  a  2  s  .com
 *
 * @param request servlet request
 * @param response servlet response
 * @param post true for post method
 * @throws SnannySostServerException for bad request or service unavailable
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response, boolean post)
        throws SnannySostServerException {
    long t1 = System.currentTimeMillis();
    System.out.println("Sos.processRequest starts");
    // retreive configuration
    SnannySostServerConfig snannySostServerConfig = SnannySostServerConfig
            .singleton(request.getServletContext());
    info = "snanny-sostServer" + snannySostServerConfig.getExtraInfo();

    // way to force initialization
    if (request.getParameter(SERVLET_PRELOAD) != null) {
        if (!preloaded) {
            System.out.println("Sos.processRequest preload");

            SosValidation.singleton(snannySostServerConfig);
            InsertSensor.singleton();
            InsertObservation.singleton();

            System.setProperty("http.proxyHost", snannySostServerConfig.getSquidHost());
            System.setProperty("http.proxyPort", snannySostServerConfig.getSquidPort());
            System.out.println(
                    "System.setProperty(\"http.proxyHost\"," + snannySostServerConfig.getSquidHost() + ");");
            System.out.println(
                    "System.setProperty(\"http.proxyPort\"," + snannySostServerConfig.getSquidPort() + ");");

        }
        preloaded = true;
        try {
            long t2 = System.currentTimeMillis();
            long t = t2 - t1;
            System.out.println("Sos.processRequest stops after : " + t + "ms");
            response.sendRedirect("/snanny-sostServer/");
            return;
        } catch (IOException lost) {
        }
    }

    // get servlet response writer
    PrintWriter out = getPrintWriter(response);

    // read request parameter                   
    SOSREQUEST sosRequest = getRequestParameter(request);

    String uuid;

    // process sos request
    switch (sosRequest) {
    case getCapabilities:
        getServiceParameter(request);
        getVersionParameter(request);
        getCapabilities(request, response, out, snannySostServerConfig);
        break;
    case describeSensor:
        getServiceParameter(request);
        getVersionParameter(request);
        describeSensor(request, response, out, snannySostServerConfig);
        break;
    case getObservationById:
        getServiceParameter(request);
        getVersionParameter(request);
        getObservationById(request, response, out, snannySostServerConfig);
        break;
    case insertSensor:
        System.out.println("Sos.processRequest insertSensor");
        checkPost(post, sosRequest);
        InsertSensor.singleton().insert(snannySostServerConfig, getPostContent(request, snannySostServerConfig),
                response, out);
        break;
    case deleteSensor:
        getServiceParameter(request);
        getVersionParameter(request);
        uuid = getSosProcedureUuid(request);
        deleteSensor(request, response, out, snannySostServerConfig, uuid);
        break;
    case insertObservation:
        checkPost(post, sosRequest);
        InsertObservation.singleton().insert(snannySostServerConfig,
                getPostContent(request, snannySostServerConfig), response, out);
        break;
    case deleteObservation:
        getServiceParameter(request);
        getVersionParameter(request);
        uuid = getSosObservationUuid(request);
        deleteObservation(request, response, out, snannySostServerConfig, uuid);
        break;

    //For a version 0, some requests are not implemented:
    case getObservation:
        break;
    case getResult:
        break;
    case insertResult:
        break;
    case deleteResult:
        break;
    }

    // close response writer
    out.close();

    long t2 = System.currentTimeMillis();
    long t = t2 - t1;
    System.out.println("Sos.processRequest stops after : " + t + "ms");

}

From source file:com.nemesis.admin.UploadServlet.java

/**
 * @param request/*from  www.  j av  a2s.  co  m*/
 * @param response
 * @throws javax.servlet.ServletException
 * @throws java.io.IOException
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 * response)
 *
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new IllegalArgumentException(
                "Request is not multipart, please 'multipart/form-data' enctype for your form.");
    }

    ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());
    PrintWriter writer = response.getWriter();
    response.setContentType("application/json");
    JsonArray json = new JsonArray();
    try {
        List<FileItem> items = uploadHandler.parseRequest(request);
        for (FileItem item : items) {
            if (!item.isFormField()) {
                final String savedFile = UUID.randomUUID().toString() + "." + getSuffix(item.getName());
                File file = new File(request.getServletContext().getRealPath("/") + "uploads/", savedFile);
                item.write(file);
                JsonObject jsono = new JsonObject();
                jsono.addProperty("name", savedFile);
                jsono.addProperty("path", file.getAbsolutePath());
                jsono.addProperty("size", item.getSize());
                json.add(jsono);
                System.out.println(json.toString());
            }
        }
    } catch (FileUploadException e) {
        throw new RuntimeException(e);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        writer.write(json.toString());
        writer.close();
    }

}

From source file:controller.CommercialController.java

@RequestMapping(value = "regub/commercial/contrats/deviscom", method = RequestMethod.POST)
//public @ResponseBody
String devisAction(HttpServletRequest request, HttpServletResponse response, HttpSession session, Model model)
        throws IOException {

    Client cli = (Client) request.getAttribute("clicom");
    int idvideo = Integer.parseInt(request.getParameter("idvideo"));
    Devis devis = new Devis();
    devis.Consulter(VidBDD.VideoPrec(idvideo).get(0).getClient(), VidBDD.VideoPrec(idvideo).get(0),
            request.getServletContext());
    //if(request.getSession()){
    //int test = Integer.parseInt(request.getParameter("select")) ;
    //request.setAttribute("Modify", this.modif.modifcontrat(id));
    //}//w  ww.j a v a  2  s  .com
    //session.setAttribute("Modify", this.modif.modifcontrat(id));
    int BUFFER_SIZE = 4096;
    ServletContext context = request.getServletContext();
    String appPath = context.getRealPath("");
    System.out.println(appPath);

    try {

        File downloadFile = new File(appPath + "\\resources\\reports\\devis.pdf");
        FileInputStream fis = new FileInputStream(downloadFile);
        // get MIME type of the file
        String mimeType = context.getMimeType(appPath + "\\resources\\reports\\devis.pdf");
        if (mimeType == null) {
            // set to binary type if MIME mapping not found
            mimeType = "application/octet-stream";
        }
        System.out.println("MIME type: " + mimeType);

        // set content attributes for the response
        response.setContentType(mimeType);
        response.setContentLength((int) downloadFile.length());

        // set headers for the response
        String headerKey = "Content-Disposition";
        String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
        response.setHeader(headerKey, headerValue);

        // get output stream of the response
        OutputStream outStream = response.getOutputStream();

        byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead = -1;

        // write bytes read from the input stream into the output stream
        while ((bytesRead = fis.read(buffer)) != -1) {
            outStream.write(buffer, 0, bytesRead);
        }

        fis.close();
        outStream.close();

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return "redirect:/regub/commercial/contrats/" + cli.getIdClient();
}

From source file:controller.CommercialController.java

@RequestMapping(value = "regub/commercial/deviscom", method = RequestMethod.POST)
//public @ResponseBody
String devis2Action(HttpServletRequest request, HttpServletResponse response, HttpSession session, Model model)
        throws IOException {

    Client cli = (Client) request.getAttribute("clicom");
    int idvideo = Integer.parseInt(request.getParameter("idvideo"));
    Devis devis = new Devis();
    devis.Consulter(VidBDD.VideoPrec(idvideo).get(0).getClient(), VidBDD.VideoPrec(idvideo).get(0),
            request.getServletContext());
    //if(request.getSession()){
    //int test = Integer.parseInt(request.getParameter("select")) ;
    //request.setAttribute("Modify", this.modif.modifcontrat(id));
    //}//www  . j  av a  2 s  .c o  m
    //session.setAttribute("Modify", this.modif.modifcontrat(id));
    int BUFFER_SIZE = 4096;
    ServletContext context = request.getServletContext();
    String appPath = context.getRealPath("");
    System.out.println(appPath);

    try {

        File downloadFile = new File(appPath + "\\resources\\reports\\devis.pdf");
        FileInputStream fis = new FileInputStream(downloadFile);
        // get MIME type of the file
        String mimeType = context.getMimeType(appPath + "\\resources\\reports\\devis.pdf");
        if (mimeType == null) {
            // set to binary type if MIME mapping not found
            mimeType = "application/octet-stream";
        }
        System.out.println("MIME type: " + mimeType);

        // set content attributes for the response
        response.setContentType(mimeType);
        response.setContentLength((int) downloadFile.length());

        // set headers for the response
        String headerKey = "Content-Disposition";
        String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
        response.setHeader(headerKey, headerValue);

        // get output stream of the response
        OutputStream outStream = response.getOutputStream();

        byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead = -1;

        // write bytes read from the input stream into the output stream
        while ((bytesRead = fis.read(buffer)) != -1) {
            outStream.write(buffer, 0, bytesRead);
        }

        fis.close();
        outStream.close();

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return "redirect:/regub/commercial/derniercontras";
}

From source file:org.auraframework.http.resource.InlineJs.java

@Override
public void write(HttpServletRequest request, HttpServletResponse response, AuraContext context)
        throws IOException {
    try {/*from  w  w  w . j  a v a 2 s.  c om*/
        // For appcached apps, inline is not expected to return a CSRF token
        if (!manifestUtil.isManifestEnabled()) {
            String token = request.getParameter("jwt");
            if (!configAdapter.validateBootstrap(token)) {
                throw new AuraJWTError("Invalid jwt parameter");
            }
        }
        DefDescriptor<? extends BaseComponentDef> appDefDesc = context.getLoadingApplicationDescriptor();
        internalWrite(request, response, appDefDesc, context);
    } catch (Throwable t) {
        if (t instanceof AuraJWTError) {
            // If jwt validation fails, just 404. Do not gack.
            try {
                servletUtilAdapter.send404(request.getServletContext(), request, response);
            } catch (ServletException e) {
                // ignore
            }
        } else {
            servletUtilAdapter.handleServletException(t, false, context, request, response, false);
            exceptionAdapter.handleException(new AuraResourceException(getName(), response.getStatus(), t));
        }
    }
}