Пример #1
0
 @Override
 protected void execute(
     final @NonNull KernelHttpRequest request, final @NonNull KernelHttpResponse response) {
   if (!request.isPrivileged()) throw new AdminAccessException();
   final String queryType = request.getParameter("queryType");
   final PrintWriter writer = response.getWriter();
   writer.print("[");
   try {
     final ValidatingKernel kernel = getKernel();
     final BeginTransactionResult btr = kernel.beginTransaction();
     final NodesTransaction txn = btr.getTxn();
     boolean commit = false;
     try {
       final Processor processor = processors.get(queryType);
       if (processor == null) writer.println("Query type '" + queryType + "' not found");
       else processor.process(txn, request, writer);
       commit = true;
     } finally {
       txn.finish(commit);
     }
     writer.print("]");
   } finally {
     writer.close();
   }
 }
Пример #2
0
  /** Builds a Router from an annotated Java Object */
  public static Router from(@NotNull final Router router, @NotNull Object... objs) {
    for (Object o : objs) {
      Processor.process(router, o);
    }

    return router;
  }
Пример #3
0
 /**
  * Processes the exchange by the processors
  *
  * @param processor the processor
  * @param exchange the exchange
  */
 protected static void doProcess(Processor processor, Exchange exchange) {
   try {
     processor.process(exchange);
   } catch (Exception e) {
     exchange.setException(e);
   }
 }
Пример #4
0
 protected void processChildren(Symbols symbols, Writer writer, String padding) {
   Processor p = children;
   while (p != null) {
     p.process(symbols, writer, line, padding);
     p = p.getNext();
   }
 }
Пример #5
0
 public void process(Processor<E> processor) {
   for (int i = 0; i < data.length; i++) {
     Object o = data[i];
     if (o != null) {
       processor.process((E) o);
     }
   }
 }
Пример #6
0
 public static boolean processFilesRecursively(
     @NotNull File root,
     @NotNull Processor<File> processor,
     @Nullable final Processor<File> directoryFilter) {
   final LinkedList<File> queue = new LinkedList<File>();
   queue.add(root);
   while (!queue.isEmpty()) {
     final File file = queue.removeFirst();
     if (!processor.process(file)) return false;
     if (file.isDirectory() && (directoryFilter == null || directoryFilter.process(file))) {
       final File[] children = file.listFiles();
       if (children != null) {
         ContainerUtil.addAll(queue, children);
       }
     }
   }
   return true;
 }
Пример #7
0
  String processContent(String content, Type type) throws ProcessingException {
    if (content != null && !content.isEmpty()) {
      for (Processor processor : type.getProcessors()) {
        content = processor.process(content);
      }
    }

    return content;
  }
Пример #8
0
 /**
  * I think in the basic framework this method is never called explicitely, because processing is
  * done implicitly by the render
  */
 @Override
 public void process(
     Processor processor, Parameters blockParameters, Parameters frameworkParameters)
     throws FrameworkException {
   HttpServletRequest request = frameworkParameters.get(Parameter.REQUEST);
   State state = State.getState(request);
   state.startBlock(frameworkParameters, null);
   setBlockParametersForProcess(state, blockParameters);
   processor.process(blockParameters);
 }
  public static void doSomethingWithUserInput(Processor proc) {
    // get user input from console
    String userInput = "test";

    // apply the processor
    Object result = proc.process(userInput);

    // display the result
    System.out.println(result);
  }
 @Override
 public PropertySource<?> load(String name, Resource resource, String profile) throws IOException {
   if (ClassUtils.isPresent("org.yaml.snakeyaml.Yaml", null)) {
     Processor processor = new Processor(resource, profile);
     Map<String, Object> source = processor.process();
     if (!source.isEmpty()) {
       return new MapPropertySource(name, source);
     }
   }
   return null;
 }
  public static boolean processFirstBytes(
      @NotNull InputStream stream, int length, @NotNull Processor<ByteSequence> processor)
      throws IOException {
    final byte[] bytes = BUFFER.get();
    assert bytes.length >= length
        : "Cannot process more than " + bytes.length + " in one call, requested:" + length;

    int n = stream.read(bytes, 0, length);
    if (n <= 0) return false;

    return processor.process(new ByteSequence(bytes, 0, n));
  }
Пример #12
0
 public void performNecessaryUpdates(Processor processor) {
   final IXtextDocument document = XtextDocumentUtil.get(textViewer);
   if (document != null && !paused) {
     final ReplaceRegion replaceRegionToBeProcessed = getAndResetReplaceRegion();
     if (replaceRegionToBeProcessed != null) {
       processor.process(new XtextReconcilerUnitOfWork(replaceRegionToBeProcessed, document));
     }
   }
   if (sessionStarted && !paused) {
     pause();
   }
 }
  public static boolean processFilesRecursively(
      @NotNull VirtualFile root, @NotNull Processor<VirtualFile> processor) {
    if (!processor.process(root)) return false;

    if (root.isDirectory()) {
      final LinkedList<VirtualFile[]> queue = new LinkedList<VirtualFile[]>();

      queue.add(root.getChildren());

      do {
        final VirtualFile[] files = queue.removeFirst();

        for (VirtualFile file : files) {
          if (!processor.process(file)) return false;
          if (file.isDirectory()) {
            queue.add(file.getChildren());
          }
        }
      } while (!queue.isEmpty());
    }

    return true;
  }
  public static void processFilesRecursively(
      @NotNull VirtualFile root,
      @NotNull Processor<VirtualFile> processor,
      @NotNull Convertor<VirtualFile, Boolean> directoryFilter) {
    if (!processor.process(root)) return;

    if (root.isDirectory() && directoryFilter.convert(root)) {
      final LinkedList<VirtualFile[]> queue = new LinkedList<VirtualFile[]>();

      queue.add(root.getChildren());

      do {
        final VirtualFile[] files = queue.removeFirst();

        for (VirtualFile file : files) {
          if (!processor.process(file)) return;
          if (file.isDirectory() && directoryFilter.convert(file)) {
            queue.add(file.getChildren());
          }
        }
      } while (!queue.isEmpty());
    }
  }
  public static boolean visitFiles(@NotNull File root, @NotNull Processor<File> processor) {
    if (!processor.process(root)) {
      return false;
    }

    File[] children = root.listFiles();
    if (children != null) {
      for (File child : children) {
        if (!visitFiles(child, processor)) {
          return false;
        }
      }
    }

    return true;
  }
  @Test
  public void noFailureDoesNotTriggerEarlyExit() throws ProcessingException {
    @SuppressWarnings("unchecked")
    final Processor<MessageProvider, MessageProvider> p1 = mock(Processor.class);
    @SuppressWarnings("unchecked")
    final Processor<MessageProvider, MessageProvider> p2 = mock(Processor.class);

    final Processor<MessageProvider, MessageProvider> processor =
        ProcessorChain.startWith(p1).failOnError().chainWith(p2).getProcessor();

    final MessageProvider input = mock(MessageProvider.class);
    final ProcessingReport report = new DummyReport(LogLevel.DEBUG);

    processor.process(report, input);

    verify(p1).process(same(report), any(MessageProvider.class));
    verify(p2).process(same(report), any(MessageProvider.class));
  }
Пример #17
0
 private boolean callProcessor(
     Processor proc, Set<? extends TypeElement> tes, RoundEnvironment renv) {
   try {
     return proc.process(tes, renv);
   } catch (BadClassFile ex) {
     log.error("proc.cant.access.1", ex.sym, ex.getDetailValue());
     return false;
   } catch (CompletionFailure ex) {
     StringWriter out = new StringWriter();
     ex.printStackTrace(new PrintWriter(out));
     log.error("proc.cant.access", ex.sym, ex.getDetailValue(), out.toString());
     return false;
   } catch (ClientCodeException e) {
     throw e;
   } catch (Throwable t) {
     throw new AnnotationProcessingError(t);
   }
 }
Пример #18
0
  public void process(int depth, Node node) {
    if (depth == 0) {
      references.traverse(node);
    }

    Processor processor = processors().get(node.getClass());
    if (processor == null) {
      log.warn("No processor defined for type {}", node.getClass());
      processor = processorDefault;
    }

    treeNavigation.push(node);

    dumpProcessor(depth, node, processor);
    processor.process(depth, node, this);

    treeNavigation.pop();
  }
  protected boolean finishCommitInWriteAction(
      @NotNull final Document document,
      @NotNull final List<Processor<Document>> finishProcessors,
      final boolean synchronously) {
    if (myProject.isDisposed()) return false;
    assert !(document instanceof DocumentWindow);
    myIsCommitInProgress = true;
    boolean success = true;
    try {
      final FileViewProvider viewProvider = getCachedViewProvider(document);
      if (viewProvider != null) {
        for (Processor<Document> finishRunnable : finishProcessors) {
          success = finishRunnable.process(document);
          if (synchronously) {
            assert success : finishRunnable + " in " + finishProcessors;
          }
          if (!success) {
            break;
          }
        }
        if (success) {
          myLastCommittedTexts.remove(document);
          viewProvider.contentsSynchronized();
        }
      } else {
        handleCommitWithoutPsi(document);
      }
    } finally {
      myDocumentCommitProcessor.log(
          "in PDI.finishDoc: ", null, synchronously, success, myUncommittedDocuments);
      if (success) {
        myUncommittedDocuments.remove(document);
        myDocumentCommitProcessor.log(
            "in PDI.finishDoc: removed doc", null, synchronously, success, myUncommittedDocuments);
      }
      myIsCommitInProgress = false;
      myDocumentCommitProcessor.log(
          "in PDI.finishDoc: exit", null, synchronously, success, myUncommittedDocuments);
    }

    return success;
  }
Пример #20
0
  private static <T> void processDependencyMap(
      T selected,
      Stack<T> callStack,
      Map<T, Set<T>> dependencies,
      Set<T> processed,
      Processor<T> processor,
      SubMonitor subMonitor)
      throws CoreException, CircularDependencyException {
    if (processed.contains(selected)) return;

    // Check for cycles
    int stackIndex = callStack.indexOf(selected);
    if (stackIndex != -1) {
      List<T> subList = callStack.subList(stackIndex, callStack.size());
      List<T> cycle = new ArrayList<T>(subList.size() + 1);
      cycle.addAll(subList);
      cycle.add(selected);

      throw new CircularDependencyException(cycle);
    }
    try {
      callStack.push(selected);

      Set<T> selectedDeps = dependencies.get(selected);

      // Process dependencies first
      if (selectedDeps != null) {
        for (T dep : selectedDeps) {
          processDependencyMap(dep, callStack, dependencies, processed, processor, subMonitor);
        }
      }

      // Process the selection
      processor.process(selected, subMonitor.newChild(1));
      processed.add(selected);
    } finally {
      callStack.pop();
    }
  }
  @Test
  public void failingOnErrorExitsEarly() throws ProcessingException {
    @SuppressWarnings("unchecked")
    final Processor<MessageProvider, MessageProvider> p1 = mock(Processor.class);
    @SuppressWarnings("unchecked")
    final Processor<MessageProvider, MessageProvider> p2 = mock(Processor.class);

    final Processor<MessageProvider, MessageProvider> processor =
        ProcessorChain.startWith(p1).failOnError().chainWith(p2).getProcessor();

    final MessageProvider input = mock(MessageProvider.class);
    final ProcessingReport report = new DummyReport(LogLevel.ERROR);

    try {
      processor.process(report, input);
      fail("No exception thrown!!");
    } catch (ProcessingException e) {
      assertMessage(e.getProcessingMessage())
          .hasMessage(BUNDLE.getMessage("processing.chainStopped"));
    }

    verify(p1).process(same(report), any(MessageProvider.class));
    verify(p2, never()).process(any(ProcessingReport.class), any(MessageProvider.class));
  }
Пример #22
0
    @SuppressWarnings("deprecation") // Old HTTP upgrade method has been deprecated
    public SocketState process(SocketWrapper<S> wrapper, SocketStatus status) {
      if (wrapper == null) {
        // Nothing to do. Socket has been closed.
        return SocketState.CLOSED;
      }

      S socket = wrapper.getSocket();
      if (socket == null) {
        // Nothing to do. Socket has been closed.
        return SocketState.CLOSED;
      }

      Processor<S> processor = connections.get(socket);
      if (status == SocketStatus.DISCONNECT && processor == null) {
        // Nothing to do. Endpoint requested a close and there is no
        // longer a processor associated with this socket.
        return SocketState.CLOSED;
      }

      wrapper.setAsync(false);
      ContainerThreadMarker.markAsContainerThread();

      try {
        if (processor == null) {
          processor = recycledProcessors.poll();
        }
        if (processor == null) {
          processor = createProcessor();
        }

        initSsl(wrapper, processor);

        SocketState state = SocketState.CLOSED;
        do {
          if (status == SocketStatus.CLOSE_NOW) {
            processor.errorDispatch();
            state = SocketState.CLOSED;
          } else if (status == SocketStatus.DISCONNECT && !processor.isComet()) {
            // Do nothing here, just wait for it to get recycled
            // Don't do this for Comet we need to generate an end
            // event (see BZ 54022)
          } else if (processor.isAsync()) {
            state = processor.asyncDispatch(status);
          } else if (state == SocketState.ASYNC_END) {
            state = processor.asyncDispatch(status);
            // release() won't get called so in case this request
            // takes a long time to process remove the socket from
            // the waiting requests now else the async timeout will
            // fire
            getProtocol().endpoint.removeWaitingRequest(wrapper);
            if (state == SocketState.OPEN) {
              // There may be pipe-lined data to read. If the data
              // isn't processed now, execution will exit this
              // loop and call release() which will recycle the
              // processor (and input buffer) deleting any
              // pipe-lined data. To avoid this, process it now.
              state = processor.process(wrapper);
            }
          } else if (processor.isComet()) {
            state = processor.event(status);
          } else if (processor.getUpgradeInbound() != null) {
            state = processor.upgradeDispatch();
          } else if (processor.isUpgrade()) {
            state = processor.upgradeDispatch(status);
          } else {
            state = processor.process(wrapper);
          }

          if (state != SocketState.CLOSED && processor.isAsync()) {
            state = processor.asyncPostProcess();
          }

          if (state == SocketState.UPGRADING) {
            // Get the HTTP upgrade handler
            HttpUpgradeHandler httpUpgradeHandler = processor.getHttpUpgradeHandler();
            // Release the Http11 processor to be re-used
            release(wrapper, processor, false, false);
            // Create the upgrade processor
            processor = createUpgradeProcessor(wrapper, httpUpgradeHandler);
            // Mark the connection as upgraded
            wrapper.setUpgraded(true);
            // Associate with the processor with the connection
            connections.put(socket, processor);
            // Initialise the upgrade handler (which may trigger
            // some IO using the new protocol which is why the lines
            // above are necessary)
            // This cast should be safe. If it fails the error
            // handling for the surrounding try/catch will deal with
            // it.
            httpUpgradeHandler.init((WebConnection) processor);
          } else if (state == SocketState.UPGRADING_TOMCAT) {
            // Get the UpgradeInbound handler
            org.apache.coyote.http11.upgrade.UpgradeInbound inbound = processor.getUpgradeInbound();
            // Release the Http11 processor to be re-used
            release(wrapper, processor, false, false);
            // Create the light-weight upgrade processor
            processor = createUpgradeProcessor(wrapper, inbound);
            inbound.onUpgradeComplete();
          }
          if (getLog().isDebugEnabled()) {
            getLog()
                .debug(
                    "Socket: ["
                        + wrapper
                        + "], Status in: ["
                        + status
                        + "], State out: ["
                        + state
                        + "]");
          }
        } while (state == SocketState.ASYNC_END
            || state == SocketState.UPGRADING
            || state == SocketState.UPGRADING_TOMCAT);

        if (state == SocketState.LONG) {
          // In the middle of processing a request/response. Keep the
          // socket associated with the processor. Exact requirements
          // depend on type of long poll
          connections.put(socket, processor);
          longPoll(wrapper, processor);
        } else if (state == SocketState.OPEN) {
          // In keep-alive but between requests. OK to recycle
          // processor. Continue to poll for the next request.
          connections.remove(socket);
          release(wrapper, processor, false, true);
        } else if (state == SocketState.SENDFILE) {
          // Sendfile in progress. If it fails, the socket will be
          // closed. If it works, the socket will be re-added to the
          // poller
          connections.remove(socket);
          release(wrapper, processor, false, false);
        } else if (state == SocketState.UPGRADED) {
          // Need to keep the connection associated with the processor
          connections.put(socket, processor);
          // Don't add sockets back to the poller if this was a
          // non-blocking write otherwise the poller may trigger
          // multiple read events which may lead to thread starvation
          // in the connector. The write() method will add this socket
          // to the poller if necessary.
          if (status != SocketStatus.OPEN_WRITE) {
            longPoll(wrapper, processor);
          }
        } else {
          // Connection closed. OK to recycle the processor. Upgrade
          // processors are not recycled.
          connections.remove(socket);
          if (processor.isUpgrade()) {
            processor.getHttpUpgradeHandler().destroy();
          } else if (processor instanceof org.apache.coyote.http11.upgrade.UpgradeProcessor) {
            // NO-OP
          } else {
            release(wrapper, processor, true, false);
          }
        }
        return state;
      } catch (java.net.SocketException e) {
        // SocketExceptions are normal
        getLog().debug(sm.getString("abstractConnectionHandler.socketexception.debug"), e);
      } catch (java.io.IOException e) {
        // IOExceptions are normal
        getLog().debug(sm.getString("abstractConnectionHandler.ioexception.debug"), e);
      }
      // Future developers: if you discover any other
      // rare-but-nonfatal exceptions, catch them here, and log as
      // above.
      catch (Throwable e) {
        ExceptionUtils.handleThrowable(e);
        // any other exception or error is odd. Here we log it
        // with "ERROR" level, so it will show up even on
        // less-than-verbose logs.
        getLog().error(sm.getString("abstractConnectionHandler.error"), e);
      }
      // Make sure socket/processor is removed from the list of current
      // connections
      connections.remove(socket);
      // Don't try to add upgrade processors back into the pool
      if (!(processor instanceof org.apache.coyote.http11.upgrade.UpgradeProcessor)
          && !processor.isUpgrade()) {
        release(wrapper, processor, true, false);
      }
      return SocketState.CLOSED;
    }
Пример #23
0
 @Override
 default void applyEffect(State state) {
   Processor.process(state, getEffectsXPR());
 }
Пример #24
0
 @Override
 default List<BoolExpr> getConditions(State state) {
   return Processor.process(state.copy(), getConditionsXPR());
 }
Пример #25
0
 public static void process(Processor p, Object s) {
   System.out.println("Using Processor " + p.name());
   System.out.println(p.process(s));
 }
Пример #26
0
 @Override
 default void instantiateArguments(State state) {
   Processor.process(state, getArgumentsXPR());
 }
Пример #27
0
  /**
   * Basic Framework implicitely also processes, i'm not sure if we should require any framework to
   * do that (perhaps we could say, that the render method must process, if that is necessary, and
   * not yet done).
   */
  @Override
  public void render(
      Renderer renderer,
      Parameters blockParameters,
      Parameters frameworkParameters,
      Writer w,
      WindowState windowState)
      throws FrameworkException {
    ServletRequest request = frameworkParameters.get(Parameter.REQUEST);
    if (request == null) {
      throw new IllegalArgumentException("No request object given");
    }

    State state = State.getState(request);
    if (state
        .isRendering()) { // mm:component used during rending of a component, that's fine, but use a
                          // new State.
      state = new State(request);
      log.debug("Alreadying rendering, taking a new state for sub-block-rendering: " + state);
    }

    log.debug("Rendering " + renderer.getBlock() + " " + renderer);
    Object prevHints = request.getAttribute(RenderHints.KEY);
    try {

      request.setAttribute(COMPONENT_CLASS_KEY, getComponentClass());
      request.setAttribute(COMPONENT_CURRENTUSER_KEY, getUserNode(frameworkParameters));

      Renderer actualRenderer = state.startBlock(frameworkParameters, renderer);
      if (!actualRenderer.equals(renderer)) {
        Parameters newBlockParameters = actualRenderer.getBlock().createParameters();
        newBlockParameters.setAllIfDefined(blockParameters);
        blockParameters = newBlockParameters;
      }
      state.setAction(request.getParameter(ACTION.getName()));
      if (state.needsProcess()) {
        log.service("Performing action on " + actualRenderer.getBlock());
        Processor processor = actualRenderer.getBlock().getProcessor();
        state.process(processor);
        log.service("Processing " + actualRenderer.getBlock() + " " + processor);
        setBlockParametersForProcess(state, blockParameters);
        processor.process(blockParameters);
        state.endProcess();
      }

      state.render(actualRenderer);

      setBlockParametersForRender(state, blockParameters);

      RenderHints hints =
          new RenderHints(
              actualRenderer,
              windowState,
              state.getId(),
              getComponentClass(),
              RenderHints.Mode.NORMAL);
      request.setAttribute(RenderHints.KEY, hints);
      actualRenderer.render(blockParameters, w, hints);
      request.setAttribute("org.mmbase.framework.hints", hints);
    } catch (FrameworkException fe) {
      log.debug(fe);
      URI uri = renderer.getUri();
      Renderer error =
          new ErrorRenderer(
              renderer.getType(),
              renderer.getBlock(),
              (uri != null) ? uri.toString() : null,
              500,
              fe);
      RenderHints hints =
          new RenderHints(
              error, windowState, state.getId(), getComponentClass(), RenderHints.Mode.NORMAL);
      error.render(blockParameters, w, hints);
    } finally {
      request.setAttribute(RenderHints.KEY, prevHints);
      state.endBlock();
    }
  }