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();
  }
Пример #2
0
 /**
  * Set Log to parent Logger.
  *
  * <p>If there is a different Log class available from a parent classloader, call {@link
  * #getLogger(String)} on it and construct a {@link LoggerLog} instance as this Log's Logger, so
  * that logging is delegated to the parent Log.
  *
  * <p>This should be used if a webapp is using Log, but wishes the logging to be directed to the
  * containers log.
  *
  * <p>If there is not parent Log, then this call is equivalent to
  *
  * <pre>
  *   Log.setLog(Log.getLogger(name));
  * </pre>
  *
  * @param name Logger name
  */
 public static void setLogToParent(String name) {
   ClassLoader loader = Log.class.getClassLoader();
   if (loader != null && loader.getParent() != null) {
     try {
       Class<?> uberlog = loader.getParent().loadClass("org.eclipse.jetty.util.log.Log");
       Method getLogger = uberlog.getMethod("getLogger", new Class[] {String.class});
       Object logger = getLogger.invoke(null, name);
       setLog(new LoggerLog(logger));
     } catch (Exception e) {
       e.printStackTrace();
     }
   } else {
     setLog(getLogger(name));
   }
 }
Пример #3
0
  protected void startServer() {

    if (server == null) {
      // stop excessive logging
      Log.setLog(null);
      System.setProperty("DEBUG", "false");
      System.setProperty("VERBOSE", "false");

      server = new Server();
    }

    Connector connector = null;
    if (useSSL) {
      SslContextFactory contextFactory = new SslContextFactory();
      contextFactory.setKeyStore(sslKeystore);
      contextFactory.setKeyStorePassword(sslPassword);
      contextFactory.setKeyManagerPassword(sslKeyPassword);
      contextFactory.setNeedClientAuth(needClientAuth);
      connector = new SslSelectChannelConnector(contextFactory);

      // Setup JSSE keystore and set parameters here correctly
      //			connector = new SslSocketConnector();
      //			((SslSocketConnector)connector).setKeystore(sslKeystore);
      //			((SslSocketConnector)connector).setPassword(sslPassword);
      //			((SslSocketConnector)connector).setKeyPassword(sslKeyPassword);
      //			((SslSocketConnector)connector).setNeedClientAuth(needClientAuth);
      // uses an entry in the keystore called "jetty"
    } else {
      // connector = new SocketConnector();
      connector = new SelectChannelConnector();
    }
    connector.setPort(port);
    server.addConnector(connector);

    // set the Server's HandlerCollection. Other handlers will be added to the HandlerCollection
    handlerCollection = new ContextHandlerCollection();
    server.setHandler(handlerCollection);

    // create servlet context
    servletContext =
        new ServletContextHandler(
            handlerCollection, servletContextString, ServletContextHandler.SESSIONS);
    //		servletContext = new ServletContextHandler(handlerCollection, servletContextString,
    // ServletContextHandler.SESSIONS);

    // create web app context
    // webAppContext = new Context(handlerCollection, webAppContextString, Context.SESSIONS);

    try {

      // add ResourceHandlers
      addResourceHandlers();

      // add servlets to the servlet context
      // servletContext.addHandler(new SecurityHandler());
      addServletsToContext(servletContext);

      //
      addWebApps();

      // add default handler to the server
      handlerCollection.addHandler(new DefaultHandler());

      // start a Jetty
      server.start();
    } catch (BindException ex) {
      logger.log(
          Level.INFO, "Could not start web server on port " + port + ": " + ex.getMessage(), ex);
      lifeCycleControlConduit.vote(meemContext.getWedgeIdentifier(), false);
      return;
    } catch (InstantiationException ex) {
      logger.log(Level.INFO, "Could not add servlet: ", ex);
      lifeCycleControlConduit.vote(meemContext.getWedgeIdentifier(), false);
      return;
    } catch (IllegalAccessException ex) {
      logger.log(Level.INFO, "Could not add servlet: ", ex);
      lifeCycleControlConduit.vote(meemContext.getWedgeIdentifier(), false);
      return;
    } catch (ClassNotFoundException ex) {
      logger.log(Level.INFO, "Could not add servlet: ", ex);
      lifeCycleControlConduit.vote(meemContext.getWedgeIdentifier(), false);
      return;
    } catch (MultiException ex) {
      logger.log(Level.INFO, "Problem while starting the web server: ", ex);
      lifeCycleControlConduit.vote(meemContext.getWedgeIdentifier(), false);
      return;
    } catch (Exception ex) {
      logger.log(Level.INFO, "Problem while starting the web server: ", ex);
      lifeCycleControlConduit.vote(meemContext.getWedgeIdentifier(), false);
      return;
    }

    lifeCycleControlConduit.vote(meemContext.getWedgeIdentifier(), true);
  }
Пример #4
0
  public static void main(String[] args) throws Exception {
    ReplayProps.Init();

    ReplayDB.init();

    ReplayLogger.log(Level.INFO, "Log opened...");

    org.eclipse.jetty.util.log.Log.setLog(ReplayLogger.replayLogger);

    final int quickTaskFrequencyInSeconds = ReplayProps.getInt("quickTaskFrequencyInSeconds", "10");
    final int longTaskFrequencyInHours = ReplayProps.getInt("longTaskFrequencyInHours", "1");

    timer = new Timer();

    if (quickTaskFrequencyInSeconds != 0) {
      timer.schedule(
          new CleanupTask.QuickTask(),
          quickTaskFrequencyInSeconds * 1000,
          quickTaskFrequencyInSeconds * 1000);
    }

    if (quickTaskFrequencyInSeconds != 0) {
      timer.schedule(
          new CleanupTask.LongTask(),
          60 * 60 * 1000 * longTaskFrequencyInHours,
          60 * 60 * 1000 * longTaskFrequencyInHours);
    }

    final int httpPort = ReplayProps.getInt("httpPort", "80");

    final Server server = new Server(httpPort);

    ServletContextHandler context =
        new ServletContextHandler(ServletContextHandler.SESSIONS | ServletContextHandler.SECURITY);
    context.setContextPath("/");
    server.setHandler(context);

    // Change default timeout to 45 seconds (from 30)
    /*
    ServerConnector http = new ServerConnector( server );
    //http.setHost( "localhost" );
    http.setPort( httpPort );
    http.setIdleTimeout( 45000 );

    server.addConnector( http );
    */

    final boolean bTestAuthorize = false;

    if (bTestAuthorize) {
      context.addServlet(
          new ServletHolder(
              new HttpServlet() {
                private static final long serialVersionUID = 1L;

                @Override
                protected void doPost(HttpServletRequest request, HttpServletResponse response)
                    throws ServletException, IOException {
                  final ServletInputStream inputStream = request.getInputStream();

                  FileUtils.ReplayOutputStream outputStream =
                      FileUtils.getReplayOutputStream("authorize.txt", false);

                  byte[] buffer = new byte[1024];

                  int readBytes = 0;

                  while ((readBytes = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, readBytes);
                  }

                  inputStream.close();
                  outputStream.close();

                  response.setContentType("text/html");
                  response
                      .getWriter()
                      .println("<p>Worked: " + request.getContentType() + " </p><br>");
                }
              }),
          "/j_security_check");
    }

    context.addServlet(new ServletHolder(new Download()), "/download/*");
    context.addServlet(new ServletHolder(new DownloadEvent()), "/downloadevent/*");
    context.addServlet(new ServletHolder(new Upload()), "/upload/*");
    context.addServlet(new ServletHolder(new UploadEvent()), "/uploadevent/*");
    context.addServlet(new ServletHolder(new StartUploading()), "/startuploading/*");
    context.addServlet(new ServletHolder(new StopUploading()), "/stopuploading/*");
    context.addServlet(new ServletHolder(new StartDownloading()), "/startdownloading/*");
    context.addServlet(new ServletHolder(new DeleteSession()), "/deletesession/*");
    context.addServlet(new ServletHolder(new EnumerateSessions()), "/enumsessions/*");
    context.addServlet(new ServletHolder(new EnumEvents()), "/enumevents/*");
    context.addServlet(new ServletHolder(new RefreshViewer()), "/refreshviewer/*");
    context.addServlet(new ServletHolder(new ViewFile()), "/viewfile/*");

    if (ReplayProps.getInt("enableBuiltInWebServer", "1") == 1) {
      context.addServlet(new ServletHolder(new Index()), "/*");
    }

    // Password protect the delete session page
    context.addServlet(
        new ServletHolder(
            new HttpServlet() {
              private static final long serialVersionUID = 1L;

              @Override
              protected void doGet(HttpServletRequest request, HttpServletResponse response)
                  throws ServletException, IOException {
                response.setContentType("text/html");
                response
                    .getWriter()
                    .append(
                        "<form method='POST' action='/j_security_check'>"
                            + "<input type='text' name='j_username'/>"
                            + "<input type='password' name='j_password'/>"
                            + "<input type='submit' value='Login'/></form>");
              }
            }),
        "/login");

    final Constraint constraint = new Constraint();
    constraint.setName(Constraint.__FORM_AUTH);
    constraint.setRoles(new String[] {"user", "admin", "moderator"});
    constraint.setAuthenticate(true);

    final ConstraintMapping constraintMapping = new ConstraintMapping();
    constraintMapping.setConstraint(constraint);
    constraintMapping.setPathSpec("/deletesession/*");

    final ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
    securityHandler.addConstraintMapping(constraintMapping);
    HashLoginService loginService = new HashLoginService();
    loginService.putUser("usern", new Password("pass"), new String[] {"user"});
    loginService.putUser("admin", new Password("pass"), new String[] {"admin"});
    securityHandler.setLoginService(loginService);

    final FormAuthenticator authenticator = new FormAuthenticator("/login", "/login", false);
    securityHandler.setAuthenticator(authenticator);

    if (!bTestAuthorize) {
      context.setSecurityHandler(securityHandler);
    }

    server.start();
    server.join();

    ReplayDB.shutdown();
  }
Пример #5
0
  public DLNARouteProvider(Context context) {
    super(context);

    // Use custom logger
    org.eclipse.jetty.util.log.Log.setLog(new JettyAndroidLog());

    this.downloadService = (DownloadService) context;
    dlnaServiceConnection =
        new ServiceConnection() {
          @Override
          public void onServiceConnected(ComponentName name, IBinder service) {
            dlnaService = (AndroidUpnpService) service;
            dlnaService
                .getRegistry()
                .addListener(
                    new RegistryListener() {
                      @Override
                      public void remoteDeviceDiscoveryStarted(
                          Registry registry, RemoteDevice remoteDevice) {}

                      @Override
                      public void remoteDeviceDiscoveryFailed(
                          Registry registry, RemoteDevice remoteDevice, Exception e) {
                        // Error is displayed in log anyways under W/trieveRemoteDescriptors
                      }

                      @Override
                      public void remoteDeviceAdded(Registry registry, RemoteDevice remoteDevice) {
                        deviceAdded(remoteDevice);
                      }

                      @Override
                      public void remoteDeviceUpdated(
                          Registry registry, RemoteDevice remoteDevice) {
                        deviceAdded(remoteDevice);
                      }

                      @Override
                      public void remoteDeviceRemoved(
                          Registry registry, RemoteDevice remoteDevice) {
                        deviceRemoved(remoteDevice);
                      }

                      @Override
                      public void localDeviceAdded(Registry registry, LocalDevice localDevice) {
                        deviceAdded(localDevice);
                      }

                      @Override
                      public void localDeviceRemoved(Registry registry, LocalDevice localDevice) {
                        deviceRemoved(localDevice);
                      }

                      @Override
                      public void beforeShutdown(Registry registry) {}

                      @Override
                      public void afterShutdown() {}
                    });

            for (Device<?, ?, ?> device :
                dlnaService.getControlPoint().getRegistry().getDevices()) {
              deviceAdded(device);
            }
            if (searchOnConnect) {
              dlnaService.getControlPoint().search();
            }
          }

          @Override
          public void onServiceDisconnected(ComponentName name) {
            dlnaService = null;
          }
        };

    if (!context
        .getApplicationContext()
        .bindService(
            new Intent(context, AndroidUpnpServiceImpl.class),
            dlnaServiceConnection,
            Context.BIND_AUTO_CREATE)) {
      Log.e(TAG, "Failed to bind to DLNA service");
    }
  }
Пример #6
0
  public void start(final int port, IRascalMonitor monitor) throws Exception {
    monitor.startJob("Loading Course Manager");
    eval.eval(monitor, "import " + "CourseManager" + ";", URIUtil.rootScheme("stdin"));
    monitor.endJob(true);

    Log.setLog(
        new Logger() {

          @Override
          public String getName() {
            return "no logger";
          }

          @Override
          public void warn(String msg, Object... args) {}

          @Override
          public void warn(Throwable thrown) {}

          @Override
          public void warn(String msg, Throwable thrown) {}

          @Override
          public void info(String msg, Object... args) {}

          @Override
          public void info(Throwable thrown) {}

          @Override
          public void info(String msg, Throwable thrown) {}

          @Override
          public boolean isDebugEnabled() {
            return false;
          }

          @Override
          public void setDebugEnabled(boolean enabled) {}

          @Override
          public void debug(String msg, Object... args) {}

          @Override
          public void debug(Throwable thrown) {}

          @Override
          public void debug(String msg, Throwable thrown) {}

          @Override
          public Logger getLogger(String name) {
            return this;
          }

          @Override
          public void ignore(Throwable ignored) {}
        });

    monitor.startJob("Starting Webserver");
    server = new Server();

    SelectChannelConnector connector = new SelectChannelConnector();
    connector.setPort(port);
    connector.setMaxIdleTime(30000);
    connector.setResponseHeaderSize(1000 * 1000);
    connector.setRequestBufferSize(1000 * 1000);
    connector.setConfidentialPort(8443);

    server.setConnectors(new Connector[] {connector});
    server.setHandler(getTutorHandler());
    server.start();
    monitor.endJob(true);
  }