Java Code Examples for com.mashape.unirest.http.exceptions.UnirestException#printStackTrace()

The following examples show how to use com.mashape.unirest.http.exceptions.UnirestException#printStackTrace() . 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: DataVecTransformClient.java    From DataVec with Apache License 2.0 6 votes vote down vote up
/**
 * @param batchCSVRecord
 * @return
 */
@Override
public SequenceBatchCSVRecord transform(SequenceBatchCSVRecord batchCSVRecord) {
    try {
        SequenceBatchCSVRecord batchCSVRecord1 = Unirest.post(url + "/transform").header("accept", "application/json")
                .header("Content-Type", "application/json")
                .header(SEQUENCE_OR_NOT_HEADER,"TRUE")
                .body(batchCSVRecord)
                .asObject(SequenceBatchCSVRecord.class)
                .getBody();
        return batchCSVRecord1;
    } catch (UnirestException e) {
        log.error("Error in transform(BatchCSVRecord)", e);
        e.printStackTrace();
    }

    return null;
}
 
Example 2
Source File: TelegramBot.java    From JavaTelegramBot-API with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Use this method to kick a user from a group or a supergroup. In the case of supergroups, the user will not be
 * able to return to the group on their own using invite links, etc., unless unbanned first. The bot must be
 * an administrator in the group for this to work
 *
 * @param chatId    The ID of the chat that you want to kick the user from
 * @param userId    The ID of the user that you want to kick from the chat
 *
 * @return True if the user was kicked successfully, otherwise False
 */
public boolean kickChatMember(String chatId, int userId) {

    HttpResponse<String> response;
    JSONObject jsonResponse;

    try {
        MultipartBody request = Unirest.post(getBotAPIUrl() + "kickChatMember")
                .field("chat_id", chatId, "application/json; charset=utf8;")
                .field("user_id", userId);

        response = request.asString();
        jsonResponse = Utils.processResponse(response);

        if(jsonResponse != null) {

            if(jsonResponse.getBoolean("result")) return true;
        }
    } catch (UnirestException e) {
        e.printStackTrace();
    }

    return false;
}
 
Example 3
Source File: DataVecTransformClient.java    From DataVec with Apache License 2.0 6 votes vote down vote up
/**
 * @param batchCSVRecord
 * @return
 */
@Override
public SequenceBatchCSVRecord transformSequence(SequenceBatchCSVRecord batchCSVRecord) {
    try {
        SequenceBatchCSVRecord batchCSVRecord1 = Unirest.post(url + "/transform")
                .header("accept", "application/json")
                .header("Content-Type", "application/json")
                .header(SEQUENCE_OR_NOT_HEADER,"true")
                .body(batchCSVRecord)
                .asObject(SequenceBatchCSVRecord.class).getBody();
        return batchCSVRecord1;
    } catch (UnirestException e) {
        log.error("Error in transformSequence");
        e.printStackTrace();
    }

    return null;
}
 
Example 4
Source File: Authorization.java    From SKIL_Examples with Apache License 2.0 6 votes vote down vote up
public String getAuthToken(String userId, String password) {
    String authToken = null;

    try {
        authToken =
                Unirest.post(MessageFormat.format("http://{0}:{1}/login", host, port))
                        .header("accept", "application/json")
                        .header("Content-Type", "application/json")
                        .body(new JSONObject()
                                .put("userId", userId)
                                .put("password", password)
                                .toString())
                        .asJson()
                        .getBody().getObject().getString("token");
    } catch (UnirestException e) {
        e.printStackTrace();
    }

    return authToken;
}
 
Example 5
Source File: YOLO2_TF_Client.java    From SKIL_Examples with Apache License 2.0 6 votes vote down vote up
public String getAuthToken(String userId, String password) {
    String authToken = null;

    try {
        authToken =
                Unirest.post(MessageFormat.format("http://{0}:{1}/login", host, port))
                        .header("accept", "application/json")
                        .header("Content-Type", "application/json")
                        .body(new JSONObject() //Using this because the field functions couldn't get translated to an acceptable json
                                .put("userId", userId)
                                .put("password", password)
                                .toString())
                        .asJson()
                        .getBody().getObject().getString("token");
    } catch (UnirestException e) {
        e.printStackTrace();
    }

    return authToken;
}
 
Example 6
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 7
Source File: E2ETest.java    From flux with Apache License 2.0 5 votes vote down vote up
@After
public void tearDown() {
    try {
        Unirest.post("http://localhost:9998/api/client-elb/delete")
                .queryString("clientId", "defaultElbId").asString();
    } catch (UnirestException e) {
        e.printStackTrace();
    }
}
 
Example 8
Source File: DataVecTransformClient.java    From DataVec with Apache License 2.0 5 votes vote down vote up
/**
 * @param transform
 * @return
 */
@Override
public SingleCSVRecord transformIncremental(SingleCSVRecord transform) {
    try {
        SingleCSVRecord singleCsvRecord = Unirest.post(url + "/transformincremental")
                .header("accept", "application/json")
                .header("Content-Type", "application/json")
                .body(transform).asObject(SingleCSVRecord.class).getBody();
        return singleCsvRecord;
    } catch (UnirestException e) {
        log.error("Error in transformIncremental(SingleCSVRecord)",e);
        e.printStackTrace();
    }
    return null;
}
 
Example 9
Source File: DataVecTransformClient.java    From DataVec with Apache License 2.0 5 votes vote down vote up
/**
 * @return
 */
@Override
public TransformProcess getCSVTransformProcess() {
    try {
        String s = Unirest.get(url + "/transformprocess").header("accept", "application/json")
                .header("Content-Type", "application/json").asString().getBody();
        return TransformProcess.fromJson(s);
    } catch (UnirestException e) {
        log.error("Error in getCSVTransformProcess()",e);
        e.printStackTrace();
    }

    return null;
}
 
Example 10
Source File: TelegramBot.java    From JavaTelegramBot-API with GNU General Public License v3.0 5 votes vote down vote up
/**
 * This allows you to respond to a callback query with some text as a response. This will either show up as an
 * alert or as a toast on the telegram client
 *
 * @param callbackQueryId       The ID of the callback query you are responding to
 * @param callbackQueryResponse The response that you would like to send in reply to this callback query
 *
 * @return True if the response was sent successfully, otherwise False
 */
public boolean answerCallbackQuery(String callbackQueryId, CallbackQueryResponse callbackQueryResponse) {

    if(callbackQueryId != null && callbackQueryResponse.getText() != null) {

        HttpResponse<String> response;
        JSONObject jsonResponse;

        try {
            MultipartBody requests = Unirest.post(getBotAPIUrl() + "answerCallbackQuery")
                    .field("callback_query_id", callbackQueryId, "application/json; charset=utf8;")
                    .field("text", callbackQueryResponse.getText(), "application/json; charset=utf8;")
                    .field("show_alert", callbackQueryResponse.isShowAlert())
                    .field("cache_time", callbackQueryResponse.getCacheTime())
                    .field("url", callbackQueryResponse.getURL() != null ? callbackQueryResponse.getURL().toExternalForm() : null, "application/json; charset=utf8;");


            response = requests.asString();
            jsonResponse = Utils.processResponse(response);

            if (jsonResponse != null) {

                if (jsonResponse.getBoolean("result")) return true;
            }
        } catch (UnirestException e) {
            e.printStackTrace();
        }
    }

    return false;
}
 
Example 11
Source File: UserProfilePhotosImpl.java    From JavaTelegramBot-API with GNU General Public License v3.0 5 votes vote down vote up
public static UserProfilePhotos createUserProfilePhotos(long user_id, TelegramBot telegramBot) {

        try {
            JSONObject json = Unirest.post(telegramBot.getBotAPIUrl() + "getUserProfilePhotos")
                    .queryString("user_id", user_id).asJson().getBody().getObject();
            if(json.getBoolean("ok")) {
                return new UserProfilePhotosImpl(json.getJSONObject("result"));
            }
        } catch (UnirestException e) {
            e.printStackTrace();
        }

        return null;
    }
 
Example 12
Source File: MultiplayerDisplay.java    From minicraft-plus-revived with GNU General Public License v3.0 5 votes vote down vote up
private void fetchName(String uuid) {
	/// HTTP REQUEST - ATTEMPT TO SEND UUID TO SERVER AND UPDATE USERNAME
	HttpResponse<JsonNode> response = null;
	
	try {
		response = Unirest.post(apiDomain+"/fetch-name")
			.field("uuid", savedUUID)
			.asJson();
	} catch (UnirestException e) {
		e.printStackTrace();
	}
	
	if(response != null) {
		JSONObject json = response.getBody().getObject();
		//if(Game.debug) System.out.println("received json from username request: " + json.toString());
		switch(json.getString("status")) {
			case "error":
				setError("problem with saved login data; please exit and login again.", false);
				savedUUID = "";
				break;
			
			case "success":
				if(Game.debug) System.out.println("successfully received username from playminicraft server");
				savedUsername = json.getString("name");
				break;
		}
	} else// if(Game.debug)
		setError("Internal server error: Couldn't fetch username from uuid");
	//System.out.println("response to username fetch was null");
}
 
Example 13
Source File: TelegramBot.java    From JavaTelegramBot-API with GNU General Public License v3.0 5 votes vote down vote up
public List<GameHighScore> getGameHighScores(GameScoreRequest gameScoreRequest) {

        HttpResponse<String> response;
        JSONObject jsonResponse;

        try {
            MultipartBody request = Unirest.post(getBotAPIUrl() + "setGameScore")
                    .field("user_id", gameScoreRequest.getUserId(), "application/json; charset=utf8;")
                    .field("chat_id", gameScoreRequest.getChatId())
                    .field("message_id", gameScoreRequest.getMessageId())
                    .field("inline_message_id", gameScoreRequest.getInlineMessageId());

            response = request.asString();
            jsonResponse = Utils.processResponse(response);

            if(jsonResponse != null) {

                List<GameHighScore> highScores = new LinkedList<>();

                for(Object object : jsonResponse.getJSONArray("result")) {

                    JSONObject jsonObject = (JSONObject) object;

                    highScores.add(GameHighScoreImpl.createGameHighscore(jsonObject));
                }

                return highScores;
            }
        } catch (UnirestException e) {
            e.printStackTrace();
        }

        return null;
    }
 
Example 14
Source File: DataVecTransformClient.java    From DataVec with Apache License 2.0 5 votes vote down vote up
/**
 * @param singleCsvRecord
 * @return
 */
@Override
public Base64NDArrayBody transformArrayIncremental(SingleCSVRecord singleCsvRecord) {
    try {
        Base64NDArrayBody array = Unirest.post(url + "/transformincrementalarray")
                .header("accept", "application/json").header("Content-Type", "application/json")
                .body(singleCsvRecord).asObject(Base64NDArrayBody.class).getBody();
        return array;
    } catch (UnirestException e) {
        log.error("Error in transformArrayIncremental(SingleCSVRecord)",e);
        e.printStackTrace();
    }

    return null;
}
 
Example 15
Source File: StateMachineResourceTest.java    From flux with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void beforeClass() {
    try {
        Unirest.post("http://localhost:9998/api/client-elb/create")
                .queryString("clientId", "defaultElbId").queryString("clientElbUrl",
                "http://localhost:9997").asString();
    } catch (UnirestException e) {
        e.printStackTrace();
    }
}
 
Example 16
Source File: ApiConnection.java    From PaystackJava with MIT License 5 votes vote down vote up
/**
 * Used to send a GET request to the Paystack API
 *
 * @param query - HashMap containing parameters to send
 * @return - JSONObject containing API response
 */
public JSONObject connectAndQueryWithGet(HashMap<String, Object> query) {
    try {
        HttpResponse<JsonNode> queryForResponse = Unirest.get(url)
                .header("Accept", "application/json")
                .header("Authorization", "Bearer " + apiKey)
                .queryString(query)
                .asJson();
        return queryForResponse.getBody().getObject();
    } catch (UnirestException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 17
Source File: SystemTest.java    From hypergraphql with Apache License 2.0 4 votes vote down vote up
@Test
void integration_test() {

    Model mainModel = ModelFactory.createDefaultModel();
    final URL dbpediaContentUrl = getClass().getClassLoader().getResource("test_services/dbpedia.ttl");
    if(dbpediaContentUrl != null) {
        mainModel.read(dbpediaContentUrl.toString(), "TTL");
    }

    Model citiesModel = ModelFactory.createDefaultModel();
    final URL citiesContentUrl = getClass().getClassLoader().getResource("test_services/cities.ttl");
    if(citiesContentUrl != null) {
        citiesModel.read(citiesContentUrl.toString(), "TTL");
    }

    Model expectedModel = ModelFactory.createDefaultModel();
    expectedModel.add(mainModel).add(citiesModel);

    Dataset ds = DatasetFactory.createTxnMem();
    ds.setDefaultModel(citiesModel);
    FusekiServer server = FusekiServer.create()
            .add("/ds", ds)
            .build()
            .start();

    HGQLConfig externalConfig = HGQLConfig.fromClasspathConfig("test_services/externalconfig.json");

    Controller externalController = new Controller();
    externalController.start(externalConfig);

    HGQLConfig config = HGQLConfig.fromClasspathConfig("test_services/mainconfig.json");

    Controller controller = new Controller();
    controller.start(config);

    ObjectMapper mapper = new ObjectMapper();
    ObjectNode bodyParam = mapper.createObjectNode();

    bodyParam.put("query", "{\n" +
            "  Person_GET {\n" +
            "    _id\n" +
            "    label\n" +
            "    name\n" +
            "    birthPlace {\n" +
            "      _id\n" +
            "      label\n" +
            "    }\n" +
            "    \n" +
            "  }\n" +
            "  City_GET {\n" +
            "    _id\n" +
            "    label}\n" +
            "}");

    Model returnedModel = ModelFactory.createDefaultModel();

    try {
        HttpResponse<InputStream> response = Unirest.post("http://localhost:8080/graphql")
                .header("Accept", "application/rdf+xml")
                .body(bodyParam.toString())
                .asBinary();


        returnedModel.read(response.getBody(), "RDF/XML");

    } catch (UnirestException e) {
        e.printStackTrace();
    }

    Resource res = ResourceFactory.createResource("http://hypergraphql.org/query");
    Selector sel = new SelectorImpl(res, null, (Object) null);
    StmtIterator iterator = returnedModel.listStatements(sel);
    Set<Statement> statements = new HashSet<>();
    while (iterator.hasNext()) {
        statements.add(iterator.nextStatement());
    }

    for (Statement statement : statements) {
        returnedModel.remove(statement);
    }

    StmtIterator iterator2 = expectedModel.listStatements();
    while (iterator2.hasNext()) {
        assertTrue(returnedModel.contains(iterator2.next()));
    }

    assertTrue(expectedModel.isIsomorphicWith(returnedModel));
    externalController.stop();
    controller.stop();
    server.stop();
}
 
Example 18
Source File: GitHubAPIHttpClient.java    From kafka-connect-github-source with MIT License 4 votes vote down vote up
protected JSONArray getNextIssues(Integer page, Instant since) throws InterruptedException {

        HttpResponse<JsonNode> jsonResponse;
        try {
            jsonResponse = getNextIssuesAPI(page, since);

            // deal with headers in any case
            Headers headers = jsonResponse.getHeaders();
            XRateLimit = Integer.valueOf(headers.getFirst(X_RATELIMIT_LIMIT_HEADER));
            XRateRemaining = Integer.valueOf(headers.getFirst(X_RATELIMIT_REMAINING_HEADER));
            XRateReset = Integer.valueOf(headers.getFirst(X_RATELIMIT_RESET_HEADER));
            switch (jsonResponse.getStatus()){
                case 200:
                    return jsonResponse.getBody().getArray();
                case 401:
                    throw new ConnectException("Bad GitHub credentials provided, please edit your config");
                case 403:
                    // we have issues too many requests.
                    log.info(jsonResponse.getBody().getObject().getString("message"));
                    log.info(String.format("Your rate limit is %s", XRateLimit));
                    log.info(String.format("Your remaining calls is %s", XRateRemaining));
                    log.info(String.format("The limit will reset at %s",
                            LocalDateTime.ofInstant(Instant.ofEpochSecond(XRateReset), ZoneOffset.systemDefault())));
                    long sleepTime = XRateReset - Instant.now().getEpochSecond();
                    log.info(String.format("Sleeping for %s seconds", sleepTime ));
                    Thread.sleep(1000 * sleepTime);
                    return getNextIssues(page, since);
                default:
                    log.error(constructUrl(page, since));
                    log.error(String.valueOf(jsonResponse.getStatus()));
                    log.error(jsonResponse.getBody().toString());
                    log.error(jsonResponse.getHeaders().toString());
                    log.error("Unknown error: Sleeping 5 seconds " +
                            "before re-trying");
                    Thread.sleep(5000L);
                    return getNextIssues(page, since);
            }
        } catch (UnirestException e) {
            e.printStackTrace();
            Thread.sleep(5000L);
            return new JSONArray();
        }
    }
 
Example 19
Source File: Chat.java    From JavaTelegramBot-API with GNU General Public License v3.0 3 votes vote down vote up
/**
 * Gets a List of ChatMember objects for all the people who are admin in the chat
 *
 * @return A List of ChatMember objects for all the people who are admin in the chat
 */
default List<ChatMember> getChatAdministrators() {

    try {

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

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

            JSONArray jsonArray = jsonResponse.getJSONArray("result");

            List<ChatMember> chatAdmins = new ArrayList<>();

            for(int i = 0; i < jsonArray.length(); ++i) {

                JSONObject jsonObject = jsonArray.getJSONObject(i);

                chatAdmins.add(createChatMember(jsonObject));
            }

            return chatAdmins;
        }
    } catch (UnirestException e) {
        e.printStackTrace();
    }

    return null;
}
 
Example 20
Source File: HGraphQLService.java    From hypergraphql with Apache License 2.0 3 votes vote down vote up
Model getModelFromRemote(String graphQlQuery) {

        ObjectMapper mapper = new ObjectMapper();

        ObjectNode bodyParam = mapper.createObjectNode();

        bodyParam.put("query", graphQlQuery);

        Model model = ModelFactory.createDefaultModel();

        LOGGER.info("\n" + url);
        LOGGER.info("\n" + graphQlQuery);

        try {

            HttpResponse<InputStream> response = Unirest.post(url)
                    .header("Accept", "application/rdf+xml")
                    .body(bodyParam.toString())
                    .asBinary();

            model.read(response.getBody(), "RDF/XML");

        } catch (UnirestException e) {
            e.printStackTrace();
        }

        return model;
    }