Example usage for java.lang Throwable fillInStackTrace

List of usage examples for java.lang Throwable fillInStackTrace

Introduction

In this page you can find the example usage for java.lang Throwable fillInStackTrace.

Prototype

public synchronized Throwable fillInStackTrace() 

Source Link

Document

Fills in the execution stack trace.

Usage

From source file:org.eclipse.epp.internal.logging.aeri.ui.LogListenerTest.java

@Test
public void testLinkageErrorCommentAdded() {
    Throwable e3 = new RuntimeException();
    e3.fillInStackTrace();
    ClassNotFoundException e2 = new ClassNotFoundException(StringUtils.class.getName(), e3);
    Throwable e1 = new Throwable("test", e2);
    Status status = new Status(IStatus.ERROR, TEST_PLUGIN_ID, "test message", e1);

    sut.logging(status, "");

    ErrorReport report = pollEvent().report;
    assertThat(report.getComment(), not(isEmptyOrNullString()));
}

From source file:com.zz.cluster4spring.support.provider.AbstractDiscoveringEndpointProvider.java

/**
 * Marks given endpoint invalid. This endpoint will not be later used for
 * methods invocation. Method removes endpoint from cache (if configured to
 * cache endpoints) and later marks particular service url invalid via
 * ConsumingRegistry.//from  www  . j  av a2s.  c  o m
 *
 * @param aBeanName
 *            name of bean that is used as proxy for remote service
 * @param aEndpoint
 *            endpoint to be marked invalid
 * @see #setCacheEndpoints(boolean)
 */
public void markInvalid(String aBeanName, E aEndpoint) {
    if (fLog.isTraceEnabled()) {
        String message = format("Starting endpoint invalidation. Bean Name: [{0}] Endpoint Info: [{1}]",
                aBeanName, aEndpoint.getServiceInfo());
        Throwable e = new Exception();
        e.fillInStackTrace();
        fLog.trace(message, e);
    }

    synchronized (this) {
        if (cacheEndpoints) {
            synchronized (cacheLock) {
                cachedEndpoints.remove(aEndpoint);
            }
        }
        Set<SI> cachedServiceInfos = null;
        String serviceKey = obtainServiceKey(aBeanName);
        try {
            // TMP revisit this - this call may lead to not necessary
            // discovering of the
            // TMP service. Probably it's better to add some method like
            // "hasLocalItems()"
            // TMP into ConsumingRegistry
            cachedServiceInfos = obtainServiceUrlsFromRegistry(serviceKey);
        } catch (Exception e) {
            if (fLog.isErrorEnabled()) {
                String message = format(
                        "Unable to obtain list of service urls from registry. Service Name is [{0}] bean name is [{1}]",
                        fServiceName, aBeanName);
                fLog.error(message, e);
            }
        }
        if (cachedServiceInfos != null) {
            SI serviceUrl = aEndpoint.getServiceInfo();
            markServiceInvalidInternal(serviceKey, cachedServiceInfos, serviceUrl);
        }
    }
}

From source file:org.unitils.mock.core.MockObject.java

/**
 * Defines behavior for this mock so that it raises the given exception when the invocation following
 * this call matches the observed behavior. E.g.
 * <p/>//from   w w w.j a  va  2 s  . c o m
 * mock.raises(MyException.class).method1();
 * <p/>
 * will throw an instance of the given exception class when method1 is called.
 * <p/>
 * Note that this behavior is executed each time a match is found. So the exception will be raised
 * each time method1() is called. If you only want to raise the exception once, use the {@link #onceRaises} method.
 *
 * @param exceptionClass The type of exception to raise, not null
 * @return The proxy instance that will record the method call, not null
 */
@MatchStatement
public T raises(Class<? extends Throwable> exceptionClass) {
    Throwable exception = createInitializedOrUninitializedInstanceOfType(exceptionClass);
    exception.fillInStackTrace();
    MatchingInvocationHandler matchingInvocationHandler = createAlwaysMatchingBehaviorDefiningMatchingInvocationHandler(
            new ExceptionThrowingMockBehavior(exception));
    return startMatchingInvocation(matchingInvocationHandler);
}

From source file:org.jbpm.executor.impl.AbstractAvailableJobsExecutor.java

@SuppressWarnings("unchecked")
protected boolean handleException(RequestInfo request, Throwable e, CommandContext ctx,
        List<CommandCallback> callbacks) {
    logger.warn("Error during command {} error message {}", request.getCommandName(), e.getMessage(), e);

    ErrorInfo errorInfo = new ErrorInfo(e.getMessage(), ExceptionUtils.getStackTrace(e.fillInStackTrace()));
    errorInfo.setRequestInfo(request);// w w w. ja  v a  2s .  c o  m

    ((List<ErrorInfo>) request.getErrorInfo()).add(errorInfo);
    logger.debug("Error Number: {}", request.getErrorInfo().size());
    if (request.getRetries() > 0) {
        request.setStatus(STATUS.RETRYING);
        request.setRetries(request.getRetries() - 1);

        // calculate next retry time
        List<Long> retryDelay = (List<Long>) ctx.getData("retryDelay");
        if (retryDelay != null) {
            long retryAdd = 0l;

            try {
                retryAdd = retryDelay.get(request.getExecutions());
            } catch (IndexOutOfBoundsException ex) {
                // in case there is no element matching given execution, use last one
                retryAdd = retryDelay.get(retryDelay.size() - 1);
            }

            request.setTime(new Date(System.currentTimeMillis() + retryAdd));
            request.setExecutions(request.getExecutions() + 1);
            logger.info("Retrying request ( with id {}) - delay configured, next retry at {}", request.getId(),
                    request.getTime());
        }

        logger.debug("Retrying ({}) still available!", request.getRetries());

        executorStoreService.updateRequest(request);

        return false;
    } else {
        logger.debug("Error no retries left!");
        request.setStatus(STATUS.ERROR);
        request.setExecutions(request.getExecutions() + 1);

        executorStoreService.updateRequest(request);

        if (callbacks != null) {
            for (CommandCallback handler : callbacks) {
                handler.onCommandError(ctx, e);
            }
        }
        return true;
    }
}

From source file:org.trianacode.taskgraph.util.FileUtils.java

public static String formatThrowable(Throwable t) {
    StringBuilder sb = new StringBuilder(t.getClass().getName());
    t.fillInStackTrace();
    StackTraceElement[] trace = t.getStackTrace();
    for (StackTraceElement stackTraceElement : trace) {
        sb.append("\t\n").append(stackTraceElement);
    }//from w w  w . j a  va  2 s .  c om
    Throwable cause = t.getCause();
    if (cause != null) {
        sb.append(formatThrowable(cause));
    }
    return sb.toString();
}

From source file:com.zz.cluster4spring.support.provider.AbstractDiscoveringEndpointProvider.java

/**
 * Notifies underlying registry that given service url under given service
 * key is invalid if service url is contained in provided set of service
 * urls//from   w  ww.  j a  va2s  .c  om
 *
 * @param aServiceKey
 *            key used to identify services url in ConsumingRegistry
 * @param aServiceInfos
 *            list of services urlsurl
 * @param aServiceInfo
 *            service url that should be marked invalidurl
 */
protected void markServiceInvalidInternal(String aServiceKey, Set<SI> aServiceInfos, SI aServiceInfo) {
    if (fLog.isTraceEnabled()) {
        String message = format(
                "Starting processing service invalidation request. Service Key: [{0}] Service Info: [{1}]",
                aServiceKey, aServiceInfo);
        Throwable ex = new Exception(); // just to have more informative
                                        // stacktrace in log
        ex.fillInStackTrace();
        fLog.trace(message, ex);
    }

    if (aServiceInfos.remove(aServiceInfo)) {
        if (fLog.isTraceEnabled()) {
            fLog.trace("Item is forwareded for registry to invalidation");
        }
        // if we were able to remove service, we need to notify registry
        invalidateServiceInRegistry(aServiceKey, aServiceInfo);
    } else {
        if (fLog.isTraceEnabled()) {
            fLog.trace(format("Service invalidation was silently skipped. Service Info: [{0}]", aServiceInfo));
        }
    }
}

From source file:org.alfresco.repo.node.integrity.IntegrityChecker.java

/**
 * Ensures that this service is registered with the transaction and saves the event
 * //from w ww  .  ja  va 2  s  . com
 * @param event IntegrityEvent
 */
@SuppressWarnings("unchecked")
private void save(IntegrityEvent event) {
    // optionally set trace
    if (traceOn) {
        // get a stack trace
        Throwable t = new Throwable();
        t.fillInStackTrace();
        StackTraceElement[] trace = t.getStackTrace();

        event.addTrace(trace);
        // done
    }

    // register this service
    AlfrescoTransactionSupport.bindIntegrityChecker(this);

    // get the event list
    Map<IntegrityEvent, IntegrityEvent> events = (Map<IntegrityEvent, IntegrityEvent>) AlfrescoTransactionSupport
            .getResource(KEY_EVENT_SET);
    if (events == null) {
        events = new HashMap<IntegrityEvent, IntegrityEvent>(113, 0.75F);
        AlfrescoTransactionSupport.bindResource(KEY_EVENT_SET, events);
    }
    // check if the event is present
    IntegrityEvent existingEvent = events.get(event);
    if (existingEvent != null) {
        // the event (or its equivalent is already present - transfer the trace
        if (traceOn) {
            existingEvent.getTraces().addAll(event.getTraces());
        }
    } else {
        // the event doesn't already exist
        events.put(event, event);
    }
    if (logger.isDebugEnabled()) {
        logger.debug("" + (existingEvent != null ? "Event already present in" : "Added event to")
                + " event set: \n" + "   event: " + event);
    }
}

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".//from www  .  j a va 2  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.pmedv.core.components.RelativeImageView.java

/**
 * initialization method.//  ww w.  ja va 2s  . c om
 * 
 * @param elem
 *            an element
 */

@SuppressWarnings("rawtypes")
private void initialize(Element elem) {

    synchronized (this) {
        bLoading = true;
        fWidth = 0;
        fHeight = 0;
    }

    int width = 0;
    int height = 0;
    boolean customWidth = false;
    boolean customHeight = false;

    try {
        fElement = elem;
        // request image from document's cache
        AttributeSet myAttr = elem.getAttributes();
        if (isURL()) {
            URL src = getSourceURL();
            if (src != null) {
                Dictionary cache = (Dictionary) getDocument().getProperty(IMAGE_CACHE_PROPERTY);
                if (cache != null) {
                    fImage = (Image) cache.get(src);
                } else {
                    fImage = Toolkit.getDefaultToolkit().getImage(src);
                }
            }
        } else {
            // load image from relative path
            String src = (String) fElement.getAttributes().getAttribute(HTML.Attribute.SRC);
            try {
                src = processSrcPath(src);
            } catch (Throwable e) {
                log.warn("exception thrown while processing src path. " + e.fillInStackTrace());
                src = (String) fElement.getAttributes().getAttribute(HTML.Attribute.SRC);
            }
            log.warn("trying to load the image from src " + src);
            fImage = Toolkit.getDefaultToolkit().createImage(src);
            try {
                waitForImage();
            } catch (InterruptedException ie) {
                fImage = null;
                log.warn("loading image from relative path failed.");
                // possibly replace with the ImageBroken icon, if that's
                // what is happening
            }
        }

        // get height & width from params or image or defaults
        height = getIntAttr(HTML.Attribute.HEIGHT, -1);
        customHeight = (height > 0);
        if (!customHeight && fImage != null) {
            height = fImage.getHeight(this);
        }
        if (height <= 0) {
            height = DEFAULT_HEIGHT;
        }

        width = getIntAttr(HTML.Attribute.WIDTH, -1);
        customWidth = (width > 0);
        if (!customWidth && fImage != null) {
            width = fImage.getWidth(this);
        }

        if (width <= 0) {
            width = DEFAULT_WIDTH;
        }

        if (fImage != null) {
            if (customHeight && customWidth) {
                Toolkit.getDefaultToolkit().prepareImage(fImage, height, width, this);
            } else {
                Toolkit.getDefaultToolkit().prepareImage(fImage, -1, -1, this);
            }
        }
    } finally {
        synchronized (this) {
            bLoading = false;
            if (customHeight || fHeight == 0) {
                fHeight = height;
            }

            if (customWidth || fWidth == 0) {
                fWidth = width;
            }
        }
    }
}

From source file:org.gradle.api.internal.file.archive.ZipCopySpecVisitorTest.java

private FileVisitDetails brokenFile(final String path, final Throwable failure) {
    final FileVisitDetails details = context.mock(FileVisitDetails.class, String.format("[%s]", path));

    context.checking(new Expectations() {
        {//from   w  w w  .  ja v a  2s .c om
            allowing(details).getRelativePath();
            will(returnValue(RelativePath.parse(true, path)));

            allowing(details).getLastModified();
            will(returnValue(1000L));

            allowing(details).isDirectory();
            will(returnValue(false));

            allowing(details).getMode();
            will(returnValue(1));

            allowing(details).copyTo(with(notNullValue(OutputStream.class)));
            will(new Action() {
                public void describeTo(Description description) {
                    description.appendText("write content");
                }

                public Object invoke(Invocation invocation) throws Throwable {
                    failure.fillInStackTrace();
                    throw failure;
                }
            });
        }
    });

    return details;
}