How do I convert an image file to a Base64 string?

A Base64 string is a way of encoding binary data using 64 printable characters, which are the 26 uppercase letters of the English alphabet, the 26 lowercase letters of the English alphabet, the 10 numerical digits, and the “+” and “/” symbols. This makes a total of 64 distinct characters, hence the name “Base64”.

Base64 encoding is commonly used when there is a need to encode binary data, especially when that data needs to be stored and transferred over media that is designed to handle text.

The primary use case of this encoding is to allow binary data to be represented in a way that looks and acts as plain text. For example, embedded images in HTML (often as data URIs), and storing complex data in XML or JSON.

In Java, you can use the java.util.Base64 classes to convert an image file to a base64 String. You can use it to convert a JPG or a PNG image file, or basically any binary image files. Here is a simple example:

package org.kodejava.util;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

public class ImageToBase64 {
    public static void main(String[] args) throws Exception {
        String imagePath = "/Users/wayan/tmp/photo-placeholder.png";

        byte[] fileContent = Files.readAllBytes(Paths.get(imagePath));
        String encodedString = Base64.getEncoder().encodeToString(fileContent);

        if (encodedString.length() > 65535) {
            System.out.println("Encoded string is too large");
        } else {
            System.out.println(encodedString);
        }
    }
}

Here are the first 200 characters of the generated base64 string:

iVBORw0KGgoAAAANSUhEUgAAAGQAAAB2CAYAAAA+/DbEAAAAAXNSR0IArs4c6QAAAIRlWElmTU0AKgAAAAgABQESAAMAAAABAAEAAAEaAAUAAAABAAAASgEbAAUAAAABAAAAUgEoAAMAAAABAAIAAIdpAAQAAAABAAAAWgAAAAAAAABIAAAAAQAAAEgAAAABAAOgAQA...

The size of a base64-encoded string could be significantly larger than the original file. It’s not always the best way to handle large files or in cases where you’re sensitive to data usage. To check the size of the generated string using the length() method of the String class.

As you can see in the code snippet above, the application will print “Encoded string is too large” if the base64 string of the image is larger than 65535 characters. Otherwise, it will print the base64 string

To use a Base64 encoded string with an HTML <img> tag, you can use the src attribute and specify the data as follows:

<img src="data:image/png;base64,iVBORw0..." alt="Your image description">

In this line:

  • data: is the Data URI scheme specifier.
  • image/png is the media type. This can be image/jpeg, image/gif, or other image types.
  • base64 indicates that the data is base64 encoded.
  • iVBORw0... is where your base64 data begins. Replace iVBORw0... with your base64 string.

You should replace image/png with the actual type of your image and replace the iVBORw0... part with your full Base64 string.

This approach allows you to inline small images directly into your HTML, reducing the number of HTTP requests. However, you should note that if images are large, this can increase the size of your HTML document and slow down load times. It might be more appropriate to use external image files for larger images.

Note that Base64 is not an encryption or hashing method, and should not be used for password or security purposes. It is a binary-to-text encoding schemes that represent binary data in an ASCII string format. It’s designed to be easily transmitted and stored while ensuring that the data remains intact without modification during transport.

Introduction to the Apache POI library for creating Excel file

Apache POI is a robust open-source library that provides APIs for manipulating various file formats based upon the Office Open XML standards (OOXML) and Microsoft’s OLE2 compound document format (OLE2). Being Java-based, it’s readily used by Java developers for creating, reading, and modifying Excel files.

To create a new Excel file using Apache POI, you will want to follow these basic steps:

1. Create a Workbook

You create an instance of Workbook which represents an Excel file. Workbook is an interface and the instance can be created by using one of its implementing classes like HSSFWorkbook (for .xls) or XSSFWorkbook (for .xlsx).

package org.kodejava.poi;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;

public class CreateWorkbook {
   public static void main(String[] args) {
      // Create Blank workbook
      try (XSSFWorkbook workbook = new XSSFWorkbook()) {
         // Write the workbook to a file
         try (FileOutputStream fileOut = new FileOutputStream("workbook.xlsx")) {
            workbook.write(fileOut);
         } catch (Exception e) {
            e.printStackTrace();
         }
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

This block of code will create a new Excel file called “workbook.xlsx” in your project directory.

2. Create a Sheet

You create a Sheet in the Workbook. A sheet is a collection of rows where your data resides. To create a new sheet using Apache POI, you can use the createSheet() method of the Workbook interface. This method returns an object of the Sheet interface.

Below is an example of creating a new sheet in an Excel workbook:

package org.kodejava.poi;

import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;

public class CreateSheetExample {
    public static void main(String[] args) {
        // Create a workbook
        try (XSSFWorkbook workbook = new XSSFWorkbook()) {
            // Create a blank sheet within the workbook
            XSSFSheet sheet = workbook.createSheet("New Sheet");

            // Write the workbook in a file system
            try (FileOutputStream out = new FileOutputStream("New.xlsx")) {
                workbook.write(out);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

This code will create a new sheet named “New Sheet” in an Excel file named New.xlsx.

3. Create Rows and Cells

Inside your Sheet, you create Row. Inside your Row, you create Cell.

Creating new rows and cells with Apache POI is quite straightforward. Here’s a step-by-step way to do this:

  • Create a workbook.
  • Within the workbook, create a sheet.
  • Within the sheet, create a row.
  • Within the row, create a cell.

Each Cell can then be populated with data. Apache POI supports various data types including a text, numeric, date, boolean and formula.

Here is an example using Apache POI in Java:

package org.kodejava.poi;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;

public class CreateCellExample {
    public static void main(String[] args) {
        // Create a workbook
        try (XSSFWorkbook workbook = new XSSFWorkbook()) {
            // Create a blank sheet within the workbook
            XSSFSheet sheet = workbook.createSheet("New Sheet");

            // Create a row within the sheet
            XSSFRow row = sheet.createRow(0);

            // Create a cell within the row
            XSSFCell cell = row.createCell(0);

            // Set the value of the cell
            cell.setCellValue("Hello, Apache POI!");

            // Write the workbook to the file system
            try (FileOutputStream out = new FileOutputStream("Cell.xlsx")) {
                workbook.write(out);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

This code will create a new workbook with a sheet named New Sheet. In that sheet, it will create a row at index 0. In that row, it will create a cell at index 0 and set its value to “Hello, Apache POI!”

This will all be saved to a new Excel file named Cell.xlsx in the current project directory.

4. Creating a Date cell

Using Apache POI involves a few steps outlined below:

  • First, you create a new Workbook, Sheet, and Row, as shown previously.
  • Then, you create a cell in any given row and set its type to CellType.NUMERIC.
  • You then use CellStyle to format the date according to your needs.

Here’s an example:

package org.kodejava.poi;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

public class CreateDateCellExample {
    public static void main(String[] args) {
        // Create a workbook
        try (Workbook workbook = new XSSFWorkbook()) {
            // Create a blank sheet within the workbook
            Sheet sheet = workbook.createSheet("Date Example");

            // Create a row within the sheet
            Row row = sheet.createRow(0);

            // Create a cell within the row and set its type to NUMERIC
            Cell cell = row.createCell(0, CellType.NUMERIC);

            // Create a CellStyle
            CellStyle cellStyle = workbook.createCellStyle();
            CreationHelper creationHelper = workbook.getCreationHelper();
            // Set the built-in date format style
            cellStyle.setDataFormat(creationHelper.createDataFormat().getFormat("m/d/yy h:mm"));

            cell.setCellStyle(cellStyle);

            // Set the value of the cell as today's date
            cell.setCellValue(new Date());

            // Write the workbook to the file system
            try (FileOutputStream out = new FileOutputStream("DateExample.xlsx")) {
                workbook.write(out);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this example, a date cell has been created, and the date format has been set to m/d/yy h:mm, but there are many other ways to format the date or time. You can use a custom format if you prefer, so long as it follows the rule of Excel custom date format.

5. Creating various types of cell

Using Apache POI, you need to create a cell and set the cell type and value accordingly.

Let’s take a look at some examples:

package org.kodejava.poi;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;

public class CreateVariousCellsExample {
    public static void main(String[] args) throws IOException {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("New Sheet");

        Row row = sheet.createRow(0);

        // Create a numeric cell
        Cell numericCell = row.createCell(0, CellType.NUMERIC);
        numericCell.setCellValue(123.456);

        // Create a string cell
        Cell stringCell = row.createCell(1, CellType.STRING);
        stringCell.setCellValue("Hello, POI!");

        // Create a boolean cell
        Cell booleanCell = row.createCell(2, CellType.BOOLEAN);
        booleanCell.setCellValue(true);

        // Create a formula cell
        Cell formulaCell = row.createCell(3, CellType.FORMULA);
        formulaCell.setCellFormula("A1*B1");

        try (FileOutputStream fileOut = new FileOutputStream("./differentCellTypes.xlsx")) {
            workbook.write(fileOut);
        }
        workbook.close();
    }
}

This code will create an Excel file named “differentCellTypes.xlsx” with a sheet named “New Sheet”. In the first row of this sheet, there will be four cells:

  • A numeric cell containing the number 123.456
  • A string cell containing the value “Hello, POI!”
  • A boolean cell containing the boolean value of true
  • A formula cell containing a formula which multiplies the values of the first and second cells.

And that’s the basic of creating an Excel file using Apache POI. More advanced features include formatting and styling cells, adding images, creating charts, formulas, hyperlinks and so forth. You would find Apache POI’s API and its official documentation very resourceful for covering those.

Do note, it’s important to always close the Workbook instance at the end to free up resources and to prevent memory leaks.

Maven Dependencies

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.2.5</version>
</dependency>

Maven Central

How do I scp between two remote hosts?

To scp between two remote hosts, you typically need to be logged into one of the hosts and execute the scp command there.

The general format is like this:

scp <user>@<source_host>:<source_file_path> <user>@<destination_host>:<destination_file_path>

Suppose, you are logged into host1, and you want to copy a file from host2 to host3.
First, make sure that the key-based ssh authentication is set up for host2 -> host1 and host1 -> host3. Then, on host1, you can execute:

scp user@host2:/path/to/source/file.txt user@host3:/path/to/destination/

This will copy file.txt from host2 to host3.

Keep in mind this command requires you to have proper SSH access and permissions for both source and destination hosts. If you do not have the necessary authentication set up, the command will ask for the password for each machine.

Set up key-based SSH authentication

To set up key-based SSH authentication, you’ll need to generate a key pair on host1, then copy the public key to host2 and host3. Here’s how you can do it:

  1. Step One — Create the RSA Key Pair on host1:

Open a terminal and run the following command:

ssh-keygen -t rsa

You will be asked to specify the file location and passphrase (optional). If you just press Enter through those prompts, it will create an RSA key pair with default settings.

  1. Step Two — Store the Keys and Passphrase:

When you are prompted to “Enter a file in which to save the key,” you can press Enter. This accepts the default file location.

At the prompt, type a secure passphrase or press enter to proceed without a passphrase.
After completing these steps, your new keys are available in your user home folder ~/.ssh/id_rsa for your private key and ~/.ssh/id_rsa.pub for your public key.

  1. Step Three — Copy the Public Key to host2 and host3:

Next, you’ll copy your public key to your host2 and host3 using the ssh-copy-id command. Like this:

ssh-copy-id user@host2
ssh-copy-id user@host3

Replace user with your username, and host2 or host3 with the IP address or hostname of your second and third machines. You will be prompted for the user password for host2 and host3 to copy the public key.

That’s it! You have set up the key-based ssh authentication. Now you can log into host2 and host3 from host1 without a password:

ssh user@host2

or

ssh user@host3

This method applies to any Linux or Unix system that uses SSH. Please refer to the documentation for Windows servers or any other non-Unix systems. Also note that the user must have ssh and shell access.

Warning: Be careful with your private key (~/.ssh/id_rsa). Don’t share your private key with anyone! In production environments, it’s a common practice to protect private keys with a strong passphrase.

Note: The scp command is not installed by default on some systems. You can install it using your system package manager (like apt, yum, etc.). Alternatively, you can use rsync or sftp depending on the systems and permissions involved.

Important: Remember about data security. Always ensure safe and secure data transfer, especially when dealing with sensitive data. Use encrypted channels for such transfers (which scp does by utilizing SSH). Make sure the user whose credentials are used for the transfer has only the necessary permissions and nothing more.

How do I create XLSX files using Apache POI?

First of all, make sure that you have the Apache POI library included in your project. If you are using Maven, you can add the following to your pom.xml:

Maven Dependencies

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.2.5</version>
</dependency>

Maven Central

Then, you can use the following code to create an Excel .xlsx file:

package org.kodejava.poi;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;

public class ExcelExample {
    public static void main(String[] args) {
        // Create a new Workbook
        Workbook workbook = new XSSFWorkbook();

        // Create a new sheet in the workbook with a name
        Sheet sheet = workbook.createSheet("MySheet");

        // Create a row at index 0
        Row row = sheet.createRow(0);

        // Create a cell at index 0
        Cell cell = row.createCell(0, CellType.STRING);
        // Assign the string "Hello" to the cell
        cell.setCellValue("Hello");

        // Add some other rows and cells similarly...
        // ...

        try (FileOutputStream fos = new FileOutputStream("MyExcel.xlsx")) {
            workbook.write(fos);
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("Excel file has been generated!");

        try {
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

This program will create an Excel .xlsx file named MyExcel.xlsx with a single sheet called “MySheet.” The sheet has a single cell in the first row which contains the string “Hello.” The output file will be generated in the root directory of your project.

The above-given code is only a basic example. Apache POI allows advanced features like applying styles to cells, merging cells, and working with formulas among others. The library also supports other Microsoft Office file formats.

Here is another slightly more complex example where we create multiple rows and cells:

package org.kodejava.poi;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;

public class ExcelAnotherExample {
    public static void main(String[] args) {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Students");

        Row rowHeader = sheet.createRow(0);
        Cell cellHeader1 = rowHeader.createCell(0, CellType.STRING);
        cellHeader1.setCellValue("ID");

        Cell cellHeader2 = rowHeader.createCell(1, CellType.STRING);
        cellHeader2.setCellValue("Name");

        for(int i = 1; i < 6; i++) {
            Row rowData = sheet.createRow(i);

            Cell cellData1 = rowData.createCell(0, CellType.NUMERIC);
            cellData1.setCellValue(i);

            Cell cellData2 = rowData.createCell(1, CellType.STRING);
            cellData2.setCellValue("Student " + i);
        }

        try (FileOutputStream fos = new FileOutputStream("StudentsData.xlsx")) {
            workbook.write(fos);
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("Excel file has been generated!");

        try {
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

This code creates an Excel file named StudentsData.xlsx with a single worksheet. The worksheet contains a listing of student names and their respective IDs. The first row is a header with “ID” and “Name” labels. The next rows contain the IDs (numeric) and names (string “Student X”) for five different students.

How do I compile and execute a JDK preview features with Maven?

To compile and execute a JDK preview features with Maven, you need to add in the following configurations in your pom.xml file:

  • Compiler Plugin: The configuration should specify the JDK version and enable the preview features. It should look similar to this:
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <release>21</release>
                <compilerArgs>--enable-preview</compilerArgs>
            </configuration>
        </plugin>
    </plugins>
</build>
  • Surefire Plugin: If you’re using the Maven Surefire Plugin to run your tests, you should also enable the preview features there. The configuration may look similar to this:
<build>
    <plugins>
    ...
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.22.2</version>
            <configuration>
                <argLine>--enable-preview</argLine>
            </configuration>
        </plugin>
    </plugins>
</build>

Before building your project, ensure that you have JDK 21-preview installed on your computer, and it’s properly set in JAVA_HOME environment variable or in the IDE settings.

Then use Maven to package or install your project:

mvn clean package
# or
mvn clean install

Please ensure that you have the correct version of maven-compiler-plugin and maven-surefire-plugin that support the JDK 21-preview features. For the project that uses Spring MVC, you should make sure all dependencies are compatible with JDK 21-preview as well.