com.mashape.unirest.http.JsonNode Java Examples

The following examples show how to use com.mashape.unirest.http.JsonNode. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ReleaseTool.java    From apicurio-studio with Apache License 2.0 9 votes vote down vote up
/**
 * Returns all issues (as JSON nodes) that were closed since the given date.
 * @param since
 * @param githubPAT
 */
private static List<JSONObject> getIssuesForRelease(String since, String githubPAT) throws Exception {
    List<JSONObject> rval = new ArrayList<>();

    String currentPageUrl = "https://api.github.com/repos/apicurio/apicurio-studio/issues";
    int pageNum = 1;
    while (currentPageUrl != null) {
        System.out.println("Querying page " + pageNum + " of issues.");
        HttpResponse<JsonNode> response = Unirest.get(currentPageUrl)
                .queryString("since", since)
                .queryString("state", "closed")
                .header("Accept", "application/json")
                .header("Authorization", "token " + githubPAT).asJson();
        if (response.getStatus() != 200) {
            throw new Exception("Failed to list Issues: " + response.getStatusText());
        }
        JSONArray issueNodes = response.getBody().getArray();
        issueNodes.forEach(issueNode -> {
            JSONObject issue = (JSONObject) issueNode;
            String closedOn = issue.getString("closed_at");
            if (since.compareTo(closedOn) < 0) {
                if (!isIssueExcluded(issue)) {
                    rval.add(issue);
                } else {
                    System.out.println("Skipping issue (excluded): " + issue.getString("title"));
                }
            } else {
                System.out.println("Skipping issue (old release): " + issue.getString("title"));
            }
        });

        System.out.println("Processing page " + pageNum + " of issues.");
        System.out.println("    Found " + issueNodes.length() + " issues on page.");
        String allLinks = response.getHeaders().getFirst("Link");
        Map<String, Link> links = Link.parseAll(allLinks);
        if (links.containsKey("next")) {
            currentPageUrl = links.get("next").getUrl();
        } else {
            currentPageUrl = null;
        }
        pageNum++;
    }

    return rval;
}
 
Example #2
Source File: RocketChatClientCallBuilder.java    From rocket-chat-rest-client with MIT License 7 votes vote down vote up
private void login() throws IOException {
      HttpResponse<JsonNode> loginResult;

      try {
          loginResult = Unirest.post(serverUrl + "v1/login").field("username", user).field("password", password).asJson();
      } catch (UnirestException e) {
          throw new IOException(e);
      }

      if (loginResult.getStatus() == 401)
          throw new IOException("The username and password provided are incorrect.");

      
if (loginResult.getStatus() != 200)
	throw new IOException("The login failed with a result of: " + loginResult.getStatus()
		+ " (" + loginResult.getStatusText() + ")");

      JSONObject data = loginResult.getBody().getObject().getJSONObject("data");
      this.authToken = data.getString("authToken");
      this.userId = data.getString("userId");
  }
 
Example #3
Source File: Get.java    From compliance with Apache License 2.0 6 votes vote down vote up
protected HttpResponse<JsonNode> queryServer(String url) throws UnirestException {
    if (log.isDebugEnabled()) {
        log.debug("begin jsonGet to " + url + " id = " + id);
    }
    HttpResponse<JsonNode> response;
    if (id != null) {
        response = Unirest.get(url)
                .header("accept", "application/json")
                .routeParam("id", id)
                .queryString(queryParams)
                .asJson();
    } else {
        response = Unirest.get(url)
                .header("accept", "application/json")
                .queryString(queryParams)
                .asJson();
    }
    if (log.isDebugEnabled()) {
        log.debug("exit jsonGet to " + url + " with status " + response.getStatusText());
    }
    return response;
}
 
Example #4
Source File: AliyunUtil.java    From ZTuoExchange_framework with MIT License 6 votes vote down vote up
public static JSONObject doPost(String url,String body,String accessId,String accessKey) throws MalformedURLException, UnirestException {
    String method = "POST";
    String accept = "application/json";
    String content_type = "application/json";
    String path = new URL(url).getFile();
    String date = DateUtil.toGMTString(new Date());
    // 1.对body做MD5+BASE64加密
    String bodyMd5 = MD5Base64(body);
    String stringToSign = method + "\n" + accept + "\n" + bodyMd5 + "\n" + content_type + "\n" + date + "\n"
            + path;
    // 2.计算 HMAC-SHA1
    String signature = HMACSha1(stringToSign, accessKey);
    // 3.得到 authorization header
    String authHeader = "Dataplus " + accessId + ":" + signature;

    HttpResponse<JsonNode> resp =  Unirest.post(url)
            .header("accept",accept)
            .header("content-type",content_type)
            .header("date",date)
            .header("Authorization",authHeader)
            .body(body)
            .asJson();
    JSONObject json = resp.getBody().getObject();
    return json;
}
 
Example #5
Source File: Client.java    From SikuliNG with MIT License 6 votes vote down vote up
public static JSONObject get(String urlCommand) {
  log.trace("get: %s", urlCommand);
  HttpResponse<JsonNode> jsonResponse = null;
  JSONObject response = null;
  try {
    jsonResponse = Unirest.get(urlBase + urlCommand)
            .header("accept", "application/json")
            .asJson();
  } catch (UnirestException e) {
    log.error("get: %s", e.getMessage());
  }
  String responseBody = "null";
  if (SX.isNotNull(jsonResponse)) {
    responseBody = jsonResponse.getBody().toString();
    response = SXJson.makeObject(responseBody);
  }
  log.trace("get: response: %s",jsonResponse.getBody().toString());
  return response;
}
 
Example #6
Source File: Network.java    From minicraft-plus-revived with GNU General Public License v3.0 6 votes vote down vote up
public static void findLatestVersion(Action callback) {
	new Thread(() -> {
		// fetch the latest version from github
		if (debug) System.out.println("Fetching release list from GitHub...");
		try {
			HttpResponse<JsonNode> response = Unirest.get("https://api.github.com/repos/chrisj42/minicraft-plus-revived/releases").asJson();
			if (response.getStatus() != 200) {
				System.err.println("Version request returned status code " + response.getStatus() + ": " + response.getStatusText());
				System.err.println("Response body: " + response.getBody());
				latestVersion = new VersionInfo(VERSION, "", "");
			} else {
				latestVersion = new VersionInfo(response.getBody().getArray().getJSONObject(0));
			}
		} catch (UnirestException e) {
			e.printStackTrace();
			latestVersion = new VersionInfo(VERSION, "", "");
		}
		
		callback.act(); // finished.
	}).start();
}
 
Example #7
Source File: AliyunUtil.java    From ZTuoExchange_framework with MIT License 6 votes vote down vote up
public static JSONObject doPost(String url,String body,String accessId,String accessKey) throws MalformedURLException, UnirestException {
    String method = "POST";
    String accept = "application/json";
    String content_type = "application/json";
    String path = new URL(url).getFile();
    String date = DateUtil.toGMTString(new Date());
    // 1.对body做MD5+BASE64加密
    String bodyMd5 = MD5Base64(body);
    String stringToSign = method + "\n" + accept + "\n" + bodyMd5 + "\n" + content_type + "\n" + date + "\n"
            + path;
    // 2.计算 HMAC-SHA1
    String signature = HMACSha1(stringToSign, accessKey);
    // 3.得到 authorization header
    String authHeader = "Dataplus " + accessId + ":" + signature;

    HttpResponse<JsonNode> resp =  Unirest.post(url)
            .header("accept",accept)
            .header("content-type",content_type)
            .header("date",date)
            .header("Authorization",authHeader)
            .body(body)
            .asJson();
    JSONObject json = resp.getBody().getObject();
    return json;
}
 
Example #8
Source File: Client.java    From pact-workshop-jvm with Apache License 2.0 6 votes vote down vote up
public List<Object> fetchAndProcessData(String dateTime) throws UnirestException {
  Optional<JsonNode> data = loadProviderJson(dateTime);
  System.out.println("data=" + data);

  if (data != null && data.isPresent()) {
    JSONObject jsonObject = data.get().getObject();
    int value = 100 / jsonObject.getInt("count");
    TemporalAccessor date =
      DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXX")
          .parse(jsonObject.getString("validDate"));

    System.out.println("value=" + value);
    System.out.println("date=" + date);
    return Arrays.asList(value, OffsetDateTime.from(date));
  } else {
    return Arrays.asList(0, null);
  }
}
 
Example #9
Source File: KeycloakRequiredActionLinkUtil.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
public static String getAdminAccessToken() throws Exception {
  Map<String, String> headers = new HashMap<>();
  headers.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED);
  BaseRequest request =
      Unirest.post(
              ProjectUtil.getConfigValue(JsonKey.SUNBIRD_SSO_URL)
                  + "realms/"
                  + ProjectUtil.getConfigValue(JsonKey.SUNBIRD_SSO_RELAM)
                  + "/protocol/openid-connect/token")
          .headers(headers)
          .field("client_id", ProjectUtil.getConfigValue(JsonKey.SUNBIRD_SSO_CLIENT_ID))
          .field("client_secret", ProjectUtil.getConfigValue(JsonKey.SUNBIRD_SSO_CLIENT_SECRET))
          .field("grant_type", "client_credentials");

  HttpResponse<JsonNode> response = request.asJson();
  ProjectLogger.log(
      "KeycloakRequiredActionLinkUtil:getAdminAccessToken: Response status = "
          + response.getStatus(),
      LoggerEnum.INFO.name());

  return response.getBody().getObject().getString(ACCESS_TOKEN);
}
 
Example #10
Source File: HttpApiServiceImpl.java    From pagerduty-client with MIT License 6 votes vote down vote up
public EventResult notifyEvent(Incident incident) throws NotifyEventException {
    try {
        HttpRequestWithBody request = Unirest.post(eventApi)
                .header("Accept", "application/json");
        request.body(incident);
        HttpResponse<JsonNode> jsonResponse = request.asJson();
        log.debug(IOUtils.toString(jsonResponse.getRawBody()));
        switch(jsonResponse.getStatus()) {
            case HttpStatus.SC_OK:
            case HttpStatus.SC_CREATED:
            case HttpStatus.SC_ACCEPTED:
                return EventResult.successEvent(JsonUtils.getPropertyValue(jsonResponse, "status"), JsonUtils.getPropertyValue(jsonResponse, "message"), JsonUtils.getPropertyValue(jsonResponse, "dedup_key"));
            case HttpStatus.SC_BAD_REQUEST:
                return EventResult.errorEvent(JsonUtils.getPropertyValue(jsonResponse, "status"), JsonUtils.getPropertyValue(jsonResponse, "message"), JsonUtils.getArrayValue(jsonResponse, "errors"));
            default:
                return EventResult.errorEvent(String.valueOf(jsonResponse.getStatus()), "", IOUtils.toString(jsonResponse.getRawBody()));
        }
    } catch (UnirestException | IOException e) {
        throw new NotifyEventException(e);
    }
}
 
Example #11
Source File: Post.java    From compliance with Apache License 2.0 6 votes vote down vote up
protected HttpResponse<JsonNode> queryServer(String url) throws UnirestException {
    if (log.isDebugEnabled()) {
        log.debug("begin jsonPost to " + url + " of " + json);
    }
    if (wireTracker != null) {
        wireTracker.bodySent = json;
    }
    HttpResponse<JsonNode> response = Unirest.post(url)
            .header("Content-Type", "application/json")
            .header("accept", "application/json")
            .body(json)
            .asJson();
    if (log.isDebugEnabled()) {
        log.debug("exit jsonPost to " + url + " with status " + response.getStatusText());
    }
    return response;
}
 
Example #12
Source File: BosonNLPWordSegmenter.java    From elasticsearch-analysis-bosonnlp with Apache License 2.0 6 votes vote down vote up
/**
 * Call BosonNLP word segmenter API via Java library Unirest.
 * 
 * @param target, the text to be processed
 * @throws JSONException
 * @throws UnirestException
 * @throws IOException
 */
public void segment(String target) throws JSONException, UnirestException, IOException {
    // Clean the word token
    this.words.clear();
    // Get the new word token of target
    String body = new JSONArray(new String[] { target }).toString();
    HttpResponse<JsonNode> jsonResponse = Unirest.post(this.TAG_URL)
            .queryString("space_mode", this.spaceMode)
            .queryString("oov_level", this.oovLevel)
            .queryString("t2s", this.t2s)
            .queryString("special_char_conv", this.specialCharConv)
            .header("Accept", "application/json")
            .header("X-Token", this.BOSONNLP_API_TOKEN).body(body).asJson();

    makeToken(jsonResponse.getBody());
}
 
Example #13
Source File: GitHubSourceConnector.java    From apicurio-studio with Apache License 2.0 6 votes vote down vote up
/**
 * Uses the GH API to add a commit comment.
 * @param repositoryUrl
 * @param commitSha
 * @param commitComment
 * @throws UnirestException
 * @throws SourceConnectorException
 */
private void addCommitComment(String repositoryUrl, String commitSha, String commitComment)
        throws UnirestException, SourceConnectorException {
    GitHubCreateCommitCommentRequest body = new GitHubCreateCommitCommentRequest();
    body.setBody(commitComment);

    GitHubResource resource = resolver.resolve(repositoryUrl);
    String addCommentUrl = this.endpoint("/repos/:org/:repo/commits/:sha/comments")
        .bind("org", resource.getOrganization())
        .bind("repo", resource.getRepository())
        .bind("path", resource.getResourcePath())
        .bind("sha", commitSha)
        .toString();

    HttpRequestWithBody request = Unirest.post(addCommentUrl).header("Content-Type", "application/json; charset=utf-8");
    addSecurityTo(request);
    HttpResponse<JsonNode> response = request.body(body).asJson();
    if (response.getStatus() != 201) {
        throw new UnirestException("Unexpected response from GitHub: " + response.getStatus() + "::" + response.getStatusText());
    }
}
 
Example #14
Source File: MicrocksConnector.java    From apicurio-studio with Apache License 2.0 6 votes vote down vote up
/**
 * Figures out the URL of the Keycloak server that is protecting Microcks.
 */
private String getKeycloakURL() throws MicrocksConnectorException {
    if (this._keycloakURL == null) {
        // Retrieve the Keycloak configuration to build keycloakURL.
        HttpResponse<JsonNode> keycloakConfig = null;
        try {
            keycloakConfig = Unirest.get(this.apiURL + "/keycloak/config")
                    .header("Accept", "application/json").asJson();
        } catch (UnirestException e) {
            logger.error("Exception while connecting to Microcks backend", e);
            throw new MicrocksConnectorException(
                    "Exception while connecting Microcks backend. Check URL.");
        }

        if (keycloakConfig.getStatus() != 200) {
            logger.error("Keycloak config cannot be fetched from Microcks server, check configuration");
            throw new MicrocksConnectorException(
                    "Keycloak configuration cannot be fetched from Microcks. Check URL.");
        }
        String authServer = keycloakConfig.getBody().getObject().getString("auth-server-url");
        String realmName = keycloakConfig.getBody().getObject().getString("realm");
        this._keycloakURL = authServer + "/realms/" + realmName;
    }
    return this._keycloakURL;
}
 
Example #15
Source File: Owl2Neo4J.java    From owl2neo4j with MIT License 6 votes vote down vote up
private void queryNeo4J (JsonObject json, String url, String errorTitle) {
    try {
        HttpResponse<JsonNode> response = Unirest.post(url)
            .body(json.toString())
            .asJson();

        if (this.verbose_output) {
            System.out.println("CQL: " + json);
            this.cqlLogger.info(json.toString());
        }

        checkForError(response);
    } catch (Exception e) {
        print_error(ANSI_RESET_DIM + errorTitle);
        print_error("CQL: " + json);
        print_error(e.getMessage());
        System.exit(1);
    }
}
 
Example #16
Source File: HttpClientLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
@Ignore
public void whenAysncRequestShouldReturnOk() throws InterruptedException, ExecutionException {
    Future<HttpResponse<JsonNode>> future = Unirest.post("http://www.mocky.io/v2/5a9ce37b3100004f00ab5154?mocky-delay=10000ms")
        .header("accept", "application/json")
        .asJsonAsync(new Callback<JsonNode>() {

            public void failed(UnirestException e) {
                // Do something if the request failed
            }

            public void completed(HttpResponse<JsonNode> response) {
                // Do something if the request is successful
            }

            public void cancelled() {
                // Do something if the request is cancelled
            }

        });
    assertEquals(200, future.get()
        .getStatus());

}
 
Example #17
Source File: ESTasks.java    From elasticsearch with Apache License 2.0 6 votes vote down vote up
public List<JSONObject> getTasks() {
    List<JSONObject> tasks = new ArrayList<>();
    LOGGER.debug("Fetching tasks on " + tasksEndPoint);
    final AtomicReference<HttpResponse<JsonNode>> response = new AtomicReference<>();
    Awaitility.await().atMost(30, TimeUnit.SECONDS).pollInterval(1, TimeUnit.SECONDS).until(() -> { // This can take some time, somtimes.
        try {
            response.set(Unirest.get(tasksEndPoint).asJson());
            return true;
        } catch (UnirestException e) {
            LOGGER.debug(e);
            return false;
        }
    });
    for (int i = 0; i < response.get().getBody().getArray().length(); i++) {
        JSONObject jsonObject = response.get().getBody().getArray().getJSONObject(i);
        tasks.add(jsonObject);
    }
    return tasks;
}
 
Example #18
Source File: ElasticsearchNodesResponse.java    From elasticsearch with Apache License 2.0 6 votes vote down vote up
private boolean endpointIsOk(JSONObject task) throws Exception {
    String url = "http://" + ElasticsearchParser.parseHttpAddress(task) + "/_nodes";
    HttpResponse<String> response = Unirest.get(url).asString();

    if (response.getStatus() < 200 || response.getStatus() >= 400) {
        LOGGER.debug("Polling Elasticsearch endpoint '" + url + "' returned bad status: " + response.getStatus() + " " + response.getStatusText());
        return false;
    }

    JsonNode body = new JsonNode(response.getBody());
    if (body.getObject().getJSONObject("nodes").length() != nodesCount) {
        LOGGER.debug("Polling Elasticsearch endpoint '" + url + "' returned wrong number of nodes (Expected " + nodesCount + " but got " + body.getObject().getJSONObject("nodes").length() + ")");
        return false;
    }

    LOGGER.debug("Polling Elasticsearch endpoint '" + url + "' succeeded");
    return true;
}
 
Example #19
Source File: HttpClientLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void shouldReturnStatusOkay() throws UnirestException {
    HttpResponse<JsonNode> jsonResponse = Unirest.get("http://www.mocky.io/v2/5a9ce37b3100004f00ab5154")
        .header("accept", "application/json")
        .queryString("apiKey", "123")
        .asJson();
    assertNotNull(jsonResponse.getBody());
    assertEquals(200, jsonResponse.getStatus());
}
 
Example #20
Source File: CustomHttpClient.java    From openvidu with Apache License 2.0 5 votes vote down vote up
private JsonObject commonRest(HttpMethod method, String path, String body, int status) throws Exception {
	HttpResponse<?> jsonResponse = null;
	JsonObject json = null;
	path = openviduUrl + (path.startsWith("/") ? path : ("/" + path));

	HttpRequest request = null;
	if (body != null && !body.isEmpty()) {
		switch (method) {
		case POST:
			request = Unirest.post(path);
			break;
		case PUT:
			request = Unirest.put(path);
			break;
		case PATCH:
		default:
			request = Unirest.patch(path);
			break;
		}
		((HttpRequestWithBody) request).header("Content-Type", "application/json").body(body.replaceAll("'", "\""));
	} else {
		switch (method) {
		case GET:
			request = Unirest.get(path);
			request.header("Content-Type", "application/x-www-form-urlencoded");
			break;
		case POST:
			request = Unirest.post(path);
			break;
		case DELETE:
			request = Unirest.delete(path);
			request.header("Content-Type", "application/x-www-form-urlencoded");
			break;
		case PUT:
			request = Unirest.put(path);
		default:
			break;
		}
	}

	request = request.header("Authorization", this.headerAuth);
	try {
		jsonResponse = request.asJson();
		if (jsonResponse.getBody() != null) {
			jsonResponse.getBody();
			json = JsonParser.parseString(((JsonNode) jsonResponse.getBody()).getObject().toString())
					.getAsJsonObject();
		}
	} catch (UnirestException e) {
		try {
			if (e.getCause().getCause().getCause() instanceof org.json.JSONException) {
				try {
					jsonResponse = request.asString();
				} catch (UnirestException e1) {
					throw new Exception("Error sending request to " + path + ": " + e.getMessage());
				}
			} else {
				throw new Exception("Error sending request to " + path + ": " + e.getMessage());
			}
		} catch (NullPointerException e2) {
			throw new Exception("Error sending request to " + path + ": " + e.getMessage());
		}
	}

	if (jsonResponse.getStatus() == 500) {
		log.error("Internal Server Error: {}", jsonResponse.getBody().toString());
	}

	if (status != jsonResponse.getStatus()) {
		System.err.println(jsonResponse.getBody().toString());
		throw new Exception(path + " expected to return status " + status + " but got " + jsonResponse.getStatus());
	}

	return json;
}
 
Example #21
Source File: Client.java    From pact-workshop-jvm with Apache License 2.0 5 votes vote down vote up
private Optional<JsonNode> loadProviderJson(String dateTime) throws UnirestException {
  HttpRequest getRequest = Unirest.get(url + "/provider.json");

  if (StringUtils.isNotEmpty(dateTime)) {
    getRequest = getRequest.queryString("validDate", dateTime);
  }

  HttpResponse<JsonNode> jsonNodeHttpResponse = getRequest.asJson();
  if (jsonNodeHttpResponse.getStatus() == 200) {
    return Optional.of(jsonNodeHttpResponse.getBody());
  } else {
    return Optional.empty();
  }
}
 
Example #22
Source File: CoinExchangeRate.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
/**
 * 每小时同步一次价格
 *
 * @throws UnirestException
 */
@Scheduled(cron = "0 0 * * * *")
public void syncPrice() throws UnirestException {
    String url = "https://forex.1forge.com/1.0.2/quotes";
    HttpResponse<JsonNode> resp = Unirest.get(url)
            .queryString("pairs", "USDCNH,USDJPY,USDHKD,SGDCNH")
            .queryString("api_key", "y4lmqQRykolHFp3VkzjYp2XZfgCdo8Tv")
            .asJson();
    log.info("forex result:{}", resp.getBody());
    JSONArray result = JSON.parseArray(resp.getBody().toString());
    result.forEach(json -> {
        JSONObject obj = (JSONObject) json;
        if ("USDCNH".equals(obj.getString("symbol"))) {
            setUsdCnyRate(new BigDecimal(obj.getDouble("price")).setScale(2, RoundingMode.DOWN));
            log.info(obj.toString());
        } else if ("USDJPY".equals(obj.getString("symbol"))) {
            setUsdJpyRate(new BigDecimal(obj.getDouble("price")).setScale(2, RoundingMode.DOWN));
            log.info(obj.toString());
        } else if ("USDHKD".equals(obj.getString("symbol"))) {
            setUsdHkdRate(new BigDecimal(obj.getDouble("price")).setScale(2, RoundingMode.DOWN));
            log.info(obj.toString());
        } else if("SGDCNH".equals(obj.getString("symbol"))){
            setSgdCnyRate(new BigDecimal(obj.getDouble("price")).setScale(2,RoundingMode.DOWN));
            log.info(obj.toString());
        }
    });
}
 
Example #23
Source File: CSVSparkTransformServerNoJsonTest.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
@Test
    public void testServer() throws Exception {
        assertTrue(server.getTransform() == null);
        JsonNode jsonStatus = Unirest.post("http://localhost:9050/transformprocess")
                        .header("accept", "application/json").header("Content-Type", "application/json")
                        .body(transformProcess.toJson()).asJson().getBody();
        assumeNotNull(server.getTransform());

        String[] values = new String[] {"1.0", "2.0"};
        SingleCSVRecord record = new SingleCSVRecord(values);
        JsonNode jsonNode =
                        Unirest.post("http://localhost:9050/transformincremental").header("accept", "application/json")
                                        .header("Content-Type", "application/json").body(record).asJson().getBody();
        SingleCSVRecord singleCsvRecord = Unirest.post("http://localhost:9050/transformincremental")
                        .header("accept", "application/json").header("Content-Type", "application/json").body(record)
                        .asObject(SingleCSVRecord.class).getBody();

        BatchCSVRecord batchCSVRecord = new BatchCSVRecord();
        for (int i = 0; i < 3; i++)
            batchCSVRecord.add(singleCsvRecord);
    /*    BatchCSVRecord batchCSVRecord1 = Unirest.post("http://localhost:9050/transform")
                        .header("accept", "application/json").header("Content-Type", "application/json")
                        .body(batchCSVRecord).asObject(BatchCSVRecord.class).getBody();

        Base64NDArrayBody array = Unirest.post("http://localhost:9050/transformincrementalarray")
                        .header("accept", "application/json").header("Content-Type", "application/json").body(record)
                        .asObject(Base64NDArrayBody.class).getBody();
*/
        Base64NDArrayBody batchArray1 = Unirest.post("http://localhost:9050/transformarray")
                        .header("accept", "application/json").header("Content-Type", "application/json")
                        .body(batchCSVRecord).asObject(Base64NDArrayBody.class).getBody();



    }
 
Example #24
Source File: Owl2Neo4J.java    From owl2neo4j with MIT License 5 votes vote down vote up
private void initTransaction () {
    // Fire empty statement to initialize transaction
    try {
        HttpResponse<JsonNode> response = Unirest.post(
            this.server_root_url + TRANSACTION_ENDPOINT)
                .body("{\"statements\":[]}")
                .asJson();
        Headers headers = response.getHeaders();
        String location = "";
        if (headers.containsKey("location")) {
            location = headers.get("location").toString();
            this.transaction = location.substring(
                location.lastIndexOf("/"),
                location.length() -1
            );
        }
        if (this.verbose_output) {
            System.out.println(
                "Transaction initialized. Commit at " +
                    location +
                    " [Neo4J status:" +
                    Integer.toString(response.getStatus()) +
                    "]"
            );
        }
        checkForError(response);
    } catch (Exception e) {
        print_error(ANSI_RESET_DIM + "Error initiating transaction");
        print_error(e.getMessage());
        System.exit(1);
    }
}
 
Example #25
Source File: HttpClientLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
public void givenFileWhenUploadedThenCorrect() throws UnirestException {

        HttpResponse<JsonNode> jsonResponse = Unirest.post("http://www.mocky.io/v2/5a9ce7663100006800ab515d")
            .field("file", new File("/path/to/file"))
            .asJson();
        assertEquals(201, jsonResponse.getStatus());
    }
 
Example #26
Source File: Owl2Neo4J.java    From owl2neo4j with MIT License 5 votes vote down vote up
private static void checkForError (HttpResponse<JsonNode> response) throws Exception {
    JSONObject jsonResponse = response.getBody().getObject();
    JSONArray errors = (JSONArray) jsonResponse.get("errors");
    if (errors.length() > 0) {
        JSONObject error = (JSONObject) errors.get(0);
        String errorMsg = error.get("code").toString() + ": \"" + error.get("message").toString() + "\"";
        throw new Exception(errorMsg);
    }
}
 
Example #27
Source File: Tool.java    From Design-Patterns-and-SOLID-Principles-with-Java with MIT License 5 votes vote down vote up
public static void main(String[] args) {
    Map<Customer, JSONArray> allTodos = new HashMap<>();
    try {
        CustomerDao dao = new DbCustomerDao();
        Collection<Customer> customers = dao.getCustomers();
        for (Customer customer : customers) {
            JsonNode body = Unirest.get("http://localhost:3000/todos")
                .queryString("userId", customer.getId())
                .asJson()
                .getBody();
            JSONArray todos = body.getArray();
            allTodos.put(customer, todos);
        }
    } catch (WarehouseException | UnirestException ex) {
        System.err.printf("Problem during execution: %s%n", ex.getMessage());
    }

    allTodos.entrySet()
        .stream()
        .sorted((a, b) -> Integer.compare(b.getValue().length(), a.getValue().length()))
        .limit(3L)
        .collect(Collectors.toList())
        .forEach(e -> System.out.printf("%s - %s (%s)%n",
            e.getKey().getId(),
            e.getKey().getName(),
            e.getValue().length()));
}
 
Example #28
Source File: MesosContainerImpl.java    From minimesos with Apache License 2.0 5 votes vote down vote up
@Override
public JSONObject getStateInfoJSON() throws UnirestException {
    String stateUrl = getStateUrl();
    GetRequest request = Unirest.get(stateUrl);
    HttpResponse<JsonNode> response = request.asJson();
    return response.getBody().getObject();
}
 
Example #29
Source File: BosonNLPWordSegmenter.java    From elasticsearch-analysis-bosonnlp with Apache License 2.0 5 votes vote down vote up
/**
 * Get the token result from BosonNLP word segmenter.
 * 
 * @param jn
 */
private void makeToken(JsonNode jn) {
    try {
        // Get Json-array as it encoded before
        JSONArray jaTemp = jn.getArray();
        if (jaTemp.length() > 0) {
            JSONObject jo = jaTemp.getJSONObject(0);
            if (jo != null && jo.has("word")) {
                JSONArray ja = jo.getJSONArray("word");

                for (int i = 0; i < ja.length(); i++) {
                    this.words.add(ja.get(i).toString());
                }
            } else {
                logger.error("Check the validation of your API TOKEN or internet",
                        new UnirestException(jo.toString()), jo);
                throw new RuntimeException("Check validation of API TOKEN or internet: " + jo.toString());
            }
        } else {
            logger.info("No string input", jaTemp);
        }
            
    } catch (JSONException e) {
        logger.error("JSONException", e, e);
        throw new RuntimeException("JSONException");
    } finally {
        // Assign to words iterator
        this.wordsIter = this.words.iterator();
    }
}
 
Example #30
Source File: HttpBasedClient.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
@Override
public ActionResponse delete(String index, String type, String id) {
  ActionResponse response = null;
  try {
    final HttpRequest request = Unirest.delete(getUrl(index, type, id, true));
    if (StringUtils.isNotEmpty(username)) {
      request.basicAuth(username, password);
    }

    final HttpResponse<String> result = request.asString();
    final boolean isSucceeded = isSucceeded(result);

    if (isSucceeded) {
      final JsonNode body = new JsonNode(result.getBody());
      response = new ActionResponse()
          .succeeded(true)
          .hit(new HitWrapper(
              getFieldAsString(body, "_index"),
              getFieldAsString(body, "_type"),
              getFieldAsString(body, "_id"),
              null));
    } else {
      throw new ActionException(result.getBody());
    }
  } catch (final UnirestException e) {
    throw new ActionException(e);
  }
  return response;
}