Search in sources :

Example 16 with BinaryResource

use of org.eclipse.scout.rt.platform.resource.BinaryResource in project scout.rt by eclipse.

the class MailHelperTest method testAddResourcesAsAttachments.

@Test
public void testAddResourcesAsAttachments() throws IOException, MessagingException {
    // create html mime message without attachments
    final String plainText = "plain text";
    final String html = "<html><body><p>plain text</p></html>";
    MailMessage definition = new MailMessage().withBodyPlainText(plainText).withBodyHtml(html);
    MimeMessage message = BEANS.get(MailHelper.class).createMimeMessage(definition);
    verifyMimeMessage(message, plainText, html);
    // add no attachments
    BEANS.get(MailHelper.class).addAttachmentsToMimeMessage(message, null);
    verifyMimeMessage(message, plainText, html);
    BEANS.get(MailHelper.class).addAttachmentsToMimeMessage(message, new ArrayList<File>());
    verifyMimeMessage(message, plainText, html);
    // add 3 attachments to mime message
    final byte[] sampleData = new byte[] { 0x0, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF };
    List<BinaryResource> attachments = new ArrayList<BinaryResource>();
    attachments.add(new BinaryResource("sample1.dat", sampleData));
    attachments.add(new BinaryResource("sample2.dat", sampleData));
    attachments.add(new BinaryResource("sample3_öüä.dat", sampleData));
    BEANS.get(MailHelper.class).addResourcesAsAttachments(message, attachments);
    // verify added attachments in java instance
    verifyMimeMessage(message, plainText, html, "sample1.dat", "sample2.dat", "sample3_öüä.dat");
    // store and recreate mime message (byte[])
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    message.writeTo(bos);
    message = BEANS.get(MailHelper.class).createMessageFromBytes(bos.toByteArray());
    // verify new instance
    verifyMimeMessage(message, plainText, html, "sample1.dat", "sample2.dat", "sample3_öüä.dat");
}
Also used : BinaryResource(org.eclipse.scout.rt.platform.resource.BinaryResource) MimeMessage(javax.mail.internet.MimeMessage) ArrayList(java.util.ArrayList) ByteArrayOutputStream(java.io.ByteArrayOutputStream) File(java.io.File) Test(org.junit.Test)

Example 17 with BinaryResource

use of org.eclipse.scout.rt.platform.resource.BinaryResource in project scout.rt by eclipse.

the class UploadRequestHandler method readUploadData.

/**
 * Since 5.2 this performs a {@link MalwareScanner#scan(BinaryResource)} on the resources and throws a
 * {@link PlatformException} if some resources are unsafe
 */
protected void readUploadData(HttpServletRequest httpReq, long maxSize, Map<String, String> uploadProperties, List<BinaryResource> uploadResources) throws FileUploadException, IOException {
    ServletFileUpload upload = new ServletFileUpload();
    upload.setHeaderEncoding(StandardCharsets.UTF_8.name());
    upload.setSizeMax(maxSize);
    for (FileItemIterator it = upload.getItemIterator(httpReq); it.hasNext(); ) {
        FileItemStream item = it.next();
        String filename = item.getName();
        if (StringUtility.hasText(filename)) {
            String[] parts = StringUtility.split(filename, "[/\\\\]");
            filename = parts[parts.length - 1];
        }
        byte[] content;
        try (InputStream in = item.openStream()) {
            content = IOUtility.readBytes(in);
        }
        String contentType = item.getContentType();
        BinaryResource res = BinaryResources.create().withFilename(filename).withContentType(contentType).withContent(content).build();
        verifyFileSafety(res);
        if (item.isFormField()) {
            // Handle non-file fields (interpreted as properties)
            String name = item.getFieldName();
            uploadProperties.put(name, new String(content, StandardCharsets.UTF_8));
        } else {
            // Handle files
            // Info: we cannot set the charset property for uploaded files here, because we simply don't know it.
            // the only thing we could do is to guess the charset (encoding) by reading the byte contents of
            // uploaded text files (for binary file types the encoding is not relevant). However: currently we
            // do not set the charset at all.
            uploadResources.add(res);
        }
    }
}
Also used : ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) BinaryResource(org.eclipse.scout.rt.platform.resource.BinaryResource) FileItemStream(org.apache.commons.fileupload.FileItemStream) InputStream(java.io.InputStream) FileItemIterator(org.apache.commons.fileupload.FileItemIterator)

Example 18 with BinaryResource

use of org.eclipse.scout.rt.platform.resource.BinaryResource in project scout.rt by eclipse.

the class DefaultValuesFilterService method getCombinedDefaultValuesConfigurationFile.

@Override
public synchronized BinaryResource getCombinedDefaultValuesConfigurationFile(String targetFilename) {
    ensureLoaded();
    byte[] content = (m_combinedDefaultValuesConfiguration == null ? null : m_combinedDefaultValuesConfiguration.getBytes(StandardCharsets.UTF_8));
    BinaryResource res = BinaryResources.create().withFilename(targetFilename).withContentType(FileUtility.getContentTypeForExtension("json")).withContent(content).withLastModified(m_lastModified).withCachingAllowed(true).withCacheMaxAge(HttpCacheControl.MAX_AGE_4_HOURS).build();
    return res;
}
Also used : BinaryResource(org.eclipse.scout.rt.platform.resource.BinaryResource)

Example 19 with BinaryResource

use of org.eclipse.scout.rt.platform.resource.BinaryResource in project scout.rt by eclipse.

the class JsonBean method toJson.

@Override
public Object toJson() {
    if (m_bean == null) {
        return null;
    }
    Class<?> type = m_bean.getClass();
    // basic types
    if (type.isPrimitive() || type == String.class || type == Boolean.class || Number.class.isAssignableFrom(type)) {
        return m_bean;
    }
    // binary resource
    if (BinaryResource.class.isAssignableFrom(type)) {
        BinaryResource binaryResource = (BinaryResource) m_bean;
        m_binaryResourceMediator.addBinaryResource(binaryResource);
        return m_binaryResourceMediator.createUrl(binaryResource);
    }
    // array
    if (type.isArray()) {
        JSONArray jsonArray = new JSONArray();
        int n = Array.getLength(m_bean);
        for (int i = 0; i < n; i++) {
            IJsonObject jsonObject = createJsonObject(Array.get(m_bean, i));
            jsonArray.put(jsonObject.toJson());
        }
        return jsonArray;
    }
    // collection
    if (Collection.class.isAssignableFrom(type)) {
        JSONArray jsonArray = new JSONArray();
        Collection collection = (Collection) m_bean;
        for (Object object : collection) {
            IJsonObject jsonObject = createJsonObject(object);
            jsonArray.put(jsonObject.toJson());
        }
        return jsonArray;
    }
    // Map
    if (Map.class.isAssignableFrom(type)) {
        JSONObject jsonMap = new JSONObject();
        Map map = (Map) m_bean;
        @SuppressWarnings("unchecked") Set<Entry> entries = (Set<Entry>) map.entrySet();
        for (Entry entry : entries) {
            if (!(entry.getKey() instanceof String)) {
                throw new IllegalArgumentException("Cannot convert " + type + " to json object");
            }
            IJsonObject jsonObject = createJsonObject(entry.getValue());
            jsonMap.put((String) entry.getKey(), jsonObject.toJson());
        }
        return jsonMap;
    }
    // bean
    if (type.getName().startsWith("java.")) {
        throw new IllegalArgumentException("Cannot convert " + type + " to json object");
    }
    try {
        TreeMap<String, Object> properties = new TreeMap<>();
        for (Field f : type.getFields()) {
            if (Modifier.isStatic(f.getModifiers())) {
                continue;
            }
            String key = f.getName();
            Object val = f.get(m_bean);
            IJsonObject jsonObject = createJsonObject(val);
            properties.put(key, jsonObject.toJson());
        }
        FastBeanInfo beanInfo = new FastBeanInfo(type, Object.class);
        for (FastPropertyDescriptor desc : beanInfo.getPropertyDescriptors()) {
            Method m = desc.getReadMethod();
            if (m == null) {
                continue;
            }
            // skip ignored annotated getters with context GUI
            IgnoreProperty ignoredPropertyAnnotation = m.getAnnotation(IgnoreProperty.class);
            if (ignoredPropertyAnnotation != null && Context.GUI.equals(ignoredPropertyAnnotation.value())) {
                continue;
            }
            String key = desc.getName();
            Object val = m.invoke(m_bean);
            IJsonObject jsonObject = createJsonObject(val);
            properties.put(key, jsonObject.toJson());
        }
        JSONObject jbean = new JSONObject();
        for (Map.Entry<String, Object> e : properties.entrySet()) {
            jbean.put(e.getKey(), e.getValue());
        }
        return jbean;
    } catch (Exception e) {
        throw new IllegalArgumentException(type + " to json", e);
    }
}
Also used : Set(java.util.Set) FastPropertyDescriptor(org.eclipse.scout.rt.platform.reflect.FastPropertyDescriptor) FastBeanInfo(org.eclipse.scout.rt.platform.reflect.FastBeanInfo) Field(java.lang.reflect.Field) Entry(java.util.Map.Entry) JSONArray(org.json.JSONArray) Method(java.lang.reflect.Method) TreeMap(java.util.TreeMap) BinaryResource(org.eclipse.scout.rt.platform.resource.BinaryResource) JSONObject(org.json.JSONObject) IgnoreProperty(org.eclipse.scout.rt.platform.annotations.IgnoreProperty) Collection(java.util.Collection) JSONObject(org.json.JSONObject) TreeMap(java.util.TreeMap) Map(java.util.Map)

Example 20 with BinaryResource

use of org.eclipse.scout.rt.platform.resource.BinaryResource in project scout.rt by eclipse.

the class AbstractForm method doExportXml.

@Override
public void doExportXml(boolean saveAs) {
    // export search parameters
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
        Writer w = new OutputStreamWriter(bos, StandardCharsets.UTF_8)) {
        XmlUtility.wellformDocument(storeToXml(), w);
        BinaryResource res = new BinaryResource("form.xml", bos.toByteArray());
        getDesktop().openUri(res, OpenUriAction.DOWNLOAD);
    } catch (Exception e) {
        BEANS.get(ExceptionHandler.class).handle(new ProcessingException(TEXTS.get("FormExportXml") + " " + getTitle(), e));
    }
}
Also used : BinaryResource(org.eclipse.scout.rt.platform.resource.BinaryResource) OutputStreamWriter(java.io.OutputStreamWriter) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Writer(java.io.Writer) OutputStreamWriter(java.io.OutputStreamWriter) PlatformException(org.eclipse.scout.rt.platform.exception.PlatformException) ProcessingException(org.eclipse.scout.rt.platform.exception.ProcessingException) VetoException(org.eclipse.scout.rt.platform.exception.VetoException) ProcessingException(org.eclipse.scout.rt.platform.exception.ProcessingException)

Aggregations

BinaryResource (org.eclipse.scout.rt.platform.resource.BinaryResource)46 Test (org.junit.Test)26 HttpCacheObject (org.eclipse.scout.rt.server.commons.servlet.cache.HttpCacheObject)19 HttpCacheKey (org.eclipse.scout.rt.server.commons.servlet.cache.HttpCacheKey)15 ProcessingException (org.eclipse.scout.rt.platform.exception.ProcessingException)4 BinaryResourceHolder (org.eclipse.scout.rt.ui.html.res.BinaryResourceHolder)4 InputStream (java.io.InputStream)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 HashSet (java.util.HashSet)2 PlatformException (org.eclipse.scout.rt.platform.exception.PlatformException)2 JSONObject (org.json.JSONObject)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 File (java.io.File)1 OutputStream (java.io.OutputStream)1 OutputStreamWriter (java.io.OutputStreamWriter)1 Writer (java.io.Writer)1 Field (java.lang.reflect.Field)1