use of java.net.ConnectException in project platform_external_apache-http by android.
the class DefaultClientConnectionOperator method openConnection.
// non-javadoc, see interface ClientConnectionOperator
public void openConnection(OperatedClientConnection conn, HttpHost target, InetAddress local, HttpContext context, HttpParams params) throws IOException {
if (conn == null) {
throw new IllegalArgumentException("Connection must not be null.");
}
if (target == null) {
throw new IllegalArgumentException("Target host must not be null.");
}
//@@@ is context allowed to be null?
if (params == null) {
throw new IllegalArgumentException("Parameters must not be null.");
}
if (conn.isOpen()) {
throw new IllegalArgumentException("Connection must not be open.");
}
final Scheme schm = schemeRegistry.getScheme(target.getSchemeName());
final SocketFactory sf = schm.getSocketFactory();
final SocketFactory plain_sf;
final LayeredSocketFactory layered_sf;
if (sf instanceof LayeredSocketFactory) {
plain_sf = staticPlainSocketFactory;
layered_sf = (LayeredSocketFactory) sf;
} else {
plain_sf = sf;
layered_sf = null;
}
InetAddress[] addresses = InetAddress.getAllByName(target.getHostName());
for (int i = 0; i < addresses.length; ++i) {
Socket sock = plain_sf.createSocket();
conn.opening(sock, target);
try {
Socket connsock = plain_sf.connectSocket(sock, addresses[i].getHostAddress(), schm.resolvePort(target.getPort()), local, 0, params);
if (sock != connsock) {
sock = connsock;
conn.opening(sock, target);
}
/*
* prepareSocket is called on the just connected
* socket before the creation of the layered socket to
* ensure that desired socket options such as
* TCP_NODELAY, SO_RCVTIMEO, SO_LINGER will be set
* before any I/O is performed on the socket. This
* happens in the common case as
* SSLSocketFactory.createSocket performs hostname
* verification which requires that SSL handshaking be
* performed.
*/
prepareSocket(sock, context, params);
if (layered_sf != null) {
Socket layeredsock = layered_sf.createSocket(sock, target.getHostName(), schm.resolvePort(target.getPort()), true);
if (layeredsock != sock) {
conn.opening(layeredsock, target);
}
conn.openCompleted(sf.isSecure(layeredsock), params);
} else {
conn.openCompleted(sf.isSecure(sock), params);
}
break;
// BEGIN android-changed
// catch SocketException to cover any kind of connect failure
} catch (SocketException ex) {
if (i == addresses.length - 1) {
final ConnectException cause;
if (ex instanceof ConnectException) {
cause = (ConnectException) ex;
} else {
cause = new ConnectException(ex.getMessage());
cause.initCause(ex);
}
throw new HttpHostConnectException(target, cause);
}
// END android-changed
} catch (ConnectTimeoutException ex) {
if (i == addresses.length - 1) {
throw ex;
}
}
}
}
use of java.net.ConnectException in project zm-mailbox by Zimbra.
the class LocalConfigCLI method exec.
private void exec(String[] args) {
CommandLine cl = null;
CommandLineParser parser = new GnuParser();
try {
cl = parser.parse(mOptions, args);
} catch (ParseException pe) {
Logging.error("Failed to parse command line: " + pe);
System.exit(1);
}
if (cl.hasOption("q")) {
Logging.setQuietMode(true);
}
if (cl.hasOption("h")) {
usage();
}
// Load known keys from BackupLC if available
loadExtensionLC("com.zimbra.cs.backup.BackupLC");
// Load known keys from ZimbraOpenOfficeExt if available
loadExtensionLC("com.zimbra.openoffice.config.OpenOfficeLC");
// Load known keys from ZimbraVoice if available
loadExtensionLC("com.zimbra.cs.voice.VoiceLC");
// info/docs for supported keys
if (cl.hasOption("i")) {
checkCompatibleOptions("i", "q", cl);
LocalConfig.printDoc(System.out, cl.getArgs(), false);
return;
}
// info/docs for all keys (hidden option)
if (cl.hasOption("all")) {
checkCompatibleOptions("all", "q", cl);
LocalConfig.printDoc(System.out, cl.getArgs(), true);
return;
}
LocalConfig lc = null;
try {
lc = new LocalConfig(cl.getOptionValue("c"));
} catch (DocumentException de) {
error("failed when reading config file", de);
} catch (ConfigException ce) {
error("failed with error in config file", ce);
}
// edit
if (cl.hasOption("e")) {
checkNotRoot("-e");
checkCompatibleOptions("e", "qfrc", cl);
String[] av = cl.getArgs();
if (av == null || av.length == 0) {
error("insufficient arguments", null);
}
for (int i = 0; i < av.length; i++) {
String key = null;
String value = null;
if (cl.hasOption("r")) {
key = av[i];
value = RandomPassword.generate();
} else {
int eqidx = av[i].indexOf("=");
if (eqidx <= 0) {
// <= 0 also catches first char being =, ie no key specified
error("argument '" + av[i] + "' not in key=value form", null);
}
key = av[i].substring(0, eqidx);
value = av[i].substring(eqidx + 1, av[i].length());
}
if (KnownKey.needForceToEdit(key) && !cl.hasOption("f")) {
error("can not edit key " + key, null);
}
lc.set(key, value);
}
try {
lc.save();
} catch (Exception e) {
error("save to " + lc.getConfigFile() + " failed", e);
}
return;
}
// unset
if (cl.hasOption("u")) {
checkNotRoot("-u");
checkCompatibleOptions("u", "qfc", cl);
String[] av = cl.getArgs();
if (av == null || av.length == 0) {
error("insufficient arguments", null);
}
for (int i = 0; i < av.length; i++) {
String key = av[i];
if (!lc.isSet(key)) {
error("key " + key + " is not set", null);
}
lc.remove(key);
}
try {
lc.save();
} catch (Exception e) {
error("save to " + lc.getConfigFile() + " failed", e);
}
return;
}
// show path
if (cl.hasOption("p")) {
checkCompatibleOptions("p", "qc", cl);
System.out.println(lc.getConfigFile());
return;
}
if (cl.hasOption("l")) {
// reset logging and run native lib load
CliUtil.toolSetup("WARN");
try {
reload();
} catch (ServiceException e) {
if (e.getCause() instanceof ConnectException) {
error("'" + Provisioning.SERVICE_MAILBOX + "' service is not running", null);
} else {
error(e.getMessage(), e);
}
}
return;
}
// print values
String format = cl.getOptionValue("m");
ConfigWriter cwriter = null;
try {
cwriter = ConfigWriter.getInstance(format, cl.hasOption("x"), !cl.hasOption("s"));
} catch (ConfigException iae) {
error("failed to create writer " + format, iae);
}
try {
// changed
if (cl.hasOption("n")) {
checkCompatibleOptions("n", "qscmx", cl);
lc.printChanged(System.out, cwriter, cl.getArgs());
return;
}
// default
if (cl.hasOption("d")) {
checkCompatibleOptions("d", "qscmx", cl);
lc.printDefaults(System.out, cwriter, cl.getArgs());
return;
}
// current
checkCompatibleOptions("", "qscmx", cl);
lc.print(System.out, cwriter, cl.getArgs());
} catch (Exception e) {
error("exception occurred when printing", e);
}
}
use of java.net.ConnectException in project adempiere by adempiere.
the class Worker method run.
/**
* Worker: Read available Online Help Pages
*/
public void run() {
if (m_links == null)
return;
URL url = null;
try {
url = new URL(m_urlString);
} catch (Exception e) {
System.err.println("OnlineHelp.Worker.run (url) - " + e);
}
if (url == null)
return;
// Read Reference Page
try {
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
HTMLEditorKit kit = new HTMLEditorKit();
HTMLDocument doc = (HTMLDocument) kit.createDefaultDocument();
doc.putProperty("IgnoreCharsetDirective", new Boolean(true));
kit.read(new InputStreamReader(is), doc, 0);
// Get The Links to the Help Pages
HTMLDocument.Iterator it = doc.getIterator(HTML.Tag.A);
Object target = null;
Object href = null;
while (it != null && it.isValid()) {
AttributeSet as = it.getAttributes();
// key keys
if (target == null || href == null) {
Enumeration en = as.getAttributeNames();
while (en.hasMoreElements()) {
Object o = en.nextElement();
if (target == null && o.toString().equals("target"))
// javax.swing.text.html.HTML$Attribute
target = o;
else if (href == null && o.toString().equals("href"))
href = o;
}
}
if (target != null && "Online".equals(as.getAttribute(target))) {
// Format: /help/<AD_Window_ID>/index.html
String hrefString = (String) as.getAttribute(href);
if (hrefString != null) {
try {
// System.err.println(hrefString);
String AD_Window_ID = hrefString.substring(hrefString.indexOf('/', 1), hrefString.lastIndexOf('/'));
m_links.put(AD_Window_ID, hrefString);
} catch (Exception e) {
System.err.println("OnlineHelp.Worker.run (help) - " + e);
}
}
}
it.next();
}
is.close();
} catch (ConnectException e) {
// System.err.println("OnlineHelp.Worker.run URL=" + url + " - " + e);
} catch (UnknownHostException uhe) {
// System.err.println("OnlineHelp.Worker.run " + uhe);
} catch (Exception e) {
System.err.println("OnlineHelp.Worker.run (e) " + e);
// e.printStackTrace();
} catch (Throwable t) {
System.err.println("OnlineHelp.Worker.run (t) " + t);
// t.printStackTrace();
}
// System.out.println("OnlineHelp - Links=" + m_links.size());
}
use of java.net.ConnectException in project lucene-solr by apache.
the class HttpShardHandler method submit.
@Override
public void submit(final ShardRequest sreq, final String shard, final ModifiableSolrParams params) {
// do this outside of the callable for thread safety reasons
final List<String> urls = getURLs(shard);
Callable<ShardResponse> task = () -> {
ShardResponse srsp = new ShardResponse();
if (sreq.nodeName != null) {
srsp.setNodeName(sreq.nodeName);
}
srsp.setShardRequest(sreq);
srsp.setShard(shard);
SimpleSolrResponse ssr = new SimpleSolrResponse();
srsp.setSolrResponse(ssr);
long startTime = System.nanoTime();
try {
// use default (currently javabin)
params.remove(CommonParams.WT);
params.remove(CommonParams.VERSION);
QueryRequest req = makeQueryRequest(sreq, params, shard);
req.setMethod(SolrRequest.METHOD.POST);
// if there are no shards available for a slice, urls.size()==0
if (urls.size() == 0) {
// all of the servers for a shard are down.
throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "no servers hosting shard: " + shard);
}
if (urls.size() <= 1) {
String url = urls.get(0);
srsp.setShardAddress(url);
try (SolrClient client = new Builder(url).withHttpClient(httpClient).build()) {
ssr.nl = client.request(req);
}
} else {
LBHttpSolrClient.Rsp rsp = httpShardHandlerFactory.makeLoadBalancedRequest(req, urls);
ssr.nl = rsp.getResponse();
srsp.setShardAddress(rsp.getServer());
}
} catch (ConnectException cex) {
//????
srsp.setException(cex);
} catch (Exception th) {
srsp.setException(th);
if (th instanceof SolrException) {
srsp.setResponseCode(((SolrException) th).code());
} else {
srsp.setResponseCode(-1);
}
}
ssr.elapsedTime = TimeUnit.MILLISECONDS.convert(System.nanoTime() - startTime, TimeUnit.NANOSECONDS);
return transfomResponse(sreq, srsp, shard);
};
try {
if (shard != null) {
MDC.put("ShardRequest.shards", shard);
}
if (urls != null && !urls.isEmpty()) {
MDC.put("ShardRequest.urlList", urls.toString());
}
pending.add(completionService.submit(task));
} finally {
MDC.remove("ShardRequest.shards");
MDC.remove("ShardRequest.urlList");
}
}
use of java.net.ConnectException in project ignite by apache.
the class RestExecutor method sendRequest.
/** */
private RestResult sendRequest(boolean demo, String path, Map<String, Object> params, String mtd, Map<String, Object> headers, String body) throws IOException {
if (demo && AgentClusterDemo.getDemoUrl() == null) {
try {
AgentClusterDemo.tryStart().await();
} catch (InterruptedException ignore) {
throw new IllegalStateException("Failed to execute request because of embedded node for demo mode is not started yet.");
}
}
String url = demo ? AgentClusterDemo.getDemoUrl() : nodeUrl;
HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
if (path != null)
urlBuilder.addPathSegment(path);
final Request.Builder reqBuilder = new Request.Builder();
if (headers != null) {
for (Map.Entry<String, Object> entry : headers.entrySet()) if (entry.getValue() != null)
reqBuilder.addHeader(entry.getKey(), entry.getValue().toString());
}
if ("GET".equalsIgnoreCase(mtd)) {
if (params != null) {
for (Map.Entry<String, Object> entry : params.entrySet()) {
if (entry.getValue() != null)
urlBuilder.addQueryParameter(entry.getKey(), entry.getValue().toString());
}
}
} else if ("POST".equalsIgnoreCase(mtd)) {
if (body != null) {
MediaType contentType = MediaType.parse("text/plain");
reqBuilder.post(RequestBody.create(contentType, body));
} else {
FormBody.Builder formBody = new FormBody.Builder();
if (params != null) {
for (Map.Entry<String, Object> entry : params.entrySet()) {
if (entry.getValue() != null)
formBody.add(entry.getKey(), entry.getValue().toString());
}
}
reqBuilder.post(formBody.build());
}
} else
throw new IllegalArgumentException("Unknown HTTP-method: " + mtd);
reqBuilder.url(urlBuilder.build());
try (Response resp = httpClient.newCall(reqBuilder.build()).execute()) {
String content = resp.body().string();
if (resp.isSuccessful()) {
JsonNode node = mapper.readTree(content);
int status = node.get("successStatus").asInt();
switch(status) {
case STATUS_SUCCESS:
return RestResult.success(node.get("response").toString());
default:
return RestResult.fail(status, node.get("error").asText());
}
}
if (resp.code() == 401)
return RestResult.fail(STATUS_AUTH_FAILED, "Failed to authenticate in grid. Please check agent\'s login and password or node port.");
return RestResult.fail(STATUS_FAILED, "Failed connect to node and execute REST command.");
} catch (ConnectException ignore) {
throw new ConnectException("Failed connect to node and execute REST command [url=" + urlBuilder + "]");
}
}
Aggregations