REST POST returns status 405, in wildflyv10 - java

I have my service defined as:
#Path("/fileservice")
public class FileService {
#POST
#Path("/path")
#Consumes("application/xml")
public Response getFilePath(FileRequest fileRequest) {
System.out.println("....." + fileRequest.client);
(...)
}
My activator:
#ApplicationPath("/services")
public class JaxRsActivator extends Application{
}
And the XML file mapping is defined as:
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name="fileDetails")
public class FileRequest {
#XmlElement public String path;
#XmlElement public String client;
And my client is:
public static void main(String args[]) throws Exception {
URI uri = new URI(SERVICE_URL);
Client client = ClientBuilder.newClient();
String xml = "<fileDetails> "
+ "<path>usr/test/a.pdf</path>"
+ "<client>abc</client>"
+"</fileDetails>" ;
Response response= client.target(uri).request().post(Entity.xml(xml));
System.out.println("Request posted :"+ response.getAllowedMethods());
System.out.println("Request posted, response status :"+ response.getStatus());
When I send request to the URL http://localhost:8080/xx/services/fileservice/path I'm getting response.getStatus() as 405.
What I'm doing wrong here?

Related

Using attributes of one class in another class

I am trying to move the assertThat method from Authentication class to the BDDStyledMethod class but the current code will generate the following error "'Creds(java.lang.String)' in 'steps.Authentication' cannot be applied to '()'"
How do i correct my code so that the assertThat method works in the BDDStyledMethod class ?
public class Authentication {
public static void Creds(String url){
RequestSpecification httpRequest=RestAssured.given()
.auth().oauth2(Authentication.login("user","password"));
Response response = httpRequest.get(url);
ResponseBody body=response.getBody();
body.prettyPrint();
System.out.println("The status received: " + response.statusLine());
assertThat("They are not the same",response.statusLine(),is("HTTP/1.1 200"));
}
}
public class BDDStyledMethod {
public static void GetActivityById(){
Authentication.Creds("www.randomurl.com");
assertThat("They are not the same",Authentication.Creds().response.statusLine(),is("HTTP/1.1 200"));
}
}
The problem is with the Creds method. It is not returning anything and the exception is raised in this line -> Authentication.Creds().response.statusLine()
We can return a string from Creds method and then try to apply assert() on the returned string in GetActivityById class.
public class Authentication {
public static String Creds(String url){
RequestSpecification httpRequest=RestAssured.given()
.auth().oauth2(Authentication.login("user","password"));
Response response = httpRequest.get(url);
ResponseBody body=response.getBody();
body.prettyPrint();
System.out.println("The status received: " + response.statusLine());
return response.statusLine().toString();
}
}
public class BDDStyledMethod {
public static void GetActivityById(){
String returned_str = Authentication.Creds("www.randomurl.com");
assertThat("They are not the same",returned_str,is("HTTP/1.1 200"));
}
}

How to Mock HttpResponse for the Web Service (Using JavaHttpClient)?

I have WebService Call using Java Http Client. Need to do Junit testing using Mockito for the Response of WebService (HttpResponse).
Gson gson = new Gson();
HttpResponse httpResponse= JavaHttpClient.callWebService("URL",object);
String json = EntityUtils.toString(httpResponse.getEntity());
response = gson.fromJson(json, ClassName.class);
log.info("Response: " + new Gson().toJson(response));
How to set the mock values for httpResponse.getEntity() ? and this should be convert to JSON as above
Thanks
Nithyanandan K
Here is some sample MockServer. Modify it for your requirement.
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.response;
import org.mockserver.client.server.MockServerClient;
import org.mockserver.initialize.ExpectationInitializer;
import org.mockserver.model.Header;
import org.mockserver.model.HttpStatusCode;
public class MockServerInitializer implements ExpectationInitializer {
/**
* Standalone mock server
*
* #param args
*/
public static void main(String[] args) {
MockServerClient mockServerClient = startClientAndServer(9999);
defineMockServerBehaviour(mockServerClient);
}
#Override
public void initializeExpectations(MockServerClient mockServerClient) {
defineMockServerBehaviour(mockServerClient);
}
public static void defineMockServerBehaviour(MockServerClient mockServer) {
mockServer.when(
request()
.withMethod("POST")
.withPath("/Sample")
).respond(
response()
.withStatusCode(HttpStatusCode.OK_200.code())
.withHeader(Header.header("Content-Type", "application/xml"))
.withBody("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
"<Response>\n" +
" <responseStatus>OK</responseStatus>\n" +
"</Response>"));
}
}

Woocommerce REST API with scribes-java library returns consumer key param missing error message

Hi guys I am trying to use scribe-java library to access the REST api via http.code looks
package org.scribe.examples;
import java.util.*;
import org.scribe.builder.*;
import org.scribe.builder.api.*;
import org.scribe.model.*;
import org.scribe.oauth.*;
public class WooCommerceOauth1Example {
private static final String RESOURCE_URL = "http://WEBSITE.COM/wc-api/v1/orders";
public static void main(String[] args) {
OAuthService service = new ServiceBuilder().provider(OneLeggedApi10.class)
.apiKey("ck_SOME_NUMBER")
.apiSecret("cs_SOME_NUMBER")
.build();
// Now let's go and ask for a protected resource!
System.out.println("Now we're going to access a protected resource...");
OAuthRequest request = new OAuthRequest(Verb.GET, RESOURCE_URL);
//Since it is a one legged protocol, access token is empty.Right?
service.signRequest(new Token("", ""), request);
Response response = request.send();
System.out.println("Got it! Lets see what we found...");
System.out.println();
System.out.println(response.getCode());
System.out.println(response.getBody());
System.out.println();
System.out.println("Thats it man! Go and build something awesome with Scribe! :)");
}
}
Throws the following error
{"errors":[{"code":"woocommerce_api_authentication_error","message":"oauth_consumer_key parameter is missing"}]}
. Any Ideas why my code is throwing the above error? Note that I have checked the v1 endpoint with http and it returns sensible message back.so basically it is working.
Removing '&' + OAuthEncoder.encode(tokenSecret) from https://github.com/fernandezpablo85/scribe-java/blob/master/src/main/java/org/scribe/services/HMACSha1SignatureService.java#L32 and adding and changed signature type to QueryString and it works now.
I will propose a PR after cleaning.Thanks Pablo. Below is the full code
package org.scribe.builder.api;
import org.scribe.model.Token;
import org.scribe.model.Verb;
public class OneLeggedApi10 extends DefaultApi10a {
#Override
public String getAccessTokenEndpoint() {
return null;
}
#Override
public String getRequestTokenEndpoint() {
return null;
}
#Override
public String getAuthorizationUrl(Token requestToken) {
return null;
}
#Override
public Verb getAccessTokenVerb() {
return Verb.GET;
}
#Override
public Verb getRequestTokenVerb() {
return Verb.GET;
}
}
And the example class
package org.scribe.examples;
import org.scribe.builder.*;
import org.scribe.builder.api.*;
import org.scribe.model.*;
import org.scribe.oauth.*;
public class WooCommerceOauth1Example {
private static final String NETWORK_NAME = "Woocommerce";
private static final String RESOURCE_URL = "http://YOUR_DOMAIN/wc-api/v1/orders/count";
private static final String SCOPE = "*"; //all permissions
public static void main(String[] args) {
OAuthService service = new ServiceBuilder().provider(OneLeggedApi10.class)
.apiKey("API_KEY")
.apiSecret("SECRET_KEY")
.debugStream(System.out)
.signatureType(SignatureType.QueryString)
/*.scope(SCOPE).*/
.build();
System.out.println("=== " + NETWORK_NAME + "'s OAuth Workflow ===");
System.out.println();
// Now let's go and ask for a protected resource!
System.out.println("Now we're going to access a protected resource...");
OAuthRequest request = new OAuthRequest(Verb.GET, RESOURCE_URL);
service.signRequest(new Token("", ""), request);
Response response = request.send();
System.out.println("Got it! Lets see what we found...");
System.out.println();
System.out.println(response.getCode());
System.out.println(response.getBody());
System.out.println();
System.out.println("Thats it man! Go and build something awesome with Scribe! :)");
}
}

send XML string to web service in Jersery

I am new to web service in jersey. I have created a web service the code is below
#Path("/remotedb")
public class RemoteDb {
#GET
#Path("/save/{xmlData}")
#Produces(MediaType.TEXT_XML)
public String saveData(#PathParam("xmlData") String xml) {
return xml;
}
}
I have this code at client side
public class WebServiceClient {
public static void callWebService() {
String xml = "<data>" +
"<table><test_id>t4</test_id><dateprix>2013-06-06 22:50:40.252</dateprix><nomtest>NOMTEST</nomtest><prixtest>12.70</prixtest><webposted>N</webposted><posteddate>2013-06-06 21:51:42.252</posteddate></table>" +
"</data>";
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client.resource(getBaseURI());
System.out.println(service.path("restful").path("remotedb").path("save").path(xml).accept(MediaType.TEXT_XML).get(String.class));
}
private static URI getBaseURI() {
return UriBuilder.fromUri("http://localhost:8080/WebServiceModule").build();
}
}
Now when i called the web service i got the following exception
Exception in thread "main" com.sun.jersey.api.client.UniformInterfaceException: GET http://localhost:8080/WebServiceModule/restful/remotedb/save/%3Cdata%3E%3Ctable%3E%3Ctest_id%3Et4%3C/test_id%3E%3Cdateprix%3E2013-06-06%2022:50:40.252%3C/dateprix%3E%3Cnomtest%3ENOMTEST%3C/nomtest%3E%3Cprixtest%3E12.70%3C/prixtest%3E%3Cwebposted%3EN%3C/webposted%3E%3Cposteddate%3E2013-06-06%2021:51:42.252%3C/posteddate%3E%3C/table%3E%3C/data%3E returned a response status of 404 Not Found
at com.sun.jersey.api.client.WebResource.handle(WebResource.java:686)
at com.sun.jersey.api.client.WebResource.access$200(WebResource.java:74)
at com.sun.jersey.api.client.WebResource$Builder.get(WebResource.java:507)
at com.main.WebServiceClient.callWebService(WebServiceClient.java:25)
at com.main.Test.main(Test.java:7)
Passing XML data in a path segment is very unorthodox and likely to raise all kind of issues. You should pass it as a query parameter, e.g. /WebServiceModule/restful/remotedb/save?xmlData=
%3Cdata...
#GET
#Path("/save")
#Produces(MediaType.TEXT_XML)
public String saveData(#QueryParam("xmlData") String xml) {
return xml;
}
}
or even better if it is a write operation as the name suggests then it should be a POST /WebServiceModule/restful/remotedb/save with the xmlData passed in the request body.
#POST
#Path("/save")
#Produces(MediaType.TEXT_XML)
public String saveData(String xml) {
return xml;
}
}
or even better yet, if you can map your xmlData to a POJO with JAXB's #XmlRootElement annotation, then you can get jersey to parse it for you:
#POST
#Path("/save")
#Consumes(MediaType.APPLICATION_XML)
public String saveData(YourXmlDataObject obj) {
return obj.getField();
}
}

Severe error for using "multipart/form-data" for a file upload service - Apache Jersey

I get this error:
SEVERE: Resource methods utilizing #FormParam and consuming "multipart/form-data" are no longer supported. See #FormDataParam
When a client web access is done for a Apache Jersey based Rest web service I am working right now:
#POST
#Path("upload")
#Consumes("multipart/form-data")
#Produces("text/plain")
public String uploadFile(#FormParam("file") File file, #FormParam("file") FormDataContentDisposition fileDetail) {
String fileLocation = "/files/" + fileDetail.getFileName();
System.out.println("File location: " + fileLocation);
// Load image
try {
byte[] imageBytes = loadImage(fileLocation);
MongoConnection conn = MongoUtil.getConnection();
conn.connect("m1", "avatar");
GridFS fs = new GridFS(conn.getDB());
GridFSInputFile in = fs.createFile(imageBytes);
in.save();
} catch (Exception e) {
e.printStackTrace();
}
return "1";
}
I have tried changing from #FormParam to #FormDataParam but it's unresolved.
What could be the fix for this?
Try this:
#Path("upload")
#Consumes("multipart/form-data")
#POST
public void handleUpload(#FormParam("file") InputStream file) throws Exception {
// do your thing
}
You can also refer this post.
For Client Side:
import java.io.File;
import javax.ws.rs.core.MediaType;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.multipart.FormDataMultiPart;
public class UploadExample {
public void upload(String url, File f, String formName) {
FormDataMultiPart form = new FormDataMultiPart().field(formName, f, MediaType.MULTIPART_FORM_DATA_TYPE);
WebResource webResource = Client.create().resource(url);
webResource.type(MediaType.MULTIPART_FORM_DATA)
.accept(MediaType.TEXT_PLAIN)
.post(form);
}
}
You will have to download and use jersey-multipart.jar

Categories

Resources