Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Friday, 20 March 2020

Slf4j NoClassDefFoundError when compiling SparkJava sample project

Problem:

When trying out the SparkJava demo for websockets (spark-websockets, "Using WebSockets and Spark to create a real-time chat app"), I get the following compilation error:

Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
 at spark.Service.<clinit>(Service.java:56)
 at spark.Spark$SingletonHolder.<clinit>(Spark.java:51)
 at spark.Spark.getInstance(Spark.java:55)
 at spark.Spark.<clinit>(Spark.java:61)
 at Chat.main(Chat.java:19)
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
 at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
 at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
 ... 5 more

Workaround:

The following workaround worked as a quick way to try out the demo code:
  • Open the project's pom.xml file
  • Add the following dependency:
    
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.21</version>
      <scope>compile</scope>
    </dependency>
    
    

If this worked, the project should now compile properly.

Notes:

The above workaround is one of many solutions that can work towards a successful compile. Others include adding a JAR file for a logger, for example. This solution was chosen as it is the quickest for a beginner to do while learning how to use SparkJava or while learning programming in Java.

This how-to was verified to work in revision 8cc09e8cea9257a0df3449106a57ad0467faf39b (Sep 4, 2017) of the spark-websockets project. Your results may vary for other revisions.

References:

Wednesday, 3 October 2018

Reminder: SparkJava 2.7.2 pom.xml known to work for new projects

Problem

For SparkJava 2.7.2, I'd like a known set of POM.xml dependencies and properties that work so I can kick-start my project. The settings in the SparkJava "getting started" tutorial result in exceptions.

Example POM.xml snippet

In your POM.xml, try these to start off:

    <properties>
        <java.version>1.8</java.version>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
  
  
    <dependencies>
  
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-server</artifactId>
            <version>9.4.6.v20170531</version>
        </dependency>
  
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.21</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.21</version>
        </dependency>
 
        <dependency>
            <groupId>com.sparkjava</groupId>
            <artifactId>spark-core</artifactId>
            <version>2.7.2</version>
        </dependency>
    </dependencies>

Notes

The above dependency versions and properties were observed to work on 2018-10-03 with SparkJava version 2.7.2. Your mileage may vary.

Once you have your SparkJava project working, feel free to change versions to suit your own project needs.

References

Tuesday, 13 December 2016

Java Enum get value from String

Problem:

In Java, I have an Enum and I'd like to be able to look up one of its value using a String.

Solution:

In order to get a specific Enum value from a String, use the java.lang.Enum.valueOf() function.

For instance, if I have the following Enum:

enum Day {Mo, Tu, We, Th, Fr, Sa, Su}

Then the following code gets Day.Th from the String "Th":

Day.valueOf("Th")
Another example, assuming the above Enum Day is defined:
Day myDayExample;
myDayExample = Day.valueOf("Th");

System.out.println(myDayExample); // prints: Th

Notes:

If either the Enum type or string is null, then java.lang.Enum.valueOf() will throw a NullPointerException.

Additionally, if no Enum constant with the name in the String exists, an IllegalArgumentException will be thrown.

For more information, check out the references below.

References:

Sunday, 11 December 2016

Efficient way to find the sign of a number in Java

Problem:

What is an efficient way to find the sign of a number in Java?

Solution:

To find the sign of a number, you can use the signum() function. (e.g. Math.signum(), Integer.signum(), Long.signum(), etc.)

For example:


int sign1 = (int) Math.signum(-123); // -1
int sign2 = (int) Math.signum(222);  //  1
int sign3 = Integer.signum(-1234);   // -1

double sign4 = Math.signum(-123.0);  // -1.0
float sign5 = Math.signum(111.0f);   //  1.0f

double sign6 = Math.signum(0.0);     //  0.0

Notes:

For more information (minimum JDK version, etc.), check out the references below.

References:

Saturday, 10 December 2016

GWT disable CellTable row highlight on mouse hover

Problem:

In GWT 2.7, how do I disable CellTable row highlight during mouse hover?

Solution:

Imagine your CellTable is named theTable. To disable the mouse-hover row highlighting, try the following:

theTable.setSkipRowHoverStyleUpdate(true);

Notes:

This was verified to work in GWT 2.7. Your mileage may vary with other versions. This reminder was meant as a quick reference for myself, so it's a bit brief. Check out the references below for more detail.

Also note that the above code might also work for GXT DataGrid, depending on version.

References:

Tuesday, 29 November 2016

View GWT emulated Long in browser developer tools

Problem:

I would like to see the long value of a GWT emulated Long in my browser's developer tools.

I already know how to pause and debug my web app, but when I inspect a Long value, it looks similar to {h:0, m:544, l:54210}.

Solution:

Imagine that we have an emulated Long value: myLongVal={h:1, m:234, l:567}

To translate this to a human-readable Long (in most, but not all cases), type the following in the developer tools console:

myLongVal.h*Math.pow(2,44) + myLongVal.m*Math.pow(2,22) + myLongVal.l

(See screenshot)

Notes:

This was verified to work in GWT 2.7. Your mileage may vary for other versions.

The above method should work for Long values that are low enough. However, overflow may occur for larger emulated Long values as the cast to a Javascript double does not cover as many bits as a long integer.

Note that if you have a browser that actually supports 64-bit integers or larger, you might be able to use the following:

(myLongVal.h << 44) + (myLongVal.m << 22) + myLongVal.l

References:

Sunday, 27 November 2016

Package-level javadoc comments

Problem:

How can I add package-level javadoc comments to my Java project?

Solution:

  • In your package's directory, add a file named "package-info.java"
  • In this file, include the package-level javadoc comment, as well as the package declaration

Example:

myprojectroot/mypackage/package-info.java:

/**
 * Provides an example package-level javadoc comment.
 * 
 * @since 1.0
 */
package myprojectroot.mypackage;

Additional hints:

  • in Eclipse, you can create this file by adding a "new file" to the package (instead of a new Java class, etc.)

References:

Friday, 29 June 2012

Reminder of my netbeans.conf file

This post is just meant to be an online reminder of my current OS X Netbeans 7.1 configuration so I can remember when I switch machines or upgrade my Netbeans version. It probably won't be too useful to others out there, but you're welcome to take a look at it nonetheless.

Also note that tuning JVM flags to work well on one machine or system configuration does not necessarily mean that it will work well on another. In fact, in some cases it can even make things worse when compared to the default settings. So if you decide to use some of the configuration below, you'll definitely want to tweak it to work well for your own machine.


Current netbeans.conf setup:

netbeans_default_options="-J-client -J-Xss2m -J-Xms1280m -J-Xmx1280m
-J-XX:PermSize=32m -J-XX:MaxPermSize=160m
-J-Dapple.laf.useScreenMenuBar=true
-J-Dapple.awt.graphics.UseQuartz=true -J-Dsun.java2d.noddraw=true
-J-Dsun.zip.disableMemoryMapping=true -J-XX:+UseParNewGC
-J-XX:+UseConcMarkSweepGC -J-XX:+CMSParallelRemarkEnabled
-J-XX:ParallelGCThreads=3 -J-XX:+CMSClassUnloadingEnabled
-J-XX:+CMSPermGenSweepingEnabled -J-Xverify:none
-J-XX:CompileThreshold=100"

(For 7.1.2, using 768m instead seems to work better as the major garbage collection cycles are much faster, and there seems to be a severe memory leak with larger amounts on the rig I'm using; the heap fills up significantly faster forcing more frequent major garbage collection cycles.)

What this is trying to do:

  • Provide enough memory to the JVM so Java doesn't frequently 'stop the world' in order to allocate more memory
  • Provide enough memory at the beginning so things don't grind to a halt in order to change the VM size early on
  • Use parallel garbage collection so Netbeans doesn't freeze for a long time when doing a major garbage collection cycle
  • Use several (but not all) cores for more efficient garbage collection
  • Make Netbeans more responsive at a slight cost of startup time
  • Provide a large enough amount of heap in order to delay time between major garbage collection cycles, also making Netbeans more responsive on average in the long run

Also note that some of the (default) flags in the configuration are there to make sure that Netbeans actually works in OS X.


Problems this is trying to solve:

The current system Netbeans is running on has ample physical memory available so a GB+ memory footprint is not an issue. However, other large programs are often used at the same time to create other resources for the same projects being developed using Netbeans. Garbage collection and memory allocations plague the system with a small VM size since opened projects can sometimes take up hundreds of MB. This creates the need to often wait for Netbeans to become responsive again after having it pause for a bit. In addition, when the system is idle for long enough, Netbeans is often paged to disk by OS X to make other programs more responsive (the current JVM flags will not be able to fix this, only more RAM will). Netbeans is often left running without restarting for weeks on end to work on parts of projects every day. The system is currently running OS X 10.7 Lion.


How well has this worked compared to the default:

The default configuration would often cause Netbeans to frequently halt when working on projects. The current configuration appears to be significantly better, without too much pausing. However, notable pauses do occur when forcing garbage collection (which doesn't appear to be necessary with the current configuration, but is still possible to do), and when loading paged memory back into RAM.


References:

Thursday, 26 April 2012

Optimize Netbeans 7.1 Memory and Configuration in OS X Manually

Reducing the memory footprint of Netbeans is often a good idea. Even on a system with plenty of RAM, a typical setup for development can quickly consume all free memory, leading to slowdowns and thrashing due to paging. Additionally, setting the initial memory usage high enough can avoid excessive memory allocations early on during the program's execution.

This post serves as a reminder of how to configure Netbeans and monitor its memory usage. It is not meant to be comprehensive, however I hope it turns out to be helpful for someone nonetheless.

Configuration:

The most direct way to configure memory usage in Netbeans 7.1 is by editing its configuration file. In OS X, the Netbeans configuration file is located directly within the application bundle. In finder, it can be found by the following:

  1. Go to your Applications folder
  2. Go into the Netbeans folder
  3. Secondary-click on the Netbeans 7.1 app, and view package contents
  4. Look for the file Contents/Resources/Netbeans/etc/netbeans.conf
  5. (optional) Backup the original in case you need to undo your changes
  6. Edit the netbeans.conf configuration file

If you would rather use terminal instead, the following string is the file's location (note that this is a single line, and any apparent line breaks are due to the blog format):

/Applications/Netbeans/Netbeans\ 7.1.app/Contents/Resources/Netbeans/etc/netbeans.conf

Note that this location is OS X specific, and in other platforms the location may vary. See the following site for details: http://wiki.netbeans.org/FaqNetbeansConf

In this file, flags to configure how the Java virtual machine runs Netbeans can be set. A good overview of these can be found here: http://performance.netbeans.org/howto/jvmswitches/

The following is an example of a tweaked configuration for netbeans_default_options:

-J-client -J-Xss2m -J-Xms256m -J-Xmx512m -J-XX:PermSize=32m -J-XX:MaxPermSize=160m -J-Dapple.laf.useScreenMenuBar=true -J-Dapple.awt.graphics.UseQuartz=true -J-Dsun.java2d.noddraw=true -J-Dsun.zip.disableMemoryMapping=true -J-XX:+UseConcMarkSweepGC -J-XX:+CMSClassUnloadingEnabled -J-XX:+CMSPermGenSweepingEnabled

Monitoring:

The easiest way to monitor the memory usage of Netbeans is to use the memory toolbar. To do this, in your menu select: View->Toolbars->Memory

In order to force garbage collection to free up some memory, simply click on the memory toolbar.