Skip to content

Commit

Permalink
Merge pull request #3 from pdudits/pr-4037
Browse files Browse the repository at this point in the history
  • Loading branch information
jbee authored Jun 17, 2019
2 parents 9b2c15a + 05aa739 commit 56d2cb4
Show file tree
Hide file tree
Showing 6 changed files with 367 additions and 128 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) [2019] Payara Foundation and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://github.com/payara/Payara/blob/master/LICENSE.txt
* See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* The Payara Foundation designates this particular file as subject to the "Classpath"
* exception as provided by the Payara Foundation in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/

package fish.payara.ejb.http.client;

import fish.payara.ejb.http.protocol.ErrorResponse;
import fish.payara.ejb.http.protocol.InvokeMethodRequest;
import fish.payara.ejb.http.protocol.InvokeMethodResponse;
import fish.payara.ejb.http.protocol.MediaTypes;
import fish.payara.ejb.http.protocol.rs.InvokeMethodResponseJsonBodyReader;

import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.UndeclaredThrowableException;
import java.util.Map;

import static java.util.Arrays.asList;
import static javax.naming.Context.SECURITY_CREDENTIALS;
import static javax.naming.Context.SECURITY_PRINCIPAL;

final class EjbHttpProxyHandlerV1 implements InvocationHandler {

private final String mediaType;
private final WebTarget invoke;
private final String jndiName;
private final Map<String, Object> jndiOptions;

public EjbHttpProxyHandlerV1(String mediaType, WebTarget invoke, String jndiName, Map<String, Object> jndiOptions) {
this.jndiName = jndiName;
this.jndiOptions = jndiOptions;
this.invoke = mediaType.equals(MediaTypes.JSON) ? invoke.register(InvokeMethodResponseJsonBodyReader.class) : invoke;
this.mediaType = mediaType;
}

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// Check for methods we should not proxy first
if (args == null && method.getName().equals("toString")) {
return toString();
}
if (args == null && method.getName().equals("hashCode")) {
// unique instance in the JVM, and no need to override
return hashCode();
}
if (args != null && args.length == 1 && method.getName().equals("equals")) {
// unique instance in the JVM, and no need to override
return equals(args[0]);
}
return invokeRemote(method, args);
}

private Object invokeRemote(Method method, Object[] args) throws Exception {
InvokeMethodRequest request = createRequest(method, args);
try (Response response = invoke
.request(mediaType)
.buildPost(Entity.entity(request, mediaType)).invoke()) {
if (response.getStatus() == Response.Status.OK.getStatusCode()) {
return response
.readEntity(InvokeMethodResponse.class, InvokeMethodResponse.ResultType.of(method)).result;
}
ErrorResponse error = response.readEntity(ErrorResponse.class);
throw LookupV1.deserialise(error);
}
}

private InvokeMethodRequest createRequest(Method method, Object[] args) {
String principal = jndiOptions.containsKey(SECURITY_PRINCIPAL)
? Lookup.base64Encode(jndiOptions.get(SECURITY_PRINCIPAL))
: "";
String credentials = jndiOptions.containsKey(SECURITY_CREDENTIALS)
? Lookup.base64Encode(jndiOptions.get(SECURITY_CREDENTIALS))
: "";
String[] argTypes = asList(method.getParameterTypes()).stream()
.map(type -> type.getName())
.toArray(String[]::new);
String[] argActualTypes = args == null ? new String[0] : asList(args).stream()
.map(arg -> arg == null ? null : arg.getClass().getName())
.toArray(String[]::new);
for (int i = 0; i < argTypes.length; i++) {
if (argActualTypes[i] == null) {
argActualTypes[i] = argTypes[i];
}
}
return new InvokeMethodRequest(principal, credentials, jndiName, method.getName(), argTypes, argActualTypes,
packArguments(args), null);
}

private Object packArguments(Object[] args) {
Object argValues = args;
if (MediaTypes.JAVA_OBJECT.equals(mediaType)) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(bos)) {
oos.writeObject(argValues);
} catch (IOException e) {
throw new UndeclaredThrowableException(e);
}
argValues = bos.toByteArray();
}
return argValues;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,7 @@
import static fish.payara.ejb.http.client.RemoteEJBContextFactory.JAXRS_CLIENT_SERIALIZATION;
import static java.lang.reflect.Proxy.newProxyInstance;
import static java.security.AccessController.doPrivileged;
import static java.util.Arrays.asList;
import static javax.naming.Context.SECURITY_CREDENTIALS;
import static javax.naming.Context.SECURITY_PRINCIPAL;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.UndeclaredThrowableException;
import java.security.PrivilegedAction;
import java.util.Map;
Expand All @@ -63,8 +55,6 @@
import javax.ws.rs.core.Response.Status;

import fish.payara.ejb.http.protocol.ErrorResponse;
import fish.payara.ejb.http.protocol.InvokeMethodRequest;
import fish.payara.ejb.http.protocol.InvokeMethodResponse;
import fish.payara.ejb.http.protocol.LookupRequest;
import fish.payara.ejb.http.protocol.LookupResponse;
import fish.payara.ejb.http.protocol.MediaTypes;
Expand Down Expand Up @@ -134,85 +124,7 @@ private static <C> C newProxy(Class<C> remoteBusinessInterface, WebTarget invoke
Map<String, Object> jndiOptions) {
return (C) newProxyInstance(doPrivileged((PrivilegedAction<ClassLoader>) remoteBusinessInterface::getClassLoader),
new Class[] { remoteBusinessInterface },
new RemoteEjbOverHttpInvocationHandler(mediaType, invoke, jndiName, jndiOptions));
new EjbHttpProxyHandlerV1(mediaType, invoke, jndiName, jndiOptions));
}

static final class RemoteEjbOverHttpInvocationHandler implements InvocationHandler {

private final String mediaType;
private final WebTarget invoke;
private final String jndiName;
private final Map<String, Object> jndiOptions;

public RemoteEjbOverHttpInvocationHandler(String mediaType, WebTarget invoke, String jndiName, Map<String, Object> jndiOptions) {
this.jndiName = jndiName;
this.jndiOptions = jndiOptions;
this.invoke = invoke;
this.mediaType = mediaType;
}

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// Check for methods we should not proxy first
if (args == null && method.getName().equals("toString")) {
return toString();
}
if (args == null && method.getName().equals("hashCode")) {
// unique instance in the JVM, and no need to override
return hashCode();
}
if (args != null && args.length == 1 && method.getName().equals("equals")) {
// unique instance in the JVM, and no need to override
return equals(args[0]);
}
return invokeRemote(method, args);
}

private Object invokeRemote(Method method, Object[] args) throws Exception {
InvokeMethodRequest request = createRequest(method, args);
try (Response response = invoke.request(mediaType).buildPost(Entity.entity(request, mediaType)).invoke()) {
if (response.getStatus() == Status.OK.getStatusCode()) {
return response.readEntity(InvokeMethodResponse.class).result;
}
ErrorResponse error = response.readEntity(ErrorResponse.class);
throw deserialise(error);
}
}

private InvokeMethodRequest createRequest(Method method, Object[] args) {
String principal = jndiOptions.containsKey(SECURITY_PRINCIPAL)
? base64Encode(jndiOptions.get(SECURITY_PRINCIPAL))
: "";
String credentials = jndiOptions.containsKey(SECURITY_CREDENTIALS)
? base64Encode(jndiOptions.get(SECURITY_CREDENTIALS))
: "";
String[] argTypes = asList(method.getParameterTypes()).stream()
.map(type -> type.getName())
.toArray(String[]::new);
String[] argActualTypes = args == null ? new String[0] : asList(args).stream()
.map(arg -> arg == null ? null : arg.getClass().getName())
.toArray(String[]::new);
for (int i = 0; i < argTypes.length; i++) {
if (argActualTypes[i] == null) {
argActualTypes[i] = argTypes[i];
}
}
return new InvokeMethodRequest(principal, credentials, jndiName, method.getName(), argTypes, argActualTypes,
packArguments(args), null);
}

private Object packArguments(Object[] args) {
Object argValues = args;
if (MediaTypes.JAVA_OBJECT.equals(mediaType)) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(bos)) {
oos.writeObject(argValues);
} catch (IOException ex) {
throw new UndeclaredThrowableException(ex);
}
argValues = bos.toByteArray();
}
return argValues;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,20 +40,19 @@
package fish.payara.ejb.http.protocol;

import javax.json.bind.annotation.JsonbPropertyOrder;
import javax.json.bind.annotation.JsonbTypeDeserializer;
import javax.json.bind.serializer.DeserializationContext;
import javax.json.bind.serializer.JsonbDeserializer;
import javax.json.stream.JsonParser;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Optional;
import java.util.stream.Stream;

/**
* Result of invoking an EJB method.
*
* @author Jan Bernitt
*/
@JsonbPropertyOrder({"type", "result"})
@JsonbTypeDeserializer(InvokeMethodResponse.Deserializer.class)
public class InvokeMethodResponse implements Serializable {

private static final long serialVersionUID = 1L;
Expand All @@ -73,36 +72,32 @@ public InvokeMethodResponse(String type, Object result) {
this.result = result;
}

// This deserializer is only fit for limited use cases. Client should employ different deserialization means,
// that make use of the expected return type as well (especially to support Optional returns)
public static class Deserializer implements JsonbDeserializer<InvokeMethodResponse> {
public static class ResultType implements Annotation {
public final Type type;

@Override
public InvokeMethodResponse deserialize(JsonParser parser, DeserializationContext ctx, Type rtType) {
String type = null;
Object result = null;
while (parser.hasNext()) {
JsonParser.Event event = parser.next();
if (event == JsonParser.Event.KEY_NAME && parser.getString().equals("type")) {
parser.next();
type = parser.getString();
} else if (event == JsonParser.Event.KEY_NAME && parser.getString().equals("result")) {
Class<?> resultClass = determineClass(type);
result = ctx.deserialize(resultClass, parser);
}
}
return new InvokeMethodResponse(result);
public Class<? extends Annotation> annotationType() {
return ResultType.class;
}

private static Class<?> determineClass(String type) {
if (type == null) {
throw new IllegalArgumentException("Type was not specified");
}
try {
return Class.forName(type);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("Could not find class for type "+type, e);
public ResultType(Method method) {
this.type = method.getGenericReturnType();
}

public static Annotation[] of(Method method) {
return new Annotation[] { new ResultType(method) };
}

public static boolean isPresent(Annotation[] annotations) {
return annotations != null && Stream.of(annotations).anyMatch(ResultType.class::isInstance);
}

public static ResultType find(Annotation[] annotations) {
Optional<ResultType> found = Optional.empty();
if (annotations != null) {
found = Stream.of(annotations).filter(ResultType.class::isInstance).map(ResultType.class::cast).findAny();
}
return found.orElseThrow(() -> new IllegalArgumentException("ResultType annotation is not present") );
}
}
}
Loading

0 comments on commit 56d2cb4

Please sign in to comment.