[OLINGO-356] Minor code clean up

This commit is contained in:
Michael Bolz 2014-08-15 06:26:22 +02:00
parent cb7a8620c2
commit b9d452740d
13 changed files with 27 additions and 247 deletions

View File

@ -43,10 +43,7 @@ import org.apache.olingo.ext.proxy.utils.ClassUtils;
public final class EntityContainerInvocationHandler extends AbstractInvocationHandler {
private static final long serialVersionUID = 7379006755693410764L;
protected final String namespace;
private final String name;
private final boolean defaultEC;
@ -192,7 +189,6 @@ public final class EntityContainerInvocationHandler extends AbstractInvocationHa
new PrimitiveCollectionInvocationHandler<T>(getService(), ref));
}
@SuppressWarnings("unchecked")
public EdmStreamValue newEdmStreamValue(
final String contentType, final InputStream stream) {

View File

@ -67,7 +67,6 @@ public class EntitySetInvocationHandler<
return new EntitySetInvocationHandler(ref, service, service.getClient().newURIBuilder(uri.toASCIIString()));
}
@SuppressWarnings("unchecked")
protected EntitySetInvocationHandler(
final Class<?> ref,
final AbstractService<?> service,

View File

@ -236,7 +236,7 @@ public class InvokerInvocationHandler<T, O extends Operations> extends AbstractI
}
@Override
@SuppressWarnings({"unchecked", "rawtype"})
@SuppressWarnings({"unchecked", "rawtypes"})
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if ("filter".equals(method.getName())
|| "orderBy".equals(method.getName())

View File

@ -320,7 +320,6 @@ public final class CoreUtils {
}
}
@SuppressWarnings("unchecked")
public static void addProperties(
final CommonEdmEnabledODataClient<?> client,
final Map<String, Object> changes,
@ -638,7 +637,6 @@ public final class CoreUtils {
return res;
}
@SuppressWarnings("unchecked")
public static Collection<Class<? extends AbstractTerm>> getAnnotationTerms(
final AbstractService<?> service, final List<ODataAnnotation> annotations) {

View File

@ -156,14 +156,14 @@ public class V4Services extends AbstractServices {
@DELETE
@Path("/monitor/{name}")
public Response removeMonitor(@Context final UriInfo uriInfo, @PathParam("name") final String name) {
public Response removeMonitor(@PathParam("name") final String name) {
providedAsync.remove(name);
return xml.createResponse(null, null, null, Status.NO_CONTENT);
}
@GET
@Path("/monitor/{name}")
public Response async(@Context final UriInfo uriInfo, @PathParam("name") final String name) {
public Response async(@PathParam("name") final String name) {
try {
if (!providedAsync.containsKey(name)) {
throw new NotFoundException();
@ -657,7 +657,6 @@ public class V4Services extends AbstractServices {
@POST
@Path("/Accounts({entityId})/Microsoft.Test.OData.Services.ODataWCFService.RefreshDefaultPI{paren:[\\(\\)]*}")
public Response actionRefreshDefaultPI(
@Context final UriInfo uriInfo,
@HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept,
@HeaderParam("Content-Type") @DefaultValue(StringUtils.EMPTY) final String contentType,
@PathParam("entityId") final String entityId,
@ -1150,7 +1149,6 @@ public class V4Services extends AbstractServices {
@GET
@Path("/GetPerson2({param:.*})/Emails")
public Response functionGetPerson2Emails(
@Context final UriInfo uriInfo,
@HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept,
@QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format) {
@ -1160,7 +1158,6 @@ public class V4Services extends AbstractServices {
@GET
@Path("/GetPerson2({param:.*})/HomeAddress")
public Response functionGetPerson2HomeAddress(
@Context final UriInfo uriInfo,
@HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept,
@QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format) {
@ -1202,7 +1199,6 @@ public class V4Services extends AbstractServices {
@GET
@Path("/GetProductsByAccessLevel({param:.*})")
public Response functionGetProductsByAccessLevel(
@Context final UriInfo uriInfo,
@HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept,
@QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format) {
@ -1235,7 +1231,6 @@ public class V4Services extends AbstractServices {
@GET
@Path("/GetBossEmails({param:.*})")
public Response functionGetBossEmails(
@Context final UriInfo uriInfo,
@HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept,
@QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format) {

View File

@ -1,208 +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.fit.server;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Random;
/**
*
*/
public class StringHelper {
public static class Stream {
private final byte[] data;
private Stream(final byte[] data) {
this.data = data;
}
public Stream(final String content, final String charset) throws UnsupportedEncodingException {
this(content.getBytes(charset));
}
public InputStream asStream() {
return new ByteArrayInputStream(data);
}
public byte[] asArray() {
return data;
}
public String asString() {
return asString("UTF-8");
}
public String asString(final String charsetName) {
return new String(data, Charset.forName(charsetName));
}
public Stream print(final OutputStream out) throws IOException {
out.write(data);
return this;
}
public Stream print() throws IOException {
return print(System.out);
}
/**
* Number of lines separated by line breaks (<code>CRLF</code>).
* A content string like <code>text\r\nmoreText</code> will result in
* a line count of <code>2</code>.
*
* @return lines count
*/
public int linesCount() {
return StringHelper.countLines(asString(), "\r\n");
}
}
public static Stream toStream(final InputStream stream) throws IOException {
byte[] result = new byte[0];
byte[] tmp = new byte[8192];
int readCount = stream.read(tmp);
while (readCount >= 0) {
byte[] innerTmp = new byte[result.length + readCount];
System.arraycopy(result, 0, innerTmp, 0, result.length);
System.arraycopy(tmp, 0, innerTmp, result.length, readCount);
result = innerTmp;
readCount = stream.read(tmp);
}
stream.close();
return new Stream(result);
}
public static Stream toStream(final String content) {
try {
return new Stream(content, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("UTF-8 should be supported on each system.");
}
}
public static String inputStreamToString(final InputStream in, final boolean preserveLineBreaks) throws IOException {
final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, Charset.forName("UTF-8")));
final StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
if (preserveLineBreaks) {
stringBuilder.append("\n");
}
}
bufferedReader.close();
final String result = stringBuilder.toString();
return result;
}
public static int countLines(final String content) {
return countLines(content, "\r\n");
}
public static int countLines(final String content, final String lineBreak) {
if (content == null) {
return -1;
}
int lastPos = content.indexOf(lineBreak);
int count = 1;
while (lastPos >= 0) {
lastPos = content.indexOf(lineBreak, lastPos + 1);
count++;
}
return count;
}
public static String inputStreamToString(final InputStream in) throws IOException {
return inputStreamToString(in, false);
}
/**
* Encapsulate given content in an {@link java.io.InputStream} with charset <code>UTF-8</code>.
*
* @param content to encapsulate content
* @return content as stream
*/
public static InputStream encapsulate(final String content) {
try {
return encapsulate(content, "UTF-8");
} catch (UnsupportedEncodingException e) {
// we know that UTF-8 is supported
throw new TestUtilRuntimeException("UTF-8 MUST be supported.", e);
}
}
/**
* Encapsulate given content in an {@link java.io.InputStream} with given charset.
*
* @param content to encapsulate content
* @param charset to be used charset
* @return content as stream
* @throws java.io.UnsupportedEncodingException if charset is not supported
*/
public static InputStream encapsulate(final String content, final String charset)
throws UnsupportedEncodingException {
return new ByteArrayInputStream(content.getBytes(charset));
}
/**
* Generate a string with given length containing random upper case characters ([A-Z]).
*
* @param len length of to generated string
* @return random upper case characters ([A-Z]).
*/
public static InputStream generateDataStream(final int len) {
return encapsulate(generateData(len));
}
/**
* Generates a string with given length containing random upper case characters ([A-Z]).
* @param len length of the generated string
* @return random upper case characters ([A-Z])
*/
public static String generateData(final int len) {
Random random = new Random();
StringBuilder b = new StringBuilder(len);
for (int j = 0; j < len; j++) {
final char c = (char) ('A' + random.nextInt('Z' - 'A' + 1));
b.append(c);
}
return b.toString();
}
private static class TestUtilRuntimeException extends RuntimeException {
private static final long serialVersionUID = 8759664297317490186L;
@SuppressWarnings("unused")
public TestUtilRuntimeException(String message, Throwable cause) {
}
}
}

View File

@ -24,6 +24,7 @@ import org.apache.catalina.LifecycleState;
import org.apache.catalina.loader.WebappLoader;
import org.apache.catalina.startup.Tomcat;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -31,6 +32,7 @@ import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
@ -123,6 +125,7 @@ public class TomcatTestServer {
}
public static class StaticContent extends HttpServlet {
private static final long serialVersionUID = 6850459331131987539L;
private final String uri;
private final String resource;
@ -135,18 +138,18 @@ public class TomcatTestServer {
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
StringHelper.Stream st;
String result;
File resourcePath = new File(resource);
if(resourcePath.exists() && resourcePath.isFile()) {
FileInputStream fin = new FileInputStream(resourcePath);
st = StringHelper.toStream(fin);
result = IOUtils.toString(fin, "UTF-8");
LOG.info("Mapped uri '{}' to resource '{}'.", uri, resource);
LOG.trace("Resource content {\n\n{}\n\n}", st.asString());
LOG.trace("Resource content {\n\n{}\n\n}", result);
} else {
LOG.debug("Unable to load resource for path {} as stream.", uri);
st = StringHelper.toStream("<html><head/><body>No resource for path found</body>");
result = "<html><head/><body>No resource for path found</body>";
}
resp.getOutputStream().write(st.asString().getBytes());
resp.getOutputStream().write(result.getBytes());
}
}

View File

@ -27,7 +27,6 @@ import org.apache.olingo.commons.api.domain.CommonODataProperty;
import org.apache.olingo.commons.api.domain.ODataValue;
import org.apache.olingo.commons.api.format.ODataFormat;
import org.apache.olingo.commons.api.serialization.ODataSerializerException;
import org.apache.olingo.fit.server.StringHelper;
import org.apache.olingo.fit.server.TomcatTestServer;
import org.apache.olingo.server.tecsvc.TechnicalServlet;
import org.junit.BeforeClass;
@ -55,7 +54,7 @@ public abstract class AbstractBaseTestITCase {
@BeforeClass
public static void init() throws Exception {
TomcatTestServer server = TomcatTestServer.init(9080)
TomcatTestServer.init(9080)
.addServlet(TechnicalServlet.class, "/olingo-server-tecsvc/odata.svc/*")
.addServlet(StaticContent.class, "/olingo-server-tecsvc/v4.0/cs02/vocabularies/Org.OData.Core.V1.xml")
.addWebApp()
@ -128,12 +127,11 @@ public abstract class AbstractBaseTestITCase {
}
public static class StaticContent extends HttpServlet {
private static final long serialVersionUID = -6663569573355398997L;
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
StringHelper.Stream st = StringHelper.toStream(
Thread.currentThread().getContextClassLoader().getResourceAsStream("org-odata-core-v1.xml"));
resp.getOutputStream().write(st.asArray());
resp.getOutputStream().write(IOUtils.toByteArray(
Thread.currentThread().getContextClassLoader().getResourceAsStream("org-odata-core-v1.xml")));
}
}
}

View File

@ -213,7 +213,7 @@ public class ContextTestITCase extends AbstractTestITCase {
assertTrue(service.getContext().entityContext().isAttached(source));
assertEquals(AttachedEntityStatus.NEW, service.getContext().entityContext().getStatus(source));
assertEquals(3, ((Collection) (source.getLinkChanges().entrySet().iterator().next().getValue())).size());
assertEquals(3, ((Collection<?>) (source.getLinkChanges().entrySet().iterator().next().getValue())).size());
for (Order order : toBeLinked) {
final EntityInvocationHandler target = (EntityInvocationHandler) Proxy.getInvocationHandler(order);
@ -487,14 +487,13 @@ public class ContextTestITCase extends AbstractTestITCase {
if (property.getKey().name().equals(sourceName)) {
if (isCollection) {
found = false;
for (Object proxy : (Collection) property.getValue()) {
if (target.equals((EntityInvocationHandler) Proxy.getInvocationHandler(proxy))) {
for (Object proxy : (Collection<?>) property.getValue()) {
if (target.equals(Proxy.getInvocationHandler(proxy))) {
found = true;
}
}
} else {
found = target.equals(
(EntityInvocationHandler) Proxy.getInvocationHandler(property.getValue()));
found = target.equals(Proxy.getInvocationHandler(property.getValue()));
}
}
}

View File

@ -30,6 +30,7 @@ import java.io.IOException;
import java.util.Collections;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.apache.olingo.client.api.CommonODataClient;
import org.apache.olingo.client.api.communication.ODataClientErrorException;
import org.apache.olingo.client.api.communication.request.retrieve.EdmMetadataRequest;
@ -51,7 +52,6 @@ import org.apache.olingo.commons.api.format.ContentType;
import org.apache.olingo.commons.api.format.ODataFormat;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.fit.AbstractBaseTestITCase;
import org.apache.olingo.fit.server.StringHelper;
import org.apache.olingo.fit.tecsvc.TecSvcConst;
import org.junit.Before;
import org.junit.Test;
@ -184,8 +184,7 @@ public class BasicITCase extends AbstractBaseTestITCase {
+ "\"cccccc67-89ab-cdef-0123-456789cccccc\"],"
+ "\"CollPropertyTimeOfDay\":[\"04:14:13\",\"23:59:59\",\"01:12:33\"]"
+ "}";
StringHelper.Stream s = StringHelper.toStream(response.getRawResponse());
assertEquals(expectedResult, s.asString());
assertEquals(expectedResult, IOUtils.toString(response.getRawResponse(), "UTF-8"));
}
@Override protected CommonODataClient<?> getClient() {

View File

@ -37,7 +37,6 @@ import org.apache.olingo.commons.api.domain.v3.ODataProperty;
import java.net.URI;
@SuppressWarnings("unchecked")
public class RetrieveRequestFactoryImpl extends AbstractRetrieveRequestFactory implements RetrieveRequestFactory {
public RetrieveRequestFactoryImpl(final ODataClient client) {

View File

@ -38,7 +38,6 @@ import org.apache.olingo.commons.api.domain.v4.ODataSingleton;
import java.net.URI;
@SuppressWarnings("unchecked")
public class RetrieveRequestFactoryImpl extends AbstractRetrieveRequestFactory
implements RetrieveRequestFactory {

View File

@ -68,17 +68,20 @@ public class TranslatedExceptionSubclassesTest {
Assert.assertNotNull("No value found for message key '" + propKey + "'", value);
//
int paraCount = countParameters(value);
Constructor ctor = clazz.getConstructor(String.class, ODataTranslatedException.MessageKey.class, String[].class);
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 = (ODataTranslatedException) ctor.newInstance(developerMessage, messageKey, paras);
ODataTranslatedException e = ctor.newInstance(developerMessage, messageKey, paras);
try {
throw e;
} catch (ODataTranslatedException translatedException) {
String formattedValue = new Formatter().format(value, paras).toString();
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());