Java Code Examples for com.mashape.unirest.http.HttpResponse#getStatus()

The following examples show how to use com.mashape.unirest.http.HttpResponse#getStatus() . 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: 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 2
Source File: AlpacaAPI.java    From alpaca-java with MIT License 6 votes vote down vote up
/**
 * Append an asset for the symbol to the end of watchlist asset list
 *
 * @param watchlistID Watchlist ID
 * @param symbol      the symbol name to add to the watchlist
 *
 * @return the watchlist
 *
 * @throws AlpacaAPIRequestException the alpaca api exception
 * @see <a href="https://docs.alpaca.markets/api-documentation/api-v2/watchlist/">Watchlists</a>
 */
public Watchlist addWatchlistAsset(String watchlistID, String symbol) throws AlpacaAPIRequestException {
    Preconditions.checkNotNull(watchlistID);
    Preconditions.checkNotNull(symbol);

    AlpacaRequestBuilder urlBuilder = new AlpacaRequestBuilder(baseAPIURL, apiVersion,
            AlpacaConstants.WATCHLISTS_ENDPOINT,
            watchlistID);

    urlBuilder.appendJSONBodyProperty("symbol", symbol);

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

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

    return alpacaRequest.getResponseObject(response, Watchlist.class);
}
 
Example 3
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 4
Source File: AlpacaAPI.java    From alpaca-java with MIT License 6 votes vote down vote up
/**
 * Create a new watchlist with initial set of assets.
 *
 * @param name    arbitrary name string, up to 64 characters
 * @param symbols set of symbol string
 *
 * @return the created watchlist
 *
 * @throws AlpacaAPIRequestException the alpaca api exception
 * @see <a href="https://docs.alpaca.markets/api-documentation/api-v2/watchlist/">Watchlists</a>
 */
public Watchlist createWatchlist(String name, String... symbols) throws AlpacaAPIRequestException {
    Preconditions.checkNotNull(name);
    Preconditions.checkState(name.length() <= 64);

    AlpacaRequestBuilder urlBuilder = new AlpacaRequestBuilder(baseAPIURL, apiVersion,
            AlpacaConstants.WATCHLISTS_ENDPOINT);

    urlBuilder.appendJSONBodyProperty("name", name);

    if (symbols != null) {
        JsonArray symbolsArray = new JsonArray();
        Arrays.stream(symbols).forEach(symbolsArray::add);

        urlBuilder.appendJSONBodyJSONProperty("symbols", symbolsArray);
    }

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

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

    return alpacaRequest.getResponseObject(response, Watchlist.class);
}
 
Example 5
Source File: AlpacaAPI.java    From alpaca-java with MIT License 6 votes vote down vote up
/**
 * Retrieves a single order for the given order_id.
 *
 * @param orderID Order ID
 * @param nested  If true, the result will roll up multi-leg orders under the legs field of primary order.
 *
 * @return the order
 *
 * @throws AlpacaAPIRequestException the alpaca API exception
 * @see <a href="https://docs.alpaca.markets/api-documentation/api-v2/orders/">Orders</a>
 */
public Order getOrder(String orderID, Boolean nested) throws AlpacaAPIRequestException {
    Preconditions.checkNotNull(orderID);

    AlpacaRequestBuilder urlBuilder = new AlpacaRequestBuilder(baseAPIURL, apiVersion,
            AlpacaConstants.ORDERS_ENDPOINT,
            orderID);

    if (nested != null) {
        urlBuilder.appendURLParameter(AlpacaConstants.NESTED_PARAMETER, nested.toString());
    }

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

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

    return alpacaRequest.getResponseObject(response, Order.class);
}
 
Example 6
Source File: PolygonAPI.java    From alpaca-java with MIT License 6 votes vote down vote up
/**
 * Get the historical dividends for this symbol.
 *
 * @param symbol symbol we want details for
 *
 * @return the stock dividends
 *
 * @throws PolygonAPIRequestException the polygon API exception
 * @see <a href="https://polygon.io/docs/#!/Meta-Data/get_v1_meta_symbols_symbol_dividends">Stock Dividends</a>
 */
public StockDividendsResponse getStockDividends(String symbol) throws PolygonAPIRequestException {
    Preconditions.checkNotNull(symbol);

    PolygonRequestBuilder builder = new PolygonRequestBuilder(baseAPIURL, PolygonConstants.VERSION_2_ENDPOINT,
            PolygonConstants.REFERENCE_ENDPOINT,
            PolygonConstants.DIVIDENDS_ENDPOINT,
            symbol);

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

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

    return polygonRequest.getResponseObject(response, StockDividendsResponse.class);
}
 
Example 7
Source File: PolygonAPI.java    From alpaca-java with MIT License 6 votes vote down vote up
/**
 * Get the previous day close for the specified ticker
 *
 * @param ticker     Ticker symbol of the request
 * @param unadjusted Set to true if the results should NOT be adjusted for splits.
 *
 * @return the previous close
 *
 * @throws PolygonAPIRequestException the polygon API exception
 * @see <a href="https://polygon.io/docs/#!/Stocks--Equities/get_v2_aggs_ticker_ticker_prev">Previous Close</a>
 */
public PreviousCloseResponse getPreviousClose(String ticker, Boolean unadjusted) throws PolygonAPIRequestException {
    Preconditions.checkNotNull(ticker);

    PolygonRequestBuilder builder = new PolygonRequestBuilder(baseAPIURL, PolygonConstants.VERSION_2_ENDPOINT,
            PolygonConstants.AGGS_ENDPOINT,
            PolygonConstants.TICKER_ENDPOINT,
            ticker,
            PolygonConstants.PREV_ENDPOINT);

    if (unadjusted != null) {
        builder.appendURLParameter(PolygonConstants.UNADJUSTED_PARAMETER, unadjusted.toString());
    }

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

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

    return polygonRequest.getResponseObject(response, PreviousCloseResponse.class);
}
 
Example 8
Source File: PolygonAPI.java    From alpaca-java with MIT License 6 votes vote down vote up
/**
 * Get the last quote for a given stock.
 *
 * @param symbol Symbol of the stock to get
 *
 * @return the last quote
 *
 * @throws PolygonAPIRequestException the polygon API exception
 * @see <a href="https://polygon.io/docs/#!/Stocks--Equities/get_v1_last_quote_stocks_symbol">Last Quote</a>
 */
public LastQuoteResponse getLastQuote(String symbol) throws PolygonAPIRequestException {
    Preconditions.checkNotNull(symbol);

    PolygonRequestBuilder builder = new PolygonRequestBuilder(baseAPIURL, PolygonConstants.VERSION_1_ENDPOINT,
            PolygonConstants.LAST_QUOTE_ENDPOINT,
            PolygonConstants.STOCKS_ENDPOINT,
            symbol);

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

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

    return polygonRequest.getResponseObject(response, LastQuoteResponse.class);
}
 
Example 9
Source File: PolygonAPI.java    From alpaca-java with MIT License 6 votes vote down vote up
/**
 * See the current snapshot of Level II data on IEX for the given ticker.
 *
 * @param locale the locale
 * @param market the market
 * @param ticker the ticker
 *
 * @return the snapshot ticker book
 *
 * @throws PolygonAPIRequestException the polygon API exception
 * @see <a href="">Docs not public yet</a>
 */
public SnapshotTickerBook getSnapshotTickerBook(String locale, Market market, String ticker)
        throws PolygonAPIRequestException {
    Preconditions.checkNotNull(locale);
    Preconditions.checkNotNull(market);
    Preconditions.checkNotNull(ticker);

    PolygonRequestBuilder builder = new PolygonRequestBuilder(baseAPIURL, PolygonConstants.VERSION_2_ENDPOINT,
            PolygonConstants.SNAPSHOT_ENDPOINT,
            PolygonConstants.LOCALE_ENDPOINT,
            locale,
            PolygonConstants.MARKETS_ENDPOINT,
            market.getAPIName(),
            PolygonConstants.TICKERS_ENDPOINT,
            ticker,
            PolygonConstants.BOOK_ENDPOINT);

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

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

    return polygonRequest.getResponseObject(response, SnapshotTickerBook.class);
}
 
Example 10
Source File: PolygonAPI.java    From alpaca-java with MIT License 5 votes vote down vote up
/**
 * Get historic NBBO quotes for a ticker.
 *
 * @param ticker         Ticker symbol we want ticks for
 * @param date           Date/Day of the historic ticks to retrieve
 * @param timestamp      Timestamp offset, used for pagination. This is the offset at which to start the results.
 *                       Using the timestamp of the last result as the offset will give you the next page of
 *                       results.
 * @param timestampLimit Maximum timestamp allowed in the results.
 * @param reverse        Reverse the order of the results. This is useful in combination with timestamp param.
 * @param limit          Limit the size of response, Max 50000
 *
 * @return the historic quotes
 *
 * @throws PolygonAPIRequestException the polygon API exception
 * @see <a href="https://polygon.io/docs/#!/Stocks--Equities/get_v2_ticks_stocks_nbbo_ticker_date">Historic
 * Quotes</a>
 */
public HistoricQuotesResponse getHistoricQuotes(String ticker, LocalDate date, Long timestamp, Long timestampLimit,
        Boolean reverse, Integer limit) throws PolygonAPIRequestException {
    Preconditions.checkNotNull(ticker);
    Preconditions.checkNotNull(date);

    PolygonRequestBuilder builder = new PolygonRequestBuilder(baseAPIURL, PolygonConstants.VERSION_2_ENDPOINT,
            PolygonConstants.TICKS_ENDPOINT,
            PolygonConstants.STOCKS_ENDPOINT,
            PolygonConstants.NBBO_ENDPOINT,
            ticker,
            TimeUtil.toDateString(date));

    if (timestamp != null) {
        builder.appendURLParameter(PolygonConstants.TIMESTAMP_PARAMETER, String.valueOf(timestamp));
    }

    if (timestampLimit != null) {
        builder.appendURLParameter(PolygonConstants.TIMESTAMP_LIMIT_PARAMETER, String.valueOf(timestampLimit));
    }

    if (reverse != null) {
        builder.appendURLParameter(PolygonConstants.REVERSE_PARAMETER, String.valueOf(reverse));
    }

    if (limit != null) {
        builder.appendURLParameter(PolygonConstants.LIMIT_PARAMETER, String.valueOf(limit));
    }

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

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

    return polygonRequest.getResponseObject(response, HistoricQuotesResponse.class);
}
 
Example 11
Source File: CustomHttpClient.java    From openvidu with Apache License 2.0 5 votes vote down vote up
private JsonObject commonRest(HttpMethod method, String path, String body, int status) throws Exception {
	HttpResponse<?> jsonResponse = null;
	JsonObject json = null;
	path = openviduUrl + (path.startsWith("/") ? path : ("/" + path));

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

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

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

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

	return json;
}
 
Example 12
Source File: PolygonAPI.java    From alpaca-java with MIT License 5 votes vote down vote up
/**
 * Get aggregates for a date range, in custom time window sizes
 *
 * @param ticker     Ticker symbol of the request
 * @param multiplier Size of the timespan multiplier
 * @param timeSpan   Size of the time window
 * @param fromDate   From date
 * @param toDate     To date
 * @param unadjusted Set to true if the results should NOT be adjusted for splits
 *
 * @return the aggregates
 *
 * @throws PolygonAPIRequestException the polygon API exception
 * @see
 * <a href="https://polygon.io/docs/#!/Stocks--Equities/get_v2_aggs_ticker_ticker_range_multiplier_timespan_from_to">Aggregates</a>
 */
public AggregatesResponse getAggregates(String ticker, Integer multiplier, Timespan timeSpan, LocalDate fromDate,
        LocalDate toDate, Boolean unadjusted) throws PolygonAPIRequestException {
    Preconditions.checkNotNull(ticker);
    Preconditions.checkNotNull(timeSpan);
    Preconditions.checkNotNull(fromDate);
    Preconditions.checkNotNull(toDate);

    PolygonRequestBuilder builder = new PolygonRequestBuilder(baseAPIURL, PolygonConstants.VERSION_2_ENDPOINT,
            PolygonConstants.AGGS_ENDPOINT,
            PolygonConstants.TICKER_ENDPOINT,
            ticker,
            PolygonConstants.RANGE_ENDPOINT,
            Integer.toString((multiplier == null) ? 1 : multiplier),
            timeSpan.getAPIName(),
            TimeUtil.toDateString(fromDate),
            TimeUtil.toDateString(toDate));

    if (unadjusted != null) {
        builder.appendURLParameter(PolygonConstants.UNADJUSTED_PARAMETER, unadjusted.toString());
    }

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

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

    return polygonRequest.getResponseObject(response, AggregatesResponse.class);
}
 
Example 13
Source File: MockPublicKeyConnector.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public boolean exists(PublicKeyDescribeRequest request) {
    try {
        String mockEndpoint = getMockEndpoint(request.getCredential());
        HttpResponse<Boolean> response = Unirest.get(mockEndpoint + "/spi/get_public_key/" + request.getPublicKeyId()).asObject(Boolean.class);
        if (response.getStatus() != 200) {
            throw new CloudConnectorException(response.getStatusText());
        }
        return response.getBody() != null && response.getBody();
    } catch (UnirestException e) {
        throw new CloudConnectorException(e.getMessage(), e);
    }
}
 
Example 14
Source File: AlpacaAPI.java    From alpaca-java with MIT License 5 votes vote down vote up
/**
 * Update the name and/or content of watchlist.
 *
 * @param watchlistID Watchlist ID
 * @param name        the new watchlist name
 * @param symbols     the new list of symbol names to replace the watchlist content
 *
 * @return the updated watchlist
 *
 * @throws AlpacaAPIRequestException the alpaca api exception
 * @see <a href="https://docs.alpaca.markets/api-documentation/api-v2/watchlist/">Watchlists</a>
 */
public Watchlist updateWatchlist(String watchlistID, String name, String... symbols)
        throws AlpacaAPIRequestException {
    Preconditions.checkNotNull(watchlistID);

    AlpacaRequestBuilder urlBuilder = new AlpacaRequestBuilder(baseAPIURL, apiVersion,
            AlpacaConstants.WATCHLISTS_ENDPOINT,
            watchlistID);

    if (name != null) {
        urlBuilder.appendJSONBodyProperty("name", name);
    }

    if (symbols != null) {
        JsonArray symbolsArray = new JsonArray();
        Arrays.stream(symbols).forEach(symbolsArray::add);

        urlBuilder.appendJSONBodyJSONProperty("symbols", symbolsArray);
    }

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

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

    return alpacaRequest.getResponseObject(response, Watchlist.class);
}
 
Example 15
Source File: PolygonAPI.java    From alpaca-java with MIT License 5 votes vote down vote up
/**
 * Get the list of currently supported markets
 *
 * @return the markets
 *
 * @throws PolygonAPIRequestException the polygon API exception
 * @see <a href="https://polygon.io/docs/#!/Reference/get_v2_reference_markets">Markets</a>
 */
public MarketsResponse getMarkets() throws PolygonAPIRequestException {
    PolygonRequestBuilder builder = new PolygonRequestBuilder(baseAPIURL, PolygonConstants.VERSION_2_ENDPOINT,
            PolygonConstants.REFERENCE_ENDPOINT,
            PolygonConstants.MARKETS_ENDPOINT);

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

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

    return polygonRequest.getResponseObject(response, MarketsResponse.class);
}
 
Example 16
Source File: Downloader.java    From minimesos with Apache License 2.0 5 votes vote down vote up
public String getFileContentAsString(String url) throws MinimesosException {
    HttpResponse<String> response = null;
    try {
        response = Unirest.get(url)
            .header("content-type", "*/*")
            .asString();
    } catch (UnirestException e) {
        throw new MinimesosException(String.format("Cannot fetch file '%s': '%s'", url, e.getMessage()));
    }
    if (response.getStatus() != HttpStatus.SC_OK) {
        throw new MinimesosException(String.format("Cannot fetch file '%s': '%s'", url, response.getStatus()));
    }
    return response.getBody();
}
 
Example 17
Source File: AlpacaAPI.java    From alpaca-java with MIT License 5 votes vote down vote up
/**
 * Returns the account associated with the API key.
 *
 * @return the account
 *
 * @throws AlpacaAPIRequestException the alpaca API exception
 * @see <a href="https://docs.alpaca.markets/api-documentation/api-v2/account/">Get the Account</a>
 */
public Account getAccount() throws AlpacaAPIRequestException {
    AlpacaRequestBuilder urlBuilder = new AlpacaRequestBuilder(baseAPIURL, apiVersion,
            AlpacaConstants.ACCOUNT_ENDPOINT);

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

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

    return alpacaRequest.getResponseObject(response, Account.class);
}
 
Example 18
Source File: DFDataProcessor.java    From df_data_service with Apache License 2.0 4 votes vote down vote up
/**
 * Start a Kafka connect in background to keep sinking meta data to mongodb
 * This is blocking process since it is a part of application initialization.
 */
private void startMetadataSink() {

    // Check if the sink is already started. If yes, do not start
    String restURI = "http://" + this.kafka_connect_rest_host + ":" + this.kafka_connect_rest_port +
            ConstantApp.KAFKA_CONNECT_REST_URL;
    String metaDBHost = config().getString("repo.connection.string", "mongodb://localhost:27017")
            .replace("//", "").split(":")[1];
    String metaDBPort = config().getString("repo.connection.string", "mongodb://localhost:27017")
            .replace("//", "").split(":")[2];
    String metaDBName = config().getString("db.name", "DEFAULT_DB");

    // Create meta-database if it is not exist
    new MongoAdminClient(metaDBHost, Integer.parseInt(metaDBPort), metaDBName)
            .createCollection(this.COLLECTION_META)
            .close();

    String metaSinkConnect = new JSONObject().put("name", "metadata_sink_connect").put("config",
            new JSONObject().put("connector.class", "org.apache.kafka.connect.mongodb.MongodbSinkConnector")
                    .put("tasks.max", "2")
                    .put("host", metaDBHost)
                    .put("port", metaDBPort)
                    .put("bulk.size", "1")
                    .put("mongodb.database", metaDBName)
                    .put("mongodb.collections", config().getString("db.metadata.collection.name", this.COLLECTION_META))
                    .put("topics", config().getString("kafka.topic.df.metadata", "df_meta"))).toString();
    try {
        HttpResponse<String> res = Unirest.get(restURI + "/metadata_sink_connect/status")
                .header("accept", ConstantApp.HTTP_HEADER_APPLICATION_JSON_CHARSET)
                .asString();

        if(res.getStatus() == ConstantApp.STATUS_CODE_NOT_FOUND) { // Add the meta sink
            Unirest.post(restURI)
                    .header("accept", "application/json").header("Content-Type", "application/json")
                    .body(metaSinkConnect).asString();
        }

        // Add the avro schema for metadata as well since df_meta-value maybe added only
        String dfMetaSchemaSubject = config().getString("kafka.topic.df.metadata", "df_meta");
        String schemaRegistryRestURL = "http://" + this.schema_registry_host_and_port + "/subjects/" +
                dfMetaSchemaSubject + "/versions";

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

        if(schmeaRes.getStatus() == ConstantApp.STATUS_CODE_NOT_FOUND) { // Add the meta sink schema
            Unirest.post(schemaRegistryRestURL)
                    .header("accept", ConstantApp.HTTP_HEADER_APPLICATION_JSON_CHARSET)
                    .header("Content-Type", ConstantApp.AVRO_REGISTRY_CONTENT_TYPE)
                    .body(new JSONObject().put("schema", config().getString("df.metadata.schema",
                            "{\"type\":\"record\"," +
                                    "\"name\": \"df_meta\"," +
                                    "\"fields\":[" +
                                    "{\"name\": \"cuid\", \"type\": \"string\"}," +
                                    "{\"name\": \"file_name\", \"type\": \"string\"}," +
                                    "{\"name\": \"file_size\", \"type\": \"string\"}, " +
                                    "{\"name\": \"file_owner\", \"type\": \"string\"}," +
                                    "{\"name\": \"last_modified_timestamp\", \"type\": \"string\"}," +
                                    "{\"name\": \"current_timestamp\", \"type\": \"string\"}," +
                                    "{\"name\": \"current_timemillis\", \"type\": \"long\"}," +
                                    "{\"name\": \"stream_offset\", \"type\": \"string\"}," +
                                    "{\"name\": \"topic_sent\", \"type\": \"string\"}," +
                                    "{\"name\": \"schema_subject\", \"type\": \"string\"}," +
                                    "{\"name\": \"schema_version\", \"type\": \"string\"}," +
                                    "{\"name\": \"status\", \"type\": \"string\"}]}"
                            )).toString()
                    ).asString();
            LOG.info(DFAPIMessage.logResponseMessage(1008, "META_DATA_SCHEMA_REGISTRATION"));
        } else {
            LOG.info(DFAPIMessage.logResponseMessage(1009, "META_DATA_SCHEMA_REGISTRATION"));
        }

        JSONObject resObj = new JSONObject(res.getBody());
        String status = "Unknown";
        if (resObj.has("connector")) {
            status = resObj.getJSONObject("connector").get("state").toString();
        }

        LOG.info(DFAPIMessage.logResponseMessage(1010, "topic:df_meta, status:" + status));

    } catch (UnirestException ue) {
        LOG.error(DFAPIMessage
                .logResponseMessage(9015, "exception details - " + ue.getCause()));
    }
}
 
Example 19
Source File: AlpacaAPI.java    From alpaca-java with MIT License 4 votes vote down vote up
/**
 * Retrieves a list of orders for the account, filtered by the supplied query parameters.
 *
 * @param status    Order status to be queried. open, closed or all. Defaults to open.
 * @param limit     The maximum number of orders in response. Defaults to 50 and max is 500.
 * @param after     The response will include only ones submitted after this timestamp (exclusive.)
 * @param until     The response will include only ones submitted until this timestamp (exclusive.)
 * @param direction The chronological order of response based on the submission time. asc or desc. Defaults to
 *                  desc.
 * @param nested    If true, the result will roll up multi-leg orders under the legs field of primary order.
 *
 * @return the orders
 *
 * @throws AlpacaAPIRequestException the alpaca API exception
 * @see <a href="https://docs.alpaca.markets/api-documentation/api-v2/orders/">Orders</a>
 */
public ArrayList<Order> getOrders(OrderStatus status, Integer limit, ZonedDateTime after, ZonedDateTime until,
        Direction direction, Boolean nested) throws AlpacaAPIRequestException {
    AlpacaRequestBuilder urlBuilder = new AlpacaRequestBuilder(baseAPIURL, apiVersion,
            AlpacaConstants.ORDERS_ENDPOINT);

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

    if (limit != null) {
        urlBuilder.appendURLParameter(AlpacaConstants.LIMIT_PARAMETER, limit.toString());
    }

    if (after != null) {
        urlBuilder.appendURLParameter(AlpacaConstants.AFTER_PARAMETER,
                after.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));
    }

    if (until != null) {
        urlBuilder.appendURLParameter(AlpacaConstants.UNTIL_PARAMETER,
                until.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));
    }

    if (direction != null) {
        urlBuilder.appendURLParameter(AlpacaConstants.DIRECTION_PARAMETER, direction.getAPIName());
    }

    if (nested != null) {
        urlBuilder.appendURLParameter(AlpacaConstants.NESTED_PARAMETER, nested.toString());
    }

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

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

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

    return alpacaRequest.getResponseObject(response, arrayListType);
}
 
Example 20
Source File: BitbucketSourceConnector.java    From apicurio-studio with Apache License 2.0 4 votes vote down vote up
@Override
public Collection<BitbucketRepository> getRepositories(String teamName) throws BitbucketException, SourceConnectorException {
    try {
    	//@formatter:off
    	Endpoint endpoint = endpoint("/repositories/:uname")
    			.bind("uname", teamName)
    			.queryParam("pagelen", "25");
    	if (!StringUtils.isEmpty(config.getRepositoryFilter())) {
    	    String filter = "name~\"" + config.getRepositoryFilter() + "\"";
    		endpoint = endpoint.queryParam("q", filter);
    	}
        //@formatter:on;

        String reposUrl = endpoint.toString();

        Collection<BitbucketRepository> rVal =  new HashSet<>();
        boolean done = false;
        
        while (!done) {
            HttpRequest request = Unirest.get(reposUrl);
            addSecurityTo(request);
            HttpResponse<com.mashape.unirest.http.JsonNode> response = request.asJson();

            JSONObject responseObj = response.getBody().getObject();

            if (response.getStatus() != 200) {
                throw new UnirestException("Unexpected response from Bitbucket: " + response.getStatus() + "::" + response.getStatusText());
            }

            responseObj.getJSONArray("values").forEach(obj -> {
                BitbucketRepository bbr = new BitbucketRepository();
                JSONObject rep = (JSONObject) obj;
                bbr.setName(rep.getString("name"));
                bbr.setUuid(rep.getString("uuid"));
                bbr.setSlug(rep.getString("slug"));
                rVal.add(bbr);
            });
            
            done = true;
            if (responseObj.has("next")) {
                String next = responseObj.getString("next");
                if (!StringUtils.isEmpty(next) && !next.equals(reposUrl)) {
                    done = false;
                    reposUrl = next;
                }
            }
        }

        return rVal;

    } catch (UnirestException e) {
        throw new BitbucketException("Error getting Bitbucket teams.", e);
    }
}