Search in sources :

Example 1 with ISObject

use of org.osgl.storage.ISObject in project actframework by actframework.

the class ApacheMultipartParser method parse.

@Override
public Map<String, String[]> parse(ActionContext context) {
    H.Request request = context.req();
    InputStream body = request.inputStream();
    Map<String, String[]> result = new HashMap<>();
    try {
        FileItemIteratorImpl iter = new FileItemIteratorImpl(body, request.header("content-type"), request.characterEncoding());
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            ISObject sobj = UploadFileStorageService.store(item, context.app());
            if (sobj.getLength() == 0L) {
                continue;
            }
            String fieldName = item.getFieldName();
            if (item.isFormField()) {
                // must resolve encoding
                // this is our default
                String _encoding = request.characterEncoding();
                String _contentType = item.getContentType();
                if (_contentType != null) {
                    ContentTypeWithEncoding contentTypeEncoding = ContentTypeWithEncoding.parse(_contentType);
                    if (contentTypeEncoding.encoding != null) {
                        _encoding = contentTypeEncoding.encoding;
                    }
                }
                mergeValueInMap(result, fieldName, sobj.asString(Charset.forName(_encoding)));
            } else {
                context.addUpload(item.getFieldName(), sobj);
                mergeValueInMap(result, fieldName, fieldName);
            }
        }
    } catch (FileUploadIOException e) {
        throw E.ioException("Error when handling upload", e);
    } catch (IOException e) {
        throw E.ioException("Error when handling upload", e);
    } catch (FileUploadException e) {
        throw E.ioException("Error when handling upload", e);
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new UnexpectedException(e);
    }
    return result;
}
Also used : UnexpectedException(org.osgl.exception.UnexpectedException) HashMap(java.util.HashMap) LimitedInputStream(org.apache.commons.fileupload.util.LimitedInputStream) InputStream(java.io.InputStream) H(org.osgl.http.H) ISObject(org.osgl.storage.ISObject) IOException(java.io.IOException) IOException(java.io.IOException) UnexpectedException(org.osgl.exception.UnexpectedException) NoSuchElementException(java.util.NoSuchElementException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 2 with ISObject

use of org.osgl.storage.ISObject in project actframework by actframework.

the class FileBinder method resolve.

@Override
public File resolve(File file, String s, ParamValueProvider paramValueProvider) {
    ActionContext ctx = $.cast(paramValueProvider);
    ISObject sobj = ctx.upload(s);
    return null == sobj ? null : sobj.asFile();
}
Also used : ISObject(org.osgl.storage.ISObject) ActionContext(act.app.ActionContext)

Example 3 with ISObject

use of org.osgl.storage.ISObject in project actframework by actframework.

the class UploadFileStorageService method _store.

private ISObject _store(FileItemStream fileItemStream) throws IOException {
    String filename = fileItemStream.getName();
    String key = newKey(filename);
    File tmpFile = getFile(key);
    InputStream input = fileItemStream.openStream();
    ThresholdingByteArrayOutputStream output = new ThresholdingByteArrayOutputStream(inMemoryCacheThreshold, tmpFile);
    IO.copy(input, output);
    ISObject retVal;
    if (output.exceedThreshold) {
        retVal = getFull(key);
    } else {
        int size = output.written;
        byte[] buf = output.buf();
        retVal = SObject.of(key, buf, size);
    }
    if (S.notBlank(filename)) {
        retVal.setFilename(filename);
    }
    String contentType = fileItemStream.getContentType();
    if (null != contentType) {
        retVal.setContentType(contentType);
    }
    return retVal;
}
Also used : ISObject(org.osgl.storage.ISObject)

Example 4 with ISObject

use of org.osgl.storage.ISObject in project actframework by actframework.

the class RenderAny method apply.

// TODO: Allow plugin to support rendering pdf, xls or other binary types
public void apply(ActionContext context) {
    Boolean hasTemplate = context.hasTemplate();
    if (null != hasTemplate && hasTemplate) {
        RenderTemplate.get(context.successStatus()).apply(context);
        return;
    }
    H.Format fmt = context.accept();
    if (fmt == UNKNOWN) {
        H.Request req = context.req();
        H.Method method = req.method();
        String methodInfo = S.concat(method.name(), " method to ");
        String acceptHeader = req.header(H.Header.Names.ACCEPT);
        throw E.unsupport(S.concat("Unknown accept content type(", acceptHeader, "): ", methodInfo, req.url()));
    }
    Result result = null;
    if (JSON == fmt) {
        List<String> varNames = context.__appRenderArgNames();
        Map<String, Object> map = new HashMap<>(context.renderArgs());
        if (null != varNames && !varNames.isEmpty()) {
            for (String name : varNames) {
                map.put(name, context.renderArg(name));
            }
        }
        result = new RenderJSON(map);
    } else if (XML == fmt) {
        List<String> varNames = context.__appRenderArgNames();
        Map<String, Object> map = new HashMap<>();
        if (null != varNames && !varNames.isEmpty()) {
            for (String name : varNames) {
                map.put(name, context.renderArg(name));
            }
        }
        result = new FilteredRenderXML(map, null, context);
    } else if (HTML == fmt || TXT == fmt || CSV == fmt) {
        if (!ignoreMissingTemplate) {
            throw E.unsupport("Template[%s] not found", context.templatePath());
        }
        context.nullValueResultIgnoreRenderArgs().apply(context.req(), context.prepareRespForWrite());
        return;
    } else if (PDF == fmt || XLS == fmt || XLSX == fmt || DOC == fmt || DOCX == fmt) {
        List<String> varNames = context.__appRenderArgNames();
        if (null != varNames && !varNames.isEmpty()) {
            Object firstVar = context.renderArg(varNames.get(0));
            String action = S.str(context.actionPath()).afterLast(".").toString();
            if (firstVar instanceof File) {
                File file = (File) firstVar;
                result = new RenderBinary(file, action);
            } else if (firstVar instanceof InputStream) {
                InputStream is = (InputStream) firstVar;
                result = new RenderBinary(is, action);
            } else if (firstVar instanceof ISObject) {
                ISObject sobj = (ISObject) firstVar;
                result = new RenderBinary(sobj.asInputStream(), action);
            }
            if (null == result) {
                throw E.unsupport("Unknown render arg type [%s] for binary response", firstVar.getClass());
            }
        } else {
            throw E.unexpected("No render arg found for binary response");
        }
    }
    if (null != result) {
        ActResponse<?> resp = context.prepareRespForWrite();
        result.status(context.successStatus()).apply(context.req(), resp);
    } else {
        throw E.unexpected("Unknown accept content type: %s", fmt.contentType());
    }
}
Also used : Format(org.osgl.http.H.Format) HashMap(java.util.HashMap) InputStream(java.io.InputStream) RenderJSON(org.osgl.mvc.result.RenderJSON) H(org.osgl.http.H) ISObject(org.osgl.storage.ISObject) Result(org.osgl.mvc.result.Result) RenderBinary(org.osgl.mvc.result.RenderBinary) ISObject(org.osgl.storage.ISObject) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) File(java.io.File)

Example 5 with ISObject

use of org.osgl.storage.ISObject in project actframework by actframework.

the class MailerContext method createMessage.

private MimeMessage createMessage() throws Exception {
    MailerConfig config = mailerConfig();
    if (null == config) {
        throw E.unexpected("Cannot find mailer config for %s", confId);
    }
    Session session = mailerConfig().session();
    if (Act.isDev()) {
        session.setDebug(true);
    }
    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(from());
    msg.setSubject(subject());
    msg.setSentDate(new Date());
    msg.setRecipients(Message.RecipientType.TO, list2Array(to()));
    msg.setRecipients(Message.RecipientType.CC, list2Array(cc()));
    msg.setRecipients(Message.RecipientType.BCC, list2Array(bcc()));
    String content = this.content;
    if (null == content) {
        ViewManager vm = Act.viewManager();
        Template t = vm.load(this);
        E.illegalStateIf(null == t, "Mail template not defined");
        content = t.render(this);
    }
    if (attachments.isEmpty()) {
        msg.setText(content, config().encoding(), accept().name());
    } else {
        Multipart mp = new MimeMultipart();
        MimeBodyPart bp = new MimeBodyPart();
        mp.addBodyPart(bp);
        bp.setText(content, config().encoding(), accept().name());
        for (ISObject sobj : attachments) {
            String fileName = sobj.getAttribute(ISObject.ATTR_FILE_NAME);
            if (S.blank(fileName)) {
                fileName = sobj.getKey();
            }
            String contentType = sobj.getAttribute(ISObject.ATTR_CONTENT_TYPE);
            if (S.blank(contentType)) {
                contentType = "application/octet-stream";
            }
            MimeBodyPart attachment = new MimeBodyPart();
            attachment.attachFile(sobj.asFile(), contentType, null);
            attachment.setFileName(fileName);
            mp.addBodyPart(attachment);
        }
        msg.setContent(mp);
    }
    msg.saveChanges();
    return msg;
}
Also used : ViewManager(act.view.ViewManager) ISObject(org.osgl.storage.ISObject) Template(act.view.Template)

Aggregations

ISObject (org.osgl.storage.ISObject)5 InputStream (java.io.InputStream)2 HashMap (java.util.HashMap)2 H (org.osgl.http.H)2 ActionContext (act.app.ActionContext)1 Template (act.view.Template)1 ViewManager (act.view.ViewManager)1 File (java.io.File)1 IOException (java.io.IOException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 List (java.util.List)1 Map (java.util.Map)1 NoSuchElementException (java.util.NoSuchElementException)1 LimitedInputStream (org.apache.commons.fileupload.util.LimitedInputStream)1 UnexpectedException (org.osgl.exception.UnexpectedException)1 Format (org.osgl.http.H.Format)1 RenderBinary (org.osgl.mvc.result.RenderBinary)1 RenderJSON (org.osgl.mvc.result.RenderJSON)1 Result (org.osgl.mvc.result.Result)1