@Test
  public void shouldNotRedirectNonCruiseRequestsToGoPage() throws IOException, ServletException {
    Handler legacyRequestHandler = jetty6Server.legacyRequestHandler();
    HttpServletResponse response = mock(HttpServletResponse.class);

    when(response.getWriter()).thenReturn(new PrintWriter(new ByteArrayOutputStream()));

    HttpServletRequest req = mock(HttpServletRequest.class);
    when(req.getMethod()).thenReturn(HttpMethods.GET);
    legacyRequestHandler.handle("/cruise_but_not_quite", req, response, Handler.REQUEST);
    verifyNoMoreInteractions(response);
    legacyRequestHandler.handle("/something_totally_different", req, response, Handler.REQUEST);
    verifyNoMoreInteractions(response);
  }
Exemple #2
0
 @Override
 public void run() {
   while (true) {
     for (SocketProcessor socket : queue) {
       if (socket.isRequestTextLoader) {
         socket.isRequestTextLoader = false;
         // TODO
         Handler handler = new FileHandler(new ErrorHandler());
         // @SuppressWarnings("unused")
         RequestBuilder rb = new RequestBuilder(socket.requestText);
         Request request = rb.getRequest();
         Response response = handler.handle(request);
         socket.sendResponse(response);
         queue.remove(socket);
         socket.close();
         // socket.sendTestResponse(socket.requestText);
         /*
          * try { socket.sendResponse( "<html><body><h1>Hello
          * World!!!</h1></body></html>");
          * socket.bufferWritter.flush(); System.out.print("Response
          * sent!"); } catch (IOException e) { // TODO Auto-generated
          * catch block e.printStackTrace(); }
          */
       }
     }
   }
 }
 @SuppressWarnings({"rawtypes", "unchecked"})
 @Override
 public void processCommand(final Object command) {
   assertValidated(command);
   final Handler commandHandler = manager.handlerFor(command.getClass());
   commandHandler.handle(command);
 }
 @BeforeMethod
 public void beforeMethod() {
   initMocks(this);
   when(handler.handle(notNull(RootContext.class), Matchers.notNull(Request.class)))
       .thenReturn(newResponsePromise(new Response(Status.OK)));
   client = new Client(handler);
 }
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   log.debug("doGet() called");
   String command = request.getParameter(COMMAND_PARAM);
   log.debug("command=" + command);
   try {
     if (command != null) {
       Handler handler = handlers.get(command);
       if (handler != null) {
         log.debug("handler=" + handler);
         handler.handle(request, response);
       } else {
         request.setAttribute("handlers", handlers);
         RequestDispatcher rd = getServletContext().getRequestDispatcher(UNKNOWN_COMMAND_URL);
         rd.forward(request, response);
       }
     } else {
       throw new Exception("no " + COMMAND_PARAM + " supplied");
     }
   } catch (Exception ex) {
     request.setAttribute(EXCEPTION_PARAM, ex);
     RequestDispatcher rd = getServletContext().getRequestDispatcher(UNKNOWN_COMMAND_URL);
     rd.forward(request, response);
   }
 }
 // Note: adding statements does not change the configuration of cached
 // values.
 public void addStatement(
     final Resource subj, final URI pred, final Value obj, final Resource... contexts)
     throws SailException {
   if (config.logWriteOperations) {
     queryHandler.handle(new AddStatementCall(id, subj, pred, obj, contexts));
   }
   baseSailConnection.addStatement(subj, pred, obj, contexts);
 }
 /**
  * This method should be called by the publisher when a new mqtt message has arrived.
  *
  * @param topic the message's topic
  * @param message the payload
  * @throws IOException
  */
 public void toArduino(String topic, String message) throws IOException {
   for (Handler handler : this.handlers) {
     if (handler.handle(topic, message)) {
       logger.info("Message {} {} handled by {}", topic, message, handler);
       return;
     }
   }
 }
Exemple #8
0
 private void dispatch() throws IOException {
   sel.select();
   for (Iterator i = sel.selectedKeys().iterator(); i.hasNext(); ) {
     SelectionKey sk = (SelectionKey) i.next();
     i.remove();
     Handler h = (Handler) sk.attachment();
     h.handle(sk);
   }
 }
 @SuppressWarnings({"unchecked", "rawtypes"})
 @Override
 public void processCommands(final Object[] commands) {
   // TODO: exception management, should we stop on failure, or ignore and go on ?
   for (final Object command : commands) {
     assertValidated(command);
     final Handler commandHandler = manager.handlerFor(command.getClass());
     commandHandler.handle(command);
   }
 }
 public void deployModuleFromZip(
     String zipFileName, JsonObject config, int instances, Handler<String> doneHandler) {
   final String modName = zipFileName.substring(0, zipFileName.length() - 4);
   ModuleIdentifier modID = new ModuleIdentifier("__vertx_tmp#" + modName + "#__vertx_tmp");
   if (unzipModule(modID, new ModuleZipInfo(false, zipFileName), false)) {
     deployModule(modID.toString(), config, instances, doneHandler);
   } else {
     doneHandler.handle(null);
   }
 }
Exemple #11
0
 public boolean map(K key, Annotation annotation) {
   final Collection<AnnotatedEntity> entities = map.get(key);
   if (!entities.isEmpty()) {
     boolean mapped = false;
     for (AnnotatedEntity e : entities) mapped = handler.handle(e, annotation) || mapped;
     return mapped;
   } else {
     unmapped.add(key);
   }
   return false;
 }
 public CloseableIteration<? extends Namespace, SailException> getNamespaces()
     throws SailException {
   if (config.logReadOperations) {
     queryHandler.handle(new GetNamespacesCall(id));
     return new RecorderIteration<Namespace, SailException>(
         (CloseableIteration<Namespace, SailException>) baseSailConnection.getNamespaces(),
         nextIterationId(),
         queryHandler);
   } else {
     return baseSailConnection.getNamespaces();
   }
 }
 public RecorderSailConnection(
     final Sail baseSail,
     final ReplayConfiguration config,
     final Handler<SailConnectionCall, SailException> queryHandler)
     throws SailException {
   this.queryHandler = queryHandler;
   this.config = config;
   if (config.logTransactions) {
     queryHandler.handle(new ConstructorCall(id));
   }
   this.baseSailConnection = baseSail.getConnection();
 }
Exemple #14
0
  private void running() {
    try {
      while (Thread.currentThread() == thread) {
        T t = pop();
        if (t != null) {
          handler.handle(t);
        }
        sleep(dequeueTime);
      }

    } catch (Exception ex) {
      Log.severe("Exception on rendering-thread", ex);
    }
  }
Exemple #15
0
  private void run(Handler handler) throws IOException {
    new SocketUtil()
        .listenIo(
            4000,
            (is, os) -> {
              Map<String, String> headers = readHeaders(is);

              os.write(
                  ("Status: 200 OK\r\n" //
                          + "Content-Type: text/html\r\n" //
                          + "\r\n")
                      .getBytes(Constants.charset));

              handler.handle(headers, os);
            });
  }
 public CloseableIteration<? extends Statement, SailException> getStatements(
     final Resource subj,
     final URI pred,
     final Value obj,
     final boolean includeInferred,
     final Resource... contexts)
     throws SailException {
   if (config.logReadOperations) {
     queryHandler.handle(new GetStatementsCall(id, subj, pred, obj, includeInferred, contexts));
     return new RecorderIteration<Statement, SailException>(
         (CloseableIteration<Statement, SailException>)
             baseSailConnection.getStatements(subj, pred, obj, includeInferred, contexts),
         nextIterationId(),
         queryHandler);
   } else {
     return baseSailConnection.getStatements(subj, pred, obj, includeInferred, contexts);
   }
 }
 public long size(final Resource... contexts) throws SailException {
   if (config.logReadOperations) {
     queryHandler.handle(new SizeCall(id, contexts));
   }
   return baseSailConnection.size(contexts);
 }
  private void doDeploy(
      final String depName,
      boolean autoRedeploy,
      boolean worker,
      boolean multiThreaded,
      String theMain,
      final ModuleIdentifier modID,
      final JsonObject config,
      final URL[] urls,
      int instances,
      final File modDir,
      final ModuleReference mr,
      final Handler<String> doneHandler) {
    checkWorkerContext();

    final String deploymentName = depName != null ? depName : genDepName();

    log.debug(
        "Deploying name : " + deploymentName + " main: " + theMain + " instances: " + instances);

    // How we determine which language implementation to use:
    // 1. Look for a prefix on the main, e.g. 'groovy:org.foo.myproject.MyGroovyMain' would force
    // the groovy
    //    language impl to be used
    // 2. If there is no prefix, then look at the extension, if any. If there is an extension
    // mapping for that
    //    extension, use that.
    // 3. No prefix and no extension mapping - use the default runtime

    LanguageImplInfo langImplInfo = null;

    final String main;
    // Look for a prefix
    int prefixMarker = theMain.indexOf(COLON);
    if (prefixMarker != -1) {
      String prefix = theMain.substring(0, prefixMarker);
      langImplInfo = languageImpls.get(prefix);
      if (langImplInfo == null) {
        throw new IllegalStateException("No language implementation known for prefix " + prefix);
      }
      main = theMain.substring(prefixMarker + 1);
    } else {
      main = theMain;
    }
    if (langImplInfo == null) {
      // No prefix - now look at the extension
      int extensionMarker = main.lastIndexOf('.');
      if (extensionMarker != -1) {
        String extension = main.substring(extensionMarker + 1);
        String langImplName = extensionMappings.get(extension);
        if (langImplName != null) {
          langImplInfo = languageImpls.get(langImplName);
          if (langImplInfo == null) {
            throw new IllegalStateException(
                "Extension mapping for "
                    + extension
                    + " specified as "
                    + langImplName
                    + ", but no language implementation known for that name");
          }
        }
      }
    }
    if (langImplInfo == null) {
      // Use the default
      langImplInfo = languageImpls.get(defaultLanguageImplName);
      if (langImplInfo == null) {
        throw new IllegalStateException(
            "Default language implementation is "
                + defaultLanguageImplName
                + " but no language implementation known for that name");
      }
    }

    // Include the language impl module as a parent of the classloader
    if (langImplInfo.moduleName != null) {
      if (!loadIncludedModules(modDir, mr, langImplInfo.moduleName)) {
        log.error("Failed to load module: " + langImplInfo.moduleName);
        doneHandler.handle(null);
        return;
      }
    }

    final VerticleFactory verticleFactory;

    final Container container = new DefaultContainer(this);

    try {
      // TODO not one verticle factory per module ref, but one per language per module ref
      verticleFactory = mr.getVerticleFactory(langImplInfo.factoryName, vertx, container);
    } catch (Exception e) {
      log.error("Failed to instantiate verticle factory", e);
      doneHandler.handle(null);
      return;
    }

    final int instCount = instances;

    class AggHandler {
      AtomicInteger count = new AtomicInteger(0);
      boolean failed;

      void done(boolean res) {
        if (!res) {
          failed = true;
        }
        if (count.incrementAndGet() == instCount) {
          String deploymentID = failed ? null : deploymentName;
          callDoneHandler(doneHandler, deploymentID);
        }
      }
    }

    final AggHandler aggHandler = new AggHandler();

    String parentDeploymentName = getDeploymentName();
    final Deployment deployment =
        new Deployment(
            deploymentName,
            main,
            modID,
            instances,
            config == null ? new JsonObject() : config.copy(),
            urls,
            modDir,
            parentDeploymentName,
            mr,
            autoRedeploy);
    mr.incRef();
    deployments.put(deploymentName, deployment);

    if (parentDeploymentName != null) {
      Deployment parentDeployment = deployments.get(parentDeploymentName);
      parentDeployment.childDeployments.add(deploymentName);
    }

    ClassLoader oldTCCL = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(mr.mcl);
    try {

      for (int i = 0; i < instances; i++) {

        // Launch the verticle instance

        Runnable runner =
            new Runnable() {
              public void run() {

                Verticle verticle = null;
                boolean error = true;

                try {
                  verticle = verticleFactory.createVerticle(main);
                  error = false;
                } catch (ClassNotFoundException e) {
                  log.error(
                      "Cannot find verticle "
                          + main
                          + " in "
                          + verticleFactory.getClass().getName(),
                      e);
                } catch (Throwable t) {
                  log.error(
                      "Failed to create verticle "
                          + main
                          + " in "
                          + verticleFactory.getClass().getName(),
                      t);
                }

                if (error) {
                  doUndeploy(
                      deploymentName,
                      new SimpleHandler() {
                        public void handle() {
                          aggHandler.done(false);
                        }
                      });
                  return;
                }
                verticle.setContainer(container);
                verticle.setVertx(vertx);

                try {
                  addVerticle(deployment, verticle, verticleFactory);
                  if (modDir != null) {
                    setPathAdjustment(modDir);
                  }
                  VoidResult vr = new VoidResult();
                  verticle.start(vr);
                  vr.setHandler(
                      new AsyncResultHandler<Void>() {
                        @Override
                        public void handle(AsyncResult<Void> ar) {
                          if (ar.succeeded()) {
                            aggHandler.done(true);
                          } else {
                            log.error(
                                "Failed to deploy verticle "
                                    + main
                                    + " in "
                                    + verticleFactory.getClass().getName(),
                                ar.exception);
                            aggHandler.done(false);
                          }
                        }
                      });
                } catch (Throwable t) {
                  t.printStackTrace();
                  vertx.reportException(t);
                  doUndeploy(
                      deploymentName,
                      new SimpleHandler() {
                        public void handle() {
                          aggHandler.done(false);
                        }
                      });
                }
              }
            };

        if (worker) {
          vertx.startInBackground(runner, multiThreaded);
        } else {
          vertx.startOnEventLoop(runner);
        }
      }
    } finally {
      Thread.currentThread().setContextClassLoader(oldTCCL);
    }
  }
 public String getNamespace(final String prefix) throws SailException {
   if (config.logReadOperations) {
     queryHandler.handle(new GetNamespaceCall(id, prefix));
   }
   return baseSailConnection.getNamespace(prefix);
 }
 public void clearNamespaces() throws SailException {
   if (config.logWriteOperations) {
     queryHandler.handle(new ClearNamespacesCall(id));
   }
   baseSailConnection.clearNamespaces();
 }
 public void commit() throws SailException {
   if (config.logTransactions) {
     queryHandler.handle(new CommitCall(id));
   }
   baseSailConnection.commit();
 }
 // Note: clearing statements does not change the configuration of cached
 // values.
 public void clear(final Resource... contexts) throws SailException {
   if (config.logWriteOperations) {
     queryHandler.handle(new ClearCall(id, contexts));
   }
   baseSailConnection.clear(contexts);
 }
 public void exit() {
   if (exitHandler != null) {
     exitHandler.handle(null);
   }
 }
 public void rollback() throws SailException {
   if (config.logTransactions) {
     queryHandler.handle(new RollbackCall(id));
   }
   baseSailConnection.rollback();
 }
 /** @see Server#handle(Socket) */
 @Override
 public void handle(Socket socket) throws Exception {
   if (handler != null) {
     handler.handle(socket);
   }
 }
 public void setNamespace(final String prefix, final String name) throws SailException {
   if (config.logWriteOperations) {
     queryHandler.handle(new SetNamespaceCall(id, prefix, name));
   }
   baseSailConnection.setNamespace(prefix, name);
 }
 public void removeNamespace(final String prefix) throws SailException {
   if (config.logWriteOperations) {
     queryHandler.handle(new RemoveNamespaceCall(id, prefix));
   }
   baseSailConnection.removeNamespace(prefix);
 }
 private void callDoneHandler(Handler<String> doneHandler, String deploymentID) {
   if (doneHandler != null) {
     doneHandler.handle(deploymentID);
   }
 }