[OLINGO-200] V3 (de)serializers + unit tests merged

This commit is contained in:
Francesco Chicchiriccò 2014-03-11 13:52:07 +01:00
parent fe0b46369b
commit 78c3eaa4f5
138 changed files with 9667 additions and 2846 deletions

View File

@ -49,6 +49,11 @@
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -18,10 +18,14 @@
*/
package org.apache.olingo.client.api;
import org.apache.olingo.client.api.domain.ODataGeospatialValue;
import org.apache.olingo.client.api.domain.ODataObjectFactory;
import org.apache.olingo.client.api.domain.ODataPrimitiveValue;
import org.apache.olingo.client.api.op.ODataBinder;
import org.apache.olingo.client.api.op.ODataDeserializer;
import org.apache.olingo.client.api.op.ODataReader;
import org.apache.olingo.client.api.op.ODataSerializer;
import org.apache.olingo.client.api.op.ODataWriter;
import org.apache.olingo.client.api.uri.URIBuilder;
import org.apache.olingo.client.api.uri.filter.FilterFactory;
import org.apache.olingo.commons.api.edm.constants.ODataServiceVersion;
@ -37,16 +41,21 @@ public interface ODataClient {
FilterFactory getFilterFactory();
ODataPrimitiveValue.Builder getPrimitiveValueBuilder();
ODataGeospatialValue.Builder getGeospatialValueBuilder();
ODataSerializer getSerializer();
ODataDeserializer getDeserializer();
ODataReader getReader();
// ODataWriter getWriter();
ODataWriter getWriter();
ODataBinder getBinder();
// ODataObjectFactory getObjectFactory();
ODataObjectFactory getObjectFactory();
// RetrieveRequestFactory getRetrieveRequestFactory();
// CUDRequestFactory getCUDRequestFactory();
// StreamedRequestFactory getStreamedRequestFactory();

View File

@ -0,0 +1,194 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.olingo.client.api.data;
import java.net.URI;
import java.util.List;
import org.w3c.dom.Element;
public interface Entry {
/**
* Gets ETag.
*
* @return ETag.
*/
String getETag();
/**
* Sets ETag.
*
* @param eTag ETag.
*/
void setETag(String eTag);
/**
* Gets base URI.
*
* @return base URI.
*/
URI getBaseURI();
/**
* Gets entry type.
*
* @return entry type.
*/
String getType();
/**
* Sets entry type.
*
* @param type entry type.
*/
void setType(String type);
/**
* Gest entry ID.
*
* @return entry ID.
*/
String getId();
/**
* Sets entry ID.
*
* @param id entry ID.
*/
void setId(String id);
/**
* Gets entry self link.
*
* @return self link.
*/
Link getSelfLink();
/**
* Sets entry self link.
*
* @param selfLink self link.
*/
void setSelfLink(Link selfLink);
/**
* Gets entry edit link.
*
* @return edit link.
*/
Link getEditLink();
/**
* Sets entry edit link.
*
* @param editLink edit link.
*/
void setEditLink(Link editLink);
/**
* Gets association links.
*
* @return association links.
*/
List<Link> getAssociationLinks();
/**
* Gets navigation links.
*
* @return links.
*/
List<Link> getNavigationLinks();
/**
* Gets media entity links.
*
* @return links.
*/
List<Link> getMediaEditLinks();
/**
* Gets operations.
*
* @return operations.
*/
List<Operation> getOperations();
/**
* Gets content.
*
* @return content.
*/
Element getContent();
/**
* Sets content.
*
* @param content content.
*/
void setContent(Element content);
/**
* Gets media entry properties.
*
* @return media entry properties.
*/
Element getMediaEntryProperties();
/**
* Sets media entry properties.
*
* @param content media entry properties.
*/
void setMediaEntryProperties(Element content);
/**
* Gets media content type.
*
* @return media content type.
*/
String getMediaContentType();
/**
* Gets media content resource.
*
* @return media content resource.
*/
String getMediaContentSource();
/**
* Set media content source.
*
* @param mediaContentSource media content source.
*/
void setMediaContentSource(String mediaContentSource);
/**
* Set media content type.
*
* @param mediaContentType media content type.
*/
void setMediaContentType(String mediaContentType);
/**
* Checks if the current entry is a media entry.
*
* @return 'TRUE' if is a media entry; 'FALSE' otherwise.
*/
boolean isMediaEntry();
}

View File

@ -16,12 +16,12 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.olingo.client.api;
package org.apache.olingo.client.api.data;
/**
* OData error.
*/
public interface ODataError {
public interface Error {
/**
* Gets error code.

View File

@ -1,4 +1,4 @@
/*
/*
* 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
@ -16,20 +16,46 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.olingo.client.api.deserializer;
package org.apache.olingo.client.api.data;
import java.net.URI;
import java.util.List;
import java.util.Map;
public interface ComplexValue extends Value {
public interface Feed {
Value getValue(String name);
/**
* Gets base URI.
*
* @return base URI.
*/
URI getBaseURI();
List<Property> getProperties();
/**
* Gets number of entries if an <tt>inlinecount</tt> was required.
*
* @return number of entries into the feed.
*/
Integer getCount();
Map<String, NavigationProperty> getNavigationProperties();
/**
* Gets entries.
*
* @return entries.
*/
List<Entry> getEntries();
Map<String, AnnotationProperty> getAnnotationProperties();
/**
* Gets next link if exists.
*
* @return next link if exists; null otherwise.
*/
URI getNext();
/**
* Sets next link.
*
* @param next next link.
*/
void setNext(URI next);
Map<String, StructuralProperty> getStructuralProperties();
}

View File

@ -0,0 +1,107 @@
/*
* 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.olingo.client.api.data;
public interface Link {
/**
* Gets rel info.
*
* @return rel info.
*/
String getRel();
/**
* Sets rel info.
*
* @param rel rel info.
*/
void setRel(String rel);
/**
* Gets type.
*
* @return type.
*/
String getType();
/**
* Sets type.
*
* @param type type.
*/
void setType(String type);
/**
* Gets title.
*
* @return title.
*/
String getTitle();
/**
* Sets title.
*
* @param title title.
*/
void setTitle(String title);
/**
* Gets href.
*
* @return href.
*/
String getHref();
/**
* Sets href.
*
* @param href href.
*/
void setHref(String href);
/**
* Gets in-line entry.
*
* @return in-line entry.
*/
Entry getInlineEntry();
/**
* Sets in-line entry.
*
* @param entry entry.
*/
void setInlineEntry(Entry entry);
/**
* Gets in-line feed.
*
* @return in-line feed.
*/
Feed getInlineFeed();
/**
* Sets in-line feed.
*
* @param feed feed.
*/
void setInlineFeed(Feed feed);
}

View File

@ -1,4 +1,4 @@
/*
/*
* 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
@ -16,15 +16,37 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.olingo.client.api.deserializer;
package org.apache.olingo.client.api.data;
import java.net.URI;
import java.util.List;
public interface StructuralProperty extends Property {
/**
* REST resource for an <tt>ODataLinkCollection</tt>.
*
* @see org.apache.olingo.client.api.domain.ODataLinkCollection
*/
public interface LinkCollection {
boolean containsCollection();
/**
* Smart management of different JSON format produced by OData services when
* <tt>$links</tt> is a single or a collection property.
*
* @return list of URIs for <tt>$links</tt>
*/
List<URI> getLinks();
Value getValue();
/**
* Sets next link.
*
* @param next next link.
*/
void setNext(final URI next);
List<Value> getValues();
/**
* Gets next link if exists.
*
* @return next link if exists; null otherwise.
*/
URI getNext();
}

View File

@ -0,0 +1,94 @@
/*
* 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.olingo.client.api.data;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.ContentType;
import org.apache.olingo.client.api.ODataClient;
import org.apache.olingo.client.api.format.ODataPubFormat;
import org.apache.olingo.commons.api.edm.constants.ODataServiceVersion;
/**
* OData link types.
*/
public enum LinkType {
/**
* Entity navigation link.
*/
ENTITY_NAVIGATION(ODataPubFormat.ATOM + ";type=entry"),
/**
* Entity set navigation link.
*/
ENTITY_SET_NAVIGATION(ODataPubFormat.ATOM + ";type=feed"),
/**
* Association link.
*/
ASSOCIATION(ContentType.APPLICATION_XML.getMimeType()),
/**
* Media-edit link.
*/
MEDIA_EDIT("*/*");
private String type;
private LinkType(final String type) {
this.type = type;
}
private LinkType setType(final String type) {
this.type = type;
return this;
}
/**
* Gets <code>LinkType</code> instance from the given rel and type.
*
* @param client OData client.
* @param rel rel.
* @param type type.
* @return <code>ODataLinkType</code> object.
*/
public static LinkType fromString(final ODataClient client, final String rel, final String type) {
if (StringUtils.isNotBlank(rel) && rel.startsWith(client.getServiceVersion().getNamespaceMap().
get(ODataServiceVersion.MEDIA_EDIT_LINK_REL))) {
return MEDIA_EDIT.setType(StringUtils.isBlank(type) ? "*/*" : type);
}
if (LinkType.ENTITY_NAVIGATION.type.equals(type)) {
return ENTITY_NAVIGATION;
}
if (LinkType.ENTITY_SET_NAVIGATION.type.equals(type)) {
return ENTITY_SET_NAVIGATION;
}
if (LinkType.ASSOCIATION.type.equals(type)) {
return ASSOCIATION;
}
throw new IllegalArgumentException("Invalid link type: " + type);
}
@Override
public String toString() {
return type;
}
}

View File

@ -1,4 +1,4 @@
/*
/*
* 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
@ -16,19 +16,21 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.olingo.client.api.deserializer;
package org.apache.olingo.client.api.data;
import java.util.List;
import java.net.URI;
public interface EntitySet extends Iterable<Entity> {
public interface Operation {
String getODataContext();
String getMetadataAnchor();
Long getODataCount();
void setMetadataAnchor(String metadataAnchor);
String getODataNextLink();
String getTitle();
String getODataDeltaLink();
void setTitle(String title);
List<Entity> getEntities();
URI getTarget();
void setTarget(URI target);
}

View File

@ -1,24 +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.olingo.client.api.deserializer;
public interface AnnotationProperty extends Property {
String getValue();
}

View File

@ -1,36 +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.olingo.client.api.deserializer;
public class ClientException extends Exception {
private static final long serialVersionUID = 5148670827051750921L;
public ClientException() {
super();
}
public ClientException(final String message) {
super(message);
}
public ClientException(final String message, final Throwable cause) {
super(message, cause);
}
}

View File

@ -1,27 +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.olingo.client.api.deserializer;
public interface NavigationProperty extends Property {
public abstract String getAssociationLink();
public abstract String getNavigationLink();
}

View File

@ -1,24 +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.olingo.client.api.deserializer;
public interface Property {
String getName();
}

View File

@ -1,28 +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.olingo.client.api.deserializer;
public interface Value {
boolean isComplex();
Object getContent();
<T> T getContentAs(T type);
}

View File

@ -0,0 +1,317 @@
/*
* 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.olingo.client.api.domain;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.olingo.client.api.data.Operation;
/**
* OData entity.
*/
public class ODataEntity extends ODataItem implements ODataInvokeResult {
private static final long serialVersionUID = 8360640095932811034L;
/**
* ETag.
*/
private String eTag;
/**
* Media entity flag.
*/
private boolean mediaEntity = false;
/**
* In case of media entity, media content type.
*/
private String mediaContentType;
/**
* In case of media entity, media content source.
*/
private String mediaContentSource;
/**
* Edit link.
*/
protected URI editLink;
/**
* Navigation links (might contain in-line entities or feeds).
*/
protected final List<ODataLink> navigationLinks = new ArrayList<ODataLink>();
/**
* Association links.
*/
protected final List<ODataLink> associationLinks = new ArrayList<ODataLink>();
/**
* Media edit links.
*/
protected final List<ODataLink> editMediaLinks = new ArrayList<ODataLink>();
/**
* Operations (legacy, functions, actions).
*/
protected final List<Operation> operations = new ArrayList<Operation>();
/**
* Entity properties.
*/
protected final List<ODataProperty> properties = new ArrayList<ODataProperty>();
/**
* Constructor.
*
* @param name OData entity name.
*/
public ODataEntity(final String name) {
super(name);
}
/**
* Gets ETag.
*
* @return ETag.
*/
public String getETag() {
return eTag;
}
/**
* Sets ETag.
*
* @param eTag ETag.
*/
public void setETag(final String eTag) {
this.eTag = eTag;
}
/**
* Searches for operation with given title.
*
* @param title operation to look for
* @return operation if found with given title, <tt>null</tt> otherwise
*/
public Operation getOperation(final String title) {
Operation result = null;
for (Operation operation : operations) {
if (title.equals(operation.getTitle())) {
result = operation;
}
}
return result;
}
/**
* Gets operations.
*
* @return operations.
*/
public List<Operation> getOperations() {
return this.operations;
}
/**
* Searches for property with given name.
*
* @param name property to look for
* @return property if found with given name, <tt>null</tt> otherwise
*/
public ODataProperty getProperty(final String name) {
ODataProperty result = null;
if (StringUtils.isNotBlank(name)) {
for (ODataProperty property : properties) {
if (name.equals(property.getName())) {
result = property;
}
}
}
return result;
}
/**
* Returns OData entity properties.
*
* @return OData entity properties.
*/
public List<ODataProperty> getProperties() {
return properties;
}
/**
* Puts the given link into one of available lists, based on its type.
*
* @param link to be added
* @return <tt>true</tt> if the given link was added in one of available lists
*/
public boolean addLink(final ODataLink link) {
boolean result = false;
switch (link.getType()) {
case ASSOCIATION:
result = associationLinks.contains(link) ? false : associationLinks.add(link);
break;
case ENTITY_NAVIGATION:
case ENTITY_SET_NAVIGATION:
result = navigationLinks.contains(link) ? false : navigationLinks.add(link);
break;
case MEDIA_EDIT:
result = editMediaLinks.contains(link) ? false : editMediaLinks.add(link);
break;
default:
}
return result;
}
/**
* Removes the given link from any list (association, navigation, edit-media).
*
* @param link to be removed
* @return <tt>true</tt> if the given link was contained in one of available lists
*/
public boolean removeLink(final ODataLink link) {
return associationLinks.remove(link) || navigationLinks.remove(link) || editMediaLinks.remove(link);
}
/**
* Returns all entity navigation links (including inline entities / feeds).
*
* @return OData entity links.
*/
public List<ODataLink> getNavigationLinks() {
return navigationLinks;
}
/**
* Returns all entity association links.
*
* @return OData entity links.
*/
public List<ODataLink> getAssociationLinks() {
return associationLinks;
}
/**
* Returns all entity media edit links.
*
* @return OData entity links.
*/
public List<ODataLink> getEditMediaLinks() {
return editMediaLinks;
}
/**
* Returns OData entity edit link.
*
* @return entity edit link.
*/
public URI getEditLink() {
return editLink;
}
/**
* Sets OData entity edit link.
*
* @param editLink edit link.
*/
public void setEditLink(final URI editLink) {
this.editLink = editLink;
}
@Override
public URI getLink() {
return super.getLink() == null ? getEditLink() : super.getLink();
}
/**
* TRUE if read-only entity.
*
* @return TRUE if read-only; FALSE otherwise.
*/
public boolean isReadOnly() {
return super.getLink() != null;
}
/**
* Checks if the current entity is a media entity.
*
* @return 'TRUE' if media entity; 'FALSE' otherwise.
*/
public boolean isMediaEntity() {
return mediaEntity;
}
/**
* Sets media entity flag.
*
* @param isMediaEntity media entity flag value.
*/
public void setMediaEntity(final boolean isMediaEntity) {
this.mediaEntity = isMediaEntity;
}
/**
* Gets media content type.
*
* @return media content type.
*/
public String getMediaContentType() {
return mediaContentType;
}
/**
* Sets media content type.
*
* @param mediaContentType media content type.
*/
public void setMediaContentType(final String mediaContentType) {
this.mediaContentType = mediaContentType;
}
/**
* Gets media content source.
*
* @return media content source.
*/
public String getMediaContentSource() {
return mediaContentSource;
}
/**
* Sets media content source.
*
* @param mediaContentSource media content source.
*/
public void setMediaContentSource(final String mediaContentSource) {
this.mediaContentSource = mediaContentSource;
}
}

View File

@ -0,0 +1,121 @@
/*
* 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.olingo.client.api.domain;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.apache.olingo.client.api.domain.ODataInvokeResult;
/**
* OData entity collection. If pagination was used to get this instance, forward page navigation URI will be available.
*/
public class ODataEntitySet extends ODataItem implements ODataInvokeResult {
private static final long serialVersionUID = 9039605899821494024L;
/**
* Link to the next page.
*/
protected URI next;
/**
* Number of ODataEntities contained in this feed. If <tt>$inlinecount</tt> was requested, this value comes from
* there.
*/
protected Integer count;
/**
* OData entities contained in this feed.
*/
protected List<ODataEntity> entities = new ArrayList<ODataEntity>();
/**
* Constructor.
*/
public ODataEntitySet() {
super(null);
}
/**
* Constructor.
*
* @param next next link.
*/
public ODataEntitySet(final URI next) {
super(null);
this.next = next;
}
/**
* Gets next page link.
*
* @return next page link; null value if single page or last page reached.
*/
public URI getNext() {
return next;
}
/**
* Sets in-line count.
*
* @param count in-line count value.
*/
public void setCount(final int count) {
this.count = count;
}
/**
* Gets in-line count.
*
* @return in-line count value.
*/
public int getCount() {
return count == null ? entities.size() : count;
}
/**
* Adds entity to the current feed.
*
* @param entity entity to be added.
* @return 'FALSE' if already exists; 'TRUE' otherwise.
*/
public boolean addEntity(final ODataEntity entity) {
return entities.contains(entity) ? false : entities.add(entity);
}
/**
* Removes an entity.
*
* @param entity entity to be removed.
* @return 'TRUE' in case of success; 'FALSE' otherwise.
*/
public boolean removeEntity(final ODataEntity entity) {
return entities.remove(entity);
}
/**
* Gets contained entities.
*
* @return feed entries.
*/
public List<ODataEntity> getEntities() {
return entities;
}
}

View File

@ -90,7 +90,7 @@ public class ODataGeospatialValue extends ODataPrimitiveValue {
* @param type type.
* @return the current builder.
*/
public Builder setType(final EdmSimpleType type) {
public Builder setType(final ODataJClientEdmPrimitiveType type) {
isSupported(type);
if (!type.isGeospatial()) {
@ -98,7 +98,7 @@ public class ODataGeospatialValue extends ODataPrimitiveValue {
"Use " + ODataPrimitiveValue.class.getSimpleName() + " for non-geospatial types");
}
if (type == EdmSimpleType.Geography || type == EdmSimpleType.Geometry) {
if (type == ODataJClientEdmPrimitiveType.Geography || type == ODataJClientEdmPrimitiveType.Geometry) {
throw new IllegalArgumentException(
type + "is not an instantiable type. "
+ "An entity can declare a property to be of type Geometry. "
@ -215,7 +215,7 @@ public class ODataGeospatialValue extends ODataPrimitiveValue {
/**
* Parses given tree as geospatial value.
*/
private Geospatial parseTree(final Element tree, final EdmSimpleType type) {
private Geospatial parseTree(final Element tree, final ODataJClientEdmPrimitiveType type) {
Geospatial value;
switch (type) {

View File

@ -0,0 +1,73 @@
/*
* 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.olingo.client.api.domain;
import java.net.URI;
import org.apache.olingo.client.api.ODataClient;
import org.apache.olingo.client.api.data.LinkType;
/**
* OData in-line entity.
*/
public class ODataInlineEntity extends ODataLink {
private static final long serialVersionUID = -4763341581843700743L;
private final ODataEntity entity;
/**
* Constructor.
*
* @param uri edit link.
* @param type type.
* @param title title.
* @param entity entity.
*/
public ODataInlineEntity(final ODataClient client,
final URI uri, final LinkType type, final String title, final ODataEntity entity) {
super(client, uri, type, title);
this.entity = entity;
}
/**
* Constructor.
*
* @param baseURI base URI.
* @param href href.
* @param type type.
* @param title title.
* @param entity entity.
*/
public ODataInlineEntity(final ODataClient client, final URI baseURI, final String href, final LinkType type,
final String title, final ODataEntity entity) {
super(client, baseURI, href, type, title);
this.entity = entity;
}
/**
* Gets wrapped entity.
*
* @return wrapped entity.
*/
public ODataEntity getEntity() {
return entity;
}
}

View File

@ -0,0 +1,75 @@
/*
* 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.olingo.client.api.domain;
import java.net.URI;
import org.apache.olingo.client.api.ODataClient;
import org.apache.olingo.client.api.data.LinkType;
/**
* OData in-line entity set.
*/
public class ODataInlineEntitySet extends ODataLink {
private static final long serialVersionUID = -77628001615355449L;
private ODataEntitySet entitySet;
/**
* Constructor.
*
* @param client OData client.
* @param uri edit link.
* @param type type.
* @param title title.
* @param entitySet entity set.
*/
public ODataInlineEntitySet(final ODataClient client, final URI uri, final LinkType type, final String title,
final ODataEntitySet entitySet) {
super(client, uri, type, title);
this.entitySet = entitySet;
}
/**
* Constructor.
*
* @param client OData client.
* @param baseURI base URI.
* @param href href.
* @param type type.
* @param title title.
* @param entitySet entity set.
*/
public ODataInlineEntitySet(final ODataClient client, final URI baseURI, final String href, final LinkType type,
final String title, final ODataEntitySet entitySet) {
super(client, baseURI, href, type, title);
this.entitySet = entitySet;
}
/**
* Gets wrapped entity set.
*
* @return wrapped entity set.
*/
public ODataEntitySet getEntitySet() {
return entitySet;
}
}

View File

@ -0,0 +1,111 @@
/*
* 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.olingo.client.api.domain;
import java.io.Serializable;
import java.net.URI;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Abstract representation of OData entities and links.
*/
public abstract class ODataItem implements Serializable {
private static final long serialVersionUID = -2600707722689304686L;
/**
* Logger.
*/
protected static final Logger LOG = LoggerFactory.getLogger(ODataItem.class);
/**
* OData item self link.
*/
protected URI link;
/**
* OData entity name/type.
*/
private final String name;
/**
* Constructor.
*
* @param name OData entity name.
*/
public ODataItem(final String name) {
this.name = name;
}
/**
* Returns self link.
*
* @return entity edit link.
*/
public URI getLink() {
return link;
}
/**
* Sets self link.
*
* @param link link.
*/
public void setLink(final URI link) {
this.link = link;
}
/**
* Returns OData entity name.
*
* @return entity name.
*/
public String getName() {
return name;
}
/**
* {@inheritDoc }
*/
@Override
public boolean equals(final Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
/**
* {@inheritDoc }
*/
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
/**
* {@inheritDoc }
*/
@Override
public String toString() {
return ReflectionToStringBuilder.toString(this, ToStringStyle.MULTI_LINE_STYLE);
}
}

View File

@ -45,8 +45,9 @@ import org.apache.olingo.commons.api.edm.constants.ODataServiceVersion;
* The Abstract Type System used to define the primitive types supported by OData is defined in detail in <a
* href="http://msdn.microsoft.com/en-us/library/dd541474.aspx">[MC-CSDL] (section 2.2.1).</a>
* </p>
* TODO: MERGE / REMOVE (OLINGO-65)!
*/
public enum EdmSimpleType {
public enum ODataJClientEdmPrimitiveType {
/**
* The absence of a value.
@ -157,7 +158,7 @@ public enum EdmSimpleType {
*
* @param clazz type.
*/
EdmSimpleType(final Class<?> clazz) {
ODataJClientEdmPrimitiveType(final Class<?> clazz) {
this(ODataServiceVersion.values(), clazz, null);
}
@ -167,7 +168,7 @@ public enum EdmSimpleType {
* @param versions supported OData versions.
* @param clazz type.
*/
EdmSimpleType(final ODataServiceVersion[] versions, final Class<?> clazz) {
ODataJClientEdmPrimitiveType(final ODataServiceVersion[] versions, final Class<?> clazz) {
this(versions, clazz, null);
}
@ -177,7 +178,7 @@ public enum EdmSimpleType {
* @param clazz type.
* @param pattern pattern.
*/
EdmSimpleType(final Class<?> clazz, final String pattern) {
ODataJClientEdmPrimitiveType(final Class<?> clazz, final String pattern) {
this(ODataServiceVersion.values(), clazz, pattern);
}
@ -188,7 +189,7 @@ public enum EdmSimpleType {
* @param clazz type.
* @param pattern pattern.
*/
EdmSimpleType(final ODataServiceVersion[] versions, final Class<?> clazz, final String pattern) {
ODataJClientEdmPrimitiveType(final ODataServiceVersion[] versions, final Class<?> clazz, final String pattern) {
this.clazz = clazz;
this.pattern = pattern;
this.versions = versions.clone();
@ -245,9 +246,9 @@ public enum EdmSimpleType {
* @param value string value type.
* @return <tt>EdmSimpleType</tt> object.
*/
public static EdmSimpleType fromValue(final String value) {
public static ODataJClientEdmPrimitiveType fromValue(final String value) {
final String noNsValue = value.substring(4);
for (EdmSimpleType edmSimpleType : EdmSimpleType.values()) {
for (ODataJClientEdmPrimitiveType edmSimpleType : ODataJClientEdmPrimitiveType.values()) {
if (edmSimpleType.name().equals(noNsValue)) {
return edmSimpleType;
}
@ -262,8 +263,8 @@ public enum EdmSimpleType {
* @param obj object.
* @return <tt>EdmSimpleType</tt> object.
*/
public static EdmSimpleType fromObject(final ODataServiceVersion workingVersion, final Object obj) {
for (EdmSimpleType edmSimpleType : EdmSimpleType.values()) {
public static ODataJClientEdmPrimitiveType fromObject(final ODataServiceVersion workingVersion, final Object obj) {
for (ODataJClientEdmPrimitiveType edmSimpleType : ODataJClientEdmPrimitiveType.values()) {
if (edmSimpleType.javaType().equals(obj.getClass())) {
return edmSimpleType == DateTimeOffset || edmSimpleType == DateTime || edmSimpleType == Date
? ((ODataTimestamp) obj).isOffset()

View File

@ -0,0 +1,248 @@
/*
* 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.olingo.client.api.domain;
import org.apache.commons.lang3.StringUtils;
import org.apache.olingo.client.api.edm.xml.ComplexType;
import org.apache.olingo.client.api.edm.xml.EntityType;
import org.apache.olingo.client.api.edm.xml.EnumType;
import org.apache.olingo.client.api.edm.xml.Schema;
import org.apache.olingo.client.api.edm.xml.XMLMetadata;
/**
* Parse type information from metadata into semantic data. TODO: REMOVE! (OLINGO-165)
*/
public class ODataJClientEdmType {
private final String typeExpression;
private final String baseType;
private final String namespaceOrAlias;
private boolean collection;
private ODataJClientEdmPrimitiveType simpleType;
private EnumType enumType;
private ComplexType complexType;
private EntityType entityType;
/**
* Constructor.
*
* @param typeExpression type expression.
*/
public ODataJClientEdmType(final String typeExpression) {
this(null, typeExpression);
}
/**
* Constructor.
*
* @param metadata metadata.
* @param typeExpression type expression.
*/
public ODataJClientEdmType(final XMLMetadata metadata, final String typeExpression) {
this.typeExpression = typeExpression;
final int collectionStartIdx = typeExpression.indexOf("Collection(");
final int collectionEndIdx = typeExpression.lastIndexOf(')');
if (collectionStartIdx == -1) {
baseType = typeExpression;
} else {
if (collectionEndIdx == -1) {
throw new IllegalArgumentException("Malformed type: " + typeExpression);
}
this.collection = true;
baseType = typeExpression.substring(collectionStartIdx + 11, collectionEndIdx);
}
final int lastDotIdx = baseType.lastIndexOf('.');
if (lastDotIdx == -1) {
throw new IllegalArgumentException("Cannot find namespace or alias in " + typeExpression);
}
namespaceOrAlias = baseType.substring(0, lastDotIdx);
final String typeName = baseType.substring(lastDotIdx + 1);
if (StringUtils.isBlank(typeName)) {
throw new IllegalArgumentException("Null or empty type name in " + typeExpression);
}
if (namespaceOrAlias.equals(ODataJClientEdmPrimitiveType.namespace())) {
this.simpleType = ODataJClientEdmPrimitiveType.fromValue(
ODataJClientEdmPrimitiveType.namespace() + "." + typeName);
} else if (metadata != null) {
if (!metadata.isNsOrAlias(namespaceOrAlias)) {
throw new IllegalArgumentException("Illegal namespace or alias: " + namespaceOrAlias);
}
final Schema schema = metadata.getSchema(namespaceOrAlias);
for (EnumType type : schema.getEnumTypes()) {
if (typeName.equals(type.getName())) {
this.enumType = type;
}
}
if (this.enumType == null) {
for (ComplexType type : schema.getComplexTypes()) {
if (typeName.equals(type.getName())) {
this.complexType = type;
}
}
if (this.complexType == null) {
for (EntityType type : schema.getEntityTypes()) {
if (typeName.equals(type.getName())) {
this.entityType = type;
}
}
}
}
if (!isSimpleType() && !isEnumType() && !isComplexType() && !isEntityType()) {
throw new IllegalArgumentException("Could not parse type information out of " + typeExpression);
}
}
}
/**
* Checks if is a collection.
*
* @return 'TRUE' if is a collection; 'FALSE' otherwise.
*/
public final boolean isCollection() {
return this.collection;
}
/**
* Checks if is a simple type.
*
* @return 'TRUE' if is a simple type; 'FALSE' otherwise.
*/
public final boolean isSimpleType() {
return this.simpleType != null;
}
/**
* Gets type as a simple type.
*
* @return simple type. An <tt>EdmTypeNotFoundException</tt> will be raised if it is not a simple type.
*/
public final ODataJClientEdmPrimitiveType getSimpleType() {
if (!isSimpleType()) {
throw new IllegalArgumentException("Cannot find Primitive in " + this.typeExpression);
}
return this.simpleType;
}
/**
* Checks if is an enum type.
*
* @return 'TRUE' if is an enum type; 'FALSE' otherwise.
*/
public final boolean isEnumType() {
return this.enumType != null;
}
/**
* Gets type as enum type.
*
* @return enum type. An <tt>EdmTypeNotFoundException</tt> will be raised if it is not an enum type.
*/
public final EnumType getEnumType() {
if (!isEnumType()) {
throw new IllegalArgumentException("Cannot find Enum in " + this.typeExpression);
}
return this.enumType;
}
/**
* Checks if is a complex type.
*
* @return 'TRUE' if is a complex type; 'FALSE' otherwise.
*/
public final boolean isComplexType() {
return this.complexType != null;
}
/**
* Gets type as complex type.
*
* @return complex type. An <tt>EdmTypeNotFoundException</tt> will be raised if it is not a complex type.
*/
public final ComplexType getComplexType() {
if (!isComplexType()) {
throw new IllegalArgumentException("Cannot find Complex in " + this.typeExpression);
}
return this.complexType;
}
/**
* Checks if is an entity type.
*
* @return 'TRUE' if is an entity type; 'FALSE' otherwise.
*/
public final boolean isEntityType() {
return this.entityType != null;
}
/**
* Gets type as entity type.
*
* @return entity type. An <tt>EdmTypeNotFoundException</tt> will be raised if it is not an entity type.
*/
public final EntityType getEntityType() {
if (!isEntityType()) {
throw new IllegalArgumentException("Cannot find Entity in " + this.typeExpression);
}
return this.entityType;
}
/**
* Gets base type.
*
* @return base type.
*/
public String getBaseType() {
return baseType;
}
/**
* Gets type expression.
*
* @return type expression.
*/
public String getTypeExpression() {
return typeExpression;
}
/**
* Gets namespace or alias retrieved from the provided type expression.
*
* @return namespace or alias.
*/
public String getNamespaceOrAlias() {
return namespaceOrAlias;
}
}

View File

@ -0,0 +1,110 @@
/*
* 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.olingo.client.api.domain;
import java.net.URI;
import org.apache.olingo.client.api.ODataClient;
import org.apache.olingo.client.api.data.LinkType;
import org.apache.olingo.client.api.utils.URIUtils;
import org.apache.olingo.commons.api.edm.constants.ODataServiceVersion;
/**
* OData link.
*/
public class ODataLink extends ODataItem {
private static final long serialVersionUID = 7274966414277952124L;
protected final ODataClient client;
/**
* Link type.
*/
protected final LinkType type;
/**
* Link rel.
*/
protected final String rel;
/**
* Constructor.
*
* @param client OData client.
* @param uri URI.
* @param type type.
* @param title title.
*/
public ODataLink(final ODataClient client, final URI uri, final LinkType type, final String title) {
super(title);
this.client = client;
this.link = uri;
this.type = type;
switch (this.type) {
case ASSOCIATION:
this.rel = client.getServiceVersion().getNamespaceMap().get(ODataServiceVersion.ASSOCIATION_LINK_REL) + title;
break;
case ENTITY_NAVIGATION:
case ENTITY_SET_NAVIGATION:
this.rel = client.getServiceVersion().getNamespaceMap().get(ODataServiceVersion.NAVIGATION_LINK_REL) + title;
break;
case MEDIA_EDIT:
default:
this.rel = client.getServiceVersion().getNamespaceMap().get(ODataServiceVersion.MEDIA_EDIT_LINK_REL) + title;
break;
}
}
/**
* Constructor.
*
* @param client OData client.
* @param baseURI base URI.
* @param href href.
* @param type type.
* @param title title.
*/
public ODataLink(final ODataClient client,
final URI baseURI, final String href, final LinkType type, final String title) {
this(client, URIUtils.getURI(baseURI, href), type, title);
}
/**
* Gets link type.
*
* @return link type;
*/
public LinkType getType() {
return type;
}
/**
* Gets link rel.
*
* @return link rel
*/
public String getRel() {
return rel;
}
}

View File

@ -0,0 +1,100 @@
/*
* 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.olingo.client.api.domain;
import java.net.URI;
import java.util.List;
/**
* Link collection wrapper.
*/
public class ODataLinkCollection {
/**
* Link to the next page.
*/
private URI next;
/**
* Contained links.
*/
private List<URI> links;
/**
* Constructor.
*/
public ODataLinkCollection() {
}
/**
* Adds link to the collection.
*
* @param link link to be added.
* @return 'TRUE' in case of success; 'FALSE' otherwise.
*/
public boolean addLink(final URI link) {
return links.add(link);
}
/**
* Removes a link.
*
* @param link link to be removed.
* @return 'TRUE' in case of success; 'FALSE' otherwise.
*/
public boolean removeLink(final URI link) {
return links.remove(link);
}
/**
* Set links.
*
* @param links links.
*/
public void setLinks(final List<URI> links) {
this.links = links;
}
/**
* Gets contained links.
*
* @return list of links.
*/
public List<URI> getLinks() {
return links;
}
/**
* Constructor.
*
* @param next next page link.
*/
public ODataLinkCollection(final URI next) {
this.next = next;
}
/**
* Gets next page link.
*
* @return next page link; null value if single page or last page reached.
*/
public URI getNext() {
return next;
}
}

View File

@ -0,0 +1,218 @@
/*
* 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.olingo.client.api.domain;
import java.net.URI;
import org.apache.olingo.client.api.domain.ODataCollectionValue;
import org.apache.olingo.client.api.domain.ODataComplexValue;
import org.apache.olingo.client.api.domain.ODataEntity;
import org.apache.olingo.client.api.domain.ODataEntitySet;
import org.apache.olingo.client.api.domain.ODataInlineEntity;
import org.apache.olingo.client.api.domain.ODataInlineEntitySet;
import org.apache.olingo.client.api.domain.ODataLink;
import org.apache.olingo.client.api.domain.ODataPrimitiveValue;
import org.apache.olingo.client.api.domain.ODataProperty;
/**
* Entry point for generating OData domain objects.
*
* @see ODataEntitySet
* @see ODataEntity
* @see ODataProperty
* @see ODataLink
*/
public interface ODataObjectFactory {
/**
* Instantiates a new entity set.
*
* @return entity set.
*/
ODataEntitySet newEntitySet();
/**
* Instantiates a new entity set.
*
* @param next next link.
* @return entity set.
*/
ODataEntitySet newEntitySet(URI next);
/**
* Instantiates a new entity.
*
* @param name OData entity name.
* @return entity.
*/
ODataEntity newEntity(String name);
/**
* Instantiates a new entity.
*
* @param name OData entity name.
* @param link self link.
* @return entity.
*/
ODataEntity newEntity(String name, URI link);
/**
* Instantiates a new in-line entity set.
*
* @param name name.
* @param link edit link.
* @param entitySet entity set.
* @return in-line entity set.
*/
ODataInlineEntitySet newInlineEntitySet(String name, URI link, ODataEntitySet entitySet);
/**
* Instantiates a new in-line entity set.
*
* @param name name.
* @param baseURI base URI.
* @param href href.
* @param entitySet entity set.
* @return in-line entity set.
*/
ODataInlineEntitySet newInlineEntitySet(String name, URI baseURI, String href, ODataEntitySet entitySet);
/**
* Instantiates a new in-line entity.
*
* @param name name.
* @param link edit link.
* @param entity entity.
* @return in-line entity.
*/
ODataInlineEntity newInlineEntity(String name, URI link, ODataEntity entity);
/**
* Instantiates a new in-line entity.
*
* @param name name.
* @param baseURI base URI.
* @param href href.
* @param entity entity.
* @return in-line entity.
*/
ODataInlineEntity newInlineEntity(String name, URI baseURI, String href, ODataEntity entity);
/**
* Instantiates a new entity navigation link.
*
* @param name name.
* @param link link.
* @return entity navigation link.
*/
ODataLink newEntityNavigationLink(String name, URI link);
/**
* Instantiates a new entity navigation link.
*
* @param name name.
* @param baseURI base URI.
* @param href href.
* @return entity navigation link.
*/
ODataLink newEntityNavigationLink(String name, URI baseURI, String href);
/**
* Instantiates a new entity set navigation link.
*
* @param name name.
* @param link link.
* @return entity set navigation link.
*/
ODataLink newFeedNavigationLink(String name, URI link);
/**
* Instantiates a new entity set navigation link.
*
* @param name name.
* @param baseURI base URI.
* @param href href.
* @return entity set navigation link.
*/
ODataLink newFeedNavigationLink(String name, URI baseURI, String href);
/**
* Instantiates a new association link.
*
* @param name name.
* @param link link.
* @return association link.
*/
ODataLink newAssociationLink(String name, URI link);
/**
* Instantiates a new association link.
*
* @param name name.
* @param baseURI base URI.
* @param href href.
* @return association link.
*/
ODataLink newAssociationLink(String name, URI baseURI, String href);
/**
* Instantiates a new media-edit link.
*
* @param name name.
* @param link link.
* @return media-edit link.
*/
ODataLink newMediaEditLink(String name, URI link);
/**
* Instantiates a new media-edit link.
*
* @param name name.
* @param baseURI base URI.
* @param href href.
* @return media-edit link.
*/
ODataLink newMediaEditLink(String name, URI baseURI, String href);
/**
* Instantiates a new primitive property.
*
* @param name name.
* @param value value.
* @return primitive property.
*/
ODataProperty newPrimitiveProperty(String name, ODataPrimitiveValue value);
/**
* Instantiates a new complex property.
*
* @param name name.
* @param value value.
* @return complex property.
*/
ODataProperty newComplexProperty(String name, ODataComplexValue value);
/**
* Instantiates a new collection property.
*
* @param name name.
* @param value value.
* @return collection property.
*/
ODataProperty newCollectionProperty(String name, ODataCollectionValue value);
}

View File

@ -31,7 +31,7 @@ import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.olingo.client.api.ODataClient;
import org.apache.olingo.client.api.domain.EdmSimpleType;
import org.apache.olingo.client.api.domain.ODataJClientEdmPrimitiveType;
import org.apache.olingo.client.api.domain.ODataDuration;
import org.apache.olingo.client.api.domain.ODataTimestamp;
import org.apache.olingo.client.api.domain.ODataValue;
@ -54,7 +54,7 @@ public class ODataPrimitiveValue extends ODataValue {
this.client = client;
}
public AbstractBuilder isSupported(final EdmSimpleType type) {
public AbstractBuilder isSupported(final ODataJClientEdmPrimitiveType type) {
if (type != null && !ArrayUtils.contains(type.getSupportedVersions(), client.getServiceVersion())) {
throw new IllegalArgumentException(String.format(
"Type %s not supported by the current OData working version", type.toString()));
@ -107,12 +107,12 @@ public class ODataPrimitiveValue extends ODataValue {
* @param type type.
* @return the current builder.
*/
public Builder setType(final EdmSimpleType type) {
public Builder setType(final ODataJClientEdmPrimitiveType type) {
isSupported(type);
if (type == EdmSimpleType.Stream) {
if (type == ODataJClientEdmPrimitiveType.Stream) {
throw new IllegalArgumentException(String.format(
"Cannot build a primitive value for %s", EdmSimpleType.Stream.toString()));
"Cannot build a primitive value for %s", ODataJClientEdmPrimitiveType.Stream.toString()));
}
this.opv.type = type;
@ -133,7 +133,7 @@ public class ODataPrimitiveValue extends ODataValue {
}
if (this.opv.type == null) {
this.opv.type = EdmSimpleType.String;
this.opv.type = ODataJClientEdmPrimitiveType.String;
}
if (this.opv.type.isGeospatial()) {
@ -181,7 +181,7 @@ public class ODataPrimitiveValue extends ODataValue {
/**
* Value type.
*/
protected EdmSimpleType type;
protected ODataJClientEdmPrimitiveType type;
/**
* Protected constructor, need to use the builder to instantiate this class.

View File

@ -23,6 +23,10 @@ import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.olingo.client.api.domain.ODataCollectionValue;
import org.apache.olingo.client.api.domain.ODataComplexValue;
import org.apache.olingo.client.api.domain.ODataPrimitiveValue;
import org.apache.olingo.client.api.domain.ODataValue;
/**
* OData entity property.
@ -71,7 +75,7 @@ public class ODataProperty implements Serializable, ODataInvokeResult {
* @param name property name.
* @param value property value.
*/
ODataProperty(final String name, final ODataValue value) {
public ODataProperty(final String name, final ODataValue value) {
this.name = name;
this.value = value;
}

View File

@ -41,17 +41,17 @@ public final class ODataTimestamp implements Serializable {
private final boolean offset;
public static ODataTimestamp getInstance(final EdmSimpleType type, final Timestamp timestamp) {
public static ODataTimestamp getInstance(final ODataJClientEdmPrimitiveType type, final Timestamp timestamp) {
return new ODataTimestamp(new SimpleDateFormat(type.pattern()),
new Date(timestamp.getTime()), timestamp.getNanos(), type == EdmSimpleType.DateTimeOffset);
new Date(timestamp.getTime()), timestamp.getNanos(), type == ODataJClientEdmPrimitiveType.DateTimeOffset);
}
public static ODataTimestamp parse(final EdmSimpleType type, final String input) {
public static ODataTimestamp parse(final ODataJClientEdmPrimitiveType type, final String input) {
final ODataTimestamp instance;
final String[] dateParts = input.split("\\.");
final SimpleDateFormat sdf = new SimpleDateFormat(type.pattern());
final boolean isOffset = type == EdmSimpleType.DateTimeOffset;
final boolean isOffset = type == ODataJClientEdmPrimitiveType.DateTimeOffset;
try {
final Date date = sdf.parse(dateParts[0]);

View File

@ -24,7 +24,7 @@ import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.olingo.client.api.domain.EdmSimpleType;
import org.apache.olingo.client.api.domain.ODataJClientEdmPrimitiveType;
/**
* Base class for all geospatial info.
@ -129,7 +129,7 @@ public abstract class Geospatial implements Serializable {
this.srid = srid;
}
public abstract EdmSimpleType getEdmSimpleType();
public abstract ODataJClientEdmPrimitiveType getEdmSimpleType();
/**
* {@inheritDoc }

View File

@ -20,7 +20,7 @@ package org.apache.olingo.client.api.domain.geospatial;
import java.util.List;
import org.apache.olingo.client.api.domain.EdmSimpleType;
import org.apache.olingo.client.api.domain.ODataJClientEdmPrimitiveType;
/**
* Wrapper for a collection of geospatials info.
@ -40,9 +40,9 @@ public class GeospatialCollection extends ComposedGeospatial<Geospatial> {
}
@Override
public EdmSimpleType getEdmSimpleType() {
public ODataJClientEdmPrimitiveType getEdmSimpleType() {
return dimension == Dimension.GEOGRAPHY
? EdmSimpleType.GeographyCollection
: EdmSimpleType.GeometryCollection;
? ODataJClientEdmPrimitiveType.GeographyCollection
: ODataJClientEdmPrimitiveType.GeometryCollection;
}
}

View File

@ -20,7 +20,7 @@ package org.apache.olingo.client.api.domain.geospatial;
import java.util.List;
import org.apache.olingo.client.api.domain.EdmSimpleType;
import org.apache.olingo.client.api.domain.ODataJClientEdmPrimitiveType;
public class LineString extends ComposedGeospatial<Point> {
@ -31,9 +31,9 @@ public class LineString extends ComposedGeospatial<Point> {
}
@Override
public EdmSimpleType getEdmSimpleType() {
public ODataJClientEdmPrimitiveType getEdmSimpleType() {
return dimension == Dimension.GEOGRAPHY
? EdmSimpleType.GeographyLineString
: EdmSimpleType.GeometryLineString;
? ODataJClientEdmPrimitiveType.GeographyLineString
: ODataJClientEdmPrimitiveType.GeometryLineString;
}
}

View File

@ -20,7 +20,7 @@ package org.apache.olingo.client.api.domain.geospatial;
import java.util.List;
import org.apache.olingo.client.api.domain.EdmSimpleType;
import org.apache.olingo.client.api.domain.ODataJClientEdmPrimitiveType;
public class MultiLineString extends ComposedGeospatial<LineString> {
@ -31,9 +31,9 @@ public class MultiLineString extends ComposedGeospatial<LineString> {
}
@Override
public EdmSimpleType getEdmSimpleType() {
public ODataJClientEdmPrimitiveType getEdmSimpleType() {
return dimension == Dimension.GEOGRAPHY
? EdmSimpleType.GeographyMultiLineString
: EdmSimpleType.GeometryMultiLineString;
? ODataJClientEdmPrimitiveType.GeographyMultiLineString
: ODataJClientEdmPrimitiveType.GeometryMultiLineString;
}
}

View File

@ -20,7 +20,7 @@ package org.apache.olingo.client.api.domain.geospatial;
import java.util.List;
import org.apache.olingo.client.api.domain.EdmSimpleType;
import org.apache.olingo.client.api.domain.ODataJClientEdmPrimitiveType;
public class MultiPoint extends ComposedGeospatial<Point> {
@ -31,9 +31,9 @@ public class MultiPoint extends ComposedGeospatial<Point> {
}
@Override
public EdmSimpleType getEdmSimpleType() {
public ODataJClientEdmPrimitiveType getEdmSimpleType() {
return dimension == Dimension.GEOGRAPHY
? EdmSimpleType.GeographyMultiPoint
: EdmSimpleType.GeometryMultiPoint;
? ODataJClientEdmPrimitiveType.GeographyMultiPoint
: ODataJClientEdmPrimitiveType.GeometryMultiPoint;
}
}

View File

@ -20,7 +20,7 @@ package org.apache.olingo.client.api.domain.geospatial;
import java.util.List;
import org.apache.olingo.client.api.domain.EdmSimpleType;
import org.apache.olingo.client.api.domain.ODataJClientEdmPrimitiveType;
public class MultiPolygon extends ComposedGeospatial<Polygon> {
@ -31,9 +31,9 @@ public class MultiPolygon extends ComposedGeospatial<Polygon> {
}
@Override
public EdmSimpleType getEdmSimpleType() {
public ODataJClientEdmPrimitiveType getEdmSimpleType() {
return dimension == Dimension.GEOGRAPHY
? EdmSimpleType.GeographyMultiPolygon
: EdmSimpleType.GeometryMultiPolygon;
? ODataJClientEdmPrimitiveType.GeographyMultiPolygon
: ODataJClientEdmPrimitiveType.GeometryMultiPolygon;
}
}

View File

@ -18,7 +18,7 @@
*/
package org.apache.olingo.client.api.domain.geospatial;
import org.apache.olingo.client.api.domain.EdmSimpleType;
import org.apache.olingo.client.api.domain.ODataJClientEdmPrimitiveType;
public class Point extends Geospatial {
@ -69,9 +69,9 @@ public class Point extends Geospatial {
}
@Override
public EdmSimpleType getEdmSimpleType() {
public ODataJClientEdmPrimitiveType getEdmSimpleType() {
return dimension == Dimension.GEOGRAPHY
? EdmSimpleType.GeographyPoint
: EdmSimpleType.GeometryPoint;
? ODataJClientEdmPrimitiveType.GeographyPoint
: ODataJClientEdmPrimitiveType.GeometryPoint;
}
}

View File

@ -20,7 +20,7 @@ package org.apache.olingo.client.api.domain.geospatial;
import java.util.List;
import org.apache.olingo.client.api.domain.EdmSimpleType;
import org.apache.olingo.client.api.domain.ODataJClientEdmPrimitiveType;
/**
* Polygon.
@ -65,9 +65,9 @@ public class Polygon extends Geospatial {
}
@Override
public EdmSimpleType getEdmSimpleType() {
public ODataJClientEdmPrimitiveType getEdmSimpleType() {
return dimension == Dimension.GEOGRAPHY
? EdmSimpleType.GeographyPolygon
: EdmSimpleType.GeometryPolygon;
? ODataJClientEdmPrimitiveType.GeographyPolygon
: ODataJClientEdmPrimitiveType.GeometryPolygon;
}
}

View File

@ -19,12 +19,68 @@
package org.apache.olingo.client.api.op;
import java.io.Serializable;
import java.net.URI;
import org.apache.olingo.client.api.data.Entry;
import org.apache.olingo.client.api.data.Feed;
import org.apache.olingo.client.api.data.Link;
import org.apache.olingo.client.api.data.LinkCollection;
import org.apache.olingo.client.api.data.ServiceDocument;
import org.apache.olingo.client.api.domain.ODataEntity;
import org.apache.olingo.client.api.domain.ODataEntitySet;
import org.apache.olingo.client.api.domain.ODataLink;
import org.apache.olingo.client.api.domain.ODataLinkCollection;
import org.apache.olingo.client.api.domain.ODataProperty;
import org.apache.olingo.client.api.domain.ODataServiceDocument;
import org.apache.olingo.client.api.format.ODataPubFormat;
import org.w3c.dom.Element;
public interface ODataBinder extends Serializable {
/**
* Gets a <tt>Feed</tt> from the given OData entity set.
*
* @param feed OData entity set.
* @param reference reference class.
* @return <tt>Feed</tt> object.
*/
Feed getFeed(ODataEntitySet feed, Class<? extends Feed> reference);
/**
* Gets an <tt>Entry</tt> from the given OData entity.
*
* @param entity OData entity.
* @param reference reference class.
* @return <tt>Entry</tt> object.
*/
Entry getEntry(ODataEntity entity, Class<? extends Entry> reference);
/**
* Gets an <tt>Entry</tt> from the given OData entity.
*
* @param entity OData entity.
* @param reference reference class.
* @param setType whether to explicitly output type information.
* @return <tt>Entry</tt> object.
*/
Entry getEntry(ODataEntity entity, Class<? extends Entry> reference, boolean setType);
/**
* Gets a <tt>Link</tt> from the given OData link.
*
* @param link OData link.
* @param isXML whether it is JSON or XML / Atom
* @return <tt>Link</tt> object.
*/
Link getLink(ODataLink link, boolean isXML);
/**
* Gets the given OData property as DOM element.
*
* @param prop OData property.
* @return <tt>Element</tt> object.
*/
Element toDOMElement(ODataProperty prop);
/**
* Gets <tt>ODataServiceDocument</tt> from the given service document resource.
*
@ -33,49 +89,14 @@ public interface ODataBinder extends Serializable {
*/
ODataServiceDocument getODataServiceDocument(ServiceDocument resource);
/**
* Gets a <tt>FeedResource</tt> from the given OData entity set.
*
* @param <T> feed resource type.
* @param feed OData entity set.
* @param reference reference class.
* @return <tt>FeedResource</tt> object.
*/
// <T extends Feed> T getFeed(ODataEntitySet feed, Class<T> reference);
/**
* Gets an <tt>EntryResource</tt> from the given OData entity.
*
* @param <T> entry resource type.
* @param entity OData entity.
* @param reference reference class.
* @return <tt>EntryResource</tt> object.
*/
// <T extends Entry> T getEntry(ODataEntity entity, Class<T> reference);
/**
* Gets an <tt>EntryResource</tt> from the given OData entity.
*
* @param <T> entry resource type.
* @param entity OData entity.
* @param reference reference class.
* @param setType whether to explicitly output type information.
* @return <tt>EntryResource</tt> object.
*/
// <T extends Entry> T getEntry(ODataEntity entity, Class<T> reference, boolean setType);
/**
* Gets the given OData property as DOM element.
*
* @param prop OData property.
* @return <tt>Element</tt> object.
*/
// Element toDOMElement(ODataProperty prop);
// ODataLinkCollection getLinkCollection(LinkCollection linkCollection);
/**
* Gets <tt>ODataEntitySet</tt> from the given feed resource.
*
* @param resource feed resource.
* @return <tt>ODataEntitySet</tt> object.
*/
// ODataEntitySet getODataEntitySet(Feed resource);
ODataEntitySet getODataEntitySet(Feed resource);
/**
* Gets <tt>ODataEntitySet</tt> from the given feed resource.
*
@ -83,14 +104,16 @@ public interface ODataBinder extends Serializable {
* @param defaultBaseURI default base URI.
* @return <tt>ODataEntitySet</tt> object.
*/
// ODataEntitySet getODataEntitySet(Feed resource, URI defaultBaseURI);
ODataEntitySet getODataEntitySet(Feed resource, URI defaultBaseURI);
/**
* Gets <tt>ODataEntity</tt> from the given entry resource.
*
* @param resource entry resource.
* @return <tt>ODataEntity</tt> object.
*/
// ODataEntity getODataEntity(Entry resource);
ODataEntity getODataEntity(Entry resource);
/**
* Gets <tt>ODataEntity</tt> from the given entry resource.
*
@ -98,17 +121,7 @@ public interface ODataBinder extends Serializable {
* @param defaultBaseURI default base URI.
* @return <tt>ODataEntity</tt> object.
*/
// ODataEntity getODataEntity(Entry resource, URI defaultBaseURI);
/**
* Gets a <tt>LinkResource</tt> from the given OData link.
*
* @param <T> link resource type.
* @param link OData link.
* @param reference reference class.
* @return <tt>LinkResource</tt> object.
*/
// @SuppressWarnings("unchecked")
// <T extends Link> T getLinkResource(ODataLink link, Class<T> reference);
ODataEntity getODataEntity(Entry resource, URI defaultBaseURI);
/**
* Gets an <tt>ODataProperty</tt> from the given DOM element.
@ -116,7 +129,13 @@ public interface ODataBinder extends Serializable {
* @param property content.
* @return <tt>ODataProperty</tt> object.
*/
// ODataProperty getProperty(Element property);
ODataProperty getODataProperty(Element property);
/**
* Gets <tt>ODataLinkCollection</tt> from the given link collection resource.
*
* @param resource link collection resource.
* @return <tt>ODataLinkCollection</tt> object.
*/
ODataLinkCollection getLinkCollection(LinkCollection resource);
}

View File

@ -20,10 +20,14 @@ package org.apache.olingo.client.api.op;
import java.io.InputStream;
import java.io.Serializable;
import org.apache.olingo.client.api.data.Entry;
import org.apache.olingo.client.api.data.Error;
import org.apache.olingo.client.api.data.Feed;
import org.apache.olingo.client.api.data.LinkCollection;
import org.apache.olingo.client.api.data.ServiceDocument;
import org.apache.olingo.client.api.edm.xml.XMLMetadata;
import org.apache.olingo.client.api.format.ODataFormat;
import org.apache.olingo.client.api.format.ODataPubFormat;
import org.w3c.dom.Element;
/**
@ -34,48 +38,41 @@ public interface ODataDeserializer extends Serializable {
XMLMetadata toMetadata(InputStream input);
/**
* Gets the ServiceDocumentResource object represented by the given InputStream.
* Gets the ServiceDocument object represented by the given InputStream.
*
* @param input stream to be de-serialized.
* @param format OData service document format.
* @return ServiceDocumentResource object.
* @return <tt>ServiceDocument</tt> object.
*/
ServiceDocument toServiceDocument(InputStream input, ODataFormat format);
/**
* Gets a feed object from the given InputStream.
*
* @param <T> reference class type
* @param input stream to be de-serialized.
* @param reference reference class (AtomFeed.class, JSONFeed.class).
* @return FeedResource instance.
* @param format Atom or JSON
* @return Feed instance.
*/
// <T extends Feed> T toFeed(InputStream input, Class<T> reference);
Feed toFeed(InputStream input, ODataPubFormat format);
/**
* Gets an entry object from the given InputStream.
*
* @param <T> reference class type
* @param input stream to be de-serialized.
* @param reference reference class (AtomEntry.class, JSONV3Entry.class).
* @return EntryResource instance.
* @param format Atom or JSON
* @return Entry instance.
*/
// <T extends Entry> T toEntry(InputStream input, Class<T> reference);
Entry toEntry(InputStream input, ODataPubFormat format);
/**
* Gets a DOM representation of the given InputStream.
*
* @param input stream to be de-serialized.
* @param format OData format.
* @param format XML or JSON
* @return DOM.
*/
// Element toPropertyDOM(InputStream input, ODataFormat format);
/**
* Gets a list of links from the given InputStream.
*
* @param input stream to be de-serialized.
* @param format OData format.
* @return de-serialized links.
*/
// LinkCollection toLinkCollection(InputStream input, ODataFormat format);
Element toPropertyDOM(InputStream input, ODataFormat format);
/**
* Gets the ODataError object represented by the given InputStream.
*
@ -83,7 +80,8 @@ public interface ODataDeserializer extends Serializable {
* @param isXML 'TRUE' if the error is represented by XML; 'FALSE' otherwise.
* @return
*/
// ODataError toODataError(InputStream input, boolean isXML);
Error toError(InputStream input, boolean isXML);
/**
* Parses the given input into a DOM tree.
*
@ -91,4 +89,14 @@ public interface ODataDeserializer extends Serializable {
* @return DOM tree
*/
Element toDOM(InputStream input);
/**
* Gets a list of links from the given InputStream.
*
* @param input stream to be de-serialized.
* @param format OData format.
* @return de-serialized links.
*/
LinkCollection toLinkCollection(InputStream input, ODataFormat format);
}

View File

@ -20,9 +20,14 @@ package org.apache.olingo.client.api.op;
import java.io.InputStream;
import java.io.Serializable;
import org.apache.olingo.client.api.data.Error;
import org.apache.olingo.client.api.domain.ODataEntity;
import org.apache.olingo.client.api.domain.ODataEntitySet;
import org.apache.olingo.client.api.domain.ODataLinkCollection;
import org.apache.olingo.client.api.domain.ODataProperty;
import org.apache.olingo.client.api.domain.ODataServiceDocument;
import org.apache.olingo.client.api.format.ODataFormat;
import org.apache.olingo.client.api.format.ODataPubFormat;
import org.apache.olingo.commons.api.edm.Edm;
/**
@ -58,7 +63,8 @@ public interface ODataReader extends Serializable {
* @param format de-serialize as AtomFeed or JSONFeed
* @return de-serialized entity set.
*/
//ODataEntitySet readEntitySet(InputStream input, ODataPubFormat format);
ODataEntitySet readEntitySet(InputStream input, ODataPubFormat format);
/**
* Parses a stream taking care to de-serializes the first OData entity found.
*
@ -66,7 +72,8 @@ public interface ODataReader extends Serializable {
* @param format de-serialize as AtomEntry or JSONEntry
* @return entity de-serialized.
*/
//ODataEntity readEntity(InputStream input, ODataPubFormat format);
ODataEntity readEntity(InputStream input, ODataPubFormat format);
/**
* Parses a stream taking care to de-serialize the first OData entity property found.
*
@ -74,7 +81,8 @@ public interface ODataReader extends Serializable {
* @param format de-serialize as XML or JSON
* @return OData entity property de-serialized.
*/
//ODataProperty readProperty(InputStream input, ODataFormat format);
ODataProperty readProperty(InputStream input, ODataFormat format);
/**
* Parses a $links request response.
*
@ -82,7 +90,8 @@ public interface ODataReader extends Serializable {
* @param format de-serialize as XML or JSON
* @return List of URIs.
*/
//ODataLinkCollection readLinks(InputStream input, ODataFormat format);
ODataLinkCollection readLinks(InputStream input, ODataFormat format);
/**
* Parses a stream into an OData error.
*
@ -90,7 +99,8 @@ public interface ODataReader extends Serializable {
* @param isXML 'TRUE' if the error is in XML format.
* @return OData error.
*/
// ODataError readError(InputStream inputStream, boolean isXML);
Error readError(InputStream inputStream, boolean isXML);
/**
* Parses a stream into the object type specified by the given reference.
*
@ -100,5 +110,5 @@ public interface ODataReader extends Serializable {
* @param reference reference.
* @return read object.
*/
//<T> T read(InputStream src, String format, Class<T> reference);
<T> T read(InputStream src, String format, Class<T> reference);
}

View File

@ -1,4 +1,4 @@
/**
/*
* 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
@ -21,6 +21,11 @@ package org.apache.olingo.client.api.op;
import java.io.OutputStream;
import java.io.Serializable;
import java.io.Writer;
import org.apache.olingo.client.api.data.Entry;
import org.apache.olingo.client.api.data.Feed;
import org.apache.olingo.client.api.data.Link;
import org.apache.olingo.client.api.format.ODataFormat;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
@ -28,91 +33,87 @@ import org.w3c.dom.Node;
*/
public interface ODataSerializer extends Serializable {
/**
* Writes <tt>FeedResource</tt> object onto the given stream.
*
* @param <T> feed resource type.
* @param obj object to be streamed.
* @param out output stream.
*/
// <T extends Feed> void feed(T obj, OutputStream out);
/**
* Writes Feed object onto the given stream.
*
* @param obj object to be streamed.
* @param out output stream.
*/
void feed(Feed obj, OutputStream out);
/**
* Writes <tt>FeedResource</tt> object by the given writer.
*
* @param <T> feed resource type.
* @param obj object to be streamed.
* @param writer writer.
*/
// <T extends Feed> void feed(T obj, Writer writer);
/**
* Writes Feed object by the given writer.
*
* @param obj object to be streamed.
* @param writer writer.
*/
void feed(Feed obj, Writer writer);
/**
* Writes <tt>EntryResource</tt> object onto the given stream.
*
* @param <T> entry resource type.
* @param obj object to be streamed.
* @param out output stream.
*/
// <T extends Entry> void entry(T obj, OutputStream out);
/**
* Writes theEntry object onto the given stream.
*
* @param obj object to be streamed.
* @param out output stream.
*/
void entry(Entry obj, OutputStream out);
/**
* Writes <tt>EntryResource</tt> object by the given writer.
*
* @param <T> entry resource type.
* @param obj object to be streamed.
* @param writer writer.
*/
// <T extends Entry> void entry(T obj, Writer writer);
/**
* Writes the Entry object by the given writer.
*
* @param obj object to be streamed.
* @param writer writer.
*/
void entry(Entry obj, Writer writer);
/**
* Writes entry content onto the given stream.
*
* @param element element to be streamed.
* @param format streaming format.
* @param out output stream.
*/
// void property(Element element, ODataFormat format, OutputStream out);
/**
* Writes entry content onto the given stream.
*
* @param element element to be streamed.
* @param format streaming format.
* @param out output stream.
*/
void property(Element element, ODataFormat format, OutputStream out);
/**
* Writes entry content by the given writer.
*
* @param element element to be streamed.
* @param format streaming format.
* @param writer writer.
*/
// void property(Element element, ODataFormat format, Writer writer);
/**
* Writes entry content by the given writer.
*
* @param element element to be streamed.
* @param format streaming format.
* @param writer writer.
*/
void property(Element element, ODataFormat format, Writer writer);
/**
* Writes OData link onto the given stream.
*
* @param link OData link to be streamed.
* @param format streaming format.
* @param out output stream.
*/
// void link(ODataLink link, ODataFormat format, OutputStream out);
/**
* Writes link onto the given stream.
*
* @param link OData link to be streamed.
* @param format streaming format.
* @param out output stream.
*/
void link(Link link, ODataFormat format, OutputStream out);
/**
* Writes OData link by the given writer.
*
* @param link OData link to be streamed.
* @param format streaming format.
* @param writer writer.
*/
// void link(ODataLink link, ODataFormat format, Writer writer);
/**
* Writes link by the given writer.
*
* @param link OData link to be streamed.
* @param format streaming format.
* @param writer writer.
*/
void link(Link link, ODataFormat format, Writer writer);
/**
* Writes DOM object onto the given stream.
*
* @param content DOM to be streamed.
* @param out output stream.
*/
void dom(Node content, OutputStream out);
/**
* Writes DOM object onto the given stream.
*
* @param content DOM to be streamed.
* @param out output stream.
*/
void dom(Node content, OutputStream out);
/**
* Writes DOM object by the given writer.
*
* @param content DOM to be streamed.
* @param writer writer.
*/
void dom(Node content, Writer writer);
/**
* Writes DOM object by the given writer.
*
* @param content DOM to be streamed.
* @param writer writer.
*/
void dom(Node content, Writer writer);
}

View File

@ -19,5 +19,13 @@
package org.apache.olingo.client.api.op;
public interface ODataV3Deserializer extends ODataDeserializer {
/**
* Gets a list of links from the given InputStream.
*
* @param input stream to be de-serialized.
* @param format OData format.
* @return de-serialized links.
*/
// LinkCollection toLinkCollection(InputStream input, ODataFormat format);
}

View File

@ -0,0 +1,94 @@
/*
* 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.olingo.client.api.op;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Collection;
import org.apache.olingo.client.api.domain.ODataEntity;
import org.apache.olingo.client.api.domain.ODataLink;
import org.apache.olingo.client.api.domain.ODataProperty;
import org.apache.olingo.client.api.format.ODataFormat;
import org.apache.olingo.client.api.format.ODataPubFormat;
/**
* OData writer.
* <br/>
* Use this interface to serialize an OData request body.
* <br/>
* This interface provides method helpers to serialize a set of entities and a single entity as well.
*/
public interface ODataWriter extends Serializable {
/**
* Writes a collection of OData entities.
*
* @param entities entities to be serialized.
* @param format serialization format.
* @return stream of serialized objects.
*/
InputStream writeEntities(Collection<ODataEntity> entities, ODataPubFormat format);
/**
* Writes a collection of OData entities.
*
* @param entities entities to be serialized.
* @param format serialization format.
* @param outputType whether to explicitly output type information.
* @return stream of serialized objects.
*/
InputStream writeEntities(Collection<ODataEntity> entities, ODataPubFormat format, boolean outputType);
/**
* Serializes a single OData entity.
*
* @param entity entity to be serialized.
* @param format serialization format.
* @return stream of serialized object.
*/
InputStream writeEntity(ODataEntity entity, ODataPubFormat format);
/**
* Serializes a single OData entity.
*
* @param entity entity to be serialized.
* @param format serialization format.
* @param outputType whether to explicitly output type information.
* @return stream of serialized object.
*/
InputStream writeEntity(ODataEntity entity, ODataPubFormat format, boolean outputType);
/**
* Writes a single OData entity property.
*
* @param property entity property to be serialized.
* @param format serialization format.
* @return stream of serialized object.
*/
InputStream writeProperty(ODataProperty property, ODataFormat format);
/**
* Writes an OData link.
*
* @param link link to be serialized.
* @param format serialization format.
* @return stream of serialized object.
*/
InputStream writeLink(ODataLink link, ODataFormat format);
}

View File

@ -16,11 +16,8 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.olingo.client.core.uri;
package org.apache.olingo.client.api.utils;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URLEncoder;
@ -28,11 +25,8 @@ import java.text.DecimalFormat;
import java.util.UUID;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.io.IOUtils;
import org.apache.http.entity.InputStreamEntity;
import org.apache.olingo.client.api.ODataClient;
import org.apache.olingo.client.api.ODataConstants;
import org.apache.olingo.client.api.domain.EdmSimpleType;
import org.apache.olingo.client.api.domain.ODataJClientEdmPrimitiveType;
import org.apache.olingo.client.api.domain.ODataDuration;
import org.apache.olingo.client.api.domain.ODataTimestamp;
import org.apache.olingo.client.api.edm.xml.CommonFunctionImport;
@ -157,11 +151,11 @@ public final class URIUtils {
: (obj instanceof ODataDuration)
? "time'" + ((ODataDuration) obj).toString() + "'"
: (obj instanceof BigDecimal)
? new DecimalFormat(EdmSimpleType.Decimal.pattern()).format((BigDecimal) obj) + "M"
? new DecimalFormat(ODataJClientEdmPrimitiveType.Decimal.pattern()).format((BigDecimal) obj) + "M"
: (obj instanceof Double)
? new DecimalFormat(EdmSimpleType.Double.pattern()).format((Double) obj) + "D"
? new DecimalFormat(ODataJClientEdmPrimitiveType.Double.pattern()).format((Double) obj) + "D"
: (obj instanceof Float)
? new DecimalFormat(EdmSimpleType.Single.pattern()).format((Float) obj) + "f"
? new DecimalFormat(ODataJClientEdmPrimitiveType.Single.pattern()).format((Float) obj) + "f"
: (obj instanceof Long)
? ((Long) obj).toString() + "L"
: (obj instanceof String)
@ -174,23 +168,4 @@ public final class URIUtils {
return value;
}
public static InputStreamEntity buildInputStreamEntity(final ODataClient client, final InputStream input) {
InputStreamEntity entity;
if (client.getConfiguration().isUseChuncked()) {
entity = new InputStreamEntity(input, -1);
} else {
byte[] bytes = new byte[0];
try {
bytes = IOUtils.toByteArray(input);
} catch (IOException e) {
LOG.error("While reading input for not chunked encoding", e);
}
entity = new InputStreamEntity(new ByteArrayInputStream(bytes), bytes.length);
}
entity.setChunked(client.getConfiguration().isUseChuncked());
return entity;
}
}

View File

@ -25,7 +25,7 @@ import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.commons.lang3.StringUtils;
import org.apache.olingo.client.api.Constants;
import org.apache.olingo.client.api.domain.EdmSimpleType;
import org.apache.olingo.client.api.domain.ODataJClientEdmPrimitiveType;
import org.apache.olingo.client.api.domain.geospatial.Geospatial;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
@ -138,39 +138,39 @@ public final class XMLUtils {
return result;
}
public static EdmSimpleType simpleTypeForNode(final Geospatial.Dimension dimension, final Node node) {
EdmSimpleType type = null;
public static ODataJClientEdmPrimitiveType simpleTypeForNode(final Geospatial.Dimension dimension, final Node node) {
ODataJClientEdmPrimitiveType type = null;
if (Constants.ELEM_POINT.equals(node.getNodeName())) {
type = dimension == Geospatial.Dimension.GEOGRAPHY
? EdmSimpleType.GeographyPoint
: EdmSimpleType.GeometryPoint;
? ODataJClientEdmPrimitiveType.GeographyPoint
: ODataJClientEdmPrimitiveType.GeometryPoint;
} else if (Constants.ELEM_MULTIPOINT.equals(node.getNodeName())) {
type = dimension == Geospatial.Dimension.GEOGRAPHY
? EdmSimpleType.GeographyMultiPoint
: EdmSimpleType.GeometryMultiPoint;
? ODataJClientEdmPrimitiveType.GeographyMultiPoint
: ODataJClientEdmPrimitiveType.GeometryMultiPoint;
} else if (Constants.ELEM_LINESTRING.equals(node.getNodeName())) {
type = dimension == Geospatial.Dimension.GEOGRAPHY
? EdmSimpleType.GeographyLineString
: EdmSimpleType.GeometryLineString;
? ODataJClientEdmPrimitiveType.GeographyLineString
: ODataJClientEdmPrimitiveType.GeometryLineString;
} else if (Constants.ELEM_MULTILINESTRING.equals(node.getNodeName())) {
type = dimension == Geospatial.Dimension.GEOGRAPHY
? EdmSimpleType.GeographyMultiLineString
: EdmSimpleType.GeometryMultiLineString;
? ODataJClientEdmPrimitiveType.GeographyMultiLineString
: ODataJClientEdmPrimitiveType.GeometryMultiLineString;
} else if (Constants.ELEM_POLYGON.equals(node.getNodeName())) {
type = dimension == Geospatial.Dimension.GEOGRAPHY
? EdmSimpleType.GeographyPolygon
: EdmSimpleType.GeometryPolygon;
? ODataJClientEdmPrimitiveType.GeographyPolygon
: ODataJClientEdmPrimitiveType.GeometryPolygon;
} else if (Constants.ELEM_MULTIPOLYGON.equals(node.getNodeName())) {
type = dimension == Geospatial.Dimension.GEOGRAPHY
? EdmSimpleType.GeographyMultiPolygon
: EdmSimpleType.GeometryMultiPolygon;
? ODataJClientEdmPrimitiveType.GeographyMultiPolygon
: ODataJClientEdmPrimitiveType.GeometryMultiPolygon;
} else if (Constants.ELEM_GEOCOLLECTION.equals(node.getNodeName())
|| Constants.ELEM_GEOMEMBERS.equals(node.getNodeName())) {
type = dimension == Geospatial.Dimension.GEOGRAPHY
? EdmSimpleType.GeographyCollection
: EdmSimpleType.GeometryCollection;
? ODataJClientEdmPrimitiveType.GeographyCollection
: ODataJClientEdmPrimitiveType.GeometryCollection;
}
return type;

View File

@ -20,18 +20,38 @@ package org.apache.olingo.client.core;
import org.apache.olingo.client.api.ODataClient;
import org.apache.olingo.client.api.domain.ODataGeospatialValue;
import org.apache.olingo.client.api.domain.ODataObjectFactory;
import org.apache.olingo.client.api.domain.ODataPrimitiveValue;
import org.apache.olingo.client.api.op.ODataWriter;
import org.apache.olingo.client.core.op.impl.ODataObjectFactoryImpl;
import org.apache.olingo.client.core.op.impl.ODataWriterImpl;
abstract class AbstractODataClient implements ODataClient {
private static final long serialVersionUID = 7269096702397630265L;
private final ODataWriter writer = new ODataWriterImpl(this);
private final ODataObjectFactory objectFactory = new ODataObjectFactoryImpl(this);
@Override
public ODataPrimitiveValue.Builder getPrimitiveValueBuilder() {
return new ODataPrimitiveValue.Builder(this);
}
@Override
public ODataGeospatialValue.Builder getGeospatialValueBuilder() {
return new ODataGeospatialValue.Builder(this);
}
@Override
public ODataWriter getWriter() {
return writer;
}
@Override
public ODataObjectFactory getObjectFactory() {
return objectFactory;
}
}

View File

@ -48,11 +48,8 @@ public class ODataV3ClientImpl extends AbstractODataClient implements ODataV3Cli
private final ODataReader reader = new ODataV3ReaderImpl(this);
// private final ODataWriterImpl writer = new ODataWriterImpl(this);
private final ODataBinder binder = new ODataV3BinderImpl(this);
// private final ODataObjectFactory objectFactory = new ODataObjectFactoryImpl(this);
//
// private final V3RetrieveRequestFactory retrieveReqFact = new V3RetrieveRequestFactory(this);
//
// private final V3CUDRequestFactory cudReqFact = new V3CUDRequestFactory(this);
@ -105,20 +102,11 @@ public class ODataV3ClientImpl extends AbstractODataClient implements ODataV3Cli
return reader;
}
// @Override
// public ODataWriterImpl getWriter() {
// return writer;
// }
@Override
public ODataBinder getBinder() {
return binder;
}
// @Override
// public ODataObjectFactoryImpl getObjectFactory() {
// return objectFactory;
// }
//
// @Override
// public V3RetrieveRequestFactory getRetrieveRequestFactory() {
// return retrieveReqFact;

View File

@ -48,11 +48,8 @@ public class ODataV4ClientImpl extends AbstractODataClient implements ODataV4Cli
private final ODataReader reader = new ODataV4ReaderImpl(this);
// private final ODataWriter writer = new ODataWriterImpl(this);
private final ODataBinder binder = new ODataV4BinderImpl(this);
// private final ODataObjectFactory objectFactory = new ODataObjectFactoryImpl(this);
//
// private final V4RetrieveRequestFactory retrieveReqFact = new V4RetrieveRequestFactory(this);
//
// private final V4CUDRequestFactory cudReqFact = new V4CUDRequestFactory(this);
@ -105,20 +102,11 @@ public class ODataV4ClientImpl extends AbstractODataClient implements ODataV4Cli
return reader;
}
// @Override
// public ODataWriterImpl getWriter() {
// return writer;
// }
@Override
public ODataBinder getBinder() {
return binder;
}
// @Override
// public ODataObjectFactoryImpl getObjectFactory() {
// return objectFactory;
// }
//
// @Override
// public V4RetrieveRequestFactory getRetrieveRequestFactory() {
// return retrieveReqFact;

View File

@ -0,0 +1,179 @@
/*
* 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.olingo.client.core.data;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.olingo.client.api.data.Entry;
import org.apache.olingo.client.api.data.Link;
import org.apache.olingo.client.api.data.Operation;
import org.w3c.dom.Element;
/**
* Abstract base for classes implementing an OData entry in Atom and JSON.
*/
public abstract class AbstractEntry extends AbstractPayloadObject implements Entry {
private static final long serialVersionUID = 2127764552600969783L;
private String eTag;
private String type;
private String id;
private Link readLink;
private Link editLink;
private final List<Link> associationLinks = new ArrayList<Link>();
private final List<Link> navigationLinks = new ArrayList<Link>();
private final List<Link> mediaEditLinks = new ArrayList<Link>();
private final List<Operation> operations = new ArrayList<Operation>();
private Element content;
private Element mediaEntryProperties;
private String mediaContentSource;
private String mediaContentType;
@Override
public String getETag() {
return eTag;
}
@Override
public void setETag(final String eTag) {
this.eTag = eTag;
}
@Override
public String getType() {
return type;
}
@Override
public void setType(final String type) {
this.type = type;
}
@Override
public String getId() {
return id;
}
@Override
public void setId(final String id) {
this.id = id;
}
@Override
public Link getSelfLink() {
return readLink;
}
@Override
public void setSelfLink(final Link readLink) {
this.readLink = readLink;
}
@Override
public Link getEditLink() {
return editLink;
}
@Override
public void setEditLink(final Link editLink) {
this.editLink = editLink;
}
@Override
public List<Link> getAssociationLinks() {
return associationLinks;
}
@Override
public List<Link> getNavigationLinks() {
return navigationLinks;
}
@Override
public List<Link> getMediaEditLinks() {
return mediaEditLinks;
}
@Override
public List<Operation> getOperations() {
return operations;
}
@Override
public Element getContent() {
return content;
}
@Override
public void setContent(final Element content) {
this.content = content;
}
/**
* {@inheritDoc }
*/
@Override
public Element getMediaEntryProperties() {
return mediaEntryProperties;
}
@Override
public void setMediaEntryProperties(final Element mediaEntryProperties) {
this.mediaEntryProperties = mediaEntryProperties;
}
@Override
public String getMediaContentType() {
return this.mediaContentType;
}
@Override
public void setMediaContentType(final String mediaContentType) {
this.mediaContentType = mediaContentType;
}
@Override
public String getMediaContentSource() {
return this.mediaContentSource;
}
@Override
public void setMediaContentSource(final String mediaContentSource) {
this.mediaContentSource = mediaContentSource;
}
@Override
public boolean isMediaEntry() {
return getMediaEntryProperties() != null || StringUtils.isNotBlank(this.mediaContentSource);
}
}

View File

@ -1,4 +1,4 @@
/*
/*
* 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
@ -16,38 +16,33 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.olingo.client.core.deserializer;
package org.apache.olingo.client.core.data;
import org.apache.olingo.client.api.deserializer.AnnotationProperty;
import java.io.Serializable;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
public class AnnotationPropertyImpl implements AnnotationProperty {
/**
* Abstract representation of a payload (Atom, JSON) object.
*/
public abstract class AbstractPayloadObject implements Serializable {
private final String name;
private static final long serialVersionUID = 1634654241914156675L;
private final String value;
public AnnotationPropertyImpl(final String name, final String value) {
this.name = name;
this.value = value;
@Override
public boolean equals(final Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
@Override
public String getName() {
return name;
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
@Override
public String getValue() {
return value;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "AnnotationPropertyImpl [name=" + name + ", value=" + value + "]";
return ReflectionToStringBuilder.toString(this, ToStringStyle.MULTI_LINE_STYLE);
}
}

View File

@ -0,0 +1,217 @@
/*
* 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.olingo.client.core.data;
import com.fasterxml.jackson.databind.util.ISO8601DateFormat;
import java.net.URI;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.olingo.client.api.ODataClient;
import org.apache.olingo.client.api.ODataConstants;
import org.apache.olingo.client.api.utils.XMLUtils;
import org.apache.olingo.commons.api.edm.constants.ODataServiceVersion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class AtomDeserializer {
private static final Logger LOG = LoggerFactory.getLogger(AtomDeserializer.class);
private static final ISO8601DateFormat ISO_DATEFORMAT = new ISO8601DateFormat();
private final ODataClient client;
public AtomDeserializer(final ODataClient client) {
this.client = client;
}
private void common(final Element input, final AtomObject object) {
if (StringUtils.isNotBlank(input.getAttribute(ODataConstants.ATTR_XMLBASE))) {
object.setBaseURI(input.getAttribute(ODataConstants.ATTR_XMLBASE));
}
final List<Element> ids = XMLUtils.getChildElements(input, ODataConstants.ATOM_ELEM_ID);
if (!ids.isEmpty()) {
object.setId(ids.get(0).getTextContent());
}
final List<Element> titles = XMLUtils.getChildElements(input, ODataConstants.ATOM_ELEM_TITLE);
if (!titles.isEmpty()) {
object.setTitle(titles.get(0).getTextContent());
}
final List<Element> summaries = XMLUtils.getChildElements(input, ODataConstants.ATOM_ELEM_SUMMARY);
if (!summaries.isEmpty()) {
object.setSummary(summaries.get(0).getTextContent());
}
final List<Element> updateds = XMLUtils.getChildElements(input, ODataConstants.ATOM_ELEM_UPDATED);
if (!updateds.isEmpty()) {
try {
object.setUpdated(ISO_DATEFORMAT.parse(updateds.get(0).getTextContent()));
} catch (Exception e) {
LOG.error("Could not parse date {}", updateds.get(0).getTextContent(), e);
}
}
}
public AtomEntryImpl entry(final Element input) {
if (!ODataConstants.ATOM_ELEM_ENTRY.equals(input.getNodeName())) {
return null;
}
final AtomEntryImpl entry = new AtomEntryImpl();
common(input, entry);
final String etag = input.getAttribute(ODataConstants.ATOM_ATTR_ETAG);
if (StringUtils.isNotBlank(etag)) {
entry.setETag(etag);
}
final List<Element> categories = XMLUtils.getChildElements(input, ODataConstants.ATOM_ELEM_CATEGORY);
if (!categories.isEmpty()) {
entry.setType(categories.get(0).getAttribute(ODataConstants.ATOM_ATTR_TERM));
}
final List<Element> links = XMLUtils.getChildElements(input, ODataConstants.ATOM_ELEM_LINK);
for (Element linkElem : links) {
final LinkImpl link = new LinkImpl();
link.setRel(linkElem.getAttribute(ODataConstants.ATTR_REL));
link.setTitle(linkElem.getAttribute(ODataConstants.ATTR_TITLE));
link.setHref(linkElem.getAttribute(ODataConstants.ATTR_HREF));
if (ODataConstants.SELF_LINK_REL.equals(link.getRel())) {
entry.setSelfLink(link);
} else if (ODataConstants.EDIT_LINK_REL.equals(link.getRel())) {
entry.setEditLink(link);
} else if (link.getRel().startsWith(
client.getServiceVersion().getNamespaceMap().get(ODataServiceVersion.NAVIGATION_LINK_REL))) {
link.setType(linkElem.getAttribute(ODataConstants.ATTR_TYPE));
entry.getNavigationLinks().add(link);
final List<Element> inlines = XMLUtils.getChildElements(linkElem, ODataConstants.ATOM_ELEM_INLINE);
if (!inlines.isEmpty()) {
final List<Element> entries =
XMLUtils.getChildElements(inlines.get(0), ODataConstants.ATOM_ELEM_ENTRY);
if (!entries.isEmpty()) {
link.setInlineEntry(entry(entries.get(0)));
}
final List<Element> feeds =
XMLUtils.getChildElements(inlines.get(0), ODataConstants.ATOM_ELEM_FEED);
if (!feeds.isEmpty()) {
link.setInlineFeed(feed(feeds.get(0)));
}
}
} else if (link.getRel().startsWith(
client.getServiceVersion().getNamespaceMap().get(ODataServiceVersion.ASSOCIATION_LINK_REL))) {
entry.getAssociationLinks().add(link);
} else if (link.getRel().startsWith(
client.getServiceVersion().getNamespaceMap().get(ODataServiceVersion.MEDIA_EDIT_LINK_REL))) {
entry.getMediaEditLinks().add(link);
}
}
final List<Element> authors = XMLUtils.getChildElements(input, ODataConstants.ATOM_ELEM_AUTHOR);
if (!authors.isEmpty()) {
final AtomEntryImpl.Author author = new AtomEntryImpl.Author();
for (Node child : XMLUtils.getChildNodes(input, Node.ELEMENT_NODE)) {
if (ODataConstants.ATOM_ELEM_AUTHOR_NAME.equals(XMLUtils.getSimpleName(child))) {
author.setName(child.getTextContent());
} else if (ODataConstants.ATOM_ELEM_AUTHOR_URI.equals(XMLUtils.getSimpleName(child))) {
author.setUri(child.getTextContent());
} else if (ODataConstants.ATOM_ELEM_AUTHOR_EMAIL.equals(XMLUtils.getSimpleName(child))) {
author.setEmail(child.getTextContent());
}
}
if (!author.isEmpty()) {
entry.setAuthor(author);
}
}
final List<Element> actions = XMLUtils.getChildElements(input, ODataConstants.ATOM_ELEM_ACTION);
for (Element action : actions) {
final OperationImpl operation = new OperationImpl();
operation.setMetadataAnchor(action.getAttribute(ODataConstants.ATTR_METADATA));
operation.setTitle(action.getAttribute(ODataConstants.ATTR_TITLE));
operation.setTarget(URI.create(action.getAttribute(ODataConstants.ATTR_TARGET)));
entry.getOperations().add(operation);
}
final List<Element> contents = XMLUtils.getChildElements(input, ODataConstants.ATOM_ELEM_CONTENT);
if (!contents.isEmpty()) {
final Element content = contents.get(0);
List<Element> props = XMLUtils.getChildElements(content, ODataConstants.ELEM_PROPERTIES);
if (props.isEmpty()) {
entry.setMediaContentSource(content.getAttribute(ODataConstants.ATOM_ATTR_SRC));
entry.setMediaContentType(content.getAttribute(ODataConstants.ATTR_TYPE));
props = XMLUtils.getChildElements(input, ODataConstants.ELEM_PROPERTIES);
if (!props.isEmpty()) {
entry.setMediaEntryProperties(props.get(0));
}
} else {
entry.setContent(props.get(0));
}
}
return entry;
}
public AtomFeedImpl feed(final Element input) {
if (!ODataConstants.ATOM_ELEM_FEED.equals(input.getNodeName())) {
return null;
}
final AtomFeedImpl feed = new AtomFeedImpl();
common(input, feed);
final List<Element> entries = XMLUtils.getChildElements(input, ODataConstants.ATOM_ELEM_ENTRY);
for (Element entry : entries) {
feed.getEntries().add(entry(entry));
}
final List<Element> links = XMLUtils.getChildElements(input, ODataConstants.ATOM_ELEM_LINK);
for (Element link : links) {
if (ODataConstants.NEXT_LINK_REL.equals(link.getAttribute(ODataConstants.ATTR_REL))) {
feed.setNext(URI.create(link.getAttribute(ODataConstants.ATTR_HREF)));
}
}
final List<Element> counts = XMLUtils.getChildElements(input, ODataConstants.ATOM_ATTR_COUNT);
if (!counts.isEmpty()) {
try {
feed.setCount(Integer.parseInt(counts.get(0).getTextContent()));
} catch (Exception e) {
LOG.error("Could not parse $inlinecount {}", counts.get(0).getTextContent(), e);
}
}
return feed;
}
}

View File

@ -0,0 +1,120 @@
/*
* 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.olingo.client.core.data;
import java.net.URI;
import java.util.Date;
import org.apache.commons.lang3.StringUtils;
public class AtomEntryImpl extends AbstractEntry implements AtomObject {
private static final long serialVersionUID = 6973729343868293279L;
public static class Author {
private String name;
private String uri;
private String email;
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public String getUri() {
return uri;
}
public void setUri(final String uri) {
this.uri = uri;
}
public String getEmail() {
return email;
}
public void setEmail(final String email) {
this.email = email;
}
public boolean isEmpty() {
return StringUtils.isBlank(name) && StringUtils.isBlank(uri) && StringUtils.isBlank(email);
}
}
private URI baseURI;
private String title;
private String summary;
private Date updated;
private Author author;
@Override
public void setBaseURI(final String baseURI) {
this.baseURI = URI.create(baseURI);
}
@Override
public URI getBaseURI() {
return baseURI;
}
public String getTitle() {
return title;
}
@Override
public void setTitle(final String title) {
this.title = title;
}
public String getSummary() {
return summary;
}
@Override
public void setSummary(final String summary) {
this.summary = summary;
}
public Date getUpdated() {
return new Date(updated.getTime());
}
@Override
public void setUpdated(final Date updated) {
this.updated = new Date(updated.getTime());
}
public Author getAuthor() {
return author;
}
public void setAuthor(final Author author) {
this.author = author;
}
}

View File

@ -0,0 +1,122 @@
/*
* 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.olingo.client.core.data;
import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.olingo.client.api.data.Entry;
import org.apache.olingo.client.api.data.Feed;
/**
* List of entries, represented via Atom.
*
* @see AtomEntry
*/
public class AtomFeedImpl extends AbstractPayloadObject implements AtomObject, Feed {
private static final long serialVersionUID = 5466590540021319153L;
private URI baseURI;
private String id;
private String title;
private String summary;
private Date updated;
private Integer count;
private final List<Entry> entries = new ArrayList<Entry>();
private URI next;
@Override
public URI getBaseURI() {
return baseURI;
}
@Override
public void setBaseURI(final String baseURI) {
this.baseURI = URI.create(baseURI);
}
public String getId() {
return id;
}
@Override
public void setId(final String id) {
this.id = id;
}
public String getTitle() {
return title;
}
@Override
public void setTitle(final String title) {
this.title = title;
}
public String getSummary() {
return summary;
}
@Override
public void setSummary(final String summary) {
this.summary = summary;
}
public Date getUpdated() {
return new Date(updated.getTime());
}
@Override
public void setUpdated(final Date updated) {
this.updated = new Date(updated.getTime());
}
public void setCount(final Integer count) {
this.count = count;
}
@Override
public Integer getCount() {
return count;
}
@Override
public List<Entry> getEntries() {
return entries;
}
@Override
public void setNext(final URI next) {
this.next = next;
}
@Override
public URI getNext() {
return next;
}
}

View File

@ -1,4 +1,4 @@
/*
/*
* 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
@ -16,15 +16,26 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.olingo.client.api.deserializer;
package org.apache.olingo.client.core.data;
import java.io.InputStream;
import java.util.Date;
public interface Reader {
/**
* Common methods for <tt>AtomEntryImpl</tt> and <tt>AtomFeedImpl</tt>.
*
* @see AtomEntryImpl
* @see AtomFeedImpl
*/
public interface AtomObject {
EntitySet readEntitySet(InputStream in) throws ClientException;
void setBaseURI(String baseURI);
Entity readEntity(InputStream in) throws ClientException;
void setId(String id);
void setTitle(String title);
void setSummary(String summary);
void setUpdated(Date updated);
Property readProperty(InputStream in) throws ClientException;
}

View File

@ -0,0 +1,184 @@
/*
* 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.olingo.client.core.data;
import java.util.List;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.ContentType;
import org.apache.olingo.client.api.ODataClient;
import org.apache.olingo.client.api.ODataConstants;
import org.apache.olingo.client.api.data.Entry;
import org.apache.olingo.client.api.data.Link;
import org.apache.olingo.client.api.utils.XMLUtils;
import org.apache.olingo.commons.api.edm.constants.ODataServiceVersion;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class AtomSerializer {
private final ODataClient client;
public AtomSerializer(final ODataClient client) {
this.client = client;
}
public <T extends AbstractPayloadObject> Element serialize(final T obj) throws ParserConfigurationException {
if (obj instanceof AtomEntryImpl) {
return entry((AtomEntryImpl) obj);
} else if (obj instanceof AtomFeedImpl) {
return feed((AtomFeedImpl) obj);
} else {
throw new IllegalArgumentException("Unsupported Atom object for standalone serialization: " + obj);
}
}
private void setLinks(final Element entry, final List<Link> links) throws ParserConfigurationException {
for (Link link : links) {
final Element linkElem = entry.getOwnerDocument().createElement(ODataConstants.ATOM_ELEM_LINK);
linkElem.setAttribute(ODataConstants.ATTR_REL, link.getRel());
linkElem.setAttribute(ODataConstants.ATTR_TITLE, link.getTitle());
linkElem.setAttribute(ODataConstants.ATTR_HREF, link.getHref());
if (StringUtils.isNotBlank(link.getType())) {
linkElem.setAttribute(ODataConstants.ATTR_TYPE, link.getType());
}
if (link.getInlineEntry() != null || link.getInlineFeed() != null) {
final Element inline = entry.getOwnerDocument().createElement(ODataConstants.ATOM_ELEM_INLINE);
linkElem.appendChild(inline);
if (link.getInlineEntry() != null) {
inline.appendChild(entry.getOwnerDocument().importNode(
entry((AtomEntryImpl) link.getInlineEntry()), true));
}
if (link.getInlineFeed() != null) {
inline.appendChild(entry.getOwnerDocument().importNode(
feed((AtomFeedImpl) link.getInlineFeed()), true));
}
}
entry.appendChild(linkElem);
}
}
private Element entry(final AtomEntryImpl entry) throws ParserConfigurationException {
final DocumentBuilder builder = XMLUtils.DOC_BUILDER_FACTORY.newDocumentBuilder();
final Document doc = builder.newDocument();
final Element entryElem = doc.createElement(ODataConstants.ATOM_ELEM_ENTRY);
entryElem.setAttribute(XMLConstants.XMLNS_ATTRIBUTE, ODataConstants.NS_ATOM);
entryElem.setAttribute(ODataConstants.XMLNS_METADATA,
client.getServiceVersion().getNamespaceMap().get(ODataServiceVersion.NS_METADATA));
entryElem.setAttribute(ODataConstants.XMLNS_DATASERVICES,
client.getServiceVersion().getNamespaceMap().get(ODataServiceVersion.NS_DATASERVICES));
entryElem.setAttribute(ODataConstants.XMLNS_GML, ODataConstants.NS_GML);
entryElem.setAttribute(ODataConstants.XMLNS_GEORSS, ODataConstants.NS_GEORSS);
if (entry.getBaseURI() != null) {
entryElem.setAttribute(ODataConstants.ATTR_XMLBASE, entry.getBaseURI().toASCIIString());
}
doc.appendChild(entryElem);
final Element category = doc.createElement(ODataConstants.ATOM_ELEM_CATEGORY);
category.setAttribute(ODataConstants.ATOM_ATTR_TERM, entry.getType());
category.setAttribute(ODataConstants.ATOM_ATTR_SCHEME,
client.getServiceVersion().getNamespaceMap().get(ODataServiceVersion.NS_SCHEME));
entryElem.appendChild(category);
if (StringUtils.isNotBlank(entry.getTitle())) {
final Element title = doc.createElement(ODataConstants.ATOM_ELEM_TITLE);
title.appendChild(doc.createTextNode(entry.getTitle()));
entryElem.appendChild(title);
}
if (StringUtils.isNotBlank(entry.getSummary())) {
final Element summary = doc.createElement(ODataConstants.ATOM_ELEM_SUMMARY);
summary.appendChild(doc.createTextNode(entry.getSummary()));
entryElem.appendChild(summary);
}
setLinks(entryElem, entry.getAssociationLinks());
setLinks(entryElem, entry.getNavigationLinks());
setLinks(entryElem, entry.getMediaEditLinks());
final Element content = doc.createElement(ODataConstants.ATOM_ELEM_CONTENT);
if (entry.isMediaEntry()) {
if (StringUtils.isNotBlank(entry.getMediaContentType())) {
content.setAttribute(ODataConstants.ATTR_TYPE, entry.getMediaContentType());
}
if (StringUtils.isNotBlank(entry.getMediaContentSource())) {
content.setAttribute(ODataConstants.ATOM_ATTR_SRC, entry.getMediaContentSource());
}
if (content.getAttributes().getLength() > 0) {
entryElem.appendChild(content);
}
if (entry.getMediaEntryProperties() != null) {
entryElem.appendChild(doc.importNode(entry.getMediaEntryProperties(), true));
}
} else {
content.setAttribute(ODataConstants.ATTR_TYPE, ContentType.APPLICATION_XML.getMimeType());
if (entry.getContent() != null) {
content.appendChild(doc.importNode(entry.getContent(), true));
}
entryElem.appendChild(content);
}
return entryElem;
}
private Element feed(final AtomFeedImpl feed) throws ParserConfigurationException {
final DocumentBuilder builder = XMLUtils.DOC_BUILDER_FACTORY.newDocumentBuilder();
final Document doc = builder.newDocument();
final Element feedElem = doc.createElement(ODataConstants.ATOM_ELEM_FEED);
feedElem.setAttribute(XMLConstants.XMLNS_ATTRIBUTE, ODataConstants.NS_ATOM);
feedElem.setAttribute(ODataConstants.XMLNS_METADATA,
client.getServiceVersion().getNamespaceMap().get(ODataServiceVersion.NS_METADATA));
feedElem.setAttribute(ODataConstants.XMLNS_DATASERVICES,
client.getServiceVersion().getNamespaceMap().get(ODataServiceVersion.NS_DATASERVICES));
feedElem.setAttribute(ODataConstants.XMLNS_GML, ODataConstants.NS_GML);
feedElem.setAttribute(ODataConstants.XMLNS_GEORSS, ODataConstants.NS_GEORSS);
if (feed.getBaseURI() != null) {
feedElem.setAttribute(ODataConstants.ATTR_XMLBASE, feed.getBaseURI().toASCIIString());
}
doc.appendChild(feedElem);
if (StringUtils.isNotBlank(feed.getTitle())) {
final Element title = doc.createElement(ODataConstants.ATOM_ELEM_TITLE);
title.appendChild(doc.createTextNode(feed.getTitle()));
feedElem.appendChild(title);
}
if (StringUtils.isNotBlank(feed.getSummary())) {
final Element summary = doc.createElement(ODataConstants.ATOM_ELEM_SUMMARY);
summary.appendChild(doc.createTextNode(feed.getSummary()));
feedElem.appendChild(summary);
}
for (Entry entry : feed.getEntries()) {
feedElem.appendChild(doc.importNode(entry((AtomEntryImpl) entry), true));
}
return feedElem;
}
}

View File

@ -0,0 +1,412 @@
/*
* 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.olingo.client.core.data;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonNode;
import java.io.IOException;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import org.apache.olingo.client.api.ODataClient;
import org.apache.olingo.client.api.ODataConstants;
import org.apache.olingo.client.api.domain.ODataJClientEdmPrimitiveType;
import org.apache.olingo.client.api.domain.geospatial.Geospatial;
import org.apache.olingo.client.api.utils.XMLUtils;
import org.apache.olingo.commons.api.edm.constants.ODataServiceVersion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
final class GeospatialJSONHandler {
/**
* Logger.
*/
private static final Logger LOG = LoggerFactory.getLogger(GeospatialJSONHandler.class);
private GeospatialJSONHandler() {
// Empty private constructor for static utility classes
}
private static Element deserializePoint(final Document document, final Iterator<JsonNode> itor) {
final Element point = document.createElementNS(ODataConstants.NS_GML, ODataConstants.ELEM_POINT);
final Element ppos = document.createElementNS(ODataConstants.NS_GML, ODataConstants.ELEM_POS);
point.appendChild(ppos);
if (itor.hasNext()) {
ppos.appendChild(document.createTextNode(itor.next().asText() + " " + itor.next().asText()));
}
return point;
}
private static void appendPoses(final Element parent, final Document document, final Iterator<JsonNode> itor) {
while (itor.hasNext()) {
final Iterator<JsonNode> lineItor = itor.next().elements();
final Element pos = document.createElementNS(ODataConstants.NS_GML, ODataConstants.ELEM_POS);
parent.appendChild(pos);
pos.appendChild(document.createTextNode(lineItor.next().asText() + " " + lineItor.next().asText()));
}
}
private static Element deserializeLineString(final Document document, final Iterator<JsonNode> itor) {
final Element lineString = document.createElementNS(ODataConstants.NS_GML, ODataConstants.ELEM_LINESTRING);
if (!itor.hasNext()) {
lineString.appendChild(document.createElementNS(ODataConstants.NS_GML, ODataConstants.ELEM_POSLIST));
}
appendPoses(lineString, document, itor);
return lineString;
}
private static Element deserializePolygon(final Document document, final Iterator<JsonNode> itor) {
final Element polygon = document.createElementNS(ODataConstants.NS_GML, ODataConstants.ELEM_POLYGON);
if (itor.hasNext()) {
final Iterator<JsonNode> extItor = itor.next().elements();
final Element exterior = document.createElementNS(
ODataConstants.NS_GML, ODataConstants.ELEM_POLYGON_EXTERIOR);
polygon.appendChild(exterior);
final Element extLR = document.createElementNS(
ODataConstants.NS_GML, ODataConstants.ELEM_POLYGON_LINEARRING);
exterior.appendChild(extLR);
appendPoses(extLR, document, extItor);
}
if (itor.hasNext()) {
final Iterator<JsonNode> intItor = itor.next().elements();
final Element interior = document.createElementNS(
ODataConstants.NS_GML, ODataConstants.ELEM_POLYGON_INTERIOR);
polygon.appendChild(interior);
final Element intLR = document.createElementNS(
ODataConstants.NS_GML, ODataConstants.ELEM_POLYGON_LINEARRING);
interior.appendChild(intLR);
appendPoses(intLR, document, intItor);
}
return polygon;
}
public static void deserialize(final JsonNode node, final Element parent, final String type) {
final Iterator<JsonNode> cooItor = node.has(ODataConstants.JSON_COORDINATES)
? node.get(ODataConstants.JSON_COORDINATES).elements()
: Collections.<JsonNode>emptyList().iterator();
Element root = null;
final ODataJClientEdmPrimitiveType edmSimpleType = ODataJClientEdmPrimitiveType.fromValue(type);
switch (edmSimpleType) {
case GeographyPoint:
case GeometryPoint:
root = deserializePoint(parent.getOwnerDocument(), cooItor);
break;
case GeographyMultiPoint:
case GeometryMultiPoint:
root = parent.getOwnerDocument().createElementNS(ODataConstants.NS_GML, ODataConstants.ELEM_MULTIPOINT);
if (cooItor.hasNext()) {
final Element pointMembers = parent.getOwnerDocument().createElementNS(
ODataConstants.NS_GML, ODataConstants.ELEM_POINTMEMBERS);
root.appendChild(pointMembers);
while (cooItor.hasNext()) {
final Iterator<JsonNode> mpItor = cooItor.next().elements();
pointMembers.appendChild(deserializePoint(parent.getOwnerDocument(), mpItor));
}
}
break;
case GeographyLineString:
case GeometryLineString:
root = deserializeLineString(parent.getOwnerDocument(), cooItor);
break;
case GeographyMultiLineString:
case GeometryMultiLineString:
root = parent.getOwnerDocument().createElementNS(
ODataConstants.NS_GML, ODataConstants.ELEM_MULTILINESTRING);
if (cooItor.hasNext()) {
final Element lineStringMembers = parent.getOwnerDocument().createElementNS(
ODataConstants.NS_GML, ODataConstants.ELEM_LINESTRINGMEMBERS);
root.appendChild(lineStringMembers);
while (cooItor.hasNext()) {
final Iterator<JsonNode> mlsItor = cooItor.next().elements();
lineStringMembers.appendChild(deserializeLineString(parent.getOwnerDocument(), mlsItor));
}
}
break;
case GeographyPolygon:
case GeometryPolygon:
root = deserializePolygon(parent.getOwnerDocument(), cooItor);
break;
case GeographyMultiPolygon:
case GeometryMultiPolygon:
root = parent.getOwnerDocument().createElementNS(
ODataConstants.NS_GML, ODataConstants.ELEM_MULTIPOLYGON);
if (cooItor.hasNext()) {
final Element surfaceMembers = parent.getOwnerDocument().createElementNS(
ODataConstants.NS_GML, ODataConstants.ELEM_SURFACEMEMBERS);
root.appendChild(surfaceMembers);
while (cooItor.hasNext()) {
final Iterator<JsonNode> mpItor = cooItor.next().elements();
surfaceMembers.appendChild(deserializePolygon(parent.getOwnerDocument(), mpItor));
}
}
break;
case GeographyCollection:
case GeometryCollection:
root = parent.getOwnerDocument().createElementNS(
ODataConstants.NS_GML, ODataConstants.ELEM_GEOCOLLECTION);
if (node.has(ODataConstants.JSON_GEOMETRIES)) {
final Iterator<JsonNode> geoItor = node.get(ODataConstants.JSON_GEOMETRIES).elements();
if (geoItor.hasNext()) {
final Element geometryMembers = parent.getOwnerDocument().createElementNS(
ODataConstants.NS_GML, ODataConstants.ELEM_GEOMEMBERS);
root.appendChild(geometryMembers);
while (geoItor.hasNext()) {
final JsonNode geo = geoItor.next();
final String collItemType = geo.get(ODataConstants.ATTR_TYPE).asText();
final String callAsType;
if (ODataJClientEdmPrimitiveType.GeographyCollection.name().equals(collItemType)
|| ODataJClientEdmPrimitiveType.GeometryCollection.name().equals(collItemType)) {
callAsType = collItemType;
} else {
callAsType =
(edmSimpleType == ODataJClientEdmPrimitiveType.GeographyCollection ? "Geography" : "Geometry")
+ collItemType;
}
deserialize(geo, geometryMembers, ODataJClientEdmPrimitiveType.namespace() + "." + callAsType);
}
}
}
break;
default:
}
if (root != null) {
parent.appendChild(root);
if (node.has(ODataConstants.JSON_CRS)) {
root.setAttribute(ODataConstants.ATTR_SRSNAME,
ODataConstants.JSON_GIS_URLPREFIX
+ node.get(ODataConstants.JSON_CRS).get(ODataConstants.PROPERTIES).get(ODataConstants.NAME).
asText().split(":")[1]);
}
}
}
private static void serializeCrs(final JsonGenerator jgen, final Node node) throws IOException {
if (node.getAttributes().getNamedItem(ODataConstants.ATTR_SRSNAME) != null) {
final String srsName = node.getAttributes().getNamedItem(ODataConstants.ATTR_SRSNAME).getTextContent();
final int prefIdx = srsName.indexOf(ODataConstants.JSON_GIS_URLPREFIX);
final String crsValue = srsName.substring(prefIdx + ODataConstants.JSON_GIS_URLPREFIX.length());
jgen.writeObjectFieldStart(ODataConstants.JSON_CRS);
jgen.writeStringField(ODataConstants.ATTR_TYPE, ODataConstants.NAME);
jgen.writeObjectFieldStart(ODataConstants.PROPERTIES);
jgen.writeStringField(ODataConstants.NAME, "EPSG:" + crsValue);
jgen.writeEndObject();
jgen.writeEndObject();
}
}
private static void serializePoint(final JsonGenerator jgen, final Node node) throws IOException {
for (String coord : node.getTextContent().split(" ")) {
jgen.writeNumber(coord);
}
}
private static void serializeLineString(final JsonGenerator jgen, final Element node) throws IOException {
for (Element element : XMLUtils.getChildElements(node, ODataConstants.ELEM_POS)) {
jgen.writeStartArray();
serializePoint(jgen, element);
jgen.writeEndArray();
}
}
private static void serializePolygon(final JsonGenerator jgen, final Element node) throws IOException {
for (Element exterior : XMLUtils.getChildElements(node, ODataConstants.ELEM_POLYGON_EXTERIOR)) {
jgen.writeStartArray();
serializeLineString(jgen,
XMLUtils.getChildElements(exterior, ODataConstants.ELEM_POLYGON_LINEARRING).get(0));
jgen.writeEndArray();
}
for (Element interior : XMLUtils.getChildElements(node, ODataConstants.ELEM_POLYGON_INTERIOR)) {
jgen.writeStartArray();
serializeLineString(jgen,
XMLUtils.getChildElements(interior, ODataConstants.ELEM_POLYGON_LINEARRING).get(0));
jgen.writeEndArray();
}
}
public static void serialize(final ODataClient client,
final JsonGenerator jgen, final Element node, final String type) throws IOException {
final ODataJClientEdmPrimitiveType edmSimpleType = ODataJClientEdmPrimitiveType.fromValue(type);
if (edmSimpleType.equals(ODataJClientEdmPrimitiveType.GeographyCollection)
|| edmSimpleType.equals(ODataJClientEdmPrimitiveType.GeometryCollection)) {
jgen.writeStringField(ODataConstants.ATTR_TYPE, ODataJClientEdmPrimitiveType.GeometryCollection.name());
} else {
final int yIdx = edmSimpleType.name().indexOf('y');
final String itemType = edmSimpleType.name().substring(yIdx + 1);
jgen.writeStringField(ODataConstants.ATTR_TYPE, itemType);
}
Element root = null;
switch (edmSimpleType) {
case GeographyPoint:
case GeometryPoint:
root = XMLUtils.getChildElements(node, ODataConstants.ELEM_POINT).get(0);
jgen.writeArrayFieldStart(ODataConstants.JSON_COORDINATES);
serializePoint(jgen, XMLUtils.getChildElements(root, ODataConstants.ELEM_POS).get(0));
jgen.writeEndArray();
break;
case GeographyMultiPoint:
case GeometryMultiPoint:
root = XMLUtils.getChildElements(node, ODataConstants.ELEM_MULTIPOINT).get(0);
jgen.writeArrayFieldStart(ODataConstants.JSON_COORDINATES);
final List<Element> pMembs = XMLUtils.getChildElements(root, ODataConstants.ELEM_POINTMEMBERS);
if (pMembs != null && !pMembs.isEmpty()) {
for (Element point : XMLUtils.getChildElements(pMembs.get(0), ODataConstants.ELEM_POINT)) {
jgen.writeStartArray();
serializePoint(jgen, XMLUtils.getChildElements(point, ODataConstants.ELEM_POS).get(0));
jgen.writeEndArray();
}
}
jgen.writeEndArray();
break;
case GeographyLineString:
case GeometryLineString:
root = XMLUtils.getChildElements(node, ODataConstants.ELEM_LINESTRING).get(0);
jgen.writeArrayFieldStart(ODataConstants.JSON_COORDINATES);
serializeLineString(jgen, root);
jgen.writeEndArray();
break;
case GeographyMultiLineString:
case GeometryMultiLineString:
root = XMLUtils.getChildElements(node, ODataConstants.ELEM_MULTILINESTRING).get(0);
jgen.writeArrayFieldStart(ODataConstants.JSON_COORDINATES);
final List<Element> lMembs = XMLUtils.getChildElements(root, ODataConstants.ELEM_LINESTRINGMEMBERS);
if (lMembs != null && !lMembs.isEmpty()) {
for (Element lineStr : XMLUtils.getChildElements(lMembs.get(0), ODataConstants.ELEM_LINESTRING)) {
jgen.writeStartArray();
serializeLineString(jgen, lineStr);
jgen.writeEndArray();
}
}
jgen.writeEndArray();
break;
case GeographyPolygon:
case GeometryPolygon:
root = XMLUtils.getChildElements(node, ODataConstants.ELEM_POLYGON).get(0);
jgen.writeArrayFieldStart(ODataConstants.JSON_COORDINATES);
serializePolygon(jgen, root);
jgen.writeEndArray();
break;
case GeographyMultiPolygon:
case GeometryMultiPolygon:
root = XMLUtils.getChildElements(node, ODataConstants.ELEM_MULTIPOLYGON).get(0);
jgen.writeArrayFieldStart(ODataConstants.JSON_COORDINATES);
final List<Element> mpMembs = XMLUtils.getChildElements(root, ODataConstants.ELEM_SURFACEMEMBERS);
if (mpMembs != null & !mpMembs.isEmpty()) {
for (Element pol : XMLUtils.getChildElements(mpMembs.get(0), ODataConstants.ELEM_POLYGON)) {
jgen.writeStartArray();
serializePolygon(jgen, pol);
jgen.writeEndArray();
}
}
jgen.writeEndArray();
break;
case GeographyCollection:
case GeometryCollection:
root = XMLUtils.getChildElements(node, ODataConstants.ELEM_GEOCOLLECTION).get(0);
final List<Element> cMembs = XMLUtils.getChildElements(root, ODataConstants.ELEM_GEOMEMBERS);
if (cMembs != null && !cMembs.isEmpty()) {
jgen.writeArrayFieldStart(ODataConstants.JSON_GEOMETRIES);
for (Node geom : XMLUtils.getChildNodes(cMembs.get(0), Node.ELEMENT_NODE)) {
try {
final DocumentBuilder builder = XMLUtils.DOC_BUILDER_FACTORY.newDocumentBuilder();
final Document doc = builder.newDocument();
final Element fakeParent = doc.createElementNS(
client.getServiceVersion().getNamespaceMap().
get(ODataServiceVersion.NS_DATASERVICES),
ODataConstants.PREFIX_DATASERVICES + "fake");
fakeParent.appendChild(doc.importNode(geom, true));
final ODataJClientEdmPrimitiveType callAsType = XMLUtils.simpleTypeForNode(
edmSimpleType == ODataJClientEdmPrimitiveType.GeographyCollection
? Geospatial.Dimension.GEOGRAPHY : Geospatial.Dimension.GEOMETRY,
geom);
jgen.writeStartObject();
serialize(client, jgen, fakeParent, callAsType.toString());
jgen.writeEndObject();
} catch (Exception e) {
LOG.warn("While serializing {}", XMLUtils.getSimpleName(geom), e);
}
}
jgen.writeEndArray();
}
break;
default:
}
if (root != null) {
serializeCrs(jgen, root);
}
}
}

View File

@ -0,0 +1,260 @@
/*
* 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.olingo.client.core.data;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonNode;
import java.io.IOException;
import java.util.Iterator;
import org.apache.commons.lang3.StringUtils;
import org.apache.olingo.client.api.ODataClient;
import org.apache.olingo.client.api.ODataConstants;
import org.apache.olingo.client.api.domain.ODataJClientEdmPrimitiveType;
import org.apache.olingo.client.api.domain.ODataPrimitiveValue;
import org.apache.olingo.client.api.utils.XMLUtils;
import org.apache.olingo.commons.api.edm.constants.ODataServiceVersion;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
* DOM tree utilities class for JSON.
*/
final class JSONDOMTreeUtils {
private JSONDOMTreeUtils() {
// Empty private constructor for static utility classes
}
/**
* Recursively builds DOM content out of JSON subtree rooted at given node.
*
* @param client OData client.
* @param document root of the DOM document being built
* @param parent parent of the nodes being generated during this step
* @param node JSON node to be used as source for DOM elements
*/
public static void buildSubtree(final ODataClient client, final Element parent, final JsonNode node) {
final Iterator<String> fieldNameItor = node.fieldNames();
final Iterator<JsonNode> nodeItor = node.elements();
while (nodeItor.hasNext()) {
final JsonNode child = nodeItor.next();
final String name = fieldNameItor.hasNext() ? fieldNameItor.next() : "";
// no name? array item
if (name.isEmpty()) {
final Element element = parent.getOwnerDocument().createElementNS(
client.getServiceVersion().getNamespaceMap().get(ODataServiceVersion.NS_DATASERVICES),
ODataConstants.PREFIX_DATASERVICES + ODataConstants.ELEM_ELEMENT);
parent.appendChild(element);
if (child.isValueNode()) {
if (child.isNull()) {
element.setAttributeNS(
client.getServiceVersion().getNamespaceMap().get(ODataServiceVersion.NS_METADATA),
ODataConstants.ATTR_NULL, Boolean.toString(true));
} else {
element.appendChild(parent.getOwnerDocument().createTextNode(child.asText()));
}
}
if (child.isContainerNode()) {
buildSubtree(client, element, child);
}
} else if (!name.contains("@") && !ODataConstants.JSON_TYPE.equals(name)) {
final Element property = parent.getOwnerDocument().createElementNS(
client.getServiceVersion().getNamespaceMap().get(ODataServiceVersion.NS_DATASERVICES),
ODataConstants.PREFIX_DATASERVICES + name);
parent.appendChild(property);
boolean typeSet = false;
if (node.hasNonNull(name + "@" + ODataConstants.JSON_TYPE)) {
property.setAttributeNS(
client.getServiceVersion().getNamespaceMap().get(ODataServiceVersion.NS_METADATA),
ODataConstants.ATTR_M_TYPE,
node.get(name + "@" + ODataConstants.JSON_TYPE).textValue());
typeSet = true;
}
if (child.isNull()) {
property.setAttributeNS(client.getServiceVersion().getNamespaceMap().
get(ODataServiceVersion.NS_METADATA),
ODataConstants.ATTR_NULL, Boolean.toString(true));
} else if (child.isValueNode()) {
if (!typeSet) {
if (child.isInt()) {
property.setAttributeNS(
client.getServiceVersion().getNamespaceMap().get(ODataServiceVersion.NS_METADATA),
ODataConstants.ATTR_M_TYPE, ODataJClientEdmPrimitiveType.Int32.toString());
}
if (child.isLong()) {
property.setAttributeNS(
client.getServiceVersion().getNamespaceMap().get(ODataServiceVersion.NS_METADATA),
ODataConstants.ATTR_M_TYPE, ODataJClientEdmPrimitiveType.Int64.toString());
}
if (child.isBigDecimal()) {
property.setAttributeNS(
client.getServiceVersion().getNamespaceMap().get(ODataServiceVersion.NS_METADATA),
ODataConstants.ATTR_M_TYPE, ODataJClientEdmPrimitiveType.Decimal.toString());
}
if (child.isDouble()) {
property.setAttributeNS(
client.getServiceVersion().getNamespaceMap().get(ODataServiceVersion.NS_METADATA),
ODataConstants.ATTR_M_TYPE, ODataJClientEdmPrimitiveType.Double.toString());
}
if (child.isBoolean()) {
property.setAttributeNS(
client.getServiceVersion().getNamespaceMap().get(ODataServiceVersion.NS_METADATA),
ODataConstants.ATTR_M_TYPE, ODataJClientEdmPrimitiveType.Boolean.toString());
}
if (child.isTextual()) {
property.setAttributeNS(
client.getServiceVersion().getNamespaceMap().get(ODataServiceVersion.NS_METADATA),
ODataConstants.ATTR_M_TYPE, ODataJClientEdmPrimitiveType.String.toString());
}
}
property.appendChild(parent.getOwnerDocument().createTextNode(child.asText()));
} else if (child.isContainerNode()) {
if (!typeSet && child.hasNonNull(ODataConstants.JSON_TYPE)) {
property.
setAttributeNS(client.getServiceVersion().getNamespaceMap().
get(ODataServiceVersion.NS_METADATA),
ODataConstants.ATTR_M_TYPE,
child.get(ODataConstants.JSON_TYPE).textValue());
}
final String type = property.getAttribute(ODataConstants.ATTR_M_TYPE);
if (StringUtils.isNotBlank(type) && ODataJClientEdmPrimitiveType.isGeospatial(type)) {
if (ODataJClientEdmPrimitiveType.Geography.toString().equals(type)
|| ODataJClientEdmPrimitiveType.Geometry.toString().equals(type)) {
final String geoType = child.get(ODataConstants.ATTR_TYPE).textValue();
property.setAttributeNS(client.getServiceVersion().getNamespaceMap().get(
ODataServiceVersion.NS_METADATA), ODataConstants.ATTR_M_TYPE,
geoType.startsWith("Geo")
? ODataJClientEdmPrimitiveType.namespace() + "." + geoType
: type + geoType);
}
if (child.has(ODataConstants.JSON_COORDINATES) || child.has(ODataConstants.JSON_GEOMETRIES)) {
GeospatialJSONHandler.deserialize(
child, property, property.getAttribute(ODataConstants.ATTR_M_TYPE));
}
} else {
buildSubtree(client, property, child);
}
}
}
}
}
/**
* Serializes DOM content as JSON.
*
* @param client OData client.
* @param jgen JSON generator.
* @param content content.
* @throws IOException in case of write error.
*/
public static void writeSubtree(final ODataClient client, final JsonGenerator jgen, final Node content)
throws IOException {
writeSubtree(client, jgen, content, false);
}
/**
* Serializes DOM content as JSON.
*
* @param client OData client.
* @param jgen JSON generator.
* @param content content.
* @param propType whether to output type information in the way needed for property values or not.
* @throws IOException in case of write error.
*/
public static void writeSubtree(
final ODataClient client, final JsonGenerator jgen, final Node content, final boolean propType)
throws IOException {
for (Node child : XMLUtils.getChildNodes(content, Node.ELEMENT_NODE)) {
final String childName = XMLUtils.getSimpleName(child);
final Node typeAttr = child.getAttributes().getNamedItem(ODataConstants.ATTR_M_TYPE);
if (typeAttr != null && ODataJClientEdmPrimitiveType.isGeospatial(typeAttr.getTextContent())) {
jgen.writeStringField(propType ? ODataConstants.JSON_TYPE : childName + "@" + ODataConstants.JSON_TYPE,
typeAttr.getTextContent());
jgen.writeObjectFieldStart(childName);
GeospatialJSONHandler.serialize(client, jgen, (Element) child, typeAttr.getTextContent());
jgen.writeEndObject();
} else if (XMLUtils.hasOnlyTextChildNodes(child)) {
if (child.hasChildNodes()) {
final String out;
if (typeAttr == null) {
out = child.getChildNodes().item(0).getNodeValue();
} else {
final ODataJClientEdmPrimitiveType type = ODataJClientEdmPrimitiveType.fromValue(typeAttr.getTextContent());
final ODataPrimitiveValue value = client.getPrimitiveValueBuilder().setType(type).
setText(child.getChildNodes().item(0).getNodeValue()).build();
out = value.toString();
jgen.writeStringField(childName + "@" + ODataConstants.JSON_TYPE, type.toString());
}
jgen.writeStringField(childName, out);
} else {
if (child.getAttributes().getNamedItem(ODataConstants.ATTR_NULL) == null) {
if (typeAttr != null && ODataJClientEdmPrimitiveType.String.toString().equals(typeAttr.getTextContent())) {
jgen.writeStringField(childName + "@" + ODataConstants.JSON_TYPE, typeAttr.getTextContent());
jgen.writeStringField(childName, StringUtils.EMPTY);
} else {
jgen.writeArrayFieldStart(childName);
jgen.writeEndArray();
}
} else {
jgen.writeNullField(childName);
}
}
} else {
if (XMLUtils.hasElementsChildNode(child)) {
jgen.writeArrayFieldStart(childName);
for (Node nephew : XMLUtils.getChildNodes(child, Node.ELEMENT_NODE)) {
if (XMLUtils.hasOnlyTextChildNodes(nephew)) {
jgen.writeString(nephew.getChildNodes().item(0).getNodeValue());
} else {
jgen.writeStartObject();
writeSubtree(client, jgen, nephew);
jgen.writeEndObject();
}
}
jgen.writeEndArray();
} else {
jgen.writeObjectFieldStart(childName);
if (typeAttr != null) {
jgen.writeStringField(ODataConstants.JSON_TYPE, typeAttr.getTextContent());
}
writeSubtree(client, jgen, child);
jgen.writeEndObject();
}
}
}
}
}

View File

@ -0,0 +1,240 @@
/*
* 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.olingo.client.core.data;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.IOException;
import java.net.URI;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.olingo.client.api.ODataConstants;
import org.apache.olingo.client.api.data.LinkType;
import org.apache.olingo.client.api.utils.XMLUtils;
import org.apache.olingo.commons.api.edm.constants.ODataServiceVersion;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* Reads JSON string into an entry.
* <br/>
* If metadata information is available, the corresponding entry fields and content will be populated.
*/
public class JSONEntryDeserializer extends ODataJacksonDeserializer<JSONEntryImpl> {
private String getTitle(final Map.Entry<String, JsonNode> entry) {
return entry.getKey().substring(0, entry.getKey().indexOf('@'));
}
private String setInline(final String name, final String suffix, final ObjectNode tree,
final ObjectCodec codec, final LinkImpl link) throws IOException {
final String entryNamePrefix = name.substring(0, name.indexOf(suffix));
if (tree.has(entryNamePrefix)) {
final JsonNode inline = tree.path(entryNamePrefix);
if (inline instanceof ObjectNode) {
final JsonParser inlineParser = inline.traverse();
inlineParser.setCodec(codec);
link.setInlineEntry(inlineParser.readValuesAs(JSONEntryImpl.class).next());
}
if (inline instanceof ArrayNode) {
final JSONFeedImpl feed = new JSONFeedImpl();
final Iterator<JsonNode> entries = ((ArrayNode) inline).elements();
while (entries.hasNext()) {
final JsonParser inlineParser = entries.next().traverse();
inlineParser.setCodec(codec);
feed.getEntries().add(inlineParser.readValuesAs(JSONEntryImpl.class).next());
}
link.setInlineFeed(feed);
}
}
return entryNamePrefix;
}
@Override
protected JSONEntryImpl doDeserialize(final JsonParser parser, final DeserializationContext ctxt)
throws IOException, JsonProcessingException {
final ObjectNode tree = (ObjectNode) parser.getCodec().readTree(parser);
if (tree.has(ODataConstants.JSON_VALUE) && tree.get(ODataConstants.JSON_VALUE).isArray()) {
throw new JsonParseException("Expected OData Entity, found EntitySet", parser.getCurrentLocation());
}
final boolean isMediaEntry =
tree.hasNonNull(ODataConstants.JSON_MEDIAREAD_LINK)
&& tree.hasNonNull(ODataConstants.JSON_MEDIA_CONTENT_TYPE);
final JSONEntryImpl entry = new JSONEntryImpl();
if (tree.hasNonNull(ODataConstants.JSON_METADATA)) {
entry.setMetadata(URI.create(tree.get(ODataConstants.JSON_METADATA).textValue()));
tree.remove(ODataConstants.JSON_METADATA);
}
if (tree.hasNonNull(ODataConstants.JSON_MEDIA_ETAG)) {
entry.setMediaETag(tree.get(ODataConstants.JSON_MEDIA_ETAG).textValue());
tree.remove(ODataConstants.JSON_MEDIA_ETAG);
}
if (tree.hasNonNull(ODataConstants.JSON_ETAG)) {
entry.setETag(tree.get(ODataConstants.JSON_ETAG).textValue());
tree.remove(ODataConstants.JSON_ETAG);
}
if (tree.hasNonNull(ODataConstants.JSON_TYPE)) {
entry.setType(tree.get(ODataConstants.JSON_TYPE).textValue());
tree.remove(ODataConstants.JSON_TYPE);
}
if (tree.hasNonNull(ODataConstants.JSON_ID)) {
entry.setId(tree.get(ODataConstants.JSON_ID).textValue());
tree.remove(ODataConstants.JSON_ID);
}
if (tree.hasNonNull(ODataConstants.JSON_READ_LINK)) {
final LinkImpl link = new LinkImpl();
link.setRel(ODataConstants.SELF_LINK_REL);
link.setHref(tree.get(ODataConstants.JSON_READ_LINK).textValue());
entry.setSelfLink(link);
tree.remove(ODataConstants.JSON_READ_LINK);
}
if (tree.hasNonNull(ODataConstants.JSON_EDIT_LINK)) {
final LinkImpl link = new LinkImpl();
link.setRel(ODataConstants.EDIT_LINK_REL);
link.setHref(tree.get(ODataConstants.JSON_EDIT_LINK).textValue());
entry.setEditLink(link);
tree.remove(ODataConstants.JSON_EDIT_LINK);
}
if (tree.hasNonNull(ODataConstants.JSON_MEDIAREAD_LINK)) {
entry.setMediaContentSource(tree.get(ODataConstants.JSON_MEDIAREAD_LINK).textValue());
tree.remove(ODataConstants.JSON_MEDIAREAD_LINK);
}
if (tree.hasNonNull(ODataConstants.JSON_MEDIAEDIT_LINK)) {
/*final LinkImpl link = new LinkImpl();
link.setHref(tree.get(ODataConstants.JSON_MEDIAEDIT_LINK).textValue());
entry.getMediaEditLinks().add(link);*/
tree.remove(ODataConstants.JSON_MEDIAEDIT_LINK);
}
if (tree.hasNonNull(ODataConstants.JSON_MEDIA_CONTENT_TYPE)) {
entry.setMediaContentType(tree.get(ODataConstants.JSON_MEDIA_CONTENT_TYPE).textValue());
tree.remove(ODataConstants.JSON_MEDIA_CONTENT_TYPE);
}
final Set<String> toRemove = new HashSet<String>();
final Iterator<Map.Entry<String, JsonNode>> itor = tree.fields();
while (itor.hasNext()) {
final Map.Entry<String, JsonNode> field = itor.next();
if (field.getKey().endsWith(ODataConstants.JSON_NAVIGATION_LINK_SUFFIX)) {
final LinkImpl link = new LinkImpl();
link.setTitle(getTitle(field));
link.setRel(client.getServiceVersion().getNamespaceMap().get(ODataServiceVersion.NAVIGATION_LINK_REL)
+ getTitle(field));
if (field.getValue().isValueNode()) {
link.setHref(field.getValue().textValue());
link.setType(LinkType.ENTITY_NAVIGATION.toString());
}
// NOTE: this should be expected to happen, but it isn't - at least up to OData 4.0
/* if (field.getValue().isArray()) {
* link.setHref(field.getValue().asText());
* link.setType(LinkType.ENTITY_SET_NAVIGATION.toString());
* } */
entry.getNavigationLinks().add(link);
toRemove.add(field.getKey());
toRemove.add(setInline(field.getKey(),
ODataConstants.JSON_NAVIGATION_LINK_SUFFIX, tree, parser.getCodec(), link));
} else if (field.getKey().endsWith(ODataConstants.JSON_ASSOCIATION_LINK_SUFFIX)) {
final LinkImpl link = new LinkImpl();
link.setTitle(getTitle(field));
link.setRel(client.getServiceVersion().getNamespaceMap().get(ODataServiceVersion.ASSOCIATION_LINK_REL)
+ getTitle(field));
link.setHref(field.getValue().textValue());
link.setType(LinkType.ASSOCIATION.toString());
entry.getAssociationLinks().add(link);
toRemove.add(field.getKey());
} else if (field.getKey().endsWith(ODataConstants.JSON_MEDIAEDIT_LINK_SUFFIX)) {
final LinkImpl link = new LinkImpl();
link.setTitle(getTitle(field));
link.setRel(client.getServiceVersion().getNamespaceMap().get(ODataServiceVersion.MEDIA_EDIT_LINK_REL)
+ getTitle(field));
link.setHref(field.getValue().textValue());
link.setType(LinkType.MEDIA_EDIT.toString());
entry.getMediaEditLinks().add(link);
toRemove.add(field.getKey());
toRemove.add(setInline(field.getKey(),
ODataConstants.JSON_MEDIAEDIT_LINK_SUFFIX, tree, parser.getCodec(), link));
} else if (field.getKey().charAt(0) == '#') {
final OperationImpl operation = new OperationImpl();
operation.setMetadataAnchor(field.getKey());
final ObjectNode opNode = (ObjectNode) tree.get(field.getKey());
operation.setTitle(opNode.get(ODataConstants.ATTR_TITLE).asText());
operation.setTarget(URI.create(opNode.get(ODataConstants.ATTR_TARGET).asText()));
entry.getOperations().add(operation);
toRemove.add(field.getKey());
}
}
tree.remove(toRemove);
try {
final DocumentBuilder builder = XMLUtils.DOC_BUILDER_FACTORY.newDocumentBuilder();
final Document document = builder.newDocument();
final Element properties = document.createElementNS(
client.getServiceVersion().getNamespaceMap().get(ODataServiceVersion.NS_METADATA),
ODataConstants.ELEM_PROPERTIES);
JSONDOMTreeUtils.buildSubtree(client, properties, tree);
if (isMediaEntry) {
entry.setMediaEntryProperties(properties);
} else {
entry.setContent(properties);
}
} catch (ParserConfigurationException e) {
throw new JsonParseException("Cannot build entry content", parser.getCurrentLocation(), e);
}
return entry;
}
}

View File

@ -0,0 +1,89 @@
/*
* 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.olingo.client.core.data;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.net.URI;
import org.apache.olingo.client.api.uri.SegmentType;
/**
* A single entry, represented via JSON.
*/
@JsonSerialize(using = JSONEntrySerializer.class)
@JsonDeserialize(using = JSONEntryDeserializer.class)
public class JSONEntryImpl extends AbstractEntry {
private static final long serialVersionUID = -5275365545400797758L;
private URI metadata;
private String mediaETag;
@JsonIgnore
@Override
public URI getBaseURI() {
URI baseURI = null;
if (metadata != null) {
final String metadataURI = getMetadata().toASCIIString();
baseURI = URI.create(metadataURI.substring(0, metadataURI.indexOf(SegmentType.METADATA.getValue())));
}
return baseURI;
}
/**
* Gets the metadata URI.
*
* @return the metadata URI
*/
public URI getMetadata() {
return metadata;
}
/**
* Sets the metadata URI.
*
* @param metadata metadata URI.
*/
public void setMetadata(final URI metadata) {
this.metadata = metadata;
}
/**
* The odata.mediaEtag annotation MAY be included; its value MUST be the ETag of the binary stream represented by this
* media entity or named stream property.
*
* @return odata.mediaEtag annotation value.
*/
public String getMediaETag() {
return mediaETag;
}
/**
* The odata.mediaEtag annotation MAY be included; its value MUST be the ETag of the binary stream represented by this
* media entity or named stream property.
*
* @param eTag odata.mediaEtag annotation value.
*/
public void setMediaETag(final String eTag) {
this.mediaETag = eTag;
}
}

View File

@ -0,0 +1,128 @@
/*
* 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.olingo.client.core.data;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.olingo.client.api.ODataConstants;
import org.apache.olingo.client.api.data.Link;
import org.apache.olingo.client.api.data.LinkType;
/**
* Writes out JSON string from an entry.
*/
public class JSONEntrySerializer extends ODataJacksonSerializer<JSONEntryImpl> {
@Override
protected void doSerialize(final JSONEntryImpl entry, final JsonGenerator jgen, final SerializerProvider provider)
throws IOException, JsonProcessingException {
jgen.writeStartObject();
if (entry.getMetadata() != null) {
jgen.writeStringField(ODataConstants.JSON_METADATA, entry.getMetadata().toASCIIString());
}
if (StringUtils.isNotBlank(entry.getType())) {
jgen.writeStringField(ODataConstants.JSON_TYPE, entry.getType());
}
if (entry.getId() != null) {
jgen.writeStringField(ODataConstants.JSON_ID, entry.getId());
}
if (entry.getSelfLink() != null) {
jgen.writeStringField(ODataConstants.JSON_READ_LINK, entry.getSelfLink().getHref());
}
if (entry.getEditLink() != null) {
jgen.writeStringField(ODataConstants.JSON_EDIT_LINK, entry.getEditLink().getHref());
}
if (entry.getMediaContentSource() != null) {
jgen.writeStringField(ODataConstants.JSON_MEDIAREAD_LINK, entry.getMediaContentSource());
}
if (entry.getMediaContentType() != null) {
jgen.writeStringField(ODataConstants.JSON_MEDIA_CONTENT_TYPE, entry.getMediaContentType());
}
final Map<String, List<String>> entitySetLinks = new HashMap<String, List<String>>();
for (Link link : entry.getNavigationLinks()) {
if (link.getInlineEntry() != null) {
jgen.writeObjectField(link.getTitle(), link.getInlineEntry());
} else if (link.getInlineFeed() != null) {
jgen.writeObjectField(link.getTitle(), link.getInlineFeed());
} else {
LinkType type = null;
try {
type = LinkType.fromString(client, link.getRel(), link.getType());
} catch (IllegalArgumentException e) {
// ignore
}
if (type == LinkType.ENTITY_SET_NAVIGATION) {
final List<String> uris;
if (entitySetLinks.containsKey(link.getTitle())) {
uris = entitySetLinks.get(link.getTitle());
} else {
uris = new ArrayList<String>();
entitySetLinks.put(link.getTitle(), uris);
}
uris.add(link.getHref());
} else {
jgen.writeStringField(link.getTitle() + ODataConstants.JSON_BIND_LINK_SUFFIX, link.getHref());
}
}
}
for (Map.Entry<String, List<String>> entitySetLink : entitySetLinks.entrySet()) {
jgen.writeArrayFieldStart(entitySetLink.getKey() + ODataConstants.JSON_BIND_LINK_SUFFIX);
for (String uri : entitySetLink.getValue()) {
jgen.writeString(uri);
}
jgen.writeEndArray();
}
for (Link link : entry.getMediaEditLinks()) {
if (link.getTitle() == null) {
jgen.writeStringField(ODataConstants.JSON_MEDIAEDIT_LINK, link.getHref());
}
if (link.getInlineEntry() != null) {
jgen.writeObjectField(link.getTitle(), link.getInlineEntry());
}
if (link.getInlineFeed() != null) {
jgen.writeObjectField(link.getTitle(), link.getInlineFeed());
}
}
if (entry.getMediaEntryProperties() == null) {
JSONDOMTreeUtils.writeSubtree(client, jgen, entry.getContent());
} else {
JSONDOMTreeUtils.writeSubtree(client, jgen, entry.getMediaEntryProperties());
}
jgen.writeEndObject();
}
}

View File

@ -1,4 +1,4 @@
/*
/*
* 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
@ -16,36 +16,35 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.olingo.client.core.deserializer;
package org.apache.olingo.client.core.data;
import org.apache.olingo.client.api.deserializer.Value;
import com.fasterxml.jackson.annotation.JsonProperty;
public class PrimitiveValue implements Value {
/**
* This class represents a bundle for an OData error returned as JSON.
*/
public class JSONErrorBundle extends AbstractPayloadObject {
private final Object content;
private static final long serialVersionUID = -4784910226259754450L;
public PrimitiveValue(final Object content) {
this.content = content;
@JsonProperty("odata.error")
private JSONErrorImpl error;
/**
* Gets error.
*
* @return OData error object.
*/
public JSONErrorImpl getError() {
return error;
}
@Override
public boolean isComplex() {
return false;
}
@Override
public Object getContent() {
return content;
}
@SuppressWarnings("unchecked")
@Override
public <T> T getContentAs(final T type) {
return (T) content;
}
@Override
public String toString() {
return String.valueOf(content);
/**
* Sets error.
*
* @param error OData error object.
*/
public void setError(final JSONErrorImpl error) {
this.error = error;
}
}

View File

@ -0,0 +1,237 @@
/*
* 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.olingo.client.core.data;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.olingo.client.api.data.Error;
/**
* This class represents an OData error returned as JSON.
*/
public class JSONErrorImpl extends AbstractPayloadObject implements Error {
private static final long serialVersionUID = -3476499168507242932L;
/**
* Error message.
*/
public static class Message extends AbstractPayloadObject {
private static final long serialVersionUID = 2577818040815637859L;
private String lang;
private String value;
/**
* Gets language.
*
* @return language.
*/
public String getLang() {
return lang;
}
/**
* Sets language.
*
* @param lang language.
*/
public void setLang(final String lang) {
this.lang = lang;
}
/**
* Gets message.
*
* @return message.
*/
public String getValue() {
return value;
}
/**
* Sets message.
*
* @param value message.
*/
public void setValue(final String value) {
this.value = value;
}
}
/**
* Inner error.
*/
static class InnerError extends AbstractPayloadObject {
private static final long serialVersionUID = -3920947476143537640L;
private String message;
private String type;
private String stacktrace;
private InnerError internalexception;
/**
* Gets inner message.
*
* @return message.
*/
public String getMessage() {
return message;
}
/**
* Sets inner message.
*
* @param message message.
*/
public void setMessage(final String message) {
this.message = message;
}
/**
* Gets type.
*
* @return type.
*/
public String getType() {
return type;
}
/**
* Sets type.
*
* @param type type.
*/
public void setType(final String type) {
this.type = type;
}
/**
* Gets stack-trace.
*
* @return stack-trace.
*/
public String getStacktrace() {
return stacktrace;
}
/**
* Sets stack-trace.
*
* @param stacktrace stack-trace.
*/
public void setStacktrace(final String stacktrace) {
this.stacktrace = stacktrace;
}
public InnerError getInternalexception() {
return internalexception;
}
public void setInternalexception(final InnerError internalexception) {
this.internalexception = internalexception;
}
}
private String code;
@JsonProperty(value = "message")
private Message message;
@JsonProperty(value = "innererror", required = false)
private InnerError innererror;
/**
* {@inheritDoc }
*/
@Override
public String getCode() {
return code;
}
/**
* Sets error code.
*
* @param code error code.
*/
public void setCode(final String code) {
this.code = code;
}
/**
* {@inheritDoc }
*/
@JsonIgnore
@Override
public String getMessageLang() {
return this.message == null ? null : this.message.getLang();
}
/**
* {@inheritDoc }
*/
@JsonIgnore
@Override
public String getMessageValue() {
return this.message == null ? null : this.message.getValue();
}
/**
* Sets the value of the message property.
*
* @param value allowed object is {@link Error.Message }
*
*/
public void setMessage(final Message value) {
this.message = value;
}
/**
* {@inheritDoc }
*/
@JsonIgnore
@Override
public String getInnerErrorMessage() {
return this.innererror == null ? null : this.innererror.getMessage();
}
/**
* {@inheritDoc }
*/
@JsonIgnore
@Override
public String getInnerErrorType() {
return this.innererror == null ? null : this.innererror.getType();
}
/**
* {@inheritDoc }
*/
@JsonIgnore
@Override
public String getInnerErrorStacktrace() {
return this.innererror == null ? null : this.innererror.getStacktrace();
}
}

View File

@ -0,0 +1,64 @@
/*
* 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.olingo.client.core.data;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.IOException;
import java.net.URI;
import java.util.Iterator;
import org.apache.olingo.client.api.ODataConstants;
/**
* Reads JSON string into a feed.
* <br/>
* If metadata information is available, the corresponding entry fields and content will be populated.
*/
public class JSONFeedDeserializer extends ODataJacksonDeserializer<JSONFeedImpl> {
@Override
protected JSONFeedImpl doDeserialize(final JsonParser parser, final DeserializationContext ctxt)
throws IOException, JsonProcessingException {
final ObjectNode tree = (ObjectNode) parser.getCodec().readTree(parser);
final JSONFeedImpl feed = new JSONFeedImpl();
if (tree.hasNonNull(ODataConstants.JSON_METADATA)) {
feed.setMetadata(URI.create(tree.get(ODataConstants.JSON_METADATA).textValue()));
}
if (tree.hasNonNull("odata.count")) {
feed.setCount(tree.get("odata.count").asInt());
}
if (tree.hasNonNull("odata.nextLink")) {
feed.setNext(URI.create(tree.get("odata.nextLink").textValue()));
}
if (tree.hasNonNull(ODataConstants.JSON_VALUE)) {
for (final Iterator<JsonNode> itor = tree.get(ODataConstants.JSON_VALUE).iterator(); itor.hasNext();) {
feed.getEntries().add(itor.next().traverse(parser.getCodec()).readValueAs(JSONEntryImpl.class));
}
}
return feed;
}
}

View File

@ -0,0 +1,99 @@
/*
* 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.olingo.client.core.data;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.apache.olingo.client.api.data.Entry;
import org.apache.olingo.client.api.data.Feed;
import org.apache.olingo.client.api.uri.SegmentType;
/**
* List of entries, represented via JSON.
*
* @see JSONEntry
*/
@JsonDeserialize(using = JSONFeedDeserializer.class)
public class JSONFeedImpl extends AbstractPayloadObject implements Feed {
private static final long serialVersionUID = -3576372289800799417L;
private URI metadata;
private Integer count;
private final List<Entry> entries = new ArrayList<Entry>();
private String next;
@Override
public URI getBaseURI() {
URI baseURI = null;
if (metadata != null) {
final String metadataURI = getMetadata().toASCIIString();
baseURI = URI.create(metadataURI.substring(0, metadataURI.indexOf(SegmentType.METADATA.getValue())));
}
return baseURI;
}
/**
* Gets the metadata URI.
*
* @return the metadata URI
*/
public URI getMetadata() {
return metadata;
}
/**
* Sets the metadata URI.
*
* @param metadata metadata URI.
*/
public void setMetadata(final URI metadata) {
this.metadata = metadata;
}
@Override
public Integer getCount() {
return count;
}
public void setCount(final Integer count) {
this.count = count;
}
@Override
public List<Entry> getEntries() {
return entries;
}
@Override
public void setNext(final URI next) {
this.next = next.toASCIIString();
}
@Override
public URI getNext() {
return next == null ? null : URI.create(next);
}
}

View File

@ -0,0 +1,117 @@
/*
* 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.olingo.client.core.data;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.apache.olingo.client.api.data.LinkCollection;
/**
* Link from an entry, represented via JSON.
*/
public class JSONLinkCollectionImpl extends AbstractPayloadObject implements LinkCollection {
private static final long serialVersionUID = -5006368367235783907L;
/**
* JSON link URL representation.
*/
static class JSONLinkURL extends AbstractPayloadObject {
private static final long serialVersionUID = 5365055617973271468L;
private URI url;
public URI getUrl() {
return url;
}
public void setUrl(final URI url) {
this.url = url;
}
}
@JsonProperty(value = "odata.metadata", required = false)
private URI metadata;
@JsonProperty(required = false)
private URI url;
@JsonProperty(value = "value", required = false)
private final List<JSONLinkURL> links = new ArrayList<JSONLinkURL>();
@JsonProperty(value = "odata.nextLink", required = false)
private String next;
/**
* Gets the metadata URI.
*/
public URI getMetadata() {
return metadata;
}
/**
* Sets the metadata URI.
*
* @param metadata metadata URI.
*/
public void setMetadata(final URI metadata) {
this.metadata = metadata;
}
/**
* {@inheritDoc }
*/
@JsonIgnore
@Override
public List<URI> getLinks() {
final List<URI> result = new ArrayList<URI>();
if (this.url == null) {
for (JSONLinkURL link : links) {
result.add(link.getUrl());
}
} else {
result.add(this.url);
}
return result;
}
/**
* {@inheritDoc }
*/
@JsonIgnore
@Override
public void setNext(final URI next) {
this.next = next == null ? null : next.toASCIIString();
}
/**
* {@inheritDoc }
*/
@JsonIgnore
@Override
public URI getNext() {
return next == null ? null : URI.create(next);
}
}

View File

@ -0,0 +1,122 @@
/*
* 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.olingo.client.core.data;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.lang3.StringUtils;
import org.apache.olingo.client.api.ODataConstants;
import org.apache.olingo.client.api.domain.ODataJClientEdmPrimitiveType;
import org.apache.olingo.client.api.utils.XMLUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
* Parse JSON string into <tt>JSONProperty</tt>.
*
* @see JSONProperty
*/
public class JSONPropertyDeserializer extends ODataJacksonDeserializer<JSONPropertyImpl> {
@Override
protected JSONPropertyImpl doDeserialize(final JsonParser parser, final DeserializationContext ctxt)
throws IOException, JsonProcessingException {
final ObjectNode tree = (ObjectNode) parser.getCodec().readTree(parser);
final JSONPropertyImpl property = new JSONPropertyImpl();
if (tree.hasNonNull(ODataConstants.JSON_METADATA)) {
property.setMetadata(URI.create(tree.get(ODataConstants.JSON_METADATA).textValue()));
tree.remove(ODataConstants.JSON_METADATA);
}
try {
final DocumentBuilder builder = XMLUtils.DOC_BUILDER_FACTORY.newDocumentBuilder();
final Document document = builder.newDocument();
Element content = document.createElement(ODataConstants.ELEM_PROPERTY);
if (property.getMetadata() != null) {
final String metadataURI = property.getMetadata().toASCIIString();
final int dashIdx = metadataURI.lastIndexOf('#');
if (dashIdx != -1) {
content.setAttribute(ODataConstants.ATTR_M_TYPE, metadataURI.substring(dashIdx + 1));
}
}
JsonNode subtree = null;
if (tree.has(ODataConstants.JSON_VALUE)) {
if (tree.has(ODataConstants.JSON_TYPE)
&& StringUtils.isBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {
content.setAttribute(ODataConstants.ATTR_M_TYPE, tree.get(ODataConstants.JSON_TYPE).asText());
}
final JsonNode value = tree.get(ODataConstants.JSON_VALUE);
if (value.isValueNode()) {
content.appendChild(document.createTextNode(value.asText()));
} else if (ODataJClientEdmPrimitiveType.isGeospatial(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {
subtree = tree.objectNode();
((ObjectNode) subtree).put(ODataConstants.JSON_VALUE, tree.get(ODataConstants.JSON_VALUE));
if (StringUtils.isNotBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {
((ObjectNode) subtree).put(
ODataConstants.JSON_VALUE + "@" + ODataConstants.JSON_TYPE,
content.getAttribute(ODataConstants.ATTR_M_TYPE));
}
} else {
subtree = tree.get(ODataConstants.JSON_VALUE);
}
} else {
subtree = tree;
}
if (subtree != null) {
JSONDOMTreeUtils.buildSubtree(client, content, subtree);
}
final List<Node> children = XMLUtils.getChildNodes(content, Node.ELEMENT_NODE);
if (children.size() == 1) {
final Element value = (Element) children.iterator().next();
if (ODataConstants.JSON_VALUE.equals(XMLUtils.getSimpleName(value))) {
if (StringUtils.isNotBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {
value.setAttribute(ODataConstants.ATTR_M_TYPE, content.getAttribute(ODataConstants.ATTR_M_TYPE));
}
content = value;
}
}
property.setContent(content);
} catch (ParserConfigurationException e) {
throw new JsonParseException("Cannot build property", parser.getCurrentLocation(), e);
}
return property;
}
}

View File

@ -0,0 +1,74 @@
/*
* 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.olingo.client.core.data;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.net.URI;
import org.w3c.dom.Element;
/**
* A single property (primitive, complex or collection) represented via JSON.
*/
@JsonSerialize(using = JSONPropertySerializer.class)
@JsonDeserialize(using = JSONPropertyDeserializer.class)
public class JSONPropertyImpl extends AbstractPayloadObject {
private static final long serialVersionUID = 553414431536637434L;
private URI metadata;
private Element content;
/**
* Gets metadata URI.
*
* @return metadata URI.
*/
public URI getMetadata() {
return metadata;
}
/**
* Sets metadata URI.
*
* @param metadata metadata URI.
*/
public void setMetadata(final URI metadata) {
this.metadata = metadata;
}
/**
* Gets content.
*
* @return content as DOM element.
*/
public Element getContent() {
return content;
}
/**
* Sets content.
*
* @param content content as DOM element.
*/
public void setContent(final Element content) {
this.content = content;
}
}

View File

@ -0,0 +1,80 @@
/*
* 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.olingo.client.core.data;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonLocation;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import org.apache.olingo.client.api.ODataConstants;
import org.apache.olingo.client.api.domain.ODataJClientEdmPrimitiveType;
import org.apache.olingo.client.api.utils.XMLUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* Writes out JSON string from <tt>JSONProperty</tt>.
*
* @see JSONProperty
*/
public class JSONPropertySerializer extends ODataJacksonSerializer<JSONPropertyImpl> {
@Override
public void doSerialize(final JSONPropertyImpl property, final JsonGenerator jgen, final SerializerProvider provider)
throws IOException, JsonProcessingException {
jgen.writeStartObject();
if (property.getMetadata() != null) {
jgen.writeStringField(ODataConstants.JSON_METADATA, property.getMetadata().toASCIIString());
}
final Element content = property.getContent();
if (XMLUtils.hasOnlyTextChildNodes(content)) {
jgen.writeStringField(ODataConstants.JSON_VALUE, content.getTextContent());
} else {
try {
final DocumentBuilder builder = XMLUtils.DOC_BUILDER_FACTORY.newDocumentBuilder();
final Document document = builder.newDocument();
final Element wrapper = document.createElement(ODataConstants.ELEM_PROPERTY);
if (XMLUtils.hasElementsChildNode(content)) {
wrapper.appendChild(document.renameNode(
document.importNode(content, true), null, ODataConstants.JSON_VALUE));
JSONDOMTreeUtils.writeSubtree(client, jgen, wrapper);
} else if (ODataJClientEdmPrimitiveType.isGeospatial(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {
wrapper.appendChild(document.renameNode(
document.importNode(content, true), null, ODataConstants.JSON_VALUE));
JSONDOMTreeUtils.writeSubtree(client, jgen, wrapper, true);
} else {
JSONDOMTreeUtils.writeSubtree(client, jgen, content);
}
} catch (Exception e) {
throw new JsonParseException("Cannot serialize property", JsonLocation.NA, e);
}
}
jgen.writeEndObject();
}
}

View File

@ -0,0 +1,100 @@
/*
* 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.olingo.client.core.data;
import org.apache.olingo.client.api.data.Entry;
import org.apache.olingo.client.api.data.Feed;
import org.apache.olingo.client.api.data.Link;
public class LinkImpl extends AbstractPayloadObject implements Link {
private static final long serialVersionUID = -3449344217160035501L;
private String title;
private String rel;
private String href;
private String type;
private Entry entry;
private Feed feed;
@Override
public String getTitle() {
return title;
}
@Override
public void setTitle(final String title) {
this.title = title;
}
@Override
public String getRel() {
return rel;
}
@Override
public void setRel(final String rel) {
this.rel = rel;
}
@Override
public String getHref() {
return href;
}
@Override
public void setHref(final String href) {
this.href = href;
}
@Override
public String getType() {
return type;
}
@Override
public void setType(final String type) {
this.type = type;
}
@Override
public Entry getInlineEntry() {
return entry;
}
@Override
public void setInlineEntry(final Entry entry) {
this.entry = entry;
}
@Override
public Feed getInlineFeed() {
return feed;
}
@Override
public void setInlineFeed(final Feed feed) {
this.feed = feed;
}
}

View File

@ -0,0 +1,309 @@
/*
* 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.olingo.client.core.data;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.olingo.client.api.ODataClient;
import org.apache.olingo.client.api.ODataConstants;
import org.apache.olingo.client.api.data.Entry;
import org.apache.olingo.client.api.domain.ODataEntity;
import org.apache.olingo.client.api.domain.ODataEntitySet;
import org.apache.olingo.client.api.format.ODataPubFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* OData entity set iterator class.
* <br/>
* <b>Please don't forget to call the <tt>close()>/<tt> method when not needed any more.</b>
*/
public class ODataEntitySetIterator implements Iterator<ODataEntity> {
/**
* Logger.
*/
private static final Logger LOG = LoggerFactory.getLogger(ODataEntitySetIterator.class);
private static final long serialVersionUID = 9039605899821494025L;
private final ODataClient odataClient;
private final InputStream stream;
private final ODataPubFormat format;
private Entry cached;
private ODataEntitySet entitySet;
private final ByteArrayOutputStream osFeed;
private final String namespaces;
private boolean available = true;
/**
* Constructor.
*
* @param odataClient client instance getting this request
* @param stream source stream.
* @param format OData format.
*/
public ODataEntitySetIterator(final ODataClient odataClient, final InputStream stream, final ODataPubFormat format) {
this.odataClient = odataClient;
this.stream = stream;
this.format = format;
this.osFeed = new ByteArrayOutputStream();
if (format == ODataPubFormat.ATOM) {
namespaces = getAllElementAttributes(stream, "feed", osFeed);
} else {
namespaces = null;
try {
if (consume(stream, "\"value\":", osFeed, true) >= 0) {
int c = 0;
while (c != '[' && (c = stream.read()) >= 0) {
osFeed.write(c);
}
}
} catch (IOException e) {
LOG.error("Error parsing feed", e);
throw new IllegalStateException(e);
}
}
}
/**
* {@inheritDoc }
*/
@Override
public boolean hasNext() {
if (available && cached == null) {
if (format == ODataPubFormat.ATOM) {
cached = nextAtomEntryFromFeed(stream, osFeed, namespaces);
} else {
cached = nextJsonEntryFromFeed(stream, osFeed);
}
if (cached == null) {
available = false;
entitySet = odataClient.getReader().
readEntitySet(new ByteArrayInputStream(osFeed.toByteArray()), format);
close();
}
}
return available;
}
/**
* {@inheritDoc }
*/
@Override
public ODataEntity next() {
if (hasNext()) {
final ODataEntity res = odataClient.getBinder().getODataEntity(cached);
cached = null;
return res;
}
throw new NoSuchElementException("No entity found");
}
/**
* Unsupported operation.
*/
@Override
public void remove() {
throw new UnsupportedOperationException("Operation not supported");
}
/**
* Closes the current iterator.
*/
public void close() {
IOUtils.closeQuietly(stream);
IOUtils.closeQuietly(osFeed);
}
/**
* Gets the next link if exists.
*
* @return next link if exists; null otherwise.
*/
public URI getNext() {
if (entitySet == null) {
throw new IllegalStateException("Iteration must be completed in order to retrieve the link for next page");
}
return entitySet.getNext();
}
private Entry nextJsonEntryFromFeed(final InputStream input, final OutputStream osFeed) {
final ByteArrayOutputStream entry = new ByteArrayOutputStream();
Entry jsonEntry = null;
try {
int c = 0;
boolean foundNewOne = false;
do {
c = input.read();
if (c == '{') {
entry.write(c);
c = -1;
foundNewOne = true;
}
if (c == ']') {
osFeed.write(c);
c = -1;
}
} while (c >= 0);
if (foundNewOne) {
int count = 1;
c = 0;
while (count > 0 && c >= 0) {
c = input.read();
if (c == '{') {
count++;
} else if (c == '}') {
count--;
}
entry.write(c);
}
if (c >= 0) {
jsonEntry = odataClient.getDeserializer().toEntry(
new ByteArrayInputStream(entry.toByteArray()), ODataPubFormat.JSON);
}
} else {
while ((c = input.read()) >= 0) {
osFeed.write(c);
}
}
} catch (Exception e) {
LOG.error("Error retrieving entities from EntitySet", e);
}
return jsonEntry;
}
/**
* De-Serializes a stream into an OData entity set.
*
* @param input stream to de-serialize.
* @param format de-serialize as AtomFeed or JSONFeed
* @return de-serialized entity set.
*/
private Entry nextAtomEntryFromFeed(final InputStream input, final OutputStream osFeed, final String namespaces) {
final ByteArrayOutputStream entry = new ByteArrayOutputStream();
Entry atomEntry = null;
try {
if (consume(input, "<entry>", osFeed, false) >= 0) {
entry.write("<entry ".getBytes(ODataConstants.UTF8));
entry.write(namespaces.getBytes(ODataConstants.UTF8));
entry.write(">".getBytes(ODataConstants.UTF8));
if (consume(input, "</entry>", entry, true) >= 0) {
atomEntry = odataClient.getDeserializer().
toEntry(new ByteArrayInputStream(entry.toByteArray()), ODataPubFormat.ATOM);
}
}
} catch (Exception e) {
LOG.error("Error retrieving entities from EntitySet", e);
}
return atomEntry;
}
private String getAllElementAttributes(final InputStream input, final String name, final OutputStream os) {
final ByteArrayOutputStream attrs = new ByteArrayOutputStream();
String res;
try {
byte[] attrsDeclaration = null;
final String key = "<" + name + " ";
if (consume(input, key, os, true) >= 0 && consume(input, ">", attrs, false) >= 0) {
attrsDeclaration = attrs.toByteArray();
os.write(attrsDeclaration);
os.write('>');
}
res = attrsDeclaration == null
? StringUtils.EMPTY
: new String(attrsDeclaration, ODataConstants.UTF8).trim();
} catch (Exception e) {
LOG.error("Error retrieving entities from EntitySet", e);
res = StringUtils.EMPTY;
}
return res.endsWith("/") ? res.substring(0, res.length() - 1) : res;
}
private int consume(
final InputStream input, final String end, final OutputStream os, final boolean includeEndKey)
throws IOException {
final char[] endKey = end.toCharArray();
final char[] endLowerKey = end.toLowerCase().toCharArray();
final char[] endUpperKey = end.toUpperCase().toCharArray();
int pos = 0;
int c = 0;
while (pos < endKey.length && (c = input.read()) >= 0) {
if (c == endLowerKey[pos] || c == endUpperKey[pos]) {
pos++;
if (includeEndKey && os != null) {
os.write(c);
}
} else if (pos > 0) {
if (!includeEndKey && os != null) {
for (int i = 0; i < pos; i++) {
os.write(endKey[i]);
}
}
if (os != null) {
os.write(c);
}
pos = 0;
} else {
if (os != null) {
os.write(c);
}
}
}
return c;
}
}

View File

@ -0,0 +1,97 @@
/*
* 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.olingo.client.core.data;
import java.io.Serializable;
import java.net.URI;
import org.apache.olingo.client.api.data.Operation;
/**
* Representation of an OData operation (legacy, action or function).
*/
public class OperationImpl extends AbstractPayloadObject implements Operation, Serializable {
private static final long serialVersionUID = -5784652334334645128L;
private String metadataAnchor;
private String title;
private URI target;
/**
* Gets metadata anchor.
*
* @return metadata anchor.
*/
@Override
public String getMetadataAnchor() {
return metadataAnchor;
}
/**
* Sets metadata anchor.
*
* @param metadataAnchor metadata anchor.
*/
@Override
public void setMetadataAnchor(final String metadataAnchor) {
this.metadataAnchor = metadataAnchor;
}
/**
* Gets title.
*
* @return title.
*/
@Override
public String getTitle() {
return title;
}
/**
* Sets title.
*
* @param title title.
*/
@Override
public void setTitle(final String title) {
this.title = title;
}
/**
* Gets target.
*
* @return target.
*/
@Override
public URI getTarget() {
return target;
}
/**
* Sets target.
*
* @param target target.
*/
@Override
public void setTarget(final URI target) {
this.target = target;
}
}

View File

@ -0,0 +1,213 @@
/*
* 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.olingo.client.core.data;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlText;
import java.util.Map;
import org.apache.olingo.client.api.data.Error;
/**
* This class represents an OData error returned as JSON.
*/
public class XMLErrorImpl extends AbstractPayloadObject implements Error {
private static final long serialVersionUID = -3476499168507242932L;
@JacksonXmlText(false)
private String code;
@JsonProperty
private Message message;
@JsonProperty(required = false)
private InnerError innererror;
@Override
public String getCode() {
return code;
}
/**
* Sets error code.
*
* @param code error code.
*/
public void setCode(final String code) {
this.code = code;
}
@JsonIgnore
@Override
public String getMessageLang() {
return this.message == null ? null : this.message.getLang();
}
@JsonIgnore
@Override
public String getMessageValue() {
return this.message == null ? null : this.message.getValue();
}
/**
* Sets the value of the message property.
*
* @param value allowed object is {@link Error.Message }
*
*/
public void setMessage(final Message value) {
this.message = value;
}
@JsonIgnore
@Override
public String getInnerErrorMessage() {
return this.innererror == null ? null : this.innererror.getMessage().getValue();
}
@JsonIgnore
@Override
public String getInnerErrorType() {
return this.innererror == null ? null : this.innererror.getType().getValue();
}
@JsonIgnore
@Override
public String getInnerErrorStacktrace() {
return this.innererror == null ? null : this.innererror.getStacktrace().getValue();
}
static class TextChildContainer extends AbstractPayloadObject {
private static final long serialVersionUID = -8908394095210115904L;
public TextChildContainer() {
super();
}
public TextChildContainer(final String value) {
super();
this.value = value;
}
@JsonCreator
public TextChildContainer(final Map<String, Object> props) {
super();
this.value = (String) props.get("");
}
private String value;
public String getValue() {
return value;
}
public void setValue(final String value) {
this.value = value;
}
}
/**
* Error message.
*/
public static class Message extends TextChildContainer {
private static final long serialVersionUID = 2577818040815637859L;
private String lang;
public Message() {
super();
}
@JsonCreator
public Message(final Map<String, Object> props) {
super(props);
this.lang = (String) props.get("lang");
}
/**
* Gets language.
*
* @return language.
*/
public String getLang() {
return lang;
}
/**
* Sets language.
*
* @param lang language.
*/
public void setLang(final String lang) {
this.lang = lang;
}
}
/**
* Inner error.
*/
static class InnerError extends AbstractPayloadObject {
private static final long serialVersionUID = -3920947476143537640L;
private TextChildContainer message;
private TextChildContainer type;
private TextChildContainer stacktrace;
private InnerError internalexception;
public TextChildContainer getMessage() {
return message;
}
public void setMessage(final TextChildContainer message) {
this.message = message;
}
public TextChildContainer getType() {
return type;
}
public void setType(final TextChildContainer type) {
this.type = type;
}
public TextChildContainer getStacktrace() {
return stacktrace;
}
public void setStacktrace(final TextChildContainer stacktrace) {
this.stacktrace = stacktrace;
}
public InnerError getInternalexception() {
return internalexception;
}
public void setInternalexception(final InnerError internalexception) {
this.internalexception = internalexception;
}
}
}

View File

@ -1,4 +1,4 @@
/*
/*
* 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
@ -16,44 +16,55 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.olingo.client.api.deserializer;
package org.apache.olingo.client.core.data;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.olingo.client.api.data.LinkCollection;
public interface Entity {
public class XMLLinkCollectionImpl implements LinkCollection {
String getODataContext();
private final List<URI> links = new ArrayList<URI>();
String getODataMetaDataEtag();
private URI next;
String getODataType();
/**
* Constructor.
*/
public XMLLinkCollectionImpl() {
}
Long getODataCount();
/**
* Constructor.
*
* @param next next page link.
*/
public XMLLinkCollectionImpl(final URI next) {
this.next = next;
}
String getODataNextLink();
/**
* {@inheritDoc }
*/
@Override
public List<URI> getLinks() {
return links;
}
String getODataDeltaLink();
/**
* {@inheritDoc }
*/
@Override
public void setNext(final URI next) {
this.next = next;
}
String getODataId();
String getODataETag();
String getODataEditLink();
String getODataReadLink();
List<Property> getProperties();
Map<String, NavigationProperty> getNavigationProperties();
Map<String, AnnotationProperty> getAnnotationProperties();
Map<String, StructuralProperty> getStructuralProperties();
Property getProperty(String name);
<T extends Property> T getProperty(String name, Class<T> clazz);
Object getPropertyContent(String name);
/**
* {@inheritDoc }
*/
@Override
public URI getNext() {
return next;
}
}

View File

@ -1,82 +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.olingo.client.core.deserializer;
import java.util.Collections;
import java.util.Map;
import org.apache.olingo.client.api.deserializer.AnnotationProperty;
import org.apache.olingo.client.api.deserializer.ComplexValue;
import org.apache.olingo.client.api.deserializer.NavigationProperty;
import org.apache.olingo.client.api.deserializer.StructuralProperty;
import org.apache.olingo.client.api.deserializer.Value;
public class ComplexValueImpl extends PropertyCollection implements ComplexValue {
public ComplexValueImpl() {
}
public ComplexValueImpl(final Map<String, AnnotationProperty> annotationProperties,
final Map<String, NavigationProperty> navigationProperties,
final Map<String, StructuralProperty> structuralProperties) {
super(annotationProperties, navigationProperties, structuralProperties);
}
@Override
public Value getValue(final String name) {
final StructuralProperty property = structuralProperties.get(name);
if (property == null) {
return null;
}
return property.getValue();
}
@Override
public Map<String, AnnotationProperty> getAnnotationProperties() {
return Collections.unmodifiableMap(annotationProperties);
}
@Override
public Map<String, NavigationProperty> getNavigationProperties() {
return Collections.unmodifiableMap(navigationProperties);
}
@Override
public boolean isComplex() {
return true;
}
@Override
public Map<String, StructuralProperty> getContent() {
return Collections.unmodifiableMap(structuralProperties);
}
@SuppressWarnings("unchecked")
@Override
public <T> T getContentAs(final T type) {
return (T) getContent();
}
@Override
public String toString() {
return "ComplexValueImpl [annotations=" + annotationProperties + ", navigationProperties=" + navigationProperties
+ ", properties=" + structuralProperties + "]";
}
}

View File

@ -1,126 +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.olingo.client.core.deserializer;
import java.util.Map;
import org.apache.olingo.client.api.deserializer.AnnotationProperty;
import org.apache.olingo.client.api.deserializer.Entity;
import org.apache.olingo.client.api.deserializer.NavigationProperty;
import org.apache.olingo.client.api.deserializer.Property;
import org.apache.olingo.client.api.deserializer.StructuralProperty;
public class EntityImpl extends PropertyCollection implements Entity {
public EntityImpl() {
}
public EntityImpl(final Map<String, AnnotationProperty> annotationProperties,
final Map<String, NavigationProperty> navigationProperties,
final Map<String, StructuralProperty> structuralProperties) {
super(annotationProperties, navigationProperties, structuralProperties);
}
@Override
public String getODataMetaDataEtag() {
return getAnnotationValue("odata.metadataEtag");
}
@Override
public String getODataType() {
return getAnnotationValue("odata.type");
}
@Override
public Long getODataCount() {
return Long.valueOf(getAnnotationValue("odata.count"));
}
@Override
public String getODataNextLink() {
return getAnnotationValue("odata.nextLink");
}
@Override
public String getODataDeltaLink() {
return getAnnotationValue("odata.deltaLink");
}
@Override
public String getODataReadLink() {
return getAnnotationValue("odata.readLink");
}
@Override
public String getODataContext() {
return getAnnotationValue("odata.context");
}
@Override
public String getODataId() {
return getAnnotationValue("odata.id");
}
@Override
public String getODataETag() {
return getAnnotationValue("odata.etag");
}
@Override
public String getODataEditLink() {
return getAnnotationValue("odata.editLink");
}
@Override
public Object getPropertyContent(final String name) {
final StructuralProperty property = structuralProperties.get(name);
if (property != null) {
return property.getValue().getContent();
}
return null;
}
@Override
public Property getProperty(final String name) {
Property property = structuralProperties.get(name);
if (property == null) {
property = annotationProperties.get(name);
}
if (property == null) {
property = navigationProperties.get(name);
}
return property;
}
@SuppressWarnings("unchecked")
@Override
public <T extends Property> T getProperty(final String name, final Class<T> clazz) {
final Property property = getProperty(name);
return (T) property;
}
private String getAnnotationValue(final String key) {
final AnnotationProperty property = annotationProperties.get(key);
if (property == null) {
return null;
}
return property.getValue();
}
}

View File

@ -1,72 +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.olingo.client.core.deserializer;
import java.io.IOException;
import org.apache.olingo.client.api.deserializer.EntitySet;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
public class EntitySetBuilder {
private final JsonParser parser;
public EntitySetBuilder(final JsonParser jp) {
parser = jp;
}
public EntitySet buildEntitySet() throws JsonParseException, IOException {
return parseEntitySet(parser);
}
private EntitySet parseEntitySet(final JsonParser jp) throws JsonParseException, IOException {
final EntitySetImpl entitySet = new EntitySetImpl();
boolean arrayStarted = false;
while (jp.nextToken() != null) {
final JsonToken token = jp.getCurrentToken();
switch (token) {
case START_ARRAY:
final PropertyCollectionBuilder builder = new PropertyCollectionBuilder(jp, entitySet);
entitySet.setPropertyCollectionBuilder(builder);
arrayStarted = true;
break;
case START_OBJECT:
if (arrayStarted) {
return entitySet;
}
break;
case VALUE_NUMBER_INT:
case VALUE_STRING:
entitySet.addAnnotation(jp.getCurrentName(), jp.getValueAsString());
break;
default:
break;
}
}
return entitySet;
}
}

View File

@ -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 org.apache.olingo.client.core.deserializer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.olingo.client.api.deserializer.Entity;
import org.apache.olingo.client.api.deserializer.EntitySet;
import com.fasterxml.jackson.core.JsonParseException;
public class EntitySetImpl implements EntitySet, Iterator<Entity> {
private String odataContext;
private Long odataCount;
private String odataNextLink;
private String odataDeltaLink;
private List<Entity> entities = null;
private PropertyCollectionBuilder propertyCollectionsBuilder;
@Override
public String getODataContext() {
return odataContext;
}
@Override
public Long getODataCount() {
return odataCount;
}
@Override
public String getODataNextLink() {
return odataNextLink;
}
@Override
public String getODataDeltaLink() {
return odataDeltaLink;
}
public void addAnnotation(final String name, final String value) {
if ("odata.context".equalsIgnoreCase(name)) {
odataContext = value;
} else if ("odata.deltaLink".equalsIgnoreCase(name)) {
odataDeltaLink = value;
} else if ("odata.count".equalsIgnoreCase(name)) {
odataCount = Long.parseLong(value);
} else if ("odata.nextLink".equalsIgnoreCase(name)) {
odataNextLink = value;
}
}
@Override
public List<Entity> getEntities() {
if (entities == null) {
entities = new ArrayList<Entity>();
while (propertyCollectionsBuilder.parseNext()) {
entities.add(propertyCollectionsBuilder.buildEntity());
}
}
return entities;
}
public void setPropertyCollectionBuilder(final PropertyCollectionBuilder builder) {
propertyCollectionsBuilder = builder;
}
@Override
public boolean hasNext() {
try {
return propertyCollectionsBuilder.hasNext();
} catch (JsonParseException e) {
} catch (IOException e) {
}
return false;
}
@Override
public Entity next() {
if (propertyCollectionsBuilder.parseNext()) {
return propertyCollectionsBuilder.buildEntity();
}
return null;
}
@Override
public void remove() {
}
@Override
public Iterator<Entity> iterator() {
return this;
}
}

View File

@ -1,89 +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.olingo.client.core.deserializer;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import org.apache.olingo.client.api.deserializer.ClientException;
import org.apache.olingo.client.api.deserializer.Entity;
import org.apache.olingo.client.api.deserializer.EntitySet;
import org.apache.olingo.client.api.deserializer.Property;
import org.apache.olingo.client.api.deserializer.Reader;
import org.apache.olingo.client.api.deserializer.StructuralProperty;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
public class JsonReader implements Reader {
@Override
public EntitySet readEntitySet(final InputStream in) throws ClientException {
final JsonFactory jsonFactory = new JsonFactory();
// or, for data binding, org.codehaus.jackson.mapper.MappingJsonFactory
try {
JsonParser jp = jsonFactory.createParser(in);
EntitySetBuilder entitySet = new EntitySetBuilder(jp);
return entitySet.buildEntitySet();
} catch (JsonParseException e) {
throw new ClientException("JSON Parsing failed.", e);
} catch (IOException e) {
throw new ClientException("JSON Parsing failed.", e);
}
}
@Override
public Entity readEntity(final InputStream in) throws ClientException {
Entity entity = null;
final JsonFactory jsonFactory = new JsonFactory();
// or, for data binding, org.codehaus.jackson.mapper.MappingJsonFactory
try {
final JsonParser jp = jsonFactory.createParser(in);
final PropertyCollectionBuilder builder = new PropertyCollectionBuilder(jp);
builder.parseNext();
entity = builder.buildEntity();
} catch (JsonParseException e) {
throw new ClientException("JSON Parsing failed.", e);
} catch (IOException e) {
throw new ClientException("JSON Parsing failed.", e);
}
return entity;
}
/*
* (non-Javadoc)
*
* @see org.apache.olingo.core.consumer.Reader#parseProperty(java.io.InputStream)
*/
@Override
public Property readProperty(final InputStream in) throws ClientException {
final Entity entity = readEntity(in);
final Map<String, StructuralProperty> properties = entity.getStructuralProperties();
if (properties.size() == 1) {
return properties.values().iterator().next();
}
return null;
}
}

View File

@ -1,89 +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.olingo.client.core.deserializer;
import org.apache.olingo.client.api.deserializer.NavigationProperty;
public class NavigationPropertyImpl implements NavigationProperty {
private final String name;
private String associationLink;
private String navigationLink;
public NavigationPropertyImpl(final String name) {
this.name = parseName(name);
}
public NavigationPropertyImpl(final String name, final String link) {
this(name);
updateLink(name, link);
}
@Override
public String getName() {
return name;
}
@Override
public String getAssociationLink() {
return associationLink;
}
@Override
public String getNavigationLink() {
return navigationLink;
}
public void updateLink(final String name, final String link) {
final String regexNavigationLink = ".*@odata.navigationLink$";
final String regexAssociationLink = ".*@odata.associationLink$";
if (name.matches(regexNavigationLink)) {
navigationLink = link;
} else if (name.matches(regexAssociationLink)) {
associationLink = link;
}
}
private String parseName(final String nameToParse) {
final String[] split = nameToParse.split("@");
if (split.length == 2) {
return split[0];
} else {
throw new IllegalArgumentException("Got OData Navigation with unparseable format '"
+ nameToParse + "'.");
}
}
public void updateLink(final NavigationProperty navigationProperty) {
if (navigationProperty.getAssociationLink() != null) {
associationLink = navigationProperty.getAssociationLink();
}
if (navigationProperty.getNavigationLink() != null) {
navigationLink = navigationProperty.getNavigationLink();
}
}
@Override
public String toString() {
return "NavigationPropertyImpl [name=" + name + ", associationLink=" + associationLink
+ ", navigationLink=" + navigationLink + "]";
}
}

View File

@ -1,96 +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.olingo.client.core.deserializer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.olingo.client.api.deserializer.AnnotationProperty;
import org.apache.olingo.client.api.deserializer.NavigationProperty;
import org.apache.olingo.client.api.deserializer.Property;
import org.apache.olingo.client.api.deserializer.StructuralProperty;
abstract class PropertyCollection {
protected Map<String, AnnotationProperty> annotationProperties = new HashMap<String, AnnotationProperty>();
protected Map<String, NavigationProperty> navigationProperties = new HashMap<String, NavigationProperty>();
protected Map<String, StructuralProperty> structuralProperties = new HashMap<String, StructuralProperty>();
public PropertyCollection() {
}
protected PropertyCollection(final Map<String, AnnotationProperty> annotationProperties,
final Map<String, NavigationProperty> navigationProperties,
final Map<String, StructuralProperty> structuralProperties) {
this.annotationProperties = annotationProperties;
this.navigationProperties = navigationProperties;
this.structuralProperties = structuralProperties;
}
public List<Property> getProperties() {
final int initialCapacity = annotationProperties.size() + navigationProperties.size() + structuralProperties.size();
final List<Property> properties = new ArrayList<Property>(initialCapacity);
properties.addAll(annotationProperties.values());
properties.addAll(navigationProperties.values());
properties.addAll(structuralProperties.values());
return properties;
}
public Map<String, AnnotationProperty> getAnnotationProperties() {
return Collections.unmodifiableMap(annotationProperties);
}
public Map<String, NavigationProperty> getNavigationProperties() {
return Collections.unmodifiableMap(navigationProperties);
}
public Map<String, StructuralProperty> getStructuralProperties() {
return Collections.unmodifiableMap(structuralProperties);
}
public void addProperty(final Property property) {
if (property == null) {
throw new IllegalArgumentException("Property parameter MUST NOT be NULL.");
}
if (property instanceof NavigationPropertyImpl) {
final NavigationPropertyImpl navProperty = (NavigationPropertyImpl) navigationProperties.get(property.getName());
if (navProperty == null) {
navigationProperties.put(property.getName(), (NavigationPropertyImpl) property);
} else {
final NavigationProperty temp = (NavigationProperty) property;
navProperty.updateLink(temp);
}
} else if (property instanceof AnnotationPropertyImpl) {
annotationProperties.put(property.getName(), (AnnotationPropertyImpl) property);
} else if (property instanceof StructuralProperty) {
structuralProperties.put(property.getName(), (StructuralProperty) property);
} else {
throw new IllegalArgumentException("Unknown class '" + property.getClass() + "'.");
}
}
}

View File

@ -1,221 +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.olingo.client.core.deserializer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.olingo.client.api.deserializer.AnnotationProperty;
import org.apache.olingo.client.api.deserializer.ComplexValue;
import org.apache.olingo.client.api.deserializer.Entity;
import org.apache.olingo.client.api.deserializer.NavigationProperty;
import org.apache.olingo.client.api.deserializer.Property;
import org.apache.olingo.client.api.deserializer.StructuralProperty;
import org.apache.olingo.client.api.deserializer.Value;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PropertyCollectionBuilder extends PropertyCollection {
private static final Logger LOG = LoggerFactory.getLogger(PropertyCollectionBuilder.class);
private JsonParser parser;
private EntitySetImpl enclosingEntitySet;
private PropertyCollectionBuilder next = null;
public PropertyCollectionBuilder(final JsonParser parser) {
this.parser = parser;
}
private PropertyCollectionBuilder() {
}
public PropertyCollectionBuilder(final JsonParser jp, final EntitySetImpl entitySet) {
this(jp);
enclosingEntitySet = entitySet;
}
public Entity buildEntity() {
final Entity entity = new EntityImpl(annotationProperties, navigationProperties, structuralProperties);
resetProperties();
return entity;
}
public ComplexValue buildComplexValue() {
final ComplexValue value = new ComplexValueImpl(annotationProperties, navigationProperties, structuralProperties);
resetProperties();
return value;
}
private void resetProperties() {
annotationProperties = new HashMap<String, AnnotationProperty>();
navigationProperties = new HashMap<String, NavigationProperty>();
structuralProperties = new HashMap<String, StructuralProperty>();
}
public boolean hasNext() throws JsonParseException, IOException {
if (parser.isClosed()) {
return false;
}
next = parseNextObject(parser, this);
return (next != null);
}
public boolean parseNext() {
try {
if (hasNext()) {
if (next != null) {
return true;
}
if (next == null) {
parser.close();
return false;
}
return true;
}
} catch (JsonParseException e) {
LOG.error("While parsing", e);
} catch (IOException e) {
LOG.error("While parsing", e);
}
return false;
}
/**
*
* @param jp
* @param builder
* @return
* @throws IOException
* @throws JsonParseException
*/
private PropertyCollectionBuilder parseNextObject(final JsonParser jp, final PropertyCollectionBuilder builder)
throws JsonParseException, IOException {
boolean endReached = readToStartObjectOrEnd(jp);
if (endReached) {
return null;
}
//
String currentFieldName = null;
List<Value> values = null;
while (jp.nextToken() != null) {
final JsonToken token = jp.getCurrentToken();
switch (token) {
case START_OBJECT:
if (currentFieldName != null) {
final ComplexValue cvp = parseNextObject(jp, new PropertyCollectionBuilder()).buildComplexValue();
if (values == null) {
builder.addProperty(new StructuralPropertyImpl(currentFieldName, cvp));
} else {
values.add(cvp);
}
}
break;
case END_OBJECT:
return builder;
case START_ARRAY:
values = new ArrayList<Value>();
break;
case END_ARRAY:
if (values != null) {
builder.addProperty(new StructuralPropertyImpl(currentFieldName, values));
values = null;
}
break;
case FIELD_NAME:
currentFieldName = jp.getCurrentName();
break;
case NOT_AVAILABLE:
break;
case VALUE_EMBEDDED_OBJECT:
break;
case VALUE_NULL:
Property nullProperty = createProperty(jp.getCurrentName(), null);
builder.addProperty(nullProperty);
break;
case VALUE_FALSE:
case VALUE_NUMBER_FLOAT:
case VALUE_NUMBER_INT:
case VALUE_STRING:
case VALUE_TRUE:
if (values == null) {
Property property = createProperty(jp.getCurrentName(), jp.getValueAsString());
builder.addProperty(property);
} else {
PrimitiveValue value = new PrimitiveValue(jp.getValueAsString());
values.add(value);
}
break;
default:
break;
}
}
return null;
}
private boolean readToStartObjectOrEnd(final JsonParser jp) throws IOException, JsonParseException {
final JsonToken endToken = JsonToken.START_OBJECT;
JsonToken token = jp.getCurrentToken() == null ? jp.nextToken() : jp.getCurrentToken();
while (token != null && token != endToken) {
if (enclosingEntitySet != null) {
switch (token) {
case VALUE_FALSE:
case VALUE_NUMBER_FLOAT:
case VALUE_NUMBER_INT:
case VALUE_TRUE:
case VALUE_STRING:
enclosingEntitySet.addAnnotation(jp.getCurrentName(), jp.getValueAsString());
break;
default:
break;
}
}
//
token = jp.nextToken();
}
return token == null;
}
private Property createProperty(final String name, final String value) {
if (name.contains("@")) {
return new NavigationPropertyImpl(name, value);
} else if (name.contains(".")) {
return new AnnotationPropertyImpl(name, value);
} else {
return new StructuralPropertyImpl(name, new PrimitiveValue(value));
}
}
}

View File

@ -1,83 +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.olingo.client.core.deserializer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.olingo.client.api.deserializer.StructuralProperty;
import org.apache.olingo.client.api.deserializer.Value;
public class StructuralPropertyImpl implements StructuralProperty {
private final List<Value> values;
private final String name;
private final boolean containsCollection;
public StructuralPropertyImpl(final String name, final Value value) {
this(name, false, value);
}
public StructuralPropertyImpl(final String name, final List<Value> values) {
// XXX: ugly -> refactor
this(name, true, values.toArray(new Value[0]));
}
public StructuralPropertyImpl(final String name, final boolean asCollection, final Value... value) {
if (value == null || value.length == 0) {
throw new IllegalArgumentException("Missing or NULL value argument.");
}
containsCollection = asCollection;
this.name = name;
values = new ArrayList<Value>(value.length);
for (Value v : value) {
values.add(v);
}
}
@Override
public Value getValue() {
return values.get(0);
}
@Override
public List<Value> getValues() {
return Collections.unmodifiableList(values);
}
@Override
public String getName() {
return name;
}
@Override
public boolean containsCollection() {
return containsCollection;
}
@Override
public String toString() {
return "StructuralPropertyImpl [name=" + name + ", containsCollection=" + containsCollection
+ ", values=" + values + "]";
}
}

View File

@ -18,161 +18,174 @@
*/
package org.apache.olingo.client.core.op.impl;
import com.fasterxml.aalto.stax.InputFactoryImpl;
import com.fasterxml.aalto.stax.OutputFactoryImpl;
import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule;
import com.fasterxml.jackson.dataformat.xml.XmlFactory;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import org.apache.olingo.client.api.ODataClient;
import org.apache.olingo.client.api.ODataConstants;
import org.apache.olingo.client.api.data.Entry;
import org.apache.olingo.client.api.data.Error;
import org.apache.olingo.client.api.data.Feed;
import org.apache.olingo.client.api.data.LinkCollection;
import org.apache.olingo.client.api.format.ODataFormat;
import org.apache.olingo.client.api.format.ODataPubFormat;
import org.apache.olingo.client.api.op.ODataDeserializer;
import org.apache.olingo.client.core.data.AtomDeserializer;
import org.apache.olingo.client.core.data.JSONEntryImpl;
import org.apache.olingo.client.core.data.JSONErrorBundle;
import org.apache.olingo.client.core.data.JSONFeedImpl;
import org.apache.olingo.client.core.data.JSONLinkCollectionImpl;
import org.apache.olingo.client.core.data.JSONPropertyImpl;
import org.apache.olingo.client.core.data.XMLErrorImpl;
import org.apache.olingo.client.core.data.XMLLinkCollectionImpl;
import org.apache.olingo.client.core.xml.XMLParser;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public abstract class AbstractODataDeserializer extends AbstractJacksonTool implements ODataDeserializer {
private static final long serialVersionUID = -4244158979195609909L;
// private final AtomDeserializer atomDeserializer;
private final AtomDeserializer atomDeserializer;
public AbstractODataDeserializer(final ODataClient client) {
super(client);
// this.atomDeserializer = new AtomDeserializer(client);
this.atomDeserializer = new AtomDeserializer(client);
}
@Override
public Feed toFeed(final InputStream input, final ODataPubFormat format) {
return format == ODataPubFormat.ATOM
? toAtomFeed(input)
: toJSONFeed(input);
}
@Override
public Entry toEntry(final InputStream input, final ODataPubFormat format) {
return format == ODataPubFormat.ATOM
? toAtomEntry(input)
: toJSONEntry(input);
}
@Override
public Element toPropertyDOM(final InputStream input, final ODataFormat format) {
return format == ODataFormat.XML
? toPropertyDOMFromXML(input)
: toPropertyDOMFromJSON(input);
}
@Override
public LinkCollection toLinkCollection(final InputStream input, final ODataFormat format) {
return format == ODataFormat.XML
? toLinkCollectionFromXML(input)
: toLinkCollectionFromJSON(input);
}
@Override
public Error toError(final InputStream input, final boolean isXML) {
return isXML
? toErrorFromXML(input)
: toErrorFromJSON(input);
}
// @Override
// @SuppressWarnings("unchecked")
// public <T extends Feed> T toFeed(final InputStream input, final Class<T> reference) {
// T entry;
//
// if (AtomFeed.class.equals(reference)) {
// entry = (T) toAtomFeed(input);
// } else {
// entry = (T) toJSONFeed(input);
// }
//
// return entry;
// }
//
// @Override
// @SuppressWarnings("unchecked")
// public <T extends Entry> T toEntry(final InputStream input, final Class<T> reference) {
// T entry;
//
// if (AtomEntry.class.equals(reference)) {
// entry = (T) toAtomEntry(input);
//
// } else {
// entry = (T) toJSONEntry(input);
// }
//
// return entry;
// }
//
// @Override
// public Element toPropertyDOM(final InputStream input, final ODataFormat format) {
// return format == ODataFormat.XML
// ? toPropertyDOMFromXML(input)
// : toPropertyDOMFromJSON(input);
// }
//
// @Override
// public LinkCollection toLinkCollection(final InputStream input, final ODataFormat format) {
// return format == ODataFormat.XML
// ? toLinkCollectionFromXML(input)
// : toLinkCollectionFromJSON(input);
// }
//
// @Override
// public ODataError toODataError(final InputStream input, final boolean isXML) {
// return isXML
// ? toODataErrorFromXML(input)
// : toODataErrorFromJSON(input);
// }
//
@Override
public Element toDOM(final InputStream input) {
return XMLParser.PARSER.deserialize(input);
}
//
// /*
// * ------------------ Protected methods ------------------
// */
// protected AtomFeed toAtomFeed(final InputStream input) {
// try {
// return atomDeserializer.feed(toDOM(input));
// } catch (Exception e) {
// throw new IllegalArgumentException("While deserializing Atom feed", e);
// }
// }
//
// protected AtomEntry toAtomEntry(final InputStream input) {
// try {
// return atomDeserializer.entry(toDOM(input));
// } catch (Exception e) {
// throw new IllegalArgumentException("While deserializing Atom entry", e);
// }
// }
//
// protected JSONFeed toJSONFeed(final InputStream input) {
// try {
// return getObjectMapper().readValue(input, JSONFeed.class);
// } catch (IOException e) {
// throw new IllegalArgumentException("While deserializing JSON feed", e);
// }
// }
//
// protected abstract AbstractJSONEntry toJSONEntry(final InputStream input);
//
// protected Element toPropertyDOMFromXML(final InputStream input) {
// return toDOM(input);
// }
//
// protected Element toPropertyDOMFromJSON(final InputStream input) {
// try {
// return getObjectMapper().readValue(input, JSONProperty.class).getContent();
// } catch (IOException e) {
// throw new IllegalArgumentException("While deserializing JSON property", e);
// }
// }
//
// protected XMLLinkCollection toLinkCollectionFromXML(final InputStream input) {
// final Element root = toDOM(input);
//
// final NodeList uris = root.getOwnerDocument().getElementsByTagName(ODataConstants.ELEM_URI);
//
// final List<URI> links = new ArrayList<URI>();
// for (int i = 0; i < uris.getLength(); i++) {
// links.add(URI.create(uris.item(i).getTextContent()));
// }
//
// final NodeList next = root.getElementsByTagName(ODataConstants.NEXT_LINK_REL);
// final XMLLinkCollection linkCollection = next.getLength() > 0
// ? new XMLLinkCollection(URI.create(next.item(0).getTextContent()))
// : new XMLLinkCollection();
// linkCollection.setLinks(links);
//
// return linkCollection;
// }
//
// protected JSONLinkCollection toLinkCollectionFromJSON(final InputStream input) {
// try {
// return getObjectMapper().readValue(input, JSONLinkCollection.class);
// } catch (IOException e) {
// throw new IllegalArgumentException("While deserializing JSON $links", e);
// }
// }
//
// protected XMLODataError toODataErrorFromXML(final InputStream input) {
// try {
// final XmlMapper xmlMapper = new XmlMapper(
// new XmlFactory(new InputFactoryImpl(), new OutputFactoryImpl()), new JacksonXmlModule());
// return xmlMapper.readValue(input, XMLODataError.class);
// } catch (Exception e) {
// throw new IllegalArgumentException("While deserializing XML error", e);
// }
// }
//
// protected JSONODataError toODataErrorFromJSON(final InputStream input) {
// try {
// return getObjectMapper().readValue(input, JSONODataErrorBundle.class).getError();
// } catch (IOException e) {
// throw new IllegalArgumentException("While deserializing JSON error", e);
// }
// }
/*
* ------------------ Protected methods ------------------
*/
protected Feed toAtomFeed(final InputStream input) {
try {
return atomDeserializer.feed(toDOM(input));
} catch (Exception e) {
throw new IllegalArgumentException("While deserializing Atom feed", e);
}
}
protected Entry toAtomEntry(final InputStream input) {
try {
return atomDeserializer.entry(toDOM(input));
} catch (Exception e) {
throw new IllegalArgumentException("While deserializing Atom entry", e);
}
}
protected Feed toJSONFeed(final InputStream input) {
try {
return getObjectMapper().readValue(input, JSONFeedImpl.class);
} catch (IOException e) {
throw new IllegalArgumentException("While deserializing JSON feed", e);
}
}
protected Entry toJSONEntry(final InputStream input) {
try {
return getObjectMapper().readValue(input, JSONEntryImpl.class);
} catch (IOException e) {
throw new IllegalArgumentException("While deserializing JSON entry", e);
}
}
protected Element toPropertyDOMFromXML(final InputStream input) {
return toDOM(input);
}
protected Element toPropertyDOMFromJSON(final InputStream input) {
try {
return getObjectMapper().readValue(input, JSONPropertyImpl.class).getContent();
} catch (IOException e) {
throw new IllegalArgumentException("While deserializing JSON property", e);
}
}
protected XMLLinkCollectionImpl toLinkCollectionFromXML(final InputStream input) {
final Element root = toDOM(input);
final NodeList uris = root.getOwnerDocument().getElementsByTagName(ODataConstants.ELEM_URI);
final NodeList next = root.getElementsByTagName(ODataConstants.NEXT_LINK_REL);
final XMLLinkCollectionImpl linkCollection = next.getLength() > 0
? new XMLLinkCollectionImpl(URI.create(next.item(0).getTextContent()))
: new XMLLinkCollectionImpl();
for (int i = 0; i < uris.getLength(); i++) {
linkCollection.getLinks().add(URI.create(uris.item(i).getTextContent()));
}
return linkCollection;
}
protected JSONLinkCollectionImpl toLinkCollectionFromJSON(final InputStream input) {
try {
return getObjectMapper().readValue(input, JSONLinkCollectionImpl.class);
} catch (IOException e) {
throw new IllegalArgumentException("While deserializing JSON $links", e);
}
}
protected Error toErrorFromXML(final InputStream input) {
try {
final XmlMapper xmlMapper = new XmlMapper(
new XmlFactory(new InputFactoryImpl(), new OutputFactoryImpl()), new JacksonXmlModule());
return xmlMapper.readValue(input, XMLErrorImpl.class);
} catch (Exception e) {
throw new IllegalArgumentException("While deserializing XML error", e);
}
}
protected Error toErrorFromJSON(final InputStream input) {
try {
return getObjectMapper().readValue(input, JSONErrorBundle.class).getError();
} catch (IOException e) {
throw new IllegalArgumentException("While deserializing JSON error", e);
}
}
}

View File

@ -18,10 +18,30 @@
*/
package org.apache.olingo.client.core.op.impl;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.olingo.client.api.ODataClient;
import org.apache.olingo.client.api.ODataConstants;
import org.apache.olingo.client.api.data.Error;
import org.apache.olingo.client.api.domain.ODataEntity;
import org.apache.olingo.client.api.domain.ODataEntitySet;
import org.apache.olingo.client.api.domain.ODataJClientEdmPrimitiveType;
import org.apache.olingo.client.api.domain.ODataLinkCollection;
import org.apache.olingo.client.api.domain.ODataProperty;
import org.apache.olingo.client.api.domain.ODataServiceDocument;
import org.apache.olingo.client.api.domain.ODataValue;
import org.apache.olingo.client.api.edm.xml.XMLMetadata;
import org.apache.olingo.client.api.format.ODataFormat;
import org.apache.olingo.client.api.format.ODataPubFormat;
import org.apache.olingo.client.api.format.ODataValueFormat;
import org.apache.olingo.client.api.op.ODataReader;
import org.apache.olingo.client.core.data.ODataEntitySetIterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public abstract class AbstractODataReader implements ODataReader {
@ -38,101 +58,99 @@ public abstract class AbstractODataReader implements ODataReader {
this.client = client;
}
// @Override
// public ODataEntitySet readEntitySet(final InputStream input, final ODataPubFormat format) {
// return client.getBinder().getODataEntitySet(
// client.getDeserializer().toFeed(input, ResourceFactory.feedClassForFormat(format)));
// }
//
// @Override
// public ODataEntity readEntity(final InputStream input, final ODataPubFormat format) {
// return client.getBinder().getODataEntity(
// client.getDeserializer().toEntry(input, ResourceFactory.entryClassForFormat(format)));
// }
//
// @Override
// public ODataProperty readProperty(final InputStream input, final ODataFormat format) {
// final Element property = client.getDeserializer().toPropertyDOM(input, format);
//
// // The ODataProperty object is used either for actual entity properties and for invoke result
// // (when return type is neither an entity nor a collection of entities).
// // Such formats are mostly the same except for collections: an entity property looks like
// // <aproperty m:type="Collection(AType)">
// // <element>....</element>
// // </aproperty>
// //
// // while an invoke result with returnType="Collection(AnotherType)" looks like
// // <functionImportName>
// // <element m:type="AnotherType">...</element>
// // <functionImportName>
// //
// // The code below is meant for "normalizing" the latter into
// // <functionImportName m:type="Collection(AnotherType)">
// // <element m:type="AnotherType">...</element>
// // <functionImportName>
// final String type = property.getAttribute(ODataConstants.ATTR_M_TYPE);
// final NodeList elements = property.getElementsByTagName(ODataConstants.ELEM_ELEMENT);
// if (StringUtils.isBlank(type) && elements != null && elements.getLength() > 0) {
// final Node elementType = elements.item(0).getAttributes().getNamedItem(ODataConstants.ATTR_M_TYPE);
// if (elementType != null) {
// property.setAttribute(ODataConstants.ATTR_M_TYPE, "Collection(" + elementType.getTextContent() + ")");
// }
// }
//
// return client.getBinder().getProperty(property);
// }
//
// @Override
// public ODataLinkCollection readLinks(final InputStream input, final ODataFormat format) {
// return client.getBinder().getLinkCollection(
// client.getDeserializer().toLinkCollection(input, format));
// }
//
// @Override
// public ODataError readError(final InputStream inputStream, final boolean isXML) {
// return client.getDeserializer().toODataError(inputStream, isXML);
// }
//
// @Override
// @SuppressWarnings("unchecked")
// public <T> T read(final InputStream src, final String format, final Class<T> reference) {
// Object res;
//
// try {
// if (ODataEntitySetIterator.class.isAssignableFrom(reference)) {
// res = new ODataEntitySetIterator(client, src, ODataPubFormat.fromString(format));
// } else if (ODataEntitySet.class.isAssignableFrom(reference)) {
// res = readEntitySet(src, ODataPubFormat.fromString(format));
// } else if (ODataEntity.class.isAssignableFrom(reference)) {
// res = readEntity(src, ODataPubFormat.fromString(format));
// } else if (ODataProperty.class.isAssignableFrom(reference)) {
// res = readProperty(src, ODataFormat.fromString(format));
// } else if (ODataLinkCollection.class.isAssignableFrom(reference)) {
// res = readLinks(src, ODataFormat.fromString(format));
// } else if (ODataValue.class.isAssignableFrom(reference)) {
// res = client.getPrimitiveValueBuilder().
// setType(ODataValueFormat.fromString(format) == ODataValueFormat.TEXT
// ? EdmSimpleType.String : EdmSimpleType.Stream).
// setText(IOUtils.toString(src)).
// build();
// } else if (AbstractEdmMetadata.class.isAssignableFrom(reference)) {
// res = readMetadata(src);
// } else if (ODataServiceDocument.class.isAssignableFrom(reference)) {
// res = readServiceDocument(src, ODataFormat.fromString(format));
// } else if (ODataError.class.isAssignableFrom(reference)) {
// res = readError(src, !format.toString().contains("json"));
// } else {
// throw new IllegalArgumentException("Invalid reference type " + reference);
// }
// } catch (Exception e) {
// LOG.warn("Cast error", e);
// res = null;
// } finally {
// if (!ODataEntitySetIterator.class.isAssignableFrom(reference)) {
// IOUtils.closeQuietly(src);
// }
// }
//
// return (T) res;
// }
@Override
public ODataEntitySet readEntitySet(final InputStream input, final ODataPubFormat format) {
return client.getBinder().getODataEntitySet(client.getDeserializer().toFeed(input, format));
}
@Override
public ODataEntity readEntity(final InputStream input, final ODataPubFormat format) {
return client.getBinder().getODataEntity(client.getDeserializer().toEntry(input, format));
}
@Override
public ODataProperty readProperty(final InputStream input, final ODataFormat format) {
final Element property = client.getDeserializer().toPropertyDOM(input, format);
// The ODataProperty object is used either for actual entity properties and for invoke result
// (when return type is neither an entity nor a collection of entities).
// Such formats are mostly the same except for collections: an entity property looks like
// <aproperty m:type="Collection(AType)">
// <element>....</element>
// </aproperty>
//
// while an invoke result with returnType="Collection(AnotherType)" looks like
// <functionImportName>
// <element m:type="AnotherType">...</element>
// <functionImportName>
//
// The code below is meant for "normalizing" the latter into
// <functionImportName m:type="Collection(AnotherType)">
// <element m:type="AnotherType">...</element>
// <functionImportName>
final String type = property.getAttribute(ODataConstants.ATTR_M_TYPE);
final NodeList elements = property.getElementsByTagName(ODataConstants.ELEM_ELEMENT);
if (StringUtils.isBlank(type) && elements != null && elements.getLength() > 0) {
final Node elementType = elements.item(0).getAttributes().getNamedItem(ODataConstants.ATTR_M_TYPE);
if (elementType != null) {
property.setAttribute(ODataConstants.ATTR_M_TYPE, "Collection(" + elementType.getTextContent() + ")");
}
}
return client.getBinder().getODataProperty(property);
}
@Override
public ODataLinkCollection readLinks(final InputStream input, final ODataFormat format) {
return client.getBinder().getLinkCollection(
client.getDeserializer().toLinkCollection(input, format));
}
@Override
public Error readError(final InputStream inputStream, final boolean isXML) {
return client.getDeserializer().toError(inputStream, isXML);
}
@Override
@SuppressWarnings("unchecked")
public <T> T read(final InputStream src, final String format, final Class<T> reference) {
Object res;
try {
if (ODataEntitySetIterator.class.isAssignableFrom(reference)) {
res = new ODataEntitySetIterator(client, src, ODataPubFormat.fromString(format));
} else if (ODataEntitySet.class.isAssignableFrom(reference)) {
res = readEntitySet(src, ODataPubFormat.fromString(format));
} else if (ODataEntity.class.isAssignableFrom(reference)) {
res = readEntity(src, ODataPubFormat.fromString(format));
} else if (ODataProperty.class.isAssignableFrom(reference)) {
res = readProperty(src, ODataFormat.fromString(format));
} else if (ODataLinkCollection.class.isAssignableFrom(reference)) {
res = readLinks(src, ODataFormat.fromString(format));
} else if (ODataValue.class.isAssignableFrom(reference)) {
res = client.getPrimitiveValueBuilder().
setType(ODataValueFormat.fromString(format) == ODataValueFormat.TEXT
? ODataJClientEdmPrimitiveType.String : ODataJClientEdmPrimitiveType.Stream).
setText(IOUtils.toString(src)).
build();
} else if (XMLMetadata.class.isAssignableFrom(reference)) {
res = readMetadata(src);
} else if (ODataServiceDocument.class.isAssignableFrom(reference)) {
res = readServiceDocument(src, ODataFormat.fromString(format));
} else if (Error.class.isAssignableFrom(reference)) {
res = readError(src, !format.toString().contains("json"));
} else {
throw new IllegalArgumentException("Invalid reference type " + reference);
}
} catch (Exception e) {
LOG.warn("Cast error", e);
res = null;
} finally {
if (!ODataEntitySetIterator.class.isAssignableFrom(reference)) {
IOUtils.closeQuietly(src);
}
}
return (T) res;
}
}

View File

@ -18,81 +18,103 @@
*/
package org.apache.olingo.client.core.op.impl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import javax.xml.parsers.DocumentBuilder;
import org.apache.olingo.client.api.ODataClient;
import org.apache.olingo.client.api.ODataConstants;
import org.apache.olingo.client.api.data.Entry;
import org.apache.olingo.client.api.data.Feed;
import org.apache.olingo.client.api.data.Link;
import org.apache.olingo.client.api.format.ODataFormat;
import org.apache.olingo.client.api.op.ODataSerializer;
import org.apache.olingo.client.api.utils.XMLUtils;
import org.apache.olingo.client.core.data.AbstractPayloadObject;
import org.apache.olingo.client.core.data.AtomEntryImpl;
import org.apache.olingo.client.core.data.AtomFeedImpl;
import org.apache.olingo.client.core.data.AtomSerializer;
import org.apache.olingo.client.core.data.JSONEntryImpl;
import org.apache.olingo.client.core.data.JSONFeedImpl;
import org.apache.olingo.client.core.data.JSONPropertyImpl;
import org.apache.olingo.client.core.xml.XMLParser;
import org.apache.olingo.commons.api.edm.constants.ODataServiceVersion;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public abstract class AbstractODataSerializer extends AbstractJacksonTool implements ODataSerializer {
private static final long serialVersionUID = -357777648541325363L;
// private final AtomSerializer atomSerializer;
private final AtomSerializer atomSerializer;
public AbstractODataSerializer(final ODataClient client) {
super(client);
// this.atomSerializer = new AtomSerializer(client);
this.atomSerializer = new AtomSerializer(client);
}
@Override
public void feed(final Feed obj, final OutputStream out) {
feed(obj, new OutputStreamWriter(out));
}
@Override
public void feed(final Feed obj, final Writer writer) {
if (obj instanceof AtomFeedImpl) {
atom((AtomFeedImpl) obj, writer);
} else {
json((JSONFeedImpl) obj, writer);
}
}
@Override
public void entry(final Entry obj, final OutputStream out) {
entry(obj, new OutputStreamWriter(out));
}
@Override
public void entry(final Entry obj, final Writer writer) {
if (obj instanceof AtomEntryImpl) {
atom((AtomEntryImpl) obj, writer);
} else {
json((JSONEntryImpl) obj, writer);
}
}
@Override
public void property(final Element element, final ODataFormat format, final OutputStream out) {
property(element, format, new OutputStreamWriter(out));
}
@Override
public void property(final Element element, final ODataFormat format, final Writer writer) {
if (format == ODataFormat.XML) {
dom(element, writer);
} else {
json(element, writer);
}
}
@Override
public void link(final Link link, final ODataFormat format, final OutputStream out) {
link(link, format, new OutputStreamWriter(out));
}
@Override
public void link(final Link link, final ODataFormat format, final Writer writer) {
if (format == ODataFormat.XML) {
xmlLink(link, writer);
} else {
jsonLink(link, writer);
}
}
// @Override
// public <T extends Feed> void feed(final T obj, final OutputStream out) {
// feed(obj, new OutputStreamWriter(out));
// }
//
// @Override
// public <T extends Feed> void feed(final T obj, final Writer writer) {
// if (obj instanceof AtomFeed) {
// atom((AtomFeed) obj, writer);
// } else {
// json((JSONFeed) obj, writer);
// }
// }
//
// @Override
// public <T extends Entry> void entry(final T obj, final OutputStream out) {
// entry(obj, new OutputStreamWriter(out));
// }
//
// @Override
// public <T extends Entry> void entry(final T obj, final Writer writer) {
// if (obj instanceof AtomEntry) {
// atom((AtomEntry) obj, writer);
// } else {
// json((JSONEntry) obj, writer);
// }
// }
//
// @Override
// public void property(final Element element, final ODataFormat format, final OutputStream out) {
// property(element, format, new OutputStreamWriter(out));
// }
//
// @Override
// public void property(final Element element, final ODataFormat format, final Writer writer) {
// if (format == ODataFormat.XML) {
// dom(element, writer);
// } else {
// json(element, writer);
// }
// }
//
// @Override
// public void link(final ODataLink link, final ODataFormat format, final OutputStream out) {
// link(link, format, new OutputStreamWriter(out));
// }
//
// @Override
// public void link(final ODataLink link, final ODataFormat format, final Writer writer) {
// if (format == ODataFormat.XML) {
// xmlLink(link, writer);
// } else {
// jsonLink(link, writer);
// }
// }
//
@Override
public void dom(final Node content, final OutputStream out) {
dom(content, new OutputStreamWriter(out));
@ -102,60 +124,60 @@ public abstract class AbstractODataSerializer extends AbstractJacksonTool implem
public void dom(final Node content, final Writer writer) {
XMLParser.PARSER.serialize(content, writer);
}
//
// /*
// * ------------------ Protected methods ------------------
// */
// protected <T extends AbstractPayloadObject> void atom(final T obj, final Writer writer) {
// try {
// dom(atomSerializer.serialize(obj), writer);
// } catch (Exception e) {
// throw new IllegalArgumentException("While serializing Atom object", e);
// }
// }
//
// protected <T extends AbstractPayloadObject> void json(final T obj, final Writer writer) {
// try {
// getObjectMapper().writeValue(writer, obj);
// } catch (IOException e) {
// throw new IllegalArgumentException("While serializing JSON object", e);
// }
// }
//
// protected void json(final Element element, final Writer writer) {
// try {
// final JSONProperty property = new JSONProperty();
// property.setContent(element);
// getObjectMapper().writeValue(writer, property);
// } catch (IOException e) {
// throw new IllegalArgumentException("While serializing JSON property", e);
// }
// }
//
// protected void xmlLink(final ODataLink link, final Writer writer) {
// try {
// final DocumentBuilder builder = XMLUtils.DOC_BUILDER_FACTORY.newDocumentBuilder();
// final Document doc = builder.newDocument();
// final Element uri = doc.createElementNS(
// client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_DATASERVICES),
// ODataConstants.ELEM_URI);
// uri.appendChild(doc.createTextNode(link.getLink().toASCIIString()));
//
// dom(uri, writer);
// } catch (Exception e) {
// throw new IllegalArgumentException("While serializing XML link", e);
// }
// }
//
// protected void jsonLink(final ODataLink link, final Writer writer) {
// final ObjectMapper mapper = getObjectMapper();
// final ObjectNode uri = mapper.createObjectNode();
// uri.put(ODataConstants.JSON_URL, link.getLink().toASCIIString());
//
// try {
// mapper.writeValue(writer, uri);
// } catch (Exception e) {
// throw new IllegalArgumentException("While serializing JSON link", e);
// }
// }
/*
* ------------------ Protected methods ------------------
*/
protected <T extends AbstractPayloadObject> void atom(final T obj, final Writer writer) {
try {
dom(atomSerializer.serialize(obj), writer);
} catch (Exception e) {
throw new IllegalArgumentException("While serializing Atom object", e);
}
}
protected <T extends AbstractPayloadObject> void json(final T obj, final Writer writer) {
try {
getObjectMapper().writeValue(writer, obj);
} catch (IOException e) {
throw new IllegalArgumentException("While serializing JSON object", e);
}
}
protected void json(final Element element, final Writer writer) {
try {
final JSONPropertyImpl property = new JSONPropertyImpl();
property.setContent(element);
getObjectMapper().writeValue(writer, property);
} catch (IOException e) {
throw new IllegalArgumentException("While serializing JSON property", e);
}
}
protected void xmlLink(final Link link, final Writer writer) {
try {
final DocumentBuilder builder = XMLUtils.DOC_BUILDER_FACTORY.newDocumentBuilder();
final Document doc = builder.newDocument();
final Element uri = doc.createElementNS(
client.getServiceVersion().getNamespaceMap().get(ODataServiceVersion.NS_DATASERVICES),
ODataConstants.ELEM_URI);
uri.appendChild(doc.createTextNode(link.getHref()));
dom(uri, writer);
} catch (Exception e) {
throw new IllegalArgumentException("While serializing XML link", e);
}
}
protected void jsonLink(final Link link, final Writer writer) {
final ObjectMapper mapper = getObjectMapper();
final ObjectNode uri = mapper.createObjectNode();
uri.put(ODataConstants.JSON_URL, link.getHref());
try {
mapper.writeValue(writer, uri);
} catch (Exception e) {
throw new IllegalArgumentException("While serializing JSON link", e);
}
}
}

View File

@ -0,0 +1,287 @@
/*
* 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.olingo.client.core.op.impl;
import java.net.URI;
import org.apache.olingo.client.api.ODataClient;
import org.apache.olingo.client.api.data.LinkType;
import org.apache.olingo.client.api.domain.ODataCollectionValue;
import org.apache.olingo.client.api.domain.ODataComplexValue;
import org.apache.olingo.client.api.domain.ODataEntity;
import org.apache.olingo.client.api.domain.ODataEntitySet;
import org.apache.olingo.client.api.domain.ODataInlineEntity;
import org.apache.olingo.client.api.domain.ODataInlineEntitySet;
import org.apache.olingo.client.api.domain.ODataLink;
import org.apache.olingo.client.api.domain.ODataObjectFactory;
import org.apache.olingo.client.api.domain.ODataPrimitiveValue;
import org.apache.olingo.client.api.domain.ODataProperty;
public class ODataObjectFactoryImpl implements ODataObjectFactory {
private static final long serialVersionUID = -3769695665946919447L;
protected final ODataClient client;
public ODataObjectFactoryImpl(final ODataClient client) {
this.client = client;
}
/**
* Instantiates a new entity set.
*
* @return entity set.
*/
@Override
public ODataEntitySet newEntitySet() {
return new ODataEntitySet();
}
/**
* Instantiates a new entity set.
*
* @param next next link.
* @return entity set.
*/
@Override
public ODataEntitySet newEntitySet(final URI next) {
return new ODataEntitySet(next);
}
/**
* Instantiates a new entity.
*
* @param name OData entity name.
* @return entity.
*/
@Override
public ODataEntity newEntity(final String name) {
return new ODataEntity(name);
}
/**
* Instantiates a new entity.
*
* @param name OData entity name.
* @param link self link.
* @return entity.
*/
@Override
public ODataEntity newEntity(final String name, final URI link) {
final ODataEntity result = new ODataEntity(name);
result.setLink(link);
return result;
}
/**
* Instantiates a new in-line entity set.
*
* @param name name.
* @param link edit link.
* @param entitySet entity set.
* @return in-line entity set.
*/
@Override
public ODataInlineEntitySet newInlineEntitySet(final String name, final URI link,
final ODataEntitySet entitySet) {
return new ODataInlineEntitySet(client, link, LinkType.ENTITY_SET_NAVIGATION, name, entitySet);
}
/**
* Instantiates a new in-line entity set.
*
* @param name name.
* @param baseURI base URI.
* @param href href.
* @param entitySet entity set.
* @return in-line entity set.
*/
@Override
public ODataInlineEntitySet newInlineEntitySet(final String name, final URI baseURI, final String href,
final ODataEntitySet entitySet) {
return new ODataInlineEntitySet(client, baseURI, href, LinkType.ENTITY_SET_NAVIGATION, name, entitySet);
}
/**
* Instantiates a new in-line entity.
*
* @param name name.
* @param link edit link.
* @param entity entity.
* @return in-line entity.
*/
@Override
public ODataInlineEntity newInlineEntity(final String name, final URI link, final ODataEntity entity) {
return new ODataInlineEntity(client, link, LinkType.ENTITY_NAVIGATION, name, entity);
}
/**
* Instantiates a new in-line entity.
*
* @param name name.
* @param baseURI base URI.
* @param href href.
* @param entity entity.
* @return in-line entity.
*/
@Override
public ODataInlineEntity newInlineEntity(final String name, final URI baseURI, final String href,
final ODataEntity entity) {
return new ODataInlineEntity(client, baseURI, href, LinkType.ENTITY_NAVIGATION, name, entity);
}
/**
* Instantiates a new entity navigation link.
*
* @param name name.
* @param link link.
* @return entity navigation link.
*/
@Override
public ODataLink newEntityNavigationLink(final String name, final URI link) {
return new ODataLink(client, link, LinkType.ENTITY_NAVIGATION, name);
}
/**
* Instantiates a new entity navigation link.
*
* @param name name.
* @param baseURI base URI.
* @param href href.
* @return entity navigation link.
*/
@Override
public ODataLink newEntityNavigationLink(final String name, final URI baseURI, final String href) {
return new ODataLink(client, baseURI, href, LinkType.ENTITY_NAVIGATION, name);
}
/**
* Instantiates a new entity set navigation link.
*
* @param name name.
* @param link link.
* @return entity set navigation link.
*/
@Override
public ODataLink newFeedNavigationLink(final String name, final URI link) {
return new ODataLink(client, link, LinkType.ENTITY_SET_NAVIGATION, name);
}
/**
* Instantiates a new entity set navigation link.
*
* @param name name.
* @param baseURI base URI.
* @param href href.
* @return entity set navigation link.
*/
@Override
public ODataLink newFeedNavigationLink(final String name, final URI baseURI, final String href) {
return new ODataLink(client, baseURI, href, LinkType.ENTITY_SET_NAVIGATION, name);
}
/**
* Instantiates a new association link.
*
* @param name name.
* @param link link.
* @return association link.
*/
@Override
public ODataLink newAssociationLink(final String name, final URI link) {
return new ODataLink(client, link, LinkType.ASSOCIATION, name);
}
/**
* Instantiates a new association link.
*
* @param name name.
* @param baseURI base URI.
* @param href href.
* @return association link.
*/
@Override
public ODataLink newAssociationLink(final String name, final URI baseURI, final String href) {
return new ODataLink(client, baseURI, href, LinkType.ASSOCIATION, name);
}
/**
* Instantiates a new media-edit link.
*
* @param name name.
* @param link link.
* @return media-edit link.
*/
@Override
public ODataLink newMediaEditLink(final String name, final URI link) {
return new ODataLink(client, link, LinkType.MEDIA_EDIT, name);
}
/**
* Instantiates a new media-edit link.
*
* @param name name.
* @param baseURI base URI.
* @param href href.
* @return media-edit link.
*/
@Override
public ODataLink newMediaEditLink(final String name, final URI baseURI, final String href) {
return new ODataLink(client, baseURI, href, LinkType.MEDIA_EDIT, name);
}
/**
* Instantiates a new primitive property.
*
* @param name name.
* @param value value.
* @return primitive property.
*/
@Override
public ODataProperty newPrimitiveProperty(final String name, final ODataPrimitiveValue value) {
return new ODataProperty(name, value);
}
/**
* Instantiates a new complex property.
*
* @param name name.
* @param value value.
* @return complex property.
*/
@Override
public ODataProperty newComplexProperty(final String name, final ODataComplexValue value) {
return new ODataProperty(name, value);
}
/**
* Instantiates a new collection property.
*
* @param name name.
* @param value value.
* @return collection property.
*/
@Override
public ODataProperty newCollectionProperty(final String name, final ODataCollectionValue value) {
return new ODataProperty(name, value);
}
}

View File

@ -19,19 +19,17 @@
package org.apache.olingo.client.core.op.impl;
import org.apache.olingo.client.core.ODataV3ClientImpl;
import org.apache.olingo.client.core.op.impl.AbstractODataBinder;
public class ODataV3BinderImpl extends AbstractODataBinder {
private static final long serialVersionUID = 8970843539708952308L;
private static final long serialVersionUID = 8970843539708952308L;
public ODataV3BinderImpl(final ODataV3ClientImpl client) {
super(client);
}
public ODataV3BinderImpl(final ODataV3ClientImpl client) {
super(client);
}
// @Override
// protected EdmType newEdmType(final String expression) {
// return new EdmV3Type(expression);
// }
}

View File

@ -29,7 +29,6 @@ import org.apache.olingo.client.core.data.v3.JSONServiceDocumentImpl;
import org.apache.olingo.client.core.data.v4.XMLServiceDocumentImpl;
import org.apache.olingo.client.core.edm.xml.v3.EdmxImpl;
import org.apache.olingo.client.core.edm.xml.v3.XMLMetadataImpl;
import org.apache.olingo.client.core.op.impl.AbstractODataDeserializer;
public class ODataV3DeserializerImpl extends AbstractODataDeserializer implements ODataV3Deserializer {
@ -59,12 +58,4 @@ public class ODataV3DeserializerImpl extends AbstractODataDeserializer implement
}
}
// @Override
// protected JSONEntry toJSONEntry(final InputStream input) {
// try {
// return getObjectMapper().readValue(input, JSONEntry.class);
// } catch (IOException e) {
// throw new IllegalArgumentException("While deserializing JSON entry", e);
// }
// }
}

View File

@ -24,7 +24,6 @@ import org.apache.olingo.client.api.domain.ODataServiceDocument;
import org.apache.olingo.client.api.format.ODataFormat;
import org.apache.olingo.client.core.ODataV3ClientImpl;
import org.apache.olingo.client.core.edm.EdmClientImpl;
import org.apache.olingo.client.core.op.impl.AbstractODataReader;
import org.apache.olingo.commons.api.edm.Edm;
public class ODataV3ReaderImpl extends AbstractODataReader {

View File

@ -19,7 +19,6 @@
package org.apache.olingo.client.core.op.impl;
import org.apache.olingo.client.api.ODataClient;
import org.apache.olingo.client.core.op.impl.AbstractODataSerializer;
public class ODataV3SerializerImpl extends AbstractODataSerializer {

View File

@ -22,8 +22,7 @@ import org.apache.olingo.client.api.data.ServiceDocument;
import org.apache.olingo.client.api.data.ServiceDocumentItem;
import org.apache.olingo.client.api.domain.ODataServiceDocument;
import org.apache.olingo.client.core.ODataV4ClientImpl;
import org.apache.olingo.client.core.op.impl.AbstractODataBinder;
import org.apache.olingo.client.core.uri.URIUtils;
import org.apache.olingo.client.api.utils.URIUtils;
public class ODataV4BinderImpl extends AbstractODataBinder {

View File

@ -30,7 +30,6 @@ import org.apache.olingo.client.core.data.v4.JSONServiceDocumentImpl;
import org.apache.olingo.client.core.data.v4.XMLServiceDocumentImpl;
import org.apache.olingo.client.core.edm.xml.v4.EdmxImpl;
import org.apache.olingo.client.core.edm.xml.v4.XMLMetadataImpl;
import org.apache.olingo.client.core.op.impl.AbstractODataDeserializer;
public class ODataV4DeserializerImpl extends AbstractODataDeserializer implements ODataV4Deserializer {
@ -59,13 +58,4 @@ public class ODataV4DeserializerImpl extends AbstractODataDeserializer implement
throw new IllegalArgumentException("Could not parse Service Document", e);
}
}
// @Override
// protected JSONEntry toJSONEntry(final InputStream input) {
// try {
// return getObjectMapper().readValue(input, JSONEntry.class);
// } catch (IOException e) {
// throw new IllegalArgumentException("While deserializing JSON entry", e);
// }
// }
}

View File

@ -24,7 +24,6 @@ import org.apache.olingo.client.api.domain.ODataServiceDocument;
import org.apache.olingo.client.api.format.ODataFormat;
import org.apache.olingo.client.core.ODataV4ClientImpl;
import org.apache.olingo.client.core.edm.EdmClientImpl;
import org.apache.olingo.client.core.op.impl.AbstractODataReader;
import org.apache.olingo.commons.api.edm.Edm;
public class ODataV4ReaderImpl extends AbstractODataReader {

View File

@ -19,7 +19,6 @@
package org.apache.olingo.client.core.op.impl;
import org.apache.olingo.client.api.ODataClient;
import org.apache.olingo.client.core.op.impl.AbstractODataSerializer;
public class ODataV4SerializerImpl extends AbstractODataSerializer {

View File

@ -0,0 +1,100 @@
/*
* 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.olingo.client.core.op.impl;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Collection;
import java.util.Collections;
import org.apache.commons.io.IOUtils;
import org.apache.olingo.client.api.ODataClient;
import org.apache.olingo.client.api.domain.ODataEntity;
import org.apache.olingo.client.api.domain.ODataLink;
import org.apache.olingo.client.api.domain.ODataProperty;
import org.apache.olingo.client.api.format.ODataFormat;
import org.apache.olingo.client.api.format.ODataPubFormat;
import org.apache.olingo.client.api.op.ODataWriter;
public class ODataWriterImpl implements ODataWriter {
private static final long serialVersionUID = 3265794768412314485L;
protected final ODataClient client;
public ODataWriterImpl(final ODataClient client) {
this.client = client;
}
@Override
public InputStream writeEntities(final Collection<ODataEntity> entities, final ODataPubFormat format) {
return writeEntities(entities, format, true);
}
@Override
public InputStream writeEntities(
final Collection<ODataEntity> entities, final ODataPubFormat format, final boolean outputType) {
final ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
for (ODataEntity entity : entities) {
client.getSerializer().entry(client.getBinder().getEntry(
entity, ResourceFactory.entryClassForFormat(format == ODataPubFormat.ATOM), outputType), output);
}
return new ByteArrayInputStream(output.toByteArray());
} finally {
IOUtils.closeQuietly(output);
}
}
@Override
public InputStream writeEntity(final ODataEntity entity, final ODataPubFormat format) {
return writeEntity(entity, format, true);
}
@Override
public InputStream writeEntity(final ODataEntity entity, final ODataPubFormat format, final boolean outputType) {
return writeEntities(Collections.<ODataEntity>singleton(entity), format, outputType);
}
@Override
public InputStream writeProperty(final ODataProperty property, final ODataFormat format) {
final ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
client.getSerializer().property(client.getBinder().toDOMElement(property), format, output);
return new ByteArrayInputStream(output.toByteArray());
} finally {
IOUtils.closeQuietly(output);
}
}
@Override
public InputStream writeLink(final ODataLink link, final ODataFormat format) {
final ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
client.getSerializer().link(client.getBinder().getLink(link, format == ODataFormat.XML), format, output);
return new ByteArrayInputStream(output.toByteArray());
} finally {
IOUtils.closeQuietly(output);
}
}
}

View File

@ -0,0 +1,111 @@
/*
* 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.olingo.client.core.op.impl;
import org.apache.olingo.client.api.data.Entry;
import org.apache.olingo.client.api.data.Feed;
import org.apache.olingo.client.api.format.ODataPubFormat;
import org.apache.olingo.client.core.data.AtomEntryImpl;
import org.apache.olingo.client.core.data.AtomFeedImpl;
import org.apache.olingo.client.core.data.JSONEntryImpl;
import org.apache.olingo.client.core.data.JSONFeedImpl;
public class ResourceFactory {
/**
* Gets a new instance of <tt>Feed</tt>.
*
* @param resourceClass reference class.
* @return <tt>Feed</tt> object.
*/
public static Feed newFeed(final Class<? extends Feed> resourceClass) {
Feed result = null;
if (AtomFeedImpl.class.equals(resourceClass)) {
result = new AtomFeedImpl();
}
if (JSONFeedImpl.class.equals(resourceClass)) {
result = new JSONFeedImpl();
}
return result;
}
/**
* Gets a new instance of <tt>Entry</tt>.
*
* @param resourceClass reference class.
* @return <tt>Entry</tt> object.
*/
public static Entry newEntry(final Class<? extends Entry> resourceClass) {
Entry result = null;
if (AtomEntryImpl.class.equals(resourceClass)) {
result = new AtomEntryImpl();
}
if (JSONEntryImpl.class.equals(resourceClass)) {
result = new JSONEntryImpl();
}
return result;
}
/**
* Gets feed reference class from the given format.
*
* @param isXML whether it is JSON or XML / Atom
* @return resource reference class.
*/
public static Class<? extends Feed> feedClassForFormat(final boolean isXML) {
return isXML ? AtomFeedImpl.class : JSONFeedImpl.class;
}
/**
* Gets entry reference class from the given format.
*
* @param isXML whether it is JSON or XML / Atom
* @return resource reference class.
*/
public static Class<? extends Entry> entryClassForFormat(final boolean isXML) {
return isXML ? AtomEntryImpl.class : JSONEntryImpl.class;
}
/**
* Gets <tt>Entry</tt> object from feed resource.
*
* @param resourceClass feed reference class.
* @return <tt>Entry</tt> object.
*/
public static Class<? extends Entry> entryClassForFeed(final Class<? extends Feed> resourceClass) {
Class<? extends Entry> result = null;
if (AtomFeedImpl.class.equals(resourceClass)) {
result = AtomEntryImpl.class;
}
if (JSONFeedImpl.class.equals(resourceClass)) {
result = JSONEntryImpl.class;
}
return result;
}
public static ODataPubFormat formatForEntryClass(final Class<? extends Entry> reference) {
return reference.equals(AtomEntryImpl.class) ? ODataPubFormat.JSON : ODataPubFormat.ATOM;
}
}

View File

@ -18,6 +18,7 @@
*/
package org.apache.olingo.client.core.uri;
import org.apache.olingo.client.api.utils.URIUtils;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;

View File

@ -18,6 +18,7 @@
*/
package org.apache.olingo.client.core.uri;
import org.apache.olingo.client.api.utils.URIUtils;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;

View File

@ -19,12 +19,11 @@
package org.apache.olingo.client.core.uri.filter;
import org.apache.olingo.client.api.uri.filter.FilterArg;
import org.apache.olingo.client.api.uri.filter.FilterArgFactory;
/**
* Filter property path; obtain instances via <tt>FilterArgFactory</tt>.
*
* @see FilterArgFactory
* @see org.apache.olingo.client.api.uri.filter.FilterArgFactory
*/
public class FilterConst implements FilterArg {

View File

@ -19,7 +19,7 @@
package org.apache.olingo.client.core.uri.filter;
import org.apache.olingo.client.api.uri.filter.FilterArg;
import org.apache.olingo.client.core.uri.URIUtils;
import org.apache.olingo.client.api.utils.URIUtils;
/**
* Filter value literals; obtain instances via <tt>FilterArgFactory</tt>.

Some files were not shown because too many files have changed in this diff Show More