@Test
  public void testGZIPContentIsProxied() throws Exception {
    final byte[] content = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    prepareProxy();
    prepareServer(
        new HttpServlet() {
          @Override
          protected void doGet(HttpServletRequest req, HttpServletResponse resp)
              throws ServletException, IOException {
            if (req.getHeader("Via") != null) resp.addHeader(PROXIED_HEADER, "true");

            resp.addHeader("Content-Encoding", "gzip");
            GZIPOutputStream gzipOutputStream = new GZIPOutputStream(resp.getOutputStream());
            gzipOutputStream.write(content);
            gzipOutputStream.close();
          }
        });

    ContentResponse response =
        client
            .newRequest("localhost", serverConnector.getLocalPort())
            .timeout(5, TimeUnit.SECONDS)
            .send();
    Assert.assertEquals(200, response.getStatus());
    Assert.assertTrue(response.getHeaders().containsKey(PROXIED_HEADER));
    Assert.assertArrayEquals(content, response.getContent());
  }
  @Test
  public void testProxyWithRequestContentAndResponseContent() throws Exception {
    prepareProxy();
    prepareServer(
        new HttpServlet() {
          @Override
          protected void doPost(HttpServletRequest req, HttpServletResponse resp)
              throws ServletException, IOException {
            if (req.getHeader("Via") != null) resp.addHeader(PROXIED_HEADER, "true");
            IO.copy(req.getInputStream(), resp.getOutputStream());
          }
        });

    byte[] content = new byte[1024];
    new Random().nextBytes(content);
    ContentResponse response =
        client
            .newRequest("localhost", serverConnector.getLocalPort())
            .method(HttpMethod.POST)
            .content(new BytesContentProvider(content))
            .timeout(5, TimeUnit.SECONDS)
            .send();

    Assert.assertEquals(200, response.getStatus());
    Assert.assertTrue(response.getHeaders().containsKey(PROXIED_HEADER));
    Assert.assertArrayEquals(content, response.getContent());
  }
 protected byte[] sendRequestToBalancer(String path) throws Exception {
   ContentResponse response =
       client
           .newRequest("localhost", getServerPort(balancer))
           .path(CONTEXT_PATH + SERVLET_PATH + path)
           .send()
           .get(5, TimeUnit.SECONDS);
   return response.getContent();
 }
示例#4
0
 protected void doDeleteRequest(String wsPart, int expectedResponse) {
   try {
     final ContentResponse response = doRequest(wsPart, HttpMethod.DELETE, null);
     System.err.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>");
     System.err.println(response.getContent());
     Assert.assertEquals(expectedResponse, response.getStatus());
   } catch (final Exception e) {
     throw new IllegalStateException(e);
   }
 }
 @Override
 public ClientResponse handle(ClientRequest cr) throws ClientHandlerException {
   try {
     final Request request = buildRequest(cr);
     writeOutBoundHeaders(cr.getHeaders(), request);
     final ContentResponse response = request.send();
     return new ClientResponse(
         response.getStatus(),
         getInBoundHeaders(response),
         new ByteArrayInputStream(response.getContent()),
         getMessageBodyWorkers());
   } catch (InterruptedException | TimeoutException | ExecutionException | IOException e) {
     throw new ClientHandlerException(e);
   }
 }
  @Test
  public void test_Expect100Continue_WithChunkedContent_Respond100Continue() throws Exception {
    start(
        new AbstractHandler() {
          @Override
          public void handle(
              String target,
              Request baseRequest,
              HttpServletRequest request,
              HttpServletResponse response)
              throws IOException, ServletException {
            baseRequest.setHandled(true);
            // Send 100-Continue and copy the content back
            ServletInputStream input = request.getInputStream();
            // Make sure we chunk the response too
            response.flushBuffer();
            IO.copy(input, response.getOutputStream());
          }
        });

    byte[] content1 = new byte[10240];
    byte[] content2 = new byte[16384];
    ContentResponse response =
        client
            .newRequest("localhost", connector.getLocalPort())
            .scheme(scheme)
            .header(HttpHeader.EXPECT.asString(), HttpHeaderValue.CONTINUE.asString())
            .content(
                new BytesContentProvider(content1, content2) {
                  @Override
                  public long getLength() {
                    return -1;
                  }
                })
            .send()
            .get(5, TimeUnit.SECONDS);

    Assert.assertNotNull(response);
    Assert.assertEquals(200, response.getStatus());

    int index = 0;
    byte[] responseContent = response.getContent();
    for (byte b : content1) Assert.assertEquals(b, responseContent[index++]);
    for (byte b : content2) Assert.assertEquals(b, responseContent[index++]);
  }
  @Test
  public void testJspDump() throws Exception {

    // System.err.println("http://127.0.0.1:9876/jsp/dump.jsp  sleeping....");
    // Thread.currentThread().sleep(5000000);
    // now test the jsp/dump.jsp
    HttpClient client = new HttpClient();
    try {
      client.start();
      ContentResponse response =
          client.GET(
              "http://127.0.0.1:"
                  + TestJettyOSGiBootCore.DEFAULT_JETTY_HTTP_PORT
                  + "/jsp/dump.jsp");
      Assert.assertEquals(HttpStatus.OK_200, response.getStatus());

      String content = new String(response.getContent());
      System.err.println("content: " + content);
      Assert.assertTrue(content.contains("<tr><th>ServletPath:</th><td>/jsp/dump.jsp</td></tr>"));
    } finally {
      client.stop();
    }
  }
  private void test_Expect100Continue_Respond100Continue(byte[]... contents) throws Exception {
    start(
        new AbstractHandler() {
          @Override
          public void handle(
              String target,
              Request baseRequest,
              HttpServletRequest request,
              HttpServletResponse response)
              throws IOException, ServletException {
            baseRequest.setHandled(true);
            // Send 100-Continue and copy the content back
            IO.copy(request.getInputStream(), response.getOutputStream());
          }
        });

    ContentResponse response =
        client
            .newRequest("localhost", connector.getLocalPort())
            .scheme(scheme)
            .header(HttpHeader.EXPECT.asString(), HttpHeaderValue.CONTINUE.asString())
            .content(new BytesContentProvider(contents))
            .send()
            .get(5, TimeUnit.SECONDS);

    Assert.assertNotNull(response);
    Assert.assertEquals(200, response.getStatus());

    int index = 0;
    byte[] responseContent = response.getContent();
    for (byte[] content : contents) {
      for (byte b : content) {
        Assert.assertEquals(b, responseContent[index++]);
      }
    }
  }
package smart.old.action.task;
  @Override
  public void onAction(ActionDialect action) {

    // 使用同步的方式进行请求
    // 注意:因为onAction方法是由Cell Cloud的action dialect进行回调的
    // 该方法独享一个线程,因此可以在此线程里进行阻塞式的调用
    // 因此,这里可以用同步的方式请求HTTP API

    // 获取参数
    JSONObject json = null;
    long equipmentId = 0;
    int rangeInHour = 0;
    try {
      json = new JSONObject(action.getParamAsString("data"));
      equipmentId = json.getLong("moId");
      rangeInHour = json.getInt("rangeInHour");
    } catch (JSONException e1) {
      e1.printStackTrace();
    }

    // URL
    HostConfig config = new MonitorSystemHostConfig();
    HostConfigContext context = new HostConfigContext(config);
    StringBuilder url =
        new StringBuilder(context.getAPIHost())
            .append("/")
            .append(API.NETEQUIPMENT)
            .append("/")
            .append(equipmentId)
            .append("/fInOctets,fOutOctets,fInRate,fOutRate?rangeInHour=")
            .append(rangeInHour);

    // 创建请求
    Request request = this.getHttpClient().newRequest(url.toString());
    request.method(HttpMethod.GET);

    // 发送请求
    ContentResponse response = null;
    try {
      response = request.send();
    } catch (InterruptedException e1) {
      e1.printStackTrace();
    } catch (TimeoutException e1) {
      e1.printStackTrace();
    } catch (ExecutionException e1) {
      e1.printStackTrace();
    }

    Properties params = new Properties();
    JSONObject data = null;
    switch (response.getStatus()) {
      case HttpStatus.OK_200:
        byte[] bytes = response.getContent();
        if (null != bytes) {
          // 获取从Web服务器上返回的数据
          String content = new String(bytes, Charset.forName("UTF-8"));
          try {
            data = new JSONObject(content);
            if ("success".equals(data.get("status"))
                && (!"".equals(data.get("dataList"))
                    && data.get("dataList") != null
                    && !"null".equals(data.get("dataList"))
                    && !data.get("dataList").equals(null))) {
              JSONArray ja = data.getJSONArray("dataList");
              System.out.println("数据总长度:" + ja.length());
              DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
              JSONObject jsob = new JSONObject();
              JSONArray jay = new JSONArray();
              int k = 0;
              if (ja.length() > 32) {
                k = 32;
              } else {
                k = ja.length();
              }
              for (int m = 0; m < 5; m++) {
                for (int i = 0; i < k; i++) {
                  JSONObject job = ja.getJSONObject(i);
                  if (job.get("mosn").equals(ja.getJSONObject(m).get("mosn"))) {
                    JSONArray ja1 = job.getJSONArray("data");
                    JSONArray ja2 = new JSONArray();
                    for (int j = 0; j < ja1.length(); j++) {
                      JSONObject jo = new JSONObject();
                      jo.put("value", Float.valueOf(ja1.getJSONArray(j).getString(0)));
                      jo.put("collectTime", df.parse(ja1.getJSONArray(j).getString(1)).getTime());
                      ja2.put(jo);
                    }
                    JSONObject job1 = new JSONObject();
                    job1.put("data", ja2);
                    job1.put("moPath", job.getString("moPath"));
                    job1.put("kpiName", job.getString("kpiName"));
                    String s = job.getString("moPath");
                    job1.put("name", s.substring(s.indexOf("(") + 1, s.lastIndexOf(")")));
                    job1.put("mosn", Long.valueOf(job.getString("mosn")));
                    jay.put(job1);
                  }
                }
              }
              jsob.put("dataList", jay);
              jsob.put("resourceId", equipmentId);

              data.remove("dataList");
              data.put("data", jsob);
              data.put("status", 300);
              data.put("errorInfo", "");
            } else {
              data.put("data", "");
              data.put("status", 603);
            }
            System.out.println("网络设备detail: " + data);

            // 设置参数
            params.addProperty(new ObjectProperty("data", data));
          } catch (JSONException e) {
            e.printStackTrace();
          } catch (ParseException e) {
            e.printStackTrace();
          }

          // 响应动作,即想客户端发送ActionDialect
          // 参数tracker 是一次动作的追踪表示。
          this.response(Action.NETEQUIPMENT, params);
        } else {
          this.reportHTTPError(Action.NETEQUIPMENT);
        }
        break;
      default:
        Logger.w(EquipmentBasicListener.class, "返回响应码" + response.getStatus());
        try {
          data = new JSONObject();
          data.put("status", 900);
        } catch (JSONException e) {
          e.printStackTrace();
        }

        // 设置参数
        params.addProperty(new ObjectProperty("data", data));

        // 响应动作,即向客户端发送 ActionDialect
        this.response(Action.NETEQUIPMENT, params);
        break;
    }
  }
  @Override
  public void onAction(ActionDialect action) {

    // 使用同步方式进行请求。
    // 因为 onAction 方法是由 Cell Cloud 的 action dialect 进行回调的,
    // 该方法独享一个线程,因此可以在此线程里进行阻塞式的调用。
    // 因此,可以用同步方式请求 HTTP API 。

    // URL
    HostConfig serviceDeskConfig = new ServiceDeskHostConfig();
    HostConfigContext context = new HostConfigContext(serviceDeskConfig);
    StringBuilder url =
        new StringBuilder(context.getAPIHost()).append("/").append(API.SERVICELEVELLIST);
    JSONObject json = null;
    String bpiId = null;
    try {
      json = new JSONObject(action.getParamAsString("data"));
      bpiId = json.getString("incidentId");

    } catch (JSONException e2) {
      e2.printStackTrace();
    }

    url.append("&bpiId=").append(bpiId);
    System.out.println("获取服务级别的URL:" + url.toString());
    // 创建请求
    Request request = this.getHttpClient().newRequest(url.toString());
    request.method(HttpMethod.GET);

    Properties params = new Properties();
    // 发送请求
    ContentResponse response = null;
    try {
      response = request.send();
    } catch (InterruptedException e1) {
      e1.printStackTrace();
    } catch (TimeoutException e1) {
      e1.printStackTrace();
    } catch (ExecutionException e1) {
      e1.printStackTrace();
    }
    JSONObject jo = null;
    switch (response.getStatus()) {
      case HttpStatus.OK_200:
        byte[] bytes = response.getContent();

        if (null != bytes) {
          // 获取从 Web 服务器上返回的数据
          String content = new String(bytes, Charset.forName("UTF-8"));
          System.out.println(content);
          try {
            jo = new JSONObject(content);
            System.out.println("响应服务级别请求的返回值为::" + jo);

            // 设置参数
            params.addProperty(new ObjectProperty("data", jo));

            // 响应动作,即向客户端发送 ActionDialect
            this.response(Action.SERVICELEVELLIST, params);

          } catch (JSONException e) {
            e.printStackTrace();
          }
        } else {
          this.reportHTTPError(Action.SERVICELEVELLIST);
        }

        break;
      default:
        Logger.w(IncidentListListener.class, "返回响应码:" + response.getStatus());
        jo = new JSONObject();
        try {
          jo.put("status", 900);
        } catch (JSONException e) {
          e.printStackTrace();
        }

        // 设置参数
        params.addProperty(new ObjectProperty("data", jo));

        // 响应动作,即向客户端发送 ActionDialect
        this.response(Action.SERVICELEVELLIST, params);
        break;
    }
  }
示例#12
0
 private static InputStream getInputStream(final ContentResponse response) {
   return new ByteArrayInputStream(response.getContent());
 }
  @Test
  public void testCachingProxy() throws Exception {
    final byte[] content = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF};
    prepareServer(
        new HttpServlet() {
          @Override
          protected void doGet(HttpServletRequest req, HttpServletResponse resp)
              throws ServletException, IOException {
            if (req.getHeader("Via") != null) resp.addHeader(PROXIED_HEADER, "true");
            resp.getOutputStream().write(content);
          }
        });

    // Don't do this at home: this example is not concurrent, not complete,
    // it is only used for this test and to verify that ProxyServlet can be
    // subclassed enough to write your own caching servlet
    final String cacheHeader = "X-Cached";
    proxyServlet =
        new ProxyServlet() {
          private Map<String, ContentResponse> cache = new HashMap<>();
          private Map<String, ByteArrayOutputStream> temp = new HashMap<>();

          @Override
          protected void service(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException {
            ContentResponse cachedResponse = cache.get(request.getRequestURI());
            if (cachedResponse != null) {
              response.setStatus(cachedResponse.getStatus());
              // Should copy headers too, but keep it simple
              response.addHeader(cacheHeader, "true");
              response.getOutputStream().write(cachedResponse.getContent());
            } else {
              super.service(request, response);
            }
          }

          @Override
          protected void onResponseContent(
              HttpServletRequest request,
              HttpServletResponse response,
              Response proxyResponse,
              byte[] buffer,
              int offset,
              int length,
              Callback callback) {
            // Accumulate the response content
            ByteArrayOutputStream baos = temp.get(request.getRequestURI());
            if (baos == null) {
              baos = new ByteArrayOutputStream();
              temp.put(request.getRequestURI(), baos);
            }
            baos.write(buffer, offset, length);
            super.onResponseContent(
                request, response, proxyResponse, buffer, offset, length, callback);
          }

          @Override
          protected void onResponseSuccess(
              HttpServletRequest request, HttpServletResponse response, Response proxyResponse) {
            byte[] content = temp.remove(request.getRequestURI()).toByteArray();
            ContentResponse cached = new HttpContentResponse(proxyResponse, content, null, null);
            cache.put(request.getRequestURI(), cached);
            super.onResponseSuccess(request, response, proxyResponse);
          }
        };
    prepareProxy();

    // First request
    ContentResponse response =
        client
            .newRequest("localhost", serverConnector.getLocalPort())
            .timeout(5, TimeUnit.SECONDS)
            .send();
    Assert.assertEquals(200, response.getStatus());
    Assert.assertTrue(response.getHeaders().containsKey(PROXIED_HEADER));
    Assert.assertArrayEquals(content, response.getContent());

    // Second request should be cached
    response =
        client
            .newRequest("localhost", serverConnector.getLocalPort())
            .timeout(5, TimeUnit.SECONDS)
            .send();
    Assert.assertEquals(200, response.getStatus());
    Assert.assertTrue(response.getHeaders().containsKey(cacheHeader));
    Assert.assertArrayEquals(content, response.getContent());
  }