Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Wednesday, November 2, 2016

JMeter SSH Sampler

https://github.com/linkeshkanna/Jmeter.SSH.FTP.Request

Jmeter Custom Sampler to make SFTP Request
To Create SSH FTP Requests in JMeter, we need this custom Sampler. This contains two jar files. 1. jmeter-ssh-sampler-1.0.2-SNAPSHOT.jar 2. jsch-0.1.53.jar We can generate this by downloading the source and building it using Maven.
I just built it using maven and checked in the jar files here.
To install this in Jmeter, 1. Copy the jmeter-ssh-sampler-1.0.2-SNAPSHOT.jar to the "Jmeter/Lib/ext" directory. 2. Copy the "jsch-0.1.53.jar" to the "Jmeter/Lib" directory 3. Restart Jmeter.
I have also added a sample test to list of the directory contents in a Public SFTP Server.

Wednesday, June 10, 2015

Intellij IDEA for Students FREE (1 Year)

Folks,
          Jetbrains is offering Intellij IDEA Ultimate Edition for one year FREE for students with edu email address. If you are student and you got .edu email address go and download the most intelligent IDE.

                            https://www.jetbrains.com/estore/students/


Happy Coding!

Friday, April 3, 2015

XML To JSON Converter

Have the following jars in the classpath,

 commons-beanutils-1.6.1.jar
 commons-collections-3.2.jar
 commons-lang-2.1.jar
 commons-logging-1.1.jar
 ezmorph-1.0.4.jar
 json-lib-2.3-jdk15.jar
 xom-1.0.jar

import net.sf.json.JSON;
import net.sf.json.xml.XMLSerializer;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class XML2JSONConverter {
    public String convertXMLTOJSON(String inputXML) {
        String jsonString = "";
        try {
            JSON objJson = new XMLSerializer().read(inputXML);
            jsonString = objJson.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonString;
    }

    static String convertStreamToString(java.io.InputStream is) {
        java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
        return s.hasNext() ? s.next() : "";
    }

    public static void main(String[] args) throws Exception {
        File inputFile = new File("input xml file path");
        InputStream inputStreams = new FileInputStream(inputFile);
        XML2JSONConverter toJASON = new XML2JSONConverter();
        System.out.println("JASON Object:" + toJASON.convertXMLTOJSON(convertStreamToString(inputStreams)));
    }
}

Java InputStream to String Covertion

Found this small method to convert InputStream to String, This will help to avoid using Apache IOUtils etc.,

 static String convertStreamToString(java.io.InputStream is) {
        java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
        return s.hasNext() ? s.next() : "";
    }


Friday, September 12, 2014

java.lang.Out OfMemoryError

Unveiling the java.lang.Out OfMemoryError
— When we encounter a java.lang.OutOfMemoryError, we often find that Java heap dumps, along with other artifacts, are generated by the Java Virtual Machine. If you feel like jumping right into a Java heap dump when you get a java.lang.OutOfMemoryError, don’t worry, it’s a normal thought. You may be able to discover something serendipitously, but it’s not always the best idea to analyze Java heap dumps, depending on the situation you are facing. We first need to investigate the root cause of the java.lang.OutOfMemoryError.


http://java.sys-con.com/node/1229281

Tuesday, September 11, 2012

Offset for given Time Zone

import java.util.TimeZone;

public String getTimeZoneOffSet(String timeZoneID) {
        TimeZone tz = TimeZone.getTimeZone(timeZoneID);
        int rawOffset = tz.getRawOffset();
        int hour = rawOffset / (60 * 60 * 1000);
        int minute = Math.abs(rawOffset / (60 * 1000)) % 60;
        return hour + ":" + minute;
    }

Test:
 tc.getTimeZoneOffSet("America/New_York")); This returns Offset for NY -->-5:0

Using Calendar Class

import java.util.Calendar;

public int getOffsetForTimeZone(String timeZoneId) {
        int a;
        Calendar calendar = new GregorianCalendar();
        TimeZone timeZ = calendar.getTimeZone();
        timeZ = timeZ.getTimeZone(timeZoneId);
        a = (int) ((timeZ.getRawOffset()) * (2.77777778 / 10000000));
        return a;
    }


Friday, April 20, 2012

opencsv - Flat File Parser

I was looking for a open source flat file parser in java and found opencsv http://opencsv.sourceforge.net/. A very clean and easy to use java utility. Would recommend this for any one who looking for flat file parser.

Tuesday, January 25, 2011

Tomcat Clustering

Open Source Load Balancing Softwares

Nice post about LB softwares and I found this on a good blog http://linuxpoison.blogspot.com/

 Linux Virtual Server

The Linux Virtual Server Project is a project to cluster many real servers together into a highly available, high-performance virtual server. The LVS load balancer handles connections from clients and passes them on the the real servers (so-called Layer 4 switching) and can virtualize almost any TCP or UDP service, like HTTP, HTTPS, NNTP, FTP, DNS, ssh, POP3, IMAP4, SMTP, etc. It is fully transparent to the client accessing the virtual service.
Homepage:
http://www.LinuxVirtualServer.org/

BalanceNG

BalanceNG is a modern software IP load balancing solution. It is small, fast, and easy to use and setup. It offers session persistence, different distribution methods (Round Robin, Random, Weighted Random, Least Session, Least Bandwidth, Hash, Agent, and Randomized Agent) and a customizable UDP health check agent in source code. It supports VRRP to set up high availability configurations on multiple nodes. It supports SNMP, integrating the BALANCENG-MIB with Net-SNMPD. It implements a very fast in-memory IP-to-location database, allowing powerful location-based server load-balancing.
Homepage:http://www.inlab.de/balanceng/

HAproxy 

HAproxy is a high-performance and highly-robust TCP and HTTP load balancer which provides cookie-based persistence, content-based switching, advanced traffic regulation with surge protection, automatic failover, run-time regex-based header control, Web-based reporting, advanced logging to help trouble-shooting buggy applications and/or networks, and a few other features. Its own event-driven state machine achieves 20,000 hits per second and surpasses GigaEthernet on modern hardware, even with tens of thousands of simultaneous connections.
Homepage:
http://haproxy.1wt.eu/

Pen

Pen is a load balancer for "simple" TCP-based protocols such as HTTP or SMTP. It allows several servers to appear as one to the outside. It automatically detects servers that are down and distributes clients among the available servers. This gives high availability and scalable performance.
Homepage:
http://siag.nu/pen/

Crossroads Load Balancer

Crossroads is a daemon running in user space, and features extensive configurability, polling of back ends using wake up calls, status reporting, many algorithms to select the 'right' back end for a request (and user-defined algorithms for very special cases), and much more. Crossroads is service-independent: it is usable for any TCP service, such as HTTP(S), SSH, SMTP, and database connections. In the case of HTTP balancing, Crossroads can provide session stickiness for back end processes that need sessions, but aren't session-aware of other back ends. Crossroads can be run as a stand-alone daemon or via inetd.
Homepage:
http://crossroads.e-tunity.com/

Balance

Balance is a simple but powerful generic TCP proxy with round-robin load balancing and failover mechanisms. Its behavior can be controlled at runtime using a simple command line syntax. Balance supports IPv6 on the listening side, which makes it a very useful tool for IPv6 migration of IPv4 only services and servers.
Homepage:
http://www.inlab.de/balance.html

Distributor load balancer

Distributor is a software TCP load balancer. Like other load balancers, it accepts connections and distributes them to an array of back end servers. It is compatible with any standard TCP protocol (HTTP, LDAP, IMAP, etc.) and is also IPv6 compatible. It has many unique and advanced features and a high-performance architecture.
Homepage:
http://distributor.sourceforge.net/

Pure Load Balancer

Pure Load Balancer is a high-performance software load balancer for the HTTP and SMTP protocols. It uses an asynchronous non-forking/non-blocking model, and provides fail-over abilities. When a backend server goes down, it automatically removes it from the server pool, and tries to bring it back to life later. Pure Load Balancer has full IPv6 support and works on OpenBSD, NetBSD, FreeBSD and Linux.
Homepage:
http://plb.sunsite.dk/

Load Balancer Project

The Load Balancer Project is a tool that allows you to balance requests using clusters of servers. The goal is to achieve high availability load balancing with a simple configuration for the load balancer and the network topology. It leaves the servers untouched so the configuration only resides on the load balancer, and it allows you to manage any type of service via a plugin model design and a transparent proxy feature.
Homepage:
http://www.jmcresearch.com/projects/loadbalancer/

mod_athena

mod_athena is an Apache-based application load balancer for large systems. It allows the HTTP server to act as a load balancer either internally to Apache's own mod_proxy (for reverse proxying), or externally to machines querying it. Arbitrary statistics are sent to the engine via a simple GET plus query-string interface, from which it will then make decisions based on chosen algorithms.
Homepage:
http://ath.sourceforge.net/

udpbalancer 

Udpbalancer is a reverse proxy that sorts UDP requests from your clients to your servers. It may operate in round-robin, volume balance, and load balance modes.
Homepage:
http://dev.acts.hu/udpbalancer/

MultiLoad

MultiLoad is a load balancer that redirects HTTP requests to pre-defined servers/locations. It gives the provider a way to balance the traffic and hides the real download location. It allows you to manage different version of each download. It is also a load balancing server extension. You can distribute files on some servers so that a downloaded file can be loaded form different servers. These servers can have different priorities to control the active traffic.
Homepage:
http://download.laukien.com

Tuesday, January 18, 2011

Hibernate Connection Fails if there is Database inconsistency or DB fail-over (Oracle RAC)

        /**
     * A static method with returns Hibernate Sessoin Object.
     *
     * @return {@link Session}
     */
    public static Session getSession() throws HibernateException {
        Session appSession = sessionFactory.openSession();
        try
        {
                if(appSession.connection().isClosed()||!appSession.isConnected()||!appSession.isOpen()){
                        System.out.println("Session Closed, Creating Session again...");
                        appSession.reconnect(appSession.connection());
                }
        }
            catch (Exception e) {
                System.err.println("Got Problem while getting Session from Factory:"+ e.getMessage());
                e.printStackTrace();
            }
        return appSession;
      
    }

Monday, October 25, 2010

Modifying the JVM heap size Formula

 
The total value of all server JVM heap sizes within the dynamic cluster for a specific node must be less than half of the total RAM of that computer. To determine the maximum heap size setting for a single server instance, use the following equation:
total_RAM / 2 / number_of_servers = maximum_heap_size
For example, to support three servers on a machine with 1.5 GB of RAM:
1.5 GB / 2 = 750 MB
750 MB / 3 = 250 MB
The maximum heap size is 250 MB for each server instance.

Monday, October 27, 2008

Applets are not running on Internet Explorer 7.0

I think there was an issue with applets on Internet Explorer 7.0. When I tried to run some applets on my windows 2003 server (SP2) box with IE 7.0 and JDK 1.5 version I could not able to load applets on my browser. I tried in almost all known ways by enabling applets through browser setting Tools -->Advanced and from java console (control panel --> java console --> Advanced) but no luck finally I thought to uninstall the java and reinstall it again and did the same but still no luck so finally I have installed lower version of Internet Explorer version 6.0 and it started working...
I think IE 7.0 has some issues still. But IE 7.0 has got some pros and cons as per my limited usage experience...

Pros:
  • Rich look and feel
  • Tabbed browsing
  • Implemented Add-on concept as Mozilla Firefox had.
Cons:
  • Though you enable Add-ons still browser through you message that you have not enabled add-on facility which really frustrates.
  • As I told Applet issue.
  • When we say Add-on user will easily sense that MicroSoft is trying to follow Mozilla's style of providing add-on's.
Fix for this issue

It started working by doing this way uninstall IE 7.0 and JDK 1.5 and then start reinstalling IE 7.0 and then install JDK 1.5. This will solve applet issue.

Thursday, August 14, 2008

Error Reporting through E-Mail using Log4j (SMTPAppender Class)

This could be one of the cool thing if you get an intimation through an email when ever your application is facing the problem in production or test environments apart from this you get log file as well so we can decrees the turn around time some what in fixing and issue and making your environment up. A few months back I have implemented the same thing for one of our production application and I have used log4j for logging and emailing the log file when ever log file get populated with error level messages.
In log4j api we have one class called SMTPAppender which will email us our log file when ever log file is populated with error level message. Just needs to configure log4j properties file with all SMTP server details.

Note: Make sure that you should have mail.jar and activation.jar files in your class path.

log4j.properties:

log4j.rootLogger=INFO, filer ,SMTPTest
log4j.appender.filer=org.apache.log4j.RollingFileAppender
log4j.appender.filer.layout=org.apache.log4j.PatternLayout
log4j.appender.filer.layout.ConversionPattern=%d{MMM dd HH:mm:ss} %-5p [%t] %c{2} - %m%n
log4j.appender.filer.File=C:\\COMSProduction.log
log4j.appender.filer.MaxFileSize=1000KB
log4j.appender.filer.MaxBackupIndex=4

#####################
#SMTP appender properties#
#####################

log4j.appender.SMTPTest=org.apache.log4j.net.SMTPAppender
log4j.appender.SMTPTest.Threshold=Error
log4j.appender.SMTPTest.BufferSize=512
log4j.appender.SMTPTest.layout=org.apache.log4j.PatternLayout
log4j.appender.SMTPTest.layout.ConversionPattern=%d %-4r [%t] %-5p (%c:%L)%x - %m%n
log4j.appender.SMTPTest.SMTPHost= smpt.youcompany.com
log4j.appender.SMTPTest.To= me@who.com
log4j.appender.SMTPTest.From= me@who.com,user@who.com
log4j.appender.SMTPTest.Subject=COMSProductionLog - <>

EmailSender.java - Load properties and configure SMTP properties with log4j.
------------------

import org.apache.log4j.Category;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.net.SMTPAppender;

import java.io.InputStream;
import java.util.Properties;

/**
* Created by IntelliJ IDEA.
* User: sirishg
* Date: Apr 5, 2007
* Time: 4:38:45 PM
* To change this template use File | Settings | File Templates.
*/

/**
* This class is responsible to email your application log file to SupportEngineers/Developers when ever application is caught with errors.
* I am using SMPTAppender(from apache log4j) to do this job.
*/

public class EmailSender {
public static Category log = org.apache.log4j.Category.getInstance(EmailSender.class.getName());

public static void postEmail() {

Properties properties = null;
try {
properties = new Properties();
InputStream inStream = LogManager.class.getResourceAsStream("log4j.properties");
properties.load(inStream);

log.info("Trying to load log4j.properties file!!");
PropertyConfigurator.configure(properties);
log.info("Successfuly loaded the property file!!");
} catch (Exception e) {
log.error("OOPS...log4j.property file has not loaded!!");
e.printStackTrace();
}

/**
* Call SMTPAppender and set all required fields to that. you can set directly from here or you can load parameters from you log4j.properties.
* I prefer to load from log4j.properties hence you will get the chance to change perameters dynamically with out recomiling your code.
*/
try {
log.info("Invoking the SMTPAppender class");
SMTPAppender emailAppender = new SMTPAppender();
if (properties != null) {
emailAppender.setSMTPHost(properties.getProperty("log4j.appender.SMTPTest.SMTPHost"));
emailAppender.setFrom(properties.getProperty("log4j.appender.SMTPTest.From"));
emailAppender.setTo(properties.getProperty("log4j.appender.SMTPTest.To"));
emailAppender.setSubject(properties.getProperty("log4j.appender.SMTPTest.Subject"));
}
emailAppender.setLayout(new PatternLayout());
emailAppender.activateOptions();
log.addAppender(emailAppender);
} catch (Exception e) {
log.error("got an error in SMTPAppender, the errors are::" + e.getStackTrace());
e.printStackTrace();
}
}
}

PostEmailTest.java
-- Small test and try to do some mistake and put an error entry into log file now see you will get an email with your log file.
public class PostEmailTest {
public static void main(String[] args) throws Exception {
LogManager manager = new LogManager();
Logger log = manager.getLogger(PostEmailTest.class);
String str = "Sirish";
if (str.equals("SIRISH")) {
log.info("both strings are equal....");
} else {
log.error("Strings are not equal....!");
/**
* Finally we rached to what we are looking for. now we got one error entry into log file and this is the time to email log file to
* SupporEngineer so invoke EmailSender class and send .log file.
*/
EmailSender.postEmail();
}
}
}

Wednesday, July 30, 2008

Friday, July 25, 2008

Execute .sql script file using java

A few days back I tried to execute our database scripts file using java in a plain way but I am not sure how good it is? but I am done with my work with no known issues but still I'm thinking is that right way to parse entair .sql file and pass the each line to JDBC API and ask JDBC API to execute that line of SQL? Here it is the method I used...

public boolean executeDBScripts(String aSQLScriptFilePath, Statement stmt) throws
IOException,SQLException {
boolean isScriptExecuted = false;
try {
BufferedReader in = new BufferedReader(new FileReader(aSQLScriptFilePath));
String str;StringBuffer sb = new StringBuffer();
while ((str = in.readLine()) != null) {
sb.append(str + "\n ");
}
in.close();
stmt.executeUpdate(sb.toString());
isScriptExecuted = true;
} catch (Exception e) {
System.err.println("Failed to Execute" + aSQLScriptFilePath +". The error is"+ e.getMessage));
}
return isScriptExecuted;
}