How do I list directory contents on a remote server using JSch?

To list the contents of a directory on a remote server using JSch (a Java library for SSH), you need to establish an SSH connection and use the SFTP protocol to query the directory. Here’s how you can do it programmatically:

Steps to List Directory Contents:

  1. Establish a session: Connect to the remote server with the appropriate credentials (host, port, username, password/key).
  2. Access the SFTP Channel: Open and connect a ChannelSftp instance.
  3. Change to the Target Directory: Navigate to the directory you want to list.
  4. Retrieve Directory Contents: Use the ls method of ChannelSftp to get the directory listing.

Here’s example code for this:

package org.kodejava.jsch;

import com.jcraft.jsch.*;

import java.util.Vector;

public class SFTPListDirectories {
   public static void main(String[] args) {
      String host = "example.com";
      int port = 22; // Default SSH port
      String user = "username";
      String password = "password"; // Or setup key-based authentication
      String remoteDirectory = "/path/to/remote/directory";

      JSch jsch = new JSch();

      try {
         // Establish SSH session
         Session session = jsch.getSession(user, host, port);
         session.setPassword(password);

         // Avoid asking for key confirmation
         session.setConfig("StrictHostKeyChecking", "no");
         session.connect();

         System.out.println("Connected to the server!");

         // Open SFTP channel
         Channel channel = session.openChannel("sftp");
         channel.connect();
         ChannelSftp channelSftp = (ChannelSftp) channel;

         System.out.println("SFTP Channel opened and connected.");

         // Change to the remote directory
         channelSftp.cd(remoteDirectory);

         // List files in the directory
         Vector<ChannelSftp.LsEntry> fileList = channelSftp.ls(remoteDirectory);

         System.out.println("Files in directory:");
         for (ChannelSftp.LsEntry entry : fileList) {
            System.out.println(entry.getFilename());
         }

         // Disconnect the channel and session
         channelSftp.exit();
         channel.disconnect();
         session.disconnect();
         System.out.println("Disconnected from the server.");
      } catch (JSchException | SftpException e) {
         e.printStackTrace();
      }
   }
}

Explanation of the Code:

  1. Session and Configuration:
    • A Session object is created and authenticated using username/password.
    • Set "StrictHostKeyChecking" to "no" if you want to bypass host key verification for testing purposes (not recommended in production).
  2. ChannelSftp:
    • The ChannelSftp object is used to navigate and interact with files/directories on the remote server.
    • The cd method is used to change to the target directory.
    • The ls method returns a Vector of ChannelSftp.LsEntry objects representing the contents.
  3. Directory Listing:
    • The getFilename() method retrieves the name of the file for each entry in the directory.
    • You can list files, directories, or other details by iterating over the entries.

Key Points to Remember:

  • The ls method may return not just files but also . (current directory) and .. (parent directory). You can filter these out if needed.
  • If using key-based authentication, you can set your private key with JSch.addIdentity("path/to/private/key").
  • Use try-with-resources or ensure proper closing of sessions and channels to avoid resource leaks.

Output Example:

For a remote directory /home/user/data containing the files:

file1.txt
file2.log
subdir

The output will be:

Connected to the server!
SFTP Channel opened and connected.
Files in directory:
.
..
file1.txt
file2.log
subdir
Disconnected from the server.

Maven Dependencies

<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.55</version>
</dependency>

Maven Central

How do I authenticate with a username and password using JSch?

To authenticate using a username and password with the JSch library (used for SSH connections in Java), you can follow these steps:

Add JSch Dependency

Make sure your project includes the JSch library. You can add it using Maven or Gradle if you’re using a build system.

For Maven:

<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.55</version>
</dependency>

For Gradle:

implementation 'com.jcraft:jsch:0.1.55'

Steps to Authenticate using Username and Password

Here is an example of setting up a basic authentication with JSch:

package org.kodejava.jsch;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class JSchUsernamePasswordExample {
   public static void main(String[] args) {
      String host = "example.com";
      int port = 22; // Default SSH port
      String username = "username";
      String password = "password";

      JSch jsch = new JSch();
      Session session = null;

      try {
         // Create a new JSch session
         session = jsch.getSession(username, host, port);

         // Set the password for authentication
         session.setPassword(password);

         // Configure session to skip strict host checking (not recommended for production)
         session.setConfig("StrictHostKeyChecking", "no");

         // Connect to the server
         System.out.println("Connecting to the server...");
         session.connect();
         System.out.println("Connected successfully!");

         // Add any additional logic for your session here
         // For example, opening channels, executing commands, etc.

      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         if (session != null && session.isConnected()) {
            // Disconnect the session
            session.disconnect();
            System.out.println("Disconnected.");
         }
      }
   }
}

Key Points in the Code:

  1. Host & Port: Replace "example.com" with your SSH server’s address and modify the port if needed (default SSH port is 22).
  2. Username and Password: Replace username and password with valid credentials for the SSH server you are connecting to.
  3. StrictHostKeyChecking:
    • Setting "StrictHostKeyChecking" to "no" disables host key verification.
    • This is acceptable for development but not recommended for production as it bypasses security checks. For production, add the server’s public key to the known hosts file.
  4. Error Handling: Ensure you include proper exception handling for debugging and connectivity issues.

This code will establish an SSH connection using the provided username and password. Depending on your use case, you can then use the Session object to open channels for executing commands, transferring files, etc.

How to Understand the Basics of ISO 8583 Message Structure

Understanding the basics of the ISO 8583 message structure can initially be daunting due to its technical nature, but breaking it down into its components makes it much easier to comprehend.

What is ISO 8583?

ISO 8583 is a standard widely used in financial transaction card-based systems (like ATMs and Point of Sale systems). It specifies how financial transaction messages are formatted, transmitted, and structured between systems. Each message represents a specific financial transaction—like a card authorization request or a fund transfer.

Basic Structure of an ISO 8583 Message

An ISO 8583 message is organized into components called Message Type Indicators (MTI), bitmaps, and data elements. Let’s explore these components in detail:


1. Message Type Indicator (MTI)

The MTI is the first part of an ISO 8583 message and is 4 digits long. It identifies the type of financial transaction being processed. These digits represent the following:

  • Digit 1 (Version): Specifies the version of ISO 8583 being used (e.g., 0 for ISO 8583:1987, 1 for ISO 8583:1993).
  • Digit 2 (Message Class): Indicates the type of message (e.g., 1 for authorization message, 2 for financial messages).
  • Digit 3 (Message Function): Determines the message’s purpose (e.g., 0 for a request, 1 for a response).
  • Digit 4 (Transaction Origin): Represents the message’s origin type (e.g., 0 for a system, 2 for an acquirer).

For example, 0200 indicates an authorization request for a transaction.


2. Bitmap

A bitmap is essentially a binary map that indicates which Data Elements (DEs) are present in the message. Each bit in the bitmap corresponds to a specific data element:

  • Primary Bitmap (64 bits): Always present, indicating whether the first 64 data elements are used.
  • Secondary Bitmap (optional, 64 bits): If the primary bitmap’s first bit is “1”, this indicates the use of an additional secondary bitmap for data elements 65–128.

For example, a bitmap like 7230000008020000 in hexadecimal shows which data elements are present and active in the message.


3. Data Elements (DEs)

Data elements hold the transaction-specific data like the amount, account number, date, time, and more. There are 128 standard data elements, organized as follows:

  • Mandatory Elements: These include crucial components such as transaction amount, processing code, etc.
  • Optional Elements: Acquired conditionally and depend on the transaction scenario.

Each data element has two key properties:

  • Data Type (e.g., numeric, alphanumeric): Specifies the type and content.
  • Length (fixed or variable): Defines the format of the element (e.g., fixed length of 10 digits or variable length preceded by a length prefix).
Examples of Common Data Elements:
DE Description Type Length
DE 3 Processing Code Numeric Fixed (6)
DE 4 Transaction Amount Numeric Fixed (12)
DE 7 Transmission Date & Time Numeric Fixed (10)
DE 37 Retrieval Reference Number Alphanumeric Fixed (12)
DE 41 Card Acceptor Terminal ID Alphanumeric Fixed (8)

Message Example Breakdown

Let’s take an example of an ISO 8583 authorization request message:

MTI         : 0200
Primary BMP : 7230000008020000
DE 3        : 001000
DE 4        : 000000010000
DE 7        : 1127220000
DE 11       : 123456
DE 41       : TERM001
DE 49       : USD

This means the message is:
1. MTI (0200): Authorization request.
2. Bitmap: Specifies that DE 3, 4, 7, 11, 41, and 49 are active.
3. Data Elements:

  • Processing Code (DE 3): 001000
  • Amount (DE 4): $100.00
  • Transmission Date & Time (DE 7): 11/27 at 22:00
  • System Trace Audit Number (DE 11): 123456
  • Terminal ID (DE 41): TERM001
  • Currency (DE 49): USD

Steps to Analyze an ISO 8583 Message

  1. Interpret MTI: Understand the type of transaction the message represents.
  2. Decode Bitmap: Identify which data elements are used in the message.
  3. Read Data Elements: Extract and interpret data elements based on the bitmap and structure.

Conclusion

ISO 8583 messages follow a structured yet flexible format. By understanding the key components like the MTI, bitmap, and data elements, you can analyze and process ISO 8583 messages effectively. Tools like parsers or libraries for your preferred programming language can simplify the heavy lifting when working with ISO 8583 in real-world applications.

How do I create a table with multiple header in iText 8?

In the following example we are going to create a table with multiple header. We will create table header with columns that spans in multiple columns and rows.

Here are the steps:

  1. Create a PdfWriter object called writer with the output filename.
  2. Create a PpdfDocument object called pdf, and pass the writer object as parameter.
  3. Using try-with-resource block, create a Document object with the pdf object as constructor argument.
  4. Instantiate a Table object. In this example we define it with five columns, and set the width of the table to take the full page width.
  5. Add table header cell using addHeaderCell() method. We add cell that spans multiple rows or multiple columns using the Cell constructor parameters rowspan and colspan.
  6. Add some rows of data to the table.
  7. Finally, we add the table object to the document.

And here is the full code snippet:

package org.kodejava.itext;

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.properties.TextAlignment;
import com.itextpdf.layout.properties.UnitValue;
import com.itextpdf.layout.properties.VerticalAlignment;

import java.io.FileNotFoundException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class TableWithMultiHeader {
    public static void main(String[] args) {
        TableWithMultiHeader demo = new TableWithMultiHeader();
        demo.createTable();
    }

    private void createTable() {
        try {
            PdfWriter writer = new PdfWriter("multi_header_table.pdf");
            PdfDocument pdf = new PdfDocument(writer);

            try (Document document = new Document(pdf)) {
                Table table = new Table(5);
                table.setWidth(UnitValue.createPercentValue(100));

                table.addHeaderCell(new Cell(2, 1)
                        .setVerticalAlignment(VerticalAlignment.MIDDLE)
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("No")));
                table.addHeaderCell(new Cell(2, 1)
                        .setVerticalAlignment(VerticalAlignment.MIDDLE)
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("Name")));
                table.addHeaderCell(new Cell(1, 2)
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("Date: " + LocalDate.now()
                                .format(DateTimeFormatter.ofPattern("dd-MMM-yyyy")))));
                table.addHeaderCell(new Cell(2, 1)
                        .setVerticalAlignment(VerticalAlignment.MIDDLE)
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("Activity")));
                table.addHeaderCell(new Cell(1, 1)
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("Start Time")));
                table.addHeaderCell(new Cell(1, 1)
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("End Time")));

                table.addCell(new Cell()
                        .setTextAlignment(TextAlignment.RIGHT)
                        .add(new Paragraph("1")));
                table.addCell(new Cell().add(new Paragraph("Alice")));
                table.addCell(new Cell()
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("10:00")));
                table.addCell(new Cell()
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("11:00")));
                table.addCell(new Cell().add(new Paragraph("Learn ukulele basic")));

                table.addCell(new Cell()
                        .setTextAlignment(TextAlignment.RIGHT)
                        .add(new Paragraph("2")));
                table.addCell(new Cell().add(new Paragraph("Bob")));
                table.addCell(new Cell()
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("09:00")));
                table.addCell(new Cell()
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("11:00")));
                table.addCell(new Cell()
                        .add(new Paragraph("Learn piano basic")));

                document.add(table);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Running the code will give you the result shown in the image below:

Multi-header Table

Maven Dependencies

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-core</artifactId>
    <version>8.0.4</version>
    <type>pom</type>
</dependency>

Maven Central

How do I add Image to a Table in iText 8?

In this example you’ll see how to add Image to a Table when creating a PDF document using iText 8. We start by finding the image resource using getResource() method and pass the absolute path to the resource name. The getResource() method return a java.net.URL object.

With this URL object in hand we then create the ImageData object using the ImageDataFactory.create() method. To the create() factory method we pass the URL object as a parameter. Finally, we create the Image object by calling the constructor of this class and passes the ImageData object as a parameter.

Here is the complete code snippet. Below we create a Premier League Ladder table showing club current position from position 1 to 10.

package org.kodejava.itext;

import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.colors.DeviceGray;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.borders.Border;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.properties.TextAlignment;
import com.itextpdf.layout.properties.UnitValue;
import com.itextpdf.layout.properties.VerticalAlignment;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static com.itextpdf.kernel.colors.DeviceGray.makeLighter;

public class TableExample {
    public static void main(String[] args) throws Exception {
        TableExample demo = new TableExample();
        demo.createTable();
    }

    private void createTable() throws Exception {
        String destination = "premier-league-ladder.pdf";
        PdfWriter writer = new PdfWriter(destination);
        PdfDocument pdf = new PdfDocument(writer);

        String[] headers = {"Position", "Club", "Played", "Won", "Drown", "Lost", "GF", "GA", "GD", "Points"};

        try (Document document = new Document(pdf)) {
            Table table = new Table(headers.length + 1);
            // Set table width to span the entire page
            table.setWidth(UnitValue.createPercentValue(100));

            URL plLogoFile = TableExample.class.getResource("/epl/pl-main-logo.png");
            ImageData plImageData = ImageDataFactory.create(Objects.requireNonNull(plLogoFile));

            table.addHeaderCell(new Cell().setBorder(Border.NO_BORDER)
                    .add(new Image(plImageData).scaleToFit(50, 50)));
            table.addHeaderCell(new Cell(1, 11).setBorder(Border.NO_BORDER)
                    .setVerticalAlignment(VerticalAlignment.MIDDLE)
                    .add(new Paragraph("Premier League Ladder").setFontSize(16).setBold()));

            for (String header : headers) {
                if (header.equals("Club")) {
                    table.addHeaderCell(new Cell(1, 2)
                            .setBackgroundColor(makeLighter(DeviceGray.GRAY))
                            .setBorderLeft(Border.NO_BORDER).setBorderRight(Border.NO_BORDER)
                            .setWidth(UnitValue.createPercentValue(28))
                            .add(new Paragraph(header)));
                } else {
                    table.addHeaderCell(newCell()
                            .setBackgroundColor(makeLighter(DeviceGray.GRAY))
                            .setWidth(UnitValue.createPercentValue(8))
                            .add(new Paragraph(header).setTextAlignment(TextAlignment.CENTER)));
                }
            }

            int position = 1;
            for (Club club : getTableData()) {
                String fileName = club.name().replace(' ', '_').toLowerCase() + ".png";
                URL logoFile = TableExample.class.getResource("/epl/logo/" + fileName);
                ImageData imageData = ImageDataFactory.create(Objects.requireNonNull(logoFile));

                table.addCell(newCell().add(newCenteredParagraph(String.valueOf(position++))));
                table.addCell(newCell().setWidth(UnitValue.createPercentValue(1))
                        .setVerticalAlignment(VerticalAlignment.MIDDLE)
                        .add(new Image(imageData).scaleAbsolute(16, 16)));
                table.addCell(newCell().setWidth(UnitValue.createPercentValue(27))
                        .add(new Paragraph(club.name())));
                table.addCell(newCell().add(newCenteredParagraph(String.valueOf(club.played()))));
                table.addCell(newCell().add(newCenteredParagraph(String.valueOf(club.won()))));
                table.addCell(newCell().add(newCenteredParagraph(String.valueOf(club.drawn()))));
                table.addCell(newCell().add(newCenteredParagraph(String.valueOf(club.lost()))));
                table.addCell(newCell().add(newCenteredParagraph(String.valueOf(club.goalsFor()))));
                table.addCell(newCell().add(newCenteredParagraph(String.valueOf(club.goalsAgainst()))));
                table.addCell(newCell().add(newCenteredParagraph(String.valueOf(club.goalDifference()))));
                table.addCell(newCell().add(newCenteredParagraph(String.valueOf(club.points()))));
            }

            document.add(table);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Cell newCell() {
        return new Cell().setBorderLeft(Border.NO_BORDER).setBorderRight(Border.NO_BORDER);
    }

    private Paragraph newCenteredParagraph(String text) {
        return new Paragraph(text).setTextAlignment(TextAlignment.CENTER);
    }

    private List<Club> getTableData() {
        List<Club> clubs = new ArrayList<>();
        clubs.add(new Club("Arsenal", 20, 4, 4, 70, 24));
        clubs.add(new Club("Liverpool", 19, 6, 2, 64, 25));
        clubs.add(new Club("Man City", 19, 5, 3, 62, 27));
        clubs.add(new Club("Aston Villa", 17, 4, 6, 59, 37));
        clubs.add(new Club("Tottenham", 15, 5, 6, 55, 39));
        clubs.add(new Club("Man United", 15, 2, 11, 39, 39));
        clubs.add(new Club("West Ham", 12, 6, 9, 43, 47));
        clubs.add(new Club("Wolves", 12, 5, 11, 42, 44));
        clubs.add(new Club("Newcastle", 12, 4, 11, 57, 45));
        clubs.add(new Club("Brighton", 10, 9, 8, 49, 44));
        return clubs;
    }

    record Club(String name, int won, int drawn, int lost, int goalsFor, int goalsAgainst) {
        public int played() {
            return won + drawn + lost;
        }

        public int goalDifference() {
            return goalsFor - goalsAgainst;
        }

        public int points() {
            return (won * 3) + drawn;
        }
    }
}

And here is the output of the generated PDF table:

Premier League Ladder Table

In the example above you can also see how to expand the width of the table to take the full width of the page.

table.setWidth(UnitValue.createPercentValue(100));

To span a table Cell to take multiple columns you can create a Cell object and specify the rowspan and colspan parameter.

table.addHeaderCell(new Cell(1, 2));

To remove the vertical border of the Cell you can set the left and right border by calling the setBorderLeft() and setBorderRight() method and passes Border.NO_BORDER as parameter.

new Cell().setBorderLeft(Border.NO_BORDER).setBorderRight(Border.NO_BORDER);

The data of the table is encapsulated using a record, this feature is introduced in Java 14, prior to this version you will create a simple POJO, which is a Java object with properties and related getters and setters method.

public record Club(String name, int won, int drawn, int lost, int goalsFor, int goalsAgainst) {}

Maven Dependencies

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-core</artifactId>
    <version>8.0.4</version>
    <type>pom</type>
</dependency>

Maven Central