Quick start for P4 API for Java on Windows

Before you begin

Ensure you have the following:

  • Java Development Kit (JDK) 17 or later. Download from the Oracle website.

  • A working version of P4 Server.

  • The server and port values for P4 Server.

  • The username for your P4 user.

  • The name of the workspace you want to connect to.

  • The P4 API for Java distribution (ZIP file) from the Perforce repository.

  • The following Java dependency libraries:

    • commons-lang3-<version>.jar - Download here. Use version 3.x and above.

    • jzlib-<version>.jar - Download here. Any recent version works.

    • commons-io-<version>.jar - Download from the Apache Commons website. Use version 2.17 and above.

Set up P4 API for Java and connect to P4 Server

P4 API for Java is provided as a set of JAR files. To use P4 API for Java, place the required files in a directory, then compile and run a Java program.

Prepare the environment

  1. Download the P4 API for Java ZIP file.

  2. Extract the contents to a directory, for example: c:/p4java.

  3. Rename the main JAR file for simplicity. For example, rename p4java-<version>.jar to just p4java.jar.

  4. Download the required dependency libraries and place them in the same directory.

    Java does not automatically include dependencies. Download the required dependency libraries (commons-lang3.jar, commons-io.jar, and jzlib.jar) and place them in the same directory.

Your directory should look like:

C:\p4java
   ├── p4java.jar
   ├── commons-lang3.jar
   ├── jzlib.jar
   └── commons-io.jar

Create a test application

  1. Create a file called TestP4.java.

  2. Copy the following code:

    Copy
    import com.perforce.p4java.server.IOptionsServer;
    import com.perforce.p4java.server.ServerFactory;
    import com.perforce.p4java.server.IServerInfo;

    public class TestP4 {
        public static void main(String[] args) throws Exception {
            String uri = "p4java://localhost:1666";

            IOptionsServer server = ServerFactory.getOptionsServer(uri, null);
            server.connect();

            IServerInfo info = server.getServerInfo();

            System.out.println("Server version: " + info.getServerVersion());
            System.out.println("Connected to: " + uri);

            server.disconnect();
        }
    }
  3. Check the uri value in the script above. This is the default server and port number on most machines and should connect to your P4 Server. However, if the values differ from the code above, get the server and port using the format: p4java://server:port. For example: p4java://localhost:1666.

Compile and run the application

  1. Open a command prompt and navigate to the directory that contains all the java files:

    cd c:\p4java
  2. Compile the program:

    javac -cp ".;*" TestP4.java
  3. Run the program:

    java -cp ".;*" TestP4
  4. Confirm that the server version is displayed. This indicates a successful connection to the P4 Server:

    Server version: P4D/NTX64/<Version> <Date>
    Connected to: p4java://localhost:1666
  5. If you receive an error or a different output:

    1. Ensure all required JAR files are in the same directory.

    2. Use -cp ".;*" to include all dependencies.

    3. If you see errors such as ClassNotFoundException, a required dependency is missing.

    4. Verify that your P4 Server is running and accessible.

Get a list of files in the P4 Server depot

Use the following script to connect to P4 Server and display up to 10 files in a workspace.

Create the script

  1. Create a file called ListFiles.java.

  2. Add the following code to the script. Update the following variables:

    • uri – Set the server and port in the format p4java://server:port.

    • username – Your P4 user.

    • password – Your P4 user password.

    • clientName – The workspace to query.

    Copy
    import java.util.List;
    import java.util.Arrays;

    import com.perforce.p4java.client.IClient;
    import com.perforce.p4java.core.file.IFileSpec;
    import com.perforce.p4java.impl.generic.core.file.FileSpec;
    import com.perforce.p4java.server.IOptionsServer;
    import com.perforce.p4java.server.ServerFactory;

    public class ListFiles {
        public static void main(String[] args) throws Exception {
            String uri = "p4java://localhost:1666";
            String username = "your-username";
            String password = "your-password";
            String clientName = "your-workspace";

            // Connect to the server
            IOptionsServer server = ServerFactory.getOptionsServer(uri, null);
            server.connect();

            // Authenticate
            server.setUserName(username);
            server.login(password);

            // Set the workspace (client)
            IClient client = server.getClient(clientName);
            server.setCurrentClient(client);

            System.out.println("Files in workspace:");

            // Define a depot path
            List<IFileSpec> fileSpecs = Arrays.asList(
                new FileSpec("//" + clientName + "/...")
            );

            // Get files from the depot
            List<IFileSpec> files = server.getDepotFiles(fileSpecs, null);

            // Print up to 10 files
            int count = 0;
            for (IFileSpec file : files) {
                System.out.println(" - " + file.getDepotPathString());
                count++;
                if (count >= 10) break;
            }

            server.disconnect();
        }
    }

Compile and run

  1. Open a command prompt and navigate to your working directory:

    cd c:\p4java

  2. Compile the program:

    javac -cp ".;*" ListFiles.java

  3. Run the program:

    java -cp ".;*" ListFiles

  4. Check the expected output:

    Files in workspace:
     - //DemoDepot/project/file1.txt
     - //DemoDepot/project/file2.txt
     - //DemoDepot/project/file3.txt

Confirm that a list of files is displayed. This indicates that the connection and authentication to the P4 Server are successful

Troubleshooting

If you encounter an error, consider the following.

  • All required JAR files must be present in the directory or included in the classpath.

  • If you see a ClassNotFoundException, a dependency is missing.

  • If you see an authentication error, ensure you call server.login() with the correct password.

Check out a file using a changelist

Use the following script to open a file for edit in a new changelist.

Create the script

  1. Create a file called CheckoutFile.java.

  2. Add the following code to the script. Update the following variables:

    • uri – Set the server and port in the format p4java://server:port.

    • username – Your P4 user.

    • password – Your P4 user password.

    • clientName – The workspace to query.

    • filePath – A file that exists locally in your workspace.

    Copy
    import java.util.List;
    import java.util.Arrays;

    import com.perforce.p4java.client.IClient;
    import com.perforce.p4java.core.IChangelist;
    import com.perforce.p4java.impl.generic.core.Changelist;
    import com.perforce.p4java.core.file.IFileSpec;
    import com.perforce.p4java.impl.generic.core.file.FileSpec;
    import com.perforce.p4java.server.IOptionsServer;
    import com.perforce.p4java.server.ServerFactory;

    public class CheckoutFile {
        public static void main(String[] args) throws Exception {
            String uri = "p4java://localhost:1666";
            String username = "your-username";
            String password = "your-password";
            String clientName = "your-workspace";

            // Update this to a file in your workspace
            String filePath = "C:/your/workspace/file.txt";

            // Connect to the server
            IOptionsServer server = ServerFactory.getOptionsServer(uri, null);
            server.connect();

            // Authenticate
            server.setUserName(username);
            server.login(password);

            // Set the workspace (client)
            IClient client = server.getClient(clientName);
            server.setCurrentClient(client);

            // Create a new changelist
            IChangelist changelist = client.createChangelist(
                Changelist.newChangelist(client, "Edit file via P4Java Quick Start")
            );

            // Open the file for edit
            List<IFileSpec> files = Arrays.asList(new FileSpec(filePath));
            client.editFiles(files, false, false, changelist.getId(), null);

            System.out.println("Opened file for edit:");
            System.out.println(" - " + filePath);
            System.out.println("Changelist: " + changelist.getId());

            server.disconnect();
        }
    }

Compile and run

  1. Open a command prompt and navigate to your working directory:

    cd c:\p4java

  2. Compile the program:

    javac -cp ".;*" CheckoutFile.java

  3. Run the program:

    java -cp ".;*" CheckoutFile

  4. Check the expected output:

    Opened file for edit:
     - C:/workspace/file.txt
    Changelist: 12345

    Make a note of the changelist number. You will need this to commit the file.

Your chosen file is now available to edit.

If you have P4V, you will see a new changelist with your selected file.

Submit a changelist

Use the following script to submit a changelist containing edited files.

Create the script

  1. Create a file called SubmitChange.java.

  2. Add the following code to the script. Update the following variables:

    • uri – Set the server and port in the format p4java://server:port.

    • username – Your P4 user.

    • password – Your P4 user password.

    • clientName – The workspace to use.

    Copy
    import java.util.Scanner;

    import com.perforce.p4java.client.IClient;
    import com.perforce.p4java.core.IChangelist;
    import com.perforce.p4java.server.IOptionsServer;
    import com.perforce.p4java.server.ServerFactory;

    public class SubmitChange {
        public static void main(String[] args) throws Exception {
            String uri = "p4java://localhost:1666";
            String username = "your-username";
            String password = "your-password";
            String clientName = "your-workspace";

            Scanner scanner = new Scanner(System.in);

            // Ask user for changelist ID
            System.out.print("Enter changelist ID to submit: ");
            int changeId = Integer.parseInt(scanner.nextLine());

            // Ask user for description
            System.out.print("Enter changelist description: ");
            String description = scanner.nextLine();

            // Connect to server
            IOptionsServer server = ServerFactory.getOptionsServer(uri, null);
            server.connect();

            // Authenticate
            server.setUserName(username);
            server.login(password);

            // Set workspace
            IClient client = server.getClient(clientName);
            server.setCurrentClient(client);

            // Get existing changelist
            IChangelist changelist = server.getChangelist(changeId);

            // Update description
            changelist.setDescription(description);

            // Submit
            changelist.submit(false);

            System.out.println("Submitted changelist: " + changeId);

            server.disconnect();
            scanner.close();
        }
    }

Compile and run

  1. Open a command prompt and navigate to your working directory:

    cd c:\p4java

  2. Compile the program:

    javac -cp ".;*" SubmitChange.java

  3. Run the program:

    java -cp ".;*" SubmitChange

  4. When asked, enter the changelist number with the file you want to commit.

  5. (Optional) Enter a changelist description.

  6. Example interaction:

    Enter changelist ID to submit: 12345
    Enter changelist description: Updated API spec file
    Submitted changelist: 12345
    

Your chosen file has now been committed. If you check P4V, you will no longer be able to see the pending changelist.

Troubleshooting

If you encounter an error:

  • Ensure the changelist ID is valid.

  • Ensure the changelist contains files.

  • If you see an authentication error, confirm server.login() is called.

  • If submission fails, verify the file was opened for edit in the previous step.

Next steps

You have successfully connected to the P4 Server, listed files, opened a file for edit, and submitted a changelist using P4 API for Java. View the documentation for Basic P4 API for Java usage model to see what other commands are available when using P4 API for Java.