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.twinsoft.convertigo.eclipse.learnproxy.http.HttpProxyWorker.java

private void closeSocket(Socket sock) {
    try {//from  www .j  ava2 s. co  m
        sock.close();
    } catch (Exception e) {
        // we cannot do anything if this op crashes
    }
}

From source file:com.l2jfree.loginserver.thread.FloodProtectedListener.java

@Override
public void run() {
    for (;;) {//from w  ww . j a  va  2 s  .  c o  m
        Socket connection = null;
        try {
            connection = _serverSocket.accept();

            if (isFlooding(connection))
                continue;

            addClient(connection);
        } catch (Exception e) {
            _log.warn("", e);

            try {
                if (connection != null)
                    connection.close();
            } catch (IOException e2) {
            }
        }

        if (isInterrupted()) {
            // shutdown?
            try {
                _serverSocket.close();
            } catch (IOException e3) {
                _log.warn("", e3);
            }
            return;
        }
    }
}

From source file:com.googlecode.android_scripting.jsonrpc.JsonRpcServerTest.java

public void testValidHandshake() throws IOException, JSONException {
    JsonRpcServer server = new JsonRpcServer(null, "foo");
    InetSocketAddress address = server.startLocal(0);
    Socket client = new Socket();
    client.connect(address);/* w  ww  . j a  v  a2 s.c o m*/
    PrintStream out = new PrintStream(client.getOutputStream());
    out.println(buildRequest(0, "_authenticate", Lists.newArrayList("foo")));
    BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
    JSONObject response = new JSONObject(in.readLine());
    Object error = response.get("error");
    assertEquals(JSONObject.NULL, error);
    client.close();
    server.shutdown();
}

From source file:fr.opensagres.xdocreport.osgi.integrationtests.remoting.RemotingTest.java

private void waitForPortToBeAvailable(int port) throws Exception {
    waitForFullInitialization();//from w w w .j  av  a 2 s  . c om

    for (int i = 0; i < 20; i++) {
        Socket s = null;
        try {
            s = new Socket((String) null, port);
            // yep, its available
            return;
        } catch (IOException e) {
            // wait
        } finally {
            if (s != null) {
                try {
                    s.close();
                } catch (IOException e) {
                }
            }
        }
        System.out.println("Waiting for server to appear on port: " + port);
        Thread.sleep(1000);
    }
    throw new java.util.concurrent.TimeoutException();
}

From source file:it.jnrpe.server.CBindingThread.java

@Override
public void run() {
    if (m_Logger.isInfoEnabled())
        m_Logger.info("LISTENING TO " + m_Binding.getIP() + ":" + m_Binding.getPort());

    try {//from  ww w  .j  a v a 2  s  .co  m
        while (!this.isInterrupted()) {
            Socket clientSocket = m_serverSocket.accept();
            if (clientSocket != null) {
                if (!canAccept(clientSocket.getInetAddress())) {
                    if (m_Logger.isInfoEnabled())
                        m_Logger.info("REFUSING CONNECTION FROM " + clientSocket.getInetAddress());

                    clientSocket.close();
                    continue;
                }

                if (m_Logger.isDebugEnabled())
                    m_Logger.trace("ACCEPTING CONNECTION FROM " + clientSocket.getInetAddress());

                //                JNRPEServerThread kk = new JNRPEServerThread(clientSocket);
                JNRPEServerThread kk = m_threadFactory.createNewThread(clientSocket);
                //                CJNRPEServer.getThreadTimeoutWatcher().watch(kk);
                kk.start();
            }
        }
    } catch (SocketException se) {
        // This exception is thrown when the server socket is closed.
        // Ignoring
    } catch (Exception e) {
        m_Logger.error("INTERNAL ERROR: " + e.getMessage(), e);
    }

    m_Logger.info("STOP LISTENING TO " + m_Binding.getIP() + ":" + m_Binding.getPort());
    exit();
}

From source file:com.fuzhepan.arpc.client.ProxyHandler.java

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    log.debug("invoke was called!");

    if (method.getName().equals("toString")) {
        return "toString method was called";
    }/*from   w  w  w .j av a  2  s .  c o m*/

    RpcContext rpcContext = new RpcContext(interfaceName, method.getName(), method.getParameterTypes(), args);

    //get service info and load balance
    List<HostPortPair> serviceList = RpcConfig.getServiceList(serviceName);
    if (serviceList == null || serviceList.size() == 0)
        throw new ClassNotFoundException("not find service : " + serviceName);
    int index = requestCount.get() % serviceList.size();
    if (requestCount.get() > 100)
        requestCount.set(0);
    else
        requestCount.getAndIncrement();
    HostPortPair hostPort = serviceList.get(index);

    Socket socket = new Socket(hostPort.host, hostPort.port);
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
    objectOutputStream.writeObject(rpcContext);
    objectOutputStream.flush();

    ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
    Object response = objectInputStream.readObject();

    objectInputStream.close();
    objectOutputStream.close();
    socket.close();

    Class methodReturnType = method.getReturnType();
    return methodReturnType.cast(response);
}

From source file:com.floragunn.searchguard.tools.SearchGuardAdmin.java

private static void main0(final String[] args) throws Exception {

    System.setProperty("sg.nowarn.client", "true");

    final HelpFormatter formatter = new HelpFormatter();
    Options options = new Options();
    options.addOption("nhnv", "disable-host-name-verification", false, "Disable hostname verification");
    options.addOption("nrhn", "disable-resolve-hostname", false, "Disable hostname beeing resolved");
    options.addOption(Option.builder("ts").longOpt("truststore").hasArg().argName("file").required()
            .desc("Path to truststore (JKS/PKCS12 format)").build());
    options.addOption(Option.builder("ks").longOpt("keystore").hasArg().argName("file").required()
            .desc("Path to keystore (JKS/PKCS12 format").build());
    options.addOption(Option.builder("tst").longOpt("truststore-type").hasArg().argName("type")
            .desc("JKS or PKCS12, if not given use file ext. to dectect type").build());
    options.addOption(Option.builder("kst").longOpt("keystore-type").hasArg().argName("type")
            .desc("JKS or PKCS12, if not given use file ext. to dectect type").build());
    options.addOption(Option.builder("tspass").longOpt("truststore-password").hasArg().argName("password")
            .desc("Truststore password").build());
    options.addOption(Option.builder("kspass").longOpt("keystore-password").hasArg().argName("password")
            .desc("Keystore password").build());
    options.addOption(Option.builder("cd").longOpt("configdir").hasArg().argName("directory")
            .desc("Directory for config files").build());
    options.addOption(Option.builder("h").longOpt("hostname").hasArg().argName("host")
            .desc("Elasticsearch host").build());
    options.addOption(Option.builder("p").longOpt("port").hasArg().argName("port")
            .desc("Elasticsearch transport port (normally 9300)").build());
    options.addOption(Option.builder("cn").longOpt("clustername").hasArg().argName("clustername")
            .desc("Clustername").build());
    options.addOption("sniff", "enable-sniffing", false, "Enable client.transport.sniff");
    options.addOption("icl", "ignore-clustername", false, "Ignore clustername");
    options.addOption(Option.builder("r").longOpt("retrieve").desc("retrieve current config").build());
    options.addOption(Option.builder("f").longOpt("file").hasArg().argName("file").desc("file").build());
    options.addOption(//from   w w  w  .  j a va2s  . c o  m
            Option.builder("t").longOpt("type").hasArg().argName("file-type").desc("file-type").build());
    options.addOption(Option.builder("tsalias").longOpt("truststore-alias").hasArg().argName("alias")
            .desc("Truststore alias").build());
    options.addOption(Option.builder("ksalias").longOpt("keystore-alias").hasArg().argName("alias")
            .desc("Keystore alias").build());
    options.addOption(Option.builder("ec").longOpt("enabled-ciphers").hasArg().argName("cipers")
            .desc("Comma separated list of TLS ciphers").build());
    options.addOption(Option.builder("ep").longOpt("enabled-protocols").hasArg().argName("protocols")
            .desc("Comma separated list of TLS protocols").build());
    //TODO mark as deprecated and replace it with "era" if "era" is mature enough
    options.addOption(Option.builder("us").longOpt("update_settings").hasArg().argName("number of replicas")
            .desc("update the number of replicas and reload configuration on all nodes and exit").build());
    options.addOption(Option.builder("i").longOpt("index").hasArg().argName("indexname")
            .desc("The index Searchguard uses to store its configs in").build());
    options.addOption(Option.builder("era").longOpt("enable-replica-autoexpand")
            .desc("enable replica auto expand and exit").build());
    options.addOption(Option.builder("dra").longOpt("disable-replica-autoexpand")
            .desc("disable replica auto expand and exit").build());
    options.addOption(
            Option.builder("rl").longOpt("reload").desc("reload configuration on all nodes and exit").build());
    options.addOption(
            Option.builder("ff").longOpt("fail-fast").desc("fail-fast if something goes wrong").build());
    options.addOption(
            Option.builder("dg").longOpt("diagnose").desc("Log diagnostic trace into a file").build());
    options.addOption(Option.builder("dci").longOpt("delete-config-index")
            .desc("Delete 'searchguard' config index and exit.").build());
    options.addOption(Option.builder("esa").longOpt("enable-shard-allocation")
            .desc("Enable all shard allocation and exit.").build());

    String hostname = "localhost";
    int port = 9300;
    String kspass = System.getenv(SG_KS_PASS) != null ? System.getenv(SG_KS_PASS) : "changeit";
    String tspass = System.getenv(SG_TS_PASS) != null ? System.getenv(SG_TS_PASS) : kspass;
    String cd = ".";
    String ks;
    String ts;
    String kst = null;
    String tst = null;
    boolean nhnv = false;
    boolean nrhn = false;
    boolean sniff = false;
    boolean icl = false;
    String clustername = "elasticsearch";
    String file = null;
    String type = null;
    boolean retrieve = false;
    String ksAlias = null;
    String tsAlias = null;
    String[] enabledProtocols = new String[0];
    String[] enabledCiphers = new String[0];
    Integer updateSettings = null;
    String index = ConfigConstants.SG_DEFAULT_CONFIG_INDEX;
    Boolean replicaAutoExpand = null;
    boolean reload = false;
    boolean failFast = false;
    boolean diagnose = false;
    boolean deleteConfigIndex = false;
    boolean enableShardAllocation = false;

    CommandLineParser parser = new DefaultParser();
    try {
        CommandLine line = parser.parse(options, args);
        hostname = line.getOptionValue("h", hostname);
        port = Integer.parseInt(line.getOptionValue("p", String.valueOf(port)));
        kspass = line.getOptionValue("kspass", kspass); //TODO null? //when no passwd is set
        tspass = line.getOptionValue("tspass", tspass); //TODO null? //when no passwd is set
        cd = line.getOptionValue("cd", cd);

        if (!cd.endsWith(File.separator)) {
            cd += File.separator;
        }

        ks = line.getOptionValue("ks");
        ts = line.getOptionValue("ts");
        kst = line.getOptionValue("kst", kst);
        tst = line.getOptionValue("tst", tst);
        nhnv = line.hasOption("nhnv");
        nrhn = line.hasOption("nrhn");
        clustername = line.getOptionValue("cn", clustername);
        sniff = line.hasOption("sniff");
        icl = line.hasOption("icl");
        file = line.getOptionValue("f", file);
        type = line.getOptionValue("t", type);
        retrieve = line.hasOption("r");
        ksAlias = line.getOptionValue("ksalias", ksAlias);
        tsAlias = line.getOptionValue("tsalias", tsAlias);
        index = line.getOptionValue("i", index);

        String enabledCiphersString = line.getOptionValue("ec", null);
        String enabledProtocolsString = line.getOptionValue("ep", null);

        if (enabledCiphersString != null) {
            enabledCiphers = enabledCiphersString.split(",");
        }

        if (enabledProtocolsString != null) {
            enabledProtocols = enabledProtocolsString.split(",");
        }

        updateSettings = line.hasOption("us") ? Integer.parseInt(line.getOptionValue("us")) : null;

        reload = line.hasOption("rl");

        if (line.hasOption("era")) {
            replicaAutoExpand = true;
        }

        if (line.hasOption("dra")) {
            replicaAutoExpand = false;
        }

        failFast = line.hasOption("ff");
        diagnose = line.hasOption("dg");
        deleteConfigIndex = line.hasOption("dci");
        enableShardAllocation = line.hasOption("esa");

    } catch (ParseException exp) {
        System.err.println("ERR: Parsing failed.  Reason: " + exp.getMessage());
        formatter.printHelp("sgadmin.sh", options, true);
        return;
    }

    if (port < 9300) {
        System.out.println("WARNING: Seems you want connect to the a HTTP port." + System.lineSeparator()
                + "         sgadmin connect through the transport port which is normally 9300.");
    }

    System.out.print("Will connect to " + hostname + ":" + port);
    Socket socket = new Socket();

    try {

        socket.connect(new InetSocketAddress(hostname, port));

    } catch (java.net.ConnectException ex) {
        System.out.println();
        System.out.println(
                "ERR: Seems there is no elasticsearch running on " + hostname + ":" + port + " - Will exit");
        System.exit(-1);
    } finally {
        try {
            socket.close();
        } catch (Exception e) {
            //ignore
        }
    }

    System.out.println(" ... done");

    final Settings.Builder settingsBuilder = Settings.builder().put("path.home", ".").put("path.conf", ".")
            .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_FILEPATH, ks)
            .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_FILEPATH, ts)
            .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_PASSWORD, kspass)
            .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_PASSWORD, tspass)
            .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_ENFORCE_HOSTNAME_VERIFICATION, !nhnv)
            .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_ENFORCE_HOSTNAME_VERIFICATION_RESOLVE_HOST_NAME,
                    !nrhn)
            .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_ENABLED, true)
            .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_TYPE,
                    kst == null ? (ks.endsWith(".jks") ? "JKS" : "PKCS12") : kst)
            .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_TYPE,
                    tst == null ? (ts.endsWith(".jks") ? "JKS" : "PKCS12") : tst)

            .putArray(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_ENABLED_CIPHERS, enabledCiphers)
            .putArray(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_ENABLED_PROTOCOLS, enabledProtocols)

            .put("cluster.name", clustername).put("client.transport.ignore_cluster_name", icl)
            .put("client.transport.sniff", sniff);

    if (ksAlias != null) {
        settingsBuilder.put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_ALIAS, ksAlias);
    }

    if (tsAlias != null) {
        settingsBuilder.put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_ALIAS, tsAlias);
    }

    Settings settings = settingsBuilder.build();

    try (TransportClient tc = TransportClient.builder().settings(settings).addPlugin(SearchGuardSSLPlugin.class)
            .addPlugin(SearchGuardPlugin.class) //needed for config update action only
            .build()
            .addTransportAddress(new InetSocketTransportAddress(new InetSocketAddress(hostname, port)))) {

        if (updateSettings != null) {
            Settings indexSettings = Settings.builder().put("index.number_of_replicas", updateSettings).build();
            tc.execute(ConfigUpdateAction.INSTANCE, new ConfigUpdateRequest(
                    new String[] { "config", "roles", "rolesmapping", "internalusers", "actiongroups" }))
                    .actionGet();
            final UpdateSettingsResponse response = tc.admin().indices()
                    .updateSettings((new UpdateSettingsRequest(index).settings(indexSettings))).actionGet();
            System.out.println("Reload config on all nodes");
            System.out.println("Update number of replicas to " + (updateSettings) + " with result: "
                    + response.isAcknowledged());
            System.exit(response.isAcknowledged() ? 0 : -1);
        }

        if (reload) {
            tc.execute(ConfigUpdateAction.INSTANCE, new ConfigUpdateRequest(
                    new String[] { "config", "roles", "rolesmapping", "internalusers", "actiongroups" }))
                    .actionGet();
            System.out.println("Reload config on all nodes");
            System.exit(0);
        }

        if (replicaAutoExpand != null) {
            Settings indexSettings = Settings.builder()
                    .put("index.auto_expand_replicas", replicaAutoExpand ? "0-all" : "false").build();
            tc.execute(ConfigUpdateAction.INSTANCE, new ConfigUpdateRequest(
                    new String[] { "config", "roles", "rolesmapping", "internalusers", "actiongroups" }))
                    .actionGet();
            final UpdateSettingsResponse response = tc.admin().indices()
                    .updateSettings((new UpdateSettingsRequest(index).settings(indexSettings))).actionGet();
            System.out.println("Reload config on all nodes");
            System.out.println("Auto-expand replicas " + (replicaAutoExpand ? "enabled" : "disabled"));
            System.exit(response.isAcknowledged() ? 0 : -1);
        }

        if (enableShardAllocation) {
            final boolean successful = tc.admin().cluster()
                    .updateSettings(new ClusterUpdateSettingsRequest()
                            .transientSettings(ENABLE_ALL_ALLOCATIONS_SETTINGS)
                            .persistentSettings(ENABLE_ALL_ALLOCATIONS_SETTINGS))
                    .actionGet().isAcknowledged();

            if (successful) {
                System.out.println("Persistent and transient shard allocation enabled");
            } else {
                System.out.println("ERR: Unable to enable shard allocation");
            }

            System.exit(successful ? 0 : -1);
        }

        if (failFast) {
            System.out.println("Failfast is activated");
        }

        if (diagnose) {
            generateDiagnoseTrace(tc);
        }

        System.out.println(
                "Contacting elasticsearch cluster '" + clustername + "' and wait for YELLOW clusterstate ...");

        ClusterHealthResponse chr = null;

        while (chr == null) {
            try {
                chr = tc.admin().cluster().health(
                        new ClusterHealthRequest().timeout(TimeValue.timeValueMinutes(5)).waitForYellowStatus())
                        .actionGet();
            } catch (Exception e) {
                if (!failFast) {
                    System.out.println("Cannot retrieve cluster state due to: " + e.getMessage()
                            + ". This is not an error, will keep on trying ...");
                    System.out.println(
                            "   * Try running sgadmin.sh with -icl and -nhnv (If thats works you need to check your clustername as well as hostnames in your SSL certificates)");
                    System.out.println(
                            "   * If this is not working, try running sgadmin.sh with --diagnose and see diagnose trace log file)");

                } else {
                    System.out.println("ERR: Cannot retrieve cluster state due to: " + e.getMessage() + ".");
                    System.out.println(
                            "   * Try running sgadmin.sh with -icl and -nhnv (If thats works you need to check your clustername as well as hostnames in your SSL certificates)");
                    System.out.println(
                            "   * If this is not working, try running sgadmin.sh with --diagnose and see diagnose trace log file)");

                    System.exit(-1);
                }

                Thread.sleep(3000);
                continue;
            }
        }

        final boolean timedOut = chr.isTimedOut();

        if (timedOut) {
            System.out.println("ERR: Timed out while waiting for a green or yellow cluster state.");
            System.out.println(
                    "   * Try running sgadmin.sh with -icl and -nhnv (If thats works you need to check your clustername as well as hostnames in your SSL certificates)");
            System.exit(-1);
        }

        System.out.println("Clustername: " + chr.getClusterName());
        System.out.println("Clusterstate: " + chr.getStatus());
        System.out.println("Number of nodes: " + chr.getNumberOfNodes());
        System.out.println("Number of data nodes: " + chr.getNumberOfDataNodes());

        final boolean indexExists = tc.admin().indices().exists(new IndicesExistsRequest(index)).actionGet()
                .isExists();

        final NodesInfoResponse nodesInfo = tc.admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet();

        if (deleteConfigIndex) {

            boolean success = true;

            if (indexExists) {
                success = tc.admin().indices().delete(new DeleteIndexRequest(index)).actionGet()
                        .isAcknowledged();
                System.out.print("Deleted index '" + index + "'");
            } else {
                System.out.print("No index '" + index + "' exists, so no need to delete it");
            }

            System.exit(success ? 0 : -1);
        }

        if (!indexExists) {
            System.out.print(index + " index does not exists, attempt to create it ... ");
            int replicas = chr.getNumberOfDataNodes() - 1;
            final boolean indexCreated = tc.admin().indices().create(new CreateIndexRequest(index)
                    // .mapping("config", source)
                    // .settings(settings)
                    //TODO "index.auto_expand_replicas", "0-all"
                    .settings("index.number_of_shards", 1, "index.number_of_replicas", replicas)).actionGet()
                    .isAcknowledged();

            if (indexCreated) {
                System.out.println("done (with " + replicas + " replicas, auto expand replicas is off)");
            } else {
                System.out.println("failed!");
                System.out.println("FAIL: Unable to create the " + index
                        + " index. See elasticsearch logs for more details");
                System.exit(-1);
            }

        } else {
            System.out.println(index + " index already exists, so we do not need to create one.");

            try {
                ClusterHealthResponse chrsg = tc.admin().cluster().health(new ClusterHealthRequest(index))
                        .actionGet();

                if (chrsg.isTimedOut()) {
                    System.out.println("ERR: Timed out while waiting for " + index + " index state.");
                }

                if (chrsg.getStatus() == ClusterHealthStatus.RED) {
                    System.out.println("ERR: " + index + " index state is RED.");
                }

                if (chrsg.getStatus() == ClusterHealthStatus.YELLOW) {
                    System.out.println(
                            "INFO: " + index + " index state is YELLOW, it seems you miss some replicas");
                }

            } catch (Exception e) {
                if (!failFast) {
                    System.out.println("Cannot retrieve " + index + " index state state due to "
                            + e.getMessage() + ". This is not an error, will keep on trying ...");
                } else {
                    System.out.println("ERR: Cannot retrieve " + index + " index state state due to "
                            + e.getMessage() + ".");
                    System.exit(-1);
                }
            }
        }

        if (retrieve) {
            String date = DATE_FORMAT.format(new Date());

            boolean success = retrieveFile(tc, cd + "sg_config_" + date + ".yml", index, "config");
            success = success & retrieveFile(tc, cd + "sg_roles_" + date + ".yml", index, "roles");
            success = success
                    & retrieveFile(tc, cd + "sg_roles_mapping_" + date + ".yml", index, "rolesmapping");
            success = success
                    & retrieveFile(tc, cd + "sg_internal_users_" + date + ".yml", index, "internalusers");
            success = success
                    & retrieveFile(tc, cd + "sg_action_groups_" + date + ".yml", index, "actiongroups");
            System.exit(success ? 0 : -1);
        }

        boolean isCdAbs = new File(cd).isAbsolute();

        System.out.println("Populate config from " + (isCdAbs ? cd : new File(".", cd).getCanonicalPath()));

        if (file != null) {
            if (type == null) {
                System.out.println("ERR: type missing");
                System.exit(-1);
            }

            if (!Arrays
                    .asList(new String[] { "config", "roles", "rolesmapping", "internalusers", "actiongroups" })
                    .contains(type)) {
                System.out.println("ERR: Invalid type '" + type + "'");
                System.exit(-1);
            }

            boolean success = uploadFile(tc, file, index, type);
            System.exit(success ? 0 : -1);
        }

        boolean success = uploadFile(tc, cd + "sg_config.yml", index, "config");
        success = success & uploadFile(tc, cd + "sg_roles.yml", index, "roles");
        success = success & uploadFile(tc, cd + "sg_roles_mapping.yml", index, "rolesmapping");
        success = success & uploadFile(tc, cd + "sg_internal_users.yml", index, "internalusers");
        success = success & uploadFile(tc, cd + "sg_action_groups.yml", index, "actiongroups");

        if (failFast && !success) {
            System.out.println("ERR: cannot upload configuration, see errors above");
            System.exit(-1);
        }

        ConfigUpdateResponse cur = tc
                .execute(ConfigUpdateAction.INSTANCE, new ConfigUpdateRequest(
                        new String[] { "config", "roles", "rolesmapping", "internalusers", "actiongroups" }))
                .actionGet();

        success = success & checkConfigUpdateResponse(cur, nodesInfo, 5);

        System.out.println("Done with " + (success ? "success" : "failures"));
        System.exit(success ? 0 : -1);
    }
    // TODO audit changes to searchguard index
}

From source file:com.sixt.service.framework.registry.consul.RegistrationManager.java

protected void unregisterService() {
    if (!isRegistered.get()) {
        return;//from  ww  w  .  ja v  a  2s .  c  om
    }
    try {
        logger.info("Unregistering {}", serviceName);
        String registryServer = serviceProps.getRegistryServer();
        int colon = registryServer.indexOf(':');
        String hostname = registryServer.substring(0, colon);
        int port = Integer.parseInt(registryServer.substring(colon + 1));
        Socket sock = new Socket(hostname, port);
        OutputStream out = sock.getOutputStream();
        out.write(unregisterString.getBytes());
        out.flush();
        sock.close();

        if (isShutdownHookRegistered.get()) {
            isShutdownHookRegistered.set(false);
        }
    } catch (Exception ex) {
        logger.error("Error unregistering from consul", ex);
    }
}

From source file:com.axelor.apps.base.service.MapService.java

private boolean testInternet(String site) {
    Socket socket = new Socket();
    InetSocketAddress address = new InetSocketAddress(site, 80);
    try {/*from   ww w.  ja va 2s.  c om*/
        socket.connect(address, 3000);
        return true;
    } catch (IOException e) {
        return false;
    } finally {
        try {
            socket.close();
        } catch (IOException e) {
        }
    }
}

From source file:at.alladin.rmbt.android.util.CheckIpTask.java

@Override
protected JSONArray doInBackground(final Void... params) {
    needsRetry = false;/* w  w w  .j ava  2 s.  c  o m*/
    serverConn = new ControlServerConnection(activity);

    try {
        Socket s = new Socket();
        InetSocketAddress addr = new InetSocketAddress(
                ConfigHelper.getCachedControlServerNameIpv4(activity.getApplicationContext()),
                ConfigHelper.getControlServerPort(activity.getApplicationContext()));
        s.connect(addr, 5000);

        privateIpv4 = s.getLocalAddress();
        s.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        Socket s = new Socket();
        InetSocketAddress addr = new InetSocketAddress(
                ConfigHelper.getCachedControlServerNameIpv6(activity.getApplicationContext()),
                ConfigHelper.getControlServerPort(activity.getApplicationContext()));
        s.connect(addr, 5000);

        privateIpv6 = s.getLocalAddress();
        s.close();
    } catch (SocketTimeoutException e) {
        e.printStackTrace();
        needsRetry = ConfigHelper.isRetryRequiredOnIpv6SocketTimeout(activity);
    } catch (Exception e) {
        needsRetry = false;
        e.printStackTrace();
    }

    newsList = new JSONArray();

    if (privateIpv4 != null) {
        JSONArray response = serverConn.requestIp(false);
        if (response != null && response.length() >= 1) {
            newsList.put(response.opt(0));
        }
    } else {
        Log.d(DEBUG_TAG, "no private ipv4 found");
    }

    if (privateIpv6 != null) {
        JSONArray response = serverConn.requestIp(true);
        if (response != null && response.length() >= 1) {
            newsList.put(response.opt(0));
        }
    } else {
        Log.d(DEBUG_TAG, "no private ipv6 found");
    }

    return newsList;
}