returning a value using REST - rest

I am getting errors when I am trying to return values using REST. The error is:
A HTTP GET method, public - should not consume any entity.
This is my class:
public class StockManagement {
ArrayList<String> items = new ArrayList<>();
ArrayList<Integer> stockLevel = new ArrayList<>();
#GET
#Produces("application/xml")
public String addItem(String item) {
if(items.contains(item)) { // returns true is item is exists else false
String r = "Item is already in list";
String result = "#Produces(\"application/xml\")" + r;
return "<StockManagementService>"+ "<div>" + result + "</div>" +"</StockManagementService>";
}
else {
String r = "Item has been added successfully";
String result = "#Produces(\"application/xml\")" + r;
items.add(item); // add item to inventory
stockLevel.add(0); // set the number of stock for the item in inventory
return "<StockManagementService>" +"<div>" + result + "</div>" +"</StockManagementService>";
}
}
#GET
#Produces("application/xml")
public String setStock(String item, int stockLevels) {
if(!items.contains(item)) {
String r = "Item is not in the inventory";
String result = "#Produces(\"application/xml\")" + r;
return "<StockManagementService>" + result + "</StockManagementService>";
}
else {
int index = items.indexOf(item);
stockLevel.set(index, stockLevels);
String r = "Set stock has been complete successfully";
String result = "#Produces(\"application/xml\")" + r;
return "<StockManagementService>" + result + "</StockManagementService>";
}
}
#GET
#Produces("application/xml")
public String addStock(String item, int numItem) {
if(!items.contains(item)) {
String r = "Error, Cannot add item";
String result = "#Produces(\"application/xml\")" + r;
return "<StockManagementService>" + result + "</StockManagementService>";
}
else {
int index = items.indexOf(item);
String r = "Successfully added stock";
String result = "#Produces(\"application/xml\")" + r;
return "<StockManagementService>" + result + "</StockManagementService>";
}
}
#GET
#Produces("application/xml")
public String removeStock(String item, int numItem) {
if(items.contains(item)) {
int index = items.indexOf(item);
int val = stockLevel.get(index);
val = val - numItem;
stockLevel.set(index, val);
String r = "Successfully removed item.";
String result = "#Produces(\"application/xml\")" + r;
return "<StockManagementService>" + result + "</StockManagementService>";
}
else {
String r = "Item is not in the inventory";
String result = "#Produces(\"application/xml\")" + r;
return "<StockManagementService>" + result + "</StockManagementService>";
}
}
This is the error shown on eclipse terminal:
SEVERE: The following errors and warnings have been detected with resource and/or provider classes:
WARNING: A HTTP GET method, public java.lang.String com.crunchify.restjersey.StockManagement.setStock(java.lang.String,int), should not consume any entity.
WARNING: A HTTP GET method, public java.lang.String com.crunchify.restjersey.StockManagement.addStock(java.lang.String,int), should not consume any entity.
WARNING: A HTTP GET method, public java.lang.String com.crunchify.restjersey.StockManagement.removeStock(java.lang.String,int), should not consume any entity.
WARNING: A HTTP GET method, public java.lang.String com.crunchify.restjersey.StockManagement.addItem(java.lang.String), should not consume any entity.
SEVERE: Consuming media type conflict. The resource methods public java.lang.String com.crunchify.restjersey.StockManagement.addStock(java.lang.String,int) and public java.lang.String com.crunchify.restjersey.StockManagement.setStock(java.lang.String,int) can consume the same media type
SEVERE: Consuming media type conflict. The resource methods public java.lang.String com.crunchify.restjersey.StockManagement.removeStock(java.lang.String,int) and public java.lang.String com.crunchify.restjersey.StockManagement.setStock(java.lang.String,int) can consume the same media type
SEVERE: Consuming media type conflict. The resource methods public java.lang.String com.crunchify.restjersey.StockManagement.addItem(java.lang.String) and public java.lang.String com.crunchify.restjersey.StockManagement.setStock(java.lang.String,int) can consume the same media type
I cannot figure out what this error means, obviously it has to be the way I am returning, any help would be appreciated.
Thanks.

No promises, but I think the WARNING is trying to remind you that, in HTTP, GET doesn't take a message body. So String item should probably be encoded into the URI itself, which might mean a #QueryParam or #PathParam annotation.
SEVERE is trying to tell you that there are multiple methods that are all trying to be mapped to the same route. That is to say, they are all mapped to the same URI with the same method and the same application type, so how is the routing logic supposed to choose between them.
That might mean that you need to specify different paths for each, or that you should have only one annotated method that has the logic to choose which implementation to use.

Related

Jena Location Mapping failed to find configuration

i am working with Jena Text Search using SPARQL. It has succeed in compile time and run time but it doesn't show the desired result which is the result should show the URI and the intended text. It looks like error messages but i get the failed description below:
DEBUG org.apache.jena.util.LocationMapper - Failed to find configuration: file:location-mapping.rdf;file:location-mapping.n3;file:location-mapping.ttl;file:etc/location-mapping.rdf;file:etc/location-mapping.n3;file:etc/location-mapping.ttl
DEBUG org.apache.jena.riot.system.stream.JenaIOEnvironment - Failed to find configuration: location-mapping.ttl;location-mapping.rdf;location-mapping.n3;etc/location-mapping.rdf;etc/location-mapping.n3;etc/location-mapping.ttl
The full codes show below:
public class JenaTextSearch {
static {LogCtl.setLog4j();
BasicConfigurator.configure();}
static Logger log = LoggerFactory.getLogger("JenaTextSearch");
public static void main (String ...argv)
{
Dataset ds = createCode();
//loadData(ds, "data.ttl");
queryData(ds);
}
public static Dataset createCode()
{
//base data
Dataset ds1 = DatasetFactory.create();
Model defaultModel = ModelFactory.createDefaultModel();
defaultModel.read("to_index/data.ttl", "N-TRIPLES");
ds1.setDefaultModel(defaultModel);
//define the index mapping
EntityDefinition entDef = new EntityDefinition ("uri", "text", ResourceFactory.createProperty(App.URI_PREFIX,"content"));
Directory dir = null;
try {
dir = new SimpleFSDirectory(Paths.get("index")); //lucene index directory
}
catch (IOException e) {
e.printStackTrace();
}
//join together into a dataset
Dataset ds = TextDatasetFactory.createLucene(ds1, dir, new TextIndexConfig(entDef));
return ds1;
}
public static void queryData(Dataset dataset)
{
String prefix = "PREFIX email: <" + App.URI_PREFIX+">" +
"PREFIX text: <http://jena.apache.org/text#>";
long startTime = System.nanoTime();
System.out.println("Email's content contains 'good'");
String query = "SELECT * WHERE " +
"{?s text:query (email:content 'good')." +
"?s email:content ?text." +
"}" ;
dataset.begin(ReadWrite.READ);
try {
Query q = QueryFactory.create(prefix+"\n"+query);
QueryExecution qexec = QueryExecutionFactory.create(q, dataset);
QueryExecUtils.executeQuery(q, qexec);
}finally { dataset.end();}
long finishTime = System.nanoTime();
double time = (finishTime-startTime)/1.0e6;
System.out.println ("Query "+String.format("FINISH - %.2fms", time));
startTime = System.nanoTime();
System.out.println("Email's content contains 'bad'");
query = "SELECT * WHERE" +
"{(?s ?score ?lit) text:query (email:content 'bad' \"highlight:s:<em class='hiLite'> | e:</em>\")." +
"?s email:content ?text." +
"}" ;
dataset.begin(ReadWrite.READ);
try {
Query q = QueryFactory.create(prefix+"\n"+query);
QueryExecution qexec = QueryExecutionFactory.create(q, dataset);
QueryExecUtils.executeQuery(q, qexec);
} finally { dataset.end() ; }
finishTime = System.nanoTime();
time = (finishTime-startTime)/1.0e6;
System.out.println("Query "+String.format("FINISH - %.2fms", time));
}}
is that a library problem or something? i use Jena 3.9 and 3.13 because it can completely each other, i think. please devise me. thank you.

How to display error message in multi file uploading with Rest webservices

Hi am in way of uploading multiple files into aws bucket using spring mvc and rest web services.
The positive scenario is working like if I select more one file its saved in aws bucket and am getting 200 here
String json1 = handler.handleResponse(response1);
System.out.println(json1);
My question is I have selected three files called x ,y and z as usual way the first file gets saved into bucket due to some issue y and z files failed to save how to inform the user that y and z are not saved into bucket
#PostMapping("/upload")
public String handleFileUpload(#RequestParam("specifications") MultipartFile[] specifications,
HttpServletRequest request,HttpSession session,final RedirectAttributes redirectAttributes) throws Exception {
for (int i = 0; i < specifications.length; i++) {
MultipartFile file = specifications[i];
String path = "Specification/";
String bucketName="BUcket/";
String inJson = "{\"filename\":\"" + file.getOriginalFilename() + "\",\"bucketname\":\""+ bucketName + "\",\"path\":\""+ path + "\"}";
addLogo(file, inJson);
}
code upload file
public void addLogo(MultipartFile file ,String inJson) throws IOException
{
String message="";
byte[] bytes = file.getBytes();
CloseableHttpClient httpclient = HttpClientBuilder.create().build();
HttpPost httppost = new HttpPost(fileUploadURL);
HttpEntity entity = MultipartEntityBuilder.create().addTextBody("json", inJson).addBinaryBody("file", bytes).build();
httppost.setEntity(entity);
HttpResponse response1 = httpclient.execute(httppost);
System.out.print(response1.getStatusLine());
ResponseHandler<String> handler = new BasicResponseHandler();
String json1 = handler.handleResponse(response1);
System.out.println(json1);
message = message + "You successfully uploaded " + file.getOriginalFilename() + "\n";
System.out.println(message);
}
by using ResponseEntity spring object, you can customize your returns based upload results. you catch IOEXception and create a specific return String,
I modified your method to be like this :
#PostMapping("/upload")
public ResponseEntity<?> handleFileUpload(#RequestParam("specifications")
MultipartFile[] specifications,
HttpServletRequest request,HttpSession session,final RedirectAttributes
redirectAttributes) throws Exception {
String failed_upload="";
for (int i = 0; i < specifications.length; i++) {
try{
MultipartFile file = specifications[i];
String path = "Specification/";
String bucketName="BUcket/";
String inJson = "{\"filename\":\"" + file.getOriginalFilename()
+ "\",\"bucketname\":\""+ bucketName + "\",\"path\":\""+ path + "\"}";
addLogo(file, inJson);
}catch(IOException){
failed_upload=failed_upload+specifications[i]+" ,";
}
} if(!failed_upload.equals("")){
return new ResponseEntity<>("Files"+failed_upload+" not uploaded",
HttpStatus.INTERNAL_SERVER_ERROR);
}else{
return new ResponseEntity<>("Everything is ok", HttpStatus.OK);
}

How to restrict to a list of query params for a REST api

I want to restrict to a set of query params for rest Method.
#Path("/users")
public class UserService {
#GET
#Path("/query")
public Response getUsers(
#QueryParam("from") int from,
#QueryParam("to") int to,
#QueryParam("orderBy") List<String> orderBy) {
return Response
.status(200)
.entity("getUsers is called, from : " + from + ", to : " + to
+ ", orderBy" + orderBy.toString()).build();
}
}
“users/query?from=100&to=200&orderBy=age&orderBy=name” [WORKS]
“users/query?x=y” [also works and when my query params are set with default values]
i want throw some exceptions based on that.

RestEasy - Unable to find MessageBodyReader ... application/xml?

i try since 2 days to find something about this problem, still don't get it. I got my Maven-Project running on Wildfly.
Rest-Code:
#Override
#GET
#Path("{id}")
// #Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Customer getOverId(#PathParam("id") String id) {
logger.info("put in " + this.getClass().getName() + " over id " + id);
// if (id != null) {
// Customer object = service.loadOneCustomer(new Integer(id));
// logger.info("found in " + this.getClass().getName());
// return Response.ok(object).build();
// }
Customer customer = service.loadOneCustomer(new Integer(id));
// logger.info("nix found");
if(customer == null) {
throw new NotFoundException("No customer found with the matching ID: " + id);
}
logger.info("Customer found: " + customer.getCustomerNumber());
// return Response.status(Status.BAD_REQUEST).build();
return customer;
}
Client-Implementation:
public Response readCustomer(String id){
log.info("Starting: Rest get a Customer with ID: " + id);
log.info(this.URL);
this.customerWebTarget = this.client.target(this.URL).path(id);
Response response = this.customerWebTarget.request().buildGet().invoke();
// TODO Customer cast application_xml auf Customer? Customer customer = response.readEntity(Customer.class);
Customer customer = response.readEntity(Customer.class);
log.info("Ending: Rest invoque a Customer with ID:" + customer.getCustomerNumber());
// System.out.println("Ending: Rest get a Customer with ID: " + response.readEntity(String.class));
return response;
}
J-Unit Test:
#Test
public void testGetCustomerById() throws Exception {
Response response = this.customerRestClient.readCustomer("112");
System.out.println("--->" + response.getStatus());
Assert.assertTrue(response.getStatus() == 200);
}
Everything works perfekt till i try to get the Java-Object from the XML i get (Customer customer = response.readEntity(Customer.class);)
Am i missing something. I mean, i get read the xml-File and see every data in it... Why can't i cast it into Java-Object?
I always get this Error:
Javax.ws.rs.ProcessingException: Unable to find a MEssageBody of content-type-application/xml and type class de.....model.Customer
Without seeing the Customer class, it's hard to tell, but most likely some or all JAXB annotations are missing. In particular, you'll need an #XmlRootElement annotation.
Can you post the Customer class please. Was it properly annotated?
Also add the #Produces back in.

How to retrieve all the Groups/Roles a user is member of using SOAP services?

I am trying to collect some user informations using SOAP services.
I was able to get the Job Title for a given user, but I don't understand how to retrieve the list of groups and roles that a user has.
Can I simply use the GroupServiceSoap.getUserPlaces(long userId, String[] classNames, int max) method? Or is there another way I can get these fields?
Currently my code:
private static URL _getURL(String remoteUser, String password, String serviceName) {
final String LIFERAY_PROTOCOL = "http://";
final String LIFERAY_TCP_PORT = "8080";
final String LIFERAY_FQDN = "localhost";
final String LIFERAY_AXIS_PATH = "/api/secure/axis/";
try {
return new URL(LIFERAY_PROTOCOL + URLEncoder.encode(remoteUser, "UTF-8") + ":"
+ URLEncoder.encode(password, "UTF-8") + "#" + LIFERAY_FQDN
+ ":" + LIFERAY_TCP_PORT + LIFERAY_AXIS_PATH + serviceName);
} catch (MalformedURLException e) {
return null;
} catch (UnsupportedEncodingException e) {
return null;
}
}
[...]
public static void main(String[] argv){
public final String LIFERAY_USER_SERVICE="Portal_UserService";
public final String LIFERAY_COMPANY_SERVICE="Portal_CompanyService";
public final String LIFERAY_GROUP_SERVICE = "Portal_GroupService";
//company.default.web.id property
public final String LIFERAY_DEFAULT_COMPANY_ID = "liferay.com";
UserServiceSoap userService = new UserServiceSoapServiceLocator().getPortal_UserService(_getURL(USER_IDENTIFIER,USER_PASSWORD, LIFERAY_USER_SERVICE));
//This code is usefull if you want to use SOAP setter.
//((Portal_UserServiceSoapBindingStub) userService).setUsername(USER_IDENTIFIER);
//((Portal_UserServiceSoapBindingStub) userService).setPassword(USER_PASSWORD);
CompanyServiceSoap companyService = new CompanyServiceSoapServiceLocator().getPortal_CompanyService(_getURL(USER_IDENTIFIER, USER_PASSWORD, LIFERAY_COMPANY_SERVICE));
long companyId = companyService.getCompanyByMx(LIFERAY_DEFAULT_COMPANY_ID).getCompanyId();
// Here I retrieve my user, and can access some properties, but not them all !
UserSoap user = userService.getUserByEmailAddress(companyId, target_user_mail);
//TODO : I got hte JobTittle that I want, later I will do something more util thant just print it, I swear it my precious !
System.out.println(user.getJobTitle());
GroupServiceSoap groupService = new GroupServiceSoapServiceLocator().getPortal_GroupService(_getURL(USER_IDENTIFIER, USER_PASSWORD, LIFERAY_GROUP_SERVICE));
//this one return an empty array
GroupSoap[] userPlaces = groupService.getUserPlaces(new String[]{"Group", "Role"}, 150);
//this return an array of size 1, but the only GroupSoap seems to be a structural groups without any usefull properties to me.
GroupSoap[] userPlaces = groupService.getUserPlaces(null, 150);
}
Use this method to get user role and group user id
UserServiceSoap.getRoleUserIds
UserServiceSoap.getGroupUserIds
HTH
It is only a partial answer.
In order to get all the User Roles one can do this :
RoleServiceSoap roleService = new RoleServiceSoapServiceLocator().getPortal_RoleService(_getURL(USER_IDENTIFIER, USER_PASSWORD, LIFERAY_ROLE_SERVICE));
RoleSoap[] userRoles = roleService.getUserRoles(user.getUserId());
with user variable an instance of UserSoap.
The SOAP access must be done by an Admin user in order to get access to the Role List. The user can't access this himself.