예제 #1
0
  public OpenImpl(String name) {
    this.name = name;
    publisherName = name;
    stateEventTypeName = "_" + name + "_state";
    state = s0;

    ClientConfig config = new DefaultClientConfig();
    client = Client.create(config);
    service = client.resource(REST_URI);
    eventTypeService = service.path(EVENTS_PATH);
    publishersService = service.path(PUBLISHERS_PATH);
    myPublisher = service.path(PUBLISHERS_PATH + "/" + publisherName);

    System.out.println("Registering events");
    ClientResponse response =
        eventTypeService
            .type(MediaType.APPLICATION_XML)
            .put(ClientResponse.class, CopalClient.eventType(stateEventTypeName));
    System.out.println(response.toString());
    System.out.println(response.getEntity(String.class).toString());

    System.out.println("Setting ttl");
    WebResource test = service.path(EVENTS_PATH + "/" + stateEventTypeName + "/ttl");
    response = test.type(MediaType.TEXT_PLAIN).put(ClientResponse.class, "" + Integer.MAX_VALUE);
    System.out.println(response.toString());
    System.out.println(response.getEntity(String.class).toString());

    String[] eventNames = {stateEventTypeName};
    System.out.println("Registering publisher");
    System.out.println(CopalClient.publisher(publisherName, eventNames));
    response =
        publishersService
            .type(MediaType.APPLICATION_XML)
            .put(ClientResponse.class, CopalClient.publisher(publisherName, eventNames));
    System.out.println(response.toString());
    System.out.println(response.getEntity(String.class).toString());

    response =
        myPublisher
            .type(MediaType.APPLICATION_XML)
            .post(ClientResponse.class, CopalClient.event(stateEventTypeName, state));
    System.out.println(response.toString());

    Runtime.getRuntime()
        .addShutdownHook(
            new Thread() {
              public void run() {
                System.out.println("Removing publisher");
                ClientResponse response = myPublisher.delete(ClientResponse.class);
                System.out.println(response.toString());
                System.out.println(response.getEntity(String.class).toString());

                System.out.println("Removing events");
                WebResource wr = service.path(EVENTS_PATH + "/" + stateEventTypeName);
                response = wr.delete(ClientResponse.class);
                System.out.println(response.toString());
                System.out.println(response.getEntity(String.class).toString());
              }
            });
  }
예제 #2
0
  /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String id = request.getParameter("id");
    String type = request.getParameter("type");
    String additions = request.getParameter("additions");
    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    WebResource service = client.resource(getBaseURI());
    Form form = new Form();
    form.add("type", type);
    form.add("additions", additions);
    ClientResponse clientRsp =
        service
            .path("rest/orders")
            .path(id)
            .type(MediaType.APPLICATION_FORM_URLENCODED)
            .put(ClientResponse.class, form);

    HttpSession session = request.getSession();

    if (clientRsp.getStatus() == 403) {
      String updateResponse = clientRsp.toString();
      session.setAttribute("updateResponse", updateResponse);
      response.sendRedirect("error.jsp?id=2");
    } else {
      String updateResponse = clientRsp.toString() + "\n" + clientRsp.getEntity(String.class);
      session.setAttribute("updateResponse", updateResponse);
      response.sendRedirect("orders.jsp");
    }
  }
예제 #3
0
 private void handleHttpError(ClientResponse r) {
   switch (r.getStatus()) {
     case 400:
       throw new BadRequestHttpException(r.toString());
     case 401:
       throw new UnauthorizedHttpException(r.toString());
     case 403:
       throw new ForbiddenHttpException(r.toString());
     case 404:
       throw new NotFoundHttpException(r.toString());
     case 500:
       throw new InternalServerErrorHttpException(r.toString());
   }
   throw new UniformInterfaceException(r);
 }
 private static String createErrorMessage(ClientResponse clientResponse) {
   clientResponse.bufferEntity();
   String errorMessage = clientResponse.toString();
   if (clientResponse.hasEntity()) {
     errorMessage = errorMessage + " " + clientResponse.getEntity(String.class);
   }
   return errorMessage;
 }
예제 #5
0
  @Override
  public boolean a() {
    System.out.println("svolgo azione a");
    state = s0;

    ClientResponse response =
        myPublisher
            .type(MediaType.APPLICATION_XML)
            .post(ClientResponse.class, CopalClient.event(stateEventTypeName, state));
    System.out.println(response.toString());
    return true;
  }
예제 #6
0
 @Override
 public void initialize(Settings settings, StorageEngine store) throws Exception {
   this.settings = settings;
   this.store = store;
   restAccess =
       new JiraRestAccess(
           settings.getJiraUrl(), settings.getJiraUser(), settings.getJiraPassword());
   ClientResponse response = restAccess.get("/myself");
   if (response.getStatus() != Status.OK.getStatusCode()) {
     throw new RuntimeException("Unable to connect to jira repository: " + response.toString());
   }
   this.projectOptional = getProject();
 }
예제 #7
0
  /**
   * Gets Glance image by using passed token.
   *
   * @param String Token
   * @return image ClientResponse
   */
  public ClientResponse getGlanceImage(String uri, String token) {
    Gson gson = new Gson();
    ClientResponse js_response = null;

    try {
      client.setAuthTokenHeader(token);
      js_response = client.get(URI.create(uri));
      _log.debug(
          "Inside getGlanceImage Response status {}", String.valueOf(js_response.getStatus()));
    } catch (Exception e) {
      _log.debug("Failed to get the glance image response");
      throw GlanceApiException.exceptions.clientResponseGetFailure(js_response.toString());
    } /* catch */

    return js_response;
  }
예제 #8
0
 @Test
 public void createTest() {
   UserToProductXml userToProduct =
       new UserToProductXml.UserToProductBuilder()
           .id(5)
           .userId("Braffa")
           .productId("978098056856")
           .productIndex("0")
           .build();
   UserToProductMsgXml UserToProductMsgXml = new UserToProductMsgXml(userToProduct);
   ClientResponse response = userToProductClient.create(UserToProductMsgXml);
   System.out.println(response);
   assertEquals(
       "create failed ",
       "POST http://localhost:8080/sellemws/rest/usertoproduct/create returned a response status of 200 OK",
       response.toString());
 }
예제 #9
0
  public static void main(String[] args) {
    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    WebResource service = client.resource(getBaseURI());

    System.out.println(
        service
            .path("rest")
            .path("helloworld")
            .accept(MediaType.TEXT_PLAIN)
            .get(String.class)
            .toString());

    // Get xml
    // ClientResponse r = service.path("rest").path("users/1")
    //		.accept(MediaType.APPLICATION_XML).get(ClientResponse.class);
    // System.out.println(r.toString());
    // String s = r.getEntity(String.class);
    // System.out.println(s);

    // Get json
    ClientResponse r1 =
        service
            .path("rest")
            .path("users")
            .accept(MediaType.APPLICATION_JSON)
            .get(ClientResponse.class);
    System.out.println(r1.toString());
    String s1 = r1.getEntity(String.class);
    System.out.println(s1);

    // Get XML
    // System.out.println(service.path("rest").path("hello")
    //		.accept(MediaType.TEXT_XML).get(String.class));

  }
  /*
   * Send GET request to KittyHawk server, and handle redirect/cookies
   */
  private ClientResponse sendGetRequest(WebResource resource) throws VNXeException {
    _logger.info("getting data: {} ", _url);
    if (_client.isUnity() == true) {
      setFields();
    }
    ClientResponse response =
        buildRequest(addQueryParameters(buildResource(resource)).getRequestBuilder())
            .get(ClientResponse.class);
    Status statusCode = response.getClientResponseStatus();
    _logger.info(response.getStatus() + ":" + response.toString());
    if (statusCode == ClientResponse.Status.OK) {
      String emcCsrfToken = response.getHeaders().getFirst(EMC_CSRF_HEADER);
      if (emcCsrfToken != null) {
        saveEmcCsrfToken(emcCsrfToken);
      }

      saveClientCookies();
      return response;
    } else if (response.getClientResponseStatus() == ClientResponse.Status.UNAUTHORIZED) {
      authenticate();
      response =
          buildRequest(addQueryParameters(buildResource(resource)).getRequestBuilder())
              .get(ClientResponse.class);
      ;
    }
    int redirectTimes = 1;
    while (response.getClientResponseStatus() == ClientResponse.Status.FOUND
        && redirectTimes < VNXeConstants.REDIRECT_MAX) {

      String code = response.getClientResponseStatus().toString();
      String data = response.getEntity(String.class);
      _logger.debug("Returned code: {}, returned data:", code, data);
      WebResource newResource = handelRedirect(response);
      if (newResource != null) {
        response = buildRequest(newResource.getRequestBuilder()).get(ClientResponse.class);
        redirectTimes++;
      } else {
        // could not find the redirect url, return
        _logger.error(
            String.format(
                "The post request to: %s failed with: %s %s",
                _url,
                response.getClientResponseStatus().toString(),
                response.getEntity(String.class)));
        throw VNXeException.exceptions.unexpectedDataError(
            "Got redirect status code, but could not get redirected URL");
      }
    }
    if (redirectTimes >= VNXeConstants.REDIRECT_MAX) {
      _logger.error("redirected too many times for the request {}", _url);
      throw VNXeException.exceptions.unexpectedDataError(
          "Redirected too many times while sending the request for " + _url);
    }

    checkResponse(response, GET_REQUEST);

    List<NewCookie> cookies = response.getCookies();
    if (cookies != null && !cookies.isEmpty()) {
      _requestCookies.addAll(cookies);
    }
    saveClientCookies();

    String emcCsrfToken = response.getHeaders().getFirst(EMC_CSRF_HEADER);
    if (emcCsrfToken != null) {
      saveEmcCsrfToken(emcCsrfToken);
    }
    return response;
  }