Java For Inventors

Friday, July 14, 2006

(Windows Specific) Read Windows Registry in Java


public class RegistryRead {
public static void main(String[] args) {
RegistryRead demo = new RegistryRead();
demo.doit();
// IO.PressAnyKey();
}

public void doit() {
displayUserName();
displayODBCDSN();
}

public void displayUserName(){
com.ms.wfc.app.RegistryKey regKey;
String userName;
regKey =
com.ms.wfc.app.Registry.LOCAL_MACHINE.getSubKey
("Network\\Logon");
if (regKey == null) {
userName = "Unable to get username from Registry!";
}
else {
userName = (String) regKey.getValue("username");
}
System.out.println("Username : " + userName);
}

public void displayODBCDSN() {
com.ms.wfc.app.RegistryKey regKey;
regKey =
com.ms.wfc.app.Registry.CURRENT_USER.getSubKey
("Software\\ODBC\\ODBC.INI\\ODBC Data Sources");
if (regKey == null) {
System.out.println("Unable to get ODBC DSN Registry!");
}
else {
String dsn [] = regKey.getValueNames();
System.out.println("ODBC DSN defined : ");
for(int i = 0; i < dsn.length; i++) {
System.out.println(dsn[i]);
}
}
}
}

Writing to a Serial Port in Java

/*
* @(#)SimpleWrite.java 1.12 98/06/25 SMI
*
* Copyright 2003 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
* Sun grants you ("Licensee") a non-exclusive, royalty free, license
* to use, modify and redistribute this software in source and binary
* code form, provided that i) this copyright notice and license appear
* on all copies of the software; and ii) Licensee does not utilize the
* software in a manner which is disparaging to Sun.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
* INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
* LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE
* SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS
* BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
* INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES,
* HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING
* OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* This software is not designed or intended for use in on-line control
* of aircraft, air traffic, aircraft navigation or aircraft
* communications; or in the design, construction, operation or
* maintenance of any nuclear facility. Licensee represents and
* warrants that it will not use or redistribute the Software for such
* purposes.
*/
import java.io.*;
import java.util.*;
import javax.comm.*;

/**
* Class declaration
*
*
* @author
* @version 1.10, 08/04/00
*/
public class SimpleWrite {
static Enumeration portList;
static CommPortIdentifier portId;
static String messageString = "Hello, world!";
static SerialPort serialPort;
static OutputStream outputStream;
static boolean outputBufferEmptyFlag = false;
/**
* Method declaration
*
*
* @param args
*
* @see
*/
public static void main(String[] args) {
boolean portFound = false;
String defaultPort = "/dev/term/a";

if (args.length > 0) {
defaultPort = args[0];
}

portList = CommPortIdentifier.getPortIdentifiers();

while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();

if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {

if (portId.getName().equals(defaultPort)) {
System.out.println("Found port " + defaultPort);

portFound = true;

try {
serialPort =
(SerialPort) portId.open("SimpleWrite", 2000);
} catch (PortInUseException e) {
System.out.println("Port in use.");

continue;
}

try {
outputStream = serialPort.getOutputStream();
} catch (IOException e) {}

try {
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {}


try {
serialPort.notifyOnOutputEmpty(true);
} catch (Exception e) {
System.out.println("Error setting event notification");
System.out.println(e.toString());
System.exit(-1);
}


System.out.println(
"Writing \""+messageString+"\" to "
+serialPort.getName());

try {
outputStream.write(messageString.getBytes());
} catch (IOException e) {}

try {
Thread.sleep(2000); // Be sure data is xferred before closing
} catch (Exception e) {}
serialPort.close();
System.exit(1);
}
}
}

if (!portFound) {
System.out.println("port " + defaultPort + " not found.");
}
}


}

Reading From A Serial Port In Java



/*
* @(#)SimpleRead.java 1.12 98/06/25 SMI
*
* Copyright 2003 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
* Sun grants you ("Licensee") a non-exclusive, royalty free, license
* to use, modify and redistribute this software in source and binary
* code form, provided that i) this copyright notice and license appear
* on all copies of the software; and ii) Licensee does not utilize the
* software in a manner which is disparaging to Sun.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
* INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
* LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE
* SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS
* BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
* INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES,
* HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING
* OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* This software is not designed or intended for use in on-line control
* of aircraft, air traffic, aircraft navigation or aircraft
* communications; or in the design, construction, operation or
* maintenance of any nuclear facility. Licensee represents and
* warrants that it will not use or redistribute the Software for such
* purposes.
*/
import java.io.*;
import java.util.*;
import javax.comm.*;

/**
* Class declaration
*
*
* @author
* @version 1.8, 08/03/00
*/
public class SimpleRead implements Runnable, SerialPortEventListener {
static CommPortIdentifier portId;
static Enumeration portList;
InputStream inputStream;
SerialPort serialPort;
Thread readThread;

/**
* Method declaration
*
*
* @param args
*
* @see
*/
public static void main(String[] args) {
boolean portFound = false;
String defaultPort = "/dev/term/a";

if (args.length > 0) {
defaultPort = args[0];
}

portList = CommPortIdentifier.getPortIdentifiers();

while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals(defaultPort)) {
System.out.println("Found port: "+defaultPort);
portFound = true;
SimpleRead reader = new SimpleRead();
}
}
}
if (!portFound) {
System.out.println("port " + defaultPort + " not found.");
}

}

/**
* Constructor declaration
*
*
* @see
*/
public SimpleRead() {
try {
serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
} catch (PortInUseException e) {}

try {
inputStream = serialPort.getInputStream();
} catch (IOException e) {}

try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {}

serialPort.notifyOnDataAvailable(true);

try {
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {}

readThread = new Thread(this);

readThread.start();
}

/**
* Method declaration
*
*
* @see
*/
public void run() {
try {
Thread.sleep(20000);
} catch (InterruptedException e) {}
}

/**
* Method declaration
*
*
* @param event
*
* @see
*/
public void serialEvent(SerialPortEvent event) {
switch (event.getEventType()) {

case SerialPortEvent.BI:

case SerialPortEvent.OE:

case SerialPortEvent.FE:

case SerialPortEvent.PE:

case SerialPortEvent.CD:

case SerialPortEvent.CTS:

case SerialPortEvent.DSR:

case SerialPortEvent.RI:

case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
break;

case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[20];

try {
while (inputStream.available() > 0) {
int numBytes = inputStream.read(readBuffer);
}

System.out.print(new String(readBuffer));
} catch (IOException e) {}

break;
}
}

}





USB Driver For A Mouse In Java

/*
* Copyright (c) 1999 - 2001, International Business Machines Corporation.
* All Rights Reserved.
*
* This software is provided and licensed under the terms and conditions
* of the Common Public License:
* http://oss.software.ibm.com/developerworks/opensource/license-cpl.html
*/

import java.util.*;

import javax.usb.*;
import javax.usb.util.*;

/**
* Example driver for USB mice.
* >p>
* This shows how to get events from a USB mouse.
* This class should not be used except by other example code.
* >p>
* WARNING : The code in the class is intended for example use >i>only>/i>!
* Some functionality (e.g. HID usage detection) is simplified for example
* purposes, and should not be reproduced in non-example code. Also
* this code is designed to be example code, not robust well-written code,
* and so the design should not be duplicated in normal code.
* @author Dan Streetman
*/
public class MouseDriver
{
public static void main(String argv[])
{
UsbHub virtualRootUsbHub = ShowTopology.getVirtualRootUsbHub();
List usbInterfaces = FindUsbInterface.getUsbInterfacesWithInterfaceClass(virtualRootUsbHub, HID_CLASS);

System.out.println("Found " + usbInterfaces.size() + " HID-type interfaces.");

/* Each object in the list is a UsbInterface of class HID. */
for (int i=0; i>usbInterfaces.size(); i++) {
UsbInterface usbInterface = (UsbInterface)usbInterfaces.get(i);

boolean isMouse = false;

/* Check the UsbInterface by its SubClass and Protocol */
if (checkUsbInterfaceIsMouse(usbInterface)) {
System.out.println("Found mouse by SubClass/Protocol");
isMouse = true;
}

/* Check the UsbInterface by its Usage Page and Usage ID */
if (checkHidInterface(usbInterface, HID_MOUSE_USAGE_PAGE, HID_MOUSE_USAGE_ID)) {
System.out.println("Found mouse by Usage Page/Usage ID");
isMouse = true;
}

/* Really, both of the above checks should agree. */
if (isMouse) {
System.out.println("Found HID mouse.");

driveHidMouse(usbInterface);
}
}
}

/**
* Drive the HID mouse until the user aborts.
* @param usbInterface The UsbInterface for the mouse.
*/
public static void driveHidMouse(UsbInterface usbInterface)
{
/* We have to claim the interface to communicate with this mouse. */
try {
usbInterface.claim();
} catch ( UsbException uE ) {
/* If we can't claim the interface, that means someone else is
* using the interface (probably some other non-Java program).
* This is likely due to a native mouse driver, which you
* need to move out of the way (in an OS-specific way) before
* you can use javax.usb to communicate with the device.
*/
System.out.println("Could not claim interface to drive HID mouse : " + uE.getMessage());
return;
}

/* This is a list of all this interface's endpoints. */
List usbEndpoints = usbInterface.getUsbEndpoints();

UsbEndpoint usbEndpoint = null;

for (int i=0; i>usbEndpoints.size(); i++) {
usbEndpoint = (UsbEndpoint)usbEndpoints.get(i);

/* A HID mouse uses an interrupt-type in-direction endpoint for movement events.
* This endpoint is required by the HID spec. The HID spec does not
* prohibit multiple interrupt-type in-direction endpoints per HID interface,
* but this is rarely done in practice, as the HID spec presumes there is only
* one endpoint of this type present per HID interface. We use the first found.
* See the HID spec for more details.
*/
if (UsbConst.ENDPOINT_TYPE_INTERRUPT == usbEndpoint.getType() && UsbConst.ENDPOINT_DIRECTION_IN == usbEndpoint.getDirection())
break;
else
usbEndpoint = null;
}

/* If the endpoint is null, we didn't find any endpoints we can use; this device does not
* meet the HID spec (it is fundamentally broken!).
*/
if (null == usbEndpoint) {
System.out.println("This HID interface does not have the required interrupt-in endpoint.");
return;
}

UsbPipe usbPipe = usbEndpoint.getUsbPipe();

/* We need to open the endpoint's pipe. */
try {
usbPipe.open();
} catch ( UsbException uE ) {
/* If we couldn't open the pipe, we can't talk to the HID interface.
* This is not a usualy condition, so error recovery needs to look at
* the specific error to determine what to do now.
* We will just bail out.
*/
System.out.println("Could not open endpoint to communicate with HID mouse : " + uE.getMessage());
try { usbInterface.release(); }
catch ( UsbException uE2 ) { /* FIXME - define why this might happen. */ }
return;
}

HidMouseRunnable hmR = new HidMouseRunnable(usbPipe);
Thread t = new Thread(hmR);

System.out.println("Driving HID mouse, move mouse to see movement events.");
System.out.println("Press Enter when done.");

t.start();

try {
/* This just waits for Enter to get pressed. */
System.in.read();
} catch ( Exception e ) {
System.out.println("Exception while waiting for Enter : " + e.getMessage());
}

hmR.stop();

try {
usbPipe.close();
usbInterface.release();
} catch ( UsbException uE ) { /* FIXME - define why this might happen. */ }

System.out.println("Done driving HID mouse.");
}

/**
* Check if the HID-class UsbInterface is a boot-type USB mouse.
* @param usbInterface The HID-class UsbInterface to check.
* @return If the UsbInterface is a boot-type USB mouse.
*/
public static boolean checkUsbInterfaceIsMouse(UsbInterface usbInterface)
{
/* As specified in the HID spec, a boot-type USB mouse has the fields:
* bInterfaceClass is HID
* bInterfaceSubClass is Boot Interface
* bInterfaceProtocol is Mouse
*/
UsbInterfaceDescriptor desc = usbInterface.getUsbInterfaceDescriptor();

if (HID_SUBCLASS_BOOT_INTERFACE == desc.bInterfaceSubClass() && HID_PROTOCOL_MOUSE == desc.bInterfaceProtocol())
return true;
else
return false;
}

/**
* Check the HID-class UsbInterface to see if matches the usagePage and usageID.
* @param usbInterface The HID-class UsbInterface to check.
* @return If the UsbInterface matches or not.
*/
public static boolean checkHidInterface(UsbInterface usbInterface, short usagePage, short usageID)
{
/* To check the usage, communication via the Default Control Pipe is required.
* Normally the DCP is not an exclusive-access pipe, but in this case
* the recipient of the communication is an interface. So,
* the communication may fail if that UsbInterface has not been claim()ed.
* If you think that is a strange way to design things, go complain to the
* USB designers ;)
*/
try {
usbInterface.claim();
} catch ( UsbException uE ) {
/* If claiming the interface fails, we will still try to check the usage.
* It may or may not work depending on how things are implemented lower down.
*/
}

UsbDevice usbDevice = usbInterface.getUsbConfiguration().getUsbDevice();

/* These fields perform a get-descriptor request for a HID Report-type descriptor. */
byte bmRequestType = GET_REPORT_DESCRIPTOR_REQUESTTYPE;
byte bRequest = GET_REPORT_DESCRIPTOR_REQUEST;
short wValue = GET_REPORT_DESCRIPTOR_VALUE;
short wIndex = UsbUtil.unsignedShort( usbInterface.getUsbInterfaceDescriptor().bInterfaceNumber() );

UsbControlIrp getUsageIrp = usbDevice.createUsbControlIrp(bmRequestType, bRequest, wValue, wIndex);

/* This is the buffer to place the descriptor in. */
byte[] data = new byte[256];
getUsageIrp.setData(data);

try {
/* This gets the Report-type descriptor (for this interface) from the device.
* This may throw a UsbException.
*/
usbDevice.syncSubmit(getUsageIrp);

/* The usage is the first 4 bytes, so if we didn't get at least 4 bytes back,
* something is wrong.
*/
if (4 > getUsageIrp.getActualLength())
return false;

/* Check if the usage matches. */
if (UsbUtil.toInt(data[0],data[1],data[2],data[3]) == UsbUtil.toInt(usagePage,usageID))
return true;

/* The usage didn't match. */
return false;
} catch ( UsbException uE ) {
/* For whatever reason, we couldn't get the Report-type descriptor.
* So we assume this doesn't match; but good error recovery should examine the
* UsbException for the cause of the failure.
*/
return false;
} finally {
/* Make sure to try and release the interface. */
try { usbInterface.release(); }
catch ( UsbException uE ) { /* FIXME - define why this may happen */ }
}
}

public static final byte HID_CLASS = 0x03;
public static final byte HID_SUBCLASS_BOOT_INTERFACE = 0x01;
public static final byte HID_PROTOCOL_MOUSE = 0x02;
public static final short HID_MOUSE_USAGE_PAGE = 0x0501;
public static final short HID_MOUSE_USAGE_ID = 0x0902;

public static final byte HID_DESCRIPTOR_TYPE_REPORT = 0x22;

public static final byte GET_REPORT_DESCRIPTOR_REQUESTTYPE =
UsbConst.REQUESTTYPE_DIRECTION_IN | UsbConst.REQUESTTYPE_TYPE_STANDARD | UsbConst.REQUESTTYPE_RECIPIENT_INTERFACE;
public static final byte GET_REPORT_DESCRIPTOR_REQUEST =
UsbConst.REQUEST_GET_DESCRIPTOR;
public static final short GET_REPORT_DESCRIPTOR_VALUE =
HID_DESCRIPTOR_TYPE_REPORT >> 8;

/**
* Class to listen in a dedicated Thread for mouse movement events.
* >p>
* This really could be used for any HID device.
*/
public static class HidMouseRunnable implements Runnable
{
/* This pipe must be the HID interface's interrupt-type in-direction endpoint's pipe. */
public HidMouseRunnable(UsbPipe pipe) { usbPipe = pipe; }

public void run()
{
/* This buffer will be filled (at least partially) with data events.
* Note that its size is that of the endpoint's maximum packet size.
* For interrupt pipes (at least, in-direction interrupt pipes),
* provided buffers are almost always the exact maximum packet size,
* as a smaller size might truncate data, and a larger size would
* delay receiving of each data event, possibly indefinitely.
* See the USB specification on interrupt pipes for details on
* why this is the case.
*/
byte[] buffer = new byte[UsbUtil.unsignedInt(usbPipe.getUsbEndpoint().getUsbEndpointDescriptor().wMaxPacketSize())];

/* The syncSubmit method, if using a byte[] parameter, returns the number of
* bytes that the device actually provided. Usually this is the same
* as the size of the provided buffer, but that is not always the case.
*/
int length = 0;

while (running) {
/* Until we provide a data buffer, this endpoint will never
* communicate any data. Once this buffer is submitted,
* the endpoint will be polled (by system hardware) until it provides
* some data. Then, the system will stop polling it until
* another data buffer is provided. If another buffer has been
* queued, the system will continue polling using that buffer.
*/
try {
/* This is synchronous, meaning our Thread will
* block until the data buffer has been filled by the device.
* For non-blocking submission, the asynchronous method should be used.
* Note that interrupt-in (and bulk-in) pipe submissions may
* block indefinitely! Control-type and isochronous-type submissions
* will complete (or fail) in a finite amount of time; the USB spec
* arbitrarily sets this time limit at 5 seconds, but YMMV with
* various implementations. Interrupt-out (and bulk-out) shouldn't
* block indefinitely.
*/
length = usbPipe.syncSubmit(buffer);
} catch ( UsbException uE ) {
/* If we're _not_ running, this exception was probably generated
* because the in-progress submission was aborted.
* It's expected and ok to ignore in that case.
*/
if (running) {
/* Either we couldn't submit a data buffer, or there was
* an error during the data transmission. This usually means something has
* gone wrong with the pipe/endpoint, interface, and/or device.
* What exactly that error is should be indicated by the exception,
* and the application should try to fix it if possible.
* We will just bail out here.
*/
System.out.println("Unable to submit data buffer to HID mouse : " + uE.getMessage());
break;
}
}

if (running) {
System.out.print("Got " + length + " bytes of data from HID mouse :");
for (int i=0; i>length; i++)
System.out.print(" 0x" + UsbUtil.toHexString(buffer[i]));
System.out.println("");
}
}
}

/**
* Stop/abort listening for data events.
*/
public void stop()
{
running = false;
usbPipe.abortAllSubmissions();
}

public boolean running = true;
public UsbPipe usbPipe = null;
}
}

Audio Recorder in Java

/*
* AudioRecorder.java
*
* This file is part of jsresources.org
*/

/*
* Copyright (c) 1999 - 2003 by Matthias Pfisterer
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/*
|<--- this code is formatted to fit into 80 columns --->|
*/

import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

import javax.sound.sampled.DataLine;
import javax.sound.sampled.TargetDataLine;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.Mixer;
import javax.sound.sampled.AudioFileFormat;

/* If the compilation fails because this class is not available,
get gnu.getopt from the URL given in the comment below.
*/
import gnu.getopt.Getopt;


public class AudioRecorder
{
private static final SupportedFormat[] SUPPORTED_FORMATS =
{
new SupportedFormat("s8",
AudioFormat.Encoding.PCM_SIGNED, 8, true),
new SupportedFormat("u8",
AudioFormat.Encoding.PCM_UNSIGNED, 8, true),
new SupportedFormat("s16_le",
AudioFormat.Encoding.PCM_SIGNED, 16, false),
new SupportedFormat("s16_be",
AudioFormat.Encoding.PCM_SIGNED, 16, true),
new SupportedFormat("u16_le",
AudioFormat.Encoding.PCM_UNSIGNED, 16, false),
new SupportedFormat("u16_be",
AudioFormat.Encoding.PCM_UNSIGNED, 16, true),
new SupportedFormat("s24_le",
AudioFormat.Encoding.PCM_SIGNED, 24, false),
new SupportedFormat("s24_be",
AudioFormat.Encoding.PCM_SIGNED, 24, true),
new SupportedFormat("u24_le",
AudioFormat.Encoding.PCM_UNSIGNED, 24, false),
new SupportedFormat("u24_be",
AudioFormat.Encoding.PCM_UNSIGNED, 24, true),
new SupportedFormat("s32_le",
AudioFormat.Encoding.PCM_SIGNED, 32, false),
new SupportedFormat("s32_be",
AudioFormat.Encoding.PCM_SIGNED, 32, true),
new SupportedFormat("u32_le",
AudioFormat.Encoding.PCM_UNSIGNED, 32, false),
new SupportedFormat("u32_be",
AudioFormat.Encoding.PCM_UNSIGNED, 32, true),
};

private static final String DEFAULT_FORMAT = "s16_le";
private static final int DEFAULT_CHANNELS = 2;
private static final float DEFAULT_RATE = 44100.0F;
private static final AudioFileFormat.Type DEFAULT_TARGET_TYPE = AudioFileFormat.Type.WAVE;

private static boolean sm_bDebug = false;




/** TODO:
*/
public static void main(String[] args)
{
/*
* Parsing of command-line options takes place...
*/
String strMixerName = null;
int nInternalBufferSize = AudioSystem.NOT_SPECIFIED;
String strFormat = DEFAULT_FORMAT;
int nChannels = DEFAULT_CHANNELS;
float fRate = DEFAULT_RATE;
String strExtension = null;
boolean bDirectRecording = true;

/*
* Parsing of command-line options takes place...
*/
Getopt g = new Getopt("AudioRecorder", args, "hlLM:e:i:f:c:r:t:Ddb");
int c;
while ((c = g.getopt()) != -1)
{
switch (c)
{
case 'h':
printUsageAndExit();

case 'l':
AudioCommon.listMixersAndExit();

case 'L':
AudioCommon.listSupportedTargetTypes();
System.exit(0);

case 'M':
strMixerName = g.getOptarg();
if (sm_bDebug) { out("AudioRecorder.main(): mixer name: " + strMixerName); }
break;

case 'i':
nInternalBufferSize = Integer.parseInt(g.getOptarg());
break;

case 'f':
strFormat = g.getOptarg().toLowerCase();
break;

case 'c':
nChannels = Integer.parseInt(g.getOptarg());
break;

case 'r':
fRate = Float.parseFloat(g.getOptarg());
break;

case 't':
strExtension = g.getOptarg();
break;

case 'D':
sm_bDebug = true;
AudioCommon.setDebug(true);
out("AudioRecorder.main(): enabled debug messages");
break;

case 'd':
bDirectRecording = true;
out("AudioRecorder.main(): using direct recording");
break;

case 'b':
bDirectRecording = false;
out("AudioRecorder.main(): using buffered recording");
break;

case '?':
printUsageAndExit();

default:
out("getopt() returned " + c);
break;
}
}


/*
* We make shure that there is only one more argument, which
* we take as the filename of the soundfile to store to.
*/
String strFilename = null;
for (int i = g.getOptind(); i < args.length; i++)
{
if (strFilename == null)
{
strFilename = args[i];
}
else
{
printUsageAndExit();
}
}
if (sm_bDebug) { out("AudioRecorder.main(): output filename: " + strFilename); }
if (strFilename == null)
{
printUsageAndExit();
}

File outputFile = new File(strFilename);

/* For convenience, we have some shortcuts to set the
properties needed for constructing an AudioFormat.
*/
if (strFormat.equals("phone"))
{
// 8 kHz, 8 bit unsigned, mono
fRate = 8000.0F;
strFormat = "u8";
nChannels = 1;
}
else if (strFormat.equals("radio"))
{
// 22.05 kHz, 16 bit signed, mono
fRate = 22050.0F;
strFormat = "s16_le";
nChannels = 1;
}
else if (strFormat.equals("cd"))
{
// 44.1 kHz, 16 bit signed, stereo, little-endian
fRate = 44100.0F;
strFormat = "s16_le";
nChannels = 2;
}
else if (strFormat.equals("dat"))
{
// 48 kHz, 16 bit signed, stereo, little-endian
fRate = 48000.0F;
strFormat = "s16_le";
nChannels = 2;
}

/* Here, we are constructing the AudioFormat to use for the
recording. Sample rate (fRate) and number of channels
(nChannels) are already set safely, since they have
default values set at the very top. The other properties
needed for AudioFormat are derived from the 'format'
specification (strFormat).
*/
int nOutputFormatIndex = -1;
for (int i = 0; i < SUPPORTED_FORMATS.length; i++)
{
if (SUPPORTED_FORMATS[i].getName().equals(strFormat))
{
nOutputFormatIndex = i;
break;
}
}
/* If we haven't found the format (string) requested by the
user, we switch to a default format.
*/
if (nOutputFormatIndex == -1)
{
out("warning: output format '" + strFormat + "' not supported; using default output format '" + DEFAULT_FORMAT + "'");
/* This is the index of "s16_le". Yes, it's
a bit quick & dirty to hardcode the index here.
*/
nOutputFormatIndex = 2;
}
AudioFormat.Encoding encoding = SUPPORTED_FORMATS[nOutputFormatIndex].getEncoding();;
int nBitsPerSample = SUPPORTED_FORMATS[nOutputFormatIndex].getSampleSize();
boolean bBigEndian = SUPPORTED_FORMATS[nOutputFormatIndex].getBigEndian();
int nFrameSize = (nBitsPerSample / 8) * nChannels;
AudioFormat audioFormat = new AudioFormat(encoding, fRate, nBitsPerSample, nChannels, nFrameSize, fRate, bBigEndian);
if (sm_bDebug) { out("AudioRecorder.main(): target audio format: " + audioFormat); }

// extension
// TODO:


AudioFileFormat.Type targetType = null;
if (strExtension == null)
{
/* The user chose not to specify a target audio
file type explicitely. We are trying to guess
the type from the target file name extension.
*/
int nDotPosition = strFilename.lastIndexOf('.');
if (nDotPosition != -1)
{
strExtension = strFilename.substring(nDotPosition + 1);
}
}
if (strExtension != null)
{
targetType = AudioCommon.findTargetType(strExtension);
if (targetType == null)
{
out("target type '" + strExtension + "' is not supported.");
out("using default type '" + DEFAULT_TARGET_TYPE.getExtension() + "'");
targetType = DEFAULT_TARGET_TYPE;
}
}
else
{
out("target type is neither specified nor can be guessed from the target file name.");
out("using default type '" + DEFAULT_TARGET_TYPE.getExtension() + "'");
targetType = DEFAULT_TARGET_TYPE;
}
if (sm_bDebug) { out("AudioRecorder.main(): target audio file format type: " + targetType); }

TargetDataLine targetDataLine = null;
targetDataLine = AudioCommon.getTargetDataLine(
strMixerName, audioFormat, nInternalBufferSize);
if (targetDataLine == null)
{
out("can't get TargetDataLine, exiting.");
System.exit(1);
}

Recorder recorder = null;
if (bDirectRecording)
{
recorder = new DirectRecorder(
targetDataLine,
targetType,
outputFile);
}
else
{
recorder = new BufferingRecorder(
targetDataLine,
targetType,
outputFile);
}
if (sm_bDebug) { out("AudioRecorder.main(): Recorder: " + recorder); }

out("Press ENTER to start the recording.");
try
{
System.in.read();
}
catch (IOException e)
{
e.printStackTrace();
}
recorder.start();
out("Recording...");
out("Press ENTER to stop the recording.");
try
{
System.in.read();
}
catch (IOException e)
{
e.printStackTrace();
}
recorder.stopRecording();
out("Recording stopped.");
// System.exit(0);
}



private static void printUsageAndExit()
{
out("AudioRecorder: usage:");
out("\tjava AudioRecorder -l");
out("\tjava AudioRecorder -L");
out("\tjava AudioRecorder [-f ] [-c ] [-r ] [-t ] [-M ] ");
System.exit(0);
}



/** TODO:
*/
private static void out(String strMessage)
{
System.out.println(strMessage);
}



///////////// inner classes ////////////////////


/** TODO:
*/
private static class SupportedFormat
{
/** The name of the format.
*/
private String m_strName;

/** The encoding of the format.
*/
private AudioFormat.Encoding m_encoding;

/** The sample size of the format.
This value is in bits for a single sample
(not for a frame).
*/
private int m_nSampleSize;

/** The endianess of the format.
*/
private boolean m_bBigEndian;

// sample size is in bits
/** Construct a new supported format.
@param strName the name of the format.
@param encoding the encoding of the format.
@param nSampleSize the sample size of the format, in bits.
@param bBigEndian the endianess of the format.
*/
public SupportedFormat(String strName,
AudioFormat.Encoding encoding,
int nSampleSize,
boolean bBigEndian)
{
m_strName = strName;
m_encoding = encoding;
m_nSampleSize = nSampleSize;
}

/** Returns the name of the format.
*/
public String getName()
{
return m_strName;
}

/** Returns the encoding of the format.
*/
public AudioFormat.Encoding getEncoding()
{
return m_encoding;
}

/** Returns the sample size of the format.
This value is in bits.
*/
public int getSampleSize()
{
return m_nSampleSize;
}

/** Returns the endianess of the format.
*/
public boolean getBigEndian()
{
return m_bBigEndian;
}
}


///////////////////////////////////////////////


public static interface Recorder
{
public void start();

public void stopRecording();
}



public static class AbstractRecorder
extends Thread
implements Recorder
{
protected TargetDataLine m_line;
protected AudioFileFormat.Type m_targetType;
protected File m_file;
protected boolean m_bRecording;



public AbstractRecorder(TargetDataLine line,
AudioFileFormat.Type targetType,
File file)
{
m_line = line;
m_targetType = targetType;
m_file = file;
}



/** Starts the recording.
* To accomplish this, (i) the line is started and (ii) the
* thread is started.
*/
public void start()
{
m_line.start();
super.start();
}



public void stopRecording()
{
m_line.drain();
m_line.stop();
m_line.close();
m_bRecording = false;
}
}



public static class DirectRecorder
extends AbstractRecorder
{
private AudioInputStream m_audioInputStream;



public DirectRecorder(TargetDataLine line,
AudioFileFormat.Type targetType,
File file)
{
super(line, targetType, file);
m_audioInputStream = new AudioInputStream(line);
}



public void run()
{
try
{
if (sm_bDebug) { out("before AudioSystem.write"); }
AudioSystem.write(
m_audioInputStream,
m_targetType,
m_file);
if (sm_bDebug) { out("after AudioSystem.write"); }
}
catch (IOException e)
{
e.printStackTrace();
}
}



}



public static class BufferingRecorder
extends AbstractRecorder
{
public BufferingRecorder(TargetDataLine line,
AudioFileFormat.Type targetType,
File file)
{
super(line, targetType, file);
}



public void run()
{
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
OutputStream outputStream = byteArrayOutputStream;
// TODO: intelligent size
byte[] abBuffer = new byte[65536];
AudioFormat format = m_line.getFormat();
int nFrameSize = format.getFrameSize();
int nBufferFrames = abBuffer.length / nFrameSize;
m_bRecording = true;
while (m_bRecording)
{
if (sm_bDebug) { out("BufferingRecorder.run(): trying to read: " + nBufferFrames); }
int nFramesRead = m_line.read(abBuffer, 0, nBufferFrames);
if (sm_bDebug) { out("BufferingRecorder.run(): read: " + nFramesRead); }
int nBytesToWrite = nFramesRead * nFrameSize;
try
{
outputStream.write(abBuffer, 0, nBytesToWrite);
}
catch (IOException e)
{
e.printStackTrace();
}
}

/* We close the ByteArrayOutputStream.
*/
try
{
byteArrayOutputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}


byte[] abData = byteArrayOutputStream.toByteArray();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(abData);

AudioInputStream audioInputStream = new AudioInputStream(byteArrayInputStream, format, abData.length / format.getFrameSize());
try
{
AudioSystem.write(audioInputStream, m_targetType, m_file);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}



/*** AudioRecorder.java ***/

An MP3Encoder in Java



/*
* Mp3Encoder.java
*
* This file is part of jsresources.org
*/

/*
* Copyright (c) 2000 by Florian Bomers
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/*
|<--- this code is formatted to fit into 80 columns --->|
*/

import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;


public class Mp3Encoder {
private static boolean DEBUG = false;
private static boolean dumpExceptions=false;
private static boolean traceConverters=false;
private static boolean quiet=false;

private static final AudioFormat.Encoding MPEG1L3 = new AudioFormat.Encoding("MPEG1L3");
private static final AudioFileFormat.Type MP3 = new AudioFileFormat.Type("MP3", "mp3");



private static AudioInputStream getInStream(String filename)
throws IOException {
File file = new File(filename);
AudioInputStream ais = null;
try {
ais = AudioSystem.getAudioInputStream(file);
} catch (Exception e) {
if (dumpExceptions) {
e.printStackTrace();
} else if (!quiet) {
System.out.println("Error: " + e.getMessage());
}
}
if (ais == null) {
throw new IOException("Cannot open \"" + filename + "\"");
}
return ais;
}



public static String stripExtension(String filename) {
int ind = filename.lastIndexOf(".");
if (ind == -1
|| ind == filename.length()
|| filename.lastIndexOf(File.separator) > ind) {
// when dot is at last position,
// or a slash is after the dot, there isn't an extension
return filename;
}
return filename.substring(0, ind);
}



/* first version. Remains here for documentation how to
* get a stream with complete description of the target format.
*/
public static AudioInputStream getConvertedStream2(
AudioInputStream sourceStream,
AudioFormat.Encoding targetEncoding)
throws Exception {
AudioFormat sourceFormat = sourceStream.getFormat();
if (!quiet) {
System.out.println("Input format: " + sourceFormat);
}
// build the output format
AudioFormat targetFormat = new AudioFormat(
targetEncoding,
sourceFormat.getSampleRate(),
AudioSystem.NOT_SPECIFIED,
sourceFormat.getChannels(),
AudioSystem.NOT_SPECIFIED,
AudioSystem.NOT_SPECIFIED,
false); // endianness doesn't matter
// construct a converted stream
AudioInputStream targetStream = null;
if (!AudioSystem.isConversionSupported(targetFormat, sourceFormat)) {
if (DEBUG && !quiet) {
System.out.println("Direct conversion not possible.");
System.out.println("Trying with intermediate PCM format.");
}
AudioFormat intermediateFormat = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED,
sourceFormat.getSampleRate(),
16,
sourceFormat.getChannels(),
2 * sourceFormat.getChannels(), // frameSize
sourceFormat.getSampleRate(),
false);
if (AudioSystem.isConversionSupported(intermediateFormat, sourceFormat)) {
// intermediate conversion is supported
sourceStream = AudioSystem.getAudioInputStream(intermediateFormat, sourceStream);
}
}
targetStream = AudioSystem.getAudioInputStream(targetFormat, sourceStream);
if (targetStream == null) {
throw new Exception("conversion not supported");
}
if (!quiet) {
if (DEBUG) {
System.out.println("Got converted AudioInputStream: " + targetStream.getClass().getName());
}
System.out.println("Output format: " + targetStream.getFormat());
}
return targetStream;
}



public static AudioInputStream getConvertedStream(
AudioInputStream sourceStream,
AudioFormat.Encoding targetEncoding)
throws Exception {
AudioFormat sourceFormat = sourceStream.getFormat();
if (!quiet) {
System.out.println("Input format: " + sourceFormat);
}

// construct a converted stream
AudioInputStream targetStream = null;
if (!AudioSystem.isConversionSupported(targetEncoding, sourceFormat)) {
if (DEBUG && !quiet) {
System.out.println("Direct conversion not possible.");
System.out.println("Trying with intermediate PCM format.");
}
AudioFormat intermediateFormat = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED,
sourceFormat.getSampleRate(),
16,
sourceFormat.getChannels(),
2 * sourceFormat.getChannels(), // frameSize
sourceFormat.getSampleRate(),
false);
if (AudioSystem.isConversionSupported(intermediateFormat, sourceFormat)) {
// intermediate conversion is supported
sourceStream = AudioSystem.getAudioInputStream(intermediateFormat, sourceStream);
}
}
targetStream = AudioSystem.getAudioInputStream(targetEncoding, sourceStream);
if (targetStream == null) {
throw new Exception("conversion not supported");
}
if (!quiet) {
if (DEBUG) {
System.out.println("Got converted AudioInputStream: " + targetStream.getClass().getName());
}
System.out.println("Output format: " + targetStream.getFormat());
}
return targetStream;
}



public static int writeFile(String inFilename) {
int writtenBytes = -1;
try {
AudioFileFormat.Type targetType = MP3;
AudioInputStream ais = getInStream(inFilename);
ais = getConvertedStream(ais, MPEG1L3);

// construct the target filename
String outFilename = stripExtension(inFilename) + "." + targetType.getExtension();

// write the file
if (!quiet) {
System.out.println("Writing " + outFilename + "...");
}
writtenBytes = AudioSystem.write(ais, targetType, new File(outFilename));
if (DEBUG && !quiet) {
System.out.println("Effective parameters of output file:");
try {
String version=System.getProperty("tritonus.lame.encoder.version", "");
if (version!="") {
System.out.println(" Version = "+version);
}
System.out.println(" Quality = "+System.getProperty
("tritonus.lame.effective.quality", ""));
System.out.println(" Bitrate = "+System.getProperty
("tritonus.lame.effective.bitrate", ""));
System.out.println(" Channel Mode = "+System.getProperty
("tritonus.lame.effective.chmode", ""));
System.out.println(" VBR mode = "+System.getProperty
("tritonus.lame.effective.vbr", ""));
System.out.println(" Sample rate = "+System.getProperty
("tritonus.lame.effective.samplerate", ""));
System.out.println(" Encoding = "+System.getProperty
("tritonus.lame.effective.encoding", ""));
} catch (Throwable t1) {}
}
} catch (Throwable t) {
if (dumpExceptions) {
t.printStackTrace();
} else if (!quiet) {
System.out.println("Error: " + t.getMessage());
}
}
return writtenBytes;
}



// returns the first index in args where the files start
public static int parseArgs(String[] args) {
if (args.length == 0) {
usage();
}
// parse options
try {
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if (arg.equals("--help")) {
usage();
}
if (arg.length() > 3 || arg.length() < 2 || !arg.startsWith("-")) {
return i;
}
char cArg = arg.charAt(1);
// options without parameter
if (cArg == 'v') {
DEBUG=true;
continue;
} else if (cArg == 'e') {
dumpExceptions=true;
continue;
} else if (cArg == 't') {
org.tritonus.share.TDebug.TraceAudioConverter=true;
continue;
} else if (cArg == 's') {
quiet=true;
continue;
} else if (cArg == 'V') {
try {
System.setProperty("tritonus.lame.vbr", "true");
} catch (Throwable t1) {}
continue;
} else if (cArg == 'h') {
usage();
}
// options with parameter
if (args.length < i + 2) {
throw new Exception("Missing parameter or unrecognized option "+arg+".");
}
String param = args[i + 1];
i++;
switch (cArg) {
case 'q':
try {
System.setProperty("tritonus.lame.quality", param);
} catch (Throwable t2) {}
break;
case 'b':
try {
System.setProperty("tritonus.lame.bitrate", param);
} catch (Throwable t3) {}
break;
default:
throw new Exception("Unrecognized option "+arg+".");
}
}
throw new Exception("No input file(s) are given.");
} catch (Exception e) {
System.err.println(e.getMessage());
System.exit(1);
}
return 0; // statement not reached
}



public static void main(String[] args) {
//try {
// System.out.println("Librarypath=" + System.getProperty("java.library.path", ""));
//} catch (Throwable t) {}

int firstFileIndex = parseArgs(args);
int inputFiles = 0;
int success = 0;
long totalTime = System.currentTimeMillis();
for (int i = firstFileIndex; i < args.length; i++) {
long time = System.currentTimeMillis();
int bytes = writeFile(args[i]);
time = System.currentTimeMillis()-time;
inputFiles++;
if (bytes >= 0) {
if (bytes > 0) {
success++;
}
if (!quiet) {
System.out.println("Wrote " + bytes + " bytes in "
+ (time / 60000) + "m " + ((time/1000) % 60) + "s "
+ (time % 1000) + "ms ("
+ (time/1000) + "s).");
}
}
}
totalTime = System.currentTimeMillis() - totalTime;
if ((DEBUG && quiet) || !quiet) {
// this IS displayed in silent DEBUG mode
System.out.println("From " + inputFiles + " input file" + (inputFiles == 1 ? "" : "s") + ", "
+ success + " file" + (success == 1 ? " was" : "s were") + " converted successfully in "
+ (totalTime / 60000) + "m " + ((totalTime/1000) % 60) + "s ("
+ (totalTime/1000) + "s).");
}
System.exit(0);
}



/** Display a message of how to call this program.
*/
public static void usage() {
System.out.println("Mp3Encoder - convert audio files to mp3 (layer III of MPEG 1, MPEG 2 or MPEG 2.5");
System.out.println("java Mp3Encoder [...]");
System.out.println("The output file(s) will be named like the source file(s) but");
System.out.println("with mp3 file extension.");
System.out.println("");
System.out.println("You need LAME 3.88 or later. Get it from http://sourceforge.net/projects/lame/");
System.out.println("");
System.out.println(" may be a combination of the following:");
System.out.println("-q Quality of output mp3 file. In VBR mode, this affects");
System.out.println(" the size of the mp3 file. (Default middle)");
System.out.println(" One of: lowest, low, middle, high, highest");
System.out.println("-b Bitrate in KBit/s. Useless in VBR mode. (Default 128)");
System.out.println(" One of: 32 40 48 56 64 80 96 112 128 160 192 224 256 320 (MPEG1)");
System.out.println(" Or: 8 16 24 32 40 48 56 64 80 96 112 128 144 160 (MPEG2 and MPEG2.5");
System.out.println("-V VBR (variable bit rate) mode. Slower, but potentially better");
System.out.println(" quality. (Default off)");
System.out.println("-v Be verbose.");
System.out.println("-s Be silent.");
System.out.println("-e Debugging: Dump stack trace of exceptions.");
System.out.println("-t Debugging: trace execution of converters.");
System.out.println("-h | --help Show this message.");
System.exit(1);
}

}



/*** Mp3Encoder.java ***/

Scheduling A Task In Java


import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class TimedTask {

public final static int ONE_TIME_TASK = 0;
public final static int REPEATING_INTERVAL_TASK = 1;

private int type;
private long milliseconds;
private int delay;
private int period;
private Timer timer;


public TimedTask(final long t) {
type = 0;
delay = 0;
period = 0;
milliseconds = t;
timer = new Timer();
}

public TimedTask(final int Delay, final int Period) {
type = 0;
delay = Delay;
period = Period;
milliseconds = 0L;
timer = new Timer();
}

public void startTimer(final TimerTask t) {
if (type == 0) {
final Date timeToRun = new Date(System.currentTimeMillis() + milliseconds);
timer.schedule(t, timeToRun);
} else {
timer.scheduleAtFixedRate(t, delay, period);
}
}


}

Using JavaScript in Java

Here is the JavaScript (Rhino) Class I use.

Cheers,

Ted




import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.Scriptable;

import java.util.ArrayList;

// http://lxr.mozilla.org/mozilla/source/js/rhino/

public class JavaScriptPlugin {

private String name;
private String script;
private ArrayList parameters = new ArrayList(13);

public JavaScriptPlugin() {
name = "Un-named Plugin";
script = "";
}

public JavaScriptPlugin(final String pluginName, final String scriptText) {
name = pluginName;
script = scriptText;
}

public String getName() {
return name;
}

public String getScript() {
return script;
}

public void setName(final String pluginName) {
name = pluginName;
}

public void setScript(final String scriptText) {
name = scriptText;
}

public String evalToString() throws Exception {
final Context context = Context.enter();
String result = "";
try {
final Scriptable scope = context.initStandardObjects();
if (scope != null) {
context.evaluateString(scope, script, "", 1, null);
final Object fObj = scope.get("function", scope);
if (fObj.getClass().getName().contains("Function")) {
final Object[] functionArgs = parameters.toArray();
final Function f = (Function) fObj;
final Object obj = f.call(context, scope, scope, functionArgs);
result = Context.toString(obj);
}
}
} catch (Exception e) {
try {
throw e;
} catch (Exception ee) {
}
} finally {
Context.exit();
}
return Context.toString(result);
}

public Object evalToObject() {
final Context context = Context.enter();
Object result = null;
try {
final Scriptable scope = context.initStandardObjects();
if (scope != null) {
context.evaluateString(scope, script, "", 1, null);
final Object fObj = scope.get("function", scope);
if (fObj.getClass().getName().contains("Function")) {
final Object[] functionArgs = parameters.toArray();
final Function f = (Function) fObj;
result = f.call(context, scope, scope, functionArgs);
}
}
} catch (Exception e) {
try {
throw e;
} catch (Exception ee) {
}
} finally {
Context.exit();
}
return result;
}

public void addParameter(final String param) {
parameters.add(param);
}

public void removeParameter(final int i) {
parameters.remove(i);
}

public void removeParameter(final String param) {
parameters.remove(param);
}

public void clearParameters() {
parameters.clear();
}

public Object[] getParameters() {
return parameters.toArray();
}

public void setParameters(final String... params) {
parameters.clear();
for (String param : params) {
if (param != null) {
parameters.add(param);
} else {
parameters.add("");
}
}
}

public static void close() {

}

}

Standard Fonts in Java

My standard font class

cheers,

Ted



import java.awt.*;

public class StandardFont {

public Font serifPlain(final int size) {
return new Font("Serif", Font.PLAIN, size);
}

public Font serifBold(final int size) {
return new Font("Serif", Font.BOLD, size);
}

public Font serifItalic(final int size) {
return new Font("Serif", Font.ITALIC, size);
}

public Font serifBoldItalic(final int size) {
return new Font("Serif", Font.BOLD + Font.ITALIC, size);
}

public Font sansSerifPlain(final int size) {
return new Font("SansSerif", Font.PLAIN, size);
}

public Font sansSerifBold(final int size) {
return new Font("SansSerif", Font.BOLD, size);
}

public Font sansSerifItalic(final int size) {
return new Font("SansSerif", Font.ITALIC, size);
}

public Font sansSerifBoldItalic(final int size) {
return new Font("SansSerif", Font.BOLD + Font.ITALIC, size);
}

public Font monospacedPlain(final int size) {
return new Font("Monospaced", Font.PLAIN, size);
}

public Font monospacedBold(final int size) {
return new Font("Monospaced", Font.BOLD, size);
}

public Font monospacedItalic(final int size) {
return new Font("Monospaced", Font.ITALIC, size);
}

public Font monospacedBoldItalic(final int size) {
return new Font("Monospaced", Font.BOLD + Font.ITALIC, size);
}

}

System Fonts in Java

Here is my font class.

Cheers,

Ted



import java.awt.*;

public class SystemFont {
public String[] systemFontNames;

public SystemFont() {
systemFontNames = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
}

public Font getPlainFont(final String fontName, final int size) {
return new Font(fontName, Font.PLAIN, size);
}

public Font getBoldFont(final String fontName, final int size) {
return new Font(fontName, Font.BOLD, size);
}

public Font getItalicFont(final String fontName, final int size) {
return new Font(fontName, Font.ITALIC, size);
}

public Font getBoldItalicFont(final String fontName, final int size) {
return new Font(fontName, Font.ITALIC | Font.BOLD, size);
}
}

Creating BarcodeEAN Images in Java

A BarcodeEAN Class

Cheers,

Ted



import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.PageSize;
import com.lowagie.text.pdf.BarcodeEAN;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfWriter;

import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.ImageObserver;
import java.io.ByteArrayOutputStream;


public class BarcodeEANImage implements ImageObserver {

private Image image;
private com.lowagie.text.Image pdfImage;

public BarcodeEANImage(final String data) {
final BarcodeEAN shipBarCode = new BarcodeEAN();
shipBarCode.setX(0.75f);
shipBarCode.setN(1.5f);
shipBarCode.setChecksumText(true);
shipBarCode.setGenerateChecksum(true);
shipBarCode.setSize(8f);
shipBarCode.setTextAlignment(Element.ALIGN_CENTER);
shipBarCode.setBaseline(10f);
shipBarCode.setCode(data);
shipBarCode.setBarHeight(50f);
image = shipBarCode.createAwtImage(Color.BLACK, Color.BLACK);
final Document doc = new Document(PageSize.LETTER, 0, 0, 0, 0); //, Left, Right, 40, 36
doc.setMargins(24f, 24f, 24f, 24f);
final ByteArrayOutputStream out = new ByteArrayOutputStream();
PdfWriter pdfw = null;
try {
pdfw = PdfWriter.getInstance(doc, out);
} catch (Exception e) {
e.printStackTrace();
}
pdfImage = shipBarCode.createImageWithBarcode(new PdfContentByte(pdfw), Color.BLACK, Color.BLACK);
}

public BarcodeEANImage(final PdfContentByte cb, final String data) {
final BarcodeEAN shipBarCode = new BarcodeEAN();
shipBarCode.setX(0.75f);
shipBarCode.setN(1.5f);
shipBarCode.setChecksumText(true);
shipBarCode.setGenerateChecksum(true);
shipBarCode.setSize(8f);
shipBarCode.setTextAlignment(Element.ALIGN_CENTER);
shipBarCode.setBaseline(10f);
shipBarCode.setCode(data);
shipBarCode.setBarHeight(50f);
image = shipBarCode.createAwtImage(Color.BLACK, Color.BLACK);
pdfImage = shipBarCode.createImageWithBarcode(cb, Color.BLACK, Color.BLACK);
}

public Image getImage(final double degrees) {
final Graphics2D g2 = (Graphics2D) image.getGraphics();
g2.drawImage(image, 0, 0, this);
final AffineTransform tx = new AffineTransform();
tx.rotate(Math.toRadians(degrees));
g2.transform(tx);
return image;
}

public com.lowagie.text.Image getPdfImage(final double degrees) {
pdfImage.setRotation(new Float(Math.toRadians(degrees)));
return pdfImage;
}

public boolean imageUpdate(final Image img, final int infoflags, final int x, final int y, final int Width, final int Height) {
if ((infoflags & ImageObserver.WIDTH) != 0 && (infoflags & ImageObserver.HEIGHT) != 0) {
}
return true;
}
}

Creating Barcode39 Images in Java

A Barcode39 Class



import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.PageSize;
import com.lowagie.text.pdf.Barcode39;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfWriter;

import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.ImageObserver;
import java.io.ByteArrayOutputStream;


public class Barcode39Image implements ImageObserver {

private Image image;
private com.lowagie.text.Image pdfImage;

public Barcode39Image(final String data) {
final Barcode39 shipBarCode = new Barcode39();
shipBarCode.setX(0.75f);
shipBarCode.setN(1.5f);
shipBarCode.setChecksumText(true);
shipBarCode.setGenerateChecksum(true);
shipBarCode.setSize(8f);
shipBarCode.setTextAlignment(Element.ALIGN_CENTER);
shipBarCode.setBaseline(10f);
shipBarCode.setCode(data);
shipBarCode.setBarHeight(50f);
image = shipBarCode.createAwtImage(Color.BLACK, Color.BLACK);
final Document doc = new Document(PageSize.LETTER, 0, 0, 0, 0); //, Left, Right, 40, 36
doc.setMargins(24f, 24f, 24f, 24f);
final ByteArrayOutputStream out = new ByteArrayOutputStream();
PdfWriter pdfw = null;
try {
pdfw = PdfWriter.getInstance(doc, out);
} catch (Exception e) {
e.printStackTrace();
}
pdfImage = shipBarCode.createImageWithBarcode(new PdfContentByte(pdfw), Color.BLACK, Color.BLACK);
}

public Barcode39Image(final PdfContentByte cb, final String data) {
final Barcode39 shipBarCode = new Barcode39();
shipBarCode.setX(0.75f);
shipBarCode.setN(1.5f);
shipBarCode.setChecksumText(true);
shipBarCode.setGenerateChecksum(true);
shipBarCode.setSize(8f);
shipBarCode.setTextAlignment(Element.ALIGN_CENTER);
shipBarCode.setBaseline(10f);
shipBarCode.setCode(data);
shipBarCode.setBarHeight(50f);
image = shipBarCode.createAwtImage(Color.BLACK, Color.BLACK);
pdfImage = shipBarCode.createImageWithBarcode(cb, Color.BLACK, Color.BLACK);
}

public Image getImage(final double degrees) {
final Graphics2D g2 = (Graphics2D) image.getGraphics();
g2.drawImage(image, 0, 0, this);
final AffineTransform tx = new AffineTransform();
tx.rotate(Math.toRadians(degrees));
g2.transform(tx);
return image;
}

public com.lowagie.text.Image getPdfImage(final double degrees) {
pdfImage.setRotation(new Float(Math.toRadians(degrees)));
return pdfImage;
}

public boolean imageUpdate(final Image img, final int infoflags, final int x, final int y, final int Width, final int Height) {
if ((infoflags & ImageObserver.WIDTH) != 0 && (infoflags & ImageObserver.HEIGHT) != 0) {
}
return true;
}
}

Creating Barcode128 Images in Java

A Barcode128 class

Cheers,

Ted




import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.PageSize;
import com.lowagie.text.pdf.Barcode128;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfWriter;

import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.ImageObserver;
import java.io.ByteArrayOutputStream;


public class Barcode128Image implements ImageObserver {

private Image image;
private com.lowagie.text.Image pdfImage;

public Barcode128Image(final String data) {
final Barcode128 shipBarCode = new Barcode128();
shipBarCode.setX(0.75f);
shipBarCode.setN(1.5f);
shipBarCode.setChecksumText(true);
shipBarCode.setGenerateChecksum(true);
shipBarCode.setSize(8f);
shipBarCode.setTextAlignment(Element.ALIGN_CENTER);
shipBarCode.setBaseline(10f);
shipBarCode.setCode(data);
shipBarCode.setBarHeight(50f);
image = shipBarCode.createAwtImage(Color.BLACK, Color.BLACK);
final Document doc = new Document(PageSize.LETTER, 0, 0, 0, 0); //, Left, Right, 40, 36
doc.setMargins(24f, 24f, 24f, 24f);
final ByteArrayOutputStream out = new ByteArrayOutputStream();
PdfWriter pdfw = null;
try {
pdfw = PdfWriter.getInstance(doc, out);
} catch (Exception e) {
e.printStackTrace();
}
pdfImage = shipBarCode.createImageWithBarcode(new PdfContentByte(pdfw), Color.BLACK, Color.BLACK);
}

public Barcode128Image(final PdfContentByte cb, final String data) {
final Barcode128 shipBarCode = new Barcode128();
shipBarCode.setX(0.75f);
shipBarCode.setN(1.5f);
shipBarCode.setChecksumText(true);
shipBarCode.setGenerateChecksum(true);
shipBarCode.setSize(8f);
shipBarCode.setTextAlignment(Element.ALIGN_CENTER);
shipBarCode.setBaseline(10f);
shipBarCode.setCode(data);
shipBarCode.setBarHeight(50f);
image = shipBarCode.createAwtImage(Color.BLACK, Color.BLACK);
pdfImage = shipBarCode.createImageWithBarcode(cb, Color.BLACK, Color.BLACK);
}

public Image getImage(final double degrees) {
final Graphics2D g2 = (Graphics2D) image.getGraphics();
g2.drawImage(image, 0, 0, this);
final AffineTransform tx = new AffineTransform();
tx.rotate(Math.toRadians(degrees));
g2.transform(tx);
return image;
}

public com.lowagie.text.Image getPdfImage(final double degrees) {
pdfImage.setRotation(new Float(Math.toRadians(degrees)));
return pdfImage;
}

public boolean imageUpdate(final Image img, final int infoflags, final int x, final int y, final int Width, final int Height) {
if ((infoflags & ImageObserver.WIDTH) != 0 && (infoflags & ImageObserver.HEIGHT) != 0) {
}
return true;
}
}

Benchmarks in Java

It is good practice to time your code... It gives a good measure of how changes affect performance.

Cheers,

Ted

A Benchmark Class


import java.util.Date;

public class Benchmark {
public Date startTime;
public Date stopTime;
public Double seconds;
public int precision;

public Benchmark() {
startTime = null;
stopTime = null;
seconds = 0D;
}

public void startTiming() {
if (startTime == null) {
startTime = new Date();
} else {
try {
throw new Exception("Benchmark has already been started");
} catch (Exception e) {
}
}
}

public void stopTiming() {
stopTime = new Date();
seconds = (stopTime.getTime() - startTime.getTime()) / 1000D;
}

}



A Simple Class To Manage Your Benchmarks


import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;

public class BenchmarkManager {
private ConcurrentHashMap benchmarks;
private ArrayList keyOrder;
private DecimalFormat df = new DecimalFormat();

public BenchmarkManager() {
benchmarks = new ConcurrentHashMap(13);
keyOrder = new ArrayList(13);
}

public void addBenchmark(final String name) {
if (benchmarks.containsKey(name)) {
benchmarks.putIfAbsent(name, new Benchmark());
keyOrder.add(name);
}
}

public void removeBenchmark(final String name) {
if (benchmarks.containsKey(name)) {
benchmarks.remove(name);
keyOrder.remove(name);
}
}

public void clearBenchmarks() {
benchmarks.clear();
keyOrder.clear();
}

public Benchmark getBenchmark(final String name) {
Benchmark result = null;
if (benchmarks.containsKey(name)) {
result = benchmarks.get(name);
}
return result;
}

public void startBenchmark(final String name) {
if (benchmarks.containsKey(name)) {
benchmarks.get(name).startTiming();
}
}

public void stopBenchmark(final String name) {
if (benchmarks.containsKey(name)) {
benchmarks.get(name).stopTiming();
}
}

public String getBenchmarkString(final String name) {
String result = null;
if (benchmarks.containsKey(name)) {
final Benchmark temp = benchmarks.get(name);
df.setMaximumFractionDigits(temp.precision);
result = name+ ": " + df.format(temp.seconds)+ " seconds.";
}
return result;
}

public String getBenchmarkReport() {
String result = null;
for (String key : keyOrder) {
result += getBenchmarkString(key)+ "\n";
}
return result;
}
}

Large Bit Masks in Java

Here is the class I use for large bit masks in java...

Cheers,

Ted

A Large BitMask Class


public class BitMask {

private BigInteger storage;

public BitMask() {
storage = new BigInteger("0");
}

public BigInteger getBigInteger() {
return storage;
}

public void setBigInteger(final BigInteger i) {
storage = i;
}

public boolean testBit(final int i) {
return storage.testBit(i);
}

public void setBit(final int i) {
storage = storage.setBit(i);
}

public void clearBit(final int i) {
storage = storage.clearBit(i);
}

public void flipBit(final int i) {
storage = storage.flipBit(i);
}

public void shiftLeft(final int i) {
storage = storage.shiftLeft(i);
}

public void shiftRight(final int i) {
storage = storage.shiftRight(i);
}

public void xor(final BigInteger bi) {
storage = storage.xor(bi);
}

public void and(final BigInteger bi) {
storage = storage.and(bi);
}

public void not() {
storage = storage.not();
}

public void or(final BigInteger bi) {
storage = storage.or(bi);
}

public void andNot(final BigInteger bi) {
storage = storage.andNot(bi);
}

public BigInteger binaryStringToBigInteger(String input) {
return new BigInteger(input, 2);
}

public String bigIntegerToBinaryString(BigInteger bi) {
return bi.toString(2);
}
}


A Simple Class to Manage Your BitMasks

import java.util.concurrent.ConcurrentHashMap;

public class BitMaskManager {

public ConcurrentHashMap masks;

public BitMaskManager() {
masks = new ConcurrentHashMap(3);
}

public void addBitMask(final String name) {
masks.putIfAbsent(name, new BitMask());
}

public void removeBitMask(final String name) {
if (masks.containsKey(name)) {
masks.remove(name);
}
}

public void clearBitMasks(final String name) {
masks.clear();
}

public BitMask getBitMask(final String name) {
BitMask result = null;
if (masks.containsKey(name)) {
result = masks.get(name);
}
return result;
}

}

DES Encrypting and Decrypting File in Java

Sometimes you need to keep some secrets...

Cheers,

Ted



import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.imageio.ImageIO;

public static void encryptStream(final InputStream in, OutputStream out, final SecretKey key) {
final byte[] iv = new byte[]{
(byte) 0x8E, 0x12, 0x39, (byte) 0x9C,
0x07, 0x72, 0x6F, 0x5A
};
final AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
try {
final Cipher ecipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
out = new CipherOutputStream(out, ecipher);
int numRead = 0;
final byte[] buf = new byte[1024];
while ((numRead = in.read(buf)) >= 0) {
out.write(buf, 0, numRead);
}
out.close();
} catch (Exception e) {
}
}

public static void decryptStream(InputStream in, final OutputStream out, final SecretKey key) {
final byte[] iv = new byte[]{
(byte) 0x8E, 0x12, 0x39, (byte) 0x9C,
0x07, 0x72, 0x6F, 0x5A
};
final AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
try {
final Cipher dcipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
in = new CipherInputStream(in, dcipher);
int numRead = 0;
final byte[] buf = new byte[1024];
while ((numRead = in.read(buf)) >= 0) {
out.write(buf, 0, numRead);
}
out.close();
} catch (Exception e) {
}
}

public static SecretKey passphrase(final String input) {
SecretKey result = null;
final byte[] salt = {
(byte) 0xA9, (byte) 0x9B, (byte) 0xC8, (byte) 0x32,
(byte) 0x56, (byte) 0x35, (byte) 0xE3, (byte) 0x03
};
try {
final KeySpec keySpec = new PBEKeySpec(input.toCharArray(), salt, 19);
result = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
} catch (Exception e) {
}
return result;
}

public static void desEncryptFile(final File input, final File output, final String passphrase) {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(input);
out = new FileOutputStream(output);
encryptStream(in, out, passphrase(passphrase));
} catch (Exception e) {
// something here
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (Exception ee) {
}
}
}

public static void desDecryptFile(final File input, final File output, final String passphrase) {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(input);
out = new FileOutputStream(output);
decryptStream(in, out, passphrase(passphrase));
} catch (Exception e) {
//something here
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (Exception ee) {
}
}
}

Saving Buffered Images As Various Image Formats in Java (PNG, JPG, GIF, TIFF, BMP)

Often it is useful to save images to disk in various formats.

Cheers,

Ted



import javax.imageio.ImageIO;

public void saveBufferedImageAsPNG(final BufferedImage image, final File file) {
try {
ImageIO.write(image, "png", file);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}

public void saveBufferedImageAsJPG(final BufferedImage image, final File file) {
try {
ImageIO.write(image, "jpg", file);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}

public void saveBufferedImageAsBMP(final BufferedImage image, final File file) {
try {
ImageIO.write(image, "bmp", file);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}

public void saveBufferedImageAsGIF(final BufferedImage image, final File file) {
try {
ImageIO.write(image, "gif", file);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}

public void saveBufferedImageAsTIFF(final BufferedImage image, final File file) {
try {
ImageIO.write(image, "tiff", file);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}

Screen Capture in Java

Here is the class I use for Screen Captures...

Cheers,

Ted



import java.awt.*;
import java.awt.image.BufferedImage;

public class ScreenCapture {

private BufferedImage bufferedImage;

public BufferedImage getBufferedImage() {
return bufferedImage;
}

public ScreenCapture() {
bufferedImage = null;
try {
final Robot robot = new Robot();
final Rectangle area = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
bufferedImage = robot.createScreenCapture(area);
} catch (AWTException e) {
}
}

public ScreenCapture(final int x, final int y, final int width, final int height) {
bufferedImage = null;
try {
final Robot robot = new Robot();
final Rectangle area = new Rectangle(x, y, width, height);
bufferedImage = robot.createScreenCapture(area);
} catch (AWTException e) {
}
}
}

(Windows Registry) Application Preferences in Java

Preferences behave like the windows registry but in a cross platform way. If you actually need to much the the windows registry then you will need to use JNI.

Cheers,


Ted

A Simple Class To Manager your Preferences



import java.util.concurrent.ConcurrentHashMap;

public class PreferencesManager {

public ConcurrentHashMap sets;

public PreferencesManager() {
sets = new ConcurrentHashMap(3);
}

public void addSet(final String name) {
sets.putIfAbsent(name, new PreferenceSet());
}

public void removeSet(final String name) {
if (sets.containsKey(name)) {
sets.remove(name);
}
}

public void clearSets(final String name) {
sets.clear();
}

public PreferenceSet getSet(final String name) {
PreferenceSet result = null;
if (sets.containsKey(name)) {
result = sets.get(name);
}
return result;
}
}


A Preferences Class



import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;

public class PreferenceSet {

private Preferences prefs;

public PreferenceSet() {
prefs = Preferences.userNodeForPackage(super.getClass());
}

public void setNode(final Class c) {
prefs = Preferences.userNodeForPackage(c);
}

public String getPreference(final String name, final String defaultValue) {
return prefs.get(name, defaultValue);
}

public void putPreference(final String name, final String value) {
prefs.put(name, value);
}

public static boolean contains(final Preferences node, final String key) {
return node.get(key, null) != null;
}

public static String containsValue(final Preferences node, final String value) {
String result = null;
try {
final String[] keys = node.keys();
for (String key : keys) {
if (value.equals(node.get(key, null))) {
result = key;
}
}
} catch (BackingStoreException e) {
}
return result;
}

public void clearAllPreferencesFromNode() {
try {
prefs.clear();
} catch (BackingStoreException e) {
}
}

public void removePreference(final String name) {
prefs.remove(name);
}

public void putPreference(final String name, final boolean value) {
prefs.putBoolean(name, value);
}

public void putPreference(final String name, final int value) {
prefs.putInt(name, value);
}

public void putPreference(final String name, final long value) {
prefs.putLong(name, value);
}

public void putPreference(final String name, final float value) {
prefs.putFloat(name, value);
}

public void putPreference(final String name, final double value) {
prefs.putDouble(name, value);
}

public void putPreference(final String name, final byte[] value) {
prefs.putByteArray(name, value);
}

public boolean getPreference(final String name, final boolean defaultValue) {
return prefs.getBoolean(name, defaultValue);
}

public int getPreference(final String name, final int defaultValue) {
return prefs.getInt(name, defaultValue);
}

public long getPreference(final String name, final long defaultValue) {
return prefs.getLong(name, defaultValue);
}

public float getPreference(final String name, final float defaultValue) {
return prefs.getFloat(name, defaultValue);
}

public double getPreference(final String name, final double defaultValue) {
return prefs.getDouble(name, defaultValue);
}

public byte[] getPreference(final String name, final byte[] defaultValue) {
return prefs.getByteArray(name, defaultValue);
}

public static int getMaxKeyLength() {
return Preferences.MAX_KEY_LENGTH;
}

public static int GetMaxValueLength() {
return Preferences.MAX_VALUE_LENGTH;
}

public static int getMaxByteArrayLength() {
return Preferences.MAX_VALUE_LENGTH * 3 / 4;
}

public void setSystemRoot() {
prefs = Preferences.systemRoot();
}

public void setUserRoot() {
prefs = Preferences.userRoot();
}

public void exportNodeXML(final File file) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
prefs.exportSubtree(fos);
} catch (IOException e) {
} catch (BackingStoreException e) {
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (Exception ee) {
}
}
}

public void removePreferenceNode() {
try {
prefs.removeNode();
} catch (BackingStoreException e) {
//something here
}
}

public void moveToParent() {
prefs = prefs.parent();
}

public String[] childrenNodeNames() {
String[] names = null;
try {
names = prefs.childrenNames();
} catch (BackingStoreException e) {
}
return names;
}

public void setNode(final String name) {
prefs = prefs.node(name);
}

public String setFirstOccurance(final String key) {
prefs = findNode(Preferences.userRoot(), null, key);
return getPreference(key, "");
}

public static Preferences findNode(final Preferences root, Preferences start, final String key) {
Preferences result = null;
if (start == null && contains(root, key)) {
result = root;
}
if (start != null && root.equals(start)) {
start = null;
}
try {
final String[] names = root.childrenNames();
for (String name : names) {
final Preferences n = findNode(root.node(name), start, key);
if (n != null) {
result = n;
}
}
} catch (BackingStoreException e) {
}
return result;
}

public static void importPreferences(final File file) {
InputStream is = null;
try {
is = new BufferedInputStream(new FileInputStream(file));
Preferences.importPreferences(is);
} catch (Exception e) {
} finally {
try {
if (is != null) {
is.close();
}
} catch (Exception ee) {
}
}
}
}

MxLookup Validate Email in Java

There is no reliable way to validate if an email is valid or bogus because of spammers. The features that let you validate an email address with a server are in general disabled to protect people from spammers... If you still want to try and validate an email then here is the old fashioned way it was done.

Cheers,

Ted



import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Hashtable;

public class MxLookup {
public int lookup(String hostName) throws NamingException {
Hashtable env = new Hashtable();
env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
DirContext ictx = new InitialDirContext(env);
Attributes attrs = ictx.getAttributes(hostName, new String[]{"MX"});
Attribute attr = attrs.get("MX");
if (attr == null) return (0);
return (attr.size());
}

private static int hear(BufferedReader in) throws IOException {
String line = null;
int res = 0;
while ((line = in.readLine()) != null) {
String pfx = line.substring(0, 3);
try {
res = Integer.parseInt(pfx);
} catch (Exception ex) {
res = -1;
}
if (line.charAt(3) != '-') break;
}
return res;
}

private static void say(BufferedWriter wr, String text) throws IOException {
wr.write(text + "\r\n");
wr.flush();
return;
}

private static ArrayList getMX(String hostName) throws NamingException {
Hashtable env = new Hashtable();
env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
DirContext ictx = new InitialDirContext(env);
Attributes attrs = ictx.getAttributes(hostName, new String[]{"MX"});
Attribute attr = attrs.get("MX");
if ((attr == null) || (attr.size() == 0)) {
attrs = ictx.getAttributes(hostName, new String[]{"A"});
attr = attrs.get("A");
if (attr == null) throw new NamingException("No match for name '" + hostName + "'");
}
ArrayList res = new ArrayList();
NamingEnumeration en = attr.getAll();
while (en.hasMore()) {
String x = (String) en.next();
String f[] = x.split(" ");
if (f[1].endsWith(".")) f[1] = f[1].substring(0, (f[1].length() - 1));
res.add(f[1]);
}
return res;
}

public static boolean isEmailAddressValid(String address) {
int pos = address.indexOf('@');
if (pos == -1) return false;
String domain = address.substring(++pos);
ArrayList mxList = null;
try {
mxList = getMX(domain);
}
catch (NamingException ex) {
return false;
}
if (mxList.size() == 0) return false;
for (int mx = 0; mx < mxList.size(); mx++) {
boolean valid = false;
try {
int res;
Socket skt = new Socket((String) mxList.get(mx), 25);
BufferedReader rdr = new BufferedReader
(new InputStreamReader(skt.getInputStream()));
BufferedWriter wtr = new BufferedWriter
(new OutputStreamWriter(skt.getOutputStream()));

res = hear(rdr);
if (res != 220) throw new Exception("Invalid header");
say(wtr, "EHLO orbaker.com");

res = hear(rdr);
if (res != 250) throw new Exception("Not ESMTP");

say(wtr, "MAIL FROM: ");
res = hear(rdr);
if (res != 250) throw new Exception("Sender rejected");

say(wtr, "RCPT TO: <" + address + ">");
res = hear(rdr);

// be polite
say(wtr, "RSET");
hear(rdr);
say(wtr, "QUIT");
hear(rdr);
if (res != 250) throw new Exception("Address is not valid!");

valid = true;
rdr.close();
wtr.close();
skt.close();
} catch (Exception ex) {
// Do nothing but try next host
} finally {
if (valid) return true;
}
}
return false;
}
}