Posts in the “java” category

Java “keytool import”: How to import a certificate into a keystore file

Java “keytool import” FAQ: Can you share some examples of the Java keytool import command and process?

When you're working with Java public and private keys, there may be a time when someone else says, "Here is a certificate. Import it into your public key keystore, and then you can do XYZ", where "XYZ" can be a variety of things, including reading their document, using their Java application, etc. To do this you need to use the Java keytool import command.

The keytool password for the Java security cacerts file is ...

In case you ever need to manually a certificate to your ${JAVA_HOME}/jre/lib/security/cacerts file, it turns out the password for that file when using the Java keytool command is changeit.

To add a certificate to that file, you’ll want to use a command like this:

keytool \
    -import \
    -alias "foobar.com" \
    -keystore ${JAVA_HOME}/jre/lib/security/cacerts \
    -file foobar.com.crt

I had to do this today for a Java/Scala script that accesses an HTTPS URL, and the site I’m accessing uses a “Let’s Encrypt” certificate.

How to search multiple jar files for a string or pattern (shell script)

Here’s a Unix shell script that I use to search Java Jar files for any type of string pattern. You can use it to search for the name of a class, the name of a package, or any other string/pattern that will show up if you manually ran jar tvf on each jar file. The advantage of this script — if you’re a Unix, Linux, or Cygwin user — is that it will search through all jar files in the current directory:

Java 10: How to implement About, Preferences, and Quit menu items on MacOS

If you want to implement About, Preferences, and Quit handlers with Java 9 and newer on MacOS systems, this example Java source code shows how to do it:

import java.awt.*;
import javax.swing.*;

public class JavaAwtDesktop {

    public static void main(String[] args) {
        new JavaAwtDesktop();
    }

    public JavaAwtDesktop() {

        Desktop desktop = Desktop.getDesktop();

        desktop.setAboutHandler(e ->
            JOptionPane.showMessageDialog(null, "About dialog")
        );
        desktop.setPreferencesHandler(e ->
            JOptionPane.showMessageDialog(null, "Preferences dialog")
        );
        desktop.setQuitHandler((e,r) -> {
                JOptionPane.showMessageDialog(null, "Quit dialog");
                System.exit(0);
            }
        );

        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("java.awt.Desktop");
            frame.setSize(new Dimension(600, 400));
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }

}

I just tested this code on MacOS 10.12.x and Java 10, and it works as expected. When you click on the About, Preferences, and Quit menu items, the example dialogs are shown.

Java BufferedImage: How to get the RGB value of each image pixel

I'm just getting started with image parsing in Java, but right away I need to do something that’s relatively hard: find a small image inside of a larger image. I’ve run into some initial problems so I’m writing small tests as I go along.

In this article I’ll share the results of a first test I’ve written to walk through all the pixels in an image (a Java BufferedImage) and print out their RGB (technically ARGB) values.

Java Date and Calendar “add” examples

Java Date class "addition" FAQ: Can you show me how to add various times increments to a Java Date object?

I've been doing a lot of work with the Date class in Java lately (both java.util.Date and java.sql.Date), and before leaving this area for a while, I thought I'd put together some "Java Date add" examples that demonstrate various "date add" and "calendar add" techniques, including how to get the date and time one hour from now, tomorrow's date, next week, next month, and next year.

A Java method to round a float value to the nearest one-half value

As a quick note, here’s a Java method that will round a float to the nearest half value, such as 1.0, 1.5, 2.0, 2.5, etc.:

/**
 * converts as follows:
 * 1.1  -> 1.0
 * 1.3  -> 1.5
 * 2.1  -> 2.0
 * 2.25 -> 2.5
 */
public static float roundToHalf(float f) {
    return Math.round(f * 2) / 2.0f;
}

The comments show how this function converts the example float values to their nearest half value, so I won’t add any more details here. I don’t remember the origin of this algorithm — I just found it in some old code, thought it was clever, and thought I’d share it here.

Java: How to convert strings to numbers

Question: How do I convert a String to an int or a float?

Short answer: You want to use the Integer.parseInt() or Float.parseFloat() methods.

Here's an example Java program that shows how to convert a String to either an int or a float:

How to speed up JDBC PreparedStatement MySQL batch inserts

If you ever need to batch-insert a lot of records into a MySQL/MariaDB database using the JDBC PreparedStatement (as in preparedStatement.executeBatch()) be sure to change the MySQL URL to use the rewriteBatchedStatements, as shown here:

"jdbc:mysql://localhost:8889/DATABASE?rewriteBatchedStatements=true"

For a recent project I needed to batch-insert about eleven million records into a MySQL database, and the runtime was about 55 minutes. Once I added rewriteBatchedStatements=true to the MySQL URL, the batch-insert time was reduced down to only three minutes. That one little change made all the difference.

How to add a JPopupMenu to a JTable

Here's an example of how to add a JPopupMenu to a JTable. The purpose of the popup menu is to let the user right-click on contents in the table and work directly with those contents.

In the code below I've taken a real class and trimmed it down considerably for these demo purposes. I hope the code remaining is useful enough to help you implement your own JPopupMenu on a JTable, or perhaps in other components as well.

A JButton listener example

JButton listener FAQ: A common Java JButton question is "How do I add a listener to a JButton?", or the equivalent, "How can I tell when a JButton is pressed?"

JButton listener solution

In short, you typically want to add an ActionListener to a JButton, as shown in the following source code snipet:

JDialog focus: How to get input focus on a JDialog

I just solved a problem I was having in a Java Swing application getting input focus on a JDialog in a homemade text editor I use on my Mac OS X systems. Using my initial Java code the JDialog was properly getting input focus the first time it was displayed, but it was not properly getting input focus when it was displayed a second (or any subsequent) time.

A Java Active Directory JAAS example

I normally don't like to put source code out here that I can't support, but in this case I thought I'd make an exception, because I remember a former co-worker having a really hard time getting this Java Active Directory JAAS code working properly. It's been over two years since I got it working for him, so I don't remember what the problems were. Hopefully if you're trying to get Java working with Active Directory (using JAAS), this example source code will get you pointed in the right direction.