Search in sources :

Example 1 with ApiStreamSource

use of com.bluenimble.platform.api.ApiStreamSource in project serverless by bluenimble.

the class InstallApiSpi method execute.

@Override
public ApiOutput execute(Api api, ApiConsumer consumer, ApiRequest request, ApiResponse response) throws ApiServiceExecutionException {
    ApiStreamSource stream = (ApiStreamSource) request.get(ApiRequest.Payload, Scope.Stream);
    Boolean start = (Boolean) request.get(Spec.Start);
    if (start == null) {
        start = false;
    }
    ApiSpace targetSpace = null;
    Api installed = null;
    try {
        targetSpace = MgmUtils.space(consumer, api);
        installed = targetSpace.install(stream);
    } catch (Exception ex) {
        throw new ApiServiceExecutionException(ex.getMessage(), ex);
    }
    if (installed == null) {
        throw new ApiServiceExecutionException("can't install api. Server can't return a valid api object");
    }
    try {
        if (start) {
            targetSpace.start(installed.getNamespace());
        }
    } catch (Exception ex) {
        throw new ApiServiceExecutionException(ex.getMessage(), ex);
    }
    return new JsonApiOutput(installed.describe(MgmUtils.options((String) request.get(CommonSpec.Options), DescribeOption.Info)));
}
Also used : ApiSpace(com.bluenimble.platform.api.ApiSpace) ApiServiceExecutionException(com.bluenimble.platform.api.ApiServiceExecutionException) Api(com.bluenimble.platform.api.Api) ApiStreamSource(com.bluenimble.platform.api.ApiStreamSource) ApiServiceExecutionException(com.bluenimble.platform.api.ApiServiceExecutionException) JsonApiOutput(com.bluenimble.platform.api.impls.JsonApiOutput)

Example 2 with ApiStreamSource

use of com.bluenimble.platform.api.ApiStreamSource in project serverless by bluenimble.

the class UpdateObjectSpi method execute.

@Override
public ApiOutput execute(Api api, ApiConsumer consumer, ApiRequest request, ApiResponse response) throws ApiServiceExecutionException {
    ApiSpace space;
    try {
        space = MgmUtils.space(consumer, api);
    } catch (ApiAccessDeniedException e) {
        throw new ApiServiceExecutionException(e.getMessage(), e).status(ApiResponse.FORBIDDEN);
    }
    String provider = (String) request.get(CommonSpec.Provider);
    String path = (String) request.get(Spec.Object);
    Boolean append = (Boolean) request.get(Spec.Append);
    if (append == null) {
        append = false;
    }
    ApiStreamSource ss = (ApiStreamSource) request.get(ApiRequest.Payload, Scope.Stream);
    Storage storage = space.feature(Storage.class, provider, request);
    StorageObject so = null;
    try {
        so = storage.root().get(path);
    } catch (StorageException e) {
        throw new ApiServiceExecutionException("storage object '" + path + "' not found", e).status(ApiResponse.NOT_FOUND);
    }
    if (so.isFolder() && ss != null) {
        throw new ApiServiceExecutionException("object '" + path + "' isn't a valid content aware storage object").status(ApiResponse.BAD_REQUEST);
    }
    InputStream stream = ss.stream();
    try {
        so.update(stream, append);
    } catch (StorageException e) {
        throw new ApiServiceExecutionException(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(stream);
    }
    return new JsonApiOutput((JsonObject) new JsonObject().set(CommonOutput.Updated, true));
}
Also used : ApiAccessDeniedException(com.bluenimble.platform.api.ApiAccessDeniedException) Storage(com.bluenimble.platform.storage.Storage) StorageObject(com.bluenimble.platform.storage.StorageObject) ApiSpace(com.bluenimble.platform.api.ApiSpace) ApiServiceExecutionException(com.bluenimble.platform.api.ApiServiceExecutionException) InputStream(java.io.InputStream) JsonObject(com.bluenimble.platform.json.JsonObject) ApiStreamSource(com.bluenimble.platform.api.ApiStreamSource) StorageException(com.bluenimble.platform.storage.StorageException) JsonApiOutput(com.bluenimble.platform.api.impls.JsonApiOutput)

Example 3 with ApiStreamSource

use of com.bluenimble.platform.api.ApiStreamSource in project serverless by bluenimble.

the class SmtpMessenger method send.

@Override
public void send(Sender sender, Recipient[] recipients, String subject, String content, ApiStreamSource... attachments) throws MessengerException {
    ClassLoader pcl = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
    // creates a new e-mail message
    try {
        if (sender == null) {
            sender = NoSender;
        }
        Message message = new MimeMessage(session);
        String senderEmail = sender.id();
        if (Lang.isNullOrEmpty(senderEmail)) {
            senderEmail = user;
        }
        String senderName = sender.name();
        if (Lang.isNullOrEmpty(senderName)) {
            message.setFrom(new InternetAddress(senderEmail));
        } else {
            message.setFrom(new InternetAddress(senderEmail, senderName));
        }
        InternetAddress[] toAddresses = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            toAddresses[i] = new InternetAddress(recipients[i].id());
        }
        message.setRecipients(Message.RecipientType.TO, toAddresses);
        message.setSubject(subject);
        message.setSentDate(new Date());
        // creates message part
        MimeBodyPart messageText = new MimeBodyPart();
        messageText.setContent(content, ApiContentTypes.Html);
        // creates multi-part
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageText);
        // adds attachments
        if (attachments != null && attachments.length > 0) {
            for (final ApiStreamSource attachment : attachments) {
                MimeBodyPart mbd = new MimeBodyPart();
                DataSource ds = new DataSource() {

                    @Override
                    public String getContentType() {
                        return attachment.contentType();
                    }

                    @Override
                    public InputStream getInputStream() throws IOException {
                        return attachment.stream();
                    }

                    @Override
                    public String getName() {
                        return attachment.name();
                    }

                    @Override
                    public OutputStream getOutputStream() throws IOException {
                        throw new UnsupportedOperationException("getOutputStream not supported");
                    }
                };
                mbd.setDataHandler(new DataHandler(ds));
                multipart.addBodyPart(mbd);
            }
        }
        // sets the multi-part as e-mail's content
        message.setContent(multipart);
        // sends the e-mail
        Transport.send(message);
    } catch (Exception ex) {
        throw new MessengerException(ex.getMessage(), ex);
    } finally {
        Thread.currentThread().setContextClassLoader(pcl);
    }
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) Multipart(javax.mail.Multipart) MimeMultipart(javax.mail.internet.MimeMultipart) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) MessengerException(com.bluenimble.platform.messaging.MessengerException) DataHandler(javax.activation.DataHandler) ApiStreamSource(com.bluenimble.platform.api.ApiStreamSource) Date(java.util.Date) IOException(java.io.IOException) MessengerException(com.bluenimble.platform.messaging.MessengerException) DataSource(javax.activation.DataSource) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) MimeBodyPart(javax.mail.internet.MimeBodyPart)

Example 4 with ApiStreamSource

use of com.bluenimble.platform.api.ApiStreamSource in project serverless by bluenimble.

the class HttpRemote method request.

private boolean request(ApiVerb verb, JsonObject spec, Callback callback, ApiStreamSource... attachments) {
    JsonObject rdata = Json.getObject(spec, Spec.Data);
    if (!Json.isNullOrEmpty(featureSpec)) {
        JsonObject master = featureSpec.duplicate();
        Json.resolve(master, ECompiler, new VariableResolver() {

            private static final long serialVersionUID = 1L;

            @Override
            public Object resolve(String namespace, String... property) {
                Object v = Json.find(rdata, property);
                Json.remove(rdata, property);
                return v;
            }
        });
        spec = master.merge(spec);
    }
    String endpoint = Json.getString(spec, Spec.Endpoint);
    String path = Json.getString(spec, Spec.Path);
    if (!Lang.isNullOrEmpty(path)) {
        endpoint += path;
    }
    Serializer.Name serName = null;
    try {
        serName = Serializer.Name.valueOf(Json.getString(spec, Spec.Serializer, Serializer.Name.text.name()).toLowerCase());
    } catch (Exception ex) {
        // ignore
        serName = Serializer.Name.text;
    }
    Serializer serializer = Serializers.get(serName);
    Request request = null;
    Response response = null;
    try {
        // contentType
        String contentType = null;
        // resole and add headers
        JsonObject headers = Json.getObject(spec, Spec.Headers);
        if (!Json.isNullOrEmpty(headers)) {
            Json.resolve(headers, ECompiler, new VariableResolver() {

                private static final long serialVersionUID = 1L;

                @Override
                public Object resolve(String namespace, String... property) {
                    return Json.find(rdata, property);
                }
            });
            Iterator<String> hnames = headers.keys();
            while (hnames.hasNext()) {
                String hn = hnames.next();
                String hv = Json.getString(headers, hn);
                if (HttpHeaders.CONTENT_TYPE.toUpperCase().equals(hn.toUpperCase())) {
                    contentType = hv;
                }
            }
        }
        if (Lang.isNullOrEmpty(contentType)) {
            contentType = ContentTypes.FormUrlEncoded;
        }
        contentType = contentType.trim();
        MediaType mediaType = MediaTypes.get(contentType);
        RequestBody body = null;
        List<RequestParameter> parameters = null;
        if (attachments != null && attachments.length > 0 && !Json.isNullOrEmpty(rdata)) {
            // multipart body
            MultipartBody.Builder builder = new MultipartBody.Builder();
            Iterator<String> pnames = rdata.keys();
            while (pnames.hasNext()) {
                String pn = pnames.next();
                builder.addFormDataPart(pn, String.valueOf(rdata.get(pn)));
            }
            for (ApiStreamSource ss : attachments) {
                try {
                    builder.addFormDataPart(ss.name(), ss.name(), RequestBody.create(MediaType.parse(contentType), IOUtils.toByteArray(ss.stream())));
                } catch (Exception ex) {
                    callback.onError(Error.Other, ex.getMessage());
                    return false;
                }
            }
        } else if (contentType.startsWith(ContentTypes.Json)) {
            body = RequestBody.create(mediaType, rdata == null ? JsonObject.EMPTY_OBJECT : rdata.toString());
        } else {
            if (!Json.isNullOrEmpty(rdata)) {
                // for bnb signature only
                if (Signers.Bnb.equals(Json.find(spec, Spec.Sign, Spec.SignProtocol))) {
                    parameters = new ArrayList<RequestParameter>();
                }
                if (verb.equals(ApiVerb.POST) || verb.equals(ApiVerb.PUT) || verb.equals(ApiVerb.PATCH)) {
                    FormBody.Builder fb = new FormBody.Builder();
                    Iterator<String> pnames = rdata.keys();
                    while (pnames.hasNext()) {
                        String pn = pnames.next();
                        fb.add(pn, String.valueOf(rdata.get(pn)));
                        if (parameters != null) {
                            parameters.add(new RequestParameter(pn, rdata.get(pn)));
                        }
                    }
                    body = fb.build();
                } else if (verb.equals(ApiVerb.GET)) {
                    HttpUrl.Builder urlBuilder = HttpUrl.parse(endpoint).newBuilder();
                    Iterator<String> pnames = rdata.keys();
                    while (pnames.hasNext()) {
                        String pn = pnames.next();
                        urlBuilder.addQueryParameter(pn, String.valueOf(rdata.get(pn)));
                        if (parameters != null) {
                            parameters.add(new RequestParameter(pn, rdata.get(pn)));
                        }
                    }
                    endpoint = urlBuilder.build().toString();
                }
            }
        }
        // create the request builder
        Request.Builder rBuilder = new Request.Builder().url(endpoint);
        rBuilder.header(HttpHeaders.USER_AGENT, DefaultUserAgent);
        // add headers
        if (!Json.isNullOrEmpty(headers)) {
            Iterator<String> hnames = headers.keys();
            while (hnames.hasNext()) {
                String hn = hnames.next();
                String hv = Json.getString(headers, hn);
                rBuilder.header(hn, hv);
            }
        }
        // create request
        switch(verb) {
            case GET:
                rBuilder.get();
                break;
            case POST:
                rBuilder.post(body);
                break;
            case DELETE:
                rBuilder.delete();
                break;
            case PUT:
                rBuilder.put(body);
                break;
            case PATCH:
                rBuilder.patch(body);
                break;
            case HEAD:
                rBuilder.head();
                break;
            default:
                break;
        }
        // build then sign
        request = sign(rBuilder.build(), spec, parameters);
        response = http.newCall(request).execute();
        if (response.code() > Json.getInteger(spec, Spec.SuccessCode, 202)) {
            callback.onError(response.code(), response.body().string());
            return false;
        } else {
            callback.onSuccess(response.code(), serializer.serialize(response.body().byteStream()));
            return true;
        }
    } catch (UnknownHostException uhex) {
        callback.onError(Error.UnknownHost, "Endpoint " + endpoint + " can't be resolved. Check your internet connection and make sure the endpoint is correct");
        return false;
    } catch (SocketTimeoutException stoex) {
        callback.onError(Error.Timeout, "Endpoint " + endpoint + " was found but " + stoex.getMessage());
        return false;
    } catch (Exception ex) {
        callback.onError(Error.Other, Lang.toError(ex));
        return false;
    } finally {
        if (response != null) {
            response.close();
        }
    }
}
Also used : ArrayList(java.util.ArrayList) JsonObject(com.bluenimble.platform.json.JsonObject) Iterator(java.util.Iterator) MediaType(okhttp3.MediaType) TextSerializer(com.bluenimble.platform.remote.impls.serializers.TextSerializer) Serializer(com.bluenimble.platform.remote.Serializer) StreamSerializer(com.bluenimble.platform.remote.impls.serializers.StreamSerializer) JsonSerializer(com.bluenimble.platform.remote.impls.serializers.JsonSerializer) XmlSerializer(com.bluenimble.platform.remote.impls.serializers.XmlSerializer) RequestBody(okhttp3.RequestBody) UnknownHostException(java.net.UnknownHostException) Request(okhttp3.Request) FormBody(okhttp3.FormBody) ApiStreamSource(com.bluenimble.platform.api.ApiStreamSource) SocketTimeoutException(java.net.SocketTimeoutException) UnknownHostException(java.net.UnknownHostException) HttpUrl(okhttp3.HttpUrl) Response(okhttp3.Response) SocketTimeoutException(java.net.SocketTimeoutException) MultipartBody(okhttp3.MultipartBody) JsonObject(com.bluenimble.platform.json.JsonObject) VariableResolver(com.bluenimble.platform.templating.VariableResolver)

Example 5 with ApiStreamSource

use of com.bluenimble.platform.api.ApiStreamSource in project serverless by bluenimble.

the class AddObjectSpi method execute.

@Override
public ApiOutput execute(Api api, ApiConsumer consumer, ApiRequest request, ApiResponse response) throws ApiServiceExecutionException {
    ApiSpace space;
    try {
        space = MgmUtils.space(consumer, api);
    } catch (ApiAccessDeniedException e) {
        throw new ApiServiceExecutionException(e.getMessage(), e).status(ApiResponse.FORBIDDEN);
    }
    String provider = (String) request.get(CommonSpec.Provider);
    ApiStreamSource stream = (ApiStreamSource) request.get(ApiRequest.Payload, Scope.Stream);
    Storage storage = space.feature(Storage.class, provider, request);
    String path = (String) request.get(Spec.Object);
    try {
        Folder root = storage.root();
        if (!Lang.isNullOrEmpty(path)) {
            String[] aPath = Lang.split(path, Lang.SLASH);
            for (String p : aPath) {
                if (!root.contains(p)) {
                    root = root.add(p, true);
                } else {
                    StorageObject so = root.get(p);
                    if (!so.isFolder()) {
                        throw new StorageException(p + " isn't a valid folder");
                    }
                    root = (Folder) so;
                }
            }
        }
        if (stream != null) {
            root.add(stream, stream.name(), true);
        }
    } catch (StorageException e) {
        throw new ApiServiceExecutionException(e.getMessage(), e);
    }
    return new JsonApiOutput((JsonObject) new JsonObject().set(CommonOutput.Added, true));
}
Also used : ApiAccessDeniedException(com.bluenimble.platform.api.ApiAccessDeniedException) Storage(com.bluenimble.platform.storage.Storage) StorageObject(com.bluenimble.platform.storage.StorageObject) ApiSpace(com.bluenimble.platform.api.ApiSpace) ApiServiceExecutionException(com.bluenimble.platform.api.ApiServiceExecutionException) JsonObject(com.bluenimble.platform.json.JsonObject) Folder(com.bluenimble.platform.storage.Folder) ApiStreamSource(com.bluenimble.platform.api.ApiStreamSource) StorageException(com.bluenimble.platform.storage.StorageException) JsonApiOutput(com.bluenimble.platform.api.impls.JsonApiOutput)

Aggregations

ApiStreamSource (com.bluenimble.platform.api.ApiStreamSource)6 ApiServiceExecutionException (com.bluenimble.platform.api.ApiServiceExecutionException)4 JsonApiOutput (com.bluenimble.platform.api.impls.JsonApiOutput)4 JsonObject (com.bluenimble.platform.json.JsonObject)4 ApiSpace (com.bluenimble.platform.api.ApiSpace)3 Storage (com.bluenimble.platform.storage.Storage)3 StorageException (com.bluenimble.platform.storage.StorageException)3 StorageObject (com.bluenimble.platform.storage.StorageObject)3 ApiAccessDeniedException (com.bluenimble.platform.api.ApiAccessDeniedException)2 Api (com.bluenimble.platform.api.Api)1 MessengerException (com.bluenimble.platform.messaging.MessengerException)1 Serializer (com.bluenimble.platform.remote.Serializer)1 JsonSerializer (com.bluenimble.platform.remote.impls.serializers.JsonSerializer)1 StreamSerializer (com.bluenimble.platform.remote.impls.serializers.StreamSerializer)1 TextSerializer (com.bluenimble.platform.remote.impls.serializers.TextSerializer)1 XmlSerializer (com.bluenimble.platform.remote.impls.serializers.XmlSerializer)1 Folder (com.bluenimble.platform.storage.Folder)1 VariableResolver (com.bluenimble.platform.templating.VariableResolver)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1