protected void purgeEntries(Field properties)
      throws IllegalArgumentException, IllegalAccessException {
    if (properties == null) return;

    if (!properties.isAccessible()) properties.setAccessible(true);

    ConcurrentHashMap map = (ConcurrentHashMap) properties.get(null);
    if (map == null) return;

    Iterator<Class> itor = map.keySet().iterator();
    while (itor.hasNext()) {
      Class clazz = itor.next();
      LOG.info("Clazz: " + clazz + " loaded by " + clazz.getClassLoader());
      if (Thread.currentThread().getContextClassLoader().equals(clazz.getClassLoader())) {
        itor.remove();
        LOG.info("removed");
      } else
        LOG.info(
            "not removed: "
                + "contextclassloader="
                + Thread.currentThread().getContextClassLoader()
                + "clazz's classloader="
                + clazz.getClassLoader());
    }
  }
Exemple #2
0
 public static Namelist fromJSONtoNamelist(JSONObject jsonObj) {
   logger.info("Convert json object to namelist...");
   if (jsonObj != null) {
     String name = jsonObj.getString("_name");
     String species = jsonObj.getString("_species");
     if (species == null) {
       JSONObject metadataJSONObj = jsonObj.getJSONObject("metadata");
       if (metadataJSONObj != null) {
         species = metadataJSONObj.getString("species");
       }
     }
     int size = jsonObj.getInt("_size");
     JSONArray data =
         jsonObj.containsKey("_data")
             ? jsonObj.getJSONArray("_data")
             : jsonObj.getJSONArray("gaggle-data");
     String[] names = new String[data.size()];
     for (int i = 0; i < data.size(); i++) {
       logger.info("Data item: " + data.getString(i));
       names[i] = data.getString(i);
     }
     logger.info("Species: " + species + " Names: " + names);
     Namelist nl = new Namelist(name, species, names);
     return nl;
   }
   return null;
 }
 private void notifyCallbackFailed(Callback callback, Throwable x) {
   try {
     if (callback != null) callback.failed(x);
   } catch (Exception xx) {
     LOG.info("Exception while notifying callback " + callback, xx);
   } catch (Error xx) {
     LOG.info("Exception while notifying callback " + callback, xx);
     throw xx;
   }
 }
 private void notifyOnSettings(SessionFrameListener listener, SettingsInfo settingsInfo) {
   try {
     if (listener != null) {
       LOG.debug("Invoking callback with {} on listener {}", settingsInfo, listener);
       listener.onSettings(this, settingsInfo);
     }
   } catch (Exception x) {
     LOG.info("Exception while notifying listener " + listener, x);
   } catch (Error x) {
     LOG.info("Exception while notifying listener " + listener, x);
     throw x;
   }
 }
 private void notifyOnException(SessionFrameListener listener, Throwable x) {
   try {
     if (listener != null) {
       LOG.debug("Invoking callback with {} on listener {}", x, listener);
       listener.onException(x);
     }
   } catch (Exception xx) {
     LOG.info("Exception while notifying listener " + listener, xx);
   } catch (Error xx) {
     LOG.info("Exception while notifying listener " + listener, xx);
     throw xx;
   }
 }
 private void notifyOnGoAway(SessionFrameListener listener, GoAwayResultInfo goAwayResultInfo) {
   try {
     if (listener != null) {
       LOG.debug("Invoking callback with {} on listener {}", goAwayResultInfo, listener);
       listener.onGoAway(this, goAwayResultInfo);
     }
   } catch (Exception x) {
     LOG.info("Exception while notifying listener " + listener, x);
   } catch (Error x) {
     LOG.info("Exception while notifying listener " + listener, x);
     throw x;
   }
 }
 private StreamFrameListener notifyOnSyn(
     SessionFrameListener listener, Stream stream, SynInfo synInfo) {
   try {
     if (listener == null) return null;
     LOG.debug("Invoking callback with {} on listener {}", synInfo, listener);
     return listener.onSyn(stream, synInfo);
   } catch (Exception x) {
     LOG.info("Exception while notifying listener " + listener, x);
     return null;
   } catch (Error x) {
     LOG.info("Exception while notifying listener " + listener, x);
     throw x;
   }
 }
 private void notifyStreamClosed(IStream stream) {
   for (Listener listener : listeners) {
     if (listener instanceof StreamListener) {
       try {
         ((StreamListener) listener).onStreamClosed(stream);
       } catch (Exception x) {
         LOG.info("Exception while notifying listener " + listener, x);
       } catch (Error x) {
         LOG.info("Exception while notifying listener " + listener, x);
         throw x;
       }
     }
   }
 }
 protected void notifyClose(Session session, GoAwayFrame frame) {
   try {
     listener.onClose(session, frame);
   } catch (Throwable x) {
     LOG.info("Failure while notifying listener " + listener, x);
   }
 }
 protected void notifyReset(Session session, ResetFrame frame) {
   try {
     listener.onReset(session, frame);
   } catch (Throwable x) {
     LOG.info("Failure while notifying listener " + listener, x);
   }
 }
 protected void notifySettings(Session session, SettingsFrame frame) {
   try {
     listener.onSettings(session, frame);
   } catch (Throwable x) {
     LOG.info("Failure while notifying listener " + listener, x);
   }
 }
  /** @see org.eclipse.jetty.util.component.AbstractLifeCycle#doStart() */
  @Override
  public void doStart() throws Exception {
    _connectorServer.start();
    ShutdownThread.register(0, this);

    LOG.info("JMX Remote URL: {}", _connectorServer.getAddress().toString());
  }
 protected void notifyFailure(Session session, Throwable failure) {
   try {
     listener.onFailure(session, failure);
   } catch (Throwable x) {
     LOG.info("Failure while notifying listener " + listener, x);
   }
 }
  /* ------------------------------------------------------------ */
  @Override
  protected void doStart() throws Exception {
    if (getStopAtShutdown()) ShutdownThread.register(this);

    LOG.info("jetty-" + __version);
    HttpGenerator.setServerVersion(__version);
    MultiException mex = new MultiException();

    if (_threadPool == null) setThreadPool(new QueuedThreadPool());

    try {
      super.doStart();
    } catch (Throwable e) {
      mex.add(e);
    }

    if (_connectors != null) {
      for (int i = 0; i < _connectors.length; i++) {
        try {
          _connectors[i].start();
        } catch (Throwable e) {
          mex.add(e);
        }
      }
    }

    if (isDumpAfterStart()) dumpStdErr();

    mex.ifExceptionThrow();
  }
  /* ------------------------------------------------------------ */
  @Override
  protected void doStop() throws Exception {
    if (isDumpBeforeStop()) dumpStdErr();

    MultiException mex = new MultiException();

    if (_graceful > 0) {
      if (_connectors != null) {
        for (int i = _connectors.length; i-- > 0; ) {
          LOG.info("Graceful shutdown {}", _connectors[i]);
          try {
            _connectors[i].close();
          } catch (Throwable e) {
            mex.add(e);
          }
        }
      }

      Handler[] contexts = getChildHandlersByClass(Graceful.class);
      for (int c = 0; c < contexts.length; c++) {
        Graceful context = (Graceful) contexts[c];
        LOG.info("Graceful shutdown {}", context);
        context.setShutdown(true);
      }
      Thread.sleep(_graceful);
    }

    if (_connectors != null) {
      for (int i = _connectors.length; i-- > 0; )
        try {
          _connectors[i].stop();
        } catch (Throwable e) {
          mex.add(e);
        }
    }

    try {
      super.doStop();
    } catch (Throwable e) {
      mex.add(e);
    }

    mex.ifExceptionThrow();

    if (getStopAtShutdown()) ShutdownThread.deregister(this);
  }
 protected boolean notifyIdleTimeout(Session session) {
   try {
     return listener.onIdleTimeout(session);
   } catch (Throwable x) {
     LOG.info("Failure while notifying listener " + listener, x);
     return true;
   }
 }
 protected Stream.Listener notifyNewStream(Stream stream, HeadersFrame frame) {
   try {
     return listener.onNewStream(stream, frame);
   } catch (Throwable x) {
     LOG.info("Failure while notifying listener " + listener, x);
     return null;
   }
 }
 protected void notifyHeaders(IStream stream, HeadersFrame frame) {
   Stream.Listener listener = stream.getListener();
   if (listener == null) return;
   try {
     listener.onHeaders(stream, frame);
   } catch (Throwable x) {
     LOG.info("Failure while notifying listener " + listener, x);
   }
 }
 public static void remove(String category, String type, String name) {
   MBeanServer server = ManagementFactory.getPlatformMBeanServer();
   try {
     server.unregisterMBean(new ObjectName(String.format(BEAN_NAME, category, type, name)));
   } catch (Exception e) {
     // Throwing runtime exception will not help matters...
     // silently fail and record the problem
     log.info("Could not remove mbean " + String.format(BEAN_NAME, category, type, name), e);
   }
 }
 @Override
 public void incoming(WebSocketFrame frame) {
   LOG.debug("incoming({})", frame);
   int count = parseCount.incrementAndGet();
   if ((count % 10) == 0) {
     LOG.info("Client parsed {} frames", count);
   }
   WebSocketFrame copy = new WebSocketFrame(frame);
   incomingFrames.incoming(copy);
 }
  /**
   * Invoked when the request handling exceeds {@link #getMaxRequestMs()}.
   *
   * <p>By default, a HTTP 503 response is returned and the handling thread is interrupted.
   *
   * @param request the current request
   * @param response the current response
   * @param handlingThread the handling thread
   */
  protected void onRequestTimeout(
      HttpServletRequest request, HttpServletResponse response, Thread handlingThread) {
    try {
      if (LOG.isDebugEnabled()) LOG.debug("Timing out {}", request);
      response.sendError(HttpStatus.SERVICE_UNAVAILABLE_503);
    } catch (Throwable x) {
      LOG.info(x);
    }

    handlingThread.interrupt();
  }
Exemple #22
0
  /**
   * Open the Socket to the destination endpoint and
   *
   * @return the open java Socket.
   * @throws IOException
   */
  public Socket connect() throws IOException {
    LOG.info("Connecting to endpoint: " + endpoint);
    socket = new Socket();
    socket.setTcpNoDelay(true);
    socket.connect(endpoint, 1000);

    out = socket.getOutputStream();
    in = socket.getInputStream();

    return socket;
  }
Exemple #23
0
  public void handleJSON(String source, String json) throws RemoteException {
    if (json != null) {
      try {
        logger.info("Sending " + json + " to " + gooseName);

        this.mySocket.broadcastJSON(json);
      } catch (Exception e) {
        logger.warn("Failed to send json to remote endpoint: " + e.getMessage());
        e.printStackTrace();
      }
    }
  }
  @Override
  protected void doStart() throws Exception {
    String jettyUserEnvVariable = System.getenv("JETTY_USER");
    if (jettyUserEnvVariable != null)
      LOG.warn(
          "JETTY_USER set to: {}. If JETTY_USER is set, starting jetty as root and using "
              + "jetty-setuid to switch user won't work!!!",
          jettyUserEnvVariable);
    if (_umask > -1) {
      LOG.info("Setting umask=0" + Integer.toString(_umask, 8));
      SetUID.setumask(_umask);
    }

    if (_rlimitNoFiles != null) {
      LOG.info("Current " + SetUID.getrlimitnofiles());
      int success = SetUID.setrlimitnofiles(_rlimitNoFiles);
      if (success < 0) LOG.warn("Failed to set rlimit_nofiles, returned status " + success);
      LOG.info("Set " + SetUID.getrlimitnofiles());
    }

    if (_startServerAsPrivileged) {
      super.doStart();
      if (_gid != 0) {
        LOG.info("Setting GID=" + _gid);
        SetUID.setgid(_gid);
      }
      if (_uid != 0) {
        LOG.info("Setting UID=" + _uid);
        SetUID.setuid(_uid);
        Passwd pw = SetUID.getpwuid(_uid);
        System.setProperty("user.name", pw.getPwName());
        System.setProperty("user.home", pw.getPwDir());
      }
    } else {
      Connector[] connectors = getConnectors();
      for (int i = 0; connectors != null && i < connectors.length; i++) {
        connectors[i].start();
      }

      if (_gid != 0) {
        LOG.info("Setting GID=" + _gid);
        SetUID.setgid(_gid);
      }

      if (_uid != 0) {
        LOG.info("Setting UID=" + _uid);
        SetUID.setuid(_uid);
        Passwd pw = SetUID.getpwuid(_uid);
        System.setProperty("user.name", pw.getPwName());
        System.setProperty("user.home", pw.getPwDir());
      }

      super.doStart();
    }
  }
 private void expireConnect(ClientDelegate client, long time) {
   String targetId = client.getTargetId();
   logger.info(
       "Client with targetId {} missing, last seen {} ms ago, closing it",
       targetId,
       System.currentTimeMillis() - time);
   client.close();
   // If the client expired, means that it did not connect,
   // so there no request to resume, and we cleanup here
   // (while normally this cleanup is done in serviceConnect())
   unschedule(targetId);
   gateway.removeClientDelegate(targetId);
 }
  @Override
  protected void doStop() throws Exception {
    // Tell the acceptors we are stopping
    interruptAcceptors();

    // If we have a stop timeout
    long stopTimeout = getStopTimeout();
    if (stopTimeout > 0 && _stopping != null) _stopping.await(stopTimeout, TimeUnit.MILLISECONDS);
    _stopping = null;

    super.doStop();

    LOG.info("Stopped {}", this);
  }
  @Override
  protected void doStart() throws Exception {
    _defaultConnectionFactory = getConnectionFactory(_defaultProtocol);
    if (_defaultConnectionFactory == null)
      throw new IllegalStateException(
          "No protocol factory for default protocol: " + _defaultProtocol);

    super.doStart();

    _stopping = new CountDownLatch(_acceptors.length);
    for (int i = 0; i < _acceptors.length; i++) getExecutor().execute(new Acceptor(i));

    LOG.info("Started {}", this);
  }
  protected boolean subnetMatch(String subnetAddress, String address) {
    Matcher cidrMatcher = CIDR_PATTERN.matcher(subnetAddress);
    if (!cidrMatcher.matches()) return false;

    String subnet = cidrMatcher.group(1);
    int prefix;
    try {
      prefix = Integer.parseInt(cidrMatcher.group(2));
    } catch (NumberFormatException x) {
      LOG.info("Ignoring malformed CIDR address {}", subnetAddress);
      return false;
    }

    byte[] subnetBytes = addressToBytes(subnet);
    if (subnetBytes == null) {
      LOG.info("Ignoring malformed CIDR address {}", subnetAddress);
      return false;
    }
    byte[] addressBytes = addressToBytes(address);
    if (addressBytes == null) {
      LOG.info("Ignoring malformed remote address {}", address);
      return false;
    }

    // Comparing IPv4 with IPv6 ?
    int length = subnetBytes.length;
    if (length != addressBytes.length) return false;

    byte[] mask = prefixToBytes(prefix, length);

    for (int i = 0; i < length; ++i) {
      if ((subnetBytes[i] & mask[i]) != (addressBytes[i] & mask[i])) return false;
    }

    return true;
  }
  public void contextDestroyed(ServletContextEvent sce) {
    try {
      // Check that the BeanELResolver class is on the classpath
      Class beanELResolver = Loader.loadClass(this.getClass(), "javax.el.BeanELResolver");

      // Get a reference via reflection to the properties field which is holding class references
      Field field = getField(beanELResolver);

      // Get rid of references
      purgeEntries(field);

      LOG.info("javax.el.BeanELResolver purged");
    } catch (ClassNotFoundException e) {
      // BeanELResolver not on classpath, ignore
    } catch (SecurityException e) {
      LOG.warn("Cannot purge classes from javax.el.BeanELResolver", e);
    } catch (IllegalArgumentException e) {
      LOG.warn("Cannot purge classes from javax.el.BeanELResolver", e);
    } catch (IllegalAccessException e) {
      LOG.warn("Cannot purge classes from javax.el.BeanELResolver", e);
    } catch (NoSuchFieldException e) {
      LOG.warn("Cannot purge classes from javax.el.BeanELResolver", e);
    }
  }
Exemple #30
0
  /**
   * Configure a jetty instance and deploy the webapps presented as args
   *
   * @param args the command line arguments
   * @throws Exception if unable to configure
   */
  public void configure(String[] args) throws Exception {
    // handle classpath bits first so we can initialize the log mechanism.
    for (int i = 0; i < args.length; i++) {
      if ("--lib".equals(args[i])) {
        try (Resource lib = Resource.newResource(args[++i])) {
          if (!lib.exists() || !lib.isDirectory()) usage("No such lib directory " + lib);
          _classpath.addJars(lib);
        }
      } else if ("--jar".equals(args[i])) {
        try (Resource jar = Resource.newResource(args[++i])) {
          if (!jar.exists() || jar.isDirectory()) usage("No such jar " + jar);
          _classpath.addPath(jar);
        }
      } else if ("--classes".equals(args[i])) {
        try (Resource classes = Resource.newResource(args[++i])) {
          if (!classes.exists() || !classes.isDirectory())
            usage("No such classes directory " + classes);
          _classpath.addPath(classes);
        }
      } else if (args[i].startsWith("--")) i++;
    }

    initClassLoader();

    LOG.info("Runner");
    LOG.debug("Runner classpath {}", _classpath);

    String contextPath = __defaultContextPath;
    boolean contextPathSet = false;
    int port = __defaultPort;
    String host = null;
    int stopPort = 0;
    String stopKey = null;

    boolean runnerServerInitialized = false;

    for (int i = 0; i < args.length; i++) {
      switch (args[i]) {
        case "--port":
          port = Integer.parseInt(args[++i]);
          break;
        case "--host":
          host = args[++i];
          break;
        case "--stop-port":
          stopPort = Integer.parseInt(args[++i]);
          break;
        case "--stop-key":
          stopKey = args[++i];
          break;
        case "--log":
          _logFile = args[++i];
          break;
        case "--out":
          String outFile = args[++i];
          PrintStream out = new PrintStream(new RolloverFileOutputStream(outFile, true, -1));
          LOG.info("Redirecting stderr/stdout to " + outFile);
          System.setErr(out);
          System.setOut(out);
          break;
        case "--path":
          contextPath = args[++i];
          contextPathSet = true;
          break;
        case "--config":
          if (_configFiles == null) _configFiles = new ArrayList<>();
          _configFiles.add(args[++i]);
          break;
        case "--lib":
          ++i; // skip

          break;
        case "--jar":
          ++i; // skip

          break;
        case "--classes":
          ++i; // skip

          break;
        case "--stats":
          _enableStats = true;
          _statsPropFile = args[++i];
          _statsPropFile = ("unsecure".equalsIgnoreCase(_statsPropFile) ? null : _statsPropFile);
          break;
        default:
          // process contexts

          if (!runnerServerInitialized) // log handlers not registered, server maybe not created,
                                        // etc
          {
            if (_server == null) // server not initialized yet
            {
              // build the server
              _server = new Server();
            }

            // apply jetty config files if there are any
            if (_configFiles != null) {
              for (String cfg : _configFiles) {
                try (Resource resource = Resource.newResource(cfg)) {
                  XmlConfiguration xmlConfiguration = new XmlConfiguration(resource.getURL());
                  xmlConfiguration.configure(_server);
                }
              }
            }

            // check that everything got configured, and if not, make the handlers
            HandlerCollection handlers =
                (HandlerCollection) _server.getChildHandlerByClass(HandlerCollection.class);
            if (handlers == null) {
              handlers = new HandlerCollection();
              _server.setHandler(handlers);
            }

            // check if contexts already configured
            _contexts =
                (ContextHandlerCollection)
                    handlers.getChildHandlerByClass(ContextHandlerCollection.class);
            if (_contexts == null) {
              _contexts = new ContextHandlerCollection();
              prependHandler(_contexts, handlers);
            }

            if (_enableStats) {
              // if no stats handler already configured
              if (handlers.getChildHandlerByClass(StatisticsHandler.class) == null) {
                StatisticsHandler statsHandler = new StatisticsHandler();

                Handler oldHandler = _server.getHandler();
                statsHandler.setHandler(oldHandler);
                _server.setHandler(statsHandler);

                ServletContextHandler statsContext = new ServletContextHandler(_contexts, "/stats");
                statsContext.addServlet(new ServletHolder(new StatisticsServlet()), "/");
                statsContext.setSessionHandler(new SessionHandler());
                if (_statsPropFile != null) {
                  HashLoginService loginService =
                      new HashLoginService("StatsRealm", _statsPropFile);
                  Constraint constraint = new Constraint();
                  constraint.setName("Admin Only");
                  constraint.setRoles(new String[] {"admin"});
                  constraint.setAuthenticate(true);

                  ConstraintMapping cm = new ConstraintMapping();
                  cm.setConstraint(constraint);
                  cm.setPathSpec("/*");

                  ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
                  securityHandler.setLoginService(loginService);
                  securityHandler.setConstraintMappings(Collections.singletonList(cm));
                  securityHandler.setAuthenticator(new BasicAuthenticator());
                  statsContext.setSecurityHandler(securityHandler);
                }
              }
            }

            // ensure a DefaultHandler is present
            if (handlers.getChildHandlerByClass(DefaultHandler.class) == null) {
              handlers.addHandler(new DefaultHandler());
            }

            // ensure a log handler is present
            _logHandler =
                (RequestLogHandler) handlers.getChildHandlerByClass(RequestLogHandler.class);
            if (_logHandler == null) {
              _logHandler = new RequestLogHandler();
              handlers.addHandler(_logHandler);
            }

            // check a connector is configured to listen on
            Connector[] connectors = _server.getConnectors();
            if (connectors == null || connectors.length == 0) {
              ServerConnector connector = new ServerConnector(_server);
              connector.setPort(port);
              if (host != null) connector.setHost(host);
              _server.addConnector(connector);
              if (_enableStats) connector.addBean(new ConnectorStatistics());
            } else {
              if (_enableStats) {
                for (Connector connector : connectors) {
                  ((AbstractConnector) connector).addBean(new ConnectorStatistics());
                }
              }
            }

            runnerServerInitialized = true;
          }

          // Create a context
          try (Resource ctx = Resource.newResource(args[i])) {
            if (!ctx.exists()) usage("Context '" + ctx + "' does not exist");

            if (contextPathSet && !(contextPath.startsWith("/"))) contextPath = "/" + contextPath;

            // Configure the context
            if (!ctx.isDirectory() && ctx.toString().toLowerCase().endsWith(".xml")) {
              // It is a context config file
              XmlConfiguration xmlConfiguration = new XmlConfiguration(ctx.getURL());
              xmlConfiguration.getIdMap().put("Server", _server);
              ContextHandler handler = (ContextHandler) xmlConfiguration.configure();
              if (contextPathSet) handler.setContextPath(contextPath);
              _contexts.addHandler(handler);
              handler.setAttribute(
                  "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
                  __containerIncludeJarPattern);
            } else {
              // assume it is a WAR file
              WebAppContext webapp = new WebAppContext(_contexts, ctx.toString(), contextPath);
              webapp.setConfigurationClasses(__plusConfigurationClasses);
              webapp.setAttribute(
                  "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
                  __containerIncludeJarPattern);
            }
          }
          // reset
          contextPathSet = false;
          contextPath = __defaultContextPath;
          break;
      }
    }

    if (_server == null) usage("No Contexts defined");
    _server.setStopAtShutdown(true);

    switch ((stopPort > 0 ? 1 : 0) + (stopKey != null ? 2 : 0)) {
      case 1:
        usage("Must specify --stop-key when --stop-port is specified");
        break;

      case 2:
        usage("Must specify --stop-port when --stop-key is specified");
        break;

      case 3:
        ShutdownMonitor monitor = ShutdownMonitor.getInstance();
        monitor.setPort(stopPort);
        monitor.setKey(stopKey);
        monitor.setExitVm(true);
        break;
    }

    if (_logFile != null) {
      NCSARequestLog requestLog = new NCSARequestLog(_logFile);
      requestLog.setExtended(false);
      _logHandler.setRequestLog(requestLog);
    }
  }