Beispiel #1
1
  public final void start(int port) throws Exception {
    String nodeId = registerForNotifications();
    port = setPort(port);

    System.out.println("DSO SharedQueue (node " + nodeId + ")");
    System.out.println(
        "Open your browser and go to - http://" + getHostName() + ":" + port + "/webapp\n");

    Server server = new Server();
    Connector connector = new SocketConnector();
    connector.setPort(port);
    server.setConnectors(new Connector[] {connector});

    queue = new Queue(port);
    worker = queue.createWorker(nodeId);

    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setResourceBase(".");

    ContextHandler ajaxContext = new ContextHandler();
    ajaxContext.setContextPath(SimpleHttpHandler.ACTION);
    ajaxContext.setResourceBase(cwd.getPath());
    ajaxContext.setClassLoader(Thread.currentThread().getContextClassLoader());
    ajaxContext.addHandler(new SimpleHttpHandler(queue));

    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[] {ajaxContext, resourceHandler});
    server.setHandler(handlers);

    startReaper();
    server.start();
    server.join();
  }
  /** Starts the server for end-to-end tests. */
  private Server createServer(int port) throws Exception {
    Server newServer = new Server(port);

    // Attach the test resources in /endtoend as static content for the test
    ResourceHandler resources = new ResourceHandler();
    URL resource = EndToEndTest.class.getResource("/endtoend");
    resources.setBaseResource(Resource.newResource(resource));
    newServer.addHandler(resources);

    Context context = new Context(newServer, "/", Context.SESSIONS);
    context.addEventListener(new GuiceServletContextListener());

    Map<String, String> initParams = Maps.newHashMap();
    String modules =
        Joiner.on(":")
            .join(
                SampleModule.class.getName(),
                DefaultGuiceModule.class.getName(),
                PropertiesModule.class.getName(),
                OAuthModule.class.getName());

    initParams.put(GuiceServletContextListener.MODULES_ATTRIBUTE, modules);
    context.setInitParams(initParams);

    // Attach the gadget rendering servlet
    ServletHolder gadgetServletHolder = new ServletHolder(new GadgetRenderingServlet());
    context.addServlet(gadgetServletHolder, GADGET_BASE);

    // Attach DataServiceServlet, wrapped in a proxy to fake errors
    ServletHolder restServletHolder =
        new ServletHolder(new ForceErrorServlet(new DataServiceServlet()));
    restServletHolder.setInitParameter("handlers", "org.apache.shindig.social.handlers");
    context.addServlet(restServletHolder, REST_BASE);
    context.addFilter(AuthenticationServletFilter.class, REST_BASE, 0);

    // Attach JsonRpcServlet, wrapped in a proxy to fake errors
    ServletHolder rpcServletHolder = new ServletHolder(new ForceErrorServlet(new JsonRpcServlet()));
    rpcServletHolder.setInitParameter("handlers", "org.apache.shindig.social.handlers");
    context.addServlet(rpcServletHolder, JSON_RPC_BASE);
    context.addFilter(AuthenticationServletFilter.class, JSON_RPC_BASE, 0);

    // Attach the ConcatProxyServlet - needed for rewritten JS
    ServletHolder concatHolder = new ServletHolder(new ConcatProxyServlet());
    context.addServlet(concatHolder, CONCAT_BASE);

    // Attach the JsServlet - needed for rewritten JS
    ServletHolder jsHolder = new ServletHolder(new JsServlet());
    context.addServlet(jsHolder, JS_BASE);

    // Attach MakeRequestServlet
    ServletHolder makeRequestHolder = new ServletHolder(new MakeRequestServlet());
    context.addServlet(makeRequestHolder, MAKE_REQUEST_BASE);

    // Attach an EchoServlet, used to test proxied rendering
    ServletHolder echoHolder = new ServletHolder(new EchoServlet());
    context.addServlet(echoHolder, "/echo");

    return newServer;
  }
  public void start() throws Exception {
    // static files
    final ResourceHandler staticHandler = new ResourceHandler();
    staticHandler.setResourceBase("html");

    Handler handler =
        new AbstractHandler() {
          @Override
          public void handle(
              String target,
              HttpServletRequest request,
              HttpServletResponse response,
              int dispatch) {
            try {
              // timeunit
              int timeunit = 1000; // second, divide millionsecond / 1000
              String timeunitLabel = "second";
              if (request.getParameter("u") != null
                  && request.getParameter("u").equalsIgnoreCase("m")) {
                timeunit = 1000 * 60;
                timeunitLabel = "minute";
              }

              // http request
              if (target.equals("/")) {
                printPageIndex(request, response);
              } else if (target.equals("/simulate")) {
                printPageSimulate(request, response, timeunit, timeunitLabel);
              } else if (target.equals("/track")) {
                printPageTrack(request, response, timeunit, timeunitLabel);
              } else
              // js/css request
              if (target.startsWith("/js") || target.startsWith("/css")) {
                response.setCharacterEncoding("utf-8");
                staticHandler.handle(target, request, response, dispatch);
              } else
              // json request
              if (target.equals("/simulateMetrics")) {
                printJsonMetrics(request, response);
              } else if (target.equals("/trackMetrics")) {
                printJsonTrack(request, response);
              }
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        };

    server = new Server(port);
    server.setHandler(handler);

    server.start();
  }
 public static void start(String resourceBase) throws Exception {
   FileServer.resourceBase = resourceBase;
   if (isStarted()) return;
   server = new Server(HTTP_PORT);
   server.setConnectors(
       new Connector[] {getPlainConnector(HTTP_PORT), getSslConnector(HTTPS_PORT)});
   ResourceHandler resourceHandler = new ResourceHandler();
   resourceHandler.setResourceBase(resourceBase);
   HandlerList handlers = new HandlerList();
   handlers.setHandlers(new Handler[] {resourceHandler, new DefaultHandler()});
   server.setHandler(handlers);
   server.start();
 }
  public S2RobotWebServer(final int port, final File docRoot) {
    this.port = port;
    this.docRoot = docRoot;

    server = new Server(port);

    final ResourceHandler resource_handler = new ResourceHandler();
    resource_handler.setWelcomeFiles(new String[] {"index.html"});
    resource_handler.setResourceBase(docRoot.getAbsolutePath());
    Log.info("serving " + resource_handler.getBaseResource());
    final HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] {resource_handler, new DefaultHandler()});
    server.setHandler(handlers);
  }
  protected void startHttpServer() throws Exception {
    Server server = new Server();
    SocketConnector sc = new SocketConnector();
    sc.setHost("127.0.0.1");
    sc.setPort(7777);
    server.addConnector(sc);
    ResourceHandler rhandler = new ResourceHandler();
    rhandler.setResourceBase(getSrcHtdocs().getAbsolutePath());

    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] {rhandler, new DefaultHandler()});
    server.setHandler(handlers);

    this.httpServer = server;
    server.start();
  }
  /**
   * Starts the web server on the default {@link #PORT}. The given resourceBase is used to be the
   * ROOT directory that serves the default context.
   *
   * <p><b>Don't forget to stop the returned HttpServer after the test</b>
   *
   * @param resourceBase the base of resources for the default context
   * @throws Exception if the test fails
   */
  protected void startWebServer(final String resourceBase) throws Exception {
    if (server_ != null) {
      throw new IllegalStateException("startWebServer() can not be called twice");
    }
    server_ = new Server(PORT);

    final WebAppContext context = new WebAppContext();
    context.setContextPath("/");
    context.setResourceBase(resourceBase);

    final ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setResourceBase(resourceBase);
    resourceHandler.getMimeTypes().addMimeMapping("js", "application/javascript");

    final HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] {resourceHandler, context});
    server_.setHandler(handlers);
    server_.setHandler(resourceHandler);
    server_.start();
  }
  public ConduitServerMain(final Config config) throws Exception {
    this.log = LogFactory.getLog(getClass());
    this.config = config;
    this.path = config.path;
    this.publicHostname = config.publicHostname;
    this.tempDirPath = new File(this.path, "tmp");

    this.database =
        new Database() {
          KeyValueStore keysByUsername =
              new FilesOnDiskKeyValueStore(new File(config.path, "keys"));
          KeyValueStore passwordsByUsername =
              new FilesOnDiskKeyValueStore(new File(config.path, "credentials"));

          @Override
          public KeyValueStore trustedKeysByUsername() {
            return keysByUsername;
          }

          @Override
          public KeyValueStore passwordsByUsername() {
            return passwordsByUsername;
          }
        };

    mkDirs(this.tempDirPath);

    basePublicUrl = "http://" + config.publicHostname + ":" + config.port;
    log.info("My public url is " + basePublicUrl);

    p4Address = new P4DepotAddress(config.p4Address);

    jetty = new Server(config.port);
    ResourceHandler defaultHandler = new ResourceHandler();
    final VFSResource root = new VFSResource("/");
    defaultHandler.setBaseResource(root);
    defaultHandler.setWelcomeFiles(new String[] {"hi.txt"});
    final List<Handler> handlers = new ArrayList<Handler>();
    handlers.add(defaultHandler);

    allocator = new TempDirAllocatorImpl(tempDirPath);

    for (ConduitDiscoveryResult conduit : findConduits()) {
      if (conduit.localPath.listFiles().length == 0) {
        FileUtils.deleteDirectory(conduit.localPath);
      } else {
        conduits.add(startConduit(basePublicUrl, root, allocator, conduit));
      }
    }

    // Add shared bzr repository
    root.addVResource("/.bzr", new File(config.path, ".bzr"));

    HttpObject addConduitPage =
        new AddConduitResource(
            new AddConduitResource.Listener() {
              @Override
              public void addConduit(
                  final ConduitType type,
                  final String name,
                  final String p4Paths,
                  final Integer p4FirstCL) {
                final String[] excludePaths = p4Paths.split("\\r?\\n");

                final List<Tuple2<String, String>> e = new ArrayList<Tuple2<String, String>>();

                for (int x = 0; x < excludePaths.length; x++) {
                  final String line = excludePaths[x].trim();
                  final boolean isExclude = line.startsWith("-");

                  P4ClientSpecServerPath parsed = P4ClientSpecServerPath.parse(line);

                  final String serverSide =
                      (isExclude ? "-" : "") + "//" + parsed.depotName + parsed.path + "/...";

                  final String clientSide = parsed.path.isEmpty() ? "/..." : parsed.path + "/...";
                  System.out.println(serverSide + " -> " + clientSide);
                  e.add(tuple(serverSide, clientSide));
                }

                ConduitCreationThread thread =
                    new ConduitCreationThread(
                        config, type, name, p4FirstCL, root, e.toArray(new Tuple2[] {}));
                creationThreads.add(thread);
                thread.start();
              }
            });

    HttpObject depotHandler =
        new HttpObject("/{conduitName}/{remainder*}", null) {

          public HostableConduit findConduitForPath(String conduitName) {
            HostableConduit foundConduit = null;
            for (HostableConduit conduit : conduits) {
              final String next = conduit.httpResource.name;
              log.debug("name: " + next);
              if (conduitName.equals(next)) {
                foundConduit = conduit;
              }
            }
            return foundConduit;
          }

          public Response relay(Request req, final Method m) {
            String conduitName = "/" + req.pathVars().valueFor("conduitName");

            HostableConduit match = findConduitForPath(conduitName);
            if (match != null) {
              return HttpObjectUtil.invokeMethod(match.httpResource, m, req);
            } else {
              log.debug("There is no conduit at " + conduitName);
              return null;
            }
          }

          @Override
          public Response get(Request req) {
            return relay(req, Method.GET);
          }

          @Override
          public Response post(Request req) {
            return relay(req, Method.POST);
          }
        };

    final HttpObject conduitLogResource =
        new HttpObject("/api/conduits/{conduitName}/log") {
          @Override
          public Response get(Request req) {
            final String conduitName = req.pathVars().valueFor("conduitName");
            final HostableConduit conduit = conduitNamed(conduitName);
            if (conduit == null) {
              return NOT_FOUND();
            } else {
              try {
                final FileInputStream in = new FileInputStream(conduit.log.location);
                return OK(Bytes("text/plain", in));
              } catch (FileNotFoundException e) {
                return INTERNAL_SERVER_ERROR(e);
              }
            }
          }
        };

    final HttpObject conduitApiResource =
        new HttpObject("/api/conduits/{conduitName}") {

          @Override
          public Response get(Request req) {
            final String conduitName = req.pathVars().valueFor("conduitName");
            final HostableConduit conduit = conduitNamed(conduitName);
            if (conduit == null) {
              return NOT_FOUND();
            } else {
              return OK(JacksonJson(conduit.toDto()));
            }
          }

          @Override
          public Response delete(Request req) {
            final String conduitName = req.pathVars().valueFor("conduitName");
            final HostableConduit conduit = conduitNamed(conduitName);
            if (conduit == null) {
              return NOT_FOUND();
            } else {
              try {
                log.info("Deleting " + conduitName);
                conduits.remove(conduit);
                conduit.orchestrator.stop();
                conduit.orchestrator.delete();
                return OK(Text("deleted"));
              } catch (Exception e) {
                return INTERNAL_SERVER_ERROR(e);
              }
            }
          }
        };

    final HttpObject conduitsApiResource =
        new HttpObject("/api/conduits") {
          @Override
          public Response get(Request req) {
            ConduitsDto conduitsDto = new ConduitsDto();

            for (HostableConduit conduit : conduits) {
              conduitsDto.conduits.add(conduit.toDto());
            }

            for (ConduitCreationThread next : creationThreads) {
              ConduitInfoDto dto = new ConduitInfoDto();
              dto.name = next.name;
              if (next.pump == null) {
                dto.status = ConduitState.STARTING;
              } else {
                dto.status = ConduitState.BUILDING;
                dto.backlogSize = next.pump.backlogSize();
                dto.p4path = next.pump.p4Path();
                dto.type = next.type;
                dto.currentP4Changelist = next.pump.currentP4Changelist();
              }

              conduitsDto.conduits.add(dto);
            }

            return OK(JacksonJson(conduitsDto));
          }
        };

    final HttpObject userDataApiResource =
        new HttpObject("/api/users/{user}/secrets") {
          @Override
          public Response put(Request req) {
            final String username = req.pathVars().valueFor("user");
            final UserSecrets secrets = readJackson(req.representation(), UserSecrets.class);

            database.passwordsByUsername().put(username, secrets.password);
            database.trustedKeysByUsername().put(username, secrets.key);

            return CREATED(Location(""));
          }
        };

    handlers.add(
        new HttpObjectsJettyHandler(
            new ClasspathResourceObject("/", "index.html", getClass()),
            new ClasspathResourceObject("/submit.py", "submit.py", getClass()),
            new ClasspathResourcesObject("/{resource*}", getClass()),
            addConduitPage,
            depotHandler,
            conduitsApiResource,
            conduitApiResource,
            userDataApiResource,
            conduitLogResource));

    jetty.setHandlers(handlers.toArray(new Handler[handlers.size()]));
    jetty.start();
  }
  @BeforeClass
  @SuppressWarnings("unchecked")
  public static void setUpClass() throws Exception {

    URI webappUri = EmbeddedJettyServer.extractResourceDir("webapp", true);
    server = new Server(port);

    ServletHolder jerseyServletHolder = new ServletHolder(ServletContainer.class);
    jerseyServletHolder.setInitParameter(
        "com.sun.jersey.config.property.resourceConfigClass",
        "com.sun.jersey.api.core.PackagesResourceConfig");
    jerseyServletHolder.setInitParameter(
        "com.sun.jersey.config.property.packages", "fr.inria.edelweiss.kgramserver.webservice");
    Context servletCtx = new Context(server, "/kgram", Context.SESSIONS);
    servletCtx.addServlet(jerseyServletHolder, "/*");
    logger.info("----------------------------------------------");
    logger.info("Corese/KGRAM endpoint started on http://localhost:" + port + "/kgram");
    logger.info("----------------------------------------------");

    ResourceHandler resource_handler = new ResourceHandler();
    resource_handler.setWelcomeFiles(new String[] {"index.html"});
    resource_handler.setResourceBase(webappUri.getRawPath());
    ContextHandler staticContextHandler = new ContextHandler();
    staticContextHandler.setContextPath("/");
    staticContextHandler.setHandler(resource_handler);
    logger.info("----------------------------------------------");
    logger.info("Corese/KGRAM webapp UI started on http://localhost:" + port);
    logger.info("----------------------------------------------");

    HandlerList handlers_s1 = new HandlerList();
    handlers_s1.setHandlers(new Handler[] {staticContextHandler, servletCtx});
    server.setHandler(handlers_s1);

    try {
      server.start();
    } catch (Exception e) {
      e.printStackTrace();
    }

    ///// Data extraction
    humanData = File.createTempFile("human", ".rdf");
    FileWriter fw = new FileWriter(humanData);
    InputStream is =
        RDFS_entailmentsTest.class.getClassLoader().getResourceAsStream("human_2007_09_11.rdf");
    int c;
    while ((c = is.read()) != -1) {
      fw.write(c);
    }
    is.close();
    fw.close();

    humanOnt = File.createTempFile("humanOnt", ".rdfs");
    fw = new FileWriter(humanOnt);
    is = RDFS_entailmentsTest.class.getClassLoader().getResourceAsStream("human_2007_09_11.rdfs");
    while ((c = is.read()) != -1) {
      fw.write(c);
    }
    is.close();
    fw.close();

    ///// Data upload
    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    WebResource service = client.resource(new URI("http://localhost:" + port + "/kgram"));

    // entailments
    MultivaluedMap formData = new MultivaluedMapImpl();
    formData.add("entailments", "true");
    service.path("sparql").path("reset").post(formData);

    formData = new MultivaluedMapImpl();
    formData.add("remote_path", humanOnt.getAbsolutePath());
    service.path("sparql").path("load").post(formData);

    formData = new MultivaluedMapImpl();
    formData.add("remote_path", humanData.getAbsolutePath());
    service.path("sparql").path("load").post(formData);
  }