JsonExporter.java 2.34 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  javax.servlet.ServletOutputStream
 *  org.apache.sling.api.SlingHttpServletResponse
 *  org.apache.sling.commons.json.JSONException
 *  org.apache.sling.commons.json.io.JSONWriter
 */
package com.adobe.granite.i18n.impl.bundle;

import com.adobe.granite.i18n.impl.bundle.ResourceBundleExporter;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Enumeration;
import java.util.ResourceBundle;
import javax.servlet.ServletOutputStream;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.io.JSONWriter;

public class JsonExporter
implements ResourceBundleExporter {
    private static final String CONTENT_TYPE_JSON = "application/json";

    public void export(ResourceBundle bundle, SlingHttpServletResponse response) throws IOException {
        StringWriter out = new StringWriter();
        JSONWriter json = new JSONWriter((Writer)out);
        try {
            json.object();
            if (bundle != null) {
                Enumeration<String> keys = bundle.getKeys();
                while (keys.hasMoreElements()) {
                    String key = keys.nextElement();
                    Object resource = bundle.getObject(key);
                    if (resource == null) continue;
                    json.key(key);
                    if (resource.getClass().isArray()) {
                        Object[] arrResource;
                        json.array();
                        for (Object res : arrResource = (Object[])resource) {
                            json.value((Object)String.valueOf(res));
                        }
                        json.endArray();
                        continue;
                    }
                    json.value((Object)String.valueOf(resource));
                }
            }
            json.endObject();
        }
        catch (JSONException je) {
            throw (IOException)new IOException("Cannot write JSON").initCause((Throwable)je);
        }
        byte[] data = out.toString().getBytes("utf-8");
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        response.setContentLength(data.length);
        response.getOutputStream().write(data);
    }
}