下面列出了org.apache.http.HttpStatus#SC_NOT_FOUND 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Throws if not ok
*/
private void handleStatus( HttpUriRequest method, StatusLine statusLine, int status ) throws KettleException {
if ( status >= 300 ) {
String message;
if ( status == HttpStatus.SC_NOT_FOUND ) {
message = String.format( "%s%s%s%s",
BaseMessages.getString( PKG, "SlaveServer.Error.404.Title" ),
Const.CR, Const.CR,
BaseMessages.getString( PKG, "SlaveServer.Error.404.Message" )
);
} else {
message = String.format( "HTTP Status %d - %s - %s",
status,
method.getURI().toString(),
statusLine.getReasonPhrase() );
}
throw new KettleException( message );
}
}
@Override
public FetchedResult get(String originalUrl, Payload payload) throws BaseFetchException {
final int responseRate = 1000;
final String mimeType = "text/plain";
Headers headers = new Headers();
int statusCode = HttpStatus.SC_MOVED_PERMANENTLY;
String redirectedUrl = _redirections.get(originalUrl);
if (redirectedUrl == null) {
redirectedUrl = originalUrl;
statusCode = HttpStatus.SC_NOT_FOUND;
} else {
headers.add(Headers.LOCATION, redirectedUrl);
}
// With max redirects set to 0, we don't get the redirected URL in the "actually fetched"
// field of the FetchedResult (it's in the headers Location:xxx entry).
FetchedResult result = new FetchedResult(originalUrl, originalUrl, 0, headers, new byte[0],
mimeType, responseRate, payload, originalUrl, 0, "192.168.1.1", statusCode, null);
return result;
}
/**
* This method will be used to check whether the a Scope exists for the given scope name in the authorization
* server.
*
* @param scopeName Scope Name
* @return whether scope exists or not
* @throws APIManagementException if an error occurs while checking the existence of the scope
*/
@Override
public boolean isScopeExists(String scopeName) throws APIManagementException {
try (Response response = scopeClient.isScopeExist(scopeName)) {
if (response.status() == HttpStatus.SC_OK) {
return true;
} else if (response.status() != HttpStatus.SC_NOT_FOUND) {
String responseString = readHttpResponseAsString(response.body());
String errorMessage = "Error occurred while checking existence of scope: " + scopeName + ". Error " +
"Status: " + response.status() + " . Error Response: " + responseString;
throw new APIManagementException(errorMessage);
}
} catch (KeyManagerClientException e) {
handleException("Error while check scope exist", e);
}
return false;
}
/**
* RtPlugin enable() must throw UnexpectedResponseException
* if service responds with 404.
* @throws Exception If something goes wrong.
*/
@Test(expected = UnexpectedResponseException.class)
public void failsToEnableItselfWhenNotInstalled() throws Exception {
final Plugin plugin = new RtPlugin(
Json.createObjectBuilder().build(),
new AssertRequest(
new Response(
HttpStatus.SC_NOT_FOUND
),
new Condition(
"Method should be a POST",
req -> "POST".equals(req.getRequestLine().getMethod())
),
new Condition(
"Resource path must be /{name}/enable",
req -> req.getRequestLine().getUri()
.endsWith("/sshfs/enable")
)
),
URI.create("http://localhost/plugins/sshfs"),
DOCKER
);
plugin.enable();
}
/**
* 不正な認証情報を使用してすべてのユーザがread可能なコレクションに対して$batchをした場合処理が受付けられること.
* batchの実行順
* 1.POST(登録)
* 2.GET(一覧取得)
* 3.GET(取得)
* 4.PUT(更新)
* 5.DELETE(削除)
*/
@Test
public final void 不正な認証情報を使用してすべてのユーザがread可能なコレクションに対して$batchをした場合処理が受付けられること() {
// 認証トークン取得
String invalidToken = "invalid token";
// ACL設定
String path = String.format("%s/%s/%s", TEST_CELL1, BOX_NAME, COL_NAME);
DavResourceUtils.setACLPrincipalAll(TEST_CELL1, MASTER_TOKEN, HttpStatus.SC_OK,
path, "<D:read />", "");
// READ→OK WRITE→403
TResponse res = UserDataUtils.batch(TEST_CELL1, BOX_NAME, COL_NAME, BOUNDARY, TEST_BODY,
invalidToken, HttpStatus.SC_ACCEPTED);
// 期待するレスポンスコード
int[] expectedCodes = new int[] {HttpStatus.SC_FORBIDDEN,
HttpStatus.SC_OK,
HttpStatus.SC_NOT_FOUND,
HttpStatus.SC_FORBIDDEN,
HttpStatus.SC_FORBIDDEN };
// レスポンスボディのチェック(ステータス)
checkBatchResponseBody(res, expectedCodes);
}
/**
* Given the result of trying to fetch the robots.txt file, decide how long until we retry (or
* refetch) it again.
*
* @param statusCode
* @return interval to wait, in milliseconds.
*/
private long calcRobotsFetchRetryDelay(int statusCode) {
if (statusCode == HttpStatus.SC_OK) {
return 12L * 60 * 60 * 1000;
} else if (statusCode == HttpStatus.SC_NOT_FOUND) {
return 24L * 60 * 60 * 1000;
} else if (statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
return 1L * 60 * 60 * 1000;
} else {
// Other errors usually indicate that the server is miss-configured,
// and we really want to treat it as a "not found" (even though we
// don't currently).
return 24L * 60 * 60 * 1000;
}
}
/**
* Please see list of status codes and their meaning:
* <br><br>
* 204 No Content: URN is in database. No further information asked.<br>
* 301 Moved Permanently: The given URN is replaced with a newer version.
* This newer version should be used instead.<br>
* 404 Not Found: The given URN is not registered in system.<br>
* 410 Gone: The given URN is registered in system but marked inactive.<br>
*
* @return the status code of the request
*/
public Optional<Date> register(MCRPIRegistrationInfo urn) {
String url = getBaseServiceURL(urn);
CloseableHttpResponse response = MCRHttpsClient.head(url);
StatusLine statusLine = response.getStatusLine();
if (statusLine == null) {
LOGGER.warn("HEAD request for {} returns no status line.", url);
return Optional.empty();
}
int headStatus = statusLine.getStatusCode();
String identifier = urn.getIdentifier();
switch (headStatus) {
case HttpStatus.SC_NO_CONTENT:
LOGGER.info("URN {} is in database. No further information asked.", identifier);
LOGGER.info("Performing update of url.");
return update(urn);
case HttpStatus.SC_NOT_FOUND:
LOGGER.info("The given URN {} is not registered in system.", identifier);
return registerNew(urn);
case HttpStatus.SC_MOVED_PERMANENTLY:
LOGGER.warn("The given URN {} is replaced with a newer version. \n "
+ "This newer version should be used instead.", identifier);
break;
case HttpStatus.SC_GONE:
LOGGER.warn("The given URN {} is registered in system but marked inactive.", identifier);
break;
default:
LOGGER.warn("Could not handle request for urnInfo {} Status code {}.", identifier, headStatus);
break;
}
return Optional.empty();
}
@Override
public FetchedResult get(String urlToFetch, Payload payload) throws BaseFetchException {
Iterator<String> outlinksIter = _graph.getChildren(urlToFetch);
if (outlinksIter == null) {
return new FetchedResult(urlToFetch, urlToFetch, System.currentTimeMillis(),
new Headers(), new byte[0], "text/plain", 0, null, urlToFetch, 0, "127.0.0.1",
HttpStatus.SC_NOT_FOUND, "");
} else if (!isValidMimeType(TEXT_MIME_TYPE)) {
throw new AbortedFetchException(urlToFetch, "Invalid mime-type: " + TEXT_MIME_TYPE,
AbortedFetchReason.INVALID_MIMETYPE);
} else {
int outlinkIndex = 1;
StringBuilder content = new StringBuilder();
while (outlinksIter.hasNext()) {
String outlink = outlinksIter.next();
if (!outlink.startsWith("http")) {
outlink = "http://" + outlink;
}
content.append(String.format(SITEMAP_ENTRY, outlink, outlinkIndex++));
}
String contentAsStr = content.toString();
return new FetchedResult(urlToFetch, urlToFetch, System.currentTimeMillis(),
new Headers(), contentAsStr.getBytes(UTF_8), TEXT_MIME_TYPE,
DEFAULT_MIN_RESPONSE_RATE, null, urlToFetch, 0, "127.0.0.1", HttpStatus.SC_OK,
"");
}
}
@Override
public ActionResult execute() {
String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID);
CourseAttributes courseAttributes = logic.getCourse(courseId);
if (courseAttributes == null) {
return new JsonResult("No course with id: " + courseId, HttpStatus.SC_NOT_FOUND);
}
return new JsonResult(new CourseData(courseAttributes));
}
/** Uploads a given file to Google Storage. */
private void uploadFile(Path filePath) throws IOException {
try {
byte[] md5hash =
Base64.decodeBase64(
storage
.objects()
.get(bucketName(project), filePath.getFileName().toString())
.execute()
.getMd5Hash());
try (InputStream inputStream = Files.newInputStream(filePath, StandardOpenOption.READ)) {
if (Arrays.equals(md5hash, DigestUtils.md5(inputStream))) {
log.info("File " + filePath.getFileName() + " is current, reusing.");
return;
}
}
log.info("File " + filePath.getFileName() + " is out of date, uploading new version.");
storage.objects().delete(bucketName(project), filePath.getFileName().toString()).execute();
} catch (GoogleJsonResponseException e) {
if (e.getStatusCode() != HttpStatus.SC_NOT_FOUND) {
throw e;
}
}
storage
.objects()
.insert(
bucketName(project),
null,
new FileContent("application/octet-stream", filePath.toFile()))
.setName(filePath.getFileName().toString())
.execute();
log.info("File " + filePath.getFileName() + " created.");
}
/**
* Must throw {@link UnexpectedResponseException} if the response code
* is not 200.
* @throws Exception If something goes wrong.
*/
@Test(expected = UnexpectedResponseException.class)
public void unexpectedResponseErrorIfResponseNot200() throws Exception {
new Inspection(
new AssertRequest(
new Response(HttpStatus.SC_NOT_FOUND)
),
"http://localhost"
);
}
private void waitForAccess( String url, String username, String password, long sleep ) throws InterruptedException {
while( true ) {
Response response = given()
.auth().preemptive().basic( username, password )
.when().get( url ).andReturn();
if( response.getStatusCode() == HttpStatus.SC_NOT_FOUND ) {
Thread.sleep( sleep );
continue;
}
assertThat( response.getContentType(), containsString( "text/plain" ) );
assertThat( response.getBody().asString(), is( "test-service-response" ) );
break;
}
}
@Test
public void testSQL2() throws IOException {
HttpPost post = new HttpPost("http://localhost:4567/sql");
List<NameValuePair> postParams = new ArrayList<>();
postParams.add(
new BasicNameValuePair("sqlStatement", "SELECT * FROM DIRS WHERE dirNumChildren = 0"));
post.setEntity(new UrlEncodedFormEntity(postParams, "UTF-8"));
HttpResponse res = client.execute(hostPort, post);
if (res.getStatusLine().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
List<String> text = IOUtils.readLines(res.getEntity().getContent());
assertThat(text.size(), is(0));
assertThat(res.getStatusLine().getStatusCode(), is(HttpStatus.SC_OK));
}
}
public BackgroundException map(final Throwable failure, final StringBuilder buffer, final int statusCode) {
switch(statusCode) {
case HttpStatus.SC_UNAUTHORIZED:
return new LoginFailureException(buffer.toString(), failure);
case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
return new ProxyLoginFailureException(buffer.toString(), failure);
case HttpStatus.SC_FORBIDDEN:
case HttpStatus.SC_NOT_ACCEPTABLE:
return new AccessDeniedException(buffer.toString(), failure);
case HttpStatus.SC_CONFLICT:
return new ConflictException(buffer.toString(), failure);
case HttpStatus.SC_NOT_FOUND:
case HttpStatus.SC_GONE:
case HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE:
return new NotfoundException(buffer.toString(), failure);
case HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE:
case HttpStatus.SC_INSUFFICIENT_STORAGE:
case HttpStatus.SC_PAYMENT_REQUIRED:
return new QuotaException(buffer.toString(), failure);
case HttpStatus.SC_UNPROCESSABLE_ENTITY:
case HttpStatus.SC_BAD_REQUEST:
case HttpStatus.SC_REQUEST_URI_TOO_LONG:
case HttpStatus.SC_METHOD_NOT_ALLOWED:
case HttpStatus.SC_NOT_IMPLEMENTED:
return new InteroperabilityException(buffer.toString(), failure);
case HttpStatus.SC_REQUEST_TIMEOUT:
case HttpStatus.SC_GATEWAY_TIMEOUT:
return new ConnectionTimeoutException(buffer.toString(), failure);
case HttpStatus.SC_LOCKED:
return new LockedException(buffer.toString(), failure);
case HttpStatus.SC_BAD_GATEWAY:
case HttpStatus.SC_INTERNAL_SERVER_ERROR:
case HttpStatus.SC_SERVICE_UNAVAILABLE:
case 429:
// Too Many Requests. Rate limiting
case 509:
// Bandwidth Limit Exceeded
return new RetriableAccessDeniedException(buffer.toString(), failure);
default:
return new InteroperabilityException(buffer.toString(), failure);
}
}
@Override
public void copyChunk(Workspace sourceWorkspace, Workspace destinationWorkspace, String chunkName) throws Exception {
if (!isTokenActive()) {
login();
}
HttpClient httpClient = new DefaultHttpClient();
String url = this.storageUrl + "/" + destinationWorkspace.getSwiftContainer() + "/"
+ chunkName;
String copyFrom = "/" + sourceWorkspace.getSwiftContainer() + "/" + chunkName;
try {
HttpPut request = new HttpPut(url);
request.setHeader(SwiftResponse.X_AUTH_TOKEN, authToken);
request.setHeader(SwiftResponse.X_COPY_FROM, copyFrom);
//request.setHeader("Content-Length", "0");
HttpResponse response = httpClient.execute(request);
SwiftResponse swiftResponse = new SwiftResponse(response);
if (swiftResponse.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
throw new UnauthorizedException("401 User unauthorized");
}
if (swiftResponse.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
throw new ObjectNotFoundException("404 Not Found");
}
if (swiftResponse.getStatusCode() < 200 || swiftResponse.getStatusCode() >= 300) {
throw new UnexpectedStatusCodeException("Unexpected status code: " + swiftResponse.getStatusCode());
}
} finally {
httpClient.getConnectionManager().shutdown();
}
}
StatefulResponse handlePut(final String dataId,
final String parentExtId,
final String requestBody,
final List<Map<String, Object>> currentStateContentForMock,
final RestfulMockStatefulMeta restfulMockStatefulMeta) {
if (dataId == null) {
return new StatefulResponse(HttpStatus.SC_BAD_REQUEST);
}
// Ensure json body is valid
final Optional<Map<String, Object>> requestDataMapOpt = convertToJsonMap(requestBody);
if (!requestDataMapOpt.isPresent()) {
return new StatefulResponse(HttpStatus.SC_BAD_REQUEST,
"Invalid JSON in request body");
}
final String fieldIdPathPattern = restfulMockStatefulMeta.getIdFieldLocation();
if (isComplexJsonStructure(fieldIdPathPattern)) {
final Optional<StatefulServiceImpl.StatefulPath> pathOpt =
findDataStateRecordPath(currentStateContentForMock,
StringUtils.split(fieldIdPathPattern, "."),
dataId);
if (!pathOpt.isPresent()) {
return new StatefulResponse(HttpStatus.SC_NOT_FOUND);
}
currentStateContentForMock.remove(pathOpt.get().getIndex().intValue());
currentStateContentForMock.add(pathOpt.get().getIndex(), requestDataMapOpt.get());
state.put(parentExtId, currentStateContentForMock); // TODO use merge
} else {
final String fieldId = restfulMockStatefulMeta.getIdFieldName();
final Object bodyId = requestDataMapOpt.get().get(fieldId);
// Ensure ids in url and body match
if (bodyId == null
|| !(bodyId instanceof String)
|| !StringUtils.equals((String)bodyId, dataId)) {
return new StatefulResponse(HttpStatus.SC_BAD_REQUEST);
}
final AtomicBoolean recordFound = new AtomicBoolean(false);
state.merge(parentExtId, currentStateContentForMock, (currentValue, p) ->
currentValue
.stream()
.map(m -> {
final boolean match = StringUtils.equals(dataId, (String) m.get(fieldId));
if (match) {
recordFound.set(true);
}
return (match)
? requestDataMapOpt.get()
: m;
})
.collect(Collectors.toList())
);
if (!recordFound.get()) {
return new StatefulResponse(HttpStatus.SC_NOT_FOUND);
}
}
return new StatefulResponse(HttpStatus.SC_NO_CONTENT);
}
public SessionUnknownException(String error) {
super(HttpStatus.SC_NOT_FOUND, "M_NO_VALID_SESSION", error);
}
public NotFoundException(String msg) {
super(HttpStatus.SC_NOT_FOUND, msg);
}
@Override
public void copyChunk(Workspace sourceWorkspace, Workspace destinationWorkspace, String chunkName) throws Exception {
if (!isTokenActive()) {
login();
}
chunkName = "chk-" + chunkName;
TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] certificate, String authType) {
return true;
}
};
SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("https", 5000, sf));
ClientConnectionManager ccm = new SingleClientConnManager(registry);
HttpClient httpClient = new DefaultHttpClient(ccm);
String url = this.storageUrl + "/" + destinationWorkspace.getSwiftContainer() + "/"
+ chunkName;
String copyFrom = "/" + sourceWorkspace.getSwiftContainer() + "/" + chunkName;
try {
HttpPut request = new HttpPut(url);
request.setHeader(SwiftResponse.X_AUTH_TOKEN, authToken);
request.setHeader(SwiftResponse.X_COPY_FROM, copyFrom);
//request.setHeader("Content-Length", "0");
HttpResponse response = httpClient.execute(request);
SwiftResponse swiftResponse = new SwiftResponse(response);
if (swiftResponse.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
throw new UnauthorizedException("401 User unauthorized");
}
if (swiftResponse.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
throw new ObjectNotFoundException("404 Not Found");
}
if (swiftResponse.getStatusCode() < 200 || swiftResponse.getStatusCode() >= 300) {
throw new UnexpectedStatusCodeException("Unexpected status code: " + swiftResponse.getStatusCode());
}
} finally {
httpClient.getConnectionManager().shutdown();
}
}
public void refresh() throws IOException {
getDescriptionEntries().clear();
final Configuration configuration = LibPensolBoot.getInstance().getGlobalConfig();
final String service =
configuration.getConfigProperty( "org.pentaho.reporting.libraries.pensol.web.LoadRepositoryDoc" );
URI uri;
String baseUrl = url + service;
try {
URIBuilder builder = new URIBuilder( baseUrl );
logger.debug( "Connecting to '" + baseUrl + '\'' );
if ( username != null ) {
builder.setParameter( "userid", username );
}
if ( password != null ) {
builder.setParameter( "password", password );
}
uri = builder.build();
} catch ( URISyntaxException e ) {
throw new IOException( "Provided URL is invalid: " + baseUrl );
}
final HttpPost filePost = new HttpPost( uri );
filePost.setHeader( "Content-Type", "application/x-www-form-urlencoded; charset=utf-8" );
HttpResponse httpResponse = client.execute( filePost, context );
final int lastStatus = httpResponse.getStatusLine().getStatusCode();
if ( lastStatus == HttpStatus.SC_UNAUTHORIZED ) {
throw new IOException( "401: User authentication failed." );
} else if ( lastStatus == HttpStatus.SC_NOT_FOUND ) {
throw new IOException( "404: Repository service not found on server." );
} else if ( lastStatus != HttpStatus.SC_OK ) {
throw new IOException( "Server error: HTTP lastStatus code " + lastStatus );
}
final InputStream postResult = httpResponse.getEntity().getContent();
try {
setRoot( performParse( postResult ) );
} finally {
postResult.close();
}
}