List of usage examples for java.util.concurrent ExecutionException printStackTrace
public void printStackTrace()
From source file:ca.zadrox.dota2esportticker.service.UpdateTeamsService.java
private void updateSearchedTeams(String searchName) { LOGD(TAG, "starting search update"); // actually, first, check for connectivity: if (!checkForConnectivity()) { LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_NO_CONNECTIVITY)); LOGD(TAG, "returning due to no connectivity"); return;/*w w w . j av a2 s. c o m*/ } LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_UPDATING)); final String BASE_URL = "http://www.gosugamers.net/dota2/rankings" + "?tname=" + searchName.replace(' ', '+') + "&tunranked=0#team"; final String TEAM_LINK_BASE_URL = "http://www.gosugamers.net/dota2/teams/"; try { String rawHtml = new OkHttpClient().newCall(new Request.Builder().url(BASE_URL).build()).execute() .body().string(); String processedHtml = rawHtml.substring(rawHtml.indexOf("<div id=\"col1\" class=\"rows\">"), rawHtml.indexOf("<div id=\"col2\" class=\"rows\">")); Elements teamRows = Jsoup.parse(processedHtml).getElementsByClass("ranking-link"); ExecutorService executorService = Executors.newFixedThreadPool(10); HashMap<ContentValues, Future<String>> newTeamInfo = new HashMap<ContentValues, Future<String>>(); HashMap<ContentValues, Future<String>> updateTeamInfo = new HashMap<ContentValues, Future<String>>(); for (Element teamRow : teamRows) { ContentValues contentValues = new ContentValues(); String teamId = teamRow.attr("data-id"); contentValues.put(MatchContract.TeamEntry._ID, teamId); String untrimmedTeamName = teamRow.getElementsByTag("h4").first().text(); String teamUrl = TEAM_LINK_BASE_URL + teamId + "-" + untrimmedTeamName.replaceAll("[\\W]?[\\W][\\W]*", "-").toLowerCase(); contentValues.put(MatchContract.TeamEntry.COLUMN_TEAM_URL, teamUrl); String teamName = untrimmedTeamName.replaceAll(" ?\\.?\\-?-?Dot[aA][\\s]?2", ""); contentValues.put(MatchContract.TeamEntry.COLUMN_TEAM_NAME, teamName); if (teamUrl.charAt(teamUrl.length() - 1) == '-') { teamUrl = teamUrl.substring(0, teamUrl.length() - 2); } // then, we query db for id of the team ( Cursor cursor = getContentResolver().query( MatchContract.TeamEntry.buildTeamUri(Long.parseLong(teamId)), new String[] { MatchContract.TeamEntry.COLUMN_TEAM_NAME, MatchContract.TeamEntry.COLUMN_TEAM_URL }, null, null, null); // -> if present, and data remains unchanged, continue. // -> if present, but data is changed, add to update queue. if (cursor.moveToFirst()) { LOGD(TAG, "Team in DB, determining if values need updating"); if (!cursor.getString(0).contentEquals(teamName) || !cursor.getString(1).contentEquals(teamUrl)) { LOGD(TAG, "Team has updated values, double checking logo & writing to DB"); updateTeamInfo.put(contentValues, executorService.submit(new TeamGetter(teamUrl))); } } // -> if not present, add to update queue. else { LOGD(TAG, "Team not in DB. Grabbing logo & writing to DB"); newTeamInfo.put(contentValues, executorService.submit(new TeamGetter(teamUrl))); } // LOGD(TAG, "\n" + // "data-id: " + teamId + "\n" + // "team-name: " + teamName + "\n" + // "team-url: " + teamUrl); // cursor.close(); } executorService.shutdown(); executorService.awaitTermination(20, TimeUnit.SECONDS); for (ContentValues contentValues : newTeamInfo.keySet()) { try { String teamLogo = newTeamInfo.get(contentValues).get(); contentValues.put(MatchContract.TeamEntry.COLUMN_TEAM_LOGO_URL, teamLogo); } catch (ExecutionException e) { LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_ERROR)); e.printStackTrace(); } } for (ContentValues contentValues : updateTeamInfo.keySet()) { try { String teamLogo = newTeamInfo.get(contentValues).get(); contentValues.put(MatchContract.TeamEntry.COLUMN_TEAM_LOGO_URL, teamLogo); String teamId = contentValues.getAsString(MatchContract.TeamEntry._ID); contentValues.remove(MatchContract.TeamEntry._ID); int updatedRows = getContentResolver().update(MatchContract.TeamEntry.CONTENT_URI, contentValues, MatchContract.TeamEntry.TABLE_NAME + "." + MatchContract.TeamEntry._ID + " = ?", new String[] { teamId }); LOGD(TAG, "updatedRows: " + updatedRows); } catch (ExecutionException e) { LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_ERROR)); e.printStackTrace(); } } getContentResolver().bulkInsert(MatchContract.TeamEntry.CONTENT_URI, newTeamInfo.keySet().toArray(new ContentValues[newTeamInfo.size()])); } catch (IOException e) { LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_ERROR)); e.printStackTrace(); } catch (InterruptedException e2) { LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_ERROR)); e2.printStackTrace(); } // String[] projection = new String[]{ // MatchContract.TeamEntry.TABLE_NAME + "." + MatchContract.TeamEntry._ID, // MatchContract.TeamEntry.COLUMN_TEAM_NAME, // MatchContract.TeamEntry.COLUMN_TEAM_URL, // MatchContract.TeamEntry.COLUMN_TEAM_LOGO_URL, // MatchContract.TeamEntry.COLUMN_TEAM_STARRED, // }; // // String sortOrder = // MatchContract.TeamEntry.COLUMN_TEAM_NAME + " ASC"; // // Cursor c = getContentResolver().query( // MatchContract.TeamEntry.CONTENT_URI, // projection, // MatchContract.TeamEntry.COLUMN_TEAM_NAME + " LIKE '%" + searchName + "%'", // null, // sortOrder // ); // // LOGD(TAG+"/UST", "Starting Printout: "); // int i = 0; // while (c.moveToNext()) { // String teamPrintOut = // "teamId: " + c.getInt(0) + " teamName: " + c.getString(1) + "\n" + // "teamUrl: " + c.getString(2) + "\n" + // "teamLogoUrl: " + c.getString(3) + "\n" + // "isFavourited: " + (c.getInt(4) == 0 ? "false" : "true"); // LOGD(TAG + "/UST", teamPrintOut); // i++; // } // LOGD(TAG+"/UST", "Stopping Printout. Count: " + i); // // c.close(); // use local broadcast manager to hide loading indicator // and signal that cursorloader for top50 can happen. LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_COMPLETED)); }
From source file:ca.zadrox.dota2esportticker.service.UpdateTeamsService.java
private void updateTopTeams() { LOGD(TAG, "starting update"); // actually, first, check for connectivity: if (!checkForConnectivity()) { LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_NO_CONNECTIVITY)); LOGD(TAG, "returning due to no connectivity"); return;/*www .j a v a 2 s .c om*/ } // first, check last update time long lastUpdate = PrefUtils.lastTeamsUpdate(this); long currentTime = TimeUtils.getUTCTime(); // if last update is less than 1 hour old, boot user to cursorloader op. if (currentTime - lastUpdate < 60000 * 60) { LOGD(TAG, "returnning due to too soon"); LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_COMPLETED)); return; } // else // use local broadcast manager to show loading indicator LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_UPDATING)); final String BASE_URL = "http://www.gosugamers.net/dota2/rankings"; final String TEAM_LINK_BASE_URL = "http://www.gosugamers.net/dota2/teams/"; // we see what teams are in top 50. (httpreq -> gosugamers) try { String rawHtml = new OkHttpClient().newCall(new Request.Builder().url(BASE_URL).build()).execute() .body().string(); String processedHtml = rawHtml.substring(rawHtml.indexOf("<div id=\"col1\" class=\"rows\">"), rawHtml.indexOf("<div id=\"col2\" class=\"rows\">")); Elements teamRows = Jsoup.parse(processedHtml).getElementsByClass("ranking-link"); ExecutorService executorService = Executors.newFixedThreadPool(10); ContentValues[] teamRanks = new ContentValues[50]; HashMap<ContentValues, Future<String>> newTeamInfo = new HashMap<ContentValues, Future<String>>(); HashMap<ContentValues, Future<String>> updateTeamInfo = new HashMap<ContentValues, Future<String>>(); int i = 0; for (Element teamRow : teamRows) { ContentValues contentValues = new ContentValues(); String teamId = teamRow.attr("data-id"); contentValues.put(MatchContract.TeamEntry._ID, teamId); String untrimmedTeamName = teamRow.getElementsByTag("h4").first().text(); String teamUrl = TEAM_LINK_BASE_URL + teamId + "-" + untrimmedTeamName.replaceAll("[\\W]?[\\W][\\W]*", "-").toLowerCase(); contentValues.put(MatchContract.TeamEntry.COLUMN_TEAM_URL, teamUrl); String teamName = untrimmedTeamName.replaceAll(" ?\\.?\\-?-?Dot[aA][\\s]?2", ""); contentValues.put(MatchContract.TeamEntry.COLUMN_TEAM_NAME, teamName); if (teamUrl.charAt(teamUrl.length() - 1) == '-') { teamUrl = teamUrl.substring(0, teamUrl.length() - 2); } // then, we query db for id of the team ( Cursor cursor = getContentResolver().query( MatchContract.TeamEntry.buildTeamUri(Long.parseLong(teamId)), new String[] { MatchContract.TeamEntry.COLUMN_TEAM_NAME, MatchContract.TeamEntry.COLUMN_TEAM_URL }, null, null, null); // -> if present, and data remains unchanged, continue. // -> if present, but data is changed, add to update queue. if (cursor.moveToFirst()) { LOGD(TAG, "Have team already?"); if (!cursor.getString(0).contentEquals(teamName) || !cursor.getString(1).contentEquals(teamUrl)) { LOGD(TAG, "Team has updated values."); updateTeamInfo.put(contentValues, executorService.submit(new TeamGetter(teamUrl))); } } // -> if not present, add to update queue. else { LOGD(TAG, "Do team update"); newTeamInfo.put(contentValues, executorService.submit(new TeamGetter(teamUrl))); } // LOGD(TAG, "\n" + // "data-id: " + teamId + "\n" + // "team-name: " + teamName + "\n" + // "team-url: " + teamUrl); teamRanks[i] = new ContentValues(); teamRanks[i].put(MatchContract.TeamRankEntry._ID, i + 1); teamRanks[i].put(MatchContract.TeamRankEntry.COLUMN_TEAM_ID, teamId); cursor.close(); i++; } executorService.shutdown(); executorService.awaitTermination(20, TimeUnit.SECONDS); for (ContentValues contentValues : newTeamInfo.keySet()) { try { String teamLogo = newTeamInfo.get(contentValues).get(); contentValues.put(MatchContract.TeamEntry.COLUMN_TEAM_LOGO_URL, teamLogo); } catch (ExecutionException e) { LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_ERROR)); e.printStackTrace(); } } for (ContentValues contentValues : updateTeamInfo.keySet()) { try { String teamLogo = updateTeamInfo.get(contentValues).get(); contentValues.put(MatchContract.TeamEntry.COLUMN_TEAM_LOGO_URL, teamLogo); String teamId = contentValues.getAsString(MatchContract.TeamEntry._ID); contentValues.remove(MatchContract.TeamEntry._ID); int updatedRows = getContentResolver().update(MatchContract.TeamEntry.CONTENT_URI, contentValues, MatchContract.TeamEntry.TABLE_NAME + "." + MatchContract.TeamEntry._ID + " = ?", new String[] { teamId }); LOGD(TAG, "updatedRows: " + updatedRows); } catch (ExecutionException e) { LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_ERROR)); e.printStackTrace(); } } getContentResolver().bulkInsert(MatchContract.TeamEntry.CONTENT_URI, newTeamInfo.keySet().toArray(new ContentValues[newTeamInfo.size()])); getContentResolver().bulkInsert(MatchContract.TeamRankEntry.CONTENT_URI, teamRanks); } catch (IOException e) { LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_ERROR)); e.printStackTrace(); } catch (InterruptedException e2) { LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_ERROR)); e2.printStackTrace(); } // String[] projection = new String[]{ // MatchContract.TeamEntry.TABLE_NAME + "." + MatchContract.TeamEntry._ID, // MatchContract.TeamEntry.COLUMN_TEAM_NAME, // MatchContract.TeamEntry.COLUMN_TEAM_URL, // MatchContract.TeamEntry.COLUMN_TEAM_LOGO_URL, // MatchContract.TeamEntry.COLUMN_TEAM_STARRED, // MatchContract.TeamRankEntry.TABLE_NAME + "." + MatchContract.TeamRankEntry._ID // }; // // String sortOrder = // MatchContract.TeamRankEntry.TABLE_NAME + "." + // MatchContract.TeamRankEntry._ID + " ASC"; // // Cursor c = getContentResolver().query( // MatchContract.TeamEntry.TOP_50_URI, // projection, // null, // null, // sortOrder // ); // // while (c.moveToNext()) { // String teamPrintOut = // "Rank: " + c.getInt(5) + "\n" + // "teamId: " + c.getInt(0) + " teamName: " + c.getString(1) + "\n" + // "teamUrl: " + c.getString(2) + "\n" + // "teamLogoUrl: " + c.getString(3) + "\n" + // "isFavourited: " + (c.getInt(4) == 0 ? "false" : "true"); // LOGD(TAG + "/UTT", teamPrintOut); // } // // c.close(); // use local broadcast manager to hide loading indicator // and signal that cursorloader for top50 can happen. PrefUtils.setLastTeamUpdate(this, currentTime); LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_COMPLETED)); }
From source file:ca.zadrox.dota2esportticker.service.UpdateMatchService.java
private void updateMatches(boolean doResults) { if (!checkForConnectivity()) { LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(UPDATE_NO_CONNECTIVITY)); return;/*from w w w . ja v a 2 s . c om*/ } LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(UPDATE_STARTED)); final String BASE_URL = "http://www.gosugamers.net/dota2/gosubet"; final String MATCH_LINK_URL_BASE = "http://www.gosugamers.net"; try { String rawHtml = new OkHttpClient().newCall(new Request.Builder().url(BASE_URL).build()).execute() .body().string(); rawHtml = rawHtml.substring(rawHtml.indexOf("<div id=\"col1\" class=\"rows\">"), rawHtml.indexOf("<div id=\"col2\" class=\"rows\">")); Document doc = Jsoup.parse(rawHtml); Elements tables = doc.getElementsByClass("matches"); ArrayList<ArrayList<String>> matchLinks = new ArrayList<ArrayList<String>>(tables.size()); int numSeries = 0; for (Element table : tables) { Elements links = table.getElementsByClass("match"); if (links.size() != 0) { ArrayList<String> innerMatchLink = new ArrayList<String>(links.size()); for (Element link : links) { String linkHref = link.attr("href"); innerMatchLink.add(MATCH_LINK_URL_BASE + linkHref); numSeries++; } matchLinks.add(innerMatchLink); } } // needed if there are massive reschedules to update content properly. Uri resultsUri = MatchContract.SeriesEntry.buildSeriesUriWithAfterTime(TimeUtils.getUTCTime()); Cursor c = getContentResolver().query(resultsUri, new String[] { MatchContract.SeriesEntry.COLUMN_GG_MATCH_PAGE }, null, null, null); while (c.moveToNext()) { if (!matchLinks.get(0).contains(c.getString(0))) { matchLinks.get(0).add(c.getString(0)); } } Iterator<ArrayList<String>> iterator = matchLinks.iterator(); int numResults = 0; ExecutorService executorService = Executors.newFixedThreadPool(10); ArrayList<Future<BundledMatchItem>> seriesItemFutures = new ArrayList<Future<BundledMatchItem>>( numSeries); LogUtils.LOGD(TAG, "Starting Retrieval, num elements gathered: " + numSeries); int i = 0; while (iterator.hasNext()) { ArrayList<String> matchList = iterator.next(); for (String matchUrl : matchList) { boolean hasResult = !iterator.hasNext(); if (!doResults && hasResult) { continue; } else if (hasResult) { numResults++; } seriesItemFutures.add(executorService.submit(new MatchGetter(matchUrl, hasResult))); i++; } } executorService.shutdown(); executorService.awaitTermination(20L, TimeUnit.SECONDS); LogUtils.LOGD(TAG, "Stopping Retrieval, elements submitted for fetching: " + i); ContentValues[] seriesEntries = new ContentValues[i]; ContentValues[] resultEntries = new ContentValues[numResults]; int seriesEntryWriteIndex = 0; int resultEntryWriteIndex = 0; for (Future<BundledMatchItem> seriesItemFuture : seriesItemFutures) { try { BundledMatchItem seriesItem = seriesItemFuture.get(); if (seriesItem != null) { seriesEntries[seriesEntryWriteIndex] = seriesItem.mMatch; seriesEntryWriteIndex++; if (seriesItem.hasResult) { resultEntries[resultEntryWriteIndex] = seriesItem.mResult; resultEntryWriteIndex++; } } } catch (ExecutionException e) { Log.e(TAG, "Should never get here"); } } this.getContentResolver().bulkInsert(MatchContract.SeriesEntry.CONTENT_URI, seriesEntries); if (doResults) this.getContentResolver().bulkInsert(MatchContract.ResultEntry.CONTENT_URI, resultEntries); PrefUtils.setLastUpdateTime(this, TimeUtils.getUTCTime()); } catch (IOException e) { Log.e(TAG, e.getMessage(), e); e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(UPDATE_COMPLETE)); PrefUtils.setLastResultsUpdateTime(this, TimeUtils.getUTCTime()); }
From source file:burlov.ultracipher.swing.SwingGuiApplication.java
/** * @param withConfirmation/* w w w . j a va 2 s . c o m*/ * @return 'true' wenn kein Abbruch durch Benutzer */ private boolean createNewCryptor(boolean withConfirmation) { char[] psw = inputPassphrase(withConfirmation, "Passphrase"); if (psw == null) { return false; } CreateCryptorTask task = new CreateCryptorTask(psw); WaitDialog dlg = new WaitDialog(getMainFrame(), "Generate key", task, 0, 100); dlg.start(); try { core.setCryptor(task.get()); } catch (ExecutionException e) { e.getCause().printStackTrace(); showError(e); } catch (InterruptedException e) { e.printStackTrace(); return false; } Arrays.fill(psw, '*'); return true; }
From source file:org.springframework.ide.eclipse.boot.dash.test.CloudFoundryClientTest.java
@Test public void startCanBeCanceled() throws Exception { IProject project = projects.createBootWebProject("slow-starter"); File jarFile = BootJarPackagingTest.packageAsJar(project, ui); String appName = appHarness.randomAppName(); try (CFPushArguments params = new CFPushArguments()) { params.setAppName(appName);/*from w w w .j a va2s. c om*/ params.setRoutes(appName + "." + CFAPPS_IO()); params.setApplicationData(jarFile); params.setNoStart(true); long starting = System.currentTimeMillis(); System.out.println("Pushing..."); client.push(params, CancelationTokens.NULL); long duration = System.currentTimeMillis() - starting; System.out.println("Pushing took: " + duration + " ms"); } CancelationTokens cancelationTokens = new CancelationTokens(); long starting = System.currentTimeMillis(); System.out.println("Starting..."); Future<Void> startResult = doAsync(() -> { client.restartApplication(appName, cancelationTokens.create()); long duration = System.currentTimeMillis() - starting; System.out.println("started in " + duration + " ms"); }); Thread.sleep(5000); long cancelTime = System.currentTimeMillis(); cancelationTokens.cancelAll(); try { startResult.get(5, TimeUnit.SECONDS); } catch (ExecutionException e) { e.printStackTrace(); long duration = System.currentTimeMillis() - cancelTime; assertEquals(OperationCanceledException.class, ExceptionUtil.getDeepestCause(e).getClass()); System.out.println("\nRestart Canceled after " + duration + " ms"); } }
From source file:com.bigdata.dastor.tools.DastorAdminCli.java
public int executeCommand(String[] arguments) throws IOException, InterruptedException { DastorAdminCli nodeCmd = this; if (arguments.length < 1) { System.err.println("Missing argument for command."); printUsage();//from w ww .j a v a 2 s .c om return 1; } String cmdName = arguments[0]; if (cmdName.equals("topo")) { nodeCmd.printRing(System.out); } else if (cmdName.equals("info")) { nodeCmd.printInfo(System.out); } else if (cmdName.equals("cleanup")) { if (arguments.length >= 2) { String[] columnFamilies = new String[arguments.length - 2]; for (int i = 0; i < columnFamilies.length; i++) { columnFamilies[i] = arguments[i + 2]; } probe.forceTableCleanup(arguments[1], columnFamilies); } else { probe.forceTableCleanup(); } } else if (cmdName.equals("compact")) { if (arguments.length >= 3) { String[] columnFamilies = new String[arguments.length - 3]; for (int i = 0; i < columnFamilies.length; i++) { columnFamilies[i] = arguments[i + 3]; } probe.forceTableCompaction(Integer.parseInt(arguments[1]), arguments[2], columnFamilies); } else if (arguments.length == 2) { // compact all keyspaces. probe.forceTableCompaction(Integer.parseInt(arguments[1])); } else { probe.forceTableCompaction(1); } } else if (cmdName.equals("bktstats")) { try { if (arguments.length >= 3) { // print the specified cf ColumnFamilyStoreMBean cfmbean = probe.getColumnFamilyMBean(arguments[1], arguments[2]); nodeCmd.printColumnFamilyStats(System.out, arguments[1], cfmbean); } else if (arguments.length == 2) { // print cfs of the specified ks nodeCmd.printColumnFamilyStats(System.out, arguments[1], false); } else { // print all cfs of all tables nodeCmd.printColumnFamilyStats(System.out, null, false); } } catch (Exception e) { System.err.println("Maybe wrong arguments."); e.printStackTrace(); return 3; } } else if (cmdName.equals("sysstats")) { nodeCmd.printColumnFamilyStats(System.out, null, true); } else if (cmdName.equals("decommission")) { probe.decommission(); } else if (cmdName.equals("loadbalance")) { probe.loadBalance(); } else if (cmdName.equals("move")) { if (arguments.length <= 1) { System.err.println("missing position code argument"); printUsage(); return 1; } probe.move(arguments[1]); } else if (cmdName.equals("removepcode")) { if (arguments.length <= 1) { System.err.println("missing position code argument"); printUsage(); return 1; } probe.removeToken(arguments[1]); } else if (cmdName.equals("snapshot")) { String snapshotName = ""; if (arguments.length > 1) { snapshotName = arguments[1]; } probe.takeSnapshot(snapshotName); } else if (cmdName.equals("csnapshot")) { probe.clearSnapshot(); } else if (cmdName.equals("thstats")) { nodeCmd.printThreadPoolStats(System.out); } else if (cmdName.equals("flush") || cmdName.equals("repair")) { if (arguments.length < 2) { System.err.println("Missing space name argument."); printUsage(); return 1; } String[] columnFamilies = new String[arguments.length - 2]; for (int i = 0; i < columnFamilies.length; i++) { columnFamilies[i] = arguments[i + 2]; } if (cmdName.equals("flush")) probe.forceTableFlush(arguments[1], columnFamilies); else // cmdName.equals("repair") probe.forceTableRepair(arguments[1], columnFamilies); } else if (cmdName.equals("drain")) { try { probe.drain(); } catch (ExecutionException ee) { System.err.println("Error occured during flushing"); ee.printStackTrace(); return 3; } } else if (cmdName.equals("setcachecap")) { if (arguments.length != 5) { System.err.println( "cacheinfo requires space and bucket name arguments, followed by key cache capacity and row cache capacity, in rows"); printUsage(); return 1; } String tableName = arguments[1]; String cfName = arguments[2]; int keyCacheCapacity = Integer.valueOf(arguments[3]); int rowCacheCapacity = Integer.valueOf(arguments[4]); probe.setCacheCapacities(tableName, cfName, keyCacheCapacity, rowCacheCapacity); } else if (cmdName.equals("getcmthresh")) { probe.getCompactionThreshold(System.out); } else if (cmdName.equals("setcmthresh")) { if (arguments.length < 2) { System.err.println("Missing threshold value(s)"); printUsage(); return 1; } int minthreshold = Integer.parseInt(arguments[1]); int maxthreshold = CompactionManager.instance.getMaximumCompactionThreshold(); if (arguments.length > 2) { maxthreshold = Integer.parseInt(arguments[2]); } if (minthreshold > maxthreshold) { System.err.println("Min threshold can't be greater than Max threshold"); printUsage(); return 1; } if (minthreshold < 2 && maxthreshold != 0) { System.err.println("Min threshold must be at least 2"); printUsage(); return 1; } probe.setCompactionThreshold(minthreshold, maxthreshold); } else if (cmdName.equals("streams")) { String otherHost = arguments.length > 1 ? arguments[1] : null; nodeCmd.printStreamInfo(otherHost == null ? null : InetAddress.getByName(otherHost), System.out); } else if (cmdName.equals("pxystats")) { nodeCmd.printProxyStats(System.out); } else if (cmdName.equals("cmstats")) { nodeCmd.printCompactionStats(System.out); } else if (cmdName.equals("ddstats")) { nodeCmd.printHhStats(System.out); } else if (cmdName.equals("gc")) { nodeCmd.requestGC(); } else if (cmdName.equals("dlvhints")) { if (arguments.length < 2) { System.err.println("Missing node host/ipaddr!"); printUsage(); return 1; } nodeCmd.deliverHints(arguments[1]); } // Following commands for cluster wide. else if (cmdName.equals("gsnapshot")) { String snapshotName = ""; if (arguments.length > 1) { snapshotName = arguments[1]; } nodeCmd.takeGlobalSnapshot(snapshotName); } else if (cmdName.equals("gcsnapshot")) { nodeCmd.clearGlobalSnapshot(); } else if (cmdName.equals("gresetbkt")) { if (arguments.length < 3) { System.err.println("Missing space or bucket name arguments."); printUsage(); return 1; } try { if ((arguments.length >= 4) && arguments[3].equals("undo")) probe.getStorageProxyMBean().graceResetClusterCFUndo(arguments[1], arguments[2]); else probe.getStorageProxyMBean().graceResetClusterCF(arguments[1], arguments[2]); } catch (Exception e) { System.err.println("Error occured during reseting!"); e.printStackTrace(); return 3; } } else if (cmdName.equals("keydist")) { if (arguments.length < 3) { System.err.println("Missing space or key arguments."); printUsage(); return 1; } List<InetAddress> eps = probe.getEndPoints(arguments[1], arguments[2]); for (InetAddress ep : eps) { System.out.println(ep); } } else { System.err.println("Unrecognized command: " + cmdName + "."); printUsage(); return 1; } return 0; }
From source file:org.springframework.ide.eclipse.boot.dash.test.CloudFoundryClientTest.java
@Test public void pushCanBeCanceled() throws Exception { String appName = appHarness.randomAppName(); IProject project = projects.createBootWebProject("slow-starter"); File jarFile = BootJarPackagingTest.packageAsJar(project, ui); CancelationTokens cancelationTokens = new CancelationTokens(); try (CFPushArguments params = new CFPushArguments()) { params.setAppName(appName);// w ww .j a va2 s . c o m params.setRoutes(appName + "." + CFAPPS_IO()); params.setApplicationData(jarFile); long starting = System.currentTimeMillis(); Future<Void> pushResult = doAsync(() -> { System.out.println("Pushing..."); client.push(params, cancelationTokens.create()); long duration = System.currentTimeMillis() - starting; System.out.println("Pushing took: " + duration + " ms"); }); Thread.sleep(Duration.ofSeconds(10).toMillis()); long cancelTime = System.currentTimeMillis(); System.out.println("Canceling..."); cancelationTokens.cancelAll(); try { pushResult.get(5, TimeUnit.SECONDS); // Cancel should happen pretty 'fast'! fail("push completed but it should have been canceled"); } catch (ExecutionException e) { // real exception is wrapped in EE by Future.get e.printStackTrace(); long duration = System.currentTimeMillis() - cancelTime; assertEquals(OperationCanceledException.class, ExceptionUtil.getDeepestCause(e).getClass()); System.out.println("\nPush Canceled after: " + duration + " ms"); } } }
From source file:io.hops.security.TestUsersGroups.java
public void testConcurrentAddUser(int cacheTime, int cacheSize) throws Exception { Configuration conf = new Configuration(); conf.set(CommonConfigurationKeys.HOPS_UG_CACHE_SECS, Integer.toString(cacheTime)); conf.set(CommonConfigurationKeys.HOPS_UG_CACHE_SIZE, Integer.toString(cacheSize)); HdfsStorageFactory.resetDALInitialized(); HdfsStorageFactory.setConfiguration(conf); HdfsStorageFactory.formatStorage();/*from w ww . j a v a 2s . c om*/ UsersGroups.createSyncRow(); final String userName = "user1"; final String groupNmae = "group1"; final int CONCURRENT_USERS = 100; ExecutorService executorService = Executors.newFixedThreadPool(CONCURRENT_USERS); List<Callable<Integer>> callables = new ArrayList<>(); for (int i = 0; i < CONCURRENT_USERS; i++) { callables.add(new AddUser(userName, groupNmae)); } List<Future<Integer>> futures = executorService.invokeAll(callables); executorService.shutdown(); executorService.awaitTermination(10, TimeUnit.SECONDS); UsersGroups.clearCache(); for (Future<Integer> f : futures) { try { f.get(); } catch (ExecutionException ex) { ex.printStackTrace(); fail(); } } }
From source file:my.home.lehome.service.SendMsgIntentService.java
private void dispatchCommand(final Intent intent) { String cmd = intent.getStringExtra("cmdString"); String servelURL = intent.getStringExtra("serverUrl"); String deviceID = intent.getStringExtra("deviceID"); boolean local = intent.getBooleanExtra("local", false); Log.d(TAG, "dispatch cmd:" + cmd + " | servelURL:" + servelURL + " | deviceID:" + deviceID + " | local:" + local);/*from www . ja v a 2 s .co m*/ final Context context = getApplicationContext(); if (local) { if (TextUtils.isEmpty(servelURL)) { saveAndNotify(intent, CommandRequest.getJsonStringResponse(400, context.getString(R.string.msg_local_saddress_not_set))); } } else { if (TextUtils.isEmpty(deviceID)) { saveAndNotify(intent, CommandRequest.getJsonStringResponse(400, context.getString(R.string.msg_no_deviceid))); } if (TextUtils.isEmpty(servelURL)) { saveAndNotify(intent, CommandRequest.getJsonStringResponse(400, context.getString(R.string.msg_saddress_not_set))); } } RequestFuture<String> future = RequestFuture.newFuture(); CommandRequest request = new CommandRequest(local ? Request.Method.POST : Request.Method.GET, // diff servelURL, cmd, future, future); mRequestQueue.add(request); try { String response = future.get(request.getTimeoutMs() + 10000, TimeUnit.MILLISECONDS); Log.d(TAG, "get cmd response:" + response); saveAndNotify(intent, CommandRequest.getJsonStringResponse(200, response)); } catch (ExecutionException e) { Throwable error = e.getCause(); Log.d(TAG, "get cmd error:" + error.toString()); String errorString = context.getString(R.string.error_unknown); int errorCode = 400; if (error instanceof ServerError) { errorString = context.getString(R.string.chat_error_conn); errorCode = 400; } else if (error instanceof TimeoutError) { errorString = context.getString(R.string.chat_error_http_error); errorCode = 400; } else if (error instanceof ParseError) { errorString = context.getString(R.string.chat_error_http_error); errorCode = 400; } else if (error instanceof NoConnectionError) { errorString = context.getString(R.string.chat_error_no_connection_error); errorCode = 400; } saveAndNotify(intent, CommandRequest.getJsonStringResponse(errorCode, errorString)); } catch (TimeoutException e) { saveAndNotify(intent, CommandRequest.getJsonStringResponse(400, context.getString(R.string.chat_error_http_error))); } catch (Exception e) { future.cancel(true); e.printStackTrace(); // saveAndNotify(intent, // CommandRequest.getJsonStringResponse( // 400, // context.getString(R.string.error_internal) // )); } }
From source file:at.itbh.bev.rest.client.BevRestClient.java
/** * Query the ReST endpoint using the command line arguments * /*from w w w . j ava2 s . c o m*/ * @param args * the command line arguments */ public void query(String[] args) { BevQueryExecutor executor = null; ResteasyClientBuilder clientBuilder = new ResteasyClientBuilder(); try { // parse the command line arguments CommandLine line = parser.parse(options, args); int threadPoolSize = 1; if (line.hasOption("t")) { threadPoolSize = Integer.parseInt(line.getOptionValue("t")); } String postalCode = null; String place = null; String addressLine = null; String houseId = null; String radius = null; String longitude = null; String latitude = null; String separator = ";"; boolean enforceUnique = false; if (line.hasOption("z")) { postalCode = line.getOptionValue("z"); } if (line.hasOption("p")) { place = line.getOptionValue("p"); } if (line.hasOption("a")) { addressLine = line.getOptionValue("a"); } if (line.hasOption("i")) { houseId = line.getOptionValue("i"); } if (line.hasOption("radius")) { radius = line.getOptionValue("radius"); } if (line.hasOption("longitude")) { longitude = line.getOptionValue("longitude"); } if (line.hasOption("latitude")) { latitude = line.getOptionValue("latitude"); } if (line.hasOption("s")) { separator = line.getOptionValue("s"); } if (line.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar BevRestClient.jar", options, true); System.exit(0); } if (line.hasOption("u")) { enforceUnique = true; } if (line.hasOption("disable-certificate-validation")) { clientBuilder.disableTrustManager(); } if (!line.hasOption("proxy-port") && line.hasOption("proxy-host")) { throw new ParseException( "The option --proxy-host is only allowed in combination with the option --proxy-port."); } if (line.hasOption("proxy-port") && !line.hasOption("proxy-host")) { throw new ParseException( "The option --proxy-port is only allowed in combination with the option --proxy-host."); } if (line.hasOption("proxy-host") && line.hasOption("proxy-port")) { clientBuilder.defaultProxy(line.getOptionValue("proxy-host"), Integer.parseInt(line.getOptionValue("proxy-port"))); } OutputStreamWriter output; if (line.hasOption("o")) { output = new OutputStreamWriter(new FileOutputStream(line.getOptionValue("o"))); } else { output = new OutputStreamWriter(System.out); } // avoid concurrent access exceptions in the Apache http client clientBuilder.connectionPoolSize(threadPoolSize); executor = new BevQueryExecutor(clientBuilder.build(), line.getOptionValue("r"), threadPoolSize); CsvPreference csvPreference = new CsvPreference.Builder('"', Objects.toString(line.getOptionValue("s"), ";").toCharArray()[0], System.getProperty("line.separator")).build(); csvWriter = new CsvMapWriter(output, csvPreference, true); if (line.hasOption("b")) { ICsvMapReader mapReader = null; try { FileReader fileReader = new FileReader(line.getOptionValue("b")); mapReader = new CsvMapReader(fileReader, csvPreference); // calculate the output header (field names) final String[] header = mapReader.getHeader(true); ArrayList<String> tempFields = new ArrayList<>(Arrays.asList(defaultFieldNames)); for (int i = 0; i < header.length; i++) { if (!tempFields.contains(header[i])) { tempFields.add(header[i]); } } fieldNames = tempFields.toArray(new String[] {}); Map<String, String> inputData; List<Future<List<BevQueryResult>>> queryResults = new ArrayList<>(); while ((inputData = mapReader.read(header)) != null) { queryResults .add(executor.query(inputData.get(INPUT_POSTAL_CODE), inputData.get(INPUT_PLACE), inputData.get(INPUT_ADDRESS_LINE), inputData.get(INPUT_HOUSE_ID), inputData.get(INPUT_LONGITUDE), inputData.get(INPUT_LATITUDE), inputData.get(INPUT_RADIUS), inputData.get(INPUT_ENFORCE_UNIQUE) == null ? false : Boolean.parseBoolean(inputData.get(INPUT_ENFORCE_UNIQUE)), inputData)); } csvWriter.writeHeader(fieldNames); for (Future<List<BevQueryResult>> queryResult : queryResults) { List<BevQueryResult> results = queryResult.get(); outputResults(separator, results); } } finally { if (mapReader != null) { mapReader.close(); } } } else { fieldNames = defaultFieldNames; Map<String, String> inputData = new HashMap<String, String>(); Future<List<BevQueryResult>> queryResult = executor.query(postalCode, place, addressLine, houseId, longitude, latitude, radius, enforceUnique, inputData); try { List<BevQueryResult> results = queryResult.get(); if (enforceUnique && results.size() == 1) { if (!results.get(0).getFoundMatch()) throw new Exception("No unique result found."); } outputResults(separator, results); } catch (ExecutionException e) { throw e.getCause(); } } } catch (ParseException exp) { System.out.println(exp.getMessage()); System.out.println(); // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar BevRestClient.jar", options, true); System.exit(-2); } catch (BevRestException e) { System.err.println(e.toString()); System.exit(e.getErrorCode()); } catch (JsonProcessingException e) { System.err.println(e.toString()); System.exit(-3); } catch (IOException e) { System.err.println(e.toString()); System.exit(-4); } catch (Throwable t) { System.err.println(t.toString()); t.printStackTrace(); System.exit(-1); } finally { if (csvWriter != null) { try { csvWriter.close(); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } } if (executor != null) { executor.dispose(); } } }