Java Spring #GetMapping not found - java

I write two functions #GetMapping in one class. Function getProcessImage is working but Function hello is not working.
NOT FOUND 404
I write two functions #GetMapping in one class. Function getProcessImage is working but Function hello is not working. It is not found 404.
#GetMapping(value = "/{processInsID}/{containerId}")
public ServiceResponse<String> getProcessImage(#PathVariable("processInsID") long procInstId,
#PathVariable("containerId") String containerId) {
AuthenticationInfo bpmAuthenInfo = new AuthenticationInfo(env.getProperty("jbpm.url"),
env.getProperty("jbpm.username"), env.getProperty("jbpm.password"), "");
String result = jbpmService.getImageProcessInProgess(bpmAuthenInfo, containerId, procInstId);
try {
return new ServiceResponse<String>(Constant.ServiceResponse.CODE_SUCCESS,
Constant.ServiceResponse.MSG_SUCCESS, result);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return new ServiceResponse<String>(Constant.ServiceResponse.CODE_ERROR, e.getMessage(), null);
}
}
#GetMapping(value = "/image/")
public ServiceResponse<String> hello() {
return new ServiceResponse<String>(Constant.ServiceResponse.CODE_ERROR,"okok", null);
}

Either you need to change your getMapping to /image (i.e remove / ) or you need to add image/ in your url path.I suggest you to remove / in your code as /image

Related

HAPI FHIR #Create Operation not returning MethodOutcome Response

I was basing my program off of the samples on hapishir's website and the operation works in that I receive the JSON body and I'm updating the database. The issue I have though is that there is no response being returned. I build the MethodOutcome object, and "return" it, but nothing appears in postman. I've written #read and #Search operations also and those both return the resource in the response on Postmat, but this #Create doesn't return any response.
ObservationResourceProvider.java
public class ObservationResourceProvider implements IResourceProvider {
public ObservationResourceProvider() { }
#Override
public Class<? extends IBaseResource> getResourceType() {
return Observation.class;
}
#Create()
public MethodOutcome createObservation(#ResourceParam Observation observation){
OpenERMDatabase db = new OpenERMDatabase();
String newObservationId = db.addNewObservation(observation);
//return the new Id if success else return an error message
MethodOutcome retVal = new MethodOutcome();
if (newObservationId != null) {
retVal.setId(new IdType("Observation", newObservationId, "1.0"));
retVal.setCreated(true);
}else {
OperationOutcome outcome = new OperationOutcome();
outcome.addIssue().setDiagnostics("An Error Occurred");
retVal.setOperationOutcome(outcome);
retVal.setCreated(false);
}
return retVal;
}
}
SimpleRestfulServer.java
#WebServlet("/*")
public class SimpleRestfulServer extends RestfulServer{
//Initialize
#Override
protected void initialize()throws ServletException{
//create a context for the appropriate version
setFhirContext(FhirContext.forDstu3());
//Register Resource Providers
registerProvider(new PatientResourceProvider());
registerProvider(new ObservationResourceProvider());
}
}
I've built an environment and debugged the server side code.
I'm sure you will get some hint from this. There are three modes defined in PreferReturnEnum, when you specify an extra header in the HEADERS with key as "Prefer" and value as " return=OperationOutcome", the value defined in operationOutcome will be retured.

Typecasting with a class that is protected

I am trying to override some class of vertx web project, since I have to change some of the features. So the tricky part comes here.
#Override
public void reroute(HttpMethod method, String path) {
int split = path.indexOf('?');
if (split == -1) {
split = path.indexOf('#');
}
if (split != -1) {
log.warn("Non path segment is not considered: " + path.substring(split));
// reroute is path based so we trim out the non url path parts
path = path.substring(0, split);
}
/*((HttpServerRequestWrapper) request).setMethod(method);
((HttpServerRequestWrapper) request).setPath(path);*/
((HttpServerRequestWrapper) request).setMethod(method);
((HttpServerRequestWrapper) request).setPath(path);
request.params().clear();
// we need to reset the normalized path
normalisedPath = null;
// we also need to reset any previous status
statusCode = -1;
// we need to reset any response headers
response().headers().clear();
// special header case cookies are parsed and cached
if (cookies != null) {
cookies.clear();
}
// reset the end handlers
if (headersEndHandlers != null) {
headersEndHandlers.clear();
}
if (bodyEndHandlers != null) {
bodyEndHandlers.clear();
}
failure = null;
restart();
}
This code throws me a compilation error saying:
'HttpServerRequestWrapper cannot be accessed from outside package'
I know for a fact that we can use reflection to create objects of a class that cannot be accessed. Can reflection be used in this case? How can I fix such an issue.
Any help will be much appreciated.
In java 8 and/or without modules it is possible to just place class like that in same package as original one to get access to all package-default classes.
Otherwise you need to use reflections like in other response, but I would add that it is good idea to cache that Class and Method instance, as using Class.forName and clazz.getDeclaredMethod each time will slowdown code.
What about getting the Class object and then calling the methods on your specific (uncasted) object?
I assume request is a class attribute of type HttpServerRequestWrapper. Then, this is what I suggest:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
...
private final Method setMethod;
private final Method setPath;
public MyConstructor() {
Method tmp1 = null, tmp2 = null;
try {
final Class<?> clazz = Class.forName("io.vertx.ext.web.impl.HttpServerRequestWrapper");
tmp1 = clazz.getMethod("setMethod", HttpMethod.class);
tmp1.setAccessible(true);
tmp2 = clazz.getMethod("setPath", String.class);
tmp2.setAccessible(true);
} catch (ClassNotFoundException e) {
// do something
} catch (NoSuchMethodException e) {
// do something
} catch (SecurityException e) {
// do something
}
this.setMethod = tmp1;
this.setPath = tmp2;
}
...
#Override
public void reroute(HttpMethod method, String path) {
...
try {
this.setMethod.invoke(request, method);
this.setPath.invoke(request, path);
} catch (IllegalAccessException e) {
// do something
} catch (IllegalArgumentException e) {
// do something
} catch (InvocationTargetException e) {
// do something
}
...
}
EDIT: I updated this answer based on #GotoFinal's suggestion.
It looks like HttpServerRequestWrapper implements HttpServerRequest. So, you can change "HttpServerRequestWrapper" to "HttpServerRequest" in your code. But remember that by doing so, you'll only be able to call methods specified in the interface.
You can see those methods in https://vertx.io/docs/apidocs/io/vertx/rxjava/core/http/HttpServerRequest.html.

Integrating javax validation with JavaFX

I have worked on several Spring MVC projects where the validation could be done very simply like such :
CONTROLLER
#RequestMapping(value = {"/newHeightUnit"}, method = RequestMethod.POST)
public String saveHeightUnit(#Valid HeightUnit heightUnit, BindingResult result, ModelMap model)
{
boolean hasCustomErrors = validate(result, heightUnit);
if ((hasCustomErrors) || (result.hasErrors()))
{
setPermissions(model);
return "heightUnitDataAccess";
}
heightUnitService.save(heightUnit);
session.setAttribute("successMessage", "Successfully added height unit \"" + heightUnit.getName() + "\"!");
return "redirect:/heightUnits/list";
}
private boolean validate(BindingResult result, HeightUnit heightUnit)
{
boolean hasCustomErrors = false;
if (heightUnitService.nameExists(heightUnit))
{
FieldError error = new FieldError("heightUnit", "name", heightUnit.getName(), false, null, null,
heightUnit.getName() + " already exists!");
result.addError(error);
hasCustomErrors = true;
}
return hasCustomErrors;
}
This would validate the entity against whatever validation annotation it had (#NotNull, #Size, #Digits, etc).
How can the same be achieved in JavaFX? I have 9 entities all with their validation annotations as I was doing in my MVC projects. I am using Spring with what you could call a view / service / dao structure. I do not use FXML at all, my UI components are all generated in pure Java and I intend for it to stay that way.
How can I use the validation annotations on my entities in a similarly friendly approach to that of Spring MVC?
Clarifications
Just for reference, this is how my entities are currently saved. There is currently no validation of the user's inputs whatsoever when they are added but everything works perfectly fine. My entities are all annotated and ready to go and i'm just looking to learn how to integrate the good ol' #Valid into the mix:
#Override
public void saveEntity()
{
TextField nameField = (TextField)formFields.get(0);
try
{
Category newCategory = new Category(null, nameField.getText(), new Date(), null);
categoryService.save(newCategory);
}
catch (Exception ex)
{
logger.error("Error adding category : " + ex.getMessage());
}
}
Thanks!
So i ended up with a pretty clean result. First off i ended up with a validator class that looks something like this :
public class EntityValidator
{
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
public Set<ConstraintViolation<Category>> validateCategory(Category category)
{
return validator.validate(category);
}
}
I am using Spring to make this class available for autowiring :
#Bean
public EntityValidator entityValidator()
{
return new EntityValidator();
}
The bean validation goes something like this :
TextField nameField = (TextField)formFields.get(0);
try
{
Category newCategory = new Category(null, nameField.getText(), new Date(), null);
Set<ConstraintViolation<Category>> errors = validator.validateCategory(newCategory);
if (errors.isEmpty())
{
categoryService.save(newCategory);
close();
}
else
{
showErrorMessages(errors);
}
}
catch (Exception ex)
{
logger.error("Error adding category : " + ex.getMessage());
}
The showErrorMessages method just takes the error Set and displays the first error in an error dialog. Since i am using validation groups, there is never more than one error in the Set so this all looks pretty clean. It will never be as simple as doing it from a controller in a web project but i'm pretty happy with the result overall.
Cheers

Unable to get data from java web service

Someone please help me i keep trying but not able to find out why i am unable to get the results.
I have created this java springboot web service where when I run the java application, a web browser page will open and when I type in the URL e.g localhost:8080/runbatchfileparam/test.bat the program will check if the test.bat file exist first. If it does, the web page will show a JSON result {“Result”: true} and the command in the batch file will be executed. If it does not exist, the web page will show {“Result”: false}.
I want to create an ASP.NET Web Service that will use the function created in the java web service. When I run the ASP.NET Web Application, a web browser page will open. User will type in URL something like this: localhost:12345/api/callbatchfile/test.bat. The java web service should be running and I should get either {“Result”: true} or {“Result”: false} when I run the C# ASP.NET Web Application too.
However I only get an empty {} without anything inside the brackets. Why is that so?
Here are my code in ASP.NET
TestController.cs
private TestClient testClient = new TestClient();
public async Task<IHttpActionResult> GET(string fileName)
{
try
{
var result = await testClient.runbatchfile(fileName);
var resultDTO = JsonConvert.DeserializeObject<TestVariable>(result);
return Json(resultDTO);
}
catch (Exception e)
{
var result = "Server is not running";
return Ok(new { ErrorMessage = result });
}
}
TestVariable.cs
public class TestVariable
{
public static int fileName { get; set; }
}
TestClient.cs
private static HttpClient client;
private static string BASE_URL = "http://localhost:8080/";
static TestClient()
{
client = new HttpClient();
client.BaseAddress = new Uri(BASE_URL);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task<string> runbatchfile(string fileName)
{
var endpoint = string.Format("runbatchfile/{0}", fileName);
var response = await client.GetAsync(endpoint);
return await response.Content.ReadAsStringAsync();
}
WebApiConfig.cs
config.Routes.MapHttpRoute(
name: "TestBatchClient",
routeTemplate: "api/runbatchfile/{fileName}",
defaults: new { action = "GET", controller = "Test" }
);
Someone please do help me. Thank you so much.
EDIT
Java web service
Application.java
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
BatchFileController.java
private static final String template = "Sum, %s!";
#RequestMapping("/runbatchfile/{param:.+}")
public ResultFormat runbatchFile(#PathVariable("param") String fileName) {
RunBatchFile rbf = new RunBatchFile();
return rbf.runBatch(fileName);
}
ResultFormat
private boolean result;
public ResultFormat(boolean result) {
this.result = result;
}
public boolean getResult() {
return result;
}
RunBatchFile.java
public ResultFormat runBatch(String fileName) {
String var = fileName;
String filePath = ("C:/Users/attsuap1/Desktop/" + var);
try {
Process p = Runtime.getRuntime().exec(filePath);
int exitVal = p.waitFor();
return new ResultFormat(exitVal == 0);
} catch (Exception e) {
e.printStackTrace();
return new ResultFormat(false);
}
}
I am not sure if this helps.. but I suspect that the AsyncTask is not really executing...
var result = await testClient.testCallBatchProject(fileName);
I would try something like below:
await testClient.testCallBatchProject(fileName).Delay(1000);
Can you try and check if the same happens for a synchronous call? .. if it does, we can zero down on the above.

What is the right way to use Espresso in android?

I am trying to run an Espresso test for my android app, but there is a problem that has been troubling me. In MainActivity, some views' visibility depends on data loaded from net, but in MainActivityTest, I can't manipulate the process of loading data, so I don't know the real data and which view should show and which view should not show. As a result, I don't know how to continue my test. Anyone can tell me how to handle this situation? Thanks!
Try using the MockWebServer library. It lets you mock http responses in your tests, like this:
/**
* Constructor for the test. Set up the mock web server here, so that the base
* URL for the application can be changed before the application loads
*/
public MyActivityTest() {
MockWebServer server = new MockWebServer();
try {
server.start();
} catch (IOException e) {
e.printStackTrace();
}
//Set the base URL for the application
MyApplication.sBaseUrl = server.url("/").toString();
//Create a dispatcher to handle requests to the mock web server
Dispatcher dispatcher = new Dispatcher() {
#Override
public MockResponse dispatch(RecordedRequest recordedRequest) throws InterruptedException {
try {
//When the activity requests the profile data, send it this
if(recordedRequest.getPath().startsWith("/users/self")) {
String fileName = "profile_200.json";
InputStream in = this.getClass().getClassLoader().getResourceAsStream(fileName);
String jsonString = new String(ByteStreams.toByteArray(in));
return new MockResponse().setResponseCode(200).setBody(jsonString);
}
//When the activity requests the image data, send it this
if(recordedRequest.getPath().startsWith("/users/self/media/recent")) {
String fileName = "media_collection_model_test.json";
InputStream in = this.getClass().getClassLoader().getResourceAsStream(fileName);
String jsonString = new String(ByteStreams.toByteArray(in));
return new MockResponse().setResponseCode(200).setBody(jsonString);
}
} catch (IOException e) {
e.printStackTrace();
}
return new MockResponse().setResponseCode(404);
}
};
server.setDispatcher(dispatcher);
}

Categories

Resources