Reputation: 633
I am implementing a java program that interfaces with Neo4j graph db via rest. Each request to the database results in an http status code like 200, 201, 401 and the like.
For my program some response codes are ok, like 200, 201 or 202 while, quite obviously, some others are NOT ok, like 401 404 and the like.
What I want to do, and actually am trying to do, is this: Use some sort of enum with Status Code (int), Status Text (as in HttpStatus) and a custom field with either OK (the response is ok for me) or NOK (the response is not ok for me).
My problem is that I have no Idea, how to traverse from the response code from REST (being the int 200) over SC_OK from HttpStatus to OK from my enum.
this obviously will not work:
int status = HttpStatus.SC_NO_CONTENT;
String StatusText = HttpStatus.getStatusText(status);
String OkOrNotOk = HttpStatusCodes.StatusText.getValue();
Can someone give me a hint?
Thanks in advance,
Chris
Upvotes: 1
Views: 7901
Reputation: 633
Here is my code that I used to achieve this:
public enum HttpStatusCode {
UNKNOWN (-1 , false),
ACCEPTED (HttpStatus.SC_ACCEPTED , true), // 202
BAD_GATEWAY (HttpStatus.SC_BAD_GATEWAY , false), // 502
BAD_REQUEST (HttpStatus.SC_BAD_REQUEST , false), // 400
CONFLICT (HttpStatus.SC_CONFLICT , false), // 409
CREATED (HttpStatus.SC_CREATED , true), // 201
CONTINUE (HttpStatus.SC_CONTINUE , true), // 100
MOVED_TEMPORARILY (HttpStatus.SC_MOVED_TEMPORARILY , false), // 302
FORBIDDEN (HttpStatus.SC_FORBIDDEN , false), // 403
GATEWAY_TIMEOUT (HttpStatus.SC_GATEWAY_TIMEOUT , false), // 504
UNPROCESSABLE_ENTITY (HttpStatus.SC_UNPROCESSABLE_ENTITY , false); // 422
private final int value;
private final boolean name;
private HttpStatusCode(int value, boolean name) {
this.value = value;
this.name = name;
}
public boolean isOk() {
return name;
}
public int getErrorCode(){
return value;
}
public static HttpStatusCode getHttpStatusCode(int errorCode){
for (HttpStatusCode code : HttpStatusCode.values()) {
if(code.getErrorCode() == errorCode)
return code;
}
return HttpStatusCode.UNKNOWN;
}
}
with this I can query like this if a return code is ok or not ok:
StringRequestEntity requestEntity = new StringRequestEntity(p.toString(),
"application/json",
"UTF-8");
mPost.setRequestEntity(requestEntity);
int status = client.executeMethod(mPost);
HttpStatusCode statusCode = HttpStatusCode.getHttpStatusCode(status);
// in case everything is fine, neo4j should return 200, 201 or 202. any other case needs to be investigated
if (!statusCode.isOk()){
logger.error(HttpErrorMessages.getHttpErrorText(statusCode.getErrorCode()));
}
maybe that helps some others too
Upvotes: 0
Reputation: 41997
It's OK if the status code is in the range 200..299. Nothing else needed.
In particular, the status text has no semantics; it's just for debugging. Don't ever change your system behavior based on it.
Upvotes: 2