Java tutorial
/* AbstractEventManager.java Copyright (c) 2014 NTT DOCOMO,INC. Released under the MIT license http://opensource.org/licenses/mit-license.php */ package org.deviceconnect.message.event; import java.io.IOException; import java.net.URISyntaxException; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Logger; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.entity.StringEntity; import org.apache.http.impl.EnglishReasonPhraseCatalog; import org.apache.http.message.BasicHttpResponse; import org.apache.http.util.EntityUtils; import org.deviceconnect.message.DConnectMessage; import org.deviceconnect.utils.URIBuilder; import org.json.JSONException; import org.json.JSONObject; /** * ?????. * ????????????? * * @author NTT DOCOMO, INC. */ public abstract class AbstractEventManager { /** * ??. ??????? */ private Map<String, EventHandler> mHandlers; /** * . */ private Logger mLogger = Logger.getLogger("org.deviceconnect.sdk"); /** * . */ private String mSessionKey; /** * EventManager??. */ public AbstractEventManager() { mHandlers = new ConcurrentHashMap<String, EventHandler>(); } /** * ?????. * * @param key * @param handler ? */ private void addHandler(final String key, final EventHandler handler) { if (key == null) { throw new IllegalArgumentException("requestCode must no be null."); } else if (handler == null) { throw new IllegalArgumentException("handler must no be null."); } mHandlers.put(key, handler); } /** * ?????????. * * @param key */ private void removeHandler(final String key) { if (key == null) { throw new IllegalArgumentException("requestCode must no be null."); } mHandlers.remove(key); } /** * ?. * * @param sessionKey */ protected void setSessionKey(final String sessionKey) { mSessionKey = sessionKey; } /** * ??. * * @return */ protected String getSessionKey() { return mSessionKey; } /** * ???????. * * @param message * @throws JSONException JSON??????? */ protected void sendEvent(final JSONObject message) throws JSONException { String deviceId = message.getString(DConnectMessage.EXTRA_DEVICE_ID); String profile = message.getString(DConnectMessage.EXTRA_PROFILE); String inter = null; if (message.has(DConnectMessage.EXTRA_INTERFACE)) { inter = message.getString(DConnectMessage.EXTRA_INTERFACE); } String attribute = message.getString(DConnectMessage.EXTRA_ATTRIBUTE); String key = getKey(profile, inter, attribute, deviceId); EventHandler handler = null; synchronized (this) { handler = mHandlers.get(key); } if (handler != null) { handler.onEvent(message); } } /** * ??URIBuilder???API???. ?????????????? * ????? * * @param builder ?API??URI??????? * @param handler ??? * @return ??? * @throws IOException ???????? * */ public HttpResponse registerEvent(final URIBuilder builder, final EventHandler handler) throws IOException { if (builder == null) { throw new IllegalArgumentException("builder must not be null."); } else if (handler == null) { throw new IllegalArgumentException("handler must not be null."); } HttpPut request; String key; try { List<NameValuePair> params = builder.getQueryParams(); key = getKey(builder); // ????null?body?? builder.setParameters(null); request = new HttpPut(builder.build()); request.setEntity(new UrlEncodedFormEntity(params)); } catch (URISyntaxException e) { throw new IllegalArgumentException("Invalid URI parameter."); } HttpResponse response = execute(request); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { String entity = EntityUtils.toString(response.getEntity(), "UTF-8"); try { JSONObject json = new JSONObject(entity); if (json != null) { int result = json.getInt(DConnectMessage.EXTRA_RESULT); if (result == DConnectMessage.RESULT_OK) { addHandler(key, handler); } } } catch (JSONException e) { // JSON??????response????????????? mLogger.warning("AbstractEventManager#registerEvent. Invalid response. : " + e.getMessage()); } } return response; } /** * ??URIBuilder???API???. ???????? * {@link #registerEvent(URIBuilder, EventHandler)}?????? * * @param builder ?API??URI??????? * @return ??? * @throws IOException ???????? */ public HttpResponse unregisterEvent(final URIBuilder builder) throws IOException { if (builder == null) { throw new IllegalArgumentException("builder must not be null."); } HttpDelete request; String key; try { List<NameValuePair> params = builder.getQueryParams(); key = getKey(builder); builder.setParameters(params); request = new HttpDelete(builder.build()); } catch (URISyntaxException e) { throw new IllegalArgumentException("Invalid URI parameter."); } HttpResponse response = execute(request); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { String entity = EntityUtils.toString(response.getEntity(), "UTF-8"); try { JSONObject json = new JSONObject(entity); if (json != null) { int result = json.getInt(DConnectMessage.EXTRA_RESULT); if (result == DConnectMessage.RESULT_OK) { removeHandler(key); } } } catch (JSONException e) { // JSON??????response????????????? mLogger.warning("AbstractEventManager#unregisterEvent. Invalid response. : " + e.getMessage()); } } return response; } /** * ?deviceId??. * * @param params * @return ?ID */ private String getDeviceId(final List<NameValuePair> params) { String deviceId = null; if (params == null || params.size() == 0) { throw new IllegalArgumentException("No parameters. You need to set some parameters to register event."); } else { for (NameValuePair pair : params) { if (pair.getName().equals(DConnectMessage.EXTRA_DEVICE_ID)) { deviceId = pair.getValue(); break; } } if (deviceId == null) { throw new IllegalArgumentException("No deviceId. Set it."); } } return deviceId; } /** * ??. * * @param builder URI * @return */ private String getKey(final URIBuilder builder) { String deviceId = getDeviceId(builder.getQueryParams()); return getKey(builder.getProfile(), builder.getInterface(), builder.getAttribute(), deviceId); } /** * ??. * * @param profile ?? * @param inter ?? * @param attribute ?? * @param deviceId ?ID * @return */ private String getKey(final String profile, final String inter, final String attribute, final String deviceId) { String tmpInter = inter != null ? inter : ""; return deviceId + "/" + profile + "/" + tmpInter + "/" + attribute; } /** * ???. */ public abstract void disconnect(); /** * ??????. * * @param request ? * @return ? * @throws IOException ??????? */ protected abstract HttpResponse execute(HttpUriRequest request) throws IOException; /** * ?????. * * @param response ? * @return ??? * @throws IOException ????? */ protected HttpResponse copyResponse(final HttpResponse response) throws IOException { int code = response.getStatusLine().getStatusCode(); HttpResponse retRes = new BasicHttpResponse(response.getProtocolVersion(), code, EnglishReasonPhraseCatalog.INSTANCE.getReason(code, null)); retRes.setHeaders(response.getAllHeaders()); retRes.setEntity(new StringEntity(EntityUtils.toString(response.getEntity(), "UTF-8"))); return retRes; } }