Java Tips: Difference between revisions

From EggeWiki
Line 14: Line 14:
Here's a class which impliments the [http://en.wikipedia.org/wiki/Luhn LUHN] algorithm.  This is useful for validating credit card numbers and CUSIPs.
Here's a class which impliments the [http://en.wikipedia.org/wiki/Luhn LUHN] algorithm.  This is useful for validating credit card numbers and CUSIPs.
* [[LUHN Source Code]]
* [[LUHN Source Code]]
* [[LUHN Test Case]]


==Apple uses Java for their iTunes Store==
==Apple uses Java for their iTunes Store==

Revision as of 17:41, 9 May 2006

Find classes which exist in multiple jars:

find . -name "*.jar" -type f -exec jar -tvf \{\} \; | cut -b 37- | grep "\.class" | sort | uniq -dc | sort

JBoss Ideas

Offline HTML code formatter with Ant task

Online HTML code formatter

Validate CUSIPs using their checksum

Here's a class which impliments the LUHN algorithm. This is useful for validating credit card numbers and CUSIPs.

Apple uses Java for their iTunes Store

  Dear Podcast Owner

  An error was encountered in your Podcast feed [ http://www.ccnorthjersey.org/podcast/rss.php ] preventing update. We will not be able to update the directory from your feed until this error is resolved:

  We had difficulty reading this feed. *java.net.~SocketTimeoutException*: Read timed out


  Sincerely,

  The iTunes Music Store Team

River Layout

Patches for Java CUP, a parser generator.

Convert from dos to unix and unix to dos formats:

  private static final Pattern DOS = Pattern.compile("\\r\\n", Pattern.MULTILINE);
  public static String dos2unix(String text) {
    return DOS.matcher(text).replaceAll("\n");
  }
  private static final Pattern UNIX = Pattern.compile("([^\\r])(\\n)", Pattern.MULTILINE);
  public static String unix2dos(String text) {
    return UNIX.matcher(text).replaceAll("$1\r\n");
  }

Ant is great, but the XML gets to suck after a while.

 Excerpt from James Duncan Davidson, the author of Ant.
 If I knew then what I knew now, I would have tried using a real scripting language, such as ~JavaScript via the Rhino component or Python via JPython, with bindings to Java objects which implemented the functionality expressed in todays tasks. Then, there would be a first class way to express logic and we wouldn't be stuck with XML as a format that is too bulky for the way that people really want to use the tool.

Ant is giving you this error when using a fileset:

java.lang.NoClassDefFoundError: org/apache/oro/text/regex/MalformedPatternException

You need to download the Jararta ORO libarary. Install the jar in you ant/lib directory.

! You get some stack trace like this:

 java.lang.NumberFormatException: multiple points
  at java.lang.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1067)
  at java.lang.Double.parseDouble(Double.java:220)
  at java.text.DigitList.getDouble(DigitList.java:127)
  at java.text.DecimalFormat.parse(DecimalFormat.java:1070)
  at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1705)
  at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1156)
  at java.text.DateFormat.parse(DateFormat.java:333)

This might be caused by your ~SimpleDateFormat object being used concurrently. The spec says you can't:

  Date formats are not synchronized. It is recommended to create separate format instances for
  each thread. If multiple threads access a format concurrently, it must be synchronized externally.

Directory Permissions for JVM

Help! When run as my user this works fine. When I run as 'foo', it gives me this nasty error

$ sudo -u foo java -version
Error occurred during initialization of VM
java.lang.Error: Properties init: Could not determine current working directory.

 -or-
$ sudo -u foo java -version
Segmentation Fault (core dumped)

Fix, make the current directory & it's parent world-readable. Or run java in a different directory where foo has read permissions.


Extract one file from a jar

jar xvf archive.jar filename.txt

Code Conventions

Sun has a fairly complete coding conventions document. The main thing I dislike is they recommend four space indents, while I prefer two.

http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html

Get a stack dump from a java app running on Windows

http://tmitevski.users.mcs2.netarray.com/stacktrace.jsp

Remove Ant Configuration Dialog from Eclipse

In Eclipse 3.0 you can launch Ant tasks. This is a great feature. If you don't want to run with the default settings, you can open the configuration settings and add environment variables and add flags. Sometimes I like to add a "-verbose" flag. The problem is after this you are stuck with the configuration dialog popping up each time you launch a target. To stop this, you must delete files in your Eclipse workspace settings. My files are in:

H:\eclipseworkspace\.metadata\.plugins\org.eclipse.debug.core\.launches

Then restart Eclipse, and you can now run Ant tasks simply by double clicking on them.

TibRv Library Error On Linux

How to refactor away the warning "The method UTC(int, int, int, int, int, int) from the type Date is deprecated"

  public static void main(String[] args) {
    final int year = 2004;
    final int month = 8;
    final int day = 24;
    // Old (easy) way:
    Date d1 = new Date(Date.UTC(year - 1900, month - 1, day, 0, 0, 0));

    // New way:
    final Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    calendar.setTimeInMillis(0); // Current milliseconds linger around - set this to get rid of them.
    calendar.set(year,month-1,day,0,0,0);
    Date d2 = calendar.getTime();
    assert d1.getTime() == d2.getTime();
  }

How to require an environment variable in an Ant file

<property environment="env"/><BR>
<fail message="Provide MY_VAR" unless="env.MY_VAR"/>

Q: How do you get the local hostname in Java?

  protected static String getHostname() {
    try {
      return java.net.InetAddress.getLocalHost().getHostName();
      // or java.net.InetAddress.getLocalHost().getCanonicalHostName();
    } catch (UnknownHostException ex) {
      return "Unknown";
    }
  }

Java Books I recommend