import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by jasintha on 8/4/16.
*/
public class RestClient {
public static void main(String[] args) {
try {
URL url = new URL("http://localhost:8080/RESTfulExample/json/product/post");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
String input = "{\"qty\":100,\"name\":\"iPad 4\"}";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
My Notes
Monday, August 15, 2016
JAVA REST Client
Convert SMAL response to JWT
Here I have used opensaml and WSO2 rg.wso2.carbon.identity.sso.saml.util.SAMLSSOUtil clazz to process this request
package org.wso2.is.jwt.inbound.authenticator.servlets;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.velocity.runtime.directive.Foreach;
import org.opensaml.saml2.core.Assertion;
import org.opensaml.saml2.core.Attribute;
import org.opensaml.saml2.core.AttributeStatement;
import org.opensaml.xml.XMLObject;
import org.w3c.dom.Element;
import org.wso2.carbon.identity.sso.agent.bean.LoggedInSessionBean;
import org.wso2.carbon.identity.sso.saml.util.SAMLSSOUtil;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import javax.xml.bind.DatatypeConverter;
import org.opensaml.saml2.core.Response;
import org.wso2.is.jwt.inbound.authenticator.util.Constants;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JWTServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
String[] samlResponses = request.getParameterMap().get(Constants.SAML_RESPONSE);
if(samlResponses!=null){
try {
LoggedInSessionBean sessionBean = new LoggedInSessionBean();
sessionBean.setSAML2SSO(sessionBean.new SAML2SSO());
String saml2ResponseString = SAMLSSOUtil.decodeForPost(samlResponses[0]);
Response saml2Response = (Response) SAMLSSOUtil.unmarshall(saml2ResponseString);
sessionBean.getSAML2SSO().setResponseString(saml2ResponseString);
sessionBean.getSAML2SSO().setSAMLResponse(saml2Response);
List<Assertion> assertions = saml2Response.getAssertions();
Assertion assertion = null;
String subject = null;
if (assertions != null && !assertions.isEmpty()) {
assertion = assertions.get(0);
}
if (assertion.getSubject() != null && assertion.getSubject().getNameID() != null) {
subject = assertion.getSubject().getNameID().getValue();
}
final Map<String, Object> attributeMap = getAssertionStatements(assertion);
String idPEntityIdValue = assertion.getIssuer().getValue();
String url = assertion.getConditions().getAudienceRestrictions().get(0).getAudiences().get(0).getAudienceURI();
String id = saml2Response.getID();
String jwtString = createJWT(id, idPEntityIdValue, subject,attributeMap,1000*60*3);
response.sendRedirect(url+ Constants.QUERY_PARAM +jwtString);
}catch (Exception e){
/*ignore*/
}
}
}
private Map<String, Object> getAssertionStatements(Assertion assertion) {
Map<String, Object> results = new HashMap<String, Object>();
if (assertion != null && assertion.getAttributeStatements() != null) {
List<AttributeStatement> attributeStatementList = assertion.getAttributeStatements();
for (AttributeStatement statement : attributeStatementList) {
List<Attribute> attributesList = statement.getAttributes();
for (Attribute attribute : attributesList) {
Element value = attribute.getAttributeValues().get(0).getDOM();
Object attributeValue = value.getTextContent();
results.put(attribute.getName(), attributeValue);
}
}
}
return results;
}
private String createJWT(String id, String issuer, String subject,Map<String,Object> claims,int ttlMillis) {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(Constants.KEY_SCRET);
Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
JwtBuilder builder = Jwts.builder().setId(id)
.setIssuedAt(now)
.setSubject(subject)
.setIssuer(issuer)
.signWith(signatureAlgorithm, signingKey);
builder.setClaims(claims);
if (ttlMillis >= 0) {
long expMillis = nowMillis + ttlMillis;
Date exp = new Date(expMillis);
builder.setExpiration(exp);
}
return builder.compact();
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
Create & Processing JWT in JAVA
I am using JJWT library to process the JWT
package org.wso2.is.jwt.inbound.authaticator;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.wso2.is.jwt.inbound.authenticator.util.Constants;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpSession;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class JWTRespondMessagTest {
public static void main(String[] args) {
try {
JWTRespondMessagTest messagTest = new JWTRespondMessagTest();
Map<String, Object> results = new HashMap<String, Object>();
results.put("org.wso2.is/mobile", "0711368118");
String jwtString = messagTest.createJWT("id","idp","jasinth@wso2",results,1000*60*5);
messagTest.readJWT(jwtString);
}catch (Exception e){
}
}
private String createJWT(String id, String issuer, String subject,Map<String,Object> claims,int ttlMillis) {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary("wso2carbon");
Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
//Let's set the JWT Claims
JwtBuilder builder = Jwts.builder().setId(id)
.setIssuedAt(now)
.setSubject(subject)
.setIssuer(issuer)
.signWith(signatureAlgorithm, signingKey);
builder.setClaims(claims);
if (ttlMillis >= 0) {
long expMillis = nowMillis + ttlMillis;
Date exp = new Date(expMillis);
builder.setExpiration(exp);
}
return builder.compact();
}
public void readJWT(String jwt){
String claimedId = "Annonimus";
String subjectId = "Annonimus";
if (jwt == null) {
} else {
try{
Claims claims = Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary("wso2carbon")).parseClaimsJws(jwt).getBody();
if(claims!=null){
subjectId = claims.getSubject();
String val =(String) claims.get("org.wso2.is/mobile");
System.out.println(val);
System.out.println(subjectId);
}
}catch (Exception e){
e.printStackTrace();
}
}
}
}
Monday, May 9, 2016
Create Dynamic extension point in Eclipse plugins
private void createDynamicExtension(){ try{ Bundle bundle = plugin.getBundle(); InputStream inputStream = bundle.getEntry("extention.xml").openStream(); String bundleIdStr = ""+bundle.getBundleId();//Get bundle ID as a String IContributor contributor = new RegistryContributor(bundleIdStr, bundle.getSymbolicName(), null, null); ExtensionRegistry extensionRegistry = (ExtensionRegistry) Platform.getExtensionRegistry(); Field declaredField = ExtensionRegistry.class.getDeclaredField("masterToken"); declaredField.setAccessible(true); Object masterToken = declaredField.get(extensionRegistry); boolean addContribution = extensionRegistry.addContribution(inputStream, contributor, false, bundle.getSymbolicName(), null, masterToken);
System.out.println(addContribution);
}catch(Exception ex){ ex.printStackTrace(); } }
Here I have provided the extension content inside the "
extention.xml" file.
Thursday, March 17, 2016
WebTec4GE (Developing next generation Graphical Editors in Eclipse IDE)
While the support extended by eclipse graphical framework is rich, development of a fine tuned
graphical editor, competing with applications developed using HTML5 and javascript support
using this framework is strenuous. Further the framework requires a secluded knowledge base
which is specific to eclipse domain Hence, building a rich graphical editor in eclipse requires a
lot of effort which is a major drawback for rich graphical editor development in eclipse plugins.
What is WebTec4GE ?
This framework was designed with the goal of providing access to ubiquitous knowledge in UI and graphical editor design into eclipse editors, the ubiquitous knowledge base being web technologies for UI design. Web technologies are evolving at a rapid phase giving developers simplistic solutions to generate most complex UIs.
Architecture overview of WebTec4GE
The core of this framework is the interface that provides access to Eclipse IDE eventing. The
web based application running on top of the browser widget, which is embedded to the eclipse
editor will have access to all eclipse ide events via a REST eventing module written to bridge
the two domains.
Using the JS interface web editors can send and receive various editor events. At the page load, javascript components of the interface are injected to each web editor using which they can interact with IDE and act as a plain-old Eclipse Editor. It contains methods to interact with workspace. It is the main communication channel for interacting with Eclipse workbench.Capture the all the IDE events notify to the Web Editor such as Menu event (save , copy, cut, undo, redo etc..and Key bindings
By default SWT uses default Web Rendering Engine available on each platform (WebKit, XULRunner or IE) ,Since this creates an inconsistency when using the same editor in different platforms.This module will package XULRunner engine for each platform within the WebTec4GE framework itself and makes rendering of the editor pages will be unique across the platforms.
Saturday, September 26, 2015
How to restart eclipse programmatically
If you want to restart eclipse programmatically then you have restart the eclipse workbench . You can use following code snippets
String message = "You must restart eclipse to apply these changes, Restart Now ?";
if(MessageDialog.openQuestion(Display.getCurrent().getActiveShell(),"Developer Studio Info", message)){
PlatformUI.getWorkbench().restart();
}
Sunday, August 17, 2014
How to use "Uri-template" with WSO2 API Manager
In this post I am going to develop a small use case which has used the "Uri-template " to find the correct resources
Pre-requires
WSO2 Developer studio - (version 3.5.0 or later)
WSO2 API Manager - (version 1.5.0 or later)
WSO2 Application server - (version 5.2.0 or later)
Contents
result will be
Create & Publish the API
Start the WSO2 API Manager and login to the publisher portal. Create the API by entering the following details
Pre-requires
WSO2 Developer studio - (version 3.5.0 or later)
WSO2 API Manager - (version 1.5.0 or later)
WSO2 Application server - (version 5.2.0 or later)
Contents
- Create a sample production service called Temperature-Reporter(TR).
- Host the TR service in the Application server.
- Create & Publish the API for TR service
- Subscribe to the API
- Invoke the TR service via API (using curl ).
Create sample production service called Temperature-Reporter(TR).
Start the Developer Studio and go the dashboard. Create a JAX-RS service called TR ,this will the our production service , this a REST service. This service provides the average temperature of major cities in the world during the major seasons. As a example NYC average temperature in the march is 4.5 in Celsius. likewise users will be able to check the avg temp by providing the city name. This is service class for the TR production service
1: package com.blogspot.jasyz.tr.service;
2: import javax.ws.rs.*;
3: import javax.ws.rs.core.Response;
4: import javax.ws.rs.core.MediaType;
5: @Path("/temp")
6: public class TemperatureReporter {
7: @GET
8: @Path("{type}")
9: @Produces(MediaType.TEXT_PLAIN)
10: public Response getTempature(@PathParam("type") String type,
11: @QueryParam("city") String city,
12: @QueryParam("month") String month){
13: double temp=0.0;
14: if("NYC".equals(city)){
15: if("jan".equals(month)){
16: if("cel".equals(type)){
17: temp = (4.0-3.0)/2.0;
18: }else{
19: temp =(39.0+26.0)/2.0;
20: }
21: }else if("feb".equals(month)){
22: if("cel".equals(type)){
23: temp = (5.0-3.0)/2.0;
24: }else{
25: temp =(40.0+27.0)/2.0;
26: }
27: }else if("mar".equals(month)){
28: if("cel".equals(type)){
29: temp = (8.0-1.0)/2.0;
30: }else{
31: temp =(48.0+34.0)/2.0;
32: }
33: }
34: // Continue the logic
35: }else{
36: return Response.status(200).entity("Sorry, Currently Information not avilable").build();
37: }
38: return Response.status(200).entity("tempareture of the "+city+" is "+temp+" in "+type).build();
39: }
40: }
Now , right click on the project and export the project then war file[1] will be created.
Host the TR service in the Application server
Start WSO2 Application Server , select the add jax RS/jax WS menu from the left side bar. Then upload the previously created war file. Then if you check the server console you will see the following message in the server console.
Try out the Raw TR service
Before create the API lets try out the TR service directly , I am going to try out this service using curl , Open the terminal and paste the following command.(Curl is already installed)
curl -v "http://10.100.1.102:9764/TR_1.0.0/services/temperature_reporter/temp/cel?month=Jan&city=NYC"
result will be
temperature of the NYC is 0.5 in cel
Create & Publish the API
Start the WSO2 API Manager and login to the publisher portal. Create the API by entering the following details
Downloads
[1] - TR Production Service war file
[1] - TR Production Service war file
Subscribe to:
Posts (Atom)