public void service(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    String uri = request.getPathInfo();

    if ((uri == null) || (uri.length() == 0)) {
      throw new ServletException("Path information is not specified");
    }

    String[] paths = uri.split(StringPool.SLASH);

    if (paths.length < 2) {
      throw new ServletException("Path " + uri + " is invalid");
    }

    HttpServlet delegate = _delegates.get(paths[1]);

    if (delegate == null) {
      throw new ServletException("No servlet registred for context " + paths[1]);
    }

    Thread currentThread = Thread.currentThread();

    ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    try {
      ClassLoader delegateClassLoader = delegate.getClass().getClassLoader();

      currentThread.setContextClassLoader(delegateClassLoader);

      delegate.service(request, response);
    } finally {
      currentThread.setContextClassLoader(contextClassLoader);
    }
  }
示例#2
1
  @Override
  public void init() throws ServletException {
    // TODO Auto-generated method stub
    super.init();
    filePath = getServletContext().getRealPath("") + File.separator + "schedule.ics";
    try {
      ical.getProperties().add(new ProdId("-//Ben Fortuna//iCal4j 1.0//EN"));
      ical.getProperties().add(Version.VERSION_2_0);
      ical.getProperties().add(CalScale.GREGORIAN);
    } catch (Exception e) {
      System.out.println("iCalendar failed to import");
    }
    registry = TimeZoneRegistryFactory.getInstance().createRegistry();
    timezone = registry.getTimeZone("America/New_York");
    tz = timezone.getVTimeZone();

    try {
      // Register the driver.
      Class.forName("org.postgresql.Driver").newInstance();
    } catch (Exception e) {
      e.printStackTrace();
    }
    String url = "jdbc:postgresql://hopper.cs.wlu.edu/corsola";
    try {
      con = DriverManager.getConnection(url, "web", "");
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
  @Override
  protected void service(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    if (_log.isDebugEnabled()) {
      _log.debug("Process service request");
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Set portal port");
    }

    PortalUtil.setPortalInetSocketAddresses(request);

    if (_httpServlets.isEmpty()) {
      response.sendError(
          HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Module framework is unavailable");

      return;
    }

    HttpServlet httpServlet = _httpServlets.get(0);

    httpServlet.service(request, response);
  }
 @Test
 public void testInit() throws Exception {
   HttpServlet servlet =
       new HttpServlet() {
         @Override
         protected void doGet(HttpServletRequest req, HttpServletResponse resp)
             throws ServletException, IOException {
           super.doGet(req, resp);
         }
       };
   ServletContext context = servlet.getServletContext();
   assertNotNull("Context is null", context);
 }
 @Override
 public void init() throws ServletException {
   Enumeration<String> params = getServletContext().getInitParameterNames();
   while (params.hasMoreElements()) {
     String key = params.nextElement();
     super.getServletContext().setAttribute(key, getServletContext().getInitParameter(key));
   }
   this.debug = Boolean.parseBoolean(super.getInitParameter("debug"));
   super.getServletContext().setAttribute("debug", debug);
   this.baseURL = super.getInitParameter("baseURL") + getServletContext().getContextPath();
   super.getServletContext().setAttribute("baseURL", baseURL);
   this.pmf = JDOHelper.getPersistenceManagerFactory("datastore");
   super.getServletContext().setAttribute("persistence", pmf);
 }
 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");
 }
  @Override
  public void init() throws ServletException {

    LOG.info("enter--init");

    super.init();
    ArrayList<MBeanServer> serverList = MBeanServerFactory.findMBeanServer(null);
    MBeanServer serverHelloWorld = (MBeanServer) serverList.get(0);
    final HelloWorldService helloWorldMBean = new HelloWorldService();
    ObjectName helloWorld = null;
    try {
      helloWorld = new ObjectName("jboss.jmx:name=HelloJMX");
      serverHelloWorld.registerMBean(helloWorldMBean, helloWorld);
    } catch (MalformedObjectNameException e) {
      e.printStackTrace();
    } catch (NullPointerException e) {
      e.printStackTrace();
    } catch (InstanceAlreadyExistsException e) {
      e.printStackTrace();
    } catch (MBeanRegistrationException e) {
      e.printStackTrace();
    } catch (NotCompliantMBeanException e) {
      e.printStackTrace();
    }

    LOG.info("exit--init");
  }
示例#8
0
  /**
   * 初始化,主要是完成module的内存加载<br>
   * 从配置文件中读取module对于类
   */
  @Override
  public void init(ServletConfig config) throws ServletException {

    packages = config.getInitParameter("package");

    super.init();
  }
示例#9
0
  public void init(ServletConfig servletConfig) throws ServletException {
    super.init(servletConfig);
    servletContext = servletConfig.getServletContext();

    try {
      SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance();
      con = scf.createConnection();
    } catch (Exception e) {
      logger.log(Level.SEVERE, "Unable to open a SOAPConnection", e);
    }

    InputStream in = servletContext.getResourceAsStream("/WEB-INF/address.properties");

    if (in != null) {
      Properties props = new Properties();

      try {
        props.load(in);

        to = props.getProperty("to");
        data = props.getProperty("data");
      } catch (IOException ex) {
        // Ignore
      }
    }
  }
 public void init(ServletConfig config) throws ServletException {
   super.init(config);
   try {
     // 应用的相对路径前缀
     String prefix = config.getServletContext().getRealPath("/");
     if (prefix == null) prefix = "";
     // 获取配置文件的文件名称
     uploadPath = config.getInitParameter(this.UPLOAD_FILE_PATH_PARAM);
     // 文件不存在提醒信息
     alarmMessage =
         config.getInitParameter(this.FILE_UN_EXIST_ALARM) == null
             ? alarmMessage
             : config.getInitParameter(this.FILE_UN_EXIST_ALARM);
     // 是否是相对路径
     String isRelatePath =
         config.getInitParameter(this.UPLOAD_FILE_PATH_RELATE_FLAG_PARAM) == null
             ? "true"
             : config.getInitParameter(this.UPLOAD_FILE_PATH_RELATE_FLAG_PARAM);
     if (isRelatePath.equalsIgnoreCase("true"))
       uploadPath = prefix + (uploadPath.indexOf("/") == 0 ? "" : "/") + uploadPath;
     if ((uploadPath.lastIndexOf("/") + 1) != uploadPath.length()) uploadPath += "/";
     logger.info("file upload path=" + uploadPath);
   } catch (Exception e) {
     logger.error("fileDownload Servlet init Error:" + e.getMessage());
     e.printStackTrace();
   }
 }
示例#11
0
  /** Initializes the servlet. */
  @Override
  public void init(ServletConfig config) throws ServletException {
    super.init(config);

    // It seems that if the servlet fails to initialize the first time,
    // init can be called again (it has been observed in Tomcat log files
    // but not explained).

    if (initAttempted) {
      // This happens - the query and update servlets share this class
      // log.info("Re-initialization of servlet attempted") ;
      return;
    }

    initAttempted = true;

    servletConfig = config;

    // Modify the (Jena) global filemanager to include loading by servlet context
    FileManager fileManager = FileManager.get();

    if (config != null) {
      servletContext = config.getServletContext();
      fileManager.addLocator(new LocatorServletContext(servletContext));
    }

    printName = config.getServletName();
    String configURI = config.getInitParameter(Joseki.configurationFileProperty);
    servletEnv();
    try {
      Dispatcher.initServiceRegistry(fileManager, configURI);
    } catch (ConfigurationErrorException confEx) {
      throw new ServletException("Joseki configuration error", confEx);
    }
  }
示例#12
0
  public void init(ServletConfig cfg) throws ServletException {
    super.init(cfg);
    String model = cfg.getInitParameter("APIModel");
    String mapping = cfg.getInitParameter("APIMapping");
    String verboseString = cfg.getInitParameter("VerboseErrors");
    String corsString = cfg.getInitParameter("SupportCORS");

    if ((model == null) || (mapping == null)) {
      throw new ServletException("Both APIModel and APIMapping init parameters must be set");
    }

    try {
      buildAPIProcessor(model, mapping, cfg);
    } catch (IOException ioe) {
      throw new ServletException(ioe);
    } catch (APIModelException ame) {
      throw new ServletException(ame);
    }

    if (verboseString != null) {
      verboseErrors = Boolean.valueOf(verboseString);
    }
    if (corsString != null) {
      if (corsString.equalsIgnoreCase("authenticated")) {
        supportCors = Cors.AUTHENTICATED;
      } else if (corsString.equalsIgnoreCase("true")) {
        supportCors = Cors.ON;
      }
    }
  }
示例#13
0
 @Override
 public void init() throws ServletException {
   super.init();
   ServletContext context = getServletContext();
   productService =
       (ProductService) context.getAttribute(ApplicationConstants.PRODUCT_SERVICE.getValue());
 }
 @Override
 public void init() throws ServletException {
   super.init();
   ServletContext context = this.getServletContext();
   nnConf = (Configuration) context.getAttribute("name.conf");
   nn = (NameNode) context.getAttribute("name.node");
 }
  @Override
  public void init() throws ServletException {

    HibernateUtil.buildSessionFactory();

    super.init();
  }
示例#16
0
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    logger.info("get: " + req.getQueryString());

    String sessionId = req.getParameter("sessionId");
    if (!Utils.isNullOrEmpty(sessionId)) {
      Session session = getSessionCache().getSessionForSessionId(sessionId);
      if (session.getUserProfile() != null) {
        String picture = req.getParameter("picture");
        if ("tmp".equals(picture)) {
          String fileName = req.getParameter("filename");
          if (fileName.contains("..")) return;
          System.out.println("fnis:" + fileName);
          File picFile = new File(Backend.getWorkDir() + "tmpfiles" + File.separator + fileName);

          OutputStream out = resp.getOutputStream();
          FileInputStream fi = new FileInputStream(picFile);
          resp.setContentType("image");
          IOUtils.copy(fi, out);
          fi.close();
          out.close();

        } else if ("user".equals(picture)) {
          try {
            byte[] rawPicture = null;
            String fromUniqueUserId = req.getParameter("uniqueUserId");

            if (session.getUserProfile().getUniqueUserID().equals(fromUniqueUserId)) {
              if (Boolean.parseBoolean(req.getParameter("bigPicture"))) {
                logger.info("sending big user picture");
                rawPicture = session.getUserProfile().getUserCredentials().getPicture();
              } else {
                logger.info("sending small user picture");
                rawPicture = session.getUserProfile().getUserCredentials().getSmallPicture();
              }
            }
            OutputStream out = resp.getOutputStream();
            if (rawPicture == null) {
              FileInputStream fi =
                  new FileInputStream(
                      Backend.getWebContentFolder().getAbsolutePath()
                          + File.separator
                          + "images"
                          + File.separator
                          + "replacement_user_image.png");
              resp.setContentType("image");
              IOUtils.copy(fi, out);
              fi.close();
            } else {
              out.write(rawPicture);
            }
            out.close();
          } catch (Exception e) {
            logger.error("error sending user picture", e);
          }
        }
      }
    } else super.doGet(req, resp);
  }
示例#17
0
  /**
   * Initialize the backend systems, the log handler and the restrictor. A subclass can tune this
   * step by overriding {@link #createRestrictor(String)} and {@link
   * #createLogHandler(ServletConfig, boolean)}
   *
   * @param pServletConfig servlet configuration
   */
  @Override
  public void init(ServletConfig pServletConfig) throws ServletException {
    super.init(pServletConfig);

    Configuration config = initConfig(pServletConfig);

    // Create a log handler early in the lifecycle, but not too early
    String logHandlerClass = config.get(ConfigKey.LOGHANDLER_CLASS);
    logHandler =
        logHandlerClass != null
            ? (LogHandler) ClassUtil.newInstance(logHandlerClass)
            : createLogHandler(pServletConfig, Boolean.valueOf(config.get(ConfigKey.DEBUG)));

    // Different HTTP request handlers
    httpGetHandler = newGetHttpRequestHandler();
    httpPostHandler = newPostHttpRequestHandler();

    if (restrictor == null) {
      restrictor =
          createRestrictor(NetworkUtil.replaceExpression(config.get(ConfigKey.POLICY_LOCATION)));
    } else {
      logHandler.info("Using custom access restriction provided by " + restrictor);
    }
    configMimeType = config.get(ConfigKey.MIME_TYPE);
    backendManager = new BackendManager(config, logHandler, restrictor);
    requestHandler = new HttpRequestHandler(config, backendManager, logHandler);

    initDiscoveryMulticast(config);
  }
  @Override
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
    System.setProperty("kotlin.running.in.server.mode", "true");
    System.setProperty("java.awt.headless", "true");

    ApplicationSettings.WEBAPP_ROOT_DIRECTORY = getServletContext().getRealPath("/");
    ApplicationSettings.EXAMPLES_DIRECTORY = ApplicationSettings.WEBAPP_ROOT_DIRECTORY + "examples";
    CommonSettings.HELP_DIRECTORY = ApplicationSettings.WEBAPP_ROOT_DIRECTORY;

    if (!loadTomcatParameters()) {
      ErrorWriter.writeErrorToConsole(
          "FATAL ERROR: Cannot load parameters from tomcat config, server didn't start");
      System.exit(1);
    }

    ErrorWriter.ERROR_WRITER = ErrorWriter.getInstance();
    //        Initializer.INITIALIZER = ServerInitializer.getInstance();

    try {
      ErrorWriter.writeInfoToConsole("Use \"help\" to look at all options");
      new File(CommonSettings.LOGS_DIRECTORY).mkdirs();
      LogWriter.init();
      ExamplesLoader.loadAllExamples();
      HelpLoader.getInstance();
      MySqlConnector.getInstance();
    } catch (Throwable e) {
      ErrorWriter.writeExceptionToConsole(
          "FATAL ERROR: Initialisation of java core environment failed, server didn't start", e);
      System.exit(1);
    }
  }
示例#19
0
 public void init(ServletConfig config) throws ServletException {
   super.init(config);
   ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext());
   dao = (DerbyDao) ctx.getBean("personDao");
   txManager = (PlatformTransactionManager) ctx.getBean("transactionManager");
   dao.createTable();
 }
 /*
  * (non-Javadoc)
  *
  * @see javax.servlet.GenericServlet#init()
  */
 @Override
 public void init() throws ServletException {
   super.init();
   try {
     LoadTest.start();
     LOGGER.info("Server started successfully.");
     LoadTest.getLoadTestServer().logState();
   } catch (ServerStartupException e) {
     LoadTest.getLoadTestServer().setServerStartupError(e);
     List<String> messages = new ArrayList<String>();
     messages.add("!!!! SiteWhere Load Test Node Failed to Start !!!!");
     messages.add("");
     messages.add("Component: " + e.getDescription());
     messages.add("Error: " + e.getComponent().getLifecycleError().getMessage());
     String message = StringMessageUtils.getBoilerPlate(messages, '*', 60);
     LOGGER.info("\n" + message + "\n");
   } catch (SiteWhereException e) {
     List<String> messages = new ArrayList<String>();
     messages.add("!!!! SiteWhere Load Test Node Failed to Start !!!!");
     messages.add("");
     messages.add("Error: " + e.getMessage());
     String message = StringMessageUtils.getBoilerPlate(messages, '*', 60);
     LOGGER.info("\n" + message + "\n");
   } catch (Throwable e) {
     List<String> messages = new ArrayList<String>();
     messages.add("!!!! Unhandled Exception !!!!");
     messages.add("");
     messages.add("Error: " + e.getMessage());
     String message = StringMessageUtils.getBoilerPlate(messages, '*', 60);
     LOGGER.info("\n" + message + "\n");
   }
 }
示例#21
0
 @Override
 public void init() throws ServletException {
   super.init();
   ServletContext ctx = getServletContext();
   service = (BookService) ctx.getAttribute("BookService");
   log.trace("Get attribute BookService --> " + service);
 }
示例#22
0
 @Override
 public void init() throws ServletException {
   super.init();
   ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
   ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
   ve.init();
 }
示例#23
0
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String pathInfo = req.getPathInfo();

    if (pathInfo.equals("/")) {
      HttpSession session = req.getSession();
      if (session == null) {
        resp.setStatus(401);
        return;
      }
      String username = (String) session.getAttribute("username");
      if (username == null) {
        resp.setStatus(401);
        return;
      }

      Map userMap = loadUserSettingsMap(username);
      if (userMap == null) {
        resp.setStatus(401);
        return;
      }
      Enumeration parameterNames = req.getParameterNames();
      while (parameterNames.hasMoreElements()) {
        String parameterName = (String) parameterNames.nextElement();
        userMap.put(parameterName, req.getParameter(parameterName));
      }
      saveUserSettingsMap(username, userMap);
      return;
    }

    super.doPost(req, resp);
  }
示例#24
0
  @Override
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
    resourcesPrefix = config.getInitParameter("resources.prefix");
    if (resourcesPrefix == null) {
      resourcesPrefix = "/skin";
    }
    String name = config.getInitParameter("application.name");
    if (name == null) {
      name = ApplicationManager.DEFAULT_HOST;
    }
    app = ApplicationManager.getInstance().getOrCreateApplication(name);
    // use init parameters that are booleans as features
    for (Enumeration<String> en = config.getInitParameterNames(); en.hasMoreElements(); ) {
      String n = en.nextElement();
      String v = config.getInitParameter(n);
      if (Boolean.TRUE.toString().equals(v) || Boolean.FALSE.toString().equals(v)) {
        app.getFeatures().put(n, Boolean.valueOf(v));
      }
    }
    container = createServletContainer(app);

    initContainer(config);
    app.setRendering(initRendering(config));

    app.addReloadListener(this);
  }
 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   super.doPost(req, resp);
   service(req, resp);
   log("method POST");
 }
示例#26
0
 /**
  * @param config
  * @throws ServletException
  */
 @Override
 public void init(ServletConfig config) throws ServletException {
   super.init(config);
   studentBookDAO = StudentBookDAO.getInstance();
   studentDAO = StudentDAO.getInstance();
   bookDAO = BookDAO.getInstance();
 }
示例#27
0
  public void init(ServletConfig config) throws ServletException {
    JmxRegistration.register();

    super.init(config);
    String path = this.getServletContext().getRealPath("/");
    OnlineResourceManager.setOnceRootPath(path);

    String csINIFilePath = config.getInitParameter("INIFilePath");
    csINIFilePath = OnlineResourceManager.getRootPath() + csINIFilePath;

    String csAppliRootPath = config.getInitParameter("ApplicationRootPath");
    OnlineResourceManager.setApplicationRootPath(csAppliRootPath);

    m_ResourceManager = OnlineResourceManagerFactory.GetInstance(csINIFilePath);

    /*
    	m_ResourceManager.setXMLConfigFilePath(csINIFilePath) ;
    	m_ResourceManager.Init() ;

    	m_ResourceManager.loadDBSemanticContextDef();

    	// Load semantic context data dictionnary: Defines semantic context associtaed to DB columns


    	// Load semantic context configuration file: Defines menus, options, ...
    	String csSemanticContext = m_ResourceManager.getSemanticContextPathFile();
    	if(csSemanticContext != null && csSemanticContext.length() != 0)
    	{
    		SemanticManager semanticManager = SemanticManager.GetInstance();
    		semanticManager.Init(csSemanticContext);
    		m_ResourceManager.registerSemanticManager(semanticManager);
    	}
    */
  }
  @Override
  public void destroy() {
    super.destroy();

    // Activity log
    UserActivity.log(Config.SYSTEM_USER, "MISC_OPENKM_STOP", null, null, null);

    // Invoke stop
    stop(this);

    try {
      // Database shutdown
      log.info("*** Hibernate shutdown ***");
      HibernateUtil.closeSessionFactory();
    } catch (Exception e) {
      log.error(e.getMessage(), e);
    }

    try {
      // Call only once during destroy time of your application
      // @see http://issues.openkm.com/view.php?id=1577
      SLF4JBridgeHandler.uninstall();
    } catch (Exception e) {
      log.error(e.getMessage(), e);
    }
  }
示例#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);
  }
  @Override
  public void init(ServletConfig config) throws ServletException {
    super.init(config);

    String initial = "<i>" + config.getInitParameter("mensajes") + "</i>";
    alMensajes.add("Bienvenido/a. Este es el ausiasChat de DAW.");
  }