Search in sources :

Example 11 with URLServiceSubscription

use of com.connectsdk.service.command.URLServiceSubscription in project butter-android by butterproject.

the class WebOSTVService method get3DEnabled.

private ServiceCommand<State3DModeListener> get3DEnabled(boolean isSubscription, final State3DModeListener listener) {
    String uri = "ssap://com.webos.service.tv.display/get3DStatus";
    ResponseListener<Object> responseListener = new ResponseListener<Object>() {

        @Override
        public void onSuccess(Object response) {
            JSONObject jsonObj = (JSONObject) response;
            JSONObject status;
            try {
                status = jsonObj.getJSONObject("status3D");
                boolean isEnabled = status.getBoolean("status");
                Util.postSuccess(listener, isEnabled);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(ServiceCommandError error) {
            Util.postError(listener, error);
        }
    };
    ServiceCommand<State3DModeListener> request;
    if (isSubscription)
        request = new URLServiceSubscription<State3DModeListener>(this, uri, null, true, responseListener);
    else
        request = new ServiceCommand<State3DModeListener>(this, uri, null, true, responseListener);
    request.send();
    return request;
}
Also used : JSONObject(org.json.JSONObject) URLServiceSubscription(com.connectsdk.service.command.URLServiceSubscription) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) ServiceCommandError(com.connectsdk.service.command.ServiceCommandError) ResponseListener(com.connectsdk.service.capability.listeners.ResponseListener) ServiceCommand(com.connectsdk.service.command.ServiceCommand)

Example 12 with URLServiceSubscription

use of com.connectsdk.service.command.URLServiceSubscription in project butter-android by butterproject.

the class WebOSTVService method unPinWebApp.

@Override
public void unPinWebApp(String webAppId, final ResponseListener<Object> listener) {
    if (webAppId == null || webAppId.length() == 0) {
        if (listener != null) {
            listener.onError(new ServiceCommandError(-1, "You must provide a valid web app id", null));
        }
        return;
    }
    String uri = "ssap://webapp/removePinnedWebApp";
    JSONObject payload = new JSONObject();
    try {
        payload.put("webAppId", webAppId);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    ResponseListener<Object> responseListener = new ResponseListener<Object>() {

        @Override
        public void onSuccess(final Object response) {
            JSONObject obj = (JSONObject) response;
            if (obj.has("pairingType")) {
                notifyPairingRequired();
            } else if (listener != null) {
                listener.onSuccess(response);
            }
        }

        @Override
        public void onError(ServiceCommandError error) {
            Util.postError(listener, error);
        }
    };
    ServiceCommand<ResponseListener<Object>> request = new URLServiceSubscription<ResponseListener<Object>>(this, uri, payload, true, responseListener);
    request.send();
}
Also used : JSONObject(org.json.JSONObject) URLServiceSubscription(com.connectsdk.service.command.URLServiceSubscription) JSONException(org.json.JSONException) ServiceCommandError(com.connectsdk.service.command.ServiceCommandError) JSONObject(org.json.JSONObject) ResponseListener(com.connectsdk.service.capability.listeners.ResponseListener)

Example 13 with URLServiceSubscription

use of com.connectsdk.service.command.URLServiceSubscription in project butter-android by butterproject.

the class WebOSTVServiceSocketClient method handleMessage.

@SuppressWarnings("unchecked")
protected void handleMessage(JSONObject message) {
    Boolean shouldProcess = true;
    if (mListener != null)
        shouldProcess = mListener.onReceiveMessage(message);
    if (!shouldProcess)
        return;
    String type = message.optString("type");
    Object payload = message.opt("payload");
    String strId = message.optString("id");
    Integer id = null;
    ServiceCommand<ResponseListener<Object>> request = null;
    if (isInteger(strId)) {
        id = Integer.valueOf(strId);
        try {
            request = (ServiceCommand<ResponseListener<Object>>) requests.get(id);
        } catch (ClassCastException ex) {
        // since request is assigned to null, don't need to do anything here
        }
    }
    if (type.length() == 0)
        return;
    if ("response".equals(type)) {
        if (request != null) {
            // Log.d(Util.T, "Found requests need to handle response");
            if (payload != null) {
                Util.postSuccess(request.getResponseListener(), payload);
            } else {
                Util.postError(request.getResponseListener(), new ServiceCommandError(-1, "JSON parse error", null));
            }
            if (!(request instanceof URLServiceSubscription)) {
                if (!(payload instanceof JSONObject && ((JSONObject) payload).has("pairingType")))
                    requests.remove(id);
            }
        } else {
            System.err.println("no matching request id: " + strId + ", payload: " + payload.toString());
        }
    } else if ("registered".equals(type)) {
        if (!(mService.getServiceConfig() instanceof WebOSTVServiceConfig)) {
            mService.setServiceConfig(new WebOSTVServiceConfig(mService.getServiceConfig().getServiceUUID()));
        }
        if (payload instanceof JSONObject) {
            String clientKey = ((JSONObject) payload).optString("client-key");
            ((WebOSTVServiceConfig) mService.getServiceConfig()).setClientKey(clientKey);
            // Track SSL certificate
            // Not the prettiest way to get it, but we don't have direct access to the SSLEngine
            ((WebOSTVServiceConfig) mService.getServiceConfig()).setServerCertificate(customTrustManager.getLastCheckedCertificate());
            handleRegistered();
            if (id != null)
                requests.remove(id);
        }
    } else if ("error".equals(type)) {
        String error = message.optString("error");
        if (error.length() == 0)
            return;
        int errorCode = -1;
        String errorDesc = null;
        try {
            String[] parts = error.split(" ", 2);
            errorCode = Integer.parseInt(parts[0]);
            errorDesc = parts[1];
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (payload != null) {
            Log.d(Util.T, "Error Payload: " + payload.toString());
        }
        if (message.has("id")) {
            Log.d(Util.T, "Error Desc: " + errorDesc);
            if (request != null) {
                Util.postError(request.getResponseListener(), new ServiceCommandError(errorCode, errorDesc, payload));
                if (!(request instanceof URLServiceSubscription))
                    requests.remove(id);
            }
        }
    } else if ("hello".equals(type)) {
        JSONObject jsonObj = (JSONObject) payload;
        if (mService.getServiceConfig().getServiceUUID() != null) {
            if (!mService.getServiceConfig().getServiceUUID().equals(jsonObj.optString("deviceUUID"))) {
                ((WebOSTVServiceConfig) mService.getServiceConfig()).setClientKey(null);
                ((WebOSTVServiceConfig) mService.getServiceConfig()).setServerCertificate((String) null);
                mService.getServiceConfig().setServiceUUID(null);
                mService.getServiceDescription().setIpAddress(null);
                mService.getServiceDescription().setUUID(null);
                disconnect();
            }
        } else {
            String uuid = jsonObj.optString("deviceUUID");
            mService.getServiceConfig().setServiceUUID(uuid);
            mService.getServiceDescription().setUUID(uuid);
        }
        state = State.REGISTERING;
        sendRegister();
    }
}
Also used : ServiceCommandError(com.connectsdk.service.command.ServiceCommandError) ResponseListener(com.connectsdk.service.capability.listeners.ResponseListener) SuppressLint(android.annotation.SuppressLint) NameNotFoundException(android.content.pm.PackageManager.NameNotFoundException) KeyException(java.security.KeyException) URISyntaxException(java.net.URISyntaxException) JSONException(org.json.JSONException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) CertificateEncodingException(java.security.cert.CertificateEncodingException) JSONObject(org.json.JSONObject) URLServiceSubscription(com.connectsdk.service.command.URLServiceSubscription) WebOSTVServiceConfig(com.connectsdk.service.config.WebOSTVServiceConfig) JSONObject(org.json.JSONObject)

Example 14 with URLServiceSubscription

use of com.connectsdk.service.command.URLServiceSubscription in project butter-android by butterproject.

the class NetcastHttpServer method start.

public void start() {
    // TODO: this method is too complex and should be refactored
    if (running)
        return;
    running = true;
    try {
        welcomeSocket = new ServerSocket(this.port);
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    while (running) {
        if (welcomeSocket == null || welcomeSocket.isClosed()) {
            stop();
            break;
        }
        Socket connectionSocket = null;
        BufferedReader inFromClient = null;
        DataOutputStream outToClient = null;
        try {
            connectionSocket = welcomeSocket.accept();
        } catch (IOException ex) {
            ex.printStackTrace();
            // this socket may have been closed, so we'll stop
            stop();
            return;
        }
        String str = null;
        int c;
        StringBuilder sb = new StringBuilder();
        try {
            inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
            while ((str = inFromClient.readLine()) != null) {
                if (str.equals("")) {
                    break;
                }
            }
            while ((c = inFromClient.read()) != -1) {
                sb.append((char) c);
                String temp = sb.toString();
                if (temp.endsWith("</envelope>"))
                    break;
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        String body = sb.toString();
        Log.d(Util.T, "got message body: " + body);
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = dateFormat.format(calendar.getTime());
        String androidOSVersion = android.os.Build.VERSION.RELEASE;
        PrintWriter out = null;
        try {
            outToClient = new DataOutputStream(connectionSocket.getOutputStream());
            out = new PrintWriter(outToClient);
            out.println("HTTP/1.1 200 OK");
            out.println("Server: Android/" + androidOSVersion + " UDAP/2.0 ConnectSDK/1.2.1");
            out.println("Cache-Control: no-store, no-cache, must-revalidate");
            out.println("Date: " + date);
            out.println("Connection: Close");
            out.println("Content-Length: 0");
            out.println();
            out.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                inFromClient.close();
                out.close();
                outToClient.close();
                connectionSocket.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        InputStream stream = null;
        try {
            stream = new ByteArrayInputStream(body.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }
        NetcastPOSTRequestParser handler = new NetcastPOSTRequestParser();
        SAXParser saxParser;
        try {
            saxParser = saxParserFactory.newSAXParser();
            saxParser.parse(stream, handler);
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
        if (body.contains("ChannelChanged")) {
            ChannelInfo channel = NetcastChannelParser.parseRawChannelData(handler.getJSONObject());
            Log.d(Util.T, "Channel Changed: " + channel.getNumber());
            for (URLServiceSubscription<?> sub : subscriptions) {
                if (sub.getTarget().equalsIgnoreCase("ChannelChanged")) {
                    for (int i = 0; i < sub.getListeners().size(); i++) {
                        @SuppressWarnings("unchecked") ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners().get(i);
                        Util.postSuccess(listener, channel);
                    }
                }
            }
        } else if (body.contains("KeyboardVisible")) {
            boolean focused = false;
            TextInputStatusInfo keyboard = new TextInputStatusInfo();
            keyboard.setRawData(handler.getJSONObject());
            try {
                JSONObject currentWidget = (JSONObject) handler.getJSONObject().get("currentWidget");
                focused = (Boolean) currentWidget.get("focus");
                keyboard.setFocused(focused);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Log.d(Util.T, "KeyboardFocused?: " + focused);
            for (URLServiceSubscription<?> sub : subscriptions) {
                if (sub.getTarget().equalsIgnoreCase("KeyboardVisible")) {
                    for (int i = 0; i < sub.getListeners().size(); i++) {
                        @SuppressWarnings("unchecked") ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners().get(i);
                        Util.postSuccess(listener, keyboard);
                    }
                }
            }
        } else if (body.contains("TextEdited")) {
            System.out.println("TextEdited");
            String newValue = "";
            try {
                newValue = handler.getJSONObject().getString("value");
            } catch (JSONException ex) {
                ex.printStackTrace();
            }
            Util.postSuccess(textChangedListener, newValue);
        } else if (body.contains("3DMode")) {
            try {
                String enabled = (String) handler.getJSONObject().get("value");
                boolean bEnabled;
                bEnabled = enabled.equalsIgnoreCase("true");
                for (URLServiceSubscription<?> sub : subscriptions) {
                    if (sub.getTarget().equalsIgnoreCase("3DMode")) {
                        for (int i = 0; i < sub.getListeners().size(); i++) {
                            @SuppressWarnings("unchecked") ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners().get(i);
                            Util.postSuccess(listener, bEnabled);
                        }
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}
Also used : DataOutputStream(java.io.DataOutputStream) ChannelInfo(com.connectsdk.core.ChannelInfo) SAXException(org.xml.sax.SAXException) URLServiceSubscription(com.connectsdk.service.command.URLServiceSubscription) SAXParser(javax.xml.parsers.SAXParser) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) TextInputStatusInfo(com.connectsdk.core.TextInputStatusInfo) PrintWriter(java.io.PrintWriter) InputStreamReader(java.io.InputStreamReader) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Calendar(java.util.Calendar) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JSONException(org.json.JSONException) ServerSocket(java.net.ServerSocket) IOException(java.io.IOException) ResponseListener(com.connectsdk.service.capability.listeners.ResponseListener) JSONObject(org.json.JSONObject) ByteArrayInputStream(java.io.ByteArrayInputStream) BufferedReader(java.io.BufferedReader) JSONObject(org.json.JSONObject) SimpleDateFormat(java.text.SimpleDateFormat) Socket(java.net.Socket) ServerSocket(java.net.ServerSocket) SAXParserFactory(javax.xml.parsers.SAXParserFactory)

Aggregations

ResponseListener (com.connectsdk.service.capability.listeners.ResponseListener)14 URLServiceSubscription (com.connectsdk.service.command.URLServiceSubscription)14 JSONObject (org.json.JSONObject)14 ServiceCommandError (com.connectsdk.service.command.ServiceCommandError)13 JSONException (org.json.JSONException)11 ServiceCommand (com.connectsdk.service.command.ServiceCommand)9 SuppressLint (android.annotation.SuppressLint)4 ChannelInfo (com.connectsdk.core.ChannelInfo)3 TextInputStatusInfo (com.connectsdk.core.TextInputStatusInfo)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 JSONArray (org.json.JSONArray)2 NameNotFoundException (android.content.pm.PackageManager.NameNotFoundException)1 AppInfo (com.connectsdk.core.AppInfo)1 ProgramInfo (com.connectsdk.core.ProgramInfo)1 ProgramList (com.connectsdk.core.ProgramList)1 TextInputStatusListener (com.connectsdk.service.capability.TextInputControl.TextInputStatusListener)1 WebOSTVServiceConfig (com.connectsdk.service.config.WebOSTVServiceConfig)1 WebAppPinStatusListener (com.connectsdk.service.sessions.WebAppSession.WebAppPinStatusListener)1 BufferedReader (java.io.BufferedReader)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1