com.mashape.unirest.http.exceptions.UnirestException Java Examples

The following examples show how to use com.mashape.unirest.http.exceptions.UnirestException. 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: PrometheusReporterTaskScopeTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@Test
public void gaugesCanBeAddedSeveralTimesIfTheyDifferInLabels() throws UnirestException {
	Gauge<Integer> gauge1 = new Gauge<Integer>() {
		@Override
		public Integer getValue() {
			return 3;
		}
	};
	Gauge<Integer> gauge2 = new Gauge<Integer>() {
		@Override
		public Integer getValue() {
			return 4;
		}
	};

	taskMetricGroup1.gauge("my_gauge", gauge1);
	taskMetricGroup2.gauge("my_gauge", gauge2);

	assertThat(CollectorRegistry.defaultRegistry.getSampleValue("flink_taskmanager_job_task_my_gauge", LABEL_NAMES, labelValues1),
		equalTo(3.));
	assertThat(CollectorRegistry.defaultRegistry.getSampleValue("flink_taskmanager_job_task_my_gauge", LABEL_NAMES, labelValues2),
		equalTo(4.));
}
 
Example #2
Source File: ContinuousSetsGetByIdIT.java    From compliance with Apache License 2.0 6 votes vote down vote up
/**
 * Verify that ContinuousSets that we obtain by way of {@link ga4gh.SequenceAnnotationServiceOuterClass.SearchContinuousSetsRequest }
 * match the ones we get via <tt>GET /continuousSets/{id}</tt>.
 * @throws GAWrapperException if the server finds the request invalid in some way
 * @throws UnirestException if there's a problem speaking HTTP to the server
 * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server
 */
@Test
public void checkContinuousSetsGetResults() throws InvalidProtocolBufferException, UnirestException, GAWrapperException {
    final int expectedNumberOfContinuousSets = 1;

    final List<ContinuousSet> continuousSets = Utils.getAllContinuousSets(client);

    assertThat(continuousSets).hasSize(expectedNumberOfContinuousSets);

    for (final ContinuousSet continuousSetFromSearch : continuousSets) {
        final ContinuousSet continuousSetFromGet = client.sequenceAnnotations.getContinuousSet(continuousSetFromSearch.getId());
        assertThat(continuousSetFromGet).isNotNull();

        assertThat(continuousSetFromGet).isEqualTo(continuousSetFromSearch);
    }

}
 
Example #3
Source File: BioMetadataSearchIT.java    From compliance with Apache License 2.0 6 votes vote down vote up
/**
 * Tests the /biosamples/search endpoint to ensure that searching
 * by individual ID returns properly formed results.
 * @throws GAWrapperException if the server finds the request invalid in some way
 * @throws UnirestException if there's a problem speaking HTTP to the server
 * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server
 */
@Test
public void checkSearchBiosamplesByIndividual() throws InvalidProtocolBufferException, UnirestException, GAWrapperException {
    // search biosamples for a known name
    final SearchIndividualsRequest ireq =
            SearchIndividualsRequest.newBuilder()
                    .setDatasetId(TestData.getDatasetId())
                    .setName(TestData.INDIVIDUAL_NAME)
                    .build();

    final SearchIndividualsResponse iresp = client.bioMetadata.searchIndividuals(ireq);
    final String individualId = iresp.getIndividualsList().get(0).getId();

    final SearchBiosamplesRequest req =
            SearchBiosamplesRequest.newBuilder()
                    .setDatasetId(TestData.getDatasetId())
                    .setIndividualId(individualId)
                    .build();

    final SearchBiosamplesResponse resp = client.bioMetadata.searchBiosamples(req);
    assertThat(resp).isNotNull();
    for (Biosample b : resp.getBiosamplesList()) {
        assertThat(b.getIndividualId()).isEqualTo(individualId);
    }
}
 
Example #4
Source File: ReadGroupSetsSearchIT.java    From compliance with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve all {@link ReadGroup}s and make sure they all contain a non-null <tt>{@link ReadGroup#getAttributes()}</tt>
 * field.  If it's non-null, it must perforce be a {@link Map}.  The contents of the {@link Map} don't concern
 * us.
 *
 * @throws GAWrapperException if the server finds the request invalid in some way
 * @throws UnirestException if there's a problem speaking HTTP to the server
 * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server
 */
@Test
public void allReadGroupsShouldContainInfoMap() throws InvalidProtocolBufferException, UnirestException, GAWrapperException {
    final SearchReadGroupSetsRequest req =
            SearchReadGroupSetsRequest.newBuilder()
                                      .setDatasetId(TestData.getDatasetId())
                                      .build();
    final SearchReadGroupSetsResponse resp = client.reads.searchReadGroupSets(req);
    final List<ReadGroupSet> readGroupSets = resp.getReadGroupSetsList();

    for (ReadGroupSet readGroupSet : readGroupSets) {
        for (ReadGroup readGroup : readGroupSet.getReadGroupsList()) {
            assertThat(readGroup.getAttributes()).isNotNull();
        }
    }
}
 
Example #5
Source File: CallSetsSearchResponseCheckIT.java    From compliance with Apache License 2.0 6 votes vote down vote up
/**
 * Tests to ensure that when requesting callsets using the Biosample Id filter that
 * only callsets with the given Biosample Id are returned.
 * @throws GAWrapperException if the server finds the request invalid in some way
 * @throws UnirestException if there's a problem speaking HTTP to the server
 * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server
 */
@Test
public void searchCallSetsByBiosampleId() throws GAWrapperException, UnirestException, InvalidProtocolBufferException {
    final Biosample biosample = Utils.getBiosampleByName(client, TestData.BIOSAMPLE_NAME);

    // grab the first VariantSet and use it as source of CallSets
    final VariantSet variantSet = Utils.getVariantSetByName(client, TestData.VARIANTSET_NAME);
    final String variantSetId = variantSet.getId();

    final SearchCallSetsRequest callSetsSearchRequest =
            SearchCallSetsRequest.newBuilder()
                    .setVariantSetId(variantSetId)
                    .setBiosampleId(biosample.getId())
                    .build();
    final SearchCallSetsResponse csResp = client.variants.searchCallSets(callSetsSearchRequest);
    assertThat(csResp.getCallSetsList()).isNotEmpty();
    for (CallSet cs: csResp.getCallSetsList()) {
        assertThat(cs.getBiosampleId()).isEqualTo(biosample.getId());
    }
}
 
Example #6
Source File: use-add-on-data.7.x.java    From api-snippets with MIT License 6 votes vote down vote up
@RequestMapping(value = "/recording",
        produces = "application/xml",
        consumes = "application/json",
        method = {RequestMethod.POST, RequestMethod.PUT})
public ResponseEntity<String> callback(@RequestParam("AddOns") String addOns) throws UnirestException {
    // If the Watson Speech to Text add-on found nothing, return immediately
    ReadContext addonsContext = JsonPath.parse(addOns);
    Map<String, Object> results = addonsContext.read("$.results");
    if(!results.containsKey("ibm_watson_speechtotext")) {
        return new ResponseEntity<>(
                "Add Watson Speech to Text add-on in your Twilio console", HttpStatus.OK);
    }

    // Retrieve the Watson Speech to Text add-on results
    String payloadUrl = addonsContext.read("$.results['ibm_watson_speechtotext'].payload[0].url");
    HttpResponse<String> response = Unirest
            .get(payloadUrl)
            .basicAuth(ACCOUNT_SID, AUTH_TOKEN)
            .asString();

    DocumentContext speechToTextContext = JsonPath.parse(response.getBody());
    List<String> transcripts = speechToTextContext
            .read("$.results[0].results[*].alternatives[0].transcript");

    return new ResponseEntity<>(String.join("", transcripts), HttpStatus.OK);
}
 
Example #7
Source File: ReferenceSetsSearchIT.java    From compliance with Apache License 2.0 6 votes vote down vote up
/**
 * Verify that all found references identify the right species (NCBI Taxonomy ID).
 *
 * @throws GAWrapperException if the server finds the request invalid in some way
 * @throws UnirestException if there's a problem speaking HTTP to the server
 * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server
 */
@Test
public void checkTaxonIdOfReferenceSets() throws InvalidProtocolBufferException, UnirestException, GAWrapperException {
    final SearchReferenceSetsRequest req =
            SearchReferenceSetsRequest.newBuilder().build();
    final SearchReferenceSetsResponse resp = client.references.searchReferenceSets(req);

    final List<ReferenceSet> refSets = resp.getReferenceSetsList();
    assertThat(refSets).isNotEmpty();

    refSets.stream().forEach(rs ->{ 
        OntologyTerm ot = rs.getSpecies();
        assertThat(ot.getTermId()).isEqualTo(TestData.REFERENCESET_SPECIES_ID);
        assertThat(ot.getTerm()).isEqualTo(TestData.REFERENCESET_SPECIES_TERM);
    });
}
 
Example #8
Source File: BasicFunctionalityTest.java    From elepy with Apache License 2.0 6 votes vote down vote up
@Test
public void canNot_FindItems_when_QueryDoesntMatch() throws IOException, UnirestException {
    Resource resource = validObject();
    resource.setUniqueField("testSearchNotFindingAnything");
    resource.setNumberMax40(BigDecimal.valueOf(25));
    resourceCrud.create(resource);
    resourceCrud.create(validObject());

    final HttpResponse<String> getRequest = Unirest.get(elepy + "/resources?q=ilterUni").asString();


    List<Resource> results = elepy.objectMapper().readValue(getRequest.getBody(), new TypeReference<List<Resource>>() {
    });

    assertThat(getRequest.getStatus()).as(getRequest.getBody()).isEqualTo(200);
    assertThat(results.size()).isEqualTo(0);
}
 
Example #9
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 #10
Source File: PrometheusReporterTaskScopeTest.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
@Test
public void gaugesCanBeAddedSeveralTimesIfTheyDifferInLabels() throws UnirestException {
	Gauge<Integer> gauge1 = new Gauge<Integer>() {
		@Override
		public Integer getValue() {
			return 3;
		}
	};
	Gauge<Integer> gauge2 = new Gauge<Integer>() {
		@Override
		public Integer getValue() {
			return 4;
		}
	};

	taskMetricGroup1.gauge("my_gauge", gauge1);
	taskMetricGroup2.gauge("my_gauge", gauge2);

	assertThat(CollectorRegistry.defaultRegistry.getSampleValue("flink_taskmanager_job_task_my_gauge", LABEL_NAMES, labelValues1),
		equalTo(3.));
	assertThat(CollectorRegistry.defaultRegistry.getSampleValue("flink_taskmanager_job_task_my_gauge", LABEL_NAMES, labelValues2),
		equalTo(4.));
}
 
Example #11
Source File: BasicFunctionalityTest.java    From elepy with Apache License 2.0 6 votes vote down vote up
@Test
public void can_SearchItems_as_Intended() throws IOException, UnirestException {
    Resource resource = validObject();
    resource.setUniqueField("testSearchTo2");
    resource.setNumberMax40(BigDecimal.valueOf(25));
    resourceCrud.create(resource);
    resourceCrud.create(validObject());
    final HttpResponse<String> getRequest = Unirest.get(elepy + "/resources?q=testsearchto").asString();


    List<Resource> results = elepy.objectMapper().readValue(getRequest.getBody(), new TypeReference<List<Resource>>() {
    });

    assertThat(getRequest.getStatus()).as(getRequest.getBody()).isEqualTo(200);
    assertThat(results.size()).isEqualTo(1);
}
 
Example #12
Source File: GithubEnterpriseApiTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void fetchExistingCredentialNotExists() throws IOException, UnirestException {
    // create a credential using default apiUrl
    createGithubEnterpriseCredential();

    String bogusUrl = "https://foo.com";

    // look up credential for apiUrl that's invalid
    Map r = new RequestBuilder(baseUrl)
        .status(200)
        .jwtToken(getJwtToken(j.jenkins, user.getId(), user.getId()))
        .get("/organizations/jenkins/scm/github-enterprise/?apiUrl="+bogusUrl)
        .build(Map.class);

    assertNull(r.get("credentialId"));
    assertEquals(bogusUrl, r.get("uri"));
}
 
Example #13
Source File: DifferentESVersionSystemTest.java    From elasticsearch with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldStartJar() {
    // Don't forward traffic. Jars are actually running on the slaves
    final JarESVersionScheduler scheduler = new JarESVersionScheduler(dockerClient, cluster.getZooKeeper().getIpAddress(), cluster, ES_BINARY);
    cluster.addAndStartProcess(scheduler, TEST_CONFIG.getClusterTimeout());
    LOG.info("Started Elasticsearch scheduler on " + scheduler.getIpAddress() + ":" + TEST_CONFIG.getSchedulerGuiPort());

    ESTasks esTasks = new ESTasks(TEST_CONFIG, scheduler.getIpAddress());
    new TasksResponse(esTasks, TEST_CONFIG.getElasticsearchNodesCount());

    ElasticsearchNodesResponse nodesResponse = new ElasticsearchNodesResponse(esTasks, TEST_CONFIG.getElasticsearchNodesCount());
    assertTrue("Elasticsearch nodes did not discover each other within 5 minutes", nodesResponse.isDiscoverySuccessful());

    final AtomicReference<String> versionNumber = new AtomicReference<>("");
    Awaitility.await().pollInterval(1L, TimeUnit.SECONDS).atMost(TEST_CONFIG.getClusterTimeout(), TimeUnit.SECONDS).until(() -> {
        try {
            versionNumber.set(Unirest.get("http://" + esTasks.getEsHttpAddressList().get(0)).asJson().getBody().getObject().getJSONObject("version").getString("number"));
            return true;
        } catch (UnirestException e) {
            return false;
        }
    });
    assertEquals("ES version is not the same as requested: " + ES_VERSION + " != " + versionNumber.get(), ES_VERSION, versionNumber.get());
}
 
Example #14
Source File: ESTasks.java    From elasticsearch with Apache License 2.0 6 votes vote down vote up
public void waitForCorrectDocumentCount(Integer docCount) throws UnirestException {
    List<String> esAddresses = getEsHttpAddressList();
    Awaitility.await().atMost(1, TimeUnit.MINUTES).pollDelay(2, TimeUnit.SECONDS).until(() -> {
        for (String httpAddress : esAddresses) {
            try {
                Integer count = getDocumentCount(httpAddress);
                if (docCount != 0 && (count == 0 || count % docCount != 0)) { // This allows for repeated testing. Only run if docCount != 0.
                    return false;
                }
            } catch (Exception e) {
                LOGGER.error("Unirest exception:" + e.getMessage());
                return false;
            }
        }
        return true;
    });
}
 
Example #15
Source File: Utils.java    From compliance with Apache License 2.0 6 votes vote down vote up
/**
 * Search for and return all {@link Variant} objects in the {@link VariantSet} with ID
 * <tt>variantSetId</tt>, from <tt>start</tt> to <tt>end</tt>.
 * @param client the connection to the server
 * @param variantSetId the ID of the {@link VariantSet}
 * @param start the start of the range to search
 * @param end the end of the range to search
 * @return the {@link List} of results
 * @throws GAWrapperException if the server finds the request invalid in some way
 * @throws UnirestException if there's a problem speaking HTTP to the server
 * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server
 */
public static List<Variant> getAllVariantsInRange(Client client,
                                                  String variantSetId,
                                                  long start, long end) throws InvalidProtocolBufferException, UnirestException, GAWrapperException {
    // get all variants in the range
    final List<Variant> result = new LinkedList<>();
    String pageToken = "";

    do {
        final SearchVariantsRequest vReq =
                SearchVariantsRequest.newBuilder()
                        .setVariantSetId(variantSetId)
                        .setReferenceName(TestData.REFERENCE_NAME)
                        .setStart(start).setEnd(end)
                        .setPageSize(100)
                        .setPageToken(pageToken)
                        .build();
        final SearchVariantsResponse vResp = client.variants.searchVariants(vReq);
        pageToken = vResp.getNextPageToken();
        result.addAll(vResp.getVariantsList());
    } while (pageToken != null && !pageToken.equals(""));

    return result;
}
 
Example #16
Source File: MediaWikiAPIPageExtractor.java    From wandora with GNU General Public License v3.0 6 votes vote down vote up
private String getArticleBody(String title) throws IOException{
    StringBuilder queryBuilder = new StringBuilder(this.baseURL)
        .append("/index.php?action=raw&title=")
        .append(URLEncoder.encode(title));

    HttpResponse<InputStream> resp;
    try {
      resp = Unirest.get(queryBuilder.toString())
              .header("accept", "text/x-wiki")
              .asBinary();
    } catch (UnirestException ex) {
      throw new IOException(ex);
    }

    InputStream body = resp.getBody();
    String bodyString = IOUtils.toString(body,"UTF-8"); 
    
    return bodyString;
}
 
Example #17
Source File: ReadGroupSetsSearchIT.java    From compliance with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve all {@link ReadGroup}s and make sure they all have the right dataset ID.
 * (Adapted from one of the JavaScript compliance tests.)
 *
 * @throws GAWrapperException if the server finds the request invalid in some way
 * @throws UnirestException if there's a problem speaking HTTP to the server
 * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server
 */
@Test
public void allReadGroupsShouldHaveCorrectDatasetId() throws InvalidProtocolBufferException, UnirestException, GAWrapperException {
    final SearchReadGroupSetsRequest req =
            SearchReadGroupSetsRequest.newBuilder()
                                      .setDatasetId(TestData.getDatasetId())
                                      .build();
    final SearchReadGroupSetsResponse resp = client.reads.searchReadGroupSets(req);
    final List<ReadGroupSet> readGroupSets = resp.getReadGroupSetsList();

    for (ReadGroupSet readGroupSet : readGroupSets) {
        for (ReadGroup readGroup : readGroupSet.getReadGroupsList()) {
            assertThat(readGroup).isNotNull();
            assertThat(readGroup.getDatasetId()).isEqualTo(TestData.getDatasetId());
        }
    }
}
 
Example #18
Source File: BitbucketServerScmTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void getOrganizationsWithCredentialId() throws IOException, UnirestException {
    String credentialId = createCredential(BitbucketServerScm.ID);
    List orgs = new RequestBuilder(baseUrl)
        .status(200)
        .jwtToken(getJwtToken(j.jenkins, authenticatedUser.getId(), authenticatedUser.getId()))
        .get("/organizations/jenkins/scm/"+BitbucketServerScm.ID+"/organizations/?apiUrl="+apiUrl+"&credentialId="+credentialId)
        .build(List.class);
    assertEquals(3, orgs.size());
    assertEquals("Vivek Pandey", ((Map)orgs.get(0)).get("name"));
    assertEquals("~vivek", ((Map)orgs.get(0)).get("key"));
    assertEquals("test1", ((Map)orgs.get(1)).get("name"));
    assertEquals("TEST", ((Map)orgs.get(1)).get("key"));
    assertEquals("testproject1", ((Map)orgs.get(2)).get("name"));
    assertEquals("TESTP", ((Map)orgs.get(2)).get("key"));
}
 
Example #19
Source File: Utils.java    From compliance with Apache License 2.0 6 votes vote down vote up
/**
 * Search for and return all {@link CallSet}s in the {@link VariantSet} named by <tt>variantSetId</tt>.
 *
 * @param client the connection to the server
 * @param variantSetId the ID of the {@link VariantSet}
 * @return the {@link List} of results
 * @throws GAWrapperException if the server finds the request invalid in some way
 * @throws UnirestException if there's a problem speaking HTTP to the server
 * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server
 */
public static List<CallSet> getAllCallSets(Client client, String variantSetId) throws InvalidProtocolBufferException, UnirestException, GAWrapperException {
    final List<CallSet> result = new LinkedList<>();
    String pageToken = "";
    do {
        final SearchCallSetsRequest callSetsSearchRequest =
                SearchCallSetsRequest.newBuilder()
                        .setPageSize(100)
                        .setPageToken(pageToken)
                        .setVariantSetId(variantSetId)
                        .build();
        final SearchCallSetsResponse csResp = client.variants.searchCallSets(callSetsSearchRequest);
        pageToken = csResp.getNextPageToken();
        result.addAll(csResp.getCallSetsList());
    } while (pageToken != null && !pageToken.equals(""));

    return result;
}
 
Example #20
Source File: ReferenceBasesSearchIT.java    From compliance with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve all {@link Reference} objects for the default {@link ReferenceSet}. Check
 * that each returned {@link Reference} has a valid-looking MD5.  (In the future, perhaps this
 * test should compute the MD5 and compare it to what's returned.)
 *
 * @throws GAWrapperException if the server finds the request invalid in some way
 * @throws UnirestException if there's a problem speaking HTTP to the server
 * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server
 */
@Test
public void checkMD5ChecksumAppearanceOfAllReferences() throws InvalidProtocolBufferException, UnirestException, GAWrapperException {
    final String referenceSetId =
            Utils.getReferenceSetIdByAssemblyId(client, TestData.REFERENCESET_ASSEMBLY_ID);

    final SearchReferencesRequest req =
            SearchReferencesRequest.newBuilder()
                    .setReferenceSetId(referenceSetId)
                    .build();
    final SearchReferencesResponse resp = client.references.searchReferences(req);
    final List<Reference> refs = resp.getReferencesList();
    assertThat(refs).isNotEmpty();

    refs.stream().forEach(ref -> assertThat(Utils.looksLikeValidMd5(ref.getMd5Checksum()))
            .isTrue());
}
 
Example #21
Source File: GitHubSourceTaskTest.java    From kafka-connect-github-source with MIT License 6 votes vote down vote up
@Test
public void test() throws UnirestException {
    gitHubSourceTask.config = new GitHubSourceConnectorConfig(initialConfig());
    gitHubSourceTask.nextPageToVisit = 1;
    gitHubSourceTask.nextQuerySince = Instant.parse("2017-01-01T00:00:00Z");
    gitHubSourceTask.gitHubHttpAPIClient = new GitHubAPIHttpClient(gitHubSourceTask.config);
    String url = gitHubSourceTask.gitHubHttpAPIClient.constructUrl(gitHubSourceTask.nextPageToVisit, gitHubSourceTask.nextQuerySince);
    System.out.println(url);
    HttpResponse<JsonNode> httpResponse = gitHubSourceTask.gitHubHttpAPIClient.getNextIssuesAPI(gitHubSourceTask.nextPageToVisit, gitHubSourceTask.nextQuerySince);
    if (httpResponse.getStatus() != 403) {
        assertEquals(200, httpResponse.getStatus());
        Set<String> headers = httpResponse.getHeaders().keySet();
        assertTrue(headers.contains(X_RATELIMIT_LIMIT_HEADER));
        assertTrue(headers.contains(X_RATELIMIT_REMAINING_HEADER));
        assertTrue(headers.contains(X_RATELIMIT_RESET_HEADER));
        assertEquals(batchSize.intValue(), httpResponse.getBody().getArray().length());
        JSONObject jsonObject = (JSONObject) httpResponse.getBody().getArray().get(0);
        Issue issue = Issue.fromJson(jsonObject);
        assertNotNull(issue);
        assertNotNull(issue.getNumber());
        assertEquals(2072, issue.getNumber().intValue());
    }
}
 
Example #22
Source File: VariantsPagingIT.java    From compliance with Apache License 2.0 6 votes vote down vote up
/**
 * Check that we can receive expected results when we request a single
 * page of variants from {@link org.ga4gh.ctk.transport.protocols.Client.Variants#searchVariants
 * (SearchVariantsRequest)}, using <tt>pageSize</tt> as the page size.
 *
 * @param variantSetId     the ID of the {@link VariantSet} we're paging through
 * @param start            the start value for the range we're searching
 * @param end              the end value for the range we're searching
 * @param pageSize         the page size we'll request
 * @param expectedVariants all of the {@link Variant} objects we expect to receive
 * @throws GAWrapperException if the server finds the request invalid in some way
 * @throws UnirestException if there's a problem speaking HTTP to the server
 * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server
 */
private void checkSinglePageOfVariants(String variantSetId,
                                       long start, long end,
                                       int pageSize,
                                       List<Variant> expectedVariants) throws InvalidProtocolBufferException, UnirestException, GAWrapperException {

    final SearchVariantsRequest pageReq =
            SearchVariantsRequest.newBuilder()
                                 .setVariantSetId(variantSetId)
                                 .setReferenceName(TestData.REFERENCE_NAME)
                                 .setStart(start).setEnd(end)
                                 .setPageSize(pageSize)
                                 .build();
    final SearchVariantsResponse pageResp = client.variants.searchVariants(pageReq);
    final List<Variant> pageOfVariants = pageResp.getVariantsList();
    final String pageToken = pageResp.getNextPageToken();

    assertThat(pageOfVariants).hasSize(expectedVariants.size());
    assertThat(expectedVariants).containsAll(pageOfVariants);

    assertThat(pageToken).isEmpty();
}
 
Example #23
Source File: AbstractRequest.java    From alpaca-java with MIT License 6 votes vote down vote up
/**
 * Invoke head.
 *
 * @param abstractRequestBuilder the abstract request builder
 *
 * @return the http response
 */
public HttpResponse<InputStream> invokeHead(AbstractRequestBuilder abstractRequestBuilder) {
    try {
        String url = abstractRequestBuilder.getURL();

        LOGGER.debug("HEAD URL " + url);

        GetRequest request = Unirest.head(url);

        if (!headers.isEmpty()) {
            request.headers(headers);

            LOGGER.debug("HEAD Headers: " + headers);
        }

        return request.asBinary();
    } catch (UnirestException e) {
        LOGGER.error("UnirestException", e);
    }

    return null;
}
 
Example #24
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 #25
Source File: CredentialApiTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void crumbRejected() throws IOException, UnirestException {
    User user = login();
    HttpClient httpClient = HttpClientBuilder.create().build();

    HttpPost post = new HttpPost( baseUrl + "/organizations/jenkins/credentials/user/" );
    post.addHeader( "Authorization", "Bearer " + getJwtToken(j.jenkins,user.getId(), user.getId()));

    HttpResponse resp =  httpClient.execute( post );
    Assert.assertEquals(403, resp.getStatusLine().getStatusCode());
    //LOGGER.info( IOUtils.toString( resp.getEntity().getContent() ));
    // assert content contains No valid crumb was included in the request
    // olamy not sure as it can be i18n sensitive
}
 
Example #26
Source File: BitbucketServerScmContentProviderTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void unauthorizedSaveContentShouldFail() throws UnirestException, IOException {
    User alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("[email protected]"));

    String aliceCredentialId = createCredential(BitbucketServerScm.ID, alice);
    StaplerRequest staplerRequest = mockStapler();
    MultiBranchProject mbp = mockMbp(aliceCredentialId, alice);

    GitContent content = new GitContent.Builder().autoCreateBranch(true).base64Data("bm9kZXsKICBlY2hvICdoZWxsbyB3b3JsZCEnCn0K")
            .branch("master").message("new commit").owner("TESTP").path("README.md").repo("pipeline-demo-test").build();

    when(staplerRequest.bindJSON(Mockito.eq(BitbucketScmSaveFileRequest.class), Mockito.any(JSONObject.class))).thenReturn(new BitbucketScmSaveFileRequest(content));

    String request = "{\n" +
            "  \"content\" : {\n" +
            "    \"message\" : \"new commit\",\n" +
            "    \"path\" : \"README.md\",\n" +
            "    \"branch\" : \"master\",\n" +
            "    \"repo\" : \"pipeline-demo-test\",\n" +
            "    \"base64Data\" : " + "\"bm9kZXsKICBlY2hvICdoZWxsbyB3b3JsZCEnCn0K\"" +
            "  }\n" +
            "}";

    when(staplerRequest.getReader()).thenReturn(new BufferedReader(new StringReader(request), request.length()));

    try {
        new BitbucketServerScmContentProvider().saveContent(staplerRequest, mbp);
    } catch (ServiceException.PreconditionRequired e) {
        assertEquals("Can't access content from Bitbucket: no credential found", e.getMessage());
        return;
    }
    fail("Should have failed with PreConditionException");
}
 
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 RestCustomerDao();
        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: GithubPipelineCreateRequestTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
    public void createPipelineNoJenkinsFile() throws UnirestException, IOException {
//        AbstractMultiBranchCreateRequest.JenkinsfileCriteria criteria = Mockito.mock(AbstractMultiBranchCreateRequest.JenkinsfileCriteria.class);
//        when(criteria.isJenkinsfileFound()).thenReturn(true);
        OrganizationImpl organization = new OrganizationImpl("jenkins", j.jenkins);
        String credentialId = createGithubCredential(user);

        JSONObject config = JSONObject.fromObject(ImmutableMap.of("repoOwner", "vivek", "repository", "empty1"));

        GithubPipelineCreateRequest request = new GithubPipelineCreateRequest(
                "empty1", new BlueScmConfig(GithubScm.ID, githubApiUrl, credentialId, config));

        request.create(organization, organization);
//        verify(criteria, atLeastOnce()).isJenkinsfileFound();
    }
 
Example #29
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 #30
Source File: CommandProxyServletUnitTest.java    From Scribengin with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testCommandServletBadCommand() throws InterruptedException, UnirestException{
  String badCommand = "xxyyzz";
  HttpResponse<String> resp = Unirest.post("http://localhost:"+Integer.toString(proxyPort))
         .field("command", badCommand)
         .asString();
  
  assertEquals("", resp.getBody());
}