You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ignite.apache.org by an...@apache.org on 2016/06/17 11:02:31 UTC
[2/3] ignite git commit: IGNITE-3277 Fixed after review.
http://git-wip-us.apache.org/repos/asf/ignite/blob/1de04e7d/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestHandler.java
----------------------------------------------------------------------
diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestHandler.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestHandler.java
index fcbfd6d..e7a7395 100644
--- a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestHandler.java
+++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestHandler.java
@@ -17,54 +17,28 @@
package org.apache.ignite.internal.processors.rest.protocols.http.jetty;
-import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.BeanDescription;
-import com.fasterxml.jackson.databind.BeanProperty;
-import com.fasterxml.jackson.databind.JsonMappingException;
-import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.SerializationConfig;
-import com.fasterxml.jackson.databind.SerializerProvider;
-import com.fasterxml.jackson.databind.module.SimpleModule;
-import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
-import com.fasterxml.jackson.databind.ser.DefaultSerializerProvider;
-import com.fasterxml.jackson.databind.ser.SerializerFactory;
-import com.fasterxml.jackson.databind.ser.impl.UnknownSerializer;
-import java.beans.IntrospectionException;
-import java.beans.Introspector;
-import java.beans.PropertyDescriptor;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
-import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
-import java.sql.SQLException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
import java.util.Collections;
-import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
-import java.util.concurrent.locks.ReadWriteLock;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteLogger;
-import org.apache.ignite.internal.processors.cache.query.GridCacheSqlIndexMetadata;
-import org.apache.ignite.internal.processors.cache.query.GridCacheSqlMetadata;
import org.apache.ignite.internal.processors.rest.GridRestCommand;
import org.apache.ignite.internal.processors.rest.GridRestProtocolHandler;
import org.apache.ignite.internal.processors.rest.GridRestResponse;
@@ -75,17 +49,10 @@ import org.apache.ignite.internal.processors.rest.request.GridRestRequest;
import org.apache.ignite.internal.processors.rest.request.GridRestTaskRequest;
import org.apache.ignite.internal.processors.rest.request.GridRestTopologyRequest;
import org.apache.ignite.internal.processors.rest.request.RestQueryRequest;
-import org.apache.ignite.internal.util.IgniteExceptionRegistry;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.internal.U;
-import org.apache.ignite.internal.visor.cache.VisorCache;
-import org.apache.ignite.internal.visor.util.VisorExceptionWrapper;
-import org.apache.ignite.lang.IgniteBiTuple;
import org.apache.ignite.lang.IgniteClosure;
-import org.apache.ignite.lang.IgniteUuid;
import org.apache.ignite.plugin.security.SecurityCredentials;
-import org.apache.ignite.plugin.security.SecurityPermissionSet;
-import org.apache.ignite.plugin.security.SecuritySubject;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.jetbrains.annotations.Nullable;
@@ -98,8 +65,7 @@ import static org.apache.ignite.internal.processors.rest.GridRestCommand.EXECUTE
import static org.apache.ignite.internal.processors.rest.GridRestResponse.STATUS_FAILED;
/**
- * Jetty REST handler. The following URL format is supported:
- * {@code /ignite?cmd=cmdName¶m1=abc¶m2=123}
+ * Jetty REST handler. The following URL format is supported: {@code /ignite?cmd=cmdName¶m1=abc¶m2=123}
*/
public class GridJettyRestHandler extends AbstractHandler {
/** Used to sent request charset. */
@@ -115,6 +81,8 @@ public class GridJettyRestHandler extends AbstractHandler {
private volatile String dfltPage;
/** Favicon. */
private volatile byte[] favicon;
+ /** Mapper from Java object to JSON. */
+ private final ObjectMapper jsonMapper;
/**
* Creates new HTTP requests handler.
@@ -130,6 +98,7 @@ public class GridJettyRestHandler extends AbstractHandler {
this.hnd = hnd;
this.log = log;
this.authChecker = authChecker;
+ this.jsonMapper = new GridJettyObjectMapper();
// Init default page and favicon.
try {
@@ -162,7 +131,8 @@ public class GridJettyRestHandler extends AbstractHandler {
* @return Long value from parameters map or {@code dfltVal} if null or not exists.
* @throws IgniteCheckedException If parsing failed.
*/
- @Nullable private static Long longValue(String key, Map<String, Object> params, Long dfltVal) throws IgniteCheckedException {
+ @Nullable private static Long longValue(String key, Map<String, Object> params,
+ Long dfltVal) throws IgniteCheckedException {
assert key != null;
String val = (String)params.get(key);
@@ -329,244 +299,6 @@ public class GridJettyRestHandler extends AbstractHandler {
}
}
- /** Custom {@code null} value serializer. */
- private static final JsonSerializer<Object> NULL_SERIALIZER = new JsonSerializer<Object>() {
- /** {@inheritDoc} */
- @Override public void serialize(Object val, JsonGenerator gen, SerializerProvider ser) throws IOException {
- gen.writeNull();
- }
- };
-
- /** Custom {@code null} string serializer. */
- private static final JsonSerializer<Object> NULL_STRING_SERIALIZER = new JsonSerializer<Object>() {
- /** {@inheritDoc} */
- @Override public void serialize(Object val, JsonGenerator gen, SerializerProvider ser) throws IOException {
- gen.writeString("");
- }
- };
-
- /** Custom serializer for {@link Throwable} */
- private static final JsonSerializer<Throwable> THROWABLE_SERIALIZER = new JsonSerializer<Throwable>() {
- /** {@inheritDoc} */
- @Override public void serialize(Throwable e, JsonGenerator gen, SerializerProvider ser) throws IOException {
- gen.writeStartObject();
-
- if (e instanceof VisorExceptionWrapper) {
- VisorExceptionWrapper wrapper = (VisorExceptionWrapper)e;
-
- gen.writeStringField("className", wrapper.getClassName());
- }
- else
- gen.writeStringField("className", e.getClass().getName());
-
- if (e.getMessage() != null)
- gen.writeStringField("message", e.getMessage());
-
- if (e.getCause() != null)
- gen.writeObjectField("cause", e.getCause());
-
- if (e instanceof SQLException) {
- SQLException sqlE = (SQLException)e;
-
- gen.writeNumberField("errorCode", sqlE.getErrorCode());
- gen.writeStringField("SQLState", sqlE.getSQLState());
- }
-
- gen.writeEndObject();
- }
- };
-
- /** Custom serializer for {@link IgniteUuid} */
- private static final JsonSerializer<IgniteUuid> IGNITE_UUID_SERIALIZER = new JsonSerializer<IgniteUuid>() {
- /** {@inheritDoc} */
- @Override public void serialize(IgniteUuid uid, JsonGenerator gen, SerializerProvider ser) throws IOException {
- gen.writeString(uid.toString());
- }
- };
-
- /** Custom serializer for {@link IgniteBiTuple} */
- private static final JsonSerializer<IgniteBiTuple> IGNITE_TUPLE_SERIALIZER = new JsonSerializer<IgniteBiTuple>() {
- /** {@inheritDoc} */
- @Override public void serialize(IgniteBiTuple t, JsonGenerator gen, SerializerProvider ser) throws IOException {
- gen.writeStartObject();
-
- gen.writeObjectField("key", t.getKey());
- gen.writeObjectField("value", t.getValue());
-
- gen.writeEndObject();
- }
- };
-
- /**
- * Custom serializer for Visor classes with non JavaBeans getters.
- */
- private static final JsonSerializer<Object> LESS_NAMING_SERIALIZER = new JsonSerializer<Object>() {
- /** Methods to exclude. */
- private final Collection<String> exclMtds = Arrays.asList("toString", "hashCode", "clone", "getClass");
-
- /** */
- private final Map<Class<?>, Collection<Method>> clsCache = new HashMap<>();
-
- /** */
- private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
-
- /** {@inheritDoc} */
- @Override public void serialize(Object bean, JsonGenerator gen, SerializerProvider ser) throws IOException {
- if (bean != null) {
- gen.writeStartObject();
-
- Class<?> cls = bean.getClass();
-
- Collection<Method> methods;
-
- // Get descriptor from cache.
- rwLock.readLock().lock();
-
- try {
- methods = clsCache.get(cls);
- }
- finally {
- rwLock.readLock().unlock();
- }
-
- // If missing in cache - build descriptor
- if (methods == null) {
- Method[] publicMtds = cls.getMethods();
-
- methods = new ArrayList<>(publicMtds.length);
-
- for (Method mtd : publicMtds) {
- Class retType = mtd.getReturnType();
-
- String mtdName = mtd.getName();
-
- if (mtd.getParameterTypes().length != 0 ||
- retType == void.class || retType == cls ||
- exclMtds.contains(mtdName) ||
- (VisorCache.class.isAssignableFrom(retType) && "history".equals(mtdName)))
- continue;
-
- mtd.setAccessible(true);
-
- methods.add(mtd);
- }
-
- /*
- * Allow multiple puts for the same class - they will simply override.
- */
- rwLock.writeLock().lock();
-
- try {
- clsCache.put(cls, methods);
- }
- finally {
- rwLock.writeLock().unlock();
- }
- }
-
- // Extract fields values using descriptor and build JSONObject.
- for (Method mtd : methods) {
- try {
- Object prop = mtd.invoke(bean);
-
- if (prop != null)
- gen.writeObjectField(mtd.getName(), prop);
- }
- catch (IOException ioe) {
- throw ioe;
- }
- catch (Exception e) {
- throw new IOException(e);
- }
- }
-
- gen.writeEndObject();
- }
- }
- };
-
- /** */
- private static final BeanSerializerModifier CUSTOM_JSON_SERIALIZER_MODIFIER = new BeanSerializerModifier() {
- /** {@inheritDoc} */
- @Override public JsonSerializer<?> modifySerializer(SerializationConfig cfg, BeanDescription beanDesc,
- JsonSerializer<?> serializer) {
- if (serializer.getClass() == UnknownSerializer.class) {
- Class<?> beanCls = beanDesc.getBeanClass();
-
- if ((beanCls.getSimpleName().startsWith("Visor") && beanCls != VisorExceptionWrapper.class) ||
- beanCls == IgniteExceptionRegistry.ExceptionInfo.class ||
- GridCacheSqlMetadata.class.isAssignableFrom(beanCls) ||
- GridCacheSqlIndexMetadata.class.isAssignableFrom(beanCls) ||
- SecuritySubject.class.isAssignableFrom(beanCls) ||
- SecurityPermissionSet.class.isAssignableFrom(beanCls))
- return LESS_NAMING_SERIALIZER;
-
- try {
- PropertyDescriptor[] props = Introspector.getBeanInfo(beanCls).getPropertyDescriptors();
-
- if (props == null || (props.length == 1 && "class".equals(props[0].getName())))
- return LESS_NAMING_SERIALIZER;
- }
- catch (IntrospectionException ignore) {
- // No-op.
- }
- }
-
- return super.modifySerializer(cfg, beanDesc, serializer);
- }
- };
-
- /**
- * Custom serializers provider that provide special serializers for {@code null} values.
- */
- private static class CustomSerializerProvider extends DefaultSerializerProvider {
- /**
- * Default constructor.
- */
- CustomSerializerProvider() {
- super();
- }
-
- /**
- * Full constructor.
- *
- * @param src Blueprint object used as the baseline for this instance.
- * @param cfg Provider configuration.
- * @param f Serializers factory.
- */
- CustomSerializerProvider(SerializerProvider src, SerializationConfig cfg, SerializerFactory f) {
- super(src, cfg, f);
- }
-
- /** {@inheritDoc} */
- public DefaultSerializerProvider createInstance(SerializationConfig cfg, SerializerFactory jsf) {
- return new CustomSerializerProvider(this, cfg, jsf);
- }
-
- /** {@inheritDoc} */
- @Override public JsonSerializer<Object> findNullValueSerializer(BeanProperty prop) throws JsonMappingException {
- if (prop.getType().getRawClass() == String.class)
- return NULL_STRING_SERIALIZER;
-
- return NULL_SERIALIZER;
- }
- }
-
- /** */
- private static final ObjectMapper JSON_MAPPER = new ObjectMapper(null, new CustomSerializerProvider(), null);
-
- static {
- final SimpleModule module = new SimpleModule();
-
- module.setSerializerModifier(CUSTOM_JSON_SERIALIZER_MODIFIER);
-
- module.addSerializer(Throwable.class, THROWABLE_SERIALIZER);
- module.addSerializer(IgniteBiTuple.class, IGNITE_TUPLE_SERIALIZER);
- module.addSerializer(IgniteUuid.class, IGNITE_UUID_SERIALIZER);
-
- JSON_MAPPER.registerModule(module);
- }
-
/**
* Process HTTP request.
*
@@ -628,7 +360,7 @@ public class GridJettyRestHandler extends AbstractHandler {
String json;
try {
- json = JSON_MAPPER.writeValueAsString(cmdRes);
+ json = jsonMapper.writeValueAsString(cmdRes);
}
catch (JsonProcessingException e1) {
U.error(log, "Failed to convert response to JSON: " + cmdRes, e1);
@@ -636,7 +368,7 @@ public class GridJettyRestHandler extends AbstractHandler {
GridRestResponse resFailed = new GridRestResponse(STATUS_FAILED, e1.getMessage());
try {
- json = JSON_MAPPER.writeValueAsString(resFailed);
+ json = jsonMapper.writeValueAsString(resFailed);
}
catch (JsonProcessingException e2) {
json = "{\"successStatus\": \"1\", \"error:\" \"" + e2.getMessage() + "\"}}";