es.tid.cep.esperanza.Utils.java Source code

Java tutorial

Introduction

Here is the source code for es.tid.cep.esperanza.Utils.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package es.tid.cep.esperanza;

import com.espertech.esper.client.ConfigurationOperations;
import com.espertech.esper.client.EPServiceProvider;
import com.espertech.esper.client.EPServiceProviderManager;
import com.espertech.esper.client.EPStatement;
import com.espertech.esper.client.EventBean;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.ServletContext;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author brox
 */
public class Utils {

    private static final Logger logger = LoggerFactory.getLogger(Utils.class);
    private static final String EPSERV_ATTR_NAME = "epService";

    public static synchronized EPServiceProvider initEPService(ServletContext sc) {
        EPServiceProvider epService = (EPServiceProvider) sc.getAttribute(EPSERV_ATTR_NAME);
        if (epService == null) {
            epService = EPServiceProviderManager.getDefaultProvider();
            Map<String, Object> def = new HashMap<String, Object>();
            def.put("id", String.class);
            def.put("type", String.class);
            ConfigurationOperations cfg = epService.getEPAdministrator().getConfiguration();
            cfg.addEventType("iotEvent", def);
            sc.setAttribute(EPSERV_ATTR_NAME, epService);
        }
        return epService;
    }

    public static synchronized void destroyEPService(ServletContext sc) {
        EPServiceProvider epService = (EPServiceProvider) sc.getAttribute(EPSERV_ATTR_NAME);
        if (epService != null) {
            epService.destroy();
            sc.removeAttribute(EPSERV_ATTR_NAME);
        }
    }

    public static Map<String, Object> JSONObject2Map(JSONObject jo) {
        Map<String, Object> map = new HashMap<String, Object>();

        Iterator it = jo.keys();
        while (it.hasNext()) {
            String key = (String) it.next();
            Object o = jo.get(key);
            if (o instanceof JSONObject) {
                map.put(key, JSONObject2Map((JSONObject) o));
            } else {
                map.put(key, o);
            }
        }
        return map;
    }

    public static Map<String, Object> JSONObject2SimpleMap(JSONObject jo) {
        Map<String, Object> map = new HashMap<String, Object>();

        Iterator it = jo.keys();
        while (it.hasNext()) {
            String key = (String) it.next();
            Object o = jo.get(key);
            if (o instanceof String) {
                map.put(key, (String) o);
            } else {
                map.put(key, o.toString());
            }
        }
        return map;
    }

    public static JSONObject Event2JSONObject(EventBean event) {
        JSONObject jo = new JSONObject();
        Map<String, Object> errors = new HashMap<String, Object>();
        String[] propertyNames = event.getEventType().getPropertyNames();
        for (String propertyName : propertyNames) {
            try {
                jo.put(propertyName, event.get(propertyName));
            } catch (JSONException je) {
                errors.put(propertyName, je.getMessage());
                logger.error(je.getMessage());
            }
        }
        if (!errors.isEmpty()) {
            jo.put("errors", errors);
        }
        return jo;
    }

    public static JSONObject Statement2JSONObject(EPStatement st) {
        if (st == null) {
            return null;
        }
        JSONObject jo = new JSONObject().put("name", st.getName()).put("text", st.getText())
                .put("state", st.getState()).put("timeLastStateChange", st.getTimeLastStateChange());
        ;
        return jo;
    }

    public static boolean DoHTTPPost(String urlStr, String content) {
        try {
            URL url = new URL(urlStr);
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            urlConn.setDoOutput(true);
            urlConn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            OutputStreamWriter printout = new OutputStreamWriter(urlConn.getOutputStream(),
                    Charset.forName("UTF-8"));
            printout.write(content);
            printout.flush();
            printout.close();

            int code = urlConn.getResponseCode();
            String message = urlConn.getResponseMessage();
            logger.debug("action http response " + code + " " + message);
            if (code / 100 == 2) {
                InputStream input = urlConn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                for (String line; (line = reader.readLine()) != null;) {
                    logger.debug("action response body: " + line);
                }
                input.close();
                return true;

            } else {
                logger.error("action response is not OK: " + code + " " + message);
                InputStream error = urlConn.getErrorStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(error));
                for (String line; (line = reader.readLine()) != null;) {
                    logger.error("action error response body: " + line);
                }
                error.close();
                return false;
            }
        } catch (MalformedURLException me) {
            logger.error("exception MalformedURLException: " + me.getMessage());
            return false;
        } catch (IOException ioe) {
            logger.error("exception IOException: " + ioe.getMessage());
            return false;
        }
    }
}