Wednesday, 28 December 2016

WSO2 - ESB | FOREACH MEDIATOR


FOREACH MEDIATOR

In the previous note, we saw how we can use custom classes as Mediators.

Moving on to cover other important mediation techniques, I was going through online documentation for 'FOREACH MEDIATOR' using this link -


when I realized, the sample code provided can be made more illustrative and a bit easier.


So code buddies, here we go with our version to create a small demo, using foreach mediator.


1. Kicking off with a sequence generation -

Declaring 'main2' as our sequence to imbibe foreach mediator -

xml version -

<?xml version="1.0" encoding="UTF-8"?>
<sequence name="main2" trace="enable" xmlns="http://ws.apache.org/ns/synapse">
<in>
<foreach expression="//m0:getQuote/m0:request"
xmlns:m0="http://services.samples"
xmlns:ns="http://org.apache.synapse/xsd" xmlns:ns3="http://org.apache.synapse/xsd">
<sequence>
<payloadFactory media-type="xml">
<format>
<m0:checkPriceRequest>
<m0:code>$1</m0:code>
</m0:checkPriceRequest>
</format>
<args>
<arg evaluator="xml" expression="//m0:request/m0:symbol"/>
</args>
</payloadFactory>
</sequence>
</foreach>
<log level="full"/>
</in>
<out/>
</sequence>


2. Defining an API to use the above sequence -

Let's call it 'foreachAPI' -


XML version -

<api xmlns="http://ws.apache.org/ns/synapse" name="foreachAPI" context="/fe">
<resource methods="POST GET" inSequence="main2" outSequence="main2"/>
</api>


3. Let's also enable the debug logging, for the above API -



4. Time to hit the API.

Let's use the same XML provided in the tutorial i.e. stockQuoteReq.xml -
    <soap:Header/>
    <soap:Body>
        <m0:getQuote>
            <m0:request><m0:symbol>IBM</m0:symbol></m0:request>
            <m0:request><m0:symbol>WSO2</m0:symbol></m0:request>
            <m0:request><m0:symbol>MSFT</m0:symbol></m0:request>
        </m0:getQuote>
    </soap:Body>
</soap:Envelope>
Save it locally, and invade the directory where it is parked. Run the below curl command -

curl -d @stockQuoteReq.xml -H "Content-Type: application/soap+xml;charset=UTF-8" "http://172.16.2.34:8280/fe/foreachAPI"



5. Output obtained, all the things done using console, no need to deploy any code 😃

o/p xml -

<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:m0="http://services.samples" xmlns:xsd="http://services.samples/xsd">
<soap:Body>
<m0:getQuote>
<m0:checkPriceRequest>
<m0:code>IBM</m0:code>
</m0:checkPriceRequest>
<m0:checkPriceRequest>
<m0:code>WSO2</m0:code>
</m0:checkPriceRequest>
<m0:checkPriceRequest>
<m0:code>MSFT</m0:code>
</m0:checkPriceRequest>
</m0:getQuote>
</soap:Body>
</soap:Envelope>

Keep experimenting buddies, share your thoughts!

Tuesday, 27 December 2016

WSO2 ESB - HELLO WORLD - CLASS MEDIATION

WSO2 - ESB

 I came across this thing recently, and generally as we developers do, I did some head banging.
Assuming that theory is not what you are looking for, this post will land you in the arena directly, with working demo, following the old school tradition - a 'Hello World' program 🙂.

This will be involving ESB 5.x.x, based on the online documentation it is too easy to proceed with the installation part, Fedora 24 or any other yummy UNIX flavor.

I suggest you to install ESB bundle with Eclipse Luna from the site, since the latest version available i.e. the one with Eclipse Mars, will throw lot of NPEs in the environment.






package abc;

import org.apache.synapse.MessageContext;
import org.apache.synapse.mediators.AbstractMediator;

public class MedTester extends AbstractMediator {

    public boolean mediate(MessageContext context) {
        // TODO Implement your mediation logic here
        System.out.println("Wassup ??????? ");
        return true;
    }
}

Steps to follow ahead -


Upload the jar for the above class in wso2esb-5.x.x/repository/components/lib folder.

Start the analytics server then your core server.

Add a sequence with class mediator.

Make sure class is uploaded successfully.


Create an API for invoking your above sequence.


Hit the below url using curl command -

http://172.16.2.34:8280/helloContext/helloAPI

curl -X GET http://172.16.2.34:8280/helloContext/helloAPI/





Here you go! Enjoy the output. 🙂



Monday, 26 December 2016

Stepping into the world of Amazon Web Services

WANT TO UPLOAD/ READ A FILE INTO/ FROM YOUR AWS S3 BUCKET, HERE IS A CODE SNIPPET

For any query/ suggestion drop me a note at vats.namit@gmail.com

HAPPY CODING!

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.amazonaws.AmazonClientException;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.InstanceProfileCredentialsProvider;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
import com.google.common.io.Files;

public class S3Handler {

static AmazonS3 s3;

final static EnvironmentProperty environmentProperty = new EnvironmentProperty();
private final static Logger logger = LogManager.getLogger(S3Handler.class);

// member variables
private String s3BucketName;
private File uploadFile;
private String fileName;

// Constructor for handling upload
public S3Handler(String bucketName, File file) throws Exception {
init();
setS3BucketName(bucketName);
setUploadFile(file);
setFileName(file.getName());
}

// Constructor for handling retrieval
public S3Handler(String bucketName, String fileName) throws Exception {
init();
setS3BucketName(bucketName);
setFileName(fileName);
}

// Initialize
private static void init() throws Exception {
String credentialFile = "";
   if(SystemProperty.getenv().containsKey(environmentProperty.getProperty("environment.credential.file.keyword"))) {
    credentialFile = SystemProperty.getenv(environmentProperty.getProperty("environment.credential.file.keyword"));
   }
if (credentialFile.equals(null) || credentialFile.isEmpty() || credentialFile.equals("")) {
credentialFile = "FileNotExist";
}
AWSCredentials credentials = null;
AWSCredentialsProvider credentialsProvider;
File file = new File(credentialFile);
ClientConfiguration clientConfig = new ClientConfiguration();
clientConfig.setProtocol(Protocol.HTTP);
clientConfig.setConnectionTimeout(0);
   clientConfig.setSocketTimeout(0);
if (file.exists()) {
credentialsProvider = new ProfileCredentialsProvider(credentialFile, "default");
try {
credentials = credentialsProvider.getCredentials();
} catch (Exception e) {
throw new AmazonClientException("Cannot load the credentials from the credential profiles file. "
+ "Please make sure that your credentials file is at the correct " + "location ("
+ credentialFile + "), and is in valid format.", e);
}
s3 = new AmazonS3Client(credentials, clientConfig);
} else {
credentialsProvider = new InstanceProfileCredentialsProvider();
credentials = credentialsProvider.getCredentials();
s3 = new AmazonS3Client(credentials, clientConfig);
}

String regionName = environmentProperty.getProperty("environment.region.name");
Region region = Region.getRegion(Regions.fromName(regionName));
s3.setRegion(region);
logger.info("S3 Client has been created...");
logger.info("Region is " + region.getName());

}

// setters-getters
public String getS3BucketName() {
return s3BucketName;
}

public void setS3BucketName(String s3BucketName) {
this.s3BucketName = s3BucketName;
}

public File getUploadFile() {
return uploadFile;
}

public void setUploadFile(File upFile) {
this.uploadFile = upFile;
}

public String getFileName() {
return fileName;
}

public void setFileName(String fileName) {
this.fileName = fileName;
}

// methods
/**
* method for uploading file to S3 uses the attributes set while invoking
* respective constructor
*/
public void uploadToS3() {

PutObjectRequest putObjectRequest = new PutObjectRequest(getS3BucketName(), getFileName(), getUploadFile())
.withSdkClientExecutionTimeout(Integer.valueOf(environmentProperty.getProperty("s3.clientExecution.Timeout")));
s3.putObject(putObjectRequest.withCannedAcl(CannedAccessControlList.Private));
logger.info("Upload to S3 bucket - " + getS3BucketName() + " over!");

}

/**
* method for retrieving file from S3 uses the attributes set while invoking
* respective constructor
* @return json String
*/
public String retrieveS3File() {

S3Object s3object = s3.getObject(new GetObjectRequest(getS3BucketName(), getFileName()));
logger.info("Content Type  : " + s3object.getObjectMetadata().getContentType());
logger.info("Content Length: " + s3object.getObjectMetadata().getContentLength());

BufferedReader reader = new BufferedReader(new InputStreamReader(s3object.getObjectContent()));
String line;
StringBuilder output = new StringBuilder();
try {
while ((line = reader.readLine()) != null) {
output.append(line + "\r\n");
}
} catch (IOException e) {
e.printStackTrace();
}
logger.info("Retrieval from S3 bucket - " + getS3BucketName() + " over!");
return output.toString();
}

/**
* Utility to create file, can be used without having s3 client
* @param fileName
* @param sb
* @return File
* @throws IOException
*/
public static File createUploadFile(String fileName, StringBuilder sb) throws IOException {

File file = new File(Files.createTempDir(), fileName + ".txt");
file.deleteOnExit();

Writer writer = new OutputStreamWriter(new FileOutputStream(file));

if (null != sb && !sb.toString().isEmpty()) {
writer.write(sb.toString());
}
writer.close();

return file;

}

}

Featured post

JAVA based project, that can be used to hit DB using JDBC, from WSO2 ESB

Hi Buddies, Here is a small project that will enable you to hit MySQL DB using WSO2 ESB - https://github.com/namitsharma99/customM...