I'm developing a web service that consumes another one. To authenticate with this other service, I have to use the SAML V2 protocol. How to programmatically consume this service in Java ?
My code without SSO:
HttpClient client = builder.build();
URIBuilder uriBuilder = new URIBuilder();
uriBuilder.setScheme(test.getScheme());
uriBuilder.setHost(test.getHost());
uriBuilder.setPort(test.getPort());
uriBuilder.setPath("Path");
uriBuilder.addParameter("id","theID");
uriBuilder.addParameter("param", "param");
try {
HttpUriRequest request = new HttpGet(uriBuilder.build());
HttpResponse response = client.execute(request);
return EntityUtils.toString(response.getEntity());
} catch (IOException | URISyntaxException e) {
e.printStackTrace();
}
You'll need to build a SAML response that meets the requirements of the target service and include it in the call. Your best option is OpenSAML or another "product" such as CXF that builds on top of it. See How to create a valid SAML 2.0 Assertion with OpenSAML library in Java for an OpenSAML example; CXF ships with good docs and examples.
Related
I am working in a project where a request(ISO 8583) need to be send via JPOS server to the backed (Remote Host as per official doc) via SOAP api.
We have implemented our system as follows:
We implemented a ISOListner in a middle ware(spring boot project) where it converts the incoming ISO message to SOAP request.
Is it possible to embed the Middle ware code to JPOS server itself and omit the mw?
If possible , what is the right place to put our conversion logic ?
Is it the ChannelAdaptor or TransactionManager ?
Few blogs suggest that we can put all logic to TransactionManager or ChannelAdaptor. If it is true
then why we need mux and channel at all? Or our architecture is ok to proceed further ?
For the sake of completeness I will include the answer to this question that was also asked in jPOS Users group (https://groups.google.com/forum/#!topic/jpos-users/PGzb4syQRzs):
We usually implement a custom participant doing the SOAP/REST thing.
In the case of REST, we use Apache's HTTP Client
(org.apache.httpcomponents:httpclient:4.5.5) that provides a nice
async interface that works great with the TransactionManager's PAUSE.
Here is an example:
public int prepare (long id, Serializable o) {
Context ctx = (Context) o;
String url = getURL (ctx);
HttpPost post = new HttpPost(url);
StringEntity entity = new StringEntity(ctx.getString(JSON_REQUEST.name()),ContentType.create("application/json", Consts.UTF_8));
post.setEntity(entity);
try {
client.execute(post, response -> {
int sc = response.getStatusLine().getStatusCode();
if (sc == HttpStatus.SC_CREATED || sc == HttpStatus.SC_OK)
ctx.put (JSON_RESPONSE.name(), EntityUtils.toString(response.getEntity()));
ctx.resume();
return null;
});
return PREPARED | PAUSE | NO_JOIN | READONLY;
} catch (IOException e) {
warn (e);
}
return ABORTED;
}
TransactionManager is the right place to add custom logic. I guess your are using mux and channel to send iso message to MW socket listener component. Which can be avoided by using a middleware like rabbitmq to connect to backend servers.
For example isomessage in transaction manager can be converted to json and send it to backend server using mq.
I'm writting an Android App and connect to Azure Service bus - Topic. I write code to connect to existing namespace like this tutorial
https://azure.microsoft.com/en-us/documentation/articles/service-bus-java-how-to-use-topics-subscriptions/
Configuration config = ServiceBusConfiguration.configureWithSASAuthentication(
"HowToSample",
"RootManageSharedAccessKey",
"SAS_key_value",
".servicebus.windows.net"
);
ServiceBusContract service = ServiceBusService.create(config);
But it throw an exception at ServiceBusContract service = ServiceBusService.create(config);.
It said "java.lang.RuntimeException: Service or property not registered: com.microsoft.windowsazure.services.serviceBus.ServiceBusContract
I looked up some way to fix it but not ok. So i use REST API to connect same this tutorial
REST API AZURE
It can run and sent message to Azure Service Bus - Topic. Now i want to write a method use to get message from this Topic's Subcription. Use Rest API like that
String url = "https://smarthomethesis.servicebus.windows.net/light_1/Subscriptions/LightSubscription/messages/head?timeout=60";
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
// Add header
String token = generateSasToken(new URI(uri));
get.setHeader("Authorization", token);
System.out.println("Llamando al post");
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
But it can't get message, responseString show
"<Error><Code>400</Code><Detail>The request is not supported for the supplied api-version ''. TrackingId:d7624c10-4fc9-43d6-b092-880947e3b820_G31,TimeStamp:1/10/2016 3:43:44 PM</Detail></Error>"
I don't know why it isn't supported. Can you help me. Thank you
According to your code in Azure Java SDK, the issue was caused by using incorrect namespace, sasKeyName & sasKey. In the reference doc, the namespace HowToSample & SAS key SAS_key_value were created by the author, that be different from yours.
So you need to replace them with the namespace & SAS key value of your service bus created. You can find them on Azure portal or new portal.
For the Service Bus REST API, try to add the api-version in the query string for the Peek-Lock Message API, please note the content from the reference doc https://msdn.microsoft.com/en-us/library/azure/hh780771.aspx.
Version and server overview
Following Azure guidelines, REST APIs now support versioning. By default, passing no version indicates current service behavior. Any changes in existing REST APIs require providing an api-version value as the query string.
Version “2012-03”,“2012-08”,“2013-04”,“2013-07”,“2013-08”,“2013-10”,“2014-01”,“2015-01”
I'm using Java EE technology for my web application. And I use Apache Solr for my search engine. AFAIK, after I config Solr successfully, Solr is running as a Restful service.
So, under my servlet, I try to call this service as another console application I do before. Here is a sample code is used to get json data from an url:
/** Get Data Fom URL Using GET Method */
public static String getResponseFromGetRequest(String url) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
/** after prepare for data. prepare for sending */
try {
/**
* HttpResponse is an interface just like HttpGet
* therefore we can't initialize them
*/
HttpResponse httpResponse = httpClient.execute(httpGet);
return parseHttpResponse(httpResponse);
} catch (ClientProtocolException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return null;
}
But the package org.apache.http.impl.client.DefaultHttpClient is not available (under tomcat server at least). So, I think maybe there are some problems here. That we cannot call another service in servlet, right? If my guess is true, how can I fix this problem?
A brief code on using an API available in java to interact with solr(you don't need to know or care about servlets, httpclients, nothing).
HttpSolrServer server = new HttpSolrServer("your restful url goes here");
SolrQuery query = new SolrQuery();
QueryResponse response = server.query(query);
List<MyClass> beans = response.getBeans(MyClass.class);
server should probably be a spring bean, it's the java representation (proxy object) of your running solr server.
query is a query to run against the server, configure this to specify what you want from solr.
response is the answer to the request.
beans are objects which are straight from solr itself (as far as i remember, your solr fields get mapped to the java object's fields by field name, no restrictions at all).
note that server has a lot of ways to do simple operations without anything explicit, like server.addBean(myBean);
Here is how to get Solrj in maven:
<dependency>
<groupId>org.apache.solr</groupId>
<artifactId>solr-solrj</artifactId>
<version>4.5.1</version>
</dependency>
If you don't have maven:
http://mvnrepository.com/artifact/org.apache.solr/solr-solrj/4.10.3
click on "Download ( JAR )".
I want to write a Java program to call a web service. WSDL is not available for this web service. I have written programs to call a web service which has wsdl. Here I don't have any idea of how I can proceed. Not able to find many samples in Internet as well.
Is there any better frame work which I can use? I am getting JSON output from web service.
I am looking at options of writing a best possible case(If I could write a generalized program which could be used for many web services with out much changes, it would be great)
Well there are several ways to consume rest service.
Using Spring framework:
import org.springframework.web.client.RestTemplate
RestTemplate restTemplate = new RestTemplate();
User user = restTemplate.getForObject("http://localhost:8080/users/2", User.class);
System.out.println("Username: " + user.getUsername());
Using apache httpclient:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet getRequest = new HttpGet("http://localhost:8080/users/2");
HttpResponse response = httpClient.execute(getRequest);
HttpEntity httpEntity = response.getEntity();
String userString = EntityUtils.toString(httpEntity);
// Transform 'userString' into object using for example GSON:
Gson gson = new Gson();
User user = gson.fromJson(userString, User.class);
System.out.println("Username: " + user.getUsername());
I'm developing a Java Server Aplication and an Android Aplication and my android app need to send and receive data from/to server (Bidirectional), for example my Android App need to Login to the server and the server need to know who is logged in.
Wich protocol do you recommend me to do this kind of program?
Usually in this situation you can use HTTP protocol for several reason. First of all you can reach your server even if it is behind a firewall or something like that.
Second using HTTP you can send XML or JSON data widely used in android.
The only limitation you have is the HTTP protocol is a synchronous protocol so you send and wait for the answer.
Using HTTP you can use your existing server architecture and you can wrap your business layer with a Webservices so that you can expose your services.
If you need that server can contact your app you can use you can use Google Cloud Mesaging.
Use Http request (get or post request) to communicate with a server.
You have to use a thread or an AsyncTask to perform your request or the execution fails from Api 11+.
I attach an example of http request that receives an xml:
import org.apache.http.*;
[..]
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
Log.d("XMLParser-getXmlFromUrl", "UnsupportedEncodingException");
e.printStackTrace();
} catch (ClientProtocolException e) {
Log.d("XMLParser-getXmlFromUrl", "ClientProtocolException");
e.printStackTrace();
} catch (IOException e) {
Log.d("XMLParser-getXmlFromUrl", "IOException");
e.printStackTrace();
}
// return XML
return xml;
}