Tuesday 16 August 2016

Soap web service client

Soap web service client

Generic client for soap web service!. This client can be used for any soap web service. You have to pass only service endpoint "url" and soap request envelop!.

Here you go!

package com.vimal.activator;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;

public class WebClient {
public static String executeWsdl(String wsdlUrl, String soapEnvelop) {
String outputString = "";

try {
soapEnvelop = URLDecoder.decode(soapEnvelop, "Utf-8");
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buffer = new byte[soapEnvelop.length()];
buffer = soapEnvelop.getBytes();
bout.write(buffer);
byte[] b = bout.toByteArray();

URL url = new URL(wsdlUrl);
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;
httpConn.setRequestProperty("Content-Length",
String.valueOf(b.length));
httpConn.setRequestProperty("Content-Type",
"text/xml; charset=utf-8");
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
OutputStream out = httpConn.getOutputStream();
out.write(b);
out.close();

// Response
InputStreamReader isr = new InputStreamReader(
httpConn.getInputStream());
BufferedReader rd = new BufferedReader(isr);

String line;
while ((line = rd.readLine()) != null)
outputString = outputString + line;

} catch (Exception e) {
e.printStackTrace();
}
return outputString;
}

private static String sampleRequestBody(String token, String serviceName) {
String xml = "<Envelope xmlns=\"http://schemas.xmlsoap.org/soap/envelope/\">"
+ "<Body>"
+ "<executeQuery xmlns=\"http://webservice.required.vimal.com\">"
+ "<filter xmlns=\"\"/>"
+ "<AuthToken xmlns=\"\">"
+ token
+ "</AuthToken>"
+ "<key xmlns=\"\">"
+ "<serviceName>"
+ serviceName
+ "</serviceName>"
+ "<dataType>JSON</dataType>"
+ "<Limit>[string?]</Limit>"
+ "<caseSensitive>true</caseSensitive>"
+ "</key>"
+ "</executeQuery>" + "</Body>" + "</Envelope>";
return xml;
}
public static void main(String[] args) throws Exception {
String xml = executeWsdl(
"http://localhost:8080/SoapWebService/Soap1",sampleRequestBody("token","servicename"));
System.out.println(xml);
}
}

Saturday 6 August 2016

Java Program to generate Triangle (Fibonacci)

Java Program to generate Triangle (Fibonacci)

Here you go with sample program!

public class Sample {

public static void main(String[] args) {
int a = 0, b = 1, i, c, n = 5, j;
for (i = 1; i <= n; i++) {
a = 0;
b = 1;
System.out.print(b);
for (j = 1; j < i; j++) {
c = a + b;
System.out.print(c);
a = b;
b = c;
}
System.out.println();
}
}
}


Output:
1
11
112
1123
11235

enjoy......................

Restful web service client

Restful web service client

Here you go with sample program.

1) Create a class named "WebClients"!

package com.vimal.sample;

import javax.ws.rs.core.MediaType;

import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.cxf.transport.http.HTTPConduit;

public class WebClients {

private static WebClient client;
public static WebClients INSTANCE = new WebClients();
public WebClient create(String url) {
WebClient clientCreate = client;
WebClient client = null;
try {
if (clientCreate != null) {
client = WebClient.fromClient(clientCreate);
client.path(url);
if(client != null) {
HTTPConduit conduit = WebClient.getConfig(client).getHttpConduit();
       conduit.getClient().setReceiveTimeout(100000000);
       conduit.getClient().setConnectionTimeout(100000000);
}
client.async();
client.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON);
}
} catch (Exception e) {
System.out.println("Webclient create method : " + e.getMessage());
}
return client;
}


static {
WebClient wclient = null;
try {
wclient = WebClient.create(UrlUtil.URL, true);
HTTPConduit conduit = WebClient.getConfig(wclient).getHttpConduit();
       conduit.getClient().setReceiveTimeout(12000000);
       conduit.getClient().setConnectionTimeout(12000000);
wclient.async();
wclient.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON);
} catch (Exception e) {
System.out.println("Webclients " + e.getMessage());
} finally {
setClient(wclient);
}
}

public static WebClient getClient() {
return client;
}

public static void setClient(WebClient client) {
WebClients.client = client;
}

}

2) How to use

String url = "sample url";
WebClient client = WebClients.INSTANCE.create(url);
Vimal resp = new Vimal();
resp = client.post(req, Vimal.class);
if(client != null) {
client.close();
}


enjoy........................

Friday 5 August 2016

Karaf monitoring using Java

Karaf monitoring using Java

Here you go with sample program!

package com.sample.factory;

import java.lang.management.ClassLoadingMXBean;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.OperatingSystemMXBean;
import java.lang.management.RuntimeMXBean;
import java.lang.management.ThreadMXBean;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;

import org.apache.karaf.bundle.core.BundleInfo;
import org.apache.karaf.bundle.core.BundleService;
import org.apache.karaf.bundle.core.BundleState;
import org.apache.karaf.shell.commands.InfoProvider;
import org.apache.karaf.shell.commands.Option;
import org.apache.karaf.shell.table.Row;
import org.apache.karaf.shell.table.ShellTable;
import org.fusesource.jansi.Ansi;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.startlevel.FrameworkStartLevel;

import com.owlike.genson.convert.DefaultConverters.PrimitiveConverterFactory.booleanConverter;
/**
 * 
 * @author vimal.m@bdbizviz.com
 *
 */
public class NodeInfoAction {
private NumberFormat fmtI = new DecimalFormat("###,###", new DecimalFormatSymbols(Locale.ENGLISH));
    private NumberFormat fmtD = new DecimalFormat("###,##0.000", new DecimalFormatSymbols(Locale.ENGLISH));

    private List<InfoProvider> infoProviders = new LinkedList<InfoProvider>();
    int bundleLevelThreshold = -1;
    boolean dontShowName;
    boolean showLoc;
    boolean showSymbolic;
    boolean showUpdate;
    boolean showRevisions;
    boolean noFormat;
    
    private static BundleContext bundleContext;
    private BundleService bundleService;

    
public NodeInfoAction() {
}

public NodeInfoAction(int bundleLevelThreshold, boolean dontShowName,
boolean showLoc, boolean showSymbolic, boolean showUpdate,
boolean showRevisions, boolean noFormat) {
this.bundleLevelThreshold = bundleLevelThreshold;
this.dontShowName = dontShowName;
this.showLoc = showLoc;
this.showSymbolic = showSymbolic;
this.showUpdate = showUpdate;
this.showRevisions = showRevisions;
this.noFormat = noFormat;
}

public NodeInfoAction(BundleContext context) {
bundleContext = context;
}
private BundleContext getBundleContext() {
return bundleContext;
}
public void setBundleService(BundleService bundleService) {
this.bundleService = bundleService;
}

public void init() {
try {
doExecute();
} catch (Exception e) {
e.printStackTrace();
}
}

protected Object doExecute() throws Exception {
        int maxNameLen = 25;
        RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
        OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
        ThreadMXBean threads = ManagementFactory.getThreadMXBean();
        MemoryMXBean mem = ManagementFactory.getMemoryMXBean();
        ClassLoadingMXBean cl = ManagementFactory.getClassLoadingMXBean();
      
        // print Karaf informations //
        System.out.println("Karaf");
        printValue("Karaf name", maxNameLen, System.getProperty("karaf.name"));
        printValue("Karaf version", maxNameLen, System.getProperty("karaf.version"));
        printValue("Karaf home", maxNameLen, System.getProperty("karaf.home"));
        printValue("Karaf base", maxNameLen, System.getProperty("karaf.base"));
        printValue("Karaf etc", maxNameLen, System.getProperty("karaf.etc"));
        printValue("OSGi Framework", maxNameLen, bundleContext.getBundle(0).getSymbolicName() + " - " +
                bundleContext.getBundle(0).getVersion());
        System.out.println();

        System.out.println("JVM");
        printValue("Java Virtual Machine", maxNameLen, runtime.getVmName() + " version " + runtime.getVmVersion());
        printValue("Version", maxNameLen, System.getProperty("java.version"));
        printValue("Vendor", maxNameLen, runtime.getVmVendor());
        printValue("Pid", maxNameLen, getPid());
        printValue("Uptime", maxNameLen, printDuration(runtime.getUptime()));
        try {
            printValue("Container CPU load", maxNameLen, String.valueOf(getInt(((getSunOsValueAsDouble(os, "getProcessCpuLoad") * 1000) / 10.0))+"%"));
            printValue("System CPU load", maxNameLen, String.valueOf(getInt(((getSunOsValueAsDouble(os, "getSystemCpuLoad") * 1000) / 10.0))+"%"));
        } catch (Exception t) {
        t.printStackTrace();
        }
        printValue("Total compile time", maxNameLen, printDuration(ManagementFactory.getCompilationMXBean().getTotalCompilationTime()));

        System.out.println("Threads");
        printValue("Live threads", maxNameLen, Integer.toString(threads.getThreadCount()));
        printValue("Daemon threads", maxNameLen, Integer.toString(threads.getDaemonThreadCount()));
        printValue("Peak", maxNameLen, Integer.toString(threads.getPeakThreadCount()));
        printValue("Total started", maxNameLen, Long.toString(threads.getTotalStartedThreadCount()));

        System.out.println("Memory");
        printValue("Current heap size", maxNameLen, printSizeInKb(mem.getHeapMemoryUsage().getUsed()));
        printValue("Maximum heap size", maxNameLen, printSizeInKb(mem.getHeapMemoryUsage().getMax()));
        printValue("Committed heap size", maxNameLen, printSizeInKb(mem.getHeapMemoryUsage().getCommitted()));
        printValue("Pending objects", maxNameLen, Integer.toString(mem.getObjectPendingFinalizationCount()));
        for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {
            String val = "Name = '" + gc.getName() + "', Collections = " + gc.getCollectionCount() + ", Time = " + printDuration(gc.getCollectionTime());
            printValue("Garbage collector", maxNameLen, val);
        }

        System.out.println("Classes");
        printValue("Current classes loaded", maxNameLen, printLong(cl.getLoadedClassCount()));
        printValue("Total classes loaded", maxNameLen, printLong(cl.getTotalLoadedClassCount()));
        printValue("Total classes unloaded", maxNameLen, printLong(cl.getUnloadedClassCount()));

        System.out.println("Operating system");
        printValue("Name", maxNameLen, os.getName() + " version " + os.getVersion());
        printValue("Architecture", maxNameLen, os.getArch());
        printValue("Processors", maxNameLen, Integer.toString(os.getAvailableProcessors()));
        try {
            printValue("Total physical memory", maxNameLen, printSizeInKb(getSunOsValueAsLong(os, "getTotalPhysicalMemorySize")));
            printValue("Free physical memory", maxNameLen, printSizeInKb(getSunOsValueAsLong(os, "getFreePhysicalMemorySize")));
            printValue("Committed virtual memory", maxNameLen, printSizeInKb(getSunOsValueAsLong(os, "getCommittedVirtualMemorySize")));
            printValue("Total swap space", maxNameLen, printSizeInKb(getSunOsValueAsLong(os, "getTotalSwapSpaceSize")));
            printValue("Free swap space", maxNameLen, printSizeInKb(getSunOsValueAsLong(os, "getFreeSwapSpaceSize")));
        } catch (Exception t) {
        t.printStackTrace();
        }

        //Display Information from external information providers.
        Map<String, Map<Object, Object>> properties = new HashMap<String, Map<Object, Object>>();
        if (infoProviders != null) {

            for (InfoProvider provider : infoProviders) {
                if (!properties.containsKey(provider.getName())) {
                    properties.put(provider.getName(), new Properties());
                }
                properties.get(provider.getName()).putAll(provider.getProperties());
            }

            List<String> sections = new ArrayList<String>(properties.keySet());
            Collections.sort(sections);
            for (String section : sections) {
                List<Object> keys = new ArrayList<Object>(properties.get(section).keySet());
                if (keys.size() > 0) {
                    System.out.println(section);

                    Collections.sort(keys, new Comparator<Object>() {
                        public int compare(Object o1, Object o2) {
                            return String.valueOf(o1).compareTo(String.valueOf(o2));
                        }
                    });

                    for (Object key : keys) {
                        printValue(String.valueOf(key), maxNameLen, String.valueOf(properties.get(section).get(key)));
                    }
                }
            }
        }
        
        System.out.println("Bundle Informations");
        Bundle[] bundles = getBundleContext().getBundles();
        if (bundles == null) {
            System.out.println("There are no installed bundles.");
            return null;
        }

        determineBundleLevelThreshold();

        // Display active start level.
        FrameworkStartLevel fsl = getBundleContext().getBundle(0).adapt(FrameworkStartLevel.class);
        if (fsl != null) {
            System.out.println("START LEVEL " + fsl.getStartLevel() + " , List Threshold: " + bundleLevelThreshold);
        }

        ShellTable table = new ShellTable();
        table.column("ID").alignRight();
        table.column("State");
        table.column("Lvl").alignRight();
        table.column("Version");

        if (!dontShowName) {
            table.column("Name");
        }
        if (showLoc) {
            table.column("Location");
        }
        if (showSymbolic) {
            table.column("Symbolic name");
        }
        if (showUpdate) {
            table.column("Update location");
        }
        if (showRevisions) {
            table.column("Revisions");
        }

        for (int i = 0; i < bundles.length; i++) {
            Bundle bundle = bundles[i];
            BundleInfo info = this.bundleService.getInfo(bundle);
            if (info.getStartLevel() >= bundleLevelThreshold) {
                ArrayList<Object> rowData = new ArrayList<Object>();
                rowData.add(info.getBundleId());
                rowData.add(getStateString(info.getState()));
                rowData.add(info.getStartLevel());
                rowData.add(info.getVersion());
                if (!dontShowName) {
                    String bundleName = (info.getName() == null) ? info.getSymbolicName() : info.getName();
                    bundleName = (bundleName == null) ? info.getUpdateLocation() : bundleName;
                    String name = bundleName + printFragments(info) + printHosts(info);
                    rowData.add(name);
                }
                if (showLoc) {
                    rowData.add(info.getUpdateLocation());
                }
                if (showSymbolic) {
                    rowData.add(info.getSymbolicName() == null ? "<no symbolic name>" : info.getSymbolicName());
                }
                if (showUpdate) {
                    rowData.add(info.getUpdateLocation());
                }
                if (showRevisions) {
                    rowData.add(info.getRevisions());
                }
                Row row = table.addRow();
                row.addContent(rowData);
            }
        }
        table.print(System.out, !noFormat);

        return null;
    }
private String printHosts(BundleInfo info) {
if (info.getFragmentHosts().size() <= 0) {
return "";
}
StringBuilder builder = new StringBuilder();
builder.append(", Hosts: ");
boolean first = true;
for (Bundle host : info.getFragmentHosts()) {
builder.append((first ? "" : ", ") + host.getBundleId());
first = false;
}
return builder.toString();
}
private String printFragments(BundleInfo info) {
if (info.getFragments().size() <= 0) {
return "";
}
StringBuilder builder = new StringBuilder();
builder.append(", Fragments: ");
boolean first = true;
for (Bundle host : info.getFragments()) {
builder.append((first ? "" : ", ") + host.getBundleId());
first = false;
}
return builder.toString();
}
private String getStateString(BundleState state) {
return (state == null) ? "" : state.toString();
}
private void determineBundleLevelThreshold() {
final String sbslProp = getBundleContext().getProperty("karaf.systemBundlesStartLevel");
if (sbslProp != null) {
try {
if (bundleLevelThreshold < 0) {
bundleLevelThreshold = Integer.valueOf(sbslProp);
}
} catch (Exception ignore) {
// ignore
}
}
}
private Integer getInt(double d) {
int val = (int) d;
return val;
}
private String printLong(long i) {
        return fmtI.format(i);
    }

    private String printSizeInKb(double size) {
        return fmtI.format((long) (size / 1024)) + " kbytes";
    }
private Double getSunOsValueAsDouble(OperatingSystemMXBean os, String name) throws Exception {
        Method mth = os.getClass().getMethod(name);
        mth.setAccessible(true);
// val = (long) ((d * 1000) / 10.0);
        return (Double) mth.invoke(os);
    }
private Long getSunOsValueAsLong(OperatingSystemMXBean os, String name) throws Exception {
        Method mth = os.getClass().getMethod(name);
        mth.setAccessible(true);
        return (Long) mth.invoke(os);
    }
protected String printDuration(double uptime) {
        uptime /= 1000;
        if (uptime < 60) {
            return fmtD.format(uptime) + " seconds";
        }
        uptime /= 60;
        if (uptime < 60) {
            long minutes = (long) uptime;
            String s = fmtI.format(minutes) + (minutes > 1 ? " minutes" : " minute");
            return s;
        }
        uptime /= 60;
        if (uptime < 24) {
            long hours = (long) uptime;
            long minutes = (long) ((uptime - hours) * 60);
            String s = fmtI.format(hours) + (hours > 1 ? " hours" : " hour");
            if (minutes != 0) {
                s += " " + fmtI.format(minutes) + (minutes > 1 ? " minutes" : " minute");
            }
            return s;
        }
        uptime /= 24;
        long days = (long) uptime;
        long hours = (long) ((uptime - days) * 24);
        String s = fmtI.format(days) + (days > 1 ? " days" : " day");
        if (hours != 0) {
            s += " " + fmtI.format(hours) + (hours > 1 ? " hours" : " hour");
        }
        return s;
    }
private String getPid() {
    String name = ManagementFactory.getRuntimeMXBean().getName();
    String[] parts = name.split("@");
return parts[0];
}
void printValue(String name, int pad, String value) {
        System.out.println(Ansi.ansi().a("  ")
                .a(Ansi.Attribute.INTENSITY_BOLD).a(name).a(spaces(pad - name.length())).a(Ansi.Attribute.RESET)
                .a("   ").a(value).toString());
    }
String spaces(int nb) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < nb; i++) {
sb.append(' ');
}
return sb.toString();
}
}