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:org.apache.tajo.cli.tsql.TestTajoCli.java

License:asdf

@Test
public void testShowMasters() throws Exception {
    TajoConf tajoConf = TpchTestBase.getInstance().getTestingCluster().getConfiguration();
    setVar(tajoCli, SessionVars.CLI_FORMATTER_CLASS, TajoCliOutputTestFormatter.class.getName());

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    TajoCli tajoCli = new TajoCli(tajoConf, new String[] {}, null, System.in, out, err);
    tajoCli.executeMetaCommand("\\admin -showmasters");

    String consoleResult = new String(out.toByteArray());

    InetSocketAddress masterAddress = tajoCli.getContext().getConf()
            .getSocketAddrVar(TajoConf.ConfVars.TAJO_MASTER_UMBILICAL_RPC_ADDRESS);

    tajoCli.close();/* w w  w.  j av a2  s.  c  om*/
    assertEquals(consoleResult, masterAddress.getHostName() + "\n");
}

From source file:org.openflamingo.remote.thrift.thriftfs.NamenodePlugin.java

@Override
public void start(Object service) {
    this.namenode = (NameNode) service;
    try {/*from  w ww .  j a  v  a  2 s.  c  o m*/
        InetSocketAddress address = NetUtils
                .createSocketAddr(conf.get(THRIFT_ADDRESS_PROPERTY, DEFAULT_THRIFT_ADDRESS));

        this.thriftServer = new ThriftPluginServer(address, new ProcessorFactory());
        thriftServer.setConf(conf);
        thriftServer.start();
        // The port may have been 0, so we update it.
        conf.set(THRIFT_ADDRESS_PROPERTY, address.getHostName() + ":" + thriftServer.getPort());
    } catch (Exception e) {
        throw new RuntimeException("Cannot start Thrift namenode plug-in", e);
    }
}

From source file:org.eclipse.mylyn.internal.commons.repositories.http.core.PollingSslProtocolSocketFactory.java

public Socket connectSocket(Socket sock, InetSocketAddress remoteAddress, InetSocketAddress localAddress,
        HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
    Assert.isNotNull(params);//from w  ww . jav a  2  s .  c  o m
    final Socket socket = (sock != null) ? sock : createSocket(params);

    if (localAddress != null) {
        socket.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
        socket.bind(localAddress);
    }

    int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    socket.connect(remoteAddress, connTimeout);

    if (socket instanceof SSLSocket) {
        return socket;
    } else {
        return getSslSupport(params).getSocketFactory().createSocket(socket, remoteAddress.getHostName(),
                remoteAddress.getPort(), true);
    }
}

From source file:com.servoy.extensions.plugins.http.HttpClient.java

public HttpClient(IClientPluginAccess plugin) {
    client = new DefaultHttpClient();
    client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, Boolean.TRUE);
    client.getAuthSchemes().register(AuthPolicy.NTLM, new NTLMSchemeFactory());
    client.getAuthSchemes().register(AuthPolicy.SPNEGO, new NegotiateSchemeFactory());
    this.plugin = plugin;

    try {/*  w  w w  . j  a  v  a  2  s .c  o  m*/
        final AllowedCertTrustStrategy allowedCertTrustStrategy = new AllowedCertTrustStrategy();
        SSLSocketFactory sf = new SSLSocketFactory(allowedCertTrustStrategy) {
            @Override
            public Socket connectSocket(Socket socket, InetSocketAddress remoteAddress,
                    InetSocketAddress localAddress, HttpParams params)
                    throws IOException, UnknownHostException, ConnectTimeoutException {
                if (socket instanceof SSLSocket) {
                    try {
                        Method s = socket.getClass().getMethod("setHost", String.class);
                        s.invoke(socket, remoteAddress.getHostName());
                    } catch (NoSuchMethodException ex) {
                    } catch (IllegalAccessException ex) {
                    } catch (InvocationTargetException ex) {
                    } catch (IllegalArgumentException ex) {
                    } catch (SecurityException ex) {
                    }
                }
                try {
                    return super.connectSocket(socket, remoteAddress, localAddress, params);
                } catch (SSLPeerUnverifiedException ex) {
                    X509Certificate[] lastCertificates = allowedCertTrustStrategy.getAndClearLastCertificates();
                    if (lastCertificates != null) {
                        // allow for next time
                        if (HttpClient.this.plugin.getApplicationType() == IClientPluginAccess.CLIENT
                                || HttpClient.this.plugin.getApplicationType() == IClientPluginAccess.RUNTIME) {
                            // show dialog
                            CertificateDialog dialog = new CertificateDialog(
                                    ((ISmartRuntimeWindow) HttpClient.this.plugin.getCurrentRuntimeWindow())
                                            .getWindow(),
                                    remoteAddress, lastCertificates);
                            if (dialog.shouldAccept()) {
                                allowedCertTrustStrategy.add(lastCertificates);
                                // try it again now with the new chain.
                                return super.connectSocket(socket, remoteAddress, localAddress, params);
                            }
                        } else {
                            Debug.error("Couldn't connect to " + remoteAddress
                                    + ", please make sure that the ssl certificates of that site are added to the java keystore."
                                    + "Download the keystore in the browser and update the java cacerts file in jre/lib/security: "
                                    + "keytool -import -file downloaded.crt -keystore cacerts");
                        }
                    }
                    throw ex;
                } finally {
                    // always just clear the last request.
                    allowedCertTrustStrategy.getAndClearLastCertificates();
                }

            }
        };
        Scheme https = new Scheme("https", 443, sf); //$NON-NLS-1$
        client.getConnectionManager().getSchemeRegistry().register(https);
    } catch (Exception e) {
        Debug.error("Can't register a https scheme", e); //$NON-NLS-1$
    }
}

From source file:com.eviware.soapui.impl.wsdl.monitor.jettyproxy.TunnelServlet.java

public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
    monitor.fireOnRequest(request, response);
    if (response.isCommitted())
        return;//from   w w w  .  j  a v  a  2s.  co  m

    ExtendedHttpMethod postMethod;

    // for this create ui server and port, properties.
    InetSocketAddress inetAddress = new InetSocketAddress(sslEndPoint, sslPort);
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    if (httpRequest.getMethod().equals("GET"))
        postMethod = new ExtendedGetMethod();
    else
        postMethod = new ExtendedPostMethod();

    JProxyServletWsdlMonitorMessageExchange capturedData = new JProxyServletWsdlMonitorMessageExchange(project);
    capturedData.setRequestHost(httpRequest.getRemoteHost());
    capturedData.setRequestHeader(httpRequest);
    capturedData.setTargetURL(this.prot + inetAddress.getHostName());

    CaptureInputStream capture = new CaptureInputStream(httpRequest.getInputStream());

    // copy headers
    Enumeration<?> headerNames = httpRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String hdr = (String) headerNames.nextElement();
        String lhdr = hdr.toLowerCase();

        if ("host".equals(lhdr)) {
            Enumeration<?> vals = httpRequest.getHeaders(hdr);
            while (vals.hasMoreElements()) {
                String val = (String) vals.nextElement();
                if (val.startsWith("127.0.0.1")) {
                    postMethod.addRequestHeader(hdr, sslEndPoint);
                }
            }
            continue;
        }

        Enumeration<?> vals = httpRequest.getHeaders(hdr);
        while (vals.hasMoreElements()) {
            String val = (String) vals.nextElement();
            if (val != null) {
                postMethod.addRequestHeader(hdr, val);
            }
        }

    }

    if (postMethod instanceof ExtendedPostMethod)
        ((ExtendedPostMethod) postMethod)
                .setRequestEntity(new InputStreamRequestEntity(capture, request.getContentType()));

    HostConfiguration hostConfiguration = new HostConfiguration();

    httpRequest.getProtocol();
    hostConfiguration.getParams().setParameter(SoapUIHostConfiguration.SOAPUI_SSL_CONFIG,
            settings.getString(SecurityTabForm.SSLTUNNEL_KEYSTOREPATH, "") + " "
                    + settings.getString(SecurityTabForm.SSLTUNNEL_KEYSTOREPASSWORD, ""));
    hostConfiguration.setHost(new URI(this.prot + sslEndPoint, true));

    hostConfiguration = ProxyUtils.initProxySettings(settings, httpState, hostConfiguration, prot + sslEndPoint,
            new DefaultPropertyExpansionContext(project));

    if (sslEndPoint.indexOf("/") < 0)
        postMethod.setPath("/");
    else
        postMethod.setPath(sslEndPoint.substring(sslEndPoint.indexOf("/"), sslEndPoint.length()));

    monitor.fireBeforeProxy(request, response, postMethod, hostConfiguration);

    if (settings.getBoolean(LaunchForm.SSLTUNNEL_REUSESTATE)) {
        if (httpState == null)
            httpState = new HttpState();
        HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, postMethod, httpState);
    } else {
        HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, postMethod);
    }
    capturedData.stopCapture();

    capturedData.setRequest(capture.getCapturedData());
    capturedData.setRawResponseBody(postMethod.getResponseBody());
    capturedData.setResponseHeader(postMethod);
    capturedData.setRawRequestData(getRequestToBytes(request.toString(), postMethod, capture));
    capturedData.setRawResponseData(
            getResponseToBytes(response.toString(), postMethod, capturedData.getRawResponseBody()));

    monitor.fireAfterProxy(request, response, postMethod, capturedData);

    StringToStringsMap responseHeaders = capturedData.getResponseHeaders();
    // copy headers to response
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    for (String name : responseHeaders.keySet()) {
        for (String header : responseHeaders.get(name))
            httpResponse.addHeader(name, header);

    }

    IO.copy(new ByteArrayInputStream(capturedData.getRawResponseBody()), httpResponse.getOutputStream());

    postMethod.releaseConnection();

    synchronized (this) {
        monitor.addMessageExchange(capturedData);
    }

    capturedData = null;
}

From source file:com.taobao.adfs.distributed.rpc.Server.java

/**
 * A convenience method to bind to a given address and report better exceptions if the address is not a valid host.
 * //  w ww.j ava2 s  .com
 * @param socket
 *          the socket to bind
 * @param address
 *          the address to bind to
 * @param backlog
 *          the number of connections allowed in the queue
 * @throws BindException
 *           if the address can't be bound
 * @throws UnknownHostException
 *           if the address isn't a valid host name
 * @throws IOException
 *           other random errors from bind
 */
public static void bind(ServerSocket socket, InetSocketAddress address, int backlog) throws IOException {
    try {
        socket.bind(address, backlog);
    } catch (BindException e) {
        BindException bindException = new BindException(
                "Problem binding to " + address + " : " + e.getMessage());
        bindException.initCause(e);
        throw bindException;
    } catch (SocketException e) {
        // If they try to bind to a different host's address, give a better
        // error message.
        if ("Unresolved address".equals(e.getMessage())) {
            throw new UnknownHostException("Invalid hostname for server: " + address.getHostName());
        } else {
            throw e;
        }
    }
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.RMHAProtocolService.java

protected void startHAAdminServer() throws Exception {
    InetSocketAddress haAdminServiceAddress = conf.getSocketAddr(YarnConfiguration.RM_HA_ADMIN_ADDRESS,
            YarnConfiguration.DEFAULT_RM_HA_ADMIN_ADDRESS, YarnConfiguration.DEFAULT_RM_HA_ADMIN_PORT);

    RPC.setProtocolEngine(conf, HAServiceProtocolPB.class, ProtobufRpcEngine.class);

    HAServiceProtocolServerSideTranslatorPB haServiceProtocolXlator = new HAServiceProtocolServerSideTranslatorPB(
            this);
    BlockingService haPbService = HAServiceProtocolProtos.HAServiceProtocolService
            .newReflectiveBlockingService(haServiceProtocolXlator);

    WritableRpcEngine.ensureInitialized();

    String bindHost = haAdminServiceAddress.getHostName();

    int serviceHandlerCount = conf.getInt(YarnConfiguration.RM_HA_ADMIN_CLIENT_THREAD_COUNT,
            YarnConfiguration.DEFAULT_RM_HA_ADMIN_CLIENT_THREAD_COUNT);

    haAdminServer = new RPC.Builder(conf).setProtocol(HAServiceProtocolPB.class).setInstance(haPbService)
            .setBindAddress(bindHost).setPort(haAdminServiceAddress.getPort())
            .setNumHandlers(serviceHandlerCount).setVerbose(false).build();

    // Enable service authorization?
    if (conf.getBoolean(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION, false)) {
        haAdminServer.refreshServiceAcl(conf, new RMPolicyProvider());
    }//from  ww w  . j av  a  2  s  . c  o m

    haAdminServer.start();
    conf.updateConnectAddr(YarnConfiguration.RM_HA_ADMIN_ADDRESS, haAdminServer.getListenerAddress());
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.TestRMHA.java

private void checkActiveRMWebServices() throws JSONException {

    // Validate web-service
    Client webServiceClient = Client.create(new DefaultClientConfig());
    InetSocketAddress rmWebappAddr = NetUtils.getConnectAddress(rm.getWebapp().getListenerAddress());
    String webappURL = "http://" + rmWebappAddr.getHostName() + ":" + rmWebappAddr.getPort();
    WebResource webResource = webServiceClient.resource(webappURL);
    String path = app.getApplicationId().toString();

    ClientResponse response = webResource.path("ws").path("v1").path("cluster").path("apps").path(path)
            .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
    assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
    JSONObject json = response.getEntity(JSONObject.class);

    assertEquals("incorrect number of elements", 1, json.length());
    JSONObject appJson = json.getJSONObject("app");
    assertEquals("ACCEPTED", appJson.getString("state"));
    // Other stuff is verified in the regular web-services related tests
}

From source file:org.apache.hadoop.dfs.NameNode.java

/**
 * Initialize the server//from  w  w w .  ja  v a2  s .  c  o m
 * 
 * @param address hostname:port to bind to
 * @param conf the configuration
 */
private void initialize(String address, Configuration conf) throws IOException {
    InetSocketAddress socAddr = NameNode.getAddress(address);
    this.handlerCount = conf.getInt("dfs.namenode.handler.count", 10);
    this.server = RPC.getServer(this, socAddr.getHostName(), socAddr.getPort(), handlerCount, false, conf);

    // The rpc-server port can be ephemeral... ensure we have the correct info
    this.nameNodeAddress = this.server.getListenerAddress();
    FileSystem.setDefaultUri(conf, getUri(nameNodeAddress));
    LOG.info("Namenode up at: " + this.nameNodeAddress);

    myMetrics = new NameNodeMetrics(conf, this);

    this.namesystem = new FSNamesystem(this, conf);
    this.server.start(); //start RPC server   

    this.emptier = new Thread(new Trash(conf).getEmptier(), "Trash Emptier");
    this.emptier.setDaemon(true);
    this.emptier.start();
}

From source file:org.apache.hadoop.thriftfs.NamenodePlugin.java

@Override
public void start(Object service) {
    this.namenode = (NameNode) service;
    try {/*from   w w w.j a  va  2 s . c o  m*/
        InetSocketAddress address = NetUtils
                .createSocketAddr(conf.get(THRIFT_ADDRESS_PROPERTY, DEFAULT_THRIFT_ADDRESS));

        this.thriftServer = new ThriftPluginServer(address, new ProcessorFactory());
        thriftServer.setConf(conf);
        thriftServer.start();
        // The port may have been 0, so we update it.
        conf.set(THRIFT_ADDRESS_PROPERTY, address.getHostName() + ":" + thriftServer.getPort());
    } catch (java.io.IOException ioe) {
        throw new RuntimeException("Cannot start Thrift namenode plug-in", ioe);
    }
}