http://git-wip-us.apache.org/repos/asf/olingo-odata4/blob/f7a7b484/lib/server-core/src/main/java/org/apache/olingo/server/core/uri/validator/UriValidator.java ---------------------------------------------------------------------- diff --git a/lib/server-core/src/main/java/org/apache/olingo/server/core/uri/validator/UriValidator.java b/lib/server-core/src/main/java/org/apache/olingo/server/core/uri/validator/UriValidator.java deleted file mode 100644 index 5db1d11..0000000 --- a/lib/server-core/src/main/java/org/apache/olingo/server/core/uri/validator/UriValidator.java +++ /dev/null @@ -1,694 +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.server.core.uri.validator; - -import java.util.HashMap; -import java.util.List; - -import org.apache.olingo.commons.api.edm.EdmAction; -import org.apache.olingo.commons.api.edm.EdmActionImport; -import org.apache.olingo.commons.api.edm.EdmEntityType; -import org.apache.olingo.commons.api.edm.EdmFunction; -import org.apache.olingo.commons.api.edm.EdmFunctionImport; -import org.apache.olingo.commons.api.edm.EdmKeyPropertyRef; -import org.apache.olingo.commons.api.edm.EdmPrimitiveType; -import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeException; -import org.apache.olingo.commons.api.edm.EdmProperty; -import org.apache.olingo.commons.api.edm.EdmReturnType; -import org.apache.olingo.commons.api.edm.EdmSingleton; -import org.apache.olingo.commons.api.edm.constants.EdmTypeKind; -import org.apache.olingo.commons.api.http.HttpMethod; -import org.apache.olingo.server.api.uri.UriInfo; -import org.apache.olingo.server.api.uri.UriParameter; -import org.apache.olingo.server.api.uri.UriResource; -import org.apache.olingo.server.api.uri.UriResourceAction; -import org.apache.olingo.server.api.uri.UriResourceEntitySet; -import org.apache.olingo.server.api.uri.UriResourceFunction; -import org.apache.olingo.server.api.uri.UriResourceKind; -import org.apache.olingo.server.api.uri.UriResourceNavigation; -import org.apache.olingo.server.api.uri.UriResourcePartTyped; -import org.apache.olingo.server.api.uri.UriResourceProperty; -import org.apache.olingo.server.api.uri.UriResourceSingleton; -import org.apache.olingo.server.api.uri.queryoption.SystemQueryOption; -import org.apache.olingo.server.api.uri.queryoption.SystemQueryOptionKind; - -public class UriValidator { - - //@formatter:off (Eclipse formatter) - //CHECKSTYLE:OFF (Maven checkstyle) - private boolean[][] decisionMatrix = - { - /* 0-FILTER 1-FORMAT 2-EXPAND 3-ID 4-COUNT 5-ORDERBY 6-SEARCH 7-SELECT 8-SKIP 9-SKIPTOKEN 10-LEVELS 11-TOP */ - /* all 0 */ { true , true , true , false, true , true , true , true , true , true , true , false }, - /* batch 1 */ { false, false, false, false, false, false, false, false, false, false, false, false }, - /* crossjoin 2 */ { true , true , true , false, true , true , true , true , true , true , true , true }, - /* entityId 3 */ { false, true , true , true , false, false, false, true , false, false, true , false }, - /* metadata 4 */ { false, true , false, false, false, false, false, false, false, false, false, false }, - /* resource 5 */ { false, true , false, false, false, false, false, false, false, false, false, false }, - /* service 6 */ { false, true , false, false, false, false, false, false, false, false, false, false }, - /* entitySet 7 */ { true , true , true , false, true , true , true , true , true , true , true , true }, - /* entitySetCount 8 */ { true, false, false, false, false, false, true, false, false, false, false, false }, - /* entity 9 */ { false, true , true , false, false, false, false, true , false, false, true , false }, - /* mediaStream 10 */ { false, true , false, false, false, false, false, false, false, false, false, false }, - /* references 11 */ { true , true , false, false, false, true , true , false, true , true , false, true }, - /* reference 12 */ { false, true , false, false, false, false, false, false, false, false, false, false }, - /* propertyComplex 13 */ { false, true , true , false, false, false, false, true , false, false, true , false }, - /* propertyComplexCollection 14 */ { true , true , true , false, true , true , false, false, true , true , true , true }, - /* propertyComplexCollectionCount 15 */ { true, false, false, false, false, false, true, false, false, false, false, false }, - /* propertyPrimitive 16 */ { false, true , false, false, false, false, false, false, false, false, false, false }, - /* propertyPrimitiveCollection 17 */ { true , true , false, false, false, true , false, false, true , true , false, true }, - /* propertyPrimitiveCollectionCount 18 */ { true, false, false, false, false, false, true, false, false, false, false, false }, - /* propertyPrimitiveValue 19 */ { false, true , false, false, false, false, false, false, false, false, false, false }, - }; - - private boolean[][] decisionMatrixForHttpMethod = - { - /* 0-FILTER 1-FORMAT 2-EXPAND 3-ID 4-COUNT 5-ORDERBY 6-SEARCH 7-SELECT 8-SKIP 9-SKIPTOKEN 10-LEVELS 11-TOP */ - /* GET 0 */ { true , true , true , true, true , true , true , true , true , true , true , true }, - /* POST 0 */ { true , false , true , false, false , true , false , true , false , false , true , false }, - /* PUT 0 */ { false , false , false , false, false , false , false , false , false , false , false , false }, - /* DELETE 0 */ { false , false , false , false, false , false, false , false, false , false , false, false }, - /* PATCH 0 */ { false , false , false , false, false , false , false , false , false , false , false , false }, - }; - - //CHECKSTYLE:ON - //@formatter:on - - private enum RowIndexForUriType { - all(0), - batch(1), - crossjoin(2), - entityId(3), - metadata(4), - resource(5), - service(6), - entitySet(7), - entitySetCount(8), - entity(9), - mediaStream(10), - references(11), - reference(12), - propertyComplex(13), - propertyComplexCollection(14), - propertyComplexCollectionCount(15), - propertyPrimitive(16), - propertyPrimitiveCollection(17), - propertyPrimitiveCollectionCount(18), - propertyPrimitiveValue(19); - - private int idx; - - RowIndexForUriType(final int i) { - idx = i; - } - - public int getIndex() { - return idx; - } - } - - private enum ColumnIndex { - filter(0), - format(1), - expand(2), - id(3), - count(4), - orderby(5), - search(6), - select(7), - skip(8), - skiptoken(9), - levels(10), - top(11); - - private int idx; - - ColumnIndex(final int i) { - idx = i; - } - - public int getIndex() { - return idx; - } - - } - - private enum RowIndexForHttpMethod { - GET(0), - POST(1), - PUT(2), - DELETE(3), - PATCH(4); - - private int idx; - - RowIndexForHttpMethod(final int i) { - idx = i; - } - - public int getIndex() { - return idx; - } - - } - - public UriValidator() { - super(); - } - - public void validate(final UriInfo uriInfo, final HttpMethod httpMethod) throws UriValidationException { - validateForHttpMethod(uriInfo, httpMethod); - validateQueryOptions(uriInfo); - validateKeyPredicates(uriInfo); - validatePropertyOperations(uriInfo, httpMethod); - } - - private ColumnIndex colIndex(final SystemQueryOptionKind queryOptionKind) throws UriValidationException { - ColumnIndex idx; - switch (queryOptionKind) { - case FILTER: - idx = ColumnIndex.filter; - break; - case FORMAT: - idx = ColumnIndex.format; - break; - case EXPAND: - idx = ColumnIndex.expand; - break; - case ID: - idx = ColumnIndex.id; - break; - case COUNT: - idx = ColumnIndex.count; - break; - case ORDERBY: - idx = ColumnIndex.orderby; - break; - case SEARCH: - idx = ColumnIndex.search; - break; - case SELECT: - idx = ColumnIndex.select; - break; - case SKIP: - idx = ColumnIndex.skip; - break; - case SKIPTOKEN: - idx = ColumnIndex.skiptoken; - break; - case LEVELS: - idx = ColumnIndex.levels; - break; - case TOP: - idx = ColumnIndex.top; - break; - default: - throw new UriValidationException("Unsupported option: " + queryOptionKind.toString(), - UriValidationException.MessageKeys.UNSUPPORTED_QUERY_OPTION, queryOptionKind.toString()); - } - - return idx; - } - - private RowIndexForUriType rowIndexForUriType(final UriInfo uriInfo) throws UriValidationException { - RowIndexForUriType idx; - - switch (uriInfo.getKind()) { - case all: - idx = RowIndexForUriType.all; - break; - case batch: - idx = RowIndexForUriType.batch; - break; - case crossjoin: - idx = RowIndexForUriType.crossjoin; - break; - case entityId: - idx = RowIndexForUriType.entityId; - break; - case metadata: - idx = RowIndexForUriType.metadata; - break; - case resource: - idx = rowIndexForResourceKind(uriInfo); - break; - case service: - idx = RowIndexForUriType.service; - break; - default: - throw new UriValidationException("Unsupported uriInfo kind: " + uriInfo.getKind(), - UriValidationException.MessageKeys.UNSUPPORTED_URI_KIND, uriInfo.getKind().toString()); - } - - return idx; - } - - private RowIndexForUriType rowIndexForResourceKind(final UriInfo uriInfo) throws UriValidationException { - RowIndexForUriType idx; - - int lastPathSegmentIndex = uriInfo.getUriResourceParts().size() - 1; - UriResource lastPathSegment = uriInfo.getUriResourceParts().get(lastPathSegmentIndex); - - switch (lastPathSegment.getKind()) { - case count: - idx = rowIndexForCount(uriInfo); - break; - case action: - idx = rowIndexForAction(lastPathSegment); - break; - case complexProperty: - idx = rowIndexForComplexProperty(lastPathSegment); - break; - case entitySet: - idx = rowIndexForEntitySet(lastPathSegment); - break; - case function: - idx = rowIndexForFunction(lastPathSegment); - break; - case navigationProperty: - idx = - ((UriResourceNavigation) lastPathSegment).isCollection() ? RowIndexForUriType.entitySet - : RowIndexForUriType.entity; - break; - case primitiveProperty: - idx = rowIndexForPrimitiveProperty(lastPathSegment); - break; - case ref: - idx = rowIndexForRef(uriInfo, lastPathSegment); - break; - case root: - idx = RowIndexForUriType.service; - break; - case singleton: - idx = RowIndexForUriType.entity; - break; - case value: - idx = rowIndexForValue(uriInfo); - break; - default: - throw new UriValidationException("Unsupported uriResource kind: " + lastPathSegment.getKind(), - UriValidationException.MessageKeys.UNSUPPORTED_URI_RESOURCE_KIND, lastPathSegment.getKind().toString()); - } - - return idx; - } - - private RowIndexForUriType rowIndexForValue(final UriInfo uriInfo) throws UriValidationException { - RowIndexForUriType idx; - int secondLastPathSegmentIndex = uriInfo.getUriResourceParts().size() - 2; - UriResource secondLastPathSegment = uriInfo.getUriResourceParts().get(secondLastPathSegmentIndex); - - switch (secondLastPathSegment.getKind()) { - case primitiveProperty: - idx = RowIndexForUriType.propertyPrimitiveValue; - break; - case entitySet: - idx = RowIndexForUriType.mediaStream; - break; - case function: - UriResourceFunction uriFunction = (UriResourceFunction) secondLastPathSegment; - - EdmFunction function; - EdmFunctionImport functionImport = uriFunction.getFunctionImport(); - if (functionImport != null) { - List<EdmFunction> functions = functionImport.getUnboundFunctions(); - function = functions.get(0); - } else { - function = uriFunction.getFunction(); - } - - EdmTypeKind functionReturnTypeKind = function.getReturnType().getType().getKind(); - boolean isFunctionCollection = function.getReturnType().isCollection(); - idx = determineReturnType(functionReturnTypeKind, isFunctionCollection); - break; - case action: - UriResourceAction uriAction = (UriResourceAction) secondLastPathSegment; - EdmActionImport actionImport = uriAction.getActionImport(); - - EdmAction action; - if (actionImport != null) { - action = actionImport.getUnboundAction(); - } else { - action = uriAction.getAction(); - } - - EdmTypeKind actionReturnTypeKind = action.getReturnType().getType().getKind(); - boolean isActionCollection = action.getReturnType().isCollection(); - idx = determineReturnType(actionReturnTypeKind, isActionCollection); - - break; - case navigationProperty: - UriResourceNavigation uriNavigation = (UriResourceNavigation) secondLastPathSegment; - - if (uriNavigation.isCollection()) { - idx = RowIndexForUriType.entitySet; - } else { - idx = RowIndexForUriType.entity; - } - break; - case singleton: - UriResourceSingleton uriSingleton = (UriResourceSingleton) secondLastPathSegment; - EdmSingleton singleton = uriSingleton.getSingleton(); - EdmTypeKind singletonReturnTypeKind = singleton.getEntityType().getKind(); - idx = determineReturnType(singletonReturnTypeKind, false); - break; - default: - throw new UriValidationException("Unexpected kind in path segment before $value: " - + secondLastPathSegment.getKind(), UriValidationException.MessageKeys.UNALLOWED_KIND_BEFORE_VALUE, - secondLastPathSegment.toString()); - } - return idx; - } - - private RowIndexForUriType determineReturnType(final EdmTypeKind functionReturnTypeKind, - final boolean isCollection) throws UriValidationException { - RowIndexForUriType idx; - switch (functionReturnTypeKind) { - case COMPLEX: - idx = isCollection ? RowIndexForUriType.propertyComplexCollection : RowIndexForUriType.propertyComplex; - break; - case ENTITY: - idx = isCollection ? RowIndexForUriType.entitySet : RowIndexForUriType.entity; - break; - case PRIMITIVE: - case ENUM: - case DEFINITION: - idx = isCollection ? RowIndexForUriType.propertyPrimitiveCollection : RowIndexForUriType.propertyPrimitive; - break; - default: - throw new UriValidationException("Unsupported function return type: " + functionReturnTypeKind, - UriValidationException.MessageKeys.UNSUPPORTED_FUNCTION_RETURN_TYPE, functionReturnTypeKind.toString()); - } - return idx; - } - - private RowIndexForUriType rowIndexForRef(final UriInfo uriInfo, final UriResource lastPathSegment) - throws UriValidationException { - RowIndexForUriType idx; - int secondLastPathSegmentIndex = uriInfo.getUriResourceParts().size() - 2; - UriResource secondLastPathSegment = uriInfo.getUriResourceParts().get(secondLastPathSegmentIndex); - - if (secondLastPathSegment instanceof UriResourcePartTyped) { - idx = - ((UriResourcePartTyped) secondLastPathSegment).isCollection() ? RowIndexForUriType.references - : RowIndexForUriType.reference; - } else { - throw new UriValidationException("secondLastPathSegment not a class of UriResourcePartTyped: " - + lastPathSegment.getClass(), UriValidationException.MessageKeys.LAST_SEGMENT_NOT_TYPED, lastPathSegment - .toString()); - } - - return idx; - } - - private RowIndexForUriType rowIndexForPrimitiveProperty(final UriResource lastPathSegment) - throws UriValidationException { - RowIndexForUriType idx; - if (lastPathSegment instanceof UriResourcePartTyped) { - idx = - ((UriResourcePartTyped) lastPathSegment).isCollection() ? RowIndexForUriType.propertyPrimitiveCollection - : RowIndexForUriType.propertyPrimitive; - } else { - throw new UriValidationException("lastPathSegment not a class of UriResourcePartTyped: " - + lastPathSegment.getClass(), UriValidationException.MessageKeys.LAST_SEGMENT_NOT_TYPED, lastPathSegment - .toString()); - } - return idx; - } - - private RowIndexForUriType rowIndexForFunction(final UriResource lastPathSegment) throws UriValidationException { - RowIndexForUriType idx; - UriResourceFunction urf = (UriResourceFunction) lastPathSegment; - EdmReturnType rt = urf.getFunction().getReturnType(); - switch (rt.getType().getKind()) { - case ENTITY: - if (((EdmEntityType) rt.getType()).hasStream()) { - idx = RowIndexForUriType.mediaStream; - } else { - idx = rt.isCollection() ? RowIndexForUriType.entitySet : RowIndexForUriType.entity; - } - break; - case PRIMITIVE: - idx = rt.isCollection() ? RowIndexForUriType.propertyPrimitiveCollection : RowIndexForUriType.propertyPrimitive; - break; - case COMPLEX: - idx = rt.isCollection() ? RowIndexForUriType.propertyComplexCollection : RowIndexForUriType.propertyComplex; - break; - default: - throw new UriValidationException("Unsupported function return type: " + rt.getType().getKind(), - UriValidationException.MessageKeys.UNSUPPORTED_FUNCTION_RETURN_TYPE, - rt.getType().getKind().toString()); - } - - return idx; - } - - private RowIndexForUriType rowIndexForEntitySet(final UriResource lastPathSegment) throws UriValidationException { - RowIndexForUriType idx; - if (lastPathSegment instanceof UriResourcePartTyped) { - idx = - ((UriResourcePartTyped) lastPathSegment).isCollection() ? RowIndexForUriType.entitySet - : RowIndexForUriType.entity; - } else { - throw new UriValidationException("lastPathSegment not a class of UriResourcePartTyped: " - + lastPathSegment.getClass(), UriValidationException.MessageKeys.LAST_SEGMENT_NOT_TYPED, lastPathSegment - .toString()); - } - return idx; - } - - private RowIndexForUriType rowIndexForComplexProperty(final UriResource lastPathSegment) - throws UriValidationException { - RowIndexForUriType idx; - if (lastPathSegment instanceof UriResourcePartTyped) { - idx = - ((UriResourcePartTyped) lastPathSegment).isCollection() ? RowIndexForUriType.propertyComplexCollection - : RowIndexForUriType.propertyComplex; - } else { - throw new UriValidationException("lastPathSegment not a class of UriResourcePartTyped: " - + lastPathSegment.getClass(), UriValidationException.MessageKeys.LAST_SEGMENT_NOT_TYPED, lastPathSegment - .toString()); - } - return idx; - } - - private RowIndexForUriType rowIndexForAction(final UriResource lastPathSegment) throws UriValidationException { - RowIndexForUriType idx; - UriResourceAction ura = (UriResourceAction) lastPathSegment; - EdmReturnType rt = ura.getAction().getReturnType(); - switch (rt.getType().getKind()) { - case ENTITY: - if (((EdmEntityType) rt.getType()).hasStream()) { - idx = RowIndexForUriType.mediaStream; - } else { - idx = rt.isCollection() ? RowIndexForUriType.entitySet : RowIndexForUriType.entity; - } - break; - case PRIMITIVE: - idx = rt.isCollection() ? RowIndexForUriType.propertyPrimitiveCollection : RowIndexForUriType.propertyPrimitive; - break; - case COMPLEX: - idx = rt.isCollection() ? RowIndexForUriType.propertyComplexCollection : RowIndexForUriType.propertyComplex; - break; - default: - throw new UriValidationException("Unsupported action return type: " + rt.getType().getKind(), - UriValidationException.MessageKeys.UNSUPPORTED_ACTION_RETURN_TYPE, rt.getType().getKind().toString()); - } - - return idx; - } - - private RowIndexForUriType rowIndexForCount(final UriInfo uriInfo) throws UriValidationException { - - RowIndexForUriType idx; - int secondLastPathSegmentIndex = uriInfo.getUriResourceParts().size() - 2; - UriResource secondLastPathSegment = uriInfo.getUriResourceParts().get(secondLastPathSegmentIndex); - switch (secondLastPathSegment.getKind()) { - case entitySet: - case navigationProperty: - idx = RowIndexForUriType.entitySetCount; - break; - case complexProperty: - idx = RowIndexForUriType.propertyComplexCollectionCount; - break; - case primitiveProperty: - idx = RowIndexForUriType.propertyPrimitiveCollectionCount; - break; - case function: - UriResourceFunction uriFunction = (UriResourceFunction) secondLastPathSegment; - - EdmFunction function; - List<EdmFunction> functions; - EdmFunctionImport functionImport = uriFunction.getFunctionImport(); - if (functionImport != null) { - functions = functionImport.getUnboundFunctions(); - function = functions.get(0); - } else { - function = uriFunction.getFunction(); - } - - EdmTypeKind functionReturnTypeKind = function.getReturnType().getType().getKind(); - boolean isCollection = function.getReturnType().isCollection(); - idx = determineReturnType(functionReturnTypeKind, isCollection); - break; - default: - throw new UriValidationException("Illegal path part kind before $count: " + secondLastPathSegment.getKind(), - UriValidationException.MessageKeys.UNALLOWED_KIND_BEFORE_COUNT, secondLastPathSegment.toString()); - } - - return idx; - } - - private void validateQueryOptions(final UriInfo uriInfo) throws UriValidationException { - RowIndexForUriType row = rowIndexForUriType(uriInfo); - - for (SystemQueryOption option : uriInfo.getSystemQueryOptions()) { - ColumnIndex col = colIndex(option.getKind()); - - if (!decisionMatrix[row.getIndex()][col.getIndex()]) { - throw new UriValidationException("System query option not allowed: " + option.getName(), - UriValidationException.MessageKeys.SYSTEM_QUERY_OPTION_NOT_ALLOWED, option.getName()); - } - } - - } - - private void validateForHttpMethod(final UriInfo uriInfo, final HttpMethod httpMethod) throws UriValidationException { - RowIndexForHttpMethod row = rowIndexForHttpMethod(httpMethod); - - for (SystemQueryOption option : uriInfo.getSystemQueryOptions()) { - ColumnIndex col = colIndex(option.getKind()); - if (!decisionMatrixForHttpMethod[row.getIndex()][col.getIndex()]) { - throw new UriValidationException("System query option " + option.getName() + " not allowed for method " - + httpMethod, UriValidationException.MessageKeys.SYSTEM_QUERY_OPTION_NOT_ALLOWED_FOR_HTTP_METHOD, option - .getName(), httpMethod.toString()); - } - } - - } - - private RowIndexForHttpMethod rowIndexForHttpMethod(final HttpMethod httpMethod) throws UriValidationException { - RowIndexForHttpMethod idx; - - switch (httpMethod) { - case GET: - idx = RowIndexForHttpMethod.GET; - break; - case POST: - idx = RowIndexForHttpMethod.POST; - break; - case PUT: - idx = RowIndexForHttpMethod.PUT; - break; - case DELETE: - idx = RowIndexForHttpMethod.DELETE; - break; - case PATCH: - idx = RowIndexForHttpMethod.PATCH; - break; - default: - throw new UriValidationException("HTTP method not supported: " + httpMethod, - UriValidationException.MessageKeys.UNSUPPORTED_HTTP_METHOD, httpMethod.toString()); - } - - return idx; - } - - private void validateKeyPredicates(final UriInfo uriInfo) throws UriValidationException { - for (UriResource pathSegment : uriInfo.getUriResourceParts()) { - if (pathSegment.getKind() == UriResourceKind.entitySet) { - UriResourceEntitySet pathEntitySet = (UriResourceEntitySet) pathSegment; - List<UriParameter> keyPredicates = pathEntitySet.getKeyPredicates(); - - if (keyPredicates != null) { - - final List<String> keyPredicateNames = pathEntitySet.getEntityType().getKeyPredicateNames(); - HashMap<String, EdmKeyPropertyRef> edmKeys = new HashMap<String, EdmKeyPropertyRef>(); - for (EdmKeyPropertyRef key : pathEntitySet.getEntityType().getKeyPropertyRefs()) { - edmKeys.put(key.getKeyPropertyName(), key); - final String alias = key.getAlias(); - if (alias != null) { - edmKeys.put(alias, key); - } - } - - for (UriParameter keyPredicate : keyPredicates) { - final String name = keyPredicate.getName(); - final String alias = keyPredicate.getAlias(); - final String value = alias == null ? - keyPredicate.getText() : - uriInfo.getValueForAlias(alias); - - EdmKeyPropertyRef edmKey = edmKeys.get(name); - if (edmKey == null) { - if (keyPredicateNames.contains(name)) { - throw new UriValidationException("Double key property: " + name, - UriValidationException.MessageKeys.DOUBLE_KEY_PROPERTY, name); - } else { - throw new UriValidationException("Unknown key property: " + name, - UriValidationException.MessageKeys.INVALID_KEY_PROPERTY, name); - } - } - - final EdmProperty property = edmKey.getProperty(); - final EdmPrimitiveType edmPrimitiveType = (EdmPrimitiveType) property.getType(); - try { - if (!edmPrimitiveType.validate(edmPrimitiveType.fromUriLiteral(value), - property.isNullable(), property.getMaxLength(), - property.getPrecision(), property.getScale(), property.isUnicode())) { - // TODO: Check exception here - throw new UriValidationException("PrimitiveTypeException", - UriValidationException.MessageKeys.INVALID_KEY_PROPERTY, name); - } - } catch (EdmPrimitiveTypeException e) { - // TODO: Check exception here - throw new UriValidationException("PrimitiveTypeException", e, - UriValidationException.MessageKeys.INVALID_KEY_PROPERTY, name); - } - - edmKeys.remove(name); - edmKeys.remove(alias); - } - } - } - } - } - - private void validatePropertyOperations(final UriInfo uriInfo, final HttpMethod method) - throws UriValidationException { - final List<UriResource> parts = uriInfo.getUriResourceParts(); - final UriResource last = parts.size() > 0 ? parts.get(parts.size() - 1) : null; - final UriResource previous = parts.size() > 1 ? parts.get(parts.size() - 2) : null; - if (last != null - && (last.getKind() == UriResourceKind.primitiveProperty - || last.getKind() == UriResourceKind.complexProperty - || last.getKind() == UriResourceKind.value && previous.getKind() == UriResourceKind.primitiveProperty)) { - final EdmProperty property = ((UriResourceProperty) - (last.getKind() == UriResourceKind.value ? previous : last)).getProperty(); - if (method == HttpMethod.PATCH && property.isCollection()) { - throw new UriValidationException("Attempt to patch collection property.", - UriValidationException.MessageKeys.UNSUPPORTED_HTTP_METHOD, method.toString()); - } - if (method == HttpMethod.DELETE && property.isNullable() != null && !property.isNullable()) { - throw new UriValidationException("Attempt to delete non-nullable property.", - UriValidationException.MessageKeys.UNSUPPORTED_HTTP_METHOD, method.toString()); - } - } - } -}
http://git-wip-us.apache.org/repos/asf/olingo-odata4/blob/f7a7b484/lib/server-core/src/main/resources/server-core-exceptions-i18n.properties ---------------------------------------------------------------------- diff --git a/lib/server-core/src/main/resources/server-core-exceptions-i18n.properties b/lib/server-core/src/main/resources/server-core-exceptions-i18n.properties deleted file mode 100644 index 98259b6..0000000 --- a/lib/server-core/src/main/resources/server-core-exceptions-i18n.properties +++ /dev/null @@ -1,140 +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. -#------------------------------------------------------------------------------- -# Basic Apache Olingo exception messages -# -ODataHandlerException.AMBIGUOUS_XHTTP_METHOD=x-http-method header '%1$s' and x-http-method-override header '%2$s' are not the same. -ODataHandlerException.INVALID_HTTP_METHOD=Invalid HTTP method given: '%1$s'. -ODataHandlerException.HTTP_METHOD_NOT_ALLOWED=HTTP method '%1$s' not allowed for this resource. -ODataHandlerException.PROCESSOR_NOT_IMPLEMENTED=No processor for interface '%1$s' registered. -ODataHandlerException.FUNCTIONALITY_NOT_IMPLEMENTED=The requested functionality has not been implemented (yet). -ODataHandlerException.ODATA_VERSION_NOT_SUPPORTED=OData version '%1$s' is not supported. -ODataHandlerException.UNSUPPORTED_CONTENT_TYPE=The content type '%1$s' is not supported for this request. - -UriParserSyntaxException.MUST_BE_LAST_SEGMENT=The segment '%1$s' must be the last segment. -UriParserSyntaxException.UNKNOWN_SYSTEM_QUERY_OPTION=The system query option '%1$s' is not defined. -UriParserSyntaxException.DOUBLE_SYSTEM_QUERY_OPTION=The system query option '%1$s' can be specified only once. -UriParserSyntaxException.WRONG_VALUE_FOR_SYSTEM_QUERY_OPTION=The system query option '%1$s' has the not-allowed value '%2$s'. -UriParserSyntaxException.WRONG_VALUE_FOR_SYSTEM_QUERY_OPTION_FORMAT=The system query option '$format' must be either 'json', 'xml', 'atom', or a valid content type; the value '%1$s' is neither. -UriParserSyntaxException.SYSTEM_QUERY_OPTION_LEVELS_NOT_ALLOWED_HERE=The system query option '$levels' is not allowed here. -UriParserSyntaxException.SYNTAX=The URI is malformed. - -UriParserSemanticException.FUNCTION_NOT_FOUND=The function import '%1$s' has no function with parameters '%2$s'. -UriParserSemanticException.RESOURCE_PART_ONLY_FOR_TYPED_PARTS='%1$s' is only allowed for typed parts. -UriParserSemanticException.RESOURCE_PART_MUST_BE_PRECEDED_BY_STRUCTURAL_TYPE=The resource part '%1$s' must be preceded by a structural type. -UriParserSemanticException.PROPERTY_AFTER_COLLECTION=The property '%1$s' must not follow a collection. -UriParserSemanticException.PROPERTY_NOT_IN_TYPE=The type '%1$s' has no property '%2$s'. -UriParserSemanticException.EXPRESSION_PROPERTY_NOT_IN_TYPE=The property '%2$s', used in a query expression, is not defined in type '%1$s'. -UriParserSemanticException.UNKNOWN_PROPERTY_TYPE=The type of the property '%1$s' is unknown. -UriParserSemanticException.INCOMPATIBLE_TYPE_FILTER=The type filter '%1$s' is incompatible. -UriParserSemanticException.TYPE_FILTER_NOT_CHAINABLE=The type filter '%2$s' can not be chained with '%1$s'. -UriParserSemanticException.PREVIOUS_PART_NOT_TYPED=The previous part of the type filter '%1$s' is not typed. -UriParserSemanticException.FUNCTION_PARAMETERS_EXPECTED=Function parameters expected for type '%1$s'. -UriParserSemanticException.UNKNOWN_PART=The part '%1$s' is not defined. -UriParserSemanticException.ONLY_FOR_TYPED_PARTS='%1$s' is only allowed for typed parts. -UriParserSemanticException.UNKNOWN_ENTITY_TYPE=The entity type '%1$s' is not defined. -UriParserSemanticException.ONLY_FOR_COLLECTIONS='%1$s' is only allowed for collections. -UriParserSemanticException.ONLY_FOR_ENTITY_TYPES='%1$s' is only allowed for entity types. -UriParserSemanticException.ONLY_FOR_STRUCTURAL_TYPES='%1$s' is only allowed for structural types. -UriParserSemanticException.ONLY_FOR_TYPED_PROPERTIES='%1$s' is only allowed for typed properties. -UriParserSemanticException.INVALID_KEY_VALUE=The key value '%1$s' is invalid. -UriParserSemanticException.PARAMETERS_LIST_ONLY_FOR_TYPED_PARTS=A list of parameters is only allowed for typed parts. -UriParserSemanticException.WRONG_NUMBER_OF_KEY_PROPERTIES=There are %2$s key properties instead of the expected %1$s. -UriParserSemanticException.NOT_ENOUGH_REFERENTIAL_CONSTRAINTS=There are not enough referential constraints. -UriParserSemanticException.KEY_NOT_ALLOWED=A key is not allowed. -UriParserSemanticException.RESOURCE_PATH_NOT_TYPED=The resource path is not typed. -UriParserSemanticException.ONLY_SIMPLE_AND_COMPLEX_PROPERTIES_IN_SELECT=Only simple and complex properties are allowed in selection. -UriParserSemanticException.COMPLEX_PROPERTY_OF_ENTITY_TYPE_EXPECTED=A complex property of an entity type is expected. -UriParserSemanticException.NOT_FOR_ENTITY_TYPE=Not allowed for entity type. -UriParserSemanticException.PREVIOUS_PART_TYPED=The previous part is typed. -UriParserSemanticException.RESOURCE_NOT_FOUND=Cannot find EntitySet, Singleton, ActionImport or FunctionImport with name '%1$s'. - -UriValidationException.UNSUPPORTED_QUERY_OPTION=The query option '%1$s' is not supported. -UriValidationException.UNSUPPORTED_URI_KIND=The URI kind '%1$s' is not supported. -UriValidationException.UNSUPPORTED_URI_RESOURCE_KIND=The URI resource kind '%1$s' is not supported. -UriValidationException.UNSUPPORTED_FUNCTION_RETURN_TYPE=The function return type '%1$s' is not supported. -UriValidationException.UNSUPPORTED_ACTION_RETURN_TYPE=The action return type '%1$s' is not supported. -UriValidationException.UNSUPPORTED_HTTP_METHOD=The HTTP method '%1$s' is not supported. -UriValidationException.SYSTEM_QUERY_OPTION_NOT_ALLOWED=The system query option '%1$s' is not allowed. -UriValidationException.SYSTEM_QUERY_OPTION_NOT_ALLOWED_FOR_HTTP_METHOD=The system query option '%1$s' is not allowed for HTTP method '%2$s'. -UriValidationException.INVALID_KEY_PROPERTY=The key property '%1$s' is invalid. -UriValidationException.DOUBLE_KEY_PROPERTY=The key property '%1$s' has been specified twice. -UriValidationException.LAST_SEGMENT_NOT_TYPED=The last segment '%1$s' is not typed. -UriValidationException.SECOND_LAST_SEGMENT_NOT_TYPED=The second last segment '%1$s' is not typed. -UriValidationException.UNALLOWED_KIND_BEFORE_VALUE=The kind '%1$s' is not allowed before '$value'. -UriValidationException.UNALLOWED_KIND_BEFORE_COUNT=The kind '%1$s' is not allowed before '$count'. - -ContentNegotiatorException.WRONG_CHARSET_IN_HEADER=The HTTP header '%1$s' with value '%2$s' contains an invalid character-set specification. -ContentNegotiatorException.UNSUPPORTED_CONTENT_TYPES=The content-type range '%1$s' is not supported. -ContentNegotiatorException.UNSUPPORTED_CONTENT_TYPE=The content type '%1$s' is not supported. -ContentNegotiatorException.NO_CONTENT_TYPE_SUPPORTED=No content type has been specified as supported. -ContentNegotiatorException.UNSUPPORTED_FORMAT_OPTION=The $format option '%1$s' is not supported. - -SerializerException.NOT_IMPLEMENTED=The requested serialization method has not been implemented yet. -SerializerException.UNSUPPORTED_FORMAT=The format '%1$s' is not supported. -SerializerException.JSON_METADATA=The metadata document cannot be provided in JSON format. -SerializerException.IO_EXCEPTION=An I/O exception occurred. -SerializerException.NULL_INPUT=The input 'null' is not allowed here. -SerializerException.NO_CONTEXT_URL=No context URL has been provided. -SerializerException.UNSUPPORTED_PROPERTY_TYPE=The type of the property '%1$s' is not yet supported. -SerializerException.INCONSISTENT_PROPERTY_TYPE=An inconsistency has been detected in the type definition of property '%1$s'. -SerializerException.MISSING_PROPERTY=The non-nullable property '%1$s' is missing. -SerializerException.WRONG_PROPERTY_VALUE=The value '%2$s' is not valid for property '%1$s'. -SerializerException.WRONG_PRIMITIVE_VALUE=The value '%2$s' is not valid for the primitive type '%1$s' and the given facets. - -DeserializerException.NOT_IMPLEMENTED=The requested deserialization method has not been implemented yet. -DeserializerException.IO_EXCEPTION=An I/O exception occurred. -DeserializerException.UNSUPPORTED_FORMAT=The format '%1$s' is not supported. -DeserializerException.JSON_SYNTAX_EXCEPTION=The syntax of the JSON document is not valid. -DeserializerException.INVALID_NULL_PROPERTY=The property '%1$s' must not be null. -DeserializerException.UNKOWN_CONTENT='%1$s' can not be mapped as a property or an annotation. -DeserializerException.INVALID_VALUE_FOR_PROPERTY=Invalid value for property '%1$s'. -DeserializerException.INVALID_TYPE_FOR_PROPERTY=Invalid JSON type for property '%1$s'. -DeserializerException.VALUE_ARRAY_NOT_PRESENT=Cannot find the value array. A collection needs at least an empty array. -DeserializerException.VALUE_TAG_MUST_BE_AN_ARRAY=Invalid JSON type for the value tag. Must be an Array. -DeserializerException.INVALID_ENTITY=Invalid JSON type for an entity. Must be a JSON object. -DeserializerException.INVALID_VALUE_FOR_NAVIGATION_PROPERTY=Invalid value for navigation property '%1$s'. Must be an array for collections or for an entity either null or an object. -DeserializerException.DUPLICATE_PROPERTY="Edm Properties must not appear twice within the same object." -DeserializerException.DUPLICATE_JSON_PROPERTY="JSON properties must not appear twice within the same object." -DeserializerException.UNKNOWN_PRIMITIVE_TYPE=Unknown primitive type '%1$s' for property '%2$s'; -DeserializerException.NAVIGATION_PROPERTY_NOT_FOUND=Can`t find navigation property with name: '%1$s'. -DeserializerException.INVALID_ANNOTATION_TYPE=The annotation '%1$s' has the wrong JSON type. - -BatchDeserializerException.INVALID_BOUNDARY=Invalid boundary at line '%1$s'. -BatchDeserializerException.INVALID_CHANGESET_METHOD=Invalid method: a ChangeSet cannot contain retrieve requests at line '%1$s'. -BatchDeserializerException.INVALID_CONTENT=Retrieve requests must not contain any body content '%1$s'. -BatchDeserializerException.INVALID_CONTENT_LENGTH=Invalid content length: content length have to be an integer and positive at line '%1$s'. -BatchDeserializerException.INVALID_CONTENT_TRANSFER_ENCODING=The Content-Transfer-Encoding should be binary: line '%1$s'. -BatchDeserializerException.INVALID_CONTENT_TYPE=Content-Type should be '%1$s'. -BatchDeserializerException.INVALID_HEADER=Invalid header: '%1$s' at line '%2$s'. -BatchDeserializerException.INVALID_HTTP_VERSION=Invalid HTTP version: The version have to be HTTP/1.1 at line '%1$s'. -BatchDeserializerException.INVALID_METHOD=Invalid HTTP method at line '%1$s'. -BatchDeserializerException.INVALID_QUERY_OPERATION_METHOD=Invalid method: a query operation can only contain retrieve requests at line '%1$s'. -BatchDeserializerException.INVALID_STATUS_LINE=Invalid HTTP status line at line '%1$s'. -BatchDeserializerException.INVALID_URI=Invalid URI at line '%1$s'. -BatchDeserializerException.FORBIDDEN_HEADER=Forbidden header at line '%1$s'. -BatchDeserializerException.MISSING_BLANK_LINE=Missing blank line at line '%1$s'. -BatchDeserializerException.MISSING_BOUNDARY_DELIMITER=Missing boundary delimiter at line '%1$s'. -BatchDeserializerException.MISSING_CLOSE_DELIMITER=Missing close delimiter at line '%1$s'. -BatchDeserializerException.MISSING_CONTENT_ID=Missing content-id at line '%1$s'. -BatchDeserializerException.MISSING_CONTENT_TRANSFER_ENCODING=Missing content transfer encoding at line '%1$s'. -BatchDeserializerException.MISSING_CONTENT_TYPE=Missing content-type at line '%1$s'. -BatchDeserializerException.MISSING_MANDATORY_HEADER=Missing mandatory header at line '%1$s'. -BatchDeserializerException.INVALID_BASE_URI=The base URI do not match the service base URI at line '%1$s'. - -BatchSerializerExecption.MISSING_CONTENT_ID=Each request within a change set required exactly one content id. \ No newline at end of file http://git-wip-us.apache.org/repos/asf/olingo-odata4/blob/f7a7b484/lib/server-core/src/test/java/org/apache/olingo/server/core/ContentNegotiatorTest.java ---------------------------------------------------------------------- diff --git a/lib/server-core/src/test/java/org/apache/olingo/server/core/ContentNegotiatorTest.java b/lib/server-core/src/test/java/org/apache/olingo/server/core/ContentNegotiatorTest.java deleted file mode 100644 index 972432d..0000000 --- a/lib/server-core/src/test/java/org/apache/olingo/server/core/ContentNegotiatorTest.java +++ /dev/null @@ -1,212 +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.server.core; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyListOf; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.apache.olingo.commons.api.edm.constants.ODataServiceVersion; -import org.apache.olingo.commons.api.format.ContentType; -import org.apache.olingo.commons.api.format.ODataFormat; -import org.apache.olingo.commons.api.http.HttpContentType; -import org.apache.olingo.commons.api.http.HttpHeader; -import org.apache.olingo.server.api.ODataRequest; -import org.apache.olingo.server.api.serializer.CustomContentTypeSupport; -import org.apache.olingo.server.api.serializer.RepresentationType; -import org.apache.olingo.server.api.uri.queryoption.FormatOption; -import org.junit.Test; - -public class ContentNegotiatorTest { - - static final private String ACCEPT_CASE_MIN = "application/json;odata.metadata=minimal"; - static final private String ACCEPT_CASE_MIN_UTF8 = "application/json;charset=UTF-8;odata.metadata=minimal"; - static final private String ACCEPT_CASE_FULL = "application/json;odata.metadata=full"; - static final private String ACCEPT_CASE_NONE = "application/json;odata.metadata=none"; - static final private String ACCEPT_CASE_JSONQ = "application/json;q=0.2"; - static final private String ACCEPT_CASE_XML = HttpContentType.APPLICATION_XML; - static final private String ACCEPT_CASE_WILDCARD1 = HttpContentType.WILDCARD; - static final private String ACCEPT_CASE_WILDCARD2 = "application/*"; - - //@formatter:off (Eclipse formatter) - //CHECKSTYLE:OFF (Maven checkstyle) - - String[][] casesServiceDocument = { - /* expected $format accept modified content types */ - { ACCEPT_CASE_MIN, null, null, null }, - { ACCEPT_CASE_MIN, "json", null, null }, - { ACCEPT_CASE_MIN, "json", ACCEPT_CASE_JSONQ, null }, - { ACCEPT_CASE_NONE, ACCEPT_CASE_NONE, null, null }, - { "a/a", "a/a", null, "a/a" }, - { ACCEPT_CASE_MIN, null, ACCEPT_CASE_JSONQ, null }, - { ACCEPT_CASE_MIN, null, ACCEPT_CASE_WILDCARD1, null }, - { ACCEPT_CASE_MIN, null, ACCEPT_CASE_WILDCARD2, null }, - { ACCEPT_CASE_MIN, null, null, ACCEPT_CASE_MIN }, - { "a/a", "a/a", null, "a/a,b/b" }, - { "a/a;x=y", "a/a", ACCEPT_CASE_WILDCARD1, "a/a;x=y" }, - { "a/a;v=w;x=y", null, "a/a;x=y", "a/a;b=c,a/a;v=w;x=y" }, - { "a/a;v=w;x=y", "a/a;x=y", null, "a/a;b=c,a/a;v=w;x=y" }, - { ACCEPT_CASE_MIN, "json", ACCEPT_CASE_MIN, null }, - { ACCEPT_CASE_FULL, null, ACCEPT_CASE_FULL, ACCEPT_CASE_FULL }, - { ACCEPT_CASE_MIN_UTF8, null, ACCEPT_CASE_MIN_UTF8, null } - }; - - String[][] casesMetadata = { - /* expected $format accept modified content types */ - { ACCEPT_CASE_XML, null, null, null }, - { ACCEPT_CASE_XML, "xml", null, null }, - { ACCEPT_CASE_XML, "xml", ACCEPT_CASE_XML, null }, - { "a/a", "a/a", null, "a/a" }, - { ACCEPT_CASE_XML, null, ACCEPT_CASE_XML, null }, - { ACCEPT_CASE_XML, null, ACCEPT_CASE_WILDCARD1, null }, - { ACCEPT_CASE_XML, null, ACCEPT_CASE_WILDCARD2, null }, - { "a/a", "a/a", null, "a/a,b/b" }, - { "a/a;x=y", "a/a", ACCEPT_CASE_WILDCARD1, "a/a;x=y" } - }; - - String[][] casesFail = { - /* expected $format accept modified content types */ - { null, "xxx/yyy", null, null }, - { null, "a/a", null, "b/b" }, - { null, "a/a;x=y", null, "a/a;v=w" }, - { null, null, "a/a;x=y", "a/a;v=w" }, - { null, "atom", null, null }, // not yet supported - { null, null, ACCEPT_CASE_FULL, null }, // not yet supported - { null, "a/b;charset=ISO-8859-1", null, "a/b" }, - { null, null, "a/b;charset=ISO-8859-1", "a/b" }, - { null, null, null, "text/plain" } - }; - //CHECKSTYLE:ON - //@formatter:on - - @Test - public void serviceDocumentSingleCase() throws Exception { - testContentNegotiation( - new String[] { ACCEPT_CASE_MIN_UTF8, null, ACCEPT_CASE_MIN_UTF8, null }, - RepresentationType.SERVICE); - } - - @Test - public void serviceDocument() throws Exception { - for (String[] useCase : casesServiceDocument) { - testContentNegotiation(useCase, RepresentationType.SERVICE); - } - } - - @Test - public void metadataSingleCase() throws Exception { - testContentNegotiation(new String[] { ACCEPT_CASE_XML, null, null, null }, RepresentationType.METADATA); - } - - @Test(expected = ContentNegotiatorException.class) - public void metadataJsonFail() throws Exception { - testContentNegotiation(new String[] { null, "json", null, null }, RepresentationType.METADATA); - } - - @Test - public void metadata() throws Exception { - for (String[] useCase : casesMetadata) { - testContentNegotiation(useCase, RepresentationType.METADATA); - } - } - - @Test - public void entityCollectionFail() throws Exception { - for (String[] useCase : casesFail) { - try { - testContentNegotiation(useCase, RepresentationType.COLLECTION_ENTITY); - fail("Exception expected for '" + useCase[1] + '|' + useCase[2] + '|' + useCase[3] + "'!"); - } catch (final ContentNegotiatorException e) {} - } - } - - @Test - public void checkSupport() throws Exception { - ContentNegotiator.checkSupport(ODataFormat.JSON.getContentType(ODataServiceVersion.V40), null, - RepresentationType.ENTITY); - ContentNegotiator.checkSupport(ContentType.TEXT_PLAIN, null, RepresentationType.VALUE); - try { - ContentNegotiator.checkSupport(ContentType.APPLICATION_SVG_XML, null, RepresentationType.ENTITY); - fail("Exception expected."); - } catch (final ContentNegotiatorException e) { - assertEquals(ContentNegotiatorException.MessageKeys.UNSUPPORTED_CONTENT_TYPE, e.getMessageKey()); - } - - ContentNegotiator.checkSupport(ContentType.create("a/b"), createCustomContentTypeSupport("a/b"), - RepresentationType.ENTITY); - ContentNegotiator.checkSupport(ContentType.create("a/b", "c=d"), createCustomContentTypeSupport("a/b"), - RepresentationType.ENTITY); - try { - ContentNegotiator.checkSupport(ContentType.create("a/b"), createCustomContentTypeSupport("a/b;c=d"), - RepresentationType.ENTITY); - fail("Exception expected."); - } catch (final ContentNegotiatorException e) { - assertEquals(ContentNegotiatorException.MessageKeys.UNSUPPORTED_CONTENT_TYPE, e.getMessageKey()); - } - } - - private void testContentNegotiation(final String[] useCase, final RepresentationType representationType) - throws ContentNegotiatorException { - - FormatOption formatOption = null; - if (useCase[1] != null) { - formatOption = mock(FormatOption.class); - when(formatOption.getFormat()).thenReturn(useCase[1]); - } - - ODataRequest request = new ODataRequest(); - if (useCase[2] != null) { - request.addHeader(HttpHeader.ACCEPT, Arrays.asList(useCase[2])); - } - - final CustomContentTypeSupport customContentTypeSupport = useCase[3] == null ? null : - createCustomContentTypeSupport(useCase[3]); - - final ContentType requestedContentType = ContentNegotiator.doContentNegotiation( - formatOption, request, customContentTypeSupport, representationType); - - assertNotNull(requestedContentType); - if (useCase[0] != null) { - assertEquals(ContentType.create(useCase[0]), requestedContentType); - } - } - - private CustomContentTypeSupport createCustomContentTypeSupport(final String contentTypeString) { - final String[] contentTypes = contentTypeString.split(","); - - List<ContentType> types = new ArrayList<ContentType>(); - for (int i = 0; i < contentTypes.length; i++) { - types.add(ContentType.create(contentTypes[i])); - } - - CustomContentTypeSupport customContentTypeSupport = mock(CustomContentTypeSupport.class); - when(customContentTypeSupport.modifySupportedContentTypes( - anyListOf(ContentType.class), any(RepresentationType.class))) - .thenReturn(types); - return customContentTypeSupport; - } -} http://git-wip-us.apache.org/repos/asf/olingo-odata4/blob/f7a7b484/lib/server-core/src/test/java/org/apache/olingo/server/core/ODataHttpHandlerImplTest.java ---------------------------------------------------------------------- diff --git a/lib/server-core/src/test/java/org/apache/olingo/server/core/ODataHttpHandlerImplTest.java b/lib/server-core/src/test/java/org/apache/olingo/server/core/ODataHttpHandlerImplTest.java deleted file mode 100644 index 8200c32..0000000 --- a/lib/server-core/src/test/java/org/apache/olingo/server/core/ODataHttpHandlerImplTest.java +++ /dev/null @@ -1,169 +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.server.core; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import javax.servlet.http.HttpServletRequest; - -import org.apache.olingo.commons.api.http.HttpMethod; -import org.apache.olingo.server.api.ODataRequest; -import org.apache.olingo.server.api.ODataTranslatedException; -import org.junit.Test; - -public class ODataHttpHandlerImplTest { - - @Test - public void extractMethod() throws Exception { - String[][] mm = { - { "GET", null, null, "GET" }, - { "GET", "xxx", "yyy", "GET" }, - { "PUT", "xxx", "yyy", "PUT" }, - { "DELETE", "xxx", "yyy", "DELETE" }, - { "PATCH", "xxx", "yyy", "PATCH" }, - - { "POST", null, null, "POST" }, - { "POST", null, "GET", "GET" }, - { "POST", null, "PATCH", "PATCH" }, - - { "POST", "GET", null, "GET" }, - { "POST", "PATCH", null, "PATCH" }, - - { "POST", "GET", "GET", "GET" }, - }; - - for (String[] m : mm) { - - HttpServletRequest hr = mock(HttpServletRequest.class); - - when(hr.getMethod()).thenReturn(m[0]); - when(hr.getHeader("X-HTTP-Method")).thenReturn(m[1]); - when(hr.getHeader("X-HTTP-Method-Override")).thenReturn(m[2]); - - ODataRequest odr = new ODataRequest(); - ODataHttpHandlerImpl.extractMethod(odr, hr); - - assertEquals(HttpMethod.valueOf(m[3]), odr.getMethod()); - } - } - - @Test - public void extractMethodFail() throws Exception { - String[][] mm = { - { "POST", "bla", null }, - { "POST", "PUT", "PATCH" }, - { "OPTIONS", null, null }, - { "HEAD", null, null }, - }; - - for (String[] m : mm) { - - HttpServletRequest hr = mock(HttpServletRequest.class); - - when(hr.getMethod()).thenReturn(m[0]); - when(hr.getHeader("X-HTTP-Method")).thenReturn(m[1]); - when(hr.getHeader("X-HTTP-Method-Override")).thenReturn(m[2]); - - ODataRequest odr = new ODataRequest(); - try { - ODataHttpHandlerImpl.extractMethod(odr, hr); - fail(); - } catch (ODataTranslatedException e) {} - } - } - - @Test - public void extractUri() { - - //@formatter:off (Eclipse formatter) - //CHECKSTYLE:OFF (Maven checkstyle) - String [][] uris = { - /* 0: host 1: cp 2: sp 3: sr 4: od 5: qp 6: spl */ - { "http://localhost", "", "", "", "", "", "0"}, - { "http://localhost", "", "", "", "/", "", "0"}, - { "http://localhost", "", "", "", "/od", "", "0"}, - { "http://localhost", "", "", "", "/od/", "", "0"}, - - { "http://localhost", "/cp", "", "", "", "", "0"}, - { "http://localhost", "/cp", "", "", "/", "", "0"}, - { "http://localhost", "/cp", "", "", "/od", "", "0"}, - { "http://localhost", "", "/sp", "", "", "", "0"}, - { "http://localhost", "", "/sp", "", "/", "", "0"}, - { "http://localhost", "", "/sp", "", "/od", "", "0"}, - { "http://localhost", "", "", "/sr", "", "", "1"}, - { "http://localhost", "", "", "/sr", "/", "", "1"}, - { "http://localhost", "", "", "/sr", "/od", "", "1"}, - { "http://localhost", "", "", "/sr/sr", "", "", "2"}, - { "http://localhost", "", "", "/sr/sr", "/", "", "2"}, - { "http://localhost", "", "", "/sr/sr", "/od", "", "2"}, - - { "http://localhost", "/cp", "/sp", "", "", "", "0"}, - { "http://localhost", "/cp", "/sp", "", "/", "", "0"}, - { "http://localhost", "/cp", "/sp", "", "/od", "", "0"}, - { "http://localhost", "/cp", "", "/sr", "/", "", "1"}, - { "http://localhost", "/cp", "", "/sr", "/od", "", "1"}, - { "http://localhost", "", "/sp", "/sr", "", "", "1"}, - { "http://localhost", "", "/sp", "/sr", "/", "", "1"}, - { "http://localhost", "", "/sp", "/sr", "/od", "", "1"}, - { "http://localhost", "/cp", "/sp", "/sr", "", "", "1"}, - { "http://localhost", "/cp", "/sp", "/sr", "/", "", "1"}, - { "http://localhost", "/cp", "/sp", "/sr", "/od", "", "1"}, - - { "http://localhost", "", "", "", "", "qp", "0"}, - { "http://localhost", "", "", "", "/", "qp", "0"}, - { "http://localhost", "/cp", "/sp", "/sr", "/od", "qp", "1"}, - - { "http://localhost:8080", "/c%20p", "/s%20p", "/s%20r", "/o%20d", "p+q", "1"}, - }; - //@formatter:on - // CHECKSTYLE:on - - for (String[] p : uris) { - HttpServletRequest hr = mock(HttpServletRequest.class); - - String requestUrl = p[0] + p[1] + p[2] + p[3] + p[4]; - String requestUri = p[1] + p[2] + p[3] + p[4]; - String queryString = p[5].isEmpty() ? null : p[5]; - - when(hr.getRequestURL()).thenReturn(new StringBuffer(requestUrl)); - when(hr.getRequestURI()).thenReturn(requestUri); - when(hr.getQueryString()).thenReturn(queryString); - when(hr.getContextPath()).thenReturn(p[1]); - when(hr.getServletPath()).thenReturn(p[2]); - - ODataRequest odr = new ODataRequest(); - ODataHttpHandlerImpl.extractUri(odr, hr, Integer.parseInt(p[6])); - - String rawBaseUri = p[0] + p[1] + p[2] + p[3]; - String rawODataPath = p[4]; - String rawQueryPath = "".equals(p[5]) ? null : p[5]; - String rawRequestUri = requestUrl + (queryString == null ? "" : "?" + queryString); - String rawServiceResolutionUri = "".equals(p[3]) ? null : p[3]; - - assertEquals(rawBaseUri, odr.getRawBaseUri()); - assertEquals(rawODataPath, odr.getRawODataPath()); - assertEquals(rawQueryPath, odr.getRawQueryPath()); - assertEquals(rawRequestUri, odr.getRawRequestUri()); - assertEquals(rawServiceResolutionUri, odr.getRawServiceResolutionUri()); - } - } -} http://git-wip-us.apache.org/repos/asf/olingo-odata4/blob/f7a7b484/lib/server-core/src/test/java/org/apache/olingo/server/core/TranslatedExceptionSubclassesTest.java ---------------------------------------------------------------------- diff --git a/lib/server-core/src/test/java/org/apache/olingo/server/core/TranslatedExceptionSubclassesTest.java b/lib/server-core/src/test/java/org/apache/olingo/server/core/TranslatedExceptionSubclassesTest.java deleted file mode 100644 index 5460d9f..0000000 --- a/lib/server-core/src/test/java/org/apache/olingo/server/core/TranslatedExceptionSubclassesTest.java +++ /dev/null @@ -1,103 +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.server.core; - -import org.apache.olingo.server.api.ODataTranslatedException; -import org.apache.olingo.server.api.serializer.SerializerException; -import org.apache.olingo.server.core.uri.parser.UriParserSemanticException; -import org.apache.olingo.server.core.uri.parser.UriParserSyntaxException; -import org.apache.olingo.server.core.uri.validator.UriValidationException; -import org.junit.Assert; -import org.junit.Test; - -import java.io.IOException; -import java.lang.reflect.Constructor; -import java.util.Formatter; -import java.util.Locale; -import java.util.Properties; -import java.util.UUID; - -/** - * Generic test for all exceptions which inherit from ODataTranslatedException - * if their MessageKeys are available in the resource bundle and the parameters are replaced. - */ -public class TranslatedExceptionSubclassesTest { - - private final Properties properties; - - public TranslatedExceptionSubclassesTest() throws IOException { - properties = new Properties(); - properties.load(Thread.currentThread().getContextClassLoader() - .getResourceAsStream("server-core-exceptions-i18n.properties")); - Locale.setDefault(Locale.ENGLISH); - } - - @Test - public void messageKeysValid() throws Exception { - testException(ODataHandlerException.class, ODataHandlerException.MessageKeys.values()); - testException(UriParserSemanticException.class, UriParserSemanticException.MessageKeys.values()); - testException(UriParserSyntaxException.class, UriParserSyntaxException.MessageKeys.values()); - testException(ContentNegotiatorException.class, ContentNegotiatorException.MessageKeys.values()); - testException(SerializerException.class, SerializerException.MessageKeys.values()); - testException(UriValidationException.class, UriValidationException.MessageKeys.values()); - testException(UriParserSyntaxException.class, UriParserSyntaxException.MessageKeys.values()); - } - - private void testException(final Class<? extends ODataTranslatedException> clazz, - final ODataTranslatedException.MessageKey[] messageKeys) throws Exception { - - for (ODataTranslatedException.MessageKey messageKey : messageKeys) { - String propKey = clazz.getSimpleName() + "." + messageKey.toString(); - String value = properties.getProperty(propKey); - Assert.assertNotNull("No value found for message key '" + propKey + "'", value); - // - int paraCount = countParameters(value); - Constructor<? extends ODataTranslatedException> ctor = - clazz.getConstructor(String.class, ODataTranslatedException.MessageKey.class, String[].class); - String[] paras = new String[paraCount]; - for (int i = 0; i < paras.length; i++) { - paras[i] = "470" + i; - } - String developerMessage = UUID.randomUUID().toString(); - ODataTranslatedException e = ctor.newInstance(developerMessage, messageKey, paras); - try { - throw e; - } catch (ODataTranslatedException translatedException) { - Formatter formatter = new Formatter(); - String formattedValue = formatter.format(value, (Object[]) paras).toString(); - formatter.close(); - Assert.assertEquals(formattedValue, translatedException.getTranslatedMessage(null).getMessage()); - Assert.assertEquals(formattedValue, translatedException.getLocalizedMessage()); - Assert.assertEquals(developerMessage, translatedException.getMessage()); - } - } - } - - - private int countParameters(String value) { - char[] chars = value.toCharArray(); - int count = 0; - for (char aChar : chars) { - if(aChar == '%') { - count++; - } - } - return count; - } -}
