http://git-wip-us.apache.org/repos/asf/usergrid/blob/2e127e62/sdks/java/src/main/java/org/apache/usergrid/java/client/entities/User.java ---------------------------------------------------------------------- diff --git a/sdks/java/src/main/java/org/apache/usergrid/java/client/entities/User.java b/sdks/java/src/main/java/org/apache/usergrid/java/client/entities/User.java deleted file mode 100644 index 0046ab2..0000000 --- a/sdks/java/src/main/java/org/apache/usergrid/java/client/entities/User.java +++ /dev/null @@ -1,158 +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.entities; - -import static com.fasterxml.jackson.databind.annotation.JsonSerialize.Inclusion.NON_NULL; -import static org.apache.usergrid.java.client.utils.JsonUtils.getBooleanProperty; -import static org.apache.usergrid.java.client.utils.JsonUtils.getStringProperty; -import static org.apache.usergrid.java.client.utils.JsonUtils.setBooleanProperty; -import static org.apache.usergrid.java.client.utils.JsonUtils.setStringProperty; - -import java.util.List; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -public class User extends Entity { - - public final static String ENTITY_TYPE = "user"; - - public final static String PROPERTY_USERNAME = "username"; - public final static String PROPERTY_EMAIL = "email"; - public final static String PROPERTY_NAME = "name"; - public final static String PROPERTY_FIRSTNAME = "firstname"; - public final static String PROPERTY_MIDDLENAME = "middlename"; - public final static String PROPERTY_LASTNAME = "lastname"; - public final static String PROPERTY_ACTIVATED = "activated"; - public final static String PROPERTY_PICTURE = "picture"; - public final static String PROPERTY_DISABLED = "disabled"; - - public User() { - super(); - setType(ENTITY_TYPE); - } - - public User(Entity entity) { - super(); - properties = entity.properties; - setType(ENTITY_TYPE); - } - - @Override - @JsonIgnore - public String getNativeType() { - return ENTITY_TYPE; - } - - @Override - @JsonIgnore - public List<String> getPropertyNames() { - List<String> properties = super.getPropertyNames(); - properties.add(PROPERTY_USERNAME); - properties.add(PROPERTY_EMAIL); - properties.add(PROPERTY_NAME); - properties.add(PROPERTY_FIRSTNAME); - properties.add(PROPERTY_MIDDLENAME); - properties.add(PROPERTY_LASTNAME); - properties.add(PROPERTY_ACTIVATED); - properties.add(PROPERTY_PICTURE); - properties.add(PROPERTY_DISABLED); - return properties; - } - - @JsonSerialize(include = NON_NULL) - public String getUsername() { - return getStringProperty(properties, PROPERTY_USERNAME); - } - - public void setUsername(String username) { - setStringProperty(properties, PROPERTY_USERNAME, username); - } - - @JsonSerialize(include = NON_NULL) - public String getName() { - return getStringProperty(properties, PROPERTY_NAME); - } - - public void setName(String name) { - setStringProperty(properties, PROPERTY_NAME, name); - } - - @JsonSerialize(include = NON_NULL) - public String getEmail() { - return getStringProperty(properties, PROPERTY_EMAIL); - } - - public void setEmail(String email) { - setStringProperty(properties, PROPERTY_EMAIL, email); - } - - @JsonSerialize(include = NON_NULL) - public Boolean isActivated() { - return getBooleanProperty(properties, PROPERTY_ACTIVATED); - } - - public void setActivated(Boolean activated) { - setBooleanProperty(properties, PROPERTY_ACTIVATED, activated); - } - - @JsonSerialize(include = NON_NULL) - public Boolean isDisabled() { - return getBooleanProperty(properties, PROPERTY_DISABLED); - } - - public void setDisabled(Boolean disabled) { - setBooleanProperty(properties, PROPERTY_DISABLED, disabled); - } - - @JsonSerialize(include = NON_NULL) - public String getFirstname() { - return getStringProperty(properties, PROPERTY_FIRSTNAME); - } - - public void setFirstname(String firstname) { - setStringProperty(properties, PROPERTY_FIRSTNAME, firstname); - } - - @JsonSerialize(include = NON_NULL) - public String getMiddlename() { - return getStringProperty(properties, PROPERTY_MIDDLENAME); - } - - public void setMiddlename(String middlename) { - setStringProperty(properties, PROPERTY_MIDDLENAME, middlename); - } - - @JsonSerialize(include = NON_NULL) - public String getLastname() { - return getStringProperty(properties, PROPERTY_LASTNAME); - } - - public void setLastname(String lastname) { - setStringProperty(properties, PROPERTY_LASTNAME, lastname); - } - - @JsonSerialize(include = NON_NULL) - public String getPicture() { - return getStringProperty(properties, PROPERTY_PICTURE); - } - - public void setPicture(String picture) { - setStringProperty(properties, PROPERTY_PICTURE, picture); - } - -}
http://git-wip-us.apache.org/repos/asf/usergrid/blob/2e127e62/sdks/java/src/main/java/org/apache/usergrid/java/client/exception/ClientException.java ---------------------------------------------------------------------- diff --git a/sdks/java/src/main/java/org/apache/usergrid/java/client/exception/ClientException.java b/sdks/java/src/main/java/org/apache/usergrid/java/client/exception/ClientException.java deleted file mode 100644 index 24f27e2..0000000 --- a/sdks/java/src/main/java/org/apache/usergrid/java/client/exception/ClientException.java +++ /dev/null @@ -1,41 +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.exception; - -/** - * Simple wrapper for client exceptions - * @author tnine - * - */ -public class ClientException extends RuntimeException{ - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * @param message - * @param cause - */ - public ClientException(String message, Throwable cause) { - super(message, cause); - } - - - -} http://git-wip-us.apache.org/repos/asf/usergrid/blob/2e127e62/sdks/java/src/main/java/org/apache/usergrid/java/client/exception/UsergridException.java ---------------------------------------------------------------------- diff --git a/sdks/java/src/main/java/org/apache/usergrid/java/client/exception/UsergridException.java b/sdks/java/src/main/java/org/apache/usergrid/java/client/exception/UsergridException.java new file mode 100644 index 0000000..a9b0cf7 --- /dev/null +++ b/sdks/java/src/main/java/org/apache/usergrid/java/client/exception/UsergridException.java @@ -0,0 +1,48 @@ +/* + * 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.exception; + +import org.jetbrains.annotations.NotNull; + +@SuppressWarnings("unused") +public class UsergridException extends RuntimeException { + + private int responseCode; + + public int getResponseCode() { + return responseCode; + } + public void setResponseCode(final int responseCode) { this.responseCode = responseCode; } + + public UsergridException(@NotNull final String message) { + super(message); + } + + public UsergridException(@NotNull final String message, @NotNull final Throwable cause) { + super(message, cause); + } + + public UsergridException(@NotNull final String message, final int responseCode) { + super(message); + this.responseCode = responseCode; + } + + public UsergridException(@NotNull final String message, @NotNull final Throwable cause, final int responseCode) { + super(message, cause); + this.responseCode = responseCode; + } +} http://git-wip-us.apache.org/repos/asf/usergrid/blob/2e127e62/sdks/java/src/main/java/org/apache/usergrid/java/client/model/UsergridDevice.java ---------------------------------------------------------------------- diff --git a/sdks/java/src/main/java/org/apache/usergrid/java/client/model/UsergridDevice.java b/sdks/java/src/main/java/org/apache/usergrid/java/client/model/UsergridDevice.java new file mode 100644 index 0000000..1833afb --- /dev/null +++ b/sdks/java/src/main/java/org/apache/usergrid/java/client/model/UsergridDevice.java @@ -0,0 +1,60 @@ +package org.apache.usergrid.java.client.model; + +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.Map; + +@SuppressWarnings("unused") +public class UsergridDevice extends UsergridEntity { + @NotNull public static String DEVICE_ENTITY_TYPE = "device"; + + @Nullable private String model; + @Nullable private String platform; + @Nullable private String osVersion; + + public UsergridDevice() { + super(DEVICE_ENTITY_TYPE); + } + + public UsergridDevice(@Nullable final String name) { + super(DEVICE_ENTITY_TYPE,name); + } + + public UsergridDevice(@NotNull final Map<String, JsonNode> properties) { + super(DEVICE_ENTITY_TYPE,null,properties); + } + + public UsergridDevice(@Nullable final String name, @NotNull final Map<String, JsonNode> properties) { + super(DEVICE_ENTITY_TYPE,name,properties); + } + + @Nullable @JsonProperty("deviceModel") + public String getModel() { + return this.model; + } + @JsonProperty("deviceModel") + public void setModel(@Nullable final String model) { + this.model = model; + } + + @Nullable @JsonProperty("devicePlatform") + public String getPlatform() { + return this.platform; + } + @JsonProperty("devicePlatform") + public void setPlatform(@Nullable final String platform) { + this.platform = platform; + } + + @Nullable @JsonProperty("deviceOSVersion") + public String getOsVersion() { + return this.osVersion; + } + @JsonProperty("deviceOSVersion") + public void setOsVersion(@Nullable final String osVersion) { + this.osVersion = osVersion; + } +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/usergrid/blob/2e127e62/sdks/java/src/main/java/org/apache/usergrid/java/client/model/UsergridEntity.java ---------------------------------------------------------------------- diff --git a/sdks/java/src/main/java/org/apache/usergrid/java/client/model/UsergridEntity.java b/sdks/java/src/main/java/org/apache/usergrid/java/client/model/UsergridEntity.java new file mode 100644 index 0000000..f1dc622 --- /dev/null +++ b/sdks/java/src/main/java/org/apache/usergrid/java/client/model/UsergridEntity.java @@ -0,0 +1,484 @@ +/* + * 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.model; + +import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectReader; +import com.fasterxml.jackson.databind.node.*; +import org.apache.usergrid.java.client.UsergridEnums.*; +import org.apache.usergrid.java.client.Usergrid; +import org.apache.usergrid.java.client.UsergridClient; +import org.apache.usergrid.java.client.response.UsergridResponse; +import org.apache.usergrid.java.client.utils.JsonUtils; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.io.IOException; +import java.util.*; + +import static org.apache.usergrid.java.client.utils.JsonUtils.*; + +@SuppressWarnings("unused") +public class UsergridEntity { + + @NotNull private static final HashMap<String,Class<? extends UsergridEntity>> subclassMappings = new HashMap<>(); + @NotNull private static final ObjectMapper entityUpdateMapper = new ObjectMapper(); + @NotNull private final ObjectReader entityUpdateReader = entityUpdateMapper.readerForUpdating(this); + + static { + subclassMappings.put("user",UsergridUser.class); + subclassMappings.put("device",UsergridDevice.class); + } + + @NotNull private String type; + @Nullable private String uuid; + @Nullable private String name; + @Nullable private Long created; + @Nullable private Long modified; + + @NotNull private Map<String, JsonNode> properties = new HashMap<>(); + + public UsergridEntity(@JsonProperty("type") @NotNull final String type) { + this.type = type; + } + + public UsergridEntity(@NotNull final String type, @Nullable final String name) { + this(type); + if( name != null ) { + this.name = name; + } + } + + public UsergridEntity(@NotNull final String type, @Nullable final String name, @NotNull final Map<String, JsonNode> properties) { + this(type,name); + this.updatePropertiesWithMap(properties); + } + + @Nullable + public static Class<? extends UsergridEntity> customSubclassForType(@NotNull final String type) { + return UsergridEntity.subclassMappings.get(type); + } + + public void copyAllProperties(@NotNull final UsergridEntity fromEntity) { + try { + this.updatePropertiesWithJsonNode(entityUpdateMapper.valueToTree(fromEntity)); + } catch( IllegalArgumentException e ) { System.out.print("Usergrid Error: Unable to update properties from entity - " + fromEntity.toString()); } + } + + public void updatePropertiesWithMap(@NotNull final Map<String,JsonNode> properties) { + try { + this.updatePropertiesWithJsonNode(entityUpdateMapper.valueToTree(properties)); + } catch( IllegalArgumentException e ) { System.out.print("Usergrid Error: Unable to update properties from map - " + properties.toString()); } + } + + public void updatePropertiesWithJsonNode(@NotNull final JsonNode node) { + try { + entityUpdateReader.readValue(node); + } catch( IOException e ) { System.out.print("Usergrid Error: Unable to update properties from jsonNode - " + node.toString()); } + } + + public static void mapCustomSubclassToType(@NotNull final String type, @NotNull final Class<? extends UsergridEntity> subclass) { + UsergridEntity.subclassMappings.put(type,subclass); + } + + @NotNull @Override public String toString() { + return toJsonString(this); + } + @NotNull public JsonNode toJsonObjectValue() { + return toJsonNode(this); + } + + @JsonIgnore + public boolean isUser() { return (this instanceof UsergridUser || this.getType().equalsIgnoreCase(UsergridUser.USER_ENTITY_TYPE)); } + + @NotNull public String getType() { return this.type; } + private void setType(@NotNull final String type) { this.type = type; } + + @Nullable public String getUuid() { return this.uuid; } + private void setUuid(@NotNull final String uuid) { this.uuid = uuid; } + + @Nullable public String getName() { return this.name; } + protected void setName(@Nullable final String name) { this.name = name; } + + @Nullable public Long getCreated() { return this.created; } + private void setCreated(@NotNull final Long created) { this.created = created; } + + @Nullable public Long getModified() { return this.modified; } + private void setModified(@NotNull final Long modified) { this.modified = modified; } + + public void setLocation(final double latitude, final double longitude) { + ObjectNode rootNode = JsonUtils.createObjectNode(); + rootNode.put("latitude", latitude); + rootNode.put("longitude", longitude); + setObjectProperty(this.properties, "location", rootNode); + } + + @Nullable + public String uuidOrName() { + String uuidOrName = this.getUuid(); + if( uuidOrName == null ) { + uuidOrName = this.getName(); + } + return uuidOrName; + } + + @NotNull + public UsergridResponse reload() { + return this.reload(Usergrid.getInstance()); + } + + @NotNull + public UsergridResponse reload(@NotNull final UsergridClient client) { + String uuidOrName = this.uuidOrName(); + if( uuidOrName == null ) { + return UsergridResponse.fromError(client, "No UUID or name found.", "The entity object must have a `uuid` or `name` assigned."); + } + UsergridResponse response = client.GET(this.getType(), uuidOrName); + if( response.ok() ) { + UsergridEntity responseEntity = response.first(); + if( responseEntity != null ) { + this.copyAllProperties(responseEntity); + } + } + return response; + } + + @NotNull + public UsergridResponse save() { + return this.save(Usergrid.getInstance()); + } + + @NotNull + public UsergridResponse save(@NotNull final UsergridClient client) { + UsergridResponse response; + if( this.getUuid() != null ) { + response = client.PUT(this); + } else { + response = client.POST(this); + } + if( response.ok() ) { + UsergridEntity responseEntity = response.first(); + if( responseEntity != null ) { + this.copyAllProperties(responseEntity); + } + } + return response; + } + + @NotNull + public UsergridResponse remove() { + return this.remove(Usergrid.getInstance()); + } + + @NotNull + public UsergridResponse remove(@NotNull final UsergridClient client) { + return client.DELETE(this); + } + + @NotNull + public UsergridResponse connect(@NotNull final String relationship, @NotNull final UsergridEntity toEntity) { + return this.connect(Usergrid.getInstance(), relationship, toEntity); + } + + @NotNull + public UsergridResponse connect(@NotNull final UsergridClient client, @NotNull final String relationship, @NotNull final UsergridEntity toEntity) { + return client.connect(this,relationship,toEntity); + } + + @NotNull + public UsergridResponse disconnect(@NotNull final String relationship, @NotNull final UsergridEntity fromEntity) { + return this.disconnect(Usergrid.getInstance(), relationship, fromEntity); + } + + @NotNull + public UsergridResponse disconnect(@NotNull final UsergridClient client, @NotNull final String relationship, @NotNull final UsergridEntity fromEntity) { + return client.disconnect(this,relationship,fromEntity); + } + + @NotNull + public UsergridResponse getConnections(@NotNull final UsergridDirection direction, @NotNull final String relationship) { + return this.getConnections(Usergrid.getInstance(),direction,relationship); + } + + @NotNull + public UsergridResponse getConnections(@NotNull final UsergridClient client, @NotNull final UsergridDirection direction, @NotNull final String relationship) { + return client.getConnections(direction,this,relationship); + } + + public void removeProperty(@NotNull final String name) { + putProperty(name, NullNode.getInstance()); + } + + public void removeProperties(@NotNull final List<String> names) { + for( String propertyName : names ) { + this.removeProperty(propertyName); + } + } + + public void putProperty(@NotNull final String name, @NotNull final String value) { + this.putProperty(name, JsonNodeFactory.instance.textNode(value)); + } + public void putProperty(@NotNull final String name, final boolean value) { + this.putProperty(name, JsonNodeFactory.instance.booleanNode(value)); + } + public void putProperty(@NotNull final String name, @NotNull final List value) { + this.putProperty(name, JsonNodeFactory.instance.pojoNode(value)); + } + public void putProperty(@NotNull final String name, final int value) { + this.putProperty(name, JsonNodeFactory.instance.numberNode(value)); + } + public void putProperty(@NotNull final String name, final long value) { + this.putProperty(name, JsonNodeFactory.instance.numberNode(value)); + } + public void putProperty(@NotNull final String name, final float value) { + this.putProperty(name, JsonNodeFactory.instance.numberNode(value)); + } + public void putProperty(@NotNull final String name, @Nullable final JsonNode value) { + UsergridEntityProperties entityProperty = UsergridEntityProperties.fromString(name); + if( entityProperty != null && !entityProperty.isMutableForEntity(this)) { + return; + } + + JsonNode valueNode = value; + if( valueNode == null ) { + valueNode = NullNode.getInstance(); + } + this.updatePropertiesWithMap(Collections.singletonMap(name,valueNode)); + } + public void putProperties(@NotNull final String jsonString) { + try { + JsonNode jsonNode = entityUpdateMapper.readTree(jsonString); + this.putProperties(jsonNode); + } catch( Exception ignore ) {} + } + public void putProperties(@NotNull final Map<String, Object> properties) { + try { + JsonNode jsonNode = entityUpdateMapper.valueToTree(properties); + this.putProperties(jsonNode); + } catch( Exception ignore ) {} + } + public void putProperties(@NotNull final JsonNode jsonNode) { + HashMap<String,JsonNode> propertiesToUpdate = new HashMap<>(); + Iterator<Map.Entry<String,JsonNode>> keys = jsonNode.fields(); + while (keys.hasNext()) { + Map.Entry<String,JsonNode> entry = keys.next(); + String key = entry.getKey(); + UsergridEntityProperties entityProperty = UsergridEntityProperties.fromString(key); + if( entityProperty == null || entityProperty.isMutableForEntity(this) ) { + propertiesToUpdate.put(key,entry.getValue()); + } + } + if( !propertiesToUpdate.isEmpty() ) { + this.updatePropertiesWithMap(propertiesToUpdate); + } + } + + @SuppressWarnings("unchecked") + public void append(@NotNull final String name, @NotNull final Object value) { + this.append(name, (value instanceof List) ? (List<Object>) value : Collections.singletonList(value)); + } + + public void append(@NotNull final String name, @NotNull final List<Object> value) { + this.insert(name, value, Integer.MAX_VALUE); + } + + @SuppressWarnings("unchecked") + public void insert(@NotNull final String name, @NotNull final Object value) { + this.insert(name, (value instanceof List) ? (List<Object>) value : Collections.singletonList(value), 0); + } + + @SuppressWarnings("unchecked") + public void insert(@NotNull final String name, @NotNull final Object value, final int index) { + this.insert(name, (value instanceof List) ? (List<Object>) value : Collections.singletonList(value), index); + } + + public void insert(@NotNull final String name, @NotNull final List<Object> value) { + this.insert(name,value,0); + } + + public void insert(@NotNull final String name, @NotNull final List<Object> value, final int index) { + int indexToInsert = index; + if (indexToInsert < 0) { + indexToInsert = 0; + } + Object propertyValue = this.getEntityProperty(name); + if( propertyValue != null ) { + ArrayList<Object> propertyArrayValue = this.convertToList(propertyValue); + propertyArrayValue = this.insertIntoArray(propertyArrayValue,value,indexToInsert); + this.putProperty(name, propertyArrayValue); + } else { + this.putProperty(name, value); + } + } + + public void pop(@NotNull final String name) { + ArrayList<Object> arrayToPop = this.getArrayToPopOrShift(name); + if( arrayToPop != null && !arrayToPop.isEmpty() ) { + arrayToPop.remove(arrayToPop.size() - 1); + this.putProperty(name, arrayToPop); + } + } + + public void shift(@NotNull final String name) { + ArrayList<Object> arrayToShift = this.getArrayToPopOrShift(name); + if( arrayToShift != null && !arrayToShift.isEmpty() ) { + arrayToShift.remove(0); + this.putProperty(name, arrayToShift); + } + } + + @Nullable + public <T> T getEntityProperty(@NotNull final String name) { + return JsonUtils.getProperty(this.properties, name); + } + + @Nullable + public JsonNode getJsonNodeProperty(@NotNull final String name) { + return this.getProperties().get(name); + } + + @Nullable + public String getStringProperty(@NotNull final String name) { + return JsonUtils.getStringProperty(this.getProperties(), name); + } + + @Nullable + public Boolean getBooleanProperty(@NotNull final String name) { + Boolean booleanValue = null; + Object object = JsonUtils.getProperty(this.getProperties(), name); + if( object instanceof Boolean ) { + booleanValue = (Boolean)object; + } + return booleanValue; + } + + @Nullable + public Number getNumberProperty(@NotNull final String name) { + Number numberValue = null; + Object object = JsonUtils.getProperty(this.getProperties(), name); + if( object instanceof Number ) { + numberValue = (Number)object; + } + return numberValue; + } + + @Nullable + public Integer getIntegerProperty(@NotNull final String name) { + Integer integerValue = null; + Object object = JsonUtils.getProperty(this.getProperties(), name); + if( object instanceof Number ) { + integerValue = ((Number)object).intValue(); + } + return integerValue; + } + + @Nullable + public Float getFloatProperty(@NotNull final String name) { + Float floatValue = null; + Object object = JsonUtils.getProperty(this.getProperties(), name); + if( object instanceof Number ) { + floatValue = ((Number)object).floatValue(); + } + return floatValue; + } + + @Nullable + public Long getLongProperty(@NotNull final String name) { + Long longValue = null; + Object object = JsonUtils.getProperty(this.getProperties(), name); + if( object instanceof Number ) { + longValue = ((Number)object).longValue(); + } + return longValue; + } + + @JsonAnyGetter @NotNull + private Map<String, JsonNode> getProperties() { + return this.properties; + } + + @JsonAnySetter + private void internalPutProperty(@NotNull final String name, @Nullable final JsonNode value) { + if (value == null) { + properties.put(name, NullNode.instance); + } else { + properties.put(name, value); + } + } + + @Nullable + @SuppressWarnings("unchecked") + private ArrayList<Object> getArrayToPopOrShift(@NotNull final String name) { + Object entityProperty = getEntityProperty(name); + ArrayList<Object> arrayToPopOrShift = null; + if (entityProperty instanceof POJONode) { + Object objectValue = ((POJONode) entityProperty).getPojo(); + if (objectValue instanceof List) { + arrayToPopOrShift = new ArrayList<>((List) objectValue); + } else { + arrayToPopOrShift = new ArrayList<>(); + arrayToPopOrShift.add(objectValue); + } + } else if( entityProperty instanceof ArrayNode ) { + arrayToPopOrShift = JsonUtils.convertToArrayList((ArrayNode)entityProperty); + } else if( entityProperty instanceof List ) { + arrayToPopOrShift = new ArrayList<>((List) entityProperty); + } + return arrayToPopOrShift; + } + + @NotNull + private ArrayList<Object> convertToList(@NotNull final Object value) { + ArrayList<Object> arrayList = new ArrayList<>(); + if( value instanceof ArrayNode ) { + arrayList = JsonUtils.convertToArrayList((ArrayNode)value); + } else if (value instanceof POJONode) { + Object objectValue = ((POJONode) value).getPojo(); + if( objectValue instanceof List ) { + arrayList.addAll((List)objectValue); + } else { + arrayList.add(objectValue); + } + } else if (value instanceof List) { + arrayList.addAll((List)value); + } else { + arrayList.add(value); + } + return arrayList; + } + + @NotNull + private ArrayList<Object> insertIntoArray(@NotNull final List<Object> propertyArrayNode, @NotNull final List<Object> arrayToInsert, final int index) { + ArrayList<Object> mergedArray = new ArrayList<>(); + if (propertyArrayNode.size() <= 0 || arrayToInsert.isEmpty()) { + mergedArray.addAll(arrayToInsert); + } else if ( index <= 0 ) { + mergedArray.addAll(arrayToInsert); + mergedArray.addAll(propertyArrayNode); + } else if ( index > 0 ) { + mergedArray.addAll(propertyArrayNode); + if ( index > propertyArrayNode.size() ) { + mergedArray.addAll(arrayToInsert); + } else { + mergedArray.addAll(index,arrayToInsert); + } + } + return mergedArray; + } +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/usergrid/blob/2e127e62/sdks/java/src/main/java/org/apache/usergrid/java/client/model/UsergridUser.java ---------------------------------------------------------------------- diff --git a/sdks/java/src/main/java/org/apache/usergrid/java/client/model/UsergridUser.java b/sdks/java/src/main/java/org/apache/usergrid/java/client/model/UsergridUser.java new file mode 100644 index 0000000..4092a21 --- /dev/null +++ b/sdks/java/src/main/java/org/apache/usergrid/java/client/model/UsergridUser.java @@ -0,0 +1,197 @@ +/* + * 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.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import org.apache.usergrid.java.client.Usergrid; +import org.apache.usergrid.java.client.UsergridClient; +import org.apache.usergrid.java.client.UsergridEnums.*; +import org.apache.usergrid.java.client.auth.UsergridUserAuth; +import org.apache.usergrid.java.client.query.UsergridQuery; +import org.apache.usergrid.java.client.response.UsergridResponse; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.HashMap; + +@SuppressWarnings("unused") +@JsonInclude(JsonInclude.Include.NON_NULL) +public class UsergridUser extends UsergridEntity { + @NotNull public final static String USER_ENTITY_TYPE = "user"; + + @Nullable private UsergridUserAuth userAuth = null; + + @Nullable private String username; + @Nullable private String email; + @Nullable private String password; + @Nullable private String picture; + + private boolean activated = false; + private boolean disabled = false; + + public UsergridUser() { + super(USER_ENTITY_TYPE); + } + + public UsergridUser(@NotNull final String username, @Nullable final String password) { + super(USER_ENTITY_TYPE); + setUsername(username); + setPassword(password); + } + + public UsergridUser(@NotNull final String name, @NotNull final HashMap<String, Object> propertyMap) { + super(USER_ENTITY_TYPE,name); + putProperties(propertyMap); + } + + public UsergridUser(@Nullable final String name, @Nullable final String username, @Nullable final String email, @Nullable final String password) { + super(USER_ENTITY_TYPE,name); + setUsername(username); + setEmail(email); + setPassword(password); + } + + public void setName(@Nullable final String name) { super.setName(name); } + + @Nullable public String getUsername() { return this.username; } + public void setUsername(@Nullable final String username) { this.username = username; } + + @Nullable public String getEmail() { return this.email; } + public void setEmail(@Nullable final String email) { this.email = email; } + + @Nullable public String getPassword() { return this.password; } + public void setPassword(@Nullable final String password) { this.password = password; } + + @Nullable public String setPicture() { return this.picture; } + public void setPicture(@Nullable final String picture) { this.picture = picture; } + + public boolean isActivated() { return this.activated; } + public void setActivated(final boolean activated) { this.activated = activated; } + + public boolean isDisabled() { return this.disabled; } + public void setDisabled(final boolean disabled) { this.disabled = disabled; } + + @Nullable public UsergridUserAuth getUserAuth() { return this.userAuth; } + public void setUserAuth(@Nullable final UsergridUserAuth userAuth) { this.userAuth = userAuth; } + + @Nullable + public String uuidOrUsername() { + String uuidOrUsername = this.getUuid(); + if( uuidOrUsername == null ) { + uuidOrUsername = this.getUsername(); + } + return uuidOrUsername; + } + + @Nullable + public String usernameOrEmail() { + String usernameOrEmail = this.getUsername(); + if( usernameOrEmail == null ) { + usernameOrEmail = this.getEmail(); + } + return usernameOrEmail; + } + + public static boolean checkAvailable(@Nullable final String email, @Nullable final String username) { + return UsergridUser.checkAvailable(Usergrid.getInstance(), email, username); + } + + public static boolean checkAvailable(@NotNull final UsergridClient client, @Nullable final String email, @Nullable final String username) { + if (email == null && username == null) { + throw new IllegalArgumentException("email and username both are null "); + } + UsergridQuery query = new UsergridQuery(USER_ENTITY_TYPE); + if (username != null) { + query.eq(UsergridUserProperties.USERNAME.toString(), username); + } + if (email != null) { + query.or().eq(UsergridUserProperties.EMAIL.toString(), email); + } + return client.GET(query).first() != null; + } + + @NotNull + public UsergridResponse create() { + return this.create(Usergrid.getInstance()); + } + + @NotNull + public UsergridResponse create(@NotNull final UsergridClient client) { + UsergridResponse response = client.POST(this); + UsergridUser createdUser = response.user(); + if( createdUser != null ) { + this.copyAllProperties(createdUser); + } + return response; + } + + @NotNull + public UsergridResponse login(@NotNull final String username, @NotNull final String password) { + return this.login(Usergrid.getInstance(),username,password); + } + + @NotNull + public UsergridResponse login(@NotNull final UsergridClient client, @NotNull final String username, @NotNull final String password) { + UsergridUserAuth userAuth = new UsergridUserAuth(username,password); + UsergridResponse response = client.authenticateUser(userAuth,false); + if( response.ok() ) { + this.userAuth = userAuth; + } + return response; + } + + @NotNull + public UsergridResponse resetPassword(@NotNull final String oldPassword, @NotNull final String newPassword) { + return this.resetPassword(Usergrid.getInstance(),oldPassword,newPassword); + } + + @NotNull + public UsergridResponse resetPassword(@NotNull final UsergridClient client, @NotNull final String oldPassword, @NotNull final String newPassword) { + return client.resetPassword(this,oldPassword,newPassword); + } + + @NotNull + public UsergridResponse reauthenticate() { + return this.reauthenticate(Usergrid.getInstance()); + } + + @NotNull + public UsergridResponse reauthenticate(@NotNull final UsergridClient client) { + return this.userAuth == null ? UsergridResponse.fromError(client, "Invalid UsergridUserAuth.", "No UsergridUserAuth found on the UsergridUser.") : client.authenticateUser(this.userAuth, false); + } + + @NotNull + public UsergridResponse logout() { + return this.logout(Usergrid.getInstance()); + } + + @NotNull + public UsergridResponse logout(@NotNull final UsergridClient client) { + UsergridResponse response; + String uuidOrUsername = this.uuidOrUsername(); + String accessToken = (this.userAuth != null) ? this.userAuth.getAccessToken() : null; + if (uuidOrUsername == null || accessToken == null ) { + response = UsergridResponse.fromError(client, "Logout Failed.", "UUID or Access Token not found on UsergridUser object."); + } else { + response = client.logoutUser(uuidOrUsername, accessToken); + if( response.ok() ) { + this.userAuth = null; + } + } + return response; + } +} http://git-wip-us.apache.org/repos/asf/usergrid/blob/2e127e62/sdks/java/src/main/java/org/apache/usergrid/java/client/query/UsergridQuery.java ---------------------------------------------------------------------- diff --git a/sdks/java/src/main/java/org/apache/usergrid/java/client/query/UsergridQuery.java b/sdks/java/src/main/java/org/apache/usergrid/java/client/query/UsergridQuery.java new file mode 100644 index 0000000..dc359c0 --- /dev/null +++ b/sdks/java/src/main/java/org/apache/usergrid/java/client/query/UsergridQuery.java @@ -0,0 +1,434 @@ +/* + * 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.query; + +import org.apache.usergrid.java.client.UsergridEnums.UsergridQueryOperator; +import org.apache.usergrid.java.client.UsergridEnums.UsergridQuerySortOrder; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.net.URLEncoder; +import java.util.*; + +@SuppressWarnings("unused") +public final class UsergridQuery { + + @NotNull private final ArrayList<String> requirementStrings = new ArrayList<>(); + @NotNull private final ArrayList<String> urlTerms = new ArrayList<>(); + @NotNull private final HashMap<String, UsergridQuerySortOrder> orderClauses = new HashMap<>(); + @NotNull private Integer limit = UsergridQuery.LIMIT_DEFAULT; + @Nullable private String cursor = null; + @Nullable private String fromStringValue = null; + @Nullable private String collectionName = null; + + public UsergridQuery() { + this(null); + } + + public UsergridQuery(@Nullable final String collectionName) { + this.collectionName = collectionName; + this.requirementStrings.add(UsergridQuery.EMPTY_STRING); + } + + private static boolean isUUID(@NotNull final String string) { + try { + UUID uuid = UUID.fromString(string); + return true; + } catch (Exception ex) { + return false; + } + } + + @NotNull + private static String encode(@NotNull final String stringValue) { + String escapedString; + try { + escapedString = URLEncoder.encode(stringValue, UTF8); + } catch (Exception e) { + escapedString = stringValue; + } + return escapedString; + } + + @NotNull + public static String strJoin(@NotNull final List<String> array, @NotNull final String separator) { + StringBuilder stringBuilder = new StringBuilder(); + for (int i = 0, il = array.size(); i < il; i++) { + if (i > 0) { + stringBuilder.append(separator); + } + stringBuilder.append(array.get(i)); + } + return stringBuilder.toString(); + } + + @NotNull + public UsergridQuery fromString(@NotNull final String stringValue) { + this.fromStringValue = stringValue; + return this; + } + + @Nullable + public String getType() { + return this.collectionName; + } + + @Nullable + public String getCollectionName() { + return this.collectionName; + } + + @Nullable + public String getCollection() { + return this.collectionName; + } + + @NotNull + public UsergridQuery type(@Nullable final String type) { + this.collectionName = type; + return this; + } + + @NotNull + public UsergridQuery collection(@Nullable final String collectionName) { + return this.type(collectionName); + } + + @NotNull + public UsergridQuery collectionName(@Nullable final String collectionName) { + return this.type(collectionName); + } + + @NotNull + public UsergridQuery cursor(@Nullable final String value) { + this.cursor = value; + return this; + } + + @NotNull + public UsergridQuery limit(@NotNull final Integer limit) { + this.limit = limit; + return this; + } + + @NotNull + private UsergridQuery addConditionalSeparator(@NotNull final String separator) { + if (!this.requirementStrings.get(0).isEmpty()) { + this.requirementStrings.add(0, separator); + this.requirementStrings.add(0, UsergridQuery.EMPTY_STRING); + } + return this; + } + + @NotNull + public UsergridQuery and() { + return this.addConditionalSeparator(UsergridQuery.AND); + } + + @NotNull + public UsergridQuery or() { + return this.addConditionalSeparator(UsergridQuery.OR); + } + + @NotNull + public UsergridQuery not() { + return this.addConditionalSeparator(UsergridQuery.NOT); + } + + @NotNull + public UsergridQuery sort(@NotNull final String term, @NotNull final UsergridQuerySortOrder sortOrder) { + this.orderClauses.put(term, sortOrder); + return this; + } + + @NotNull + public UsergridQuery ascending(@NotNull final String term) { + return this.asc(term); + } + + @NotNull + public UsergridQuery asc(@NotNull final String term) { + return this.sort(term, UsergridQuerySortOrder.ASC); + } + + @NotNull + public UsergridQuery descending(@NotNull final String term) { + return this.desc(term); + } + + @NotNull + public UsergridQuery desc(@NotNull final String term) { + return this.sort(term, UsergridQuerySortOrder.DESC); + } + + @NotNull + public UsergridQuery contains(@NotNull final String term, @NotNull final String value) { + return this.containsWord(term, value); + } + + @NotNull + public UsergridQuery containsString(@NotNull final String term, @NotNull final String value) { + return this.containsWord(term, value); + } + + @NotNull + public UsergridQuery containsWord(@NotNull final String term, @NotNull final String value) { + return this.addRequirement(term + SPACE + CONTAINS + SPACE + ((UsergridQuery.isUUID(value)) ? EMPTY_STRING : APOSTROPHE) + value + ((UsergridQuery.isUUID(value)) ? EMPTY_STRING : APOSTROPHE)); + } + + @NotNull + public UsergridQuery filter(@NotNull final String term, @NotNull final Object value) { + return this.eq(term, value); + } + + @NotNull + public UsergridQuery equals(@NotNull final String term, @NotNull final Object value) { + return this.eq(term, value); + } + + @NotNull + public UsergridQuery eq(@NotNull final String term, @NotNull final Object value) { + return this.addOperationRequirement(term, UsergridQueryOperator.EQUAL, value); + } + + @NotNull + public UsergridQuery greaterThan(@NotNull final String term, @NotNull final Object value) { + return this.gt(term, value); + } + + @NotNull + public UsergridQuery gt(@NotNull final String term, @NotNull final Object value) { + return this.addOperationRequirement(term, UsergridQueryOperator.GREATER_THAN, value); + } + + @NotNull + public UsergridQuery greaterThanOrEqual(@NotNull final String term, @NotNull final Object value) { + return this.gte(term, value); + } + + @NotNull + public UsergridQuery gte(@NotNull final String term, @NotNull final Object value) { + return this.addOperationRequirement(term, UsergridQueryOperator.GREATER_THAN_EQUAL_TO, value); + } + + @NotNull + public UsergridQuery lessThan(@NotNull final String term, @NotNull final Object value) { + return this.lt(term, value); + } + + @NotNull + public UsergridQuery lt(@NotNull final String term, @NotNull final Object value) { + return this.addOperationRequirement(term, UsergridQueryOperator.LESS_THAN, value); + } + + @NotNull + public UsergridQuery lessThanOrEqual(@NotNull final String term, @NotNull final Object value) { + return this.lte(term, value); + } + + @NotNull + public UsergridQuery lte(@NotNull final String term, @NotNull final Object value) { + return this.addOperationRequirement(term, UsergridQueryOperator.LESS_THAN_EQUAL_TO, value); + } + + @NotNull + public UsergridQuery locationWithin(final double distance, final double latitude, final double longitude) { + return this.addRequirement(LOCATION + SPACE + WITHIN + SPACE + distance + SPACE + OF + SPACE + latitude + SPACE + COMMA + longitude); + } + + @NotNull + public UsergridQuery urlTerm(@NotNull final String term, @NotNull final String equalsValue) { + if (term.equalsIgnoreCase(QL)) { + this.ql(equalsValue); + } else { + this.urlTerms.add(UsergridQuery.encode(term) + EQUALS + UsergridQuery.encode(equalsValue)); + } + return this; + } + + @NotNull + public UsergridQuery ql(@NotNull final String value) { + return this.addRequirement(value); + } + + @NotNull + public UsergridQuery addRequirement(@NotNull final String requirement) { + String requirementString = this.requirementStrings.remove(0); + if (!requirement.isEmpty() && !requirementString.isEmpty()) { + requirementString += SPACE + AND + SPACE; + } + requirementString += requirement; + this.requirementStrings.add(0, requirementString); + return this; + } + + @NotNull + public UsergridQuery addOperationRequirement(@NotNull final String term, @NotNull final UsergridQueryOperator operation, final int intValue) { + return this.addOperationRequirement(term, operation, Integer.valueOf(intValue)); + } + + @NotNull + public UsergridQuery addOperationRequirement(@NotNull final String term, @NotNull final UsergridQueryOperator operation, @NotNull final Object value) { + if (value instanceof String) { + String valueString = value.toString(); + if (!UsergridQuery.isUUID(valueString)) { + valueString = APOSTROPHE + value + APOSTROPHE; + } + return addRequirement(term + SPACE + operation.operatorValue() + SPACE + valueString); + } else { + return addRequirement(term + SPACE + operation.operatorValue() + SPACE + value.toString()); + } + } + + @NotNull + private String constructOrderByString() { + String orderByString = EMPTY_STRING; + if (!this.orderClauses.isEmpty()) { + for (Map.Entry<String, UsergridQuerySortOrder> orderClause : this.orderClauses.entrySet()) { + if (!orderByString.isEmpty()) { + orderByString += COMMA; + } + orderByString += orderClause.getKey() + SPACE + orderClause.getValue().toString(); + } + if (!orderByString.isEmpty()) { + orderByString = SPACE + ORDER_BY + SPACE + orderByString; + } + } + return orderByString; + } + + @NotNull + private String constructURLTermsString() { + String urlTermsString = EMPTY_STRING; + if (!this.urlTerms.isEmpty()) { + urlTermsString = UsergridQuery.strJoin(this.urlTerms, AMPERSAND); + } + return urlTermsString; + } + + @NotNull + private String constructRequirementString() { + ArrayList<String> requirementStrings = new ArrayList<>(this.requirementStrings); + String firstString = requirementStrings.get(0); + if (firstString.isEmpty()) { + requirementStrings.remove(0); + } + String requirementsString = EMPTY_STRING; + if (!requirementStrings.isEmpty()) { + firstString = requirementStrings.get(0); + if (firstString.equalsIgnoreCase(OR) || firstString.equalsIgnoreCase(AND) || firstString.equalsIgnoreCase(NOT)) { + requirementStrings.remove(0); + } + if (!requirementStrings.isEmpty()) { + Collections.reverse(requirementStrings); + requirementsString = UsergridQuery.strJoin(requirementStrings, SPACE); + } + } + return requirementsString; + } + + @NotNull + private String constructURLAppend() { + return this.constructURLAppend(true); + } + + @NotNull + private String constructURLAppend(final boolean autoURLEncode) { + if (this.fromStringValue != null) { + String requirementsString = this.fromStringValue; + if (autoURLEncode) { + requirementsString = UsergridQuery.encode(requirementsString); + } + return QUESTION_MARK + QL + EQUALS + requirementsString; + } + String urlAppend = EMPTY_STRING; + if (this.limit != LIMIT_DEFAULT) { + urlAppend += LIMIT + EQUALS + this.limit.toString(); + } + String urlTermsString = this.constructURLTermsString(); + if (!urlTermsString.isEmpty()) { + if (!urlAppend.isEmpty()) { + urlAppend += AMPERSAND; + } + urlAppend += urlTermsString; + } + if (this.cursor != null && !this.cursor.isEmpty()) { + if (!urlAppend.isEmpty()) { + urlAppend += AMPERSAND; + } + urlAppend += CURSOR + EQUALS + this.cursor; + } + + String requirementsString = this.constructRequirementString(); + if (!requirementsString.isEmpty()) { + requirementsString = SELECT_ALL + SPACE + WHERE + SPACE + requirementsString; + } else { + requirementsString = SELECT_ALL + SPACE; + } + + String orderByString = this.constructOrderByString(); + if (!orderByString.isEmpty()) { + requirementsString += orderByString; + } + if (!requirementsString.isEmpty()) { + if (autoURLEncode) { + requirementsString = UsergridQuery.encode(requirementsString); + } + if (!urlAppend.isEmpty()) { + urlAppend += AMPERSAND; + } + urlAppend += QL + EQUALS + requirementsString; + } + if (!urlAppend.isEmpty()) { + urlAppend = QUESTION_MARK + urlAppend; + } + return urlAppend; + } + + @NotNull + public String build() { + return this.build(true); + } + + @NotNull + public String build(final boolean autoURLEncode) { + return this.constructURLAppend(autoURLEncode); + } + + private static final int LIMIT_DEFAULT = 10; + @NotNull private static final String AMPERSAND = "&"; + @NotNull private static final String AND = "and"; + @NotNull private static final String APOSTROPHE = "'"; + @NotNull private static final String COMMA = ","; + @NotNull private static final String CONTAINS = "contains"; + @NotNull private static final String CURSOR = "cursor"; + @NotNull private static final String EMPTY_STRING = ""; + @NotNull private static final String EQUALS = "="; + @NotNull private static final String LIMIT = "limit"; + @NotNull private static final String LOCATION = "location"; + @NotNull private static final String NOT = "not"; + @NotNull private static final String OF = "of"; + @NotNull private static final String OR = "or"; + @NotNull private static final String ORDER_BY = "order by"; + @NotNull private static final String QL = "ql"; + @NotNull private static final String QUESTION_MARK = "?"; + @NotNull private static final String SELECT_ALL = "select *"; + @NotNull private static final String SPACE = " "; + @NotNull private static final String UTF8 = "UTF-8"; + @NotNull private static final String WHERE = "where"; + @NotNull private static final String WITHIN = "within"; +} http://git-wip-us.apache.org/repos/asf/usergrid/blob/2e127e62/sdks/java/src/main/java/org/apache/usergrid/java/client/response/AggregateCounter.java ---------------------------------------------------------------------- diff --git a/sdks/java/src/main/java/org/apache/usergrid/java/client/response/AggregateCounter.java b/sdks/java/src/main/java/org/apache/usergrid/java/client/response/AggregateCounter.java deleted file mode 100644 index 240d09f..0000000 --- a/sdks/java/src/main/java/org/apache/usergrid/java/client/response/AggregateCounter.java +++ /dev/null @@ -1,52 +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.response; - -import static org.apache.usergrid.java.client.utils.JsonUtils.toJsonString; - -public class AggregateCounter { - - private long timestamp; - private long value; - - public AggregateCounter(long timestamp, long value) { - this.timestamp = timestamp; - this.value = value; - } - - public long getTimestamp() { - return timestamp; - } - - public void setTimestamp(long timestamp) { - this.timestamp = timestamp; - } - - public long getValue() { - return value; - } - - public void setValue(long value) { - this.value = value; - } - - @Override - public String toString() { - return toJsonString(this); - } - -} http://git-wip-us.apache.org/repos/asf/usergrid/blob/2e127e62/sdks/java/src/main/java/org/apache/usergrid/java/client/response/AggregateCounterSet.java ---------------------------------------------------------------------- diff --git a/sdks/java/src/main/java/org/apache/usergrid/java/client/response/AggregateCounterSet.java b/sdks/java/src/main/java/org/apache/usergrid/java/client/response/AggregateCounterSet.java deleted file mode 100644 index 499af3e..0000000 --- a/sdks/java/src/main/java/org/apache/usergrid/java/client/response/AggregateCounterSet.java +++ /dev/null @@ -1,111 +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.response; - -import static org.apache.usergrid.java.client.utils.JsonUtils.toJsonString; - -import java.util.List; -import java.util.UUID; - -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.databind.annotation.JsonSerialize.Inclusion; - -public class AggregateCounterSet { - private String name; - private UUID user; - private UUID group; - private UUID queue; - private String category; - private List<AggregateCounter> values; - - public AggregateCounterSet(String name, UUID user, UUID group, - String category, List<AggregateCounter> values) { - this.name = name; - this.user = user; - this.group = group; - this.category = category; - this.values = values; - } - - public AggregateCounterSet(String name, UUID queue, String category, - List<AggregateCounter> values) { - this.name = name; - setQueue(queue); - this.category = category; - this.values = values; - } - - @JsonSerialize(include = Inclusion.NON_NULL) - public UUID getUser() { - return user; - } - - public void setUser(UUID user) { - this.user = user; - } - - @JsonSerialize(include = Inclusion.NON_NULL) - public UUID getGroup() { - return group; - } - - public void setGroup(UUID group) { - this.group = group; - } - - @JsonSerialize(include = Inclusion.NON_NULL) - public String getCategory() { - return category; - } - - public void setCategory(String category) { - this.category = category; - } - - @JsonSerialize(include = Inclusion.NON_NULL) - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @JsonSerialize(include = Inclusion.NON_NULL) - public List<AggregateCounter> getValues() { - return values; - } - - public void setValues(List<AggregateCounter> values) { - this.values = values; - } - - @JsonSerialize(include = Inclusion.NON_NULL) - public UUID getQueue() { - return queue; - } - - public void setQueue(UUID queue) { - this.queue = queue; - } - - @Override - public String toString() { - return toJsonString(this); - } - -} http://git-wip-us.apache.org/repos/asf/usergrid/blob/2e127e62/sdks/java/src/main/java/org/apache/usergrid/java/client/response/ApiResponse.java ---------------------------------------------------------------------- diff --git a/sdks/java/src/main/java/org/apache/usergrid/java/client/response/ApiResponse.java b/sdks/java/src/main/java/org/apache/usergrid/java/client/response/ApiResponse.java deleted file mode 100644 index a87e293..0000000 --- a/sdks/java/src/main/java/org/apache/usergrid/java/client/response/ApiResponse.java +++ /dev/null @@ -1,421 +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.response; - -import static org.apache.usergrid.java.client.utils.JsonUtils.toJsonString; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.databind.annotation.JsonSerialize.Inclusion; -import org.apache.usergrid.java.client.entities.Entity; -import org.apache.usergrid.java.client.entities.Message; -import org.apache.usergrid.java.client.entities.User; - -public class ApiResponse { - - private String accessToken; - - private String error; - private String errorDescription; - private String errorUri; - private String exception; - - private String path; - private String uri; - private String status; - private long timestamp; - private UUID application; - private List<Entity> entities; - private UUID next; - private String cursor; - private String action; - private List<Object> list; - private Object data; - private Map<String, UUID> applications; - private Map<String, JsonNode> metadata; - private Map<String, List<String>> params; - private List<AggregateCounterSet> counters; - private ClientCredentialsInfo credentials; - - private List<Message> messages; - private List<QueueInfo> queues; - private UUID last; - private UUID queue; - private UUID consumer; - - private User user; - - private final Map<String, JsonNode> properties = new HashMap<String, JsonNode>(); - - public ApiResponse() { - } - - @JsonAnyGetter - public Map<String, JsonNode> getProperties() { - return properties; - } - - @JsonAnySetter - public void setProperty(String key, JsonNode value) { - properties.put(key, value); - } - - @JsonProperty("access_token") - @JsonSerialize(include = Inclusion.NON_NULL) - public String getAccessToken() { - return accessToken; - } - - @JsonProperty("access_token") - public void setAccessToken(String accessToken) { - this.accessToken = accessToken; - } - - @JsonSerialize(include = Inclusion.NON_NULL) - public String getError() { - return error; - } - - public void setError(String error) { - this.error = error; - } - - @JsonSerialize(include = Inclusion.NON_NULL) - @JsonProperty("error_description") - public String getErrorDescription() { - return errorDescription; - } - - @JsonProperty("error_description") - public void setErrorDescription(String errorDescription) { - this.errorDescription = errorDescription; - } - - @JsonSerialize(include = Inclusion.NON_NULL) - @JsonProperty("error_uri") - public String getErrorUri() { - return errorUri; - } - - @JsonProperty("error_uri") - public void setErrorUri(String errorUri) { - this.errorUri = errorUri; - } - - @JsonSerialize(include = Inclusion.NON_NULL) - public String getException() { - return exception; - } - - public void setException(String exception) { - this.exception = exception; - } - - @JsonSerialize(include = Inclusion.NON_NULL) - public String getPath() { - return path; - } - - public void setPath(String path) { - this.path = path; - } - - @JsonSerialize(include = Inclusion.NON_NULL) - public String getUri() { - return uri; - } - - public void setUri(String uri) { - this.uri = uri; - } - - @JsonSerialize(include = Inclusion.NON_NULL) - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public long getTimestamp() { - return timestamp; - } - - public void setTimestamp(long timestamp) { - this.timestamp = timestamp; - } - - @JsonSerialize(include = Inclusion.NON_NULL) - public UUID getApplication() { - return application; - } - - public void setApplication(UUID application) { - this.application = application; - } - - @JsonSerialize(include = Inclusion.NON_NULL) - public List<Entity> getEntities() { - return entities; - } - - public void setEntities(List<Entity> entities) { - this.entities = entities; - } - - public int getEntityCount() { - if (entities == null) { - return 0; - } - return entities.size(); - } - - public Entity getFirstEntity() { - if ((entities != null) && (entities.size() > 0)) { - return entities.get(0); - } - return null; - } - - public <T extends Entity> T getFirstEntity(Class<T> t) { - return Entity.toType(getFirstEntity(), t); - } - - public Entity getLastEntity() { - if ((entities != null) && (entities.size() > 0)) { - return entities.get(entities.size() - 1); - } - return null; - } - - public <T extends Entity> T getLastEntity(Class<T> t) { - return Entity.toType(getLastEntity(), t); - } - - public <T extends Entity> List<T> getEntities(Class<T> t) { - return Entity.toType(entities, t); - } - - @JsonSerialize(include = Inclusion.NON_NULL) - public UUID getNext() { - return next; - } - - public void setNext(UUID next) { - this.next = next; - } - - @JsonSerialize(include = Inclusion.NON_NULL) - public String getCursor() { - return cursor; - } - - public void setCursor(String cursor) { - this.cursor = cursor; - } - - @JsonSerialize(include = Inclusion.NON_NULL) - public String getAction() { - return action; - } - - public void setAction(String action) { - this.action = action; - } - - @JsonSerialize(include = Inclusion.NON_NULL) - public List<Object> getList() { - return list; - } - - public void setList(List<Object> list) { - this.list = list; - } - - @JsonSerialize(include = Inclusion.NON_NULL) - public Object getData() { - return data; - } - - public void setData(Object data) { - this.data = data; - } - - @JsonSerialize(include = Inclusion.NON_NULL) - public Map<String, UUID> getApplications() { - return applications; - } - - public void setApplications(Map<String, UUID> applications) { - this.applications = applications; - } - - @JsonSerialize(include = Inclusion.NON_NULL) - public Map<String, JsonNode> getMetadata() { - return metadata; - } - - public void setMetadata(Map<String, JsonNode> metadata) { - this.metadata = metadata; - } - - @JsonSerialize(include = Inclusion.NON_NULL) - public Map<String, List<String>> getParams() { - return params; - } - - public void setParams(Map<String, List<String>> params) { - this.params = params; - } - - @JsonSerialize(include = Inclusion.NON_NULL) - public List<AggregateCounterSet> getCounters() { - return counters; - } - - public void setCounters(List<AggregateCounterSet> counters) { - this.counters = counters; - } - - @JsonSerialize(include = Inclusion.NON_NULL) - public ClientCredentialsInfo getCredentials() { - return credentials; - } - - public void setCredentials(ClientCredentialsInfo credentials) { - this.credentials = credentials; - } - - @JsonSerialize(include = Inclusion.NON_NULL) - public User getUser() { - return user; - } - - public void setUser(User user) { - this.user = user; - } - - @Override - public String toString() { - return toJsonString(this); - } - - @JsonSerialize(include = Inclusion.NON_NULL) - public List<Message> getMessages() { - return messages; - } - - public void setMessages(List<Message> messages) { - this.messages = messages; - } - - @JsonIgnore - public int getMessageCount() { - if (messages == null) { - return 0; - } - return messages.size(); - } - - @JsonIgnore - public Message getFirstMessage() { - if ((messages != null) && (messages.size() > 0)) { - return messages.get(0); - } - return null; - } - - @JsonIgnore - public Entity getLastMessage() { - if ((messages != null) && (messages.size() > 0)) { - return messages.get(messages.size() - 1); - } - return null; - } - - @JsonSerialize(include = Inclusion.NON_NULL) - public UUID getLast() { - return last; - } - - public void setLast(UUID last) { - this.last = last; - } - - @JsonSerialize(include = Inclusion.NON_NULL) - public List<QueueInfo> getQueues() { - return queues; - } - - public void setQueues(List<QueueInfo> queues) { - this.queues = queues; - } - - @JsonIgnore - public QueueInfo getFirstQueue() { - if ((queues != null) && (queues.size() > 0)) { - return queues.get(0); - } - return null; - } - - @JsonIgnore - public QueueInfo getLastQueue() { - if ((queues != null) && (queues.size() > 0)) { - return queues.get(queues.size() - 1); - } - return null; - } - - @JsonIgnore - public UUID getLastQueueId() { - QueueInfo q = getLastQueue(); - if (q != null) { - return q.getQueue(); - } - return null; - } - - @JsonSerialize(include = Inclusion.NON_NULL) - public UUID getQueue() { - return queue; - } - - public void setQueue(UUID queue) { - this.queue = queue; - } - - @JsonSerialize(include = Inclusion.NON_NULL) - public UUID getConsumer() { - return consumer; - } - - public void setConsumer(UUID consumer) { - this.consumer = consumer; - } - -} http://git-wip-us.apache.org/repos/asf/usergrid/blob/2e127e62/sdks/java/src/main/java/org/apache/usergrid/java/client/response/ClientCredentialsInfo.java ---------------------------------------------------------------------- diff --git a/sdks/java/src/main/java/org/apache/usergrid/java/client/response/ClientCredentialsInfo.java b/sdks/java/src/main/java/org/apache/usergrid/java/client/response/ClientCredentialsInfo.java deleted file mode 100644 index 7ac6b36..0000000 --- a/sdks/java/src/main/java/org/apache/usergrid/java/client/response/ClientCredentialsInfo.java +++ /dev/null @@ -1,58 +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.response; - -import static org.apache.usergrid.java.client.utils.JsonUtils.toJsonString; - -import com.fasterxml.jackson.annotation.JsonProperty; - -public class ClientCredentialsInfo { - - private String id; - private String secret; - - public ClientCredentialsInfo(String id, String secret) { - this.id = id; - this.secret = secret; - } - - @JsonProperty("client_id") - public String getId() { - return id; - } - - @JsonProperty("client_id") - public void setId(String id) { - this.id = id; - } - - @JsonProperty("client_secret") - public String getSecret() { - return secret; - } - - @JsonProperty("client_secret") - public void setSecret(String secret) { - this.secret = secret; - } - - @Override - public String toString() { - return toJsonString(this); - } - -} http://git-wip-us.apache.org/repos/asf/usergrid/blob/2e127e62/sdks/java/src/main/java/org/apache/usergrid/java/client/response/QueueInfo.java ---------------------------------------------------------------------- diff --git a/sdks/java/src/main/java/org/apache/usergrid/java/client/response/QueueInfo.java b/sdks/java/src/main/java/org/apache/usergrid/java/client/response/QueueInfo.java deleted file mode 100644 index 04fe717..0000000 --- a/sdks/java/src/main/java/org/apache/usergrid/java/client/response/QueueInfo.java +++ /dev/null @@ -1,44 +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.response; - -import java.util.UUID; - -public class QueueInfo { - - String path; - UUID queue; - - public QueueInfo() { - } - - public String getPath() { - return path; - } - - public void setPath(String path) { - this.path = path; - } - - public UUID getQueue() { - return queue; - } - - public void setQueue(UUID queue) { - this.queue = queue; - } -} http://git-wip-us.apache.org/repos/asf/usergrid/blob/2e127e62/sdks/java/src/main/java/org/apache/usergrid/java/client/response/UsergridResponse.java ---------------------------------------------------------------------- diff --git a/sdks/java/src/main/java/org/apache/usergrid/java/client/response/UsergridResponse.java b/sdks/java/src/main/java/org/apache/usergrid/java/client/response/UsergridResponse.java new file mode 100644 index 0000000..8618d94 --- /dev/null +++ b/sdks/java/src/main/java/org/apache/usergrid/java/client/response/UsergridResponse.java @@ -0,0 +1,222 @@ +/* + * 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.*; +import com.fasterxml.jackson.databind.JsonNode; +import okhttp3.Headers; +import org.apache.usergrid.java.client.UsergridClient; +import org.apache.usergrid.java.client.UsergridEnums; +import org.apache.usergrid.java.client.UsergridRequest; +import org.apache.usergrid.java.client.model.UsergridEntity; +import org.apache.usergrid.java.client.model.UsergridUser; +import org.apache.usergrid.java.client.query.UsergridQuery; +import org.apache.usergrid.java.client.utils.JsonUtils; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.*; + +import static org.apache.usergrid.java.client.utils.JsonUtils.toJsonString; + +@SuppressWarnings("unused") +@JsonInclude(JsonInclude.Include.NON_NULL) +public class UsergridResponse { + + @Nullable private UsergridClient client; + @NotNull private Map<String, JsonNode> properties = new HashMap<>(); + + private int statusCode = 0; + @Nullable private JsonNode responseJson = null; + @Nullable private String cursor; + @Nullable private List<UsergridEntity> entities; + @Nullable private Map<String, String> headers; + @Nullable private UsergridQuery query; + @Nullable private UsergridResponseError responseError = null; + + @Nullable private String accessToken; + @Nullable private Long expires; + + public boolean ok() { return (statusCode > 0 && statusCode < 400); } + public int count() { return (entities == null) ? 0 : entities.size(); } + public boolean hasNextPage() { return (cursor != null); } + @NotNull @Override public String toString() { + return toJsonString(this); + } + + @Nullable public UsergridEntity first() { return (entities == null || entities.isEmpty()) ? null : entities.get(0); } + @Nullable public UsergridEntity entity() { + return first(); + } + @Nullable public UsergridEntity last() { return (entities == null || entities.isEmpty()) ? null : entities.get(entities.size() - 1); } + + @Nullable + public UsergridUser user() { + UsergridEntity entity = this.first(); + if( entity != null && entity instanceof UsergridUser ) { + return (UsergridUser) entity; + } + return null; + } + + @Nullable + public List<UsergridUser> users() { + ArrayList<UsergridUser> users = null; + if( entities != null && !entities.isEmpty() ) { + for( UsergridEntity entity : entities ) { + if( entity instanceof UsergridUser ) { + if( users == null ) { + users = new ArrayList<>(); + } + users.add((UsergridUser)entity); + } + } + } + return users; + } + + public int getStatusCode() { return this.statusCode; } + + @Nullable @JsonIgnore + public UsergridClient getClient() { + return client; + } + @JsonIgnore public void setClient(@Nullable final UsergridClient client) { this.client = client; } + + @Nullable @JsonIgnore + public JsonNode getResponseJson() { + return responseJson; + } + private void setResponseJson(@Nullable final JsonNode responseJson) {this.responseJson = responseJson; } + + @Nullable @JsonIgnore + public UsergridQuery getQuery() { + return query; + } + private void setQuery(@Nullable final UsergridQuery query) { this.query = query; } + + @Nullable + public UsergridResponseError getResponseError() { + return responseError; + } + private void setResponseError(@Nullable final UsergridResponseError responseError) { this.responseError = responseError; } + + @Nullable + public Map<String, String> getHeaders() { + return headers; + } + private void setHeaders(@Nullable final Map<String, String> headers) { this.headers = headers; } + + @Nullable + public List<UsergridEntity> getEntities() { return entities; } + private void setEntities(@NotNull final List<UsergridEntity> entities) { this.entities = entities; } + + @Nullable @JsonProperty("cursor") + public String getCursor() { + return cursor; + } + @JsonProperty("cursor") + private void setCursor(@NotNull final String cursor) { this.cursor = cursor; } + + @Nullable @JsonProperty("access_token") + public String getAccessToken() { return this.accessToken; } + @JsonProperty("access_token") + private void setAccessToken(@NotNull final String accessToken) { this.accessToken = accessToken; } + + @Nullable @JsonProperty("expires_in") + public Long getExpires() { return this.expires; } + @JsonProperty("expires_in") + private void setExpires(@NotNull final Long expires) { this.expires = expires; } + + @JsonProperty("user") + private void setUser(@NotNull final UsergridUser user) { + if( this.entities == null ) { + this.entities = new ArrayList<>(); + } + this.entities.add(user); + } + + @NotNull @JsonAnyGetter + public Map<String, JsonNode> getProperties() { + return properties; + } + @JsonAnySetter + private void setProperty(@NotNull final String key, @NotNull final JsonNode value) { + properties.put(key, value); + } + + @NotNull + public UsergridResponse loadNextPage() { + UsergridClient client = this.client; + UsergridEntity entity = this.first(); + if( this.hasNextPage() && client != null && entity != null ) { + Map<String, Object> paramsMap = new HashMap<>(); + paramsMap.put("cursor", getCursor()); + UsergridRequest request = new UsergridRequest(UsergridEnums.UsergridHttpMethod.GET, UsergridRequest.APPLICATION_JSON_MEDIA_TYPE, client.clientAppUrl(), paramsMap, null, null, this.getQuery(), client.authForRequests() , entity.getType()); + return client.sendRequest(request); + } else { + return UsergridResponse.fromError(client,"Error Loading Next Page.","Unable to load next page."); + } + } + + @NotNull + public static UsergridResponse fromError(@Nullable final UsergridClient client, @NotNull final String errorName, @NotNull final String errorDescription) { + UsergridResponse response = new UsergridResponse(); + response.client = client; + response.responseError = new UsergridResponseError(errorName,errorDescription); + return response; + } + + @NotNull + public static UsergridResponse fromException(@Nullable final UsergridClient client, @NotNull final Exception ex) { + UsergridResponse response = new UsergridResponse(); + response.client = client; + response.responseError = new UsergridResponseError(ex.getClass().toString(), ex.getMessage(), ex.getCause().toString()); + return response; + } + + @NotNull + public static UsergridResponse fromResponse(@NotNull final UsergridClient client, @NotNull final UsergridRequest request, @NotNull final okhttp3.Response requestResponse) { + UsergridResponse response; + JsonNode responseJson; + try { + String responseJsonString = requestResponse.body().string(); + responseJson = JsonUtils.mapper.readTree(responseJsonString); + } catch ( Exception e ) { + return UsergridResponse.fromException(client,e); + } + if ( responseJson.has("error") ) { + response = new UsergridResponse(); + response.responseError = JsonUtils.fromJsonNode(responseJson,UsergridResponseError.class); + } else { + response = JsonUtils.fromJsonNode(responseJson,UsergridResponse.class); + } + response.client = client; + response.responseJson = responseJson; + response.statusCode = requestResponse.code(); + + Headers responseHeaders = requestResponse.headers(); + HashMap<String,String> headers = new HashMap<>(); + for (int i = 0; i < responseHeaders.size(); i++) { + headers.put(responseHeaders.name(i),responseHeaders.value(i)); + } + + response.headers = headers; + response.query = request.getQuery(); + return response; + } +}