Rest Web service parameter issue - java

am using below code to test a basic web service. When am passing normal string it works fine for example - http://localhost.com:8080/CheckRest/rest/pmg?p1=xyz. It displays HELLO xyz
But when I add '#' to the URL it doesnt give the right output for example - http://localhost.com:8080/CheckRest/rest/pmg?p1=xyz#abc. It then displays HELLO xyz instead of HELLO xyz#abc
package com.check.ws;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
#Path("/pmg")
public class CheckCall {
#GET
#Produces(MediaType.TEXT_PLAIN)
public String sayPlainTextHello() {
return " ";
}
// This method is called if XML is request
#GET
#Produces(MediaType.TEXT_XML)
public String sayXMLHello() {
return "<?xml version=\"1.0\"?>" + "<pmg> </pmg>";
}
// This method is called if HTML is request
#GET
#Produces(MediaType.TEXT_HTML)
public String sayHtmlHello(#QueryParam("p1") String par1) {
return "<html> <body> HELLO </body> </html>"+par1;
}
}

The pound/hash sign (#) indicates the beginning of the URL fragment identifier. If you want to use a pound/hash sign in your query string, you need to URL encode it by replacing it with %23:
http://localhost.com:8080/CheckRest/rest/pmg?p1=xyz%23abc

Related

I want to take value from one API response body and use into another api request using Cucumber gherkin

Scenario: Verify the manifest of published app
1. Given Base url "baseUrl" and path "basepath"
2. And Headers are
3. And Query parameter
4. And App with below details
5. When I execute the another API with Base url "baseUrl" and path "basePath"
6. And Append with Attributevalue (complete url will be , baseUrl + basePath + AttributeValue )
7. And api headers
8. And query parameters
9. Then Success message with 200 status code
I have implemented something very similar recently. You can utilize below code and modify it to your need. You'll probably need to omit some steps from your feature . Those steps are included as part of step def implementation in below code
Feature
#get
Scenario: get employee
Given an employee exist in the database with id "2"
When user retrieves employee info by id
Then the status code for get employee is 200
StepDefs
import io.cucumber.java.en.Given;
import io.cucumber.java.en.When;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.And;
import io.restassured.RestAssured;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import static org.junit.jupiter.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
public class secondIT {
public static Response response;
public static ValidatableResponse json;
public static RequestSpecification request;
public static String id;
public static JsonPath jsonPathEvaluator;
#Given("an employee exist in the database with id {string}")
public void an_employee_exists_with_id(String ID){
secondIT.id=ID;
RestAssured.baseURI = "http://dummy.www.com/api/v1";
secondIT.request = RestAssured.given();
}
#When("user retrieves employee info by id")
public void user_retrieves_employee_info_by_id(){
secondIT.response = secondIT.request.pathParam("id", secondIT.id).get("/employee/{id}");
secondIT.jsonPathEvaluator = secondIT.response.jsonPath();
assertNotNull(response);
}
#Then("the status code for get employee is {int}")
public void verify_status(int sc){
System.out.println("status code check.. " );
secondIT.json = secondIT.response.then().statusCode(sc);
System.out.println("status code: " + secondIT.response.getStatusCode());
assertEquals(sc,secondIT.response.getStatusCode());
}
}

jersey #PathParam: how to pass a variable which contains more than one slashes

package com.java4s;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
#Path("/customers")
public class RestServicePathParamJava4s {
#GET
#Path("{name}/{country}")
#Produces("text/html")
public Response getResultByPassingValue(
#PathParam("name") String name,
#PathParam("country") String country) {
String output = "Customer name - "+name+", Country - "+country+"";
return Response.status(200).entity(output).build();
}
}
In web.xml I have specified URL pattern as /rest/* and in RestServicePathParamJava4s.java we specified class level #Path as /customers and method level #Path as {name}/{country}
So the final URL should be
http://localhost:2013/RestPathParamAnnotationExample/rest/customers/Java4/USA
and the response should be displayed as
Customer name - Java4, Country - USA
If I give the 2 input given below it is showing an error. How to solve this?
http://localhost:2013/RestPathParamAnnotationExample/rest/customers/Java4:kum77./#.com/USA`
Here Java4:kum77./#.com this one is one string and it contains forward slash. how to accept this by using #PathParam or whatever I need to use MultivaluedMap. If somebody knows this plz help me. if anyone knows what is MultivaluedMap, give me a simple example?
You'll need to use a regex for for the name path expression
#Path("{name: .*}/{country}")
This will allow anything to be in the name template, and the last segment will be the country.
Test
#Path("path")
public class PathParamResource {
#GET
#Path("{name: .*}/{country}")
#Produces("text/html")
public Response getResultByPassingValue(#PathParam("name") String name,
#PathParam("country") String country) {
String output = "Customer name - " + name + ", Country - " + country + "";
return Response.status(200).entity(output).build();
}
}
$ curl http://localhost:8080/api/path/Java4:kum77./#.com/USA
Customer name - Java4:kum77./#.com, Country - USA
$ curl http://localhost:8080/api/path/Java4/USA
Customer name - Java4, Country - USA

How to publish "Hello world" Rest web service?

package my.first.rest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("hello")
public class Hello {
// This method is called if TEXT_PLAIN is requested
#GET
#Produces(MediaType.TEXT_PLAIN)
public String sayHelloInPlainText() {
return "Hello world!";
}
http://stackoverflow.com/questions/2893796/create-hello-world-with-restful-web-service-and-jersey
// This method is called if HTML is requested
#GET
#Produces(MediaType.TEXT_HTML)
public String sayHelloInHtml() {
return "<html> " + "<title>" + "Hello world!" + "</title>"
+ "<body><h1>" + "Hello world!" + "</body></h1>" + "</html> ";
}
}
This is my code I wrote web service Restful. When I publish with Test Client Then this error is coming:
IWAB0489E Error when deploying Web service to Axis runtime
axis-admin failed with {http://schemas.xmlsoap.org/soap/envelope/}
Server.userException java.net.ConnectException: Connection refused: connect
How will I fix it? This is coming with Rest only, not with SOAP.
You have to download the jersey [implementation of REST from sunmicrosystem] and include those jars in your application apart from this you have to modify your web.xml accordingly.
There are multiple beginners tutorial available on net - click here

Need to send arraylist to webservice from client and return modified arraylist

I have started out by creating a basic webservice with a #GET method shown below.
package com.webservice.eoin;
import java.awt.PageAttributes.MediaType;
import java.util.ArrayList;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
#Path("/webservice")
public class Web_service {
#PUT
#Path("/getname")
#Produces("text/plain")
public String getname()
{
return "hello!!!";
}
}
this works fine when I run it. I have all the jar files and web.xml file setup etc. What i want to do next is create a client that sends an arraylist of strings to the webservice and returns a modified version of the arraylist to the client. My question is first of all how do you set up the client? and how do I run it so it sends this arraylist to the server. Ive read a lot of tutorials but Iam finding some of them hard to follow. Im new to making webservices in Java. Thank you in advance
First of all, I am sorry I copied a lot of code from the project I am working on currently, but it would be cumbersome otherwise. Please excuse if I have typos or compile errors. Also, beware that you need an external library for this.
The client:
import java.net.URI;
import java.util.List;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.client.apache.ApacheHttpClient;
import com.sun.jersey.client.apache.config.ApacheHttpClientConfig;
import com.sun.jersey.client.apache.config.DefaultApacheHttpClientConfig;
public Client {
private final URI fServerURI;
private final ApacheHttpClient fClient;
private final MediaType fMediaType= MediaType.APPLICATION_XML_TYPE;
public Client() {
final String apiEndpoint= "...";
final DefaultApacheHttpClientConfig clientConfig;
fServerURI= UriBuilder.fromUri(apiEndpoint).build();
clientConfig= new DefaultApacheHttpClientConfig();
clientConfig.getProperties().put(ApacheHttpClientConfig.PROPERTY_HANDLE_COOKIES, true);
fClient= ApacheHttpClient.create(clientConfig);
}
private <T> T call(WebResource resource, RequestType requestType, Object requestEntity, GenericType<T> acceptType, String taskMessage) {
return acceptCall(resource, requestType, acceptType, requestEntity);
}
private <T> T acceptCall(WebResource resource, RequestType requestType, GenericType<T> acceptType, Object requestEntity) {
switch (requestType) {
case POST:
return resource.accept(fMediaType).post(acceptType, requestEntity);
case PUT:
return resource.accept(fMediaType).put(acceptType, requestEntity);
case DELETE:
resource.accept(fMediaType).delete();
return null;
default:
return resource.accept(fMediaType).get(acceptType);
}
public MyArrayList sendArrayList(MyArrayList list) {
WebResource resource= createResource();
resource= resource.path("webservice").path("sendarraylist");
resource= resource.queryParam("arraylist", list);
return call(resource, RequestType.POST, null, new GenericType<MyArrayList>() {
}, "Send my array list");
}
public static void main(String ... args) {
Client c= new Client();
MyArrayList result= c.sendArrayList(new MyArrayList(/*whatevs goes inside*/));
}
}
In the server you need something like:
#POST
#Path("/sendarraylist")
#Consumes(MediaType.APPLICATION_XML)
#Produces(MediaType.APPLICATION_XML)
MyArrayList modifyList(#QueryParam("arraylist") MyArrayList list) {
//do stuff
}
The last thing that is left is to create MyArrayList class according JAXB rules (see this example: http://www.vogella.com/articles/JAXB/article.html)

No response back from REST WS called by jQuery/JSON

I know there is a lot of these posts but I couldn't really get this to work since I am new to both REST and JQuery:
I am using REST-WS with Java 5 and I am able to call it and get result back with "Poster" ,the firefox plugin to test it. When I call the URL below I should get the employee in order '0' in the map by calling the method "getCustomer" in the resource class shown below.
Although I am not able to get the result and getting an error "unknown "using jQuery and returning JSON when I call the REST from an html page with body as below:
<body>
jQuery to REST <br><br>
jQuery
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function (){
$.ajax({
type: "GET",
url: "http://localhost:8081/RestDemo/services/customers/0",
dataType: "json",
success: function (data) {
alert(data.name);
},
error: function(e){
alert("Error: " + e);
}
});
});
});
</script>
<br>
<br>
<button>Return Customer</button>
</body>
This is my Resource class:
package com.myeclipseide.ws;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import com.sun.jersey.spi.resource.Singleton;
#Produces("application/xml")
#Path("customers")
#Singleton
#XmlRootElement(name = "customers")
public class CustomerResource {
private TreeMap<Integer, Customer> customerMap = new TreeMap<Integer, Customer>();
public CustomerResource() {
// hardcode a single customer into the database for demonstration
// purposes
Customer customer = new Customer();
customer.setName("Harold Abernathy");
customer.setAddress("Sheffield, UK");
addCustomer(customer);
}
#GET
#XmlElement(name = "customer")
public List<Customer> getCustomers() {
List<Customer> customers = new ArrayList<Customer>();
customers.addAll(customerMap.values());
return customers;
}
#GET
#Path("/{id}")
#Produces("application/json")
public String getCustomer(#PathParam("id") int cId) {
return "{\"name\": \"unknown\", \"address\": -1}"; //customerMap.get(cId);
}
#POST
#Path("add")
#Produces("text/html")
#Consumes("application/xml")
public String addCustomer(Customer customer) {
int id = customerMap.size();
customer.setId(id);
customerMap.put(id, customer);
return "Customer " + customer.getName() + " added with Id " + id;
}
}
I appreciate anyone's help,
Thanks!
I got it!
Returning {"name": "unknown", "address": -1} is right because that's exactly what is hard coded in my method return,
so i replaced return "{\"name\": \"unknown\", \"address\": -1}";
simply with a correct form which is
return "{\"name\": \" " + customer.getName() + " \", \"address\": \"" + customer.getAddress() + "\"}";
and obviously it works!
Thanks everyone.
I appreciate anyone's help,
If you are stumped, take a look at what is in the web countainer's log files. If necessary, turn on debug logging.
The next thing would be to use your web browser's built-in "web developer" support to see what request is actually being sent.

Categories