Search in sources :

Example 1 with VCellApiRpcRequest

use of org.vcell.api.client.VCellApiRpcRequest in project vcell by virtualcell.

the class RpcRestlet method handle.

@Override
public void handle(Request req, Response response) {
    if (req.getMethod().equals(Method.GET)) {
        try {
            User authuser = null;
            HttpRequest request = (HttpRequest) req;
            // Use "WWW-Authenticate - Basic" authentication scheme
            // Browser takes care of asking user for credentials and sending them
            // Must be used with https connection to hide credentials
            Header authHeader = request.getHeaders().getFirst("Authorization");
            if (authHeader != null) {
                // caller included a user and password
                String typeAndCredential = authHeader.getValue();
                // System.out.println("--"+up);
                java.util.StringTokenizer st = new java.util.StringTokenizer(typeAndCredential, " ");
                String type = st.nextToken();
                String userAndPasswordB64 = st.nextToken();
                String s = new String(Base64.getDecoder().decode(userAndPasswordB64));
                // System.out.println("type="+type+" decoded="+s);
                if (type.equals("Basic")) {
                    java.util.StringTokenizer st2 = new java.util.StringTokenizer(s, ":");
                    if (st2.countTokens() == 2) {
                        String usr = st2.nextToken();
                        String pw = st2.nextToken();
                        // System.out.println("user="+usr+" password="+pw);
                        UserLoginInfo.DigestedPassword dpw = new UserLoginInfo.DigestedPassword(pw);
                        // System.out.println(dpw);
                        VCellApiApplication application = ((VCellApiApplication) getApplication());
                        authuser = application.getUserVerifier().authenticateUser(usr, dpw.getString().toCharArray());
                    // System.out.println(authuser);
                    }
                }
            }
            if (authuser == null) {
                // Response headers container might be null so add one if necessary
                if (((HttpResponse) response).getHeaders() == null) {
                    ((HttpResponse) response).getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, new Series(Header.class));
                }
                // Tell whoever called us we want a user and password that we will check against admin vcell users
                HttpResponse.addHeader(response, "WWW-Authenticate", "Basic");
                response.setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
                return;
            }
            Form form = request.getResourceRef().getQueryAsForm();
            if (form.getFirst("stats") != null) {
                // get .../rpc?stats=value 'value'
                String requestTypeString = form.getFirstValue("stats", true);
                if ((authuser.getName().equals("frm") || authuser.getName().equals("les") || authuser.getName().equals("ion") || authuser.getName().equals("danv") || authuser.getName().equals("mblinov") || authuser.getName().equals("ACowan"))) {
                    String result = restDatabaseService.getBasicStatistics();
                    response.setStatus(Status.SUCCESS_OK);
                    response.setEntity(result, MediaType.TEXT_HTML);
                    return;
                }
            }
        } catch (Exception e) {
            String errMesg = "<html><body>Error RpcRestlet.handle(...) req='" + req.toString() + "' <br>err='" + e.getMessage() + "'</br>" + "</body></html>";
            getLogger().severe(errMesg);
            e.printStackTrace();
            response.setStatus(Status.SERVER_ERROR_INTERNAL);
            response.setEntity(errMesg, MediaType.TEXT_HTML);
        }
    } else if (req.getMethod().equals(Method.POST)) {
        String destination = null;
        String method = null;
        try {
            VCellApiApplication application = ((VCellApiApplication) getApplication());
            User vcellUser = application.getVCellUser(req.getChallengeResponse(), AuthenticationPolicy.prohibitInvalidCredentials);
            HttpRequest request = (HttpRequest) req;
            String username = vcellUser.getName();
            String userkey = vcellUser.getID().toString();
            destination = request.getHeaders().getFirstValue("Destination");
            method = request.getHeaders().getFirstValue("Method");
            String returnRequired = request.getHeaders().getFirstValue("ReturnRequired");
            String timeoutMS = request.getHeaders().getFirstValue("TimeoutMS");
            String compressed = request.getHeaders().getFirstValue("Compressed");
            String klass = request.getHeaders().getFirstValue("Class");
            if (lg.isTraceEnabled()) {
                lg.trace("username=" + username + ", userkey=" + userkey + ", destination=" + destination + ", method=" + method + ", returnRequired=" + returnRequired + ", timeoutMS=" + timeoutMS + ", compressed=" + compressed + ", class=" + klass);
            }
            req.bufferEntity();
            Serializable rpcRequestBodyObject = VCellApiClient.fromCompressedSerialized(req.getEntity().getStream());
            if (!(rpcRequestBodyObject instanceof VCellApiRpcBody)) {
                throw new RuntimeException("expecting post content of type VCellApiRpcBody");
            }
            VCellApiRpcBody rpcBody = (VCellApiRpcBody) rpcRequestBodyObject;
            if (rpcBody.rpcRequest.methodName == null || (User.isGuest(username) && !vcellguestAllowed.contains(rpcBody.rpcRequest.methodName))) {
                throw new IllegalArgumentException(User.createGuestErrorMessage(rpcBody.rpcRequest.methodName));
            }
            RpcServiceType st = null;
            VCellQueue queue = null;
            switch(rpcBody.rpcRequest.rpcDestination) {
                case DataRequestQueue:
                    {
                        st = RpcServiceType.DATA;
                        queue = VCellQueue.DataRequestQueue;
                        break;
                    }
                case DbRequestQueue:
                    {
                        st = RpcServiceType.DB;
                        queue = VCellQueue.DbRequestQueue;
                        break;
                    }
                case SimReqQueue:
                    {
                        st = RpcServiceType.DISPATCH;
                        queue = VCellQueue.SimReqQueue;
                        break;
                    }
                default:
                    {
                        throw new RuntimeException("unsupported RPC Destination: " + rpcBody.rpcDestination);
                    }
            }
            VCellApiRpcRequest vcellapiRpcRequest = rpcBody.rpcRequest;
            Serializable serializableResultObject = null;
            /*if(vcellapiRpcRequest.methodName != null && vcellapiRpcRequest.methodName.equals("getVCInfoContainer")) {
					serializableResultObject = restDatabaseService.getVCInfoContainer(vcellUser);
				}else if(vcellapiRpcRequest.methodName != null && vcellapiRpcRequest.methodName.equals("getBioModelXML")) {
					serializableResultObject = restDatabaseService.getBioModelXML((KeyValue)vcellapiRpcRequest.args[1], vcellUser);
				}else if(vcellapiRpcRequest.methodName != null && vcellapiRpcRequest.methodName.equals("getMathModelXML")) {
					serializableResultObject = restDatabaseService.getMathModelXML((KeyValue)vcellapiRpcRequest.args[1], vcellUser);
				}else */
            if (vcellapiRpcRequest.methodName != null && vcellapiRpcRequest.methodName.equals("getSimulationStatus")) {
                if (vcellapiRpcRequest.args[1] instanceof KeyValue[]) {
                    serializableResultObject = restDatabaseService.getSimulationStatus((KeyValue[]) vcellapiRpcRequest.args[1], vcellUser);
                } else if (vcellapiRpcRequest.args[1] instanceof KeyValue) {
                    serializableResultObject = restDatabaseService.getSimulationStatus((KeyValue) vcellapiRpcRequest.args[1], vcellUser);
                }
            } else if (vcellapiRpcRequest.methodName != null && vcellapiRpcRequest.methodName.equals("getSpecialUsers")) {
                serializableResultObject = restDatabaseService.getSpecialUsers(vcellUser);
            } else {
                Object[] arglist = vcellapiRpcRequest.args;
                String[] specialProperties = rpcBody.specialProperties;
                Object[] specialValues = rpcBody.specialValues;
                VCRpcRequest vcRpcRequest = new VCRpcRequest(vcellUser, st, method, arglist);
                VCellApiApplication vcellApiApplication = (VCellApiApplication) getApplication();
                RpcService rpcService = vcellApiApplication.getRpcService();
                serializableResultObject = rpcService.sendRpcMessage(queue, vcRpcRequest, new Boolean(rpcBody.returnedRequired), specialProperties, specialValues, new UserLoginInfo(username, null));
            }
            byte[] serializedResultObject = VCellApiClient.toCompressedSerialized(serializableResultObject);
            response.setStatus(Status.SUCCESS_OK, "rpc method=" + method + " succeeded");
            response.setEntity(new ByteArrayRepresentation(serializedResultObject));
        } catch (Exception e) {
            getLogger().severe("internal error invoking " + destination + ":" + method + "(): " + e.getMessage());
            e.printStackTrace();
            response.setStatus(Status.SERVER_ERROR_INTERNAL);
            if (e.getCause() instanceof ServerRejectedSaveException) {
                // send back actual exception, client needs specific cause
                try {
                    byte[] serializedResultObject = VCellApiClient.toCompressedSerialized(e.getCause());
                    response.setEntity(new ByteArrayRepresentation(serializedResultObject));
                    return;
                } catch (Exception e1) {
                    e1.printStackTrace();
                // continue and send error message
                }
            }
            response.setEntity("internal error invoking " + destination + ":" + method + "(): " + e.getMessage(), MediaType.TEXT_PLAIN);
        }
    }
}
Also used : Serializable(java.io.Serializable) User(org.vcell.util.document.User) RpcServiceType(cbit.vcell.message.VCRpcRequest.RpcServiceType) KeyValue(org.vcell.util.document.KeyValue) Form(org.restlet.data.Form) VCellApiApplication(org.vcell.rest.VCellApiApplication) VCellQueue(cbit.vcell.message.VCellQueue) HttpRequest(org.restlet.engine.adapter.HttpRequest) VCellApiRpcBody(org.vcell.api.client.VCellApiClient.VCellApiRpcBody) VCRpcRequest(cbit.vcell.message.VCRpcRequest) ServerRejectedSaveException(cbit.vcell.clientdb.ServerRejectedSaveException) VCellApiRpcRequest(org.vcell.api.client.VCellApiRpcRequest) ServerRejectedSaveException(cbit.vcell.clientdb.ServerRejectedSaveException) Series(org.restlet.util.Series) Header(org.restlet.engine.header.Header) ByteArrayRepresentation(org.restlet.representation.ByteArrayRepresentation) UserLoginInfo(org.vcell.util.document.UserLoginInfo)

Aggregations

ServerRejectedSaveException (cbit.vcell.clientdb.ServerRejectedSaveException)1 VCRpcRequest (cbit.vcell.message.VCRpcRequest)1 RpcServiceType (cbit.vcell.message.VCRpcRequest.RpcServiceType)1 VCellQueue (cbit.vcell.message.VCellQueue)1 Serializable (java.io.Serializable)1 Form (org.restlet.data.Form)1 HttpRequest (org.restlet.engine.adapter.HttpRequest)1 Header (org.restlet.engine.header.Header)1 ByteArrayRepresentation (org.restlet.representation.ByteArrayRepresentation)1 Series (org.restlet.util.Series)1 VCellApiRpcBody (org.vcell.api.client.VCellApiClient.VCellApiRpcBody)1 VCellApiRpcRequest (org.vcell.api.client.VCellApiRpcRequest)1 VCellApiApplication (org.vcell.rest.VCellApiApplication)1 KeyValue (org.vcell.util.document.KeyValue)1 User (org.vcell.util.document.User)1 UserLoginInfo (org.vcell.util.document.UserLoginInfo)1