Example usage for java.net InetSocketAddress toString

List of usage examples for java.net InetSocketAddress toString

Introduction

In this page you can find the example usage for java.net InetSocketAddress toString.

Prototype

@Override
public String toString() 

Source Link

Document

Constructs a string representation of this InetSocketAddress.

Usage

From source file:com.ethercis.vehr.Launcher.java

public void start(String[] args) throws Exception {
    boolean debug = false;
    List<String> normalizedArguments = new ArrayList<>(Arrays.asList(args));

    CommandLineParser parser = new DefaultParser();
    CommandLine commandLine = parser.parse(options, args);

    if (commandLine.hasOption("debug"))
        debug = true;/*from   w  w  w.  jav  a  2  s  . co  m*/

    if (commandLine.hasOption("dialect")) {
        String compatibilityValue = commandLine.getOptionValue("dialect", "STANDARD");
        //TODO: add compatibility argument in args
        normalizedArguments.add("-" + I_ServiceRunMode.SERVER_DIALECT_PARAMETER);
        normalizedArguments.add(I_ServiceRunMode.DialectSpace.valueOf(compatibilityValue).name());
    }

    Integer httpPort = Integer.parseInt(commandLine.getOptionValue(command_server_port, default_port));
    String httpHost = commandLine.getOptionValue(command_server_host, default_host);

    InetSocketAddress socketAddress = new InetSocketAddress(httpHost, httpPort);

    logger.info("Server starting on host:" + httpHost + " port:" + httpPort);

    server = new Server(socketAddress);
    if (debug)
        server.setStopAtShutdown(true);
    //create and initialize vEhrHandler
    vEhrGateServlet = new VEhrGateServlet();
    vEhrGateServlet.init(normalizedArguments.toArray(new String[] {}));

    ServletContextHandler servletContextHandler = new ServletContextHandler(server, "/",
            ServletContextHandler.NO_SESSIONS | ServletContextHandler.NO_SECURITY);

    //add filter to allow CORS
    FilterHolder cors = new FilterHolder(CrossOriginFilter.class);
    //        FilterHolder cors = servletContextHandler.addFilter(CrossOriginFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
    cors.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, null);
    cors.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*");
    cors.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_EXPOSE_HEADERS_HEADER, "*");
    cors.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET, POST, DELETE, PUT, OPTIONS, HEAD");
    cors.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM,
            "X-Requested-With,Content-Type,Accept,Origin");
    cors.setName("cross-origin");
    FilterMapping filterMapping = new FilterMapping();
    filterMapping.setFilterName("cross-origin");
    filterMapping.setPathSpec("*");
    servletContextHandler.addFilter(cors, "/*", EnumSet.allOf(DispatcherType.class));
    //        servletContextHandler.addFilter(cors, "/*", null);
    //        servletContextHandler.getServletHandler().addFilter(cors, filterMapping);

    ServletHolder servletHolder = new ServletHolder(vEhrGateServlet);
    servletContextHandler.addServlet(servletHolder, "/");

    HandlerList handlerList = new HandlerList();
    handlerList.setHandlers(new Handler[] { servletContextHandler, new DefaultHandler() });
    server.setHandler(handlerList);

    try {
        server.start();
    } catch (BindException e) {
        logger.error("Address already in use! (" + socketAddress.toString() + ")");
        throw new IllegalArgumentException("Address already in use! (" + socketAddress.toString() + ")");
    }
    logger.info("Server listening at:" + server.getURI().toString());
    if (!debug)
        server.join();

}

From source file:my.adam.smo.client.SocketClient.java

@Override
public RpcChannel connect(final InetSocketAddress sa) {
    RpcChannel rpcChannel = new RpcChannel() {
        private Channel c = bootstrap.connect(sa).awaitUninterruptibly().getChannel();

        @Override//from w w  w  .  j a va 2s  .  c  o  m
        public void callMethod(Descriptors.MethodDescriptor method, RpcController controller, Message request,
                Message responsePrototype, RpcCallback<Message> done) {
            StopWatch stopWatch = new StopWatch("callMethod");
            stopWatch.start();

            long id = seqNum.addAndGet(1);

            logger.trace("calling method: " + method.getFullName());

            //infinit reconnection loop
            while (reconnect && !c.isOpen()) {
                logger.debug("channel closed " + sa);
                logger.debug("trying to reconnect");
                c.disconnect().awaitUninterruptibly();
                c.unbind().awaitUninterruptibly();
                c = bootstrap.connect(sa).awaitUninterruptibly().getChannel();
                try {
                    Thread.sleep(reconnect_delay * 1000);
                } catch (InterruptedException e) {
                    logger.error("error while sleeping", e);
                }
            }

            RPCommunication.Request protoRequest = RPCommunication.Request.newBuilder()
                    .setServiceName(method.getService().getFullName()).setMethodName(method.getName())
                    .setMethodArgument(request.toByteString()).setRequestId(id).build();

            logger.trace("request built: " + request.toString());

            if (enableSymmetricEncryption) {
                protoRequest = getEncryptedRequest(protoRequest);
                logger.trace("symmetric encryption enabled, encrypted request: " + protoRequest.toString());
            }

            if (enableAsymmetricEncryption) {
                protoRequest = getAsymEncryptedRequest(protoRequest);
                logger.trace("asymmetric encryption enabled, encrypted request: " + protoRequest.toString());
            }

            callbackMap.put(id, done);
            descriptorProtoMap.put(id, responsePrototype);

            c.write(protoRequest);
            logger.trace("request sent: " + protoRequest.toString());

            stopWatch.stop();
            logger.trace(stopWatch.shortSummary());
        }
    };
    logger.trace("connected to address: " + sa.toString());
    return rpcChannel;
}

From source file:my.adam.smo.client.HTTPClient.java

@Override
public RpcChannel connect(final InetSocketAddress sa) {
    RpcChannel rpcChannel = new RpcChannel() {
        private Channel c = bootstrap.connect(sa).awaitUninterruptibly().getChannel();

        @Override// w  ww. ja  va  2 s  . c  o  m
        public void callMethod(Descriptors.MethodDescriptor method, RpcController controller, Message request,
                Message responsePrototype, RpcCallback<Message> done) {
            StopWatch stopWatch = new StopWatch("callMethod");
            stopWatch.start();

            long id = seqNum.addAndGet(1);

            logger.trace("calling method: " + method.getFullName());

            HttpRequest httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
                    "http://" + sa.getHostName() + ":" + sa.getPort());
            httpRequest.setHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
            httpRequest.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
            httpRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE,
                    HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED);

            RPCommunication.Request protoRequest = RPCommunication.Request.newBuilder()
                    .setServiceName(method.getService().getFullName()).setMethodName(method.getName())
                    .setMethodArgument(request.toByteString()).setRequestId(id).build();

            logger.trace("request built: " + request.toString());

            if (enableSymmetricEncryption) {
                protoRequest = getEncryptedRequest(protoRequest);
                logger.trace("symmetric encryption enabled, encrypted request: " + protoRequest.toString());
            }

            if (enableAsymmetricEncryption) {
                protoRequest = getAsymEncryptedRequest(protoRequest);
                logger.trace("asymmetric encryption enabled, encrypted request: " + protoRequest.toString());
            }

            byte[] arr = protoRequest.toByteArray();

            ChannelBuffer s = Base64.encode(ChannelBuffers.copiedBuffer(arr), Base64Dialect.STANDARD);

            httpRequest.setContent(s);

            httpRequest.addHeader(HttpHeaders.Names.CONTENT_LENGTH, s.readableBytes());

            httpRequest.setChunked(false);

            callbackMap.put(id, done);
            descriptorProtoMap.put(id, responsePrototype);

            c.write(httpRequest);
            logger.trace("request sent: " + protoRequest.toString());

            stopWatch.stop();
            logger.trace(stopWatch.shortSummary());
        }
    };
    logger.trace("connected to address: " + sa.toString());
    return rpcChannel;
}

From source file:org.cloudata.core.master.CloudataMaster.java

/**
 * Master lock? acquire ?? ? .//from   w  ww . jav  a  2s.c o m
 * 
 * @throws IOException
 */
private void masterInit() throws IOException {
    if (!fs.isReady()) {
        LOG.fatal("FileSystem is not ready. " + "check " + conf.get("cloudata.root")
                + " directory. CloudataMaster shutdown");
        shutdown();
    }
    masterInitTime = new Date();
    masterElected = true;
    setClusterReady(false);

    masterMetrics = new CloudataMasterMetrics(conf);
    (new Thread(threadGroup, new UpdateMetricsThread())).start();

    addLockEventHandler();

    try {
        loadAllTableSchemas(conf);
        synchronized (Constants.SC_LOCK_PATH) {
            LockUtil.createNodes(zk, LockUtil.getZKPath(conf, Constants.SC_LOCK_PATH), "0".getBytes(),
                    CreateMode.PERSISTENT, true);
            LockUtil.createNodes(zk, LockUtil.getZKPath(conf, Constants.MC_LOCK_PATH), "0".getBytes(),
                    CreateMode.PERSISTENT, true);
        }
    } catch (IOException e) {
        LOG.fatal("CloudataMaster shutdown cause:" + e.getMessage(), e);
        shutdown();
        return;
    }

    Thread rootTabletAssignmentThread = new Thread(threadGroup, new RootTabletAssignmentThread());
    rootTabletAssignmentThread.start();

    InetSocketAddress infoServerAddress = NetworkUtil
            .getAddress(conf.get("masterServer.info.address", "0.0.0.0:57000"));

    try {
        this.infoServer = new CStatusHttpServer("master", infoServerAddress.getHostName(),
                infoServerAddress.getPort());
        this.infoServer.start();
        LOG.info("Info Http Server started: " + infoServerAddress.toString());
    } catch (Exception e) {
        LOG.warn("Error while info server init:" + e.getMessage());
    }

    // ? ? tablet drop?  
    List<String> dropTables = null;
    try {
        dropTables = zk.getChildren(LockUtil.getZKPath(conf, Constants.TABLE_DROP), false);
    } catch (NoNodeException e) {
    } catch (Exception e) {
        throw new IOException(e);
    }
    if (dropTables != null) {
        for (String eachDropTable : dropTables) {
            asyncTaskManager.runAsyncTask(new TableDropTask(eachDropTable));
        }
    }
}

From source file:edu.umass.cs.reconfiguration.SQLReconfiguratorDB.java

private boolean addToNodeConfig(NodeIDType node, InetSocketAddress sockAddr, int version,
        boolean isReconfigurator) {
    String cmd = "insert into " + getNodeConfigTable() + " (" + Columns.RC_NODE_ID.toString() + ", "
            + Columns.INET_ADDRESS.toString() + ", " + Columns.PORT.toString() + ", "
            + Columns.NODE_CONFIG_VERSION.toString() + ", " + Columns.IS_RECONFIGURATOR.toString()
            + " ) values (?,?,?,?,?)";

    PreparedStatement insertCP = null;
    Connection conn = null;//from   ww  w  .  jav  a2 s  .  c  o m
    boolean added = false;
    try {
        conn = this.getDefaultConn();
        insertCP = conn.prepareStatement(cmd);
        insertCP.setString(1, node.toString());
        insertCP.setString(2, sockAddr.toString());
        insertCP.setInt(3, sockAddr.getPort());
        insertCP.setInt(4, version);
        insertCP.setInt(5, isReconfigurator ? 1 : 0); // 1 means true
        insertCP.executeUpdate();
        // conn.commit();
        added = true;
    } catch (SQLException sqle) {
        if (!SQL.DUPLICATE_KEY.contains(sqle.getSQLState())) {
            log.severe("SQLException while inserting RC record using " + cmd);
            sqle.printStackTrace();
        }
    } finally {
        cleanup(insertCP);
        cleanup(conn);
    }
    return added;
}