com.google.ipc.invalidation.util.TypedUtil Java Examples

The following examples show how to use com.google.ipc.invalidation.util.TypedUtil. 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
Source File: PersistenceUtils.java    From android-chromium with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Deserializes a Ticl state blob. Returns either the parsed state or {@code null}
 * if it could not be parsed.
 */
public static PersistentTiclState deserializeState(Logger logger, byte[] stateBlobBytes,
    DigestFunction digestFn) {
  PersistentStateBlob stateBlob;
  try {
    // Try parsing the envelope protocol buffer.
    stateBlob = PersistentStateBlob.parseFrom(stateBlobBytes);
  } catch (InvalidProtocolBufferException exception) {
    logger.severe("Failed deserializing Ticl state: %s", exception.getMessage());
    return null;
  }

  // Check the mac in the envelope against the recomputed mac from the state.
  PersistentTiclState ticlState = stateBlob.getTiclState();
  ByteString mac = generateMac(ticlState, digestFn);
  if (!TypedUtil.<ByteString>equals(mac, stateBlob.getAuthenticationCode())) {
    logger.warning("Ticl state failed MAC check: computed %s vs %s", mac,
        stateBlob.getAuthenticationCode());
    return null;
  }
  return ticlState;
}
 
Example #2
Source File: AndroidInternalScheduler.java    From 365browser with Apache License 2.0 6 votes vote down vote up
/** Runs all tasks that are ready to run. */
void handleImplicitSchedulerEvent() {
  try {
    while (!scheduledTasks.isEmpty() && (scheduledTasks.firstKey() <= clock.nowMs())) {
      Map.Entry<Long, String> scheduledTask = scheduledTasks.pollFirstEntry();
      Runnable runnable = TypedUtil.mapGet(registeredTasks, scheduledTask.getValue());
      if (runnable == null) {
        logger.severe("No task registered for %s", scheduledTask.getValue());
        continue;
      }
      runnable.run();
    }
  } finally {
    if (!scheduledTasks.isEmpty()) {
      ensureIntentScheduledForSoonestTask();
    }
  }
}
 
Example #3
Source File: ProtoValidator.java    From android-chromium with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Constructs a message info.
 *
 * @param messageAccessor descriptor for the protocol buffer
 * @param fields information about the fields
 */
public MessageInfo(Accessor messageAccessor, FieldInfo... fields) {
  // Track which fields in the message descriptor have not yet been covered by a FieldInfo.
  // We'll use this to verify that we get a FieldInfo for every field.
  Set<String> unusedDescriptors = new HashSet<String>();
  unusedDescriptors.addAll(messageAccessor.getAllFieldNames());

  this.messageAccessor = messageAccessor;
  for (FieldInfo info : fields) {
    // Lookup the field given the name in the FieldInfo.
    boolean removed = TypedUtil.remove(unusedDescriptors, info.getFieldDescriptor().getName());
    Preconditions.checkState(removed, "Bad field: %s", info.getFieldDescriptor().getName());

    // Add the field info to the number -> info map.
    fieldInfo.add(info);

    if (info.getPresence() == Presence.REQUIRED) {
      ++numRequiredFields;
    }
  }
  Preconditions.checkState(unusedDescriptors.isEmpty(), "Not all fields specified in %s: %s",
      messageAccessor, unusedDescriptors);
}
 
Example #4
Source File: InvalidationTestService.java    From android-chromium with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
protected void create(Request request, Response.Builder response) {
  synchronized (LOCK) {
    validateRequest(request, Action.CREATE, Parameter.ACTION, Parameter.CLIENT,
        Parameter.CLIENT_TYPE, Parameter.ACCOUNT, Parameter.AUTH_TYPE, Parameter.INTENT);
    logger.info("Creating client %s:%s", request.getClientKey(), clientMap.keySet());
    if (!TypedUtil.containsKey(clientMap, request.getClientKey())) {
      // If no client exists with this key, create one.
      clientMap.put(
          request.getClientKey(), new ClientState(request.getAccount(), request.getAuthType(),
              request.getIntent()));
    } else {
      // Otherwise, verify that the existing client has the same account / auth type / intent.
      ClientState existingState = TypedUtil.mapGet(clientMap, request.getClientKey());
      Preconditions.checkState(request.getAccount().equals(existingState.account));
      Preconditions.checkState(request.getAuthType().equals(existingState.authType));
    }
    response.setStatus(Response.Status.SUCCESS);
  }
}
 
Example #5
Source File: PersistenceUtils.java    From android-chromium with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Deserializes a Ticl state blob. Returns either the parsed state or {@code null}
 * if it could not be parsed.
 */
public static PersistentTiclState deserializeState(Logger logger, byte[] stateBlobBytes,
    DigestFunction digestFn) {
  PersistentStateBlob stateBlob;
  try {
    // Try parsing the envelope protocol buffer.
    stateBlob = PersistentStateBlob.parseFrom(stateBlobBytes);
  } catch (InvalidProtocolBufferException exception) {
    logger.severe("Failed deserializing Ticl state: %s", exception.getMessage());
    return null;
  }

  // Check the mac in the envelope against the recomputed mac from the state.
  PersistentTiclState ticlState = stateBlob.getTiclState();
  ByteString mac = generateMac(ticlState, digestFn);
  if (!TypedUtil.<ByteString>equals(mac, stateBlob.getAuthenticationCode())) {
    logger.warning("Ticl state failed MAC check: computed %s vs %s", mac,
        stateBlob.getAuthenticationCode());
    return null;
  }
  return ticlState;
}
 
Example #6
Source File: MemoryStorageImpl.java    From android-chromium with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void readKey(final String key, final Callback<SimplePair<Status, byte[]>> done) {
  scheduler.schedule(Scheduler.NO_DELAY,
      new NamedRunnable("MemoryStorage.readKey") {
    @Override
    public void run() {
      byte[] value = TypedUtil.mapGet(ticlPersistentState, key);
      final SimplePair<Status, byte[]> result;
      if (value != null) {
        result = SimplePair.of(Status.newInstance(Status.Code.SUCCESS, ""), value);
      } else {
        String error = "No value present in map for " + key;
        result = SimplePair.of(Status.newInstance(Status.Code.PERMANENT_FAILURE, error), null);
      }
      done.accept(result);
    }
  });
}
 
Example #7
Source File: MemoryStorageImpl.java    From 365browser with Apache License 2.0 6 votes vote down vote up
@Override
public void readKey(final String key, final Callback<SimplePair<Status, byte[]>> done) {
  scheduler.schedule(Scheduler.NO_DELAY,
      new NamedRunnable("MemoryStorage.readKey") {
    @Override
    public void run() {
      byte[] value = TypedUtil.mapGet(ticlPersistentState, key);
      final SimplePair<Status, byte[]> result;
      if (value != null) {
        result = SimplePair.of(Status.newInstance(Status.Code.SUCCESS, ""), value);
      } else {
        String error = "No value present in map for " + key;
        result = SimplePair.of(Status.newInstance(Status.Code.PERMANENT_FAILURE, error), null);
      }
      done.accept(result);
    }
  });
}
 
Example #8
Source File: AndroidInvalidationService.java    From android-chromium with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * 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 #9
Source File: AndroidListenerState.java    From 365browser with Apache License 2.0 6 votes vote down vote up
/**
 * Overridden for tests which compare listener states to verify that they have been correctly
 * (un)marshalled. We implement equals rather than exposing private data.
 */
@Override
public boolean equals(Object object) {
  if (this == object) {
    return true;
  }

  if (!(object instanceof AndroidListenerState)) {
    return false;
  }

  AndroidListenerState that = (AndroidListenerState) object;

  return (this.isDirty == that.isDirty)
      && (this.requestCodeSeqNum == that.requestCodeSeqNum)
      && (this.desiredRegistrations.size() == that.desiredRegistrations.size())
      && (this.desiredRegistrations.containsAll(that.desiredRegistrations))
      && TypedUtil.<Bytes>equals(this.clientId, that.clientId)
      && equals(this.delayGenerators, that.delayGenerators)
      && equals(this.registrationRetries, that.registrationRetries);
}
 
Example #10
Source File: PersistenceUtils.java    From 365browser with Apache License 2.0 6 votes vote down vote up
/**
 * Deserializes a Ticl state blob. Returns either the parsed state or {@code null}
 * if it could not be parsed.
 */
public static PersistentTiclState deserializeState(Logger logger, byte[] stateBlobBytes,
    DigestFunction digestFn) {
  PersistentStateBlob stateBlob;
  try {
    // Try parsing the envelope protocol buffer.
    stateBlob = PersistentStateBlob.parseFrom(stateBlobBytes);
  } catch (ValidationException exception) {
    logger.severe("Failed deserializing Ticl state: %s", exception.getMessage());
    return null;
  }

  // Check the mac in the envelope against the recomputed mac from the state.
  PersistentTiclState ticlState = stateBlob.getTiclState();
  Bytes mac = generateMac(ticlState, digestFn);
  if (!TypedUtil.<Bytes>equals(mac, stateBlob.getAuthenticationCode())) {
    logger.warning("Ticl state failed MAC check: computed %s vs %s", mac,
        stateBlob.getAuthenticationCode());
    return null;
  }
  return ticlState;
}
 
Example #11
Source File: AndroidInvalidationService.java    From android-chromium with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * 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 #12
Source File: MemoryStorageImpl.java    From android-chromium with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void readKey(final String key, final Callback<SimplePair<Status, byte[]>> done) {
  scheduler.schedule(Scheduler.NO_DELAY,
      new NamedRunnable("MemoryStorage.readKey") {
    @Override
    public void run() {
      byte[] value = TypedUtil.mapGet(ticlPersistentState, key);
      final SimplePair<Status, byte[]> result;
      if (value != null) {
        result = SimplePair.of(Status.newInstance(Status.Code.SUCCESS, ""), value);
      } else {
        String error = "No value present in map for " + key;
        result = SimplePair.of(Status.newInstance(Status.Code.PERMANENT_FAILURE, error), null);
      }
      done.accept(result);
    }
  });
}
 
Example #13
Source File: ProtoValidator.java    From android-chromium with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Constructs a message info.
 *
 * @param messageAccessor descriptor for the protocol buffer
 * @param fields information about the fields
 */
public MessageInfo(Accessor messageAccessor, FieldInfo... fields) {
  // Track which fields in the message descriptor have not yet been covered by a FieldInfo.
  // We'll use this to verify that we get a FieldInfo for every field.
  Set<String> unusedDescriptors = new HashSet<String>();
  unusedDescriptors.addAll(messageAccessor.getAllFieldNames());

  this.messageAccessor = messageAccessor;
  for (FieldInfo info : fields) {
    // Lookup the field given the name in the FieldInfo.
    boolean removed = TypedUtil.remove(unusedDescriptors, info.getFieldDescriptor().getName());
    Preconditions.checkState(removed, "Bad field: %s", info.getFieldDescriptor().getName());

    // Add the field info to the number -> info map.
    fieldInfo.add(info);

    if (info.getPresence() == Presence.REQUIRED) {
      ++numRequiredFields;
    }
  }
  Preconditions.checkState(unusedDescriptors.isEmpty(), "Not all fields specified in %s: %s",
      messageAccessor, unusedDescriptors);
}
 
Example #14
Source File: InvalidationTestService.java    From android-chromium with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
protected void create(Request request, Response.Builder response) {
  synchronized (LOCK) {
    validateRequest(request, Action.CREATE, Parameter.ACTION, Parameter.CLIENT,
        Parameter.CLIENT_TYPE, Parameter.ACCOUNT, Parameter.AUTH_TYPE, Parameter.INTENT);
    logger.info("Creating client %s:%s", request.getClientKey(), clientMap.keySet());
    if (!TypedUtil.containsKey(clientMap, request.getClientKey())) {
      // If no client exists with this key, create one.
      clientMap.put(
          request.getClientKey(), new ClientState(request.getAccount(), request.getAuthType(),
              request.getIntent()));
    } else {
      // Otherwise, verify that the existing client has the same account / auth type / intent.
      ClientState existingState = TypedUtil.mapGet(clientMap, request.getClientKey());
      Preconditions.checkState(request.getAccount().equals(existingState.account));
      Preconditions.checkState(request.getAuthType().equals(existingState.authType));
    }
    response.setStatus(Response.Status.SUCCESS);
  }
}
 
Example #15
Source File: AndroidInternalScheduler.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Handles an event intent created in {@link #schedule} by running that event, along with any
 * other events whose time has come.
 */
void handleSchedulerEvent(AndroidSchedulerEvent event) {
  Runnable recurringTaskRunnable = TypedUtil.mapGet(registeredTasks, event.getEventName());
  if (recurringTaskRunnable == null) {
    throw new NullPointerException("No task registered for " + event.getEventName());
  }
  if (ticlId != event.getTiclId()) {
    logger.warning("Ignoring event with wrong ticl id (not %s): %s", ticlId, event);
    return;
  }
  recurringTaskRunnable.run();
  handleImplicitSchedulerEvent();
}
 
Example #16
Source File: MemoryStorageImpl.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void deleteKey(final String key, final Callback<Boolean> done) {
  scheduler.schedule(Scheduler.NO_DELAY,
      new NamedRunnable("MemoryStorage.deleteKey") {
    @Override
    public void run() {
      TypedUtil.remove(ticlPersistentState, key);
      done.accept(true);
    }
  });
}
 
Example #17
Source File: TiclStateManager.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/** Returns whether the digest in {@code state} is correct. */
private static boolean isDigestValid(AndroidTiclStateWithDigest state, Logger logger) {
  Sha1DigestFunction digester = new Sha1DigestFunction();
  digester.update(state.getState().toByteArray());
  byte[] computedDigest = digester.getDigest();
  if (!TypedUtil.<Bytes>equals(new Bytes(computedDigest), state.getDigest())) {
    logger.warning("Android TICL state digest mismatch; computed %s for %s",
        computedDigest, state);
    return false;
  }
  return true;
}
 
Example #18
Source File: MemoryStorageImpl.java    From 365browser with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteKey(final String key, final Callback<Boolean> done) {
  scheduler.schedule(Scheduler.NO_DELAY,
      new NamedRunnable("MemoryStorage.deleteKey") {
    @Override
    public void run() {
      TypedUtil.remove(ticlPersistentState, key);
      done.accept(true);
    }
  });
}
 
Example #19
Source File: InvalidationClientCore.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Returns whether the token in the header of {@code parsedMessage} matches either the
 * client token or nonce of this Ticl (depending on which is non-{@code null}).
 */
private boolean validateToken(ParsedMessage parsedMessage) {
  if (clientToken != null) {
    // Client token case.
    if (!TypedUtil.<Bytes>equals(clientToken, parsedMessage.header.token)) {
      logger.info("Incoming message has bad token: server = %s, client = %s",
          parsedMessage.header.token, clientToken);
      statistics.recordError(ClientErrorType.TOKEN_MISMATCH);
      return false;
    }
    return true;
  } else if (nonce != null) {
    // Nonce case.
    if (!TypedUtil.<Bytes>equals(nonce, parsedMessage.header.token)) {
      statistics.recordError(ClientErrorType.NONCE_MISMATCH);
      logger.info("Rejecting server message with mismatched nonce: Client = %s, Server = %s",
          nonce, parsedMessage.header.token);
      return false;
    } else {
      logger.info("Accepting server message with matching nonce: %s", nonce);
      return true;
    }
  }
  // Neither token nor nonce; ignore message.
  logger.warning("Neither token nor nonce was set in validateToken: %s, %s", clientToken, nonce);
  return false;
}
 
Example #20
Source File: AndroidInternalScheduler.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Handles an event intent created in {@link #schedule} by running the corresponding recurring
 * task.
 * <p>
 * REQUIRES: a recurring task with the name in the intent be present in {@link #registeredTasks}.
 */
void handleSchedulerEvent(AndroidSchedulerEvent event) {
  Runnable recurringTaskRunnable = Preconditions.checkNotNull(
      TypedUtil.mapGet(registeredTasks, event.getEventName()),
      "No task registered for %s", event.getEventName());
  if (ticlId != event.getTiclId()) {
    logger.warning("Ignoring event with wrong ticl id (not %s): %s", ticlId, event);
    return;
  }
  recurringTaskRunnable.run();
}
 
Example #21
Source File: Statistics.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Looks for an enum value with the given {@code fieldName} in {@code valueOfMap} and increments
 * the corresponding entry in {@code counts} by {@code counterValue}. Call to update statistics
 * for a single performance counter.
 */
private static <Key extends Enum<Key>> void incrementPerformanceCounterValue(Logger logger,
    Map<String, Key> valueOfMap, Map<Key, Integer> counts, String fieldName, int counterValue) {
  Key type = TypedUtil.mapGet(valueOfMap, fieldName);
  if (type != null) {
    int currentValue = TypedUtil.mapGet(counts, type);
    counts.put(type, currentValue + counterValue);
  } else {
    logger.warning("Skipping unknown enum value name %s", fieldName);
  }
}
 
Example #22
Source File: Statistics.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Given the serialized {@code performanceCounters} of the client statistics, returns a Statistics
 * object with the performance counter values from {@code performanceCounters}.
 */

public static Statistics deserializeStatistics(Logger logger,
    Collection<PropertyRecord> performanceCounters) {
  Statistics statistics = new Statistics();

  // For each counter, parse out the counter name and value.
  for (PropertyRecord performanceCounter : performanceCounters) {
    String counterName = performanceCounter.getName();
    String[] parts = counterName.split("\\.");
    if (parts.length != 2) {
      logger.warning("Perf counter name must of form: class.value, skipping: %s", counterName);
      continue;
    }
    String className = parts[0];
    String fieldName = parts[1];
    int counterValue = performanceCounter.getValue();

    // Call the relevant method in a loop (i.e., depending on the type of the class).
    if (TypedUtil.<String>equals(className, SENT_MESSAGE_TYPE_NAME)) {
      incrementPerformanceCounterValue(logger, SENT_MESSAGE_TYPE_NAME_TO_VALUE_MAP,
          statistics.sentMessageTypes, fieldName, counterValue);
    } else if (TypedUtil.<String>equals(className, INCOMING_OPERATION_TYPE_NAME)) {
      incrementPerformanceCounterValue(logger, INCOMING_OPERATION_TYPE_NAME_TO_VALUE_MAP,
          statistics.incomingOperationTypes, fieldName, counterValue);
    } else if (TypedUtil.<String>equals(className, RECEIVED_MESSAGE_TYPE_NAME)) {
      incrementPerformanceCounterValue(logger, RECEIVED_MESSAGE_TYPE_NAME_TO_VALUE_MAP,
          statistics.receivedMessageTypes, fieldName, counterValue);
    } else if (TypedUtil.<String>equals(className,  LISTENER_EVENT_TYPE_NAME)) {
      incrementPerformanceCounterValue(logger, LISTENER_EVENT_TYPE_NAME_TO_VALUE_MAP,
          statistics.listenerEventTypes, fieldName, counterValue);
    } else if (TypedUtil.<String>equals(className,  CLIENT_ERROR_TYPE_NAME)) {
      incrementPerformanceCounterValue(logger, CLIENT_ERROR_TYPE_NAME_TO_VALUE_MAP,
          statistics.clientErrorTypes, fieldName, counterValue);
    } else {
      logger.warning("Skipping unknown enum class name %s", className);
    }
  }
  return statistics;
}
 
Example #23
Source File: Statistics.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Looks for an enum value with the given {@code fieldName} in {@code valueOfMap} and increments
 * the corresponding entry in {@code counts} by {@code counterValue}. Call to update statistics
 * for a single performance counter.
 */
private static <Key extends Enum<Key>> void incrementPerformanceCounterValue(Logger logger,
    Map<String, Key> valueOfMap, Map<Key, Integer> counts, String fieldName, int counterValue) {
  Key type = TypedUtil.mapGet(valueOfMap, fieldName);
  if (type != null) {
    int currentValue = TypedUtil.mapGet(counts, type);
    counts.put(type, currentValue + counterValue);
  } else {
    logger.warning("Skipping unknown enum value name %s", fieldName);
  }
}
 
Example #24
Source File: AndroidInternalScheduler.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Handles an event intent created in {@link #schedule} by running the corresponding recurring
 * task.
 * <p>
 * REQUIRES: a recurring task with the name in the intent be present in {@link #registeredTasks}.
 */
void handleSchedulerEvent(AndroidSchedulerEvent event) {
  Runnable recurringTaskRunnable = Preconditions.checkNotNull(
      TypedUtil.mapGet(registeredTasks, event.getEventName()),
      "No task registered for %s", event.getEventName());
  if (ticlId != event.getTiclId()) {
    logger.warning("Ignoring event with wrong ticl id (not %s): %s", ticlId, event);
    return;
  }
  recurringTaskRunnable.run();
}
 
Example #25
Source File: InvalidationClientCore.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Handles a token-control message.
 * @param headerToken token in the server message
 * @param newToken the new token provided, or {@code null} if this is a destroy message.
 */
private void handleTokenChanged(ByteString headerToken, final ByteString newToken) {
  Preconditions.checkState(internalScheduler.isRunningOnThread(), "Not on internal thread");

  // The server is either supplying a new token in response to an InitializeMessage, spontaneously
  // destroying a token we hold, or spontaneously upgrading a token we hold.

  if (newToken != null) {
    // Note: headerToken cannot be null, so a null nonce or clientToken will always be non-equal.
    boolean headerTokenMatchesNonce = TypedUtil.<ByteString>equals(headerToken, nonce);
    boolean headerTokenMatchesExistingToken =
        TypedUtil.<ByteString>equals(headerToken, clientToken);
    boolean shouldAcceptToken = headerTokenMatchesNonce || headerTokenMatchesExistingToken;
    if (!shouldAcceptToken) {
      logger.info("Ignoring new token; %s does not match nonce = %s or existing token = %s",
          newToken, nonce, clientToken);
      return;
    }
    logger.info("New token being assigned at client: %s, Old = %s",
        CommonProtoStrings2.toLazyCompactString(newToken),
        CommonProtoStrings2.toLazyCompactString(clientToken));

    // Start the regular heartbeats now.
    heartbeatTask.ensureScheduled("Heartbeat-after-new-token");
    setNonce(null);
    setClientToken(newToken);
    persistentWriteTask.ensureScheduled("Write-after-new-token");
  } else {
    logger.info("Destroying existing token: %s",
        CommonProtoStrings2.toLazyCompactString(clientToken));
    acquireToken("Destroy");
  }
}
 
Example #26
Source File: InvalidationClientCore.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Returns whether the token in the header of {@code parsedMessage} matches either the
 * client token or nonce of this Ticl (depending on which is non-{@code null}).
 */
private boolean validateToken(ParsedMessage parsedMessage) {
  if (clientToken != null) {
    // Client token case.
    if (!TypedUtil.<ByteString>equals(clientToken, parsedMessage.header.token)) {
      logger.info("Incoming message has bad token: server = %s, client = %s",
          CommonProtoStrings2.toLazyCompactString(parsedMessage.header.token),
          CommonProtoStrings2.toLazyCompactString(clientToken));
      statistics.recordError(ClientErrorType.TOKEN_MISMATCH);
      return false;
    }
    return true;
  } else if (nonce != null) {
    // Nonce case.
    if (!TypedUtil.<ByteString>equals(nonce, parsedMessage.header.token)) {
      statistics.recordError(ClientErrorType.NONCE_MISMATCH);
      logger.info("Rejecting server message with mismatched nonce: Client = %s, Server = %s",
          CommonProtoStrings2.toLazyCompactString(nonce),
          CommonProtoStrings2.toLazyCompactString(parsedMessage.header.token));
      return false;
    } else {
      logger.info("Accepting server message with matching nonce: %s",
          CommonProtoStrings2.toLazyCompactString(nonce));
      return true;
    }
  }
  // Neither token nor nonce; ignore message.
  logger.warning("Neither token nor nonce was set in validateToken: %s, %s", clientToken, nonce);
  return false;
}
 
Example #27
Source File: Statistics.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Given the serialized {@code performanceCounters} of the client statistics, returns a Statistics
 * object with the performance counter values from {@code performanceCounters}.
 */

public static Statistics deserializeStatistics(Logger logger,
    Collection<PropertyRecord> performanceCounters) {
  Statistics statistics = new Statistics();

  // For each counter, parse out the counter name and value.
  for (PropertyRecord performanceCounter : performanceCounters) {
    String counterName = performanceCounter.getName();
    String[] parts = counterName.split("\\.");
    if (parts.length != 2) {
      logger.warning("Perf counter name must of form: class.value, skipping: %s", counterName);
      continue;
    }
    String className = parts[0];
    String fieldName = parts[1];
    int counterValue = performanceCounter.getValue();

    // Call the relevant method in a loop (i.e., depending on the type of the class).
    if (TypedUtil.<String>equals(className, SENT_MESSAGE_TYPE_NAME)) {
      incrementPerformanceCounterValue(logger, SENT_MESSAGE_TYPE_NAME_TO_VALUE_MAP,
          statistics.sentMessageTypes, fieldName, counterValue);
    } else if (TypedUtil.<String>equals(className, INCOMING_OPERATION_TYPE_NAME)) {
      incrementPerformanceCounterValue(logger, INCOMING_OPERATION_TYPE_NAME_TO_VALUE_MAP,
          statistics.incomingOperationTypes, fieldName, counterValue);
    } else if (TypedUtil.<String>equals(className, RECEIVED_MESSAGE_TYPE_NAME)) {
      incrementPerformanceCounterValue(logger, RECEIVED_MESSAGE_TYPE_NAME_TO_VALUE_MAP,
          statistics.receivedMessageTypes, fieldName, counterValue);
    } else if (TypedUtil.<String>equals(className,  LISTENER_EVENT_TYPE_NAME)) {
      incrementPerformanceCounterValue(logger, LISTENER_EVENT_TYPE_NAME_TO_VALUE_MAP,
          statistics.listenerEventTypes, fieldName, counterValue);
    } else if (TypedUtil.<String>equals(className,  CLIENT_ERROR_TYPE_NAME)) {
      incrementPerformanceCounterValue(logger, CLIENT_ERROR_TYPE_NAME_TO_VALUE_MAP,
          statistics.clientErrorTypes, fieldName, counterValue);
    } else {
      logger.warning("Skipping unknown enum class name %s", className);
    }
  }
  return statistics;
}
 
Example #28
Source File: Statistics.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Given the serialized {@code performanceCounters} of the client statistics, returns a Statistics
 * object with the performance counter values from {@code performanceCounters}.
 */

public static Statistics deserializeStatistics(Logger logger,
    Collection<PropertyRecord> performanceCounters) {
  Statistics statistics = new Statistics();

  // For each counter, parse out the counter name and value.
  for (PropertyRecord performanceCounter : performanceCounters) {
    String counterName = performanceCounter.getName();
    String[] parts = counterName.split("\\.");
    if (parts.length != 2) {
      logger.warning("Perf counter name must of form: class.value, skipping: %s", counterName);
      continue;
    }
    String className = parts[0];
    String fieldName = parts[1];
    int counterValue = performanceCounter.getValue();

    // Call the relevant method in a loop (i.e., depending on the type of the class).
    if (TypedUtil.<String>equals(className, SENT_MESSAGE_TYPE_NAME)) {
      incrementPerformanceCounterValue(logger, SENT_MESSAGE_TYPE_NAME_TO_VALUE_MAP,
          statistics.sentMessageTypes, fieldName, counterValue);
    } else if (TypedUtil.<String>equals(className, INCOMING_OPERATION_TYPE_NAME)) {
      incrementPerformanceCounterValue(logger, INCOMING_OPERATION_TYPE_NAME_TO_VALUE_MAP,
          statistics.incomingOperationTypes, fieldName, counterValue);
    } else if (TypedUtil.<String>equals(className, RECEIVED_MESSAGE_TYPE_NAME)) {
      incrementPerformanceCounterValue(logger, RECEIVED_MESSAGE_TYPE_NAME_TO_VALUE_MAP,
          statistics.receivedMessageTypes, fieldName, counterValue);
    } else if (TypedUtil.<String>equals(className,  LISTENER_EVENT_TYPE_NAME)) {
      incrementPerformanceCounterValue(logger, LISTENER_EVENT_TYPE_NAME_TO_VALUE_MAP,
          statistics.listenerEventTypes, fieldName, counterValue);
    } else if (TypedUtil.<String>equals(className,  CLIENT_ERROR_TYPE_NAME)) {
      incrementPerformanceCounterValue(logger, CLIENT_ERROR_TYPE_NAME_TO_VALUE_MAP,
          statistics.clientErrorTypes, fieldName, counterValue);
    } else {
      logger.warning("Skipping unknown enum class name %s", className);
    }
  }
  return statistics;
}
 
Example #29
Source File: MemoryStorageImpl.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void deleteKey(final String key, final Callback<Boolean> done) {
  scheduler.schedule(Scheduler.NO_DELAY,
      new NamedRunnable("MemoryStorage.deleteKey") {
    @Override
    public void run() {
      TypedUtil.remove(ticlPersistentState, key);
      done.accept(true);
    }
  });
}
 
Example #30
Source File: InvalidationClientCore.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Handles a token-control message.
 * @param headerToken token in the server message
 * @param newToken the new token provided, or {@code null} if this is a destroy message.
 */
private void handleTokenChanged(Bytes headerToken, final Bytes newToken) {
  Preconditions.checkState(internalScheduler.isRunningOnThread(), "Not on internal thread");

  // The server is either supplying a new token in response to an InitializeMessage, spontaneously
  // destroying a token we hold, or spontaneously upgrading a token we hold.

  if (newToken != null) {
    // Note: headerToken cannot be null, so a null nonce or clientToken will always be non-equal.
    boolean headerTokenMatchesNonce = TypedUtil.<Bytes>equals(headerToken, nonce);
    boolean headerTokenMatchesExistingToken = TypedUtil.<Bytes>equals(headerToken, clientToken);
    boolean shouldAcceptToken = headerTokenMatchesNonce || headerTokenMatchesExistingToken;
    if (!shouldAcceptToken) {
      logger.info("Ignoring new token; %s does not match nonce = %s or existing token = %s",
          newToken, nonce, clientToken);
      return;
    }
    logger.info("New token being assigned at client: %s, Old = %s", newToken, clientToken);

    // Start the regular heartbeats now.
    heartbeatTask.ensureScheduled("Heartbeat-after-new-token");
    setNonce(null);
    setClientToken(newToken);
    persistentWriteTask.ensureScheduled("Write-after-new-token");
  } else {
    logger.info("Destroying existing token: %s", clientToken);
    acquireToken("Destroy");
  }
}