com.google.firebase.database.DatabaseException Java Examples

The following examples show how to use com.google.firebase.database.DatabaseException. 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: CustomClassMapper.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
private static Long convertLong(Object obj) {
  if (obj instanceof Integer) {
    return ((Integer) obj).longValue();
  } else if (obj instanceof Long) {
    return (Long) obj;
  } else if (obj instanceof Double) {
    Double value = (Double) obj;
    if (value >= Long.MIN_VALUE && value <= Long.MAX_VALUE) {
      return value.longValue();
    } else {
      throw new DatabaseException(
          "Numeric value out of 64-bit long range: "
              + value
              + ". Did you mean to use a double instead of a long?");
    }
  } else {
    throw new DatabaseException(
        "Failed to convert a value of type " + obj.getClass().getName() + " to long");
  }
}
 
Example #2
Source File: CustomClassMapper.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Converts a standard library Java representation of JSON data to an object of the class provided
 * through the GenericTypeIndicator
 *
 * @param object The representation of the JSON data
 * @param typeIndicator The indicator providing class of the object to convert to
 * @return The POJO object.
 */
public static <T> T convertToCustomClass(Object object, GenericTypeIndicator<T> typeIndicator) {
  Class<?> clazz = typeIndicator.getClass();
  Type genericTypeIndicatorType = clazz.getGenericSuperclass();
  if (genericTypeIndicatorType instanceof ParameterizedType) {
    ParameterizedType parameterizedType = (ParameterizedType) genericTypeIndicatorType;
    if (!parameterizedType.getRawType().equals(GenericTypeIndicator.class)) {
      throw new DatabaseException(
          "Not a direct subclass of GenericTypeIndicator: " + genericTypeIndicatorType);
    }
    // We are guaranteed to have exactly one type parameter
    Type type = parameterizedType.getActualTypeArguments()[0];
    return deserializeToType(object, type);
  } else {
    throw new DatabaseException(
        "Not a direct subclass of GenericTypeIndicator: " + genericTypeIndicatorType);
  }
}
 
Example #3
Source File: Utilities.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Extracts the path string from the original URL without changing the encoding (unlike
 * Uri.getPath()).
 */
private static String extractPathString(String originalUrl) {
  int schemeOffset = originalUrl.indexOf("//");
  if (schemeOffset == -1) {
    throw new DatabaseException("Firebase Database URL is missing URL scheme");
  }

  String urlWithoutScheme = originalUrl.substring(schemeOffset + 2);
  int pathOffset = urlWithoutScheme.indexOf("/");
  if (pathOffset != -1) {
    int queryOffset = urlWithoutScheme.indexOf("?");
    if (queryOffset != -1) {
      return urlWithoutScheme.substring(pathOffset + 1, queryOffset);
    } else {
      return urlWithoutScheme.substring(pathOffset + 1);
    }
  } else {
    return "";
  }
}
 
Example #4
Source File: CustomClassMapper.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static <T> T deserializeToEnum(Object object, Class<T> clazz) {
  if (object instanceof String) {
    String value = (String) object;
    // We cast to Class without generics here since we can't prove the bound
    // T extends Enum<T> statically
    try {
      return (T) Enum.valueOf((Class) clazz, value);
    } catch (IllegalArgumentException e) {
      throw new DatabaseException(
          "Could not find enum value of " + clazz.getName() + " for value \"" + value + "\"");
    }
  } else {
    throw new DatabaseException(
        "Expected a String while deserializing to enum "
            + clazz
            + " but got a "
            + object.getClass());
  }
}
 
Example #5
Source File: CustomClassMapper.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static <T> T deserializeToEnum(Object object, Class<T> clazz) {
  if (object instanceof String) {
    String value = (String) object;
    // We cast to Class without generics here since we can't prove the bound
    // T extends Enum<T> statically
    try {
      return (T) Enum.valueOf((Class) clazz, value);
    } catch (IllegalArgumentException e) {
      throw new DatabaseException(
          "Could not find enum value of " + clazz.getName() + " for value \"" + value + "\"");
    }
  } else {
    throw new DatabaseException(
        "Expected a String while deserializing to enum "
            + clazz
            + " but got a "
            + object.getClass());
  }
}
 
Example #6
Source File: ValidationPath.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
private void checkValid() throws DatabaseException {
  if (byteLength > MAX_PATH_LENGTH_BYTES) {
    throw new DatabaseException(
        "Data has a key path longer than "
            + MAX_PATH_LENGTH_BYTES
            + " bytes ("
            + byteLength
            + ").");
  }
  if (parts.size() > MAX_PATH_DEPTH) {
    throw new DatabaseException(
        "Path specified exceeds the maximum depth that can be written ("
            + MAX_PATH_DEPTH
            + ") or object contains a cycle "
            + toErrorString());
  }
}
 
Example #7
Source File: DefaultRunLoop.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
public static String messageForException(Throwable t) {
  if (t instanceof OutOfMemoryError) {
    return "Firebase Database encountered an OutOfMemoryError. You may need to reduce the"
        + " amount of data you are syncing to the client (e.g. by using queries or syncing"
        + " a deeper path). See "
        + "https://firebase.google"
        + ".com/docs/database/ios/structure-data#best_practices_for_data_structure"
        + " and "
        + "https://firebase.google.com/docs/database/android/retrieve-data#filtering_data";
  } else if (t instanceof DatabaseException) {
    // Exception should be self-explanatory and they shouldn't contact support.
    return "";
  } else {
    return "Uncaught exception in Firebase Database runloop ("
        + FirebaseDatabase.getSdkVersion()
        + "). Please report to [email protected]";
  }
}
 
Example #8
Source File: ValidationPath.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
private void checkValid() throws DatabaseException {
  if (byteLength > MAX_PATH_LENGTH_BYTES) {
    throw new DatabaseException(
        "Data has a key path longer than "
            + MAX_PATH_LENGTH_BYTES
            + " bytes ("
            + byteLength
            + ").");
  }
  if (parts.size() > MAX_PATH_DEPTH) {
    throw new DatabaseException(
        "Path specified exceeds the maximum depth that can be written ("
            + MAX_PATH_DEPTH
            + ") or object contains a cycle "
            + toErrorString());
  }
}
 
Example #9
Source File: InfoTestIT.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testInfoNodeSetValueWithPriority() {
  DatabaseReference ref = FirebaseDatabase.getInstance().getReference(".info");
  try {
    ref.setValueAsync("hi", 5);
    fail("Should not be allowed");
  } catch (DatabaseException expected) {
    // No-op, expected
  }
}
 
Example #10
Source File: ValidationPath.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
private ValidationPath(Path path) throws DatabaseException {
  for (ChildKey key : path) {
    parts.add(key.asString());
  }

  // Initialize to number of '/' chars needed in path.
  byteLength = Math.max(1, parts.size());
  for (int i = 0; i < parts.size(); i++) {
    byteLength += utf8Bytes(parts.get(i));
  }
  checkValid();
}
 
Example #11
Source File: InfoTestIT.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testInfoNodeSetPriority() {
  DatabaseReference ref = FirebaseDatabase.getInstance().getReference(".info");
  try {
    ref.setPriorityAsync("hi");
    fail("Should not be allowed");
  } catch (DatabaseException expected) {
    // No-op, expected
  }
}
 
Example #12
Source File: CustomClassMapper.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
private static Boolean convertBoolean(Object obj) {
  if (obj instanceof Boolean) {
    return (Boolean) obj;
  } else {
    throw new DatabaseException(
        "Failed to convert value of type " + obj.getClass().getName() + " to boolean");
  }
}
 
Example #13
Source File: InfoTestIT.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testInfoNodeSetValue() {
  DatabaseReference ref = FirebaseDatabase.getInstance().getReference(".info");
  try {
    ref.setValueAsync("hi");
    fail("Should not be allowed");
  } catch (DatabaseException expected) {
    // No-op, expected
  }
}
 
Example #14
Source File: FirebaseDatabaseTestIT.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testDatabaseUrlWithPathInGetInstance() {
  FirebaseApp app = appWithoutDbUrl("dbUrlWithPathInGetInstance");
  try {      
    FirebaseDatabase.getInstance(app, IntegrationTestUtils.getDatabaseUrl() 
        + "/paths/are/not/allowed");
    fail("no error thrown for DB URL with path");
  } catch (DatabaseException expected) { // ignore
  }
}
 
Example #15
Source File: Repo.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
private void updateInfo(ChildKey childKey, Object value) {
  if (childKey.equals(Constants.DOT_INFO_SERVERTIME_OFFSET)) {
    serverClock.setOffset((Long) value);
  }

  Path path = new Path(Constants.DOT_INFO, childKey);
  try {
    Node node = NodeUtilities.NodeFromJSON(value);
    infoData.update(path, node);
    List<? extends Event> events = this.infoSyncTree.applyServerOverwrite(path, node);
    this.postEvents(events);
  } catch (DatabaseException e) {
    logger.error("Failed to parse info update", e);
  }
}
 
Example #16
Source File: Path.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
public static Path getRelative(Path from, Path to) {
  ChildKey outerFront = from.getFront();
  ChildKey innerFront = to.getFront();
  if (outerFront == null) {
    return to;
  } else if (outerFront.equals(innerFront)) {
    return getRelative(from.popFront(), to.popFront());
  } else {
    throw new DatabaseException("INTERNAL ERROR: " + to + " is not contained in " + from);
  }
}
 
Example #17
Source File: ValidationPath.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
private void push(String child) throws DatabaseException {
  // Count the '/'
  if (parts.size() > 0) {
    byteLength += 1;
  }
  parts.add(child);
  byteLength += utf8Bytes(child);
  checkValid();
}
 
Example #18
Source File: CustomClassMapper.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
private static Integer convertInteger(Object obj) {
  if (obj instanceof Integer) {
    return (Integer) obj;
  } else if (obj instanceof Long || obj instanceof Double) {
    double value = ((Number) obj).doubleValue();
    if (value >= Integer.MIN_VALUE && value <= Integer.MAX_VALUE) {
      return ((Number) obj).intValue();
    } else {
      throw new DatabaseException(
          "Numeric value out of 32-bit integer range: "
              + value
              + ". Did you mean to use a long or double instead of an int?");
    }
  } else {
    throw new DatabaseException(
        "Failed to convert a value of type " + obj.getClass().getName() + " to int");
  }
}
 
Example #19
Source File: CustomClassMapper.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static <T> T deserializeToClass(Object obj, Class<T> clazz) {
  if (obj == null) {
    return null;
  } else if (clazz.isPrimitive()
      || Number.class.isAssignableFrom(clazz)
      || Boolean.class.isAssignableFrom(clazz)
      || Character.class.isAssignableFrom(clazz)) {
    return deserializeToPrimitive(obj, clazz);
  } else if (String.class.isAssignableFrom(clazz)) {
    return (T) convertString(obj);
  } else if (clazz.isArray()) {
    throw new DatabaseException(
        "Converting to Arrays is not supported, please use Lists instead");
  } else if (clazz.getTypeParameters().length > 0) {
    throw new DatabaseException(
        "Class "
            + clazz.getName()
            + " has generic type "
            + "parameters, please use GenericTypeIndicator instead");
  } else if (clazz.equals(Object.class)) {
    return (T) obj;
  } else if (clazz.isEnum()) {
    return deserializeToEnum(obj, clazz);
  } else {
    return convertBean(obj, clazz);
  }
}
 
Example #20
Source File: ValidationTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testInvalidUpdate() {
  Map[] invalidUpdates = new Map[]{
      ImmutableMap.of(".sv", "foo"),
      ImmutableMap.of(".value", "foo"),
      ImmutableMap.of(".priority", ImmutableMap.of("a", "b")),
      ImmutableMap.of("foo", "value", "foo/bar", "value"),
      ImmutableMap.of("foo", Double.POSITIVE_INFINITY),
      ImmutableMap.of("foo", Double.NEGATIVE_INFINITY),
      ImmutableMap.of("foo", Double.NaN),
  };
  Path path = new Path("path");
  for (Map map : invalidUpdates) {
    try {
      Validation.parseAndValidateUpdate(path, map);
      fail("No error thrown for invalid update: " + map);
    } catch (DatabaseException expected) {
      // expected
    }
  }
}
 
Example #21
Source File: ValidationTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testWritableKey() {
  String[] invalidKeys = new String[]{
      null, "", ".info", ".foo", "foo#", "foo$", "foo[", "foo]"
  };
  for (String key : invalidKeys) {
    try {
      Validation.validateWritableKey(key);
      fail("No error thrown for non-writable key: " + key);
    } catch (DatabaseException expected) {
      // expected
    }
  }
}
 
Example #22
Source File: DataTestIT.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void invalidDoubleValues()
    throws DatabaseException, TestFailure, TimeoutException, InterruptedException {
  DatabaseReference node = IntegrationTestUtils.getRandomNode(masterApp);
  Object[] invalidValues =
      new Object[] {
          Double.NEGATIVE_INFINITY,
          Double.POSITIVE_INFINITY,
          Double.NaN,
          Float.NEGATIVE_INFINITY,
          Float.POSITIVE_INFINITY,
          Float.NaN
      };
  for (Object invalidValue : invalidValues) {
    try {
      node.setValueAsync(invalidValue);
      fail("NaN or Inf are not allowed as values.");
    } catch (DatabaseException expected) {
      assertEquals("Invalid value: Value cannot be NaN, Inf or -Inf.", expected.getMessage());
    }
  }
}
 
Example #23
Source File: ValidationTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testInvalidRootPathString() {
  String[] invalidPaths = new String[]{
      ".info/foo.", ".info/foo#", ".info/foo$", ".info/foo[", ".info/foo]"
  };
  for (String path : invalidPaths) {
    try {
      Validation.validateRootPathString(path);
      fail("No error thrown for invalid path: " + path);
    } catch (DatabaseException expected) {
      // expected
    }
  }
}
 
Example #24
Source File: Validation.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
public static void validateRootPathString(String pathString) throws DatabaseException {
  if (pathString.startsWith(".info")) {
    validatePathString(pathString.substring(5));
  } else if (pathString.startsWith("/.info")) {
    validatePathString(pathString.substring(6));
  } else {
    validatePathString(pathString);
  }
}
 
Example #25
Source File: DataTestIT.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testAsciiControlCharacters() throws DatabaseException {
  DatabaseReference node = IntegrationTestUtils.getRandomNode(masterApp);
  // Test all controls characters PLUS 0x7F (127).
  for (int i = 0; i <= 32; i++) {
    String ch = new String(Character.toChars(i < 32 ? i : 127));
    Map<String, Object> obj = TestHelpers.buildObjFromPath(new Path(ch), "test_value");
    try {
      node.setValueAsync(obj);
      fail("Ascii control character should not be allowed in path.");
    } catch (DatabaseException e) {
      // expected
    }
  }
}
 
Example #26
Source File: PriorityUtilities.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
public static Node parsePriority(Path nodePath, Object value) {
  Node priority = NodeUtilities.NodeFromJSON(value);
  if (priority instanceof LongNode) {
    priority =
        new DoubleNode(
            Double.valueOf((Long) priority.getValue()), PriorityUtilities.NullPriority());
  }
  if (!isValidPriority(priority)) {
    throw new DatabaseException(
        (nodePath != null ? "Path '" + nodePath + "'" : "Node")
            + " contains invalid priority: Must be a string, double, ServerValue, or null");
  }
  return priority;
}
 
Example #27
Source File: ParseUrlTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testUrlParsingSslDetection() throws DatabaseException {
  // Hosts with custom ports are considered non-secure
  ParsedUrl parsed = Utilities.parseUrl("http://gsoltis.fblocal.com:9000");
  assertFalse(parsed.repoInfo.secure);

  // Hosts with the default ports are considered secure
  parsed = Utilities.parseUrl("http://gsoltis.firebaseio.com");
  assertTrue(parsed.repoInfo.secure);
}
 
Example #28
Source File: ParseUrlTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testUrlParsingWithNamespace() throws DatabaseException {
  ParsedUrl parsed = Utilities.parseUrl("http://localhost/foo/bar?ns=mrschmidt");
  assertEquals("mrschmidt", parsed.repoInfo.namespace);

  parsed = Utilities.parseUrl("http://10.0.2.2:9000/foo/bar?ns=mrschmidt");
  assertEquals(parsed.path.toString(), "/foo/bar");
  assertEquals("mrschmidt", parsed.repoInfo.namespace);
}
 
Example #29
Source File: ParseUrlTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testUrlParsing() throws DatabaseException {
  ParsedUrl parsed = Utilities.parseUrl("http://gsoltis.fblocal.com:9000");
  assertEquals("/", parsed.path.toString());
  assertEquals("gsoltis.fblocal.com:9000", parsed.repoInfo.host);
  assertEquals("gsoltis.fblocal.com:9000", parsed.repoInfo.internalHost);

  parsed = Utilities.parseUrl("http://gsoltis.firebaseio.com/foo/bar");
  assertEquals("gsoltis.firebaseio.com", parsed.repoInfo.host);
  assertEquals("gsoltis.firebaseio.com", parsed.repoInfo.internalHost);

  parsed = Utilities.parseUrl("http://gsoltis.firebaseio.com/foo/empty space");
  assertEquals("/foo/empty space", parsed.path.toString());
  assertEquals("gsoltis.firebaseio.com", parsed.repoInfo.host);
  assertEquals("gsoltis.firebaseio.com", parsed.repoInfo.internalHost);

  parsed = Utilities.parseUrl("http://gsoltis.firebaseio.com/foo/\\;:@\uD83D\uDE00");
  assertEquals("/foo/\\;:@\uD83D\uDE00", parsed.path.toString());
  assertEquals("gsoltis.firebaseio.com", parsed.repoInfo.host);
  assertEquals("gsoltis.firebaseio.com", parsed.repoInfo.internalHost);
}
 
Example #30
Source File: SqlPersistenceStorageEngineTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testConcurrentUsageFails() {
  try {
    getCleanPersistenceCache();
    fail("We should have failed to access the database again.");
  } catch (DatabaseException e) {
    // expected.
  }
}