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

The following examples show how to use com.mashape.unirest.http.HttpResponse#getStatusText() . 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: RocketChatClientCallBuilder.java    From rocket-chat-rest-client with MIT License 7 votes vote down vote up
private void login() throws IOException {
      HttpResponse<JsonNode> loginResult;

      try {
          loginResult = Unirest.post(serverUrl + "v1/login").field("username", user).field("password", password).asJson();
      } catch (UnirestException e) {
          throw new IOException(e);
      }

      if (loginResult.getStatus() == 401)
          throw new IOException("The username and password provided are incorrect.");

      
if (loginResult.getStatus() != 200)
	throw new IOException("The login failed with a result of: " + loginResult.getStatus()
		+ " (" + loginResult.getStatusText() + ")");

      JSONObject data = loginResult.getBody().getObject().getJSONObject("data");
      this.authToken = data.getString("authToken");
      this.userId = data.getString("userId");
  }
 
Example 3
Source File: AuthHelper.java    From BotServiceStressToolkit with MIT License 6 votes vote down vote up
public static TokenResponse getToken(String appId, String clientSecret) throws AuthenticationException {

		HttpResponse<InputStream> postResponse;
		try {
			postResponse = Unirest.post("https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token")
					.field("grant_type", "client_credentials")
					.field("client_id", appId)
					.field("client_secret", clientSecret)
					.field("scope", String.format("%s/.default", appId)).asBinary();

			if (postResponse.getStatus() == 200) {
				Jsonb jsonb = JsonbBuilder.create();
				TokenResponse resp = jsonb.fromJson(postResponse.getBody(), TokenResponse.class);
				return resp;
			} else {
				throw new AuthenticationException("Status code is not 200: " + postResponse.getStatus()
						+ ". Response text: " + postResponse.getStatusText());
			}

		} catch (UnirestException e) {
			throw new AuthenticationException("Error authenticating Bot", e);
		}
	}
 
Example 4
Source File: GitHubSourceConnector.java    From apicurio-studio with Apache License 2.0 6 votes vote down vote up
/**
 * Uses the GH API to add a commit comment.
 * @param repositoryUrl
 * @param commitSha
 * @param commitComment
 * @throws UnirestException
 * @throws SourceConnectorException
 */
private void addCommitComment(String repositoryUrl, String commitSha, String commitComment)
        throws UnirestException, SourceConnectorException {
    GitHubCreateCommitCommentRequest body = new GitHubCreateCommitCommentRequest();
    body.setBody(commitComment);

    GitHubResource resource = resolver.resolve(repositoryUrl);
    String addCommentUrl = this.endpoint("/repos/:org/:repo/commits/:sha/comments")
        .bind("org", resource.getOrganization())
        .bind("repo", resource.getRepository())
        .bind("path", resource.getResourcePath())
        .bind("sha", commitSha)
        .toString();

    HttpRequestWithBody request = Unirest.post(addCommentUrl).header("Content-Type", "application/json; charset=utf-8");
    addSecurityTo(request);
    HttpResponse<JsonNode> response = request.body(body).asJson();
    if (response.getStatus() != 201) {
        throw new UnirestException("Unexpected response from GitHub: " + response.getStatus() + "::" + response.getStatusText());
    }
}
 
Example 5
Source File: AbstractAPIRequestException.java    From alpaca-java with MIT License 5 votes vote down vote up
/**
 * Instantiates a new Abstract api request exception.
 *
 * @param apiName      the api name
 * @param httpResponse the http response
 */
public AbstractAPIRequestException(String apiName, HttpResponse<InputStream> httpResponse) {
    super();

    this.apiName = apiName;
    this.httpResponse = httpResponse;

    this.requestStatusCode = httpResponse.getStatus();
    this.requestStatusText = httpResponse.getStatusText();
}
 
Example 6
Source File: RequestExecutor.java    From Bastion with GNU General Public License v3.0 5 votes vote down vote up
private Response convertToRawResponse(HttpResponse<InputStream> httpResponse) {
    return new RawResponse(httpResponse.getStatus(),
            httpResponse.getStatusText(),
            httpResponse.getHeaders().entrySet().stream().flatMap(header ->
                    header.getValue().stream().map(headerValue ->
                            new ApiHeader(header.getKey(), headerValue))).collect(Collectors.toList()),
            httpResponse.getBody());
}
 
Example 7
Source File: GitHubSourceConnector.java    From apicurio-studio with Apache License 2.0 5 votes vote down vote up
/**
 * @see io.apicurio.hub.api.connectors.ISourceConnector#createResourceContent(java.lang.String, java.lang.String, java.lang.String)
 */
@Override
public void createResourceContent(String repositoryUrl, String commitMessage, String content) throws SourceConnectorException {
    try {
        String b64Content = Base64.encodeBase64String(content.getBytes(StandardCharsets.UTF_8));

        GitHubResource resource = resolver.resolve(repositoryUrl);

        GitHubCreateFileRequest requestBody = new GitHubCreateFileRequest();
        requestBody.setMessage(commitMessage);
        requestBody.setContent(b64Content);
        requestBody.setBranch(resource.getBranch());

        String createContentUrl = this.endpoint("/repos/:org/:repo/contents/:path")
            .bind("org", resource.getOrganization())
            .bind("repo", resource.getRepository())
            .bind("path", resource.getResourcePath())
            .toString();

        HttpRequestWithBody request = Unirest.put(createContentUrl).header("Content-Type", "application/json; charset=utf-8");
        addSecurityTo(request);
        HttpResponse<InputStream> response = request.body(requestBody).asBinary();
        if (response.getStatus() != 201) {
            throw new UnirestException("Unexpected response from GitHub: " + response.getStatus() + "::" + response.getStatusText());
        }
    } catch (UnirestException e) {
        logger.error("Error creating Github resource content.", e);
        throw new SourceConnectorException("Error creating Github resource content.", e);
    }
}
 
Example 8
Source File: MicrocksConnector.java    From apicurio-studio with Apache License 2.0 5 votes vote down vote up
/**
 * Upload an OAS v3 specification content to Microcks. This will trigger service discovery and mock
 * endpoint publication on the Microcks side.
 * 
 * @param content OAS v3 specification content
 * @throws MicrocksConnectorException if upload fails for many reasons
 */
public String uploadResourceContent(String content) throws MicrocksConnectorException {
    String oauthToken = this.getKeycloakOAuthToken();
    MultipartBody uploadRequest = Unirest.post(this.apiURL + "/artifact/upload")
            .header("Authorization", "Bearer " + oauthToken)
            .field("file", new ByteArrayInputStream(content.getBytes(Charset.forName("UTF-8"))), "open-api-contract.yml");

    HttpResponse<String> response = null;
    try {
        response = uploadRequest.asString();
    } catch (UnirestException e) {
        logger.error("Exception while connecting to Microcks backend", e);
        throw new MicrocksConnectorException("Exception while connecting Microcks backend. Check URL.");
    }

    switch (response.getStatus()) {
        case 201:
            String serviceRef = response.getBody();
            logger.info("Microcks mocks have been created/updated for " + serviceRef);
            return serviceRef;
        case 204:
            logger.warn("NoContent returned by Microcks server");
            throw new MicrocksConnectorException(
                    "NoContent returned by Microcks server is unexpected return");
        case 400:
            logger.error(
                    "ClientRequestMalformed returned by Microcks server: " + response.getStatusText());
            throw new MicrocksConnectorException("ClientRequestMalformed returned by Microcks server");
        case 500:
            logger.error("InternalServerError returned by Microcks server");
            throw new MicrocksConnectorException("InternalServerError returned by Microcks server");
        default:
            logger.error("Unexpected response from Microcks server: " + response.getStatusText());
            throw new MicrocksConnectorException(
                    "Unexpected response by Microcks server: " + response.getStatusText());
    }
}
 
Example 9
Source File: SpeedInfo.java    From OpenWokuan with Do What The F*ck You Want To Public License 5 votes vote down vote up
public void refreshInfo() throws UnirestException, HttpResponseException {
    HttpResponse<String> infoResp = Unirest.get("http://bj.wokuan.cn/web/startenrequest.php?ComputerMac={ComputerMac}&ADSLTxt={ADSLTxt}&Type=2&reqsn={reqsn}&oem=00&ComputerId={ComputerId}")
            .routeParam("ComputerMac", rMac)
            .routeParam("ADSLTxt", accID)
            .routeParam("reqsn", genReqSN())
            .routeParam("ComputerId", cID)
            .header("Accept", SpeedBooster.httpAccept)
            .header("Accept-Language", SpeedBooster.httpLang)
            .header("User-Agent", SpeedBooster.httpUA)
            .asString();
    if (infoResp.getStatus() == 200) {
        Document respDoc = Jsoup.parse(infoResp.getBody());
        String[] respArgs = respDoc.getElementById("webcode").text().split("&");
        for (String it : respArgs) {
            String[] kp = it.split("=");
            if (kp[0].equalsIgnoreCase("ov")) actionStatus = kp[1];
            if (kp[0].equalsIgnoreCase("os")) oldSpeed = Integer.parseInt(kp[1]);
            if (kp[0].equalsIgnoreCase("up")) upSpeed = Integer.parseInt(kp[1]);
            if (kp[0].equalsIgnoreCase("glst")) hoursLeft = Float.parseFloat(kp[1]);
            if (kp[0].equalsIgnoreCase("gus")) upSpeedID = kp[1];
            if (kp[0].equalsIgnoreCase("old")) oldSpeedID = kp[1];
            if (kp[0].equalsIgnoreCase("cn")) accID = kp[1];//*
            if (kp[0].equalsIgnoreCase("stu")) isBoosting = kp[1].equals("1");
            if (kp[0].equalsIgnoreCase("random")) ranNum = Integer.parseInt(kp[1]);
        }
    } else
        throw new HttpResponseException(infoResp.getStatus(), infoResp.getStatusText());
}
 
Example 10
Source File: MockPublicKeyConnector.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public void register(PublicKeyRegisterRequest request) {
    try {
        String mockEndpoint = getMockEndpoint(request.getCredential());
        HttpResponse<String> response = Unirest.post(mockEndpoint + "/spi/register_public_key").body(request.getPublicKeyId()).asString();
        if (response.getStatus() != 200) {
            throw new CloudConnectorException(response.getStatusText());
        }
    } catch (UnirestException e) {
        throw new CloudConnectorException(e.getMessage(), e);
    }
}
 
Example 11
Source File: MockPublicKeyConnector.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public void unregister(PublicKeyUnregisterRequest request) {
    try {
        String mockEndpoint = getMockEndpoint(request.getCredential());
        HttpResponse<String> response = Unirest.post(mockEndpoint + "/spi/unregister_public_key").body(request.getPublicKeyId()).asString();
        if (response.getStatus() != 200) {
            throw new CloudConnectorException(response.getStatusText());
        }
    } catch (UnirestException e) {
        throw new CloudConnectorException(e.getMessage(), e);
    }
}
 
Example 12
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 13
Source File: BaseBotSampler.java    From BotServiceStressToolkit with MIT License 4 votes vote down vote up
protected void ensureResponseSuccess(@SuppressWarnings("rawtypes") HttpResponse response)
		throws HttpResponseException {
	if (response.getStatus() > 400) {
		throw new HttpResponseException(response.getStatus(), response.getStatusText());
	}
}
 
Example 14
Source File: GitHubSourceConnector.java    From apicurio-studio with Apache License 2.0 4 votes vote down vote up
/**
 * @see io.apicurio.hub.api.connectors.ISourceConnector#updateResourceContent(java.lang.String, java.lang.String, java.lang.String, io.apicurio.hub.api.beans.ResourceContent)
 */
@Override
public String updateResourceContent(String repositoryUrl, String commitMessage, String commitComment,
        ResourceContent content) throws SourceConnectorException {
    try {
        String b64Content = Base64.encodeBase64String(content.getContent().getBytes(StandardCharsets.UTF_8));

        GitHubResource resource = resolver.resolve(repositoryUrl);

        GitHubUpdateFileRequest requestBody = new GitHubUpdateFileRequest();
        requestBody.setMessage(commitMessage);
        requestBody.setContent(b64Content);
        requestBody.setSha(content.getSha());
        requestBody.setBranch(resource.getBranch());

        String createContentUrl = this.endpoint("/repos/:org/:repo/contents/:path")
            .bind("org", resource.getOrganization())
            .bind("repo", resource.getRepository())
            .bind("path", resource.getResourcePath())
            .toString();

        HttpRequestWithBody request = Unirest.put(createContentUrl).header("Content-Type", "application/json; charset=utf-8");
        addSecurityTo(request);
        HttpResponse<JsonNode> response = request.body(requestBody).asJson();
        if (response.getStatus() != 200) {
            throw new UnirestException("Unexpected response from GitHub: " + response.getStatus() + "::" + response.getStatusText());
        }
        JsonNode node = response.getBody();
        String newSha = node.getObject().getJSONObject("content").getString("sha");
        
        if (commitComment != null && !commitComment.trim().isEmpty()) {
            String commitSha = node.getObject().getJSONObject("commit").getString("sha");
            this.addCommitComment(repositoryUrl, commitSha, commitComment);
        }
        
        return newSha;
    } catch (UnirestException e) {
        logger.error("Error updating Github resource content.", e);
        throw new SourceConnectorException("Error updating Github resource content.", e);
    }
}
 
Example 15
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);
    }
}
 
Example 16
Source File: BitbucketSourceConnector.java    From apicurio-studio with Apache License 2.0 4 votes vote down vote up
/**
 * @see io.apicurio.hub.api.bitbucket.IBitbucketSourceConnector#getBranches(java.lang.String, java.lang.String)
 */
@Override
public Collection<SourceCodeBranch> getBranches(String group, String repo)
        throws BitbucketException, SourceConnectorException {
    try {
        //@formatter:off
        String branchesUrl = endpoint("/repositories/:uname/:repo/refs/branches")
                .bind("uname", group)
                .bind("repo", repo)
                .queryParam("pagelen", "25")
                .toString();
        //@formatter:on;

        Collection<SourceCodeBranch> rVal =  new HashSet<>();
        boolean done = false;

        while (!done) {
            HttpRequest request = Unirest.get(branchesUrl);
            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 -> {
                JSONObject b = (JSONObject) obj;
                SourceCodeBranch branch = new SourceCodeBranch();
                branch.setName(b.getString("name"));
                branch.setCommitId(b.getJSONObject("target").getString("hash"));
                rVal.add(branch);
            });
            
            done = true;
            if (responseObj.has("next")) {
                String next = responseObj.getString("next");
                if (!StringUtils.isEmpty(next) && !next.equals(branchesUrl)) {
                    done = false;
                    branchesUrl = next;
                }
            }
        }

        return rVal;

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