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:io.crate.integrationtests.BlobSslEnabledITest.java

@Test
public void testGetBlob() throws Exception {
    // this test verifies that the non-zero-copy code path in the HttpBlobHandler works
    String digest = uploadSmallBlob();
    String blobUri = blobUri(digest);

    // can't follow redirects because ssl isn't really enabled
    // -> figure out the node that really has the blob

    CloseableHttpClient client = HttpClients.custom().disableRedirectHandling().build();
    List<String> redirectLocations = getRedirectLocations(client, blobUri, address);
    InetSocketAddress correctAddress;
    if (redirectLocations.isEmpty()) {
        correctAddress = address;/*from   ww  w .j a  v  a2s . c  o  m*/
    } else {
        correctAddress = address2;
    }

    HttpGet httpGet = new HttpGet(String.format(Locale.ENGLISH, "http://%s:%s/_blobs/%s",
            correctAddress.getHostName(), correctAddress.getPort(), blobUri));

    CloseableHttpResponse response = client.execute(httpGet);
    assertEquals(1500, response.getEntity().getContentLength());
}

From source file:org.diorite.impl.client.connection.listeners.HandshakeListener.java

public void startConnection(final RequestType type) {
    switch (type) {
    case STATUS://from  w w w . ja v a  2 s  .  c o  m
        // TODO finish
        break;
    case LOGIN:
        this.networkManager.setPacketListener(new LoginListener(this.core, this.networkManager));
        // TODO finish
        final InetSocketAddress address = (InetSocketAddress) this.networkManager.getSocketAddress();
        this.networkManager.sendPacket(
                new PacketHandshakingServerboundSetProtocol(PacketHandshakeListener.CURRENT_PROTOCOL,
                        RequestType.LOGIN, address.getPort(), address.getHostName()));
        this.networkManager.setProtocol(EnumProtocol.LOGIN);
        this.networkManager.sendPacket(new PacketLoginServerboundStart(
                new GameProfileImpl(DioriteUtils.getCrackedUuid("player"), "player")));
        break;
    }
}

From source file:com.jbombardier.reports.OldReportGenerator.java

public void generate(Map<InetSocketAddress, ResultsPackage> agentResults, File reportsDir) {
    Chunker chunker = new Chunker();

    Log.set(Log.LEVEL_DEBUG);/*from  w  ww.j  a  v  a 2 s.  c o  m*/

    Set<String> totalsTransactionNames = new HashSet<String>();
    Set<String> perAgentTransactionNames = new HashSet<String>();
    Set<String> perAgentPerThreadTransactionNames = new HashSet<String>();
    Set<String> agentStrings = new HashSet<String>();

    Set<InetSocketAddress> keySet = agentResults.keySet();
    for (InetSocketAddress inetSocketAddress : keySet) {
        String agentString = inetSocketAddress.getHostName();
        Log.debug("Process result from agent " + agentString);
        agentStrings.add(agentString);

        ResultsPackage resultsPerThread = agentResults.get(inetSocketAddress);

        Set<String> threadNames = resultsPerThread.getThreadResults().keySet();
        for (String threadName : threadNames) {
            Log.debug("Processing result for thread name ", threadName);
            ThreadResults results = resultsPerThread.getThreadResults().get(threadName);

            Set<String> transactionIDs = results.keySet();
            for (String transactionID : transactionIDs) {
                Log.debug("Processing transactionID '" + transactionID + "'");
                String agentKey = agentString + "." + transactionID + ".elapsed";
                String agentThreadKey = agentString + "." + threadName + "." + transactionID + ".elapsed";
                String totalKey = "total." + transactionID + ".elapsed";

                totalsTransactionNames.add(totalKey);
                perAgentTransactionNames.add(agentKey);
                perAgentPerThreadTransactionNames.add(agentThreadKey);

                AggregatedResultSeries aggregatedResultSeries = results.get(transactionID);
                List<AggregatedResult> aggregatedResults = aggregatedResultSeries.getResults();
                for (AggregatedResult result : aggregatedResults) {
                    Log.debug(result.toString());
                    chunker.onNewResult(agentKey, result.time, result.mean() * 1e-6f);
                    chunker.onNewResult(totalKey, result.time, result.mean() * 1e-6f);
                }
            }
        }
    }

    // The first chart is the [all agents, all threads, all transactions] mean transaction time chart
    TimeSeriesCollection timeSeriesCollection = extractTimeSeries(chunker, totalsTransactionNames,
            Statistic.Mean);
    render("All transactions mean per second elapsed times", timeSeriesCollection,
            new File(reportsDir, "all.transactions.elapsed.png"));

    // The second chart is the [all agents, all threads, all transactions] transaction count chart
    timeSeriesCollection = extractTimeSeries(chunker, totalsTransactionNames, Statistic.Count);
    render("All transactions per second counts", timeSeriesCollection,
            new File(reportsDir, "all.transactions.count.png"));

    // Now lets do the same for each agent
    for (final String agent : agentStrings) {
        TimeSeriesCollection agentTimeSeriesCollection = new TimeSeriesCollection();
        for (String perAgentPerThreadTransactionName : perAgentTransactionNames) {
            if (perAgentPerThreadTransactionName.startsWith(agent)) {
                List<Chunk> timeOrderedResults = chunker
                        .getTimeOrderedResults(perAgentPerThreadTransactionName);
                TimeSeries extractTimeSeries = extractTimeSeries(timeOrderedResults,
                        perAgentPerThreadTransactionName, Statistic.Mean);
                agentTimeSeriesCollection.addSeries(extractTimeSeries);
            }
        }

        render(agent + " transactions mean per second elapsed times", agentTimeSeriesCollection,
                new File(reportsDir, agent + ".transactions.elapsed.png"));
    }

    // Lets have a stab at writing out some csv stuff
    writePerSecondResults(reportsDir, chunker, totalsTransactionNames);
}

From source file:com.googlecode.gmail4j.http.HttpProxyAwareSslSocketFactory.java

@Override
public Socket createSocket() throws IOException {
    //FIXME won't work..
    log.debug("Creating socket! with proxy: " + proxy.address());
    InetSocketAddress addr = (InetSocketAddress) proxy.address();
    ProxyClient proxyClient = new ProxyClient();
    proxyClient.getHostConfiguration().setHost("imap.gmail.com", 993);
    proxyClient.getHostConfiguration().setProxy(addr.getHostName(), addr.getPort());
    if (proxyCredentials != null) {
        proxyClient.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                proxyCredentials.getUsername(), new String(proxyCredentials.getPasword())));
    }/*from ww  w  . ja v a2 s . co  m*/
    log.debug("Trying to connect to proxy");
    ProxyClient.ConnectResponse resp = proxyClient.connect();
    if (resp.getConnectMethod().getStatusCode() != HttpStatus.SC_OK) {
        log.error("Failed to connect. " + resp.getConnectMethod().getStatusLine());
        throw new GmailException(
                "Failed connecting to IMAP through proxy: " + resp.getConnectMethod().getStatusLine());
    }
    log.debug("Connected, returning socket");
    return resp.getSocket();
}

From source file:org.eclipse.jubula.launch.java.SwingAutLaunchConfigurationDelegate.java

@Override
public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor)
        throws CoreException {

    String autMainType = verifyMainTypeName(configuration);
    String autArgs = getProgramArguments(configuration);
    String autId = AutLaunchUtils.getAutId(configuration);

    ILaunchConfigurationWorkingCopy workingCopy = configuration.getWorkingCopy();
    workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME,
            CommandConstants.AUT_SERVER_LAUNCHER);

    InetSocketAddress agentAddr = AutLaunchUtils.verifyConnectedAgentAddress();

    String[] args = { Integer.toString(agentAddr.getPort()), autMainType,
            StringUtils.join(new StartSwingAutServerCommand().getLaunchClasspath(), IStartAut.PATH_SEPARATOR),
            CommandConstants.AUT_SWING_SERVER, agentAddr.getHostName(), Integer.toString(agentAddr.getPort()),
            autId, CommandConstants.RC_COMMON_AGENT_INACTIVE, autArgs };

    workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS,
            StringUtils.join(args, " ")); //$NON-NLS-1$

    super.launch(workingCopy, ILaunchManager.DEBUG_MODE, launch, monitor);
}

From source file:common.NameNode.java

public static URI getUri(InetSocketAddress namenode) {
    int port = namenode.getPort();
    String portString = port == DEFAULT_PORT ? "" : (":" + port);
    return URI.create(FSConstants.HDFS_URI_SCHEME + "://" + namenode.getHostName() + portString);
}

From source file:org.apache.hadoop.hdfs.qjournal.server.JournalNodeHttpServer.java

void start() throws IOException {
    final InetSocketAddress bindAddr = getAddress(conf);

    // initialize the webserver for uploading/downloading files.
    LOG.info("Starting web server as: " + SecurityUtil.getServerPrincipal(
            conf.get(DFS_JOURNALNODE_INTERNAL_SPNEGO_USER_NAME_KEY), bindAddr.getHostName()));

    int tmpInfoPort = bindAddr.getPort();
    httpServer = new HttpServer("journal", bindAddr.getHostName(), tmpInfoPort, tmpInfoPort == 0, conf,
            new AccessControlList(conf.get(DFS_ADMIN, " "))) {
        {//from  w  w w.  j  a  v  a2 s  . c o m
            if (UserGroupInformation.isSecurityEnabled()) {
                initSpnego(conf, DFS_JOURNALNODE_INTERNAL_SPNEGO_USER_NAME_KEY,
                        DFSUtil.getSpnegoKeytabKey(conf, DFS_JOURNALNODE_KEYTAB_FILE_KEY));
            }
        }
    };
    httpServer.setAttribute(JN_ATTRIBUTE_KEY, localJournalNode);
    httpServer.setAttribute(JspHelper.CURRENT_CONF, conf);
    httpServer.addInternalServlet("getJournal", "/getJournal", GetJournalEditServlet.class, true);
    httpServer.start();

    // The web-server port can be ephemeral... ensure we have the correct info
    infoPort = httpServer.getPort();

    LOG.info("Journal Web-server up at: " + bindAddr + ":" + infoPort);
}

From source file:com.chinamobile.bcbsp.bspstaff.StaffRunner.java

/**
 * Start to run a BSP staff./*from   w  ww  .  ja  v a2 s . c  o  m*/
 */
@Override
public void run() {
    try {
        String sep = System.getProperty("path.separator");
        File workDir = new File(new File(staff.getJobFile()).getParent(), "work");
        boolean isCreated = workDir.mkdirs();
        if (!isCreated) {
            LOG.debug("StaffRunner.workDir : " + workDir);
        }
        StringBuffer classPath = new StringBuffer();
        classPath.append(System.getProperty("java.class.path"));
        classPath.append(sep);
        if (Constants.USER_BC_BSP_JOB_TYPE_C.equals(this.conf.getJobType())) {
            String exe = conf.getJobExe();
            if (exe != null) {
                classPath.append(sep);
                classPath.append(exe);
                classPath.append(sep);
                classPath.append(workDir);
            }
        } else {
            String jar = conf.getJar();
            // if jar exists, it into workDir
            if (jar != null) {
                RunJar.unJar(new File(jar), workDir);
                File[] libs = new File(workDir, "lib").listFiles();
                if (libs != null) {
                    for (int i = 0; i < libs.length; i++) {
                        // add libs from jar to classpath
                        classPath.append(sep);
                        classPath.append(libs[i]);
                    }
                }
                classPath.append(sep);
                classPath.append(new File(workDir, "classes"));
                classPath.append(sep);
                classPath.append(workDir);
            }
        }
        // Build exec child jmv args.
        Vector<String> vargs = new Vector<String>();
        File jvm = new File(new File(System.getProperty("java.home"), "bin"), "java");
        vargs.add(jvm.toString());

        // bsp.child.java.opts
        String javaOpts = conf.getConf().get("bsp.child.java.opts", "-Xmx200m");
        javaOpts = javaOpts.replace("@taskid@", staff.getStaffID().toString());
        String[] javaOptsSplit = javaOpts.split(" ");
        for (int i = 0; i < javaOptsSplit.length; i++) {
            vargs.add(javaOptsSplit[i]);
        }

        // Add classpath.
        vargs.add("-classpath");
        vargs.add(classPath.toString());

        // Setup the log4j prop
        long logSize = StaffLog.getStaffLogLength(((BSPConfiguration) conf.getConf()));
        vargs.add("-Dbcbsp.log.dir=" + new File(System.getProperty("bcbsp.log.dir")).getAbsolutePath());
        vargs.add("-Dbcbsp.root.logger=INFO,TLA");

        LOG.info("debug: staff ID is " + staff.getStaffID());

        vargs.add("-Dbcbsp.tasklog.taskid=" + staff.getStaffID());
        vargs.add("-Dbcbsp.tasklog.totalLogFileSize=" + logSize);

        // Add main class and its arguments
        vargs.add(WorkerManager.Child.class.getName());
        InetSocketAddress addr = workerManager.getStaffTrackerReportAddress();

        vargs.add(addr.getHostName());
        vargs.add(Integer.toString(addr.getPort()));
        vargs.add(staff.getStaffID().toString());
        vargs.add(Integer.toString(getFaultSSStep()));
        vargs.add(workerManager.getHostName());
        vargs.add(this.conf.getJobType());

        // Run java
        runChild(vargs.toArray(new String[0]), workDir);
    } catch (Exception e) {
        LOG.error("[run]", e);
    }
}

From source file:co.cask.tigon.DistributedMain.java

public void startUp(PrintStream out) throws Exception {
    registerShutDownHook();// w  w w . j av a  2  s  . c  o  m
    flowOperations.startAndWait();
    List<String> commandList = Lists.newArrayList();
    for (CLICommands cliCommand : CLICommands.values()) {
        commandList.add(cliCommand.toString().toLowerCase());
    }
    consoleReader.setPrompt("tigon> ");
    String line;
    while ((line = consoleReader.readLine()) != null) {
        String[] args = line.split("\\s+");
        String command = args[0].toUpperCase();
        try {
            CLICommands cmd = null;
            try {
                cmd = CLICommands.valueOf(command);
            } catch (IllegalArgumentException e) {
                out.println("Available Commands : ");
                out.println(StringUtils.join(commandList, ", "));
                continue;
            }

            if (args.length < cmd.getArgCount()) {
                throw new InvalidCLIArgumentException(cmd.printHelp());
            }

            if (cmd.equals(CLICommands.START)) {
                Map<String, String> runtimeArgs = Maps.newHashMap();
                if (args.length > cmd.getArgCount()) {
                    try {
                        runtimeArgs = DeployClient
                                .fromPosixArray(Arrays.copyOfRange(args, cmd.getArgCount(), args.length));
                    } catch (IllegalArgumentException e) {
                        LOG.error("Runtime Args are not in the correct format [ --key1=val1 --key2=val2 ]");
                        continue;
                    }
                }
                flowOperations.startFlow(new File(args[1]), args[2], runtimeArgs);
            } else if (cmd.equals(CLICommands.LIST)) {
                out.println(StringUtils.join(flowOperations.listAllFlows(), ", "));
            } else if (cmd.equals(CLICommands.STOP)) {
                flowOperations.stopFlow(args[1]);
            } else if (cmd.equals(CLICommands.DELETE)) {
                flowOperations.deleteFlow(args[1]);
            } else if (cmd.equals(CLICommands.SET)) {
                flowOperations.setInstances(args[1], args[2], Integer.valueOf(args[3]));
            } else if (cmd.equals(CLICommands.STATUS)) {
                Service.State state = flowOperations.getStatus(args[1]);
                String status = (state != null) ? state.toString() : "NOT FOUND";
                out.println(status);
            } else if (cmd.equals(CLICommands.FLOWLETINFO)) {
                out.println(String.format("%-20s %s", "Flowlet Name", "Instance Count"));
                Map<String, Integer> flowletInfoMap = flowOperations.getFlowInfo(args[1]);
                for (Map.Entry<String, Integer> flowletInfo : flowletInfoMap.entrySet()) {
                    out.println(String.format("%-20s %s", flowletInfo.getKey(), flowletInfo.getValue()));
                }
            } else if (cmd.equals(CLICommands.DISCOVER)) {
                for (InetSocketAddress socketAddress : flowOperations.discover(args[1], args[2])) {
                    out.println(String.format("%s:%s", socketAddress.getHostName(), socketAddress.getPort()));
                }
            } else if (cmd.equals(CLICommands.SHOWLOGS)) {
                flowOperations.addLogHandler(args[1], System.out);
            } else if (cmd.equals(CLICommands.SERVICEINFO)) {
                out.println(StringUtils.join(flowOperations.getServices(args[1]), "\n"));
            } else if (cmd.equals(CLICommands.VERSION)) {
                out.println(ProjectInfo.getVersion().getBuildVersion());
            } else if (cmd.equals(CLICommands.HELP)) {
                try {
                    out.println(CLICommands.valueOf(args[1].toUpperCase()).printHelp());
                } catch (IllegalArgumentException e) {
                    out.println("Command Not Found");
                }
            } else {
                //QUIT Command
                break;
            }
        } catch (InvalidCLIArgumentException e) {
            out.println(e.getMessage());
        }
    }
}

From source file:co.rsk.net.discovery.PeerExplorer.java

private void addConnection(PongPeerMessage message, InetSocketAddress incommingAddress) {
    Node senderNode = new Node(message.getNodeId(), incommingAddress.getHostName(), incommingAddress.getPort());
    if (!StringUtils.equals(senderNode.getHexId(), this.localNode.getHexId())) {
        OperationResult result = this.distanceTable.addNode(senderNode);
        if (result.isSuccess()) {
            ByteArrayWrapper senderId = new ByteArrayWrapper(senderNode.getId());
            this.establishedConnections.put(senderId, senderNode);
        } else {/*from ww  w .j  ava2 s  .c  o m*/
            this.challengeManager.startChallenge(result.getAffectedEntry().getNode(), senderNode, this);
        }
    }
}