001/*
002 * The contents of this file are subject to the terms of the Common Development and
003 * Distribution License (the License). You may not use this file except in compliance with the
004 * License.
005 *
006 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
007 * specific language governing permission and limitations under the License.
008 *
009 * When distributing Covered Software, include this CDDL Header Notice in each file and include
010 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
011 * Header, with the fields enclosed by brackets [] replaced by your own identifying
012 * information: "Portions copyright [year] [name of copyright owner]".
013 *
014 * Copyright 2014-2015 ForgeRock AS.
015 */
016
017package org.forgerock.json.resource.examples;
018
019import static org.forgerock.json.resource.examples.DemoUtils.*;
020
021import java.util.concurrent.atomic.AtomicReference;
022
023import org.forgerock.json.resource.Connection;
024import org.forgerock.json.resource.ConnectionFactory;
025import org.forgerock.json.resource.Requests;
026import org.forgerock.json.resource.ResourceException;
027import org.forgerock.json.resource.ResourceResponse;
028import org.forgerock.util.AsyncFunction;
029import org.forgerock.util.promise.Promise;
030import org.forgerock.util.promise.ResultHandler;
031
032/**
033 * An example client application which performs an asynchronous read, modify,
034 * write update cycle for a resource in an in memory resource container. This
035 * example does not require any command line arguments.
036 */
037public final class AsyncReadModifyWriteDemo {
038    private AsyncReadModifyWriteDemo() {
039        // No implementation.
040    }
041
042    /**
043     * Main method.
044     *
045     * @param args
046     *            The command line arguments: this example does not have any.
047     * @throws ResourceException
048     *             If an unexpected error occurred.
049     */
050    public static void main(final String[] args) throws ResourceException {
051        final ConnectionFactory server = getConnectionFactory();
052        final AtomicReference<Connection> connectionHolder = new AtomicReference<>();
053
054        // @formatter:off
055        log("Opening connection");
056        final Promise<ResourceResponse, ResourceException> promise = server.getConnectionAsync()
057            .thenAsync(new AsyncFunction<Connection, ResourceResponse, ResourceException>() {
058                /*
059                 * Read resource.
060                 */
061                @Override
062                public Promise<ResourceResponse, ResourceException> apply(final Connection connection)
063                        throws ResourceException {
064                    log("Reading resource");
065                    connectionHolder.set(connection); // Save connection for later.
066                    return connection.readAsync(ctx(), Requests.newReadRequest("users/1"));
067                }
068            }).thenAsync(new AsyncFunction<ResourceResponse, ResourceResponse, ResourceException>() {
069                /*
070                 * Update resource.
071                 */
072                @Override
073                public Promise<ResourceResponse, ResourceException> apply(final ResourceResponse user)
074                        throws ResourceException {
075                    log("Resource read and has revision " + user.getRevision());
076                    log("Updating resource");
077                    return connectionHolder.get().updateAsync(ctx(),
078                            Requests.newUpdateRequest("users/1", userAliceWithIdAndRev(1, 1)));
079                }
080            }).thenOnResult(new ResultHandler<ResourceResponse>() {
081                /*
082                 * Check updated resource.
083                 */
084                @Override
085                public void handleResult(final ResourceResponse user) {
086                    log("Updated resource now has revision " + user.getRevision());
087                }
088            }).thenAlways(new Runnable() {
089                /*
090                 * Close the connection.
091                 */
092                @Override
093                public void run() {
094                    log("Closing connection");
095                    final Connection connection = connectionHolder.get();
096                    if (connection != null) {
097                        connection.close();
098                    }
099                }
100            });
101        // @formatter:on
102
103        // Wait for update to complete/fail.
104        promise.getOrThrowUninterruptibly();
105    }
106
107}