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.hadoop.mapreduce.v2.app.job.impl.TaskAttemptImpl.java

private static void sendJHStartEventForAssignedFailTask(TaskAttemptImpl taskAttempt) {
    if (null == taskAttempt.container) {
        return;//from   w  ww .  j  a v a  2 s  .c  o m
    }
    taskAttempt.launchTime = taskAttempt.clock.getTime();

    InetSocketAddress nodeHttpInetAddr = NetUtils.createSocketAddr(taskAttempt.container.getNodeHttpAddress());
    taskAttempt.trackerName = nodeHttpInetAddr.getHostName();
    taskAttempt.httpPort = nodeHttpInetAddr.getPort();
    taskAttempt.sendLaunchedEvents();
}

From source file:com.cloudbees.jenkins.plugins.bitbucket.client.BitbucketCloudApiClient.java

private void setClientProxyParams(String host, HttpClientBuilder builder) {
    Jenkins jenkins = Jenkins.getInstance();
    ProxyConfiguration proxyConfig = null;
    if (jenkins != null) {
        proxyConfig = jenkins.proxy;//w ww  .jav a  2  s. c o m
    }

    Proxy proxy = Proxy.NO_PROXY;
    if (proxyConfig != null) {
        proxy = proxyConfig.createProxy(host);
    }

    if (proxy.type() != Proxy.Type.DIRECT) {
        final InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();
        LOGGER.fine("Jenkins proxy: " + proxy.address());
        builder.setProxy(new HttpHost(proxyAddress.getHostName(), proxyAddress.getPort()));
        String username = proxyConfig.getUserName();
        String password = proxyConfig.getPassword();
        if (username != null && !"".equals(username.trim())) {
            LOGGER.fine("Using proxy authentication (user=" + username + ")");
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(username, password));
            AuthCache authCache = new BasicAuthCache();
            authCache.put(HttpHost.create(proxyAddress.getHostName()), new BasicScheme());
            context = HttpClientContext.create();
            context.setCredentialsProvider(credentialsProvider);
            context.setAuthCache(authCache);
        }
    }
}

From source file:org.apache.hadoop.gateway.GatewayServer.java

private synchronized void start() throws Exception {

    // Create the global context handler.
    contexts = new ContextHandlerCollection();
    // A map to keep track of current deployments by cluster name.
    deployments = new ConcurrentHashMap<String, WebAppContext>();

    // Determine the socket address and check availability.
    InetSocketAddress address = config.getGatewayAddress();
    checkAddressAvailability(address);/*from  w ww.  j ava  2s  .  com*/

    // Start Jetty.
    if (config.isSSLEnabled()) {
        jetty = new Server();
    } else {
        jetty = new Server(address);
    }
    if (config.isSSLEnabled()) {
        SSLService ssl = services.getService("SSLService");
        String keystoreFileName = config.getGatewaySecurityDir() + File.separatorChar + "keystores"
                + File.separatorChar + "gateway.jks";
        Connector connector = (Connector) ssl.buildSSlConnector(keystoreFileName);
        connector.setHost(address.getHostName());
        connector.setPort(address.getPort());
        jetty.addConnector(connector);
    }
    jetty.setHandler(contexts);
    try {
        jetty.start();
    } catch (IOException e) {
        log.failedToStartGateway(e);
        throw e;
    }

    // Create a dir/file based cluster topology provider.
    File topologiesDir = calculateAbsoluteTopologiesDir();
    monitor = new FileTopologyProvider(topologiesDir);
    monitor.addTopologyChangeListener(listener);

    // Load the current topologies.
    log.loadingTopologiesFromDirectory(topologiesDir.getAbsolutePath());
    monitor.reloadTopologies();

    // Start the topology monitor.
    log.monitoringTopologyChangesInDirectory(topologiesDir.getAbsolutePath());
    monitor.startMonitor();
}

From source file:eu.operando.operandoapp.OperandoProxyStatus.java

private void updateStatusView() {
    OperandoProxyStatus proxyStatus = OperandoProxyStatus.STOPPED;
    OperandoProxyLink proxyLink = OperandoProxyLink.INVALID;
    boolean isProxyRunning = MainUtil.isServiceRunning(mainContext.getContext(), ProxyService.class);
    boolean isProxyPaused = MainUtil.isProxyPaused(mainContext);
    if (isProxyRunning) {
        if (isProxyPaused) {
            proxyStatus = OperandoProxyStatus.PAUSED;
        } else {// w  ww  .  j av a 2  s .  c  o  m
            proxyStatus = OperandoProxyStatus.ACTIVE;
        }
    }
    try {
        Proxy proxy = APL.getCurrentHttpProxyConfiguration();
        InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();
        if (proxyAddress != null) {
            //TODO: THIS SHOULD BE DYNAMIC
            String proxyHost = proxyAddress.getHostName();
            int proxyPort = proxyAddress.getPort();

            if (proxyHost.equals("127.0.0.1") && proxyPort == 8899) {
                proxyLink = OperandoProxyLink.VALID;
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    String info = "";
    try {
        InputStream is = getResources().openRawResource(R.raw.info_template);
        info = IOUtils.toString(is);
        IOUtils.closeQuietly(is);
    } catch (IOException e) {
        e.printStackTrace();
    }
    info = info.replace("@@status@@", proxyStatus.name());
    info = info.replace("@@link@@", proxyLink.name());
    webView.loadDataWithBaseURL("", info, "text/html", "UTF-8", "");
    webView.setBackgroundColor(Color.TRANSPARENT); //TRANSPARENT
}

From source file:com.streamsets.datacollector.credential.cyberark.TestWebServicesFetcher.java

protected Server createServer(int port, boolean serverSsl, boolean clientSsl) {
    Server server = new Server();
    if (!serverSsl) {
        InetSocketAddress addr = new InetSocketAddress("localhost", port);
        ServerConnector connector = new ServerConnector(server);
        connector.setHost(addr.getHostName());
        connector.setPort(addr.getPort());
        server.setConnectors(new Connector[] { connector });
    } else {//from   w w w .jav a  2 s .c  o  m
        SslContextFactory sslContextFactory = createSslContextFactory(clientSsl);
        ServerConnector httpsConnector = new ServerConnector(server,
                new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory());
        httpsConnector.setPort(port);
        httpsConnector.setHost("localhost");
        server.setConnectors(new Connector[] { httpsConnector });
    }
    return server;
}

From source file:jp.ne.sakura.kkkon.java.net.inetaddress.testapp.android.NetworkConnectionCheckerTestApp.java

/** Called when the activity is first created. */
@Override/*from www .  jav a 2  s .  c  o m*/
public void onCreate(Bundle savedInstanceState) {
    final Context context = this.getApplicationContext();

    {
        NetworkConnectionChecker.initialize();
    }

    super.onCreate(savedInstanceState);

    /* Create a TextView and set its content.
     * the text is retrieved by calling a native
     * function.
     */
    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);

    TextView tv = new TextView(this);
    tv.setText("reachable=");
    layout.addView(tv);
    this.textView = tv;

    Button btn1 = new Button(this);
    btn1.setText("invoke Exception");
    btn1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            final int count = 2;
            int[] array = new int[count];
            int value = array[count]; // invoke IndexOutOfBOundsException
        }
    });
    layout.addView(btn1);

    {
        Button btn = new Button(this);
        btn.setText("disp isReachable");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                final boolean isReachable = NetworkConnectionChecker.isReachable();
                Toast toast = Toast.makeText(context, "IsReachable=" + isReachable, Toast.LENGTH_LONG);
                toast.show();
            }
        });
        layout.addView(btn);
    }

    {
        Button btn = new Button(this);
        btn.setText("upload http AsyncTask");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                AsyncTask<String, Void, Boolean> asyncTask = new AsyncTask<String, Void, Boolean>() {

                    @Override
                    protected Boolean doInBackground(String... paramss) {
                        Boolean result = true;
                        Log.d(TAG, "upload AsyncTask tid=" + android.os.Process.myTid());
                        try {
                            //$(BRAND)/$(PRODUCT)/$(DEVICE)/$(BOARD):$(VERSION.RELEASE)/$(ID)/$(VERSION.INCREMENTAL):$(TYPE)/$(TAGS)
                            Log.d(TAG, "fng=" + Build.FINGERPRINT);
                            final List<NameValuePair> list = new ArrayList<NameValuePair>(16);
                            list.add(new BasicNameValuePair("fng", Build.FINGERPRINT));

                            HttpPost httpPost = new HttpPost(paramss[0]);
                            //httpPost.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, new Integer(5*1000) );
                            httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
                            DefaultHttpClient httpClient = new DefaultHttpClient();
                            Log.d(TAG, "socket.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                            Log.d(TAG, "connection.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
                                    new Integer(5 * 1000));
                            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                                    new Integer(5 * 1000));
                            Log.d(TAG, "socket.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                            Log.d(TAG, "connection.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                            // <uses-permission android:name="android.permission.INTERNET"/>
                            // got android.os.NetworkOnMainThreadException, run at UI Main Thread
                            HttpResponse response = httpClient.execute(httpPost);
                            Log.d(TAG, "response=" + response.getStatusLine().getStatusCode());
                        } catch (Exception e) {
                            Log.d(TAG, "got Exception. msg=" + e.getMessage(), e);
                            result = false;
                        }
                        Log.d(TAG, "upload finish");
                        return result;
                    }

                };

                asyncTask.execute("http://kkkon.sakura.ne.jp/android/bug");
                asyncTask.isCancelled();
            }
        });
        layout.addView(btn);
    }

    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(0.0.0.0)");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        try {
                            destHost = InetAddress.getByName("0.0.0.0");
                            if (null != destHost) {
                                try {
                                    if (destHost.isReachable(5 * 1000)) {
                                        Log.d(TAG, "destHost=" + destHost.toString() + " reachable");
                                    } else {
                                        Log.d(TAG, "destHost=" + destHost.toString() + " not reachable");
                                    }
                                } catch (IOException e) {

                                }
                            }
                        } catch (UnknownHostException e) {

                        }
                        Log.d(TAG, "destHost=" + destHost);
                    }
                });
                thread.start();
                try {
                    thread.join(1000);
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }
    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(www.google.com)");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        Log.d(TAG, "start");
                        try {
                            InetAddress dest = InetAddress.getByName("www.google.com");
                            if (null == dest) {
                                dest = destHost;
                            }

                            if (null != dest) {
                                final String[] uris = new String[] { "http://www.google.com/",
                                        "https://www.google.com/" };
                                for (final String destURI : uris) {
                                    URI uri = null;
                                    try {
                                        uri = new URI(destURI);
                                    } catch (URISyntaxException e) {
                                        //Log.d( TAG, e.toString() );
                                    }

                                    if (null != uri) {
                                        URL url = null;
                                        try {
                                            url = uri.toURL();
                                        } catch (MalformedURLException ex) {
                                            Log.d(TAG, "got exception:" + ex.toString(), ex);
                                        }

                                        URLConnection conn = null;
                                        if (null != url) {
                                            Log.d(TAG, "openConnection before");
                                            try {
                                                conn = url.openConnection();
                                                if (null != conn) {
                                                    conn.setConnectTimeout(3 * 1000);
                                                    conn.setReadTimeout(3 * 1000);
                                                }
                                            } catch (IOException e) {
                                                //Log.d( TAG, "got Exception" + e.toString(), e );
                                            }
                                            Log.d(TAG, "openConnection after");
                                            if (conn instanceof HttpURLConnection) {
                                                HttpURLConnection httpConn = (HttpURLConnection) conn;
                                                int responceCode = -1;
                                                try {
                                                    Log.d(TAG, "getResponceCode before");
                                                    responceCode = httpConn.getResponseCode();
                                                    Log.d(TAG, "getResponceCode after");
                                                } catch (IOException ex) {
                                                    Log.d(TAG, "got exception:" + ex.toString(), ex);
                                                }
                                                Log.d(TAG, "responceCode=" + responceCode);
                                                if (0 < responceCode) {
                                                    isReachable = true;
                                                    destHost = dest;
                                                }
                                                Log.d(TAG,
                                                        " HTTP ContentLength=" + httpConn.getContentLength());
                                                httpConn.disconnect();
                                                Log.d(TAG,
                                                        " HTTP ContentLength=" + httpConn.getContentLength());
                                            }
                                        }
                                    } // if uri

                                    if (isReachable) {
                                        //break;
                                    }
                                } // for uris
                            } else {
                            }
                        } catch (UnknownHostException e) {
                            Log.d(TAG, "dns error" + e.toString());
                            destHost = null;
                        }
                        {
                            if (null != destHost) {
                                Log.d(TAG, "destHost=" + destHost);
                            }
                        }
                        Log.d(TAG, "end");
                    }
                });
                thread.start();
                try {
                    thread.join();
                    {
                        final String addr = (null == destHost) ? ("") : (destHost.toString());
                        final String reachable = (isReachable) ? ("reachable") : ("not reachable");
                        Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable,
                                Toast.LENGTH_LONG);
                        toast.show();
                    }
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }

    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(kkkon.sakura.ne.jp)");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        Log.d(TAG, "start");
                        try {
                            InetAddress dest = InetAddress.getByName("kkkon.sakura.ne.jp");
                            if (null == dest) {
                                dest = destHost;
                            }
                            if (null != dest) {
                                try {
                                    if (dest.isReachable(5 * 1000)) {
                                        Log.d(TAG, "destHost=" + dest.toString() + " reachable");
                                        isReachable = true;
                                    } else {
                                        Log.d(TAG, "destHost=" + dest.toString() + " not reachable");
                                    }
                                    destHost = dest;
                                } catch (IOException e) {

                                }
                            } else {
                            }
                        } catch (UnknownHostException e) {
                            Log.d(TAG, "dns error" + e.toString());
                            destHost = null;
                        }
                        {
                            if (null != destHost) {
                                Log.d(TAG, "destHost=" + destHost);
                            }
                        }
                        Log.d(TAG, "end");
                    }
                });
                thread.start();
                try {
                    thread.join();
                    {
                        final String addr = (null == destHost) ? ("") : (destHost.toString());
                        final String reachable = (isReachable) ? ("reachable") : ("not reachable");
                        Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable,
                                Toast.LENGTH_LONG);
                        toast.show();
                    }
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }

    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(kkkon.sakura.ne.jp) support proxy");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        try {
                            String target = null;
                            {
                                ProxySelector proxySelector = ProxySelector.getDefault();
                                Log.d(TAG, "proxySelector=" + proxySelector);
                                if (null != proxySelector) {
                                    URI uri = null;
                                    try {
                                        uri = new URI("http://www.google.com/");
                                    } catch (URISyntaxException e) {
                                        Log.d(TAG, e.toString());
                                    }
                                    List<Proxy> proxies = proxySelector.select(uri);
                                    if (null != proxies) {
                                        for (final Proxy proxy : proxies) {
                                            Log.d(TAG, " proxy=" + proxy);
                                            if (null != proxy) {
                                                if (Proxy.Type.HTTP == proxy.type()) {
                                                    final SocketAddress sa = proxy.address();
                                                    if (sa instanceof InetSocketAddress) {
                                                        final InetSocketAddress isa = (InetSocketAddress) sa;
                                                        target = isa.getHostName();
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            if (null == target) {
                                target = "kkkon.sakura.ne.jp";
                            }
                            InetAddress dest = InetAddress.getByName(target);
                            if (null == dest) {
                                dest = destHost;
                            }
                            if (null != dest) {
                                try {
                                    if (dest.isReachable(5 * 1000)) {
                                        Log.d(TAG, "destHost=" + dest.toString() + " reachable");
                                        isReachable = true;
                                    } else {
                                        Log.d(TAG, "destHost=" + dest.toString() + " not reachable");
                                        {
                                            ProxySelector proxySelector = ProxySelector.getDefault();
                                            //Log.d( TAG, "proxySelector=" + proxySelector );
                                            if (null != proxySelector) {
                                                URI uri = null;
                                                try {
                                                    uri = new URI("http://www.google.com/");
                                                } catch (URISyntaxException e) {
                                                    //Log.d( TAG, e.toString() );
                                                }

                                                if (null != uri) {
                                                    List<Proxy> proxies = proxySelector.select(uri);
                                                    if (null != proxies) {
                                                        for (final Proxy proxy : proxies) {
                                                            //Log.d( TAG, " proxy=" + proxy );
                                                            if (null != proxy) {
                                                                if (Proxy.Type.HTTP == proxy.type()) {
                                                                    URL url = uri.toURL();
                                                                    URLConnection conn = null;
                                                                    if (null != url) {
                                                                        try {
                                                                            conn = url.openConnection(proxy);
                                                                            if (null != conn) {
                                                                                conn.setConnectTimeout(
                                                                                        3 * 1000);
                                                                                conn.setReadTimeout(3 * 1000);
                                                                            }
                                                                        } catch (IOException e) {
                                                                            Log.d(TAG, "got Exception"
                                                                                    + e.toString(), e);
                                                                        }
                                                                        if (conn instanceof HttpURLConnection) {
                                                                            HttpURLConnection httpConn = (HttpURLConnection) conn;
                                                                            if (0 < httpConn
                                                                                    .getResponseCode()) {
                                                                                isReachable = true;
                                                                            }
                                                                            Log.d(TAG, " HTTP ContentLength="
                                                                                    + httpConn
                                                                                            .getContentLength());
                                                                            Log.d(TAG, " HTTP res=" + httpConn
                                                                                    .getResponseCode());
                                                                            //httpConn.setInstanceFollowRedirects( false );
                                                                            //httpConn.setRequestMethod( "HEAD" );
                                                                            //conn.connect();
                                                                            httpConn.disconnect();
                                                                            Log.d(TAG, " HTTP ContentLength="
                                                                                    + httpConn
                                                                                            .getContentLength());
                                                                            Log.d(TAG, " HTTP res=" + httpConn
                                                                                    .getResponseCode());
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }

                                    }
                                    destHost = dest;
                                } catch (IOException e) {
                                    Log.d(TAG, "got Excpetion " + e.toString());
                                }
                            } else {
                            }
                        } catch (UnknownHostException e) {
                            Log.d(TAG, "dns error" + e.toString());
                            destHost = null;
                        }
                        {
                            if (null != destHost) {
                                Log.d(TAG, "destHost=" + destHost);
                            }
                        }
                    }
                });
                thread.start();
                try {
                    thread.join();
                    {
                        final String addr = (null == destHost) ? ("") : (destHost.toString());
                        final String reachable = (isReachable) ? ("reachable") : ("not reachable");
                        Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable,
                                Toast.LENGTH_LONG);
                        toast.show();
                    }
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }

    setContentView(layout);
}

From source file:com.cloudbees.jenkins.plugins.bitbucket.server.client.BitbucketServerAPIClient.java

private void setClientProxyParams(String host, HttpClientBuilder builder) {
    Jenkins jenkins = Jenkins.getInstance();
    ProxyConfiguration proxyConfig = null;
    if (jenkins != null) {
        proxyConfig = jenkins.proxy;//from w ww .j  a v  a 2 s  .c  o m
    }

    final Proxy proxy;

    if (proxyConfig != null) {
        URI hostURI = URI.create(host);
        proxy = proxyConfig.createProxy(hostURI.getHost());
    } else {
        proxy = Proxy.NO_PROXY;
    }

    if (proxy.type() != Proxy.Type.DIRECT) {
        final InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();
        LOGGER.log(Level.FINE, "Jenkins proxy: {0}", proxy.address());
        builder.setProxy(new HttpHost(proxyAddress.getHostName(), proxyAddress.getPort()));
        String username = proxyConfig.getUserName();
        String password = proxyConfig.getPassword();
        if (username != null && !"".equals(username.trim())) {
            LOGGER.fine("Using proxy authentication (user=" + username + ")");
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(username, password));
            AuthCache authCache = new BasicAuthCache();
            authCache.put(HttpHost.create(proxyAddress.getHostName()), new BasicScheme());
            context = HttpClientContext.create();
            context.setCredentialsProvider(credentialsProvider);
            context.setAuthCache(authCache);
        }
    }
}

From source file:org.apache.flink.runtime.jobmanager.JobManager.java

public JobManager(ExecutionMode executionMode) throws Exception {

    final String ipcAddressString = GlobalConfiguration.getString(ConfigConstants.JOB_MANAGER_IPC_ADDRESS_KEY,
            null);/*from w  ww  .j ava2 s  .com*/

    InetAddress ipcAddress = null;
    if (ipcAddressString != null) {
        try {
            ipcAddress = InetAddress.getByName(ipcAddressString);
        } catch (UnknownHostException e) {
            throw new Exception("Cannot convert " + ipcAddressString + " to an IP address: " + e.getMessage(),
                    e);
        }
    }

    final int ipcPort = GlobalConfiguration.getInteger(ConfigConstants.JOB_MANAGER_IPC_PORT_KEY,
            ConfigConstants.DEFAULT_JOB_MANAGER_IPC_PORT);

    // Read the suggested client polling interval
    this.recommendedClientPollingInterval = GlobalConfiguration.getInteger(
            ConfigConstants.JOBCLIENT_POLLING_INTERVAL_KEY, ConfigConstants.DEFAULT_JOBCLIENT_POLLING_INTERVAL);

    // read the default number of times that failed tasks should be re-executed
    this.defaultExecutionRetries = GlobalConfiguration.getInteger(ConfigConstants.DEFAULT_EXECUTION_RETRIES_KEY,
            ConfigConstants.DEFAULT_EXECUTION_RETRIES);

    // delay between retries should be one heartbeat timeout
    this.delayBetweenRetries = 2
            * GlobalConfiguration.getLong(ConfigConstants.JOB_MANAGER_DEAD_TASKMANAGER_TIMEOUT_KEY,
                    ConfigConstants.DEFAULT_JOB_MANAGER_DEAD_TASKMANAGER_TIMEOUT);

    // Load the job progress collector
    this.eventCollector = new EventCollector(this.recommendedClientPollingInterval);

    this.libraryCacheManager = new BlobLibraryCacheManager(new BlobServer(),
            GlobalConfiguration.getConfiguration());

    // Register simple job archive
    int archived_items = GlobalConfiguration.getInteger(ConfigConstants.JOB_MANAGER_WEB_ARCHIVE_COUNT,
            ConfigConstants.DEFAULT_JOB_MANAGER_WEB_ARCHIVE_COUNT);
    if (archived_items > 0) {
        this.archive = new MemoryArchivist(archived_items);
        this.eventCollector.registerArchivist(archive);
    } else {
        this.archive = null;
    }

    this.currentJobs = new ConcurrentHashMap<JobID, ExecutionGraph>();

    // Create the accumulator manager, with same archiving limit as web
    // interface. We need to store the accumulators for at least one job.
    // Otherwise they might be deleted before the client requested the
    // accumulator results.
    this.accumulatorManager = new AccumulatorManager(Math.min(1, archived_items));

    // Determine own RPC address
    final InetSocketAddress rpcServerAddress = new InetSocketAddress(ipcAddress, ipcPort);

    // Start job manager's IPC server
    try {
        final int handlerCount = GlobalConfiguration.getInteger(ConfigConstants.JOB_MANAGER_IPC_HANDLERS_KEY,
                ConfigConstants.DEFAULT_JOB_MANAGER_IPC_HANDLERS);
        this.jobManagerServer = RPC.getServer(this, rpcServerAddress.getHostName(), rpcServerAddress.getPort(),
                handlerCount);
        this.jobManagerServer.start();
    } catch (IOException e) {
        throw new Exception("Cannot start RPC server: " + e.getMessage(), e);
    }

    LOG.info("Starting job manager in " + executionMode + " mode");

    // Try to load the instance manager for the given execution mode
    if (executionMode == ExecutionMode.LOCAL) {
        final int numTaskManagers = GlobalConfiguration
                .getInteger(ConfigConstants.LOCAL_INSTANCE_MANAGER_NUMBER_TASK_MANAGER, 1);
        this.instanceManager = new LocalInstanceManager(numTaskManagers);
    } else if (executionMode == ExecutionMode.CLUSTER) {
        this.instanceManager = new InstanceManager();
    } else {
        throw new IllegalArgumentException("ExecutionMode");
    }

    // create the scheduler and make it listen at the availability of new instances
    this.scheduler = new Scheduler(this.executorService);
    this.instanceManager.addInstanceListener(this.scheduler);
}

From source file:org.apache.hama.bsp.BSPMaster.java

BSPMaster(HamaConfiguration conf, String identifier) throws IOException, InterruptedException {
    this.conf = conf;
    this.masterIdentifier = identifier;

    // Create the scheduler and init scheduler services
    Class<? extends TaskScheduler> schedulerClass = conf.getClass("bsp.master.taskscheduler",
            SimpleTaskScheduler.class, TaskScheduler.class);
    this.taskScheduler = ReflectionUtils.newInstance(schedulerClass, conf);

    InetSocketAddress inetSocketAddress = getAddress(conf);
    // inetSocketAddress is null if we are in local mode, then we should start
    // nothing.//from ww  w .ja  v a2  s . c o m
    if (inetSocketAddress != null) {
        host = inetSocketAddress.getHostName();
        port = inetSocketAddress.getPort();
        LOG.info("RPC BSPMaster: host " + host + " port " + port);

        startTime = System.currentTimeMillis();
        this.masterServer = RPC.getServer(this, host, port, conf);

        infoPort = conf.getInt("bsp.http.infoserver.port", 40013);

        infoServer = new HttpServer("bspmaster", host, infoPort, true, conf);
        infoServer.setAttribute("bsp.master", this);

        // starting webserver
        infoServer.start();

        if (conf.getBoolean("bsp.monitor.fd.enabled", false)) {
            this.supervisor.set(FDProvider.createSupervisor(
                    conf.getClass("bsp.monitor.fd.supervisor.class", UDPSupervisor.class, Supervisor.class),
                    conf));
        }

        while (!Thread.currentThread().isInterrupted()) {
            try {
                if (fs == null) {
                    fs = FileSystem.get(conf);
                }
            } catch (IOException e) {
                LOG.error("Can't get connection to Hadoop Namenode!", e);
            }
            try {
                // clean up the system dir, which will only work if hdfs is out of
                // safe mode
                if (systemDir == null) {
                    systemDir = new Path(getSystemDir());
                }

                LOG.info("Cleaning up the system directory");
                LOG.info(systemDir);
                fs.delete(systemDir, true);
                if (FileSystem.mkdirs(fs, systemDir, new FsPermission(SYSTEM_DIR_PERMISSION))) {
                    break;
                }
                LOG.error("Mkdirs failed to create " + systemDir);
                LOG.info(SUBDIR);

            } catch (AccessControlException ace) {
                LOG.warn("Failed to operate on bsp.system.dir (" + systemDir + ") because of permissions.");
                LOG.warn(
                        "Manually delete the bsp.system.dir (" + systemDir + ") and then start the BSPMaster.");
                LOG.warn("Bailing out ... ");
                throw ace;
            } catch (IOException ie) {
                LOG.info("problem cleaning system directory: " + systemDir, ie);
            }
            Thread.sleep(FS_ACCESS_RETRY_PERIOD);
        }

        if (Thread.currentThread().isInterrupted()) {
            throw new InterruptedException();
        }

        deleteLocalFiles(SUBDIR);
    } else {
        System.out.println(localModeMessage);
        LOG.info(localModeMessage);
    }
}

From source file:org.jenkinsci.plugins.fod.FoDAPI.java

private HttpClient getHttpClient() {
    final String METHOD_NAME = CLASS_NAME + ".getHttpClient";
    PrintStream logger = FodBuilder.getLogger();

    if (null == this.httpClient) {
        HttpClientBuilder builder = HttpClientBuilder.create();
        if (null != proxyConfig) {
            String fodBaseUrl = null;

            if (null != this.baseUrl && !this.baseUrl.isEmpty()) {
                fodBaseUrl = this.baseUrl;
            } else {
                fodBaseUrl = PUBLIC_FOD_BASE_URL;
            }//from   w w w .  jav  a 2s. c  om

            Proxy proxy = proxyConfig.createProxy(fodBaseUrl);
            InetSocketAddress address = (InetSocketAddress) proxy.address();
            HttpHost proxyHttpHost = new HttpHost(address.getHostName(), address.getPort(),
                    proxy.address().toString().indexOf("https") != 0 ? "http" : "https");
            builder.setProxy(proxyHttpHost);

            if (null != proxyConfig.getUserName() && !proxyConfig.getUserName().trim().equals("")
                    && null != proxyConfig.getPassword() && !proxyConfig.getPassword().trim().equals("")) {
                Credentials credentials = new UsernamePasswordCredentials(proxyConfig.getUserName(),
                        proxyConfig.getPassword());
                AuthScope authScope = new AuthScope(address.getHostName(), address.getPort());
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(authScope, credentials);
                builder.setDefaultCredentialsProvider(credsProvider);
            }
            logger.println(METHOD_NAME + ": using proxy configuration: " + proxyHttpHost.getSchemeName() + "://"
                    + proxyHttpHost.getHostName() + ":" + proxyHttpHost.getPort());
        }
        this.httpClient = builder.build();
    }
    return this.httpClient;
}