Java Code Examples for com.google.ipc.invalidation.ticl.PersistenceUtils

The following examples show how to use com.google.ipc.invalidation.ticl.PersistenceUtils. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * Returns the persisted state for the client with key {@code clientKey} in
 * {@code storageForClient}, or {@code null} if no valid state could be found.
 * <p>
 * REQUIRES: {@code storageForClient}.load() has been called successfully.
 */


PersistentTiclState decodeTiclState(final String clientKey, AndroidStorage storageForClient) {
  synchronized (lock) {
    // Retrieve the serialized state.
    final Map<String, byte[]> properties = storageForClient.getPropertiesUnsafe();
    byte[] clientStateBytes = TypedUtil.mapGet(properties,
        InvalidationClientCore.CLIENT_TOKEN_KEY);
    if (clientStateBytes == null) {
      logger.warning("No client state found in storage for %s: %s", clientKey,
          properties.keySet());
      return null;
    }

    // Deserialize it.
    PersistentTiclState clientState =
        PersistenceUtils.deserializeState(logger, clientStateBytes, digestFn);
    if (clientState == null) {
      logger.warning("Invalid client state found in storage for %s", clientKey);
      return null;
    }
    return clientState;
  }
}
 
Example 2
/**
 * Returns the persisted state for the client with key {@code clientKey} in
 * {@code storageForClient}, or {@code null} if no valid state could be found.
 * <p>
 * REQUIRES: {@code storageForClient}.load() has been called successfully.
 */


PersistentTiclState decodeTiclState(final String clientKey, AndroidStorage storageForClient) {
  synchronized (lock) {
    // Retrieve the serialized state.
    final Map<String, byte[]> properties = storageForClient.getPropertiesUnsafe();
    byte[] clientStateBytes = TypedUtil.mapGet(properties,
        InvalidationClientCore.CLIENT_TOKEN_KEY);
    if (clientStateBytes == null) {
      logger.warning("No client state found in storage for %s: %s", clientKey,
          properties.keySet());
      return null;
    }

    // Deserialize it.
    PersistentTiclState clientState =
        PersistenceUtils.deserializeState(logger, clientStateBytes, digestFn);
    if (clientState == null) {
      logger.warning("Invalid client state found in storage for %s", clientKey);
      return null;
    }
    return clientState;
  }
}
 
Example 3
/**
 * Handles receipt of a GCM message for a client that was unknown or not started. If the client
 * was unknown, drops the message. If the client was not started, rewrites the client's
 * persistent state to have a last-message-sent-time of 0, ensuring that the client will
 * send a heartbeat to the server when restarted. Since we drop the received GCM message,
 * the client will be disconnected by the invalidation pusher; this heartbeat ensures a
 * timely reconnection.
 */
private void handleGcmMessageForUnstartedClient(AndroidClientProxy proxy) {
  if (proxy == null) {
    // Unknown client; nothing to do.
    return;
  }

  // Client is not started. Open its storage. We are going to use unsafe calls here that
  // bypass the normal storage API. This is safe in this context because we hold a lock
  // that prevents anyone else from starting this client or accessing its storage. We
  // really should not be holding a lock across I/O, but at least this is only local
  // file I/O, and we're only writing a few bytes. Additionally, since we currently only
  // have one Ticl, we should only ever enter this function if we're not being used for
  // anything else.
  final String clientKey = proxy.getClientKey();
  logger.info("Received message for unloaded client; rewriting state file: %s", clientKey);

  // This storage must have been loaded, because we got this proxy from the client manager,
  // which always ensures that its entries have that property.
  AndroidStorage storageForClient = proxy.getStorage();
  PersistentTiclState clientState = decodeTiclState(clientKey, storageForClient);
  if (clientState == null) {
    // Logging done in decodeTiclState.
    return;
  }

  // Rewrite the last message sent time.
  PersistentTiclState newState = PersistentTiclState.newBuilder(clientState)
      .setLastMessageSendTimeMs(0).build();

  // Serialize the new state.
  byte[] newClientState = PersistenceUtils.serializeState(newState, digestFn);

  // Write it out.
  storageForClient.getPropertiesUnsafe().put(InvalidationClientCore.CLIENT_TOKEN_KEY,
      newClientState);
  storageForClient.storeUnsafe();
}
 
Example 4
/**
 * Handles receipt of a GCM message for a client that was unknown or not started. If the client
 * was unknown, drops the message. If the client was not started, rewrites the client's
 * persistent state to have a last-message-sent-time of 0, ensuring that the client will
 * send a heartbeat to the server when restarted. Since we drop the received GCM message,
 * the client will be disconnected by the invalidation pusher; this heartbeat ensures a
 * timely reconnection.
 */
private void handleGcmMessageForUnstartedClient(AndroidClientProxy proxy) {
  if (proxy == null) {
    // Unknown client; nothing to do.
    return;
  }

  // Client is not started. Open its storage. We are going to use unsafe calls here that
  // bypass the normal storage API. This is safe in this context because we hold a lock
  // that prevents anyone else from starting this client or accessing its storage. We
  // really should not be holding a lock across I/O, but at least this is only local
  // file I/O, and we're only writing a few bytes. Additionally, since we currently only
  // have one Ticl, we should only ever enter this function if we're not being used for
  // anything else.
  final String clientKey = proxy.getClientKey();
  logger.info("Received message for unloaded client; rewriting state file: %s", clientKey);

  // This storage must have been loaded, because we got this proxy from the client manager,
  // which always ensures that its entries have that property.
  AndroidStorage storageForClient = proxy.getStorage();
  PersistentTiclState clientState = decodeTiclState(clientKey, storageForClient);
  if (clientState == null) {
    // Logging done in decodeTiclState.
    return;
  }

  // Rewrite the last message sent time.
  PersistentTiclState newState = PersistentTiclState.newBuilder(clientState)
      .setLastMessageSendTimeMs(0).build();

  // Serialize the new state.
  byte[] newClientState = PersistenceUtils.serializeState(newState, digestFn);

  // Write it out.
  storageForClient.getPropertiesUnsafe().put(InvalidationClientCore.CLIENT_TOKEN_KEY,
      newClientState);
  storageForClient.storeUnsafe();
}
 
Example 5
Source Project: 365browser   Source File: TiclService.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Handles a {@code message} for a {@code ticl}. If the {@code ticl} is started, delivers the
 * message. If the {@code ticl} is not started, drops the message and clears the last message send
 * time in the Ticl persistent storage so that the Ticl will send a heartbeat the next time it
 * starts.
 */
private void handleServerMessage(boolean isTiclStarted, byte[] message) {
  if (isTiclStarted) {
    // Normal case -- message for a started Ticl. Deliver the message.
    resources.getNetworkListener().onMessageReceived(message);
    return;
  }

  // Even if the client is stopped, attempt to send invalidations if the client is configured to
  // receive them.
  maybeSendBackgroundInvalidationIntent(message);

  // The Ticl isn't started. Rewrite persistent storage so that the last-send-time is a long
  // time ago. The next time the Ticl starts, it will send a message to the data center, which
  // ensures that it will be marked online and that the dropped message (or an equivalent) will
  // be delivered.
  // Android storage implementations are required to execute callbacks inline, so this code
  // all executes synchronously.
  resources.getLogger().fine("Message for unstarted Ticl; rewrite state");
  resources.getStorage().readKey(InvalidationClientCore.CLIENT_TOKEN_KEY,
      new Callback<SimplePair<Status, byte[]>>() {
    @Override
    public void accept(SimplePair<Status, byte[]> result) {
      byte[] stateBytes = result.second;
      if (stateBytes == null) {
        resources.getLogger().info("No persistent state found for client; not rewriting");
        return;
      }
      // Create new state identical to the old state except with a cleared
      // lastMessageSendTimeMs.
      PersistentTiclState state = PersistenceUtils.deserializeState(
          resources.getLogger(), stateBytes, digestFn);
      if (state == null) {
        resources.getLogger().warning("Ignoring invalid Ticl state: %s",
            Bytes.toLazyCompactString(stateBytes));
        return;
      }
      PersistentTiclState.Builder stateBuilder = state.toBuilder();
      stateBuilder.lastMessageSendTimeMs = 0L;
      state = stateBuilder.build();

      // Serialize the new state and write it to storage.
      byte[] newClientState = PersistenceUtils.serializeState(state, digestFn);
      resources.getStorage().writeKey(InvalidationClientCore.CLIENT_TOKEN_KEY, newClientState,
          new Callback<Status>() {
            @Override
            public void accept(Status status) {
              if (status.getCode() != Status.Code.SUCCESS) {
                resources.getLogger().warning(
                    "Failed saving rewritten persistent state to storage");
              }
            }
      });
    }
  });
}
 
Example 6
/**
 * Handles a {@code message} for a {@code ticl}. If the {@code ticl} is started, delivers the
 * message. If the {@code ticl} is not started, drops the message and clears the last message send
 * time in the Ticl persistent storage so that the Ticl will send a heartbeat the next time it
 * starts.
 */
private void handleServerMessage(boolean isTiclStarted, byte[] message) {
  if (isTiclStarted) {
    // Normal case -- message for a started Ticl. Deliver the message.
    resources.getNetworkListener().onMessageReceived(message);
    return;
  }
  // The Ticl isn't started. Rewrite persistent storage so that the last-send-time is a long
  // time ago. The next time the Ticl starts, it will send a message to the data center, which
  // ensures that it will be marked online and that the dropped message (or an equivalent) will
  // be delivered.
  // Android storage implementations are required to execute callbacks inline, so this code
  // all executes synchronously.
  resources.getLogger().fine("Message for unstarted Ticl; rewrite state");
  resources.getStorage().readKey(InvalidationClientCore.CLIENT_TOKEN_KEY,
      new Callback<SimplePair<Status, byte[]>>() {
    @Override
    public void accept(SimplePair<Status, byte[]> result) {
      byte[] stateBytes = result.second;
      if (stateBytes == null) {
        resources.getLogger().info("No persistent state found for client; not rewriting");
        return;
      }
      // Create new state identical to the old state except with a cleared
      // lastMessageSendTimeMs.
      PersistentTiclState state = PersistenceUtils.deserializeState(
          resources.getLogger(), stateBytes, digestFn);
      if (state == null) {
        resources.getLogger().warning("Ignoring invalid Ticl state: %s", stateBytes);
        return;
      }
      PersistentTiclState newState = PersistentTiclState.newBuilder(state)
          .setLastMessageSendTimeMs(0)
          .build();

      // Serialize the new state and write it to storage.
      byte[] newClientState = PersistenceUtils.serializeState(newState, digestFn);
      resources.getStorage().writeKey(InvalidationClientCore.CLIENT_TOKEN_KEY, newClientState,
          new Callback<Status>() {
            @Override
            public void accept(Status status) {
              if (status.getCode() != Status.Code.SUCCESS) {
                resources.getLogger().warning(
                    "Failed saving rewritten persistent state to storage");
              }
            }
      });
    }
  });
}
 
Example 7
/**
 * Handles a {@code message} for a {@code ticl}. If the {@code ticl} is started, delivers the
 * message. If the {@code ticl} is not started, drops the message and clears the last message send
 * time in the Ticl persistent storage so that the Ticl will send a heartbeat the next time it
 * starts.
 */
private void handleServerMessage(boolean isTiclStarted, byte[] message) {
  if (isTiclStarted) {
    // Normal case -- message for a started Ticl. Deliver the message.
    resources.getNetworkListener().onMessageReceived(message);
    return;
  }
  // The Ticl isn't started. Rewrite persistent storage so that the last-send-time is a long
  // time ago. The next time the Ticl starts, it will send a message to the data center, which
  // ensures that it will be marked online and that the dropped message (or an equivalent) will
  // be delivered.
  // Android storage implementations are required to execute callbacks inline, so this code
  // all executes synchronously.
  resources.getLogger().fine("Message for unstarted Ticl; rewrite state");
  resources.getStorage().readKey(InvalidationClientCore.CLIENT_TOKEN_KEY,
      new Callback<SimplePair<Status, byte[]>>() {
    @Override
    public void accept(SimplePair<Status, byte[]> result) {
      byte[] stateBytes = result.second;
      if (stateBytes == null) {
        resources.getLogger().info("No persistent state found for client; not rewriting");
        return;
      }
      // Create new state identical to the old state except with a cleared
      // lastMessageSendTimeMs.
      PersistentTiclState state = PersistenceUtils.deserializeState(
          resources.getLogger(), stateBytes, digestFn);
      if (state == null) {
        resources.getLogger().warning("Ignoring invalid Ticl state: %s", stateBytes);
        return;
      }
      PersistentTiclState newState = PersistentTiclState.newBuilder(state)
          .setLastMessageSendTimeMs(0)
          .build();

      // Serialize the new state and write it to storage.
      byte[] newClientState = PersistenceUtils.serializeState(newState, digestFn);
      resources.getStorage().writeKey(InvalidationClientCore.CLIENT_TOKEN_KEY, newClientState,
          new Callback<Status>() {
            @Override
            public void accept(Status status) {
              if (status.getCode() != Status.Code.SUCCESS) {
                resources.getLogger().warning(
                    "Failed saving rewritten persistent state to storage");
              }
            }
      });
    }
  });
}