Java Code Examples for com.squareup.okhttp.Response#message()

The following examples show how to use com.squareup.okhttp.Response#message() . 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: HarborClient.java    From harbor-java-client with Apache License 2.0 6 votes vote down vote up
/**
 * This endpoint returns all projects created by Harbor, and can be filtered
 * by project name.</br>
 * <b>URL</b>: /projects</br>
 * <b>Method</b>: GET
 *
 * @param projectName
 *            (Project name for filtering results)
 * @param isPublic
 *            (Public sign for filtering projects)
 * @return
 * @throws IOException
 * @throws HarborClientException
 */
public List<Project> getProjects(String projectName, String isPublic) throws IOException, HarborClientException {
	List<NameValuePair> qparams = new ArrayList<>();
	qparams.add(new BasicNameValuePair("project_name", projectName));
	qparams.add(new BasicNameValuePair("is_public", isPublic));
	qparams.removeIf(o -> Objects.isNull(o.getValue()));
	String url = getBaseUrl() + "projects?" + URLEncodedUtils.format(qparams, "UTF-8");
	Request request = new Request.Builder().url(url).get().build();
	Response response = okhttpClient.newCall(request).execute();
	logger.debug(String.format(REQUEST_RESPONSE_INFO, request, response));
	if (response.code() != 200) {
		throw new HarborClientException(String.valueOf(response.code()), response.message());
	}
	return mapper.readValue(response.body().string(), new TypeReference<List<Project>>() {
	});
}
 
Example 2
Source File: RestVolleyDownload.java    From RestVolley with Apache License 2.0 6 votes vote down vote up
/**
 * sync download.
 * @param localPath local file path
 * @return {@link DownloadResponse}
 */
public DownloadResponse syncDownload(String localPath) {
    File localFile = newFile(localPath + SUFIX_TMP);
    DownloadResponse downloadResponse = new DownloadResponse();
    bindOkHttpClient();
    try {
        Response result = mOkHttpClient.newCall(mRequestBuilder.build()).execute();
        //write stream to file
        File resultFile  = writeStream2File(result, localFile, mIsAppend, null) ? new File(localPath) : localFile;
        downloadResponse = new DownloadResponse(resultFile, result.headers(), result.code(), result.message());
    } catch (Exception e) {
        e.printStackTrace();
    }

    return downloadResponse;
}
 
Example 3
Source File: ApiClient.java    From nifi-api-client-java with Apache License 2.0 6 votes vote down vote up
/**
 * Handle the given response, return the deserialized object when the response is successful.
 *
 * @param <T> Type
 * @param response Response
 * @param returnType Return type
 * @throws ApiException If the response has a unsuccessful status code or
 *   fail to deserialize the response body
 * @return Type
 */
public <T> T handleResponse(Response response, Type returnType) throws ApiException {
    if (response.isSuccessful()) {
        if (returnType == null || response.code() == 204) {
            // returning null if the returnType is not defined,
            // or the status code is 204 (No Content)
            return null;
        } else {
            return deserialize(response, returnType);
        }
    } else {
        String respBody = null;
        if (response.body() != null) {
            try {
                respBody = response.body().string();
            } catch (IOException e) {
                throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap());
            }
        }
        throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody);
    }
}
 
Example 4
Source File: HarborClient.java    From harbor-java-client with Apache License 2.0 6 votes vote down vote up
/**
 * Let user see the recent operation logs of the projects which he is member
 * of.</br>
 * <b>URL</b>: /logs</br>
 * <b>Method</b>: GET
 *
 * @param lines
 *            (The number of logs to be shown, default is 10 if lines,
 *            start_time, end_time are not provided)
 * @param startTime
 *            (The start time of logs to be shown in unix timestap)
 * @param endTime
 *            (The end time of logs to be shown in unix timestap)
 * @return required logs.
 * @throws IOException
 * @throws HarborClientException
 */
public List<Log> getLogs(String lines, String startTime, String endTime) throws IOException, HarborClientException {
	logger.debug("get logs lines %s, start time %s, end time %s", lines, startTime, endTime);
	List<NameValuePair> qparams = new ArrayList<>();
	qparams.add(new BasicNameValuePair("lines", lines));
	qparams.add(new BasicNameValuePair("start_time", startTime));
	qparams.add(new BasicNameValuePair("end_time", endTime));
	qparams.removeIf(o -> Objects.isNull(o.getValue()));
	String url = getBaseUrl() + "/logs?" + URLEncodedUtils.format(qparams, "UTF-8");
	Request request = new Request.Builder().url(url).get().build();
	Response response = okhttpClient.newCall(request).execute();
	logger.debug(String.format(REQUEST_RESPONSE_INFO, request, response));
	if (response.code() != 200) {
		throw new HarborClientException(String.valueOf(response.code()), response.message());
	}
	return mapper.readValue(response.body().string(), new TypeReference<List<Log>>() {
	});
}
 
Example 5
Source File: HarborClient.java    From harbor-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Let users see the most popular public repositories.</br>
 * <b>URL</b>: /repositories/top</br>
 * <b>Method</b>: GET
 *
 * @param count
 *            (The number of the requested public repositories, default is
 *            10 if not provided)
 * @return Retrieved top repositories.
 * @throws IOException
 * @throws HarborClientException
 */
public List<PopRepo> getTopRepositories(String count) throws IOException, HarborClientException {
	String url = getBaseUrl() + "repositories/top";
	if (count != null) {
		url = url + "?count=" + count;
	}
	Request request = new Request.Builder().url(url).get().build();
	Response response = okhttpClient.newCall(request).execute();
	logger.debug(String.format(REQUEST_RESPONSE_INFO, request, response));
	if (response.code() != 200) {
		throw new HarborClientException(String.valueOf(response.code()), response.message());
	}
	return mapper.readValue(response.body().string(), new TypeReference<List<PopRepo>>() {
	});
}
 
Example 6
Source File: HttpClient.java    From zsync4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Retrieves the requested ranges for the resource referred to by the given uri.
 *
 * @param uri
 * @param ranges
 * @param receiver
 * @param listener
 * @throws IOException
 * @throws HttpError
 */
public void partialGet(URI uri, List<ContentRange> ranges, Map<String, ? extends Credentials> credentials,
    RangeReceiver receiver, RangeTransferListener listener) throws IOException, HttpError {
  final Set<ContentRange> remaining = new LinkedHashSet<>(ranges);
  while (!remaining.isEmpty()) {
    final List<ContentRange> next = copyOf(limit(remaining, min(remaining.size(), MAXIMUM_RANGES_PER_HTTP_REQUEST)));
    final HttpTransferListener requestListener = listener.newTransfer(next);
    final Response response = executeWithAuthRetry(uri, credentials, requestListener, next);
    final int code = response.code();
    // tolerate case that server does not support range requests
    if (code == HTTP_OK) {
      receiver.receive(new ContentRange(0, response.body().contentLength()), inputStream(response, requestListener));
      return;
    }
    // otherwise only accept partial content response
    if (code != HTTP_PARTIAL) {
      throw new HttpError(response.message(), code);
    }
    // check if we're dealing with multipart (multiple ranges) or simple (single range) response
    final MediaType mediaType = parseContentType(response);
    if (mediaType != null && "multipart".equals(mediaType.type())) {
      final byte[] boundary = getBoundary(mediaType);
      handleMultiPartBody(response, receiver, remaining, requestListener, boundary);
    } else {
      handleSinglePartBody(response, receiver, remaining, requestListener);
    }
  }
}
 
Example 7
Source File: Downloader.java    From external-resources with Apache License 2.0 5 votes vote down vote up
public Resources load(@Cache.Policy int policy) throws ExternalResourceException {
  buildUrl();

  Logger.i(ExternalResources.TAG, "Load configuration from url: " + url.build());

  final CacheControl cacheControl;
  switch (policy) {
    case Cache.POLICY_NONE:
      cacheControl = new CacheControl.Builder().noCache().noStore().build();
      break;
    case Cache.POLICY_OFFLINE:
      cacheControl = CacheControl.FORCE_CACHE;
      break;
    case Cache.POLICY_ALL:
    default:
      cacheControl = new CacheControl.Builder().build();
      break;
  }

  Logger.v(ExternalResources.TAG, "CachePolicy: " + policy);

  Request request = new Request.Builder().url(url.build()).cacheControl(cacheControl).build();

  try {
    Response response = client.newCall(request).execute();
    int responseCode = response.code();

    Logger.d(ExternalResources.TAG, "Response code: " + responseCode);
    if (responseCode >= 300) {
      response.body().close();
      throw new ResponseException(responseCode + " " + response.message(), policy, responseCode);
    }

    return converter.fromReader(response.body().charStream());
  } catch (IOException e) {
    throw new ExternalResourceException(e);
  }
}
 
Example 8
Source File: ApiClient.java    From ariADDna with Apache License 2.0 5 votes vote down vote up
/**
 * Handle the given response, return the deserialized object when the response is successful.
 *
 * @param <T> Type
 * @param response Response
 * @param returnType Return type
 * @throws ApiException If the response has a unsuccessful status code or
 *   fail to deserialize the response body
 * @return Type
 */
public <T> T handleResponse(Response response, Type returnType) throws ApiException {
    LOGGER.info("Method {handleResponse} was called with response code: {}, returnType is {}",
            response.code(), returnType == null ? null : returnType.getTypeName());
    if (response.isSuccessful()) {
        if (returnType == null || response.code() == 204) {
            // returning null if the returnType is not defined,
            // or the status code is 204 (No Content)
            return null;
        } else {
            return deserialize(response, returnType);
        }
    } else {
        String respBody = null;
        if (response.body() != null) {
            try {
                respBody = response.body().string();
            } catch (IOException e) {
                LOGGER.error(
                        "Method {handleResponse} was called, response code: {}, exception: {}",
                        response.code(), e.getStackTrace());
                throw new ApiException(response.message(), e, response.code(),
                        response.headers().toMultimap());
            }
        }
        LOGGER.error(
                "Method {handleResponse} was called, response.body() == null, response.code = {}, response.message() = {}, response.headers() = {}",
                response.code(), response.message(), response.headers().toMultimap());
        throw new ApiException(response.message(), response.code(),
                response.headers().toMultimap(), respBody);
    }
}
 
Example 9
Source File: HarborClient.java    From harbor-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve tags from a relevant repository.</br>
 * <b>URL</b>: /repositories/tags</br>
 * <b>Method</b>: GET
 *
 * @param repoName
 *            [required] (Relevant repository name)
 * @return RepositorieTags
 * @throws IOException
 * @throws HarborClientException
 */
public List<String> getRepositorieTags(String repoName) throws IOException, HarborClientException {
	String url = getBaseUrl() + "repositories/tags?repo_name=" + repoName;
	Request request = new Request.Builder().url(url).get().build();
	Response response = okhttpClient.newCall(request).execute();
	logger.debug(String.format(REQUEST_RESPONSE_INFO, request, response));
	if (response.code() != 200) {
		throw new HarborClientException(String.valueOf(response.code()), response.message());
	}
	return mapper.readValue(response.body().string(), new TypeReference<List<String>>() {
	});
}
 
Example 10
Source File: HarborClient.java    From harbor-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Let user search repositories accompanying with relevant project ID and
 * repo name.</br>
 * <b>URL</b>: /repositories</br>
 * <b>Method</b>: GET
 *
 * @param projectId
 *            [required] (Relevant project ID)
 * @param q
 *            (Repo name for filtering results)
 * @return respositories
 * @throws IOException
 * @throws HarborClientException
 */
public List<String> getRepositories(String projectId, String q) throws IOException, HarborClientException {
	String url = getBaseUrl() + "repositories?project_id=" + projectId;
	if (q != null) {
		url = url + "&q=" + q;
	}
	Request request = new Request.Builder().url(url).get().build();
	Response response = okhttpClient.newCall(request).execute();
	logger.debug(String.format(REQUEST_RESPONSE_INFO, request, response));
	if (response.code() != 200) {
		throw new HarborClientException(String.valueOf(response.code()), response.message());
	}
	return mapper.readValue(response.body().string(), new TypeReference<List<String>>() {
	});
}
 
Example 11
Source File: HarborClient.java    From harbor-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * For user to search a specified project's relevant role members.</br>
 * <b>URL</b>:/projects/{project_id}/members/</br>
 * <b>Method</b>: GET
 *
 * @param projectId
 *            [required] (Relevant project ID)
 * @return relevant role members
 * @throws IOException
 * @throws HarborClientException
 */
public List<ProjectMember> getProjectMembers(int projectId) throws IOException, HarborClientException {
	String url = getBaseUrl() + "projects/" + projectId + "/members/";
	Request request = new Request.Builder().url(url).get().build();
	Response response = okhttpClient.newCall(request).execute();
	logger.debug(String.format(REQUEST_RESPONSE_INFO, request, response));
	if (response.code() != 200) {
		throw new HarborClientException(String.valueOf(response.code()), response.message());
	}
	return mapper.readValue(response.body().string(), new TypeReference<List<ProjectMember>>() {
	});
}
 
Example 12
Source File: HawkularMetricsClient.java    From apiman with Apache License 2.0 4 votes vote down vote up
/**
 * @param response
 */
private static HawkularMetricsException hawkularMetricsError(Response response) {
    // TODO better error handling goes here.
    return new UnexpectedMetricsException(response.message());
}
 
Example 13
Source File: HarborClient.java    From harbor-java-client with Apache License 2.0 3 votes vote down vote up
/**
 * The Search endpoint returns information about the projects and
 * repositories offered at public status or related to the current logged in
 * user. </br>
 * <b>URL</b>: /search</br>
 * <b><b>Method</b>: GET</b>
 *
 * @param q
 *            [required] (Search parameter for project and repository name)
 * @return The response includes the project and repository list in a proper
 *         display order.
 * @throws IOException
 * @throws HarborClientException
 */
public Search search(String q) throws IOException, HarborClientException {
	String url = getBaseUrl() + "search?q=" + q;
	Request request = new Request.Builder().url(url).get().build();
	Response response = okhttpClient.newCall(request).execute();
	logger.debug(String.format(REQUEST_RESPONSE_INFO, request, response));
	if (response.code() != 200) {
		throw new HarborClientException(String.valueOf(response.code()), response.message());
	}
	return mapper.readValue(response.body().string(), Search.class);
}
 
Example 14
Source File: HarborClient.java    From harbor-java-client with Apache License 2.0 3 votes vote down vote up
/**
 * Retreive manifests from a relevant repository.</br>
 * <b>URL</b>: /repositories/manifests</br>
 * <b>Method</b>: GET
 *
 * @param repoName
 *            [required] (Repository name)
 * @param tag
 *            [required] (Tag name)
 * @return
 * @throws IOException
 * @throws HarborClientException
 */
public Manifest getManifest(String repoName, String tag) throws IOException, HarborClientException {
	String url = getBaseUrl() + "repositories/manifests?repo_name=" + repoName + "&tag=" + tag;
	Request request = new Request.Builder().url(url).get().build();
	Response response = okhttpClient.newCall(request).execute();
	logger.debug(String.format(REQUEST_RESPONSE_INFO, request, response));
	if (response.code() != 200) {
		throw new HarborClientException(String.valueOf(response.code()), response.message());
	}
	return mapper.readValue(response.body().string(), Manifest.class);
}
 
Example 15
Source File: HarborClient.java    From harbor-java-client with Apache License 2.0 3 votes vote down vote up
/**
 * Statistic all of the projects number and repositories number relevant to
 * the logined user, also the public projects number and repositories
 * number. </br>
 * <b>URL</b>: /statistics</br>
 * <b>Method</b>: GET
 *
 * @return The projects number and repositories number relevant to the user.
 * @throws IOException
 * @throws HarborClientException
 */
public ProjectAndRepoNum getStatistics() throws IOException, HarborClientException {
	String url = getBaseUrl() + "statistics";
	Request request = new Request.Builder().url(url).get().build();
	Response response = okhttpClient.newCall(request).execute();
	logger.debug(String.format(REQUEST_RESPONSE_INFO, request, response));
	if (response.code() != 200) {
		throw new HarborClientException(String.valueOf(response.code()), response.message());
	}
	return mapper.readValue(response.body().string(), ProjectAndRepoNum.class);
}
 
Example 16
Source File: HarborClient.java    From harbor-java-client with Apache License 2.0 3 votes vote down vote up
/**
 * For user to get role members accompany with relevant project and
 * user.</br>
 * <b>URL</b>: /projects/{project_id}/members/{user_id}</br>
 * <b>Method</b>: GET
 *
 * @param projectId
 *            [required] (Relevant project ID)
 * @param userId
 *            [required] (Relevant user ID)
 * @return role members
 * @throws IOException
 * @throws HarborClientException
 */
public Member getRole(int projectId, int userId) throws IOException, HarborClientException {
	String url = getBaseUrl() + "projects/" + projectId + "/members/" + userId;
	Request request = new Request.Builder().url(url).get().build();
	Response response = okhttpClient.newCall(request).execute();
	logger.debug(String.format(REQUEST_RESPONSE_INFO, request, response));
	if (response.code() != 200) {
		throw new HarborClientException(String.valueOf(response.code()), response.message());
	}
	return mapper.readValue(response.body().string(), Member.class);
}
 
Example 17
Source File: HttpClient.java    From zsync4j with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
/**
 * Opens a connection to the remote resource referred to by the given uri. The returned stream is
 * decorated with to report download progress to the given listener.
 *
 * @param uri The URI of the resource to retrieve
 * @param credentials The credentials for authenticating with remote hosts
 * @param listener Listener to monitor long running transfers
 * @return
 * @throws IOException
 * @throws HttpError
 */
public InputStream get(URI uri, Map<String, ? extends Credentials> credentials, HttpTransferListener listener)
    throws IOException, HttpError {
  final Response response = executeWithAuthRetry(uri, credentials, listener, Collections.<ContentRange>emptyList());
  final int code = response.code();
  if (code != HTTP_OK) {
    throw new HttpError(response.message(), code);
  }
  return inputStream(response, listener);
}