List of usage examples for java.net InetSocketAddress getPort
public final int getPort()
From source file:org.apache.synapse.transport.passthru.core.PassThroughListeningIOReactorManager.java
/** * Start SSL endpoint in IO reactor which is external to PTT Axis Listeners started at server startup * @param inetSocketAddress InetSocketAddress * @param nHttpServerEventHandler ServerHandler responsible for handle events of port * @param endpointName Endpoint Name//from w w w . j a v a 2s .co m * @param sslConfiguration SSL information for create secure connection * @return */ public boolean startDynamicPTTSSLEndpoint(InetSocketAddress inetSocketAddress, NHttpServerEventHandler nHttpServerEventHandler, String endpointName, SSLConfiguration sslConfiguration) { try { // get Shared IO Reactor and Start Endpoint ListenerEndpoint endpoint = startEndpoint(inetSocketAddress, getSharedSSLIOReactor(nHttpServerEventHandler, endpointName, inetSocketAddress.getPort(), sslConfiguration), endpointName); if (endpoint != null) { portServerHandlerMapper.put(inetSocketAddress.getPort(), nHttpServerEventHandler); dynamicPTTListeningEndpointMapper.put(inetSocketAddress.getPort(), endpoint); return true; } else { return false; } } catch (Exception e) { log.error("Cannot Start Endpoint for " + endpointName, e); return false; } }
From source file:com.mgmtp.perfload.core.client.web.ssl.LtSSLSocketFactory.java
@Override public Socket connectSocket(final Socket sock, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpParams params) throws IOException { checkArgument(remoteAddress != null, "Remote address may not be null"); checkArgument(params != null, "HTTP parameters may not be null"); Socket socket = sock != null ? sock : new Socket(); if (localAddress != null) { socket.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params)); socket.bind(localAddress);/*from w w w . j a va 2 s .c o m*/ } socket.setSoTimeout(HttpConnectionParams.getSoTimeout(params)); socket.connect(remoteAddress, HttpConnectionParams.getConnectionTimeout(params)); if (socket instanceof SSLSocket) { return socket; } return getSSLContext().getSocketFactory().createSocket(socket, remoteAddress.getHostName(), remoteAddress.getPort(), true); }
From source file:com.all.dht.DhtManager.java
private void removeRemoteEntity(DHTValueEntity valueEntity, Boolean oversized) { AllMessage<String> deleteMessage = new AllMessage<String>(DELETE_DHT_VALUE_REQUEST_TYPE, valueEntity.getPrimaryKey().toHexString()); deleteMessage.putProperty(IS_OVERSIZED_VALUE, oversized.toString()); InetSocketAddress contactAddress = (InetSocketAddress) valueEntity.getCreator().getContactAddress(); networkingService.send(dht.getLocalNodeID().toHexString(), deleteMessage, contactAddress.getAddress().getHostAddress(), contactAddress.getPort() + 1); }
From source file:com.xmlcalabash.library.ApacheHttpRequest.java
public void run() throws SaxonApiException { super.run();// w w w .j a v a2 s . c o m XdmNode requestDoc = source.read(); XdmNode start = S9apiUtils.getDocumentElement(requestDoc); if (!c_request.equals(start.getNodeName())) { throw new UnsupportedOperationException("Not a c:http-request!"); } // Check for valid attributes XdmSequenceIterator iter = start.axisIterator(Axis.ATTRIBUTE); boolean ok = true; while (iter.hasNext()) { XdmNode attr = (XdmNode) iter.next(); QName name = attr.getNodeName(); if (_method.equals(name) || _href.equals(name) || _detailed.equals(name) || _status_only.equals(name) || _username.equals(name) || _password.equals(name) || _auth_method.equals(name) || _send_authorization.equals(name) || _override_content_type.equals(name)) { // nop } else { if (XMLConstants.DEFAULT_NS_PREFIX.equals(name.getNamespaceURI())) { throw new XProcException("Unsupported attribute on c:http-request: " + name); } } } method = start.getAttributeValue(_method); statusOnly = "true".equals(start.getAttributeValue(_status_only)); detailed = "true".equals(start.getAttributeValue(_detailed)); overrideContentType = start.getAttributeValue(_override_content_type); if (start.getAttributeValue(_href) == null) { throw new XProcException("The 'href' attribute must be specified on p:http-request"); } requestURI = start.getBaseURI().resolve(start.getAttributeValue(_href)); if ("file".equals(requestURI.getScheme())) { doFile(); return; } client = new HttpClient(); String timeOutStr = step.getExtensionAttribute(cx_timeout); if (timeOutStr != null) { HttpMethodParams params = client.getParams(); params.setSoTimeout(Integer.parseInt(timeOutStr)); } ProxySelector proxySelector = ProxySelector.getDefault(); List<Proxy> plist = proxySelector.select(requestURI); // I have no idea what I'm expected to do if I get more than one... if (plist.size() > 0) { Proxy proxy = plist.get(0); switch (proxy.type()) { case DIRECT: // nop; break; case HTTP: // This can't cause a ClassCastException, right? InetSocketAddress addr = (InetSocketAddress) proxy.address(); String host = addr.getHostName(); int port = addr.getPort(); client.getHostConfiguration().setProxy(host, port); break; default: // FIXME: send out a log message break; } } if (start.getAttributeValue(_username) != null) { String user = start.getAttributeValue(_username); String pass = start.getAttributeValue(_password); String meth = start.getAttributeValue(_auth_method); if (meth == null || !("basic".equals(meth.toLowerCase()) || "digest".equals(meth.toLowerCase()))) { throw XProcException.stepError(3, "Unsupported auth-method: " + meth); } String host = requestURI.getHost(); int port = requestURI.getPort(); AuthScope scope = new AuthScope(host, port); UsernamePasswordCredentials cred = new UsernamePasswordCredentials(user, pass); client.getState().setCredentials(scope, cred); } iter = start.axisIterator(Axis.CHILD); XdmNode body = null; while (iter.hasNext()) { XdmNode event = (XdmNode) iter.next(); // FIXME: What about non-whitespace text nodes? if (event.getNodeKind() == XdmNodeKind.ELEMENT) { if (body != null) { throw new UnsupportedOperationException("Elements follow c:multipart or c:body"); } if (XProcConstants.c_header.equals(event.getNodeName())) { headers.add(new Header(event.getAttributeValue(_name), event.getAttributeValue(_value))); } else if (XProcConstants.c_multipart.equals(event.getNodeName()) || XProcConstants.c_body.equals(event.getNodeName())) { body = event; } else { throw new UnsupportedOperationException("Unexpected request element: " + event.getNodeName()); } } } HttpMethodBase httpResult; if (method == null) { throw new XProcException("Method must be specified."); } if ("get".equals(method.toLowerCase())) { httpResult = doGet(); } else if ("post".equals(method.toLowerCase())) { httpResult = doPost(body); } else if ("put".equals(method.toLowerCase())) { httpResult = doPut(body); } else if ("head".equals(method.toLowerCase())) { httpResult = doHead(); } else { throw new UnsupportedOperationException("Unrecognized http method: " + method); } TreeWriter tree = new TreeWriter(runtime); tree.startDocument(requestURI); try { // Execute the method. int statusCode = client.executeMethod(httpResult); String contentType = getContentType(httpResult); if (overrideContentType != null) { if ((xmlContentType(contentType) && overrideContentType.startsWith("image/")) || (contentType.startsWith("text/") && overrideContentType.startsWith("image/")) || (contentType.startsWith("image/") && xmlContentType(overrideContentType)) || (contentType.startsWith("image/") && overrideContentType.startsWith("text/")) || (contentType.startsWith("multipart/") && !overrideContentType.startsWith("multipart/")) || (!contentType.startsWith("multipart/") && overrideContentType.startsWith("multipart/"))) { throw XProcException.stepError(30); } //System.err.println(overrideContentType + " overrides " + contentType); contentType = overrideContentType; } if (detailed) { tree.addStartElement(XProcConstants.c_response); tree.addAttribute(_status, "" + statusCode); tree.startContent(); for (Header header : httpResult.getResponseHeaders()) { // I don't understand why/how HeaderElement parsing works. I get very weird results. // So I'm just going to go the long way around... String h = header.toString(); int cp = h.indexOf(":"); String name = header.getName(); String value = h.substring(cp + 1).trim(); tree.addStartElement(XProcConstants.c_header); tree.addAttribute(_name, name); tree.addAttribute(_value, value); tree.startContent(); tree.addEndElement(); } if (statusOnly) { // Skip reading the result } else { // Read the response body. InputStream bodyStream = httpResult.getResponseBodyAsStream(); readBodyContent(tree, bodyStream, httpResult); } tree.addEndElement(); } else { if (statusOnly) { // Skip reading the result } else { // Read the response body. InputStream bodyStream = httpResult.getResponseBodyAsStream(); readBodyContent(tree, bodyStream, httpResult); } } } catch (Exception e) { throw new XProcException(e); } finally { // Release the connection. httpResult.releaseConnection(); } tree.endDocument(); XdmNode resultNode = tree.getResult(); result.write(resultNode); }
From source file:helma.main.Server.java
/** * The main method of the Server. Basically, we set up Applications and than * periodically check for changes in the apps.properties file, shutting down * apps or starting new ones.//w ww . j a v a 2s . c om */ public void run() { try { if (config.hasXmlrpcPort()) { InetSocketAddress xmlrpcPort = config.getXmlrpcPort(); String xmlparser = sysProps.getProperty("xmlparser"); if (xmlparser != null) { XmlRpc.setDriver(xmlparser); } if (xmlrpcPort.getAddress() != null) { xmlrpc = new WebServer(xmlrpcPort.getPort(), xmlrpcPort.getAddress()); } else { xmlrpc = new WebServer(xmlrpcPort.getPort()); } if (paranoid) { xmlrpc.setParanoid(true); String xallow = sysProps.getProperty("allowXmlRpc"); if (xallow != null) { StringTokenizer st = new StringTokenizer(xallow, " ,;"); while (st.hasMoreTokens()) xmlrpc.acceptClient(st.nextToken()); } } xmlrpc.start(); logger.info("Starting XML-RPC server on port " + (xmlrpcPort)); } appManager = new ApplicationManager(appsProps, this); if (xmlrpc != null) { xmlrpc.addHandler("$default", appManager); } // add shutdown hook to close running apps and servers on exit shutdownhook = new HelmaShutdownHook(); Runtime.getRuntime().addShutdownHook(shutdownhook); } catch (Exception x) { throw new RuntimeException("Error setting up Server", x); } // set the security manager. // the default implementation is helma.main.HelmaSecurityManager. try { String secManClass = sysProps.getProperty("securityManager"); if (secManClass != null) { SecurityManager secMan = (SecurityManager) Class.forName(secManClass).newInstance(); System.setSecurityManager(secMan); logger.info("Setting security manager to " + secManClass); } } catch (Exception x) { logger.error("Error setting security manager", x); } // start embedded web server if (jetty != null) { try { jetty.start(); } catch (Exception m) { throw new RuntimeException("Error starting embedded web server", m); } } // start applications appManager.startAll(); while (Thread.currentThread() == mainThread) { try { Thread.sleep(3000L); } catch (InterruptedException ie) { } try { appManager.checkForChanges(); } catch (Exception x) { logger.warn("Caught in app manager loop: " + x); } } }
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 w w. j a v a2s . 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.synapse.transport.passthru.core.PassThroughListeningIOReactorManager.java
/** * Start Endpoint in IOReactor which is external to PTT Axis2 Listeners started at server startup * * @param inetSocketAddress Socket Address of starting endpoint * @param nHttpServerEventHandler ServerHandler responsible for handle events of port * @param endpointName Endpoint Name * @return Is Endpoint started/* w w w .j a va 2 s.c o m*/ */ public boolean startDynamicPTTEndpoint(InetSocketAddress inetSocketAddress, NHttpServerEventHandler nHttpServerEventHandler, String endpointName) { try { // get Shared IO Reactor and Start Endpoint ListenerEndpoint endpoint = startEndpoint(inetSocketAddress, getSharedIOReactor(nHttpServerEventHandler, endpointName), endpointName); if (endpoint != null) { portServerHandlerMapper.put(inetSocketAddress.getPort(), nHttpServerEventHandler); dynamicPTTListeningEndpointMapper.put(inetSocketAddress.getPort(), endpoint); return true; } else { return false; } } catch (Exception e) { log.error("Cannot Start Endpoint for " + endpointName, e); return false; } }
From source file:org.apache.hadoop.hdfs.shortcircuit.DomainSocketFactory.java
/** * Get information about a domain socket path. * * @param addr The inet address to use. * @param conf The client configuration. * * @return Information about the socket path. *///from w w w .j a v a 2 s . co m public PathInfo getPathInfo(InetSocketAddress addr, DFSClient.Conf conf) { // If there is no domain socket path configured, we can't use domain // sockets. if (conf.getDomainSocketPath().isEmpty()) return PathInfo.NOT_CONFIGURED; // If we can't do anything with the domain socket, don't create it. if (!conf.isDomainSocketDataTraffic() && (!conf.isShortCircuitLocalReads() || conf.isUseLegacyBlockReaderLocal())) { return PathInfo.NOT_CONFIGURED; } // If the DomainSocket code is not loaded, we can't create // DomainSocket objects. if (DomainSocket.getLoadingFailureReason() != null) { return PathInfo.NOT_CONFIGURED; } // UNIX domain sockets can only be used to talk to local peers if (!DFSClient.isLocalAddress(addr)) return PathInfo.NOT_CONFIGURED; String escapedPath = DomainSocket.getEffectivePath(conf.getDomainSocketPath(), addr.getPort()); PathState status = pathMap.getIfPresent(escapedPath); if (status == null) { return new PathInfo(escapedPath, PathState.VALID); } else { return new PathInfo(escapedPath, status); } }
From source file:org.apache.hadoop.mapreduce.v2.app.job.impl.TaskAttemptImpl.java
private static void sendJHStartEventForAssignedFailTask(TaskAttemptImpl taskAttempt) { if (null == taskAttempt.container) { return;// ww w .j ava 2s .co 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: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);// www .ja v a 2 s . co m // 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(); }