user3732065
user3732065

Reputation: 11

How to receive Attributes in PubSub

Could anyone help me to receive the attributes from a PubSub-Message? The Message is shown correctly but without the attributes. My Receive-Class looks like this:

public class ReceiveMessageServlet extends HttpServlet {

@Override
public final void doPost(final HttpServletRequest req,
                         final HttpServletResponse resp)
        throws IOException {
    // Validating unique subscription token before processing the message
    String subscriptionToken = System.getProperty(
            Constants.BASE_PACKAGE + ".subscriptionUniqueToken");
    if (!subscriptionToken.equals(req.getParameter("token"))) {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        resp.getWriter().close();
        return;
    }

    ServletInputStream inputStream = req.getInputStream();

    // Parse the JSON message to the POJO model class
    JsonParser parser = JacksonFactory.getDefaultInstance()
            .createJsonParser(inputStream);
    parser.skipToKey("message");
    PubsubMessage message = parser.parseAndClose(PubsubMessage.class);

    // Store the message in the datastore
    Entity messageToStore = new Entity("PubsubMessage");
    messageToStore.setProperty("message",
            new String(message.decodeData(), "UTF-8"));
    messageToStore.setProperty("receipt-time", System.currentTimeMillis());
    DatastoreService datastore =
            DatastoreServiceFactory.getDatastoreService();
    datastore.put(messageToStore);

    // Invalidate the cache
    MemcacheService memcacheService =
            MemcacheServiceFactory.getMemcacheService();
    memcacheService.delete(Constants.MESSAGE_CACHE_KEY);

    // Acknowledge the message by returning a success code
    resp.setStatus(HttpServletResponse.SC_OK);
    resp.getWriter().close();


}

}

I have tried it with message.getAttributes() but without any success.

Upvotes: 1

Views: 1605

Answers (1)

Teyam
Teyam

Reputation: 8092

You may want to check the added PubsubIO functionality that allows the Read and Write transforms to provide access to Cloud Pub/Sub message attributes which has been added in the latest release.

Try using withAttributes method. This,

Causes the source to return a PubsubMessage that includes Pubsub attributes. The user must supply a parsing function to transform the PubsubMessage into an output type. A Coder for the output type T must be registered or set on the output via PCollection.setCoder(Coder).

Hope it helps.

Upvotes: 1

Related Questions