http://git-wip-us.apache.org/repos/asf/usergrid/blob/2e127e62/sdks/java/src/main/java/org/apache/usergrid/java/client/response/UsergridResponseError.java ---------------------------------------------------------------------- diff --git a/sdks/java/src/main/java/org/apache/usergrid/java/client/response/UsergridResponseError.java b/sdks/java/src/main/java/org/apache/usergrid/java/client/response/UsergridResponseError.java new file mode 100644 index 0000000..387ae56 --- /dev/null +++ b/sdks/java/src/main/java/org/apache/usergrid/java/client/response/UsergridResponseError.java @@ -0,0 +1,98 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.usergrid.java.client.response; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.JsonNode; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.HashMap; +import java.util.Map; + +@SuppressWarnings("unused") +@JsonInclude(JsonInclude.Include.NON_NULL) +public class UsergridResponseError { + + @Nullable private String errorName; + @Nullable private String errorDescription; + @Nullable private String errorException; + + @NotNull private final Map<String, JsonNode> properties = new HashMap<>(); + + public UsergridResponseError() { + this(null,null,null); + } + public UsergridResponseError(@Nullable final String errorName) { + this(errorName, null, null); + } + public UsergridResponseError(@Nullable final String errorName, @Nullable final String errorDescription) { + this(errorName,errorDescription,null); + } + public UsergridResponseError(@Nullable final String errorName, @Nullable final String errorDescription, @Nullable final String errorException) { + this.errorName = errorName; + this.errorDescription = errorDescription; + this.errorException = errorException; + } + + @NotNull + @JsonAnyGetter + public Map<String, JsonNode> getProperties() { + return properties; + } + + @JsonAnySetter + public void setProperty(@NotNull final String key, @NotNull final JsonNode value) { + properties.put(key, value); + } + + @Nullable + @JsonProperty("error") + public String getErrorName() { + return errorName; + } + + @JsonProperty("error") + public void setErrorName(@NotNull final String errorName) { + this.errorName = errorName; + } + + @Nullable + @JsonProperty("exception") + public String getErrorException() { + return errorException; + } + + @JsonProperty("exception") + public void setErrorException(@NotNull final String errorException) { + this.errorException = errorException; + } + + @Nullable + @JsonProperty("error_description") + public String getErrorDescription() { + return errorDescription; + } + + @JsonProperty("error_description") + public void setErrorDescription(@NotNull final String errorDescription) { + this.errorDescription = errorDescription; + } +}
http://git-wip-us.apache.org/repos/asf/usergrid/blob/2e127e62/sdks/java/src/main/java/org/apache/usergrid/java/client/utils/JsonUtils.java ---------------------------------------------------------------------- diff --git a/sdks/java/src/main/java/org/apache/usergrid/java/client/utils/JsonUtils.java b/sdks/java/src/main/java/org/apache/usergrid/java/client/utils/JsonUtils.java index a465199..d2f43fb 100644 --- a/sdks/java/src/main/java/org/apache/usergrid/java/client/utils/JsonUtils.java +++ b/sdks/java/src/main/java/org/apache/usergrid/java/client/utils/JsonUtils.java @@ -16,167 +16,119 @@ */ package org.apache.usergrid.java.client.utils; -import java.io.IOException; -import java.util.Map; -import java.util.UUID; - import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.JsonNodeFactory; -import org.apache.usergrid.java.client.exception.ClientException; - -public class JsonUtils { - - - static ObjectMapper mapper = new ObjectMapper(); - - public static String getStringProperty(Map<String, JsonNode> properties, - String name) { - JsonNode value = properties.get(name); - if (value != null) { - return value.asText(); - } - return null; - } - - public static void setStringProperty(Map<String, JsonNode> properties, - String name, String value) { - if (value == null) { - properties.remove(name); - } else { - properties.put(name, JsonNodeFactory.instance.textNode(value)); - } - } - - public static Long getLongProperty(Map<String, JsonNode> properties, - String name) { - JsonNode value = properties.get(name); - if (value != null) { - return value.asLong(0); - } - return null; - } - - public static void setLongProperty(Map<String, JsonNode> properties, - String name, Long value) { - if (value == null) { - properties.remove(name); - } else { - properties.put(name, JsonNodeFactory.instance.numberNode(value)); - } - } +import com.fasterxml.jackson.databind.module.SimpleModule; +import com.fasterxml.jackson.databind.node.*; +import org.apache.usergrid.java.client.exception.UsergridException; +import org.apache.usergrid.java.client.model.UsergridEntity; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; - public static void setFloatProperty(Map<String, JsonNode> properties, String name, Float value){ - if(value == null){ - properties.remove(name); - }else{ - properties.put(name, JsonNodeFactory.instance.numberNode(value)); - } - } - - public static Boolean getBooleanProperty(Map<String, JsonNode> properties, - String name) { - JsonNode value = properties.get(name); - if (value != null) { - return value.asBoolean(); - } - return false; - } +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.Map; - public static void setBooleanProperty(Map<String, JsonNode> properties, - String name, Boolean value) { - if (value == null) { - properties.remove(name); - } else { - properties.put(name, JsonNodeFactory.instance.booleanNode(value)); - } - } +@SuppressWarnings("unused") +public final class JsonUtils { - public static UUID getUUIDProperty(Map<String, JsonNode> properties, - String name) { - JsonNode value = properties.get(name); - if (value != null) { - UUID uuid = null; - try { - uuid = UUID.fromString(value.asText()); - } catch (Exception e) { - } - return uuid; - } - return null; - } + @NotNull public static final ObjectMapper mapper = new ObjectMapper(); - public static void setUUIDProperty(Map<String, JsonNode> properties, - String name, UUID value) { - if (value == null) { - properties.remove(name); - } else { - properties.put(name, - JsonNodeFactory.instance.textNode(value.toString())); - } - } + static { + SimpleModule module = new SimpleModule(); + module.addDeserializer(UsergridEntity.class, new UsergridEntityDeserializer()); + mapper.registerModule(module); + } - public static String toJsonString(Object obj) { - try { - return mapper.writeValueAsString(obj); - } catch (JsonGenerationException e) { - throw new ClientException("Unable to generate json", e); - } catch (JsonMappingException e) { - throw new ClientException("Unable to map json", e); - } catch (IOException e) { - throw new ClientException("IO error", e); - } - } + @NotNull + public static ObjectNode createObjectNode() { + return mapper.createObjectNode(); + } - public static <T> T parse(String json, Class<T> c) { - try { - return mapper.readValue(json, c); - } catch (JsonGenerationException e) { - throw new ClientException("Unable to generate json", e); + @Nullable + public static String getStringProperty(@NotNull final Map<String, JsonNode> properties, @NotNull final String name) { + JsonNode value = properties.get(name); + if (value != null) { + return value.asText(); + } + return null; + } + + @NotNull + public static ArrayList<Object> convertToArrayList(@NotNull final ArrayNode arrayNode) { + ArrayList<Object> arrayList = new ArrayList<>(); + Iterator<JsonNode> iterator = arrayNode.elements(); + while( iterator.hasNext() ) { + arrayList.add(iterator.next()); + } + return arrayList; + } + + @NotNull + public static String toJsonString(@NotNull final Object obj) { + try { + return mapper.writeValueAsString(obj); + } catch (JsonGenerationException e) { + throw new UsergridException("Unable to generate json", e); } catch (JsonMappingException e) { - throw new ClientException("Unable to map json", e); + throw new UsergridException("Unable to map json", e); } catch (IOException e) { - throw new ClientException("IO error", e); + throw new UsergridException("IO error", e); } - } - - public static JsonNode toJsonNode(Object obj) { - return mapper.convertValue(obj, JsonNode.class); - } - - public static <T> T fromJsonNode(JsonNode json, Class<T> c) { - try { - JsonParser jp = json.traverse(); - return mapper.readValue(jp, c); - } catch (JsonGenerationException e) { - throw new ClientException("Unable to generate json", e); + } + + @NotNull + public static JsonNode toJsonNode(@NotNull final Object obj) { + return mapper.convertValue(obj, JsonNode.class); + } + + @NotNull + public static <T> T fromJsonNode(@NotNull final JsonNode json, @NotNull final Class<T> c) { + try { + JsonParser jp = json.traverse(); + return mapper.readValue(jp, c); + } catch (JsonGenerationException e) { + throw new UsergridException("Unable to generate json", e); } catch (JsonMappingException e) { - throw new ClientException("Unable to map json", e); + throw new UsergridException("Unable to map json", e); } catch (IOException e) { - throw new ClientException("IO error", e); + throw new UsergridException("IO error", e); } - } - - public static <T> T getObjectProperty(Map<String, JsonNode> properties, - String name, Class<T> c) { - JsonNode value = properties.get(name); - if (value != null) { - return fromJsonNode(value, c); - } - return null; - } - - public static void setObjectProperty(Map<String, JsonNode> properties, - String name, Object value) { - if (value == null) { - properties.remove(name); - } else { - properties.put(name, - JsonNodeFactory.instance.textNode(value.toString())); - } - } + } + public static void setObjectProperty(@NotNull final Map<String, JsonNode> properties, @NotNull final String name, @Nullable final ObjectNode value) { + if (value == null) { + properties.remove(name); + } else { + properties.put(name, value); + } + } + + @Nullable + @SuppressWarnings("unchecked") + public static <T> T getProperty(@NotNull final Map<String, JsonNode> properties, @NotNull final String name) { + JsonNode value = properties.get(name); + if( value == null ) { + return null; + } else if (value instanceof TextNode) { + return (T) value.asText(); + } else if (value instanceof LongNode) { + Long valueLong = value.asLong(); + return (T) valueLong; + } else if (value instanceof BooleanNode) { + Boolean valueBoolean = value.asBoolean(); + return (T) valueBoolean; + } else if (value instanceof IntNode) { + Integer valueInteger = value.asInt(); + return (T) valueInteger; + } else if (value instanceof FloatNode) { + return (T) Float.valueOf(value.toString()); + } else { + return (T) value; + } + } } http://git-wip-us.apache.org/repos/asf/usergrid/blob/2e127e62/sdks/java/src/main/java/org/apache/usergrid/java/client/utils/MapUtils.java ---------------------------------------------------------------------- diff --git a/sdks/java/src/main/java/org/apache/usergrid/java/client/utils/MapUtils.java b/sdks/java/src/main/java/org/apache/usergrid/java/client/utils/MapUtils.java index dd128eb..cbf6d51 100644 --- a/sdks/java/src/main/java/org/apache/usergrid/java/client/utils/MapUtils.java +++ b/sdks/java/src/main/java/org/apache/usergrid/java/client/utils/MapUtils.java @@ -16,24 +16,21 @@ */ package org.apache.usergrid.java.client.utils; +import org.jetbrains.annotations.NotNull; + import java.util.HashMap; import java.util.List; import java.util.Map; -public class MapUtils { - - public static <T> Map<String, T> newMapWithoutKeys(Map<String, T> map, - List<String> keys) { - Map<String, T> newMap = null; - if (map != null) { - newMap = new HashMap<String, T>(map); - } else { - newMap = new HashMap<String, T>(); - } - for (String key : keys) { - newMap.remove(key); - } - return newMap; - } +@SuppressWarnings("unused") +public final class MapUtils { + @NotNull + public static <T> Map<String, T> newMapWithoutKeys(@NotNull final Map<String, T> map, @NotNull final List<String> keys) { + Map<String, T> newMap = new HashMap<>(); + for (String key : keys) { + newMap.remove(key); + } + return newMap; + } } http://git-wip-us.apache.org/repos/asf/usergrid/blob/2e127e62/sdks/java/src/main/java/org/apache/usergrid/java/client/utils/ObjectUtils.java ---------------------------------------------------------------------- diff --git a/sdks/java/src/main/java/org/apache/usergrid/java/client/utils/ObjectUtils.java b/sdks/java/src/main/java/org/apache/usergrid/java/client/utils/ObjectUtils.java index 465845a..1d05405 100644 --- a/sdks/java/src/main/java/org/apache/usergrid/java/client/utils/ObjectUtils.java +++ b/sdks/java/src/main/java/org/apache/usergrid/java/client/utils/ObjectUtils.java @@ -16,21 +16,23 @@ */ package org.apache.usergrid.java.client.utils; +import org.jetbrains.annotations.Nullable; + import java.util.Map; -public class ObjectUtils { +public final class ObjectUtils { - public static boolean isEmpty(Object s) { - if (s == null) { - return true; - } - if ((s instanceof String) && (((String) s).trim().length() == 0)) { - return true; - } - if (s instanceof Map) { - return ((Map<?, ?>) s).isEmpty(); - } - return false; - } + public static boolean isEmpty(@Nullable final Object s) { + if (s == null) { + return true; + } + if ((s instanceof String) && (((String) s).trim().length() == 0)) { + return true; + } + if (s instanceof Map) { + return ((Map<?, ?>) s).isEmpty(); + } + return false; + } } http://git-wip-us.apache.org/repos/asf/usergrid/blob/2e127e62/sdks/java/src/main/java/org/apache/usergrid/java/client/utils/UrlUtils.java ---------------------------------------------------------------------- diff --git a/sdks/java/src/main/java/org/apache/usergrid/java/client/utils/UrlUtils.java b/sdks/java/src/main/java/org/apache/usergrid/java/client/utils/UrlUtils.java deleted file mode 100644 index bf2a2b3..0000000 --- a/sdks/java/src/main/java/org/apache/usergrid/java/client/utils/UrlUtils.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.usergrid.java.client.utils; - -import static java.net.URLEncoder.encode; -import static org.apache.usergrid.java.client.utils.ObjectUtils.isEmpty; - -import java.io.UnsupportedEncodingException; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import org.apache.usergrid.java.client.exception.ClientException; - -public class UrlUtils { - - - public static URL url(String s) { - try { - return new URL(s); - } catch (MalformedURLException e) { - throw new ClientException("Incorrect URL format", e); - } - } - - public static URL url(URL u, String s) { - try { - return new URL(u, s); - } catch (MalformedURLException e) { - throw new ClientException("Incorrect URL format", e); - } - } - - public static String path(Object... segments) { - String path = ""; - boolean first = true; - for (Object segment : segments) { - if (segment instanceof Object[]) { - segment = path((Object[]) segment); - } - if (!isEmpty(segment)) { - if (first) { - path = segment.toString(); - first = false; - } else { - if (!path.endsWith("/")) { - path += "/"; - } - path += segment.toString(); - } - } - } - return path; - } - - @SuppressWarnings("rawtypes") - public static String encodeParams(Map<String, Object> params) { - if (params == null) { - return ""; - } - boolean first = true; - StringBuilder results = new StringBuilder(); - for (Entry<String, Object> entry : params.entrySet()) { - if (entry.getValue() instanceof List) { - for (Object o : (List) entry.getValue()) { - if (!isEmpty(o)) { - if (!first) { - results.append('&'); - } - first = false; - results.append(entry.getKey()); - results.append("="); - try { - results.append(encode(o.toString(), "UTF-8")); - } catch (UnsupportedEncodingException e) { - throw new ClientException("Unknown encoding", e); - } - } - } - } else if (!isEmpty(entry.getValue())) { - if (!first) { - results.append('&'); - } - first = false; - results.append(entry.getKey()); - results.append("="); - try { - results.append(encode(entry.getValue().toString(), "UTF-8")); - } catch (UnsupportedEncodingException e) { - throw new ClientException("Unsupported string encoding", e); - } - } - } - return results.toString(); - } - - public static String addQueryParams(String url, Map<String, Object> params) { - if (params == null) { - return url; - } - if (!url.contains("?")) { - url += "?"; - } - url += encodeParams(params); - return url; - } - -} http://git-wip-us.apache.org/repos/asf/usergrid/blob/2e127e62/sdks/java/src/main/java/org/apache/usergrid/java/client/utils/UsergridEntityDeserializer.java ---------------------------------------------------------------------- diff --git a/sdks/java/src/main/java/org/apache/usergrid/java/client/utils/UsergridEntityDeserializer.java b/sdks/java/src/main/java/org/apache/usergrid/java/client/utils/UsergridEntityDeserializer.java new file mode 100644 index 0000000..5daeace --- /dev/null +++ b/sdks/java/src/main/java/org/apache/usergrid/java/client/utils/UsergridEntityDeserializer.java @@ -0,0 +1,41 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.usergrid.java.client.utils; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.usergrid.java.client.model.UsergridEntity; +import org.jetbrains.annotations.NotNull; + +import java.io.IOException; + +public final class UsergridEntityDeserializer extends JsonDeserializer<UsergridEntity> { + + @NotNull private static final ObjectMapper objectMapper = new ObjectMapper(); + + @NotNull + public UsergridEntity deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException { + UsergridEntity entity = UsergridEntityDeserializer.objectMapper.readValue(jsonParser,UsergridEntity.class); + Class<? extends UsergridEntity> entitySubClass = UsergridEntity.customSubclassForType(entity.getType()); + if( entitySubClass != null ) { + entity = JsonUtils.mapper.convertValue(entity,entitySubClass); + } + return entity; + } +} http://git-wip-us.apache.org/repos/asf/usergrid/blob/2e127e62/sdks/java/src/test/java/org/apache/usergrid/client/ClientAuthFallBackTestCase.java ---------------------------------------------------------------------- diff --git a/sdks/java/src/test/java/org/apache/usergrid/client/ClientAuthFallBackTestCase.java b/sdks/java/src/test/java/org/apache/usergrid/client/ClientAuthFallBackTestCase.java new file mode 100644 index 0000000..944aaef --- /dev/null +++ b/sdks/java/src/test/java/org/apache/usergrid/client/ClientAuthFallBackTestCase.java @@ -0,0 +1,72 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.usergrid.client; + +import org.apache.usergrid.java.client.*; +import org.apache.usergrid.java.client.auth.UsergridAppAuth; +import org.apache.usergrid.java.client.query.UsergridQuery; +import org.apache.usergrid.java.client.response.UsergridResponse; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertTrue; + +public class ClientAuthFallBackTestCase { + + private static UsergridQuery usersQuery = new UsergridQuery("users").desc("created"); + + @Before + public void before() { + Usergrid.initSharedInstance(SDKTestConfiguration.ORG_NAME, SDKTestConfiguration.APP_NAME, SDKTestConfiguration.USERGRID_URL, SDKTestConfiguration.authFallBack); + Usergrid.authenticateApp(new UsergridAppAuth(SDKTestConfiguration.APP_CLIENT_ID, SDKTestConfiguration.APP_CLIENT_SECRET)); + + String[] segments = {"roles","guest","permissions"}; + Map<String, Object> params = new HashMap<>(); + params.put("permission","get,post,put,delete:/**"); + UsergridRequest request = new UsergridRequest(UsergridEnums.UsergridHttpMethod.DELETE, UsergridRequest.APPLICATION_JSON_MEDIA_TYPE, Usergrid.clientAppUrl(), params, null, Usergrid.authForRequests(), segments); + Usergrid.sendRequest(request); + } + + @After + public void after() { + Usergrid.setAuthMode(UsergridEnums.UsergridAuthMode.APP); + String[] segments = {"roles","guest","permissions"}; + Map<String, Object> params = new HashMap<>(); + params.put("permission","get,post,put,delete:/**"); + UsergridRequest request = new UsergridRequest(UsergridEnums.UsergridHttpMethod.POST, UsergridRequest.APPLICATION_JSON_MEDIA_TYPE, Usergrid.clientAppUrl(), params, null, Usergrid.authForRequests(), segments); + Usergrid.sendRequest(request); + Usergrid.reset(); + } + + @Test + public void authFallBackNONETest() { + Usergrid.setAuthMode(UsergridEnums.UsergridAuthMode.NONE); + UsergridResponse resp = Usergrid.GET(usersQuery); + assertTrue("The returned response should have error", resp.getResponseError() != null); + } + + @Test + public void authFallBackAPPTest() { + Usergrid.setAuthMode(UsergridEnums.UsergridAuthMode.APP); + UsergridResponse resp = Usergrid.GET(usersQuery); + assertTrue("The returned response should not have error", resp.getResponseError() == null); + } +} http://git-wip-us.apache.org/repos/asf/usergrid/blob/2e127e62/sdks/java/src/test/java/org/apache/usergrid/client/ClientAuthTestCase.java ---------------------------------------------------------------------- diff --git a/sdks/java/src/test/java/org/apache/usergrid/client/ClientAuthTestCase.java b/sdks/java/src/test/java/org/apache/usergrid/client/ClientAuthTestCase.java new file mode 100644 index 0000000..79e1bbc --- /dev/null +++ b/sdks/java/src/test/java/org/apache/usergrid/client/ClientAuthTestCase.java @@ -0,0 +1,85 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.usergrid.client; + +import org.apache.usergrid.java.client.Usergrid; +import org.apache.usergrid.java.client.UsergridEnums.*; +import org.apache.usergrid.java.client.auth.UsergridAppAuth; +import org.apache.usergrid.java.client.auth.UsergridUserAuth; +import org.apache.usergrid.java.client.model.UsergridUser; +import org.apache.usergrid.java.client.response.UsergridResponse; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class ClientAuthTestCase { + + @Before + public void before() { + Usergrid.initSharedInstance(SDKTestConfiguration.ORG_NAME, SDKTestConfiguration.APP_NAME, SDKTestConfiguration.USERGRID_URL); + } + + @After + public void after() { + Usergrid.reset(); + } + + @Test + public void clientAuth_APP() { + Usergrid.setAuthMode(UsergridAuthMode.APP); + UsergridAppAuth appAuth = new UsergridAppAuth(SDKTestConfiguration.APP_CLIENT_ID, SDKTestConfiguration.APP_CLIENT_SECRET); + UsergridResponse response = Usergrid.authenticateApp(appAuth); + assertTrue("response status is OK", response.ok()); + assertNull("no error thrown", response.getResponseError()); + assertTrue("appAuth.isValidToken should be true", appAuth.isValidToken()); + assertNotNull("should have a valid token", appAuth.getAccessToken()); + assertNotNull("should have an expiry", appAuth.getExpiry()); + assertEquals("client.appAuth.token should be set to the token returned from Usergrid", Usergrid.getAppAuth(), appAuth); + assertTrue("should have a token that is not empty", appAuth.getAccessToken().length() > 0); + assertTrue("client.appAuth.expiry should be set to a future date", appAuth.getExpiry() > System.currentTimeMillis()); + } + + @Test + public void clientAuth_USER() { + Usergrid.setAuthMode(UsergridAuthMode.USER); + UsergridUserAuth userAuth = new UsergridUserAuth(SDKTestConfiguration.APP_UserName, SDKTestConfiguration.APP_Password); + UsergridResponse response = Usergrid.authenticateUser(userAuth); + assertTrue("response status is OK", response.ok()); + assertNull("no error thrown", response.getResponseError()); + assertTrue("appAuth.isValidToken should be true", userAuth.isValidToken()); + assertNotNull("should have a token", userAuth.getAccessToken()); + assertNotNull("should have an expiry", userAuth.getExpiry()); + + UsergridUser currentUser = Usergrid.getCurrentUser(); + assertNotNull("client.currentUser should not be null", currentUser); + assertNotNull("client.currentUser().getUserAuth() should not be null", currentUser.getUserAuth()); + assertEquals("client.currentUser().userAuth should be the same as userAuth", currentUser.getUserAuth(), userAuth); + assertTrue("should have a token that is not empty", userAuth.getAccessToken().length() > 0); + assertTrue("client.currentUser().userAuth.getExpiry() should be set to a future date", userAuth.getExpiry() > System.currentTimeMillis()); + assertEquals("client.authForRequests() should be the same as userAuth", Usergrid.authForRequests(), userAuth); + } + + @Test + public void clientAuth_NONE() { + Usergrid.setAuthMode(UsergridAuthMode.NONE); + UsergridUserAuth userAuth = new UsergridUserAuth(SDKTestConfiguration.APP_UserName, SDKTestConfiguration.APP_Password); + Usergrid.authenticateUser(userAuth); + assertNull("no auth should be returned from client.authForRequests", Usergrid.authForRequests()); + } +} http://git-wip-us.apache.org/repos/asf/usergrid/blob/2e127e62/sdks/java/src/test/java/org/apache/usergrid/client/ClientConnectionsTestCase.java ---------------------------------------------------------------------- diff --git a/sdks/java/src/test/java/org/apache/usergrid/client/ClientConnectionsTestCase.java b/sdks/java/src/test/java/org/apache/usergrid/client/ClientConnectionsTestCase.java new file mode 100644 index 0000000..72b88dd --- /dev/null +++ b/sdks/java/src/test/java/org/apache/usergrid/client/ClientConnectionsTestCase.java @@ -0,0 +1,171 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.usergrid.client; + +import org.apache.usergrid.java.client.UsergridEnums.UsergridDirection; +import org.apache.usergrid.java.client.Usergrid; +import org.apache.usergrid.java.client.auth.UsergridAppAuth; +import org.apache.usergrid.java.client.model.UsergridEntity; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class ClientConnectionsTestCase { + + @Before + public void before() { + Usergrid.initSharedInstance(SDKTestConfiguration.ORG_NAME, SDKTestConfiguration.APP_NAME, SDKTestConfiguration.USERGRID_URL, SDKTestConfiguration.authFallBack); + UsergridAppAuth appAuth = new UsergridAppAuth(SDKTestConfiguration.APP_CLIENT_ID, SDKTestConfiguration.APP_CLIENT_SECRET); + Usergrid.authenticateApp(appAuth); + } + + @After + public void after() { + Usergrid.reset(); + } + + @Test + public void clientConnect() { + String collectionName = "testClientConnection" + System.currentTimeMillis(); + + UsergridEntity entityOne = new UsergridEntity(collectionName,"john"); + entityOne.putProperty("place","San Jose"); + entityOne.save(); + assertNotNull(entityOne.getUuid()); + + UsergridEntity entityTwo = new UsergridEntity(collectionName,"amici"); + entityOne.putProperty("place","San Jose"); + entityTwo.save(); + assertNotNull(entityTwo.getUuid()); + + //should connect entities by passing UsergridEntity objects as parameters + Usergrid.connect(entityOne, "likes", entityTwo); + + UsergridEntity responseEntity = Usergrid.getConnections(UsergridDirection.OUT, entityOne, "likes").first(); + assertNotNull(responseEntity); + assertEquals("both entities name should be same", entityTwo.getName(),responseEntity.getName()); + assertEquals("both entities uuid should be same", entityTwo.getUuid(),responseEntity.getUuid()); + + //should connect entities by passing a source UsergridEntity object and a target uuid. + Usergrid.connect(entityOne.getType(), entityOne.getUuid(), "visited", entityTwo.getUuid()); + + responseEntity = Usergrid.getConnections(UsergridDirection.OUT, entityOne, "visited").first(); + assertNotNull(responseEntity); + assertEquals("both entities name should be same", entityTwo.getName(),responseEntity.getName()); + assertEquals("both entities uuid should be same", entityTwo.getUuid(),responseEntity.getUuid()); + + //should connect entities by passing source type, source uuid, and target uuid as parameters + Usergrid.connect(entityTwo.getType(), entityTwo.getUuid(), "visitor", entityOne.getUuid()); + + responseEntity = Usergrid.getConnections(UsergridDirection.OUT, entityTwo, "visitor").first(); + assertNotNull(responseEntity); + assertEquals("both entities name should be same", entityOne.getName(),responseEntity.getName()); + assertEquals("both entities uuid should be same", entityOne.getUuid(),responseEntity.getUuid()); + + //should connect entities by passing source type, source name, target type, and target name as parameters + assertNotNull(entityOne.getName()); + assertNotNull(entityTwo.getName()); + Usergrid.connect(entityTwo.getType(), entityTwo.getName(), "welcomed", entityOne.getType(), entityOne.getName()); + + responseEntity = Usergrid.getConnections(UsergridDirection.OUT, entityTwo, "welcomed").first(); + assertNotNull(responseEntity); + assertEquals("both entities name should be same", entityOne.getName(),responseEntity.getName()); + assertEquals("both entities uuid should be same", entityOne.getUuid(),responseEntity.getUuid()); + + //should connect entities by passing source type, source name, target type, and target name as parameters + Usergrid.connect(entityTwo.getType(), entityTwo.getName(), "invalidLink", "invalidName"); + responseEntity = Usergrid.getConnections(UsergridDirection.OUT, entityTwo, "invalidLink").first(); + assertNull("response entity should be null.", responseEntity); + } + + @Test + public void clientGetConnect() { + String collectionName = "testClientGetConnection" + System.currentTimeMillis(); + + //should set properties for a given object, overwriting properties that exist and creating those that don\'t + UsergridEntity entityOne = new UsergridEntity(collectionName, "john"); + entityOne.putProperty("place","San Jose"); + entityOne.save(); + + //should set properties for a given object, overwriting properties that exist and creating those that don\'t + UsergridEntity entityTwo = new UsergridEntity(collectionName, "amici"); + entityTwo.putProperty("place","San Jose"); + entityTwo.save(); + + //should connect entities by passing UsergridEntity objects as parameters + Usergrid.connect(entityOne, "likes", entityTwo); + Usergrid.connect(entityOne, "visited", entityTwo); + + UsergridEntity responseEntity = Usergrid.getConnections(UsergridDirection.OUT, entityOne, "likes").first(); + assertNotNull(responseEntity); + assertEquals("both entities name should be same", entityTwo.getName(),responseEntity.getName()); + assertEquals("both entities uuid should be same", entityTwo.getUuid(),responseEntity.getUuid()); + + responseEntity = Usergrid.getConnections(UsergridDirection.IN, entityTwo, "visited").first(); + assertNotNull(responseEntity); + assertEquals("both entities name should be same", entityOne.getName(),responseEntity.getName()); + assertEquals("both entities uuid should be same", entityOne.getUuid(),responseEntity.getUuid()); + + } + + @Test + public void clientDisConnect() { + String collectionName = "testClientGetConnection" + System.currentTimeMillis(); + + //should set properties for a given object, overwriting properties that exist and creating those that don\'t + UsergridEntity entityOne = new UsergridEntity(collectionName,"john"); + entityOne.putProperty("place","San Jose"); + entityOne.save(); + assertNotNull(entityOne.getName()); + assertNotNull(entityOne.getUuid()); + + //should set properties for a given object, overwriting properties that exist and creating those that don\'t + UsergridEntity entityTwo = new UsergridEntity(collectionName, "amici"); + entityTwo.putProperty("place","San Jose"); + entityTwo.save(); + assertNotNull(entityTwo.getName()); + assertNotNull(entityTwo.getUuid()); + + //should connect entities by passing UsergridEntity objects as parameters + Usergrid.connect(entityOne, "likes", entityTwo); + Usergrid.connect(entityOne, "visited", entityTwo); + Usergrid.connect(entityOne, "twice", entityTwo); + Usergrid.connect(entityOne, "thrice", entityTwo); + + //should disConnect entities by passing UsergridEntity objects as parameters + Usergrid.disconnect(entityOne, "likes", entityTwo); + UsergridEntity responseEntity = Usergrid.getConnections(UsergridDirection.IN, entityTwo, "likes").first(); + assertNull("responseEntity should be null", responseEntity); + + //should disConnect entities by passing source type, source uuid, and target uuid as parameters + Usergrid.disconnect(entityOne.getType(), entityOne.getUuid(), "visited", entityTwo.getUuid()); + responseEntity = Usergrid.getConnections(UsergridDirection.OUT, entityOne, "visited").first(); + assertNull("responseEntity should be null", responseEntity); + + //should disConnect entities by passing source type, source name, target type, and target name as parameters + Usergrid.disconnect(entityOne.getType(), entityOne.getName(), "twice", entityTwo.getType(), entityTwo.getName()); + responseEntity = Usergrid.getConnections(UsergridDirection.OUT, entityOne, "twice").first(); + assertNull("responseEntity should be null", responseEntity); + + //should fail to disConnect entities when specifying target name without type + Usergrid.disconnect(entityTwo.getType(), entityTwo.getName(), "thrice", entityOne.getName()); + responseEntity = Usergrid.getConnections(UsergridDirection.OUT, entityTwo, "thrice").first(); + assertNull("both entities name should be same",responseEntity); + } +} http://git-wip-us.apache.org/repos/asf/usergrid/blob/2e127e62/sdks/java/src/test/java/org/apache/usergrid/client/ClientRestTestCase.java ---------------------------------------------------------------------- diff --git a/sdks/java/src/test/java/org/apache/usergrid/client/ClientRestTestCase.java b/sdks/java/src/test/java/org/apache/usergrid/client/ClientRestTestCase.java new file mode 100644 index 0000000..b01a167 --- /dev/null +++ b/sdks/java/src/test/java/org/apache/usergrid/client/ClientRestTestCase.java @@ -0,0 +1,90 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.usergrid.client; + +import org.apache.usergrid.java.client.Usergrid; +import org.apache.usergrid.java.client.auth.UsergridAppAuth; +import org.apache.usergrid.java.client.model.UsergridEntity; +import org.apache.usergrid.java.client.response.UsergridResponse; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; + +import static org.junit.Assert.*; + +public class ClientRestTestCase { + + final String collectionName = "testClientConnection" + System.currentTimeMillis(); + + @Before + public void before() { + Usergrid.initSharedInstance(SDKTestConfiguration.ORG_NAME, SDKTestConfiguration.APP_NAME, SDKTestConfiguration.USERGRID_URL, SDKTestConfiguration.authFallBack); + UsergridAppAuth appAuth = new UsergridAppAuth(SDKTestConfiguration.APP_CLIENT_ID, SDKTestConfiguration.APP_CLIENT_SECRET); + Usergrid.authenticateApp(appAuth); + createCollectionAndEntity(); + } + + @After + public void after() { + Usergrid.reset(); + } + + public void createCollectionAndEntity() { + UsergridEntity entityOne = new UsergridEntity(collectionName,"john"); + entityOne.putProperty("place", "San Jose"); + entityOne.save(); + + UsergridEntity entityTwo = new UsergridEntity(collectionName,"amici"); + entityTwo.putProperty("place", "San Jose"); + entityTwo.save(); + + assertNotNull(entityOne.getUuid()); + assertNotNull(entityTwo.getUuid()); + + Usergrid.connect(entityOne, "likes", entityTwo); + Usergrid.connect(entityOne.getType(), entityOne.getUuid(), "visited", entityTwo.getUuid()); + } + + @Test + public void clientGET() { + // Retrieve the response. + UsergridResponse response = Usergrid.GET(collectionName, "john"); + assertTrue("response should be ok", response.ok()); + assertNull("no error thrown", response.getResponseError()); + + assertNotNull(response.getEntities()); + assertTrue("response entities is an Array", response.getEntities().getClass() == ArrayList.class); + + // response.first should exist and have a valid uuid + UsergridEntity firstEntity = response.first(); + assertNotNull(firstEntity); + assertNotNull("first entity is not null and has uuid", firstEntity.getUuid()); + + // response.entity should exist, equals the first entity, and have a valid uuid + UsergridEntity responseEntity = response.entity(); + assertNotNull(responseEntity); + assertEquals(firstEntity, responseEntity); + assertNotNull("entity is not null and has uuid", responseEntity.getUuid()); + + // response.last should exist and have a valid uuid + UsergridEntity lastEntity = response.last(); + assertNotNull(lastEntity); + assertNotNull("last entity is not null and has uuid", lastEntity.getUuid()); + } +} http://git-wip-us.apache.org/repos/asf/usergrid/blob/2e127e62/sdks/java/src/test/java/org/apache/usergrid/client/EntityTestCase.java ---------------------------------------------------------------------- diff --git a/sdks/java/src/test/java/org/apache/usergrid/client/EntityTestCase.java b/sdks/java/src/test/java/org/apache/usergrid/client/EntityTestCase.java new file mode 100644 index 0000000..42c3054 --- /dev/null +++ b/sdks/java/src/test/java/org/apache/usergrid/client/EntityTestCase.java @@ -0,0 +1,676 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.usergrid.client; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.TextNode; +import org.apache.usergrid.java.client.UsergridEnums.UsergridDirection; +import org.apache.usergrid.java.client.Usergrid; +import org.apache.usergrid.java.client.auth.UsergridAppAuth; +import org.apache.usergrid.java.client.model.UsergridEntity; +import org.apache.usergrid.java.client.query.UsergridQuery; +import org.apache.usergrid.java.client.response.UsergridResponse; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.*; + +public class EntityTestCase { + + @Before + public void before() { + Usergrid.initSharedInstance(SDKTestConfiguration.ORG_NAME, SDKTestConfiguration.APP_NAME, SDKTestConfiguration.USERGRID_URL, SDKTestConfiguration.authFallBack); + Usergrid.authenticateApp(new UsergridAppAuth(SDKTestConfiguration.APP_CLIENT_ID, SDKTestConfiguration.APP_CLIENT_SECRET)); + } + + @After + public void after() { + Usergrid.reset(); + } + + @Test + public void testEntityCreationSuccess() { + String collectionName = "ect" + System.currentTimeMillis(); + String entityName = "testEntity1"; + + HashMap<String,JsonNode> map = new HashMap<>(); + map.put("name",new TextNode(entityName)); + map.put("color",new TextNode("red")); + map.put("shape",new TextNode("square")); + + UsergridEntity entity = new UsergridEntity(collectionName,null,map); + UsergridResponse response = entity.save(); + assertNull(response.getResponseError()); + + UsergridEntity eLookUp = Usergrid.GET(collectionName, entityName).first(); + assertNotNull("The returned entity is null!", eLookUp); + assertEquals("entities has the correct type", eLookUp.getType(),collectionName); + assertEquals("entities has the correct name", eLookUp.getName(),entityName); + assertEquals("entities has the correct color", eLookUp.getStringProperty("color"),"red"); + assertEquals("entities has the correct shape", eLookUp.getStringProperty("shape"),"square"); + } + + @Test + public void testDuplicateEntityNameFailure() { + String collectionName = "testDuplicateEntityNameFailure" + System.currentTimeMillis(); + + UsergridEntity entity = new UsergridEntity(collectionName,"test3"); + UsergridResponse response = Usergrid.POST(entity); + assertNull("First entity create should have succeeded.", response.getResponseError()); + + response = Usergrid.POST(entity); + assertNotNull("Second entity create should not succeed!", response.getResponseError()); + } + + @Test + public void testEntityLookupByName() { + String collectionName = "testEntityLookupByName" + System.currentTimeMillis(); + String entityName = "testEntity4"; + + UsergridEntity entity = new UsergridEntity(collectionName,entityName); + entity.save(); + + UsergridEntity eLookup = Usergrid.GET(collectionName, entityName).first(); + assertNotNull("The returned entity is null!", eLookup); + assertEquals("The returned entity does not have the same UUID", entity.getUuid(),eLookup.getUuid()); + } + + @Test + public void testEntityLookupByUUID() { + String collectionName = "testEntityLookupByUUID" + System.currentTimeMillis(); + String entityName = "testEntity5"; + + UsergridEntity entity = new UsergridEntity(collectionName,entityName); + entity.save(); + assertNotNull(entity.getUuid()); + + UsergridEntity eLookup = Usergrid.GET(collectionName, entity.getUuid()).first(); + assertNotNull("The returned entity is null!", eLookup); + assertEquals("The returned entity does not have the same UUID", entity.getUuid(),eLookup.getUuid()); + } + + @Test + public void testEntityLookupByQuery() { + String collectionName = "testEntityLookupByQuery" + System.currentTimeMillis(); + String entityName = "testEntity6"; + + UsergridEntity entity = new UsergridEntity(collectionName,entityName); + entity.putProperty("color","red"); + entity.putProperty("shape","square"); + entity.save(); + + SDKTestUtils.indexSleep(); + + UsergridQuery query = new UsergridQuery(collectionName).eq("color", "red"); + UsergridEntity eLookup = Usergrid.GET(query).first(); + + assertNotNull("The entity was not returned on lookup", eLookup); + assertEquals("The returned entity does not have the same UUID", entity.getUuid(),eLookup.getUuid()); + + query = new UsergridQuery(collectionName).eq("name", entityName); + eLookup = Usergrid.GET(query).first(); + + assertNotNull("The entity was not returned on lookup", eLookup); + assertEquals("The returned entity does not have the same UUID", entity.getUuid(),eLookup.getUuid()); + + query = new UsergridQuery(collectionName).eq("shape", "square"); + eLookup = Usergrid.GET(query).first(); + + assertNotNull("The entity was not returned on lookup", eLookup); + assertEquals("The returned entity does not have the same UUID", entity.getUuid(),eLookup.getUuid()); + + query = new UsergridQuery(collectionName).eq("shape", "circle"); + eLookup = Usergrid.GET(query).first(); + + assertNull("The entity was not expected to be returned on lookup", eLookup); + } + + @Test + public void testEntityUpdate() { + String collectionName = "testEntityLookupByUUID" + System.currentTimeMillis(); + String entityName = "testEntity7"; + + UsergridEntity entity = new UsergridEntity(collectionName,entityName); + entity.putProperty("color","red"); + entity.putProperty("shape","square"); + entity.putProperty("orientation","up"); + entity.save(); + + SDKTestUtils.sleep(1000); + + UsergridQuery query = new UsergridQuery(collectionName).eq("orientation", "up"); + UsergridEntity eLookup = Usergrid.GET(query).first(); + assertNotNull(eLookup); + + assertEquals("The returned entity does not have the same UUID when querying by field", entity.getUuid(),eLookup.getUuid()); + + entity.putProperty("orientation", "down"); + entity.save(); + assertNotNull(entity.getUuid()); + + eLookup = Usergrid.GET(collectionName, entity.getUuid()).first(); + assertNotNull(eLookup); + + assertEquals("The returned entity does not have the same UUID", entity.getUuid(),eLookup.getUuid()); + assertEquals("The field was not updated!", eLookup.getStringProperty("orientation"),"down"); + + SDKTestUtils.sleep(1000); + + query = new UsergridQuery(collectionName).eq("orientation", "up"); + eLookup = Usergrid.GET(query).first(); + + assertNull("The entity was returned for old value!", eLookup); + } + + @Test + public void testEntityDelete() { + String collectionName = "testEntityDelete" + System.currentTimeMillis(); + String entityName = "testEntity8"; + + UsergridEntity entity = new UsergridEntity(collectionName,entityName); + entity.putProperty("color","red"); + entity.putProperty("shape","square"); + entity.putProperty("orientation","up"); + entity.save(); + + SDKTestUtils.indexSleep(); + + assertNotNull(entity.getUuid()); + assertNotNull(entity.getName()); + + UsergridQuery query = new UsergridQuery(collectionName).eq("orientation", "up"); + UsergridEntity eLookup = Usergrid.GET(query).first(); + + assertNotNull("The returned entity was null!", eLookup); + assertEquals("The returned entity does not have the same UUID when querying by field", entity.getUuid(),eLookup.getUuid()); + + Usergrid.DELETE(entity); + + eLookup = Usergrid.GET(collectionName, entity.getUuid()).first(); + assertNull("The entity was not expected to be returned by UUID", eLookup); + + eLookup = Usergrid.GET(collectionName, entity.getName()).first(); + assertNull("The entity was not expected to be returned by getName", eLookup); + + query = new UsergridQuery(collectionName).eq("color", "red"); + eLookup = Usergrid.GET(query).first(); + assertNull("The entity was not expected to be returned", eLookup); + + query = new UsergridQuery(collectionName).eq("shape", "square"); + eLookup = Usergrid.GET(query).first(); + assertNull("The entity was not expected to be returned", eLookup); + + query = new UsergridQuery(collectionName).eq("orientation", "up"); + eLookup = Usergrid.GET(query).first(); + assertNull("The entity was not expected to be returned", eLookup); + } + + @Test + public void testEntityPutPropertyAndSave() { + String collectionName = "testEntityPutProperty" + System.currentTimeMillis(); + String entityName = "testEntity9"; + + UsergridEntity entity = new UsergridEntity(collectionName,entityName); + entity.putProperty("color","red"); + entity.putProperty("shape","square"); + entity.putProperty("orientation","up"); + entity.putProperty("sides", 4); + entity.save(); + + UsergridEntity eLookUp = Usergrid.GET(collectionName, entityName).first(); + + //Check if the property was added correctly + assertNotNull("The entity returned is not null.", eLookUp); + assertEquals("The entity putProperty() was successful ", eLookUp.getStringProperty("orientation"),"up"); + assertEquals("The entity putProperty() was successful ", eLookUp.getIntegerProperty("sides"), new Integer(4)); + + //Overwrite the property if it exists. + entity.putProperty("orientation", "horizontal"); + entity.save(); + + eLookUp = Usergrid.GET(collectionName, entityName).first(); + assertNotNull("The returned entity was null!", eLookUp); + assertEquals("The entity putProperty() was successful ", eLookUp.getStringProperty("orientation"),"horizontal"); + + //should not be able to set the name key (name is immutable) + entity.putProperty("name","entityNew"); + entity.save(); + + eLookUp = Usergrid.GET(collectionName, entityName).first(); + assertNotNull("The returned entity was null!", eLookUp); + assertEquals("The entity putProperty() was successful ", eLookUp.getName(),"testEntity9"); + } + + @Test + public void testEntityPutProperties() { + String collectionName = "testEntityProperties" + System.currentTimeMillis(); + String entityName = "testEntity9"; + + UsergridEntity entity = new UsergridEntity(collectionName,entityName); + entity.putProperty("color","black"); + entity.putProperty("orientation","up"); + entity.save(); + + UsergridEntity eLookUp = Usergrid.GET(collectionName, entityName).first(); + assertNotNull("The entity returned is not null.", eLookUp); + assertEquals("The entity putProperty() was successful ", eLookUp.getStringProperty("orientation"),"up"); + assertEquals("overwrite existing property", eLookUp.getStringProperty("color"),"black"); + } + + @Test + public void testEntityRemovePropertiesAndSave() { + String collectionName = "testEntityProperties" + System.currentTimeMillis(); + + Map<String, String> fields = new HashMap<>(3); + fields.put("color", "red"); + + String entityName = "testEntity9"; + + //should set properties for a given object, overwriting properties that exist and creating those that don\'t + UsergridEntity entity = SDKTestUtils.createEntity(collectionName, entityName, fields); + Map<String, Object> properties = new HashMap<>(); + properties.put("shape", "square"); + properties.put("orientation", "up"); + properties.put("color", "black"); + entity.putProperties(properties); + entity.save(); + + UsergridEntity eLookUp = Usergrid.GET(collectionName, "testEntity9").first(); + assertNotNull("The entity returned is not null.", eLookUp); + + String[] removeProperties = {"shape", "color"}; + entity.removeProperties(Arrays.asList(removeProperties)); + entity.save(); + + eLookUp = Usergrid.GET(collectionName, "testEntity9").first(); + assertNotNull("The entity returned is not null.", eLookUp); + assertTrue("overwrite existing property", eLookUp.getStringProperty("color") == null); + assertTrue("overwrite existing property", eLookUp.getStringProperty("shape") == null); + + } + + @Test + public void testEntityRemoveProperty() { + String collectionName = "testEntityProperties" + System.currentTimeMillis(); + + Map<String, String> fields = new HashMap<>(3); + fields.put("color", "red"); + + String entityName = "testEntity11"; + + //should set properties for a given object, overwriting properties that exist and creating those that don\'t + UsergridEntity entity = SDKTestUtils.createEntity(collectionName, entityName, fields); + Map<String, Object> properties = new HashMap<>(); + properties.put("shape", "square"); + properties.put("orientation", "up"); + properties.put("color", "black"); + entity.putProperties(properties); + entity.save(); + + UsergridEntity eLookUp = Usergrid.GET(collectionName, "testEntity11").first(); + assertNotNull("The entity returned is not null.", eLookUp); + + entity.removeProperty("color"); + entity.removeProperty("shape"); + entity.save(); + + eLookUp = Usergrid.GET(collectionName, "testEntity11").first(); + assertNotNull("The entity returned is not null.", eLookUp); + assertTrue("overwrite existing property", eLookUp.getStringProperty("color") == null); + assertTrue("overwrite existing property", eLookUp.getStringProperty("shape") == null); + + } + + @Test + public void testEntityAppendInArray() { + String collectionName = "testEntityProperties" + System.currentTimeMillis(); + String entityName = "testEntity1"; + + UsergridEntity entity = new UsergridEntity(collectionName,entityName); + entity.save(); + + ArrayList<Object> lenArr = new ArrayList<>(); + lenArr.add(1); + lenArr.add(2); + lenArr.add(3); + lenArr.add(4); + entity.insert("lenArray", lenArr); + entity.save(); + + lenArr = new ArrayList<>(); + lenArr.add(6); + lenArr.add(7); + entity.append("lenArray", lenArr); + entity.save(); + + UsergridEntity eLookUp = Usergrid.GET(collectionName, entityName).first(); + assertNotNull("The entity returned is not null.", eLookUp); + + ArrayNode toCompare = new ArrayNode(JsonNodeFactory.instance); + toCompare.add(1).add(2).add(3).add(4).add(6).add(7); + assertEquals("The two arrays should be equal.", eLookUp.getJsonNodeProperty("lenArray"),toCompare); + } + + @Test + public void testEntityPrependInArray() { + String collectionName = "testEntityProperties" + System.currentTimeMillis(); + String entityName = "testEntity1"; + + UsergridEntity entity = new UsergridEntity(collectionName,entityName); + entity.save(); + + ArrayList<Object> lenArr = new ArrayList<>(); + lenArr.add(1); + lenArr.add(2); + lenArr.add(3); + lenArr.add(4); + entity.putProperty("lenArray", lenArr); + entity.save(); + + lenArr = new ArrayList<>(); + lenArr.add(6); + lenArr.add(7); + + entity.insert("lenArray", lenArr, 0); + entity.save(); + UsergridEntity eLookUp = Usergrid.GET(collectionName, entityName).first(); + assertNotNull("The entity returned is not null.", eLookUp); + + ArrayNode toCompare = new ArrayNode(JsonNodeFactory.instance); + toCompare.add(6).add(7).add(1).add(2).add(3).add(4); + assertEquals("The two arrays should be equal.", eLookUp.getJsonNodeProperty("lenArray"),toCompare); + } + + @Test + public void testEntityPopInArray() { + String collectionName = "testEntityProperties" + System.currentTimeMillis(); + String entityName = "testEntity1"; + + UsergridEntity entity = new UsergridEntity(collectionName,entityName); + entity.save(); + + ArrayList<Object> lenArr = new ArrayList<>(); + lenArr.add(1); + lenArr.add(2); + lenArr.add(3); + entity.putProperty("lenArray", lenArr); + entity.save(); + + // should remove the last value of an existing array + entity.pop("lenArray"); + entity.save(); + + UsergridEntity eLookUp = Usergrid.GET(collectionName, entityName).first(); + assertNotNull("The entity returned is not null.", eLookUp); + + ArrayNode toCompare = new ArrayNode(JsonNodeFactory.instance); + toCompare.add(1).add(2); + assertEquals("The two arrays should be equal.", eLookUp.getJsonNodeProperty("lenArray"),toCompare); + + // value should remain unchanged if it is not an array + entity.putProperty("foo", "test1"); + entity.save(); + + entity.pop("foo"); + entity.save(); + + eLookUp = Usergrid.GET(collectionName, entityName).first(); + assertNotNull("The entity returned is not null.", eLookUp); + assertEquals("foo should equal test1.", eLookUp.getStringProperty("foo"), "test1"); + + //should gracefully handle empty arrays + ArrayList<Object> lenArr2 = new ArrayList<>(); + entity.putProperty("foo", lenArr2); + entity.save(); + entity.pop("foo"); + + eLookUp = Usergrid.GET(collectionName, entityName).first(); + assertNotNull("The entity returned is not null.", eLookUp); + + toCompare = new ArrayNode(JsonNodeFactory.instance); + assertEquals("The two arrays should be equal.", eLookUp.getJsonNodeProperty("foo"),toCompare); + } + + @Test + public void testEntityShiftInArray() { + String collectionName = "testEntityProperties" + System.currentTimeMillis(); + String entityName = "testEntity1"; + + //should remove the last value of an existing array + UsergridEntity entity = new UsergridEntity(collectionName,entityName); + entity.save(); + + ArrayList<Object> lenArr = new ArrayList<>(); + lenArr.add(1); + lenArr.add(2); + lenArr.add(3); + entity.putProperty("lenArray", lenArr); + entity.save(); + + entity.shift("lenArray"); + entity.save(); + + UsergridEntity eLookUp = Usergrid.GET(collectionName, entityName).first(); + assertNotNull("The entity returned is not null.", eLookUp); + + ArrayNode toCompare = new ArrayNode(JsonNodeFactory.instance); + toCompare.add(2).add(3); + assertEquals("The two arrays should be equal.", eLookUp.getJsonNodeProperty("lenArray"),toCompare); + + //value should remain unchanged if it is not an array + entity.putProperty("foo", "test1"); + entity.shift("foo"); + entity.save(); + + eLookUp = Usergrid.GET(collectionName, entityName).first(); + assertNotNull("The entity returned is not null.", eLookUp); + assertEquals("The entity returned is not null.", eLookUp.getStringProperty("foo"), "test1"); + + //should gracefully handle empty arrays + ArrayList<Object> lenArr2 = new ArrayList<>(); + entity.putProperty("foo", lenArr2); + entity.shift("foo"); + entity.save(); + + eLookUp = Usergrid.GET(collectionName, entityName).first(); + assertNotNull("The entity returned is not null.", eLookUp); + assertEquals("The two arrays should be equal.", eLookUp.getJsonNodeProperty("foo"), new ArrayNode(JsonNodeFactory.instance)); + } + + @Test + public void testEntityInsertInArray() { + String collectionName = "testEntityProperties" + System.currentTimeMillis(); + String entityName = "testEntity1"; + + //should set properties for a given object, overwriting properties that exist and creating those that don\'t + UsergridEntity entity = new UsergridEntity(collectionName,entityName); + entity.save(); + + ArrayList<Object> lenArr = new ArrayList<>(); + lenArr.add(1); + lenArr.add(2); + lenArr.add(3); + lenArr.add(4); + entity.putProperty("lenArray", lenArr); + entity.save(); + + ArrayList<Object> lenArr2 = new ArrayList<>(); + lenArr2.add(6); + lenArr2.add(7); + + entity.insert("lenArray", lenArr2, 6); + entity.save(); + + UsergridEntity eLookUp = Usergrid.GET(collectionName, entityName).first(); + assertNotNull("The entity returned is not null.", eLookUp); + + ArrayNode toCompare = new ArrayNode(JsonNodeFactory.instance); + toCompare.add(1).add(2).add(3).add(4).add(6).add(7); + assertEquals("The two arrays should be equal.", eLookUp.getJsonNodeProperty("lenArray"),toCompare); + + //should merge an array of values into an existing array at the specified index + lenArr = new ArrayList<>(); + lenArr.add(1); + lenArr.add(2); + lenArr.add(3); + lenArr.add(4); + + entity.putProperty("lenArray", lenArr); + entity.save(); + + lenArr2 = new ArrayList<>(); + lenArr2.add(5); + lenArr2.add(6); + lenArr2.add(7); + lenArr2.add(8); + + entity.insert("lenArray", lenArr2, 2); + entity.save(); + + eLookUp = Usergrid.GET(collectionName, entityName).first(); + assertNotNull("The entity returned is not null.", eLookUp); + + toCompare = new ArrayNode(JsonNodeFactory.instance); + toCompare.add(1).add(2).add(5).add(6).add(7).add(8).add(3).add(4); + assertEquals("The two arrays should be equal.", eLookUp.getJsonNodeProperty("lenArray"),toCompare); + + //should convert an existing value into an array when inserting a second value + entity.putProperty("foo", "test"); + entity.insert("foo", "test1", 1); + entity.save(); + + eLookUp = Usergrid.GET(collectionName, entityName).first(); + assertNotNull("The entity returned is not null.", eLookUp); + + toCompare = new ArrayNode(JsonNodeFactory.instance); + toCompare.add("test").add("test1"); + assertEquals("The two arrays should be equal.", eLookUp.getJsonNodeProperty("foo"),toCompare); + + //should create a new array when a property does not exist + entity.insert("foo1", "test2", 1); + entity.save(); + + eLookUp = Usergrid.GET(collectionName, entityName).first(); + assertNotNull("The entity returned is not null.", eLookUp); + + toCompare = new ArrayNode(JsonNodeFactory.instance); + toCompare.add("test2"); + assertEquals("The two arrays should be equal.", eLookUp.getJsonNodeProperty("foo1"),toCompare); + + //should gracefully handle index out of positive range + entity.putProperty("ArrayIndex", "test1"); + entity.insert("ArrayIndex", "test2", 1000); + entity.save(); + + eLookUp = Usergrid.GET(collectionName, entityName).first(); + assertNotNull("The entity returned is not null.", eLookUp); + + toCompare = new ArrayNode(JsonNodeFactory.instance); + toCompare.add("test1").add("test2"); + assertEquals("The two arrays should be equal.", eLookUp.getJsonNodeProperty("ArrayIndex"),toCompare); + + //should gracefully handle index out of negative range + entity.insert("ArrayIndex", "test3", -1000); + entity.save(); + + eLookUp = Usergrid.GET(collectionName, entityName).first(); + assertNotNull("The entity returned is not null.", eLookUp); + + toCompare = new ArrayNode(JsonNodeFactory.instance); + toCompare.add("test3").add("test1").add("test2"); + assertEquals("The two arrays should be equal.", eLookUp.getJsonNodeProperty("ArrayIndex"),toCompare); + } + + @Test + public void testEntityConnectDisconnectGetConnections() { + String collectionName = "testEntityProperties" + System.currentTimeMillis(); + String entityOneName = "testEntity1"; + String entityTwoName = "testEntity2"; + + UsergridEntity entityOne = new UsergridEntity(collectionName,entityOneName); + entityOne.putProperty("color","red"); + entityOne.putProperty("shape","square"); + entityOne.save(); + + UsergridEntity entityTwo = new UsergridEntity(collectionName,entityTwoName); + entityTwo.putProperty("color","green"); + entityTwo.putProperty("shape","circle"); + entityTwo.save(); + + assertNotNull(entityOne.getUuid()); + assertNotNull(entityTwo.getUuid()); + assertNotNull(entityOne.getName()); + assertNotNull(entityTwo.getName()); + assertNotNull(entityOne.uuidOrName()); + assertNotNull(entityTwo.uuidOrName()); + + //should connect entities by passing a target UsergridEntity object as a parameter + entityOne.connect("likes", entityTwo); + entityOne.save(); + + UsergridEntity eLookUpConnectedEntity = entityOne.getConnections(UsergridDirection.OUT, "likes").first(); + assertNotNull("The connected entity returned is not null.", eLookUpConnectedEntity); + + assertEquals("The entity name should be equals.", eLookUpConnectedEntity.getName(),entityTwoName); + + eLookUpConnectedEntity = entityTwo.getConnections(UsergridDirection.IN, "likes").first(); + assertNotNull("The connected entity returned is not null.", eLookUpConnectedEntity); + assertEquals("The entity name should be equals.", eLookUpConnectedEntity.getName(),entityOneName); + + entityOne.disconnect("likes", entityTwo); + entityOne.save(); + + eLookUpConnectedEntity = entityTwo.getConnections(UsergridDirection.IN, "likes").first(); + assertNull("The entity returned is not null.", eLookUpConnectedEntity); + + //should connect entities by passing target uuid as a parameter + Usergrid.connect(entityOne.getType(),entityOne.getUuid(),"visited",entityTwo.getUuid()); + entityOne.save(); + + eLookUpConnectedEntity = entityOne.getConnections(UsergridDirection.OUT, "visited").first(); + assertNotNull("The connected entity returned is not null.", eLookUpConnectedEntity); + assertEquals("The entity name should be equals.", eLookUpConnectedEntity.getName(),entityTwoName); + + Usergrid.disconnect(entityOne.getType(),entityOne.getUuid(),"visited",entityTwo.getUuid()); + entityOne.save(); + + eLookUpConnectedEntity = entityOne.getConnections(UsergridDirection.OUT, "visited").first(); + assertNull("The entity returned is not null.", eLookUpConnectedEntity); + + //should connect entities by passing target type and name as parameters + Usergrid.connect(entityOne.getType(),entityOne.getUuid(),"revisit",entityTwo.getType(),entityTwo.getName()); + entityOne.save(); + + eLookUpConnectedEntity = entityOne.getConnections(UsergridDirection.OUT, "revisit").first(); + assertNotNull("The connected entity returned is not null.", eLookUpConnectedEntity); + assertEquals("The entity name should be equals.", eLookUpConnectedEntity.getName(),entityTwoName); + + Usergrid.disconnect(entityOne.getType(),entityOne.getUuid(),"revisit",entityTwo.getType(),entityTwo.getName()); + entityOne.save(); + + eLookUpConnectedEntity = entityOne.getConnections(UsergridDirection.OUT, "revisit").first(); + assertNull("The entity returned is not null.", eLookUpConnectedEntity); + } +} http://git-wip-us.apache.org/repos/asf/usergrid/blob/2e127e62/sdks/java/src/test/java/org/apache/usergrid/client/QueryTestCase.java ---------------------------------------------------------------------- diff --git a/sdks/java/src/test/java/org/apache/usergrid/client/QueryTestCase.java b/sdks/java/src/test/java/org/apache/usergrid/client/QueryTestCase.java new file mode 100644 index 0000000..f013134 --- /dev/null +++ b/sdks/java/src/test/java/org/apache/usergrid/client/QueryTestCase.java @@ -0,0 +1,194 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.usergrid.client; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.DoubleNode; +import org.apache.usergrid.java.client.Usergrid; +import org.apache.usergrid.java.client.auth.UsergridAppAuth; +import org.apache.usergrid.java.client.model.UsergridEntity; +import org.apache.usergrid.java.client.query.UsergridQuery; +import org.apache.usergrid.java.client.response.UsergridResponse; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.*; + +public class QueryTestCase { + + public static final String COLLECTION = "shapes"; + + public static float distFrom(float lat1, float lng1, float lat2, float lng2) { + double earthRadius = 6371000; //meters + double dLat = Math.toRadians(lat2 - lat1); + double dLng = Math.toRadians(lng2 - lng1); + double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.sin(dLng / 2) * Math.sin(dLng / 2); + double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); + return (float) (earthRadius * c); + } + + @Before + public void before() { + Usergrid.initSharedInstance(SDKTestConfiguration.ORG_NAME, SDKTestConfiguration.APP_NAME, SDKTestConfiguration.USERGRID_URL, SDKTestConfiguration.authFallBack); + Usergrid.authenticateApp(new UsergridAppAuth(SDKTestConfiguration.APP_CLIENT_ID, SDKTestConfiguration.APP_CLIENT_SECRET)); + } + + @After + public void after() { + Usergrid.reset(); + } + + /** + * Test a basic set of queries where there is inclusion and exclusion based on + * two fields + */ + @Test + public void testBasicQuery() { + + UsergridQuery qDelete = new UsergridQuery(COLLECTION); + Usergrid.DELETE(qDelete); + + Map<String, UsergridEntity> entityMapByUUID = SDKTestUtils.createColorShapes(COLLECTION); + Map<String, UsergridEntity> entityMapByName = new HashMap<>(entityMapByUUID.size()); + + for (Map.Entry<String, UsergridEntity> uuidEntity : entityMapByUUID.entrySet()) { + entityMapByName.put(uuidEntity.getValue().getName(), uuidEntity.getValue()); + } + + SDKTestUtils.indexSleep(); + + Map<String, String> fields = new HashMap<>(7); + fields.put("red", "square"); + fields.put("blue", "circle"); + fields.put("yellow", "triangle"); + + for (Map.Entry<String, String> entry : fields.entrySet()) { + UsergridEntity targetEntity = entityMapByName.get(entry.getKey() + entry.getValue()); + + UsergridResponse response = Usergrid.GET(new UsergridQuery(COLLECTION).eq("color", entry.getKey())); + assertNotNull("entities returned should not be null.", response.getEntities()); + assertTrue("query for " + entry.getKey() + " shape should return 1, not: " + response.getEntities().size(), response.getEntities().size() == 1); + + UsergridEntity responseEntity = response.first(); + assertNotNull("first entity should not be null.", responseEntity); + assertEquals("query for " + entry.getKey() + " shape should the right UUID", responseEntity.getUuid(),targetEntity.getUuid()); + } + Usergrid.DELETE(qDelete); + } + + /** + * Test that geolocation is working as expected with different ranges and radius + * also test that results are sorted ascending by distance from the specified point + */ + @Test + public void testGeoQuery() { + + String collectionName = "sdkTestLocation"; + + UsergridQuery deleteQuery = new UsergridQuery(collectionName); + Usergrid.DELETE(deleteQuery); + + ArrayList<UsergridEntity> entities = new ArrayList<>(); + UsergridEntity apigeeOffice = new UsergridEntity(collectionName,"Apigee Office"); + apigeeOffice.setLocation(37.334115, -121.894340); + entities.add(apigeeOffice); + + UsergridEntity amicis = new UsergridEntity(collectionName,"Amicis"); + amicis.setLocation(37.335616, -121.894168); + entities.add(amicis); + + UsergridEntity sanPedroMarket = new UsergridEntity(collectionName,"SanPedroMarket"); + sanPedroMarket.setLocation(37.336499, -121.894356); + entities.add(sanPedroMarket); + + UsergridEntity saintJamesPark = new UsergridEntity(collectionName,"saintJamesPark"); + saintJamesPark.setLocation(37.339079, -121.891422); + entities.add(saintJamesPark); + + UsergridEntity sanJoseNews = new UsergridEntity(collectionName,"sanJoseNews"); + sanJoseNews.setLocation(37.337812, -121.890784); + entities.add(sanJoseNews); + + UsergridEntity deAnza = new UsergridEntity(collectionName,"deAnza"); + deAnza.setLocation(37.334370, -121.895081); + entities.add(deAnza); + + Usergrid.POST(entities); + + SDKTestUtils.indexSleep(); + + float centerLat = 37.334110f; + float centerLon = -121.894340f; + + // Test a large distance + UsergridResponse queryResponse = Usergrid.GET(new UsergridQuery(collectionName).locationWithin(611.00000, centerLat, centerLon)); + assertNotNull(queryResponse.getEntities()); + + float lastDistanceFrom = 0; + for (UsergridEntity entity : queryResponse.getEntities()) { + + JsonNode locationNode = entity.getEntityProperty("location"); + assertNotNull("location node should not be null", locationNode); + + DoubleNode lat = (DoubleNode) locationNode.get("latitude"); + DoubleNode lon = (DoubleNode) locationNode.get("longitude"); + + float distanceFrom = distFrom(centerLat, centerLon, lat.floatValue(), lon.floatValue()); + System.out.println("Entity " + entity.getName() + " is " + distanceFrom + " away"); + + assertTrue("Entity " + entity.getName() + " was included but is not within specified distance (" + distanceFrom + ")", distanceFrom <= 611.0); + + if (lastDistanceFrom != 0) { + assertTrue("GEO results are not sorted by distance ascending: expected " + lastDistanceFrom + " <= " + distanceFrom, lastDistanceFrom <= distanceFrom); + } + + lastDistanceFrom = distanceFrom; + } + + // Test a small distance + queryResponse = Usergrid.GET(new UsergridQuery(collectionName).locationWithin(150, centerLat, centerLon)); + assertNotNull(queryResponse.getEntities()); + + lastDistanceFrom = 0; + for (UsergridEntity entity : queryResponse.getEntities()) { + + JsonNode locationNode = entity.getEntityProperty("location"); + assertNotNull("location node should not be null", locationNode); + + DoubleNode lat = (DoubleNode) locationNode.get("latitude"); + DoubleNode lon = (DoubleNode) locationNode.get("longitude"); + + float distanceFrom = distFrom(centerLat, centerLon, lat.floatValue(), lon.floatValue()); + System.out.println("Entity " + entity.getName() + " is " + distanceFrom + " away"); + + assertTrue("Entity " + entity.getName() + " was included but is not within specified distance (" + distanceFrom + ")", distanceFrom <= 150); + + if (lastDistanceFrom != 0) { + assertTrue("GEO results are not sorted by distance ascending: expected " + lastDistanceFrom + " <= " + distanceFrom, lastDistanceFrom <= distanceFrom); + } + + lastDistanceFrom = distanceFrom; + } + + Usergrid.DELETE(deleteQuery); + } +} http://git-wip-us.apache.org/repos/asf/usergrid/blob/2e127e62/sdks/java/src/test/java/org/apache/usergrid/client/SDKTestConfiguration.java ---------------------------------------------------------------------- diff --git a/sdks/java/src/test/java/org/apache/usergrid/client/SDKTestConfiguration.java b/sdks/java/src/test/java/org/apache/usergrid/client/SDKTestConfiguration.java new file mode 100644 index 0000000..8663326 --- /dev/null +++ b/sdks/java/src/test/java/org/apache/usergrid/client/SDKTestConfiguration.java @@ -0,0 +1,38 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.usergrid.client; + +import org.apache.usergrid.java.client.UsergridEnums.UsergridAuthMode; + +public class SDKTestConfiguration { + public static final String APP_CLIENT_ID = "b3U6THNcevskEeOQZLcUROUUVA"; //"YXA6_j0WsfFCEeWKoy6txsCOfA" ; + public static final String APP_CLIENT_SECRET = "b3U6RZHYznP28xieBzQPackFPmmnevU"; //"YXA6jg8x4wjq1AAyQBKtn4bRd1l0gJ8"; // + + public static final String APP_UserName = "rwalsh"; //"test";// //"b3U66ne33W4OEeWXmAIj6QFb-Q"; + public static final String APP_Password = "Apigee123"; //"test";//"b3U6PxbpQiTrXKCWu0n1CjK1uTZXuG4"; + public static final String USERGRID_URL = "https://api.usergrid.com/"; + public static final String ORG_NAME = "rwalsh"; + public static final String APP_NAME = "sandbox"; + + public static UsergridAuthMode authFallBack = UsergridAuthMode.APP; + +// public static final String APP_CLIENT_ID = "YXA61n2kpFffEeWs9QLknKqhHw"; +// public static final String APP_CLIENT_SECRET = "YXA69_aRW1IHLgMTUUYSitsGwOLY8uQ"; +// public static final String USERGRID_URL = "https://fhirsandbox-prod.apigee.net/appservices"; +// public static final String ORG_NAME = "usergrid"; +// public static final String APP_NAME = "sandbox"; +}