List of usage examples for java.net InetSocketAddress getPort
public final int getPort()
From source file:co.cask.tigon.DistributedMain.java
public void startUp(PrintStream out) throws Exception { registerShutDownHook();/*from ww w .ja va 2s. 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:org.apache.hadoop.mapred.JobTrackerHADaemon.java
public void start() throws IOException { Configuration jtConf = new Configuration(conf); String logicalName = HAUtil.getLogicalName(jtConf); String jtId = HAUtil.getJobTrackerId(jtConf); HAUtil.setGenericConf(jtConf, logicalName, jtId, HAUtil.JOB_TRACKER_SPECIFIC_KEYS); // Login HA daemon, if auth is not kerberos login() is a NOP InetSocketAddress addr = HAUtil.getJtHaRpcAddress(conf, jtId); String localMachine = addr.getHostName(); UserGroupInformation.setConfiguration(conf); SecurityUtil.login(conf, JobTracker.JT_KEYTAB_FILE, JobTracker.JT_USER_NAME, localMachine); // To avoid the JT from doing a new login() as re-login seems to be destructive JobTracker.loggedIn = true;/*from w w w . j a v a 2s .c o m*/ //Using a thread outside of all login context to start/stop the JT //otherwise the credentials of the UGI making the RPC call to activate //get in the way breaking things. jtRunner = new JobTrackerRunner(); jtRunner.start(); this.proto = new JobTrackerHAServiceProtocol(jtConf, jtRunner); RPC.setProtocolEngine(conf, HAServiceProtocolPB.class, ProtobufRpcEngine.class); HAServiceProtocolServerSideTranslatorPB haServiceProtocolXlator = new HAServiceProtocolServerSideTranslatorPB( proto); BlockingService haPbService = HAServiceProtocolService .newReflectiveBlockingService(haServiceProtocolXlator); WritableRpcEngine.ensureInitialized(); InetSocketAddress rpcAddr = HAUtil.getJtHaRpcAddress(conf); this.rpcServer = RPC.getServer(HAServiceProtocolPB.class, haPbService, rpcAddr.getHostName(), rpcAddr.getPort(), conf); // set service-level authorization security policy if (conf.getBoolean(CommonConfigurationKeys.HADOOP_SECURITY_AUTHORIZATION, false)) { rpcServer.refreshServiceAcl(conf, new MapReducePolicyProvider()); } this.rpcServer.start(); // set port in config int port = rpcServer.getListenerAddress().getPort(); HAUtil.setJtHaRpcAddress(conf, rpcAddr.getHostName() + ":" + port); LOG.info("Started " + getClass().getSimpleName() + " on port " + port); }
From source file:eu.stratosphere.client.CliFrontendJobManagerConnectionTest.java
@Test public void testValidConfig() { try {//from www . j av a 2 s . c om String[] arguments = {}; CommandLine line = new PosixParser().parse(CliFrontend.getJobManagerAddressOption(new Options()), arguments, false); TestingCliFrontend frontend = new TestingCliFrontend(CliFrontendTestUtils.getConfigDir()); InetSocketAddress address = frontend.getJobManagerAddress(line); assertNotNull(address); assertEquals(CliFrontendTestUtils.TEST_JOB_MANAGER_ADDRESS, address.getAddress().getHostAddress()); assertEquals(CliFrontendTestUtils.TEST_JOB_MANAGER_PORT, address.getPort()); } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); fail("Program caused an exception: " + e.getMessage()); } }
From source file:com.ksc.http.conn.ssl.SdkTLSSocketFactory.java
public Socket connectSocket(final int connectTimeout, final Socket socket, final HttpHost host, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context) throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("connecting to " + remoteAddress.getAddress() + ":" + remoteAddress.getPort()); }/*from ww w . j av a 2 s. c o m*/ Socket connectedSocket; try { connectedSocket = super.connectSocket(connectTimeout, socket, host, remoteAddress, localAddress, context); if (!masterSecretValidator.isMasterSecretValid(connectedSocket)) { throw log(new IllegalStateException("Invalid SSL master secret")); } } catch (final SSLException sslEx) { if (shouldClearSslSessionsPredicate.test(sslEx)) { // clear any related sessions from our cache if (LOG.isDebugEnabled()) { LOG.debug("connection failed due to SSL error, clearing TLS session cache", sslEx); } clearSessionCache(sslContext.getClientSessionContext(), remoteAddress); } throw sslEx; } if (connectedSocket instanceof SSLSocket) { SdkSSLSocket sslSocket = new SdkSSLSocket((SSLSocket) connectedSocket); return KscSdkMetrics.isHttpSocketReadMetricEnabled() ? new SdkSSLMetricsSocket(sslSocket) : sslSocket; } SdkSocket sdkSocket = new SdkSocket(connectedSocket); return KscSdkMetrics.isHttpSocketReadMetricEnabled() ? new SdkMetricsSocket(sdkSocket) : sdkSocket; }
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 w w w. jav a2s . co m*/ this.challengeManager.startChallenge(result.getAffectedEntry().getNode(), senderNode, this); } } }
From source file:eu.stratosphere.client.CliFrontendJobManagerConnectionTest.java
@Test public void testYarnConfig() { try {/*from w w w . j a v a 2s. co m*/ String[] arguments = {}; CommandLine line = new PosixParser().parse(CliFrontend.getJobManagerAddressOption(new Options()), arguments, false); TestingCliFrontend frontend = new TestingCliFrontend(CliFrontendTestUtils.getConfigDirWithYarnFile()); InetSocketAddress address = frontend.getJobManagerAddress(line); assertNotNull(address); assertEquals(CliFrontendTestUtils.TEST_YARN_JOB_MANAGER_ADDRESS, address.getAddress().getHostAddress()); assertEquals(CliFrontendTestUtils.TEST_YARN_JOB_MANAGER_PORT, address.getPort()); } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); fail("Program caused an exception: " + e.getMessage()); } }
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 ww .ja v a2s . com*/ 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:org.apache.hadoop.hdfs.qjournal.server.JournalNodeJspHelper.java
/** * Fetch stats from a single given journal node over http. *//* w w w. j a v a 2 s.c om*/ private String fetchStats(InetSocketAddress jn) throws IOException { try { return DFSUtil.getHTMLContentWithTimeout(new URI("http", null, jn.getAddress().getHostAddress(), jn.getPort(), "/journalStats", null, null).toURL(), HTTP_CONNECT_TIMEOUT, HTTP_READ_TIMEOUT); } catch (Exception e) { LOG.error("Problem connecting to " + getHostAddress(jn), e); return null; } }
From source file:net.transmutator4j.RunTransmutator4j.java
@Override public void run() { long startTime = System.currentTimeMillis(); InetAddress localhost;/*from w ww. j av a2 s .c om*/ try { localhost = InetAddress.getLocalHost(); } catch (UnknownHostException e) { throw new IllegalStateException("can not resolve local host", e); } //socket get dynamically generated port SocketAddress socket = new InetSocketAddress(localhost, 0); AsynchronousChannelGroup group; try { group = AsynchronousChannelGroup.withFixedThreadPool(10, Executors.defaultThreadFactory()); } catch (IOException e1) { throw new IllegalStateException("can not create channel group", e1); } try ( AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open(group).bind(socket, 1); ) { int numTotalTests = runUnmutatedTests(); long unmutatedTimeEnd = System.currentTimeMillis(); long unmutatedElapsedTime = unmutatedTimeEnd - startTime; listener.testInfo(numTotalTests, unmutatedElapsedTime); System.out.println("unmutated tests took " + unmutatedElapsedTime + " ms"); long timeOut = computeTimeoutTime(unmutatedElapsedTime); InetSocketAddress inetSocketAddress = (InetSocketAddress) server.getLocalAddress(); int port = inetSocketAddress.getPort(); server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() { @Override public void completed(AsynchronousSocketChannel resultChannel, Object attachment) { try { ObjectInputStream in = new ObjectInputStream(Channels.newInputStream(resultChannel)); MutationTestResult testResult = (MutationTestResult) in.readObject(); in.close(); listener.mutationResult(testResult); boolean stillPassed = testResult.testsStillPassed(); System.out.print(stillPassed ? "P" : "."); System.out.flush(); numberOfMutationsMade++; if (stillPassed) { numberOfMutationsThatStillPassedTests++; } } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); throw new RuntimeException("error getting test result ", e); } //accept a new connection server.accept(null, this); } @Override public void failed(Throwable e, Object attachment) { // System.err.println(attachment + " failed with:" + e.getClass().getName()); // e.printStackTrace(); } }); OUTER: for (String classToMutate : new ClassPathClassRepository()) { boolean shouldMutate = shouldMutate(classToMutate); if (shouldMutate) { System.out.printf("mutating %s%n", classToMutate); boolean done = false; int mutationCount = 0; while (!done) { JavaProcessBuilder builder = new JavaProcessBuilder( "net.transmutator4j.Transmutator4j", classToMutate, nameOfTestSuite, Integer.toString(mutationCount), Integer.toString(port)); try { TimedProcess timedProcess = new TimedProcess(builder.getBuilder(), timeOut); int exitValue = timedProcess.call(); TransmutatorUtil.EXIT_STATES exitState = TransmutatorUtil.EXIT_STATES .getValueFor(exitValue); if (exitState == TransmutatorUtil.EXIT_STATES.NO_MUTATIONS_MADE) { done = true; System.out.println(); } else if (exitState == TransmutatorUtil.EXIT_STATES.TIMED_OUT) { numberOfMutationsThatTimedOut++; } } catch (InterruptedException e) { System.err.println("detected cancellation...halting"); //stop iterating through all the classes //by breaking out of outer for loop break OUTER; } mutationCount++; } } } //kill any waiting connections this will cause the completionHandler's fail to get called group.shutdownNow(); //group.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS); long endTime = System.currentTimeMillis(); System.out.printf("took %d ms to run %d mutations of which %d caused timeouts and %d still passed%n", (endTime - startTime), numberOfMutationsMade, numberOfMutationsThatTimedOut, numberOfMutationsThatStillPassedTests); } catch (Exception e) { throw new RuntimeException(e); } finally { if (listener != null) { try { listener.close(); } catch (IOException ignored) { //ignore } } group.shutdown(); } }
From source file:org.elasticsearch.rest.action.admin.indices.upgrade.UpgradeTest.java
HttpRequestBuilder httpClient() { InetSocketAddress[] addresses = cluster().httpAddresses(); InetSocketAddress address = addresses[randomInt(addresses.length - 1)]; return new HttpRequestBuilder(HttpClients.createDefault()).host(address.getHostName()) .port(address.getPort()); }