public void setUp(String username, Map<String, String> initParams) throws Exception {
    ServiceRegistry mockServiceRegistry = EasyMock.createNiceMock(ServiceRegistry.class);
    EasyMock.expect(mockServiceRegistry.lookupServiceURL("test-cluster", "NAMENODE"))
        .andReturn("test-nn-scheme://test-nn-host:411")
        .anyTimes();
    EasyMock.expect(mockServiceRegistry.lookupServiceURL("test-cluster", "JOBTRACKER"))
        .andReturn("test-jt-scheme://test-jt-host:511")
        .anyTimes();

    GatewayServices mockGatewayServices = EasyMock.createNiceMock(GatewayServices.class);
    EasyMock.expect(mockGatewayServices.getService(GatewayServices.SERVICE_REGISTRY_SERVICE))
        .andReturn(mockServiceRegistry)
        .anyTimes();

    EasyMock.replay(mockServiceRegistry, mockGatewayServices);

    String descriptorUrl = getTestResource("rewrite.xml").toExternalForm();

    Log.setLog(new NoOpLogger());

    server = new ServletTester();
    server.setContextPath("/");
    server.getContext().addEventListener(new UrlRewriteServletContextListener());
    server
        .getContext()
        .setInitParameter(
            UrlRewriteServletContextListener.DESCRIPTOR_LOCATION_INIT_PARAM_NAME, descriptorUrl);
    server.getContext().setAttribute(GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE, "test-cluster");
    server
        .getContext()
        .setAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE, mockGatewayServices);

    FilterHolder setupFilter =
        server.addFilter(SetupFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
    setupFilter.setFilter(new SetupFilter(username));
    FilterHolder rewriteFilter =
        server.addFilter(UrlRewriteServletFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
    if (initParams != null) {
      for (Map.Entry<String, String> entry : initParams.entrySet()) {
        rewriteFilter.setInitParameter(entry.getKey(), entry.getValue());
      }
    }
    rewriteFilter.setFilter(new UrlRewriteServletFilter());

    interactions = new ArrayQueue<MockInteraction>();

    ServletHolder servlet = server.addServlet(MockServlet.class, "/");
    servlet.setServlet(new MockServlet("mock-servlet", interactions));

    server.start();

    interaction = new MockInteraction();
    request = new HttpTester();
    response = new HttpTester();
  }
 protected void writeData(ServletResponse response, String data) throws IOException {
   idleCheck.activity();
   Log.debug("Session[" + session.getSessionId() + "]: writeData(START): " + data);
   ServletOutputStream os = response.getOutputStream();
   os.println("Content-Type: text/plain");
   os.println();
   os.println(data);
   os.println(boundarySeperator);
   response.flushBuffer();
   Log.debug("Session[" + session.getSessionId() + "]: writeData(END): " + data);
 }
  /* ------------------------------------------------------------ */
  private int checkNonce(String nonce, Request request) {
    try {
      byte[] n = B64Code.decode(nonce.toCharArray());
      if (n.length != 24) {
        return -1;
      }

      long ts = 0;
      long sk = _nonceSecret;
      byte[] n2 = new byte[16];
      System.arraycopy(n, 0, n2, 0, 8);
      for (int i = 0; i < 8; i++) {
        n2[8 + i] = (byte) (sk & 0xff);
        sk = sk >> 8;
        ts = (ts << 8) + (0xff & (long) n[7 - i]);
      }

      long age = request.getTimeStamp() - ts;
      if (Log.isDebugEnabled()) {
        Log.debug("age=" + age);
      }

      byte[] hash = null;
      try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.reset();
        md.update(n2, 0, 16);
        hash = md.digest();
      } catch (Exception e) {
        Log.warn(e);
      }

      for (int i = 0; i < 16; i++) {
        if (n[i + 8] != hash[i]) {
          return -1;
        }
      }

      if (_maxNonceAge > 0 && (age < 0 || age > _maxNonceAge)) {
        return 0; // stale
      }

      return 1;
    } catch (Exception e) {
      Log.ignore(e);
    }
    return -1;
  }
Example #4
0
  @Before
  public void init() throws Exception {
    _server = new Server();
    _connector = new LocalConnector(_server);
    ServletContextHandler context =
        new ServletContextHandler(
            ServletContextHandler.NO_SECURITY | ServletContextHandler.NO_SESSIONS);

    _server.addConnector(_connector);
    _server.setHandler(context);

    context.setContextPath("/");

    context.addServlet(DefaultServlet.class, "/");
    context.addServlet(FailServlet.class, "/fail/*");
    context.addServlet(ErrorServlet.class, "/error/*");

    ErrorPageErrorHandler error = new ErrorPageErrorHandler();
    context.setErrorHandler(error);
    error.addErrorPage(599, "/error/599");
    error.addErrorPage(IllegalStateException.class.getCanonicalName(), "/error/TestException");
    error.addErrorPage(ErrorPageErrorHandler.GLOBAL_ERROR_PAGE, "/error/GlobalErrorPage");

    _server.start();
    ((StdErrLog) Log.getLogger(ServletHandler.class)).setHideStacks(true);
  }
@ServerEndpoint("/echo/primitives/characterobject")
public class CharacterObjectTextSocket {
  private static final Logger LOG = Log.getLogger(CharacterObjectTextSocket.class);

  private Session session;

  @OnOpen
  public void onOpen(Session session) {
    this.session = session;
  }

  @OnMessage
  public void onMessage(Character c) throws IOException {
    if (c == null) {
      session.getAsyncRemote().sendText("Error: Character is null");
    } else {
      String msg = c.toString();
      session.getAsyncRemote().sendText(msg);
    }
  }

  @OnError
  public void onError(Throwable cause) throws IOException {
    LOG.warn("Error", cause);
    session.getBasicRemote().sendText("Exception: " + StackUtil.toString(cause));
  }
}
@ServerEndpoint("/echo/primitives/byteobject")
public class ByteObjectTextSocket {
  private static final Logger LOG = Log.getLogger(ByteObjectTextSocket.class);

  private Session session;

  @OnOpen
  public void onOpen(Session session) {
    this.session = session;
  }

  @OnMessage
  public void onMessage(Byte b) throws IOException {
    if (b == null) {
      session.getAsyncRemote().sendText("Error: Byte is null");
    } else {
      String msg = String.format("0x%02X", b);
      session.getAsyncRemote().sendText(msg);
    }
  }

  @OnError
  public void onError(Throwable cause) throws IOException {
    LOG.warn("Error", cause);
    session.getBasicRemote().sendText("Exception: " + StackUtil.toString(cause));
  }
}
/**
 * Registers mbeans with the default platform MBean Server.
 *
 * @author David Ranalli Jan 29, 2016
 */
public class JmxMonitorManager {
  private static final Logger log = Log.getLogger(JmxMonitorManager.class.getName());
  private static final String BEAN_NAME = "jetty-nosql.%s:type=%s,name=%s";

  public static void monitor(Object mbean, String category, String type, String name) {
    MBeanServer server = ManagementFactory.getPlatformMBeanServer();
    try {
      server.registerMBean(mbean, 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 add mbean " + mbean + " as " + String.format(BEAN_NAME, category, type, name),
          e);
    }
  }

  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 boolean check(Object credentials) {
      if (credentials instanceof char[]) {
        credentials = new String((char[]) credentials);
      }
      String password =
          (credentials instanceof String) ? (String) credentials : credentials.toString();

      try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] ha1;
        if (credentials instanceof Credential.MD5) {
          // Credentials are already a MD5 digest - assume it's in
          // form user:realm:password (we have no way to know since
          // it's a digest, alright?)
          ha1 = ((Credential.MD5) credentials).getDigest();
        } else {
          // calc A1 digest
          md.update(username.getBytes(StringUtil.__ISO_8859_1));
          md.update((byte) ':');
          md.update(realm.getBytes(StringUtil.__ISO_8859_1));
          md.update((byte) ':');
          md.update(password.getBytes(StringUtil.__ISO_8859_1));
          ha1 = md.digest();
        }
        // calc A2 digest
        md.reset();
        md.update(method.getBytes(StringUtil.__ISO_8859_1));
        md.update((byte) ':');
        md.update(uri.getBytes(StringUtil.__ISO_8859_1));
        byte[] ha2 = md.digest();

        // calc digest
        // request-digest = <"> < KD ( H(A1), unq(nonce-value) ":"
        // nc-value ":" unq(cnonce-value) ":" unq(qop-value) ":" H(A2) )
        // <">
        // request-digest = <"> < KD ( H(A1), unq(nonce-value) ":" H(A2)
        // ) > <">

        md.update(TypeUtil.toString(ha1, 16).getBytes(StringUtil.__ISO_8859_1));
        md.update((byte) ':');
        md.update(nonce.getBytes(StringUtil.__ISO_8859_1));
        md.update((byte) ':');
        md.update(nc.getBytes(StringUtil.__ISO_8859_1));
        md.update((byte) ':');
        md.update(cnonce.getBytes(StringUtil.__ISO_8859_1));
        md.update((byte) ':');
        md.update(qop.getBytes(StringUtil.__ISO_8859_1));
        md.update((byte) ':');
        md.update(TypeUtil.toString(ha2, 16).getBytes(StringUtil.__ISO_8859_1));
        byte[] digest = md.digest();

        // check digest
        return (TypeUtil.toString(digest, 16).equalsIgnoreCase(response));
      } catch (Exception e) {
        Log.warn(e);
      }

      return false;
    }
  public String newNonce(Request request) {
    long ts = request.getTimeStamp();
    long sk = _nonceSecret;

    byte[] nounce = new byte[24];
    for (int i = 0; i < 8; i++) {
      nounce[i] = (byte) (ts & 0xff);
      ts = ts >> 8;
      nounce[8 + i] = (byte) (sk & 0xff);
      sk = sk >> 8;
    }

    byte[] hash = null;
    try {
      MessageDigest md = MessageDigest.getInstance("MD5");
      md.reset();
      md.update(nounce, 0, 16);
      hash = md.digest();
    } catch (Exception e) {
      Log.warn(e);
    }

    for (int i = 0; i < hash.length; i++) {
      nounce[8 + i] = hash[i];
      if (i == 23) {
        break;
      }
    }

    return new String(B64Code.encode(nounce));
  }
/**
 * ConsoleNotifier
 *
 * <p>Provides a way to output notification messages to a log file
 */
public class LoggingNotifier implements EventNotifier {
  private static final Logger LOG = Log.getLogger(LoggingNotifier.class);

  String _messageFormat;

  /* ------------------------------------------------------------ */
  /**
   * Constructs a new notifier with specified format string
   *
   * @param format the {@link java.util.Formatter format string}
   * @throws IllegalArgumentException
   */
  public LoggingNotifier(String format) throws IllegalArgumentException {
    if (format == null) throw new IllegalArgumentException("Message format cannot be null");

    _messageFormat = format;
  }

  /* ------------------------------------------------------------ */
  /**
   * @see
   *     org.eclipse.jetty.monitor.jmx.EventNotifier#notify(org.eclipse.jetty.monitor.jmx.EventTrigger,
   *     org.eclipse.jetty.monitor.jmx.EventState, long)
   */
  public void notify(EventTrigger trigger, EventState<?> state, long timestamp) {
    String output = String.format(_messageFormat, state);

    LOG.info(output);
  }
}
  @Before
  public void setUp() throws Exception {
    File docRoot = new File("target/test-output/docroot/");
    docRoot.mkdirs();
    docRoot.deleteOnExit();

    System.setProperty("org.mortbay.jetty.util.DEBUG", "");
    _server = new Server();

    SelectChannelConnector connector = new SelectChannelConnector();
    _server.addConnector(connector);

    _handler = new TestHandler();
    _server.setHandler(_handler);

    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    MBeanContainer mBeanContainer = new MBeanContainer(mBeanServer);
    mBeanContainer.addBean(Log.getLog());

    _counter = _handler.getRequestCounter();
    mBeanContainer.addBean(_counter);

    _server.addBean(mBeanContainer);
    _server.getContainer().addEventListener(mBeanContainer);
    _server.start();

    startClient(null);

    _monitor = new JMXMonitor();

    int port = _server.getConnectors()[0].getLocalPort();
    _requestUrl = "http://localhost:" + port + "/";
  }
Example #12
0
  private void addWebServerJMXSupport(Server server) {
    MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
    server.getContainer().addEventListener(mbContainer);
    server.addBean(mbContainer);

    // Register loggers as MBeans
    mbContainer.addBean(Log.getLog());
  }
  @Test
  public void testStop() throws Exception {
    TestLifeCycle lifecycle = new TestLifeCycle();
    TestListener listener = new TestListener();
    lifecycle.addLifeCycleListener(listener);

    // need to set the state to something other than stopped or stopping or
    // else
    // stop() will return without doing anything

    lifecycle.start();
    lifecycle.setCause(cause);

    try {
      ((StdErrLog) Log.getLogger(AbstractLifeCycle.class)).setHideStacks(true);
      lifecycle.stop();
      assertTrue(false);
    } catch (Exception e) {
      assertEquals(cause, e);
      assertEquals(cause, listener.getCause());
    } finally {
      ((StdErrLog) Log.getLogger(AbstractLifeCycle.class)).setHideStacks(false);
    }

    lifecycle.setCause(null);

    lifecycle.stop();

    // check that the stopping event has been thrown
    assertTrue("The stopping event didn't occur", listener.stopping);

    // check that the stopped event has been thrown
    assertTrue("The stopped event didn't occur", listener.stopped);

    // check that the stopping event occurs before the stopped event
    assertTrue(
        "The stopping event must occur before the stopped event",
        listener.stoppingTime <= listener.stoppedTime);
    // System.out.println("STOPING TIME : " + listener.stoppingTime + " : " + listener.stoppedTime);

    // check that the lifecycle's state is stopped
    assertTrue("The lifecycle state is not stooped", lifecycle.isStopped());
  }
/** Dummy impl of MuxAddServer */
public class DummyMuxAddServer implements MuxAddServer {
  @SuppressWarnings("unused")
  private static final Logger LOG = Log.getLogger(DummyMuxAddServer.class);

  private AdapterEchoSocket echo;
  private WebSocketPolicy policy;
  private EventDriverFactory eventDriverFactory;

  public DummyMuxAddServer() {
    this.policy = WebSocketPolicy.newServerPolicy();
    this.eventDriverFactory = new EventDriverFactory(policy);
    this.echo = new AdapterEchoSocket();
  }

  @Override
  public UpgradeRequest getPhysicalHandshakeRequest() {
    // TODO Auto-generated method stub
    return null;
  }

  @Override
  public UpgradeResponse getPhysicalHandshakeResponse() {
    // TODO Auto-generated method stub
    return null;
  }

  @Override
  public void handshake(Muxer muxer, MuxChannel channel, UpgradeRequest request)
      throws MuxException, IOException {
    StringBuilder response = new StringBuilder();
    response.append("HTTP/1.1 101 Switching Protocols\r\n");
    response.append("Connection: upgrade\r\n");
    // not meaningful (per Draft 08) hresp.append("Upgrade: websocket\r\n");
    // not meaningful (per Draft 08) hresp.append("Sec-WebSocket-Accept:
    // Kgo85/8KVE8YPONSeyhgL3GwqhI=\r\n");
    response.append("\r\n");

    EventDriver websocket = this.eventDriverFactory.wrap(echo);
    WebSocketSession session = new WebSocketSession(request.getRequestURI(), websocket, channel);
    session.setNegotiatedSubprotocol("echo");
    channel.setSession(session);
    channel.setSubProtocol("echo");
    channel.onOpen();
    session.open();

    MuxAddChannelResponse addChannelResponse = new MuxAddChannelResponse();
    addChannelResponse.setChannelId(channel.getChannelId());
    addChannelResponse.setEncoding(MuxAddChannelResponse.IDENTITY_ENCODING);
    addChannelResponse.setFailed(false);
    addChannelResponse.setHandshake(response.toString());

    muxer.output(addChannelResponse);
  }
}
public class SpnegoAuthenticator extends LoginAuthenticator {
  private static final Logger LOG = Log.getLogger(SpnegoAuthenticator.class);

  public String getAuthMethod() {
    return Constraint.__SPNEGO_AUTH;
  }

  public Authentication validateRequest(
      ServletRequest request, ServletResponse response, boolean mandatory)
      throws ServerAuthException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;

    String header = req.getHeader(HttpHeaders.AUTHORIZATION);

    if (!mandatory) {
      return _deferred;
    }

    // check to see if we have authorization headers required to continue
    if (header == null) {
      try {
        if (_deferred.isDeferred(res)) {
          return Authentication.UNAUTHENTICATED;
        }

        LOG.debug("SpengoAuthenticator: sending challenge");
        res.setHeader(HttpHeaders.WWW_AUTHENTICATE, HttpHeaders.NEGOTIATE);
        res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return Authentication.SEND_CONTINUE;
      } catch (IOException ioe) {
        throw new ServerAuthException(ioe);
      }
    } else if (header != null && header.startsWith(HttpHeaders.NEGOTIATE)) {
      String spnegoToken = header.substring(10);

      UserIdentity user = _loginService.login(null, spnegoToken);

      if (user != null) {
        return new UserAuthentication(getAuthMethod(), user);
      }
    }

    return Authentication.UNAUTHENTICATED;
  }

  public boolean secureResponse(
      ServletRequest request, ServletResponse response, boolean mandatory, User validatedUser)
      throws ServerAuthException {
    return true;
  }
}
Example #16
0
  @Override
  public Resource getResource(String uriInContext) throws MalformedURLException {
    Resource resource = null;
    // Try to get regular resource
    //        replacer.getAutoconfigTempDirectory().getAbsolutePath()
    try {
      resource = getAutoconfigResource(uriInContext);
      if (resource == null) {
        //                resource = super.getResource(uriInContext);
        resource = getResourceFromMavenOrSuper(uriInContext);
      }
    } catch (Exception e) {
      logger.warn("find autoconfig resource error! " + uriInContext, e);
    }
    // If no regular resource exists check for access to /WEB-INF/lib or /WEB-INF/classes
    if ((resource == null || !resource.exists()) && uriInContext != null && webInfClasses != null) {
      String uri = URIUtil.canonicalPath(uriInContext);

      try {
        // Replace /WEB-INF/classes with real classes directory
        if (uri.startsWith(WEB_INF_CLASSES_PREFIX)) {
          Resource res = null;
          int i = 0;
          while (res == null && (i < webInfClasses.size())) {
            String newPath = uri.replace(WEB_INF_CLASSES_PREFIX, webInfClasses.get(i).getPath());
            res = Resource.newResource(newPath);
            if (!res.exists()) {
              res = null;
              i++;
            }
          }
          return res;
        }
        // Return the real jar file for all accesses to
        // /WEB-INF/lib/*.jar
        else if (uri.startsWith(WEB_INF_LIB_PREFIX)) {
          String jarName = uri.replace(WEB_INF_LIB_PREFIX, "");
          if (jarName.startsWith("/") || jarName.startsWith("\\")) jarName = jarName.substring(1);
          if (jarName.length() == 0) return null;
          File jarFile = webInfJarMap.get(jarName);
          if (jarFile != null) return Resource.newResource(jarFile.getPath());

          return null;
        }
      } catch (MalformedURLException e) {
        throw e;
      } catch (IOException e) {
        Log.ignore(e);
      }
    }
    return resource;
  }
  /** On Connect, close socket */
  public static class FastCloseSocket extends AbstractCloseSocket {
    private static final Logger LOG =
        Log.getLogger(ManyConnectionsCleanupTest.FastCloseSocket.class);
    private final AtomicInteger calls;

    public FastCloseSocket(AtomicInteger calls) {
      this.calls = calls;
    }

    @Override
    public void onWebSocketConnect(Session sess) {
      LOG.debug("onWebSocketConnect({})", sess);
      calls.incrementAndGet();
      sess.close(StatusCode.NORMAL, "FastCloseServer");
    }
  }
Example #18
0
/**
 * {@link ProxyEngine} is the class for SPDY proxy functionalities that receives a SPDY request and
 * converts it to any protocol to its server side.
 *
 * <p>This class listens for SPDY events sent by clients; subclasses are responsible for translating
 * these SPDY client events into appropriate events to forward to the server, in the appropriate
 * protocol that is understood by the server.
 */
public abstract class ProxyEngine {
  protected final Logger logger = Log.getLogger(getClass());
  private final String name;

  protected ProxyEngine() {
    this(name());
  }

  private static String name() {
    try {
      return InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException x) {
      return "localhost";
    }
  }

  public abstract StreamFrameListener proxy(
      Stream clientStream,
      SynInfo clientSynInfo,
      ProxyEngineSelector.ProxyServerInfo proxyServerInfo);

  protected ProxyEngine(String name) {
    this.name = name;
  }

  public String getName() {
    return name;
  }

  protected void addRequestProxyHeaders(Stream stream, Fields headers) {
    addViaHeader(headers);
    InetSocketAddress address = stream.getSession().getRemoteAddress();
    if (address != null) headers.add("X-Forwarded-For", address.getHostName());
  }

  protected void addResponseProxyHeaders(Stream stream, Fields headers) {
    addViaHeader(headers);
  }

  private void addViaHeader(Fields headers) {
    headers.add("Via", "http/1.1 " + getName());
  }

  protected void customizeRequestHeaders(Stream stream, Fields headers) {}

  protected void customizeResponseHeaders(Stream stream, Fields headers) {}
}
Example #19
0
/** Simple Echo WebSocket, using async writes of echo */
@WebSocket
public class ABSocket {
  private static Logger LOG = Log.getLogger(ABSocket.class);

  private Session session;

  private String abbreviate(String message) {
    if (message.length() > 80) {
      return '"' + message.substring(0, 80) + "\"...";
    }
    return '"' + message + '"';
  }

  @OnWebSocketMessage
  public void onBinary(byte buf[], int offset, int len) {
    LOG.debug("onBinary(byte[{}],{},{})", buf.length, offset, len);

    // echo the message back.
    ByteBuffer data = ByteBuffer.wrap(buf, offset, len);
    this.session.getRemote().sendBytesByFuture(data);
  }

  @OnWebSocketConnect
  public void onOpen(Session sess) {
    this.session = sess;
  }

  @OnWebSocketMessage
  public void onText(String message) {
    if (LOG.isDebugEnabled()) {
      if (message == null) {
        LOG.debug("onText() msg=null");
      } else {
        LOG.debug("onText() size={}, msg={}", message.length(), abbreviate(message));
      }
    }

    try {
      // echo the message back.
      this.session.getRemote().sendStringByFuture(message);
    } catch (WebSocketException e) {
      LOG.warn("Unable to echo TEXT message", e);
    }
  }
}
  /** On Connect, throw unhandled exception */
  public static class FastFailSocket extends AbstractCloseSocket {
    private static final Logger LOG =
        Log.getLogger(ManyConnectionsCleanupTest.FastFailSocket.class);
    private final AtomicInteger calls;

    public FastFailSocket(AtomicInteger calls) {
      this.calls = calls;
    }

    @Override
    public void onWebSocketConnect(Session sess) {
      LOG.debug("onWebSocketConnect({})", sess);
      calls.incrementAndGet();
      // Test failure due to unhandled exception
      // this should trigger a fast-fail closure during open/connect
      throw new RuntimeException("Intentional FastFail");
    }
  }
/** Producer of {@link org.eclipse.jetty.websocket.api.Session} instances */
public class JettyWebSocketSessionProducer {
  private static final Logger LOG = Log.getLogger(JettyWebSocketSessionProducer.class);

  @Produces
  public Session getSession(InjectionPoint injectionPoint) {
    if (LOG.isDebugEnabled()) {
      LOG.debug("getSession({})", injectionPoint);
    }
    WebSocketScopeContext ctx = WebSocketScopeContext.current();
    if (ctx == null) {
      throw new IllegalStateException("Not in a " + WebSocketScope.class.getName());
    }
    org.eclipse.jetty.websocket.api.Session sess = ctx.getSession();
    if (sess == null) {
      throw new IllegalStateException("No Session Available");
    }
    return sess;
  }
}
/**
 * Convert an {@link Enum} to JSON. If fromJSON is true in the constructor, the JSON generated will
 * be of the form {class="com.acme.TrafficLight",value="Green"} If fromJSON is false, then only the
 * string value of the enum is generated.
 */
public class JSONEnumConvertor implements JSON.Convertor {
  private static final Logger LOG = Log.getLogger(JSONEnumConvertor.class);
  private boolean _fromJSON;
  private Method _valueOf;

  {
    try {
      Class<?> e = Loader.loadClass(getClass(), "java.lang.Enum");
      _valueOf = e.getMethod("valueOf", Class.class, String.class);
    } catch (Exception e) {
      throw new RuntimeException("!Enums", e);
    }
  }

  public JSONEnumConvertor() {
    this(false);
  }

  public JSONEnumConvertor(boolean fromJSON) {
    _fromJSON = fromJSON;
  }

  public Object fromJSON(Map map) {
    if (!_fromJSON) throw new UnsupportedOperationException();
    try {
      Class c = Loader.loadClass(getClass(), (String) map.get("class"));
      return _valueOf.invoke(null, c, map.get("value"));
    } catch (Exception e) {
      LOG.warn(e);
    }
    return null;
  }

  public void toJSON(Object obj, Output out) {
    if (_fromJSON) {
      out.addClass(obj.getClass());
      out.add("value", ((Enum) obj).name());
    } else {
      out.add(((Enum) obj).name());
    }
  }
}
  /** On Message, return container information */
  public static class ContainerSocket extends AbstractCloseSocket {
    private static final Logger LOG =
        Log.getLogger(ManyConnectionsCleanupTest.ContainerSocket.class);
    private final WebSocketServerFactory container;
    private final AtomicInteger calls;
    private Session session;

    public ContainerSocket(WebSocketServerFactory container, AtomicInteger calls) {
      this.container = container;
      this.calls = calls;
    }

    @Override
    public void onWebSocketText(String message) {
      LOG.debug("onWebSocketText({})", message);
      calls.incrementAndGet();
      if (message.equalsIgnoreCase("openSessions")) {
        Collection<WebSocketSession> sessions = container.getOpenSessions();

        StringBuilder ret = new StringBuilder();
        ret.append("openSessions.size=").append(sessions.size()).append('\n');
        int idx = 0;
        for (WebSocketSession sess : sessions) {
          ret.append('[').append(idx++).append("] ").append(sess.toString()).append('\n');
        }
        session.getRemote().sendStringByFuture(ret.toString());
        session.close(StatusCode.NORMAL, "ContainerSocket");
      } else if (message.equalsIgnoreCase("calls")) {
        session.getRemote().sendStringByFuture(String.format("calls=%,d", calls.get()));
      }
    }

    @Override
    public void onWebSocketConnect(Session sess) {
      LOG.debug("onWebSocketConnect({})", sess);
      this.session = sess;
    }
  }
Example #24
0
/**
 * Used to discover the rest of the server URIs through a HTTP GET request to the server root (/).
 */
@Path("/")
public class DiscoveryService {

  private static final Logger LOGGER = Log.getLogger(DiscoveryService.class);
  private final Configuration configuration;
  private final OutputFormat outputFormat;

  public DiscoveryService(
      @Context Configuration configuration, @Context OutputFormat outputFormat) {
    this.configuration = configuration;
    this.outputFormat = outputFormat;
  }

  @GET
  @Produces(MediaType.APPLICATION_JSON)
  public Response getDiscoveryDocument() throws URISyntaxException {
    String webAdminManagementUri =
        configuration.getString(
            Configurator.MANAGEMENT_PATH_PROPERTY_KEY, Configurator.DEFAULT_MANAGEMENT_API_PATH);
    String dataUri =
        configuration.getString(
            Configurator.REST_API_PATH_PROPERTY_KEY, Configurator.DEFAULT_DATA_API_PATH);

    DiscoveryRepresentation dr = new DiscoveryRepresentation(webAdminManagementUri, dataUri);
    return outputFormat.ok(dr);
  }

  @GET
  @Produces(MediaType.WILDCARD)
  public Response redirectToBrowser() {
    try {
      return Response.seeOther(new URI(Configurator.BROWSER_PATH)).build();
    } catch (URISyntaxException e) {
      LOGGER.warn(e.getMessage());
      return Response.serverError().build();
    }
  }
}
public class WebListenerAnnotationHandler extends AbstractDiscoverableAnnotationHandler {
  private static final Logger LOG = Log.getLogger(WebListenerAnnotationHandler.class);

  public WebListenerAnnotationHandler(WebAppContext context) {
    super(context);
  }

  public void handle(ClassInfo info, String annotationName) {
    if (annotationName == null || !"javax.servlet.annotation.WebListener".equals(annotationName))
      return;

    WebListenerAnnotation wlAnnotation =
        new WebListenerAnnotation(_context, info.getClassName(), info.getContainingResource());
    addAnnotation(wlAnnotation);
  }

  public void handle(FieldInfo info, String annotationName) {
    if (annotationName == null || !"javax.servlet.annotation.WebListener".equals(annotationName))
      return;
    LOG.warn(
        "@WebListener is not applicable to fields: "
            + info.getClassInfo().getClassName()
            + "."
            + info.getFieldName());
  }

  public void handle(MethodInfo info, String annotationName) {
    if (annotationName == null || !"javax.servlet.annotation.WebListener".equals(annotationName))
      return;
    LOG.warn(
        "@WebListener is not applicable to methods: "
            + info.getClassInfo().getClassName()
            + "."
            + info.getMethodName()
            + " "
            + info.getSignature());
  }
}
public class PlatformAnnotationConfiguration extends AnnotationConfiguration {

  private static final Logger LOG = Log.getLogger(PlatformAnnotationConfiguration.class);

  private List<Resource> getResources(ClassLoader aLoader) throws IOException {
    if (aLoader instanceof URLClassLoader) {
      List<Resource> _result = new ArrayList<Resource>();
      URL[] _urls = ((URLClassLoader) aLoader).getURLs();
      for (URL _url : _urls) {
        _result.add(Resource.newResource(_url));
      }
      return _result;
    }
    return Collections.emptyList();
  }

  public void parseContainerPath(final WebAppContext context, final AnnotationParser parser)
      throws Exception {
    final Set<Handler> handlers = new HashSet<Handler>();
    handlers.addAll(_discoverableAnnotationHandlers);
    handlers.addAll(_containerInitializerAnnotationHandlers);
    if (_classInheritanceHandler != null) {
      handlers.add(_classInheritanceHandler);
    }
    _containerPathStats = new CounterStatistic();
    List<Resource> _resources = getResources(getClass().getClassLoader());
    for (Resource r : _resources) {
      if (_parserTasks != null) {
        ParserTask task = new ParserTask(parser, handlers, r, _containerClassNameResolver);
        _parserTasks.add(task);
        _containerPathStats.increment();
        if (LOG.isDebugEnabled()) {
          task.setStatistic(new TimeStatistic());
        }
      }
    }
  }
}
Example #27
0
@ServerEndpoint("/echo/primitives/short")
public class ShortTextSocket {
  private static final Logger LOG = Log.getLogger(ShortTextSocket.class);

  private Session session;

  @OnOpen
  public void onOpen(Session session) {
    this.session = session;
  }

  @OnMessage
  public void onMessage(short s) throws IOException {
    String msg = Short.toString(s);
    session.getAsyncRemote().sendText(msg);
  }

  @OnError
  public void onError(Throwable cause) throws IOException {
    LOG.warn("Error", cause);
    session.getBasicRemote().sendText("Exception: " + StackUtil.toString(cause));
  }
}
Example #28
0
  public static MockResponse expect(String uri, MockResponse mockResponse) {
    if (uri == null) {
      throw new NullPointerException("URI is mandatory");
    }

    synchronized (lock) {
      while (mockResponses.containsKey(uri) || mockListeneres.containsKey(uri)) {
        try {
          lock.wait(1000);
        } catch (InterruptedException e) {
          Log.debug(e.getMessage(), e);
        }
      }

      mockResponses.put(uri, mockResponse);
      if (responses.get() == null) {
        responses.set(new ArrayList<MockResponse>());
      }
      responses.get().add(mockResponse);

      return mockResponse;
    }
  }
Example #29
0
  @SuppressWarnings("unchecked")
  public static <E> MockListener<E> listen(String uri, MockListener<E> mockListener) {
    if (uri == null) {
      throw new NullPointerException("URI is mandatory");
    }

    synchronized (lock) {
      while (mockResponses.containsKey(uri) || mockListeneres.containsKey(uri)) {
        try {
          lock.wait(1000);
        } catch (InterruptedException e) {
          Log.debug(e.getMessage(), e);
        }
      }

      mockListeneres.put(uri, (MockListener<Object>) mockListener);
      if (listeners.get() == null) {
        listeners.set(new ArrayList<MockListener<Object>>());
      }
      listeners.get().add((MockListener<Object>) mockListener);

      return mockListener;
    }
  }
/**
 * AntWebAppContext
 *
 * <p>Extension of WebAppContext to allow configuration via Ant environment.
 */
public class AntWebAppContext extends WebAppContext {
  private static final Logger LOG = Log.getLogger(WebAppContext.class);

  public final AntWebInfConfiguration antWebInfConfiguration = new AntWebInfConfiguration();
  public final WebXmlConfiguration webXmlConfiguration = new WebXmlConfiguration();
  public final MetaInfConfiguration metaInfConfiguration = new MetaInfConfiguration();
  public final FragmentConfiguration fragmentConfiguration = new FragmentConfiguration();
  public final EnvConfiguration envConfiguration = new EnvConfiguration();
  public final PlusConfiguration plusConfiguration = new PlusConfiguration();
  public final AnnotationConfiguration annotationConfiguration = new AnnotationConfiguration();
  public final JettyWebXmlConfiguration jettyWebXmlConfiguration = new JettyWebXmlConfiguration();

  public final Configuration[] DEFAULT_CONFIGURATIONS = {
    antWebInfConfiguration,
    webXmlConfiguration,
    metaInfConfiguration,
    fragmentConfiguration,
    envConfiguration,
    plusConfiguration,
    annotationConfiguration,
    jettyWebXmlConfiguration
  };

  public static final String DEFAULT_CONTAINER_INCLUDE_JAR_PATTERN =
      ".*/.*jsp-api-[^/]*\\.jar$|.*/.*jsp-[^/]*\\.jar$|.*/.*taglibs[^/]*\\.jar$|.*/.*jstl[^/]*\\.jar$|.*/.*jsf-impl-[^/]*\\.jar$|.*/.*javax.faces-[^/]*\\.jar$|.*/.*myfaces-impl-[^/]*\\.jar$";

  /** Location of jetty-env.xml file. */
  private File jettyEnvXml;

  /** List of web application libraries. */
  private List libraries = new ArrayList();

  /** List of web application class directories. */
  private List classes = new ArrayList();

  /** context xml file to apply to the webapp */
  private File contextXml;

  /** List of extra scan targets for this web application. */
  private FileSet scanTargets;

  /** context attributes to set * */
  private Attributes attributes;

  private Project project;

  private List<File> scanFiles;

  /** Extra scan targets. */
  private FileMatchingConfiguration extraScanTargetsConfiguration;

  private FileMatchingConfiguration librariesConfiguration;

  public static void dump(ClassLoader loader) {
    while (loader != null) {
      System.err.println(loader);
      if (loader instanceof URLClassLoader) {
        URL[] urls = ((URLClassLoader) loader).getURLs();
        if (urls != null) {
          for (URL u : urls) System.err.println("\t" + u + "\n");
        }
      }
      loader = loader.getParent();
    }
  }

  /**
   * AntURLClassLoader
   *
   * <p>Adapt the AntClassLoader which is not a URLClassLoader - this is needed for jsp to be able
   * to search the classpath.
   */
  public static class AntURLClassLoader extends URLClassLoader {
    private AntClassLoader antLoader;

    public AntURLClassLoader(AntClassLoader antLoader) {
      super(new URL[] {}, antLoader);
      this.antLoader = antLoader;
    }

    @Override
    public InputStream getResourceAsStream(String name) {
      return super.getResourceAsStream(name);
    }

    @Override
    public void close() throws IOException {
      super.close();
    }

    @Override
    protected void addURL(URL url) {
      super.addURL(url);
    }

    @Override
    public URL[] getURLs() {
      Set<URL> urls = new HashSet<URL>();

      // convert urls from antLoader
      String[] paths =
          antLoader.getClasspath().split(new String(new char[] {File.pathSeparatorChar}));
      if (paths != null) {
        for (String p : paths) {
          File f = new File(p);
          try {
            urls.add(f.toURI().toURL());
          } catch (Exception e) {
            LOG.ignore(e);
          }
        }
      }

      // add in any that may have been added to us as a URL directly
      URL[] ourURLS = super.getURLs();
      if (ourURLS != null) {
        for (URL u : ourURLS) urls.add(u);
      }

      return urls.toArray(new URL[urls.size()]);
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
      return super.findClass(name);
    }

    @Override
    protected Package definePackage(String name, Manifest man, URL url)
        throws IllegalArgumentException {
      return super.definePackage(name, man, url);
    }

    @Override
    public URL findResource(String name) {
      return super.findResource(name);
    }

    @Override
    public Enumeration<URL> findResources(String name) throws IOException {
      return super.findResources(name);
    }

    @Override
    protected PermissionCollection getPermissions(CodeSource codesource) {
      return super.getPermissions(codesource);
    }

    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
      return super.loadClass(name);
    }

    @Override
    protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
      return super.loadClass(name, resolve);
    }

    @Override
    protected Object getClassLoadingLock(String className) {
      return super.getClassLoadingLock(className);
    }

    @Override
    public URL getResource(String name) {
      return super.getResource(name);
    }

    @Override
    public Enumeration<URL> getResources(String name) throws IOException {
      return super.getResources(name);
    }

    @Override
    protected Package definePackage(
        String name,
        String specTitle,
        String specVersion,
        String specVendor,
        String implTitle,
        String implVersion,
        String implVendor,
        URL sealBase)
        throws IllegalArgumentException {
      return super.definePackage(
          name, specTitle, specVersion, specVendor, implTitle, implVersion, implVendor, sealBase);
    }

    @Override
    protected Package getPackage(String name) {
      return super.getPackage(name);
    }

    @Override
    protected Package[] getPackages() {
      return super.getPackages();
    }

    @Override
    protected String findLibrary(String libname) {
      return super.findLibrary(libname);
    }

    @Override
    public void setDefaultAssertionStatus(boolean enabled) {
      super.setDefaultAssertionStatus(enabled);
    }

    @Override
    public void setPackageAssertionStatus(String packageName, boolean enabled) {
      super.setPackageAssertionStatus(packageName, enabled);
    }

    @Override
    public void setClassAssertionStatus(String className, boolean enabled) {
      super.setClassAssertionStatus(className, enabled);
    }

    @Override
    public void clearAssertionStatus() {
      super.clearAssertionStatus();
    }
  }

  /** AntServletHolder */
  public static class AntServletHolder extends ServletHolder {

    public AntServletHolder() {
      super();
    }

    public AntServletHolder(Class<? extends Servlet> servlet) {
      super(servlet);
    }

    public AntServletHolder(Servlet servlet) {
      super(servlet);
    }

    public AntServletHolder(String name, Class<? extends Servlet> servlet) {
      super(name, servlet);
    }

    public AntServletHolder(String name, Servlet servlet) {
      super(name, servlet);
    }

    protected String getSystemClassPath(ClassLoader loader) throws Exception {
      StringBuilder classpath = new StringBuilder();
      while (loader != null) {
        if (loader instanceof URLClassLoader) {
          URL[] urls = ((URLClassLoader) loader).getURLs();
          if (urls != null) {
            for (int i = 0; i < urls.length; i++) {
              Resource resource = Resource.newResource(urls[i]);
              File file = resource.getFile();
              if (file != null && file.exists()) {
                if (classpath.length() > 0) classpath.append(File.pathSeparatorChar);
                classpath.append(file.getAbsolutePath());
              }
            }
          }
        } else if (loader instanceof AntClassLoader) {
          classpath.append(((AntClassLoader) loader).getClasspath());
        }

        loader = loader.getParent();
      }

      return classpath.toString();
    }
  }

  /** AntServletHandler */
  public static class AntServletHandler extends ServletHandler {

    @Override
    public ServletHolder newServletHolder(Holder.Source source) {
      return new AntServletHolder();
    }
  }

  /**
   * Default constructor. Takes application name as an argument
   *
   * @param name web application name.
   */
  public AntWebAppContext(Project project) throws Exception {
    super();
    this.project = project;
    setConfigurations(DEFAULT_CONFIGURATIONS);
    setAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN, DEFAULT_CONTAINER_INCLUDE_JAR_PATTERN);
    setParentLoaderPriority(true);
  }

  /** Adds a new Ant's attributes tag object if it have not been created yet. */
  public void addAttributes(Attributes atts) {
    if (this.attributes != null) {
      throw new BuildException("Only one <attributes> tag is allowed!");
    }

    this.attributes = atts;
  }

  public void addLib(FileSet lib) {
    libraries.add(lib);
  }

  public void addClasses(FileSet classes) {
    this.classes.add(classes);
  }

  @Override
  protected ServletHandler newServletHandler() {
    return new AntServletHandler();
  }

  public void setJettyEnvXml(File jettyEnvXml) {
    this.jettyEnvXml = jettyEnvXml;
    TaskLog.log(
        "jetty-env.xml file: = " + (jettyEnvXml == null ? null : jettyEnvXml.getAbsolutePath()));
  }

  public File getJettyEnvXml() {
    return this.jettyEnvXml;
  }

  public List getLibraries() {
    return librariesConfiguration.getBaseDirectories();
  }

  public void addScanTargets(FileSet scanTargets) {
    if (this.scanTargets != null) {
      throw new BuildException("Only one <scanTargets> tag is allowed!");
    }

    this.scanTargets = scanTargets;
  }

  public List getScanTargetFiles() {
    if (this.scanTargets == null) return null;

    FileMatchingConfiguration configuration = new FileMatchingConfiguration();
    configuration.addDirectoryScanner(scanTargets.getDirectoryScanner(project));
    return configuration.getBaseDirectories();
  }

  public List<File> getScanFiles() {
    if (scanFiles == null) scanFiles = initScanFiles();
    return scanFiles;
  }

  public boolean isScanned(File file) {
    List<File> files = getScanFiles();
    if (files == null || files.isEmpty()) return false;
    return files.contains(file);
  }

  public List<File> initScanFiles() {
    List<File> scanList = new ArrayList<File>();

    if (getDescriptor() != null) {
      try {
        Resource r = Resource.newResource(getDescriptor());
        scanList.add(r.getFile());
      } catch (IOException e) {
        throw new BuildException(e);
      }
    }

    if (getJettyEnvXml() != null) {
      try {
        Resource r = Resource.newResource(getJettyEnvXml());
        scanList.add(r.getFile());
      } catch (IOException e) {
        throw new BuildException("Problem configuring scanner for jetty-env.xml", e);
      }
    }

    if (getDefaultsDescriptor() != null) {
      try {
        if (!AntWebAppContext.WEB_DEFAULTS_XML.equals(getDefaultsDescriptor())) {
          Resource r = Resource.newResource(getDefaultsDescriptor());
          scanList.add(r.getFile());
        }
      } catch (IOException e) {
        throw new BuildException("Problem configuring scanner for webdefaults.xml", e);
      }
    }

    if (getOverrideDescriptor() != null) {
      try {
        Resource r = Resource.newResource(getOverrideDescriptor());
        scanList.add(r.getFile());
      } catch (IOException e) {
        throw new BuildException("Problem configuring scanner for webdefaults.xml", e);
      }
    }

    // add any extra classpath and libs
    List<File> cpFiles = getClassPathFiles();
    if (cpFiles != null) scanList.addAll(cpFiles);

    // any extra scan targets
    @SuppressWarnings("unchecked")
    List<File> scanFiles = (List<File>) getScanTargetFiles();
    if (scanFiles != null) scanList.addAll(scanFiles);

    return scanList;
  }

  @Override
  public void setWar(String path) {
    super.setWar(path);

    try {
      Resource war = Resource.newResource(path);
      if (war.exists() && war.isDirectory() && getDescriptor() == null) {
        Resource webXml = war.addPath("WEB-INF/web.xml");
        setDescriptor(webXml.toString());
      }
    } catch (IOException e) {
      throw new BuildException(e);
    }
  }

  /** */
  public void doStart() {
    try {
      TaskLog.logWithTimestamp("Starting web application " + this.getDescriptor());
      if (jettyEnvXml != null && jettyEnvXml.exists())
        envConfiguration.setJettyEnvXml(Resource.toURL(jettyEnvXml));

      ClassLoader parentLoader = this.getClass().getClassLoader();
      if (parentLoader instanceof AntClassLoader)
        parentLoader = new AntURLClassLoader((AntClassLoader) parentLoader);

      setClassLoader(new WebAppClassLoader(parentLoader, this));
      if (attributes != null && attributes.getAttributes() != null) {
        for (Attribute a : attributes.getAttributes()) setAttribute(a.getName(), a.getValue());
      }

      // apply a context xml file if one was supplied
      if (contextXml != null) {
        XmlConfiguration xmlConfiguration = new XmlConfiguration(Resource.toURL(contextXml));
        TaskLog.log("Applying context xml file " + contextXml);
        xmlConfiguration.configure(this);
      }

      super.doStart();
    } catch (Exception e) {
      TaskLog.log(e.toString());
    }
  }

  /** @see WebApplicationProxy#stop() */
  public void doStop() {
    try {
      scanFiles = null;
      TaskLog.logWithTimestamp("Stopping web application " + this);
      Thread.currentThread().sleep(500L);
      super.doStop();
    } catch (InterruptedException e) {
      TaskLog.log(e.toString());
    } catch (Exception e) {
      TaskLog.log(e.toString());
    }
  }

  /** @return a list of classpath files (libraries and class directories). */
  public List<File> getClassPathFiles() {
    List<File> classPathFiles = new ArrayList<File>();
    Iterator classesIterator = classes.iterator();
    while (classesIterator.hasNext()) {
      FileSet clazz = (FileSet) classesIterator.next();
      classPathFiles.add(clazz.getDirectoryScanner(project).getBasedir());
    }

    Iterator iterator = libraries.iterator();
    while (iterator.hasNext()) {
      FileSet library = (FileSet) iterator.next();
      String[] includedFiles = library.getDirectoryScanner(project).getIncludedFiles();
      File baseDir = library.getDirectoryScanner(project).getBasedir();

      for (int i = 0; i < includedFiles.length; i++) {
        classPathFiles.add(new File(baseDir, includedFiles[i]));
      }
    }

    return classPathFiles;
  }

  /**
   * @return a <code>FileMatchingConfiguration</code> object describing the configuration of all
   *     libraries added to this particular web app (both classes and libraries).
   */
  public FileMatchingConfiguration getLibrariesConfiguration() {
    FileMatchingConfiguration config = new FileMatchingConfiguration();

    Iterator classesIterator = classes.iterator();
    while (classesIterator.hasNext()) {
      FileSet clazz = (FileSet) classesIterator.next();
      config.addDirectoryScanner(clazz.getDirectoryScanner(project));
    }

    Iterator librariesIterator = libraries.iterator();
    while (librariesIterator.hasNext()) {
      FileSet library = (FileSet) librariesIterator.next();
      config.addDirectoryScanner(library.getDirectoryScanner(project));
    }

    return config;
  }

  public File getContextXml() {
    return contextXml;
  }

  public void setContextXml(File contextXml) {
    this.contextXml = contextXml;
  }
}