下面列出了org.apache.http.HttpStatus#SC_BAD_REQUEST 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/** Handles URLs predicted as malicious. */
private void blockedMaliciousSiteRequested() {
try {
HttpResponse response =
new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_BAD_REQUEST, "MAL");
HttpEntity httpEntity = new FileEntity(new File("index.html"), ContentType.WILDCARD);
BufferedWriter bufferedWriter =
new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
bufferedWriter.write(response.getStatusLine().toString());
String headers =
"Proxy-agent: FilterProxy/1.0\r\n"
+ httpEntity.getContentType().toString()
+ "\r\n"
+ "Content-Length: "
+ httpEntity.getContentLength()
+ "\r\n\r\n";
bufferedWriter.write(headers);
// Pass index.html content
bufferedWriter.write(EntityUtils.toString(httpEntity));
bufferedWriter.flush();
bufferedWriter.close();
} catch (IOException e) {
logger.error("Error writing to client when requested a blocked site", e);
}
}
/**
* Maps some of the common HTTP errors to the corresponding exceptions.
*/
private void throwOnCommonError(int status) throws IOException {
switch (status) {
case HttpStatus.SC_BAD_REQUEST:
throw new MalformedRequestException();
case HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE:
throw new UnsupportedMediaTypeException();
case HttpStatus.SC_NOT_FOUND:
throw new NotFoundException();
case HttpStatus.SC_UNAUTHORIZED:
throw new UnauthorizedException();
case HttpStatus.SC_FORBIDDEN:
throw new ForbiddenException();
case HttpStatus.SC_CONFLICT:
throw new ConflictException();
case HttpStatus.SC_UNPROCESSABLE_ENTITY:
throw new ValidationException();
}
if (status >= 400) {
throw new IOException("Unexpected status code on response: " + status);
}
}
@Override
public ActionResult execute() {
String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID);
String feedbackSessionName = getNonNullRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME);
FeedbackSessionAttributes feedbackSession = logic.getFeedbackSession(feedbackSessionName, courseId);
if (!feedbackSession.isOpened()) {
return new JsonResult("Reminder email could not be sent out "
+ "as the feedback session is not open for submissions.", HttpStatus.SC_BAD_REQUEST);
}
FeedbackSessionStudentRemindRequest remindRequest =
getAndValidateRequestBody(FeedbackSessionStudentRemindRequest.class);
String[] usersToRemind = remindRequest.getUsersToRemind();
taskQueuer.scheduleFeedbackSessionRemindersForParticularUsers(courseId, feedbackSessionName,
usersToRemind, userInfo.getId());
return new JsonResult("Reminders sent");
}
protected static void processStandardHttpResponseCodes(HttpResponse httpResponse) throws AuthenticationException, IOException {
int code = httpResponse.getStatusLine().getStatusCode();
Log.d(TAG, "Response http code: " + code);
if (code >= 200 && code <= 299)
return;
if (code == HttpStatus.SC_UNAUTHORIZED || code == HttpStatus.SC_FORBIDDEN) {
String OTP = getHeaderValue(httpResponse, "X-GitHub-OTP");
if (code == HttpStatus.SC_UNAUTHORIZED && OTP != null && OTP.contains("required")) {
throw new OTPAuthenticationException(Utils.trimToNull(OTP.replace("required;", "")));
}
throw new AuthenticationException("Authentication problem: " + getResponseContentAsString(httpResponse));
} else if (code == HttpStatus.SC_BAD_REQUEST || code == HttpStatus.SC_NOT_FOUND) {
throw new InvalidObjectException("HttpCode=" + code + " message: " + getResponseContentAsString(httpResponse));
} else {
throw new IOException("HttpCode=" + code + " message: " + getResponseContentAsString(httpResponse));
}
}
@Override
public void failed(HttpClientCallbackResult result) {
String reStr = StringHelper.isEmpty(result.getReplyDataAsString())
? "GodEyeRestService " + method + " is failed."
: result.getReplyDataAsString();
if (result.getRetCode() != HttpStatus.SC_BAD_REQUEST) {
/**
* Confusing.......
*/
logger.err(this, "GodEyeRestService " + method + " get result is failed -returnCode["
+ result.getRetCode() + "] and retMsg[" + reStr + "]", result.getException());
response.resume(reStr);
}
else {
response.resume(reStr + ",exception=" + result.getException());
}
}
public Credentials getUserFromAuthToken(String token) throws DAOException {
AuthTokenUtils.AuthToken authToken;
try {
authToken = new AuthTokenUtils.AuthToken(keyManager.getSymmetricKey(),token);
} catch (AuthenticationException e) {
throw new DAOException(HttpStatus.SC_INTERNAL_SERVER_ERROR,"internal error");
}
if(authToken.isExpired()) throw new DAOException(HttpStatus.SC_UNAUTHORIZED,"Expired");
Query q = new QueryBuilder().select().from(Credentials.class).where(Credentials.AUTH_TOKEN_KEY,OPERAND.EQ,token).build();
TransientObject to = ObjectUtils.get1stOrNull(dao.query(q));
if(to!=null){
return new ServerCredentials(to);
} else {
throw new DAOException(HttpStatus.SC_BAD_REQUEST,"invalid auth token");
}
}
@Override
public ActionResult execute() {
String regkey = getNonNullRequestParamValue(Const.ParamsNames.REGKEY);
String entityType = getNonNullRequestParamValue(Const.ParamsNames.ENTITY_TYPE);
switch (entityType) {
case Const.EntityType.STUDENT:
return getStudentJoinStatus(regkey);
case Const.EntityType.INSTRUCTOR:
return getInstructorJoinStatus(regkey);
default:
return new JsonResult("Error: invalid entity type", HttpStatus.SC_BAD_REQUEST);
}
}
public Credentials getUserFromRecoveryToken(String token) throws DAOException {
Query q = new QueryBuilder().select().from(Credentials.class).where(Credentials.RECOVERY_TOKEN_KEY,OPERAND.EQ,token).build();
TransientObject to = ObjectUtils.get1stOrNull(dao.query(q));
if(to!=null){
ServerCredentials sc = new ServerCredentials(to);
sc.setAuthToken(AuthTokenUtils.getNewToken(keyManager.getSymmetricKey(), sc));
sc.setRecoveryToken(AuthTokenUtils.getNewToken(keyManager.getSymmetricKey(), sc));
dao.save(sc);
return sc;
} else {
throw new DAOException(HttpStatus.SC_BAD_REQUEST,"invalid recovery token");
}
}
/**
* レスポンスコードからログレベルの判定.
* @param statusCode ステータスコード
* @return ステータスコードから判定されたログレベル
*/
static Severity decideSeverity(int statusCode) {
// 設定が省略されている場合はエラーコードからログレベルを取得
if (statusCode >= HttpStatus.SC_INTERNAL_SERVER_ERROR) {
// 500系の場合はウォーニング(500以上はまとめてウォーニング)
return Severity.WARN;
} else if (statusCode >= HttpStatus.SC_BAD_REQUEST) {
// 400系の場合はインフォ
return Severity.INFO;
} else {
// それ以外の場合は考えられないのでウォーニング.
// 200系とか300系をDcCoreExceptionで処理する場合はログレベル設定をちゃんと書きましょう.
return Severity.WARN;
}
}
@Override
public ActionResult execute() {
String instructorId = getRequestParamValue(Const.ParamsNames.INSTRUCTOR_ID);
String instructorEmail = getRequestParamValue(Const.ParamsNames.INSTRUCTOR_EMAIL);
String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID);
InstructorAttributes instructor;
if (instructorId != null) {
instructor = logic.getInstructorForGoogleId(courseId, instructorId);
} else if (instructorEmail != null) {
instructor = logic.getInstructorForEmail(courseId, instructorEmail);
} else {
throw new InvalidHttpParameterException("Instructor to delete not specified");
}
if (instructor == null) {
return new JsonResult("Instructor is successfully deleted.", HttpStatus.SC_OK);
}
// Deleting last instructor from the course is not allowed if you're not the admin
if (userInfo.isInstructor && !hasAlternativeInstructor(courseId, instructor.email)) {
return new JsonResult("The instructor you are trying to delete is the last instructor in the course. "
+ "Deleting the last instructor from the course is not allowed.", HttpStatus.SC_BAD_REQUEST);
}
logic.deleteInstructorCascade(courseId, instructor.email);
return new JsonResult("Instructor is successfully deleted.", HttpStatus.SC_OK);
}
@Override
public ActionResult execute() {
String entityType = getNonNullRequestParamValue(Const.ParamsNames.ENTITY_TYPE);
switch (entityType) {
case Const.EntityType.STUDENT:
return getStudentCourses();
case Const.EntityType.INSTRUCTOR:
return getInstructorCourses();
default:
return new JsonResult("Error: invalid entity type", HttpStatus.SC_BAD_REQUEST);
}
}
@Override
public void failed(HttpClientCallbackResult result) {
String reStr = result.getReplyDataAsString();
if (result.getRetCode() != HttpStatus.SC_BAD_REQUEST) {
/**
* Confusing.......
*/
logger.err(this,
"get query result failed -returnCode[" + result.getRetCode() + "] and retMsg[" + reStr + "]",
result.getException());
response.resume(reStr);
}
}
/**
* Reads record.
*
* @param id records id
* @return record
* @throws IOException if error reading record
* @throws URISyntaxException if invalid URI
* @throws ParserConfigurationException if error parsing response
* @throws SAXException if error parsing response
* @throws XPathExpressionException if error parsing response
* @throws TransformerException if error parsing response
*/
public String readRecord(String id) throws IOException, URISyntaxException, ParserConfigurationException, SAXException, XPathExpressionException, TransformerException {
HttpGet request = new HttpGet(recordUri(id));
try (CloseableHttpResponse httpResponse = httpClient.execute(request); InputStream contentStream = httpResponse.getEntity().getContent();) {
String reasonMessage = httpResponse.getStatusLine().getReasonPhrase();
String responseContent = IOUtils.toString(contentStream, "UTF-8");
LOG.trace(String.format("RESPONSE: %s, %s", responseContent, reasonMessage));
if (httpResponse.getStatusLine().getStatusCode()==429 || httpResponse.getStatusLine().getStatusCode()==503) {
Date retryAfter = getRetryAfter(httpResponse);
if (retryAfter!=null) {
long delay = retryAfter.getTime()-System.currentTimeMillis();
if (delay>0) {
LOG.debug(String.format("Harvestiong suspended for %d milliseconds.", delay));
try {
Thread.sleep(delay);
} catch (InterruptedException ex) {
// ignore
}
}
return readRecord(id);
}
}
if (httpResponse.getStatusLine().getStatusCode() >= 400) {
throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase());
}
Document responseDoc = parseDocument(responseContent);
XPath xPath = XPathFactory.newInstance().newXPath();
String errorCode = StringUtils.stripToNull((String) xPath.evaluate("/OAI-PMH/error/@code", responseDoc, XPathConstants.STRING));
if (errorCode != null) {
throw new HttpResponseException(HttpStatus.SC_BAD_REQUEST, String.format("Invalid OAI-PMH response with code: %s", errorCode));
}
Node metadataNode = (Node) xPath.evaluate("/OAI-PMH/GetRecord/record/metadata/*[1]", responseDoc, XPathConstants.NODE);
if (metadataNode == null) {
throw new IOException("Error reading metadata");
}
Document metadataDocument = emptyDocument();
metadataDocument.appendChild(metadataDocument.importNode(metadataNode, true));
return XmlUtils.toString(metadataDocument);
}
}
public void getAllModules() {
SugarRestClient client = new SugarRestClient(TestAccount.Url, TestAccount.Username, TestAccount.Password);
SugarRestRequest request = new SugarRestRequest(RequestType.AllModulesRead);
SugarRestResponse response = client.execute(request);
List<String> allAvailableModules = (List<String>)response.getData();
assertNotNull(response);
assertEquals(response.getStatusCode(), HttpStatus.SC_OK);
assertTrue(allAvailableModules.size() > 0);
// Get all mapped modules
List<String> allMappedModules = ModuleMapper.getInstance().getAllModules();
int count = 0;
for (String module : allMappedModules) {
// Do a bulk read module test
response = bulkReadModule(client, module);
// assertNotNull(response);
// assertEquals(response.getStatusCode(), HttpStatus.SC_OK);
int statusOk = (int)HttpStatus.SC_OK;
int statusBadRequest = (int)HttpStatus.SC_BAD_REQUEST;
int statusOInternalError = (int)HttpStatus.SC_INTERNAL_SERVER_ERROR;
if (response.getStatusCode() == statusOk) {
System.out.println("Module name:" + module + ":::: Status" + response.getStatusCode());
System.out.println(response.getJsonRawResponse());
System.out.println(response.getError().getTrace());
count = count + 1;
}
}
System.out.println("Total Count::::" + allMappedModules.size());
System.out.println("Count::::" + count);
/*
for (String module : allAvailableModules) {
if (!allMappedModules.contains(module) ) {
// Do a bulk read module test
response = bulkReadModule(client, module);
// assertNotNull(response);
// assertEquals(response.getStatusCode(), HttpStatus.SC_OK);
if (response.getStatusCode() == (int)HttpStatus.SC_BAD_REQUEST) {
System.out.println("Module name:" + module + ":::: Status" + response.getStatusCode());
System.out.println(response.getJsonRawResponse());
System.out.println(response.getError().getTrace());
}
}
}
*/
}
@Override
protected void execute() {
boolean enable = settingsService.isUrlRedirectionEnabled() && settingsService.getUrlRedirectType() == UrlRedirectType.NORMAL;
HttpPost request = new HttpPost(enable ? URL_REDIRECTION_REGISTER_URL : URL_REDIRECTION_UNREGISTER_URL);
int port = settingsService.getPort();
boolean trial = !settingsService.isLicenseValid();
Date trialExpires = settingsService.getTrialExpires();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("serverId", settingsService.getServerId()));
params.add(new BasicNameValuePair("redirectFrom", settingsService.getUrlRedirectFrom()));
params.add(new BasicNameValuePair("port", String.valueOf(port)));
params.add(new BasicNameValuePair("localIp", settingsService.getLocalIpAddress()));
params.add(new BasicNameValuePair("localPort", String.valueOf(port)));
params.add(new BasicNameValuePair("contextPath", settingsService.getUrlRedirectContextPath()));
params.add(new BasicNameValuePair("trial", String.valueOf(trial)));
if (trial && trialExpires != null) {
params.add(new BasicNameValuePair("trialExpires", String.valueOf(trialExpires.getTime())));
} else {
params.add(new BasicNameValuePair("licenseHolder", settingsService.getLicenseEmail()));
}
HttpClient client = new DefaultHttpClient();
try {
urlRedirectionStatus.setText(enable ? "Registering web address..." : "Unregistering web address...");
request.setEntity(new UrlEncodedFormEntity(params, StringUtil.ENCODING_UTF8));
HttpResponse response = client.execute(request);
StatusLine status = response.getStatusLine();
switch (status.getStatusCode()) {
case HttpStatus.SC_BAD_REQUEST:
urlRedirectionStatus.setText(EntityUtils.toString(response.getEntity()));
testUrlRedirection = false;
break;
case HttpStatus.SC_OK:
urlRedirectionStatus.setText(enable ? "Successfully registered web address." : "Web address disabled.");
break;
default:
testUrlRedirection = false;
throw new IOException(status.getStatusCode() + " " + status.getReasonPhrase());
}
} catch (Throwable x) {
LOG.warn(enable ? "Failed to register web address." : "Failed to unregister web address.", x);
urlRedirectionStatus.setText(enable ? ("Failed to register web address. " + x.getMessage() +
" (" + x.getClass().getSimpleName() + ")") : "Web address disabled.");
} finally {
client.getConnectionManager().shutdown();
}
// Test redirection, but only once.
if (testUrlRedirection) {
testUrlRedirection = false;
testUrlRedirection();
}
// Don't do it again if disabled.
if (!enable && urlRedirectionFuture != null) {
urlRedirectionFuture.cancel(false);
}
}
private void evaluateResponse(HttpResponse httpResponse) {
// Early exit, if there is no HTTP Response:
if (httpResponse == null) {
return;
}
// Early exit, if we can't determine the Status:
if (httpResponse.getStatusLine() == null) {
return;
}
// Get the HTTP Status Code:
int httpStatusCode = httpResponse.getStatusLine().getStatusCode();
// Is it OK? So we can exit here:
if (httpStatusCode == HttpStatus.SC_OK) {
return;
}
// The Error Reason:
String reasonPhrase = httpResponse.getStatusLine().getReasonPhrase();
// If it is a Bad Request, we could not retry it:
if (httpStatusCode == HttpStatus.SC_BAD_REQUEST) {
throw new FcmBadRequestException(reasonPhrase);
}
// If we are unauthorized, we could not retry it:
if (httpStatusCode == HttpStatus.SC_UNAUTHORIZED) {
throw new FcmAuthenticationException(reasonPhrase);
}
// Any Status Code between 500 and 600 could be retried:
if (httpStatusCode >= 500 && httpStatusCode < 600) {
// Holds the Duration, which has been sent by the Server:
OutParameter<Duration> result = new OutParameter<>();
// Try to determine the next interval we can send at:
if (RetryHeaderUtils.tryDetermineRetryDelay(httpResponse, result)) {
throw new FcmRetryAfterException(httpStatusCode, reasonPhrase, result.get());
}
}
throw new FcmGeneralException(httpStatusCode, reasonPhrase);
}
/**
* Adds an index to elasticsearch if it does not exist.
*
* @param index The name of the index to create.
* @throws IOException If an error occurred during requests to ES.
*/
private void addIndex(final String index) throws IOException {
logger.info("Adding index '{}'...", index);
String resourcePath = "/" + index;
if (doesResourceNotExist(resourcePath)) {
try {
ObjectNode setting = objectMapper.createObjectNode();
ObjectNode indexSetting = objectMapper.createObjectNode();
indexSetting.put("number_of_shards", config.getElasticSearchIndexShardCount());
indexSetting.put("number_of_replicas", config.getElasticSearchIndexReplicationCount());
setting.set("index", indexSetting);
elasticSearchAdminClient.performRequest(HttpMethod.PUT, resourcePath, Collections.emptyMap(),
new NStringEntity(setting.toString(), ContentType.APPLICATION_JSON));
logger.info("Added '{}' index", index);
} catch (ResponseException e) {
boolean errorCreatingIndex = true;
Response errorResponse = e.getResponse();
if (errorResponse.getStatusLine().getStatusCode() == HttpStatus.SC_BAD_REQUEST) {
JsonNode root = objectMapper.readTree(EntityUtils.toString(errorResponse.getEntity()));
String errorCode = root.get("error").get("type").asText();
if ("index_already_exists_exception".equals(errorCode)) {
errorCreatingIndex = false;
}
}
if (errorCreatingIndex) {
throw e;
}
}
} else {
logger.info("Index '{}' already exists", index);
}
}
public SessionNotValidatedException() {
super(HttpStatus.SC_BAD_REQUEST, "M_SESSION_NOT_VALIDATED", "This validation session has not yet been completed");
}
StatefulResponse handlePost(final String parentExtId, final String requestBody, final List<Map<String, Object>> currentStateContentForMock, final RestfulMockStatefulMeta restfulMockStatefulMeta) {
// Validate is valid json body
final Optional<Map<String, Object>> requestDataMapOpt = convertToJsonMap(requestBody);
if (!requestDataMapOpt.isPresent()) {
return new StatefulResponse(HttpStatus.SC_BAD_REQUEST,
"Invalid JSON in request body");
}
final Map<String, Object> requestDataMap = requestDataMapOpt.get();
// TODO amend id handler here to add id according to the path...
appendIdToJson(requestDataMap, restfulMockStatefulMeta);
final String fieldIdPathPattern = restfulMockStatefulMeta.getIdFieldLocation();
if (isComplexJsonStructure(fieldIdPathPattern)) {
// TODO
// Amend POST to add items according to path...
state.put(parentExtId, currentStateContentForMock); // TODO use merge
} else {
state.merge(parentExtId, currentStateContentForMock, (currentValue, p) -> {
currentValue.add(requestDataMap);
return currentValue;
});
}
return new StatefulResponse(HttpStatus.SC_CREATED);
}
/**
* Check if httpResponse has an error status.
*
* @param httpResponse
* tge {@link HttpResponse}
* @return true if status code >= 400
*/
public static boolean isError(HttpResponse httpResponse) {
return httpResponse.getStatusLine().getStatusCode() >= HttpStatus.SC_BAD_REQUEST;
}