You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@olingo.apache.org by fm...@apache.org on 2013/07/26 13:22:27 UTC
[22/51] [partial] initial commit
http://git-wip-us.apache.org/repos/asf/incubator-olingo-odata2/blob/ff2b0a0e/odata-core/src/main/java/org/apache/olingo/odata2/core/debug/DebugInfoRequest.java
----------------------------------------------------------------------
diff --git a/odata-core/src/main/java/org/apache/olingo/odata2/core/debug/DebugInfoRequest.java b/odata-core/src/main/java/org/apache/olingo/odata2/core/debug/DebugInfoRequest.java
new file mode 100644
index 0000000..3f7d0e2
--- /dev/null
+++ b/odata-core/src/main/java/org/apache/olingo/odata2/core/debug/DebugInfoRequest.java
@@ -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.odata2.core.debug;
+
+import java.io.IOException;
+import java.net.URI;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.olingo.odata2.core.ep.util.JsonStreamWriter;
+
+/**
+ * @author SAP AG
+ */
+public class DebugInfoRequest implements DebugInfo {
+
+ private final String method;
+ private final URI uri;
+ private final Map<String, List<String>> headers;
+
+ public DebugInfoRequest(final String method, final URI uri, final Map<String, List<String>> headers) {
+ this.method = method;
+ this.uri = uri;
+ this.headers = headers;
+ }
+
+ @Override
+ public String getName() {
+ return "Request";
+ }
+
+ @Override
+ public void appendJson(final JsonStreamWriter jsonStreamWriter) throws IOException {
+ jsonStreamWriter.beginObject()
+ .namedStringValueRaw("method", method).separator()
+ .namedStringValue("uri", uri.toString());
+
+ if (!headers.isEmpty()) {
+ jsonStreamWriter.separator()
+ .name("headers")
+ .beginObject();
+ boolean first = true;
+ for (final String name : headers.keySet()) {
+ for (final String value : headers.get(name)) {
+ if (!first) {
+ jsonStreamWriter.separator();
+ }
+ first = false;
+ jsonStreamWriter.namedStringValue(name, value);
+ }
+ }
+ jsonStreamWriter.endObject();
+ }
+
+ jsonStreamWriter.endObject();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-olingo-odata2/blob/ff2b0a0e/odata-core/src/main/java/org/apache/olingo/odata2/core/debug/DebugInfoResponse.java
----------------------------------------------------------------------
diff --git a/odata-core/src/main/java/org/apache/olingo/odata2/core/debug/DebugInfoResponse.java b/odata-core/src/main/java/org/apache/olingo/odata2/core/debug/DebugInfoResponse.java
new file mode 100644
index 0000000..9407710
--- /dev/null
+++ b/odata-core/src/main/java/org/apache/olingo/odata2/core/debug/DebugInfoResponse.java
@@ -0,0 +1,77 @@
+/*******************************************************************************
+ * 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.odata2.core.debug;
+
+import java.io.IOException;
+import java.util.Map;
+
+import org.apache.olingo.odata2.api.commons.HttpStatusCodes;
+import org.apache.olingo.odata2.core.ep.util.JsonStreamWriter;
+
+/**
+ * @author SAP AG
+ */
+public class DebugInfoResponse implements DebugInfo {
+
+ private final HttpStatusCodes status;
+ private final Map<String, String> headers;
+
+ public DebugInfoResponse(final HttpStatusCodes status, final Map<String, String> headers) {
+ this.status = status;
+ this.headers = headers;
+ }
+
+ @Override
+ public String getName() {
+ return "Response";
+ }
+
+ @Override
+ public void appendJson(final JsonStreamWriter jsonStreamWriter) throws IOException {
+ jsonStreamWriter.beginObject();
+
+ if (status != null) {
+ jsonStreamWriter.name("status")
+ .beginObject()
+ .name("code").unquotedValue(Integer.toString(status.getStatusCode())).separator()
+ .namedStringValueRaw("info", status.getInfo())
+ .endObject();
+ }
+
+ if (!headers.isEmpty()) {
+ if (status != null) {
+ jsonStreamWriter.separator();
+ }
+
+ jsonStreamWriter.name("headers")
+ .beginObject();
+ boolean first = true;
+ for (final String name : headers.keySet()) {
+ if (!first) {
+ jsonStreamWriter.separator();
+ }
+ first = false;
+ jsonStreamWriter.namedStringValue(name, headers.get(name));
+ }
+ jsonStreamWriter.endObject();
+ }
+
+ jsonStreamWriter.endObject();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-olingo-odata2/blob/ff2b0a0e/odata-core/src/main/java/org/apache/olingo/odata2/core/debug/DebugInfoRuntime.java
----------------------------------------------------------------------
diff --git a/odata-core/src/main/java/org/apache/olingo/odata2/core/debug/DebugInfoRuntime.java b/odata-core/src/main/java/org/apache/olingo/odata2/core/debug/DebugInfoRuntime.java
new file mode 100644
index 0000000..543ef7c
--- /dev/null
+++ b/odata-core/src/main/java/org/apache/olingo/odata2/core/debug/DebugInfoRuntime.java
@@ -0,0 +1,153 @@
+/*******************************************************************************
+ * 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.odata2.core.debug;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import org.apache.olingo.odata2.api.processor.ODataContext.RuntimeMeasurement;
+import org.apache.olingo.odata2.core.ep.util.JsonStreamWriter;
+
+/**
+ * @author SAP AG
+ */
+public class DebugInfoRuntime implements DebugInfo {
+
+ private class RuntimeNode {
+ protected String className;
+ protected String methodName;
+ protected long timeStarted;
+ protected long timeStopped;
+ protected List<RuntimeNode> children = new ArrayList<RuntimeNode>();
+ public long memoryStarted;
+ public long memoryStopped;
+
+ protected RuntimeNode() {
+ timeStarted = 0;
+ timeStopped = Long.MAX_VALUE;
+ memoryStarted = 0;
+ memoryStopped = 0;
+ }
+
+ private RuntimeNode(final RuntimeMeasurement runtimeMeasurement) {
+ className = runtimeMeasurement.getClassName();
+ methodName = runtimeMeasurement.getMethodName();
+ timeStarted = runtimeMeasurement.getTimeStarted();
+ timeStopped = runtimeMeasurement.getTimeStopped();
+ memoryStarted = runtimeMeasurement.getMemoryStarted();
+ memoryStopped = runtimeMeasurement.getMemoryStopped();
+ }
+
+ protected boolean add(final RuntimeMeasurement runtimeMeasurement) {
+ if (timeStarted <= runtimeMeasurement.getTimeStarted()
+ && timeStopped != 0 && timeStopped >= runtimeMeasurement.getTimeStopped()) {
+ for (RuntimeNode candidate : children) {
+ if (candidate.add(runtimeMeasurement)) {
+ return true;
+ }
+ }
+ children.add(new RuntimeNode(runtimeMeasurement));
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ /**
+ * Combines runtime measurements with identical class names and method
+ * names into one measurement, assuming that they originate from a loop
+ * or a similar construct where a summary measurement has been intended.
+ */
+ protected void combineRuntimeMeasurements() {
+ RuntimeNode preceding = null;
+ for (Iterator<RuntimeNode> iterator = children.iterator(); iterator.hasNext();) {
+ final RuntimeNode child = iterator.next();
+ if (preceding != null
+ && preceding.timeStopped != 0 && child.timeStopped != 0
+ && preceding.timeStopped <= child.timeStarted
+ && preceding.children.isEmpty() && child.children.isEmpty()
+ && preceding.methodName.equals(child.methodName)
+ && preceding.className.equals(child.className)) {
+ preceding.timeStarted = child.timeStarted - (preceding.timeStopped - preceding.timeStarted);
+ preceding.timeStopped = child.timeStopped;
+
+ preceding.memoryStarted = child.memoryStarted - (preceding.memoryStopped - preceding.memoryStarted);
+ preceding.memoryStopped = child.memoryStopped;
+
+ iterator.remove();
+ } else {
+ preceding = child;
+ child.combineRuntimeMeasurements();
+ }
+ }
+ }
+ }
+
+ private final RuntimeNode rootNode;
+
+ public DebugInfoRuntime(final List<RuntimeMeasurement> runtimeMeasurements) {
+ rootNode = new RuntimeNode();
+ for (final RuntimeMeasurement runtimeMeasurement : runtimeMeasurements) {
+ rootNode.add(runtimeMeasurement);
+ }
+ rootNode.combineRuntimeMeasurements();
+ }
+
+ @Override
+ public String getName() {
+ return "Runtime";
+ }
+
+ @Override
+ public void appendJson(final JsonStreamWriter jsonStreamWriter) throws IOException {
+ appendJsonChildren(jsonStreamWriter, rootNode);
+ }
+
+ private static void appendJsonNode(final JsonStreamWriter jsonStreamWriter, final RuntimeNode node) throws IOException {
+ jsonStreamWriter.beginObject()
+ .namedStringValueRaw("class", node.className).separator()
+ .namedStringValueRaw("method", node.methodName).separator()
+ .name("duration")
+ .unquotedValue(node.timeStopped == 0 ? null :
+ Long.toString((node.timeStopped - node.timeStarted) / 1000))
+ .separator()
+ .name("memory")
+ .unquotedValue(node.memoryStopped == 0 ? null :
+ Long.toString((node.memoryStopped - node.memoryStarted) / 1000))
+ .separator()
+ .name("children");
+ appendJsonChildren(jsonStreamWriter, node);
+ jsonStreamWriter.endObject();
+ }
+
+ private static void appendJsonChildren(final JsonStreamWriter jsonStreamWriter, final RuntimeNode node) throws IOException {
+ jsonStreamWriter.beginArray();
+ boolean first = true;
+ for (final RuntimeNode childNode : node.children) {
+ if (!first) {
+ jsonStreamWriter.separator();
+ }
+ first = false;
+ appendJsonNode(jsonStreamWriter, childNode);
+ }
+ jsonStreamWriter.endArray();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-olingo-odata2/blob/ff2b0a0e/odata-core/src/main/java/org/apache/olingo/odata2/core/debug/DebugInfoUri.java
----------------------------------------------------------------------
diff --git a/odata-core/src/main/java/org/apache/olingo/odata2/core/debug/DebugInfoUri.java b/odata-core/src/main/java/org/apache/olingo/odata2/core/debug/DebugInfoUri.java
new file mode 100644
index 0000000..6893e97
--- /dev/null
+++ b/odata-core/src/main/java/org/apache/olingo/odata2/core/debug/DebugInfoUri.java
@@ -0,0 +1,126 @@
+/*******************************************************************************
+ * 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.odata2.core.debug;
+
+import java.io.IOException;
+
+import org.apache.olingo.odata2.api.edm.EdmException;
+import org.apache.olingo.odata2.api.exception.ODataApplicationException;
+import org.apache.olingo.odata2.api.uri.UriInfo;
+import org.apache.olingo.odata2.api.uri.expression.ExceptionVisitExpression;
+import org.apache.olingo.odata2.api.uri.expression.ExpressionParserException;
+import org.apache.olingo.odata2.api.uri.expression.FilterExpression;
+import org.apache.olingo.odata2.api.uri.expression.OrderByExpression;
+import org.apache.olingo.odata2.core.ep.util.JsonStreamWriter;
+import org.apache.olingo.odata2.core.uri.ExpandSelectTreeCreator;
+import org.apache.olingo.odata2.core.uri.ExpandSelectTreeNodeImpl;
+import org.apache.olingo.odata2.core.uri.expression.JsonVisitor;
+
+/**
+ * @author SAP AG
+ */
+public class DebugInfoUri implements DebugInfo {
+
+ private final UriInfo uriInfo;
+ private final ExpressionParserException exception;
+
+ public DebugInfoUri(final UriInfo uriInfo, final Exception exception) {
+ this.uriInfo = uriInfo;
+
+ Throwable candidate = exception;
+ while (candidate != null && !(candidate instanceof ExpressionParserException)) {
+ candidate = candidate.getCause();
+ }
+ this.exception = (ExpressionParserException) candidate;
+ }
+
+ @Override
+ public String getName() {
+ return "URI";
+ }
+
+ @Override
+ public void appendJson(final JsonStreamWriter jsonStreamWriter) throws IOException {
+ jsonStreamWriter.beginObject();
+
+ if (exception != null) {
+ jsonStreamWriter.name("error")
+ .beginObject();
+ if (exception.getFilterTree() != null) {
+ jsonStreamWriter.namedStringValue("filter", exception.getFilterTree().getUriLiteral());
+ }
+ jsonStreamWriter.endObject();
+ }
+
+ if (uriInfo != null) {
+ if (exception != null
+ && (uriInfo.getFilter() != null || uriInfo.getOrderBy() != null
+ || !uriInfo.getExpand().isEmpty() || !uriInfo.getSelect().isEmpty())) {
+ jsonStreamWriter.separator();
+ }
+
+ final FilterExpression filter = uriInfo.getFilter();
+ if (filter != null) {
+ String filterString;
+ try {
+ filterString = (String) filter.accept(new JsonVisitor());
+ } catch (final ExceptionVisitExpression e) {
+ filterString = null;
+ } catch (final ODataApplicationException e) {
+ filterString = null;
+ }
+ jsonStreamWriter.name("filter").unquotedValue(filterString);
+ if (uriInfo.getOrderBy() != null
+ || !uriInfo.getExpand().isEmpty() || !uriInfo.getSelect().isEmpty()) {
+ jsonStreamWriter.separator();
+ }
+ }
+
+ final OrderByExpression orderBy = uriInfo.getOrderBy();
+ if (orderBy != null) {
+ String orderByString;
+ try {
+ orderByString = (String) orderBy.accept(new JsonVisitor());
+ } catch (final ExceptionVisitExpression e) {
+ orderByString = null;
+ } catch (final ODataApplicationException e) {
+ orderByString = null;
+ }
+ jsonStreamWriter.name("orderby").unquotedValue(orderByString);
+ if (!uriInfo.getExpand().isEmpty() || !uriInfo.getSelect().isEmpty()) {
+ jsonStreamWriter.separator();
+ }
+ }
+
+ if (!uriInfo.getExpand().isEmpty() || !uriInfo.getSelect().isEmpty()) {
+ String expandSelectString;
+ try {
+ ExpandSelectTreeCreator expandSelectCreator = new ExpandSelectTreeCreator(uriInfo.getSelect(), uriInfo.getExpand());
+ final ExpandSelectTreeNodeImpl expandSelectTree = expandSelectCreator.create();
+ expandSelectString = expandSelectTree.toJsonString();
+ } catch (final EdmException e) {
+ expandSelectString = null;
+ }
+ jsonStreamWriter.name("expand/select").unquotedValue(expandSelectString);
+ }
+ }
+
+ jsonStreamWriter.endObject();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-olingo-odata2/blob/ff2b0a0e/odata-core/src/main/java/org/apache/olingo/odata2/core/debug/ODataDebugResponseWrapper.java
----------------------------------------------------------------------
diff --git a/odata-core/src/main/java/org/apache/olingo/odata2/core/debug/ODataDebugResponseWrapper.java b/odata-core/src/main/java/org/apache/olingo/odata2/core/debug/ODataDebugResponseWrapper.java
new file mode 100644
index 0000000..e99d730
--- /dev/null
+++ b/odata-core/src/main/java/org/apache/olingo/odata2/core/debug/ODataDebugResponseWrapper.java
@@ -0,0 +1,139 @@
+/*******************************************************************************
+ * 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.odata2.core.debug;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStreamWriter;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+
+import org.apache.olingo.odata2.api.commons.HttpContentType;
+import org.apache.olingo.odata2.api.commons.HttpStatusCodes;
+import org.apache.olingo.odata2.api.exception.ODataException;
+import org.apache.olingo.odata2.api.processor.ODataContext;
+import org.apache.olingo.odata2.api.processor.ODataResponse;
+import org.apache.olingo.odata2.api.uri.UriInfo;
+import org.apache.olingo.odata2.core.ep.util.CircleStreamBuffer;
+import org.apache.olingo.odata2.core.ep.util.JsonStreamWriter;
+import org.apache.olingo.odata2.core.exception.MessageService;
+import org.apache.olingo.odata2.core.exception.ODataRuntimeException;
+
+/**
+ * Wraps an OData response into an OData response containing additional
+ * information useful for support purposes.
+ * @author SAP AG
+ */
+public class ODataDebugResponseWrapper {
+
+ public static final String ODATA_DEBUG_QUERY_PARAMETER = "odata-debug";
+ public static final String ODATA_DEBUG_JSON = "json";
+
+ private final ODataContext context;
+ private final ODataResponse response;
+ private final UriInfo uriInfo;
+ private final Exception exception;
+ private final boolean isJson;
+
+ public ODataDebugResponseWrapper(final ODataContext context, final ODataResponse response, final UriInfo uriInfo, final Exception exception, final String debugValue) {
+ this.context = context;
+ this.response = response;
+ this.uriInfo = uriInfo;
+ this.exception = exception;
+ isJson = ODATA_DEBUG_JSON.equals(debugValue);
+ }
+
+ public ODataResponse wrapResponse() {
+ try {
+ return ODataResponse.status(HttpStatusCodes.OK)
+ .entity(isJson ? wrapInJson(createParts()) : null)
+ .contentHeader(isJson ? HttpContentType.APPLICATION_JSON : null)
+ .build();
+ } catch (final ODataException e) {
+ throw new ODataRuntimeException("Should not happen", e);
+ } catch (final IOException e) {
+ throw new ODataRuntimeException("Should not happen", e);
+ }
+ }
+
+ private List<DebugInfo> createParts() throws ODataException {
+ List<DebugInfo> parts = new ArrayList<DebugInfo>();
+
+ // body
+ if (response.getContentHeader() != null && response.getEntity() != null) {
+ parts.add(new DebugInfoBody(response));
+ }
+
+ // request
+ parts.add(new DebugInfoRequest(context.getHttpMethod(),
+ context.getPathInfo().getRequestUri(),
+ context.getRequestHeaders()));
+
+ // response
+ Map<String, String> responseHeaders = new HashMap<String, String>();
+ for (final String name : response.getHeaderNames()) {
+ responseHeaders.put(name, response.getHeader(name));
+ }
+ parts.add(new DebugInfoResponse(response.getStatus(), responseHeaders));
+
+ // URI
+ if (uriInfo != null
+ && (uriInfo.getFilter() != null || uriInfo.getOrderBy() != null
+ || !uriInfo.getExpand().isEmpty() || !uriInfo.getSelect().isEmpty())) {
+ parts.add(new DebugInfoUri(uriInfo, exception));
+ }
+
+ // runtime measurements
+ if (context.getRuntimeMeasurements() != null) {
+ parts.add(new DebugInfoRuntime(context.getRuntimeMeasurements()));
+ }
+
+ // exceptions
+ if (exception != null) {
+ final Locale locale = MessageService.getSupportedLocale(context.getAcceptableLanguages(), Locale.ENGLISH);
+ parts.add(new DebugInfoException(exception, locale));
+ }
+
+ return parts;
+ }
+
+ private InputStream wrapInJson(final List<DebugInfo> parts) throws IOException {
+ CircleStreamBuffer csb = new CircleStreamBuffer();
+ BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(csb.getOutputStream(), "UTF-8"));
+ JsonStreamWriter jsonStreamWriter = new JsonStreamWriter(writer);
+ jsonStreamWriter.beginObject();
+ boolean first = true;
+ for (final DebugInfo part : parts) {
+ if (!first) {
+ jsonStreamWriter.separator();
+ }
+ first = false;
+ jsonStreamWriter.name(part.getName().toLowerCase(Locale.ROOT));
+ part.appendJson(jsonStreamWriter);
+ }
+ jsonStreamWriter.endObject();
+ writer.flush();
+ csb.closeWrite();
+ return csb.getInputStream();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-olingo-odata2/blob/ff2b0a0e/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/AbstractSimpleType.java
----------------------------------------------------------------------
diff --git a/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/AbstractSimpleType.java b/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/AbstractSimpleType.java
new file mode 100644
index 0000000..09057c0
--- /dev/null
+++ b/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/AbstractSimpleType.java
@@ -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.odata2.core.edm;
+
+import org.apache.olingo.odata2.api.edm.Edm;
+import org.apache.olingo.odata2.api.edm.EdmException;
+import org.apache.olingo.odata2.api.edm.EdmFacets;
+import org.apache.olingo.odata2.api.edm.EdmLiteralKind;
+import org.apache.olingo.odata2.api.edm.EdmSimpleType;
+import org.apache.olingo.odata2.api.edm.EdmSimpleTypeException;
+import org.apache.olingo.odata2.api.edm.EdmTypeKind;
+
+/**
+ * Abstract implementation of the EDM simple-type interface.
+ * @author SAP AG
+ */
+public abstract class AbstractSimpleType implements EdmSimpleType {
+
+ @Override
+ public boolean equals(final Object obj) {
+ return this == obj || (obj != null && getClass() == obj.getClass());
+ }
+
+ @Override
+ public int hashCode() {
+ return getClass().hashCode();
+ }
+
+ @Override
+ public String getNamespace() throws EdmException {
+ return EDM_NAMESPACE;
+ }
+
+ @Override
+ public EdmTypeKind getKind() {
+ return EdmTypeKind.SIMPLE;
+ }
+
+ @Override
+ public String getName() throws EdmException {
+ final String name = getClass().getSimpleName();
+ return name.startsWith(EDM_NAMESPACE) ? name.substring(3) : name;
+ }
+
+ @Override
+ public boolean isCompatible(final EdmSimpleType simpleType) {
+ return equals(simpleType);
+ }
+
+ @Override
+ public boolean validate(final String value, final EdmLiteralKind literalKind, final EdmFacets facets) {
+ try {
+ valueOfString(value, literalKind, facets, getDefaultType());
+ return true;
+ } catch (final EdmSimpleTypeException e) {
+ return false;
+ }
+ }
+
+ @Override
+ public final <T> T valueOfString(final String value, final EdmLiteralKind literalKind, final EdmFacets facets, final Class<T> returnType) throws EdmSimpleTypeException {
+ if (value == null) {
+ if (facets == null || facets.isNullable() == null || facets.isNullable()) {
+ return null;
+ } else {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.LITERAL_NULL_NOT_ALLOWED);
+ }
+ }
+
+ if (literalKind == null) {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.LITERAL_KIND_MISSING);
+ }
+
+ return internalValueOfString(value, literalKind, facets, returnType);
+ }
+
+ protected abstract <T> T internalValueOfString(String value, EdmLiteralKind literalKind, EdmFacets facets, Class<T> returnType) throws EdmSimpleTypeException;
+
+ @Override
+ public final String valueToString(final Object value, final EdmLiteralKind literalKind, final EdmFacets facets) throws EdmSimpleTypeException {
+ if (value == null) {
+ if (facets == null || facets.isNullable() == null || facets.isNullable()) {
+ return null;
+ } else {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.VALUE_NULL_NOT_ALLOWED);
+ }
+ }
+
+ if (literalKind == null) {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.LITERAL_KIND_MISSING);
+ }
+
+ final String result = internalValueToString(value, literalKind, facets);
+ return literalKind == EdmLiteralKind.URI ? toUriLiteral(result) : result;
+ }
+
+ protected abstract <T> String internalValueToString(T value, EdmLiteralKind literalKind, EdmFacets facets) throws EdmSimpleTypeException;
+
+ @Override
+ public String toUriLiteral(final String literal) throws EdmSimpleTypeException {
+ return literal;
+ }
+
+ @Override
+ public String toString() {
+ try {
+ return getNamespace() + Edm.DELIMITER + getName();
+ } catch (final EdmException e) {
+ return super.toString();
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-olingo-odata2/blob/ff2b0a0e/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/Bit.java
----------------------------------------------------------------------
diff --git a/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/Bit.java b/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/Bit.java
new file mode 100644
index 0000000..a131195
--- /dev/null
+++ b/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/Bit.java
@@ -0,0 +1,57 @@
+/*******************************************************************************
+ * 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.odata2.core.edm;
+
+import org.apache.olingo.odata2.api.edm.EdmException;
+import org.apache.olingo.odata2.api.edm.EdmFacets;
+import org.apache.olingo.odata2.api.edm.EdmLiteralKind;
+import org.apache.olingo.odata2.api.edm.EdmSimpleTypeException;
+
+/**
+ * Implementation of the internal simple type Bit.
+ * @author SAP AG
+ */
+public class Bit extends AbstractSimpleType {
+
+ private static final Bit instance = new Bit();
+
+ public static Bit getInstance() {
+ return instance;
+ }
+
+ @Override
+ public String getNamespace() throws EdmException {
+ return SYSTEM_NAMESPACE;
+ }
+
+ @Override
+ public Class<?> getDefaultType() {
+ return Byte.class;
+ }
+
+ @Override
+ protected <T> T internalValueOfString(final String value, final EdmLiteralKind literalKind, final EdmFacets facets, final Class<T> returnType) throws EdmSimpleTypeException {
+ return EdmSByte.getInstance().internalValueOfString(value, literalKind, facets, returnType);
+ }
+
+ @Override
+ protected <T> String internalValueToString(final T value, final EdmLiteralKind literalKind, final EdmFacets facets) throws EdmSimpleTypeException {
+ return EdmSByte.getInstance().internalValueToString(value, literalKind, facets);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-olingo-odata2/blob/ff2b0a0e/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/EdmBinary.java
----------------------------------------------------------------------
diff --git a/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/EdmBinary.java b/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/EdmBinary.java
new file mode 100644
index 0000000..21c7ed1
--- /dev/null
+++ b/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/EdmBinary.java
@@ -0,0 +1,151 @@
+/*******************************************************************************
+ * 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.odata2.core.edm;
+
+import java.util.Locale;
+
+import org.apache.commons.codec.DecoderException;
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.codec.binary.Hex;
+
+import org.apache.olingo.odata2.api.edm.EdmFacets;
+import org.apache.olingo.odata2.api.edm.EdmLiteralKind;
+import org.apache.olingo.odata2.api.edm.EdmSimpleTypeException;
+
+/**
+ * Implementation of the EDM simple type Binary.
+ * @author SAP AG
+ */
+public class EdmBinary extends AbstractSimpleType {
+
+ private static final EdmBinary instance = new EdmBinary();
+
+ public static EdmBinary getInstance() {
+ return instance;
+ }
+
+ @Override
+ public Class<?> getDefaultType() {
+ return byte[].class;
+ }
+
+ @Override
+ public boolean validate(final String value, final EdmLiteralKind literalKind, final EdmFacets facets) {
+ if (value == null) {
+ return facets == null || facets.isNullable() == null || facets.isNullable();
+ }
+
+ if (literalKind == null) {
+ return false;
+ }
+
+ return validateLiteral(value, literalKind) && validateMaxLength(value, literalKind, facets);
+ }
+
+ private static boolean validateLiteral(final String value, final EdmLiteralKind literalKind) {
+ return literalKind == EdmLiteralKind.URI ?
+ value.matches("(?:X|binary)'(?:\\p{XDigit}{2})*'") : Base64.isBase64(value);
+ }
+
+ private static boolean validateMaxLength(final String value, final EdmLiteralKind literalKind, final EdmFacets facets) {
+ return facets == null || facets.getMaxLength() == null ? true :
+ literalKind == EdmLiteralKind.URI ?
+ // In URI representation, each byte is represented as two hexadecimal digits;
+ // additionally, we have to account for the prefix and the surrounding "'"s.
+ facets.getMaxLength() >= (value.length() - (value.startsWith("X") ? 3 : 8)) / 2
+ :
+ // In default representation, every three bytes are represented as four base-64 characters.
+ // Additionally, there could be up to two padding "=" characters if the number of bytes is
+ // not a multiple of three, and there could be carriage return/line feed combinations.
+ facets.getMaxLength() >= value.length() * 3 / 4 - (value.endsWith("==") ? 2 : value.endsWith("=") ? 1 : 0) - crlfLength(value);
+ }
+
+ private static int crlfLength(final String value) {
+ int result = 0;
+ int index = 0;
+ while (index >= 0) {
+ index = value.indexOf("\r\n", index);
+ if (index > 0) {
+ result++;
+ index++;
+ }
+ }
+ return result * 2;
+ }
+
+ @Override
+ protected <T> T internalValueOfString(final String value, final EdmLiteralKind literalKind, final EdmFacets facets, final Class<T> returnType) throws EdmSimpleTypeException {
+ if (!validateLiteral(value, literalKind)) {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.LITERAL_ILLEGAL_CONTENT.addContent(value));
+ }
+ if (!validateMaxLength(value, literalKind, facets)) {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.LITERAL_FACETS_NOT_MATCHED.addContent(value, facets));
+ }
+
+ byte[] result;
+ if (literalKind == EdmLiteralKind.URI) {
+ try {
+ result = Hex.decodeHex(value.substring(value.startsWith("X") ? 2 : 7, value.length() - 1).toCharArray());
+ } catch (final DecoderException e) {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.LITERAL_ILLEGAL_CONTENT.addContent(value), e);
+ }
+ } else {
+ result = Base64.decodeBase64(value);
+ }
+
+ if (returnType.isAssignableFrom(byte[].class)) {
+ return returnType.cast(result);
+ } else if (returnType.isAssignableFrom(Byte[].class)) {
+ Byte[] byteArray = new Byte[result.length];
+ for (int i = 0; i < result.length; i++) {
+ byteArray[i] = result[i];
+ }
+ return returnType.cast(byteArray);
+ } else {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.VALUE_TYPE_NOT_SUPPORTED.addContent(returnType));
+ }
+ }
+
+ @Override
+ protected <T> String internalValueToString(final T value, final EdmLiteralKind literalKind, final EdmFacets facets) throws EdmSimpleTypeException {
+ byte[] byteArrayValue;
+ if (value instanceof byte[]) {
+ byteArrayValue = (byte[]) value;
+ } else if (value instanceof Byte[]) {
+ final int length = ((Byte[]) value).length;
+ byteArrayValue = new byte[length];
+ for (int i = 0; i < length; i++) {
+ byteArrayValue[i] = ((Byte[]) value)[i].byteValue();
+ }
+ } else {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.VALUE_TYPE_NOT_SUPPORTED.addContent(value.getClass()));
+ }
+
+ if (facets != null && facets.getMaxLength() != null && byteArrayValue.length > facets.getMaxLength()) {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.VALUE_FACETS_NOT_MATCHED.addContent(value, facets));
+ }
+
+ return Base64.encodeBase64String(byteArrayValue);
+ }
+
+ @Override
+ public String toUriLiteral(final String literal) throws EdmSimpleTypeException {
+ return "binary'" + Hex.encodeHexString(Base64.decodeBase64(literal)).toUpperCase(Locale.ROOT) + "'";
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-olingo-odata2/blob/ff2b0a0e/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/EdmBoolean.java
----------------------------------------------------------------------
diff --git a/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/EdmBoolean.java b/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/EdmBoolean.java
new file mode 100644
index 0000000..0c8d8d9
--- /dev/null
+++ b/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/EdmBoolean.java
@@ -0,0 +1,81 @@
+/*******************************************************************************
+ * 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.odata2.core.edm;
+
+import org.apache.olingo.odata2.api.edm.EdmFacets;
+import org.apache.olingo.odata2.api.edm.EdmLiteralKind;
+import org.apache.olingo.odata2.api.edm.EdmSimpleType;
+import org.apache.olingo.odata2.api.edm.EdmSimpleTypeException;
+
+/**
+ * Implementation of the EDM simple type Boolean.
+ * @author SAP AG
+ */
+public class EdmBoolean extends AbstractSimpleType {
+
+ private static final EdmBoolean instance = new EdmBoolean();
+
+ public static EdmBoolean getInstance() {
+ return instance;
+ }
+
+ @Override
+ public boolean isCompatible(final EdmSimpleType simpleType) {
+ return simpleType instanceof Bit || simpleType instanceof EdmBoolean;
+ }
+
+ @Override
+ public Class<?> getDefaultType() {
+ return Boolean.class;
+ }
+
+ @Override
+ public boolean validate(final String value, final EdmLiteralKind literalKind, final EdmFacets facets) {
+ return value == null ?
+ facets == null || facets.isNullable() == null || facets.isNullable() :
+ validateLiteral(value);
+ }
+
+ private static boolean validateLiteral(final String value) {
+ return "true".equals(value) || "1".equals(value)
+ || "false".equals(value) || "0".equals(value);
+ }
+
+ @Override
+ protected <T> T internalValueOfString(final String value, final EdmLiteralKind literalKind, final EdmFacets facets, final Class<T> returnType) throws EdmSimpleTypeException {
+ if (validateLiteral(value)) {
+ if (returnType.isAssignableFrom(Boolean.class)) {
+ return returnType.cast(Boolean.valueOf("true".equals(value) || "1".equals(value)));
+ } else {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.VALUE_TYPE_NOT_SUPPORTED.addContent(returnType));
+ }
+ } else {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.LITERAL_ILLEGAL_CONTENT.addContent(value));
+ }
+ }
+
+ @Override
+ protected <T> String internalValueToString(final T value, final EdmLiteralKind literalKind, final EdmFacets facets) throws EdmSimpleTypeException {
+ if (value instanceof Boolean) {
+ return Boolean.toString((Boolean) value);
+ } else {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.VALUE_TYPE_NOT_SUPPORTED.addContent(value.getClass()));
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-olingo-odata2/blob/ff2b0a0e/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/EdmByte.java
----------------------------------------------------------------------
diff --git a/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/EdmByte.java b/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/EdmByte.java
new file mode 100644
index 0000000..8196b46
--- /dev/null
+++ b/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/EdmByte.java
@@ -0,0 +1,91 @@
+/*******************************************************************************
+ * 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.odata2.core.edm;
+
+import org.apache.olingo.odata2.api.edm.EdmFacets;
+import org.apache.olingo.odata2.api.edm.EdmLiteralKind;
+import org.apache.olingo.odata2.api.edm.EdmSimpleType;
+import org.apache.olingo.odata2.api.edm.EdmSimpleTypeException;
+
+/**
+ * Implementation of the EDM simple type Byte.
+ * @author SAP AG
+ */
+public class EdmByte extends AbstractSimpleType {
+
+ private static final EdmByte instance = new EdmByte();
+
+ public static EdmByte getInstance() {
+ return instance;
+ }
+
+ @Override
+ public boolean isCompatible(final EdmSimpleType simpleType) {
+ return simpleType instanceof Bit
+ || simpleType instanceof Uint7
+ || simpleType instanceof EdmByte;
+ }
+
+ @Override
+ public Class<?> getDefaultType() {
+ return Short.class;
+ }
+
+ @Override
+ protected <T> T internalValueOfString(final String value, final EdmLiteralKind literalKind, final EdmFacets facets, final Class<T> returnType) throws EdmSimpleTypeException {
+ Short valueShort;
+ try {
+ valueShort = Short.parseShort(value);
+ } catch (final NumberFormatException e) {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.LITERAL_ILLEGAL_CONTENT.addContent(value), e);
+ }
+ if (valueShort < 0 || valueShort > 255) {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.LITERAL_ILLEGAL_CONTENT.addContent(value));
+ }
+
+ if (returnType.isAssignableFrom(Short.class)) {
+ return returnType.cast(valueShort);
+ } else if (returnType.isAssignableFrom(Byte.class)) {
+ if (valueShort <= Byte.MAX_VALUE) {
+ return returnType.cast(valueShort.byteValue());
+ } else {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.LITERAL_UNCONVERTIBLE_TO_VALUE_TYPE.addContent(value, returnType));
+ }
+ } else if (returnType.isAssignableFrom(Integer.class)) {
+ return returnType.cast(valueShort.intValue());
+ } else if (returnType.isAssignableFrom(Long.class)) {
+ return returnType.cast(valueShort.longValue());
+ } else {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.VALUE_TYPE_NOT_SUPPORTED.addContent(returnType));
+ }
+ }
+
+ @Override
+ protected <T> String internalValueToString(final T value, final EdmLiteralKind literalKind, final EdmFacets facets) throws EdmSimpleTypeException {
+ if (value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long) {
+ if (((Number) value).longValue() >= 0 && ((Number) value).longValue() <= 255) {
+ return value.toString();
+ } else {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.VALUE_ILLEGAL_CONTENT.addContent(value));
+ }
+ } else {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.VALUE_TYPE_NOT_SUPPORTED.addContent(value.getClass()));
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-olingo-odata2/blob/ff2b0a0e/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/EdmDateTime.java
----------------------------------------------------------------------
diff --git a/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/EdmDateTime.java b/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/EdmDateTime.java
new file mode 100644
index 0000000..1834b83
--- /dev/null
+++ b/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/EdmDateTime.java
@@ -0,0 +1,236 @@
+/*******************************************************************************
+ * 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.odata2.core.edm;
+
+import java.util.Calendar;
+import java.util.Date;
+import java.util.TimeZone;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.olingo.odata2.api.edm.EdmFacets;
+import org.apache.olingo.odata2.api.edm.EdmLiteralKind;
+import org.apache.olingo.odata2.api.edm.EdmSimpleTypeException;
+
+/**
+ * Implementation of the EDM simple type DateTime.
+ * @author SAP AG
+ */
+public class EdmDateTime extends AbstractSimpleType {
+
+ private static final Pattern PATTERN = Pattern.compile(
+ "(\\p{Digit}{1,4})-(\\p{Digit}{1,2})-(\\p{Digit}{1,2})"
+ + "T(\\p{Digit}{1,2}):(\\p{Digit}{1,2})(?::(\\p{Digit}{1,2})(\\.(\\p{Digit}{0,3}?)0*)?)?");
+ private static final Pattern JSON_PATTERN = Pattern.compile("/Date\\((-?\\p{Digit}+)\\)/");
+ private static final EdmDateTime instance = new EdmDateTime();
+
+ public static EdmDateTime getInstance() {
+ return instance;
+ }
+
+ @Override
+ public Class<?> getDefaultType() {
+ return Calendar.class;
+ }
+
+ @Override
+ protected <T> T internalValueOfString(final String value, final EdmLiteralKind literalKind, final EdmFacets facets, final Class<T> returnType) throws EdmSimpleTypeException {
+ // In JSON, we allow also the XML literal form, so there is on purpose
+ // no exception if the JSON pattern does not match.
+ if (literalKind == EdmLiteralKind.JSON) {
+ final Matcher matcher = JSON_PATTERN.matcher(value);
+ if (matcher.matches()) {
+ long millis;
+ try {
+ millis = Long.parseLong(matcher.group(1));
+ } catch (final NumberFormatException e) {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.LITERAL_ILLEGAL_CONTENT.addContent(value), e);
+ }
+ if (returnType.isAssignableFrom(Long.class)) {
+ return returnType.cast(millis);
+ } else if (returnType.isAssignableFrom(Date.class)) {
+ return returnType.cast(new Date(millis));
+ } else if (returnType.isAssignableFrom(Calendar.class)) {
+ Calendar dateTimeValue = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
+ dateTimeValue.clear();
+ dateTimeValue.setTimeInMillis(millis);
+ return returnType.cast(dateTimeValue);
+ } else {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.VALUE_TYPE_NOT_SUPPORTED.addContent(returnType));
+ }
+ }
+ }
+
+ Calendar dateTimeValue = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
+ dateTimeValue.clear();
+
+ if (literalKind == EdmLiteralKind.URI) {
+ if (value.length() > 10 && value.startsWith("datetime'") && value.endsWith("'")) {
+ parseLiteral(value.substring(9, value.length() - 1), facets, dateTimeValue);
+ } else {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.LITERAL_ILLEGAL_CONTENT.addContent(value));
+ }
+ } else {
+ parseLiteral(value, facets, dateTimeValue);
+ }
+
+ if (returnType.isAssignableFrom(Calendar.class)) {
+ return returnType.cast(dateTimeValue);
+ } else if (returnType.isAssignableFrom(Long.class)) {
+ return returnType.cast(dateTimeValue.getTimeInMillis());
+ } else if (returnType.isAssignableFrom(Date.class)) {
+ return returnType.cast(dateTimeValue.getTime());
+ } else {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.VALUE_TYPE_NOT_SUPPORTED.addContent(returnType));
+ }
+ }
+
+ /**
+ * Parses a formatted date/time value and sets the values of a
+ * {@link Calendar} object accordingly.
+ * @param value the formatted date/time value as String
+ * @param facets additional constraints for parsing (optional)
+ * @param dateTimeValue the Calendar object to be set to the parsed value
+ * @throws EdmSimpleTypeException
+ */
+ protected static void parseLiteral(final String value, final EdmFacets facets, final Calendar dateTimeValue) throws EdmSimpleTypeException {
+ final Matcher matcher = PATTERN.matcher(value);
+ if (!matcher.matches()) {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.LITERAL_ILLEGAL_CONTENT.addContent(value));
+ }
+
+ dateTimeValue.set(
+ Short.parseShort(matcher.group(1)),
+ Byte.parseByte(matcher.group(2)) - 1, // month is zero-based
+ Byte.parseByte(matcher.group(3)),
+ Byte.parseByte(matcher.group(4)),
+ Byte.parseByte(matcher.group(5)),
+ matcher.group(6) == null ? 0 : Byte.parseByte(matcher.group(6)));
+
+ if (matcher.group(7) != null) {
+ if (matcher.group(7).length() == 1 || matcher.group(7).length() > 8) {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.LITERAL_ILLEGAL_CONTENT.addContent(value));
+ }
+ final String decimals = matcher.group(8);
+ if (facets != null && facets.getPrecision() != null && facets.getPrecision() < decimals.length()) {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.LITERAL_FACETS_NOT_MATCHED.addContent(value, facets));
+ }
+ final String milliSeconds = decimals + "000".substring(decimals.length());
+ dateTimeValue.set(Calendar.MILLISECOND, Short.parseShort(milliSeconds));
+ }
+
+ // The Calendar class does not check any values until a get method is called,
+ // so we do just that to validate the fields set above, not because we want
+ // to return something else. For strict checks, the lenient mode is switched
+ // off temporarily.
+ dateTimeValue.setLenient(false);
+ try {
+ dateTimeValue.getTimeInMillis();
+ } catch (final IllegalArgumentException e) {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.LITERAL_ILLEGAL_CONTENT.addContent(value), e);
+ }
+ dateTimeValue.setLenient(true);
+ }
+
+ @Override
+ protected <T> String internalValueToString(final T value, final EdmLiteralKind literalKind, final EdmFacets facets) throws EdmSimpleTypeException {
+ long timeInMillis;
+ if (value instanceof Date) {
+ timeInMillis = ((Date) value).getTime();
+ } else if (value instanceof Calendar) {
+ timeInMillis = ((Calendar) value).getTimeInMillis();
+ } else if (value instanceof Long) {
+ timeInMillis = ((Long) value).longValue();
+ } else {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.VALUE_TYPE_NOT_SUPPORTED.addContent(value.getClass()));
+ }
+
+ if (literalKind == EdmLiteralKind.JSON) {
+ return "/Date(" + timeInMillis + ")/";
+ }
+
+ Calendar dateTimeValue = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
+ dateTimeValue.setTimeInMillis(timeInMillis);
+
+ StringBuilder result = new StringBuilder(23); // 23 characters are enough for millisecond precision.
+ final int year = dateTimeValue.get(Calendar.YEAR);
+ appendTwoDigits(result, year / 100);
+ appendTwoDigits(result, year % 100);
+ result.append('-');
+ appendTwoDigits(result, dateTimeValue.get(Calendar.MONTH) + 1); // month is zero-based
+ result.append('-');
+ appendTwoDigits(result, dateTimeValue.get(Calendar.DAY_OF_MONTH));
+ result.append('T');
+ appendTwoDigits(result, dateTimeValue.get(Calendar.HOUR_OF_DAY));
+ result.append(':');
+ appendTwoDigits(result, dateTimeValue.get(Calendar.MINUTE));
+ result.append(':');
+ appendTwoDigits(result, dateTimeValue.get(Calendar.SECOND));
+
+ try {
+ appendMilliseconds(result, timeInMillis, facets);
+ } catch (final IllegalArgumentException e) {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.VALUE_FACETS_NOT_MATCHED.addContent(value, facets), e);
+ }
+
+ return result.toString();
+ }
+
+ /**
+ * Appends the given number to the given string builder,
+ * assuming that the number has at most two digits, performance-optimized.
+ * @param result a {@link StringBuilder}
+ * @param number an integer that must satisfy <code>0 <= number <= 99</code>
+ */
+ private static void appendTwoDigits(final StringBuilder result, final int number) {
+ result.append((char) ('0' + number / 10));
+ result.append((char) ('0' + number % 10));
+ }
+
+ protected static void appendMilliseconds(final StringBuilder result, final long milliseconds, final EdmFacets facets) throws IllegalArgumentException {
+ final int digits = milliseconds % 1000 == 0 ? 0 : milliseconds % 100 == 0 ? 1 : milliseconds % 10 == 0 ? 2 : 3;
+ if (digits > 0) {
+ result.append('.');
+ for (int d = 100; d > 0; d /= 10) {
+ final byte digit = (byte) (milliseconds % (d * 10) / d);
+ if (digit > 0 || milliseconds % d > 0) {
+ result.append((char) ('0' + digit));
+ }
+ }
+ }
+
+ if (facets != null && facets.getPrecision() != null) {
+ final int precision = facets.getPrecision();
+ if (digits > precision) {
+ throw new IllegalArgumentException();
+ }
+ if (digits == 0 && precision > 0) {
+ result.append('.');
+ }
+ for (int i = digits; i < precision; i++) {
+ result.append('0');
+ }
+ }
+ }
+
+ @Override
+ public String toUriLiteral(final String literal) throws EdmSimpleTypeException {
+ return "datetime'" + literal + "'";
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-olingo-odata2/blob/ff2b0a0e/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/EdmDateTimeOffset.java
----------------------------------------------------------------------
diff --git a/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/EdmDateTimeOffset.java b/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/EdmDateTimeOffset.java
new file mode 100644
index 0000000..9958238
--- /dev/null
+++ b/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/EdmDateTimeOffset.java
@@ -0,0 +1,166 @@
+/*******************************************************************************
+ * 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.odata2.core.edm;
+
+import java.util.Calendar;
+import java.util.Date;
+import java.util.TimeZone;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.olingo.odata2.api.edm.EdmFacets;
+import org.apache.olingo.odata2.api.edm.EdmLiteralKind;
+import org.apache.olingo.odata2.api.edm.EdmSimpleTypeException;
+
+/**
+ * Implementation of the EDM simple type DateTimeOffset.
+ *
+ * Details about parsing of time strings to {@link EdmDateTimeOffset} objects can be found in {@link org.apache.olingo.odata2.api.edm.EdmSimpleType} documentation.
+ *
+ * @author SAP AG
+ */
+public class EdmDateTimeOffset extends AbstractSimpleType {
+
+ private static final Pattern PATTERN = Pattern.compile(
+ "\\p{Digit}{1,4}-\\p{Digit}{1,2}-\\p{Digit}{1,2}"
+ + "T\\p{Digit}{1,2}:\\p{Digit}{1,2}(?::\\p{Digit}{1,2}(?:\\.\\p{Digit}{1,7})?)?"
+ + "(Z|([-+]\\p{Digit}{1,2}:\\p{Digit}{2}))?");
+ private static final Pattern JSON_PATTERN = Pattern.compile(
+ "/Date\\((-?\\p{Digit}+)(?:(\\+|-)(\\p{Digit}{1,4}))?\\)/");
+ private static final EdmDateTimeOffset instance = new EdmDateTimeOffset();
+
+ public static EdmDateTimeOffset getInstance() {
+ return instance;
+ }
+
+ @Override
+ public Class<?> getDefaultType() {
+ return Calendar.class;
+ }
+
+ @Override
+ protected <T> T internalValueOfString(final String value, final EdmLiteralKind literalKind, final EdmFacets facets, final Class<T> returnType) throws EdmSimpleTypeException {
+ if (literalKind == EdmLiteralKind.URI) {
+ if (value.length() > 16 && value.startsWith("datetimeoffset'") && value.endsWith("'")) {
+ return internalValueOfString(value.substring(15, value.length() - 1), EdmLiteralKind.DEFAULT, facets, returnType);
+ } else {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.LITERAL_ILLEGAL_CONTENT.addContent(value));
+ }
+ }
+
+ Calendar dateTimeValue = null;
+
+ if (literalKind == EdmLiteralKind.JSON) {
+ final Matcher matcher = JSON_PATTERN.matcher(value);
+ if (matcher.matches()) {
+ long millis;
+ try {
+ millis = Long.parseLong(matcher.group(1));
+ } catch (final NumberFormatException e) {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.LITERAL_ILLEGAL_CONTENT.addContent(value), e);
+ }
+ String timeZone = "GMT";
+ if (matcher.group(2) != null) {
+ final int offsetInMinutes = Integer.parseInt(matcher.group(3));
+ if (offsetInMinutes >= 24 * 60) {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.LITERAL_ILLEGAL_CONTENT.addContent(value));
+ }
+ if (offsetInMinutes != 0) {
+ timeZone += matcher.group(2) + String.valueOf(offsetInMinutes / 60)
+ + ":" + String.format("%02d", offsetInMinutes % 60);
+ // Convert the local-time milliseconds to UTC.
+ millis -= (matcher.group(2).equals("+") ? 1 : -1) * offsetInMinutes * 60 * 1000;
+ }
+ }
+ dateTimeValue = Calendar.getInstance(TimeZone.getTimeZone(timeZone));
+ dateTimeValue.clear();
+ dateTimeValue.setTimeInMillis(millis);
+ }
+ }
+
+ if (dateTimeValue == null) {
+ final Matcher matcher = PATTERN.matcher(value);
+ if (!matcher.matches()) {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.LITERAL_ILLEGAL_CONTENT.addContent(value));
+ }
+
+ final String timeZoneOffset = matcher.group(1) != null && matcher.group(2) != null && !matcher.group(2).matches("[-+]0+:0+") ? matcher.group(2) : null;
+ dateTimeValue = Calendar.getInstance(TimeZone.getTimeZone("GMT" + timeZoneOffset));
+ if (dateTimeValue.get(Calendar.ZONE_OFFSET) == 0 && timeZoneOffset != null) {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.LITERAL_ILLEGAL_CONTENT.addContent(value));
+ }
+ dateTimeValue.clear();
+ EdmDateTime.parseLiteral(value.substring(0, matcher.group(1) == null ? value.length() : matcher.start(1)), facets, dateTimeValue);
+ }
+
+ if (returnType.isAssignableFrom(Calendar.class)) {
+ return returnType.cast(dateTimeValue);
+ } else if (returnType.isAssignableFrom(Long.class)) {
+ return returnType.cast(dateTimeValue.getTimeInMillis());
+ } else if (returnType.isAssignableFrom(Date.class)) {
+ return returnType.cast(dateTimeValue.getTime());
+ } else {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.VALUE_TYPE_NOT_SUPPORTED.addContent(returnType));
+ }
+ }
+
+ @Override
+ protected <T> String internalValueToString(final T value, final EdmLiteralKind literalKind, final EdmFacets facets) throws EdmSimpleTypeException {
+ Long milliSeconds; // number of milliseconds since 1970-01-01T00:00:00Z
+ int offset; // offset in milliseconds from GMT to the requested time zone
+ if (value instanceof Date) {
+ milliSeconds = ((Date) value).getTime();
+ // Although java.util.Date, as stated in its documentation,
+ // "is intended to reflect coordinated universal time (UTC)",
+ // its toString() method uses the default time zone. And so do we.
+ Calendar dateTimeValue = Calendar.getInstance();
+ dateTimeValue.setTime((Date) value);
+ offset = dateTimeValue.get(Calendar.ZONE_OFFSET) + dateTimeValue.get(Calendar.DST_OFFSET);
+ } else if (value instanceof Calendar) {
+ final Calendar dateTimeValue = (Calendar) ((Calendar) value).clone();
+ milliSeconds = dateTimeValue.getTimeInMillis();
+ offset = dateTimeValue.get(Calendar.ZONE_OFFSET) + dateTimeValue.get(Calendar.DST_OFFSET);
+ } else if (value instanceof Long) {
+ milliSeconds = (Long) value;
+ offset = 0;
+ } else {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.VALUE_TYPE_NOT_SUPPORTED.addContent(value.getClass()));
+ }
+
+ milliSeconds += offset; // Convert from UTC to local time.
+ final int offsetInMinutes = offset / 60 / 1000;
+
+ if (literalKind == EdmLiteralKind.JSON) {
+ return "/Date(" + milliSeconds + (offset == 0 ? "" : String.format("%+05d", offsetInMinutes)) + ")/";
+
+ } else {
+ final String localTimeString = EdmDateTime.getInstance().valueToString(milliSeconds, EdmLiteralKind.DEFAULT, facets);
+ final int offsetHours = offsetInMinutes / 60;
+ final int offsetMinutes = Math.abs(offsetInMinutes % 60);
+ final String offsetString = offset == 0 ? "Z" : String.format("%+03d:%02d", offsetHours, offsetMinutes);
+
+ return localTimeString + offsetString;
+ }
+ }
+
+ @Override
+ public String toUriLiteral(final String literal) throws EdmSimpleTypeException {
+ return "datetimeoffset'" + literal + "'";
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-olingo-odata2/blob/ff2b0a0e/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/EdmDecimal.java
----------------------------------------------------------------------
diff --git a/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/EdmDecimal.java b/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/EdmDecimal.java
new file mode 100644
index 0000000..4f31be9
--- /dev/null
+++ b/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/EdmDecimal.java
@@ -0,0 +1,199 @@
+/*******************************************************************************
+ * 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.odata2.core.edm;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.olingo.odata2.api.edm.EdmFacets;
+import org.apache.olingo.odata2.api.edm.EdmLiteralKind;
+import org.apache.olingo.odata2.api.edm.EdmSimpleType;
+import org.apache.olingo.odata2.api.edm.EdmSimpleTypeException;
+
+/**
+ * Implementation of the EDM simple type Decimal.
+ * @author SAP AG
+ */
+public class EdmDecimal extends AbstractSimpleType {
+
+ // value-range limitation according to the CSDL document
+ private static final int MAX_DIGITS = 29;
+
+ private static final Pattern PATTERN = Pattern.compile("(?:\\+|-)?(?:0*(\\p{Digit}{1,29}?))(?:\\.(\\p{Digit}{1,29}?)0*)?(M|m)?");
+ private static final EdmDecimal instance = new EdmDecimal();
+
+ public static EdmDecimal getInstance() {
+ return instance;
+ }
+
+ @Override
+ public boolean isCompatible(final EdmSimpleType simpleType) {
+ return simpleType instanceof Bit
+ || simpleType instanceof Uint7
+ || simpleType instanceof EdmByte
+ || simpleType instanceof EdmSByte
+ || simpleType instanceof EdmInt16
+ || simpleType instanceof EdmInt32
+ || simpleType instanceof EdmInt64
+ || simpleType instanceof EdmSingle
+ || simpleType instanceof EdmDouble
+ || simpleType instanceof EdmDecimal;
+ }
+
+ @Override
+ public Class<?> getDefaultType() {
+ return BigDecimal.class;
+ }
+
+ @Override
+ public boolean validate(final String value, final EdmLiteralKind literalKind, final EdmFacets facets) {
+ if (value == null) {
+ return facets == null || facets.isNullable() == null || facets.isNullable();
+ }
+
+ if (literalKind == null) {
+ return false;
+ }
+
+ return validateLiteral(value, literalKind) && validatePrecisionAndScale(value, facets);
+ }
+
+ private static boolean validateLiteral(final String value, final EdmLiteralKind literalKind) {
+ final Matcher matcher = PATTERN.matcher(value);
+ return matcher.matches()
+ && (literalKind == EdmLiteralKind.URI) != (matcher.group(3) == null);
+ }
+
+ private static final boolean validatePrecisionAndScale(final String value, final EdmFacets facets) {
+ if (facets == null || facets.getPrecision() == null && facets.getScale() == null) {
+ return true;
+ }
+
+ final Matcher matcher = PATTERN.matcher(value);
+ matcher.matches();
+ final int significantIntegerDigits = matcher.group(1).equals("0") ? 0 : matcher.group(1).length();
+ final int decimals = matcher.group(2) == null ? 0 : matcher.group(2).length();
+ return (facets.getPrecision() == null || facets.getPrecision() >= significantIntegerDigits + decimals)
+ && (facets.getScale() == null || facets.getScale() >= decimals);
+ }
+
+ @Override
+ protected <T> T internalValueOfString(final String value, final EdmLiteralKind literalKind, final EdmFacets facets, final Class<T> returnType) throws EdmSimpleTypeException {
+ if (!validateLiteral(value, literalKind)) {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.LITERAL_ILLEGAL_CONTENT.addContent(value));
+ }
+ if (!validatePrecisionAndScale(value, facets)) {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.LITERAL_FACETS_NOT_MATCHED.addContent(value, facets));
+ }
+
+ final BigDecimal valueBigDecimal = new BigDecimal(
+ literalKind == EdmLiteralKind.URI ? value.substring(0, value.length() - 1) : value);
+
+ if (returnType.isAssignableFrom(BigDecimal.class)) {
+ return returnType.cast(valueBigDecimal);
+ } else if (returnType.isAssignableFrom(Double.class)) {
+ if (BigDecimal.valueOf(valueBigDecimal.doubleValue()).compareTo(valueBigDecimal) == 0) {
+ return returnType.cast(valueBigDecimal.doubleValue());
+ } else {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.LITERAL_UNCONVERTIBLE_TO_VALUE_TYPE.addContent(value, returnType));
+ }
+ } else if (returnType.isAssignableFrom(Float.class)) {
+ if (BigDecimal.valueOf(valueBigDecimal.floatValue()).compareTo(valueBigDecimal) == 0) {
+ return returnType.cast(valueBigDecimal.floatValue());
+ } else {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.LITERAL_UNCONVERTIBLE_TO_VALUE_TYPE.addContent(value, returnType));
+ }
+ } else {
+ try {
+ if (returnType.isAssignableFrom(BigInteger.class)) {
+ return returnType.cast(valueBigDecimal.toBigIntegerExact());
+ } else if (returnType.isAssignableFrom(Long.class)) {
+ return returnType.cast(valueBigDecimal.longValueExact());
+ } else if (returnType.isAssignableFrom(Integer.class)) {
+ return returnType.cast(valueBigDecimal.intValueExact());
+ } else if (returnType.isAssignableFrom(Short.class)) {
+ return returnType.cast(valueBigDecimal.shortValueExact());
+ } else if (returnType.isAssignableFrom(Byte.class)) {
+ return returnType.cast(valueBigDecimal.byteValueExact());
+ } else {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.VALUE_TYPE_NOT_SUPPORTED.addContent(returnType));
+ }
+ } catch (final ArithmeticException e) {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.LITERAL_UNCONVERTIBLE_TO_VALUE_TYPE.addContent(value, returnType), e);
+ }
+ }
+ }
+
+ @Override
+ protected <T> String internalValueToString(final T value, final EdmLiteralKind literalKind, final EdmFacets facets) throws EdmSimpleTypeException {
+ String result;
+ if (value instanceof Long || value instanceof Integer || value instanceof Short || value instanceof Byte || value instanceof BigInteger) {
+ result = value.toString();
+ final int digits = result.startsWith("-") ? result.length() - 1 : result.length();
+ if (digits > MAX_DIGITS) {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.VALUE_ILLEGAL_CONTENT.addContent(value));
+ }
+ if (facets != null && facets.getPrecision() != null && facets.getPrecision() < digits) {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.VALUE_FACETS_NOT_MATCHED.addContent(value, facets));
+ }
+
+ } else if (value instanceof Double || value instanceof Float || value instanceof BigDecimal) {
+ BigDecimal bigDecimalValue;
+ try {
+ if (value instanceof Double) {
+ bigDecimalValue = BigDecimal.valueOf((Double) value);
+ } else if (value instanceof Float) {
+ bigDecimalValue = BigDecimal.valueOf((Float) value);
+ } else {
+ bigDecimalValue = (BigDecimal) value;
+ }
+ } catch (final NumberFormatException e) {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.VALUE_ILLEGAL_CONTENT.addContent(value), e);
+ }
+
+ if (bigDecimalValue.precision() - bigDecimalValue.scale() > MAX_DIGITS
+ || bigDecimalValue.scale() > MAX_DIGITS) {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.VALUE_ILLEGAL_CONTENT.addContent(value));
+ }
+
+ final int digits = bigDecimalValue.scale() >= 0 ?
+ Math.max(bigDecimalValue.precision(), bigDecimalValue.scale()) :
+ bigDecimalValue.precision() - bigDecimalValue.scale();
+ if (facets == null
+ || (facets.getPrecision() == null || facets.getPrecision() >= digits)
+ && (facets.getScale() == null || facets.getScale() >= bigDecimalValue.scale())) {
+ result = bigDecimalValue.toPlainString();
+ } else {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.VALUE_FACETS_NOT_MATCHED.addContent(value, facets));
+ }
+
+ } else {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.VALUE_TYPE_NOT_SUPPORTED.addContent(value.getClass()));
+ }
+
+ return result;
+ }
+
+ @Override
+ public String toUriLiteral(final String literal) throws EdmSimpleTypeException {
+ return literal + "M";
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-olingo-odata2/blob/ff2b0a0e/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/EdmDouble.java
----------------------------------------------------------------------
diff --git a/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/EdmDouble.java b/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/EdmDouble.java
new file mode 100644
index 0000000..2f299b9
--- /dev/null
+++ b/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/EdmDouble.java
@@ -0,0 +1,164 @@
+/*******************************************************************************
+ * 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.odata2.core.edm;
+
+import java.math.BigDecimal;
+import java.util.Locale;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.olingo.odata2.api.edm.EdmFacets;
+import org.apache.olingo.odata2.api.edm.EdmLiteralKind;
+import org.apache.olingo.odata2.api.edm.EdmSimpleType;
+import org.apache.olingo.odata2.api.edm.EdmSimpleTypeException;
+
+/**
+ * Implementation of the EDM simple type Double.
+ * @author SAP AG
+ */
+public class EdmDouble extends AbstractSimpleType {
+
+ // value-range limitations according to the CSDL document
+ private static final int MAX_PRECISION = 15;
+ private static final int MAX_SCALE = 308;
+
+ private static final Pattern PATTERN = Pattern.compile(
+ "(?:\\+|-)?\\p{Digit}{1,15}(?:\\.\\p{Digit}{1,15})?(?:(?:E|e)(?:\\+|-)?\\p{Digit}{1,3})?(D|d)?");
+ private static final EdmDouble instance = new EdmDouble();
+
+ public static EdmDouble getInstance() {
+ return instance;
+ }
+
+ @Override
+ public boolean isCompatible(final EdmSimpleType simpleType) {
+ return simpleType instanceof Bit
+ || simpleType instanceof Uint7
+ || simpleType instanceof EdmByte
+ || simpleType instanceof EdmSByte
+ || simpleType instanceof EdmInt16
+ || simpleType instanceof EdmInt32
+ || simpleType instanceof EdmInt64
+ || simpleType instanceof EdmSingle
+ || simpleType instanceof EdmDouble;
+ }
+
+ @Override
+ public Class<?> getDefaultType() {
+ return Double.class;
+ }
+
+ @Override
+ protected <T> T internalValueOfString(final String value, final EdmLiteralKind literalKind, final EdmFacets facets, final Class<T> returnType) throws EdmSimpleTypeException {
+ String valueString = value;
+ Double result = null;
+ // Handle special values first.
+ if (value.equals("-INF")) {
+ result = Double.NEGATIVE_INFINITY;
+ } else if (value.equals("INF")) {
+ result = Double.POSITIVE_INFINITY;
+ } else if (value.equals("NaN")) {
+ result = Double.NaN;
+ } else {
+ // Now only "normal" numbers remain.
+ final Matcher matcher = PATTERN.matcher(value);
+ if (!matcher.matches()
+ || (literalKind == EdmLiteralKind.URI) == (matcher.group(1) == null)) {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.LITERAL_ILLEGAL_CONTENT.addContent(value));
+ }
+
+ if (literalKind == EdmLiteralKind.URI) {
+ valueString = value.substring(0, value.length() - 1);
+ }
+
+ // The number format is checked above, so we don't have to catch NumberFormatException.
+ result = Double.valueOf(valueString);
+ // "Real" infinite values have been treated already above, so we can throw an exception
+ // if the conversion to a float results in an infinite value.
+ if (result.isInfinite()) {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.LITERAL_ILLEGAL_CONTENT.addContent(value));
+ }
+ }
+
+ if (returnType.isAssignableFrom(Double.class)) {
+ return returnType.cast(result);
+ } else if (returnType.isAssignableFrom(Float.class)) {
+ if (result.floatValue() == result) {
+ return returnType.cast(result.floatValue());
+ } else {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.LITERAL_UNCONVERTIBLE_TO_VALUE_TYPE.addContent(value, returnType));
+ }
+ } else if (result.isInfinite() || result.isNaN()) {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.LITERAL_UNCONVERTIBLE_TO_VALUE_TYPE.addContent(value, returnType));
+ } else {
+ try {
+ final BigDecimal valueBigDecimal = new BigDecimal(valueString);
+ if (returnType.isAssignableFrom(BigDecimal.class)) {
+ return returnType.cast(valueBigDecimal);
+ } else if (returnType.isAssignableFrom(Long.class)) {
+ return returnType.cast(valueBigDecimal.longValueExact());
+ } else if (returnType.isAssignableFrom(Integer.class)) {
+ return returnType.cast(valueBigDecimal.intValueExact());
+ } else if (returnType.isAssignableFrom(Short.class)) {
+ return returnType.cast(valueBigDecimal.shortValueExact());
+ } else if (returnType.isAssignableFrom(Byte.class)) {
+ return returnType.cast(valueBigDecimal.byteValueExact());
+ } else {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.VALUE_TYPE_NOT_SUPPORTED.addContent(returnType));
+ }
+
+ } catch (final ArithmeticException e) {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.LITERAL_UNCONVERTIBLE_TO_VALUE_TYPE.addContent(value, returnType), e);
+ }
+ }
+ }
+
+ @Override
+ protected <T> String internalValueToString(final T value, final EdmLiteralKind literalKind, final EdmFacets facets) throws EdmSimpleTypeException {
+ if (value instanceof Long) {
+ if (Math.abs((Long) value) < Math.pow(10, MAX_PRECISION)) {
+ return value.toString();
+ } else {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.VALUE_ILLEGAL_CONTENT.addContent(value));
+ }
+ } else if (value instanceof Integer || value instanceof Short || value instanceof Byte) {
+ return value.toString();
+ } else if (value instanceof Double) {
+ final String result = value.toString();
+ return ((Double) value).isInfinite() ? result.toUpperCase(Locale.ROOT).substring(0, value.toString().length() - 5) : result;
+ } else if (value instanceof Float) {
+ final String result = value.toString();
+ return ((Float) value).isInfinite() ? result.toUpperCase(Locale.ROOT).substring(0, value.toString().length() - 5) : result;
+ } else if (value instanceof BigDecimal) {
+ if (((BigDecimal) value).precision() <= MAX_PRECISION && Math.abs(((BigDecimal) value).scale()) <= MAX_SCALE) {
+ return ((BigDecimal) value).toString();
+ } else {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.VALUE_ILLEGAL_CONTENT.addContent(value));
+ }
+ } else {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.VALUE_TYPE_NOT_SUPPORTED.addContent(value.getClass()));
+ }
+ }
+
+ @Override
+ public String toUriLiteral(final String literal) {
+ return literal.equals("-INF") || literal.equals("INF") || literal.equals("NaN") ?
+ literal : literal + "D";
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-olingo-odata2/blob/ff2b0a0e/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/EdmGuid.java
----------------------------------------------------------------------
diff --git a/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/EdmGuid.java b/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/EdmGuid.java
new file mode 100644
index 0000000..4387ef2
--- /dev/null
+++ b/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/EdmGuid.java
@@ -0,0 +1,86 @@
+/*******************************************************************************
+ * 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.odata2.core.edm;
+
+import java.util.UUID;
+
+import org.apache.olingo.odata2.api.edm.EdmFacets;
+import org.apache.olingo.odata2.api.edm.EdmLiteralKind;
+import org.apache.olingo.odata2.api.edm.EdmSimpleTypeException;
+
+/**
+ * Implementation of the EDM simple type Guid.
+ * @author SAP AG
+ */
+public class EdmGuid extends AbstractSimpleType {
+
+ private static final String PATTERN = "\\p{XDigit}{8}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{12}";
+ private static final EdmGuid instance = new EdmGuid();
+
+ public static EdmGuid getInstance() {
+ return instance;
+ }
+
+ @Override
+ public Class<?> getDefaultType() {
+ return UUID.class;
+ }
+
+ @Override
+ public boolean validate(final String value, final EdmLiteralKind literalKind, final EdmFacets facets) {
+ return value == null ?
+ facets == null || facets.isNullable() == null || facets.isNullable() :
+ validateLiteral(value, literalKind);
+ }
+
+ private boolean validateLiteral(final String value, final EdmLiteralKind literalKind) {
+ return value.matches(literalKind == EdmLiteralKind.URI ? toUriLiteral(PATTERN) : PATTERN);
+ }
+
+ @Override
+ protected <T> T internalValueOfString(final String value, final EdmLiteralKind literalKind, final EdmFacets facets, final Class<T> returnType) throws EdmSimpleTypeException {
+ UUID result;
+ if (validateLiteral(value, literalKind)) {
+ result = UUID.fromString(
+ literalKind == EdmLiteralKind.URI ? value.substring(5, value.length() - 1) : value);
+ } else {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.LITERAL_ILLEGAL_CONTENT.addContent(value));
+ }
+
+ if (returnType.isAssignableFrom(UUID.class)) {
+ return returnType.cast(result);
+ } else {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.VALUE_TYPE_NOT_SUPPORTED.addContent(returnType));
+ }
+ }
+
+ @Override
+ protected <T> String internalValueToString(final T value, final EdmLiteralKind literalKind, final EdmFacets facets) throws EdmSimpleTypeException {
+ if (value instanceof UUID) {
+ return ((UUID) value).toString();
+ } else {
+ throw new EdmSimpleTypeException(EdmSimpleTypeException.VALUE_TYPE_NOT_SUPPORTED.addContent(value.getClass()));
+ }
+ }
+
+ @Override
+ public String toUriLiteral(final String literal) {
+ return "guid'" + literal + "'";
+ }
+}