/**
   * A Molgenis common web application initializer
   *
   * @param servletContext
   * @param appConfig
   * @param isDasUsed is the molgenis-omx-das module used?
   * @throws ServletException
   */
  protected void onStartup(ServletContext servletContext, Class<?> appConfig, boolean isDasUsed)
      throws ServletException {
    // Create the 'root' Spring application context
    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
    rootContext.register(appConfig);

    // Manage the lifecycle of the root application context
    servletContext.addListener(new ContextLoaderListener(rootContext));

    // Register and map the dispatcher servlet
    ServletRegistration.Dynamic dispatcherServlet =
        servletContext.addServlet("dispatcher", new DispatcherServlet(rootContext));
    if (dispatcherServlet == null) {
      logger.warn(
          "ServletContext already contains a complete ServletRegistration for servlet 'dispatcher'");
    } else {
      final int maxSize = 32 * 1024 * 1024;
      int loadOnStartup = (isDasUsed ? 2 : 1);
      dispatcherServlet.setLoadOnStartup(loadOnStartup);
      dispatcherServlet.addMapping("/");
      dispatcherServlet.setMultipartConfig(
          new MultipartConfigElement(null, maxSize, maxSize, maxSize));
      dispatcherServlet.setInitParameter("dispatchOptionsRequest", "true");
    }

    // add filters
    javax.servlet.FilterRegistration.Dynamic etagFilter =
        servletContext.addFilter("etagFilter", new ShallowEtagHeaderFilter());
    etagFilter.addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST), true, "dispatcher");

    // enable use of request scoped beans in FrontController
    servletContext.addListener(new RequestContextListener());
  }
Ejemplo n.º 2
0
  @Override
  protected synchronized RequestProcessor getRequestProcessor(ModuleConfig moduleConfig)
      throws ServletException {

    ServletContext servletContext = getServletContext();

    String key = Globals.REQUEST_PROCESSOR_KEY + moduleConfig.getPrefix();

    RequestProcessor requestProcessor = (RequestProcessor) servletContext.getAttribute(key);

    if (requestProcessor == null) {
      ControllerConfig controllerConfig = moduleConfig.getControllerConfig();

      try {
        requestProcessor =
            (RequestProcessor)
                InstanceFactory.newInstance(
                    ClassLoaderUtil.getPortalClassLoader(), controllerConfig.getProcessorClass());
      } catch (Exception e) {
        throw new ServletException(e);
      }

      requestProcessor.init(this, moduleConfig);

      servletContext.setAttribute(key, requestProcessor);
    }

    return requestProcessor;
  }
Ejemplo n.º 3
0
 private static String getContextPath(ServletContext context) {
   // cette m茅thode retourne le contextPath de la webapp
   // en utilisant ServletContext.getContextPath si servlet api 2.5
   // ou en se d茅brouillant sinon
   // (on n'a pas encore pour l'instant de request pour appeler HttpServletRequest.getContextPath)
   if (context.getMajorVersion() == 2 && context.getMinorVersion() >= 5
       || context.getMajorVersion() > 2) {
     // api servlet 2.5 (Java EE 5) minimum pour appeler ServletContext.getContextPath
     return context.getContextPath();
   }
   URL webXmlUrl;
   try {
     webXmlUrl = context.getResource("/WEB-INF/web.xml");
   } catch (final MalformedURLException e) {
     throw new IllegalStateException(e);
   }
   String contextPath = webXmlUrl.toExternalForm();
   contextPath = contextPath.substring(0, contextPath.indexOf("/WEB-INF/web.xml"));
   final int indexOfWar = contextPath.indexOf(".war");
   if (indexOfWar > 0) {
     contextPath = contextPath.substring(0, indexOfWar);
   }
   // tomcat peut renvoyer une url commen莽ant pas "jndi:/localhost"
   // (v5.5.28, webapp dans un r茅pertoire)
   if (contextPath.startsWith("jndi:/localhost")) {
     contextPath = contextPath.substring("jndi:/localhost".length());
   }
   final int lastIndexOfSlash = contextPath.lastIndexOf('/');
   if (lastIndexOfSlash != -1) {
     contextPath = contextPath.substring(lastIndexOfSlash);
   }
   return contextPath;
 }
Ejemplo n.º 4
0
  public void handleRequest(HttpServletRequest request, HttpServletResponse response) {

    String pathInfo = request.getPathInfo();
    System.out.println(" yo les mec" + pathInfo + "");
    switch (pathInfo + "") {
      case "/add":
        System.out.println("addpersonne");
        ajouterPersonne(request);
        break;
      case "/addResponsable":
        System.out.println("addResponsable");
        addResponsable(request);
        break;
      case "/deleteResponsable":
        deleteResponsable(request);
        break;
      case "/deleteInvite":
        deleteInvite(request);
        break;
    }
    AfficherListeInvite(request, response);
    RequestDispatcher rd;
    ServletContext context = this.getServletContext();
    rd = context.getRequestDispatcher(JSP_PATH);
    try {
      rd.forward(request, response);
    } catch (Exception e) {
    }
  }
Ejemplo n.º 5
0
 private static String getServletContextIdentifier(ServletContext context) {
   if (context.getMajorVersion() == 2 && context.getMinorVersion() < 5) {
     return context.getServletContextName();
   } else {
     return context.getContextPath();
   }
 }
Ejemplo n.º 6
0
  @RequestMapping(value = "add", method = RequestMethod.POST)
  public String add(
      String name,
      String email,
      String tel,
      String cid,
      String password,
      MultipartFile photofile,
      Model model)
      throws Exception {

    String newFileName = null;

    if (photofile.getSize() > 0) {
      newFileName = MultipartHelper.generateFilename(photofile.getOriginalFilename());
      File attachfile = new File(servletContext.getRealPath(SAVED_DIR) + "/" + newFileName);
      photofile.transferTo(attachfile);

      makeThumbnailImage(
          servletContext.getRealPath(SAVED_DIR) + "/" + newFileName,
          servletContext.getRealPath(SAVED_DIR) + "/s-" + newFileName + ".png");
    }

    Student student = new Student();
    student.setName(name);
    student.setEmail(email);
    student.setTel(tel);
    student.setCid(cid);
    student.setPassword(password);
    student.setPhoto(newFileName);

    studentDao.insert(student);

    return "redirect:list.do";
  }
Ejemplo n.º 7
0
  public static Response respond(
      Bindings b, ServletContext con, String name, String message, int status) {
    try {

      String context = con.getContextPath();
      String baseFilePath = ServletUtils.withTrailingSlash(con.getRealPath("/"));
      String basePrefix = name.startsWith("/") ? "" : baseFilePath;

      String[] filesToTry =
          new String[] {
            "/etc/elda/conf.d/" + context + "/_errors/" + name + ".vm",
            basePrefix + "_errors/" + name + ".vm",
            "/etc/elda/conf.d/" + context + "/_errors/" + "_error" + ".vm",
            basePrefix + "_errors/" + "_error" + ".vm"
          };

      String page = fetchPage(filesToTry, fallBack);

      if (message == null) message = "Odd, no additional information is available.";
      b.put("_message", message);

      String builtPage = apply(b, page, name, message);

      return Response.status(status).entity(builtPage).build();
    } catch (Throwable e) {
      log.error("An exception occurred when rendering an error page:");
      log.error("  " + e.getMessage());
      return Response.status(Status.INTERNAL_SERVER_ERROR).entity(fallBack).build();
    }
  }
  @RequestMapping(value = "codiRoomMyClothesUpload", method = RequestMethod.POST)
  public String codiRoomMyClothesUpload(
      Clothes clothes, MultipartFile file, HttpServletRequest request) throws IOException {

    if (!file.isEmpty()) {

      ServletContext application = request.getServletContext();
      String url = "/resource/image/clothes";
      String path = application.getRealPath(url);
      String temp = file.getOriginalFilename();
      String fname = temp.substring(temp.lastIndexOf("\\") + 1);
      String fpath = path + "\\" + fname;

      InputStream ins = file.getInputStream(); // part.getInputStream();
      OutputStream outs = new FileOutputStream(fpath);

      byte[] buffer = new byte[1024];

      int len = 0;

      while ((len = ins.read(buffer, 0, 1024)) >= 0) outs.write(buffer, 0, len);

      outs.flush();
      outs.close();
      ins.close();

      clothes.setImage(fname);
    }

    clothesDao.addClothes(clothes);

    return "redirect:codiRoomMyClothes";
  }
  @Override
  public void contextInitialized(ServletContextEvent sce) {

    ServletContext context = sce.getServletContext();
    cdiContainer = (CdiContainer) context.getAttribute("org.ops4j.pax.cdi.container");
    cdiContainer.start(context);
    WeldManager manager = cdiContainer.unwrap(WeldManager.class);

    CdiInstanceFactoryBuilder builder = new CdiInstanceFactoryBuilder(manager);
    @SuppressWarnings("unchecked")
    Map<String, Object> attributes =
        (Map<String, Object>) context.getAttribute("org.ops4j.pax.web.attributes");
    if (attributes != null) {
      attributes.put("org.ops4j.pax.cdi.ClassIntrospecter", builder);
      log.info("registered CdiInstanceFactoryBuilder for Undertow");
    }
    context.setAttribute("org.ops4j.pax.cdi.BeanManager", cdiContainer.getBeanManager());

    JspFactory jspFactory = JspFactory.getDefaultFactory();
    if (jspFactory != null) {
      JspApplicationContext jspApplicationContext = jspFactory.getJspApplicationContext(context);

      jspApplicationContext.addELResolver(manager.getELResolver());
      jspApplicationContext.addELContextListener(new WeldELContextListener());
    }
    super.contextInitialized(sce);
  }
  /**
   * Load config.
   *
   * @param servletContext the servlet context
   * @return the configuration
   */
  Configuration loadConfig(ServletContext servletContext) {
    String handlers = servletContext.getInitParameter(ContextConfigParams.PARAM_HANDLERS);
    String layout = servletContext.getInitParameter(ContextConfigParams.PARAM_LAYOUT);
    String filters = servletContext.getInitParameter(ContextConfigParams.PARAM_FILTERS);
    String options = servletContext.getInitParameter(ContextConfigParams.PARAM_OPTIONS);
    String metaData = servletContext.getInitParameter(ContextConfigParams.PARAM_META_DATA);
    String properties = servletContext.getInitParameter(ContextConfigParams.PARAM_PROPERTIES);

    Configuration config = Configuration.INSTANCE;
    if (handlers != null && !handlers.equals("")) {
      config.setHandlers(new ReflectUtil<Handler>().getNewInstanceList(handlers.split(";")));
    }
    config.setLayout(new ReflectUtil<Layout>().getNewInstance(layout));
    if (filters != null && !filters.equals("")) {
      config.setFilters(new ReflectUtil<AuditEventFilter>().getNewInstanceList(filters.split(";")));
    }
    config.setCommands(options);
    config.setMetaData(new ReflectUtil<MetaData>().getNewInstance(metaData));
    if (properties != null && !properties.equals("")) {
      String[] propertiesList = properties.split(";");
      for (String property : propertiesList) {
        String[] keyValue = property.split(":");
        config.addProperty(keyValue[0], keyValue[1]);
      }
    }
    return config;
  }
 public void init(ServletConfig config) throws ServletException {
   super.init(config);
   ServletContext sc = config.getServletContext();
   ICP = (InterfaceCachePojo) sc.getAttribute("ICP");
   useInterfaceCaching = (String) sc.getAttribute("useInterfaceCaching");
   defaultCacheName = (String) sc.getAttribute("DefaultCacheName");
 }
Ejemplo n.º 12
0
  @Override
  public void contextInitialized(ServletContextEvent sce) {
    final ServletContext context = sce.getServletContext();

    LOGGER = LumifyLoggerFactory.getLogger(ApplicationBootstrap.class);

    LOGGER.info("Servlet context initialized...");
    try {
      if (context != null) {
        final Configuration config = fetchApplicationConfiguration(context);
        LOGGER.info("Running application with configuration:\n%s", config);

        InjectHelper.inject(this, LumifyBootstrap.bootstrapModuleMaker(config));

        // Store the injector in the context for a servlet to access later
        context.setAttribute(Injector.class.getName(), InjectHelper.getInjector());
        if (!config.get(Configuration.MODEL_PROVIDER).equals(Configuration.UNKNOWN_STRING)) {
          FrameworkUtils.initializeFramework(
              InjectHelper.getInjector(), userRepository.getSystemUser());
        }

        InjectHelper.getInjector().getInstance(OntologyRepository.class);

        LOGGER.warn(
            "JavaScript / Less modifications will not be reflected on server. Run `grunt watch` from webapp directory in development");
      } else {
        LOGGER.error("Servlet context could not be acquired!");
      }
    } catch (Exception ex) {
      LOGGER.error("Failed to initialize context", ex);
      throw new RuntimeException("Failed to initialize context", ex);
    }
  }
Ejemplo n.º 13
0
  /**
   * Looks up and returns a repository bound in the servlet context of the given filter.
   *
   * @return repository from servlet context
   * @throws RepositoryException if the repository is not available
   */
  public Repository getRepository() throws RepositoryException {
    String name = config.getInitParameter(Repository.class.getName());
    if (name == null) {
      name = Repository.class.getName();
    }

    ServletContext context = config.getServletContext();
    Object repository = context.getAttribute(name);
    if (repository instanceof Repository) {
      return (Repository) repository;
    } else if (repository != null) {
      throw new RepositoryException(
          "Invalid repository: Attribute "
              + name
              + " in servlet context "
              + context.getServletContextName()
              + " is an instance of "
              + repository.getClass().getName());
    } else {
      throw new RepositoryException(
          "Repository not found: Attribute "
              + name
              + " does not exist in servlet context "
              + context.getServletContextName());
    }
  }
Ejemplo n.º 14
0
  /**
   * Calculate and return an absolute pathname to the XML file to contain our persistent storage
   * information.
   *
   * @throws Exception if an input/output error occurs
   */
  private String calculatePath() throws Exception {

    // Can we access the database via file I/O?
    String path = context.getRealPath(pathname);
    if (path != null) {
      return (path);
    }

    // Does a copy of this file already exist in our temporary directory
    File dir = (File) context.getAttribute("javax.servlet.context.tempdir");
    File file = new File(dir, "struts-example-database.xml");
    if (file.exists()) {
      return (file.getAbsolutePath());
    }

    // Copy the static resource to a temporary file and return its path
    InputStream is = context.getResourceAsStream(pathname);
    BufferedInputStream bis = new BufferedInputStream(is, 1024);
    FileOutputStream os = new FileOutputStream(file);
    BufferedOutputStream bos = new BufferedOutputStream(os, 1024);
    byte buffer[] = new byte[1024];
    while (true) {
      int n = bis.read(buffer);
      if (n <= 0) {
        break;
      }
      bos.write(buffer, 0, n);
    }
    bos.close();
    bis.close();
    return (file.getAbsolutePath());
  }
 public void init(final ServletContext context, final Map<String, String> paras) {
   _startTime = new Date();
   _context = context;
   _sipFactory = (SipFactory) context.getAttribute(ServletContextConstants.SIP_FACTORY);
   _mrcpFactory = (MrcpFactory) context.getAttribute(ServletContextConstants.MRCP_FACTORY);
   _appJarUrl =
       _context.getRealPath("/")
           + "WEB-INF"
           + File.separator
           + "lib"
           + File.separator
           + "tropo.jar";
   _cache = Collections.synchronizedMap(new WeakHashMap<Object, Application>());
   _tmx = ManagementFactory.getThreadMXBean();
   _mmx = ManagementFactory.getMemoryMXBean();
   try {
     _tropoBuildDate = Utils.getManifestAttribute(_appJarUrl, "Build-Date");
   } catch (final IOException t) {
     LOG.error(t.toString(), t);
     _tropoBuildDate = "Unknown";
   }
   try {
     _tropoVersionNo = Utils.getManifestAttribute(_appJarUrl, "Version-No");
   } catch (final IOException t) {
     LOG.error(t.toString(), t);
     _tropoVersionNo = "Unknown";
   }
   try {
     _tropoBuildNo = Utils.getManifestAttribute(_appJarUrl, "Build-No");
   } catch (final IOException t) {
     LOG.error(t.toString(), t);
     _tropoBuildNo = "Unknown";
   }
   LOG.info(toString() + " / " + getVersionNo() + " / " + getBuildNo());
 }
  public void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
      out.println("<!DOCTYPE html>");
      out.println("<html>");
      out.println("<head>");
      out.println("<title>Servlet E2</title>");
      out.println("</head>");
      out.println("<body>");
      ServletContext sc = getServletContext();

      out.println("<h2> Your Result:</h2>");
      Integer scoree = (Integer) sc.getAttribute("score");
      Integer size = (Integer) sc.getAttribute("bankSize");
      int passingScore = (int) (0.60 * size);

      if (scoree >= passingScore) {
        out.println("<h2> Congratulations!!!</h2>" + scoree);
        double percentage = 100 * scoree / size;
        out.println("<h3> YOU GOT&nbsp" + percentage + "!!</h3>");

      } else {

        out.println("<h2> SORRY You Failed!!!</h2>");
        double percentage = 100 * scoree / size;
        out.println("<h3> YOU GOT&nbsp" + percentage + "!!</h3>");
      }
      out.println("</body>");
      out.println("</html>");
    } catch (Exception e) {
      System.out.println("Exception in Servlet CalculateResult");
    }
  }
Ejemplo n.º 17
0
 private void onStart(Context context) {
   ServletContext servletContext = context.getServletContext();
   if (servletContext.getAttribute(this.MERGED_WEB_XML) == null) {
     servletContext.setAttribute(this.MERGED_WEB_XML, getEmptyWebXml());
   }
   TomcatResources.get(context).addClasspathResources();
 }
Ejemplo n.º 18
0
 @Override
 public void init() throws ServletException {
   super.init();
   ServletContext ctx = getServletContext();
   service = (BookService) ctx.getAttribute("BookService");
   log.trace("Get attribute BookService --> " + service);
 }
Ejemplo n.º 19
0
  @Override
  public void onStartup(ServletContext container) throws ServletException {

    AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
    ctx.register(AppConfig.class);
    ctx.register(SecurityConfig.class);
    container.addListener(new ContextLoaderListener(ctx));

    container
        .addFilter("springSecurityFilterChain", DelegatingFilterProxy.class)
        .addMappingForUrlPatterns(null, false, "/*");
    Map<String, String> initParams = new HashMap<String, String>();
    initParams.put("encoding", "UTF-8");
    initParams.put("forceEncoding", "true");
    FilterRegistration.Dynamic ceFilter =
        container.addFilter("encodingFilter", CharacterEncodingFilter.class);
    ceFilter.setInitParameters(initParams);
    ceFilter.addMappingForUrlPatterns(null, false, "/*");

    ctx.setServletContext(container);

    ServletRegistration.Dynamic servlet =
        container.addServlet("dispatcher", new DispatcherServlet(ctx));

    servlet.setLoadOnStartup(1);
    servlet.addMapping("/");
  }
Ejemplo n.º 20
0
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    // For application Attributes
    ServletContext application = getServletContext();

    // Retrieve parameter "id"
    int id = Integer.parseInt(req.getParameter("id"));

    // Retrieve task from database
    EntityManager em = PersistenceUtils.createEntityManager();
    Task editTask = Task.findById(em, id);

    // Retrieve parameter "text"
    String text = req.getParameter("text");

    // Update Text
    editTask.setText(text);

    // Update task on database
    try {
      editTask.update(em);
    } catch (Exception e) {
      // TODO: Exception handling
    }
    em.close();

    // Redirect to index
    String base = (String) application.getAttribute("base");
    resp.sendRedirect(base + "/index");
  }
 @Override
 public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp) {
   ServletContext servletContext = req.getHttpServletRequest().getServletContext();
   DecoratedObjectFactory objFactory =
       (DecoratedObjectFactory) servletContext.getAttribute(DecoratedObjectFactory.ATTR);
   return new DecoratorsSocket(objFactory);
 }
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  @Override
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
      CompanyInformationDTO item = new CompanyInformationDTO();
      item.setAddress((String) request.getParameter("Address"));
      item.setPhone((String) request.getParameter("Phone"));
      item.setCompanyDescription((String) request.getParameter("CompanyDescription"));
      item.setServiceDescription((String) request.getParameter("ServiceDescription"));
      item.setBriefCompanyDescription(
          CommonHelpers.Truncate((String) request.getParameter("BriefCompanyDescription"), 300));
      item.setBriefServiceDescription(
          CommonHelpers.Truncate((String) request.getParameter("BriefServiceDescription"), 300));
      item.setPreferExplanation((String) request.getParameter("PreferExplanation"));

      boolean kq = bean.insert(item);

      if (kq == true) {
        request.setAttribute("Message", "Insert successfully");
      } else {
        request.setAttribute("Message", "Insert failed");
      }

      String url = "/views/admin/SelectCompanyInformation.jsp";
      ServletContext sc = getServletContext();
      RequestDispatcher rd = sc.getRequestDispatcher(url);
      rd.forward(request, response);
    } catch (Exception ex) {
      out.println(ex.getMessage());
    } finally {
      out.close();
    }
  }
Ejemplo n.º 23
0
  public Request(HttpServletRequest httpServletRequest, String defaultTemplate) {
    super(httpServletRequest);
    setRequestMethod(httpServletRequest.getMethod());

    this.template = defaultTemplate;

    //
    ServletContext context = getSession().getServletContext();
    Theme.Platform platform = (Theme.Platform) context.getAttribute("platform");
    logger.debug("PLATFORM: {}", platform);

    if (platform == null) {
      String userAgentString = getHeader("User-Agent");
      UserAgent userAgent = UserAgent.getUserAgent(userAgentString);

      // Determine platform
      if (userAgent.getPlatform() == UserAgent.Platform.Android
          || userAgent.getPlatform() == UserAgent.Platform.IPhone
          || userAgent.getPlatform() == UserAgent.Platform.IPod
          || userAgent.getPlatform() == UserAgent.Platform.IPad) {
        platform = Theme.Platform.Mobile;
      } else {
        platform = Theme.Platform.Desktop;
      }

      context.setAttribute("platform", platform);
    }
  }
Ejemplo n.º 24
0
 @Override
 public void init() throws ServletException {
   super.init();
   ServletContext context = getServletContext();
   productService =
       (ProductService) context.getAttribute(ApplicationConstants.PRODUCT_SERVICE.getValue());
 }
  public void doPost(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    req.setCharacterEncoding("UTF-8");

    Map<String, String[]> parametersMap = req.getParameterMap();
    ServletContext context = req.getSession().getServletContext();

    List<JavaWorldNews> yourList = (List<JavaWorldNews>) context.getAttribute("javaNews");

    Boolean archiveFlag = false;

    if ((Boolean) req.getSession().getAttribute("javaWorldIndexFlag") == false) {
      archiveFlag = true;
    }
    req.getSession().setAttribute("javaWorldAchiveFlag", archiveFlag);

    for (JavaWorldNews list : yourList) {
      JavaWorldNewsArchive javaWorldNewsArchive =
          new JavaWorldNewsArchive(list.getTitle(), list.getDescription(), list.getLink());
      JavaWorldArchiveJpaDao javaWorldArchiveJpaDao = new JavaWorldArchiveJpaDao();
      if (javaWorldArchiveJpaDao.create(javaWorldNewsArchive).equals("duplicate")) {
        break;
      }
    }

    res.sendRedirect("JavaWorldNewsController");
  }
Ejemplo n.º 26
0
  private int getMaxSize() {
    if (maxSize != -1) {
      return maxSize;
    }

    int size = -1;
    ServletContext context = ResteasyProviderFactory.getContextData(ServletContext.class);
    if (context != null) {
      String s = context.getInitParameter(ResteasyContextParameters.RESTEASY_GZIP_MAX_INPUT);
      if (s != null) {
        try {
          size = Integer.parseInt(s);
        } catch (NumberFormatException e) {
          LogMessages.LOGGER.invalidFormat(
              ResteasyContextParameters.RESTEASY_GZIP_MAX_INPUT,
              Integer.toString(DEFAULT_MAX_SIZE));
        }
      }
    }
    if (size == -1) {
      size = DEFAULT_MAX_SIZE;
    }

    return size;
  }
Ejemplo n.º 27
0
  protected void initWebSettings() throws Exception {
    ServletContext servletContext = getServletContext();

    String xml = HttpUtil.URLtoString(servletContext.getResource("/WEB-INF/web.xml"));

    checkWebSettings(xml);
  }
Ejemplo n.º 28
0
 public String replaceApplicationBean2() {
   ServletContext application =
       (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
   Object oldValue = application.getAttribute("applicationBean");
   application.setAttribute("applicationBean", oldValue);
   return null;
 }
Ejemplo n.º 29
0
  /** @see HttpServlet#HttpServlet() */
  @Override
  public void init(ServletConfig config) throws ServletException {

    String log4jLocation = config.getInitParameter("log4j-properties-location");

    ServletContext sc = config.getServletContext();

    if (log4jLocation == null) {

      BasicConfigurator.configure();
    } else {
      String webAppPath = sc.getRealPath("/");
      String log4jProp = webAppPath + log4jLocation;
      File output = new File(log4jProp);

      if (output.exists()) {

        PropertyConfigurator.configure(log4jProp);
      } else {

        BasicConfigurator.configure();
      }
    }

    super.init(config);
  }
Ejemplo n.º 30
0
  public void uploadImage(UploadEvent evento) throws FileNotFoundException {
    FacesContext fc = FacesContext.getCurrentInstance();
    ServletContext sc = (ServletContext) fc.getExternalContext().getContext();
    String caminhoReal = sc.getRealPath("/");
    String extensao = "";
    UploadItem item = evento.getUploadItem();
    String fileName = item.getFileName();
    String ext[] = fileName.split("\\.");
    int i = ext.length;

    if (i > 1) {
      extensao = ext[i - 1];
    }

    Long tempo = System.currentTimeMillis();
    OutputStream out =
        new FileOutputStream(caminhoReal + "/ImagensPizza/" + "img" + tempo + "." + extensao);
    setImagePath("/ImagensPizza/" + "img" + tempo + "." + extensao);

    try {
      out.write(item.getData());
      out.close();

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