Pages

Wednesday, 12 February 2014

SNMP and its linux command

SNMP basic components and its functions:

    The SNMP architecture consists of
    The SNMP Manager
    A managed device
    An SNMP Agent
    Management Information Databases (otherwise known as Management Information Bases or MIBs)

    The SNMP Manager - (Usually the Network Management System - NMS) communicates with the multiple SNMP Agents implemented in the network.

    A managed device - or the network element is a part of the network that requires some form of monitoring and management e.g. routers, switches, servers, workstations, printers, UPSs, etc..

    An SNMP Agent - is a program that is bundled within the managed device. Enabling this agent allows it to collect the Management Information Database from the device locally to make it available to the SNMP Manager on request. These Agents could be standard (e.g. Net-SNMP) or specific to a vendor. (e.g. HP Insight Agent). The agent listens at port 161. TODO: UDP or TCP?

    Management Information Base / database - The commonly shared database between the Agent and the Manager is called Management Information Base (MIB). In short, MIB files are the set of questions that the SNMP Manager can ask the Agent. The Agent collects these data locally and stores it, as defined in the MIB.

    The MIBs contain a standard set of statistical and control values defined for the managed devices on a network. The SNMP protocol also allows the extension of these standard values with values specific to a particular Agent through the use of private MIBs. So the SNMP Manager should be aware of these standard and private questions for every type of Agent.
     
     
     

Linux Command 

One can simply issue one snmpwalk request on the root node of the sub-tree and the command gets the value of every node in the sub-tree.

[root@localhost ~]# snmpwalk -v 2c 169.254.0.8 -c FortiManager | grep OID
...
SNMPv2-SMI::mib-2.47.1.2.1.1.3.1 = OID: SNMPv2-SMI::enterprises.12356
...
[root@localhost ~]# snmpwalk -v 2c 169.254.0.8 -c FortiManager SNMPv2-SMI::enterprises.12356
...
SNMPv2-SMI::enterprises.12356.101.4.1.6.0 = Gauge32: 0
SNMPv2-SMI::enterprises.12356.101.4.1.7.0 = Gauge32: 0
SNMPv2-SMI::enterprises.12356.101.4.1.8.0 = Gauge32: 9
SNMPv2-SMI::enterprises.12356.101.4.1.9.0 = Gauge32: 80
SNMPv2-SMI::enterprises.12356.101.4.1.10.0 = Gauge32: 254764
SNMPv2-SMI::enterprises.12356.101.4.1.11.0 = Gauge32: 0
SNMPv2-SMI::enterprises.12356.101.4.1.12.0 = Gauge32: 0
SNMPv2-SMI::enterprises.12356.101.4.1.13.0 = Gauge32: 0
SNMPv2-SMI::enterprises.12356.101.4.1.14.0 = Gauge32: 0
...

[root@localhost ~]# snmpget -v 2c 169.254.0.8 -c FortiManager SNMPv2-SMI::enterprises.12356.101.4.1.8.0
SNMPv2-SMI::enterprises.12356.101.4.1.8.0 = Gauge32: 11


Friday, 20 September 2013

GWTModuleBase URL and HostPageBase URL

http://stackoverflow.com/q/12615663

Say I'm hosting a project at http://example.com/foo. I put all of the GWT files (which are generated in the /war/ directory after compiling) in http://example.com/foo/GwtModule directory.
Then on my host page, which is http://example.com/foo/bar, I put the following in the HTML:
<script type="text/javascript" src="http://example.com/foo/GwtModule/GwtModule.noCache.js"></script>.
My questions are:
  • Will GWT know to fetch its resources (e.g css files) from foo/GwtModule folder rather than trying to get them from foo/bar folder?
  • If I wanted to send a HTTP request to foo/signup, would GWT.getModuleBaseUrl() + "signup" work or will I have to parse the base url, remove "/bar" from it and replace it with "/signup"?
  • If I run the code locally as well as on a web server, will GWT automatically determine if the base url is http://localhost/foo/bar or http://example.com/foo/bar , or do I need to hard-code the base urls somewhere?
 http://stackoverflow.com/a/12618532
Will GWT know to fetch its resources (e.g css files) from foo/GwtModule folder rather than trying to get them from foo/bar folder?
Yes.
GWT always resolves the module base from the script URL (or a special <meta name='gwt:property'>)
If I wanted to send a HTTP request to foo/signup, would GWT.getModuleBaseUrl() + "signup" work or will I have to parse the base url, remove "/bar" from it and replace it with "/signup"?
GWT.getModuleBaseURL() will be /foo/GwtModule/.
You can either use GWT.getModuleBaseURL() + "/../signup" or "GWT.getHostPageBaseURL() + "/signup", in your case they'll both resolve to the same /foo/signup URL.
If I run the code locally as well as on a web server, will GWT automatically determine if the base url is http://localhost/foo/bar or http://example.com/foo/bar, or do I need to hard-code the base urls somewhere?
See answer to first question.
That means you'll have to use <script src="GwtModule/GwtModule.nocache.js"> or <script src="/foo/GwtModule/GwtModule.nocache.js"> in your host page.

Friday, 6 September 2013

JVM Class loader and java class initialization

JVM Class Loader

http://javarevisited.blogspot.sg/2012/07/when-class-loading-initialization-java-example.html 

What is ClassLoader in Java

In short here is the location from which Bootstrap, Extension and Application ClassLoader load Class files.

1) Bootstrap ClassLoader - JRE/lib/rt.jar
2) Extension ClassLoader - JRE/lib/ext or any directory denoted by java.ext.dirs
3) Application ClassLoader - CLASSPATH environment variable, -classpath or -cp option, Class-Path attribute of Manifest inside JAR file.

How ClassLoader works in Java

As I explained earlier Java ClassLoader works in three principles : delegation, visibility and uniqueness.


Delegation principles
As discussed on when a class is loaded and initialized in Java, a class is loaded in Java, when its needed. Suppose you have an application specific class called Abc.class, first request of loading this class will come to Application ClassLoader which will delegate to its parent Extension ClassLoader which further delegates to Primordial or Bootstrap class loader. Primordial will look for that class in rt.jar and since that class is not there, request comes to Extension class loader which looks on jre/lib/ext directory and tries to locate this class there, if class is found there than Extension class loader will load that class and Application class loader will never load that class but if its not loaded by extension class-loader than Application class loader loads it from Classpath in Java. Remember Classpath is used to load class files while PATH is used to locate executable like javac or java command.
Visibility Principle
According to visibility principle, Child ClassLoader can see class loaded by Parent ClassLoader but vice-versa is not true. Which mean if class Abc is loaded by Application class loader than trying to load class ABC explicitly using extension ClassLoader will throw either java.lang.ClassNotFoundException. as shown in below Example

package test;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Java program to demonstrate How ClassLoader works in Java,
 * in particular about visibility principle of ClassLoader.
 *
 * @author Javin Paul
 */


public class ClassLoaderTest {
 
    public static void main(String args[]) {
        try {         
            //printing ClassLoader of this class
            System.out.println("ClassLoaderTest.getClass().getClassLoader() : "

                                 + ClassLoaderTest.class.getClassLoader());

         
            //trying to explicitly load this class again using Extension class loader
            Class.forName("test.ClassLoaderTest", true 

                            ,  ClassLoaderTest.class.getClassLoader().getParent());
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ClassLoaderTest.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

Output:
ClassLoaderTest.getClass().getClassLoader() : sun.misc.Launcher$AppClassLoader@601bb1
16/08/2012 2:43:48 AM test.ClassLoaderTest main
SEVERE: null
java.lang.ClassNotFoundException: test.ClassLoaderTest
        at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
        at sun.misc.Launcher$ExtClassLoader.findClass(Launcher.java:229)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:247)
        at test.ClassLoaderTest.main(ClassLoaderTest.java:29)
Uniqueness Principle
According to this principle a class loaded by Parent should not be loaded by Child ClassLoader again. Though its completely possible to write class loader which violates Delegation and Uniqueness principles and loads class by itself, its not something which is beneficial. You should follow all  class loader principle while writing your own ClassLoader.


Class loading and Initialization

http://javarevisited.blogspot.sg/2012/07/when-class-loading-initialization-java-example.html

When a Class is initialized in Java

After class loading, initialization of class takes place which means initializing all static members of class. A Class is initialized in Java when :

1) an Instance of class is created using either new() keyword or using reflection using class.forName(), which may throw ClassNotFoundException in Java.
2) an static method of Class is invoked.
3) an static field of Class is assigned.
4) an static field of class is used which is not a constant variable.
5) if Class is a top level class and an assert statement lexically nested within class is executed.



How Class is initialized in Java

Here are some of the rules of class initialization in Java:

1) Classes are initialized from top to bottom so field declared on top initialized before field declared in bottom
2) Super Class is initialized before Sub Class or derived class in Java
3) If Class initialization is triggered due to access of static field, only Class which has declared static field is initialized and it doesn't trigger initialization of super class or sub class even if static field is referenced by Type  of Sub Class, Sub Interface or by implementation class of interface.

4) interface initialization in Java doesn't cause super interfaces to be initialized.
5) static fields are initialized during static initialization of class while non static fields are initialized when instance of class is created. It means static fields are initialized before non static fields in Java.

6)non static fields are initialized by constructors in Java. sub class constructor implicitly call super class constructor before doing any initialization, which guarantees that non static or instance variables of super class is initialized before sub class.

Wednesday, 4 September 2013

URL, URI, Context Path, path info

Consider following servlet conf 
 <servlet>
        <servlet-name>NewServlet</servlet-name>
        <servlet-class>NewServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>NewServlet</servlet-name>
        <url-pattern>/NewServlet/*</url-pattern>
    </servlet-mapping>
Now When I hit url http://localhost:8084/JSPTemp1/NewServlet/jhi it will invoke NewServlet as it is mapped with pattern.
here
getRequestURI() =  /JSPTemp1/NewServlet/jhi
getPathInfo() = /jhi
getPathInfo()
returns
a String, decoded by the web container, specifying extra path information that comes after the servlet path but before the query string in the request URL; or null if the URL does not have any extra path information
getRequestURI()
returns
a String containing the part of the URL from the protocol name up to the query string



Its very important to know how container picks a servlet from which web app .(means how it identify the correct web app and then correct servlet)

Since the request uri consist of three main parts
Context Path- this helps container to choose the correct web app
ServletPath-this helps container to identify correct servlet into the from the requested web app.
PathInfo-in case of directory match

So if the request uri is
http://server.com/MyApp/servlet/xyz ,the container will first look for a web app named MyApp if it exists then it will look for the resource(here servlet) mapped to /servlet/xyz.

In case if there is no web app named MyApp then it (Tomcat)will look into the default web app (ROOT) for the servlet mapped to the uri /MyApp/servlet/xyz and proceed acc to that.

Web application and Servlets notes

Servlet Context and Session Listeners

• Servlet context listeners.
– These listeners are notified when the servlet context (i.e., the Web application) is initialized and destroyed.
• Servlet context attribute listeners.
– These listeners are notified when attributes are added to, removed from, or replaced in the servlet context.
• Session listeners.
– These listeners are notified when session objects are created, invalidated, or timed out.
• Session attribute listeners.
– These listeners are notified when attributes are added to, removed from, or replaced in any session.

Implement the appropriate interface.
– Use ServletContextListener, ServletContextAttributeListener,
HttpSessionListener, or HttpSessionAttributeListener

Use these objects.
– This process is application specific, but there are some common
themes. For example, with the servlet context, you are most likely
to read initialization parameters (getInitParameter), store data for
later access (setAttribute), and read previously stored data
(getAttribute).

Declare the listener.
– You do this with the listener and listener-class
elements of the general Web application deployment descriptor
(web.xml) or of a tag library descriptor file.

Provide any needed initialization parameters.
– Servlet context listeners commonly read context initialization
parameters to use as the basis of data that is made available to all
servlets and JSP pages. You use the context-param web.xml
element to provide the names and values of these initialization
parameters.

How to pass parameters to whole web application – ServletContext

Here’s a serlvet code example to demonstrate how to pass a parameter to whole web application by using ServletContext “init-param” in web.xml.

In the deployment descriptor (web.xml)

Put your parameter value in “init-param” and make sure outside the “servlet” element
        <servlet>
  <servlet-name>ServletName</servlet-name>
  <servlet-class>com.mkyong.ServletDemo</servlet-class>
 </servlet>
 
 <context-param>
   <param-name>email</param-name>
   <param-value>admin@email.com</param-value>
 </context-param>

Servlet code

public void doGet(HttpServletRequest request, HttpServletResponse response)
 throws IOException{
 
  PrintWriter pw = response.getWriter();
  pw.println(getServletContext().getInitParameter("email"));
 
 }
The “getServletContext().getInitParameter(“email”)” method is use to get the ServletContext parameter value in web.xml. In addition , this parameter is accessible by the whole web application.

How to pass parameters to a servlet – ServletConfig

Here’s a serlvet code example to demonstrate how to pass a parameter to a servlet by using ServletConfig “init-param” in web.xml

In the deployment descriptor (web.xml)

Put your parameter value in “init-param” and make sure inside the “servlet” element
        <servlet>
  <servlet-name>ServletName</servlet-name>
  <servlet-class>com.mkyong.ServletDemo</servlet-class>
 
  <init-param>
   <param-name>email</param-name>
   <param-value>admin@email.com</param-value>
  </init-param>
 </servlet>
 
 <servlet-mapping>
  <servlet-name>ServletName</servlet-name>
  <url-pattern>/Demo</url-pattern>
 </servlet-mapping>

Servlet code

public void doGet(HttpServletRequest request, HttpServletResponse response)
 throws IOException{
 
  PrintWriter pw = response.getWriter();
  pw.println(getServletConfig().getInitParameter("email"));
 
 }
The “getServletConfig().getInitParameter(“email”)” method is use to get the ServletConfig parameter value in web.xml. Btw, this parameter only available for this servlet only. If you want a parameter which allow globally access by whole web application, you need put the parameter in servlet context element.
Here’s an example to pass parameter to whole web application.

Thursday, 22 August 2013

Allow and instruct the web application to query an untrusted https URL

Https query from web application like JSON to the site that needs to add certification exception (the trust) manually. When the user use their own browser to launch a https query to a web site that its certificate is not supported by the standard authorities, the user will be prompted for a permission to accept the certificate as an exception.

For web application server to launch the query, there is no way to prompt the web application to accept the exception, and the default is to reject the untrusted certificate. The web server will complain that the certificate is not found from the keystore for the requested target.

javax.xml.ws.soap.SOAPFaultException
sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target


Now, we have to tell the web server to trust the certificate from the target.
1> Query the target URL by web browser.
2> Download and save the certificate <xxx.pem> from the target.
3> Append the certificate to the keystore

1. cd /usr/java/jdk1.6.0_33/jre/lib/security

2. /usr/java/jdk1.6.0_33/bin/keytool -import -v -trustcacerts -alias <Create your own> -file <filepath/xxx.pem> -keypass changeit -keystore ./cacerts -storepass changeit







Tuesday, 13 August 2013

Mounting file system, fstab, mtab

Basic format: mount -t <filesystem type> old_dir new_dir

1> Mounting a directory to another directory to let them access the same content
mount --bind old_dir<directory has content> new_dir<directory designed to access the content>

2> Mounting a device <like CDROM> with no -t parameter, it will let the OS to guess
mount /dev/cdrom /cd

3> NFS
  • /etc/exports specifies the access control of the mounting directory.

/home vale(rw) vstout(rw) vlight(rw)
/usr/X11R6 vale(ro) vstout(ro) vlight(ro)
/usr/TeX vale(ro) vstout(ro) vlight(ro)
/ vale(rw,no_root_squash)
/home/ftp (ro) 
/var/myApp 172.16.95.17/255.255.255.255(rw,no_root_squash) 

Each line defines a directory and the hosts allowed to mount it. Wildcard is allowed (* ?).
Range of ip address / network mask can be used to specify the host. 
If no host is give, any host matches and is allowed to mount the directory.
  • CLI form to mount NFS volume. 
    mount -t nfs nfs_volume local_dir options
     
  • /etc/fstab entry of NFS
[root@localhost ~]# cat /etc/fstab
/dev/VolGroup00/LogVol00 /                       ext3    defaults        1 1
/dev/VolGroup00/LogVol01 /data                   ext3    defaults        1 2
LABEL=/boot1            /boot                   ext3    defaults        1 2
tmpfs                   /dev/shm                tmpfs   defaults        0 0
devpts                  /dev/pts                devpts  gid=5,mode=620  0 0
sysfs                   /sys                    sysfs   defaults        0 0
proc                    /proc                   proc    defaults        0 0
LABEL=SWAP-sda6         swap                    swap    defaults        0 0
172.16.95.93:/var/myApp    /logserver-1/var/myApp     nfs     hard,intr       0 0

4> fstab and mtab
[root@localhost ~]# cat /etc/fstab
/dev/VolGroup00/LogVol00 /                       ext3    defaults        1 1
LABEL=/boot             /boot                   ext3    defaults        1 2
tmpfs                   /dev/shm                tmpfs   defaults        0 0
devpts                  /dev/pts                devpts  gid=5,mode=620  0 0
sysfs                   /sys                    sysfs   defaults        0 0
proc                    /proc                   proc    defaults        0 0
/dev/VolGroup00/LogVol01 swap                    swap    defaults        0 0
/var/myApp /localserver-1/var/myApp none rw,bind 0 0

There are 3 ways of using fstab.
1> mount -a will cause all the filesystem listed on fstab to be mounted, except those noted as noauto. Adding the -F will make mount fork. Usually it is used by boot scripts.

2> To mount or umount the filesystem mentioned on the fstab, it is sufficed to give only the device or the mount point.

e.g In fstab, /tmp/a /tmp/b none rw,bind 0 0
mount /tmp/a or mount /tmp/b will suffice.

3>  Normally, only the superuser can mount  file  systems.   However, when  fstab  contains  the user option on a line, anybody can mount the corresponding system.