---
schema_version: "1"
id: 79b9df84a7e329cd3ddb9c010f7e6d0db4f9be00f0da8c330c93296d1afcf14e
title: "Step 4: Publish and Subscribe to Platform Events"
collection: developer
version: current
locale: en-us
portal_url: https://docs.salesforce.com/developer/current/en-us/event-bus/pub-sub-api/guides/qs-java-publish-subscribe.md
canonical_url: https://developer.salesforce.com/docs/platform/pub-sub-api/guide/qs-java-publish-subscribe.html
source_site: developer.salesforce.com
content_type: documentation
content_hash: 69b627c1e6cb9c13dce302948fc8e1510927336a9e986bf086f81cd73756b7b4
products:
  - Pub/Sub API
  - Event Bus Docs
---
# Step 4: Publish and Subscribe to Platform Events

Use the Java examples for the `Subscribe` RPC and `PublishStream` RPC to try out publishing and receiving events.

**Prerequisites**

- If you’re using a Developer Edition org and you set up a namespace prefix, modify the Java code that builds the event message to prepend the namespace prefix to the platform event fields. In `java/src/main/java/utility/CommonContext.java`, modify the `createEventMessage` and `createEventMessages` methods to include the namespace prefix in the field names.

1. In a Terminal window, navigate to the top-level `java` folder.
2. To run the Subscribe RPC example, enter: `./run.sh genericpubsub.Subscribe`
3. The Subscribe example prints out logging info on the terminal, similar to:

   ```
   2024-04-09 11:56:35,443 [main] java.lang.Class - Using grpcHost api.pubsub.salesforce.com and grpcPort 7443
   2024-04-09 11:56:36,610 [main] utility.APISessionCredentials - Client Trace Id for current request:
   161d4754-cd94-446e-8c41-77626805dd7c
   2024-04-09 11:56:37,126 [main] java.lang.Class - Subscription started for topic:
   /event/Order_Event__e.
   2024-04-09 11:56:37,128 [main] utility.APISessionCredentials - Client Trace Id for current request:
   aeecdf2c-9522-4d1d-a4ba-359f137cf53e
   2024-04-09 11:56:42,140 [main] java.lang.Class - Subscription Active. Received a total of 0 events.
   ```

   Because no events were published, the count of received events is zero.

4. Before you can publish events, modify the code to specify the event fields and values to publish. In this quick start, you modify the code to supply the user ID for the `CreatedById` field in the event message. You use the sample values for the other event fields. In a text editor or an IDE, such as Visual Studio Code, open the `java/src/main/java/utility/CommonContext.java` from your `pub-sub-api` folder.

5. There are several `createEventMessage` methods and one `createEventMessages` method that build the event messages. This method is used in `Publish.java`.

   ```
   // Used by Publish.java
   public GenericRecord createEventMessage(Schema schema)
   ```

   These methods are used in `PublishStream.java`. In this quick start, we use `PublishStream.java` with the default argument value of `SINGLE_PUBLISH_REQUEST` of `true`, so the `createEventMessages` method is used.

   ```
   // Used by PublishStream.java when SINGLE_PUBLISH_REQUEST is false
   public GenericRecord createEventMessage(Schema schema, final int counter)

   // Used by PublishStream.java when SINGLE_PUBLISH_REQUEST is true
   public List<GenericRecord> createEventMessages(Schema schema, final int numEvents)
   ```

   Provide a valid `CreatedById` value for the published event message in this method. Replace the `<User_Id>` placeholder value of the `CreatedById` field with a valid user ID in your Salesforce org. To get the user ID, see [Find the Salesforce ID for a User or Profile](https://help.salesforce.com/s/articleView?id=000381643&type=1).

   ```
       public List<GenericRecord> createEventMessages(Schema schema, final int numEvents) {

        String[] orderNumbers = {"99","100","101","102","103"};
        String[] cities = {"Los Angeles", "New York", "San Francisco", "San Jose", "Boston"};
        Double[] amounts = {35.0, 20.0, 2.0, 123.0, 180.0};

        // Update CreatedById with the appropriate User Id from your org.
        List<GenericRecord> events = new ArrayList<>();
        for (int i=0; i<numEvents; i++) {
            events.add(new GenericRecordBuilder(schema)
                    .set("CreatedDate", System.currentTimeMillis())
                    .set("CreatedById", "<User_Id>")
                    .set("Order_Number__c", orderNumbers[i % 5])
                    .set("City__c", cities[i % 5])
                    .set("Amount__c", amounts[i % 5]).build());
        }

        return events;
    }
   ```

6. Optional. If you want to supply other event fields and values, make additional changes.
7. To publish all events in one publish request using the `createEventMessages` method, in `java/src/main/resources/arguments.yaml`, set `SINGLE_PUBLISH_REQUEST` to true: `SINGLE_PUBLISH_REQUEST: true`
8. In a new terminal window, navigate to the top-level `java` folder in your `pub-sub-api` folder.
9. To build the Java client, enter: `mvn clean install`
10. To run the `PublishStream` RPC example, enter: `./run.sh genericpubsub.PublishStream`
    The example publishes five events as set in the `arguments.yaml` file’s default configuration. It prints out logging information to the terminal.
11. Return to the terminal for the Subscribe example. The output shows the events received.

```
2024-04-09 11:56:51,302 [pool-3-thread-1] java.lang.Class - Received event with payload:
{
  "CreatedDate": 1712689010574,
  "CreatedById": "0055f000005mc66AAA",
  "Order_Number__c": "99",
  "City__c": "Los Angeles",
  "Amount__c": 35.0
}
with schema name: Order_Event__e
2024-04-09 11:56:51,302 [pool-3-thread-2] java.lang.Class - Received event with payload:
{
  "CreatedDate": 1712689010574,
  "CreatedById": "0055f000005mc66AAA",
  "Order_Number__c": "100",
  "City__c": "New York",
  "Amount__c": 20.0
}
with schema name: Order_Event__e
2024-04-09 11:56:51,302 [pool-3-thread-3] java.lang.Class - Received event with payload:
{
  "CreatedDate": 1712689010574,
  "CreatedById": "0055f000005mc66AAA",
  "Order_Number__c": "101",
  "City__c": "San Francisco",
  "Amount__c": 2.0
}
with schema name: Order_Event__e
2024-04-09 11:56:51,303 [pool-3-thread-2] java.lang.Class - Received event with payload:
{
  "CreatedDate": 1712689010574,
  "CreatedById": "0055f000005mc66AAA",
  "Order_Number__c": "102",
  "City__c": "San Jose",
  "Amount__c": 123.0
}
with schema name: Order_Event__e
2024-04-09 11:56:51,303 [pool-3-thread-1] java.lang.Class - Received event with payload:
{
  "CreatedDate": 1712689010574,
  "CreatedById": "0055f000005mc66AAA",
  "Order_Number__c": "103",
  "City__c": "Boston",
  "Amount__c": 180.0
}
with schema name: Order_Event__e

```

## Learn More

To learn more about the example code, see [Implementation](https://github.com/forcedotcom/pub-sub-api/tree/main/java#implementation) and [Limitations](https://github.com/forcedotcom/pub-sub-api/tree/main/java#limitations) in the Readme page of the `pub-sub-api` GitHub repository.

The client code for the Pub/Sub API RPC methods is in the [genericpubsub](https://github.com/forcedotcom/pub-sub-api/tree/main/java/src/main/java/genericpubsub) folder. To check out the implementation for each RPC method, open the corresponding Java file in the `genericpubsub` folder. For the `PublishStream` example, open [PublishStream.java](https://github.com/forcedotcom/pub-sub-api/blob/main/java/src/main/java/genericpubsub/PublishStream.java). And for the `Subscribe` example, open [Subscribe.java](https://github.com/forcedotcom/pub-sub-api/blob/main/java/src/main/java/genericpubsub/Subscribe.java).

For more information about the `PublishStream` and `Subscribe` RPC methods, see [PublishStream RPC Method](https://developer.salesforce.com/docs/platform/pub-sub-api/references/methods/publishstream-rpc.html) and [Subscribe RPC Method](https://developer.salesforce.com/docs/platform/pub-sub-api/references/methods/subscribe-rpc.html).

To run other RPC methods, use this command format: `./run.sh <package_name>.<example_class_name>`
