/** Executes an authentication request via HTTP POST */
  private <T> T executeAuthenticationPost(WebResource webResource, Class<T> returnClass)
      throws CIWiseRESTConnectorTokenExpiredException, CIWiseRESTConnectorException {

    // Map query params for POST operation MultivaluedMap, MultivaluedMapImpl

    MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
    queryParams.add("username", getConnector().getConfig().getUsername());
    queryParams.add("password", getConnector().getConfig().getPassword());

    /** Call HTTP POST */
    ClientResponse clientResponse =
        webResource
            .queryParams(queryParams)
            .accept(MediaType.APPLICATION_JSON)
            .post(ClientResponse.class);

    if (clientResponse.getStatus() == 200) {
      return clientResponse.getEntity(returnClass);
    } else if (clientResponse.getStatus() == 401) {
      throw new CIWiseRESTConnectorTokenExpiredException(
          "The access token has expired; " + clientResponse.getEntity(String.class));
    } else {
      throw new CIWiseRESTConnectorException(
          String.format(
              "ERROR - statusCode: %d - message: %s",
              clientResponse.getStatus(), clientResponse.getEntity(String.class)));
    }
  }
  private static WebResource.Builder getBuilder(
      String url, String authorization, Map<String, String> key, Boolean overwrite) {
    Client client = Client.create();
    WebResource wr = client.resource(url);

    MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();

    if (key != null && !key.isEmpty()) {
      for (String k : key.keySet()) {
        queryParams.add(k, key.get(k));
      }
    }

    if (overwrite != null && overwrite) {
      queryParams.add(CLOUDHUB_OVERRITE_REST_PARAMETER, overwrite.toString());
    }

    if (queryParams.isEmpty()) {
      return wr.header(HTTP_AUTH_HEADER_NAME, authorization).type(MediaType.APPLICATION_JSON);
    } else {
      return wr.queryParams(queryParams)
          .header(HTTP_AUTH_HEADER_NAME, authorization)
          .type(MediaType.APPLICATION_JSON);
    }
  }
Example #3
0
 // Registra un MR para su gestion
 // curl -d "ip=192.168.119.35&port=10001&domain=broadcaster&type=Webservices"
 // http://192.168.119.35:9999/mbs/register
 @POST
 @Path("/register")
 @Produces(MediaType.TEXT_PLAIN)
 @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
 public String register(
     @FormParam("ip") String ip,
     @FormParam("port") String port,
     @FormParam("domain") String domain,
     @FormParam("type") String type) {
   if (domain.equals("SNMPInstrumentingServer")) {
     Client client = Client.create();
     WebResource webResource =
         client.resource(
             "http://"
                 + MBeanServerMaster.INSTRUMENTING_SERVER_IP
                 + ":"
                 + MBeanServerMaster.INSTRUMENTING_SERVER_WS_PORT
                 + "/snmp_mbs/register");
     MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
     queryParams.add("domain", "SNMPInstrumentingServer");
     queryParams.add("type", type);
     ClientResponse s =
         webResource.queryParams(queryParams).post(ClientResponse.class, queryParams);
     if (s.getEntity(String.class).equals("ok"))
       DynamicMBeanMirrorFactory.register(ip, port, domain, type);
   } else DynamicMBeanMirrorFactory.register(ip, port, domain, type);
   return "";
 }
 protected WebResource addQueryParameters(WebResource resource) {
   if (_queryParams == null) {
     return resource; // no query parameters
   }
   _logger.debug("_queryParams:" + _queryParams);
   return resource.queryParams(_queryParams);
 }
  public User getUser(long id, Boolean includeAttributes) {
    WebResource wr = getBaseWebResource("users", "user", id);
    MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();

    if (includeAttributes != null) {

      queryParams.add("includeattributes", includeAttributes.toString());
    }
    return wr.queryParams(queryParams).get(User.class);
  }
Example #6
0
  // follow the detour
  private static void authorizeToken(String username, String password) {
    System.out.println("Authenticating to OAuth token service\n");

    WebResource resource = client.resource(TOKEN_SERVICE + "NoBrowserAuthorization");

    MultivaluedMapImpl query = new MultivaluedMapImpl();
    query.add("username", username);
    query.add("password", password);
    query.add("request_token", params.getToken());

    String s = resource.queryParams(query).get(String.class);

    System.out.println("Authenticated ok\n");
  }
 /** Queries GeoNames API for a given geonameId and return the JSON string */
 private String fetchJsonFromGeoNames(String geoNameId) {
   String result = null;
   if (cache.containsKey("geoname_json_" + geoNameId)) {
     return cache.get("geoname_json_" + geoNameId);
   } else {
     Client c = Client.create();
     WebResource r = c.resource(geonamesApiUrl);
     MultivaluedMap<String, String> params = new MultivaluedMapImpl();
     params.add("geonameId", geoNameId);
     params.add("username", apiUser);
     result = r.queryParams(params).get(String.class);
     cache.put("geoname_json_" + geoNameId, result);
   }
   return result;
 }
Example #8
0
  public <T> T get(
      URI uri, MultivaluedMap<String, String> queryParams, Class<T> clazz, String mediaType) {
    if (uri == null)
      throw new IllegalArgumentException(
          "The URI can't be null. This usually means that a previous "
              + "call to Mgmt REST api failed.");

    com.sun.jersey.api.client.WebResource resource = resource();
    if (queryParams != null) {
      resource = resource.queryParams(queryParams);
    }
    ClientResponse response =
        resource.uri(uri).type(mediaType).accept(mediaType).get(ClientResponse.class);
    if (response.getStatus() >= 300) {
      handleHttpError(response);
    }
    return response.getEntity(clazz);
  }
  /** {@inheritDoc} */
  @Override
  public List<ProductRelease> findAll(
      Integer page,
      Integer pageSize,
      String orderBy,
      String orderType,
      String productName,
      String osType) {
    String url;
    url =
        getBaseHost()
            + MessageFormat.format(ClientConstants.BASE_PRODUCT_RELEASE_PATH, productName);
    WebResource wr = getClient().resource(url);
    MultivaluedMap<String, String> searchParams = new MultivaluedMapImpl();
    searchParams = addParam(searchParams, "osType", osType);
    searchParams = addParam(searchParams, "page", page);
    searchParams = addParam(searchParams, "pageSize", pageSize);
    searchParams = addParam(searchParams, "orderBy", orderBy);
    searchParams = addParam(searchParams, "orderType", orderType);

    return wr.queryParams(searchParams).accept(getType()).get(ProductReleases.class);
  }
Example #10
0
  @Override
  public String sendGetRequest(
      final String serviceURI, final MultivaluedMap<String, String> queryParams) {
    try {
      WebResource resource = getClient(serviceURI);
      resource = resource.queryParams(queryParams);

      ClientResponse response = resource.type(MediaType.APPLICATION_JSON).get(ClientResponse.class);

      String msgResp = parseResponse(response);

      if (response.getStatus() != 200) {
        logger.error("Erreur lors de la sauvegarde à distance. Reponse de l'API : {}", msgResp);
        msgResp = null;
      }

      return msgResp;
    } catch (Exception ex) {
      logger.error("", ex);
    }

    return null;
  }
Example #11
0
  @Override
  public void processAction() {

    if (source == null || source.isEmpty()) {
      source = cache.getString(WorkflowCache.RECENTLOCATION);
    }

    log.info(String.format("Action [%s] is being executed for [%s] ", getName(), workflowName));
    log.info(String.format("Using [%s]", clientURL));
    Client client = Client.create();
    client.setReadTimeout(990000);
    WebResource webResource = client.resource(clientURL);

    MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
    for (Entry ent : (List<Entry>) cache.getAll(Entry.class)) {
      queryParams.add(
          "filepath", StringHelper.joinDirectoryString(source, ent.getString(Entry.NAME)));
    }

    queryParams.add("callback", config.getCallbackURL());
    queryParams.add("actionid", String.valueOf(getID()));
    queryParams.add("workflowid", String.valueOf(workflowId));
    queryParams.add("actionsetid", String.valueOf(actionSetId));

    try {
      ClientResponse response = webResource.queryParams(queryParams).post(ClientResponse.class);

      if (response.getClientResponseStatus() != ClientResponse.Status.OK) {
        final String error =
            String.format(
                "Action [%s] executed for [%s] but got HTTP status: %s ",
                getName(), workflowName, response.getClientResponseStatus().toString());
        log.error(error);
        log.error(String.format("HTTP response: %s ", response.getEntity(String.class)));
        log.error(String.format("HTTP headers: %s ", response.getHeaders()));

        CoreThreadFactory.getCallBackExecutorService()
            .execute(
                new Runnable() {
                  @Override
                  public void run() {
                    listener.onActionError(RepositoryAction.this, error);
                  }
                });
      } else {
        log.info(
            String.format(
                "Action [%s] executed for [%s] with HTTP status: %s ",
                getName(), workflowName, response.getClientResponseStatus().toString()));
        CoreThreadFactory.getCallBackExecutorService()
            .execute(
                new Runnable() {
                  @Override
                  public void run() {
                    listener.onActionFinished(RepositoryAction.this);
                  }
                });
      }
    } catch (final Exception e) {
      log.error(
          String.format("Action [%s] executed for [%s] but got error", getName(), workflowName), e);
      CoreThreadFactory.getCallBackExecutorService()
          .execute(
              new Runnable() {
                @Override
                public void run() {
                  listener.onActionError(
                      RepositoryAction.this,
                      e.getMessage() + " [make sure that repository client is running]");
                }
              });
    }
  }
 private ClientResponse getClientResponse(MultivaluedMapImpl queryParams) {
   WebResource webResource = getWalletExplorerWebResource();
   ClientResponse response =
       webResource.queryParams(queryParams).type("application/json").get(ClientResponse.class);
   return response;
 }