Search in sources :

Example 1 with ByteArrayRepresentation

use of org.restlet.representation.ByteArrayRepresentation in project camel by apache.

the class DefaultRestletBinding method populateRestletResponseFromExchange.

public void populateRestletResponseFromExchange(Exchange exchange, Response response) throws Exception {
    Message out;
    if (exchange.isFailed()) {
        // 500 for internal server error which can be overridden by response code in header
        response.setStatus(Status.valueOf(500));
        Message msg = exchange.hasOut() ? exchange.getOut() : exchange.getIn();
        if (msg.isFault()) {
            out = msg;
        } else {
            // print exception as message and stacktrace
            Exception t = exchange.getException();
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            t.printStackTrace(pw);
            response.setEntity(sw.toString(), MediaType.TEXT_PLAIN);
            return;
        }
    } else {
        out = exchange.hasOut() ? exchange.getOut() : exchange.getIn();
    }
    // get content type
    MediaType mediaType = out.getHeader(Exchange.CONTENT_TYPE, MediaType.class);
    if (mediaType == null) {
        Object body = out.getBody();
        mediaType = MediaType.TEXT_PLAIN;
        if (body instanceof String) {
            mediaType = MediaType.TEXT_PLAIN;
        } else if (body instanceof StringSource || body instanceof DOMSource) {
            mediaType = MediaType.TEXT_XML;
        }
    }
    // get response code
    Integer responseCode = out.getHeader(Exchange.HTTP_RESPONSE_CODE, Integer.class);
    if (responseCode != null) {
        response.setStatus(Status.valueOf(responseCode));
    }
    // set response body according to the message body
    Object body = out.getBody();
    if (body instanceof WrappedFile) {
        // grab body from generic file holder
        GenericFile<?> gf = (GenericFile<?>) body;
        body = gf.getBody();
    }
    if (body == null) {
        // empty response
        response.setEntity("", MediaType.TEXT_PLAIN);
    } else if (body instanceof Response) {
        // its already a restlet response, so dont do anything
        LOG.debug("Using existing Restlet Response from exchange body: {}", body);
    } else if (body instanceof Representation) {
        response.setEntity(out.getBody(Representation.class));
    } else if (body instanceof InputStream) {
        response.setEntity(new InputRepresentation(out.getBody(InputStream.class), mediaType));
    } else if (body instanceof File) {
        response.setEntity(new FileRepresentation(out.getBody(File.class), mediaType));
    } else if (body instanceof byte[]) {
        byte[] bytes = out.getBody(byte[].class);
        response.setEntity(new ByteArrayRepresentation(bytes, mediaType, bytes.length));
    } else {
        // fallback and use string
        String text = out.getBody(String.class);
        response.setEntity(text, mediaType);
    }
    LOG.debug("Populate Restlet response from exchange body: {}", body);
    if (exchange.getProperty(Exchange.CHARSET_NAME) != null) {
        CharacterSet cs = CharacterSet.valueOf(exchange.getProperty(Exchange.CHARSET_NAME, String.class));
        response.getEntity().setCharacterSet(cs);
    }
    // set headers at the end, as the entity must be set first
    // NOTE: setting HTTP headers on restlet is cumbersome and its API is "weird" and has some flaws
    // so we need to headers two times, and the 2nd time we add the non-internal headers once more
    Series<Header> series = new Series<Header>(Header.class);
    for (Map.Entry<String, Object> entry : out.getHeaders().entrySet()) {
        String key = entry.getKey();
        Object value = entry.getValue();
        if (!headerFilterStrategy.applyFilterToCamelHeaders(key, value, exchange)) {
            boolean added = setResponseHeader(exchange, response, key, value);
            if (!added) {
                // we only want non internal headers
                if (!key.startsWith("Camel") && !key.startsWith("org.restlet")) {
                    String text = exchange.getContext().getTypeConverter().tryConvertTo(String.class, exchange, value);
                    if (text != null) {
                        series.add(key, text);
                    }
                }
            }
        }
    }
    // set HTTP headers so we return these in the response
    if (!series.isEmpty()) {
        response.getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, series);
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) Message(org.apache.camel.Message) StringWriter(java.io.StringWriter) WrappedFile(org.apache.camel.WrappedFile) MediaType(org.restlet.data.MediaType) CharacterSet(org.restlet.data.CharacterSet) PrintWriter(java.io.PrintWriter) InputRepresentation(org.restlet.representation.InputRepresentation) InputStream(java.io.InputStream) EmptyRepresentation(org.restlet.representation.EmptyRepresentation) StringRepresentation(org.restlet.representation.StringRepresentation) InputRepresentation(org.restlet.representation.InputRepresentation) ByteArrayRepresentation(org.restlet.representation.ByteArrayRepresentation) FileRepresentation(org.restlet.representation.FileRepresentation) StreamRepresentation(org.restlet.representation.StreamRepresentation) Representation(org.restlet.representation.Representation) DecodeRepresentation(org.restlet.engine.application.DecodeRepresentation) ParseException(java.text.ParseException) RuntimeCamelException(org.apache.camel.RuntimeCamelException) ChallengeResponse(org.restlet.data.ChallengeResponse) Response(org.restlet.Response) Series(org.restlet.util.Series) Header(org.restlet.data.Header) FileRepresentation(org.restlet.representation.FileRepresentation) ByteArrayRepresentation(org.restlet.representation.ByteArrayRepresentation) StringSource(org.apache.camel.StringSource) WrappedFile(org.apache.camel.WrappedFile) GenericFile(org.apache.camel.component.file.GenericFile) File(java.io.File) Map(java.util.Map) GenericFile(org.apache.camel.component.file.GenericFile)

Example 2 with ByteArrayRepresentation

use of org.restlet.representation.ByteArrayRepresentation in project camel by apache.

the class DefaultRestletBinding method createRepresentationFromBody.

protected Representation createRepresentationFromBody(Exchange exchange, MediaType mediaType) {
    Object body = exchange.getIn().getBody();
    if (body == null) {
        return new EmptyRepresentation();
    }
    // unwrap file
    if (body instanceof WrappedFile) {
        body = ((WrappedFile) body).getFile();
    }
    if (body instanceof InputStream) {
        return new InputRepresentation((InputStream) body, mediaType);
    } else if (body instanceof File) {
        return new FileRepresentation((File) body, mediaType);
    } else if (body instanceof byte[]) {
        return new ByteArrayRepresentation((byte[]) body, mediaType);
    } else if (body instanceof String) {
        return new StringRepresentation((CharSequence) body, mediaType);
    }
    // fallback as string
    body = exchange.getIn().getBody(String.class);
    if (body != null) {
        return new StringRepresentation((CharSequence) body, mediaType);
    } else {
        return new EmptyRepresentation();
    }
}
Also used : InputRepresentation(org.restlet.representation.InputRepresentation) EmptyRepresentation(org.restlet.representation.EmptyRepresentation) WrappedFile(org.apache.camel.WrappedFile) StringRepresentation(org.restlet.representation.StringRepresentation) InputStream(java.io.InputStream) FileRepresentation(org.restlet.representation.FileRepresentation) ByteArrayRepresentation(org.restlet.representation.ByteArrayRepresentation) WrappedFile(org.apache.camel.WrappedFile) GenericFile(org.apache.camel.component.file.GenericFile) File(java.io.File)

Example 3 with ByteArrayRepresentation

use of org.restlet.representation.ByteArrayRepresentation 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)

Example 4 with ByteArrayRepresentation

use of org.restlet.representation.ByteArrayRepresentation in project vcell by virtualcell.

the class BiomodelDiagramServerResource method get_png.

@Override
@Get("image/png")
public ByteArrayRepresentation get_png() {
    VCellApiApplication application = ((VCellApiApplication) getApplication());
    User vcellUser = application.getVCellUser(getChallengeResponse(), AuthenticationPolicy.ignoreInvalidCredentials);
    String vcml = getBiomodelVCML(vcellUser);
    if (vcml == null) {
        throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, "BioModel not found");
    }
    try {
        BioModel bioModel = XmlHelper.XMLToBioModel(new XMLSource(vcml));
        Integer imageWidthInPixels = 1000;
        BufferedImage bufferedImage = ITextWriter.generateDocReactionsImage(bioModel.getModel(), imageWidthInPixels);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "png", outputStream);
        byte[] imageBytes = outputStream.toByteArray();
        return new ByteArrayRepresentation(imageBytes, MediaType.IMAGE_PNG, imageBytes.length);
    } catch (Exception e) {
        e.printStackTrace();
        throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e.getMessage());
    }
}
Also used : User(org.vcell.util.document.User) BioModel(cbit.vcell.biomodel.BioModel) VCellApiApplication(org.vcell.rest.VCellApiApplication) ByteArrayRepresentation(org.restlet.representation.ByteArrayRepresentation) ResourceException(org.restlet.resource.ResourceException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) XMLSource(cbit.vcell.xml.XMLSource) BufferedImage(java.awt.image.BufferedImage) PermissionException(org.vcell.util.PermissionException) ObjectNotFoundException(org.vcell.util.ObjectNotFoundException) ResourceException(org.restlet.resource.ResourceException) Get(org.restlet.resource.Get)

Aggregations

ByteArrayRepresentation (org.restlet.representation.ByteArrayRepresentation)4 File (java.io.File)2 InputStream (java.io.InputStream)2 WrappedFile (org.apache.camel.WrappedFile)2 GenericFile (org.apache.camel.component.file.GenericFile)2 EmptyRepresentation (org.restlet.representation.EmptyRepresentation)2 FileRepresentation (org.restlet.representation.FileRepresentation)2 InputRepresentation (org.restlet.representation.InputRepresentation)2 StringRepresentation (org.restlet.representation.StringRepresentation)2 Series (org.restlet.util.Series)2 VCellApiApplication (org.vcell.rest.VCellApiApplication)2 User (org.vcell.util.document.User)2 BioModel (cbit.vcell.biomodel.BioModel)1 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 XMLSource (cbit.vcell.xml.XMLSource)1 BufferedImage (java.awt.image.BufferedImage)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1