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

The following examples show how to use com.mashape.unirest.http.exceptions.UnirestException. These examples are extracted from open source projects. 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 Project: compliance   Source File: Get.java    License: 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 2
@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 3
Source Project: elepy   Source File: BasicFunctionalityTest.java    License: 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 4
Source Project: api-snippets   Source File: use-add-on-data.7.x.java    License: 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 5
Source Project: compliance   Source File: BioMetadataSearchIT.java    License: 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 6
Source Project: compliance   Source File: ContinuousSetsGetByIdIT.java    License: 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 7
Source Project: compliance   Source File: ReadGroupSetsSearchIT.java    License: 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 8
Source Project: elasticsearch   Source File: ESTasks.java    License: 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 9
@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 10
Source Project: alpaca-java   Source File: AbstractRequest.java    License: 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 11
Source Project: compliance   Source File: ReferenceBasesSearchIT.java    License: 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 12
Source Project: compliance   Source File: Utils.java    License: 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 13
Source Project: flink   Source File: PrometheusReporterTaskScopeTest.java    License: 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 14
Source Project: compliance   Source File: ReadGroupSetsSearchIT.java    License: 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 15
Source Project: blueocean-plugin   Source File: BitbucketServerScmTest.java    License: 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 16
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 Project: compliance   Source File: Utils.java    License: 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 18
Source Project: kafka-connect-github-source   Source File: GitHubSourceTaskTest.java    License: 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 19
Source Project: compliance   Source File: VariantsPagingIT.java    License: 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 20
Source Project: apicurio-studio   Source File: GitHubSourceConnector.java    License: 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 21
Source Project: blueocean-plugin   Source File: GithubEnterpriseApiTest.java    License: 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 22
Source Project: compliance   Source File: CallSetsSearchResponseCheckIT.java    License: 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 23
Source Project: elepy   Source File: BasicFunctionalityTest.java    License: 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 24
Source Project: compliance   Source File: ReferenceSetsSearchIT.java    License: 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 25
Source Project: df_data_service   Source File: SchemaRegistryClient.java    License: Apache License 2.0 5 votes vote down vote up
public static void addSchemaIfNotAvailable(Properties properties) {

        String schemaUri;
        String subject = properties.getProperty(ConstantApp.PK_SCHEMA_SUB_OUTPUT);
        String schemaString = properties.getProperty(ConstantApp.PK_SCHEMA_STR_OUTPUT);
        String srKey = ConstantApp.PK_KAFKA_SCHEMA_REGISTRY_HOST_PORT.replace("_", ".");

        if (properties.getProperty(srKey) == null) {
            schemaUri = "http://localhost:8081";
        } else {
            schemaUri = "http://" + properties.getProperty(srKey);
        }

        String schemaRegistryRestURL = schemaUri + "/subjects/" + subject + "/versions";

        try {
            HttpResponse<String> schemaRes = Unirest.get(schemaRegistryRestURL + "/latest")
                    .header("accept", HTTP_HEADER_APPLICATION_JSON_CHARSET)
                    .asString();

            if(schemaRes.getStatus() == ConstantApp.STATUS_CODE_NOT_FOUND) { // Add the meta sink schema
                Unirest.post(schemaRegistryRestURL)
                        .header("accept", HTTP_HEADER_APPLICATION_JSON_CHARSET)
                        .header("Content-Type", AVRO_REGISTRY_CONTENT_TYPE)
                        .body(schemaString).asString();
                LOG.info("Subject - " + subject + " Not Found, so create it.");
            } else {
                LOG.info("Subject - " + subject + " Found.");
            }
        } catch (UnirestException ue) {
            ue.printStackTrace();
        }
    }
 
Example 26
Source Project: Flink-CEPplus   Source File: PrometheusReporterTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@link io.prometheus.client.Counter} may not decrease, so report {@link Counter} as {@link io.prometheus.client.Gauge}.
 *
 * @throws UnirestException Might be thrown on HTTP problems.
 */
@Test
public void counterIsReportedAsPrometheusGauge() throws UnirestException {
	Counter testCounter = new SimpleCounter();
	testCounter.inc(7);

	assertThatGaugeIsExported(testCounter, "testCounter", "7.0");
}
 
Example 27
Source Project: compliance   Source File: ReferenceSetsPagingIT.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Check that we can page 1 by 1 through the {@link ReferenceSet}s we receive from
 * {@link Client.References#searchReferenceSets(SearchReferenceSetsRequest)}.
 * <p>
 * The call to retrieve all {@link ReferenceSet}s may return fewer than all of them, subject to
 * server-imposed limits.  The 1-by-1 paging must enumerate them all, however.  The set of "all"
 * must be a subset of those gathered one-by-one.
 * </p>
 *
 * @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 checkPagingOneByOneThroughReferenceSets() throws InvalidProtocolBufferException, UnirestException, GAWrapperException {
    // retrieve them all - this may return fewer than "all," however.
    final List<ReferenceSet> listOfReferenceSets = Utils.getAllReferenceSets(client);
    assertThat(listOfReferenceSets).isNotEmpty();

    // we will do a set comparison after retrieving them 1 at a time
    final Set<ReferenceSet> setOfExpectedReferenceSets = new HashSet<>(listOfReferenceSets);
    assertThat(listOfReferenceSets).hasSize(setOfExpectedReferenceSets.size());

    final Set<ReferenceSet> setOfReferenceSetsGathered1By1 = new HashSet<>(setOfExpectedReferenceSets.size());
    // page through the ReferenceSets using the same query parameters and collect them
    String pageToken = "";
    do {
        final SearchReferenceSetsRequest pageReq =
                SearchReferenceSetsRequest.newBuilder()
                                       .setPageSize(1)
                                       .setPageToken(pageToken)
                                       .build();
        final SearchReferenceSetsResponse pageResp = client.references.searchReferenceSets(pageReq);
        final List<ReferenceSet> pageOfReferenceSets = pageResp.getReferenceSetsList();
        pageToken = pageResp.getNextPageToken();

        assertThat(pageOfReferenceSets).hasSize(1);
        setOfReferenceSetsGathered1By1.add(pageOfReferenceSets.get(0));

    } while (pageToken != null && !pageToken.equals(""));

    assertThat(setOfReferenceSetsGathered1By1).containsAll(setOfExpectedReferenceSets);
}
 
Example 28
Source Project: javabank   Source File: Client.java    License: MIT License 5 votes vote down vote up
public int getImposterCount() {
    try {
        HttpResponse<JsonNode> response = Unirest.get(baseUrl + "/imposters").asJson();
        return ((JSONArray) response.getBody().getObject().get("imposters")).length();
    } catch (UnirestException e) {
        return -1;
    }
}
 
Example 29
Source Project: scava   Source File: RedmineRestClient.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public RedmineComment getComment(int issueId, int commentId)
		throws JsonProcessingException, UnirestException, IOException {
	RedmineIssue issue = getIssue(issueId);
	if (null != issue) {
		for (BugTrackingSystemComment comment : issue.getComments()) {
			if (comment.getCommentId().equals(commentId)) {
				return (RedmineComment) comment;
			}
		}
	}

	return null;
}
 
Example 30
public SourceForgeComment getComment(int ticketId, String slug)
		throws JsonParseException, JsonMappingException, IOException,
		UnirestException {
	SourceForgeTicket ticket = getTicket(ticketId);
	if (null != ticket) {
		for (BugTrackingSystemComment comment : ticket.getComments()) {
			if (comment.getCommentId().equals(slug)) {
				return (SourceForgeComment) comment;
			}
		}
	}
	return null;
}