Example usage for java.net InetSocketAddress getHostName

List of usage examples for java.net InetSocketAddress getHostName

Introduction

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

Prototype

public final String getHostName() 

Source Link

Document

Gets the hostname .

Usage

From source file:com.bigstep.datalake.DLFileSystem.java

/**
 * Return a URL pointing to given path on the namenode.
 *
 * @param path  to obtain the URL for/*w  ww  .j av a2  s.  c om*/
 * @param query string to append to the path
 * @return namenode URL referring to the given path
 * @throws IOException on error constructing the URL
 */
private URL getNamenodeURL(String path, String query) throws IOException {
    InetSocketAddress nnAddr = getCurrentNNAddr();
    final URL url = new URL(getTransportScheme(), nnAddr.getHostName(), nnAddr.getPort(), path + '?' + query);
    if (LOG.isTraceEnabled()) {
        LOG.trace("url=" + url);
    }
    return url;
}

From source file:org.apache.hadoop.http.HttpServer.java

/**
 * Configure an ssl listener on the server.
 * @param addr address to listen on/*from  w  ww  .  j  a  v a 2  s  .  c  o  m*/
 * @param sslConf conf to retrieve ssl options
 * @param needCertsAuth whether x509 certificate authentication is required
 * @param needKrbAuth whether to allow kerberos auth
 */
public void addSslListener(InetSocketAddress addr, Configuration sslConf, boolean needCertsAuth,
        boolean needKrbAuth) throws IOException {
    if (webServer.isStarted()) {
        throw new IOException("Failed to add ssl listener");
    }
    if (needCertsAuth) {
        // setting up SSL truststore for authenticating clients
        System.setProperty("javax.net.ssl.trustStore", sslConf.get("ssl.server.truststore.location", ""));
        System.setProperty("javax.net.ssl.trustStorePassword",
                sslConf.get("ssl.server.truststore.password", ""));
        System.setProperty("javax.net.ssl.trustStoreType", sslConf.get("ssl.server.truststore.type", "jks"));
    }
    Krb5AndCertsSslSocketConnector.MODE mode;
    if (needCertsAuth && needKrbAuth)
        mode = MODE.BOTH;
    else if (!needCertsAuth && needKrbAuth)
        mode = MODE.KRB;
    else // Default to certificates
        mode = MODE.CERTS;

    SslSocketConnector sslListener = new Krb5AndCertsSslSocketConnector(mode);
    sslListener.setHost(addr.getHostName());
    sslListener.setPort(addr.getPort());
    sslListener.setKeystore(sslConf.get("ssl.server.keystore.location"));
    sslListener.setPassword(sslConf.get("ssl.server.keystore.password", ""));
    sslListener.setKeyPassword(sslConf.get("ssl.server.keystore.keypassword", ""));
    sslListener.setKeystoreType(sslConf.get("ssl.server.keystore.type", "jks"));
    sslListener.setNeedClientAuth(needCertsAuth);
    webServer.addConnector(sslListener);
}

From source file:common.DataNode.java

/**
 * This method starts the data node with the specified conf.
 * // w ww.  ja v  a  2  s.  co  m
 * @param conf - the configuration
 *  if conf's CONFIG_PROPERTY_SIMULATED property is set
 *  then a simulated storage based data node is created.
 * 
 * @param dataDirs - only for a non-simulated storage data node
 * @throws IOException
 */
void startDataNode(Configuration conf, AbstractList<File> dataDirs, DatanodeProtocol namenode)
        throws IOException {
    // use configured nameserver & interface to get local hostname
    if (conf.get(DFSConfigKeys.DFS_DATANODE_HOST_NAME_KEY) != null) {
        machineName = conf.get(DFSConfigKeys.DFS_DATANODE_HOST_NAME_KEY);
    }
    if (machineName == null) {
        machineName = DNS.getDefaultHost(conf.get("dfs.datanode.dns.interface", "default"),
                conf.get("dfs.datanode.dns.nameserver", "default"));
    }
    this.nameNodeAddr = NameNode.getAddress(conf);

    this.socketTimeout = conf.getInt(DFSConfigKeys.DFS_CLIENT_SOCKET_TIMEOUT_KEY, HdfsConstants.READ_TIMEOUT);
    this.socketWriteTimeout = conf.getInt("dfs.datanode.socket.write.timeout", HdfsConstants.WRITE_TIMEOUT);
    /* Based on results on different platforms, we might need set the default 
     * to false on some of them. */
    this.transferToAllowed = conf.getBoolean("dfs.datanode.transferTo.allowed", true);
    this.writePacketSize = conf.getInt(DFSConfigKeys.DFS_CLIENT_WRITE_PACKET_SIZE_KEY,
            DFSConfigKeys.DFS_CLIENT_WRITE_PACKET_SIZE_DEFAULT);
    InetSocketAddress socAddr = NetUtils.createSocketAddr(conf.get("dfs.datanode.address", "0.0.0.0:50010"));
    int tmpPort = socAddr.getPort();
    storage = new DataStorage();
    // construct registration
    this.dnRegistration = new DatanodeRegistration(machineName + ":" + tmpPort);

    // connect to name node
    this.namenode = namenode;

    // get version and id info from the name-node
    NamespaceInfo nsInfo = handshake();
    StartupOption startOpt = getStartupOption(conf);
    assert startOpt != null : "Startup option must be set.";

    boolean simulatedFSDataset = conf.getBoolean("dfs.datanode.simulateddatastorage", false);
    if (simulatedFSDataset) {
        setNewStorageID(dnRegistration);
        dnRegistration.storageInfo.layoutVersion = FSConstants.LAYOUT_VERSION;
        dnRegistration.storageInfo.namespaceID = nsInfo.namespaceID;
        // it would have been better to pass storage as a parameter to
        // constructor below - need to augment ReflectionUtils used below.
        conf.set(DFSConfigKeys.DFS_DATANODE_STORAGEID_KEY, dnRegistration.getStorageID());
        try {
            //Equivalent of following (can't do because Simulated is in test dir)
            //  this.data = new SimulatedFSDataset(conf);
            this.data = (FSDatasetInterface) ReflectionUtils.newInstance(
                    Class.forName("org.apache.hadoop.hdfs.server.datanode.SimulatedFSDataset"), conf);
        } catch (ClassNotFoundException e) {
            throw new IOException(StringUtils.stringifyException(e));
        }
    } else { // real storage
        // read storage info, lock data dirs and transition fs state if necessary
        storage.recoverTransitionRead(nsInfo, dataDirs, startOpt);
        // adjust
        this.dnRegistration.setStorageInfo(storage);
        // initialize data node internal structure
        this.data = new FSDataset(storage, conf);
    }

    // find free port
    ServerSocket ss = (socketWriteTimeout > 0) ? ServerSocketChannel.open().socket() : new ServerSocket();
    Server.bind(ss, socAddr, 0);
    ss.setReceiveBufferSize(DEFAULT_DATA_SOCKET_SIZE);
    // adjust machine name with the actual port
    tmpPort = ss.getLocalPort();
    selfAddr = new InetSocketAddress(ss.getInetAddress().getHostAddress(), tmpPort);
    this.dnRegistration.setName(machineName + ":" + tmpPort);
    LOG.info("Opened info server at " + tmpPort);

    this.threadGroup = new ThreadGroup("dataXceiverServer");
    this.dataXceiverServer = new Daemon(threadGroup, new DataXceiverServer(ss, conf, this));
    this.threadGroup.setDaemon(true); // auto destroy when empty

    this.blockReportInterval = conf.getLong("dfs.blockreport.intervalMsec", BLOCKREPORT_INTERVAL);
    this.initialBlockReportDelay = conf.getLong("dfs.blockreport.initialDelay", BLOCKREPORT_INITIAL_DELAY)
            * 1000L;
    if (this.initialBlockReportDelay >= blockReportInterval) {
        this.initialBlockReportDelay = 0;
        LOG.info("dfs.blockreport.initialDelay is greater than " + "dfs.blockreport.intervalMsec."
                + " Setting initial delay to 0 msec:");
    }
    this.heartBeatInterval = conf.getLong("dfs.heartbeat.interval", HEARTBEAT_INTERVAL) * 1000L;

    //initialize periodic block scanner
    String reason = null;
    if (conf.getInt("dfs.datanode.scan.period.hours", 0) < 0) {
        reason = "verification is turned off by configuration";
    } else if (!(data instanceof FSDataset)) {
        reason = "verifcation is supported only with FSDataset";
    }
    if (reason == null) {
        blockScanner = new DataBlockScanner(this, (FSDataset) data, conf);
    } else {
        LOG.info("Periodic Block Verification is disabled because " + reason + ".");
    }

    //create a servlet to serve full-file content
    InetSocketAddress infoSocAddr = NetUtils
            .createSocketAddr(conf.get("dfs.datanode.http.address", "0.0.0.0:50075"));
    String infoHost = infoSocAddr.getHostName();
    int tmpInfoPort = infoSocAddr.getPort();
    this.infoServer = new HttpServer("datanode", infoHost, tmpInfoPort, tmpInfoPort == 0, conf);
    if (conf.getBoolean("dfs.https.enable", false)) {
        boolean needClientAuth = conf.getBoolean(DFSConfigKeys.DFS_CLIENT_HTTPS_NEED_AUTH_KEY,
                DFSConfigKeys.DFS_CLIENT_HTTPS_NEED_AUTH_DEFAULT);
        InetSocketAddress secInfoSocAddr = NetUtils
                .createSocketAddr(conf.get("dfs.datanode.https.address", infoHost + ":" + 0));
        Configuration sslConf = new HdfsConfiguration(false);
        sslConf.addResource(conf.get("dfs.https.server.keystore.resource", "ssl-server.xml"));
        this.infoServer.addSslListener(secInfoSocAddr, sslConf, needClientAuth);
    }
    this.infoServer.addInternalServlet(null, "/streamFile/*", StreamFile.class);
    this.infoServer.addInternalServlet(null, "/getFileChecksum/*", FileChecksumServlets.GetServlet.class);
    this.infoServer.setAttribute("datanode.blockScanner", blockScanner);
    this.infoServer.setAttribute("datanode.conf", conf);
    this.infoServer.addServlet(null, "/blockScannerReport", DataBlockScanner.Servlet.class);
    this.infoServer.start();
    // adjust info port
    this.dnRegistration.setInfoPort(this.infoServer.getPort());
    myMetrics = new DataNodeMetrics(conf, dnRegistration.getName());

    // set service-level authorization security policy
    if (conf.getBoolean(ServiceAuthorizationManager.SERVICE_AUTHORIZATION_CONFIG, false)) {
        ServiceAuthorizationManager.refresh(conf, new HDFSPolicyProvider());
    }

    //init ipc server
    InetSocketAddress ipcAddr = NetUtils.createSocketAddr(conf.get("dfs.datanode.ipc.address"));
    ipcServer = RPC.getServer(DataNode.class, this, ipcAddr.getHostName(), ipcAddr.getPort(),
            conf.getInt("dfs.datanode.handler.count", 3), false, conf);
    ipcServer.start();
    dnRegistration.setIpcPort(ipcServer.getListenerAddress().getPort());

    LOG.info("dnRegistration = " + dnRegistration);

    plugins = conf.getInstances("dfs.datanode.plugins", ServicePlugin.class);
    for (ServicePlugin p : plugins) {
        try {
            p.start(this);
            LOG.info("Started plug-in " + p);
        } catch (Throwable t) {
            LOG.warn("ServicePlugin " + p + " could not be started", t);
        }
    }
}

From source file:com.github.hrpc.rpc.Server.java

public static void bind(ServerSocket socket, InetSocketAddress address, int backlog, Option conf,
        String rangeConf) throws IOException {
    try {/*from w  w  w . ja v a2 s. c o  m*/
        IntegerRanges range = null;
        if (rangeConf != null) {
            range = conf.getRange(rangeConf, "");
        }
        if (range == null || range.isEmpty() || (address.getPort() != 0)) {
            socket.bind(address, backlog);
        } else {
            for (Integer port : range) {
                if (socket.isBound())
                    break;
                try {
                    InetSocketAddress temp = new InetSocketAddress(address.getAddress(), port);
                    socket.bind(temp, backlog);
                } catch (BindException e) {
                    //Ignored
                }
            }
            if (!socket.isBound()) {
                throw new BindException("Could not find a free port in " + range);
            }
        }
    } catch (SocketException e) {
        throw NetUtils.wrapException(null, 0, address.getHostName(), address.getPort(), e);
    }
}

From source file:com.chinamobile.bcbsp.workermanager.WorkerManager.java

/**
 * Initialize workerManager./* www  . j a v  a  2 s.co  m*/
 */
@SuppressWarnings("static-access")
public synchronized void initialize() throws IOException {
    if (this.conf.get(Constants.BC_BSP_WORKERMANAGER_RPC_HOST) != null) {
        this.workerManagerName = conf.get(Constants.BC_BSP_WORKERMANAGER_RPC_HOST);
    }
    if (this.workerManagerName == null) {
        this.workerManagerName = DNS.getDefaultHost(conf.get("bsp.dns.interface", "default"),
                conf.get("bsp.dns.nameserver", "default"));
    }
    // check local disk
    checkLocalDirs(conf.getStrings(Constants.BC_BSP_LOCAL_DIRECTORY));
    deleteLocalFiles("workerManager");
    this.workerFaultList = new ArrayList<Fault>();
    this.reportStaffStatusList = new ArrayList<StaffStatus>();
    this.runningStaffs = new ConcurrentHashMap<StaffAttemptID, StaffInProgress>();
    this.finishedStaffs = new ConcurrentHashMap<StaffAttemptID, StaffInProgress>();
    this.runningJobs = new ConcurrentHashMap<BSPJobID, RunningJob>();
    this.finishedJobs = new ConcurrentHashMap<BSPJobID, RunningJob>();
    this.runningJobtoWorkerAgent = new ConcurrentHashMap<BSPJobID, WorkerAgentForJob>();
    this.reprotStaffsMap = new ConcurrentHashMap<StaffAttemptID, StaffInProgress>();
    this.conf.set(Constants.BC_BSP_WORKERAGENT_HOST, this.workerManagerName);
    this.conf.set(Constants.BC_BSP_WORKERMANAGER_RPC_HOST, this.workerManagerName);
    this.maxStaffsCount = conf.getInt(Constants.BC_BSP_WORKERMANAGER_MAXSTAFFS, 1);
    WorkerManager.HEART_BEAT_INTERVAL = conf.getInt(Constants.HEART_BEAT_INTERVAL, 1000);
    LOG.info("The max number of staffs is : " + this.maxStaffsCount);
    int rpcPort = -1;
    String rpcAddr = null;
    if (!this.initialized) {
        rpcAddr = conf.get(Constants.BC_BSP_WORKERMANAGER_RPC_HOST,
                Constants.DEFAULT_BC_BSP_WORKERMANAGER_RPC_HOST);
        rpcPort = conf.getInt(Constants.BC_BSP_WORKERMANAGER_RPC_PORT, 5000);
        if (-1 == rpcPort || null == rpcAddr) {
            throw new IllegalArgumentException("Error rpc address " + rpcAddr + " port" + rpcPort);
        }
        this.workerServer = RPC.getServer(this, rpcAddr, rpcPort, conf);
        this.workerServer.start();
        this.rpcServer = rpcAddr + ":" + rpcPort;
        LOG.info("Worker rpc server --> " + rpcServer);
    }
    String address = conf.get(Constants.BC_BSP_WORKERMANAGER_REPORT_ADDRESS);
    InetSocketAddress socAddr = NetUtils.createSocketAddr(address);
    String bindAddress = socAddr.getHostName();
    int tmpPort = socAddr.getPort();
    // RPC initialization
    this.staffReportServer = RPC.getServer(this, bindAddress, tmpPort, 10, false, this.conf);
    this.staffReportServer.start();
    // http server
    InetAddress addr = InetAddress.getLocalHost();
    String ipSlave = addr.getHostAddress().toString();
    winfoPort = conf.getInt("bcbsp.http.winfoserver.port", 40027);
    winfoServer = new HttpServer("bcbsp", ipSlave, winfoPort, true, conf);
    winfoServer.setAttribute("WorkerManager", this);
    LOG.info("prot: 40027");
    LOG.info("ljn test : controllerClient before start ");
    winfoServer.start();
    LOG.info("server has started");
    LOG.info("ljn test : controllerClient before register ");
    // get the assigned address
    this.staffReportAddress = staffReportServer.getListenerAddress();
    LOG.info("WorkerManager up at: " + this.staffReportAddress);
    DistributedCache.purgeCache(this.conf);
    LOG.info("ljn test : DistributedCache ");
    LOG.info("ljn test : bspControllerAddr " + bspControllerAddr);
    LOG.info("ljn test : BSPRPCProtocolVersion.versionID " + BSPRPCProtocolVersion.versionID);
    // establish the communication link to bsp master
    try {
        this.controllerClient = (ControllerProtocol) RPC.waitForProxy(ControllerProtocol.class,
                BSPRPCProtocolVersion.versionID, bspControllerAddr, conf);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    LOG.info("ljn test : controllerClient controllerClient start ");
    // establish the communication link to standby bsp master
    if ("ha".equals(conf.get(Constants.BC_BSP_HA_FLAG, ""))) {
        this.standbyControllerClient = (ControllerProtocol) RPC.waitForProxy(ControllerProtocol.class,
                BSPRPCProtocolVersion.versionID, this.standbyControllerAddr, conf);
    }
    LOG.info("bspControllerAddr = " + bspControllerAddr + " standbyControllerAddr = " + standbyControllerAddr);
    LOG.info("ljn test : controllerClient before register ");
    // enroll in bsp controller
    if (-1 == rpcPort || null == rpcAddr) {
        throw new IllegalArgumentException("Error rpc address " + rpcAddr + " port" + rpcPort);
    }
    LOG.info("ljn test : controllerClient before lsManager.start ");
    this.lsManager.start();
    LOG.info("ljn test : controllerClient before lsManager.start  over");
    workerMangerStatus = new WorkerManagerStatus(workerManagerName, cloneAndResetRunningStaffStatuses(),
            maxStaffsCount, currentStaffsCount, finishedStaffsCount, failures, this.rpcServer, workerFaultList);
    this.workerMangerStatus.setHost(bindAddress);
    this.workerMangerStatus.setHttpPort(this.staffReportAddress.toString());
    this.workerMangerStatus.setLocalIp(ipSlave);
    LOG.info("ljn test : controllerClient before register ");
    if (!this.controllerClient.register(workerMangerStatus)) {
        LOG.error("There is a problem in establishing communication" + " link with BSPController");
        throw new IOException("There is a problem in establishing" + " communication link with BSPController.");
    } else {
        LOG.info("have registed to bsp master");
    }
    if ("ha".equals(conf.get(Constants.BC_BSP_HA_FLAG, ""))) {
        if (!this.standbyControllerClient.register(workerMangerStatus)) {
            LOG.error("There is a problem in establishing communication" + " link with BSPController");
            throw new IOException(
                    "There is a problem in establishing" + " communication link with BSPController.");
        } else {
            LOG.info("have registed to standby bsp master");
        }
    }
    this.running = true;
    this.initialized = true;
    LOG.info("ljn test : controllerClient after register ");
}

From source file:orca.ektorp.client.ContextualSSLSocketFactory.java

/**
 * @since 4.1//from   w w  w  .  ja v a  2  s  . com
 * @param socket socket
 * @param remoteAddress remote address
 * @param localAddress local address
 * @param params HTTP params
 * @throws IOException in case of IO error
 * @throws UnknownHostException in case of unknonwn host
 * @throws ConnectTimeoutException in case of connect timeout
 * @return returns the socket
 */
public Socket connectSocket(final Socket socket, final InetSocketAddress remoteAddress,
        final InetSocketAddress localAddress, final HttpParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    if (remoteAddress == null) {
        throw new IllegalArgumentException("Remote address may not be null");
    }
    if (params == null) {
        throw new IllegalArgumentException("HTTP parameters may not be null");
    }
    //Here!
    Socket sock = socket != null ? socket : this.socketfactory.createSocket();
    if (localAddress != null) {
        sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
        sock.bind(localAddress);
    }

    int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    int soTimeout = HttpConnectionParams.getSoTimeout(params);

    try {
        sock.setSoTimeout(soTimeout);
        sock.connect(remoteAddress, connTimeout);
    } catch (SocketTimeoutException ex) {
        throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out");
    }

    String hostname;
    if (remoteAddress instanceof HttpInetSocketAddress) {
        hostname = ((HttpInetSocketAddress) remoteAddress).getHttpHost().getHostName();
    } else {
        hostname = remoteAddress.getHostName();
    }

    SSLSocket sslsock;
    // Setup SSL layering if necessary
    if (sock instanceof SSLSocket) {
        sslsock = (SSLSocket) sock;
    } else {
        int port = remoteAddress.getPort();
        sslsock = (SSLSocket) this.socketfactory.createSocket(sock, hostname, port, true);
        prepareSocket(sslsock);
    }
    if (this.hostnameVerifier != null) {
        try {
            this.hostnameVerifier.verify(hostname, sslsock);
            // verifyHostName() didn't blowup - good!
        } catch (IOException iox) {
            // close the socket before re-throwing the exception
            try {
                sslsock.close();
            } catch (Exception x) {
                /*ignore*/ }
            throw iox;
        }
    }
    return sslsock;
}

From source file:org.apache.hadoop.hdfs.server.datanode.DataNode.java

/**
 * This method starts the data node with the specified conf.
 * /*  ww w .  j  av a2s  .  co m*/
 * @param conf - the configuration
 *  if conf's CONFIG_PROPERTY_SIMULATED property is set
 *  then a simulated storage based data node is created.
 * 
 * @param dataDirs - only for a non-simulated storage data node
 * @throws IOException
 * @throws MalformedObjectNameException 
 * @throws MBeanRegistrationException 
 * @throws InstanceAlreadyExistsException 
 */
void startDataNode(Configuration conf, AbstractList<File> dataDirs, SecureResources resources)
        throws IOException {
    if (UserGroupInformation.isSecurityEnabled() && resources == null)
        throw new RuntimeException("Cannot start secure cluster without " + "privileged resources.");

    this.secureResources = resources;
    // use configured nameserver & interface to get local hostname
    if (conf.get("slave.host.name") != null) {
        machineName = conf.get("slave.host.name");
    }
    if (machineName == null) {
        machineName = DNS.getDefaultHost(conf.get("dfs.datanode.dns.interface", "default"),
                conf.get("dfs.datanode.dns.nameserver", "default"));
    }
    InetSocketAddress nameNodeAddr = NameNode.getServiceAddress(conf, true);

    this.socketTimeout = conf.getInt("dfs.socket.timeout", HdfsConstants.READ_TIMEOUT);
    this.socketWriteTimeout = conf.getInt("dfs.datanode.socket.write.timeout", HdfsConstants.WRITE_TIMEOUT);
    /* Based on results on different platforms, we might need set the default 
     * to false on some of them. */
    this.transferToAllowed = conf.getBoolean("dfs.datanode.transferTo.allowed", true);
    this.writePacketSize = conf.getInt("dfs.write.packet.size", 64 * 1024);

    InetSocketAddress socAddr = DataNode.getStreamingAddr(conf);
    int tmpPort = socAddr.getPort();
    storage = new DataStorage();
    // construct registration
    this.dnRegistration = new DatanodeRegistration(machineName + ":" + tmpPort);

    // connect to name node
    this.namenode = (DatanodeProtocol) RPC.waitForProxy(DatanodeProtocol.class, DatanodeProtocol.versionID,
            nameNodeAddr, conf);
    // get version and id info from the name-node
    NamespaceInfo nsInfo = handshake();
    StartupOption startOpt = getStartupOption(conf);
    assert startOpt != null : "Startup option must be set.";

    boolean simulatedFSDataset = conf.getBoolean("dfs.datanode.simulateddatastorage", false);
    if (simulatedFSDataset) {
        setNewStorageID(dnRegistration);
        dnRegistration.storageInfo.layoutVersion = FSConstants.LAYOUT_VERSION;
        dnRegistration.storageInfo.namespaceID = nsInfo.namespaceID;
        // it would have been better to pass storage as a parameter to
        // constructor below - need to augment ReflectionUtils used below.
        conf.set("StorageId", dnRegistration.getStorageID());
        try {
            //Equivalent of following (can't do because Simulated is in test dir)
            //  this.data = new SimulatedFSDataset(conf);
            this.data = (FSDatasetInterface) ReflectionUtils.newInstance(
                    Class.forName("org.apache.hadoop.hdfs.server.datanode.SimulatedFSDataset"), conf);
        } catch (ClassNotFoundException e) {
            throw new IOException(StringUtils.stringifyException(e));
        }
    } else { // real storage
        // read storage info, lock data dirs and transition fs state if necessary
        storage.recoverTransitionRead(nsInfo, dataDirs, startOpt);
        // adjust
        this.dnRegistration.setStorageInfo(storage);
        // initialize data node internal structure
        this.data = new FSDataset(storage, conf);
    }

    // register datanode MXBean
    this.registerMXBean(conf); // register the MXBean for DataNode

    // Allow configuration to delay block reports to find bugs
    artificialBlockReceivedDelay = conf.getInt("dfs.datanode.artificialBlockReceivedDelay", 0);

    // find free port or use privileged port provide
    ServerSocket ss;
    if (secureResources == null) {
        ss = (socketWriteTimeout > 0) ? ServerSocketChannel.open().socket() : new ServerSocket();
        Server.bind(ss, socAddr, 0);
    } else {
        ss = resources.getStreamingSocket();
    }
    ss.setReceiveBufferSize(DEFAULT_DATA_SOCKET_SIZE);
    // adjust machine name with the actual port
    tmpPort = ss.getLocalPort();
    selfAddr = new InetSocketAddress(ss.getInetAddress().getHostAddress(), tmpPort);
    this.dnRegistration.setName(machineName + ":" + tmpPort);
    LOG.info("Opened info server at " + tmpPort);

    this.threadGroup = new ThreadGroup("dataXceiverServer");
    this.dataXceiverServer = new Daemon(threadGroup, new DataXceiverServer(ss, conf, this));
    this.threadGroup.setDaemon(true); // auto destroy when empty

    this.blockReportInterval = conf.getLong("dfs.blockreport.intervalMsec", BLOCKREPORT_INTERVAL);
    this.initialBlockReportDelay = conf.getLong("dfs.blockreport.initialDelay", BLOCKREPORT_INITIAL_DELAY)
            * 1000L;
    if (this.initialBlockReportDelay >= blockReportInterval) {
        this.initialBlockReportDelay = 0;
        LOG.info("dfs.blockreport.initialDelay is greater than " + "dfs.blockreport.intervalMsec."
                + " Setting initial delay to 0 msec:");
    }
    this.heartBeatInterval = conf.getLong("dfs.heartbeat.interval", HEARTBEAT_INTERVAL) * 1000L;
    DataNode.nameNodeAddr = nameNodeAddr;

    //initialize periodic block scanner
    String reason = null;
    if (conf.getInt("dfs.datanode.scan.period.hours", 0) < 0) {
        reason = "verification is turned off by configuration";
    } else if (!(data instanceof FSDataset)) {
        reason = "verifcation is supported only with FSDataset";
    }
    if (reason == null) {
        blockScanner = new DataBlockScanner(this, (FSDataset) data, conf);
    } else {
        LOG.info("Periodic Block Verification is disabled because " + reason + ".");
    }

    //create a servlet to serve full-file content
    InetSocketAddress infoSocAddr = DataNode.getInfoAddr(conf);
    String infoHost = infoSocAddr.getHostName();
    int tmpInfoPort = infoSocAddr.getPort();
    this.infoServer = (secureResources == null)
            ? new HttpServer("datanode", infoHost, tmpInfoPort, tmpInfoPort == 0, conf,
                    SecurityUtil.getAdminAcls(conf, DFSConfigKeys.DFS_ADMIN))
            : new HttpServer("datanode", infoHost, tmpInfoPort, tmpInfoPort == 0, conf,
                    SecurityUtil.getAdminAcls(conf, DFSConfigKeys.DFS_ADMIN), secureResources.getListener());
    if (conf.getBoolean("dfs.https.enable", false)) {
        boolean needClientAuth = conf.getBoolean("dfs.https.need.client.auth", false);
        InetSocketAddress secInfoSocAddr = NetUtils
                .createSocketAddr(conf.get("dfs.datanode.https.address", infoHost + ":" + 0));
        Configuration sslConf = new Configuration(false);
        sslConf.addResource(conf.get("dfs.https.server.keystore.resource", "ssl-server.xml"));
        this.infoServer.addSslListener(secInfoSocAddr, sslConf, needClientAuth);
    }
    this.infoServer.addInternalServlet(null, "/streamFile/*", StreamFile.class);
    this.infoServer.addInternalServlet(null, "/getFileChecksum/*", FileChecksumServlets.GetServlet.class);

    this.infoServer.setAttribute("datanode", this);
    this.infoServer.setAttribute("datanode.blockScanner", blockScanner);
    this.infoServer.setAttribute(JspHelper.CURRENT_CONF, conf);
    this.infoServer.addServlet(null, "/blockScannerReport", DataBlockScanner.Servlet.class);

    if (WebHdfsFileSystem.isEnabled(conf, LOG)) {
        infoServer.addJerseyResourcePackage(
                DatanodeWebHdfsMethods.class.getPackage().getName() + ";" + Param.class.getPackage().getName(),
                WebHdfsFileSystem.PATH_PREFIX + "/*");
    }
    this.infoServer.start();
    // adjust info port
    this.dnRegistration.setInfoPort(this.infoServer.getPort());
    myMetrics = DataNodeInstrumentation.create(conf, dnRegistration.getStorageID());

    // set service-level authorization security policy
    if (conf.getBoolean(ServiceAuthorizationManager.SERVICE_AUTHORIZATION_CONFIG, false)) {
        ServiceAuthorizationManager.refresh(conf, new HDFSPolicyProvider());
    }

    // BlockTokenSecretManager is created here, but it shouldn't be
    // used until it is initialized in register().
    this.blockTokenSecretManager = new BlockTokenSecretManager(false, 0, 0);
    //init ipc server
    InetSocketAddress ipcAddr = NetUtils.createSocketAddr(conf.get("dfs.datanode.ipc.address"));
    ipcServer = RPC.getServer(this, ipcAddr.getHostName(), ipcAddr.getPort(),
            conf.getInt("dfs.datanode.handler.count", 3), false, conf, blockTokenSecretManager);
    dnRegistration.setIpcPort(ipcServer.getListenerAddress().getPort());

    LOG.info("dnRegistration = " + dnRegistration);
}

From source file:org.elasticsearch.test.ElasticsearchIntegrationTest.java

protected HttpRequestBuilder httpClient() {
    final NodesInfoResponse nodeInfos = client().admin().cluster().prepareNodesInfo().get();
    final NodeInfo[] nodes = nodeInfos.getNodes();
    assertTrue(nodes.length > 0);/*from  w ww .  ja v a 2s  .c  o m*/
    TransportAddress publishAddress = randomFrom(nodes).getHttp().address().publishAddress();
    assertEquals(1, publishAddress.uniqueAddressTypeId());
    InetSocketAddress address = ((InetSocketTransportAddress) publishAddress).address();
    return new HttpRequestBuilder(HttpClients.createDefault()).host(address.getHostName())
            .port(address.getPort());
}

From source file:nz.dataview.websyncclientgui.WebSYNCClientGUIView.java

/**
 * try to detect if a proxy exists, and update the UI
 * /*from www.  j  av  a 2s .  co  m*/
 * @return
 */
private void detectProxy() {

    try {
        proxyDetectedLabel.setText("");
        List l = ProxySelector.getDefault().select(new URI(knURLField.getText()));

        for (Iterator iter = l.iterator(); iter.hasNext();) {
            Proxy proxy = (Proxy) iter.next();
            if ("DIRECT".equals(proxy.type().toString())) {
                proxyEnabled = false;
                useProxyField.setSelected(proxyEnabled);
                proxyFieldsUpdate(proxyEnabled);
            } else {
                InetSocketAddress addr = (InetSocketAddress) proxy.address();
                if (addr != null) {
                    // if we have a proxy set the correct fields and state of UI
                    proxyEnabled = true;
                    useProxyField.setSelected(proxyEnabled);
                    proxyHostField.setText(addr.getHostName());
                    proxyPortField.setText(Integer.toString(addr.getPort()));
                    proxyFieldsUpdate(proxyEnabled);

                }
            }
            String text = (String) "Proxy settings detected and updated";
            proxyDetectedLabel.setText(text);
        }
    } catch (Exception e) {
        showErrorDialog("Detect Proxy", "Problem in detecting proxy, please set proxy settings manually");
    }

}

From source file:de.dal33t.powerfolder.clientserver.ServerClient.java

/**
 * @return the string representing the server address
 *///from w ww .  j a  v a  2s  .c o  m
public String getServerString() {
    String addrStr;
    if (server != null) {
        if (server.isMySelf()) {
            addrStr = "myself";
        } else {
            InetSocketAddress addr = server.getReconnectAddress();
            if (addr != null) {
                if (addr.getAddress() != null) {
                    addrStr = NetworkUtil.getHostAddressNoResolve(addr.getAddress());
                } else {
                    addrStr = addr.getHostName();
                }
            } else {
                addrStr = "";
            }

            if (addr != null && addr.getPort() != ConnectionListener.DEFAULT_PORT) {
                addrStr += ":" + addr.getPort();
            }
        }
    } else {
        addrStr = "";
    }
    if (hasWebURL()) {
        return getWebURL();
    } else if (StringUtils.isNotBlank(addrStr)) {
        return "pf://" + addrStr;
    } else {
        return "n/a";
    }

}