Example usage for java.net Socket close

List of usage examples for java.net Socket close

Introduction

In this page you can find the example usage for java.net Socket close.

Prototype

public synchronized void close() throws IOException 

Source Link

Document

Closes this socket.

Usage

From source file:com.jredrain.startup.Bootstrap.java

private void await() throws Exception {
    // Negative values - don't wait on port - redrain is embedded or we just don't like ports
    if (port == -2) {
        return;//from w  w  w  .ja  va  2  s . c  om
    }
    if (port == -1) {
        try {
            awaitThread = Thread.currentThread();
            while (!stopAwait) {
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException ex) {
                    // continue and check the flag
                }
            }
        } finally {
            awaitThread = null;
        }
        return;
    }

    // Set up a server socket to wait on
    try {
        awaitSocket = new ServerSocket(RedrainProperties.getInt("redrain.shutdown"));
    } catch (IOException e) {
        logger.error("[redrain] agent .await: create[{}] ", RedrainProperties.getInt("redrain.shutdown"), e);
        return;
    }

    try {
        awaitThread = Thread.currentThread();
        // Loop waiting for a connection and a valid command
        while (!stopAwait) {
            ServerSocket serverSocket = awaitSocket;
            if (serverSocket == null) {
                break;
            }
            // Wait for the next connection
            Socket socket = null;
            StringBuilder command = new StringBuilder();
            try {
                InputStream stream;
                long acceptStartTime = System.currentTimeMillis();
                try {
                    socket = serverSocket.accept();
                    socket.setSoTimeout(10 * 1000); // Ten seconds
                    stream = socket.getInputStream();
                } catch (SocketTimeoutException ste) {
                    // This should never happen but bug 56684 suggests that
                    // it does.
                    logger.warn("[redrain] agentServer accept.timeout",
                            Long.valueOf(System.currentTimeMillis() - acceptStartTime), ste);
                    continue;
                } catch (AccessControlException ace) {
                    logger.warn("[redrain] agentServer .accept security exception: {}", ace.getMessage(), ace);
                    continue;
                } catch (IOException e) {
                    if (stopAwait) {
                        break;
                    }
                    logger.error("[redrain] agent .await: accept: ", e);
                    break;
                }

                // Read a set of characters from the socket
                int expected = 1024; // Cut off to avoid DoS attack
                while (expected < shutdown.length()) {
                    if (random == null) {
                        random = new Random();
                    }
                    expected += (random.nextInt() % 1024);
                }
                while (expected > 0) {
                    int ch = -1;
                    try {
                        ch = stream.read();
                    } catch (IOException e) {
                        logger.warn("[redrain] agent .await: read: ", e);
                        ch = -1;
                    }
                    if (ch < 32) // Control character or EOF terminates loop
                        break;
                    command.append((char) ch);
                    expected--;
                }
            } finally {
                try {
                    if (socket != null) {
                        socket.close();
                    }
                } catch (IOException e) {
                }
            }
            boolean match = command.toString().equals(shutdown);
            if (match) {
                break;
            } else {
                logger.warn("[redrain] agent .await: Invalid command '" + command.toString() + "' received");
            }
        }
    } finally {
        ServerSocket serverSocket = awaitSocket;
        awaitThread = null;
        awaitSocket = null;
        // Close the server socket and return
        if (serverSocket != null) {
            try {
                serverSocket.close();
            } catch (IOException e) {
                // Ignore
            }
        }
    }

}

From source file:com.oneapm.base.SparkAggregation.java

private static void startZookeeperService(final FlowConstant flowConstant,
        final ZookeeperClient zookeeperClient) throws IOException {

    final Date startTime = new Date();
    ScheduledExecutorService service = Executors.newScheduledThreadPool(3, new ThreadFactory() {
        @Override//from  w ww .  j av a2s.  c  o  m
        public Thread newThread(Runnable r) {
            return new Thread(r, "Zookeeper-Writer-ThreadPool");
        }
    });

    final String zookeeper = Config.getConfig("alert.cnf").getProperty("kafaka.zoo", "127.0.0.1:2181");
    final String kafaka = Config.getConfig("alert.cnf").getProperty("kafaka.zoo", "127.0.0.1:9092");
    zookeeperClient.setLicense("/ni/license");
    zookeeperClient.createNode("/ni", "", true);
    zookeeperClient.createNode("/ni/process", "", true);
    zookeeperClient.createNode("/ni/process/Alarm", "", false);
    service.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            try {
                //?
                checkComponent();
                writeData();
            } catch (Exception e) {
                LOG.warn("zookeeper?:" + e.getMessage());
            }
        }

        //?
        private void checkComponent() {
            Socket clientSocket = null;
            try {
                String[] zookeeperInfo = zookeeper.split(":");
                clientSocket = new Socket(zookeeperInfo[0], Integer.valueOf(zookeeperInfo[1]));

                flowConstant.isZookeeperOkFlag = true;
                flowConstant.isKafkaOkFlag = true;
            } catch (Exception e) {
                flowConstant.isZookeeperOkFlag = false;
                flowConstant.isKafkaOkFlag = false;
            } finally {
                if (clientSocket != null) {
                    try {
                        clientSocket.close();
                    } catch (IOException e) {
                        LOG.warn("socket:" + e.getMessage());
                    }
                }
            }
            //                //kafka?
            //                try {
            //                    String[] kafakaInfo = kafaka.split(":");
            //                    clientSocket = new Socket(kafakaInfo[0], Integer.valueOf(kafakaInfo[1]));
            //
            //                    flowConstant.isKafkaOkFlag = true;
            //                } catch (Exception e) {
            //                    flowConstant.isKafkaOkFlag = false;
            //                } finally {
            //                    try {
            //                        clientSocket.close();
            //                    } catch (IOException e) {
            //                        LOG.warn("socket:" + e.getMessage());
            //                    }
            //                }
        }

        private void writeData() {
            Map<String, String> processInfoMap = new HashMap<String, String>();

            try {
                processInfoMap.put("host", String.valueOf(InetAddress.getLocalHost()));
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            processInfoMap.put("setupLocation", System.getProperty("user.dir"));
            processInfoMap.put("startupTime", String.valueOf(startTime.getTime()));
            String licence = "no license";
            if (Integer.parseInt(zookeeperClient.getLicense().split("\n")[2].split("=")[1]) == 1) {
                licence = "ok";
            }
            processInfoMap.put("licence", licence);
            if (flowConstant.isEsOKFlag && flowConstant.isKafkaOkFlag && flowConstant.isZookeeperOkFlag) {
                processInfoMap.put("status", "ok");
            } else {
                List<String> components = new ArrayList<String>();
                if (!flowConstant.isEsOKFlag) {
                    components.add("es is not available!");
                }
                if (!flowConstant.isZookeeperOkFlag) {
                    components.add("zookeeper is not available!");
                }
                if (!flowConstant.isKafkaOkFlag) {
                    components.add("kafka is not available!");
                }

                processInfoMap.put("status", StringUtils.join(components, ";"));
            }
            String processInfo = JSON.toJSONString(processInfoMap);

            if (zookeeperClient.isExists("/ni/process/Alarm")) {
                zookeeperClient.writeData("/ni/process/Alarm", processInfo);
            } else {
                zookeeperClient.createNode("/ni", "", true);
                zookeeperClient.createNode("/ni/process", "", true);
                zookeeperClient.createNode("/ni/process/Alarm", "", false);
                zookeeperClient.writeData("/ni/process/Alarm", processInfo);
            }
        }

    }, 10, 60, TimeUnit.SECONDS);
}

From source file:net.lightbody.bmp.proxy.jetty.http.handler.ProxyHandler.java

protected HttpTunnel newHttpTunnel(HttpRequest request, HttpResponse response, InetAddress iaddr, int port,
        int timeoutMS) throws IOException {
    try {/*from w ww.ja v  a 2 s . c  om*/
        Socket socket = null;
        InputStream in = null;

        String chained_proxy_host = System.getProperty("http.proxyHost");
        if (chained_proxy_host == null) {
            socket = new Socket(iaddr, port);
            socket.setSoTimeout(timeoutMS);
            socket.setTcpNoDelay(true);
        } else {
            int chained_proxy_port = Integer.getInteger("http.proxyPort", 8888).intValue();

            Socket chain_socket = new Socket(chained_proxy_host, chained_proxy_port);
            chain_socket.setSoTimeout(timeoutMS);
            chain_socket.setTcpNoDelay(true);
            if (log.isDebugEnabled())
                log.debug("chain proxy socket=" + chain_socket);

            LineInput line_in = new LineInput(chain_socket.getInputStream());
            byte[] connect = request.toString()
                    .getBytes(net.lightbody.bmp.proxy.jetty.util.StringUtil.__ISO_8859_1);
            chain_socket.getOutputStream().write(connect);

            String chain_response_line = line_in.readLine();
            HttpFields chain_response = new HttpFields();
            chain_response.read(line_in);

            // decode response
            int space0 = chain_response_line.indexOf(' ');
            if (space0 > 0 && space0 + 1 < chain_response_line.length()) {
                int space1 = chain_response_line.indexOf(' ', space0 + 1);

                if (space1 > space0) {
                    int code = Integer.parseInt(chain_response_line.substring(space0 + 1, space1));

                    if (code >= 200 && code < 300) {
                        socket = chain_socket;
                        in = line_in;
                    } else {
                        Enumeration iter = chain_response.getFieldNames();
                        while (iter.hasMoreElements()) {
                            String name = (String) iter.nextElement();
                            if (!_DontProxyHeaders.containsKey(name)) {
                                Enumeration values = chain_response.getValues(name);
                                while (values.hasMoreElements()) {
                                    String value = (String) values.nextElement();
                                    response.setField(name, value);
                                }
                            }
                        }
                        response.sendError(code);
                        if (!chain_socket.isClosed())
                            chain_socket.close();
                    }
                }
            }
        }

        if (socket == null)
            return null;
        HttpTunnel tunnel = new HttpTunnel(socket, in, null);
        return tunnel;
    } catch (IOException e) {
        log.debug(e);
        response.sendError(HttpResponse.__400_Bad_Request);
        return null;
    }
}

From source file:com.irccloud.android.GingerbreadImageProxy.java

private void processRequest(HttpRequest request, Socket client) throws IllegalStateException, IOException {
    if (request == null) {
        return;//www. j a va2  s  . c  o  m
    }
    URL url = new URL(request.getRequestLine().getUri());

    HttpURLConnection conn = null;

    Proxy proxy = null;
    String host = null;
    int port = -1;

    if (Build.VERSION.SDK_INT < 11) {
        Context ctx = IRCCloudApplication.getInstance().getApplicationContext();
        if (ctx != null) {
            host = android.net.Proxy.getHost(ctx);
            port = android.net.Proxy.getPort(ctx);
        }
    } else {
        host = System.getProperty("http.proxyHost", null);
        try {
            port = Integer.parseInt(System.getProperty("http.proxyPort", "8080"));
        } catch (NumberFormatException e) {
            port = -1;
        }
    }

    if (host != null && host.length() > 0 && !host.equalsIgnoreCase("localhost")
            && !host.equalsIgnoreCase("127.0.0.1") && port > 0) {
        InetSocketAddress proxyAddr = new InetSocketAddress(host, port);
        proxy = new Proxy(Proxy.Type.HTTP, proxyAddr);
    }

    if (url.getProtocol().toLowerCase().equals("https")) {
        conn = (HttpsURLConnection) ((proxy != null) ? url.openConnection(proxy)
                : url.openConnection(Proxy.NO_PROXY));
    } else {
        conn = (HttpURLConnection) ((proxy != null) ? url.openConnection(proxy)
                : url.openConnection(Proxy.NO_PROXY));
    }

    conn.setConnectTimeout(30000);
    conn.setReadTimeout(30000);
    conn.setUseCaches(true);

    if (!isRunning)
        return;

    try {
        client.getOutputStream().write(
                ("HTTP/1.0 " + conn.getResponseCode() + " " + conn.getResponseMessage() + "\n\n").getBytes());

        if (conn.getResponseCode() == 200 && conn.getInputStream() != null) {
            byte[] buff = new byte[8192];
            int readBytes;
            while (isRunning && (readBytes = conn.getInputStream().read(buff, 0, buff.length)) != -1) {
                client.getOutputStream().write(buff, 0, readBytes);
            }
        }
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        client.close();
    }

    conn.disconnect();
    stop();
}

From source file:com.clavain.munin.MuninNode.java

/**
 * Will load the plugin list from munin-node
 *///from www  . ja  v a2s.  c o m
public boolean loadPlugins() {
    setLoadedPlugins(new CopyOnWriteArrayList<MuninPlugin>());
    String l_lastProceeded = "";

    try {
        Socket cs = new Socket();
        cs.setKeepAlive(false);
        cs.setSoLinger(true, 0);
        cs.setReuseAddress(true);
        cs.setSoTimeout(com.clavain.muninmxcd.socketTimeout);
        if (!str_via.equals("unset")) {
            cs.connect(new InetSocketAddress(this.getStr_via(), this.getPort()),
                    com.clavain.muninmxcd.socketTimeout);
        } else {
            cs.connect(new InetSocketAddress(this.getHostname(), this.getPort()),
                    com.clavain.muninmxcd.socketTimeout);
        }

        if (p.getProperty("kill.sockets").equals("true")) {
            SocketCheck sc = new SocketCheck(cs, getUnixtime());
            sc.setHostname(this.getHostname());
            com.clavain.muninmxcd.v_sockets.add(sc);
        }
        PrintStream os = new PrintStream(cs.getOutputStream());
        BufferedReader in = new BufferedReader(new InputStreamReader(cs.getInputStream()));

        String s = in.readLine();

        if (s != null) {
            // Set version
            os.println("version");
            Thread.sleep(150);
            s = in.readLine();

            String version = s.substring(s.indexOf(":") + 1, s.length()).trim();
            this.str_muninVersion = version;

            if (authpw != null) {
                // if authpw is set, verify
                if (!authpw.trim().equals("")) {
                    os.println("config muninmxauth");
                    Thread.sleep(150);
                    String apw = in.readLine();
                    s = in.readLine();
                    if (!apw.trim().equals(this.getAuthpw())) {
                        logger.error("Invalid muninmxauth password for host: " + this.getHostname());
                        cs.close();
                        return false;
                    }
                }
            }
            // check anyway if muninmxauth plugin is present
            else {
                os.println("config muninmxauth");
                Thread.sleep(100);
                String apw = in.readLine();
                if (!apw.trim().equals("# Unknown service")) {
                    logger.error(
                            "no auth password given, but muninmxauth plugin present on " + this.getHostname());
                    cs.close();
                    return false;
                }
                s = in.readLine();
            }

            // get list of available plugins
            if (str_via.equals("unset")) {
                os.println("list");
            } else {
                os.println("list " + str_hostname);
            }

            Thread.sleep(250);
            s = in.readLine();

            // if response is empty and host is not via, do a list $hostname
            if (s.trim().equals("") && str_via.equals("unset")) {
                logger.info("Plugin Response Empty on " + this.getHostname()
                        + " trying to load with list $hostname");
                os.println("list " + this.getHostname());
                Thread.sleep(250);
                s = in.readLine();
            }

            String l_tmp;
            StringTokenizer l_st = new StringTokenizer(s, " ");

            // create plugin
            MuninPlugin l_mp = new MuninPlugin();
            // negative support
            ArrayList<String> tmp_negatives = new ArrayList<String>();

            while (l_st.hasMoreTokens()) {

                String l_strPlugin = l_st.nextToken();

                // check for track_pkg and muninmx essentials
                if (l_strPlugin.equals("muninmx_trackpkg")) {
                    this.setTrack_pkg(true);
                    continue;
                }

                // got essentials?
                if (l_strPlugin.equals("muninmx_essentials")) {
                    this.setEssentials(true);
                    continue;
                }

                if (isPluginIgnored(l_strPlugin.toUpperCase())) {
                    continue;
                }

                l_mp.setPluginName(l_strPlugin);

                os.println("config " + l_strPlugin);

                // create graphs for plugin
                int l_iGraphsFound = 0;
                int l_iTmp = 0;
                MuninGraph l_mg = new MuninGraph();
                l_mg.setQueryInterval(this.getQueryInterval());
                while ((l_tmp = in.readLine()) != null) {
                    if (l_tmp.startsWith(".")) {
                        break;
                    }
                    // collect graphs only for plugin
                    String l_strName;
                    String l_strType;
                    String l_strValue;

                    if (!l_tmp.contains("graph_") && !l_tmp.trim().equals("") && !l_tmp.contains("host_name")
                            && !l_tmp.contains("multigraph") && !l_tmp.trim().equals("graph no")
                            && !l_tmp.trim().equals("# Bad exit")
                            && !l_tmp.trim().contains("info Currently our peer")
                            && !l_tmp.trim().startsWith("#")
                            && !l_tmp.trim().contains("Bonding interface errors")) {
                        l_lastProceeded = l_tmp;
                        l_strName = l_tmp.substring(0, l_tmp.indexOf("."));
                        l_strType = l_tmp.substring(l_tmp.indexOf(".") + 1, l_tmp.indexOf(" "));
                        l_strValue = l_tmp.substring(l_tmp.indexOf(" ") + 1, l_tmp.length());
                        //System.err.println("Name: " + l_strName + " Type: " + l_strType + " Value: " + l_strValue);

                        if (l_strType.equals("label")) {
                            l_iTmp++;

                            if (l_iTmp > 1) {
                                l_mp.addGraph(l_mg);
                                l_mg = new MuninGraph();
                                l_mg.setQueryInterval(this.getQueryInterval());
                            }
                            l_mg.setGraphName(l_strName);
                            l_mg.setGraphLabel(l_strValue);
                        } else if (l_strType.equals("draw")) {
                            l_mg.setGraphDraw(l_strValue);
                        } else if (l_strType.equals("type")) {
                            l_mg.setGraphType(l_strValue);
                        } else if (l_strType.equals("info")) {
                            l_mg.setGraphInfo(l_strValue);
                        } else if (l_strType.equals("negative")) {
                            // add to temporary negative list to set negatives later
                            tmp_negatives.add(l_strValue);
                        }

                        //System.out.println(l_strName); 
                        //System.out.println(l_strType);
                        //System.out.println(l_strValue);
                    } else {
                        // set plugin title
                        if (l_tmp.contains("graph_title")) {
                            l_mp.setPluginTitle(l_tmp.substring(12, l_tmp.length()));
                        }
                        // set plugin info, if any
                        if (l_tmp.contains("graph_info")) {
                            l_mp.setPluginInfo(l_tmp.substring(11, l_tmp.length()));
                        }
                        // set graph category
                        if (l_tmp.contains("graph_category")) {
                            l_mp.setPluginCategory(l_tmp.substring(15, l_tmp.length()));
                        }
                        // set graph vlabel
                        if (l_tmp.contains("graph_vlabel")) {
                            l_mp.setPluginLabel(l_tmp.substring(13, l_tmp.length()));
                        }
                        // set plugin title
                        if (l_tmp.contains("graph_mxdraw")) {
                            l_mp.setStr_LineMode(l_tmp.substring(13, l_tmp.length()));
                        }
                    }

                }

                // add to pluginlist
                l_mp.addGraph(l_mg);

                Iterator it = l_mp.getGraphs().iterator();
                while (it.hasNext()) {
                    MuninGraph l_mpNg = (MuninGraph) it.next();
                    if (tmp_negatives.contains(l_mpNg.getGraphName())) {
                        l_mpNg.setNegative(true);
                    }
                }

                // add plugin if it got valid graphs and add nodeid (req. for alerts)
                if (l_mp.getGraphs().size() > 0) {
                    l_mp.set_NodeId(this.getNode_id());
                    getLoadedPlugins().add(l_mp);
                }
                // flush temporary negatives
                tmp_negatives.clear();
                l_mp = null;
                l_mp = new MuninPlugin();
                //String l_strGraphTitle = s.substring(s.indexOf("graph_title") + 11,s.length());
                //System.out.println(" - " + l_strGraphTitle);
            }
            cs.close();
            in.close();
            os.close();
            last_plugin_load = getUnixtime();
            //System.out.println(s);
        } else {
            cs.close();
            in.close();
            os.close();
            logger.warn("Error loading plugins on " + str_hostname + " (" + this.getNode_id()
                    + "). Check connectivity or munin-node");
        }
        /*
        for (MuninPlugin l_mn : getLoadedPlugins()) {
        i_GraphCount = i_GraphCount + l_mn.getGraphs().size();
        logger.debug(l_mn.getGraphs().size() + " graphs found for plugin: " + l_mn.getPluginName().toUpperCase() + " on node: " + this.getNodename());
        }*/
    } catch (Exception ex) {
        logger.error("Error loading plugins on " + str_hostname + " (" + this.getNode_id() + ") : "
                + ex.getMessage());
        ex.printStackTrace();
        return false;
    }

    return true;
}

From source file:com.connectsdk.device.netcast.NetcastHttpServer.java

public void start() {
    if (running)/*w  w  w.  jav  a 2  s  . co m*/
        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("Connect SDK", "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.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("Connect SDK", "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("Connect SDK", "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;

                if (enabled.equalsIgnoreCase("true"))
                    bEnabled = true;
                else
                    bEnabled = false;

                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();
            }
        }
    }
}

From source file:fm.last.android.player.StreamProxy.java

private void processRequest(HttpRequest request, Socket client) throws IllegalStateException, IOException {
    if (request == null) {
        return;/*w  w  w  . j a v  a  2s.  co m*/
    }
    Log.d(LOG_TAG, "processing");
    String url = request.getRequestLine().getUri();

    DefaultHttpClient seed = new DefaultHttpClient();
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    SingleClientConnManager mgr = new MyClientConnManager(seed.getParams(), registry);
    DefaultHttpClient http = new DefaultHttpClient(mgr, seed.getParams());
    HttpGet method = new HttpGet(url);
    for (Header h : request.getAllHeaders()) {
        method.addHeader(h);
    }
    HttpResponse realResponse = null;
    try {
        Log.d(LOG_TAG, "starting download");
        realResponse = http.execute(method);
        Log.d(LOG_TAG, "downloaded");
    } catch (ClientProtocolException e) {
        Log.e(LOG_TAG, "Error downloading", e);
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error downloading", e);
    }

    if (realResponse == null) {
        return;
    }

    if (!isRunning)
        return;

    Log.d(LOG_TAG, "downloading...");

    InputStream data = realResponse.getEntity().getContent();
    StatusLine line = realResponse.getStatusLine();
    HttpResponse response = new BasicHttpResponse(line);
    response.setHeaders(realResponse.getAllHeaders());

    Log.d(LOG_TAG, "reading headers");
    StringBuilder httpString = new StringBuilder();
    httpString.append(response.getStatusLine().toString());

    httpString.append("\n");
    for (Header h : response.getAllHeaders()) {
        httpString.append(h.getName()).append(": ").append(h.getValue()).append("\n");
    }
    httpString.append("\n");
    Log.d(LOG_TAG, "headers done");

    try {
        byte[] buffer = httpString.toString().getBytes();
        int readBytes;
        Log.d(LOG_TAG, "writing to client");
        client.getOutputStream().write(buffer, 0, buffer.length);

        // Start streaming content.
        byte[] buff = new byte[8192];
        while (isRunning && (readBytes = data.read(buff, 0, buff.length)) != -1) {
            client.getOutputStream().write(buff, 0, readBytes);
        }
    } catch (Exception e) {
        Log.e("", e.getMessage(), e);
    } finally {
        mgr.shutdown();
        client.close();
        Log.d(LOG_TAG, "streaming complete");
    }
}

From source file:com.connectsdk.service.netcast.NetcastHttpServer.java

public void start() {
    //TODO: this method is too complex and should be refactored
    if (running)//  w ww  . j a  v a  2s  . c om
        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();
            }
        }
    }
}

From source file:com.clavain.munin.MuninNode.java

public void run() {
    b_isRunning = true;/*from ww  w .j  a v a  2 s  .co  m*/

    if (this.str_via.equals("unset")) {
        logger.info(getHostname() + " Monitoring job started");
    } else {
        logger.info(getHostname() + " (VIA: " + this.str_via + ") Monitoring job started");
    }

    int iCurTime = getUnixtime();
    int iPluginRefreshTime = last_plugin_load + Integer.parseInt(p.getProperty("plugin.refreshtime"));
    try {
        // update plugins, maybe we have some new :)
        // double try to load plugins if fail

        if (getPluginList().size() > 0) {
            if (!is_init) {
                logger.info("[Job: " + getHostname() + "] Updating Database");
                // update graphs in database too
                for (MuninPlugin it_pl : getPluginList()) {
                    if (it_pl.getGraphs().size() > 0) {
                        //logger.info(it_pl.getPluginName());
                        dbUpdatePluginForNode(getNode_id(), it_pl);
                    }
                }
                // delete now missing plugins
                dbDeleteMissingPlugins(getNode_id(), getPluginList());
                logger.info("[Job: " + getHostname() + "] Databaseupdate Done");
                is_init = true;
            } else {
                if (iCurTime > iPluginRefreshTime) {
                    logger.info("Refreshing Plugins on " + this.getHostname());
                    this.loadPlugins();
                    dbUpdateAllPluginsForNode(this);
                }
            }
        } else {
            this.loadPlugins();
        }

        Socket clientSocket = new Socket();
        clientSocket.setSoTimeout(com.clavain.muninmxcd.socketTimeout);
        clientSocket.setKeepAlive(false);
        clientSocket.setReuseAddress(true);
        if (this.str_via.equals("unset")) {
            clientSocket.connect(new InetSocketAddress(this.getHostname(), this.getPort()),
                    com.clavain.muninmxcd.socketTimeout);
        } else {
            clientSocket.connect(new InetSocketAddress(this.getStr_via(), this.getPort()),
                    com.clavain.muninmxcd.socketTimeout);
        }
        lastSocket = clientSocket;
        SocketCheck sc = new SocketCheck(clientSocket, getUnixtime());
        if (p.getProperty("kill.sockets").equals("true")) {
            sc.setHostname(this.getHostname());
            com.clavain.muninmxcd.v_sockets.add(sc);
        }
        this.i_lastRun = getUnixtime();

        // track packages?
        if (this.track_pkg) {
            updateTrackPackages(clientSocket);
        }

        // gather essentials?
        if (this.essentials) {
            updateEssentials(clientSocket);
        }

        // update graphs for all plugins
        Iterator it = this.getLoadedPlugins().iterator();
        while (it.hasNext()) {
            MuninPlugin l_mp = (MuninPlugin) it.next();
            if (logMore) {
                logger.info(getHostname() + " fetching graphs for " + l_mp.getPluginName().toUpperCase());
            }
            // snmp support
            if (!str_via.equals("unset")) {
                l_mp.updateAllGraps(this.getStr_via(), this.getPort(), clientSocket, getQueryInterval());
            } else {
                l_mp.updateAllGraps(this.getHostname(), this.getPort(), clientSocket, getQueryInterval());
            }
            // add all graphs to insertion queue for mongodb
            queuePluginFetch(l_mp.returnAllGraphs(), l_mp.getPluginName());
        }
        clientSocket.close();

        if (p.getProperty("kill.sockets").equals("true")) {
            com.clavain.muninmxcd.v_sockets.remove(sc);
        }
        sc = null;
    } catch (Exception ex) {
        logger.fatal("Error in thread for host: " + getHostname() + " : " + ex.getLocalizedMessage());
        ex.printStackTrace();
    }
    int iRunTime = getUnixtime() - iCurTime;
    dbUpdateLastContact(this.getNode_id());
    logger.info(getHostname() + " Monitoring job stopped - runtime: " + iRunTime);

}

From source file:lia.gsi.net.GSIGssSocketFactory.java

/**
 * @param inetAddress :/*from   w  ww  .  j  a v  a 2s .  c  o m*/
 *            the remote address
 * @param port :
 *            the remote port
 * @param doDelegation :
 *            if true, the client credential is delegated
 * @param fullDelegation :
 *            if doDelegation is set, this parameter specifies the type of delegation (FULL or LIMITED)
 * @return the GSI-protected socket connected to the remote host
 * @throws IOException
 */
public java.net.Socket createSocket(java.net.InetAddress inetAddress, int port, boolean doDelegation,
        boolean fullDelegation) throws IOException {
    // raw socket
    Socket socket = null;
    try {
        //override the search path for the CA directory: (GSI-SSHTERM writes in the ~/.globus/certificates so we don;t use this)
        //1) java X509_CERT_DIR property
        //2) override with X509_CERT_DIR env var
        //3) default /etc/grid-security/certificates
        String x509CertDir = System.getProperty("X509_CERT_DIR");
        if (x509CertDir == null) {
            x509CertDir = System.getenv("X509_CERT_DIR");
            if (x509CertDir == null)
                x509CertDir = "/etc/grid-security/certificates";
            System.setProperty("X509_CERT_DIR", x509CertDir);
        }

        String x509UserProxy = System.getenv("X509_USER_PROXY");
        if (x509UserProxy == null)
            x509UserProxy = CoGProperties.getDefault().getProxyFile();
        System.out.println("Trying " + x509UserProxy);
        GSSCredential credential = createUserCredential(x509UserProxy);
        if (credential == null) {
            throw new IOException("User credential not initialized !");
        }

        logger.info("createSocket() user credential is " + credential.getName());
        GSSManager manager = ExtendedGSSManager.getInstance();
        org.globus.gsi.gssapi.auth.GSSAuthorization gssAuth = org.globus.gsi.gssapi.auth.HostAuthorization
                .getInstance();
        GSSName targetName = gssAuth.getExpectedName(null, inetAddress.getCanonicalHostName());
        ExtendedGSSContext context = (ExtendedGSSContext) manager.createContext(targetName,
                GSSConstants.MECH_OID, credential, GSSContext.DEFAULT_LIFETIME);
        context.setOption(GSSConstants.GSS_MODE, GSIConstants.MODE_GSI);
        context.requestCredDeleg(doDelegation);
        if (doDelegation) {

            if (fullDelegation) {
                context.setOption(GSSConstants.DELEGATION_TYPE, GSIConstants.DELEGATION_TYPE_FULL);
            } else {
                context.setOption(GSSConstants.DELEGATION_TYPE, GSIConstants.DELEGATION_TYPE_LIMITED);
            }
        }

        SocketAddress socketAddress = new InetSocketAddress(inetAddress, port);
        socket = new Socket();
        socket.connect(socketAddress, GSI_CONNECT_TIMEOUT);
        GSIGssSocket gsiSocket = new GSIGssSocket(socket, context);
        gsiSocket.setUseClientMode(true);
        gsiSocket.setAuthorization(gssAuth);
        // Should be GSI_MODE ?
        gsiSocket.setWrapMode(GssSocket.SSL_MODE);
        gsiSocket.startHandshake();
        socket = gsiSocket;
    } catch (Throwable e) {
        if (socket != null) {
            try {
                socket.close();
            } catch (Exception e1) {
                logger.debug("Socket is already closed.");
            }
        }
        throw new IOException(e.toString());
    }
    // return the wrapped socket
    return socket;

}