下面列出了org.apache.http.client.HttpResponseException#getStatusCode ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* wfapi describe
* @param jobName
* @param buildNo
*/
public WfWithDetails getWfDescribe(String jobName, int buildNo) throws IOException
{
String path = "/";
try {
JenkinsClient client = getClient();
WfWithDetails wfWithDetails = getClient().get(path + "job/" + EncodingUtils.encode(jobName) + "/" + buildNo + "/wfapi/describe", WfWithDetails.class);
wfWithDetails.setClient(client);
setBuildingInfo(wfWithDetails, jobName);
return wfWithDetails;
} catch (HttpResponseException e) {
// LOGGER.debug("getWfDescribe(jobName={}) status={}", jobName, e.getStatusCode());
if (e.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
return null;
}
throw e;
}
}
public Stage getWfNodeDescribe(String jobName, int buildNo, int stageId) throws IOException {
String path = "/";
try {
JenkinsClient client = getClient();
Stage stage = client.get(path + "job/" + EncodingUtils.encode(jobName) + "/" + buildNo + "/execution/node/" + stageId + "/wfapi/describe", Stage.class);
if (null != stage && CollectionUtils.isNotEmpty(stage.getStageFlowNodes())) {
stage.setClient(client);
for (StageFlowNodes stageFlowNode : stage.getStageFlowNodes()) {
int nodeId = stageFlowNode.getId();
StageFlowNodesLog log = client.get(path + "job/" + EncodingUtils.encode(jobName) + "/" + buildNo + "/execution/node/" + nodeId + "/wfapi/log", StageFlowNodesLog.class);
log.setClient(client);
stageFlowNode.setLog(log);
}
}
return stage;
} catch (HttpResponseException e) {
// LOGGER.debug("getWfDescribe(jobName={}) status={}", jobName, e.getStatusCode());
if (e.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
return null;
}
throw e;
}
}
private QueryResponse query(URIBuilder builder, HttpEntity entity) throws IOException, URISyntaxException {
if (cred != null && !cred.isEmpty()) {
builder = builder.addParameter("access_token", getAccessToken());
}
QueryResponse response = null;
try {
response = query(builder.build(), entity);
} catch (HttpResponseException ex) {
if (ex.getStatusCode() == 401) {
clearToken();
if (cred != null && !cred.isEmpty()) {
builder = builder.addParameter("access_token", getAccessToken());
}
response = query(builder.build(), entity);
} else {
throw ex;
}
}
return response;
}
/**
* Reads item metadata.
* @param itemId item id
* @param format metadata format
* @param token token
* @return item metadata if available
* @throws URISyntaxException if invalid URL
* @throws IOException if operation fails
*/
public String readItemMetadata(String itemId, MetadataFormat format, String token) throws IOException, URISyntaxException {
URIBuilder builder = new URIBuilder(itemMetaUri(itemId));
builder.setParameter("format", (format != null ? format : MetadataFormat.DEFAULT).toString());
if (token!=null) {
builder.setParameter("token", token);
}
HttpGet req = new HttpGet(builder.build());
try {
return execute(req, 0);
} catch (HttpResponseException ex) {
if (ex.getStatusCode() == 500) {
return null;
}
throw ex;
}
}
/**
* Delete the credential stored in the specified user's domain.
*
* @param userName jenkins user name
* @param domainName name of domain
* @param credentialId credentialId
* @throws IOException
*/
public void deleteUserDomainCredential(String userName, String domainName, String credentialId) throws IOException {
String path = "/user/" + userName + "/credentials/store/user/domain/" + domainName + "/credential/" + credentialId;
try {
client.post(path + "/doDelete", false);
logger.info("deleted credential at " + path);
} catch (HttpResponseException e) {
if (e.getStatusCode() == 404) {
logger.debug("received 404 while trying to delete credential at " + path);
} else {
logger.error("error deleting credential at " + path);
logger.error("message = " + e.getMessage());
throw e;
}
}
}
private JSONArray getJSONArray(String url) throws IOException, CredentialInvalidException {
try {
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Bearer " + authToken);
headers.put("Content-Type", "application/json");
headers.put("Accept", "application/json");
final String httpResponse = httpGet(url, "UTF-8", headers);
return new JSONArray(httpResponse);
} catch (HttpResponseException httpResponseException) {
if (httpResponseException.getStatusCode() == 404) {
return null;
}
throw httpResponseException;
} catch (JSONException e) {
throw new IOException(e);
}
}
@GuardedBy("lock")
void authenticate(HttpClient client) throws IOException {
if (id == null || id.isEmpty() || password == null || password.isEmpty()) {
invalid = "Unable to re-authenticate expired token: missing appleId/ password.";
} else {
try {
Auth auth = Auth.from(client, id, password);
if (auth.dsPrsID().equals(token.auth().dsPrsID())) {
token = Token.from(auth);
} else {
logger.error("-- reauthentication() > mismatched dsPrsID: {} > {}",
token.auth().dsPrsID(), auth.dsPrsID());
invalid = "Unable to re-authenticate expired token: account mismatch.";
}
} catch (HttpResponseException ex) {
if (ex.getStatusCode() == 401) {
invalid = "Unable to re-authenticate expired token: invalid appleId/ password.";
}
}
}
testIsInvalid();
}
@Subscribe public void onServiceError(ServiceErrorEvent event) {
final Exception error = event.getError();
if (error instanceof HttpResponseException) {
HttpResponseException httpError = (HttpResponseException) error;
if (httpError.getStatusCode() == 403) {
mService.logout();
Toast.makeText(mActivity, R.string.unauthorized, Toast.LENGTH_LONG).show();
mActivity.startActivity(new Intent(mActivity, WelcomeActivity.class));
mActivity.finish();
return;
}
}
new AlertDialog.Builder(mActivity)
.setTitle(R.string.error)
.setMessage(error.toString())
.setPositiveButton(android.R.string.ok, null)
.show();
}
private DataReference readContent() throws IOException, URISyntaxException {
WafFile file = files.poll();
try {
return file.readContent(httpClient, iteratorContext.getLastHarvestDate());
} catch (HttpResponseException ex) {
if (ex.getStatusCode()!=403 && ex.getStatusCode()!=404) {
throw ex;
}
return null;
}
}
/**
* Reads content of the folder.
* @param httpClient HTTP client
* @return content
* @throws IOException if error reading content
* @throws URISyntaxException if invalid URL
*/
public WafFolderContent readContent(CloseableHttpClient httpClient) throws IOException, URISyntaxException {
List<WafFile> files = new ArrayList<>();
List<WafFolder> subFolders = new ArrayList<>();
HtmlUrlScrapper scrapper = new HtmlUrlScrapper(httpClient, creds);
try {
List<URL> urls = scrapper.scrap(folderUrl);
for (URL u: urls) {
if (Thread.currentThread().isInterrupted()) {
return new WafFolderContent(this, Collections.emptyList(), Collections.emptyList());
}
if (u.toExternalForm().endsWith("/") || !cutOff(u.toExternalForm(),"/").contains(".")) {
subFolders.add(new WafFolder(broker, u, matchPattern, creds));
} else if (StringUtils.isBlank(matchPattern) || multiMatchUrl(u,matchPattern)) {
files.add(new WafFile(broker, u, creds));
}
}
} catch (HttpResponseException ex) {
if (ex.getStatusCode()!=403) {
throw ex;
}
}
LOG.debug(formatForLog("WAF FILES in %s: %s",folderUrl,files.toString()));
LOG.debug(formatForLog("WAF SUBFOLDERS in %s: %s",folderUrl,subFolders.toString()));
return new WafFolderContent(this, subFolders, files);
}
/**
* Reads metadata.
*
* @param id id of the metadata
* @return string representing metadata
* @throws URISyntaxException if invalid URI
* @throws IOException if reading metadata fails
*/
public String readXml(String id) throws URISyntaxException, IOException {
URI xmlUri = createXmlUri(id);
try {
return readContent(xmlUri);
} catch (HttpResponseException ex) {
if (ex.getStatusCode() == 401) {
clearToken();
xmlUri = createXmlUri(id);
return readContent(xmlUri);
} else {
throw ex;
}
}
}
/**
* Deletes record by id.
*
* @param id record id
* @return publish response
* @throws IOException if reading response fails
* @throws URISyntaxException if URL has invalid syntax
*/
public PublishResponse delete(String id) throws URISyntaxException, IOException {
URI deleteUri = createItemUri(id);
try {
return delete(deleteUri);
} catch (HttpResponseException ex) {
if (ex.getStatusCode() == 401) {
clearToken();
deleteUri = createItemUri(id);
return delete(deleteUri);
} else {
throw ex;
}
}
}
public void deletePipeline(FolderJob folder, String pipeline) throws IOException {
try {
jenkins.deleteJob(folder, pipeline);
logger.info("Deleted pipeline " + pipeline);
} catch(HttpResponseException e) {
if(e.getStatusCode() != 404) {
throw e;
}
}
}
public void deleteFolder(String folder) throws IOException {
try {
jenkins.deleteJob(folder);
logger.info("Deleted folder " + folder);
} catch(HttpResponseException e) {
if(e.getStatusCode() != 404) {
throw e;
}
}
}
private JSONArray getJSONArray(String url) throws IOException, JSONException, CredentialInvalidException {
try {
return new JSONArray(httpGet(url, "UTF-8"));
} catch (HttpResponseException httpResponseException) {
if (httpResponseException.getStatusCode() == 404) {
return null;
}
throw httpResponseException;
}
}
private void handleHttpResponseException(HttpResponseException e)
throws CredentialInvalidException, HttpResponseException {
if (e.getStatusCode() == 401 || e.getStatusCode() == 403) {
throw new CredentialInvalidException();
} else {
throw e;
}
}
/**
* Get a single Job from the server.
*
* @return A single Job, null if not present
* @throws IOException
*/
public JobWithDetails getJob(String jobName) throws IOException {
try {
JobWithDetails job = client.get("/job/"+encode(jobName),JobWithDetails.class);
job.setClient(client);
return job;
} catch (HttpResponseException e) {
if(e.getStatusCode() == 404) {
return null;
}
throw e;
}
}
/**
* Try to download file, if download server is handling too many requests, will retry to download file after a few
* seconds again, the max retry count and retry-after time are set in the profile.
*
*/
private void tryDownloadFile(String fileName, Path destination) throws Exception {
if (log.isTraceEnable()) {
log.info(this, "try to download file " + fileName + " to " + destination);
}
DownloadResult result = DownloadResult.FAILURE;
this.retryCount = DataConvertHelper
.toInt(this.getConfigManager().getFeatureConfiguration(this.feature, "download.retry.count"), 20);
while (retryCount-- > 0) {
try {
if (downloadFile(fileName, destination)) {
result = DownloadResult.SUCCESS;
if (log.isTraceEnable()) {
log.info(this, "Download file: " + fileName + " successfully");
}
break;
}
}
catch (Exception ex) {
if (ex instanceof HttpResponseException) {
HttpResponseException hre = (HttpResponseException) ex;
if (hre.getStatusCode() != UpgradeConstants.HTTP_CODE_TOO_MANY_REQUESTS) {
throw ex;
}
if (log.isTraceEnable()) {
log.info(this,
"Server now is handling too many download requests, so need one more retry after "
+ retryAfter + " seconds");
}
ThreadHelper.suspend(retryAfter * 1000);
result = DownloadResult.SERVER_BUSY;
continue;
}
else {
result = DownloadResult.FAILURE;
break;
}
}
}
if (result == DownloadResult.SERVER_BUSY) {
if (log.isTraceEnable()) {
log.err(this, "Reached the max value of retry count, so download task was failed");
}
throw new Exception("Server busy");
}
else if (result == DownloadResult.FAILURE) {
if (log.isTraceEnable()) {
log.err(this, "Failed to download file: " + fileName);
}
throw new Exception("Failed to download");
}
}
/**
*
* @param url
* the url to retrive
* @param lastModified
* header we got last time we queried that url, or null
* @param eTag
* header we got last time we queried that url, or null
* @return
* @throws ClientProtocolException
* @throws IOException
* @throws NotModifiedException
* if the url hasn't changed since we asked for it last time
*/
public HttpResult getBinary(String url, String lastModified, String eTag, int timeout) throws ClientProtocolException, IOException,
NotModifiedException {
HttpResult result = null;
long start = System.currentTimeMillis();
CloseableHttpClient client = newClient(timeout);
CloseableHttpResponse response = null;
try {
HttpGet httpget = new HttpGet(url);
HttpClientContext context = HttpClientContext.create();
httpget.addHeader(HttpHeaders.ACCEPT_LANGUAGE, ACCEPT_LANGUAGE);
httpget.addHeader(HttpHeaders.PRAGMA, PRAGMA_NO_CACHE);
httpget.addHeader(HttpHeaders.CACHE_CONTROL, CACHE_CONTROL_NO_CACHE);
httpget.addHeader(HttpHeaders.USER_AGENT, userAgent);
if (lastModified != null) {
httpget.addHeader(HttpHeaders.IF_MODIFIED_SINCE, lastModified);
}
if (eTag != null) {
httpget.addHeader(HttpHeaders.IF_NONE_MATCH, eTag);
}
try {
response = client.execute(httpget, context);
int code = response.getStatusLine().getStatusCode();
if (code == HttpStatus.SC_NOT_MODIFIED) {
throw new NotModifiedException("'304 - not modified' http code received");
} else if (code >= 300) {
throw new HttpResponseException(code, "Server returned HTTP error code " + code);
}
} catch (HttpResponseException e) {
if (e.getStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
throw new NotModifiedException("'304 - not modified' http code received");
} else {
throw e;
}
}
Header lastModifiedHeader = response.getFirstHeader(HttpHeaders.LAST_MODIFIED);
String lastModifiedHeaderValue = lastModifiedHeader == null ? null : StringUtils.trimToNull(lastModifiedHeader.getValue());
if (lastModifiedHeaderValue != null && StringUtils.equals(lastModified, lastModifiedHeaderValue)) {
throw new NotModifiedException("lastModifiedHeader is the same");
}
Header eTagHeader = response.getFirstHeader(HttpHeaders.ETAG);
String eTagHeaderValue = eTagHeader == null ? null : StringUtils.trimToNull(eTagHeader.getValue());
if (eTag != null && StringUtils.equals(eTag, eTagHeaderValue)) {
throw new NotModifiedException("eTagHeader is the same");
}
HttpEntity entity = response.getEntity();
byte[] content = null;
String contentType = null;
if (entity != null) {
content = EntityUtils.toByteArray(entity);
if (entity.getContentType() != null) {
contentType = entity.getContentType().getValue();
}
}
String urlAfterRedirect = url;
if (context.getRequest() instanceof HttpUriRequest) {
HttpUriRequest req = (HttpUriRequest) context.getRequest();
HttpHost host = context.getTargetHost();
urlAfterRedirect = req.getURI().isAbsolute() ? req.getURI().toString() : host.toURI() + req.getURI();
}
long duration = System.currentTimeMillis() - start;
result = new HttpResult(content, contentType, lastModifiedHeaderValue, eTagHeaderValue, duration, urlAfterRedirect);
} finally {
IOUtils.closeQuietly(response);
IOUtils.closeQuietly(client);
}
return result;
}
public static Auth authenticate(HttpClient httpClient, String id, String password) throws IOException {
logger.trace("<< authenticate() < id: {} password: {}", id, password);
AuthenticationRequestFactory authenticationRequestFactory = AuthenticationRequestFactory.instance();
PropertyListResponseHandler<NSDictionary> nsDictionaryResponseHandler
= PropertyListResponseHandler.dictionary();
try {
HttpUriRequest request = authenticationRequestFactory.apply(id, password);
NSDictionary authentication = httpClient.execute(request, nsDictionaryResponseHandler);
logger.debug("-- authenticate() - authentication: {}", authentication.toASCIIPropertyList());
NSDictionary appleAccountInfo = PListsLegacy.getAs(authentication, "appleAccountInfo", NSDictionary.class);
String dsPrsID = PListsLegacy.getAs(appleAccountInfo, "dsPrsID", NSNumber.class).toString();
NSDictionary tokens = PListsLegacy.getAs(authentication, "tokens", NSDictionary.class);
String mmeAuthToken = PListsLegacy.getAs(tokens, "mmeAuthToken", NSString.class).getContent();
logger.debug("-- authenticate() - dsPrsID: {}", dsPrsID);
logger.debug("-- authenticate() - mmeAuthToken: {}", mmeAuthToken);
Auth auth = new Auth(dsPrsID, mmeAuthToken);
logger.trace(">> authenticate() > auth: {}", auth);
return auth;
} catch (HttpResponseException ex) {
logger.warn("--authenticate() - HttpResponseException: {}", ex.getMessage());
int statusCode = ex.getStatusCode();
if (statusCode == 401) {
throw new HttpResponseException(statusCode, "Bad appleId/ password or not an iCloud account?");
}
if (statusCode == 409) {
throw new HttpResponseException(statusCode, "Two-step enabled or partial iCloud account activation?");
}
throw ex;
}
}