Beispiel #1
0
  /**
   * Parses content of an <code>InputSource</code> to create an XML <code>Element</code> object.
   *
   * @param source the input source that is supposed to contain XML to be parsed, not <code>null
   *     </code>.
   * @return the parsed result, not <code>null</code>.
   * @throws IOException if there is an I/O error.
   * @throws ParseException if the content is not considered to be valid XML.
   */
  private Element parse(InputSource source) throws IOException, ParseException {

    // TODO: Consider using an XMLReader instead of a SAXParser

    // Initialize our SAX event handler
    Handler handler = new Handler();

    try {
      // Let SAX parse the XML, using our handler
      SAXParserProvider.get().parse(source, handler);

    } catch (SAXException exception) {

      // TODO: Log: Parsing failed
      String exMessage = exception.getMessage();

      // Construct complete message
      String message = "Failed to parse XML";
      if (TextUtils.isEmpty(exMessage)) {
        message += '.';
      } else {
        message += ": " + exMessage;
      }

      // Throw exception with message, and register cause exception
      throw new ParseException(message, exception, exMessage);
    }

    Element element = handler.getElement();

    return element;
  }
 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);
   }
 }
 static Object load(InputStream is, String name, Handler handler) {
   try {
     try {
       XMLReader reader = XMLUtil.createXMLReader();
       reader.setEntityResolver(handler);
       reader.setContentHandler(handler);
       reader.parse(new InputSource(is));
       return handler.getResult();
     } finally {
       is.close();
     }
   } catch (SAXException ex) {
     if (System.getProperty("org.netbeans.optionsDialog") != null) {
       System.out.println("File: " + name);
       ex.printStackTrace();
     }
     return handler.getResult();
   } catch (IOException ex) {
     if (System.getProperty("org.netbeans.optionsDialog") != null) {
       System.out.println("File: " + name);
       ex.printStackTrace();
     }
     return handler.getResult();
   } catch (Exception ex) {
     if (System.getProperty("org.netbeans.optionsDialog") != null) {
       System.out.println("File: " + name);
       ex.printStackTrace();
     }
     return handler.getResult();
   }
 }
  private boolean handleFault(int i) {
    Handler handler = _chain.get(i);

    boolean success = false;
    _invoked[i] = true;

    try {
      if (handler instanceof LogicalHandler) {
        _logicalContext.getMessage().setPayload(_source);
        success = handler.handleFault(_logicalContext);
        _source = _logicalContext.getMessage().getPayload();
      } else if (handler instanceof SOAPHandler) {
        try {
          _soapContext.setMessage(_source);
          success = handler.handleFault(_soapContext);
          _source = _soapContext.getMessage().getSOAPPart().getContent();
        } catch (SOAPException e) {
          throw new WebServiceException(e);
        }
      } else {
        throw new WebServiceException(
            L.l("Unsupported Handler type: {0}", handler.getClass().getName()));
      }

      _protocolException = null;
    } catch (ProtocolException e) {
      _protocolException = e;
      serializeProtocolException();
    } catch (RuntimeException e) {
      _runtimeException = e;
      serializeRuntimeException();
    }

    return success;
  }
Beispiel #5
0
 @SuppressWarnings({"rawtypes", "unchecked"})
 @Override
 public void processCommand(final Object command) {
   assertValidated(command);
   final Handler commandHandler = manager.handlerFor(command.getClass());
   commandHandler.handle(command);
 }
Beispiel #6
0
  @SuppressWarnings("unused") // called through reflection by RequestServer
  /** Return a list of all REST API Routes and a Markdown Table of Contents. */
  public MetadataV3 listRoutes(int version, MetadataV3 docs) {
    MarkdownBuilder builder = new MarkdownBuilder();
    builder.comment("Preview with http://jbt.github.io/markdown-editor");
    builder.heading1("REST API Routes Table of Contents");
    builder.hline();

    builder.tableHeader("HTTP method", "URI pattern", "Input schema", "Output schema", "Summary");

    docs.routes = new RouteBase[RequestServer.numRoutes()];
    int i = 0;
    for (Route route : RequestServer.routes()) {
      docs.routes[i++] = (RouteBase) Schema.schema(version, Route.class).fillFromImpl(route);

      builder.tableRow(
          route._http_method,
          route._url_pattern.toString().replace("(?<", "{").replace(">.*)", "}"),
          Handler.getHandlerMethodInputSchema(route._handler_method).getSimpleName(),
          Handler.getHandlerMethodOutputSchema(route._handler_method).getSimpleName(),
          route._summary);
    }

    docs.markdown = builder.toString();
    return docs;
  }
Beispiel #7
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(); }
          */
       }
     }
   }
 }
 /**
  * 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;
     }
   }
 }
Beispiel #9
0
 @Override
 public void mouseReleased(MouseEvent e) {
   menu.clearPressed();
   if (menu.getState() == State.MENU) { // menu navigation
     if (new Rectangle(820, 100, 350, 40).contains(e.getPoint())) {
       menu.setReleased(1);
     } else if (new Rectangle(820, 540, 350, 40).contains(e.getPoint())) {
       menu.setReleased(0);
     } else if (new Rectangle(950, 600, 200, 75).contains(e.getPoint())) {
       menu.startGame();
     } else if (new Rectangle(700, 590, 125, 94).contains(e.getPoint())) {
       menu.setReleased(8);
       if (!menu.getMods()[0]) {
         menu.setHD(true);
       } else {
         menu.setHD(false);
       }
     } else if (new Rectangle(825, 590, 125, 94).contains(e.getPoint())) {
       menu.setReleased(9);
       if (!menu.getMods()[1]) {
         menu.setFL(true);
       } else {
         menu.setFL(false);
       }
     } else {
       for (int i = 0; i < menu.getSong().getNumOfDifficulties(); i++) {
         if (new Rectangle(300, 200 + 100 * i, 125, 94).contains(e.getPoint())) {
           menu.setDiff(i);
           break;
         }
       }
     }
   } else if (menu.getState() == State.PAUSE) { // pause navigation
     if (new Rectangle(550, 200, 125, 94).contains(e.getPoint())) {
       try {
         menu.getSong().playSong();
       } catch (Exception exception) {
       }
       menu.setState(State.GAME);
     } else if (new Rectangle(550, 300, 125, 94).contains(e.getPoint())) {
       menu.setState(State.ENDSCREEN);
     } else if (new Rectangle(550, 400, 125, 94).contains(e.getPoint())) {
       handler.unpause();
       handler.unpause();
       handler.reset();
       menu.setState(State.MENU);
       menu.reset();
     }
   } else if (menu.getState() == State.ENDSCREEN) { // end screen navigation
     if (new Rectangle(1000, 550, 200, 100).contains(e.getPoint())) {
       handler.unpause();
       handler.unpause();
       handler.reset();
       menu.setState(State.MENU);
       menu.reset();
     }
   }
 }
Beispiel #10
0
 public void handle(final Callback[] callbacks)
     throws IOException, UnsupportedCallbackException {
   for (Callback callback : callbacks) {
     Handler handler = DigestAuthCallback.this.handlers.get(callback.getClass());
     if (handler != null) {
       handler.handler(this.context, callback);
     }
   }
 }
Beispiel #11
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);
   }
 }
Beispiel #12
0
 @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);
   }
 }
  /* (non-Javadoc)
   * @see de.miethxml.kabeja.parser.Handler#releaseDXFDocument()
   */
  public void releaseDXFDocument() {
    this.doc = null;

    Iterator i = handlers.values().iterator();

    while (i.hasNext()) {
      Handler handler = (Handler) i.next();
      handler.releaseDXFDocument();
    }
  }
Beispiel #14
0
 public void forEach(Handler handler) {
   for (Operation operation : operations) {
     if (operation instanceof ValueOperation) {
       ValueOperation valueOperation = (ValueOperation) operation;
       handler.put(valueOperation.getKey(), valueOperation.getValue());
     } else {
       handler.delete(operation.getKey());
     }
   }
 }
 @Override
 public void buildGraph(Graph graph) {
   Handler handler = new Handler();
   for (OpenStreetMapProvider provider : _providers) {
     _log.debug("gathering osm from provider: " + provider);
     provider.readOSM(handler);
   }
   _log.debug("building osm street graph");
   handler.buildGraph(graph);
 }
  public static void main(final String[] args) {
    final String eventFile = args[0];
    final String outFile = args[1];

    final Handler handler = new Handler(outFile);
    final EventsManager events = EventsUtils.createEventsManager();
    events.addHandler(handler);
    new EventsReaderXMLv1(events).parse(eventFile);
    handler.close();
  }
Beispiel #17
0
 public void start() throws Exception {
   synchronized (handlers) {
     started.set(true);
     for (Stage stage : stagesOrdered()) {
       currStage = stage;
       for (Handler handler : handlers.get(stage)) {
         handler.start();
       }
     }
   }
 }
Beispiel #18
0
  private void init() {
    WIDTH = getWidth();
    HEIGHT = getHeight();

    handler = new Handler();

    handler.addObject(new Player(100, 100, handler, ObjectId.Player));

    handler.createLevel();

    this.addKeyListener(new KeyInput(handler));
  }
  public String toString() {
    StringBuilder sb = new StringBuilder("HandlerChainInvoker[\n");

    for (Handler handler : _chain) {
      sb.append(handler.toString());
      sb.append('\n');
    }

    sb.append(']');

    return sb.toString();
  }
Beispiel #20
0
 public void closeClient(String user) {
   Handler client = (Handler) handlers.get(user);
   client.sendStop();
   try {
     client.close();
   } catch (IOException ex) {
     Logger.getLogger(EchoServer.class.getName()).log(Level.SEVERE, null, ex);
   }
   handlers.remove(user);
   sendOnlineUsersMsg();
   Logger.getLogger(EchoServer.class.getName())
       .log(Level.INFO, "Closed a client", new Object[] {client.getUsername()});
 }
  private boolean matchOneChar(char ch) {
    if (ch == CharIndexed.OUT_OF_BOUNDS) return false;

    boolean retval = handler.includes(ch);
    if (insens) {
      retval =
          retval
              || handler.includes(toUpperCase(ch, unicodeAware))
              || handler.includes(toLowerCase(ch, unicodeAware));
    }

    if (negate) retval = !retval;
    return retval;
  }
Beispiel #22
0
 @Override
 public void execute(Handler handler) throws ParseException {
   Object o2 = handler.pop();
   Object o1 = handler.pop();
   if (o1 instanceof Number && o2 instanceof Number) {
     handler.push(((Number) o1).doubleValue() <= ((Number) o2).doubleValue());
     return;
   }
   if (o1 instanceof String && o2 instanceof String) {
     handler.push(((String) o1).compareTo((String) o2) <= 0);
     return;
   }
   throw new ParseException("operandes to not comparable");
 }
  @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);
  }
Beispiel #24
0
 public void sendMessage(String receivers, String msg, String sender) {
   String messageString = "MESSAGE#" + sender + "#" + msg;
   String[] receiversarray = receivers.split(",");
   if (receiversarray.length == 1) {
     String receiver = receiversarray[0];
     if (receiver.equals("*")) {
       for (Handler handler : handlers.values()) {
         handler.sendMessage(messageString);
         Logger.getLogger(EchoServer.class.getName())
             .log(
                 Level.INFO,
                 handler.getUsername() + " Sent a message to all: " + messageString,
                 new Object[] {handler.getUsername()});
       }
     } else {
       Handler handler = (Handler) handlers.get(receiver);
       handler.sendMessage(messageString);
       Logger.getLogger(EchoServer.class.getName())
           .log(
               Level.INFO,
               handler.getUsername() + " Sent a message: " + messageString + " to: " + receiver,
               new Object[] {handler.getUsername()});
     }
   }
 }
Beispiel #25
0
 public void sendOnlineUsersMsg() {
   StringBuilder onlineUsers = new StringBuilder();
   boolean first = true;
   for (String user : handlers.keySet()) {
     if (!first) {
       onlineUsers.append(",");
     }
     onlineUsers.append(user);
     first = false;
   }
   for (Handler client : handlers.values()) {
     client.sendOnline(onlineUsers.toString());
   }
 }
 public static void parseHandlers(
     XMLExtendedStreamReader reader, PathAddress parentAddress, List<ModelNode> list)
     throws XMLStreamException {
   Map<String, Handler> handlerMap = HandlerFactory.getHandlerMap();
   while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
     String tagName = reader.getLocalName();
     Handler handler = handlerMap.get(tagName);
     if (handler != null) {
       handler.parse(reader, parentAddress, list);
     } else {
       throw UndertowMessages.MESSAGES.unknownHandler(tagName, reader.getLocation());
     }
   }
 }
Beispiel #27
0
 private List<String> determineMethodsAllowed(HttpManager manager, Resource res) {
   List<String> list = new ArrayList<String>();
   for (Handler f : manager.getAllHandlers()) {
     if (f.isCompatible(res)) {
       for (String m : f.getMethods()) {
         Method httpMethod = Method.valueOf(m);
         if (!handlerHelper.isNotCompatible(res, httpMethod)) {
           list.add(m);
         }
       }
     }
   }
   return list;
 }
 public Handler parserViewCommand(Handler handler, String taskInfo, Logger logger)
     throws Exception {
   logger.log(Level.INFO, "start to parse the search command");
   switch (taskInfo.toLowerCase()) {
     case STRING_EVENT:
       handler.setKeyWord(STRING_EVENT);
       break;
     case STRING_DEADLINE:
       handler.setKeyWord(STRING_DEADLINE);
       break;
     case STRING_EMPTY:
       handler.setKeyWord(STRING_EMPTY);
       break;
     case STRING_TASKS:
       handler.setKeyWord(STRING_TASKS);
       break;
     case STRING_OVERDUE:
       handler.setKeyWord(STRING_OVERDUE);
       break;
     case STRING_DONE:
       handler.setKeyWord(STRING_DONE);
       break;
     default:
       logger.log(Level.WARNING, "the entered command is invalid");
       handler.setHasError(true);
       handler.setFeedBack(COMMAND_INVALID);
   }
   return handler;
 }
  public void execute(Handler handler) {
    int operand1;
    int operand2;
    int result;

    operand2 = ((Integer) handler.pop()).intValue();
    operand1 = ((Integer) handler.pop()).intValue();
    if (operand2 > 0) {
      result = operand1 << operand2;
    } else {
      result = operand1 >> -operand2;
    }
    handler.push(new Integer(result));
  }
Beispiel #30
0
    private void readSettings(Handler handler, int length, byte flags, int streamId)
        throws IOException {
      if (streamId != 0) throw ioException("TYPE_SETTINGS streamId != 0");
      if ((flags & FLAG_ACK) != 0) {
        if (length != 0) throw ioException("FRAME_SIZE_ERROR ack frame should be empty!");
        handler.ackSettings();
        return;
      }

      if (length % 6 != 0) throw ioException("TYPE_SETTINGS length %% 6 != 0: %s", length);
      Settings settings = new Settings();
      for (int i = 0; i < length; i += 6) {
        short id = source.readShort();
        int value = source.readInt();

        switch (id) {
          case 1: // SETTINGS_HEADER_TABLE_SIZE
            break;
          case 2: // SETTINGS_ENABLE_PUSH
            if (value != 0 && value != 1) {
              throw ioException("PROTOCOL_ERROR SETTINGS_ENABLE_PUSH != 0 or 1");
            }
            break;
          case 3: // SETTINGS_MAX_CONCURRENT_STREAMS
            id = 4; // Renumbered in draft 10.
            break;
          case 4: // SETTINGS_INITIAL_WINDOW_SIZE
            id = 7; // Renumbered in draft 10.
            if (value < 0) {
              throw ioException("PROTOCOL_ERROR SETTINGS_INITIAL_WINDOW_SIZE > 2^31 - 1");
            }
            break;
          case 5: // SETTINGS_MAX_FRAME_SIZE
            if (value < INITIAL_MAX_FRAME_SIZE || value > 16777215) {
              throw ioException("PROTOCOL_ERROR SETTINGS_MAX_FRAME_SIZE: %s", value);
            }
            break;
          case 6: // SETTINGS_MAX_HEADER_LIST_SIZE
            break; // Advisory only, so ignored.
          default:
            throw ioException("PROTOCOL_ERROR invalid settings id: %s", id);
        }
        settings.set(id, 0, value);
      }
      handler.settings(false, settings);
      if (settings.getHeaderTableSize() >= 0) {
        hpackReader.headerTableSizeSetting(settings.getHeaderTableSize());
      }
    }