public CloseableHttpResponse execute() { CloseableHttpResponse response; try { response = closeableHttpClient.execute(httpRequestBase, context); } catch (SocketTimeoutException ste) { throw new RuntimeException("Socket timeout: " + ste.getMessage(), ste); } catch (HttpHostConnectException connectEx) { throw new RuntimeException("Connection error: " + connectEx.getMessage(), connectEx); } catch (IOException e) { throw new RuntimeException("Error while executing http request: " + e.getMessage(), e); } return response; }
public static String doPost(String url, String json) throws Exception { try { CloseableHttpClient client = getHttpClient(url); HttpPost post = new HttpPost(url); config(post); logger.info("====> Executing request: " + post.getRequestLine()); if (!StringUtils.isEmpty(json)) { StringEntity s = new StringEntity(json, "UTF-8"); s.setContentEncoding("UTF-8"); s.setContentType("application/json"); post.setEntity(s); } String responseBody = client.execute(post, getStringResponseHandler()); logger.info("====> Getting response from request " + post.getRequestLine() + " The responseBody: " + responseBody); return responseBody; } catch (Exception e) { if (e instanceof HttpHostConnectException || e.getCause() instanceof ConnectException) { throw new ConnectException("====> 连接服务器" + url + "失败: " + e.getMessage()); } logger.error("====> HttpRequestUtil.doPost: " + e.getMessage(), e); } return null; }
public static String doGet(String url) throws Exception { try { CloseableHttpClient client = getHttpClient(url); HttpGet httpget = new HttpGet(url); config(httpget); logger.info("====> Executing request: " + httpget.getRequestLine()); String responseBody = client.execute(httpget, getStringResponseHandler()); logger.info("====> Getting response from request " + httpget.getRequestLine() + " The responseBody: " + responseBody); return responseBody; } catch (Exception e) { if (e instanceof HttpHostConnectException || e.getCause() instanceof ConnectException) { throw e; } logger.error("HttpRequestUtil.doGet: " + e.getMessage()); } return null; }
/** * Wait for the server is ready. */ private void waitForServerReady() throws IOException, InterruptedException { final HttpGet httpget = new HttpGet(getPingUri()); HttpResponse response = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_FOUND, "")); int counter = 0; while (true) { try { response = httpclient.execute(httpget); final int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_OK) { break; } checkRetries(counter); } catch (final HttpHostConnectException ex) { // NOSONAR - Wait, and check later log.info("Check failed, retrying..."); checkRetries(counter); } finally { EntityUtils.consume(response.getEntity()); } counter++; } }
@Test(expected=HttpHostConnectException.class) public void testConnectFailure() throws Exception { final HttpContext context = new BasicHttpContext(); final HttpHost host = new HttpHost("somehost"); final InetAddress ip1 = InetAddress.getByAddress(new byte[] {10, 0, 0, 1}); final InetAddress ip2 = InetAddress.getByAddress(new byte[] {10, 0, 0, 2}); Mockito.when(dnsResolver.resolve("somehost")).thenReturn(new InetAddress[] { ip1, ip2 }); Mockito.when(socketFactoryRegistry.lookup("http")).thenReturn(plainSocketFactory); Mockito.when(schemePortResolver.resolve(host)).thenReturn(80); Mockito.when(plainSocketFactory.createSocket(Mockito.<HttpContext>any())).thenReturn(socket); Mockito.when(plainSocketFactory.connectSocket( Mockito.anyInt(), Mockito.<Socket>any(), Mockito.<HttpHost>any(), Mockito.<InetSocketAddress>any(), Mockito.<InetSocketAddress>any(), Mockito.<HttpContext>any())).thenThrow(new ConnectException()); connectionOperator.connect(conn, host, null, 1000, SocketConfig.DEFAULT, context); }
public String getRedirectUrl() { StringBuilder authUrl = new StringBuilder(ServiceAuthConstants.AUTH_SERVICE_URL.get()); authUrl.append("/redirectUrl"); HttpResponse response; try { Request temp = Request.Get(authUrl.toString()).addHeader(ServiceAuthConstants.ACCEPT, ServiceAuthConstants.APPLICATION_JSON); response = temp.execute().returnResponse(); int statusCode = response.getStatusLine().getStatusCode(); if(statusCode >= 300) { log.error("Got error from Auth service. statusCode: {}", statusCode); return ""; } Map<String, Object> jsonData = jsonMapper.readValue(response.getEntity().getContent()); if( jsonData != null && !jsonData.isEmpty()) { if (jsonData.containsKey("redirectUrl")) { return (String)jsonData.get("redirectUrl"); } } } catch(HttpHostConnectException ex) { log.error("Auth Service not reachable at [{}]", ServiceAuthConstants.AUTH_SERVICE_URL); } catch (IOException e) { log.error("Failed to get the redirectUrl from Auth Service.", e); } return ""; }
@Test(expected = HttpHostConnectException.class) public void testServerStopsSpecifyPort() throws Exception { int port = getFreePort(); JettyServer jettyServer = new JettyServer(); jettyServer.start(port); HttpClient httpClient = new DefaultHttpClient(); HttpGet workflowListGet = new HttpGet("http://localhost:" + port); HttpResponse response = httpClient.execute(workflowListGet); Assert.assertEquals(response.getStatusLine().getStatusCode(), 403); EntityUtils.consume(response.getEntity()); jettyServer.stop(); httpClient.execute(workflowListGet); }
public boolean check() throws InterruptedException { try { HttpResponse<String> health = Unirest.get(url + "/admin/healthcheck") .basicAuth("test", "test") .asString(); if (health.getStatus() == 200) { log.info("Healthy with {}", health.getBody()); return true; } else { log.error("Unhealthy with {}", health.getBody()); return false; } } catch (UnirestException e) { if (e.getCause() instanceof HttpHostConnectException && duration < maxDuration) { log.info("Unable to connect, retrying..."); duration = duration + DELAY; Thread.sleep(TimeUnit.SECONDS.toMillis(DELAY)); return check(); } log.error("Unable to connect.", e); return false; } }
/** * 异常信息统一处理 * * @param resObj 响应对象 * @param ec 异常�? * @param optionStatus 自定义状态编�? * @param optionErrorMessage 自定义错误信�? */ private void setException(ResponseObject resObj, Exception ec,Integer optionStatus,String optionErrorMessage) { String errorMessage=""; resObj.setStatus(optionStatus);//链接超时代码 if(ec instanceof UnknownHostException){ errorMessage=ec.getMessage(); } if(ec instanceof ConnectTimeoutException){ errorMessage=ec.getMessage(); } if(ec instanceof HttpHostConnectException){ errorMessage=ec.getMessage(); } resObj.setErrorMessage(errorMessage); resObj.setOptionErrorMessage(optionErrorMessage); }
@Test public void stop() throws Exception { storage.stop(); try { // Should not respond after stop status(); } catch (SocketTimeoutException | HttpHostConnectException e) { // Do nothing } }
public void updateSecureConnection( final OperatedClientConnection conn, final HttpHost target, final HttpContext context, final HttpParams params) throws IOException { if (conn == null) { throw new IllegalArgumentException("Connection may not be null"); } if (target == null) { throw new IllegalArgumentException("Target host may not be null"); } if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } if (!conn.isOpen()) { throw new IllegalStateException("Connection must be open"); } final Scheme schm = schemeRegistry.getScheme(target.getSchemeName()); if (!(schm.getSchemeSocketFactory() instanceof SchemeLayeredSocketFactory)) { throw new IllegalArgumentException ("Target scheme (" + schm.getName() + ") must have layered socket factory."); } SchemeLayeredSocketFactory lsf = (SchemeLayeredSocketFactory) schm.getSchemeSocketFactory(); Socket sock; try { sock = lsf.createLayeredSocket( conn.getSocket(), target.getHostName(), target.getPort(), params); } catch (ConnectException ex) { throw new HttpHostConnectException(target, ex); } prepareSocket(sock, context, params); conn.update(sock, target, lsf.isSecure(sock), params); }
@Test(expected = IllegalStateException.class) public void testStartRestServerKo3() throws IOException { retries = 0; httpclient = Mockito.mock(CloseableHttpClient.class); Mockito.when(httpclient.execute(ArgumentMatchers.any(HttpGet.class))).thenThrow(new HttpHostConnectException(null, null, new InetAddress[0])); startRestServer("log4j2.json"); }
private boolean canRetry(Throwable e, HttpMethod method) { Throwable nestedException = e.getCause(); if (method == HttpMethod.GET) { return nestedException instanceof SocketTimeoutException || nestedException instanceof HttpHostConnectException || nestedException instanceof ConnectTimeoutException; } else { return nestedException instanceof HttpHostConnectException || nestedException instanceof ConnectTimeoutException; } }
@Before public void init() { socketTimeoutException.initCause(new SocketTimeoutException()); httpHostConnectException .initCause(new HttpHostConnectException(new ConnectTimeoutException(), new HttpHost(serviceOne, 80))); connectTimeoutException.initCause(new ConnectTimeoutException()); }
@Override protected void collectData(Gson gson, String user, List<String> subscriptions) { Map<String, String> subscriptionData = new HashMap<>(); for (String url : subscriptions) { try (CloseableHttpClient httpClient = HttpClientHelper.buildHttpClient()) { HttpUriRequest query = RequestBuilder.get() .setUri(url) .build(); try (CloseableHttpResponse queryResponse = httpClient.execute(query)) { HttpEntity entity = queryResponse.getEntity(); if (entity != null) { String data = EntityUtils.toString(entity); if (data != null && data.length() > 0) { if (data.contains("www.dnsrsearch.com")) { subscriptionData.put(url, "not found"); } else { subscriptionData.put(url, "up"); } } else { subscriptionData.put(url, "down"); } } else { subscriptionData.put(url, "down"); } } } catch (HttpHostConnectException hhce) { subscriptionData.put(url, "down"); } catch (Throwable throwable) { logger.error(throwable.getMessage(), throwable); subscriptionData.put(url, "down"); } } DataResponse response = new DataResponse(); response.setType("UpDownResponse"); response.setId(user); response.setResult(MessageConstants.SUCCESS); response.setSubscriptionData(subscriptionData); responseQueue.add(gson.toJson(response)); }
@Test public void testClosed() throws Exception { HttpUriRequest request = composeRequest(); crusher.close(); try { http.execute(request); Assert.fail("Exception is expected"); } catch (HttpHostConnectException e) { LOGGER.debug("Exception dump", e); } }
public FlowableServiceException wrapException(Exception e, HttpUriRequest request) { if (e instanceof HttpHostConnectException) { return new FlowableServiceException("Unable to connect to the Flowable server."); } else if (e instanceof ConnectTimeoutException) { return new FlowableServiceException("Connection to the Flowable server timed out."); } else { // Use the raw exception message return new FlowableServiceException(e.getClass().getName() + ": " + e.getMessage()); } }
/** * 构造异常类. * * @param e 异常 */ public AbAppException(Exception e) { super(); try { if( e instanceof HttpHostConnectException) { msg = AbConstant.UNKNOWNHOSTEXCEPTION; }else if (e instanceof ConnectException) { msg = AbConstant.CONNECTEXCEPTION; }else if (e instanceof UnknownHostException) { msg = AbConstant.UNKNOWNHOSTEXCEPTION; }else if (e instanceof SocketException) { msg = AbConstant.SOCKETEXCEPTION; }else if (e instanceof SocketTimeoutException) { msg = AbConstant.SOCKETTIMEOUTEXCEPTION; }else if( e instanceof NullPointerException) { msg = AbConstant.NULLPOINTEREXCEPTION; }else if( e instanceof ClientProtocolException) { msg = AbConstant.CLIENTPROTOCOLEXCEPTION; }else { if (e == null || StringUtils.isEmpty(e.getMessage())) { msg = AbConstant.NULLMESSAGEEXCEPTION; }else{ msg = e.getMessage(); } } } catch (Exception e1) { } }
public static boolean checkReadyURL(String url) throws IOException { try (CloseableHttpClient client = HttpClientBuilder.create().build()) { HttpPost post = new HttpPost(url + "/ready"); try (CloseableHttpResponse response = client.execute(post)) { int code = response.getStatusLine().getStatusCode(); return code == 200; } catch (HttpHostConnectException refused) { // Thrown if the URL or host does not yet exist! return false; } } }
private Result postValues(String url, List<String[]> datas) { HttpPost httpPost = new HttpPost(url); List<NameValuePair> valuePairs = new ArrayList<>(); for (String[] keyValue : datas) { valuePairs.add(new BasicNameValuePair(keyValue[0], keyValue[1])); } Integer tryCount = 0; while (reties > tryCount) { try { httpPost.setEntity(new UrlEncodedFormEntity(valuePairs, "utf-8")); httpPost.setHeader("token", token); String result = EntityUtils.toString(HTTP_CLIENT.execute(httpPost).getEntity(), Consts.UTF_8); Result result1 = JSON.parseObject(result, ResultImpl.class); if (result1.getCode() != 0) { throw new JapiException(result1.getMsg()); } return result1; } catch (IOException e) { if (e instanceof HttpHostConnectException) { tryCount++; LOGGER.warn("try connect server " + tryCount + " count."); try { TimeUnit.SECONDS.sleep(tryTime); } catch (InterruptedException e1) { e1.printStackTrace(); } } } } if (tryCount <= reties) { LOGGER.error("server connect failed."); } return null; }
private Result postFile(String url, List<String[]> datas, File file) { if (!file.exists()) { throw new JapiException(file.getAbsolutePath() + " file not exist."); } HttpPost httpPost = new HttpPost(url); Integer tryCount = 0; while (reties > tryCount) { try { final MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create(); multipartEntity.setCharset(Charset.forName("utf-8")); multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); for (String[] nameValue : datas) { multipartEntity.addPart(nameValue[0], new StringBody(nameValue[1], ContentType.APPLICATION_JSON)); } multipartEntity.addBinaryBody("file", file); httpPost.setEntity(multipartEntity.build()); httpPost.setHeader("token", token); String result = EntityUtils.toString(HTTP_CLIENT.execute(httpPost).getEntity()); Result result1 = JSON.parseObject(result, ResultImpl.class); if (result1.getCode() != 0) { throw new JapiException(result1.getMsg()); } return result1; } catch (IOException e) { if (e instanceof HttpHostConnectException) { tryCount++; LOGGER.warn("try connect server " + tryCount + " count."); try { TimeUnit.SECONDS.sleep(tryTime); } catch (InterruptedException e1) { e1.printStackTrace(); } } } } if (tryCount <= reties) { LOGGER.error("server connect failed."); } return null; }
private void assertRefused(Exchange exchange, String portExt) { Map<String, Object> headers = exchange.getOut().getHeaders(); //no http response: assertNull(headers.get(Exchange.HTTP_RESPONSE_CODE)); //and got an exception: assertIsInstanceOf(HttpHostConnectException.class, exchange.getException()); //with message: assertEquals("Connection to http://127.0.0.1" + portExt + " refused", exchange.getException().getMessage()); }
/** * 构造异常类. * * @param e 异常 */ public AbAppException(Exception e) { super(); try { if( e instanceof HttpHostConnectException) { msg = AbAppConfig.UNKNOWN_HOST_EXCEPTION; }else if (e instanceof ConnectException) { msg = AbAppConfig.CONNECT_EXCEPTION; }else if (e instanceof ConnectTimeoutException) { msg = AbAppConfig.CONNECT_EXCEPTION; }else if (e instanceof UnknownHostException) { msg = AbAppConfig.UNKNOWN_HOST_EXCEPTION; }else if (e instanceof SocketException) { msg = AbAppConfig.SOCKET_EXCEPTION; }else if (e instanceof SocketTimeoutException) { msg = AbAppConfig.SOCKET_TIMEOUT_EXCEPTION; }else if( e instanceof NullPointerException) { msg = AbAppConfig.NULL_POINTER_EXCEPTION; }else if( e instanceof ClientProtocolException) { msg = AbAppConfig.CLIENT_PROTOCOL_EXCEPTION; }else { if (e == null || AbStrUtil.isEmpty(e.getMessage())) { msg = AbAppConfig.NULL_MESSAGE_EXCEPTION; }else{ msg = e.getMessage(); } } } catch (Exception e1) { } }
@Test public void testSimpleRequest_connectionRefused_netHttpTransport() throws IOException, Failure { HttpRequestFactory factory = new NetHttpTransport().createRequestFactory(); GenericUrl url = new GenericUrl("http://localhost:" + (port - 10) + "/" + ENDPOINT); TestService.Iface client = new TestService.Client(new HttpClientHandler( () -> url, factory, provider)); try { client.test(new Request("request")); fail("No exception"); } catch (HttpHostConnectException ex) { assertThat(ex.getMessage(), is(startsWith("Connect to localhost:" + (port - 10) + " failed: Connection refused"))); } }
@Test public void testSimpleRequest_connectionRefused_apacheHttpTransport() throws IOException, Failure { HttpRequestFactory factory = new ApacheHttpTransport().createRequestFactory(); GenericUrl url = new GenericUrl("http://localhost:" + (port - 10) + "/" + ENDPOINT); TestService.Iface client = new TestService.Client(new HttpClientHandler( () -> url, factory, provider)); try { client.test(new Request("request")); fail("No exception"); } catch (HttpHostConnectException ex) { assertThat(ex.getMessage(), is(startsWith("Connect to localhost:" + (port - 10) + " failed: Connection refused"))); } }
@Override public void torrentAddError(Exception e) { if (e instanceof HttpHostConnectException) { AndroidUtilsUI.showConnectionError(activity, session.getRemoteProfile().getID(), R.string.connerror_hostconnect, true); } else { String s = activity.getResources().getString( R.string.adding_torrent_error, TextUtils.htmlEncode(name), AndroidUtils.getCausesMesssages(e)); AndroidUtilsUI.showConnectionError(activity, AndroidUtils.fromHTML(s), true); } }
@Test public void tryConnectWithBasicAuthentication() throws Exception { try { ClientHttpRequest req = factory.createRequest(connSettings.getPollEndpoint().toURI(), HttpMethod.POST); req.execute(); fail("connection must fail"); } catch (Throwable e) { assertThat(e, instanceOf(HttpHostConnectException.class)); } verifyLog(mockAppender, "Re-using cached 'basic' auth scheme for http://localhost:80"); }
public static void waitUrlAvailable(final String url) throws InterruptedException, IOException { for (int i = 0; i < 50; i++) { Thread.sleep(100); try { if (HttpClients.createDefault().execute(new HttpGet(url)).getStatusLine().getStatusCode() > -100) break; } catch (HttpHostConnectException ex) { } } }
private static Boolean isHostUnavailableException(Throwable ex, Boolean isCause) { if (ex == null) return false; Class clazz = ex.getClass(); return clazz == java.net.UnknownHostException.class || clazz == HttpHostConnectException.class || clazz == ClientProtocolException.class || clazz == NoHttpResponseException.class || clazz == org.apache.http.conn.HttpHostConnectException.class || (!isCause && isHostUnavailableException(ex.getCause(), true)); }
WWWGateway(HttpClient client, WWWSynchronizer processor, ScheduledExecutorService scheduler, WireSerializer serializer, Multicaster<Listener, Message> caster) throws IOException { this.synchro = processor; this.client = client; this.caster = caster; this.scheduler = scheduler; this.serializer = serializer; this.cloudListeners = new ConcurrentHashMap<Cloud, UUID>(); this.cloudMessages = new ConcurrentBuildingMap<Cloud, Queue<Message>>(new Factory<Queue<Message>>() { @Override public Queue<Message> make() { return new ConcurrentLinkedQueue<Message>(); } }); long period = loadSyncPeriod(); this.scheduler.scheduleAtFixedRate(new Runnable() { @Override public void run() { sync(EnumSet.of(Sync.TX, Sync.RX)); } }, period, period, TimeUnit.MILLISECONDS); this.urlRoot = System.getProperty(SYSP_ADDRESS, "https://www.zapnos.org/"); this.urlMsgs = composeUrl("api/1.0/messages"); try { ping(client); } catch (HttpHostConnectException ex) { log.warn("Unable to ping WWW endpoint - {}", ex.getMessage()); } }
@Override protected Integer doInBackground(Void... params) { mResetKey = "Error!"; HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 5000); HttpConnectionParams.setSoTimeout(httpParams, 10000); HttpClient client = new DefaultHttpClient(httpParams); int res = -1; try { Random random = new Random(); mResetKey = "" + (random.nextInt(900000) + 100000); String post = ServerInfo.RESET_SERVER + "/update_reset_code.php?user=" + prefs.getString(getString(R.string.user_name),"") + "&code=" + mResetKey; HttpPost httpPost = new HttpPost(post); HttpEntity localHttpEntity = client.execute(httpPost).getEntity(); if (localHttpEntity != null) { res = Integer.valueOf(new BufferedReader(new InputStreamReader(localHttpEntity.getContent(), "UTF-8")).readLine()); } } catch (HttpHostConnectException e) { return -1; } catch (IOException localIOException){ return -1; } return res; }
@Override protected Boolean doInBackground(Context... ctx) { this.context = ctx[0]; GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context); HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 5000); HttpConnectionParams.setSoTimeout(params, 10000); HttpClient client = new DefaultHttpClient(params); try { String regID = gcm.register(RegisterDevice.GCM_SENDER_ID); preferences.edit().putString(RegisterDevice.PROPERTY_REG_ID,regID).commit(); String regIDOld = preferences.getString(RegisterDevice.PROPERTY_REG_ID_OLD,""); String post = ServerInfo.RESET_SERVER + "/update_device_id.php?dev_id=" + regIDOld + "&dev_id_new=" + regID; HttpPost httpPost = new HttpPost(post); HttpEntity localHttpEntity = client.execute(httpPost).getEntity(); if (localHttpEntity != null) { int res = Integer.valueOf(new BufferedReader(new InputStreamReader(localHttpEntity.getContent(), "UTF-8")).readLine()); return res != -1; } } catch (HttpHostConnectException e) { return false; } catch (IOException localIOException){ return false; } return false; }
/** * Make a http request to http://127.0.0.1:<proxy-port>/nginx_status and find writing count. * @param proxyPort * @return */ private int findWritingCount(int proxyPort) { try { URL url = new URL("http", "127.0.0.1", proxyPort, "/nginx_status"); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpUriRequest request = new HttpGet(url.toURI()); HttpResponse response = httpClient.execute(request); if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("http://127.0.0.1:" + proxyPort + "/nginx_status was not found"); } BufferedReader reader = new BufferedReader(new InputStreamReader( (response.getEntity().getContent()))); String output, result = ""; while ((output = reader.readLine()) != null) { result += output; } Pattern pattern = Pattern.compile("(Writing: )([0-1]*)"); Matcher matcher = pattern.matcher(result); if (matcher.find()) { // Deduct one to remove the above request int writingCount = Integer.parseInt(matcher.group(2)) - 1; if(log.isDebugEnabled()) { log.debug(String.format("Writing count: [proxy] %d [value] %d", proxyPort, writingCount)); } return writingCount; } throw new RuntimeException("Writing block was not found in nginx_status response"); } catch (HttpHostConnectException ignore) { if(ignore.getMessage().contains("Connection refused")) { log.warn("Could not find in-flight request count, connection refused: " + "http://127.0.0.1:" + proxyPort + "/nginx_status"); } } catch (Exception e) { log.error("Could not find in-flight request count: http://127.0.0.1:" + proxyPort + "/nginx_status", e); } return 0; }
@Test(expected = HttpHostConnectException.class) public void testServerStops() throws Exception { JettyServer jettyServer = new JettyServer(); int port = jettyServer.start(); HttpClient httpClient = new DefaultHttpClient(); HttpGet workflowListGet = new HttpGet("http://localhost:" + port); HttpResponse response = httpClient.execute(workflowListGet); Assert.assertEquals(response.getStatusLine().getStatusCode(), 403); EntityUtils.consume(response.getEntity()); jettyServer.stop(); httpClient.execute(workflowListGet); }
public static void bug(XHook hook, Throwable ex) { if (ex instanceof InvocationTargetException) { InvocationTargetException exex = (InvocationTargetException) ex; if (exex.getTargetException() != null) ex = exex.getTargetException(); } int priority; if (ex instanceof ActivityShare.AbortException) priority = Log.WARN; else if (ex instanceof ActivityShare.ServerException) priority = Log.WARN; else if (ex instanceof ConnectTimeoutException) priority = Log.WARN; else if (ex instanceof FileNotFoundException) priority = Log.WARN; else if (ex instanceof HttpHostConnectException) priority = Log.WARN; else if (ex instanceof NameNotFoundException) priority = Log.WARN; else if (ex instanceof NoClassDefFoundError) priority = Log.WARN; else if (ex instanceof OutOfMemoryError) priority = Log.WARN; else if (ex instanceof RuntimeException) priority = Log.WARN; else if (ex instanceof SecurityException) priority = Log.WARN; else if (ex instanceof SocketTimeoutException) priority = Log.WARN; else if (ex instanceof SSLPeerUnverifiedException) priority = Log.WARN; else if (ex instanceof StackOverflowError) priority = Log.WARN; else if (ex instanceof TransactionTooLargeException) priority = Log.WARN; else if (ex instanceof UnknownHostException) priority = Log.WARN; else if (ex instanceof UnsatisfiedLinkError) priority = Log.WARN; else priority = Log.ERROR; boolean xprivacy = false; for (StackTraceElement frame : ex.getStackTrace()) if (frame.getClassName() != null && frame.getClassName().startsWith("biz.bokhorst.xprivacy")) { xprivacy = true; break; } if (!xprivacy) priority = Log.WARN; log(hook, priority, ex.toString() + " uid=" + Process.myUid() + "\n" + Log.getStackTraceString(ex)); }