Example #1
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);
    }
  }
Example #2
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);
  }
Example #3
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
      }
    }
  }
Example #4
0
 public void destroy() {
   super.destroy();
   try {
     link.close();
   } catch (Exception e) {
     System.err.println(e.getMessage());
   }
 }
 /** Run once when servlet loaded. */
 public void init(ServletConfig config) throws ServletException {
   super.init(config);
   context = config.getServletContext();
   theApp = (LockssApp) context.getAttribute(ServletManager.CONTEXT_ATTR_LOCKSS_APP);
   servletMgr = (ServletManager) context.getAttribute(ServletManager.CONTEXT_ATTR_SERVLET_MGR);
   if (theApp instanceof LockssDaemon) {
     acctMgr = getLockssDaemon().getAccountManager();
   }
 }
Example #6
0
 /** {@inheritDoc} */
 @Override
 public void destroy() {
   backendManager.destroy();
   if (discoveryMulticastResponder != null) {
     discoveryMulticastResponder.stop();
     discoveryMulticastResponder = null;
   }
   super.destroy();
 }
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
    ctx = config.getServletContext();
    // set the response content type
    if (ctx.getInitParameter("responseContentType") != null) {
      responseContentType = ctx.getInitParameter("responseContentType");
    }
    // allow for resources dir over-ride at the xhp level otherwise allow
    // for the jmaki level resources
    if (ctx.getInitParameter("jmaki-xhp-resources") != null) {
      resourcesDir = ctx.getInitParameter("jmaki-xhp-resources");
    } else if (ctx.getInitParameter("jmaki-resources") != null) {
      resourcesDir = ctx.getInitParameter("jmaki-resources");
    }
    // allow for resources dir over-ride
    if (ctx.getInitParameter("jmaki-classpath-resources") != null) {
      classpathResourcesDir = ctx.getInitParameter("jmaki-classpath-resources");
    }

    String requireSessionString = ctx.getInitParameter("requireSession");
    if (requireSessionString != null) {
      if ("false".equals(requireSessionString)) {
        requireSession = false;
        getLogger().severe("XmlHttpProxyServlet: intialization. Session requirement disabled.");
      } else if ("true".equals(requireSessionString)) {
        requireSession = true;
        getLogger().severe("XmlHttpProxyServlet: intialization. Session requirement enabled.");
      }
    }
    String xdomainString = ctx.getInitParameter("allowXDomain");
    if (xdomainString != null) {
      if ("true".equals(xdomainString)) {
        allowXDomain = true;
        getLogger().severe("XmlHttpProxyServlet: intialization. xDomain access is enabled.");
      } else if ("false".equals(xdomainString)) {
        allowXDomain = false;
        getLogger().severe("XmlHttpProxyServlet: intialization. xDomain access is disabled.");
      }
    }
    // if there is a proxyHost and proxyPort specified create an HttpClient with the proxy
    String proxyHost = ctx.getInitParameter("proxyHost");
    String proxyPortString = ctx.getInitParameter("proxyPort");
    if (proxyHost != null && proxyPortString != null) {
      int proxyPort = 8080;
      try {
        proxyPort = new Integer(proxyPortString).intValue();
        xhp = new XmlHttpProxy(proxyHost, proxyPort);
      } catch (NumberFormatException nfe) {
        getLogger()
            .severe("XmlHttpProxyServlet: intialization error. The proxyPort must be a number");
        throw new ServletException(
            "XmlHttpProxyServlet: intialization error. The proxyPort must be a number");
      }
    } else {
      xhp = new XmlHttpProxy();
    }
  }
Example #8
0
  public JxpSource getJxpServlet(String name) {
    JxpSource source = _httpServlets.get(name);
    if (source != null) return source;

    try {
      Class c = Class.forName(name);
      Object n = c.newInstance();
      if (!(n instanceof HttpServlet))
        throw new RuntimeException("class [" + name + "] is not a HttpServlet");

      HttpServlet servlet = (HttpServlet) n;
      servlet.init(createServletConfig(name));
      source = new ServletSource(servlet);
      _httpServlets.put(name, source);
      return source;
    } catch (Exception e) {
      throw new RuntimeException("can't load [" + name + "]", e);
    }
  }
 public void init(ServletConfig config) throws ServletException {
   super.init(config);
   //		Timer t=new Timer(2000, new ActionListener(){
   //			public void actionPerformed(ActionEvent e){
   //				System.out.println(new Date());
   //			}
   //
   //		});
   //		t.start();
 }
Example #10
0
  @Override
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
    String initial = getServletContext().getInitParameter("pagina");
    ;

    try {
      count = Integer.parseInt(initial);
    } catch (NumberFormatException e) {
      count = 0;
    }
  }
Example #11
0
  public static void showServletInfo(HttpServlet servlet, PrintStream out) {
    out.println("Servlet Info");
    out.println(" getServletName(): " + servlet.getServletName());
    out.println(" getRootPath(): " + getRootPath());
    out.println(" Init Parameters:");
    Enumeration params = servlet.getInitParameterNames();
    while (params.hasMoreElements()) {
      String name = (String) params.nextElement();
      out.println("  " + name + ": " + servlet.getInitParameter(name));
    }
    out.println();

    ServletContext context = servlet.getServletContext();
    out.println("Context Info");

    try {
      out.println(" context.getResource('/'): " + context.getResource("/"));
    } catch (java.net.MalformedURLException e) {
    } // cant happen
    out.println(" context.getServerInfo(): " + context.getServerInfo());
    out.println("  name: " + getServerInfoName(context.getServerInfo()));
    out.println("  version: " + getServerInfoVersion(context.getServerInfo()));

    out.println(" context.getInitParameterNames():");
    params = context.getInitParameterNames();
    while (params.hasMoreElements()) {
      String name = (String) params.nextElement();
      out.println("  " + name + ": " + context.getInitParameter(name));
    }

    out.println(" context.getAttributeNames():");
    params = context.getAttributeNames();
    while (params.hasMoreElements()) {
      String name = (String) params.nextElement();
      out.println("  context.getAttribute(\"" + name + "\"): " + context.getAttribute(name));
    }

    out.println();
  }
Example #12
0
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
    try {

      int a;
      a = 3;
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      String url = "jdbc:odbc:books";
      connection = DriverManager.getConnection(url);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Example #13
0
  /**
   * Write a file to the response stream. Handles Range requests.
   *
   * @param servlet called from here
   * @param req the request
   * @param res the response
   * @param file to serve
   * @param contentType content type, if null, will try to guess
   * @throws IOException on write error
   */
  public static void returnFile(
      HttpServlet servlet,
      HttpServletRequest req,
      HttpServletResponse res,
      File file,
      String contentType)
      throws IOException {

    // No file, nothing to view
    if (file == null) {
      log.info(
          "returnFile(): "
              + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_NOT_FOUND, 0));
      res.sendError(HttpServletResponse.SC_NOT_FOUND);
      return;
    }

    // check that it exists
    if (!file.exists()) {
      log.info(
          "returnFile(): "
              + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_NOT_FOUND, 0));
      res.sendError(HttpServletResponse.SC_NOT_FOUND);
      return;
    }

    // not a directory
    if (!file.isFile()) {
      log.info(
          "returnFile(): "
              + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_BAD_REQUEST, 0));
      res.sendError(HttpServletResponse.SC_BAD_REQUEST);
      return;
    }

    // Set the type of the file
    String filename = file.getPath();
    if (null == contentType) {
      if (filename.endsWith(".html")) contentType = "text/html; charset=iso-8859-1";
      else if (filename.endsWith(".xml")) contentType = "text/xml; charset=iso-8859-1";
      else if (filename.endsWith(".txt") || (filename.endsWith(".log"))) contentType = CONTENT_TEXT;
      else if (filename.indexOf(".log.") > 0) contentType = CONTENT_TEXT;
      else if (filename.endsWith(".nc")) contentType = "application/x-netcdf";
      else contentType = servlet.getServletContext().getMimeType(filename);

      if (contentType == null) contentType = "application/octet-stream";
    }

    returnFile(req, res, file, contentType);
  }
 public void init(ServletConfig servletconfig) throws ServletException {
   super.init(servletconfig);
   try {
     System.out.println("inside init");
     Class.forName("oracle.jdbc.driver.OracleDriver");
     System.out.println("driver is created");
     con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "care", "care");
     System.out.println("Connection is created");
     st = con.createStatement();
     System.out.println("statement is created");
   } catch (Exception exception) {
     System.out.println(exception);
   }
 }
Example #15
0
 /**
  * @param config the ServletConfig object that contains configutation information for this
  *     servlet.
  * @exception ServletException if an exception occurs that interrupts the servlet's normal
  *     operation.
  */
 public void init(ServletConfig config) throws ServletException {
   super.init(config);
   if (debug.messageEnabled()) {
     debug.message("CDCClientServlet.init:CDCClientServlet " + "Initializing...");
   }
   try {
     tokenManager = SSOTokenManager.getInstance();
   } catch (SSOException ssoe) {
     debug.error("CDCClientServlet.init:unable to get SSOTokenManager", ssoe);
   }
   authURLCookieName =
       SystemProperties.get(Constants.AUTH_UNIQUE_COOKIE_NAME, "sunIdentityServerAuthNServer");
   authURLCookieDomain = SystemProperties.get(Constants.AUTH_UNIQUE_COOKIE_DOMAIN, "");
   deployDescriptor =
       SystemProperties.get(Constants.AM_DISTAUTH_DEPLOYMENT_DESCRIPTOR, "/distauth");
 }
  @Override
  public void init(ServletConfig config) throws ServletException {
    super.init(config);

    // --- Forward proxy setup (only if needed) ---
    ProxyProperties proxyProps = getProxyProperties(config);
    if (proxyProps != null) {
      LOG.debug("ProxyProperties: " + proxyProps);
      HttpClientFactory.setProxyProperties(proxyProps);
    }

    manager = new ConsumerManager();
    manager.setAssociations(new InMemoryConsumerAssociationStore());
    manager.setNonceVerifier(new InMemoryNonceVerifier(5000));
    manager.setMinAssocSessEnc(AssociationSessionType.DH_SHA256);
  }
 public void init(ServletConfig sc) throws ServletException {
   super.init(sc);
   try {
     Class.forName("com.mysql.jdbc.Driver");
     System.out.println("driver is loaded");
     con = DriverManager.getConnection(url, un, password);
     System.out.println("connected");
     stmt = con.createStatement();
     System.out.println("wrapper created");
   } catch (ClassNotFoundException cnfe) {
     System.out.println("driver Not Loaded" + cnfe.getMessage());
     return;
   } catch (SQLException sqle) {
     System.out.println("connection problem" + sqle.getMessage());
     return;
   }
 }
Example #18
0
  public void init(ServletConfig config) throws ServletException {
    try {

      String ps = config.getServletContext().getRealPath("/WEB-INF/jiql.properties");
      if (!new File(ps).exists()) {
        return;
      }
      NameValuePairs p = new NameValuePairs(ps);
      theUser = (String) p.get("user");
      thePassword = (String) p.get("password");
      if (p.getInt("maxUpload") > 0) mU = p.getInt("maxUpload");

    } catch (Exception e) {
      tools.util.LogMgr.err("JiqlServlet.init " + e.toString());
      e.printStackTrace(System.out);
    }
    super.init(config);
  }
Example #19
0
 @Override
 public void init(final ServletConfig config) throws ServletException {
   super.init(config);
   try {
     HTTPContext.init(config.getServletContext());
     final Enumeration<String> en = config.getInitParameterNames();
     while (en.hasMoreElements()) {
       String key = en.nextElement().toLowerCase(Locale.ENGLISH);
       final String val = config.getInitParameter(key);
       if (key.startsWith(Prop.DBPREFIX)) key = key.substring(Prop.DBPREFIX.length());
       if (key.equalsIgnoreCase(MainProp.USER[0].toString())) {
         user = val;
       } else if (key.equalsIgnoreCase(MainProp.PASSWORD[0].toString())) {
         pass = val;
       }
     }
   } catch (final IOException ex) {
     throw new ServletException(ex);
   }
 }
Example #20
0
 @Override
 public void init(final ServletConfig config) throws ServletException {
   super.init(config);
   try {
     HTTPContext.init(config.getServletContext());
     final Enumeration<String> en = config.getInitParameterNames();
     while (en.hasMoreElements()) {
       String key = en.nextElement().toLowerCase(Locale.ENGLISH);
       final String val = config.getInitParameter(key);
       if (key.startsWith(Prop.DBPREFIX)) key = key.substring(Prop.DBPREFIX.length());
       if (key.equalsIgnoreCase(StaticOptions.USER.name())) {
         username = val;
       } else if (key.equalsIgnoreCase(StaticOptions.PASSWORD.name())) {
         password = val;
       } else if (key.equalsIgnoreCase(StaticOptions.AUTHMETHOD.name())) {
         auth = AuthMethod.valueOf(val);
       }
     }
   } catch (final IOException ex) {
     throw new ServletException(ex);
   }
 }
 public void init(ServletConfig config) throws javax.servlet.ServletException {
   super.init(config);
 }
Example #22
0
 public void init(ServletConfig conf) throws ServletException {
   super.init(conf);
 }
Example #23
0
 /**
  * Initializes the servlet.
  *
  * @throws ServletException Serlvet Init Error.
  */
 @Override
 public void init() throws ServletException {
   super.init();
   accessControl = SpringUtil.getAccessControl();
 }
 @Override
 public void destroy() {
   super.destroy();
 }
 @Override
 public void init(ServletConfig config) throws ServletException {
   super.init(config);
 }
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("utf-8");
    if (jjNumber.isDigit(jjTools.getParameter(request, "maxSize"))) {
      maxSize = Long.parseLong(jjTools.getParameter(request, "maxSize"));
    }

    response.setCharacterEncoding("utf-8");
    String name = request.getParameter("name");
    name = name == null ? "" : name;
    response.setContentType("text/plain");
    super.init(getServletConfig());
    //        response.setContentType("text/plain");
    PrintWriter out = response.getWriter();
    //        out.println();

    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    //        fileItemFactory.setSizeThreshold(1024 * 1024); //1 MB

    try {
      ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
      List items = uploadHandler.parseRequest(request);
      Iterator itr = items.iterator();
      while (itr.hasNext()) {
        FileItem item = (FileItem) itr.next();
        if (item.isFormField()) {
          /*
           * Field
           */
          //                    out.println("Field Name=" + item.getFieldName() + ", Value=" +
          // item.getString());
          data.put(item.getFieldName(), item.getString());
        } else {
          /*
           * File
           */
          File folderAddress =
              new File(request.getServletContext().getRealPath(Save_Folder_Name)); // "/" +
          String extension = "";
          String nameWithoutExtension = item.getName();
          if (item.getName().lastIndexOf(".") > -1) {
            extension = item.getName().substring(item.getName().lastIndexOf("."));
            nameWithoutExtension =
                item.getName()
                    .substring(
                        item.getName().lastIndexOf("\\") + 1, item.getName().lastIndexOf("."));
          }
          folderAddress.mkdirs();
          nameWithoutExtension = "P";
          File file =
              new File(
                  folderAddress
                      + "/"
                      + nameWithoutExtension.toLowerCase()
                      + jjNumber.getRandom(10)
                      + extension.toLowerCase());
          String i = "0000000000";
          while (file.exists()) {
            i = jjNumber.getRandom(10);
            file =
                new File(
                    folderAddress
                        + "/"
                        + nameWithoutExtension.toLowerCase()
                        + i
                        + extension.toLowerCase());
          }
          if (!name.equals("")) {
            file = new File(folderAddress + "/" + name);
          }
          //                    out.println("File Name=" + item.getName()
          //                            + ", Field Name=" + item.getFieldName()
          //                            + ", Content type=" + item.getContentType()
          //                            + ", File Size=" + item.getSize()
          //                            + ", Save Address=" + file);
          //                    out.println(file);
          //                    String urlPath =
          // request.getRequestURL().toString().replace("Upload2", "Upload") + "/" +
          // file.getName().replace("\\", "/");
          //                    out.println("<html><head><meta http-equiv='Content-Type'
          // content='text/html; charset=utf-8'></head><body><input type='text' name='T1' size='58'
          // value='" + urlPath + "'></body></html>");
          data.put(item.getFieldName(), file.getAbsolutePath());
          if (!file.getName().toLowerCase().endsWith(".exe")) {
            item.write(file);
          }
          long size = file.length();
          ServerLog.Print("?>>>>>>" + file + "   -    Size:" + size);
          if (size > maxSize) {
            file.delete();
            out.print("big");
          } else {
            out.print(
                file.getName()
                    .replace(" ", "%20")
                    .replace("<pre style=\"word-wrap: break-word; white-space: pre-wrap;\">", ""));
            ServerLog.Print("Write pic in: " + file + " size:" + file.length());
            String name2 = file.getName().substring(0, file.getName().lastIndexOf("."));
            String extension2 =
                file.getName()
                    .substring(file.getName().lastIndexOf(".") + 1, file.getName().length());
            File file2 = new File(file.getParent() + "/" + name2 + "_small." + extension2);
            if (extension2.toLowerCase().equals("jpg")
                || extension2.toLowerCase().equals("png")
                || extension2.toLowerCase().equals("gif")) {
              jjPicture.doChangeSizeOfPic(file, file2, 250);
            }
          }
        }
      }
    } catch (Exception ex) {
      Server.ErrorHandler(ex);
    }
    out.flush();
    out.close();
  }
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
    context = config.getServletContext();

    TextProcessor tp = new CaseFolder();

    try {
      wikipedia =
          new Wikipedia(
              context.getInitParameter("mysql_server"),
              context.getInitParameter("mysql_database"),
              context.getInitParameter("mysql_user"),
              context.getInitParameter("mysql_password"));
    } catch (Exception e) {
      throw new ServletException("Could not connect to wikipedia database.");
    }

    // Escaper escaper = new Escaper() ;

    definer = new Definer(this);
    comparer = new Comparer(this);
    searcher = new Searcher(this);

    try {
      wikifier = new Wikifier(this, tp);

    } catch (Exception e) {
      System.err.println("Could not initialize wikifier");
    }

    try {
      File dataDirectory = new File(context.getInitParameter("data_directory"));

      if (!dataDirectory.exists() || !dataDirectory.isDirectory()) {
        throw new Exception();
      }

      cachingThread = new CacherThread(dataDirectory, tp);
      cachingThread.start();
    } catch (Exception e) {
      throw new ServletException("Could not locate wikipedia data directory.");
    }

    try {
      TransformerFactory tf = TransformerFactory.newInstance();

      transformersByName = new HashMap<String, Transformer>();
      transformersByName.put(
          "help", buildTransformer("help", new File("/research/wikipediaminer/web/xsl"), tf));
      transformersByName.put(
          "loading", buildTransformer("loading", new File("/research/wikipediaminer/web/xsl"), tf));
      transformersByName.put(
          "search", buildTransformer("search", new File("/research/wikipediaminer/web/xsl"), tf));
      transformersByName.put(
          "compare", buildTransformer("compare", new File("/research/wikipediaminer/web/xsl"), tf));
      transformersByName.put(
          "wikify", buildTransformer("wikify", new File("/research/wikipediaminer/web/xsl"), tf));

      Transformer serializer = TransformerFactory.newInstance().newTransformer();
      serializer.setOutputProperty(OutputKeys.INDENT, "yes");
      serializer.setOutputProperty(OutputKeys.METHOD, "xml");
      serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");
      transformersByName.put("serializer", serializer);

    } catch (Exception e) {
      throw new ServletException("Could not load xslt library.");
    }
  }
Example #28
0
 public void init(ServletConfig config) throws ServletException {
   super.init(config);
   // 获取Web应用中的ApplicationContext实例
   ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
 }
Example #29
0
 /**
  * called when the class is loaded to initialize the servlet
  *
  * @param config ServletConfig:
  */
 public void init(ServletConfig config) throws ServletException {
   super.init(config);
   initTime = new java.util.Date().toString();
   hitCount = 0;
 }
Example #30
0
 @Override
 public void init() throws ServletException {
   super.init();
   return;
 }