@DataBoundConstructor
  public WwpassSecurityRealm(String certFile, String keyFile, String name, boolean allowsSignup) {

    this.disableSignup = !allowsSignup;

    this.name = name;

    if (certFile != null && !certFile.isEmpty() && keyFile != null && !keyFile.isEmpty()) {
      this.certFile = certFile;
      this.keyFile = keyFile;
    } else {
      if (System.getProperty("os.name").startsWith("Windows")) {
        this.certFile = DEFAULT_CERT_FILE_WINDOWS;
        this.keyFile = DEFAULT_KEY_FILE_WINDOWS;
      } else if (System.getProperty("os.name").startsWith("Linux")) {
        this.certFile = DEFAULT_CERT_FILE_LINUX;
        this.keyFile = DEFAULT_KEY_FILE_LINUX;
      } else {
        LOGGER.severe(Messages.WwpassSession_UnsupportedOsError());
        throw new Failure(Messages.WwpassSession_AuthError());
      }
    }

    if (!hasSomeUser()) {
      // if Hudson is newly set up with the security realm and there's no user account created yet,
      // insert a filter that asks the user to create one
      try {
        PluginServletFilter.addFilter(CREATE_FIRST_USER_FILTER);
      } catch (ServletException e) {
        throw new AssertionError(e); // never happen because our Filter.init is no-op
      }
    }
  }
  /**
   * Constructor.
   *
   * @param rq request
   * @param rs response
   * @throws IOException I/O exception
   */
  public HTTPContext(final HttpServletRequest rq, final HttpServletResponse rs) throws IOException {

    req = rq;
    res = rs;
    final String m = rq.getMethod();
    method = HTTPMethod.get(m);

    final StringBuilder uri = new StringBuilder(req.getRequestURL());
    final String qs = req.getQueryString();
    if (qs != null) uri.append('?').append(qs);
    log(false, m, uri);

    // set UTF8 as default encoding (can be overwritten)
    res.setCharacterEncoding(UTF8);

    segments = toSegments(req.getPathInfo());
    path = join(0);

    user = System.getProperty(DBUSER);
    pass = System.getProperty(DBPASS);

    // set session-specific credentials
    final String auth = req.getHeader(AUTHORIZATION);
    if (auth != null) {
      final String[] values = auth.split(" ");
      if (values[0].equals(BASIC)) {
        final String[] cred = Base64.decode(values[1]).split(":", 2);
        if (cred.length != 2) throw new LoginException(NOPASSWD);
        user = cred[0];
        pass = cred[1];
      } else {
        throw new LoginException(WHICHAUTH, values[0]);
      }
    }
  }
Example #3
0
  /** For debugging. */
  public static void main(String[] args) throws Exception {
    final String usage = "NutchBean query";

    if (args.length == 0) {
      System.err.println(usage);
      System.exit(-1);
    }

    final Configuration conf = NutchConfiguration.create();
    final NutchBean bean = new NutchBean(conf);
    try {
      final Query query = Query.parse(args[0], conf);
      final Hits hits = bean.search(query, 10);
      System.out.println("Total hits: " + hits.getTotal());
      final int length = (int) Math.min(hits.getTotal(), 10);
      final Hit[] show = hits.getHits(0, length);
      final HitDetails[] details = bean.getDetails(show);
      final Summary[] summaries = bean.getSummary(details, query);

      for (int i = 0; i < hits.getLength(); i++) {
        System.out.println(" " + i + " " + details[i] + "\n" + summaries[i]);
      }
    } catch (Throwable t) {
      LOG.error("Exception occured while executing search: " + t, t);
      System.exit(1);
    }
    System.exit(0);
  }
Example #4
0
 // For war agent needs to be switched on
 private boolean listenForDiscoveryMcRequests(Configuration pConfig) {
   // Check for system props, system env and agent config
   boolean sysProp =
       System.getProperty("jolokia." + ConfigKey.DISCOVERY_ENABLED.getKeyValue()) != null;
   boolean env = System.getenv("JOLOKIA_DISCOVERY") != null;
   boolean config = pConfig.getAsBoolean(ConfigKey.DISCOVERY_ENABLED);
   return sysProp || env || config;
 }
  boolean handleLoggedInUser(
      FilterChain chain,
      HttpServletRequest httpRequest,
      HttpServletResponse httpResponse,
      ServiceAccess serviceAccess,
      AuthorizationRequestData rdo)
      throws ServletException, IOException {

    VOUserDetails userDetails = rdo.getUserDetails();
    if (userDetails != null) {
      httpRequest.getSession().setAttribute(PORTAL_HAS_BEEN_REQUESTED, !rdo.isMarketplace());

      // if the user wants to use another organization he must login
      // again (the service sessions are destroyed as well)

      // don't let a user with status PASSWORD_MUST_BE_CHANGED see any
      // site but the one to change the pwd
      if (!authSettings.isServiceProvider()) {
        if (userDetails.getStatus() == UserAccountStatus.PASSWORD_MUST_BE_CHANGED
            && !rdo.isRequestedToChangePwd()) {
          forwardToPwdPage(userDetails.getUserId(), httpRequest, httpResponse);
          return true;
        }
      }

      // TODO stavreva: check this again
      if (authSettings.isServiceProvider() || !rdo.isRequestedToChangePwd()) {
        long t = System.currentTimeMillis();
        if (ADMStringUtils.isBlank(httpRequest.getServletPath())
            || httpRequest.getServletPath().startsWith(MenuBean.LINK_DEFAULT)) {
          String defaultUrl = getDefaultUrl(serviceAccess, rdo, httpRequest);
          forward(defaultUrl, httpRequest, httpResponse);
        }

        if (loginPage.equalsIgnoreCase(httpRequest.getServletPath())) {
          sendRedirect(httpRequest, httpResponse, MenuBean.LINK_DEFAULT);
        }

        if (isPageForbiddenToAccess(httpRequest, rdo, serviceAccess)) {
          forward(insufficientAuthoritiesUrl, httpRequest, httpResponse);
        }
        chain.doFilter(httpRequest, httpResponse);
        if (logger.isDebugLoggingEnabled()) {
          logger.logDebug(
              "URL='"
                  + rdo.getRelativePath()
                  + "' processed in "
                  + (System.currentTimeMillis() - t)
                  + "ms");
        }
        return true;
      }
    }

    return false;
  }
Example #6
0
 // Try to find an URL for system props or config
 private String findAgentUrl(Configuration pConfig) {
   // System property has precedence
   String url = System.getProperty("jolokia." + ConfigKey.DISCOVERY_AGENT_URL.getKeyValue());
   if (url == null) {
     url = System.getenv("JOLOKIA_DISCOVERY_AGENT_URL");
     if (url == null) {
       url = pConfig.get(ConfigKey.DISCOVERY_AGENT_URL);
     }
   }
   return NetworkUtil.replaceExpression(url);
 }
  public void init(FilterConfig config) throws ServletException {

    Log log = LogFactory.getLog(this.getClass());
    log.info("PsqStoreConfigFilter: init(config) called");

    String path = "";

    try {
      URL pathUrl = config.getServletContext().getResource("/");

      path = new File(config.getServletContext().getRealPath("/")).getAbsolutePath();

      log.info(" protocol=" + pathUrl.getProtocol());
      log.info(" path=" + path);

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

    if (config.getInitParameter("derby-home") != null) {

      String myHome = config.getInitParameter("derby-home");
      if (!myHome.startsWith("/")) {
        myHome = path + File.separator + myHome;
      }

      log.info("derby-home(final)=" + myHome);
      System.setProperty("xpsq.derby.home", myHome);

      if (PsqContext.getStore("derby") != null) {
        PsqContext.getStore("derby").initialize();
      }
    }

    if (config.getInitParameter("bdb-home") != null) {

      String myHome = config.getInitParameter("bdb-home");
      if (!myHome.startsWith("/")) {
        myHome = path + File.separator + myHome;
      }

      log.info("bdb-home(final)=" + myHome);
      System.setProperty("xpsq.bdb.home", myHome);

      if (PsqContext.getStore("bdb") != null) {
        PsqContext.getStore("bdb").initialize();
      }
    }
  }
 /**
  * Writes a log message.
  *
  * @param str strings to be written
  * @param time add performance info
  */
 public void log(final boolean time, final Object... str) {
   final Object[] obj = new Object[str.length + (time ? 2 : 1)];
   obj[0] = remote();
   System.arraycopy(str, 0, obj, 1, str.length);
   if (time) obj[obj.length - 1] = perf.toString();
   context.log.write(obj);
 }
Example #9
0
  /** @param e */
  @Override
  public void contextInitialized(ServletContextEvent e) {
    ServletContext context = e.getServletContext();

    // retrieve jyro.home
    String dirName = context.getInitParameter(Jyro.JYRO_HOME);
    if (dirName == null) {
      dirName = System.getProperty(Jyro.JYRO_HOME);
      if (dirName == null) {
        throw new IllegalStateException(
            Jyro.JYRO_HOME + " not specified in servlet or context paramter, system property");
      }
    }

    // resolve relative path
    File dir = new File(dirName);
    if (!dir.isAbsolute()) {
      dirName = context.getRealPath(dirName);
      dir = new File(dirName);
    }
    logger.info(Jyro.JYRO_HOME + "=" + dirName);

    // build and startup Jyro
    String contextPath = context.getContextPath();
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    try {
      platform = new JyroPlatform(contextPath, dir, loader, null);
      platform.startup();
    } catch (Exception ex) {
      throw new IllegalStateException(ex);
    }
  }
/**
 * This filter is used in production, to put HTTP cache headers with a long (1 month) expiration
 * time.
 */
public class CachingHttpHeadersFilter implements Filter {

  // Cache period is 1 month (in ms)
  private static final long CACHE_PERIOD = TimeUnit.DAYS.toMillis(31L);

  // We consider the last modified date is the start up time of the server
  private static final long LAST_MODIFIED = System.currentTimeMillis();

  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
    // Nothing to initialize
  }

  @Override
  public void destroy() {
    // Nothing to destroy
  }

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    httpResponse.setHeader("Cache-Control", "max-age=2678400000, public");
    httpResponse.setHeader("Pragma", "cache");

    // Setting Expires header, for proxy caching
    httpResponse.setDateHeader("Expires", CACHE_PERIOD + System.currentTimeMillis());

    // Setting the Last-Modified header, for browser caching
    httpResponse.setDateHeader("Last-Modified", LAST_MODIFIED);

    chain.doFilter(request, response);
  }
}
Example #11
0
  public void init(FilterConfig filterConfig) throws ServletException {
    this.filterConfig = filterConfig;
    String configFile = System.getProperty("jboss.server.config.dir") + "/picketlink.xml";
    if (new File(configFile).exists()) this.configFile = configFile;

    this.servletContext = filterConfig.getServletContext();
    processConfiguration(filterConfig);
  }
 static {
   try {
     __nullServletWriter = new ServletWriter(IO.getNullStream());
     __nullServletOut = new ServletOut(IO.getNullStream());
   } catch (Exception e) {
     log.fatal(e);
     System.exit(1);
   }
 }
Example #13
0
  @Override
  public void doFilter(
      ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
      throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
    HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;

    // Skip oauth for local connections
    if (!"127.0.0.1".equals(servletRequest.getRemoteAddr())) {
      // Read the OAuth parameters from the request
      OAuthServletRequest request = new OAuthServletRequest(httpRequest);
      OAuthParameters params = new OAuthParameters();
      params.readRequest(request);

      String consumerKey = params.getConsumerKey();

      // Set the secret(s), against which we will verify the request
      OAuthSecrets secrets = new OAuthSecrets();
      secrets.setConsumerSecret(m_tokenStore.getToken(consumerKey));

      // Check that the timestamp has not expired
      String timestampStr = params.getTimestamp();
      if (timestampStr == null) {
        logger.warn("Missing OAuth headers");
        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Missing OAuth headers");
        return;
      }

      long msgTime = Util.parseLong(timestampStr) * 1000L; // Message time is in seconds
      long currentTime = System.currentTimeMillis();

      // if the message is older than 5 min it is no good
      if (Math.abs(msgTime - currentTime) > 300000) {
        logger.warn(
            "OAuth message time out, msg time: " + msgTime + " current time: " + currentTime);
        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Message expired");
        return;
      }

      // Verify the signature
      try {
        if (!OAuthSignature.verify(request, params, secrets)) {
          logger.warn("Invalid OAuth signature");

          httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid OAuth signature");
          return;
        }
      } catch (OAuthSignatureException e) {
        logger.warn("OAuth exception", e);

        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid OAuth request");
        return;
      }
    }

    filterChain.doFilter(servletRequest, servletResponse);
  }
Example #14
0
 public byte[] toByteArray() {
   byte[] newBuf = null;
   if (!wrapped) {
     // We haven't wrapped yet so copy up to the current position
     newBuf = new byte[position];
     System.arraycopy(buf, 0, newBuf, 0, position);
   } else {
     // We'll have wrapped, so it's a two step process.
     // Copy everything following the position, then everything before
     newBuf = new byte[buf.length];
     // "position" is where we'd write next so it's the oldest byte.
     // So copy starting there for as many as are between there and the end.
     System.arraycopy(buf, position, newBuf, 0, (buf.length - position));
     // Now copy starting at 0, placing into the end of the last copy, up to position.
     System.arraycopy(buf, 0, newBuf, (buf.length - position), position);
   }
   return newBuf;
 }
  @Override
  public void init(FilterConfig fc) throws ServletException {
    log.info("DispatcherFilter starting ...");
    log.info("java.version = {}", JdkUtils.JAVA_VERSION);
    log.info("webmvc.version = {}", WebConfig.VERSION);
    log.info("user.dir = {}", System.getProperty("user.dir"));
    log.info("java.io.tmpdir = {}", System.getProperty("java.io.tmpdir"));
    log.info("user.timezone = {}", System.getProperty("user.timezone"));
    log.info("file.encoding = {}", System.getProperty("file.encoding"));

    try {
      long ts = System.currentTimeMillis();

      ServletContext sc = fc.getServletContext();
      String configLocation = fc.getInitParameter("configLocation");
      WebInitializer.initialize(sc, configLocation);

      httpEncoding = WebConfig.getHttpEncoding();
      httpCache = WebConfig.isHttpCache();
      router = WebConfig.getRouter();
      bypassRequestUrls = WebConfig.getBypassRequestUrls();
      corsRequestProcessor = WebConfig.getCORSRequestProcessor();
      resultHandlerResolver = WebConfig.getResultHandlerResolver();
      fileUploadResolver = WebConfig.getFileUploadResolver();
      exceptionHandler = WebConfig.getExceptionHandler();

      log.info("web.root = {}", WebConfig.getWebroot());
      log.info("web.development = {}", WebConfig.isDevelopment());
      log.info("web.upload.dir = {}", WebConfig.getUploaddir());
      log.info("web.urls.router = {}", router.getClass().getName());
      log.info(
          "web.urls.bypass = {}",
          (bypassRequestUrls == null) ? null : bypassRequestUrls.getClass().getName());
      log.info(
          "web.urls.cors = {}",
          (corsRequestProcessor == null) ? null : corsRequestProcessor.getClass().getName());

      for (Plugin plugin : WebConfig.getPlugins()) {
        log.info("load plugin: {}", plugin.getClass().getName());
        plugin.initialize();
      }

      for (Interceptor interceptor : WebConfig.getInterceptors()) {
        log.info("load interceptor: {}", interceptor.getClass().getName());
        interceptor.initialize();
      }

      log.info(
          "DispatcherFilter initialize successfully, Time elapsed: {} ms.",
          System.currentTimeMillis() - ts);

    } catch (Exception e) {
      log.error("Failed to initialize DispatcherFilter", e);
      log.error("*************************************");
      log.error("          System.exit(1)             ");
      log.error("*************************************");
      System.exit(1);
    }
  }
Example #16
0
  public static void showServerInfo(PrintStream out) {
    out.println("Server Info");
    out.println(
        " getDocumentBuilderFactoryVersion(): "
            + XMLEntityResolver.getDocumentBuilderFactoryVersion());
    out.println();

    Properties sysp = System.getProperties();
    Enumeration e = sysp.propertyNames();
    List<String> list = Collections.list(e);
    Collections.sort(list);

    out.println("System Properties:");
    for (String name : list) {
      String value = System.getProperty(name);
      out.println("  " + name + " = " + value);
    }
    out.println();
  }
Example #17
0
 public void test_init_absolutePath() throws ServletException {
   String os = System.getProperty("os.name");
   if (os.startsWith("Windows")) {
     config.parameterValue = "C:/Temp";
   } else {
     config.parameterValue = "/abc/def";
   }
   servlet.init(config);
   assertEquals("prefix value", config.parameterValue, servlet.prefix);
 }
Example #18
0
  Object evalScript(
      String script,
      StringBuffer scriptOutput,
      boolean captureOutErr,
      HttpServletRequest request,
      HttpServletResponse response)
      throws EvalError {
    // Create a PrintStream to capture output
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream pout = new PrintStream(baos);

    // Create an interpreter instance with a null inputstream,
    // the capture out/err stream, non-interactive
    Interpreter bsh = new Interpreter(null, pout, pout, false);

    // set up interpreter
    bsh.set("bsh.httpServletRequest", request);
    bsh.set("bsh.httpServletResponse", response);

    // Eval the text, gathering the return value or any error.
    Object result = null;
    String error = null;
    PrintStream sout = System.out;
    PrintStream serr = System.err;
    if (captureOutErr) {
      System.setOut(pout);
      System.setErr(pout);
    }
    try {
      // Eval the user text
      result = bsh.eval(script);
    } finally {
      if (captureOutErr) {
        System.setOut(sout);
        System.setErr(serr);
      }
    }
    pout.flush();
    scriptOutput.append(baos.toString());
    return result;
  }
  @Override
  public HttpSession getSession() {
    long key = 0;
    if (getCookies().length == 0) {
      key = System.nanoTime();
      THttpSessionStore.set(key);
    } else {
      key = Long.parseLong(getCookies()[0].getValue());
    }

    return THttpSessionStore.get(key);
  }
  /**
   * Initializes the servlet context, based on the servlet context. Parses all context parameters
   * and passes them on to the database context.
   *
   * @param sc servlet context
   * @throws IOException I/O exception
   */
  static synchronized void init(final ServletContext sc) throws IOException {
    // skip process if context has already been initialized
    if (context != null) return;

    // set servlet path as home directory
    final String path = sc.getRealPath("/");
    System.setProperty(Prop.PATH, path);

    // parse all context parameters
    final HashMap<String, String> map = new HashMap<String, String>();
    // store default web root
    map.put(MainProp.HTTPPATH[0].toString(), path);

    final Enumeration<?> en = sc.getInitParameterNames();
    while (en.hasMoreElements()) {
      final String key = en.nextElement().toString();
      if (!key.startsWith(Prop.DBPREFIX)) continue;

      // only consider parameters that start with "org.basex."
      String val = sc.getInitParameter(key);
      if (eq(key, DBUSER, DBPASS, DBMODE, DBVERBOSE)) {
        // store servlet-specific parameters as system properties
        System.setProperty(key, val);
      } else {
        // prefix relative paths with absolute servlet path
        if (key.endsWith("path") && !new File(val).isAbsolute()) {
          val = path + File.separator + val;
        }
        // store remaining parameters (without project prefix) in map
        map.put(key.substring(Prop.DBPREFIX.length()).toUpperCase(Locale.ENGLISH), val);
      }
    }
    context = new Context(map);

    if (SERVER.equals(System.getProperty(DBMODE))) {
      new BaseXServer(context);
    } else {
      context.log = new Log(context);
    }
  }
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
     throws IOException, ServletException {
   final long startTime = System.currentTimeMillis();
   PerformanceFilterResponse filterResponse =
       new PerformanceFilterResponse((HttpServletResponse) response);
   chain.doFilter(request, filterResponse);
   try {
     processResponse(request, filterResponse, startTime);
   } catch (Throwable t) {
     Log logger = LogFactory.getLog(PerformanceMeasurementFilter.class);
     logger.error(t.getMessage(), t);
   }
 }
Example #22
0
  /** @service the servlet service request. called once for each servlet request. */
  public void service(HttpServletRequest servReq, HttpServletResponse servRes) throws IOException {
    String name;
    String value[];
    String val;

    servRes.setHeader("AUTHORIZATION", "user fred:mypassword");
    ServletOutputStream out = servRes.getOutputStream();

    HttpSession session = servReq.getSession(true);
    session.setAttribute("timemilis", new Long(System.currentTimeMillis()));
    if (session.isNew()) {
      out.println("<p> Session is new ");
    } else {
      out.println("<p> Session is not new ");
    }
    Long l = (Long) session.getAttribute("timemilis");
    out.println("<p> Session id = " + session.getId());
    out.println("<p> TimeMillis = " + l);

    out.println("<H2>Servlet Params</H2>");
    Enumeration e = servReq.getParameterNames();
    while (e.hasMoreElements()) {
      name = (String) e.nextElement();
      value = servReq.getParameterValues(name);
      out.println(name + " : ");
      for (int i = 0; i < value.length; ++i) {
        out.println(value[i]);
      }
      out.println("<p>");
    }

    out.println("<H2> Request Headers : </H2>");
    e = servReq.getHeaderNames();
    while (e.hasMoreElements()) {
      name = (String) e.nextElement();
      val = (String) servReq.getHeader(name);
      out.println("<p>" + name + " : " + val);
    }
    try {
      BufferedReader br = servReq.getReader();
      String line = null;
      while (null != (line = br.readLine())) {
        out.println(line);
      }
    } catch (IOException ie) {
      ie.printStackTrace();
    }

    session.invalidate();
  }
Example #23
0
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // get the number of workers to run
    int count = this.getRequestedCount(request, 4);
    // get the executor service
    final ServletContext sc = this.getServletContext();
    final ExecutorService executorService = (ExecutorService) sc.getAttribute("myExecutorService");
    // create work coordinator
    CountDownLatch countDownLatch = new CountDownLatch(count);

    Long t1 = System.nanoTime();
    // create the workers
    List<RunnableWorkUnit2> workers = new ArrayList<RunnableWorkUnit2>();
    for (int i = 0; i < count; i++) {
      RunnableWorkUnit2 wu =
          new RunnableWorkUnit2("RunnableTask" + String.valueOf(i + 1), countDownLatch);
      workers.add(wu);
    }
    // run the workers through the executor
    for (RunnableWorkUnit2 wu : workers) {
      executorService.execute(wu);
    }

    try {
      System.out.println("START WAITING");
      countDownLatch.await();
      System.out.println("DONE WAITING");
    } catch (InterruptedException ex) {
      ex.printStackTrace();
    }

    Long t2 = System.nanoTime();
    Writer w = response.getWriter();
    w.write(String.format("\n Request processed in %dms!", (t2 - t1) / 1000000));
    w.flush();
    w.close();
  }
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    httpResponse.setHeader("Cache-Control", "max-age=" + CACHE_TIME_TO_LIVE + ", public");
    httpResponse.setHeader("Pragma", "cache");

    // Setting Expires header, for proxy caching
    httpResponse.setDateHeader("Expires", CACHE_TIME_TO_LIVE + System.currentTimeMillis());

    // Setting the Last-Modified header, for browser caching
    httpResponse.setDateHeader("Last-Modified", LAST_MODIFIED);

    chain.doFilter(request, response);
  }
Example #25
0
  private synchronized Scope _scope() {

    if (_inScopeSetup) return _scope;

    if (_getScopeTime() > _lastScopeInitTime) _scopeInited = false;

    if (_scopeInited) return _scope;

    _scopeInited = true;
    _lastScopeInitTime = System.currentTimeMillis();

    _setupScope();

    _setStaticAdapterType();

    _setAdapterSelectorFunction();

    return _scope;
  }
/**
 * This filter is used in production, to put HTTP cache headers with a long (1 month) expiration
 * time.
 */
public class CachingHttpHeadersFilter implements Filter {

  // We consider the last modified date is the start up time of the server
  private static final long LAST_MODIFIED = System.currentTimeMillis();

  private long CACHE_TIME_TO_LIVE = TimeUnit.DAYS.toMillis(31L);

  private Environment env;

  public CachingHttpHeadersFilter(Environment env) {
    this.env = env;
  }

  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
    CACHE_TIME_TO_LIVE =
        TimeUnit.DAYS.toMillis(
            env.getProperty("jhipster.http.cache.timeToLiveInDays", Long.class, 31L));
  }

  @Override
  public void destroy() {
    // Nothing to destroy
  }

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {

    HttpServletResponse httpResponse = (HttpServletResponse) response;

    httpResponse.setHeader("Cache-Control", "max-age=" + CACHE_TIME_TO_LIVE + ", public");
    httpResponse.setHeader("Pragma", "cache");

    // Setting Expires header, for proxy caching
    httpResponse.setDateHeader("Expires", CACHE_TIME_TO_LIVE + System.currentTimeMillis());

    // Setting the Last-Modified header, for browser caching
    httpResponse.setDateHeader("Last-Modified", LAST_MODIFIED);

    chain.doFilter(request, response);
  }
}
Example #27
0
  private void setNoCacheHeaders(HttpServletResponse pResp) {
    pResp.setHeader("Cache-Control", "no-cache");
    pResp.setHeader("Pragma", "no-cache");
    // Check for a date header and set it accordingly to the recommendations of
    // RFC-2616 (http://tools.ietf.org/html/rfc2616#section-14.21)
    //
    //   "To mark a response as "already expired," an origin server sends an
    //    Expires date that is equal to the Date header value. (See the rules
    //  for expiration calculations in section 13.2.4.)"
    //
    // See also #71

    long now = System.currentTimeMillis();
    pResp.setDateHeader("Date", now);
    // 1h  in the past since it seems, that some servlet set the date header on their
    // own so that it cannot be guaranteed that these headers are really equals.
    // It happened on Tomcat that Date: was finally set *before* Expires: in the final
    // answers some times which seems to be an implementation peculiarity from Tomcat
    pResp.setDateHeader("Expires", now - 3600000);
  }
  private void processResponse(
      ServletRequest request, PerformanceFilterResponse response, final long startTime) {
    final int elapsedTime = (int) (System.currentTimeMillis() - startTime);
    final String outputDirectory =
        filterConfig
            .getServletContext()
            .getInitParameter("org.kuali.kra.perftest.REPORT_DIRECTORY");
    final HttpSample httpSample =
        new HttpSample(
            (HttpServletRequest) request, response, outputDirectory, startTime, elapsedTime);

    Thread t =
        new Thread(
            new Runnable() {
              public void run() {
                logSample(httpSample, outputDirectory);
              }
            });

    t.start();
  }
  private static void initJetWebEngine(ServletContext sc) {
    // 设置环境变量,以便 JetConfig 能够读取该变量
    String webappdir = sc.getRealPath("/");
    if (webappdir != null) {
      // 在 weblogic 中以 war 方式部署的时候,无法使用 getRealPath 方法.
      System.setProperty("webapp.dir", webappdir);
    }

    JetConfig config = new JetConfig();
    config.load(JetConfig.TEMPLATE_LOADER, WebResourceLoader.class.getName());
    config.load(JetConfig.TEMPLATE_PATH, "/"); // 默认 Webapp 根目录

    String location = sc.getInitParameter(CONFIG_LOCATION);
    if (location != null && location.length() > 0) {
      config.loadSerlvetResource(sc, location);
    } else {
      config.loadClasspath(JetConfig.DEFAULT_CONFIG_FILE);
    }

    engine = new JetWebEngine(config, sc);
  }
Example #30
0
  public static void log(String depbugstatement) {
    SimpleLayout layout = new SimpleLayout();

    FileAppender appender = null;
    try {
      String userDir = System.getProperty("user.dir");
      // FileInputStream fis = null;
      if (userDir.indexOf(":") != -1) {
        appender = new FileAppender(layout, "..\\server\\default\\log\\caIMAGE.log", false);
      } else {
        appender = new FileAppender(layout, "../log/caIMAGE.log", false);
      }

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

    logger.addAppender(appender);
    logger.setLevel((Level) Level.DEBUG);
    logger.debug(depbugstatement);
  }