Migrating from Jersey to RestEasy - resteasy

I'm working out to migrate from jersey to RestEasy service.
While migrating i'm trying to find an equivalent method in RestEasy for post method in WebResource.
WebResource.post(clazz, data); // Equivalent method of post in RestEasy
Can anybody help me on this?

jax-rs 2.0 (json) way to do this with resteasy is:
Create a client
final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
final CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
cm.setMaxTotal(200);
cm.setDefaultMaxPerRoute(20);
final ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);
final Client client = new ResteasyClientBuilder().httpEngine(engine).register(ResteasyJackson2Provider.class).build();
Create a WebTarget
final ResteasyWebTarget webtarget = (ResteasyWebTarget) client.target(serviceUrl);
Make the POST call to your endpoint
final Response response = webtarget.path("yourEndpointPath>").request().post(Entity.entity(data, MediaType.APPLICATION_JSON_TYPE));

Related

Perform OAuth authentication from WPF application

I've got an existing Web API backend that uses OAuth to authenticate a vue.js frontend call's. This is an existing one and I can't modify it.
I need to perform the authentication from a new WPF Application I wrote.
I've composed the query using the HttpClient in the form
http://backend/api/signin?grant_type=password&username=user&password=1234hola
but I receive an error regarding the grant_type. Is there a tutorial I can follow? I didn't think it was that difficult to perform the authentication, but I think I'm missing something really stupid
Thanks in advance
You should add the credentials to the header as suggested here:
var client = new HttpClient() { BaseAddress = new Uri("http://url.com") };
var request = new HttpRequestMessage(HttpMethod.Post, "/path");
var byteArray = new UTF8Encoding().GetBytes("<clientid>:<clientsecret>");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
...
var response = await client.SendAsync(request);

Azure B2C authentication without a ClientSecret

I've successfully implemented this tutorial and have a client + server working locally.
However, the front-end application that I'm building is an Angular app - this means that it isn't possible to store a client secret in it..
Relevant code:
ConfidentialClientApplication cca = new ConfidentialClientApplication(Startup.ClientId, Startup.Authority, Startup.RedirectUri, new ClientCredential(Startup.ClientSecret), userTokenCache, null);
var user = cca.Users.FirstOrDefault();
AuthenticationResult result = await cca.AcquireTokenSilentAsync(scope, user, Startup.Authority, false);
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, apiEndpoint);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
How can I set my frontend up securely to work without having a client secret, based on the tutorial mentioned?
I'm currently using this angular library .
You can achieve this by using implicit grant flow
You can seamlessly integrate into any SPA application.
Follow https://learn.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-reference-spa, this article helps you.
There is an SPA sample already available in GitHub, you can try https://github.com/Azure-Samples/active-directory-b2c-javascript-hellojs-singlepageapp
you can use oidc-client library instead hello.js in above sample, both are very similar and easy to implement.

Authenticate a Google PubSub POST request using OAuth2

I need to form a POST to publish a Google PubSub message. I can't use the client libraries because they use gRPC which is incompatible with Google App Engine. I can form the critical POST request, but I'm not sure how to authenticate it using OAuth2.
This link shows what I'm doing, but it obscures the authentication part.
https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.topics/publish
(If GAE standard environment would support gRPC this would not matter.)
JSONObject obj = new JSONObject();
JSONArray attr = new JSONArray();
obj.put("script_name","foo_script.py");
obj.put("script_args","arg1");
attr.put(obj);
JSONObject jsontop = new JSONObject();
jsontop.put("messages",attr);
URL url = new URL("https://pubsub.googleapis.com/v1/projects/{my-URL}/topics/topic_run_script:publish");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
This code comes back "401 : UNAUTHENTICATED". How do I authenticate it?
App Engine has an API to fetch an access token that you can use to when calling Google services. For documentation and an example, see https://cloud.google.com/appengine/docs/standard/java/appidentity/#asserting_identity_to_google_apis
You might also be able to use the pubsub client library on GAE Std if you switch to the Java 8 environment. This doc implies that it should work.

Call Parse.com REST services from Google App Engine

I have created a database in the Parse.com cloud. I now need to write a Servlet in my Google App Engine application to call the REST services on Parse. The REST services require
user authentication which is the Parse app id and the Javascript key.
...
URL url = new URL("https://api.parse.com/1/classes/OBJECT");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type", "application/json");
Base64 enc = new Base64();
String userpassword = "{PARSE_APP_ID}" + ":" + "javascript-key={PARSE_JS_KEY}";
String encodedAuthorization = enc.encodeBase64String(userpassword.getBytes());
connection.setRequestProperty("Authorization", "Basic " + encodedAuthorization);
connection.setRequestMethod("GET");
...
I use org.apache.commons.codec.binary.Base64 for encoding to get REST call authenticated.
The Parse.com REST API recommends using the following request format to make a HTTP call:
https://myAppID:javascript-key=myJavaScriptKey#api.parse.com/1/classes/GameScore/Ed1nuqPvcm
The problem is that I kept getting
{"error":"unauthorized"}
Is there anyone having the experience with working with calling a authenticated REST service? Thanks!
EDIT.
URL url = new URL("https://api.parse.com/1/classes/OBJECT");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("X-Parse-Application-Id", "{APP_ID}");
connection.setRequestProperty("X-Parse-REST-API-Key", "REST_ID");
connection.setRequestProperty("Content-Type", "application/json");
I still got the same error while the responseCode was "200".
Cheers,
Use the header version of authentication instead:
connection.setRequestProperty("X-Parse-Application-Id", "app id here");
connection.setRequestProperty("X-Parse-REST-API-Key", "rest key here");

Is apache commons like HttpClient library equivalent supported in Apex Code on Salesforce's Force.com Platform?

I am trying to perform an external Http REST API callout using Apex Class from within my Salesforce Development Organization.
I was wondering if there is support for an equivalent HttpClient library like that of Apache Commons' HttpClient. Is there one?
From the documentation I realize that one way of doing it would be use the System.Http class to perform the request. Refer here for :Salesforce's System Classes and System.Http.
Example:
public class HttpCalloutSample {
// Pass in the endpoint to be used using the string url
public String getContent(String url) {
// Instantiate a new http object
Http h = new Http();
// Instantiate a new HTTP request, specify the method (GET) as well as the endpoint
HttpRequest req = new HttpRequest();
req.setEndpoint(url);
req.setMethod('GET');
// Send the request, and return a response
HttpResponse res = h.send(req);
return res.getBody();
}
}
The reason I am asking this question is because I remember running across a Apex Code Snippet from a tutorial that used such an API. I cant seem to find it now.
P.S: I understand the the Apex Code is a different language and Java libraries like the HttpClient do not run on the Salesforce platform. And there may not be direct language level way to integrate them both, unless there is a Apex Code binding to the library.
The System.HTTP class and friends is the only way to make HTTP requests from ApexCode. As you say apex is not java and you can't run random java libraries in apex.

Resources