Monday 19 September 2011

Java Constant Pool : String


For those who already experienced in Java Programming should already familiar with the concept of String constant pool.
String s1 = “jim”;
String s2 = “jim”;

System.out.println(s1==s2); // true.
Object s2 is the same object with s1. But if you create using new operator:
String s1 = “jim”;
String s2 = new String(“jim”);
System.out.println(s1==s2); //false.
It will allocate new Object instead getting from String constant pool.
Another sample:
String s1 = “jim”;
String s2 = “j”+”im”;String s3 = “j”;
String im = “im”;
s3+= im;
System.out.println(s1==s2); //true.System.out.println(s1==s3); //false.
Concatenation during runtime will create new String Object.
Sample if using final modifier:
final String s1 = “j”;
final String s2 = “im”;
String jim = “jim”;
System.out.println(s1+s2 == jim); // returns true: Constant expression.
String s3 = “j”;
String s4 = “im”;
System.out.println(s3 + s4 == jim); // returns false: Not a constant expression.
Concatenation of 2 final String is a Constant.
Although is not necessary for us programmer to know about the detail of JVM implementation about String Constant Pool. Some would say “I’m not stupid, I used equals to check equality of Strings. And I don’t really care how JVM in my OS implemented the damn Constant Pool”. But for me knowing this knowledge is something great, and somehow I think it will help me in the future :)
More information about this : JLS – Lexical Structure
  • Literal strings within the same class (§8) in the same package (§7) represent references to the same String object (§4.3.1).

  • Literal strings within different classes in the same package represent references to the same String object.

  • Literal strings within different classes in different packages likewise represent references to the same String object.

  • Strings computed by constant expressions (§15.28) are computed at compile time and then treated as if they were literals.

  • Strings computed by concatenation at run time are newly created and therefore distinct.
References Url :
http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.10.5
http://java.sun.com/docs/books/vmspec/html/ConstantPool.doc.html

7 new cool features in Java 7


The evolution of the Java language and VM continues! Mark Reinhold (Chief Architect of the Java Platform Group) announced yesterday that the first release candidate for Java 7 is available for download, he confirms that the final released date is planned for July 28.
For a good overview of the new features and what’s coming next in Java 8, I recommend this video on the Oracle Media Network, which features Adam Messinger, Mark Reinhold, John Rose and Joe Darcy. I think Mark sums up Java 7 very well when describing it as an evolutionary release, with good number “smaller” changes that make for a great update to the language and platform.
I had a chance to play a bit with the release candidate (made easier by the Netbeans 7  JDK 7 support!), and decided to list 7 features (full list is here) I’m particularly excited about. Here they are;
1. Strings in switch Statements (doc)
Did you know previous to Java 7 you could only do a switch on char, byte, short, int, Character, Byte, Short, Integer, or an enum type (spec)? Java 7 adds Strings making the switch instruction much friendlier to String inputs. The alternative before was to do with with if/else if/else statements paired with a bunch of String.equals() calls. The result is much cleaner and compact code.
  1. public void testStringSwitch(String direction) {  
  2.     switch (direction) {  
  3.          case "up":  
  4.              y--;  
  5.          break;  
  6.   
  7.          case "down":  
  8.              y++;  
  9.          break;  
  10.   
  11.          case "left":  
  12.              x--;  
  13.          break;  
  14.   
  15.          case "right":  
  16.              x++;  
  17.          break;  
  18.   
  19.         default:  
  20.             System.out.println("Invalid direction!");  
  21.         break;  
  22.     }  
  23. }  
2. Type Inference for Generic Instance Creation (doc)
Previously when using generics you had to specify the type twice, in the declaration and the constructor;
  1. List<String> strings = new ArrayList<String>();  
In Java 7, you just use the diamond operator without the type;
  1. List<String> strings = new ArrayList<>();  
If the compiler can infer the type arguments from the context, it does all the work for you. Note that you have always been able do a “new ArrayList()” without the type, but this results in an unchecked conversion warning.
Type inference becomes even more useful for more complex cases;
  1. // Pre-Java 7  
  2. // Map<String,Map<String,int>>m=new HashMap<String, Map<String,int>>();  
  3.   
  4. // Java 7  
  5. Map<String, Map<String, int>> m = new HashMap<>();  
3. Multiple Exception Handling Syntax (doc)
Tired of repetitive error handling code in “exception happy” APIs like java.io and java.lang.reflect?
  1. try {  
  2.     Class a = Class.forName("wrongClassName");  
  3.     Object instance = a.newInstance();  
  4. catch (ClassNotFoundException ex) {  
  5.     System.out.println("Failed to create instance");  
  6. catch (IllegalAccessException ex) {  
  7.     System.out.println("Failed to create instance");  
  8. catch (InstantiationException ex) {  
  9.    System.out.println("Failed to create instance");  
  10. }  
When the exception handling is basically the same, the improved catch operator now supports multiple exceptions in a single statement separated by “|”.
  1. try {  
  2.     Class a = Class.forName("wrongClassName");  
  3.     Object instance = a.newInstance();  
  4. catch (ClassNotFoundException | IllegalAccessException |  
  5.    InstantiationException ex) {  
  6.    System.out.println("Failed to create instance");  
  7. }  
Sometimes developers use a “catch (Exception ex) to achieve a similar result, but that’s a dangerous idea because it makes code catch exceptions it can’t handle and instead should bubble up (IllegalArgumentException, OutOfMemoryError, etc.).

4. The try-with-resources Statement (doc)
The new try statement allows opening up a “resource” in a try block and automatically closing the resource when the block is done.
For example, in this piece of code we open a file and print line by line to stdout, but pay close attention to the finally block;
  1. try {  
  2.     in = new BufferedReader(new FileReader("test.txt"));  
  3.   
  4.     String line = null;  
  5.     while ((line = in.readLine()) != null) {  
  6.         System.out.println(line);  
  7.     }  
  8. catch (IOException ex) {  
  9.     ex.printStackTrace();  
  10. finally {  
  11.     try {  
  12.         if (in != null) in.close();  
  13.     } catch (IOException ex) {  
  14.         ex.printStackTrace();  
  15.     }  
  16. }  
When using a resource that has to be closed, a finally block is needed to make sure the clean up code is executed even if there are exceptions thrown back (in this example we catch IOException but if we didn’t, finally would still be executed). The new try-with-resources statement allows us to automatically close these resources in a more compact set of code;
  1. try (BufferedReader in=new BufferedReader(new FileReader("test.txt")))  
  2. {  
  3.      String line = null;  
  4.      while ((line = in.readLine()) != null) {  
  5.          System.out.println(line);  
  6.      }  
  7.  } catch (IOException ex) {  
  8.      ex.printStackTrace();  
  9.  }  
So “in” will be closed automatically at the end of the try block because it implements an interface called java.lang.AutoCloseable. An additional benefit is we don’t have to call the awkward IOException on close(), and what this statement does is “suppress” the exception for us (although there is a mechanism to get that exception if needed, Throwable.getSuppressed()).
5. Improved File IO API (docs 1, 2)
There are quite a bit of changes in the java.nio package. Many are geared towards performance improvements, but long awaited enhancements over java.io (specially java.io.File) have finally materialized in a new package called java.nio.file.
For example, to read a small file and print all the lines (see example above);
  1. List<String> lines =  Files.readAllLines(  
  2. FileSystems.getDefault().getPath("test.txt"), StandardCharsets.UTF_8);  
  3.   
  4. for (String line : lines) System.out.println(line);  
java.nio.file.Path is an interface that pretty much serves as a replacement for java.io.File, we need a java.nio.file.FileSystem to get paths, which you can get by using the java.nio.file.FileSystems factory (getDefault() gives you the default file system).
java.nio.file.Files then provides static methods for file related operations. In this example we can read a whole file much more easily by using readAllLines(). This class also has methods to create symbolic links, which was impossible to do pre-Java 7. Another feature long overdue is the ability to set file permissions for POSIX compliant file systems via the Files.setPosixFilePermissions method. These are all long over due file related operations, impossible without JNI methods or System.exec() hacks.
I didn’t have time to play with it but this package also contains a very interesting capability via the WatchService API which allows notification of file changes. You can for example, register directories you want to watch and get notified when a file is added, removed or updated. Before, this required manually polling the directories, which is not fun code to write.
For more on monitoring changes read this tutorial from Oracle.
6. Support for Non-Java Languages: invokedynamic (doc)
The first new instruction since Java 1.0 was released and introduced in this version is called invokedynamic. Most developers will never interact or be aware of this new bytecode. The exciting part of this feature is that it improves support for compiling programs that use dynamic typing. Java is statically typed (which means you know the type of a variable at compile time) and dynamically typed languages (like Ruby, bash scripts, etc.) need this instruction to support these type of variables.
The JVM already supports many types of non-Java languages, but this instruction makes the JVM more language independent, which is good news for people who would like to implement components in different languages and/or want to inter-operate between those languages and standard Java programs.
7. JLayerPane (doc)
Finally, since I’m a UI guy, I want to mention JLayerPane. This component is similar to the one provided in the JXLayer project. I’ve used JXLayer many times in the past in order to add effects on top of Swing components. Similarly, JLayerPane allows you to decorate a Swing component by drawing on top of it and respond to events without modifying the original component.
This example from the JLayerPane tutorial shows a component using this functionality, providing a “spotlight” effect on a panel.
You could also blur the entire window, draw animations on top of components, or create transition effects.
And that’s just a subset of the features, Java 7 is a long overdue update to the platform and language which offers a nice set of new functionality. The hope is the time from Java 7 to 8 is a lot shorter than from 6 to 7!

Friday 16 September 2011

Advanced techniques for using the UNIX Find command.

Find all files in current directory and subdirectory, greater than some size using find command in Unix:

find . -size +1000c -exec ls -l {} \;

Always use a c after the number, and specify the size in bytes, otherwise you will get confuse because find -size list files based on size of disk block. to find files using a range of file sizes, a minus or plus sign can be specified before the number. The minus sign means "less than," and the plus sign means "greater than." Suppose if you want to find all the files within a range you can use find command as below.

-size n[cwbkMG]
              File uses n units of space.  The following suffixes can be used:
              `b'    for 512-byte blocks (this is the default if no suffix is used)
              `c'    for bytes
              `w'    for two-byte words
              `k'    for Kilobytes (units of 1024 bytes)
              `M'    for Megabytes (units of 1048576 bytes)
              `G'    for Gigabytes (units of 1073741824 bytes)
              The  size  does  not count indirect blocks, but it does count blocks in sparse files that are not actually allocated.
              Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files  differently.   The  `b'  suffix
              always denotes 512-byte blocks and never 1 Kilobyte blocks, which is different to the behaviour of -ls.

+ equal to greater than
- equal to less than


Example :

find . -size +2G -exec ls -lh {} \;
It return files which size is greater than 2GB.
find . -size +50000000c -exec ls -lh {} \;
It return files which size is greater than 50M

find . -type f -name "*.java*" -print
It return files which extension are .java and end with other character


There's nothing quite like the thrill of exploring, discovering new 
people, places, and things. The territory might change, but a few
principles remain the same. One of those principles is to keep a written
record of your journey; another is to know and use your tools.

The UNIX® operating system is much like a vast, uncharted wilderness.
As you travel the terrain, you can
pick up tools that assist you later. The find command is
such a tool. The
find command is capable of much more than simply locating
files; it can automatically execute sequences of other UNIX commands,
using the filenames found for input, as this article explains.

Find with few limits

All operating systems worth their salt have a tool to assist you in
finding things. Unlike most of these tools, the UNIX find
command can automatically perform many operations for you on the files
it finds.

Standard find tools found in graphical user interfaces
(GUIs) allow you to do a
few common tasks with the files you find: You can mark them for cutting,
copying, and pasting; you can move them to a new location; and you can
open them with the program used to create them. These operations involve
two or more steps and aren't automatic -- you find the files first, and
then you use the GUI to mark them for the next operation. This approach
is fine for many users, but the explorer wants more.

The UNIX find command can delete, copy, move, and
execute files that it finds. In addition, with the
-exec parameter, it can automatically run files through any
sequence of UNIX commands you need. It can
even ask you before it performs such operations on any file.

Simplify management of your file system

The UNIX find command, like most UNIX commands, has an
intimidating array of options and switches that can discourage people
from learning its depth -- but true explorers aren't intimidated just
because the territory is vast. A good general principle goes a long way
toward simplifying a complex topic. Start up an xterm, and try the
following command:

$ find . -name *.gif -exec ls {} \;

The -exec parameter holds the real power. When a file is
found that matches the search criteria, the -exec
parameter defines what to do with the file. This example tells the
computer
to:

  1. Search from the current directory on down, using the dot (.)
    just after find.
  2. Locate all files that have a name ending in .gif (graphic files).
  3. List all found files, using the ls command.
The -exec parameter requires further scrutiny. When a
filename is found that matches the search criteria, the find
command executes the ls {} string, substituting the
filename and path for the {} text. If saturn.gif was found
in the search, find would execute this command:

$ ls ./gif_files/space/solar_system/saturn.gif

The rest of the article builds on this general principle: Thoughtful
use of the find command can make the management of UNIX
file systems a much easier task. For example, the find
command can process commands based on the type of file system where the
file is found, if you use the -fstype parameter. And it's
often useful to have the find command prompt you before it
executes commands on a found file; you can tell it to do so by using the
-ok parameter, as you'll see next.

Optional execution

An important alternative to the -exec parameter is -ok;
it behaves the same as -exec, but it prompts you to see if
you want to run the command on that file.
Suppose you want to remove most of the .txt files in your home
directory, but you wish to do it on a file-by-file basis. Delete
operations like the UNIX rm command are dangerous, because
it's possible to inadvertently
delete files that are important when they're found by an automated
process like find; you might want to scrutinize all the
files the system finds before removing them.

The following command lists all the .txt files in your home
directory. To delete the files, you must enter Y or y when
the find command prompts you for action by
listing the filename:

$ find $HOME/. -name *.txt -ok rm {} \;

Each file found is listed, and the system pauses for you to enter
Y or y. If you press the Enter
key, the system won't delete
the file. Listing1 shows some sample results:


Listing 1. Sample results
< rm ... /home/bill/./.kde/share/apps/karm/karmdata.txt > ?
< rm ... /home/bill/./archives/LDDS.txt > ?
< rm ... /home/bill/./www/txt/textfile1.txt > ?
< rm ... /home/bill/./www/txt/faq.txt > ?
< rm ... /home/bill/./www/programs/MIKE.txt > ?
< rm ... /home/bill/./www/programs/EESTRING.txt > ?
.
.
.
After each question mark, the system paused; in this case, the Enter
key was pressed to continue to the next file. (No files were removed.)
The -ok parameter lets you control the automatic processing
of each found file,
adding a measure of safety to the danger of automatic file removal.

If too many files are involved for you to spend time with the -ok
parameter, a good rule of thumb is to run the find command
with -exec to list the files that would be deleted; then,
after examining the list to be sure no important files will be deleted,
run the command again, replacing ls with rm.

Both -exec and -ok are useful, and you must
decide which
works best for you in your current situation. Remember, safety first!

Use find creatively

You can perform myriad tasks with the find command. This
section provides some examples of ways you can put find to
work as you manage your file system.

To keep things simple, these examples avoid -exec
commands that involve the piping of output from one command to another.
However, you're free to use commands like these in a find's -exec
clause.

Clean out temporary files

You can use find to clean directories and subdirectories
of the temporary files generated during normal use, thereby saving disk
space. To do so, use the following command:

$ find . \( -name a.out -o -name '*.o' -o -name 'core' \) -exec rm {} \;

File masks identifying the file types to be removed are
located between the parentheses; each file mask is preceded by -name.
This list can be extended to include any temporary file types you can
come up with that need to be cleaned off the system. In the course of
compiling and linking code, programmers and their tools generate file
types like those shown in the example: a.out, *.o,
and core. Other users have similar commonly generated
temporary files and can edit the command accordingly, using file masks
like *.tmp,
*.junk, and so on. You might also find it useful to put the
command into a script called clean, which you can execute
whenever you need to clean a directory.

Copy a directory's contents

The find command lets you copy the entire contents of a
directory
while preserving the permissions, times, and ownership of every file and
subdirectory. To do so,
combine find and the cpio command, like this:

Listing 2. Combining the find and cpio command

$ cd /path/to/source/dir
$ find . | cpio -pdumv /path/to/destination/dir

The cpio command is a copy command designed to copy
files into and out of a cpio
or tar archive, automatically preserving permissions, times, and
ownership of files and subdirectories.

List the first lines of
text files

Some people use the first line of every text file as a heading or
description of the file's contents. A report that lists the filenames
and first line of each text file can make sifting through several
hundred text files a lot easier. The following command lists the first
line in every text file in your home directory in a report, ready to be
examined at your leisure with the less command:


Listing 3. The less command

$ find $HOME/. -name *.txt -exec head -n 1 -v {} \; > report.txt

$ less < report.txt

Maintain LOG and TMP file
storage spaces

To maintain LOG and TMP file storage space for applications that
generate a lot of these files,
you can put the following commands into a cron job that
runs daily:

Listing 4. Maintaining LOG and TMP file
storage spaces


$ find $LOGDIR -type d -mtime +0 -exec compress -r {} \;

$ find $LOGDIR -type d -mtime +5 -exec rm -f {} \;

The first command runs all the directories (-type d)
found in the $LOGDIR directory wherein a file's data has been modified
within the last 24 hours (-mtime +0) and compresses them (compress
-r {}
) to save disk space. The second command deletes them (rm
-f {}
) if they are more than a work-week old (-mtime +5),
to increase the free space on the disk. In this way, the cron job
automatically keeps the directories for a window of time that you
specify.

Copy complex directory
trees

If you want to copy complex directory trees from one machine to
another while preserving copy permissions and the User ID and Group ID
(UID and GID -- numbers used by the operating system to mark files for
ownership purposes), and leaving user files alone, find and
cpio once again come to the rescue:

Listing 5. Maintaining LOG and TMP file
storage spaces


$ cd /source/directory

$ find . -depth -print | cpio -o -O /target/directory

Find links that point to
nothing

To find links that point to nothing, use the perl
interpreter
with find, like this:

$ find / -type l -print | perl -nle '-e || print';

This command starts at the topmost directory (/) and lists all links (-type
l -print
) that
the perl interpreter determines point to nothing (-nle
'-e || print'
) -- see the Resources
section for more information regarding this tip from the Unix Guru
Universe site. You can further pipe the output through the rm -f
{}
functionality if you want to delete the files. Perl is,
of course, one of the many powerful interpretive language tools also
found in most UNIX toolkits.

Locate and rename
unprintable directories

It's possible in UNIX for an errant or malicious program to create a
directory with unprintable characters. Locating and renaming these
directories makes it easier to examine and remove them. To do so, you
first include the -i switch of ls to get the
directory's inode number. Then, use find
to turn the inode number into a filename that can be renamed with the mv
command:

Listing 6. Locating and renaming unprintable
directories


$ ls -ail
$ find . -inum 211028 -exec mv {} newname.dir \;

List zero-length files
To list all zero-length files, use this command:

$ find . -empty -exec ls {} \;

After finding empty files, you might choose to delete them by
replacing the ls command
with the rm command.

Clearly, your use of the UNIX find command is limited
only by your knowledge and creativity.
$ find . -inum 211028 -exec mv {} newname.dir \;

List zero-length files
To list all zero-length files, use this command:


$ find . -empty -exec ls {} \;

After finding empty files, you might choose to delete them by
replacing the ls command
with the rm command.

Clearly, your use of the UNIX find command is limited
only by your knowledge and creativity.
Resources

Learn

Tuesday 13 September 2011

Remove 'None' Option from Radio Button or Select List in JIRA

Simple way to remove 'None' Option from Radio Button

1.) Select Field Configurations options from JIRA Admin .
2.) Select desire fields like radio/select list upon you applied such script to remove 'none' option
3.) Select Edit option , front of fields name.
4.) Paste such script (below) on Edit Field Description


<script type="text/javascript">
radio= document.getElementById('customfield_11260_none');
radio.style.display='none';
elem= document.getElementById('customfield_11260_none');
do {
  elem = elem.nextSibling;
} while(elem.nodeType != 1); // 1 == Node.ELEMENT_NODE
if(elem) elem.style.display = 'none';
</script>

5.) Update .


 Simple way to remove 'None' Option from Select List 

Follow up the simple way

Paste this script on Edit Field Description

 <script type="text/javascript">
try{
var select = document.getElementById('customfield_11490');
//select.options[0].text="";
select.remove(0);
}catch(err){}
</script>

Update ..........


customfield_11260_none name of 'none' option fields . right click on the browser and search fields name like customfield_<id_of_fields>_none.


Or either use firebug to find out the fields values .





Monday 12 September 2011

How to change custom fields in JIRA

Example illustrated below , how we change text custom fields to select custom fields in jira. 

1. Stop Jira
     $JBOSS_HOME/bin/shutdown -S

2. UPDATE customfield SET CUSTOMFIELDTYPEKEY='com.atlassian.jira.plugin.system.customfieldtypes:select', CUSTOMFIELDSEARCHERKEY=NULL where cfname="My Text Field";


3. Start Jira
  $JBOSS_HOME/bin/run.sh -b 0.0.0.0

4. Configure the custom field to add the options. I assume you have to add an option for every distinct value, which you can probably find with:


select * from customfieldvalue where customfield=(select id from customfield where cfname='My Text Field');

and then use some version of DISTINCT to identify the unique value. Text with spaces may cause a problem.
5. Edit the custom field to set the Searcher
6. Add options value in this fields if it is select fields.
6. Reindex



more details , please visit on this url :
http://confluence.atlassian.com/display/JIRA/Changing+Custom+Field+Types