Saturday, 24 November 2012

HTTP Status 404 - / on tomcat


HTTP Status 404 - /

type Status report

message /

description The requested resource (/) is not available.

Apache Tomcat/6.0.26




When you choose to  "Start" your Tomcat and when you Open http://localhost/ in a browser: you will see a 404 error message.
This occurs because your eclipse fails to copy the ROOT files in the metadata folder and http://localhost/ will result in a 404 error. But, the error page comes from Tomcat, so it shows that Tomcat is running. The problem is that Eclipse doesn't copy the default Web application to the Eclipse/Tomcat folder. However, if you copy the ROOT files as described below, http://localhost/ will give the default Tomcat page.


Eclipse forgets to copy the default app (ROOT) when it creates a Tomcat folder inside the Eclipse workspace.
>> Go to C:\apache-tomcat-7.0.27\webapps,  copy the ROOT folder.
>>Go to your Eclipse workspace >> .metadata folder>>.plugins>>org.eclipse.wst.server.core>>wtpwebapps.
>>Paste ROOT (say "yes" if asked if you want to merge/replace folders/files). Then reload http://localhost/ to see the Tomcat welcome page.

Saturday, 17 November 2012

Access restriction: The type ResolverConfiguration.Options is not accessible due to restriction on required library C:\Program Files\Java\jre6\lib\rt.jar

This error may occurs when your project is not able to identify your JRE system library. So the get the workaround you have to follow these steps.


-->Go to the project properties.
-->Remove the JRE System Library
-->Add it back :
                     Select "Add Library" and select the JRE System Library.

The main reason for this to happen is that if  you are trying to replace a standard class which ships with some different Java Version with one in the library you have.


Tuesday, 6 November 2012

permgen space error in ant








set ANT_OPTS as the system variable
with value
-Xms512m -Xmx1024m -XX:PermSize=1024m -XX:MaxPermSize=2048m

How to solve java Permgen Space error


You must have often come across something OutOfMemoryError: PermGen Space error. 

Let's first get in to a little detail of  what actually is permanent generation heap space and why Permgen Space error comes and how to handle this.

What is:-

                  There are two memory regions in the JVM: the heap and the stack. Local variables and methods reside on the stack, everything else on the heap.

The  heap memory is structured again into regions, called generations. 
The Java virtual machine is organized into three generations: a young generation, an old generation, and a permanent generation.
Most objects are initially allocated in the young generation. The old generation contains objects that have survived some number of young generation collections, as well as some large objects that may be allocated directly in the old generation. The longer an object lives, the higher the chance it will be promoted to an older generation.

Young generations are more garbage collected than older generations. 

However, there is also some separate heap space called permanent generation. Since it is a separate region, it is not considered part of the Java Heap space. Objects in this space are relatively permanent. Class definitions are stored here, as are static instances.
For the HotSpot Java VM, the memory pools for serial garbage collection are the following.

Eden Space (heap): The pool from which memory is initially allocated for most objects.
Survivor Space (heap): The pool containing objects that have survived the garbage collection of the Eden space.
Tenured Generation (heap): The pool containing objects that have existed for some time in the survivor space.
Permanent Generation (non-heap): The pool containing all the reflective data of the virtual machine itself, such as class and method objects. With Java VMs that use class data sharing, this generation is divided into read-only and read-write areas.
Code Cache (non-heap): The HotSpot Java VM also includes a code cache, containing memory that is used for compilation and storage of native code.





How:-

          
       The prime reason for the error is the deployment and undeployment of classes all the time .


Let's take the scenario of a web server.
When an application is deployed or undeployed, its class definitions and Classloader are respectively put into and removed from the permanent generation heap. The problem arises when the undeployment of classes happens and they are not fully garbage collected.

              Let’s say we have a class A, which is part of a jar in a web application that is deployed on some webserver. In the lib folder of the web server, there is some logging framework present, which has a Log class with the method abc(Class B) with which classes can be registered for logging. Let’s say that the class A gets registered by this method and the Log class starts keeping a reference to the B's  object. When the class A gets undeployed, it is still registered with the Log class. The Log class will still have a reference to it and hence, it will never be garbage collected. Moreover, since the class A has a reference to its ClassLoader in turn, the ClassLoader itself will never be garbage collected either, and so will none of the classes it loaded. This will lead to the permgen space error.



How to fix this:


Set –Xms(initial java heap size) and –Xmx(maximum java heap size)


-Xms512m -Xmx1024m -XX:PermSize=1024m -XX:MaxPermSize=2048m





















Wednesday, 12 September 2012

Python script to get the RAM and available hard disk memory

Python uses ctypes module to abstract the hardware information. ctypes allows to call functions in dlls/shared libraries and has extensive facilities to create, access and manipulate simple and complicated C data types in Python - in other words: wrap libraries in pure Python. It is even possible to implement C callback functions in pure Python.

ctypes works on Windows, Windows CE, Mac OS X, Linux, Solaris, FreeBSD, OpenBSD


import ctypes
import platform
import os

class SysInfo:

    def __init__(self):

        self.totalRam, self.availRam = self.ram()
        self.totalRam = self.totalRam / (1048576)
        self.availRam = self.availRam / (1048576)



    def ram(self):
    try:
        kernel32 = ctypes.windll.kernel32
        c_ulong = ctypes.c_ulong
        class MEMORYSTATUS(ctypes.Structure):
            _fields_ = [
                ('dwLength', c_ulong),
                ('dwMemoryLoad', c_ulong),
                ('dwTotalPhys', c_ulong),
                ('dwAvailPhys', c_ulong),
                ('dwTotalPageFile', c_ulong),
                ('dwAvailPageFile', c_ulong),
                ('dwTotalVirtual', c_ulong),
                ('dwAvailVirtual', c_ulong)
            ]

        memoryStatus = MEMORYSTATUS()
        memoryStatus.dwLength = ctypes.sizeof(MEMORYSTATUS)
        kernel32.GlobalMemoryStatus(ctypes.byref(memoryStatus))
        return (memoryStatus.dwTotalPhys, memoryStatus.dwAvailPhys)
    except , err;
        print "No ram found"



    def get_free_space(self,folder, format="GB"):
        """
            Return folder/drive free space
        """
    try:
        fConstants = {"GB": 1073741824,
                      "MB": 1048576,
                      "KB": 1024,
                      "B": 1
                      }
        if platform.system() == 'Windows':
            free_bytes = ctypes.c_ulonglong(0)
            ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(folder), None, None, ctypes.pointer(free_bytes))
            #return (int(free_bytes.value/fConstants[format.upper()]), format)
            return (int(free_bytes.value/1073741824), format)
        else:
            return (int(os.statvfs(folder).f_bfree*os.statvfs(folder).f_bsize/fConstants[format.upper()]), format)
    except , err;
        print "No hard disk found"
       
if __name__ == "__main__":
        sys = SysInfo()
        print "System Memory : %dMb total" % sys.totalRam
        print "Available System Memory  : %dMb free" % sys.availRam
        byteformat = "GB"
        drive = raw_input("Enter drive:")
        space,size =  sys.get_free_space(drive+":", byteformat)
        print space,size

Ant script to create zip using 7zip commands


<?xml version="1.0" encoding="UTF-8"?>

<project name="zip-test" default="zip-file" basedir=".">

<property name="project-name" value="test" />
<property name="folder-to-zip" value="D:\abc\*" />
<echo message = "${folder-to-zip}"/>

<target name="clean">
   <echo message="${project-name}.7z"/>
<delete file="${project-name}.7z" />
</target>


<target name = "zip-file">
   <echo message = "${folder-to-zip}"/>
<exec executable="7z.exe">
<arg value="a"/>
<arg line="-t7z ${project-name} ${folder-to-zip}"/>
</exec>
</target>
<target name="run" depends="clean" />

</project>

Django Error:1005 "Can't create table 'nameofdb.#sql-*****' errno: 121"

While trying to configure Merengue CMS + Django on Opensuse , I got stuck here. The instant I run the "python manage.py migrate" it started giving error (1005 "Can't create table 'nameofdb.#sql-*****' errno: 121" ).After checking INNODB(MySql engine) status I found out that it is because of violation of some Foreign Key constraints.
                                    As the Django uses MYISM as the default engine it was having problems migrating the tables in Mysql 5.5 as the default engine in Mysql 5.5 is INNODB.
After doing a lot of googling , the solutions I tried out are as follows:-
1). In the settings.py script
     DATABASE_OPTIONS={'init_command': 'SET storage_engine=INNODB',}.
     Though it didnot work out for me.
2). ALTER TABLE <tablename> ENGINE=INNODB;
     Though it is worst solution as it was having too many tables, but i did it after doing the migration, though it      started the server, but it showed 500 Internal server error.
3). The solution provided by the Django community https://code.djangoproject.com/wiki/AlterModelOnSyncDB. I copied the whole code in __init.py. But nothing changed.

After spending lot of time I am still trying to find out the solution. Folks do provide your solutions.

In the meantime I am switching to Mezannine:-)

Saturday, 8 September 2012

from django.core import management ImportError: No module named django.core

After doing a lot of research I found out the reason that this error comes because of the wrong way of installing Django. So , you need to follow my blog http://toolsdeve.blogspot.in/2012/09/setting-up-django-on-windows.html.

Setting Up Django on windows

As Django is entirely a  Python Web framework, Django requires Python.  It works with  Python versions from 2.5 to 2.7 (due to backwards incompatibilities in Python 3.0, Django does not currently work with Python 3.0).
Steps:-
1)  Install Python 2.5 or later from http://www.python.org.
2)  Remove any earlier version of Django you already have.
3) Download and Install the current version of Django from https://docs.djangoproject.com/en/1.4/misc/distributions/.
4) Open your command prompt
               >>>>>cd c:\django\bin> python setup.py install
5) Django folder will automatically be copied into your python\sitepackage folder.
              >>>>>cd C:\Python27\Lib\site-packages\django\bin> django-admin.py

If you get this:


Usage: django-admin.py subcommand [options] [args]

Options:
  -v VERBOSITY, --verbosity=VERBOSITY
                        Verbosity level; 0=minimal output, 1=normal output,
                        2=verbose output, 3=very verbose output
  --settings=SETTINGS   The Python path to a settings module, e.g.
                        "myproject.settings.main". If this isn't provided, t
                        DJANGO_SETTINGS_MODULE environment variable will be
                        used.
  --pythonpath=PYTHONPATH
                        A directory to add to the Python path, e.g.
                        "/home/djangoprojects/myproject".
  --traceback           Print traceback on exception
  --version             show program's version number and exit
  -h, --help            show this help message and exit

Type 'django-admin.py help <subcommand>' for help on a specific subcommand.

Available subcommands:

[django]
    cleanup
    compilemessages
    createcachetable
    dbshell
    diffsettings
    dumpdata
    flush
    inspectdb
    loaddata
    makemessages
    runfcgi
    runserver
    shell
    sql
    sqlall
    sqlclear
    sqlcustom
    sqlflush
    sqlindexes
    sqlinitialdata
    sqlsequencereset
    startapp
    startproject
    syncdb
    test
    testserver
    validate
>>>you are done with your settings.....enjoy...:-)


Thursday, 23 August 2012

Calculating Disk Space in Java


In Java by using a few API's are there through which we can directly obtain the space given in a drive.



package com.test;

import java.io.File;

public class SizeInfo
{
    public static void main(String[] args)
    {

       System.out.print("Enter the drive: ");
       BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       String path= null;
       try {
         path= br.readLine();

      File file = new File(path + ":");

//the size returned will be in bytes.

     long totalSpace = file.getTotalSpace();
     long usableSpace = file.getUsableSpace();
     long freeSpace = file.getFreeSpace();



     System.out.println("Total size : " + TotalSpace /1048576 + " Gb");
     System.out.println("Space free : " + UsableSpace /1048576 + " Gb");
     System.out.println("Space free : " + FreeSpace /1073741824 + " Gb");
}catch(Exception ex)
{
ex.printstacktrace();
}
    }
}


getUsableSpace() method does a few additional checks, about write permissions and actual space available to the user. Also, on some systems a certain percentage of total disk space is reserved for admin/root users. This can make your checks for space pass incorrectly if you happen to use the getFreeSpace() method.

Saturday, 16 June 2012

Configuration of Findbugs with Jenkins for Ant projects

After spending a lot of time on the configuration of Findbugs with Jenkins for Ant projects. I thought of putting it altogether just to save your time:-)

Well lets have a brief introduction about these two tools.

Jenkins:- Jenkins is an awesome tool that monitors executions of repeated jobs, such as building a software project or jobs run by cron.
Findbugs:- FindBugs is a static analysis tool that finds coding mistakes by examining Java classfiles or Jar files. It actually reads your bytecode of the class files. Static analysis means that FindBugs can find bugs by simply inspecting a program's code: executing the program is not necessary.

So, let's dive in a step by step manner.

First install the default plugin provided by the Jenkins.
Goto >> Dashboard >> Manage Jenkins >> Findbugs Plugin. This plugin requires the utility plugin-in called
"Static Analysis Utilities". Please ensure that the latest version of this plug-in is also installed.

Ant Configuration:-

Download the .zip or .tzr.gz from http://findbugs.sourceforge.net/downloads.html
Extract it in the plugins folder of the jenkins.
Copy the "lib/findbugs-ant.jar" from your FindBugs installation to the "lib" folder of your ant installation.
Set the environmental variables:-
ANT_HOME----
JAVA_HOME----
FINDBUGS_HOME----{Your findbugs .zip(extracted path)}
Go to Java>>jdk>>jre>>lib copy findbugs-ant.jar.

Now comes the most important part to write ant script for your findbugs.So there you go.



      
        Ant build sample for running 
        - findbugs
   










 
 






   
       
   


       
           
               
           
       
   


   
   
       
       
       
              message="Error: FINDBUGS_HOME not set or findbugs.jar not found."/>
       
                 classname="edu.umd.cs.findbugs.anttask.FindBugsTask"
                 classpath="${findbugs.home.dir}/lib/findbugs-ant.jar"/>

       
       
       
 jvmargs="-Xmx1024m"
 timeout="3600000"
 home="${findbugs.home.dir}"
 workHard="true"
 output="xml:withMessages" 
                                  outputFile="${report.findbugs.dir}/findbugs.xml">
 
 
       


   
  
   
       
 out="${htm.dir}/findbugs.html"
 style="${findbugs.home.dir}/src/xsl/default.xsl" />

   
    
   
            description="Run the build"
            depends="clean, 
prepare.report.dir,
                findbugs, 
                report.findbugs">
   
 





INCLUDING MULTIPLE JAR FOR ANALYSIS:-

There are basically three ways to include multiple jars your build.xml
1. Put all the jars inside the  
     one by one.
2. Use rejarForAnalysis  script inside the bin folder of your findbugs.zip folder. There has not been a proper     document given by the findbugs team. http://findbugs.sourceforge.net/manual/rejarForAnalysis.html. This I   think is a little vague. So I thought of putting everything altogether.
    Install Cygwin on the windows to run the rejarForAnalysis.sh on your windows environment.
    http://cygwin.com/cygwin-ug-net/setup-net.html
    Command to create jar(using multiple jars) from cygwin.
    find . -name "*.jar" | xargs "${findbugs.home.dir}\bin\rejarForAnalysis"
 This will create a single jar comprising of multiple jars. Put this single jar for analysis.

3. Let's make it a little more simple. (Frankly speaking it took almost half a day to conclude this)....:-)
    Add this in your build.xml just before calling the findbugs task.---->
    
    
 
 


This will create a single jar at run-time and you don't need to install cygwin.


========================================================================\All the best with Jenkins and Findbugs.