List of usage examples for java.net InetSocketAddress getPort
public final int getPort()
From source file:com.xmlcalabash.library.HttpRequest.java
public void gorun() throws SaxonApiException { super.gorun(); XdmNode requestDoc = source.read(stepContext); XdmNode start = S9apiUtils.getDocumentElement(requestDoc); if (!c_request.equals(start.getNodeName())) { throw XProcException.stepError(40); }/*w w w .j a v a 2s .co m*/ // 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(step.getNode(), "Unsupported attribute on c:request for p:http-request: " + name); } } } String send = step.getExtensionAttribute(cx_send_binary); encodeBinary = !"true".equals(send); method = start.getAttributeValue(_method); statusOnly = "true".equals(start.getAttributeValue(_status_only)); detailed = "true".equals(start.getAttributeValue(_detailed)); overrideContentType = start.getAttributeValue(_override_content_type); if (method == null) { throw XProcException.stepError(6); } if (statusOnly && !detailed) { throw XProcException.stepError(4); } if (start.getAttributeValue(_href) == null) { throw new XProcException(step.getNode(), "The 'href' attribute must be specified on c:request for p:http-request"); } requestURI = start.getBaseURI().resolve(start.getAttributeValue(_href)); if ("file".equals(requestURI.getScheme())) { doFile(); return; } // What about cookies String saveCookieKey = step.getExtensionAttribute(cx_save_cookies); String useCookieKeys = step.getExtensionAttribute(cx_use_cookies); String cookieKey = step.getExtensionAttribute(cx_cookies); if (saveCookieKey == null) { saveCookieKey = cookieKey; } if (useCookieKeys == null) { useCookieKeys = cookieKey; } client = new HttpClient(); client.getParams().setCookiePolicy(CookiePolicy.RFC_2109); client.getParams().setParameter("http.protocol.single-cookie-header", true); HttpState state = client.getState(); if (useCookieKeys != null) { for (String key : useCookieKeys.split("\\s+")) { for (Cookie cookie : runtime.getCookies(key)) { state.addCookie(cookie); } } } 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); if ("basic".equals(meth.toLowerCase())) { client.getParams().setAuthenticationPreemptive(true); } } 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())) { String name = event.getAttributeValue(_name); if (name == null) { continue; // this can't happen, right? } if (name.toLowerCase().equals("content-type")) { // We'll deal with the content-type header later headerContentType = event.getAttributeValue(_value).toLowerCase(); } else { 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()); } } } String lcMethod = method.toLowerCase(); // You can only have a body on PUT or POST if (body != null && !("put".equals(lcMethod) || "post".equals(lcMethod))) { throw XProcException.stepError(5); } HttpMethodBase httpResult; if ("get".equals(lcMethod)) { httpResult = doGet(); } else if ("post".equals(lcMethod)) { httpResult = doPost(body); } else if ("put".equals(lcMethod)) { httpResult = doPut(body); } else if ("head".equals(lcMethod)) { httpResult = doHead(); } else if ("delete".equals(lcMethod)) { httpResult = doDelete(); } 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); // Deal with cookies if (saveCookieKey != null) { runtime.clearCookies(saveCookieKey); state = client.getState(); Cookie[] cookies = state.getCookies(); for (Cookie cookie : cookies) { runtime.addCookie(saveCookieKey, cookie); } } 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(); if (bodyStream != null) { readBodyContent(tree, bodyStream, httpResult); } } tree.addEndElement(); } else { if (statusOnly) { // Skip reading the result } else { // Read the response body. InputStream bodyStream = httpResult.getResponseBodyAsStream(); if (bodyStream != null) { readBodyContent(tree, bodyStream, httpResult); } else { throw XProcException.dynamicError(6); } } } } catch (Exception e) { throw new XProcException(e); } finally { // Release the connection. httpResult.releaseConnection(); } tree.endDocument(); XdmNode resultNode = tree.getResult(); result.write(stepContext, resultNode); }
From source file:org.apache.hama.bsp.GroomServer.java
public synchronized void initialize() throws IOException { if (this.conf.get(Constants.PEER_HOST) != null) { this.localHostname = conf.get(Constants.PEER_HOST); }//w w w .ja va 2 s. c om if (localHostname == null) { this.localHostname = DNS.getDefaultHost(conf.get("bsp.dns.interface", "default"), conf.get("bsp.dns.nameserver", "default")); } // check local disk checkLocalDirs(getLocalDirs()); deleteLocalFiles(SUBDIR); // Clear out state tables this.tasks.clear(); this.runningJobs = new TreeMap<BSPJobID, RunningJob>(); this.runningTasks = new ConcurrentHashMap<TaskAttemptID, TaskInProgress>(); this.finishedTasks = new LinkedHashMap<TaskAttemptID, TaskInProgress>(); this.conf.set(Constants.PEER_HOST, localHostname); this.conf.set(Constants.GROOM_RPC_HOST, localHostname); this.maxCurrentTasks = conf.getInt(Constants.MAX_TASKS_PER_GROOM, 3); this.assignedPeerNames = new HashMap<TaskAttemptID, Integer>(2 * this.maxCurrentTasks); int rpcPort = -1; String rpcAddr = null; if (false == this.initialized) { rpcAddr = conf.get(Constants.GROOM_RPC_HOST, Constants.DEFAULT_GROOM_RPC_HOST); rpcPort = conf.getInt(Constants.GROOM_RPC_PORT, Constants.DEFAULT_GROOM_RPC_PORT); if (-1 == rpcPort || null == rpcAddr) throw new IllegalArgumentException("Error rpc address " + rpcAddr + " port" + rpcPort); this.workerServer = RPC.getServer(this, rpcAddr, rpcPort, conf); this.workerServer.start(); this.rpcServer = rpcAddr + ":" + rpcPort; } server = new HttpServer("groomserver", rpcAddr, conf.getInt("bsp.http.groomserver.port", Constants.DEFAULT_GROOM_INFO_SERVER), true, conf); FileSystem local = FileSystem.getLocal(conf); server.setAttribute("groom.server", this); server.setAttribute("local.file.system", local); server.setAttribute("conf", conf); server.setAttribute("log", LOG); server.addServlet("taskLog", "/tasklog", TaskLogServlet.class); LOG.info("starting webserver: " + rpcAddr); server.start(); String address = BSPNetUtils.getServerAddress(conf, "bsp.groom.report.bindAddress", "bsp.groom.report.port", "bsp.groom.report.address"); InetSocketAddress socAddr = BSPNetUtils.createSocketAddr(address); String bindAddress = socAddr.getHostName(); int tmpPort = socAddr.getPort(); // RPC initialization this.taskReportServer = RPC.getServer(this, bindAddress, tmpPort, conf.getInt("hama.groom.report.server.handler.threads.num", 5), false, this.conf); this.taskReportServer.start(); // get the assigned address this.taskReportAddress = taskReportServer.getListenerAddress(); this.conf.set("bsp.groom.report.address", taskReportAddress.getHostName() + ":" + taskReportAddress.getPort()); LOG.info("TaskReportServer up at: " + this.taskReportAddress); this.groomHostName = rpcAddr; this.groomServerName = "groomd_" + this.rpcServer.replace(':', '_'); LOG.info("Starting groom: " + this.rpcServer); // establish the communication link to bsp master this.masterClient = (MasterProtocol) RPC.waitForProxy(MasterProtocol.class, HamaRPCProtocolVersion.versionID, bspMasterAddr, conf); this.instructor = new Instructor(); this.instructor.bind(DispatchTasksDirective.class, new DispatchTasksHandler()); instructor.start(); if (this.taskMonitorService == null) { this.taskMonitorService = Executors.newScheduledThreadPool(1); long monitorPeriod = this.conf.getLong(Constants.GROOM_PING_PERIOD, Constants.DEFAULT_GROOM_PING_PERIOD); if (monitorPeriod > 0) { this.taskMonitorService.scheduleWithFixedDelay(new BSPTasksMonitor(), 1000, monitorPeriod, TimeUnit.MILLISECONDS); } } if (conf.getBoolean("bsp.monitor.enabled", false)) { new Monitor(conf, zk, this.groomServerName).start(); } if (conf.getBoolean("bsp.monitor.fd.enabled", false)) { this.sensor.set(FDProvider.createSensor( conf.getClass("bsp.monitor.fd.sensor.class", UDPSensor.class, Sensor.class), (HamaConfiguration) conf)); this.sensor.get().start(); } // enroll in bsp master once the GroomServer is ready to accept tasks if (-1 == rpcPort || null == rpcAddr) throw new IllegalArgumentException("Error rpc address " + rpcAddr + " port" + rpcPort); if (!this.masterClient.register(new GroomServerStatus(groomServerName, cloneAndResetRunningTaskStatuses(), failures, maxCurrentTasks, this.rpcServer, groomHostName))) { LOG.error("There is a problem in establishing communication" + " link with BSPMaster"); throw new IOException("There is a problem in establishing" + " communication link with BSPMaster."); } this.running = true; this.initialized = true; }
From source file:org.apache.james.protocols.smtp.AbstractSMTPServerTest.java
@Test public void testHeloEnforcementDisabled() throws Exception { TestMessageHook hook = new TestMessageHook(); InetSocketAddress address = new InetSocketAddress("127.0.0.1", TestUtils.getFreePort()); ProtocolServer server = null;/* w ww .j a v a 2 s .c o m*/ try { Protocol protocol = createProtocol(hook); ((SMTPConfigurationImpl) protocol.getConfiguration()).setHeloEhloEnforcement(false); server = createServer(protocol, address); server.bind(); SMTPClient client = createClient(); client.connect(address.getAddress().getHostAddress(), address.getPort()); assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode())); client.setSender(SENDER); assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode())); client.quit(); assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode())); client.disconnect(); Iterator<MailEnvelope> queued = hook.getQueued().iterator(); assertFalse(queued.hasNext()); } finally { if (server != null) { server.unbind(); } } }
From source file:net.spy.memcached.CouchbaseConnection.java
private List<CouchbaseNode> createConnections(List<InetSocketAddress> addrs) throws IOException { List<CouchbaseNode> nodeList = new LinkedList<CouchbaseNode>(); for (InetSocketAddress a : addrs) { HttpParams params = new SyncBasicHttpParams(); params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000) .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.USER_AGENT, "Spymemcached Client/1.1"); HttpProcessor httpproc = new ImmutableHttpProcessor( new HttpRequestInterceptor[] { new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue(), }); AsyncNHttpClientHandler protocolHandler = new AsyncNHttpClientHandler(httpproc, new MyHttpRequestExecutionHandler(), new DefaultConnectionReuseStrategy(), new DirectByteBufferAllocator(), params); protocolHandler.setEventListener(new EventLogger()); AsyncConnectionManager connMgr = new AsyncConnectionManager(new HttpHost(a.getHostName(), a.getPort()), NUM_CONNS, protocolHandler, params); getLogger().info("Added %s to connect queue", a); CouchbaseNode node = connFactory.createCouchDBNode(a, connMgr); node.init();/* w w w .j av a 2s . c o m*/ nodeList.add(node); } return nodeList; }
From source file:org.dcache.srm.client.FlexibleCredentialSSLConnectionSocketFactory.java
@Override public Socket connectSocket(final int connectTimeout, final Socket socket, final HttpHost host, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context) throws IOException { Args.notNull(host, "HTTP host"); Args.notNull(remoteAddress, "Remote address"); final Socket sock = socket != null ? socket : createSocket(context); if (localAddress != null) { sock.bind(localAddress);/*from w ww. ja v a 2s .co m*/ } try { if (connectTimeout > 0 && sock.getSoTimeout() == 0) { sock.setSoTimeout(connectTimeout); } LOGGER.debug("Connecting socket to {} with timeout {}", remoteAddress, connectTimeout); sock.connect(remoteAddress, connectTimeout); } catch (final IOException ex) { try { sock.close(); } catch (final IOException ignore) { } throw ex; } // Setup SSL layering if necessary if (sock instanceof SSLSocket) { final SSLSocket sslsock = (SSLSocket) sock; LOGGER.debug("Starting handshake"); sslsock.startHandshake(); verifyHostname(sslsock, host.getHostName()); return sock; } else { return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), context); } }
From source file:org.apache.james.protocols.smtp.AbstractSMTPServerTest.java
@Test public void testInvalidNoBracketsEnformance() throws Exception { TestMessageHook hook = new TestMessageHook(); InetSocketAddress address = new InetSocketAddress("127.0.0.1", TestUtils.getFreePort()); ProtocolServer server = null;/*from w ww .j a v a 2 s . co m*/ try { Protocol protocol = createProtocol(hook); ((SMTPConfigurationImpl) protocol.getConfiguration()).setUseAddressBracketsEnforcement(false); server = createServer(protocol, address); server.bind(); SMTPClient client = createClient(); client.connect(address.getAddress().getHostAddress(), address.getPort()); assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode())); client.helo("localhost"); assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode())); client.mail(SENDER); assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode())); client.addRecipient(RCPT1); assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode())); client.quit(); assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode())); client.disconnect(); Iterator<MailEnvelope> queued = hook.getQueued().iterator(); assertFalse(queued.hasNext()); } finally { if (server != null) { server.unbind(); } } }
From source file:com.all.dht.DhtManager.java
private void processOversizedValueRequest(AllMessage<String> message) { String senderId = message.getProperty(MESSAGE_SENDER); if (senderId != null && !dht.getLocalNodeID().toHexString().equals(senderId)) { log.info("Processing OVERSIZED_DHT_VALUE_REQUEST_TYPE for key : " + message.getBody()); Contact sender = dht.getRouteTable().get(KUID.createWithHexString(senderId)); InetSocketAddress senderAddress = (InetSocketAddress) sender.getContactAddress(); byte[] oversizedValue = dhtFileUtils.readFromFileSystem(message.getBody()); if (oversizedValue != null) { AllMessage<String> response = new AllMessage<String>(OVERSIZED_DHT_VALUE_RESPONSE_TYPE, new String(oversizedValue)); response.putProperty(MESSAGE_SENDER, dht.getLocalNodeID().toHexString()); response.putProperty(DHT_PRIMARY_KEY, message.getBody()); networkingService.send(dht.getLocalNodeID().toHexString(), response, senderAddress.getAddress().getHostAddress(), senderAddress.getPort() + 1); }//from w w w .j a v a 2s . c o m } }
From source file:org.apache.synapse.transport.nhttp.HttpCoreNIOListener.java
/** * Start specific end points given by InetSockeAddress list * * @param endpointsClosed InetSocketAddresses of endpoints to be started * @throws AxisFault//from ww w . ja va 2s . c om */ private void startSpecificEndpoints(List<InetSocketAddress> endpointsClosed) throws AxisFault { Queue<ListenerEndpoint> endpoints = new LinkedList<ListenerEndpoint>(); // Ensure simple but stable order List<InetSocketAddress> addressList = endpointsClosed; Collections.sort(addressList, new Comparator<InetSocketAddress>() { public int compare(InetSocketAddress a1, InetSocketAddress a2) { String s1 = a1.toString(); String s2 = a2.toString(); return s1.compareTo(s2); } }); for (InetSocketAddress address : addressList) { endpoints.add(ioReactor.listen(address)); } // Wait for the endpoint to become ready, i.e. for the listener to start accepting // requests. while (!endpoints.isEmpty()) { ListenerEndpoint endpoint = endpoints.remove(); try { endpoint.waitFor(); if (log.isInfoEnabled()) { InetSocketAddress address = (InetSocketAddress) endpoint.getAddress(); if (!address.isUnresolved()) { log.info(name + " started on " + address.getHostName() + ":" + address.getPort()); } else { log.info(name + " started on " + address); } } } catch (InterruptedException e) { log.warn("Listener startup was interrupted"); break; } } }
From source file:org.apache.synapse.transport.nhttp.HttpCoreNIOListener.java
private void startEndpoints() throws AxisFault { Queue<ListenerEndpoint> endpoints = new LinkedList<ListenerEndpoint>(); Set<InetSocketAddress> addressSet = new HashSet<InetSocketAddress>(); addressSet.addAll(connFactory.getBindAddresses()); if (NHttpConfiguration.getInstance().getMaxActiveConnections() != -1) { addMaxConnectionCountController(NHttpConfiguration.getInstance().getMaxActiveConnections()); }/* w ww . j a v a 2s . c o m*/ if (listenerContext.getBindAddress() != null) { addressSet.add(new InetSocketAddress(listenerContext.getBindAddress(), listenerContext.getPort())); } if (addressSet.isEmpty()) { addressSet.add(new InetSocketAddress(listenerContext.getPort())); } // Ensure simple but stable order List<InetSocketAddress> addressList = new ArrayList<InetSocketAddress>(addressSet); Collections.sort(addressList, new Comparator<InetSocketAddress>() { public int compare(InetSocketAddress a1, InetSocketAddress a2) { String s1 = a1.toString(); String s2 = a2.toString(); return s1.compareTo(s2); } }); for (InetSocketAddress address : addressList) { endpoints.add(ioReactor.listen(address)); } // Wait for the endpoint to become ready, i.e. for the listener to start accepting // requests. while (!endpoints.isEmpty()) { ListenerEndpoint endpoint = endpoints.remove(); try { endpoint.waitFor(); if (log.isInfoEnabled()) { InetSocketAddress address = (InetSocketAddress) endpoint.getAddress(); if (!address.isUnresolved()) { log.info(name + " started on " + address.getHostName() + ":" + address.getPort()); } else { log.info(name + " started on " + address); } } } catch (InterruptedException e) { log.warn("Listener startup was interrupted"); break; } } }