can we use jersey client for Apache CXF webservice? - java

We have a REST service using apache CXF. Can we use Jersey client to call this service.
Is there any mistake?

The idea of a web service is to allow communication between hetrogenous systems. So no matter what framework is used to create the web service, you should be able to call it using any client, provided both client and server conforms to the JAX-RS specifications. So in your case you should be able to call a REST services developed using Apache CFX using the jersey client. As both the frameworks follows the JAX-RS spec.

Like said above, you can use even simple Http client to consume the REST service. With HTTP, you can easily perform GET, PUT, POST, DELETE
Example of simple http client for your reference
URL url = null;
try {
url = new URL(urlStr);
} catch (MalformedURLException e) {
throw new Exception("Malformed URL", e);
}
HttpURLConnection con = null;
try {
if (user != null && pass != null)
Authenticator.setDefault(new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, pass
.toCharArray());
}
});
// end of authentication test
SSLUtilities.trustAllHostnames();
SSLUtilities.trustAllHttpsCertificates();
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setAllowUserInteraction(true);
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestProperty("Content-Type", ConTypeGet);
s_logger.debug("Execute GET request Content-Type: "
+ con.getRequestProperty("Content-Type"));
s_logger.debug("URL:" + url);
con.connect();

Related

Spring - Doing a Post Request to a Rest Endpoint which returns a file

I've been searching through the web for a while now and wasn't able to find a proper solution, so i'm asking here.
I've got a Spring Application where I receive a POST request from the frontend (only knows the endpoint of the spring application). The controller should then do another POST request to another API which creates a PDF depending on the served data in the request and returns it. Now the question is: How can i do a Post Request and get the file which is being returned as attachment, so that Spring can send it back to my frontend (Angular).
So far i have the following:
#PostMapping(path = "/print/{username}")
public File printCompetences(#PathVariable final String username,
#RequestBody final List<PrintableCompetence> competences)
{
try {
ObjectMapper objectMapper = new ObjectMapper();
String competencesJson = objectMapper.writeValueAsString(competences);
URL url = new URL(flask_url);
URLConnection con = url.openConnection();
con.setRequestProperty("Content-Type", "application/json; utf-8");
con.setRequestProperty("Accept", "application/json");
con.setDoOutput(true);
try(OutputStream os = con.getOutputStream()) {
byte[] input = competencesJson.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
} catch (MalformedURLException malformedURLException) {
System.err.println(malformedURLException.getMessage());
malformedURLException.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Would be nice if someone could help me with ideas on how to handle this :)
if you're using spring, try using RestTemplate like this.
How to programmatically consume a file from a Rest API using Spring?

Accessing secured rest api at server side generated by hyperledger composer rest server

I am generating rest apis using composer-rest-server. I am authenticating rest api using passport-jwt. In composer rest server we get access_token in cookie.
We can set withCredentials:true for accessing these apis using client side but how can we call these apis using server side
Now when we make the same api call initiated from the server side(java), it fails. Giving us 401: Authorization Required error.
So my question is - Is it possible to call secured composer APIs from server side(java) ? If anyone has tried this before please let me know.
Try this code to retrieve cookies:
public void getCookieUsingCookieHandler() {
try {
// Instantiate CookieManager;
// make sure to set CookiePolicy
CookieManager manager = new CookieManager();
manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);
// get content from URLConnection;
// cookies are set by web site
URL url = new URL("http://host.example.com");
URLConnection connection = url.openConnection();
connection.getContent();
// get cookies from underlying
// CookieStore
CookieStore cookieJar = manager.getCookieStore();
List <HttpCookie> cookies =
cookieJar.getCookies();
for (HttpCookie cookie : cookies) {
if (cookie.getName().equalsIgnoreCase("access_token")) {
System.out.println("CookieHandler retrieved cookie: " + cookie.getValue());
break;
}
}
} catch(Exception e) {
System.out.println("Unable to get cookie using CookieHandler");
e.printStackTrace();
}
}
One can refer it from here: https://docs.oracle.com/javase/tutorial/deployment/doingMoreWithRIA/accessingCookies.html

Not found in embedded jetty

I deploy rest web-service (Jersey) in embedded jetty.
My server:
Map<String,Object> initMap = new HashMap<String, Object>();
initMap.put("com.sun.jersey.api.json.POJOMappingFeature", "true");
initMap.put("com.sun.jersey.config.property.packages", "com.extern.rest");
ResourceConfig rc = new PackagesResourceConfig(initMap);
restServer = HttpServerFactory.create("http://localhost:5555/core-gw-rs/", rc);
restServer.start()
My client:
URL url = new URL(buildUrl(params, path));
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.connect();
When I do a query from a client, in response I receive a status of 404. When a request is made by a browser to the same address get required result (200 status).
Update
Method:
#GET
#Path("{accountUuid}/domain/rfc822")
public Response fetchData(#PathParam("accountUuid") String accountUuid) {
return Response.ok().build();
}
The problem was that I started another soap service on another server (the same port, but different context) It remains a mystery why I was able to get through the browser.

Java HTTP PUT with Digest authentication in Java

I am trying to upload a file with Java using PUT, server does Digest authentication. I want to keep it lean, so I try to use HttpURLConnection.
public void putData(String path, byte [] data) throws IOException, MalformedURLException {
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user,password.toCharArray());
}});
debug("Default authenticator set");
//Safeguard against double slashes
if (path.startsWith("/")) {
path = path.replaceFirst("/","");
}
debug(hostname + path);
URL url = new URL(hostname + path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
debug("HttpURLConnection acquired");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("PUT");
conn.setRequestProperty("Content-Length",String.valueOf(data.length));
conn.setRequestProperty("Content-type","application/binary");
conn.setFixedLengthStreamingMode(data.length);
conn.connect();
debug("Properties set");
OutputStream out = conn.getOutputStream();
debug("Outputstrem acquired");
out.write(data,0,data.length);
out.flush();
out.close();
debug("Data written, stream closed.");
}
For some reason, this fails hopelessly: I see a 401 coming back, and then it's done. If I disable authorization, same code works. Downloading a file with similar code using digest authentication "just works". Any ideas? I'd really rather not start using the next so many libraries like htclient from Apache or so (...it's 2010... you'd expect http requests with digest authN to work in any standard library).
You should at least try conn.getInputStream() at the end of your method, to force evaluation of the server response. Otherwise, potential error messages from the server will not be detected properly.

Using HTTP Basic-Auth with Google App Engine URLFetch service

How can I specify the username and password for making Basic-Auth requests with App Engine's URLFetch service (in Java)?
It seems I can set HTTP headers:
URL url = new URL("http://www.example.com/comment");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("X-MyApp-Version", "2.7.3");
What are the appropriate headers for Basic-Auth?
This is a basic auth header over http:
Authorization: Basic base64 encoded(username:password)
eg:
GET /private/index.html HTTP/1.0
Host: myhost.com
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
You will need to do this:
URL url = new URL("http://www.example.com/comment");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization",
"Basic "+codec.encodeBase64String(("username:password").getBytes());
And to do that you will want to get a base64 codec api, like the Apache Commons Codec
For those interested in doing this in Python (as I was), the code looks like this:
result = urlfetch.fetch("http://www.example.com/comment",
headers={"Authorization":
"Basic %s" % base64.b64encode("username:pass")})
You set up an Authenticator before you call openConnection() like this,
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password.toCharArray());
}
});
Since there is only one global default authenticator, this doesn't really work well when you have multiple users doing the URLFetch in multiple threads. I would use Apache HttpClient if that's the case.
EDIT: I was wrong. App Engine doesn't allow Authenticator. Even if it's allowed, we would have the multi-thread issue with a global authenticator instance. Even though you can't create threads, your requests may still get served in different threads. So we just add the header manually using this function,
import com.google.appengine.repackaged.com.google.common.util.Base64;
/**
* Preemptively set the Authorization header to use Basic Auth.
* #param connection The HTTP connection
* #param username Username
* #param password Password
*/
public static void setBasicAuth(HttpURLConnection connection,
String username, String password) {
StringBuilder buf = new StringBuilder(username);
buf.append(':');
buf.append(password);
byte[] bytes = null;
try {
bytes = buf.toString().getBytes("ISO-8859-1");
} catch (java.io.UnsupportedEncodingException uee) {
assert false;
}
String header = "Basic " + Base64.encode(bytes);
connection.setRequestProperty("Authorization", header);
}
Using HttpURLConnection gave me some problems (for some reason the server I was trying to connect to didn't accept auth credentials), and finally I realized that it's actually much easier to do using GAE's low-level URLFetch API (com.google.appengine.api.urlfetch) like so:
URL fetchurl = new URL(url);
String nameAndPassword = credentials.get("name")+":"+credentials.get("password");
String authorizationString = "Basic " + Base64.encode(nameAndPassword.getBytes());
HTTPRequest request = new HTTPRequest(fetchurl);
request.addHeader(new HTTPHeader("Authorization", authorizationString));
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);
System.out.println(new String(response.getContent()));
This worked.
There is a wrapper on Apache HttpClient for App Engine
please go through the post http://esxx.blogspot.com/2009/06/using-apaches-httpclient-on-google-app.html
http://peterkenji.blogspot.com/2009/08/using-apache-httpclient-4-with-google.html
Note on the first answer: setRequestProperty should get the property name without the colon ("Authorization" rather than "Authorization:").

Categories