Configuring the Java editor in Eclipse to use spaces in place of tabs

I was attempting to switch my use of tabs (in Eclipse Juno) to pure spaces. The problem was, even though the Text Editor configuration within Eclipse was set to use “Insert spaces for tabs”, this was not having any effect on my Java code.

Solution: the Java editor is using an Eclipse editor “profile” which is overriding the default Text Editor configuration parameters; thus, you need to customize the Java editor profile.

  1. Open up Eclipse preferences (Mac: Eclipse->Preferences)
  2. Navigate to Java->Editor->Formatter
  3. Create a new ‘Active Profile’, and call it whatever you like
  4. Edit the newly created profile (click Edit)
  5. Next to the ‘Tab policy’ item, select ‘Spaces only’ under the drop-down menuImage
  6. Click OK and make sure you use this profile
  7. (optional) for exiting code, you can convert source code to use the new tab policy by highlighting all the code, and right-clicking to select: Source->Correct Indentation
Advertisements

Compiling and executing a Processing sketch as a Java class

Processing sketches (PDEs) are translated from the processing syntax to pure Java and are compiled and packaged into executable JARs. Is it possible to by pass the packaging step and go straight from the Java code to your own compiled class? Yes it is!

NOTE: Apart from your source and compiled class file, you will need the Processing “core.jar” binary to compile the class as well as run it.

Steps:

  1. Use Processing to create a sketch file (.pde) and use the “Export” capability to export it to your native enviornment
  2. Open the generated export folder and navigate to the “source” directory. Inside here you will find the Java source file
  3. Compile the Java source file via: javac -cp "core.jar" SOURCE_FILE.java
  4. Run the compiled class via the following command: java -cp "core.jar:." CLASS_FILE

Using a servlet config file with a CXF JAX-RS web-service

I spent some time searching for how to do this, so thought I’d share my findings.

Problem:

I created an Apache CXF JAX-RS web-service using the Maven2 archetype “cxf-jaxrs-service (Simple CXF JAX-RS webapp service using Spring configuration)”. Using this as a boiler-plate, I then created my own RESTful web-service endpoint.

The problem was, without having my class extend HttpServlet, how would I get a hold of configuration parameters specified in a servlet configuration file? For example, within Tomcat’s META-INF/context.xml?

Solution:

It’s as simple as just utilizing the @Servlet context variable.

First, ensure you have the following Maven dependency included in your project’s pom.xml:


<dependency>

<groupId>javax.servlet</groupId>

<artifactId>servlet-api</artifactId>

<version>2.4</version>

<scope>provided</scope>

</dependency>

Second, define a variable within your REST resource class as such:


@Context private ServletContext context;

Finally, read parameters from the context variable via:


context.getInitParameter("MyParameterName");

That’s it!

Computing T-Distribution Cumulative Probability Density Function

I’ll be the first to admit, its been a long time since I was in Statistics class, but it’s really one of the most useful classes out there, even the esoteric parts of it.

Recently, I had to write code to compute bias estimation for climate change data, and one of the key stats used in computing bias estimation along with its summary statistics is: the t-distribution cumulative probability density function, or tcdf for short.

In Java land, we are fortunate to have the Apache Commons Math library, which allows computation of tcdf and inverse-tcdf:
http://commons.apache.org/math/userguide/distribution.html 

Something like the following, using Apache Commons Math, will allow calculation of an inverse tcdf:

TDistribution t = new TDistributionImpl(degreeOfFreedom);
a = (t.inverseCumulativeProbability(0.975))

Sending e-mail in Java via SMTP protocol

I was attempting to send e-mail, using the following code, in Java but was receiving SMTP protocol errors. I thought perhaps I required authentication or some other type of initilization, but turns out the problem was just missing jars.

Java code:

Properties emailProps = new Properties();
emailProps.setProperty("mail.host", "<YOUR_SMTP_HOST>");
emailProps.setProperty("mail.debug", "true");


Session session = Session.getInstance(emailProps);
Message msg = new MimeMessage(session);


try {
msg.setSubject("<YOUR MESSAGE>");
msg.setSentDate(new Date());
msg.setFrom(InternetAddress.parse("<FROM_ADDRESS>")[0]);
msg.setRecipient(Message.RecipientType.TO,
InternetAddress.parse("<TO_ADDRESS>", false)[0]);
msg.setText(<YOUR_MESSAGE_TEXT>);
Transport.send(msg);
} catch (MessagingException e) {
e.printStackTrace();
}

Exception I was getting:
javax.mail.NoSuchProviderException: Unable to locate provider for protocol: smtp

Solution:
Include the following dependencies (maven2 example):

<dependency>
<groupId>org.apache.geronimo.javamail</groupId>
<artifactId>geronimo-javamail_1.4_mail</artifactId>
<version>1.8.1</version>
</dependency>
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-activation_1.1_spec</artifactId>
<version>1.1</version>
</dependency>

Unable to shutdown Tomcat because of port in use

Was having an annoying problem where I could not shutdown a running tomcat instance.

The below is the shutdown issue I was facing:

> $CATALINA_HOME/bin/shutdown.sh
Error: Exception thrown by the agent : java.rmi.server.ExportException: Port already in use: 9999; nested exception is:
java.net.BindException: Address already in use

A work-around (bad one by the way) was to just kill the catalina process:
> ps -A | grep catalina
> kill <port number>

However, I finally figured it out. Turns out switching on jmxremote (Java remote console memory monitoring) within catalina.sh was to blame. I’m not using remote monitoring anymore, so I just removed the following red entry from $CATALINA_HOME/bin/catalina.sh JAVA_OPTS line:

JAVA_OPTS=”$JAVA_OPTS -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=9999 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager”

Try that and see if it works!

Setting custom range for your plot within JFreeChart

My data had Y-values that were all around the 1.217 to 1.219 billion data range; however, JFreeChart was auto calculating the proper orientation of the graph and making the range start from zero and end at my highest range value. This makes my data which should look like a slope=1 sideways line look instead like a slope=0 flat line.

JFreeChart has a method in the NumberAxis class called ‘setAutoRangeIncludesZero’ which lets you choose whether to start your range from zero by default. Unfortunately, my ‘RangeAxis’ object was of type ValueAxis, and this class doesn’t have any such method.

Here is the solution:

NumberAxis yaxis = (NumberAxis) chart.getXYPlot().getRangeAxis();

yaxis.setAutoRangeIncludesZero(false);