What is asymmetric cryptography?

The problem with symmetric cryptography is how to distribute the secret key to the involved parties. In assymetric cryptography (also: public key cryptography), algorithms use two different keys: a private and a public one. A message encrypted with a private key can be decrypted with its public key (and in some cases vice versa). The owner of the key pair holds the private key, and may distribute the public key to anyone. Someone who wants to send a secret message uses the public key of the intended receiver to encrypt it. Only the receiver holds the private key and can decrypt it.

Compared to secret key encryption, public key encryption is slow.

A popular assymetric cryptographic algorithm is RSA, used in PGP.

Aligning decimal numbers to the decimal fields

You can use the class FieldPosition and one of the Format classes. FieldPosition keeps track of where a certain part in the formatted string is located. Those parts are dependent on the type of Format class you use and are defined in constants. For example, the class DateFormat contains constants like DAY_OF_WEEK_FIELD or MONTH_FIELD. Likewise, the NumberFormat class contains two constants: INTEGER_FIELD and FRACTION_FIELD. When you invoke the method format, you can supply an instance of FieldPosition which will be filled in with information about the position of the field (beginIndex and endIndex).

Main.java:

import java.text.*;
 
public class Main {
   public static void main(String args[]) {
      double array[] = { 0, 0.1, 1.0, 213.034, 12.43, 12, 0.9832, 4567 };
 
      NumberFormat nf = NumberFormat.getInstance();
      StringBuffer buffer = new StringBuffer();
      for (int i=0; i<array.length; i++) {
         FieldPosition fp = new FieldPosition(NumberFormat.FRACTION_FIELD);
         buffer.setLength(0);
         nf.format(array[i], buffer, fp);
 
         alignInColumn(buffer, fp);
      }
   }
 
   public static void alignInColumn(StringBuffer sb, FieldPosition fp) {
      int col = 10-fp.getBeginIndex();
      if (fp.getBeginIndex() == fp.getEndIndex())
         col--;
 
      for (int i=0; i<col; i++) { 
         System.out.print(' ');
      }
      System.out.println(sb);
   }
}

outputs:

        0
        0.1
        1
      213.034
       12.43
       12
        0.983
    4,567

Fetching today’s date in Java

Try this:

import java.util.*;
import java.text.*;
 
public class Main { 
   public static void main(String[] args) throws Exception {
      System.out.println(getDateTime("dd-MM-yyyy HH:mm:ss.SSS"));
   }
 
   public static String getDateTime(String format) {
      Calendar calendar = Calendar.getInstance();
      SimpleDateFormat dateFormat = new SimpleDateFormat(format);
      Date date = calendar.getTime();
      return dateFormat.format(calendar.getTime());
   }
}

Using java.util.logging to log to an XML file

Use the standard XMLFormatter class, already used by default by several standard handlers.

Main.java:

import java.util.logging.*;
import java.io.*;
 
public class Main
{
   public static void main(String argv[]) {
      Logger logger = Logger.getLogger("main");
      logger.setUseParentHandlers(false);
      ConsoleHandler ch = new ConsoleHandler();
      ch.setLevel(Level.ALL);
      logger.addHandler(ch);
 
      ch.setFormatter(new XMLFormatter());

      LogRecord logRecord = new LogRecord(Level.SEVERE, "Something went seriously wrong");
      logRecord.setMillis(1000);
      logRecord.setParameters(new Object[] { "param1", "param2" });
      logRecord.setSequenceNumber(123456);
      logRecord.setSourceClassName(Main.class.getName());
      logRecord.setSourceMethodName("main");

      logger.log(logRecord); 
   }
}

outputs:

<? xml version="1.0" encoding="windows-1252" standalone="no"?>
<!DOCTYPE log SYSTEM "logger.dtd">
<log>
<record>
  <date>1969-12-31T16:00:01</date>
  <millis>1000</millis>
  <sequence>123456</sequence>
  <level>SEVERE</level>
  <class>Main</class>
  <method>main</method>
  <thread>10</thread>
  <message>Something went seriously wrong</message>
</record>

A Grep utility that makes uses of Java’s RegEx package

Here’s a simple example that gets you started. It allows you to search a pattern (-cpat) in a set of files that match a certain regular expression (-fpat). You can specify a directory from where it should start searching with the option -root. -R tells the grepper to recurse through subdirectories. Below are a couple examples.

Grep.java:

import java.util.regex.*;
import java.io.*;
 
public class Grep
{
   Pattern pattern;
   FileFilter fileFilter;
 
   public Grep(String contentRegex) {
      pattern = Pattern.compile(contentRegex);
   }
 
   public void searchInDir(String startDir, String dirRegex, boolean recurse) 
                                                 throws IOException {
      final Pattern patternFile = Pattern.compile(dirRegex);
      fileFilter = new FileFilter() {
         public boolean accept(File f) {
            if (f.isDirectory()) return true;
 
            Matcher m = patternFile.matcher(f.getName());
            if (m.matches()) return true;
            return false;
         }
      };
 
      searchInDir_aux(new File(startDir), recurse);
   }
    
   public void searchInDir_aux(File dir, boolean recurse) throws IOException {
      File[] contents = dir.listFiles(fileFilter);
      for (int i=0; i<contents.length; i++) {
         File fileToCheck = contents[i];
         if (fileToCheck.isFile()) {
            searchInFile(fileToCheck);
         }
         else if (recurse) {
            searchInDir_aux(fileToCheck, recurse);
         }
      }            
   } 
 
   public void searchInFile(File file) throws IOException {
      System.out.println("=====> " + file);
      BufferedReader br = new BufferedReader(new FileReader(file));
      String line = null;
      int count=0;
      while ((line = br.readLine()) != null) {
         count++;
         Matcher m = pattern.matcher(line);
         while (m.find()) {
            System.out.println(count + ": " + line);
            System.out.print(count + ": ");
            indent(m.start());
            System.out.print("^");
            indent(m.end()-m.start()-2);
            System.out.println("^");
         }
      } 
      br.close();
   }
 
   public static void indent(int h) {
      for (int i=0; i<h; i++) 
         System.out.print(' ');
   }
 
   public static void main(String []args) throws Exception {
      String contentPattern=null, filePattern=null, startDir=null;
      boolean recurse = false;
  
      int i = -1;
      while (++i < args.length) {
         String arg = args[i];
	 if (!arg.startsWith("-")) {
            System.err.println("argument error: " + arg + "n");
            printUsage();
            System.exit(1);
         }  
         if (arg.equals("-fpat")) {
            if (i == args.length-1 || args[i+1].startsWith("-")) {
               System.err.println("Missing filename RE pattern");
               printUsage();
               System.exit(1);
            }
            filePattern = args[++i];
            continue;
         }
         else if (arg.equals("-cpat")) {
            if (i == args.length-1 || args[i+1].startsWith("-")) {
               System.err.println("Missing contents RE pattern");
               printUsage();
               System.exit(1);
            }
            contentPattern = args[++i];
            continue;
         }
         else if (arg.equals("-R")) {
            recurse = true;
            continue;
         }
         else if (arg.equals("-root")) {
            if (i == args.length-1 || args[i+1].startsWith("-")) {
               System.err.println("Missing starting directory");
               printUsage();
               System.exit(1);
            }
            startDir = args[++i];
            continue;
         }
      }                  
      if (contentPattern == null || filePattern == null) {
         printUsage();
         System.exit(1);
      }
      if (startDir == null) {
         startDir = ".";          // take current directory
      }
 
      Grep grep = new Grep(contentPattern);
      grep.searchInDir(startDir, filePattern, recurse);
   }
 
   private static void printUsage() {
      System.err.println("Usage: java [optional] -fpat fileRegex -cpat contentRegex");
      System.err.println("Where [optional] is one of the following:");
      System.err.println("    -R  recursively search subdirectories");
      System.err.println("    -root <STARTDIR>  specifies starting directory");
      System.exit(1);
   }
}

For example:

(searches all files for the pattern import)
  
C:myregextest> c:jdk1.4binjava Grep -fpat .* -cpat import
=====> .Grep$1.class
=====> .Grep.class
=====> .Grep.java
1: import java.util.regex.*;
1: ^    ^
2: import java.io.*;
2: ^    ^
 
(recursively searches c:winnt for files ending on .ini for the pattern micro.{5})
 
C:myregextest> c:jdk1.4binjava Grep -R -root c:winnt -fpat .*.ini -cpat micro.{5}
 
. . . [result]  

Zipping a file in Java

The following example creates a zip file of the file that you provide at command line.

Main.java:

import java.util.zip.*;
import java.io.*;
 
public class Main
{
   public static void main(String []args) throws Exception {
      if (args.length != 1) {
         System.err.println("Usage: java Main <file>");
         System.exit(1);
      }
 
      FileOutputStream fos = new FileOutputStream(args[0] + ".zip");
      BufferedOutputStream bos = new BufferedOutputStream(fos);
      ZipOutputStream zos = new ZipOutputStream(bos);
 
      File inFile = new File(args[0]);
      FileInputStream fis = new FileInputStream(inFile);
      BufferedInputStream bis = new BufferedInputStream(fis);
      
      ZipEntry zipEntry = new ZipEntry(inFile.toString());
      zipEntry.setMethod(ZipEntry.DEFLATED);
      zos.putNextEntry(zipEntry);
 
      byte[] buffer = new byte[1024];
      int length;
      while ((length = bis.read(buffer)) != -1) {
         zos.write(buffer, 0, length);
      }
  
      zos.closeEntry();
      zos.close();
      bis.close();
   }
}

Creating a full screen JFrame

From 1.4, call the method setFullScreenMode on the default screen device.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame implements ActionListener
{
   public Main()
   {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      Button maxButton = new Button("Make this JFrame full-screen");
      getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
      getContentPane().add(maxButton);
      maxButton.addActionListener(this);
   }
 
   public void actionPerformed(ActionEvent ae) {     
      GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
      device.setFullScreenWindow(this);
   }
 
   public static void main(String args[])
   {
      Main main = new Main();
      main.setSize(300, 150);
      main.setVisible(true);
   }
}

Catching an event when a JTabbedPane tab is selected

You can add a ChangeListener to your JTabbedPane component to catch the events. The first example shows you how. The event will be raised after the change has already occurred. If you want to catch the event before the change occurs, ie. to disallow a user from selecting a tab, you have to override the setSelectedIndex method. The second example shows how to prevent users from selecting tabs with odd index numbers.
First example:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame implements ActionListener {
   JTabbedPane tabbedPane;
   int ntabs = 0;
 
   public Main() {
      getContentPane().setLayout(new BorderLayout());
      tabbedPane = new JTabbedPane();
      createTab();
 
      getContentPane().add(BorderLayout.CENTER, tabbedPane);
      setJMenuBar(createMenuBar());
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      tabbedPane.addChangeListener(new ChangeListener() {
         public void stateChanged(ChangeEvent ce) {
            System.out.println("Tab " + (tabbedPane.getSelectedIndex() + 1) + " is selected");
         }
      });
  
      setTitle("JTabbedPane Orientation Demonstration");
      setSize(new Dimension(400, 400));
   }
 
   protected JMenuBar createMenuBar() {
      JMenuBar menuBar = new JMenuBar();
 
      JMenu menu = new JMenu("JTabbedPane");
      JMenuItem menuItem1 = new JMenuItem("Create new tab");
      menuItem1.addActionListener(this);
      menu.add(menuItem1);
      menuBar.add(menu);
 
      return menuBar;
   }
  
   public void actionPerformed(ActionEvent e) {
      if (e.getActionCommand().equals("Create new tab")) {
         createTab();
      }
   }
 
   protected void createTab() {
      ntabs++;
      tabbedPane.addTab("Tab #" + ntabs, new JLabel("Tab #" + ntabs));
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
}

Second example:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame implements ActionListener {
   JTabbedPane tabbedPane;
   int ntabs = 0;
 
   public Main() {
      getContentPane().setLayout(new BorderLayout());
      tabbedPane = new JTabbedPane() {
         public void setSelectedIndex(int index) {
            System.out.println("index selected: " + index);
            if (index % 2 == 0) {
               System.out.println("allowed");
               super.setSelectedIndex(index);
            }
            else {
               System.out.println("not allowed");
            }
         }
      };
      createTab();
 
      getContentPane().add(BorderLayout.CENTER, tabbedPane);
      setJMenuBar(createMenuBar());
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      setTitle("JTabbedPane Selection Demonstration");
      setSize(new Dimension(400, 400));
   }
 
   protected JMenuBar createMenuBar() {
      JMenuBar menuBar = new JMenuBar();
 
      JMenu menu = new JMenu("JTabbedPane");
      JMenuItem menuItem1 = new JMenuItem("Create new tab");
      menuItem1.addActionListener(this);
      menu.add(menuItem1);
      menuBar.add(menu);
 
      return menuBar;
   }
  
   public void actionPerformed(ActionEvent e) {
      if (e.getActionCommand().equals("Create new tab")) {
         createTab();
      }
   }
 
   protected void createTab() {
      tabbedPane.addTab("Tab #" + ntabs, new JLabel("Tab #" + ntabs));
      ntabs++;
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
}