List of usage examples for java.net InetSocketAddress getHostName
public final String getHostName()
From source file:org.apache.hadoop.mapred.LinuxTaskController.java
@Override public void initializeJob(String user, String jobid, Path credentials, Path jobConf, TaskUmbilicalProtocol taskTracker, InetSocketAddress ttAddr) throws IOException { List<String> command = new ArrayList<String>(Arrays.asList(taskControllerExe, user, localStorage.getDirsString(), Integer.toString(Commands.INITIALIZE_JOB.getValue()), jobid, credentials.toUri().getPath().toString(), jobConf.toUri().getPath().toString())); File jvm = // use same jvm as parent new File(new File(System.getProperty("java.home"), "bin"), "java"); command.add(jvm.toString());//w ww. j a v a2 s. co m command.add("-classpath"); command.add(System.getProperty("java.class.path")); command.add("-Dhadoop.log.dir=" + TaskLog.getBaseLogDir()); command.add("-Dhadoop.root.logger=INFO,console"); command.add("-Djava.library.path=" + System.getProperty("java.library.path")); command.add(JobLocalizer.class.getName()); // main of JobLocalizer command.add(user); command.add(jobid); // add the task tracker's reporting address command.add(ttAddr.getHostName()); command.add(Integer.toString(ttAddr.getPort())); String[] commandArray = command.toArray(new String[0]); ShellCommandExecutor shExec = new ShellCommandExecutor(commandArray); if (LOG.isDebugEnabled()) { LOG.debug("initializeJob: " + Arrays.toString(commandArray)); } try { shExec.execute(); if (LOG.isDebugEnabled()) { logOutput(shExec.getOutput()); } } catch (ExitCodeException e) { int exitCode = shExec.getExitCode(); logOutput(shExec.getOutput()); throw new IOException("Job initialization failed (" + exitCode + ") with output: " + shExec.getOutput(), e); } }
From source file:name.persistent.behaviours.RemoteDomainSupport.java
private HttpResponse resolveRemotePURL(InetSocketAddress addr, String source, String qs, String accept, String language, Set<String> via) throws IOException, InterruptedException { HTTPObjectClient client = HTTPObjectClient.getInstance(); String url = qs == null ? source : source + "?" + qs; BasicHttpRequest req = new BasicHttpRequest("GET", url); if (accept != null) { req.setHeader("Accept", accept); }/*from ww w . j av a2 s . c o m*/ if (language != null) { req.setHeader("Accept-Language", language); } StringBuilder sb = new StringBuilder(); for (String v : via) { if (v.contains(VIA) && (v.endsWith(VIA) || v.contains(VIA + ","))) throw new InternalServerError("Request Loop Detected\n" + via + "\n" + VIA); if (sb.length() > 0) { sb.append(","); } sb.append(v); } sb.append(VIA); req.setHeader("Via", sb.toString()); try { HttpResponse resp = client.service(addr, req); if (!resp.containsHeader("Via")) { String original = "1.1 " + addr.getHostName(); if (addr.getPort() != 80 && addr.getPort() != 443) { original += ":" + addr.getPort(); } resp.addHeader("Via", original); } StatusLine status = resp.getStatusLine(); if (status.getStatusCode() >= 500) { ProtocolVersion ver = status.getProtocolVersion(); String phrase = status.getReasonPhrase(); resp.setStatusLine(new BasicStatusLine(ver, 502, phrase)); blackList.put(addr, Boolean.TRUE); return resp; } else { return resp; } } catch (GatewayTimeout e) { blackList.put(addr, Boolean.TRUE); return null; } }
From source file:com.budrotech.jukebox.service.ssl.SSLSocketFactory.java
/** * @since 4.1// w ww. j a v a 2s .c o m */ public Socket connectSocket(final Socket sock, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpParams params) throws IOException { if (remoteAddress == null) { throw new IllegalArgumentException("Remote address may not be null"); } if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } SSLSocket sslSocket = (SSLSocket) (sock != null ? sock : createSocket()); if (localAddress != null) { // sslSocket.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params)); sslSocket.bind(localAddress); } int connTimeout = HttpConnectionParams.getConnectionTimeout(params); int soTimeout = HttpConnectionParams.getSoTimeout(params); try { sslSocket.connect(remoteAddress, connTimeout); } catch (SocketTimeoutException ex) { throw new ConnectTimeoutException(String.format("Connect to %s/%s timed out", remoteAddress.getHostName(), remoteAddress.getAddress())); } sslSocket.setSoTimeout(soTimeout); if (this.hostnameVerifier != null) { try { this.hostnameVerifier.verify(remoteAddress.getHostName(), sslSocket); // verifyHostName() didn't blowup - good! } catch (IOException iox) { // close the socket before re-throwing the exception try { sslSocket.close(); } catch (Exception x) { /*ignore*/ } throw iox; } } return sslSocket; }
From source file:org.apache.hadoop.hdfs.server.namenode.NameNode.java
/** * Initialize name-node.//from w ww .j av a 2s.c o m * * @param conf the configuration */ private void initialize(Configuration conf) throws IOException { InetSocketAddress socAddr = NameNode.getAddress(conf); UserGroupInformation.setConfiguration(conf); SecurityUtil.login(conf, DFSConfigKeys.DFS_NAMENODE_KEYTAB_FILE_KEY, DFSConfigKeys.DFS_NAMENODE_USER_NAME_KEY, socAddr.getHostName()); int handlerCount = conf.getInt("dfs.namenode.handler.count", 10); // set service-level authorization security policy if (serviceAuthEnabled = conf.getBoolean(ServiceAuthorizationManager.SERVICE_AUTHORIZATION_CONFIG, false)) { ServiceAuthorizationManager.refresh(conf, new HDFSPolicyProvider()); } myMetrics = NameNodeInstrumentation.create(conf); this.namesystem = new FSNamesystem(this, conf); if (UserGroupInformation.isSecurityEnabled()) { namesystem.activateSecretManager(); } // create rpc server InetSocketAddress dnSocketAddr = getServiceRpcServerAddress(conf); if (dnSocketAddr != null) { int serviceHandlerCount = conf.getInt(DFSConfigKeys.DFS_NAMENODE_SERVICE_HANDLER_COUNT_KEY, DFSConfigKeys.DFS_NAMENODE_SERVICE_HANDLER_COUNT_DEFAULT); this.serviceRpcServer = RPC.getServer(this, dnSocketAddr.getHostName(), dnSocketAddr.getPort(), serviceHandlerCount, false, conf, namesystem.getDelegationTokenSecretManager()); this.serviceRPCAddress = this.serviceRpcServer.getListenerAddress(); setRpcServiceServerAddress(conf); } this.server = RPC.getServer(this, socAddr.getHostName(), socAddr.getPort(), handlerCount, false, conf, namesystem.getDelegationTokenSecretManager()); // The rpc-server port can be ephemeral... ensure we have the correct info this.serverAddress = this.server.getListenerAddress(); FileSystem.setDefaultUri(conf, getUri(serverAddress)); LOG.info("Namenode up at: " + this.serverAddress); startHttpServer(conf); this.server.start(); //start RPC server if (serviceRpcServer != null) { serviceRpcServer.start(); } startTrashEmptier(conf); }
From source file:org.apache.chemistry.opencmis.client.bindings.spi.http.ApacheClientHttpInvoker.java
/** * Builds a SSL Socket Factory for the Apache HTTP Client. *///from w ww .ja v a 2 s . c om private SchemeLayeredSocketFactory getSSLSocketFactory(final UrlBuilder url, final BindingSession session) { // get authentication provider AuthenticationProvider authProvider = CmisBindingsHelper.getAuthenticationProvider(session); // check SSL Socket Factory final SSLSocketFactory sf = authProvider.getSSLSocketFactory(); if (sf == null) { // no custom factory -> return default factory return org.apache.http.conn.ssl.SSLSocketFactory.getSocketFactory(); } // check hostame verifier and use default if not set final HostnameVerifier hv = (authProvider.getHostnameVerifier() == null ? new BrowserCompatHostnameVerifier() : authProvider.getHostnameVerifier()); if (hv instanceof X509HostnameVerifier) { return new org.apache.http.conn.ssl.SSLSocketFactory(sf, (X509HostnameVerifier) hv); } // build new socket factory return new SchemeLayeredSocketFactory() { @Override public boolean isSecure(Socket sock) { return true; } @Override public Socket createSocket(HttpParams params) throws IOException { return sf.createSocket(); } @Override public Socket connectSocket(final Socket socket, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpParams params) throws IOException { Socket sock = socket != null ? socket : createSocket(params); if (localAddress != null) { sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params)); sock.bind(localAddress); } int connTimeout = HttpConnectionParams.getConnectionTimeout(params); int soTimeout = HttpConnectionParams.getSoTimeout(params); try { sock.setSoTimeout(soTimeout); sock.connect(remoteAddress, connTimeout); } catch (SocketTimeoutException ex) { closeSocket(sock); throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out!"); } String host; if (remoteAddress instanceof HttpInetSocketAddress) { host = ((HttpInetSocketAddress) remoteAddress).getHttpHost().getHostName(); } else { host = remoteAddress.getHostName(); } SSLSocket sslSocket; if (sock instanceof SSLSocket) { sslSocket = (SSLSocket) sock; } else { int port = remoteAddress.getPort(); sslSocket = (SSLSocket) sf.createSocket(sock, host, port, true); } verify(hv, host, sslSocket); return sslSocket; } @Override public Socket createLayeredSocket(final Socket socket, final String host, final int port, final HttpParams params) throws IOException { SSLSocket sslSocket = (SSLSocket) sf.createSocket(socket, host, port, true); verify(hv, host, sslSocket); return sslSocket; } }; }
From source file:com.github.hrpc.rpc.Client.java
/** * Make a call, passing <code>rpcRequest</code>, to the IPC server defined by * <code>remoteId</code>, returning the rpc respond. * * @param rpcKind//from w w w. jav a 2 s .co m * @param rpcRequest - contains serialized method and method parameters * @param remoteId - the target rpc server * @param serviceClass - service class for RPC * @returns the rpc response * Throws exceptions if there are network problems or if the remote code * threw an exception. */ public Writable call(RPC.RpcKind rpcKind, Writable rpcRequest, ConnectionId remoteId, int serviceClass) throws IOException { final Call call = createCall(rpcKind, rpcRequest); Connection connection = getConnection(remoteId, call, serviceClass); try { connection.sendRpcRequest(call); // send the rpc request } catch (RejectedExecutionException e) { throw new IOException("connection has been closed", e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); LOG.warn("interrupted waiting to send rpc request to server", e); throw new IOException(e); } boolean interrupted = false; synchronized (call) { while (!call.done) { try { call.wait(); // wait for the result } catch (InterruptedException ie) { // save the fact that we were interrupted interrupted = true; } } if (interrupted) { // set the interrupt flag now that we are done waiting Thread.currentThread().interrupt(); } if (call.error != null) { if (call.error instanceof RemoteException) { call.error.fillInStackTrace(); throw call.error; } else { // local exception InetSocketAddress address = connection.getRemoteAddress(); throw NetUtils.wrapException(address.getHostName(), address.getPort(), NetUtils.getHostname(), 0, call.error); } } else { return call.getRpcResponse(); } } }
From source file:net.java.sip.communicator.service.httputil.SSLSocketFactoryEx.java
/** * @since 4.1/*from w w w . ja v a 2 s .co m*/ */ @Override public Socket connectSocket(final Socket socket, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { if (remoteAddress == null) { throw new IllegalArgumentException("Remote address may not be null"); } if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } Socket sock = socket != null ? socket : this.context.getSocketFactory().createSocket(); if (localAddress != null) { sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params)); sock.bind(localAddress); } int connTimeout = HttpConnectionParams.getConnectionTimeout(params); int soTimeout = HttpConnectionParams.getSoTimeout(params); try { sock.setSoTimeout(soTimeout); sock.connect(remoteAddress, connTimeout); } catch (SocketTimeoutException ex) { throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out"); } String hostname; if (remoteAddress instanceof HttpInetSocketAddress) { hostname = ((HttpInetSocketAddress) remoteAddress).getHttpHost().getHostName(); } else { hostname = remoteAddress.getHostName(); } SSLSocket sslsock; // Setup SSL layering if necessary if (sock instanceof SSLSocket) { sslsock = (SSLSocket) sock; } else { int port = remoteAddress.getPort(); sslsock = (SSLSocket) this.context.getSocketFactory().createSocket(sock, hostname, port, true); } return sslsock; }
From source file:com.hortonworks.hbase.replication.bridge.HBaseServer.java
/** * A convenience method to bind to a given address and report * better exceptions if the address is not a valid host. * @param socket the socket to bind//from w ww. jav a2 s. co m * @param address the address to bind to * @param backlog the number of connections allowed in the queue * @throws BindException if the address can't be bound * @throws UnknownHostException if the address isn't a valid host name * @throws IOException other random errors from bind */ public static void bind(ServerSocket socket, InetSocketAddress address, int backlog) throws IOException { try { socket.bind(address, backlog); } catch (BindException e) { BindException bindException = new BindException( "Problem binding to " + address + " : " + e.getMessage()); bindException.initCause(e); throw bindException; } catch (SocketException e) { // If they try to bind to a different host's address, give a better // error message. if ("Unresolved address".equals(e.getMessage())) { throw new UnknownHostException("Invalid hostname for server: " + address.getHostName()); } throw e; } }
From source file:org.apache.hadoop.hdfs.server.namenode.ClusterJspHelper.java
/** * Helper function that generates the decommissioning report. Connect to each * Namenode over http via JmxJsonServlet to collect the data nodes status. *//* w w w. j ava 2 s .c o m*/ DecommissionStatus generateDecommissioningReport() { String clusterid = ""; Configuration conf = new Configuration(); List<ConfiguredNNAddress> cnns = null; try { cnns = DFSUtil.flattenAddressMap(DFSUtil.getNNServiceRpcAddresses(conf)); } catch (Exception e) { // catch any exception encountered other than connecting to namenodes DecommissionStatus dInfo = new DecommissionStatus(clusterid, e); return dInfo; } // Outer map key is datanode. Inner map key is namenode and the value is // decom status of the datanode for the corresponding namenode Map<String, Map<String, String>> statusMap = new HashMap<String, Map<String, String>>(); // Map of exceptions encountered when connecting to namenode // key is namenode and value is exception Map<String, Exception> decommissionExceptions = new HashMap<String, Exception>(); List<String> unreportedNamenode = new ArrayList<String>(); for (ConfiguredNNAddress cnn : cnns) { InetSocketAddress isa = cnn.getAddress(); NamenodeMXBeanHelper nnHelper = null; try { nnHelper = new NamenodeMXBeanHelper(isa, conf); String mbeanProps = queryMbean(nnHelper.httpAddress, conf); if (clusterid.equals("")) { clusterid = nnHelper.getClusterId(mbeanProps); } nnHelper.getDecomNodeInfoForReport(statusMap, mbeanProps); } catch (Exception e) { // catch exceptions encountered while connecting to namenodes String nnHost = isa.getHostName(); decommissionExceptions.put(nnHost, e); unreportedNamenode.add(nnHost); continue; } } updateUnknownStatus(statusMap, unreportedNamenode); getDecommissionNodeClusterState(statusMap); return new DecommissionStatus(statusMap, clusterid, getDatanodeHttpPort(conf), decommissionExceptions); }
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); }/*from w ww. j av a 2 s . c om*/ // 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); }