List of usage examples for java.net InetSocketAddress getPort
public final int getPort()
From source file:eu.stratosphere.nephele.profiling.impl.JobManagerProfilerImpl.java
public JobManagerProfilerImpl(InetAddress jobManagerbindAddress) throws ProfilingException { // Start profiling IPC server final int handlerCount = GlobalConfiguration.getInteger(RPC_NUM_HANDLER_KEY, DEFAULT_NUM_HANLDER); final int rpcPort = GlobalConfiguration.getInteger(ProfilingUtils.JOBMANAGER_RPC_PORT_KEY, ProfilingUtils.JOBMANAGER_DEFAULT_RPC_PORT); final InetSocketAddress rpcServerAddress = new InetSocketAddress(jobManagerbindAddress, rpcPort); Server profilingServerTmp = null;//from w w w. j a va 2s.c o m try { profilingServerTmp = RPC.getServer(this, rpcServerAddress.getHostName(), rpcServerAddress.getPort(), handlerCount); profilingServerTmp.start(); } catch (IOException ioe) { throw new ProfilingException( "Cannot start profiling RPC server: " + StringUtils.stringifyException(ioe)); } this.profilingServer = profilingServerTmp; }
From source file:com.cloudera.util.StatusHttpServer.java
/** * Configure an ssl listener on the server. * /*from w ww. j a v a 2 s.c om*/ * @param addr * address to listen on * @param keystore * location of the keystore * @param storPass * password for the keystore * @param keyPass * password for the key */ public void addSslListener(InetSocketAddress addr, String keystore, String storPass, String keyPass) throws IOException { if (sslConnector != null || webServer.isStarted()) { throw new IOException("Failed to add ssl listener"); } sslConnector = new SslSocketConnector(); sslConnector.setHost(addr.getHostName()); sslConnector.setPort(addr.getPort()); sslConnector.setKeystore(keystore); sslConnector.setPassword(storPass); sslConnector.setKeyPassword(keyPass); webServer.addConnector(sslConnector); }
From source file:com.maxmind.minfraud.WebServiceClient.java
private WebServiceClient(WebServiceClient.Builder builder) { host = builder.host;// w ww.j av a 2 s . co m port = builder.port; useHttps = builder.useHttps; locales = builder.locales; licenseKey = builder.licenseKey; userId = builder.userId; mapper = new ObjectMapper(); mapper.disable(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); RequestConfig.Builder configBuilder = RequestConfig.custom().setConnectTimeout(builder.connectTimeout) .setSocketTimeout(builder.readTimeout); if (builder.proxy != null) { InetSocketAddress address = (InetSocketAddress) builder.proxy.address(); HttpHost proxyHost = new HttpHost(address.getHostName(), address.getPort()); configBuilder.setProxy(proxyHost); } RequestConfig config = configBuilder.build(); httpClient = HttpClientBuilder.create().setUserAgent(userAgent()).setDefaultRequestConfig(config).build(); }
From source file:org.apache.hadoop.hdfs.qjournal.server.JournalNodeJournalSyncer.java
/** * Recovers a single segment/* w ww . ja va 2 s. com*/ * * @param elf * descriptor of the segment to be recovered * @param task * contains journal description * @throws IOException */ void recoverSegments(SyncTask task) throws IOException { // obtain the list of segments that are valid if (!prepareRecovery(task)) { return; } // iterate through all nodes for (InetSocketAddress jn : journalNodes) { if (isLocalIpAddress(jn.getAddress()) && jn.getPort() == journalNode.getPort()) { // we do not need to talk to ourselves continue; } try { // get manifest for log that we care about List<EditLogFile> remoteLogFiles = getManifest(jn, task.journal, task.recoveryStartTxid); // go through all remote segments for (EditLogFile relf : remoteLogFiles) { recoverSegment(jn, relf, task); } // if we are done, there is no need to iterate more if (!task.hasMissingValidSegments()) { LOG.info(logMsg + "recovery finished."); break; } } catch (Exception e) { LOG.error(logMsg + "error", e); continue; } } }
From source file:io.crate.integrationtests.BlobHttpIntegrationTest.java
public List<String> getRedirectLocations(CloseableHttpClient client, String uri, InetSocketAddress address) throws IOException { CloseableHttpResponse response = null; try {/*w ww .j av a2s .com*/ HttpClientContext context = HttpClientContext.create(); HttpHead httpHead = new HttpHead(String.format(Locale.ENGLISH, "http://%s:%s/_blobs/%s", address.getHostName(), address.getPort(), uri)); response = client.execute(httpHead, context); List<URI> redirectLocations = context.getRedirectLocations(); if (redirectLocations == null) { // client might not follow redirects automatically if (response.containsHeader("location")) { List<String> redirects = new ArrayList<>(1); for (Header location : response.getHeaders("location")) { redirects.add(location.getValue()); } return redirects; } return Collections.emptyList(); } List<String> redirects = new ArrayList<>(1); for (URI redirectLocation : redirectLocations) { redirects.add(redirectLocation.toString()); } return redirects; } finally { if (response != null) { IOUtils.closeWhileHandlingException(response); } } }
From source file:fr.letroll.ttorrentandroid.tracker.TrackerService.java
/** * Process the announce request.//from www.jav a2 s . com * * <p> * This method attempts to read and parse the incoming announce request into * an announce request message, then creates the appropriate announce * response message and sends it back to the client. * </p> * * @param request The incoming announce request. * @param response The response object. * @param body The validated response body output stream. */ private void process(Request request, Response response, OutputStream body) throws IOException { // Prepare the response headers. response.setContentType("text/plain"); response.setValue("Server", this.version); response.setDate("Date", System.currentTimeMillis()); /** * Parse the query parameters into an announce request message. * * We need to rely on our own query parsing function because * SimpleHTTP's Query map will contain UTF-8 decoded parameters, which * doesn't work well for the byte-encoded strings we expect. */ HTTPAnnounceRequestMessage announceRequest; try { announceRequest = this.parseRequest(request); } catch (MessageValidationException e) { requestParseFailed.mark(); LOG.error("Failed to parse request", e); this.serveError(response, body, Status.BAD_REQUEST, e.getMessage()); return; } LOG.trace("Announce request is {}", announceRequest); // The requested torrent must be announced by the tracker. TrackedTorrent torrent = this.torrents.get(announceRequest.getHexInfoHash()); if (torrent == null) { requestNoTorrent.mark(); LOG.warn("No such torrent: {}: Have {}", announceRequest.getHexInfoHash(), this.torrents.keySet()); this.serveError(response, body, Status.BAD_REQUEST, TrackerMessage.ErrorMessage.FailureReason.UNKNOWN_TORRENT); return; } int peerPort = -1; List<InetSocketAddress> peerAddresses = announceRequest.getPeerAddresses(); Iterator<InetSocketAddress> peerAddressIterator = peerAddresses.iterator(); while (peerAddressIterator.hasNext()) { InetSocketAddress peerAddress = peerAddressIterator.next(); if (peerPort == -1) peerPort = peerAddress.getPort(); if (!Peer.isValidIpAddress(peerAddress)) { LOG.debug("Peer specified invalid address {}", peerAddress); peerAddressIterator.remove(); } } if (peerPort == -1) { LOG.debug("Peer specified no valid address."); this.serveError(response, body, Status.BAD_REQUEST, TrackerMessage.ErrorMessage.FailureReason.MISSING_PEER_ADDRESS); } if (peerAddresses.isEmpty()) { InetSocketAddress peerAddress = new InetSocketAddress(request.getClientAddress().getAddress(), peerPort); LOG.debug("Peer specified no valid address; using {} instead.", peerAddress); peerAddresses.add(peerAddress); } TrackedPeer client = torrent.getPeer(announceRequest.getPeerId()); TrackerMessage.AnnounceEvent event = announceRequest.getEvent(); // When no event is specified, it's a periodic update while the client // is operating. If we don't have a peer for this announce, it means // the tracker restarted while the client was running. Consider this // announce request as a 'started' event. if ((event == null || TrackerMessage.AnnounceEvent.NONE.equals(event)) && client == null) { event = TrackerMessage.AnnounceEvent.STARTED; } // If an event other than 'started' is specified and we also haven't // seen the peer on this torrent before, something went wrong. A // previous 'started' announce request should have been made by the // client that would have had us register that peer on the torrent this // request refers to. if (event != null && client == null && !TrackerMessage.AnnounceEvent.STARTED.equals(event)) { requestInvalidEvent.mark(); this.serveError(response, body, Status.BAD_REQUEST, TrackerMessage.ErrorMessage.FailureReason.INVALID_EVENT); return; } // Update the torrent according to the announce event try { client = torrent.update(event, announceRequest.getPeerId(), peerAddresses, announceRequest.getUploaded(), announceRequest.getDownloaded(), announceRequest.getLeft()); } catch (IllegalArgumentException e) { requestUpdateFailed.mark(); LOG.error("Failed to update torrent", e); this.serveError(response, body, Status.BAD_REQUEST, TrackerMessage.ErrorMessage.FailureReason.INVALID_EVENT); return; } // Craft and output the answer HTTPAnnounceResponseMessage announceResponse; try { announceResponse = new HTTPAnnounceResponseMessage(request.getClientAddress().getAddress(), (int) TimeUnit.MILLISECONDS.toSeconds(torrent.getAnnounceInterval()), // TrackedTorrent.MIN_ANNOUNCE_INTERVAL_SECONDS, // this.version, torrent.seeders(), torrent.leechers(), torrent.getSomePeers(client, announceRequest.getNumWant())); BytesBEncoder encoder = new BytesBEncoder(); encoder.bencode( announceResponse.toBEValue(announceRequest.getCompact(), announceRequest.getNoPeerIds())); body.write(encoder.toByteArray()); // This is the raw network stream. } catch (Exception e) { requestResponseFailed.mark(); LOG.error("Failed to send response", e); this.serveError(response, body, Status.INTERNAL_SERVER_ERROR, e.getMessage()); } }
From source file:org.apache.activemq.artemis.tests.integration.amqp.SaslKrb5LDAPSecurityTest.java
private void rewriteKerb5Conf() throws Exception { StringBuilder sb = new StringBuilder(); InputStream is2 = this.getClass().getClassLoader().getResourceAsStream("minikdc-krb5.conf"); BufferedReader r = null;/*from w w w.ja v a2 s . c om*/ try { r = new BufferedReader(new InputStreamReader(is2, StandardCharsets.UTF_8)); String line = r.readLine(); while (line != null) { sb.append(line).append("{3}"); line = r.readLine(); } } finally { IOUtils.closeQuietly(r); IOUtils.closeQuietly(is2); } InetSocketAddress addr = (InetSocketAddress) kdcServer.getTransports()[0].getAcceptor().getLocalAddress(); int port = addr.getPort(); File krb5conf = new File(testDir, "krb5.conf").getAbsoluteFile(); FileUtils.writeStringToFile(krb5conf, MessageFormat.format(sb.toString(), getRealm(), "localhost", Integer.toString(port), System.getProperty("line.separator"))); System.setProperty("java.security.krb5.conf", krb5conf.getAbsolutePath()); System.setProperty("sun.security.krb5.debug", "true"); // refresh the config Class<?> classRef; if (System.getProperty("java.vendor").contains("IBM")) { classRef = Class.forName("com.ibm.security.krb5.internal.Config"); } else { classRef = Class.forName("sun.security.krb5.Config"); } Method refreshMethod = classRef.getMethod("refresh", new Class[0]); refreshMethod.invoke(classRef, new Object[0]); LOG.info("krb5.conf to: {}", krb5conf.getAbsolutePath()); }
From source file:org.apache.flink.yarn.CliFrontendYarnAddressConfigurationTest.java
@Test public void testManualOptionsOverridesYarn() throws Exception { File emptyFolder = temporaryFolder.newFolder(); File testConfFile = new File(emptyFolder.getAbsolutePath(), "flink-conf.yaml"); Files.createFile(testConfFile.toPath()); TestCLI frontend = new TestCLI(emptyFolder.getAbsolutePath()); RunOptions options = CliFrontendParser.parseRunCommand(new String[] { "-m", "10.221.130.22:7788" }); frontend.retrieveClient(options);/*from w w w.j a v a 2 s .c om*/ Configuration config = frontend.getConfiguration(); InetSocketAddress expectedAddress = InetSocketAddress.createUnresolved("10.221.130.22", 7788); checkJobManagerAddress(config, expectedAddress.getHostName(), expectedAddress.getPort()); }
From source file:com.hortonworks.hbase.replication.bridge.ReplicationBridgeServer.java
/** * Starts a HRegionServer at the default location * * @param conf/* w w w. j av a 2 s.com*/ * @throws IOException * @throws InterruptedException * @throws KeeperException * @throws ZkConnectException */ public ReplicationBridgeServer(Configuration conf) throws IOException, InterruptedException, KeeperException { this.conf = conf; // Set how many times to retry talking to another server over HConnection. HConnectionManager.setServerSideHConnectionRetries(this.conf, LOG); // Server to handle client requests. String hostname = conf.get("hbase.regionserver.ipc.address", Strings.domainNamePointerToHostName( DNS.getDefaultHost(conf.get("hbase.regionserver.dns.interface", "default"), conf.get("hbase.regionserver.dns.nameserver", "default")))); port = conf.getInt("hbase.bridge.server.port", BRIDGE_SERVER_PORT); // Creation of a HSA will force a resolve. InetSocketAddress initialIsa = new InetSocketAddress(hostname, port); if (initialIsa.getAddress() == null) { throw new IllegalArgumentException("Failed resolve of " + initialIsa); } this.rpcServer = HBaseRPC.getServer(this, new Class<?>[] { HRegionInterface.class }, initialIsa.getHostName(), // BindAddress is IP we got for this server. initialIsa.getPort(), conf.getInt("hbase.regionserver.handler.count", 10), conf.getInt("hbase.regionserver.metahandler.count", 10), conf.getBoolean("hbase.rpc.verbose", false), conf, HConstants.QOS_THRESHOLD); }
From source file:io.tourniquet.junit.http.rules.HttpExchangeTest.java
@Test public void testGetDestinationAddress() throws Exception { //prepare/*from w w w .ja v a 2 s. c om*/ exchange.setDestinationAddress(InetSocketAddress.createUnresolved("somehost", 12345)); //act InetSocketAddress dest = subject.getDestinationAddress(); //assert assertNotNull(dest); assertEquals("somehost", dest.getHostName()); assertEquals(12345, dest.getPort()); }