You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@olingo.apache.org by sk...@apache.org on 2014/05/23 12:58:09 UTC
[14/59] [abbrv] [partial] Removing /ODataJClient: merge complete
http://git-wip-us.apache.org/repos/asf/olingo-odata4/blob/19f3792f/ODataJClient/proxy/src/main/java/com/msopentech/odatajclient/proxy/api/impl/Container.java
----------------------------------------------------------------------
diff --git a/ODataJClient/proxy/src/main/java/com/msopentech/odatajclient/proxy/api/impl/Container.java b/ODataJClient/proxy/src/main/java/com/msopentech/odatajclient/proxy/api/impl/Container.java
deleted file mode 100644
index 0f46e35..0000000
--- a/ODataJClient/proxy/src/main/java/com/msopentech/odatajclient/proxy/api/impl/Container.java
+++ /dev/null
@@ -1,522 +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 com.msopentech.odatajclient.proxy.api.impl;
-
-import com.msopentech.odatajclient.engine.client.ODataClient;
-import com.msopentech.odatajclient.engine.communication.header.ODataHeaderValues;
-import com.msopentech.odatajclient.engine.communication.request.UpdateType;
-import com.msopentech.odatajclient.engine.communication.request.batch.ODataBatchRequest;
-import com.msopentech.odatajclient.engine.communication.request.batch.ODataBatchResponseItem;
-import com.msopentech.odatajclient.engine.communication.request.batch.ODataChangeset;
-import com.msopentech.odatajclient.engine.communication.request.batch.ODataChangesetResponseItem;
-import com.msopentech.odatajclient.engine.communication.request.cud.ODataDeleteRequest;
-import com.msopentech.odatajclient.engine.communication.request.cud.ODataEntityUpdateRequest;
-import com.msopentech.odatajclient.engine.communication.request.streamed.ODataMediaEntityUpdateRequest;
-import com.msopentech.odatajclient.engine.communication.request.streamed.ODataStreamUpdateRequest;
-import com.msopentech.odatajclient.engine.communication.response.ODataBatchResponse;
-import com.msopentech.odatajclient.engine.communication.response.ODataEntityCreateResponse;
-import com.msopentech.odatajclient.engine.communication.response.ODataEntityUpdateResponse;
-import com.msopentech.odatajclient.engine.communication.response.ODataResponse;
-import com.msopentech.odatajclient.engine.data.ODataEntity;
-import com.msopentech.odatajclient.engine.data.ODataLink;
-import com.msopentech.odatajclient.engine.data.ODataLinkType;
-import com.msopentech.odatajclient.engine.format.ODataMediaFormat;
-import com.msopentech.odatajclient.engine.uri.URIBuilder;
-import com.msopentech.odatajclient.engine.utils.URIUtils;
-import com.msopentech.odatajclient.proxy.api.AbstractContainer;
-import com.msopentech.odatajclient.proxy.api.EntityContainerFactory;
-import com.msopentech.odatajclient.proxy.api.annotations.NavigationProperty;
-import com.msopentech.odatajclient.proxy.api.context.AttachedEntity;
-import com.msopentech.odatajclient.proxy.api.context.AttachedEntityStatus;
-import com.msopentech.odatajclient.proxy.api.context.EntityLinkDesc;
-import com.msopentech.odatajclient.proxy.utils.EngineUtils;
-import java.io.InputStream;
-import java.lang.reflect.Proxy;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import org.apache.commons.lang3.StringUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-class Container implements AbstractContainer {
-
- private static final long serialVersionUID = -3320312269235907501L;
-
- /**
- * Logger.
- */
- private static final Logger LOG = LoggerFactory.getLogger(Container.class);
-
- private final ODataClient client;
-
- private final EntityContainerFactory factory;
-
- Container(final ODataClient client, final EntityContainerFactory factory) {
- this.client = client;
- this.factory = factory;
- }
-
- /**
- * Transactional changes commit.
- */
- @Override
- public void flush() {
- final ODataBatchRequest request = client.getBatchRequestFactory().getBatchRequest(factory.getServiceRoot());
- final ODataBatchRequest.BatchStreamManager streamManager = request.execute();
- final ODataChangeset changeset = streamManager.addChangeset();
-
- final TransactionItems items = new TransactionItems();
- final List<EntityLinkDesc> delayedUpdates = new ArrayList<EntityLinkDesc>();
-
- int pos = 0;
-
- for (AttachedEntity attachedEntity : EntityContainerFactory.getContext().entityContext()) {
- final AttachedEntityStatus status = attachedEntity.getStatus();
- if (((status != AttachedEntityStatus.ATTACHED
- && status != AttachedEntityStatus.LINKED) || attachedEntity.getEntity().isChanged())
- && !items.contains(attachedEntity.getEntity())) {
- pos++;
- pos = processEntityContext(attachedEntity.getEntity(), pos, items, delayedUpdates, changeset);
- }
- }
-
- processDelayedUpdates(delayedUpdates, pos, items, changeset);
-
- final ODataBatchResponse response = streamManager.getResponse();
-
- if (response.getStatusCode() != 202) {
- throw new IllegalStateException("Operation failed");
- }
-
- final Iterator<ODataBatchResponseItem> iter = response.getBody();
-
- if (!items.isEmpty()) {
- if (!iter.hasNext()) {
- throw new IllegalStateException("Unexpected operation result");
- }
-
- final ODataBatchResponseItem item = iter.next();
- if (!(item instanceof ODataChangesetResponseItem)) {
- throw new IllegalStateException("Unexpected batch response item " + item.getClass().getSimpleName());
- }
-
- final ODataChangesetResponseItem chgres = (ODataChangesetResponseItem) item;
-
- for (Integer changesetItemId : items.sortedValues()) {
- LOG.debug("Expected changeset item {}", changesetItemId);
- final ODataResponse res = chgres.next();
- if (res.getStatusCode() >= 400) {
- throw new IllegalStateException("Transaction failed: " + res.getStatusMessage());
- }
-
- final EntityTypeInvocationHandler handler = items.get(changesetItemId);
-
- if (handler != null) {
- if (res instanceof ODataEntityCreateResponse) {
- LOG.debug("Upgrade created object '{}'", handler);
- handler.setEntity(((ODataEntityCreateResponse) res).getBody());
- } else if (res instanceof ODataEntityUpdateResponse) {
- LOG.debug("Upgrade updated object '{}'", handler);
- handler.setEntity(((ODataEntityUpdateResponse) res).getBody());
- }
- }
- }
- }
-
- EntityContainerFactory.getContext().detachAll();
- }
-
- private void batch(
- final EntityTypeInvocationHandler handler, final ODataEntity entity, final ODataChangeset changeset) {
-
- switch (EntityContainerFactory.getContext().entityContext().getStatus(handler)) {
- case NEW:
- batchCreate(handler, entity, changeset);
- break;
-
- case CHANGED:
- batchUpdate(handler, entity, changeset);
- break;
-
- case DELETED:
- batchDelete(handler, entity, changeset);
- break;
-
- default:
- if (handler.isChanged()) {
- batchUpdate(handler, entity, changeset);
- }
- }
- }
-
- private void batchCreate(
- final EntityTypeInvocationHandler handler, final ODataEntity entity, final ODataChangeset changeset) {
-
- LOG.debug("Create '{}'", handler);
-
- final URIBuilder uriBuilder = client.getURIBuilder(factory.getServiceRoot()).
- appendEntitySetSegment(handler.getEntitySetName());
- changeset.addRequest(client.getCUDRequestFactory().getEntityCreateRequest(uriBuilder.build(), entity));
- }
-
- private void batchUpdateMediaEntity(
- final EntityTypeInvocationHandler handler,
- final URI uri,
- final InputStream input,
- final ODataChangeset changeset) {
-
- LOG.debug("Update media entity '{}'", uri);
-
- final ODataMediaEntityUpdateRequest req =
- client.getStreamedRequestFactory().getMediaEntityUpdateRequest(uri, input);
-
- req.setContentType(StringUtils.isBlank(handler.getEntity().getMediaContentType())
- ? ODataMediaFormat.WILDCARD.toString()
- : ODataMediaFormat.fromFormat(handler.getEntity().getMediaContentType()).toString());
-
- if (StringUtils.isNotBlank(handler.getETag())) {
- req.setIfMatch(handler.getETag());
- }
-
- changeset.addRequest(req);
- }
-
- private void batchUpdateMediaResource(
- final EntityTypeInvocationHandler handler,
- final URI uri,
- final InputStream input,
- final ODataChangeset changeset) {
-
- LOG.debug("Update media entity '{}'", uri);
-
- final ODataStreamUpdateRequest req = client.getStreamedRequestFactory().getStreamUpdateRequest(uri, input);
-
- if (StringUtils.isNotBlank(handler.getETag())) {
- req.setIfMatch(handler.getETag());
- }
-
- changeset.addRequest(req);
- }
-
- private void batchUpdate(
- final EntityTypeInvocationHandler handler,
- final ODataEntity changes,
- final ODataChangeset changeset) {
-
- LOG.debug("Update '{}'", changes.getEditLink());
-
- final ODataEntityUpdateRequest req =
- client.getCUDRequestFactory().getEntityUpdateRequest(UpdateType.PATCH, changes);
- req.setPrefer(ODataHeaderValues.preferReturnContent);
-
- if (StringUtils.isNotBlank(handler.getETag())) {
- req.setIfMatch(handler.getETag());
- }
-
- changeset.addRequest(req);
- }
-
- private void batchUpdate(
- final EntityTypeInvocationHandler handler,
- final URI uri,
- final ODataEntity changes,
- final ODataChangeset changeset) {
-
- LOG.debug("Update '{}'", uri);
-
- final ODataEntityUpdateRequest req =
- client.getCUDRequestFactory().getEntityUpdateRequest(uri, UpdateType.PATCH, changes);
- req.setPrefer(ODataHeaderValues.preferReturnContent);
-
- if (StringUtils.isNotBlank(handler.getETag())) {
- req.setIfMatch(handler.getETag());
- }
-
- changeset.addRequest(req);
- }
-
- private void batchDelete(
- final EntityTypeInvocationHandler handler, final ODataEntity entity, final ODataChangeset changeset) {
-
- LOG.debug("Delete '{}'", entity.getEditLink());
-
- final ODataDeleteRequest req = client.getCUDRequestFactory().getDeleteRequest(URIUtils.getURI(
- factory.getServiceRoot(), entity.getEditLink().toASCIIString()));
-
- if (StringUtils.isNotBlank(handler.getETag())) {
- req.setIfMatch(handler.getETag());
- }
-
- changeset.addRequest(req);
- }
-
- private int processEntityContext(
- final EntityTypeInvocationHandler handler,
- int pos,
- final TransactionItems items,
- final List<EntityLinkDesc> delayedUpdates,
- final ODataChangeset changeset) {
-
- LOG.debug("Process '{}'", handler);
-
- items.put(handler, null);
-
- final ODataEntity entity = handler.getEntity();
- entity.getNavigationLinks().clear();
-
- final AttachedEntityStatus currentStatus = EntityContainerFactory.getContext().entityContext().
- getStatus(handler);
-
- if (AttachedEntityStatus.DELETED != currentStatus) {
- entity.getProperties().clear();
- EngineUtils.addProperties(client, factory.getMetadata(), handler.getPropertyChanges(), entity);
- }
-
- for (Map.Entry<NavigationProperty, Object> property : handler.getLinkChanges().entrySet()) {
- final ODataLinkType type = Collection.class.isAssignableFrom(property.getValue().getClass())
- ? ODataLinkType.ENTITY_SET_NAVIGATION
- : ODataLinkType.ENTITY_NAVIGATION;
-
- final Set<EntityTypeInvocationHandler> toBeLinked = new HashSet<EntityTypeInvocationHandler>();
- final String serviceRoot = factory.getServiceRoot();
-
- for (Object proxy : type == ODataLinkType.ENTITY_SET_NAVIGATION
- ? (Collection) property.getValue() : Collections.singleton(property.getValue())) {
-
- final EntityTypeInvocationHandler target =
- (EntityTypeInvocationHandler) Proxy.getInvocationHandler(proxy);
-
- final AttachedEntityStatus status =
- EntityContainerFactory.getContext().entityContext().getStatus(target);
-
- final URI editLink = target.getEntity().getEditLink();
-
- if ((status == AttachedEntityStatus.ATTACHED || status == AttachedEntityStatus.LINKED)
- && !target.isChanged()) {
- entity.addLink(buildNavigationLink(
- property.getKey().name(),
- URIUtils.getURI(serviceRoot, editLink.toASCIIString()), type));
- } else {
- if (!items.contains(target)) {
- pos = processEntityContext(target, pos, items, delayedUpdates, changeset);
- pos++;
- }
-
- final Integer targetPos = items.get(target);
- if (targetPos == null) {
- // schedule update for the current object
- LOG.debug("Schedule '{}' from '{}' to '{}'", type.name(), handler, target);
- toBeLinked.add(target);
- } else if (status == AttachedEntityStatus.CHANGED) {
- entity.addLink(buildNavigationLink(
- property.getKey().name(),
- URIUtils.getURI(serviceRoot, editLink.toASCIIString()), type));
- } else {
- // create the link for the current object
- LOG.debug("'{}' from '{}' to (${}) '{}'", type.name(), handler, targetPos, target);
-
- entity.addLink(
- buildNavigationLink(property.getKey().name(), URI.create("$" + targetPos), type));
- }
- }
- }
-
- if (!toBeLinked.isEmpty()) {
- delayedUpdates.add(new EntityLinkDesc(property.getKey().name(), handler, toBeLinked, type));
- }
- }
-
- // insert into the batch
- LOG.debug("{}: Insert '{}' into the batch", pos, handler);
- batch(handler, entity, changeset);
-
- items.put(handler, pos);
-
- int startingPos = pos;
-
- if (handler.getEntity().isMediaEntity()) {
-
- // update media properties
- if (!handler.getPropertyChanges().isEmpty()) {
- final URI targetURI = currentStatus == AttachedEntityStatus.NEW
- ? URI.create("$" + startingPos)
- : URIUtils.getURI(factory.getServiceRoot(), handler.getEntity().getEditLink().toASCIIString());
- batchUpdate(handler, targetURI, entity, changeset);
- pos++;
- items.put(handler, pos);
- }
-
- // update media content
- if (handler.getStreamChanges() != null) {
- final URI targetURI = currentStatus == AttachedEntityStatus.NEW
- ? URI.create("$" + startingPos + "/$value")
- : URIUtils.getURI(
- factory.getServiceRoot(), handler.getEntity().getEditLink().toASCIIString() + "/$value");
-
- batchUpdateMediaEntity(handler, targetURI, handler.getStreamChanges(), changeset);
-
- // update media info (use null key)
- pos++;
- items.put(null, pos);
- }
- }
-
- for (Map.Entry<String, InputStream> streamedChanges : handler.getStreamedPropertyChanges().entrySet()) {
- final URI targetURI = currentStatus == AttachedEntityStatus.NEW
- ? URI.create("$" + startingPos) : URIUtils.getURI(
- factory.getServiceRoot(),
- EngineUtils.getEditMediaLink(streamedChanges.getKey(), entity).toASCIIString());
-
- batchUpdateMediaResource(handler, targetURI, streamedChanges.getValue(), changeset);
-
- // update media info (use null key)
- pos++;
- items.put(handler, pos);
- }
-
- return pos;
- }
-
- private ODataLink buildNavigationLink(final String name, final URI uri, final ODataLinkType type) {
- switch (type) {
- case ENTITY_NAVIGATION:
- return client.getObjectFactory().newEntityNavigationLink(name, uri);
-
- case ENTITY_SET_NAVIGATION:
- return client.getObjectFactory().newFeedNavigationLink(name, uri);
-
- default:
- throw new IllegalArgumentException("Invalid link type " + type.name());
- }
- }
-
- private void processDelayedUpdates(
- final List<EntityLinkDesc> delayedUpdates,
- int pos,
- final TransactionItems items,
- final ODataChangeset changeset) {
-
- for (EntityLinkDesc delayedUpdate : delayedUpdates) {
- pos++;
- items.put(delayedUpdate.getSource(), pos);
-
- final ODataEntity changes = client.getObjectFactory().newEntity(delayedUpdate.getSource().getEntity().
- getName());
-
- AttachedEntityStatus status =
- EntityContainerFactory.getContext().entityContext().getStatus(delayedUpdate.getSource());
-
- final URI sourceURI;
- if (status == AttachedEntityStatus.CHANGED) {
- sourceURI = URIUtils.getURI(
- factory.getServiceRoot(),
- delayedUpdate.getSource().getEntity().getEditLink().toASCIIString());
- } else {
- int sourcePos = items.get(delayedUpdate.getSource());
- sourceURI = URI.create("$" + sourcePos);
- }
-
- for (EntityTypeInvocationHandler target : delayedUpdate.getTargets()) {
- status = EntityContainerFactory.getContext().entityContext().getStatus(target);
-
- final URI targetURI;
- if (status == AttachedEntityStatus.CHANGED) {
- targetURI = URIUtils.getURI(
- factory.getServiceRoot(), target.getEntity().getEditLink().toASCIIString());
- } else {
- int targetPos = items.get(target);
- targetURI = URI.create("$" + targetPos);
- }
-
- changes.addLink(delayedUpdate.getType() == ODataLinkType.ENTITY_NAVIGATION
- ? client.getObjectFactory().newEntityNavigationLink(delayedUpdate.getSourceName(), targetURI)
- : client.getObjectFactory().newFeedNavigationLink(delayedUpdate.getSourceName(), targetURI));
-
- LOG.debug("'{}' from {} to {}", new Object[] {
- delayedUpdate.getType().name(), sourceURI, targetURI });
- }
-
- batchUpdate(delayedUpdate.getSource(), sourceURI, changes, changeset);
- }
- }
-
- private class TransactionItems {
-
- private final List<EntityTypeInvocationHandler> keys = new ArrayList<EntityTypeInvocationHandler>();
-
- private final List<Integer> values = new ArrayList<Integer>();
-
- public EntityTypeInvocationHandler get(final Integer value) {
- if (value != null && values.contains(value)) {
- return keys.get(values.indexOf(value));
- } else {
- return null;
- }
- }
-
- public Integer get(final EntityTypeInvocationHandler key) {
- if (key != null && keys.contains(key)) {
- return values.get(keys.indexOf(key));
- } else {
- return null;
- }
- }
-
- public void remove(final EntityTypeInvocationHandler key) {
- if (keys.contains(key)) {
- values.remove(keys.indexOf(key));
- keys.remove(key);
- }
- }
-
- public void put(final EntityTypeInvocationHandler key, final Integer value) {
- // replace just in case of null current value; otherwise add the new entry
- if (key != null && keys.contains(key) && values.get(keys.indexOf(key)) == null) {
- remove(key);
- }
- keys.add(key);
- values.add(value);
- }
-
- public List<Integer> sortedValues() {
- final List<Integer> sortedValues = new ArrayList<Integer>(values);
- Collections.<Integer>sort(sortedValues);
- return sortedValues;
- }
-
- public boolean contains(final EntityTypeInvocationHandler key) {
- return keys.contains(key);
- }
-
- public int size() {
- return keys.size();
- }
-
- public boolean isEmpty() {
- return keys.isEmpty();
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/olingo-odata4/blob/19f3792f/ODataJClient/proxy/src/main/java/com/msopentech/odatajclient/proxy/api/impl/EntityCollectionInvocationHandler.java
----------------------------------------------------------------------
diff --git a/ODataJClient/proxy/src/main/java/com/msopentech/odatajclient/proxy/api/impl/EntityCollectionInvocationHandler.java b/ODataJClient/proxy/src/main/java/com/msopentech/odatajclient/proxy/api/impl/EntityCollectionInvocationHandler.java
deleted file mode 100644
index 7f43d4d..0000000
--- a/ODataJClient/proxy/src/main/java/com/msopentech/odatajclient/proxy/api/impl/EntityCollectionInvocationHandler.java
+++ /dev/null
@@ -1,152 +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 com.msopentech.odatajclient.proxy.api.impl;
-
-import com.msopentech.odatajclient.proxy.api.AbstractEntityCollection;
-import com.msopentech.odatajclient.proxy.api.annotations.Operation;
-import com.msopentech.odatajclient.proxy.utils.ClassUtils;
-import java.io.Serializable;
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Method;
-import java.net.URI;
-import java.util.Collection;
-import java.util.Iterator;
-import org.apache.commons.lang3.ArrayUtils;
-
-public class EntityCollectionInvocationHandler<T extends Serializable>
- extends AbstractInvocationHandler implements AbstractEntityCollection<T> {
-
- private static final long serialVersionUID = 98078202642671726L;
-
- private final Collection<T> items;
-
- private final Class<?> itemRef;
-
- private final String entityContainerName;
-
- private final URI uri;
-
- public EntityCollectionInvocationHandler(final EntityContainerInvocationHandler containerHandler,
- final Collection<T> items, final Class<?> itemRef, final String entityContainerName) {
-
- this(containerHandler, items, itemRef, entityContainerName, null);
- }
-
- public EntityCollectionInvocationHandler(final EntityContainerInvocationHandler containerHandler,
- final Collection<T> items, final Class<?> itemRef, final String entityContainerName, final URI uri) {
-
- super(containerHandler.getClient(), containerHandler);
-
- this.items = items;
- this.itemRef = itemRef;
- this.entityContainerName = entityContainerName;
- this.uri = uri;
- }
-
- @Override
- public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
- final Annotation[] methodAnnots = method.getAnnotations();
-
- if (isSelfMethod(method, args)) {
- return invokeSelfMethod(method, args);
- } else if (!ArrayUtils.isEmpty(methodAnnots) && methodAnnots[0] instanceof Operation) {
- if (this.uri == null) {
- throw new IllegalStateException("This entity collection has not yet been flushed");
- }
-
- final com.msopentech.odatajclient.engine.metadata.edm.v3.EntityContainer container =
- containerHandler.getFactory().getMetadata().getSchema(ClassUtils.getNamespace(itemRef)).
- getEntityContainer(entityContainerName);
- final com.msopentech.odatajclient.engine.metadata.edm.v3.FunctionImport funcImp =
- container.getFunctionImport(((Operation) methodAnnots[0]).name());
-
- return functionImport((Operation) methodAnnots[0], method, args,
- client.getURIBuilder(this.uri.toASCIIString()).
- appendFunctionImportSegment(((Operation) methodAnnots[0]).name()).build(),
- funcImp);
- } else {
- throw new UnsupportedOperationException("Method not found: " + method);
- }
- }
-
- @Override
- public int size() {
- return items.size();
- }
-
- @Override
- public boolean isEmpty() {
- return items.isEmpty();
- }
-
- @Override
- public boolean contains(final Object object) {
- return items.contains(object);
- }
-
- @Override
- public Iterator<T> iterator() {
- return items.iterator();
- }
-
- @Override
- public Object[] toArray() {
- return items.toArray();
- }
-
- @Override
- public <T> T[] toArray(final T[] array) {
- return items.toArray(array);
- }
-
- @Override
- public boolean add(final T element) {
- return items.add(element);
- }
-
- @Override
- public boolean remove(final Object object) {
- return items.remove(object);
- }
-
- @Override
- public boolean containsAll(final Collection<?> collection) {
- return items.containsAll(collection);
- }
-
- @Override
- public boolean addAll(final Collection<? extends T> collection) {
- return items.addAll(collection);
- }
-
- @Override
- public boolean removeAll(final Collection<?> collection) {
- return items.removeAll(collection);
- }
-
- @Override
- public boolean retainAll(final Collection<?> collection) {
- return items.retainAll(collection);
- }
-
- @Override
- public void clear() {
- items.clear();
- }
-}
http://git-wip-us.apache.org/repos/asf/olingo-odata4/blob/19f3792f/ODataJClient/proxy/src/main/java/com/msopentech/odatajclient/proxy/api/impl/EntityContainerInvocationHandler.java
----------------------------------------------------------------------
diff --git a/ODataJClient/proxy/src/main/java/com/msopentech/odatajclient/proxy/api/impl/EntityContainerInvocationHandler.java b/ODataJClient/proxy/src/main/java/com/msopentech/odatajclient/proxy/api/impl/EntityContainerInvocationHandler.java
deleted file mode 100644
index 01896b5..0000000
--- a/ODataJClient/proxy/src/main/java/com/msopentech/odatajclient/proxy/api/impl/EntityContainerInvocationHandler.java
+++ /dev/null
@@ -1,120 +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 com.msopentech.odatajclient.proxy.api.impl;
-
-import com.msopentech.odatajclient.engine.client.ODataV3Client;
-import com.msopentech.odatajclient.engine.uri.URIBuilder;
-import com.msopentech.odatajclient.engine.utils.URIUtils;
-import com.msopentech.odatajclient.proxy.api.EntityContainerFactory;
-import com.msopentech.odatajclient.proxy.api.annotations.EntityContainer;
-import com.msopentech.odatajclient.proxy.api.annotations.Operation;
-import com.msopentech.odatajclient.proxy.utils.ClassUtils;
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Method;
-import java.lang.reflect.Proxy;
-import org.apache.commons.lang3.ArrayUtils;
-
-public class EntityContainerInvocationHandler extends AbstractInvocationHandler {
-
- private static final long serialVersionUID = 7379006755693410764L;
-
- private final EntityContainerFactory factory;
-
- protected final String schemaName;
-
- private final String entityContainerName;
-
- private final boolean defaultEC;
-
- public static EntityContainerInvocationHandler getInstance(
- final ODataV3Client client, final Class<?> ref, final EntityContainerFactory factory) {
-
- final EntityContainerInvocationHandler instance = new EntityContainerInvocationHandler(client, ref, factory);
- instance.containerHandler = instance;
- return instance;
- }
-
- private EntityContainerInvocationHandler(
- final ODataV3Client client, final Class<?> ref, final EntityContainerFactory factory) {
-
- super(client, null);
-
- final Annotation annotation = ref.getAnnotation(EntityContainer.class);
- if (!(annotation instanceof EntityContainer)) {
- throw new IllegalArgumentException(ref.getName()
- + " is not annotated as @" + EntityContainer.class.getSimpleName());
- }
-
- this.factory = factory;
- this.entityContainerName = ((EntityContainer) annotation).name();
- this.defaultEC = ((EntityContainer) annotation).isDefaultEntityContainer();
- this.schemaName = ClassUtils.getNamespace(ref);
- }
-
- EntityContainerFactory getFactory() {
- return factory;
- }
-
- boolean isDefaultEntityContainer() {
- return defaultEC;
- }
-
- String getEntityContainerName() {
- return entityContainerName;
- }
-
- String getSchemaName() {
- return schemaName;
- }
-
- @Override
- @SuppressWarnings("unchecked")
- public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
- if (isSelfMethod(method, args)) {
- return invokeSelfMethod(method, args);
- } else if ("flush".equals(method.getName()) && ArrayUtils.isEmpty(args)) {
- new Container(client, factory).flush();
- return ClassUtils.returnVoid();
- } else {
- final Annotation[] methodAnnots = method.getAnnotations();
- // 1. access top-level entity sets
- if (methodAnnots.length == 0) {
- final Class<?> returnType = method.getReturnType();
-
- return Proxy.newProxyInstance(
- Thread.currentThread().getContextClassLoader(),
- new Class<?>[] { returnType },
- EntitySetInvocationHandler.getInstance(returnType, this));
- } // 2. invoke function imports
- else if (methodAnnots[0] instanceof Operation) {
- final com.msopentech.odatajclient.engine.metadata.edm.v3.EntityContainer container =
- getFactory().getMetadata().getSchema(schemaName).getEntityContainer(entityContainerName);
- final com.msopentech.odatajclient.engine.metadata.edm.v3.FunctionImport funcImp =
- container.getFunctionImport(((Operation) methodAnnots[0]).name());
-
- final URIBuilder uriBuilder = client.getURIBuilder(factory.getServiceRoot()).
- appendFunctionImportSegment(URIUtils.rootFunctionImportURISegment(container, funcImp));
-
- return functionImport((Operation) methodAnnots[0], method, args, uriBuilder.build(), funcImp);
- } else {
- throw new UnsupportedOperationException("Method not found: " + method);
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/olingo-odata4/blob/19f3792f/ODataJClient/proxy/src/main/java/com/msopentech/odatajclient/proxy/api/impl/EntitySetInvocationHandler.java
----------------------------------------------------------------------
diff --git a/ODataJClient/proxy/src/main/java/com/msopentech/odatajclient/proxy/api/impl/EntitySetInvocationHandler.java b/ODataJClient/proxy/src/main/java/com/msopentech/odatajclient/proxy/api/impl/EntitySetInvocationHandler.java
deleted file mode 100644
index b8bb0a1..0000000
--- a/ODataJClient/proxy/src/main/java/com/msopentech/odatajclient/proxy/api/impl/EntitySetInvocationHandler.java
+++ /dev/null
@@ -1,396 +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 com.msopentech.odatajclient.proxy.api.impl;
-
-import com.msopentech.odatajclient.engine.communication.request.retrieve.ODataValueRequest;
-import com.msopentech.odatajclient.engine.communication.response.ODataRetrieveResponse;
-import com.msopentech.odatajclient.engine.data.ODataEntity;
-import com.msopentech.odatajclient.engine.data.ODataEntitySet;
-import com.msopentech.odatajclient.engine.format.ODataValueFormat;
-import com.msopentech.odatajclient.engine.uri.URIBuilder;
-import com.msopentech.odatajclient.proxy.api.AbstractEntityCollection;
-import com.msopentech.odatajclient.proxy.api.AbstractEntitySet;
-import com.msopentech.odatajclient.proxy.api.EntityContainerFactory;
-import com.msopentech.odatajclient.proxy.api.annotations.CompoundKey;
-import com.msopentech.odatajclient.proxy.api.annotations.CompoundKeyElement;
-import com.msopentech.odatajclient.proxy.api.annotations.EntitySet;
-import com.msopentech.odatajclient.proxy.api.annotations.EntityType;
-import com.msopentech.odatajclient.proxy.api.context.AttachedEntityStatus;
-import com.msopentech.odatajclient.proxy.api.context.EntityContext;
-import com.msopentech.odatajclient.proxy.api.context.EntityUUID;
-import com.msopentech.odatajclient.proxy.api.Query;
-import com.msopentech.odatajclient.proxy.utils.ClassUtils;
-import java.io.Serializable;
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Method;
-import java.lang.reflect.ParameterizedType;
-import java.lang.reflect.Proxy;
-import java.lang.reflect.Type;
-import java.net.URI;
-import java.util.AbstractMap;
-import java.util.ArrayList;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeSet;
-import org.apache.commons.lang3.ArrayUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-class EntitySetInvocationHandler<
- T extends Serializable, KEY extends Serializable, EC extends AbstractEntityCollection<T>>
- extends AbstractInvocationHandler
- implements AbstractEntitySet<T, KEY, EC> {
-
- private static final long serialVersionUID = 2629912294765040027L;
-
- /**
- * Logger.
- */
- private static final Logger LOG = LoggerFactory.getLogger(EntitySetInvocationHandler.class);
-
- private final Class<T> typeRef;
-
- private final Class<EC> collTypeRef;
-
- private final String entitySetName;
-
- private final URI uri;
-
- @SuppressWarnings({ "rawtypes", "unchecked" })
- static EntitySetInvocationHandler getInstance(
- final Class<?> ref, final EntityContainerInvocationHandler containerHandler) {
-
- return new EntitySetInvocationHandler(ref, containerHandler);
- }
-
- @SuppressWarnings("unchecked")
- private EntitySetInvocationHandler(
- final Class<?> ref,
- final EntityContainerInvocationHandler containerHandler) {
-
- super(containerHandler.getClient(), containerHandler);
-
- final Annotation annotation = ref.getAnnotation(EntitySet.class);
- if (!(annotation instanceof EntitySet)) {
- throw new IllegalArgumentException("Return type " + ref.getName()
- + " is not annotated as @" + EntitySet.class.getSimpleName());
- }
-
- this.entitySetName = ((EntitySet) annotation).name();
-
- final Type[] abstractEntitySetParams =
- ((ParameterizedType) ref.getGenericInterfaces()[0]).getActualTypeArguments();
-
- this.typeRef = (Class<T>) abstractEntitySetParams[0];
- if (typeRef.getAnnotation(EntityType.class) == null) {
- throw new IllegalArgumentException("Invalid entity '" + typeRef.getSimpleName() + "'");
- }
- this.collTypeRef = (Class<EC>) abstractEntitySetParams[2];
-
- final URIBuilder uriBuilder = client.getURIBuilder(containerHandler.getFactory().getServiceRoot());
-
- if (!containerHandler.isDefaultEntityContainer()) {
- uriBuilder.appendStructuralSegment(containerHandler.getEntityContainerName()).appendStructuralSegment(".");
- }
-
- uriBuilder.appendEntitySetSegment(entitySetName);
- this.uri = uriBuilder.build();
- }
-
- Class<T> getTypeRef() {
- return typeRef;
- }
-
- Class<EC> getCollTypeRef() {
- return collTypeRef;
- }
-
- String getEntitySetName() {
- return entitySetName;
- }
-
- URI getUri() {
- return uri;
- }
-
- @Override
- @SuppressWarnings("unchecked")
- public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
- if (isSelfMethod(method, args)) {
- return invokeSelfMethod(method, args);
- } else if (method.getName().startsWith("new") && ArrayUtils.isEmpty(args)) {
- if (method.getName().endsWith("Collection")) {
- return newEntityCollection(method.getReturnType());
- } else {
- return newEntity(method.getReturnType());
- }
- } else {
- throw new UnsupportedOperationException("Method not found: " + method);
- }
- }
-
- @SuppressWarnings("unchecked")
- private <NE> NE newEntity(final Class<NE> reference) {
- final ODataEntity entity = client.getObjectFactory().newEntity(
- containerHandler.getSchemaName() + "." + ClassUtils.getEntityTypeName(reference));
-
- final EntityTypeInvocationHandler handler = EntityTypeInvocationHandler.getInstance(
- entity, containerHandler.getEntityContainerName(), entitySetName, reference, containerHandler);
- EntityContainerFactory.getContext().entityContext().attachNew(handler);
-
- return (NE) Proxy.newProxyInstance(
- Thread.currentThread().getContextClassLoader(),
- new Class<?>[] { reference },
- handler);
- }
-
- @SuppressWarnings("unchecked")
- private <NEC> NEC newEntityCollection(final Class<NEC> reference) {
- return (NEC) Proxy.newProxyInstance(
- Thread.currentThread().getContextClassLoader(),
- new Class<?>[] { reference },
- new EntityCollectionInvocationHandler<T>(
- containerHandler, new ArrayList<T>(), typeRef, containerHandler.getEntityContainerName()));
- }
-
- @Override
- public Long count() {
- final ODataValueRequest req = client.getRetrieveRequestFactory().
- getValueRequest(client.getURIBuilder(this.uri.toASCIIString()).appendCountSegment().build());
- req.setFormat(ODataValueFormat.TEXT);
- return Long.valueOf(req.execute().getBody().asPrimitive().toString());
- }
-
- @Override
- public Boolean exists(final KEY key) throws IllegalArgumentException {
- boolean result = false;
-
- try {
- result = get(key) != null;
- } catch (Exception e) {
- LOG.error("Could not check existence of {}({})", this.entitySetName, key, e);
- }
-
- return result;
- }
-
- private LinkedHashMap<String, Object> getCompoundKey(final Object key) {
- final Set<CompoundKeyElementWrapper> elements = new TreeSet<CompoundKeyElementWrapper>();
-
- for (Method method : key.getClass().getMethods()) {
- final Annotation annotation = method.getAnnotation(CompoundKeyElement.class);
- if (annotation instanceof CompoundKeyElement) {
- elements.add(new CompoundKeyElementWrapper(
- ((CompoundKeyElement) annotation).name(), method, ((CompoundKeyElement) annotation).position()));
- }
- }
-
- final LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
-
- for (CompoundKeyElementWrapper element : elements) {
- try {
- map.put(element.getName(), element.getMethod().invoke(key));
- } catch (Exception e) {
- LOG.warn("Error retrieving compound key element '{}' value", element.getName(), e);
- }
- }
-
- return map;
- }
-
- @Override
- public T get(KEY key) throws IllegalArgumentException {
- return get(key, typeRef);
- }
-
- @Override
- @SuppressWarnings("unchecked")
- public <S extends T> S get(final KEY key, final Class<S> typeRef) throws IllegalArgumentException {
- if (key == null) {
- throw new IllegalArgumentException("Null key");
- }
-
- final EntityUUID uuid = new EntityUUID(
- ClassUtils.getNamespace(typeRef),
- containerHandler.getEntityContainerName(),
- entitySetName,
- ClassUtils.getNamespace(typeRef) + "." + ClassUtils.getEntityTypeName(typeRef),
- key);
-
- LOG.debug("Ask for '{}({})'", typeRef.getSimpleName(), key);
-
- EntityTypeInvocationHandler handler =
- EntityContainerFactory.getContext().entityContext().getEntity(uuid);
-
- if (handler == null) {
- // not yet attached: search against the service
- try {
- LOG.debug("Search for '{}({})' into the service", typeRef.getSimpleName(), key);
- final URIBuilder uriBuilder = client.getURIBuilder(this.uri.toASCIIString());
-
- if (key.getClass().getAnnotation(CompoundKey.class) == null) {
- LOG.debug("Append key segment '{}'", key);
- uriBuilder.appendKeySegment(key);
- } else {
- LOG.debug("Append compound key segment '{}'", key);
- uriBuilder.appendKeySegment(getCompoundKey(key));
- }
-
- LOG.debug("Execute query '{}'", uriBuilder.toString());
-
- final ODataRetrieveResponse<ODataEntity> res =
- client.getRetrieveRequestFactory().getEntityRequest(uriBuilder.build()).execute();
-
- handler = EntityTypeInvocationHandler.getInstance(res.getBody(), this, typeRef);
- handler.setETag(res.getEtag());
- } catch (Exception e) {
- LOG.info("Entity '" + uuid + "' not found", e);
- }
- } else if (isDeleted(handler)) {
- // object deleted
- LOG.debug("Object '{}({})' has been delete", typeRef.getSimpleName(), uuid);
- handler = null;
- }
-
- return handler == null ? null : (S) Proxy.newProxyInstance(
- Thread.currentThread().getContextClassLoader(),
- new Class<?>[] { typeRef },
- handler);
- }
-
- @SuppressWarnings("unchecked")
- public <S extends T> Map.Entry<List<S>, URI> fetchPartialEntitySet(final URI uri, final Class<S> typeRef) {
- final ODataRetrieveResponse<ODataEntitySet> res =
- client.getRetrieveRequestFactory().getEntitySetRequest(uri).execute();
-
- final ODataEntitySet entitySet = res.getBody();
-
- final List<S> items = new ArrayList<S>(entitySet.getEntities().size());
- for (ODataEntity entity : entitySet.getEntities()) {
- final EntityTypeInvocationHandler handler = EntityTypeInvocationHandler.getInstance(entity, this, typeRef);
-
- final EntityTypeInvocationHandler handlerInTheContext =
- EntityContainerFactory.getContext().entityContext().getEntity(handler.getUUID());
-
- items.add((S) Proxy.newProxyInstance(
- Thread.currentThread().getContextClassLoader(),
- new Class<?>[] { typeRef },
- handlerInTheContext == null ? handler : handlerInTheContext));
- }
-
- return new AbstractMap.SimpleEntry<List<S>, URI>(items, entitySet.getNext());
- }
-
- @SuppressWarnings("unchecked")
- public <S extends T, SEC extends AbstractEntityCollection<S>> SEC fetchWholeEntitySet(
- final URI entitySetURI, final Class<S> typeRef, final Class<SEC> collTypeRef) {
-
- final List<S> items = new ArrayList<S>();
-
- URI nextURI = entitySetURI;
- while (nextURI != null) {
- final Map.Entry<List<S>, URI> entitySet = fetchPartialEntitySet(nextURI, typeRef);
- nextURI = entitySet.getValue();
- items.addAll(entitySet.getKey());
- }
-
- return (SEC) Proxy.newProxyInstance(
- Thread.currentThread().getContextClassLoader(),
- new Class<?>[] { collTypeRef },
- new EntityCollectionInvocationHandler<S>(
- containerHandler, items, typeRef, containerHandler.getEntityContainerName(), entitySetURI));
- }
-
- @Override
- public EC getAll() {
- return getAll(collTypeRef);
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public <S extends T, SEC extends AbstractEntityCollection<S>> SEC getAll(final Class<SEC> collTypeRef) {
- final Class<S> typeRef = (Class<S>) ClassUtils.extractTypeArg(collTypeRef);
-
- final URI entitySetURI = client.getURIBuilder(this.uri.toASCIIString()).appendStructuralSegment(
- ClassUtils.getNamespace(typeRef) + "." + ClassUtils.getEntityTypeName(typeRef)).build();
-
- return fetchWholeEntitySet(entitySetURI, typeRef, collTypeRef);
- }
-
- @Override
- public Query<T, EC> createQuery() {
- return new QueryImpl<T, EC>(this.client, this.collTypeRef, this.uri, this);
- }
-
- @Override
- public <S extends T, SEC extends AbstractEntityCollection<S>> Query<S, SEC> createQuery(
- final Class<SEC> reference) {
-
- return new QueryImpl<S, SEC>(this.client, reference, this.uri, this);
- }
-
- @Override
- public void delete(final KEY key) throws IllegalArgumentException {
- final EntityContext entityContext = EntityContainerFactory.getContext().entityContext();
-
- EntityTypeInvocationHandler entity = entityContext.getEntity(new EntityUUID(
- ClassUtils.getNamespace(typeRef),
- containerHandler.getEntityContainerName(),
- entitySetName,
- ClassUtils.getNamespace(typeRef) + "." + ClassUtils.getEntityTypeName(typeRef),
- key));
-
- if (entity == null) {
- // search for entity
- final T searched = get(key);
- entity = (EntityTypeInvocationHandler) Proxy.getInvocationHandler(searched);
- entityContext.attach(entity, AttachedEntityStatus.DELETED);
- } else {
- entityContext.setStatus(entity, AttachedEntityStatus.DELETED);
- }
- }
-
- @Override
- public <S extends T> void delete(final Iterable<S> entities) {
- final EntityContext entityContext = EntityContainerFactory.getContext().entityContext();
-
- for (T en : entities) {
- final EntityTypeInvocationHandler entity = (EntityTypeInvocationHandler) Proxy.getInvocationHandler(en);
- if (entityContext.isAttached(entity)) {
- entityContext.setStatus(entity, AttachedEntityStatus.DELETED);
- } else {
- entityContext.attach(entity, AttachedEntityStatus.DELETED);
- }
- }
- }
-
- private boolean isDeleted(final EntityTypeInvocationHandler handler) {
- return EntityContainerFactory.getContext().entityContext().getStatus(handler) == AttachedEntityStatus.DELETED;
- }
-
- @Override
- public EntitySetIterator<T, KEY, EC> iterator() {
- return new EntitySetIterator<T, KEY, EC>(
- client.getURIBuilder(this.uri.toASCIIString()).appendStructuralSegment(
- ClassUtils.getNamespace(typeRef) + "." + ClassUtils.getEntityTypeName(typeRef)).build(),
- this);
- }
-}
http://git-wip-us.apache.org/repos/asf/olingo-odata4/blob/19f3792f/ODataJClient/proxy/src/main/java/com/msopentech/odatajclient/proxy/api/impl/EntitySetIterator.java
----------------------------------------------------------------------
diff --git a/ODataJClient/proxy/src/main/java/com/msopentech/odatajclient/proxy/api/impl/EntitySetIterator.java b/ODataJClient/proxy/src/main/java/com/msopentech/odatajclient/proxy/api/impl/EntitySetIterator.java
deleted file mode 100644
index 121d1ff..0000000
--- a/ODataJClient/proxy/src/main/java/com/msopentech/odatajclient/proxy/api/impl/EntitySetIterator.java
+++ /dev/null
@@ -1,85 +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 com.msopentech.odatajclient.proxy.api.impl;
-
-import com.msopentech.odatajclient.proxy.api.AbstractEntityCollection;
-import java.io.Serializable;
-import java.net.URI;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.NoSuchElementException;
-
-class EntitySetIterator<T extends Serializable, KEY extends Serializable, EC extends AbstractEntityCollection<T>>
- implements Iterator<T> {
-
- private final EntitySetInvocationHandler<T, KEY, EC> esi;
-
- private URI next;
-
- private Iterator<T> current;
-
- EntitySetIterator(final URI uri, EntitySetInvocationHandler<T, KEY, EC> esi) {
- this.esi = esi;
- this.next = uri;
- this.current = Collections.<T>emptyList().iterator();
- }
-
- @Override
- public boolean hasNext() {
- boolean res = false;
- if (this.current.hasNext()) {
- res = true;
- } else if (this.next == null) {
- res = false;
- } else {
- goon();
- res = current.hasNext();
- }
- return res;
- }
-
- @Override
- public T next() {
- T res;
- try {
- res = this.current.next();
- } catch (NoSuchElementException e) {
- if (this.next == null) {
- throw e;
- }
- goon();
- res = next();
- }
-
- return res;
- }
-
- @Override
- public void remove() {
- this.current.remove();
- }
-
- private void goon() {
- final Map.Entry<List<T>, URI> entitySet = esi.fetchPartialEntitySet(this.next, this.esi.getTypeRef());
- this.next = entitySet.getValue();
- this.current = entitySet.getKey().iterator();
- }
-}
http://git-wip-us.apache.org/repos/asf/olingo-odata4/blob/19f3792f/ODataJClient/proxy/src/main/java/com/msopentech/odatajclient/proxy/api/impl/EntityTypeInvocationHandler.java
----------------------------------------------------------------------
diff --git a/ODataJClient/proxy/src/main/java/com/msopentech/odatajclient/proxy/api/impl/EntityTypeInvocationHandler.java b/ODataJClient/proxy/src/main/java/com/msopentech/odatajclient/proxy/api/impl/EntityTypeInvocationHandler.java
deleted file mode 100644
index 33ff4bb..0000000
--- a/ODataJClient/proxy/src/main/java/com/msopentech/odatajclient/proxy/api/impl/EntityTypeInvocationHandler.java
+++ /dev/null
@@ -1,578 +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 com.msopentech.odatajclient.proxy.api.impl;
-
-import com.msopentech.odatajclient.engine.communication.request.retrieve.ODataMediaRequest;
-import com.msopentech.odatajclient.engine.communication.response.ODataRetrieveResponse;
-import com.msopentech.odatajclient.engine.data.ODataEntity;
-import com.msopentech.odatajclient.engine.data.ODataInlineEntity;
-import com.msopentech.odatajclient.engine.data.ODataInlineEntitySet;
-import com.msopentech.odatajclient.engine.data.ODataLink;
-import com.msopentech.odatajclient.engine.data.ODataOperation;
-import com.msopentech.odatajclient.engine.data.ODataProperty;
-import com.msopentech.odatajclient.engine.format.ODataMediaFormat;
-import com.msopentech.odatajclient.engine.utils.URIUtils;
-import com.msopentech.odatajclient.proxy.api.AbstractEntityCollection;
-import com.msopentech.odatajclient.proxy.api.context.AttachedEntityStatus;
-import com.msopentech.odatajclient.proxy.api.EntityContainerFactory;
-import com.msopentech.odatajclient.proxy.api.context.EntityContext;
-import com.msopentech.odatajclient.proxy.api.annotations.EntityType;
-import com.msopentech.odatajclient.proxy.api.annotations.Operation;
-import com.msopentech.odatajclient.proxy.api.annotations.NavigationProperty;
-import com.msopentech.odatajclient.proxy.api.annotations.Property;
-import com.msopentech.odatajclient.proxy.api.context.EntityUUID;
-import com.msopentech.odatajclient.proxy.utils.ClassUtils;
-import com.msopentech.odatajclient.proxy.utils.EngineUtils;
-import java.io.InputStream;
-import java.lang.annotation.Annotation;
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.Method;
-import java.lang.reflect.ParameterizedType;
-import java.lang.reflect.Proxy;
-import java.lang.reflect.Type;
-import java.net.URI;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.lang3.ArrayUtils;
-import org.apache.commons.lang3.StringUtils;
-
-public class EntityTypeInvocationHandler extends AbstractInvocationHandler {
-
- private static final long serialVersionUID = 2629912294765040037L;
-
- private final String entityContainerName;
-
- private ODataEntity entity;
-
- private final Class<?> typeRef;
-
- private Map<String, Object> propertyChanges = new HashMap<String, Object>();
-
- private Map<String, InputStream> streamedPropertyChanges = new HashMap<String, InputStream>();
-
- private Map<NavigationProperty, Object> linkChanges = new HashMap<NavigationProperty, Object>();
-
- private InputStream stream;
-
- private EntityUUID uuid;
-
- private final EntityContext entityContext = EntityContainerFactory.getContext().entityContext();
-
- private int propertiesTag;
-
- private int linksTag;
-
- static EntityTypeInvocationHandler getInstance(
- final ODataEntity entity,
- final EntitySetInvocationHandler<?, ?, ?> entitySet,
- final Class<?> typeRef) {
-
- return getInstance(
- entity,
- entitySet.containerHandler.getEntityContainerName(),
- entitySet.getEntitySetName(),
- typeRef,
- entitySet.containerHandler);
- }
-
- static EntityTypeInvocationHandler getInstance(
- final ODataEntity entity,
- final String entityContainerName,
- final String entitySetName,
- final Class<?> typeRef,
- final EntityContainerInvocationHandler containerHandler) {
-
- return new EntityTypeInvocationHandler(entity, entityContainerName, entitySetName, typeRef, containerHandler);
- }
-
- private EntityTypeInvocationHandler(
- final ODataEntity entity,
- final String entityContainerName,
- final String entitySetName,
- final Class<?> typeRef,
- final EntityContainerInvocationHandler containerHandler) {
-
- super(containerHandler.getClient(), containerHandler);
- this.entityContainerName = entityContainerName;
- this.typeRef = typeRef;
-
- this.entity = entity;
- this.entity.setMediaEntity(typeRef.getAnnotation(EntityType.class).hasStream());
-
- this.uuid = new EntityUUID(
- ClassUtils.getNamespace(typeRef),
- entityContainerName,
- entitySetName,
- entity.getName(),
- EngineUtils.getKey(containerHandler.getFactory().getMetadata(), typeRef, entity));
-
- this.stream = null;
- this.propertiesTag = 0;
- this.linksTag = 0;
- }
-
- public void setEntity(final ODataEntity entity) {
- this.entity = entity;
- this.entity.setMediaEntity(typeRef.getAnnotation(EntityType.class).hasStream());
-
- this.uuid = new EntityUUID(
- getUUID().getSchemaName(),
- getUUID().getContainerName(),
- getUUID().getEntitySetName(),
- getUUID().getName(),
- EngineUtils.getKey(containerHandler.getFactory().getMetadata(), typeRef, entity));
-
- this.propertyChanges.clear();
- this.linkChanges.clear();
- this.streamedPropertyChanges.clear();
- this.propertiesTag = 0;
- this.linksTag = 0;
- this.stream = null;
- }
-
- public EntityUUID getUUID() {
- return uuid;
- }
-
- public String getName() {
- return this.entity.getName();
- }
-
- public String getEntityContainerName() {
- return uuid.getContainerName();
- }
-
- public String getEntitySetName() {
- return uuid.getEntitySetName();
- }
-
- public Class<?> getTypeRef() {
- return typeRef;
- }
-
- public ODataEntity getEntity() {
- return entity;
- }
-
- public Map<String, Object> getPropertyChanges() {
- return propertyChanges;
- }
-
- public Map<NavigationProperty, Object> getLinkChanges() {
- return linkChanges;
- }
-
- /**
- * Gets the current ETag defined into the wrapped entity.
- *
- * @return
- */
- public String getETag() {
- return this.entity.getETag();
- }
-
- /**
- * Overrides ETag value defined into the wrapped entity.
- *
- * @param eTag ETag.
- */
- public void setETag(final String eTag) {
- this.entity.setETag(eTag);
- }
-
- @Override
- @SuppressWarnings("unchecked")
- public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
- final Annotation[] methodAnnots = method.getAnnotations();
-
- if (isSelfMethod(method, args)) {
- return invokeSelfMethod(method, args);
- } else if (!ArrayUtils.isEmpty(methodAnnots) && methodAnnots[0] instanceof Operation) {
- final ODataOperation operation = this.entity.getOperation(((Operation) methodAnnots[0]).name());
- if (operation == null) {
- throw new IllegalArgumentException(
- "Could not find any FunctionImport named " + ((Operation) methodAnnots[0]).name());
- }
-
- final com.msopentech.odatajclient.engine.metadata.edm.v3.EntityContainer container =
- containerHandler.getFactory().getMetadata().getSchema(ClassUtils.getNamespace(typeRef)).
- getEntityContainer(entityContainerName);
- final com.msopentech.odatajclient.engine.metadata.edm.v3.FunctionImport funcImp =
- container.getFunctionImport(((Operation) methodAnnots[0]).name());
-
- return functionImport((Operation) methodAnnots[0], method, args,
- operation.getTarget(), funcImp);
- } // Assumption: for each getter will always exist a setter and viceversa.
- else if (method.getName().startsWith("get")) {
- // get method annotation and check if it exists as expected
- final Object res;
-
- final Method getter = typeRef.getMethod(method.getName());
-
- final Property property = ClassUtils.getAnnotation(Property.class, getter);
- if (property == null) {
- final NavigationProperty navProp = ClassUtils.getAnnotation(NavigationProperty.class, getter);
- if (navProp == null) {
- throw new UnsupportedOperationException("Unsupported method " + method.getName());
- } else {
- // if the getter refers to a navigation property ... navigate and follow link if necessary
- res = getNavigationPropertyValue(navProp, getter);
- }
- } else {
- // if the getter refers to a property .... get property from wrapped entity
- res = getPropertyValue(property, getter.getGenericReturnType());
- }
-
- // attach the current handler
- attach();
-
- return res;
- } else if (method.getName().startsWith("set")) {
- // get the corresponding getter method (see assumption above)
- final String getterName = method.getName().replaceFirst("set", "get");
- final Method getter = typeRef.getMethod(getterName);
-
- final Property property = ClassUtils.getAnnotation(Property.class, getter);
- if (property == null) {
- final NavigationProperty navProp = ClassUtils.getAnnotation(NavigationProperty.class, getter);
- if (navProp == null) {
- throw new UnsupportedOperationException("Unsupported method " + method.getName());
- } else {
- // if the getter refers to a navigation property ...
- if (ArrayUtils.isEmpty(args) || args.length != 1) {
- throw new IllegalArgumentException("Invalid argument");
- }
-
- setNavigationPropertyValue(navProp, args[0]);
- }
- } else {
- setPropertyValue(property, args[0]);
- }
-
- return ClassUtils.returnVoid();
- } else {
- throw new UnsupportedOperationException("Method not found: " + method);
- }
- }
-
- private Object getNavigationPropertyValue(final NavigationProperty property, final Method getter) {
- final Class<?> type = getter.getReturnType();
- final Class<?> collItemType;
- if (AbstractEntityCollection.class.isAssignableFrom(type)) {
- final Type[] entityCollectionParams =
- ((ParameterizedType) type.getGenericInterfaces()[0]).getActualTypeArguments();
- collItemType = (Class<?>) entityCollectionParams[0];
- } else {
- collItemType = type;
- }
-
- final Object navPropValue;
-
- if (linkChanges.containsKey(property)) {
- navPropValue = linkChanges.get(property);
- } else {
- final ODataLink link = EngineUtils.getNavigationLink(property.name(), entity);
- if (link instanceof ODataInlineEntity) {
- // return entity
- navPropValue = getEntityProxy(
- ((ODataInlineEntity) link).getEntity(),
- property.targetContainer(),
- property.targetEntitySet(),
- type,
- false);
- } else if (link instanceof ODataInlineEntitySet) {
- // return entity set
- navPropValue = getEntityCollection(
- collItemType,
- type,
- property.targetContainer(),
- ((ODataInlineEntitySet) link).getEntitySet(),
- link.getLink(),
- false);
- } else {
- // navigate
- final URI uri = URIUtils.getURI(
- containerHandler.getFactory().getServiceRoot(), link.getLink().toASCIIString());
-
- if (AbstractEntityCollection.class.isAssignableFrom(type)) {
- navPropValue = getEntityCollection(
- collItemType,
- type,
- property.targetContainer(),
- client.getRetrieveRequestFactory().getEntitySetRequest(uri).execute().getBody(),
- uri,
- true);
- } else {
- final ODataRetrieveResponse<ODataEntity> res =
- client.getRetrieveRequestFactory().getEntityRequest(uri).execute();
-
- navPropValue = getEntityProxy(
- res.getBody(),
- property.targetContainer(),
- property.targetEntitySet(),
- type,
- res.getEtag(),
- true);
- }
- }
-
- if (navPropValue != null) {
- int checkpoint = linkChanges.hashCode();
- linkChanges.put(property, navPropValue);
- updateLinksTag(checkpoint);
- }
- }
-
- return navPropValue;
- }
-
- private Object getPropertyValue(final String name, final Type type) {
- try {
- final Object res;
-
- if (propertyChanges.containsKey(name)) {
- res = propertyChanges.get(name);
- } else {
-
- res = type == null
- ? EngineUtils.getValueFromProperty(
- containerHandler.getFactory().getMetadata(), entity.getProperty(name))
- : EngineUtils.getValueFromProperty(
- containerHandler.getFactory().getMetadata(), entity.getProperty(name), type);
-
- if (res != null) {
- int checkpoint = propertyChanges.hashCode();
- propertyChanges.put(name, res);
- updatePropertiesTag(checkpoint);
- }
- }
-
- return res;
- } catch (Exception e) {
- throw new IllegalArgumentException("Error getting value for property '" + name + "'", e);
- }
- }
-
- private Object getPropertyValue(final Property property, final Type type) {
- if (!(type instanceof ParameterizedType) && (Class<?>) type == InputStream.class) {
- return getStreamedProperty(property);
- } else {
- return getPropertyValue(property.name(), type);
- }
- }
-
- public Object getAdditionalProperty(final String name) {
- return getPropertyValue(name, null);
- }
-
- public Collection<String> getAdditionalPropertyNames() {
- final Set<String> res = new HashSet<String>(propertyChanges.keySet());
- final Set<String> propertyNames = new HashSet<String>();
- for (Method method : typeRef.getMethods()) {
- final Annotation ann = method.getAnnotation(Property.class);
- if (ann != null) {
- final String property = ((Property) ann).name();
- propertyNames.add(property);
-
- // maybe someone could add a normal attribute to the additional set
- res.remove(property);
- }
- }
-
- for (ODataProperty property : entity.getProperties()) {
- if (!propertyNames.contains(property.getName())) {
- res.add(property.getName());
- }
- }
-
- return res;
- }
-
- private void setNavigationPropertyValue(final NavigationProperty property, final Object value) {
- // 1) attach source entity
- attach(AttachedEntityStatus.CHANGED, false);
-
- // 2) attach the target entity handlers
- for (Object link : AbstractEntityCollection.class.isAssignableFrom(value.getClass())
- ? (AbstractEntityCollection) value : Collections.singleton(value)) {
-
- final InvocationHandler etih = Proxy.getInvocationHandler(link);
- if (!(etih instanceof EntityTypeInvocationHandler)) {
- throw new IllegalArgumentException("Invalid argument type");
- }
-
- final EntityTypeInvocationHandler handler = (EntityTypeInvocationHandler) etih;
- if (!handler.getTypeRef().isAnnotationPresent(EntityType.class)) {
- throw new IllegalArgumentException(
- "Invalid argument type " + handler.getTypeRef().getSimpleName());
- }
-
- if (!entityContext.isAttached(handler)) {
- entityContext.attach(handler, AttachedEntityStatus.LINKED);
- }
- }
-
- // 3) add links
- linkChanges.put(property, value);
- }
-
- private void setPropertyValue(final Property property, final Object value) {
- if (property.type().equalsIgnoreCase("Edm.Stream")) {
- setStreamedProperty(property, (InputStream) value);
- } else {
- propertyChanges.put(property.name(), value);
- }
-
- attach(AttachedEntityStatus.CHANGED);
- }
-
- public void addAdditionalProperty(final String name, final Object value) {
- propertyChanges.put(name, value);
- attach(AttachedEntityStatus.CHANGED);
- }
-
- private void updatePropertiesTag(final int checkpoint) {
- if (checkpoint == propertiesTag) {
- propertiesTag = propertyChanges.hashCode();
- }
- }
-
- private void updateLinksTag(final int checkpoint) {
- if (checkpoint == linksTag) {
- linksTag = linkChanges.hashCode();
- }
- }
-
- public boolean isChanged() {
- return this.linkChanges.hashCode() != this.linksTag
- || this.propertyChanges.hashCode() != this.propertiesTag
- || this.stream != null
- || !this.streamedPropertyChanges.isEmpty();
- }
-
- public void setStream(final InputStream stream) {
- if (typeRef.getAnnotation(EntityType.class).hasStream()) {
- IOUtils.closeQuietly(this.stream);
- this.stream = stream;
- attach(AttachedEntityStatus.CHANGED);
- }
- }
-
- public InputStream getStreamChanges() {
- return this.stream;
- }
-
- public Map<String, InputStream> getStreamedPropertyChanges() {
- return streamedPropertyChanges;
- }
-
- public InputStream getStream() {
-
- final String contentSource = entity.getMediaContentSource();
-
- if (this.stream == null
- && typeRef.getAnnotation(EntityType.class).hasStream()
- && StringUtils.isNotBlank(contentSource)) {
-
- final String comntentType =
- StringUtils.isBlank(entity.getMediaContentType()) ? "*/*" : entity.getMediaContentType();
-
- final URI contentSourceURI = URIUtils.getURI(containerHandler.getFactory().getServiceRoot(), contentSource);
-
- final ODataMediaRequest retrieveReq = client.getRetrieveRequestFactory().getMediaRequest(contentSourceURI);
- retrieveReq.setFormat(ODataMediaFormat.fromFormat(comntentType));
-
- this.stream = retrieveReq.execute().getBody();
- }
-
- return this.stream;
- }
-
- public Object getStreamedProperty(final Property property) {
-
- InputStream res = streamedPropertyChanges.get(property.name());
-
- try {
- if (res == null) {
- final URI link = URIUtils.getURI(
- containerHandler.getFactory().getServiceRoot(),
- EngineUtils.getEditMediaLink(property.name(), this.entity).toASCIIString());
-
- final ODataMediaRequest req = client.getRetrieveRequestFactory().getMediaRequest(link);
- res = req.execute().getBody();
-
- }
- } catch (Exception e) {
- res = null;
- }
-
- return res;
-
- }
-
- private void setStreamedProperty(final Property property, final InputStream input) {
- final Object obj = propertyChanges.get(property.name());
- if (obj != null && obj instanceof InputStream) {
- IOUtils.closeQuietly((InputStream) obj);
- }
-
- streamedPropertyChanges.put(property.name(), input);
- }
-
- private void attach() {
- if (!entityContext.isAttached(this)) {
- entityContext.attach(this, AttachedEntityStatus.ATTACHED);
- }
- }
-
- private void attach(final AttachedEntityStatus status) {
- attach(status, true);
- }
-
- private void attach(final AttachedEntityStatus status, final boolean override) {
- if (entityContext.isAttached(this)) {
- if (override) {
- entityContext.setStatus(this, status);
- }
- } else {
- entityContext.attach(this, status);
- }
- }
-
- @Override
- public String toString() {
- return uuid.toString();
- }
-
- @Override
- public int hashCode() {
- return uuid.hashCode();
- }
-
- @Override
- public boolean equals(final Object obj) {
- return obj instanceof EntityTypeInvocationHandler
- && ((EntityTypeInvocationHandler) obj).getUUID().equals(uuid);
- }
-}
http://git-wip-us.apache.org/repos/asf/olingo-odata4/blob/19f3792f/ODataJClient/proxy/src/main/java/com/msopentech/odatajclient/proxy/api/impl/QueryImpl.java
----------------------------------------------------------------------
diff --git a/ODataJClient/proxy/src/main/java/com/msopentech/odatajclient/proxy/api/impl/QueryImpl.java b/ODataJClient/proxy/src/main/java/com/msopentech/odatajclient/proxy/api/impl/QueryImpl.java
deleted file mode 100644
index ad2ee28..0000000
--- a/ODataJClient/proxy/src/main/java/com/msopentech/odatajclient/proxy/api/impl/QueryImpl.java
+++ /dev/null
@@ -1,171 +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 com.msopentech.odatajclient.proxy.api.impl;
-
-import com.msopentech.odatajclient.engine.client.ODataClient;
-import com.msopentech.odatajclient.engine.uri.URIBuilder;
-import com.msopentech.odatajclient.engine.uri.filter.ODataFilter;
-import com.msopentech.odatajclient.proxy.api.AbstractEntityCollection;
-import com.msopentech.odatajclient.proxy.api.NoResultException;
-import com.msopentech.odatajclient.proxy.api.NonUniqueResultException;
-import com.msopentech.odatajclient.proxy.api.Query;
-import com.msopentech.odatajclient.proxy.api.Sort;
-import com.msopentech.odatajclient.proxy.utils.ClassUtils;
-import java.io.Serializable;
-import java.net.URI;
-import org.apache.commons.lang3.StringUtils;
-
-public class QueryImpl<T extends Serializable, EC extends AbstractEntityCollection<T>> implements Query<T, EC> {
-
- private static final long serialVersionUID = -300830736753191114L;
-
- private final ODataClient client;
-
- private final Class<T> typeRef;
-
- private final Class<EC> collTypeRef;
-
- private final EntitySetInvocationHandler handler;
-
- private final URI baseURI;
-
- private String filter;
-
- private String orderBy;
-
- private Integer maxResults;
-
- private Integer firstResult;
-
- @SuppressWarnings("unchecked")
- QueryImpl(final ODataClient client,
- final Class<EC> collTypeRef, final URI baseURI, final EntitySetInvocationHandler handler) {
-
- this.client = client;
- this.typeRef = (Class<T>) ClassUtils.extractTypeArg(collTypeRef);
- this.collTypeRef = collTypeRef;
- this.baseURI = baseURI;
- this.handler = handler;
- }
-
- @Override
- public Query<T, EC> setFilter(final String filter) {
- this.filter = filter;
- return this;
- }
-
- @Override
- public Query<T, EC> setFilter(final ODataFilter filter) {
- this.filter = filter.build();
- return this;
- }
-
- @Override
- public String getFilter() {
- return filter;
- }
-
- @Override
- public Query<T, EC> setOrderBy(final Sort... sort) {
- final StringBuilder builder = new StringBuilder();
- for (Sort sortClause : sort) {
- builder.append(sortClause.getKey()).append(' ').append(sortClause.getValue()).append(',');
- }
- builder.deleteCharAt(builder.length() - 1);
-
- this.orderBy = builder.toString();
- return this;
- }
-
- @Override
- public Query<T, EC> setOrderBy(final String orderBy) {
- this.orderBy = orderBy;
- return this;
- }
-
- @Override
- public String getOrderBy() {
- return orderBy;
- }
-
- @Override
- public Query<T, EC> setMaxResults(final int maxResults) throws IllegalArgumentException {
- if (maxResults <= 0) {
- throw new IllegalArgumentException("maxResults must be positive");
- }
-
- this.maxResults = maxResults;
- return this;
- }
-
- @Override
- public int getMaxResults() {
- return maxResults;
- }
-
- @Override
- public Query<T, EC> setFirstResult(final int firstResult) throws IllegalArgumentException {
- if (firstResult <= 0) {
- throw new IllegalArgumentException("firstResult must be positive");
- }
-
- this.firstResult = firstResult;
- return this;
- }
-
- @Override
- public int getFirstResult() {
- return firstResult;
- }
-
- @Override
- public T getSingleResult() throws NoResultException, NonUniqueResultException {
- final EC result = getResult();
- if (result.isEmpty()) {
- throw new NoResultException();
- }
- if (result.size() > 1) {
- throw new NonUniqueResultException();
- }
-
- return result.iterator().next();
- }
-
- @Override
- @SuppressWarnings("unchecked")
- public EC getResult() {
- final URIBuilder uriBuilder = client.getURIBuilder(this.baseURI.toASCIIString()).
- appendStructuralSegment(ClassUtils.getNamespace(typeRef) + "." + ClassUtils.getEntityTypeName(typeRef));
-
- if (StringUtils.isNotBlank(filter)) {
- uriBuilder.filter(filter);
- }
- if (StringUtils.isNotBlank(orderBy)) {
- uriBuilder.orderBy(orderBy);
- }
- if (maxResults != null) {
- uriBuilder.top(maxResults);
- }
- if (firstResult != null) {
- uriBuilder.skip(firstResult);
- }
-
- return (EC) handler.fetchWholeEntitySet(uriBuilder.build(), typeRef, collTypeRef);
- }
-}