Пример #1
0
  @Override
  public boolean startResponse(HttpVersion version, int status, String reason) {
    if (updateState(State.IDLE, State.RECEIVE)) {
      HttpExchange exchange = connection.getExchange();
      // The exchange may be null if it failed concurrently
      if (exchange != null) {
        HttpConversation conversation = exchange.getConversation();
        HttpResponse response = exchange.getResponse();

        String method = exchange.getRequest().method();
        parser.setHeadResponse(HttpMethod.HEAD.is(method) || HttpMethod.CONNECT.is(method));
        response.version(version).status(status).reason(reason);

        // Probe the protocol handlers
        HttpClient client = connection.getHttpClient();
        ProtocolHandler protocolHandler =
            client.findProtocolHandler(exchange.getRequest(), response);
        Response.Listener handlerListener = null;
        if (protocolHandler != null) {
          handlerListener = protocolHandler.getResponseListener();
          LOG.debug("Found protocol handler {}", protocolHandler);
        }
        exchange.getConversation().updateResponseListeners(handlerListener);

        LOG.debug("Receiving {}", response);
        ResponseNotifier notifier = connection.getDestination().getResponseNotifier();
        notifier.notifyBegin(conversation.getResponseListeners(), response);
      }
    }
    return false;
  }
Пример #2
0
  private ProtocolHandler newProtocolHandler() throws ConfigurationException {
    QFactory f = getFactory();
    Element e = getPersist().getChild("protocol-handler");
    if (e == null) {
      throw new ConfigurationException("protocol-handler element is required.");
    }

    String handlerName = e.getAttributeValue("class");
    String packagerName = e.getAttributeValue("packager");

    ProtocolHandler handler = (ProtocolHandler) f.newInstance(handlerName);
    f.setLogger(handler, e);
    f.setConfiguration(handler, e);

    ISOPackager packager = (ISOPackager) f.newInstance(packagerName);
    handler.setPackager(packager);
    f.setConfiguration(packager, e);

    QFactory.invoke(handler, "setHeader", e.getAttributeValue("header"));
    return handler;
  }
  @Override
  public UpgradeInfo upgrade(final UpgradeRequest request, final UpgradeResponse response) {

    try {
      final TyrusEndpoint endpoint = getEndpoint(request);
      if (endpoint != null) {
        final ProtocolHandler protocolHandler = loadHandler(request);
        if (protocolHandler == null) {
          handleUnsupportedVersion(request, response);
          return HANDSHAKE_FAILED_UPGRADE_INFO;
        }

        final ExtendedExtension.ExtensionContext extensionContext =
            new ExtendedExtension.ExtensionContext() {

              private final Map<String, Object> properties = new HashMap<String, Object>();

              @Override
              public Map<String, Object> getProperties() {
                return properties;
              }
            };

        protocolHandler.handshake(endpoint, request, response, extensionContext);
        return new SuccessfulUpgradeInfo(
            endpoint, protocolHandler, incomingBufferSize, request, extensionContext);
      }
    } catch (HandshakeException e) {
      LOGGER.log(Level.SEVERE, e.getMessage(), e);
      response.setStatus(e.getCode());
      return HANDSHAKE_FAILED_UPGRADE_INFO;
    }

    response.setStatus(500);
    return NOT_APPLICABLE_UPGRADE_INFO;
  }
Пример #4
0
 /**
  * This is the RequestProcessor thread that continuously processes Client Requests from the
  * RequestProcessor Request Queue.
  */
 public void run() {
   done = false;
   while (!done) {
     if (!requests.isEmpty()) {
       Request r = requests.remove();
       System.out.println("Processing Request: " + r.getMessage());
       protocol.processRequest(r);
     } else {
       try {
         Thread.sleep(100);
       } catch (InterruptedException e) {
         e.printStackTrace();
       }
     }
   }
 }
    TyrusConnection(
        TyrusEndpoint endpoint,
        ProtocolHandler protocolHandler,
        int incomingBufferSize,
        Writer writer,
        Connection.CloseListener closeListener,
        UpgradeRequest upgradeRequest,
        ExtendedExtension.ExtensionContext extensionContext) {
      protocolHandler.setWriter(writer);
      final TyrusWebSocket socket = endpoint.createSocket(protocolHandler);

      socket.onConnect(upgradeRequest);
      this.socket = socket;
      this.readHandler =
          new TyrusReadHandler(
              protocolHandler, socket, endpoint, incomingBufferSize, extensionContext);
      this.writer = writer;
      this.closeListener = closeListener;
      this.extensionContext = extensionContext;
      this.endpoint = endpoint;
    }
    @Override
    public void handle(ByteBuffer data) {
      try {
        if (data != null && data.hasRemaining()) {

          if (buffer != null) {
            data = Utils.appendBuffers(buffer, data, incomingBufferSize, BUFFER_STEP_SIZE);
          } else {
            int newSize = data.remaining();
            if (newSize > incomingBufferSize) {
              throw new IllegalArgumentException("Buffer overflow.");
            } else {
              final int roundedSize =
                  (newSize % BUFFER_STEP_SIZE) > 0
                      ? ((newSize / BUFFER_STEP_SIZE) + 1) * BUFFER_STEP_SIZE
                      : newSize;
              final ByteBuffer result =
                  ByteBuffer.allocate(roundedSize > incomingBufferSize ? newSize : roundedSize);
              result.flip();
              data = Utils.appendBuffers(result, data, incomingBufferSize, BUFFER_STEP_SIZE);
            }
          }

          do {
            final Frame incomingFrame = protocolHandler.unframe(data);

            if (incomingFrame == null) {
              buffer = data;
              break;
            } else {
              Frame frame = incomingFrame;

              for (Extension extension : negotiatedExtensions) {
                if (extension instanceof ExtendedExtension) {
                  try {
                    frame =
                        ((ExtendedExtension) extension).processIncoming(extensionContext, frame);
                  } catch (Throwable t) {
                    LOGGER.log(
                        Level.FINE,
                        String.format(
                            "Extension '%s' threw an exception during processIncoming method invocation: \"%s\".",
                            extension.getName(), t.getMessage()),
                        t);
                  }
                }
              }

              protocolHandler.process(frame, socket);
            }
          } while (true);
        }
      } catch (FramingException e) {
        LOGGER.log(Level.FINE, e.getMessage(), e);
        socket.onClose(
            new CloseFrame(
                new CloseReason(
                    CloseReason.CloseCodes.getCloseCode(e.getClosingCode()), e.getMessage())));
      } catch (Exception e) {
        LOGGER.log(Level.FINE, e.getMessage(), e);
        if (endpoint.onError(socket, e)) {
          socket.onClose(
              new CloseFrame(
                  new CloseReason(CloseReason.CloseCodes.UNEXPECTED_CONDITION, e.getMessage())));
        }
      }
    }
Пример #7
0
  /*
   * Create a new LB
   */
  @POST
  @Consumes("application/json")
  @Produces("application/json")
  public String post(String content) {
    logger.info("POST loadbalancers");

    Device device = null;

    // process POSTed body
    LoadBalancerDataModel lbModel = new LoadBalancerDataModel();
    LoadBalancer lb = new LoadBalancer();
    Integer lbId = 0;
    int x = 0;
    try {
      JSONObject jsonObject = new JSONObject(content);
      String name = (String) jsonObject.get("name");
      lb.setName(name);
      logger.info("   name = " + name);

      // minimally request needs nodes
      if (!jsonObject.has("nodes")) {
        throw new LBaaSException("nodes are required", 400); //  bad request			
      }

      // check to ensure protocol is supported
      if (jsonObject.has("protocol")) {
        String protocol = (String) jsonObject.get("protocol");
        if (!ProtocolHandler.exists(protocol)) {
          throw new LBaaSException(
              "protocol specified not supported : " + protocol, 400); //  bad request				
        } else {
          logger.info("   protocol = " + protocol);
          lb.setProtocol(protocol);
          lb.setPort(ProtocolHandler.getPort(protocol));
          logger.info("   port = " + lb.getPort());
        }
      }

      // nodes
      Nodes nodes = new Nodes();
      JSONArray jsonNodesArray = (JSONArray) jsonObject.get("nodes");
      for (x = 0; x < jsonNodesArray.length(); x++) {
        Node node = new Node();
        // logger.info("node["+x+"] = "+ jsonNodesArray.getJSONObject(x));
        JSONObject jsonNode = jsonNodesArray.getJSONObject(x);
        String address = (String) jsonNode.get("address");
        node.setAddress(address);
        String port = (String) jsonNode.get("port");
        node.setPort(Integer.valueOf(port));
        node.setStatus("ONLINE");
        node.setId(new Integer(x + 1));
        logger.info("   Node[" + x + "]");
        logger.info("      address = " + address);
        logger.info("      port = " + port);
        logger.info("      status = " + node.getStatus());
        nodes.getNodes().add(node);
      }
      lb.setNodes(nodes);

      // vips
      VirtualIps virtualIps = new VirtualIps();
      if (jsonObject.has("virtualIps")) {
        JSONArray jsonVIPArray = (JSONArray) jsonObject.get("virtualIps");
        for (x = 0; x < jsonVIPArray.length(); x++) {
          VirtualIp virtualIp = new VirtualIp();
          // logger.info("vip["+x+"] = "+ jsonVIPArray.getJSONObject(x));
          JSONObject jsonVip = jsonVIPArray.getJSONObject(x);

          String address = (String) jsonVip.get("address");
          virtualIp.setAddress(address);

          if (jsonVip.get("ipVersion").toString().equalsIgnoreCase("IPV4"))
            virtualIp.setIpVersion(IpVersion.IPV_4);
          else virtualIp.setIpVersion(IpVersion.IPV_6);

          if (jsonVip.get("type").toString().equalsIgnoreCase("public"))
            virtualIp.setType(VipType.PUBLIC);
          else virtualIp.setType(VipType.PRIVATE);

          virtualIp.setId(new Integer(x + 1));

          logger.info("   VIP[" + x + "]");
          logger.info("      address = " + virtualIp.getAddress());
          logger.info("      ipversion = " + virtualIp.getIpVersion().toString());
          logger.info("      type = " + virtualIp.getType().toString());
          virtualIps.getVirtualIps().add(virtualIp);
        }
        lb.setVirtualIps(virtualIps);
      }

      // find free device to use
      DeviceDataModel deviceModel = new DeviceDataModel();
      device = deviceModel.findFreeDevice();
      if (device == null) {
        throw new LBaaSException("cannot find free device available", 503); //  not available
      }

      logger.info("found free device at id : " + device.getId().toString());

      // create new LB
      lb.setDevice(device.getId()); // set lb device id
      lbId = lbModel.createLoadBalancer(lb); // write it to datamodel

      // set device lb and write it back to data model
      device.setLbId(lbId);
      deviceModel.setDevice(device);

    } catch (JSONException e) {
      return e.toString();
    }

    // read LB back from data model, it will now have valid id
    LoadBalancer lbResponse = lbModel.getLoadBalancer(lbId);

    // have the device process the request
    try {
      lbaasTaskManager.sendJob(lbResponse.getDevice(), LbToJson(lb, ACTION_CREATE));
    } catch (JSONException jsone) {
      throw new LBaaSException(
          "internal server error JSON exception :" + jsone.toString(), 500); //  internal error
    }

    // respond with JSON
    try {
      return LbToJson(lbResponse, null);
    } catch (JSONException jsone) {
      throw new LBaaSException(
          "internal server error JSON exception :" + jsone.toString(), 500); //  internal error
    }
  }