Checking the last-modified date of a URL file

The getLastModified() Method in the URLConnection connection class allows you to get the Last modified date.

It can be done in the following manner:

...
        String urlpath = new String("http://www.esus.com/respondquestionexample.html");
	url = new URL(urlpath);
	connection = url.openConnection();
        connection.connect();
        System.out.println(urlpath+ " was last modified on "+ new java.util.Date(connection.getLastModified()));
...

The getLastModified() method returns a long value, the number of seconds since the start of the epoch( 1970 ) till the modified date. The output for the above url was “Last Modified on Thu Apr 19 03:01:25 GMT+05:30 2001″

When to use UDP sockets

TCP sockets are connection-oriented and reliable sockets i.e they make sure for data to be successfully transmitted to destination, so if u want to transfer files or some imp. data u need to do it thru TCP

on the contrary, UDP sockets are connection less i.e. data divided into packets can transfer to dest. via any of valid routes and as no acknowledgement is required from destn. it is unreliable data transfer mode so if you are transferring lee useful data like some voice rec. or video streams u can use it.

Creating a digital certificate with keytool

Look at the command-line options of keytool.

For example, to create a public/private key pair and store it in the default keystore (in my case C:Windows.keystore) under the alias mykey:

C:> keytool -genkey -keyalg RSA -alias mykey
Enter keystore password:  esuspass
keytool error: Key pair not generated, alias <mykey> already exists

C:>keytool -genkey -keyalg RSA -alias esuskey
Enter keystore password:  esuspass
What is your first and last name?
  [Unknown]:  Joris Van den Bogaert
What is the name of your organizational unit?
  [Unknown]:  Esus Team
What is the name of your organization?
  [Unknown]:  Esus, Inc.
What is the name of your City or Locality?
  [Unknown]:  Meerbeek
What is the name of your State or Province?
  [Unknown]:
What is the two-letter country code for this unit?
  [Unknown]:  BE
Is <CN=Joris Van den Bogaert, OU=Esus Team, O="Esus, Inc.", L=Meerbeek, ST=Unkno
wn, C=BE> correct?
  [no]:  yes

Encrypting/decrypting a message using a symmetric encryption method (eg. DES)

Eric Young has written an implementation of DES. Here are the source files:

Des.java
DesCrypt.java
DesKey.java
Int32Manipulator.java

The Des.java file has been slightly modified (added a memset method to ensure 8 bytes are used for the key).

Here’s an example on how to use these classes:

public class Main
{
   public static void main(String []args) {
      // key (8 bytes) 
      String key = "12345678";
 
      // encrypt using Eric Young's DES Java implementation
      byte[] de = Des.encrypt(key, "Esus.com, aiming to provide the largest Java directory on the web");
 
      // decrypt 
      String s = Des.decrypt(key, de);
      System.out.println(s);
   }
}

Encrypting/decrypting a message using an assymetric encryption method (eg. RSA)

The following code demonstrates using a pair of RSA public/private key pairs to secure a message between a producer and a consumer. It also generates and validates a signature along the way since that is another common task.
AsymetricTest.java:

import org.bouncycastle.jce.provider.BouncyCastleProvider;
 
import java.security.*;
import javax.crypto.*;
 
public class AsymetricTest {
 
    // these algorithms need to work together!
    public static String keyAlgorithm = "RSA" ;
    public static String cipherAlgorithm = "RSA/OAEP" ;
    public static String signatureAlgorithm = "SHA1WithRSAEncryption" ;
 
    static public void main(String[] args) {
	String testData = "Hugh, and only Hugh, can prevent florist friars." ;
 
	try {
	    // make sure the BC provider is registered.
	    Security.addProvider(new BouncyCastleProvider());
 
	    /***
	     * Generate two pairs of keys, one for the producer
	     * and one for the consumer.
	     ***/
	    KeyPairGenerator gen = KeyPairGenerator.getInstance(keyAlgorithm, "BC");
	    gen.initialize(1024, new SecureRandom());
 
	    System.out.println("Generating keys . . .") ;
	    KeyPair producerPair = gen.generateKeyPair();
	    KeyPair consumerPair = gen.generateKeyPair();
	    System.out.println("Generated keys, proceeding") ;
 
	    /***
	     * first on the producer side: encrypt and sign the
	     * original data.  The producer knows the consumer public key.
	     ***/
 
	    // encrypt the testData using the public key
	    byte[] encryptedData = encrypt(testData.getBytes(), consumerPair.getPublic()) ;
 	    
	    System.out.println("Encrypted byte count: " + encryptedData.length) ;
 
	    // generate a digital signature
	    byte[] dataSignature = generateSignature(testData, producerPair.getPrivate()) ;
 
	    System.out.println("Signature created, bytes: " + dataSignature.length) ;
 
	    /***
	     * uncomment one of these lines to befoul either the
	     * encrypted data or the signature "in transit" if you want
	     * to see a failure in the next steps.
	     ***/
	    //encryptedData[8] = 0 ;
	    //dataSignature[8] = 0 ;
 	    
	    /***
	     * and now on the consumer side: decrypt the original data,
	     * then use that result to validate the signature.  The
	     * consumer knows the producer's public key.
	     ***/
 
	    // decrypt the message using the private key
	    byte[] receivedData = decrypt(encryptedData, consumerPair.getPrivate()) ;
	    System.out.println("Data decoded, byte count: " + receivedData.length) ;
	    System.out.println("[" + new String(receivedData) + "]") ;
 
	    // and validate the signature
	    if ( ! validateSignature(receivedData, dataSignature, producerPair.getPublic()) ) {
		throw new SignatureException("Signature validation failed") ;
		}
 
	    System.out.println("Signature OK.") ;
	    }
	catch ( Exception ex ) {
	    ex.printStackTrace() ;
	    }
 	    
	System.exit(0);
	}

    public static byte[] encrypt(byte[] toEncrypt, PublicKey key)
				    throws GeneralSecurityException {
	Cipher cipher = Cipher.getInstance(cipherAlgorithm) ;
	cipher.init(Cipher.ENCRYPT_MODE, key) ;
 
	byte[] result = cipher.doFinal(toEncrypt) ;
	return result ;
    }

    public static byte[] decrypt(byte[] toDecrypt, PrivateKey key)
				    throws GeneralSecurityException {
	Cipher deCipher = Cipher.getInstance(cipherAlgorithm) ;
	deCipher.init(Cipher.DECRYPT_MODE, key) ;
 
	deCipher.update(toDecrypt) ;
 
	byte[] result = deCipher.doFinal() ;
	return result ;
    }

    public static byte[] generateSignature(String toSign, PrivateKey key)
				    throws GeneralSecurityException {
	Signature genSig = Signature.getInstance(signatureAlgorithm) ;
	genSig.initSign(key) ;
 
	genSig.update(toSign.getBytes()) ;
 
	byte[] result = genSig.sign() ;
	return result ;
    }

    public static boolean validateSignature(byte[] dataToValidate, byte[] sigToValidate, PublicKey key)
				    throws GeneralSecurityException {
	Signature valSig = Signature.getInstance(signatureAlgorithm) ;
	valSig.initVerify(key) ;
 
	valSig.update(dataToValidate) ;
 
	return valSig.verify(sigToValidate) ;
	}
    }

(tested with the BouncyCastle JCE provider, http://www.bouncycastle.org)

Find out the decimal symbol separator for a particular locale

The class DecimalFormatSymbols contains localized date-time formatting info such as the names of the months, names of weekdays, etc. and also separators like decimal symbol and grouping separator. Look at the API for more information.

Main.java:

import java.text.*;
import java.util.*; 
     
public class Main {
   public static void main(String args[]) {
      DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.US);
      System.out.println(dfs.getDecimalSeparator());
 
      dfs = new DecimalFormatSymbols(Locale.FRENCH);
      System.out.println(dfs.getDecimalSeparator());
   }
}

outputs:

.
,

Get the weekday of a date in Java

Main.java:

import java.util.*;
 
public class Main
{
   public static void main(String []args) {
      String[] days = { "", "Sunday", "Monday", "Tuesday", 
                        "Wednesday", "Thursday", "Friday", "Saturday" };
 
      Calendar cal = Calendar.getInstance();
      cal.setTime(new Date());
      int dayOfWeek  = cal.get(Calendar.DAY_OF_WEEK);
      System.out.println(days[dayOfWeek]);
   }
}

Reading resources from a JAR file

For this example, create the following directory structure:

   myresources
       |
       --- text
       |    |
       |    --- <a href="http://www.esus.com/example.txt">example.txt</a>
       |
       --- image
            |
            --- <a href="http://www.esus.com/images/djkrush.jpg">djkrush.jpg</a>

Create a manifest file to specify the class that contains the main method.

mymanifest:

Main-Class: Main
 

(notice the extra carriage-return!)

Main.java:

import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.net.*;
import java.io.*;
   
public class Main {
   public static void main(String[] args) throws Exception {
      Image img = getImageFileFromJar("myresources/images/djkrush.jpg");
      String txt = getTxtFileFromJar("myresources/text/example.txt");
 
      System.out.println("img = " + img + "n");
      System.out.println("txt = ");
      System.out.println(txt);
 
      System.exit(0);
   }
 
   public static Image getImageFileFromJar(String file) throws Exception {
      URL url = Main.class.getResource(file);
 
      return new ImageIcon(url).getImage();
   }
 
   public static String getTxtFileFromJar(String file) throws Exception {
      InputStream in = Main.class.getResourceAsStream(file);
   
      BufferedReader br =new BufferedReader(new InputStreamReader(in));
      String line;
  
      StringBuffer sb = new StringBuffer();    
      while((line = br.readLine()) !=null) {
        sb.append(line + "rn");
      }
 
      return sb.toString();
   }
}

jar everything up:

   jar cmfv mymanifest res.jar myresources Main.class

run:

   java -jar res.jar

output:

img = sun.awt.windows.WImage@c4b3fd8b
 
txt = 
It is, in fact, nothing short of a miracle that the modern methods 
of instruction have not yet entirely strangled the holy curiosity 
of inquiry; for this delicate little plant, aside from stimulation, 
stands mainly in need of freedom; without this it goes to wrack and 
ruin without fail. It is a very grave mistake to think that the 
enjoyment of seeing and searching can promoted by means of coercion 
and sense of duty. To the contrary, I believe that it would be 
possible to rob even a healthy beast of prey of its voraciousness, 
if it were possible, with the aid of a whip, to force the beast to 
devour continuously, even when not hungry,especiallyif the food, 
handed out under such coercion, were to be selected accordingly. 
 
Albert Einstein 

Get started with the Java Preferences API

The Preferences API, introduced in JDK1.4, allows you to save and retrieve user and system configuration data. What you typically would do before was to save this configuration data in an XML, INI or Properties file in a specified directory known to your application. When you use the preferences API, you don’t care where this data is located. On a Windows machine, it’ll be saved in the registry, even though it is subject to change in future releases. On linux, files will be used to save your preferences (/etc/.java/.systemPrefs for system preferences and USERHOME/.java/.userPrefs for user preferences).

The Preferences API is very simple to use. Instantiate a Preferences object and use the method put to save a key, value pair. With get you can retrieve the values, even with another VM. The API uses the packagename to differentiate between preferences of different applications.

Here’s an example where you can set some preferences. When it starts up, it fills up the fields according to their values in the backing store.

comesusexamplespreferencesMain.java:

package com.esus.examples.preferences;
 
import javax.swing.border.*;
import java.util.prefs.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame 
{
   Preferences preferences;
 
   public static final String APPLICATIONPATH = "applicationpath";
   public static final String USERFONT        = "userfont";
   public static final String LASTUSERLOGIN   = "lastuserlogin";
   public static final String LDAPURL         = "ldapurl";
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      loadPreferences();
 
      JLabel appPathLabel       = new JLabel("Application Path:");
      JLabel userFontLabel      = new JLabel("User font:");
      JLabel lastUserLoginLabel = new JLabel("Last user logged in: ");
      JLabel ldapURLLabel       = new JLabel("LDAP url:");
      final JTextField appPathTf       = new JTextField(
                                  preferences.get(APPLICATIONPATH, ""));
      final JTextField userFontTf      = new JTextField(
                                  preferences.get(USERFONT, ""));
      final JTextField lastUserLoginTf = new JTextField(
                                  preferences.get(LASTUSERLOGIN, ""));
      final JTextField ldapURLTf       = new JTextField(
                                  preferences.get(LDAPURL, ""));
 
      JPanel prefsPanel = new JPanel();
      prefsPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
      prefsPanel.setLayout(new GridLayout(4, 4, 10, 10));
      prefsPanel.add(appPathLabel);
      prefsPanel.add(appPathTf);
      prefsPanel.add(userFontLabel);
      prefsPanel.add(userFontTf);
      prefsPanel.add(lastUserLoginLabel);
      prefsPanel.add(lastUserLoginTf);
      prefsPanel.add(ldapURLLabel);
      prefsPanel.add(ldapURLTf);
 
      JPanel buttonPanel = new JPanel();
      buttonPanel.setLayout(new GridLayout(1, 2, 70, 70));
 
      JButton cancelButton = new JButton("Cancel");
      cancelButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.exit(0);
         }
      });
 
      JButton saveButton = new JButton("Save");
      saveButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            try {
               preferences.put(APPLICATIONPATH, appPathTf.getText());
               preferences.put(USERFONT,        userFontTf.getText());
               preferences.put(LASTUSERLOGIN,   lastUserLoginTf.getText());
               preferences.put(LDAPURL,         ldapURLTf.getText());
 
               // ensure all data is flushed to the backing store
               preferences.flush();
 
               System.out.println("Preferences saved!");
            }
            catch(BackingStoreException e) {
               e.printStackTrace();
            }
         }
      });
 
      buttonPanel.add(cancelButton);
      buttonPanel.add(saveButton);
 
      getContentPane().setLayout(new BorderLayout());
      getContentPane().add(BorderLayout.CENTER, prefsPanel);
      getContentPane().add(BorderLayout.SOUTH, buttonPanel);
   }
 
   public void loadPreferences() {
      preferences = Preferences.userNodeForPackage(this.getClass());
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(350, 190);
      main.setVisible(true);
   }
}

Take a look at the Windows registry in the key \HKEY_CURRENT_USERSOFTWAREJavaSoftPrefs

.

If you want to load these preferences from another application, specify the node.

Main2.java:

import java.util.prefs.*;
 
public class Main2
{
   public static final String APPLICATIONPATH = "applicationpath";
   public static final String USERFONT        = "userfont";
   public static final String LASTUSERLOGIN   = "lastuserlogin";
   public static final String LDAPURL         = "ldapurl";
 
   public static void main(String []args) {
      String nodename = "/com/esus/examples/preferences";
 
      Preferences preferences = Preferences.userRoot().node(nodename);
      System.out.println(preferences.get(APPLICATIONPATH, ""));
      System.out.println(preferences.get(USERFONT, ""));
      System.out.println(preferences.get(LASTUSERLOGIN, ""));
      System.out.println(preferences.get(LDAPURL, ""));
   }
}

outputs:

c:application
Courier New
Joris Van den Bogaert
ldap://localhost:389

Notice also that by using userRoot you are working with preferences for that user. You can also work with system preferences (shared by all users) by specifying systemRoot.

When you perform a get, you have 2 parameters: one for the key and one for the default value. Whenever the value is not available on the backing store, the default value will be returned, if specified.

In the following example, PORT is not available on the backing store.

Main3.java:

import java.util.prefs.*;
 
public class Main3
{
   public static final String APPLICATIONPATH = "applicationpath";
   public static final String USERFONT        = "userfont";
   public static final String LASTUSERLOGIN   = "lastuserlogin";
   public static final String LDAPURL         = "ldapurl";
   public static final String PORT            = "port";
 
   public static final String DEFAULTPORT     = "2506";
 
   public static void main(String []args) {
      String nodename = "/com/esus/examples/preferences";
 
      Preferences preferences = Preferences.userRoot().node(nodename);
      System.out.println(preferences.get(APPLICATIONPATH, ""));
      System.out.println(preferences.get(USERFONT, ""));
      System.out.println(preferences.get(LASTUSERLOGIN, ""));
      System.out.println(preferences.get(LDAPURL, ""));
 
      System.out.println(preferences.get(PORT, DEFAULTPORT));
   }
}

outputs:

c:application
Courier New
Joris Van den Bogaert
ldap://localhost:389
2506

Validating a textfield using the regex package

You can use a custom InputVerifier in which you try to match the desired regular expression for that textfield.

Main.java:

import java.util.regex.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.text.*;
 
public class Main extends JFrame
{
   public Main() {
      super("JFormattedTextField REGEX example");
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      getContentPane().setLayout(new BorderLayout());
      JFormattedTextField ftf = new JFormattedTextField();
      getContentPane().add(BorderLayout.NORTH, ftf);
      ftf.setInputVerifier(new RegExFieldVerifier("[abcd]+"));
 
      getContentPane().add(BorderLayout.SOUTH, new JTextField("Normal textfield"));
      getContentPane().add(BorderLayout.CENTER, 
                               new JLabel("<HTML>REGEX USED:  [abcd]+   allowed: " +
                                          "one or more of the following characters: " +
                                          "a,b,c or d.<BR>Use the TAB key to switch!</HTML>"));
 
   }
 
   public static void main(String []args) throws Exception {
      Main main = new Main();
      main.setSize(300, 300);
      main.setVisible(true);
   }
}
 
class RegExFieldVerifier extends InputVerifier {
   Pattern pattern;
 
   public RegExFieldVerifier(String regex) {
      pattern = Pattern.compile(regex);
   }
 
   public boolean verify(JComponent input) {
      if (input instanceof JFormattedTextField) {
         JFormattedTextField ftf = (JFormattedTextField)input;
         String line = ftf.getText();
         Matcher m = pattern.matcher(line);
         if (!m.matches()) 
            System.out.println("Doesn't match regular expression " + 
                               pattern.pattern());      
         return m.matches();
      }        
      return true;     
   }
 
   public boolean shouldYieldFocus(JComponent input) {
      return verify(input);
   }
}