Posts Tagged ‘JAVA’

What’s New in the compiler of the JDK 7

Monday, September 7th, 2009

JavaLogo_060909

Darcy Joseph tells us of the developments that have the compiler in JDK 7. They are usually minor changes discussed at the forums, which include various amenities in the language syntax.

The news of the JDK 7 will be:

  • Switch to objects of type String
  • Automatic resource management
  • Improved type inference for the creation of Generics
  • Invocation of methods with varargs simplified
  • Improvements in numeric literals
  • Language Support for Collections
  • Language support for JSR 292

Let’s see in detail these features.

Switch to objects of type String

It will be possible to use the switch operator with objects of type String. This will avoid potential “if-then-else”. So this new feature would allow us to:

  String s = ...
  switch (s) {
   case "A1":
      processA1 (s);
      // And continue ...
 
    case "A2":
    case "A3":
      processA2A3 (s);
      break;
 
    case "A4"
       processA4 (s);
      // And continue ...
 
    default:
      processDefault (s);
      break;
  }

Automatic resource management

A “resource” is an object that must be closed manually, such as java.io.InputStream, OutputStream, Reader, Writer, Formatter;
java.nio.Channel; java.net.Socket; java.sql.Connection, Statement, ResultSet among others. These resources are usually open in a try block and close in a finally.

Recursos automatic management is a special form of the operator where you try one or more state resources. The scope of these resources is limited to the block. When the block ends, either normally or abruptly, all declared resources are automatically closed.

The main advantage is that it eliminates the need for manual closing, and it causes errors. Furthermore, it “prevents” the second exception (the close ()), always leaving the exception of the block that is usually more interesting.

An example usage would be:

 static String readFirstLineFromFile(String path) throws IOException {
 
        try (BufferedReader br = new BufferedReader(new FileReader(path)) {
 
           return br.readLine();
 
        }
 }

As we see, the try block () declares a resource, is then used within the block. When finished, it closes automatically. It is also possible to declare more than one resource:

try (InputStream in = new FileInputStream(src);
     OutputStream out = new FileOutputStream(destination)) {
 
            byte[] buf = new byte[8192];
            int n;
            while ((n = in.read(buf)) >= 0)
                out.write(buf, 0, n);
}

Improved type inference for the creation of Generics

This also includes the possibility to infer the types for instantiation using Generics. In cases parameterized types are obvious from the context, this parameter in the constructor can be omitted and replaced with an empty set <>.

For example, the following line:

 Map<String, List<String>> testmap = new HashMap<String, List<String>>();

can be replaced by:

Map<String, List<String> testmap = new HashMap<>();

Improvements in numeric literals

Just as we can declare decimal numeric literals, octal and hexadecimal literals now we can declare binary. This is very useful in certain areas. For this, use the prefix 0b, which is also the same compilers that use C / C + +, Ruby and Python. For example:

// A literal 'byte' 8-bit
byte wcByte = (byte)0b00100101;
 
// A literal 'short' 16-bit
short wcShort = (short)0b1010000101010101;
 
//  More literal 'int' of 32-bit 'int'
int wcInt1 = 0b10100001010001011010000101000101;
int wcInt2 = 0b101;

These variables are then used normally, for example:

class A2 {
public static void main(String[] args) {
    System.out.println("The decimal value of 10100101 is " + 0b10100101);
}

On the other hand, added the possibility to use an underscore (_) separator of numbers, to facilitate the reading of them. Thus, the compiler will ignore the character “_” when used in numeric literals. For example:

int numberOfTelephone = 757_757_7575;
long CreditCard = 1234_5678_9123_4567L;
long bundle = 777_77_7575L;
float money = 12_345_132.75;
long hexBytes = 0xFF_EC_AE_5E;
long hexWords = 0xFFEC_AE5E;
long maxLong = 0x7fff_ffff_ffff_ffffL;
long bytes = 0b11010010_01101001_10010101_10010010;

Language Support for Collections

It adds language support to treat like Arrays Collection.

For example, you can write the following to declare an immutable List:

final List wcDigits = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 9];

It will also be possible to access lists and maps using array syntax:

public class Main {
  public static void main(String[] arguments) {
    List wcArrayList = Arrays.asList(new String[] {"a","b","c"});
    String fristElement = wcArrayList[0]
 
    Map testmap = new HashMap(4);
    testmap[Integer.valueOf(1)] = "One";
}

Language support for JSR 292

This low-level change made minor changes to the Java language to be simpler to work with some features of the JVM. This will allow Java code to interoperate and / or implement libraries in other languages. That is, will ensure greater integration between Java and code in other languages. For more information read the proposal of support for JSR 292.

The 10 most important skills for future programmers

Sunday, September 6th, 2009

It is important to ensure that we are benefiting as much as possible when we invest time and effort to train and learn new things.

The following list will see the 10 we should learn skills that our curriculum is relevant for the next 5 years. This list is not complete and covers some niche markets (such as mainframes). However, if you learn at least seven items in this list you will not miss it.

1. One of the “Big 3″ (Java, . NET & PHP)

Barring a radical change in the world of development (such as an asteroid falling on Redmond), most developers will need to know any of the three major systems development: Java,. NET (VB.NET or C #) or PHP. Nor enough to know the main language. As projects grow and are grabbing more functionality, we will need to know the frameworks and libraries associated with depth.

2. Rich Internet Applications (RIA – Rich Internet Applications)

They can love or hate, but in recent years, Flash is being used for something other than funny animations. Flash also gained additional functionality in the form of Flex and AIR. Competitors of Flash, as JavaFX and Silverlight are also improving in performance. The browsers are improving their JavaScript engine, which is emerging as a web application platform. To make things more complicated, HTML 5 is going to incorporate lots of RIA functionality, including connection to the database, thus the formal seal of the W3C to AJAX. In the near future, have experience of RIA will be a determining factor in our curriculum.

3. Web Development

Web development will not disappear in the future. Many developers were happy so far ignored the web, or just staying with “the basics” that gave them their framework. But companies are demanding more and more to those who really know how to work with the underlying technologies. So we should improve our knowledge of JavaScript, CSS and HTML to succeed in the next five years.

4. Web Services

“REST or SOAP? JSON or XML? Although the election and the answers depend on the project, it is increasingly difficult to be a developer without having to consume Web Services (even if our development is not a Web application). Even the land area used to be ODBC, COM or RPC are now moving to Web services of some kind. Developers who can not work with Web services will end up relegated to maintenance on legacy code.

5. Human skills

There is a trend that has occurred some time ago: the increasing visibility of IT within and outside the organization. The developers are taking more and more meetings that are not development and process for obtaining feedback from them. For example, the CFO can not change the accounting rules without working with IT to update the system. And an operations manager can not change the process of call without IT center update the CRM work-flow. Similarly, customers often need to work directly with development teams to ensure their needs are met. Will it be necessary for all developers to consider how to win friends and influence people? No. But the developers that they will do will be much more valuable to their employers – and are highly sought after in the market.

6. A dynamic programming language and / or functional

Languages like Ruby, Python, F # and Groovy are not yet very popular – but so are the ideas behind them. For example, the LINQ system. NET is a direct descendant of functional programming techniques. Both Ruby and Python are becoming increasingly popular in some quarters, thanks to the Rails framework and Silverlight respectively. Learn one of these languages will not only improve our curriculum, but also will expand our horizon. All great developers recommend learning at least one dynamic or functional languages to make learning new ways of thinking.

7. Agile Methodologies

As time passes, the ideas behind Agile become more defined and better expressed. Many organizations are adopting Agile or proofs of concept for doing Agile. Although Agile is no silver bullet to avoid failure in a project definitely has its place in many projects. Developers who have experience in working and understanding Agile environments will be increasingly in demand in the next five years.

8. Domain Knowledge

Hand in hand with the agile methodologies, development teams are increasingly viewed partners in the project definition. This means that developers who understand the problem domain will be able to contribute to the project in a very visible and valuable. With Agile, a developer can say “From here, we can very easily add this functionality, and you get great value,” or “Hey, this requirement is not in keeping with the pattern of use that the logs show. No matter how many developers resist the idea of knowing anything about the problem domain, it is undeniable that more and more organizations prefer (if not even require) developers to at least understand the basics of the business.

9. “Hygiene” development

Until a few years ago, many (if not all) organizations had no access to bug tracking systems, version control and other tools, all developers are summarized and their preferred IDE. But thanks to the creation of new integrated development environments and the explosion of free software environments of high quality, since there are almost no organizations without these tools. Developers have to know much more than just do a checkout of the code. You need to have a rigorous hygiene habits to ensure they are properly coordinated with the team. The “solitary programmers” that keep everything local, non-document changes and others will not be welcome in traditional organizations, and will be aa directly out of place in Agile environments, where you use a strong coordination between equipment to operate.

10. Mobile Development

During the late 1990 web development grew and gained widespread adoption, so begin to displace traditional desktop applications. In 2008, development for mobile devices eventually took off, and over the next five years will grow steadily. Of course, there are several approaches to mobile development: web applications designed to run on mobile devices, RIAs aimed at this market, and applications that run directly on the devices. No matter what path we choose, we will serve add mobile development skills to our group.

FTP connection with JAVA

Tuesday, August 25th, 2009

Java again gives us another tool.

What is FTP?

FTP protocol that allows us to send or receive data from one point to another, be it a PC, server, or any other node that is connected to a network.

Usually when you have a web host these accounts have FTP congratulate sending files from our pc to the server that is hosting our site.

Investigating around I found a FTP client library very useful, I have tried it and going great. The library JvFTP Client provides interesting tasks, including:

  • Uploading / downloading files
  • Uploading directories recursively
  • Concurrent data transfer
  • Data transfer mode passive / active
  • Swing components to display directories
  • Components AWTpara display directories

This tool is available in jvftp and can be used in two ways, you run directly the jar, or do your own programming, including the libraries in your project.

If you want to program your own example here I leave a little guide on how you can do, let’s see …

… The first thing to do is incorporate the packages downloaded from jvftp in your project. Then you import the libraries to the class in which you make the connection:

import cz.dhl.io.*;
import cz.dhl.ftp.*;
import java.io.IOException;

Now we create the connection, the connection to prepare the data before creating access the FTP site. Let’s start with the server:

FtpConnect cn = FtpConnect.newConnect("ftp://ftp.domain.com");

ftp.domain.com value which is the server you are connecting. Each ftp account that include at least the server name, username and password. To log in using that account is something like this:

// Username
cn.setUserName("username");

// Password
cn.setPassWord("password");

Then it creates an object of type FTP, which is responsible for rendering all the information from our FTP site.

Ftp ftp1 = new Ftp();

Now the connection to the FTP site to begin processing the respective tasks

ftp1.connect(cn);

A practical example to test the connection would be to show the current directory with their files:

CoFile dir = new FtpFile(ftp1.pwd(), ftp1);

// Make a list of files that have the current directory
CoFile cfls[] = dir.listCoFiles();
if ( cfls != null )
        for (int n = 0; n < cfls.length; n++)
                    System.out.println( cfls[n].getName() + (cfls[n].isDirectory() ? "/" : ""));

Finally, there is only close the connection.

ftp1.disconnect();

Download jvftp

Happy Programming!!! ;-)

Print PDF with JPedal

Sunday, August 16th, 2009

Researching a bit about the handling of a PDF document I found a library called JPedal for manipulating PDF documents from Java.
Like other libraries I’ve seen among other iText and iReport, which are very comprehensive and allow you to do many tasks, including printing. Disadvantage that the latter is that you need to have installed Acrobat Reader and for many users this is not possible.
But even with JPedal lets you see the Acrobat Reader tools within the Java application, providing a task pane for the PDF to manipulate.

With PrinterJob.lookupPrintServices can get the services available and print them PrinterJob a concrete one.

PrintService[] psService = PrinterJob.lookupPrintServices();
PrinterJob pjPrintJob = PrinterJob.getPrinterJob();
pjPrintJob.setPrintService(psService[0]);

// Assigns the size of the paper to A4.

Paper paper = new Paper();
paper.setSize(595, 842);
paper.setImageableArea(0, 0, 595, 842);
PageFormat pf = pjPrintJob.defaultPage();
pf.setPaper(paper);

Loads the PDF to be printed. The file is called wc_PDF.pdf printed and given format.

PdfDecoder pdfD = null;
pdfD = new PdfDecoder(true);
pdfD.openPdfFile("wc_PDF.pdf");
pdfD.setPageFormat(pf);

It sends the file to print

printJob.setPageable(pdfD);
printJob.print();

And to finalize the document is closed.

pdf.closePdfFile();

Download JPedal..

The example would then complete as follows:

import java.awt.print.Paper;
import java.awt.print.PrinterJob;
import java.awt.print.PageFormat;
import javax.print.PrintService;
import org.jpedal.PdfDecoder;

public final void wc_PrintPDF() {
    PdfDecoder pdfD = null;
    try {
        PrintService[] psService = PrinterJob.lookupPrintServices();
        PrinterJob pjPrintJob = PrinterJob.getPrinterJob();
        pjPrintJob.setPrintService(psService[0]);

        Paper paper = new Paper();
        paper.setSize(595, 842);
        paper.setImageableArea(0, 0, 595, 842);
        PageFormat pf = pjPrintJob.defaultPage();
        pf.setPaper(paper);

        pdfD = new PdfDecoder(true);
        pdfD.openPdfFile("wc_PDF.pdf");
        pdfD.setPageFormat(pf);

        pjPrintJob.setPageable(pdfD);
        pjPrintJob.print();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        pdfD.closePdfFile();
    }
}

Java: Get the IP address of a website.

Monday, May 25th, 2009

Trouble

You need to get the IP address of a website using your domain name.

Solution

Use the method InetAddress.getByName(String host) to library java.net.InetAddress

Code

/**
 *
 * @author VenuThomas
 */
import java.net.InetAddress;
import java.net.UnknownHostException;

public class Main {

 /**
 * @param args the command line arguments
 */
 public static void main(String[] args) {
 // TODO code application logic here
 try {
 InetAddress address = InetAddress.getByName("www.google.com");

 // Output: www.google.com/74.125.45.100
 System.out.println(address);

 } catch (UnknownHostException e) {
 System.out.println("Could not find www.google.com");
 }
 }
}

Java: Change To Uppercase/Lowercase A String

Monday, May 25th, 2009

Trouble

Looking for a change to case-insensitive string.

Solution

Use the methods toUpperCase() or toLowerCase() of class String

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

// define the string
String cad = "Welcome to WiseCodes.Com";

// string to uppercase
// OUTPUT: WELCOME TO WISECODES.COM ...
String cad_uppr = cad.toUpperCase();
System.out.println(cad_uppr);

// string to lowercase
// OUTPUT: welcome to wisecodes.com ...
String cad_lowr = cad.toLowerCase();
System.out.println(cad_lowr);

}
}

Develop JavaFX Application And Win!!

Monday, March 23rd, 2009

Develop an application in JavaFX and win cool prizes !!
Compete in JavaFX  coding by “JavaFX Coding Challenge”  The deadline is May 29.

  • 1st Place: $25,000
  • 2nd Place: $10,000
  • 3rd Place: $5,000

Student category: Three prizes at $1,500 each to the top three applications submitted by students

Deadlines

  • Contest starts: March 23rd, 2009
  • Contest deadline: May 29th, 2009
  • Judging period: June 1st – June 29th, 2009
  • Winners announced: Week of June 29th, 2009

Click Here.. http://javafx.com/challenge/

Validate: Username, Email Id, Phone No, Zip Code & URL In 5 Languages(JS, C#.Net, VB.Net, JAVA & PHP)

Monday, March 23rd, 2009

Validate of Username, Email Id, Phone No, Zip/Postal Code & URL In Javascript, C#.Net, VB.Net, JAVA & PHP !

1. Validate username: Validate alpha numeric values
2. Validate email addresses : example@domain.com
3. Validate Phone numbers: Validate US phone number eg: 123-456-7890
4. Validate Zip/Postal Codes: Validate US Zip/Postal Code eg: 12345-6789
5. Validate Domain Name eg: http://live.com

Validate username: Validate alpha numeric values

?View Code JAVASCRIPT
function is_valid_username(str_username)
{
 var filter = /^([a-zA-Z\s0-9]*)$/;
 if (!filter.test(str_username))
 {
 alert(’Wrong username format.’);
 }
 else
 {
 alert('Username format is ok.')
 }
 return false;
}
?View Code CSHARP
 using System.Text.RegularExpressions;
 
 private void is_valid_username(string str_username)
 {
 Regex matchRegex = new Regex(@"^[a-zA-Z0-9_]{3,16}$");
 MatchCollection matches  = matchRegex.Matches(str_username);
 if(matches.Count==0)
 {
 Response.Write("Wrong username format."); // In Webserver
 //MessageBox.Show("Wrong username format."); //In Windows Form
 }
 else
 {
 Response.Write("Username format is ok."); // In Webserver
 //MessageBox.Show("Username format is ok."); //In Windows Form
 }
 }
Imports System.Text.RegularExpressions
 
Private Sub is_valid_username(ByVal str_username As String)
    Dim matchRegex As New Regex("^[a-zA-Z0-9_]{3,16}$")
    Dim matches As MatchCollection = matchRegex.Matches(str_username)
    If matches.Count = 0 Then
        Response.Write("Wrong username format.") ' In Webserver
        'MessageBox.Show("Wrong username format."); 'In Windows Form
    Else
        Response.Write("Username format is ok.")    ' In Webserver
        'MessageBox.Show("Username format is ok."); 'In Windows Form
    End If
End Sub
import java.util.regex.*;
 
public class is_valid_username
{
 public static void main(String str_username)
 {
 Pattern p=Pattern.compile("^[A-Za-z0-9]+$");
 Matcher m=p.matcher(str_username);
 boolean matchFound = m.matches();
 if(matchFound)
 {
 System.out.println("Username format is ok.");
 }
 else
 {
 System.out.println("Wrong username format.");
 }
 }
}
Function is_valid_username($str_username)
{
 if (preg_match('/^[a-z\d_]{5,20}$/i',$str_username))
 {
     echo "Username format is ok.";
 }
 else
 {
     echo "Wrong username format.";
 }
}

Validate email addresses : example@domain.com

?View Code JAVASCRIPT
function is_valid_email(str_email_id)
{
 var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
 if (!filter.test(str_email_id))
 {
 alert(’Wrong email address format.’);
 }
 else
 {
 alert('Email address format is ok.')
 }
 return false;
}
?View Code CSHARP
 using System.Text.RegularExpressions;
 private void is_valid_email(string email_id)
 {
 Regex matchRegex = new Regex(@"[a-zA-Z0-9_\-\.]+@[a-zA-Z0-9_\-\.]+\.[a-zA-Z]{2,5}");
 MatchCollection matches  = matchRegex.Matches(email_id);
 if(matches.Count==0)
 {
 Response.Write("Wrong email address format."); // In Webserver
 //MessageBox.Show("Wrong email address format."); //In Windows Form
 }
 else
 {
 Response.Write("Email address format is ok."); // In Webserver
 //MessageBox.Show("Email address format is ok."); //In Windows Form
 }
 }
Imports System.Text.RegularExpressions
 
Private Sub is_valid_email(ByVal email_id As String)
    Dim matchRegex As New Regex("[a-zA-Z0-9_\-\.]+@[a-zA-Z0-9_\-\.]+\.[a-zA-Z]{2,5}")
    Dim matches As MatchCollection = matchRegex.Matches(email_id)
    If matches.Count = 0 Then
        Response.Write("Wrong email address format.") ' In Webserver
        'MessageBox.Show("Wrong email address format."); 'In Windows Form
    Else
        Response.Write("Email address format is ok.")    ' In Webserver
        'MessageBox.Show("Email address format is ok."); 'In Windows Form
    End If
End Sub
import java.util.regex.*;
public class is_valid_email
{
 public static void main(String str_email_id)
 {
 Pattern p=Pattern.compile("[a-zA-Z]*[0-9]*@[a-zA-Z]*.[a-zA-Z]*");
 Matcher m=p.matcher(str_email_id);
 boolean matchFound = m.matches();
 if(matchFound)
 {
 System.out.println("Email address format is ok.");
 }
 else
 {
 System.out.println("Wrong email address format.");
 }
 }
}
Function is_valid_email($email_id)
{
 if (preg_match('/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/',$email_id))
 {
     echo "Email address format is ok.";
 }
 else
 {
     echo "Wrong email address format.";
 }
}

Validate Phone numbers: Validate US phone number eg: 123-456-7890

?View Code JAVASCRIPT
function is_valid_phone_no(str_phone_no)
{
 var filter =  /^((\+?1-)?\d\d\d-)?\d\d\d-\d\d\d\d$/;
 if (!filter.test(str_phone_no))
 {
 alert(’Wrong phone number format.’);
 }
 else
 {
 alert('Phone number format is ok.')
 }
 return false;
}
?View Code CSHARP
 using System.Text.RegularExpressions;
 
 private void is_valid_phone_no(string str_phone_no)
 {
 Regex matchRegex = new Regex(@"\d{3}-\d{3}-\d{4}$");
 MatchCollection matches  = matchRegex.Matches(str_phone_no);
 if(matches.Count==0)
 {
 Response.Write("Wrong phone number format."); // In Webserver
 //MessageBox.Show("Wrong phone number format."); //In Windows Form
 }
 else
 {
 Response.Write("Phone number format is ok."); // In Webserver
 //MessageBox.Show("Phone number format is ok."); //In Windows Form
 }
 }
Imports System.Text.RegularExpressions
Private Sub is_valid_phone_no(ByVal str_phone_no As String)
    Dim matchRegex As New Regex("\d{3}-\d{3}-\d{4}$")
    Dim matches As MatchCollection = matchRegex.Matches(str_phone_no)
    If matches.Count = 0 Then
        Response.Write("Wrong phone number format.") ' In Webserver
        'MessageBox.Show("Wrong phone number format."); 'In Windows Form
    Else
        Response.Write("Phone number format is ok.")    ' In Webserver
        'MessageBox.Show("Phone number format is ok."); 'In Windows Form
    End If
End Sub
import java.util.regex.*;
public class is_valid_phone_no
{
 public static void main(String str_phone_no)
 {
 Pattern p=Pattern.compile("^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$");
 Matcher m=p.matcher(str_phone_no);
 boolean matchFound = m.matches();
 if(matchFound)
 {
 System.out.println("Phone number format is ok.");
 }
 else
 {
 System.out.println("Wrong phone number format.");
 }
 }
}
Function is_valid_phone_no($str_phone_no)
{
 if (preg_match('/\(?\d{3}\)?[-\s.]?\d{3}[-\s.]\d{4}/x',$str_phone_no))
 {
     echo "Phone number format is ok.";
 }
 else
 {
     echo "Wrong phone number format.";
 }
}

Validate Zip/Postal Codes: Validate US Zip/Postal Code eg: 12345-6789

?View Code JAVASCRIPT
function is_valid_zip_code(str_zip_code)
{
 var filter =  /^\d\d\d\d\d-\d\d\d\d$/;
 if (!filter.test(str_zip_code))
 {
 alert(’Wrong Zip/Postal Code format.’);
 }
 else
 {
 alert('Zip/Postal Code format is ok.')
 }
 return false;
}
?View Code CSHARP
 using System.Text.RegularExpressions;
 
 private void is_valid_zip_code(string str_zip_code)
 {
 Regex matchRegex = new Regex(@"\d{5}-\d{4}$");
 MatchCollection matches  = matchRegex.Matches(str_zip_code);
 if(matches.Count==0)
 {
 Response.Write("Wrong Zip/Postal Code format."); // In Webserver
 //MessageBox.Show("Wrong Zip/Postal Code format."); //In Windows Form
 }
 else
 {
 Response.Write("Zip/Postal Code format is ok."); // In Webserver
 //MessageBox.Show("Zip/Postal Code format is ok."); //In Windows Form
 }
 }
Imports System.Text.RegularExpressions
Private Sub is_valid_zip_code(ByVal str_zip_code As String)
    Dim matchRegex As New Regex("\d{5}-\d{4}$")
    Dim matches As MatchCollection = matchRegex.Matches(str_zip_code)
    If matches.Count = 0 Then
        Response.Write("Wrong Zip/Postal Code format.") ' In Webserver
        'MessageBox.Show("Wrong Zip/Postal Code format."); 'In Windows Form
    Else
        Response.Write("Zip/Postal Code format is ok.")    ' In Webserver
        'MessageBox.Show("Zip/Postal Code format is ok."); 'In Windows Form
    End If
End Sub
import java.util.regex.*;
public class is_valid_zip_code
{
 public static void main(String str_zip_code)
 {
 Pattern p=Pattern.compile("^(\\d{5})[- ]?(\\d{4})$");
 Matcher m=p.matcher(str_zip_code);
 boolean matchFound = m.matches();
if(matchFound)
 {
 System.out.println("Zip/Postal Code format is ok.");
 }
 else
 {
 System.out.println("Wrong Zip/Postal Code format.");
 }
 }
}
Function is_valid_zip_code($str_zip_code)
{
 if (preg_match('/^([0-9]{5})(-[0-9]{4})?$/i',$str_zip_code))
{
     echo "Zip/Postal Code format is ok.";
 }
 else
 {
     echo "Wrong Zip/Postal Code format.";
 }
}

Validate Domain Name eg: http://live.com

?View Code JAVASCRIPT
function is_valid_url(str_url)
{
 var filter =   /^(ht|f)tps?:\/\/[a-z0-9-\.]+\.[a-z]{2,4}\/?([^\s&lt;&gt;\#%"\,\{\}\\|\\\^\[\]`]+)?$/
 if (!filter.test(str_url))
 {
 alert(’Wrong URL format.’);
 }
 else
 {
 alert('URL format is ok.')
 }
 return false;
}
?View Code CSHARP
 using System.Text.RegularExpressions;
 private void is_valid_url(string str_url)
 {
Regex matchRegex = new Regex(@"(http|https)://([\w-]+\.)+[\w-]+(/[\w- ./?%&amp;=]*)?");
 MatchCollection matches  = matchRegex.Matches(str_url);
 if(matches.Count==0)
 {
 Response.Write("Wrong URL format."); // In Webserver
 //MessageBox.Show("Wrong URL format."); //In Windows Form
 }
 else
 {
 Response.Write("URL format is ok."); // In Webserver
 //MessageBox.Show("URL format is ok."); //In Windows Form
 }
 }
Imports System.Text.RegularExpressions
 
Private Sub is_valid_url(ByVal str_url As String)
    Dim matchRegex As New Regex("(http|https)://([\w-]+\.)+[\w-]+(/[\w- ./?%&amp;=]*)?")
    Dim matches As MatchCollection = matchRegex.Matches(str_url)
    If matches.Count = 0 Then
        Response.Write("Wrong URL format.") ' In Webserver
        'MessageBox.Show("Wrong URL format."); 'In Windows Form
    Else
        Response.Write("URL format is ok.")    ' In Webserver
        'MessageBox.Show("URL format is ok."); 'In Windows Form
    End If
End Sub
import java.util.regex.*;
public class is_valid_url
{
 public static void main(String str_url)
 {
 Pattern p=Pattern.compile("(http|https)://([\w-]+\.)+[\w-]+(/[\w- ./?%&amp;=]*)?");
 Matcher m=p.matcher(str_url);
 boolean matchFound = m.matches();
 if(matchFound)
 {
 System.out.println("URL format is ok.");
 }
 else
 {
 System.out.println("Wrong URL format.");
 }
 }
}
Function is_valid_url($str_url)
{
 if (preg_match('/^([0-9]{5})(-[0-9]{4})?$/i',$str_url))
 {
     echo "URL format is ok.";
 }
 else
 {
     echo "Wrong URL format.";
 }
}

Mobile-enabled “JavaFX SDK 1.1″

Sunday, March 8th, 2009

Read My Perv Post: The First & Basic Overview Of JavaFX

Sun Microsystems is 12 February 2009, the development environment for mobile RIA “JavaFX Mobile” released, RIA-enhanced strategies. JavaFX’s Web site, available for download.

JavaFX is a scripting language “JavaFX Script”, runtime environment. Drag the Web GUI and functionality of desktop applications and browser features, such as the ability to drop, to develop interactive Web applications. JavaFX Mobile is a mobile version.

Sun has released the “JavaFX 1.1 SDK”, the emulator “JavaFX Mobile Emulator”, including the latest version of JavaFX, JavaFX Mobile was fully supported. Developers are using it, “Java Platform Micro Edition (Java ME)” for mobile devices that operate in RIA development.

According to Sun, the world’s 26 million mobile phones which support Java, Java is a leading mobile platform. Sun’s Java RIA strategy aims to capitalize on a wide range of technology diffusion.

The Sun, JavaFX Mobile announcement and the UK Sony Ericsson, LG Electronics and Korean cell phone manufacturers and carriers such as JavaFX Moile has also said it is cooperating with the phone.

Sun Microsystems Inc.
http://www.sun.com

“JavaFX 1.1 SDK” download
http://www.javafx.com/

The First & Basic Overview Of JavaFX

Sunday, March 8th, 2009

December 2008, finally has been released JavaFX. Since 2007, it was announced at JavaOne a half years, Therefore, this release of JavaFX 1.0 was based on a series of intensive short-term and explains the JavaFX.

What is JavaFX

JavaFX is Sun Microsystems (Sun following the notation) is a new platform for rich client provides. Java is in the name, Java is platform independent. However, technology is a Java-based.
JavaFX development are done in open source. The java.net project in OpenJFX, OpenJFX-Compiler project & SceneGraph is being vigorously developed in the project. However, at present does not seem to have been the source of all.
JavaFX, 2007 in San Francisco was announced at JavaOne. Initially, RIA (Rich Internet Application) is used for the side, RIA can build not just a different user interface. For example, Java’s Swing GUI’s API is only part of the application that was created using JavaFX build, it is possible.
As described above for the Java JavaFX is built on technology, Java is well and good, Java API diversity can be used seamlessly.

JavaFX area covered by

JavaFX is a desktop PC application that operates not only cover various areas including mobile phones. JavaFX will run on Java VM. The Java VM as well as Java SE, Java ME in the CLDC (Connected Limited Device Configuration) and CDC (Connected Device Configuration) you can run. Therefore, mobile phones and smart phones, set-top box and can run JavaFX. In addition, Blu-ray players are employed by the CDC based on the BD-J, JavaFX will cover the area. CLDC does not adopt the Google Android, but the 2008 JavaOne JavaFX demo was run.
Which covers various areas such JavaFX is, in each region, in a different way of creating applications. The specific language of the script to build the user interface was developed in JavaFX Script. Using JavaFX Script, Java was once boasts the “Write Once, Run Anywhere” are able to achieve again.

JavaFX development history

JavaFX is original, SeeBeyond’s Christopher Oliver was started as a personal project of his. JavaFX is not at that time, Form Follows Function (F3) was named.
The Sun in September 2005, it acquired SeeBeyond, F3 is now Sun’s technology assets. Later, Oliver says, established in 2006 to 11 blogs, then F3 is released. Then F3 is the Java SE and Java 2D and Swing to depend on and could not work only on your desktop. However, in embedded applications in a mobile phone F3 to make this work is important. So the strategy was adopted, JavaSE was acquired companies. This is just before JavaOne 2007, and 2007 will be the month.
Usually, the phone will work CLDC, JavaSE phone company for the CDC had been developed. The CDC JSR 209 Advanced Graphics and User Interface Optional Package for the J2ME Platform with Swing and Java 2D can run. Therefore, CDC and JSR 209 for embedded applications based on JavaFX was established.
And, JavaOne 2007 in F3 is JavaFX is renamed and a major announcement was that.
JavaOne 2007 in F3 and was originally organized the session, but that did not receive much attention.
Immediately after the announcement at JavaOne, OpenJFX project is started in the JavaFX SDK was released.
Were published during this operation was in JavaFX interpreter. In other words, the interpretation of the script at startup, Java transformation classes, was the flow of work to compile from. This is a drawback that would start a long time there.
Therefore, prior to the compilation was done at every boot, the system was adopted by the compiler. To develop a compiler OpenJFX-Compiler project was launched in 2007, also GUI components SceneGraph is being developed in the project. The JavaFX Desktop for desktop of the year’s preview of the SDK was released in July. Of course, is to work on a compiler.
And December 4, JavaFX Desktop 1.0, including the JavaFX SDK 1.0 has been released. In addition, JavaFX SDK for applications built with JavaFX Mobile is also included in the beta.
The 2007 version of the compiler and interpreter version was published in the grammar and API has been changed, and many other areas. Also, Preview SDK and some API in the official version so you must be careful to change. For these changes is summarized in the Appendix at the end of this series, please do help.

NetBeans Installation

JavaFX is the Web site of the following three tools can be downloaded as a single package.

  • NetBeans IDE 6.5 for JavaFX 1.1 (NetBeans JavaFX to be incorporated into a plug-in development)
  • JavaFX 1.1 Production Suite (Plugin for Adobe Illustrator and Photoshop )
  • JavaFX 1.1 SDK (command line tools)

JavaFX
JavaFX download page

Here, NetBeans IDE 6.5 for JavaFX 1.0 using JavaFX about how to develop applications. NetBeans IDE 6.5 for JavaFX is JavaFX in the NetBeans Web site or the Web allows people to download the installer from the site. The already installed NetBeans can be installed via the Update Center.

Introduction to JavaFX Script

Actually using JavaFX NetBeans So let’s look at the steps of application development. First Project Creation Wizard “JavaFX Script Application”, choose to create a project.

Project Creation Wizard
Project Creation Wizard

Project was created
Project was created

Project was to create a simple JavaFX Script is Main.fx are included. It is particularly difficult at first just to see what you think.

package thecoders_javafxapp3;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.text.Text;
import javafx.scene.text.Font;
 
Stage {
title: "Application title"
width: 250
height: 80
scene: Scene {
content: Text {
font : Font {
size : 16
}
x: 10, y: 30
content: "Application content"
}
}
}

JavaFX Script is a window corresponding to the stage (Stage) have a concept. Also, in a single stage multiple scenes (Scene) can be defined. Around this concept is similar to Flex. In addition, the Java syntax is very different, it can be defined using a notation declared in the user interface.
To debug JavaFX applications will run the project, right-click “Run Project” or selected, click the button on the toolbar. NetBeans project has a main idea, you can only run from the toolbar is set to project the main project. If you want to change the main project from the project right-click menu “Set as Main Project” is set to project the main project if you choose.

JavaFX should be created immediately after the window appears as follows: When you run the project. Output in Web Click here..

JavaFX

JavaFX project was performed

JavaFX Script Editor Features

NetBeans is the JavaFX Script Editor features such as input completion and error checking script.

javafx_06

JavaFX Script code completion
The palettes that are located on the right side of the editor area drag to paste code snippets to the editor by drop. Snippets that are registered in the palette is a simple thing, JavaFX to know and control will be available in a good clue.

Palette
Palette

JavaFX event handling

As an example, with event handling and let’s create a simple JavaFX application. Creating the application of the following would change the color and the mouse to the area of the rectangle overlap. In Web Click here..

javafx_08

Mouse Over

javafx_09
Creating sample application

Source code is as follows. Rectangle is a rectangle shape to draw, onMouseEntered onMouseExited when overlapped and the shape of mouse, which describes the process to change the background color when off.

import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.text.Text;
import javafx.scene.text.Font;
import javafx.scene.shape.*;
import javafx.scene.paint.*;
import javafx.scene.input.*;
/**
* @author VenuThomas
*/
 
Stage {
title: "Sample Program"
scene: Scene {
width: 350
height: 175
content:[
Rectangle {
x: 50
y: 50
width: 250
height: 55
fill: Color.BLACK
onMouseEntered: function( e: MouseEvent ):Void { var rect: Rectangle = e.node as Rectangle;
rect.fill = Color.BLUE
}
onMouseExited: function( e: MouseEvent ):Void { var rect: Rectangle = e.node as Rectangle ;
rect.fill = Color.BLACK
}
 
}
Text {
font: Font {
size: 20
name: "Monospaced"
}
x: 60,
y: 85
fill: Color.WHITE
content: bind "code.venuthomas.net"
}
]
}

There are many benefits and challenges of new technology

RIA platform and Microsoft’s Silverlight and Adobe’s AIR, which is crammed with powerful competitive platform, JavaFX and whether it is the mainstream is unclear. JavaFX is based on Java platform, but have to learn the new JavaFX Script must have the tools and the development is still far and have the disadvantage in comparison to other competing technologies.
But JavaFX rich in Java can take advantage of existing assets, JavaVM and reliability by running on a Java platform many unique advantages. Also, NetBeans plugin for JavaFX, but there is room for much improvement in terms of function, which is open-source development tools, that can get a free development environment for developers and benefits might be true.
JavaFX is still 1.1 has just been released. I look to the future trends.

Sun Microsystems Inc.
http://www.sun.com

“JavaFX 1.1 SDK” download
http://www.javafx.com/