namespace Electronic_Filing_of_Appeals
{
public class GenerateXML
{
public ElectronicRecordAppellateCase CreateXml()
{
My lies on the CreateXML() portion of this code. The error being kicked back is
Electronic_Filing_of_Appeals.GenerateXML.CreateXml(): not all code paths return a value
I've tried different approached but the same result.
Any clue from the professionals?
Your method is suppoed to return an instance of ElectronicRecordAppellateCase class. I guess you are returning the result in some If condition in your method or so like this.
public ElectronicRecordAppellateCase CreateXml()
{
ElectronicRecordAppellateCase output=new ElectronicRecordAppellateCase();
if(someVariableAlreadyDefined>otherVariable)
{
//do something useful
return output;
}
// Not returning anything if the if condition is not true!!!!
}
Solution : Make sure you are returning a valid return value from the method.
public ElectronicRecordAppellateCase CreateXml()
{
ElectronicRecordAppellateCase output=new ElectronicRecordAppellateCase();
if(someVariableAlreadyDefined>otherVariable)
{
return output;
}
return null; //you can return the object here as needed
}
If you specify output type, your method HAS to provide a value following every path of the code. When you see this error, it means one or more scenarios in your method don't return a value of a specified type, but result in a termination of the method instead.
This is an example of such problematic method:
public ElectronicRecordAppellateCase CreateXml()
{
if (something)
{
return new ElectronicRecordAppellateCase();
}
// if the something is false, the method doesn't provide any output value!!!
}
This could be solved like this for instance:
public ElectronicRecordAppellateCase CreateXml()
{
if (something)
{
return new ElectronicRecordAppellateCase();
}
else return null; // "else" isn't really needed here
}
See the pattern?
not all code paths return value means, you function may not return a expected value
you don't show your code so I made a example
for example, the follow function has 3 paths, if parm equal 1, if parm equal 2 but if parm is not equal 1 or 2 don't return a value
function SomeObject foo(integer parm){
if (parm == 1) {
return new SomeObject();
}
if (parm == 2) {
return new SomeObject();
}
//What if parm equal something else???
}
Related
I'm very new to dart and i am countering an issue with a function that suppose return a List<CloseObservations> and not a Future<dynamic> and i couldn't figure out why my function do not return the correct type.
This is my function :
getData(BuildContext context) async {
List<CloseObservations> closeObservationData = new List();
WorkSiteState state = BlocProvider.of<WorkSiteBloc>(context).state;
List<Stage> stages = state.workSites[state.currentIndex].stages;
for (Stage stage in stages) {
String stageName = stage.name;
int closeNumber;
try {
for (Plan plan in stage.plans) {
for (Observation observation in plan.observations) {
if (!observation.open) {
closeNumber++;
}
}
}
} finally {
closeObservationData.add(CloseObservations(stageName, closeNumber));
}
}
return closeObservationData;
}
I hope the explanation of my problem is clear, if not tell me.
Thank you for your help !
You should explicitly specify return type of your function:
Future<List<CloseObservations>> getData(BuildContext context) async {
...
Async functions always return Future (there's also FutureOr, but you shouldn't return it - that's bad practice). If you don't need it to return Future, make it synchronous by removing async keyword and changing return type to List.
New to WebFlux, reactive, and handlers. I've got things "working", but am not understanding why following code is returning "okay" with empty body, vice "not found".
Clarification: The issue-of-concern is in the final return statement of DemoPOJOHandler.getById(). The "short-circuit" code works as expected (i.e., returns "Bad Request" status), but the "switchIfEmpty" path of the final return statement does not appear to get exercised if a DemoPOJORepo.getById(int) returns Mono.empty().
(Note: I've hacked up a list-based "repo" to avoid dealing with database while figuring out handlers and http return types.)
Router implementation ("/v1" is a set of annotation based RESTful endpoints)...
#Configuration
public class DemoPOJORouter {
#Bean
public RouterFunction<ServerResponse> route(DemoPOJOHandler requestHandler) {
return nest(path("/v2"),
nest(accept(APPLICATION_JSON),
RouterFunctions.route(RequestPredicates.GET("/DemoPOJO"), requestHandler::getAll)
.andRoute(RequestPredicates.GET("/DemoPOJO/{id}"), requestHandler::getById)
.andRoute(RequestPredicates.POST("/DemoPOJO"), requestHandler::add)));
}
}
Handler implementation has been "stripped down" to only the code in question. I have a feeling that much of the style is "still imperative", but I've attempted to put the reactive stuff where it "makes the most sense".
If I supply a bad value on the URI (i.e., "foo"), then I get the http "bad request" returned. But, never seem to get the "not found" that should be generated by "switchIfEmpty" if a validly formatted int value is supplied, but it does not map to an entry in the repo.
#Component
public class DemoPOJOHandler {
public static final String PATH_VAR_ID = "id";
private DemoPOJORepo repo = null;
public Mono<ServerResponse> getById(ServerRequest request) {
Mono<DemoPOJO> monoDemoPOJO = null;
Map<String, String> pathVariables = request.pathVariables();
int id = -1;
checkRepoRef(); // part of the list hack
// short-circuit if request doesn't contain id (should never happen)
if ((pathVariables == null)
|| (!pathVariables.containsKey(PATH_VAR_ID))) {
return ServerResponse.badRequest().build();
}
// short-circuit if bad id value
try {
id = Integer.parseInt(pathVariables.get(PATH_VAR_ID));
} catch(NumberFormatException e) {
return ServerResponse.badRequest().build();
}
// get entity by keyValue
monoDemoPOJO = repo.getById(id);
return monoDemoPOJO
.flatMap(demoPOJO -> ServerResponse.ok()
.contentType(MediaType.APPLICATION_JSON)
.syncBody(demoPOJO)
.switchIfEmpty(ServerResponse.notFound().build()));
}
}
Hack of a list-based repo to avoid dealing with data/APIs while working on handlers and http return types.
// local hack to avoid a database for testing
public class DemoPOJORepo {
private static DemoPOJORepo fpRepo = null;
private static int NUM_ROWS = 100;
private Map<Integer, DemoPOJO> fooPOJOMap;
private DemoPOJORepo() {
initMap();
}
public static DemoPOJORepo getInstance() {
if (fpRepo == null) {
fpRepo = new DemoPOJORepo();
}
return fpRepo;
}
public Mono<DemoPOJO> getById(int id) {
Mono<DemoPOJO> monoDP;
if (fooPOJOMap.containsKey(id)) {
monoDP = Mono.just(fooPOJOMap.get(id));
} else {
monoDP = Mono.empty();
}
return monoDP;
}
private Mono<Void> initMap() {
fooPOJOMap = new TreeMap<Integer, DemoPOJO>();
int offset = -1;
for(int ndx=0; ndx<NUM_ROWS; ndx++) {
offset = ndx + 1;
fooPOJOMap.put(offset, new DemoPOJO(offset, "foo_" + offset, offset+100));
}
return Mono.empty();
}
}
Your brackets are in the wrong place causing the swithIfEmpy to apply to the ServerResponse.ok() publisher not the monoDemoPOJO, replace the return with this and it should work:
return monoDemoPOJO
.flatMap(demoPOJO -> ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).syncBody(demoPOJO))
.switchIfEmpty(ServerResponse.notFound().build());
As I can see the code is right. The response code is Bad request because you are trying to convert "foo" to Integer, and when it throws an exception you are returning a Bad request response, so I think it works perfectly fine.
If you use an Integer id that is not present in your database then the answer must be a not found response
I am implementing a method using Vertx to check the existence of certain value in the database and use Handler with AsyncResult.
I would like to know which one is the best practice:
Option 1: When nothing found, Handler is with succeededFuture but with result as FALSE:
public void checkExistence (..., String itemToFind, Handler<AsyncResult<Boolean>> resultHandler) {
// ....
doQuery(..., queryHandler -> {
if (queryHandler.succeeded()) {
List<JsonObject> results = queryHandler.result();
boolean foundIt = false;
for (JsonObject json: results) {
if (json.getString("someKey").equals(itemToFind)) {
foundIt = true;
break;
}
}
resultHandler.handle(Future.succeededFuture(foundIt));
} else {
resultHandler.handle(Future.failedFuture(queryHandler.cause().toString()));
}
});
}
Option 2: When nothing found, Handler is with failedFuture:
public void checkExistence (..., String itemToFind, Handler<AsyncResult<Void>> resultHandler) {
// ....
doQuery(..., queryHandler -> {
if (queryHandler.succeeded()) {
List<JsonObject> results = queryHandler.result();
boolean foundIt = false;
for (JsonObject json: results) {
if (json.getString("someKey").equals(itemToFind)) {
foundIt = true;
break;
}
}
// HERE IS THE DIFFERENCE!!!
if (foundIt) {
resultHandler.handle(Future.succeededFuture());
} else {
resultHandler.handle(Future.failedFuture("Item " + itemToFind + " not found!"));
}
} else {
resultHandler.handle(Future.failedFuture(queryHandler.cause().toString()));
}
});
}
UPDATE:
Let's say I have another example, instead of checking the existence, I would like to get all the results. Do I check the Empty results? Do I treat Empty as failure or success?
Option 1: only output them when it's not null or empty, otherwise, fail it
public void getItems(..., String itemType, Handler<AsyncResult<List<Item>>> resultHandler) {
// ....
doQuery(..., queryHandler -> {
if (queryHandler.succeeded()) {
List<Item> items = queryHandler.result();
if (items != null && !items.empty()) {
resultHandler.handle(Future.succeededFuture(items));
} else {
resultHandler.handle(Future.failedFuture("No items found!"));
}
} else {
resultHandler.handle(Future.failedFuture(queryHandler.cause().toString()));
}
});
}
Option 2: output results I got, even though it could be empty or null
public void getItems(..., String itemType, Handler<AsyncResult<List<Item>>> resultHandler) {
// ....
doQuery(..., queryHandler -> {
if (queryHandler.succeeded()) {
List<Item> items = queryHandler.result();
resultHandler.handle(Future.succeededFuture(items));
} else {
resultHandler.handle(Future.failedFuture(queryHandler.cause().toString()));
}
});
}
The 1st one option is better, because you can clearly say, that checkExistence returned True or False and completed successfully or it failed with some exception (database issue, etc.).
But lets say, you've decided to stick with 2nd option. Then, imagine you have another method:
void getEntity(int id, Handler<AsyncResult<Entity>> resultHandler);
If entity with provided id doesn't exists, will you throw exception (using Future.failedFuture) or return null (using Future.succeededFuture)? I think, you should throw exception to make your methods logic similar to each other. But again, is that exceptional situation?
For case with returning list of entities you can just return empty list, if there are no entities. Same goes to single entity: it's better to return Optional<Entity> instead of Entity, because in this way you avoid NullPointerException and don't have nullable variables in the code. What's better: Optional<List<Entity>> or empty List<Entity>, it's open question.
Particularly if you're writing this as reusable code, then definitely go with your first option. This method is simply determining whether an item exists, and so should simply return whether it does or not. How is this particular method to know whether it's an error condition that the item doesn't exist?
Some caller might determine that it is indeed an error; it that's the case, then it will throw an appropriate exception if the Future returns with false. But another caller might simply need to know whether the item exists before proceeding; in that case, you'll find yourself using exception handling to compose your business logic.
I'm write this function:
public static String QueryString(string queryStringKey)
{
if (HttpContext.Current.Request.QueryString[queryStringKey] != null)
{
if (HttpContext.Current.Request.QueryString[queryStringKey].ToString() != string.Empty)
return HttpContext.Current.Request.QueryString.GetValues(1).ToString();
}
return "NAQ";
}
And i want to get just one value from querystring parameter.
for example i send "page" to my function and url is: "sth.com/?page=1&page=2"
and function return to me: "1,2" ; but i want first value: "1", How?
GetValues returns a string[] if the key exists. An array is zero based, so you get the first element by using array[0], you are using GetValues(1) in your code, i assume that you wanted the first.
You could also use the Enumerable.First extension method:
Request.QueryString.GetValues("page").First();
Since GetValues returns not an empty array but null if the key was not present you need to check that explicitely (FirstOrDefault doesn't work):
public static String QueryString(string queryStringKey)
{
if (HttpContext.Current != null && HttpContext.Current.Request != null)
{
string[] values = HttpContext.Current.Request.QueryString.GetValues("queryStringKey");
if (values != null) return values.First();
}
return "NAQ";
}
A better approach would be -
public static String QueryString(string queryStringKey)
{
if (HttpContext.Current!=null && HttpContext.Current.Request!=null && !string.IsNullOrEmpty(HttpContext.Current.Request.QueryString[queryStringKey])
{
return HttpContext.Current.Request.QueryString.GetValues(queryStringKey).First();
}
return "NAQ";
}
I am beginner with spring, I have a search form and I want to error or the form is blank it sends me to the error page otherwise it sends me to the page result.
if anyone can help me
thank you
here is my code.
#SuppressWarnings( { "unchecked" })
#RequestMapping("/search.html")
public String findAllData(Map model, SearchForm seachForm) {
model.put("allData", searchService.searchData(seachForm));
if("seachForm"!=null)
{
return "displayForm";
}
else
{
return "redirect:/searchForm.htm";
}
if("seachForm"!=null){
return "displayForm";
}else{
return "redirect:/searchForm.htm";
}
seachForm is not a String, try with
if(seachForm != null){
return "displayForm";
}else{
return "redirect:/searchForm.htm";
}
Greetings.
As MG_Bautista showed searchForm is definitely not a String (you should have gotten a compile error), but searchForm would also never be null. It'll just be a bunch of zero-length Strings. You have to do iterate over all fields of searchForm like
if ("".equals(searchForm.getUserName()) &&
"".equals(searchForm.getAddress())) {
return "displayForm";
} else {
return "redirect:/searchForm.htm";
}