com.mashape.unirest.http.HttpResponse Java Examples

The following examples show how to use com.mashape.unirest.http.HttpResponse. 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: AlpacaAPI.java    From alpaca-java with MIT License 6 votes vote down vote up
/**
 * Returns the market calendar.
 *
 * @param start The first date to retrieve data for (inclusive)
 * @param end   The last date to retrieve data for (inclusive)
 *
 * @return the calendar
 *
 * @throws AlpacaAPIRequestException the alpaca API exception
 * @see <a href="https://docs.alpaca.markets/api-documentation/api-v2/calendar/">Calendar</a>
 */
public ArrayList<Calendar> getCalendar(LocalDate start, LocalDate end) throws AlpacaAPIRequestException {
    AlpacaRequestBuilder urlBuilder = new AlpacaRequestBuilder(baseAPIURL, apiVersion,
            AlpacaConstants.CALENDAR_ENDPOINT);

    if (start != null) {
        urlBuilder.appendURLParameter(AlpacaConstants.START_PARAMETER, TimeUtil.toDateString(start));
    }

    if (end != null) {
        urlBuilder.appendURLParameter(AlpacaConstants.END_PARAMETER, TimeUtil.toDateString(end));
    }

    HttpResponse<InputStream> response = alpacaRequest.invokeGet(urlBuilder);

    if (response.getStatus() != 200) {
        throw new AlpacaAPIRequestException(response);
    }

    Type arrayListType = new TypeToken<ArrayList<Calendar>>() {}.getType();

    return alpacaRequest.getResponseObject(response, arrayListType);
}
 
Example #3
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 #4
Source File: StateMachineResourceTest.java    From flux with Apache License 2.0 6 votes vote down vote up
@Test
public void testPostScheduledEvent_withoutCorrelationIdTag() throws Exception {
    String stateMachineDefinitionJson = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("state_machine_definition.json"));
    Unirest.post(STATE_MACHINE_RESOURCE_URL).header("Content-Type", "application/json").body(stateMachineDefinitionJson).asString();

    String eventJson = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("event_data.json"));

    //request with searchField param missing
    final HttpResponse<String> eventPostResponse = Unirest.post(STATE_MACHINE_RESOURCE_URL + SLASH + "magic_number_1" + "/context/events?triggerTime=123").header("Content-Type", "application/json").body(eventJson).asString();
    assertThat(eventPostResponse.getStatus()).isEqualTo(Response.Status.BAD_REQUEST.getStatusCode());


    //request with searchField param having value other than correlationId
    final HttpResponse<String> eventPostResponseWithWrongTag = Unirest.post(STATE_MACHINE_RESOURCE_URL + SLASH + "magic_number_1" + "/context/events?searchField=dummy&triggerTime=123").header("Content-Type", "application/json").body(eventJson).asString();
    assertThat(eventPostResponseWithWrongTag.getStatus()).isEqualTo(Response.Status.BAD_REQUEST.getStatusCode());
}
 
Example #5
Source File: RestUtil.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
public static Future<HttpResponse<JsonNode>> executeAsync(BaseRequest request) {
  ProjectLogger.log("RestUtil:execute: request url = " + request.getHttpRequest().getUrl());
  Promise<HttpResponse<JsonNode>> promise = Futures.promise();

  request.asJsonAsync(
      new Callback<JsonNode>() {

        @Override
        public void failed(UnirestException e) {
          promise.failure(e);
        }

        @Override
        public void completed(HttpResponse<JsonNode> response) {
          promise.success(response);
        }

        @Override
        public void cancelled() {
          promise.failure(new Exception("cancelled"));
        }
      });

  return promise.future();
}
 
Example #6
Source File: HelloResource.java    From microservices-comparison with Apache License 2.0 6 votes vote down vote up
public String hello (Request request, Response response) {
    String token = readToken(request);
    HttpResponse<Car[]> carHttpResponse;
    try {
        carHttpResponse = Unirest.get("https://localhost:8099/cars")
                .header("Accept", "application/json")
                .header("Authorization", "Bearer " + token)
                .asObject(Car[].class);
    } catch (UnirestException e) {
        throw new RuntimeException(e);
    }
    Car[] cars = carHttpResponse.getBody();
    List<String> carNames = Arrays.stream(cars)
            .map(Car::getName)
            .collect(toList());
    return "We have these cars available: " + carNames;
}
 
Example #7
Source File: PolygonAPI.java    From alpaca-java with MIT License 6 votes vote down vote up
/**
 * The mappings for conditions on trades and quotes.
 *
 * @param conditionMappingsType Ticker type we want mappings for
 *
 * @return the conditions mapping
 *
 * @throws PolygonAPIRequestException the polygon api request exception
 * @see <a href="https://polygon.io/docs/#!/Stocks--Equities/get_v1_meta_conditions_ticktype">Condition Mappings</a>
 */
public ConditionsMapping getConditionsMapping(ConditionMappingsType conditionMappingsType)
        throws PolygonAPIRequestException {
    Preconditions.checkNotNull(conditionMappingsType);

    PolygonRequestBuilder builder = new PolygonRequestBuilder(baseAPIURL, PolygonConstants.VERSION_1_ENDPOINT,
            PolygonConstants.META_ENDPOINT,
            PolygonConstants.CONDITIONS_ENDPOINT,
            conditionMappingsType.getAPIName());

    HttpResponse<InputStream> response = polygonRequest.invokeGet(builder);

    if (response.getStatus() != 200) {
        throw new PolygonAPIRequestException(response);
    }

    return polygonRequest.getResponseObject(response, ConditionsMapping.class);
}
 
Example #8
Source File: Owl2Neo4J.java    From owl2neo4j with MIT License 6 votes vote down vote up
private void commitTransaction () {
    // Fire empty statement to initialize transaction
    try {
        HttpResponse<JsonNode> response = Unirest.post(
            this.server_root_url + TRANSACTION_ENDPOINT + this.transaction + "/commit")
            .body("{\"statements\":[]}")
                .asJson();
        if (this.verbose_output) {
            System.out.println(
                "Transaction committed. [Neo4J status:" +
                Integer.toString(response.getStatus()) +
                "]"
            );
        }
        checkForError(response);
    } catch (Exception e) {
        print_error(ANSI_RESET_DIM + "Error committing transaction");
        print_error(e.getMessage());
        System.exit(1);
    }
}
 
Example #9
Source File: PolygonAPI.java    From alpaca-java with MIT License 6 votes vote down vote up
/**
 * Snapshot allows you to see all tickers current minute aggregate, daily aggregate and last trade. As well as
 * previous days aggregate and calculated change for today.
 *
 * @return the snapshot all tickers
 *
 * @throws PolygonAPIRequestException the polygon API exception
 * @see
 * <a href="https://polygon.io/docs/#!/Stocks--Equities/get_v2_snapshot_locale_us_markets_stocks_tickers">Snapshot
 * - All Tickers</a>
 */
public SnapshotAllTickersResponse getSnapshotAllTickers() throws PolygonAPIRequestException {
    PolygonRequestBuilder builder = new PolygonRequestBuilder(baseAPIURL, PolygonConstants.VERSION_2_ENDPOINT,
            PolygonConstants.SNAPSHOT_ENDPOINT,
            PolygonConstants.LOCALE_ENDPOINT,
            PolygonConstants.US_ENDPOINT,
            PolygonConstants.MARKETS_ENDPOINT,
            PolygonConstants.STOCKS_ENDPOINT,
            PolygonConstants.TICKERS_ENDPOINT);

    HttpResponse<InputStream> response = polygonRequest.invokeGet(builder);

    if (response.getStatus() != 200) {
        throw new PolygonAPIRequestException(response);
    }

    return polygonRequest.getResponseObject(response, SnapshotAllTickersResponse.class);
}
 
Example #10
Source File: RestAction.java    From cognitivej with Apache License 2.0 6 votes vote down vote up
private T doWork() {
    try {
        setupErrorHandlers();
        WorkingContext workingContext = workingContext();
        HttpRequest builtRequest = buildUnirest(workingContext)
                .queryString(workingContext.getQueryParams())
                .headers(workingContext.getHeaders()).header("Ocp-Apim-Subscription-Key", cognitiveContext.subscriptionKey);
        if (!workingContext.getHttpMethod().equals(HttpMethod.GET) && workingContext().getPayload().size() > 0) {
            buildBody((HttpRequestWithBody) builtRequest);
        }
        HttpResponse response;
        if (typedResponse() == InputStream.class)
            response = builtRequest.asBinary();
        else
            response = builtRequest.asString();

        checkForError(response);
        return postProcess(typeResponse(response.getBody()));
    } catch (UnirestException | IOException e) {
        throw new CognitiveException(e);
    }
}
 
Example #11
Source File: TelegramBot.java    From JavaTelegramBot-API with GNU General Public License v3.0 6 votes vote down vote up
/**
 * A method used to get a Chat object via the chats ID
 *
 * @param chatID The Chat ID of the chat you want a Chat object of
 *
 * @return A Chat object or null if the chat does not exist or you don't have permission to get this chat
 */
public Chat getChat(String chatID) {

    try {

        MultipartBody request = Unirest.post(getBotAPIUrl() + "getChat")
                .field("chat_id", chatID, "application/json; charset=utf8;");
        HttpResponse<String> response = request.asString();
        JSONObject jsonResponse = Utils.processResponse(response);

        if (jsonResponse != null && Utils.checkResponseStatus(jsonResponse)) {

            JSONObject result = jsonResponse.getJSONObject("result");

            return ChatImpl.createChat(result, this);
        }
    } catch (UnirestException e) {
        e.printStackTrace();
    }

    return null;
}
 
Example #12
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 #13
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 #14
Source File: HealthChecker.java    From dropwizard-experiment with MIT License 6 votes vote down vote up
public boolean check() throws InterruptedException {
    try {
        HttpResponse<String> health = Unirest.get(url + "/admin/healthcheck")
                .basicAuth("test", "test")
                .asString();

        if (health.getStatus() == 200) {
            log.info("Healthy with {}", health.getBody());
            return true;
        } else {
            log.error("Unhealthy with {}", health.getBody());
            return false;
        }
    } catch (UnirestException e) {
        if (e.getCause() instanceof HttpHostConnectException && duration < maxDuration) {
            log.info("Unable to connect, retrying...");
            duration = duration + DELAY;
            Thread.sleep(TimeUnit.SECONDS.toMillis(DELAY));
            return check();
        }
        log.error("Unable to connect.", e);
        return false;
    }
}
 
Example #15
Source File: StateMachineResourceTest.java    From flux with Apache License 2.0 6 votes vote down vote up
@Test
public void testEventUpdate_taskCancelled() throws Exception {
    String stateMachineDefinitionJson = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream(
            "state_machine_definition.json"));
    final HttpResponse<String> smCreationResponse = Unirest.post(STATE_MACHINE_RESOURCE_URL).header(
            "Content-Type", "application/json").body(stateMachineDefinitionJson).asString();
    Event event = eventsDAO.findBySMIdAndName(smCreationResponse.getBody(), "event0");
    assertThat(event.getStatus()).isEqualTo(Event.EventStatus.pending);

    /* Mark the task path as cancelled. */
    TestWorkflow.shouldCancel = true;
    try {
        testEventUpdate_IneligibleTaskStatus_Util(smCreationResponse);
    } finally {
        TestWorkflow.shouldCancel = false;
    }
}
 
Example #16
Source File: Chat.java    From JavaTelegramBot-API with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Gets the amount of people in the chat
 *
 * @return The amount of people in the chat
 */
default Integer getChatMembersCount() {

    try {

        MultipartBody request = Unirest.post(getBotInstance().getBotAPIUrl() + "getChatMembersCount")
                .field("chat_id", getId(), "application/json; charset=utf8;");
        HttpResponse<String> response = request.asString();
        JSONObject jsonResponse = processResponse(response);

        if (jsonResponse != null && Utils.checkResponseStatus(jsonResponse)) {

            return jsonResponse.getInt("result");
        }
    } catch (UnirestException e) {
        e.printStackTrace();
    }

    return null;
}
 
Example #17
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 #18
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 #19
Source File: PolygonAPI.java    From alpaca-java with MIT License 6 votes vote down vote up
/**
 * List of stock exchanges which are supported by Polygon.io
 *
 * @return the exchanges
 *
 * @throws PolygonAPIRequestException the polygon API exception
 * @see <a href="https://polygon.io/docs/#!/Stocks--Equities/get_v1_meta_exchanges">Exchanges</a>
 */
public ArrayList<Exchange> getExchanges() throws PolygonAPIRequestException {
    PolygonRequestBuilder builder = new PolygonRequestBuilder(baseAPIURL, PolygonConstants.VERSION_1_ENDPOINT,
            PolygonConstants.META_ENDPOINT,
            PolygonConstants.EXCHANGES_ENDPOINT);

    HttpResponse<InputStream> response = polygonRequest.invokeGet(builder);

    if (response.getStatus() != 200) {
        throw new PolygonAPIRequestException(response);
    }

    Type listType = new TypeToken<ArrayList<Exchange>>() {}.getType();

    return polygonRequest.getResponseObject(response, listType);
}
 
Example #20
Source File: AlpacaAPI.java    From alpaca-java with MIT License 6 votes vote down vote up
/**
 * Get a list of assets.
 *
 * @param assetStatus e.g. “active”. By default, all statuses are included.
 * @param assetClass  Defaults to us_equity.
 *
 * @return the assets
 *
 * @throws AlpacaAPIRequestException the alpaca API exception
 * @see <a href="https://docs.alpaca.markets/api-documentation/api-v2/assets/">Assets</a>
 */
public ArrayList<Asset> getAssets(AssetStatus assetStatus, String assetClass) throws AlpacaAPIRequestException {
    AlpacaRequestBuilder urlBuilder = new AlpacaRequestBuilder(baseAPIURL, apiVersion,
            AlpacaConstants.ASSETS_ENDPOINT);

    if (assetStatus != null) {
        urlBuilder.appendURLParameter(AlpacaConstants.STATUS_PARAMETER, assetStatus.getAPIName());
    }

    if (assetClass != null) {
        urlBuilder.appendURLParameter(AlpacaConstants.ASSET_CLASS_PARAMETER, assetClass.trim());
    }

    HttpResponse<InputStream> response = alpacaRequest.invokeGet(urlBuilder);

    if (response.getStatus() != 200) {
        throw new AlpacaAPIRequestException(response);
    }

    Type arrayListType = new TypeToken<ArrayList<Asset>>() {}.getType();

    return alpacaRequest.getResponseObject(response, arrayListType);
}
 
Example #21
Source File: APIHeadTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void defaultCacheHeaderTest() throws Exception {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
    hudson.model.User alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("[email protected]"));

    RequestBuilder requestBuilder = request().authAlice().get("/organizations/jenkins/users/");

    HttpResponse<List> response = requestBuilder.execute(List.class);

    List<String> list = response.getHeaders().get("Cache-Control");

    assertThat(list.get(0), containsString("no-cache"));
    assertThat(list.get(0), containsString("no-store"));
    assertThat(list.get(0), containsString("no-transform"));
}
 
Example #22
Source File: UpdateChecker.java    From Lukkit with MIT License 5 votes vote down vote up
/**
 * Check for updates against the GitHub repo releases page.
 *
 * @param pluginVersion the locally installed plugin version
 */
public static void checkForUpdates(String pluginVersion) {
    try {
        HttpResponse<JsonNode> res = Unirest.get("https://api.github.com/repos/" + GITHUB_ORG + "/Lukkit/releases/latest").asJson();
        String tagName = res.getBody().getObject().getString("tag_name").replace("v", "");

        if (isOutOfDate(pluginVersion.split("-")[0], tagName)) {
            Main.logger.info("A new version of Lukkit has been released: " + tagName);
            Main.logger.info("You can download it from https://www.spigotmc.org/resources/lukkit.32599/ or https://github.com/jammehcow/Lukkit/releases");
        } else {
            Main.logger.info("You're up to date with the latest version of Lukkit.");
        }
    } catch (Exception e ) { e.printStackTrace(); }
}
 
Example #23
Source File: AbstractRequest.java    From alpaca-java with MIT License 5 votes vote down vote up
/**
 * Gets response json.
 *
 * @param httpResponse the http response
 *
 * @return the response json
 */
public JsonElement getResponseJSON(HttpResponse<InputStream> httpResponse) {
    JsonElement responseJsonElement = null;

    try (JsonReader jsonReader = new JsonReader(new InputStreamReader(httpResponse.getRawBody()))) {
        responseJsonElement = GsonUtil.JSON_PARSER.parse(jsonReader);
    } catch (Exception e) {
        LOGGER.error("Exception", e);
    }

    return responseJsonElement;
}
 
Example #24
Source File: BasicFunctionalityTest.java    From elepy with Apache License 2.0 5 votes vote down vote up
@Test
void can_Login_and_UpdateOwnPassword_AsSuperUser() throws JsonProcessingException, UnirestException {
    createInitialUsersViaHttp();

    final HttpResponse<String> authorizedFind = Unirest
            .patch(elepy + "/users" + "/[email protected]")
            .queryString("password", "newPassword")
            .basicAuth("[email protected]", "[email protected]")
            .asString();

    final var admin = userCrud.getById("[email protected]").orElseThrow();
    assertThat(authorizedFind.getStatus()).isEqualTo(200);
    assertThat(BCrypt.checkpw("newPassword", admin.getPassword()))
            .isTrue();
}
 
Example #25
Source File: SchemaRegistryClient.java    From df_data_service with 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 File: RequestExecutor.java    From Bastion with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Executes the given HTTP request and retrieves the response.
 *
 * @return The HTTP response retrieved from the remote server.
 */
public Response execute() {
    try {
        HttpResponse<InputStream> httpResponse = performRequest();
        return convertToRawResponse(httpResponse);
    } catch (UnirestException exception) {
        if (exception.getCause() instanceof SocketTimeoutException) {
            throw new AssertionError(String.format("Failed to receive response before timeout of [%s] ms", resolveTimeoutOrFallbackToGlobal(bastionHttpRequest, configuration)));
        }
        throw new IllegalStateException("Failed executing request", exception);
    }
}
 
Example #27
Source File: StateMachineResourceTest.java    From flux with Apache License 2.0 5 votes vote down vote up
@Test
@Ignore("Feature no longer in use")
public void shouldProxyEventToOldCluster() throws Exception {
    final String stateMachineId = "some_random_machine_do_not_exist";
    final String eventJson = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("event_data.json"));
    final HttpResponse<String> httpResponse = Unirest.post(STATE_MACHINE_RESOURCE_URL + SLASH + stateMachineId + "/context/events").header("Content-Type", "application/json").body(eventJson).asString();
    assertThat(httpResponse.getStatus()).isEqualTo(HttpStatus.SC_ACCEPTED);
}
 
Example #28
Source File: PolygonAPI.java    From alpaca-java with MIT License 5 votes vote down vote up
/**
 * Get the mapping of ticker types to descriptions / long names.
 *
 * @return the ticker types
 *
 * @see <a href="https://polygon.io/docs/#!/Reference/get_v2_reference_types">Ticker Types</a>
 */
public TickerTypes getTickerTypes() throws PolygonAPIRequestException {
    PolygonRequestBuilder builder = new PolygonRequestBuilder(baseAPIURL, PolygonConstants.VERSION_2_ENDPOINT,
            PolygonConstants.REFERENCE_ENDPOINT,
            PolygonConstants.TYPES_ENDPOINT);

    HttpResponse<InputStream> response = polygonRequest.invokeGet(builder);

    if (response.getStatus() != 200) {
        throw new PolygonAPIRequestException(response);
    }

    return polygonRequest.getResponseObject(response, TickersResponse.class);
}
 
Example #29
Source File: HttpClientLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
public void givenInputStreamWhenUploadedThenCorrect() throws UnirestException, IOException {
    try (InputStream inputStream = new FileInputStream(new File("/path/to/file/artcile.txt"))) {

        HttpResponse<JsonNode> jsonResponse = Unirest.post("http://www.mocky.io/v2/5a9ce7663100006800ab515d")
            .field("file", inputStream, ContentType.APPLICATION_OCTET_STREAM, "article.txt")
            .asJson();
        assertEquals(201, jsonResponse.getStatus());

    }
}
 
Example #30
Source File: StateMachineResourceTest.java    From flux with Apache License 2.0 5 votes vote down vote up
@Test
@Ignore("Feature no longer in use")
public void shouldProxyScheduledEventToOldCluster() throws Exception {
    final String stateMachineId = "some_random_machine_do_not_exist";
    final String eventJson = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("event_data.json"));
    final HttpResponse<String> httpResponse = Unirest.post(STATE_MACHINE_RESOURCE_URL + SLASH + stateMachineId + "/context/events?triggerTime=0").header("Content-Type", "application/json").body(eventJson).asString();
    assertThat(httpResponse.getStatus()).isEqualTo(HttpStatus.SC_ACCEPTED);
}