List of usage examples for java.lang Throwable Throwable
public Throwable()
From source file:hudson.ClassicPluginStrategy.java
public <T> List<ExtensionComponent<T>> findComponents(Class<T> type, Hudson hudson) { List<ExtensionFinder> finders; if (type == ExtensionFinder.class) { // Avoid infinite recursion of using ExtensionFinders to find ExtensionFinders finders = Collections.<ExtensionFinder>singletonList(new ExtensionFinder.Sezpoz()); } else {/* w w w .j a v a2 s . com*/ finders = hudson.getExtensionList(ExtensionFinder.class); } /** * See {@link ExtensionFinder#scout(Class, Hudson)} for the dead lock issue and what this does. */ if (LOGGER.isLoggable(Level.FINER)) LOGGER.log(Level.FINER, "Scout-loading ExtensionList: " + type, new Throwable()); for (ExtensionFinder finder : finders) { finder.scout(type, hudson); } List<ExtensionComponent<T>> r = Lists.newArrayList(); for (ExtensionFinder finder : finders) { try { r.addAll(finder.find(type, hudson)); } catch (AbstractMethodError e) { // backward compatibility for (T t : finder.findExtensions(type, hudson)) r.add(new ExtensionComponent<T>(t)); } } List<ExtensionComponent<T>> filtered = Lists.newArrayList(); for (ExtensionComponent<T> e : r) { if (ExtensionFilter.isAllowed(type, e)) filtered.add(e); } return filtered; }
From source file:mondrian.test.DiffRepository.java
/** * Returns the name of the current testcase by looking up the call * stack for a method whose name starts with "test", for example * "testFoo".//w ww. j a v a2 s . c o m * * @param fail Whether to fail if no method is found * @return Name of current testcase, or null if not found */ public String getCurrentTestCaseName(boolean fail) { // check thread-local first String testCaseName = CurrentTestCaseName.get(); if (testCaseName != null) { return testCaseName; } // Clever, this. Dump the stack and look up it for a method which // looks like a testcase name, e.g. "testFoo". final StackTraceElement[] stackTrace; //noinspection ThrowableInstanceNeverThrown Throwable runtimeException = new Throwable(); runtimeException.fillInStackTrace(); stackTrace = runtimeException.getStackTrace(); for (StackTraceElement stackTraceElement : stackTrace) { final String methodName = stackTraceElement.getMethodName(); if (methodName.startsWith("test")) { return methodName; } } if (fail) { throw new RuntimeException("no testcase on current callstack"); } else { return null; } }
From source file:org.ebayopensource.turmeric.eclipse.utils.wsdl.WSDLUtil.java
/** * Gets the service location from wsdl./* w ww . ja v a 2s. c o m*/ * * @param wsdl the wsdl * @return the service location from wsdl */ public static String getServiceLocationFromWSDL(final Definition wsdl) { String serviceLocation = null; if (wsdl != null && wsdl.getServices().isEmpty() == false) { for (Object obj : ((javax.wsdl.Service) (wsdl.getServices().values().toArray()[0])).getPorts() .values()) { javax.wsdl.Port port = (javax.wsdl.Port) obj; if (port.getExtensibilityElements().size() > 0) { Object elem = port.getExtensibilityElements().get(0); if (elem instanceof javax.wsdl.extensions.http.HTTPAddress) { serviceLocation = ((javax.wsdl.extensions.http.HTTPAddress) elem).getLocationURI(); break; } else if (elem instanceof javax.wsdl.extensions.soap.SOAPAddress) { serviceLocation = ((javax.wsdl.extensions.soap.SOAPAddress) elem).getLocationURI(); break; } else { try { final Method method = elem.getClass().getMethod("getLocationURI"); final Object result = method.invoke(elem); if (result != null) { serviceLocation = result.toString(); //although we have found the service location, //but we would still prefer the http and soap addresses, //thus we will not break from the loop. } } catch (Exception e) { StackTraceElement[] elements = new Throwable().getStackTrace(); Logger.getLogger(WSDLUtil.class.getName()).throwing(elements[0].getClassName(), elements[0].getMethodName(), e); } } } } } return serviceLocation; }
From source file:com.android.leanlauncher.Workspace.java
/** * Adds the specified child in the specified screen. The position and dimension of * the child are defined by x, y, spanX and spanY. * * @param child The child to add in one of the workspace's screens. * @param x The X position of the child in the screen's grid. * @param y The Y position of the child in the screen's grid. * @param spanX The number of cells spanned horizontally by the child. * @param spanY The number of cells spanned vertically by the child. * @param insert When true, the child is inserted at the beginning of the children list. *//*from w ww .j a va 2 s . c om*/ void addInScreen(View child, long container, int x, int y, int spanX, int spanY, boolean insert) { if (container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { if (getScreen() == null) { Log.e(TAG, "Skipping child, screen not found"); // DEBUGGING - Print out the stack trace to see where we are adding from new Throwable().printStackTrace(); return; } } final CellLayout layout; layout = getScreen(); child.setOnKeyListener(new IconKeyEventListener()); ViewGroup.LayoutParams genericLp = child.getLayoutParams(); CellLayout.LayoutParams lp; if (genericLp == null || !(genericLp instanceof CellLayout.LayoutParams)) { lp = new CellLayout.LayoutParams(x, y, spanX, spanY); } else { lp = (CellLayout.LayoutParams) genericLp; lp.cellX = x; lp.cellY = y; lp.cellHSpan = spanX; lp.cellVSpan = spanY; } if (spanX < 0 && spanY < 0) { lp.isLockedToGrid = false; } // Get the canonical child id to uniquely represent this view in this screen ItemInfo info = (ItemInfo) child.getTag(); int childId = LauncherAppState.getInstance().getViewIdForItem(info); if (!layout.addViewToCellLayout(child, insert ? 0 : -1, childId, lp, true)) { // TODO: This branch occurs when the workspace is adding views // outside of the defined grid // maybe we should be deleting these items from the LauncherModel? Log.d(TAG, "Failed to add to item at (" + lp.cellX + "," + lp.cellY + ") to CellLayout"); } child.setHapticFeedbackEnabled(false); child.setOnLongClickListener(mLauncher); if (child instanceof DropTarget) { mDragController.addDropTarget((DropTarget) child); } }
From source file:com.android.mail.ui.TwoPaneController.java
/** * Pops the "view stack" to the last screen the user was viewing. * * @param preventClose Whether to prevent closing the app if the stack is empty. *//* www.ja v a 2 s . com*/ protected void popView(boolean preventClose) { // If the user is in search query entry mode, or the user is viewing // search results, exit // the mode. int mode = mViewMode.getMode(); if (mode == ViewMode.SEARCH_RESULTS_LIST) { mActivity.finish(); } else if (mode == ViewMode.CONVERSATION || mViewMode.isAdMode()) { // Go to conversation list. mViewMode.enterConversationListMode(); } else if (mode == ViewMode.SEARCH_RESULTS_CONVERSATION) { mViewMode.enterSearchResultsListMode(); } else { // The Folder List fragment can be null for monkeys where we get a back before the // folder list has had a chance to initialize. final FolderListFragment folderList = getFolderListFragment(); if (mode == ViewMode.CONVERSATION_LIST && folderList != null && mFolder != null && mFolder.parent != Uri.EMPTY) { // If the user navigated via the left folders list into a child folder, // back should take the user up to the parent folder's conversation list. navigateUpFolderHierarchy(); // Otherwise, if we are in the conversation list but not in the default // inbox and not on expansive layouts, we want to switch back to the default // inbox. This fixes b/9006969 so that on smaller tablets where we have this // hybrid one and two-pane mode, we will return to the inbox. On larger tablets, // we will instead exit the app. } else { // Don't think mLayout could be null but checking just in case if (mLayout == null) { LogUtils.wtf(LOG_TAG, new Throwable(), "mLayout is null"); } // mFolder could be null if back is pressed while account is waiting for sync final boolean shouldLoadInbox = mode == ViewMode.CONVERSATION_LIST && mFolder != null && !mFolder.folderUri.equals(mAccount.settings.defaultInbox) && mLayout != null && !mLayout.isExpansiveLayout(); if (shouldLoadInbox) { loadAccountInbox(); } else if (!preventClose) { // There is nothing else to pop off the stack. mActivity.finish(); } } } }
From source file:org.eclipse.epp.internal.logging.aeri.ui.LogListenerTest.java
@Test public void testServerProblemIgnoreHandled() { Throwable t1 = new Throwable(); t1.fillInStackTrace();//from w w w . j a v a2 s .c o m Status s1 = new Status(IStatus.ERROR, TEST_PLUGIN_ID, "test message", t1); ErrorReport report = Reports.newErrorReport(s1, settings, configuration); ProblemStatus status = new ProblemStatus(); status.setIncidentFingerprint(Reports.traceIdentityHash(report)); status.setBugUrl("http://the.url"); status.setAction(RequiredAction.IGNORE); when(problemStatusIndex.seen(org.mockito.Matchers.any(ErrorReport.class))).thenReturn(Optional.of(status)); sut.logging(s1, ""); verifyNoErrorReportLogged(); }
From source file:alma.acs.logging.AcsLogger.java
/** * Logs the given <code>LogRecord</code>. * The record can be modified or dropped by the optional filters provided in {@link #addLogRecordFilter(alma.acs.logging.AcsLogger.LogRecordFilter)}. * <p>// w w w. ja v a2s. c o m * Adding of context information: * <ul> * <li> If the LogRecord has a parameter that is a map which contains additional information * about the line of code, thread, etc., the log record will be taken as provided, and no context * information will be added. This can be useful if * <ul> * <li> the log record was reconstructed from a remote error by the ACS error handling code * (see <code>AcsJException</code>), or * <li> if in very exceptional cases application code needs to manipulate such information by hand. * </ul> * <li> otherwise, context information is inferred, similar to {@link LogRecord#inferCaller()}, * but additionally including thread name and line of code. * </ul> * Note that by overloading this method, we intercept all logging activities of the base class. * * @see java.util.logging.Logger#log(java.util.logging.LogRecord) */ public void log(LogRecord record) { // Throw exception if level OFF was used to log this record, see http://jira.alma.cl/browse/COMP-1928 // Both Level.OFF and AcsLogLevel.OFF use the same value INTEGER.max, but we anyway check for both. if (record.getLevel().intValue() == Level.OFF.intValue() || record.getLevel().intValue() == AcsLogLevel.OFF.intValue()) { throw new IllegalArgumentException( "Level OFF must not be used for actual logging, but only for level filtering."); } StopWatch sw_all = null; if (PROFILE) { sw_all = new StopWatch(null); } // Level could be null and must then be inherited from the ancestor loggers, // e.g. during JDK shutdown when the log level is nulled by the JDK LogManager Logger loggerWithLevel = this; while (loggerWithLevel != null && loggerWithLevel.getLevel() == null && loggerWithLevel.getParent() != null) { loggerWithLevel = loggerWithLevel.getParent(); } int levelValue = -1; if (loggerWithLevel.getLevel() == null) { // HSO 2007-09-05: With ACS 6.0.4 the OMC uses this class (previously plain JDK logger) and has reported // that no level was found, which yielded a NPE. To be investigated further. // Probably #createUnconfiguredLogger was used without setting parent logger nor log level. // Just to be safe I add the necessary checks and warning message that improve over a NPE. if (!noLevelWarningPrinted) { System.out.println("Logger configuration error: no log level found for logger " + getLoggerName() + " or its ancestors. Will use Level.ALL instead."); noLevelWarningPrinted = true; } // @TODO: decide if resorting to ALL is desirable, or to use schema defaults, INFO, etc levelValue = Level.ALL.intValue(); } else { // level is fine, reset the flag to print the error message again when log level is missing. noLevelWarningPrinted = false; levelValue = loggerWithLevel.getLevel().intValue(); } // filter by log level to avoid unnecessary retrieval of context data. // The same check will be repeated by the base class implementation of this method that gets called afterwards. if (record.getLevel().intValue() < levelValue || levelValue == offValue) { return; } // modify the logger name if necessary if (loggerName != null) { record.setLoggerName(loggerName); } // check if this record already has the context data attached which ACS needs but the JDK logging API does not provide LogParameterUtil paramUtil = new LogParameterUtil(record); Map<String, Object> specialProperties = paramUtil.extractSpecialPropertiesMap(); if (specialProperties == null) { // we prepend the special properties map to the other parameters specialProperties = LogParameterUtil.createPropertiesMap(); List<Object> paramList = paramUtil.getNonSpecialPropertiesMapParameters(); paramList.add(0, specialProperties); record.setParameters(paramList.toArray()); String threadName = Thread.currentThread().getName(); specialProperties.put(LogParameterUtil.PARAM_THREAD_NAME, threadName); specialProperties.put(LogParameterUtil.PARAM_PROCESSNAME, this.processName); specialProperties.put(LogParameterUtil.PARAM_SOURCEOBJECT, this.sourceObject); // Get the stack trace StackTraceElement stack[] = (new Throwable()).getStackTrace(); // search for the first frame before the "Logger" class. int ix = 0; boolean foundNonLogFrame = false; while (ix < stack.length) { StackTraceElement frame = stack[ix]; String cname = frame.getClassName(); if (!foundNonLogFrame && !loggerClassNames.contains(cname)) { // We've found the relevant frame. record.setSourceClassName(cname); record.setSourceMethodName(frame.getMethodName()); int lineNumber = frame.getLineNumber(); specialProperties.put(LogParameterUtil.PARAM_LINE, Long.valueOf(lineNumber)); foundNonLogFrame = true; if (this.callStacksToBeIgnored.isEmpty()) { break; // performance optimization: avoid checking all "higher" stack frames } } if (foundNonLogFrame) { if (callStacksToBeIgnored.contains(concatenateIgnoreLogData(cname, frame.getMethodName()))) { //System.out.println("Won't log record with message " + record.getMessage()); return; } } ix++; } // We haven't found a suitable frame, so just punt. This is // OK as we are only committed to making a "best effort" here. } StopWatch sw_afterAcsLogger = null; if (PROFILE) { sw_afterAcsLogger = sw_all.createStopWatchForSubtask("afterAcsLogger"); LogParameterUtil logParamUtil = new LogParameterUtil(record); logParamUtil.setStopWatch(sw_afterAcsLogger); } // Let the delegate or Logger base class handle the rest. if (delegate != null) { delegate.log(record); } else { super.log(record); } if (PROFILE) { sw_afterAcsLogger.stop(); sw_all.stop(); long elapsedNanos = sw_all.getLapTimeNanos(); if (profileSlowestCallStopWatch == null || profileSlowestCallStopWatch.getLapTimeNanos() < elapsedNanos) { profileSlowestCallStopWatch = sw_all; } profileLogTimeStats.addValue(elapsedNanos); if (profileLogTimeStats.getN() >= profileStatSize) { String msg = "Local logging times in ms for the last " + profileStatSize + " logs: "; msg += "mean=" + profileMillisecFormatter.format(profileLogTimeStats.getMean() * 1E-6); msg += ", median=" + profileMillisecFormatter.format(profileLogTimeStats.getPercentile(50) * 1E-6); msg += ", stdev=" + profileMillisecFormatter.format(profileLogTimeStats.getStandardDeviation() * 1E-6); msg += "; details of slowest log (from "; msg += IsoDateFormat.formatDate(profileSlowestCallStopWatch.getStartTime()) + "): "; msg += profileSlowestCallStopWatch.getSubtaskDetails(); System.out.println(msg); profileSlowestCallStopWatch = null; profileLogTimeStats.clear(); } } }
From source file:com.alibaba.wasp.MiniWaspCluster.java
/** * Do a simulated kill all masters and entityGroups servers. Useful when it is * impossible to bring the mini-cluster back for clean shutdown. *///from w w w . j a v a 2s. co m public void killAll() { for (JVMClusterUtil.FServerThread rst : getFServerThreads()) { rst.getFServer().abort("killAll"); } for (JVMClusterUtil.MasterThread masterThread : getMasterThreads()) { masterThread.getMaster().abort("killAll", new Throwable()); } }
From source file:org.dspace.storage.rdbms.MockDatabaseManager.java
/** * Obtain an RDBMS connection.// w w w .j a v a 2 s. c o m * * @return A new database connection. * @exception SQLException * If a database error occurs, or a connection cannot be * obtained. */ @Mock public static Connection getConnection() throws SQLException { initialize(); //we need to find who creates so many connections Throwable t = new Throwable(); StackTraceElement[] elements = t.getStackTrace(); String callers = ""; for (int i = 0; i < Math.min(elements.length, 4); i++) { callers += " > " + elements[i].getClassName() + ":" + elements[i].getMethodName(); } //uncomment to see the infromation on callers //log.info(callers+" ("+connectionPool.getNumActive()+" "+connectionPool.getNumIdle()+")"); return DriverManager.getConnection("jdbc:apache:commons:dbcp:" + poolName); }
From source file:com.alipay.vbizplatform.web.controller.MyCarManageController.java
/** * ?//w w w . ja v a2s. c om * @param request * @param response * @return */ @RequestMapping("/queryCarSeries") public String queryCarSeries(HttpServletRequest request, HttpServletResponse response) { logger.info("uid={},class={},method=queryCarSeries,desc=", super.getUserInfo(request).getUid(), this.getClass().getName()); Map<String, String> pageParam = super.getParametersFromPage(request); long startTime = System.currentTimeMillis(); String brandName = null; // ? String picUrl = null; // String bgUrl = null; String uId = null; //? Map<String, List<Map<String, Object>>> vehicleSeciesMap = null; try { uId = super.getUserInfo(request).getUid(); if (StringUtils.isNotEmpty(pageParam.get("brandName"))) { // ? brandName = URLDecoder.decode(pageParam.get("brandName"), "UTF-8"); } if (StringUtils.isNotEmpty(pageParam.get("picUrl"))) { // ?id picUrl = URLDecoder.decode(pageParam.get("picUrl"), "UTF-8"); } if (StringUtils.isNotEmpty(pageParam.get("bgUrl"))) { // ? bgUrl = URLDecoder.decode(pageParam.get("bgUrl"), "UTF-8"); } // ?session //request.getSession().setAttribute("newVehicleModel", vo); // 1??? vehicleSeciesMap = myCarManageService.getVehicleSecies(brandName); request.setAttribute("viId", ObjectUtil.toString(pageParam.get("viId"))); request.setAttribute("carSeriesMap", vehicleSeciesMap); request.setAttribute("brandName", brandName); request.setAttribute("picUrl", picUrl); request.setAttribute("bgUrl", bgUrl); request.setAttribute("upst", pageParam.get("upst")); request.setAttribute("newCarFlag", pageParam.get("newCarFlag")); } catch (Exception e) { if (logger.isErrorEnabled()) { logger.error("?", e); } logUtil.log(new Throwable(), "CARSERIES", uId, MethodCallResultEnum.EXCEPTION, null, "?", startTime); super.redirectErrorPage("BUSY-ERR", "??", null, null, response); return null; } if (logger.isInfoEnabled()) { logger.info("??,uid={},toPage->page/cars/selectCarSeries.jsp", super.getUserInfo(request).getUid()); } logUtil.log(new Throwable(), "CARSERIES", uId, MethodCallResultEnum.SUCCESS, null, "??", startTime); return "page/cars/selectCarSeries"; }