1 /* 2 * Copyright (c) 2007 Mockito contributors 3 * This program is made available under the terms of the MIT License. 4 */ 5 package org.mockito.internal.debugging; 6 7 import java.io.Serializable; 8 9 import org.mockito.internal.exceptions.stacktrace.StackTraceFilter; 10 import org.mockito.invocation.Location; 11 12 public class LocationImpl implements Location, Serializable { 13 14 private static final long serialVersionUID = -9054861157390980624L; 15 // Limit the amount of objects being created, as this class is heavily instantiated: 16 private static final StackTraceFilter stackTraceFilter = new StackTraceFilter(); 17 18 private String stackTraceLine; 19 private String sourceFile; 20 LocationImpl()21 public LocationImpl() { 22 this(new Throwable(), false); 23 } 24 LocationImpl(Throwable stackTraceHolder, boolean isInline)25 public LocationImpl(Throwable stackTraceHolder, boolean isInline) { 26 this(stackTraceFilter, stackTraceHolder, isInline); 27 } 28 LocationImpl(StackTraceFilter stackTraceFilter)29 public LocationImpl(StackTraceFilter stackTraceFilter) { 30 this(stackTraceFilter, new Throwable(), false); 31 } 32 LocationImpl( StackTraceFilter stackTraceFilter, Throwable stackTraceHolder, boolean isInline)33 private LocationImpl( 34 StackTraceFilter stackTraceFilter, Throwable stackTraceHolder, boolean isInline) { 35 computeStackTraceInformation(stackTraceFilter, stackTraceHolder, isInline); 36 } 37 38 @Override toString()39 public String toString() { 40 return stackTraceLine; 41 } 42 43 /** 44 * Eagerly compute the stacktrace line from the stackTraceHolder. Storing the Throwable is 45 * memory-intensive for tests that have large stacktraces and have a lot of invocations on 46 * mocks. 47 */ computeStackTraceInformation( StackTraceFilter stackTraceFilter, Throwable stackTraceHolder, boolean isInline)48 private void computeStackTraceInformation( 49 StackTraceFilter stackTraceFilter, Throwable stackTraceHolder, boolean isInline) { 50 StackTraceElement filtered = stackTraceFilter.filterFirst(stackTraceHolder, isInline); 51 52 // there are corner cases where exception can have a null or empty stack trace 53 // for example, a custom exception can override getStackTrace() method 54 if (filtered == null) { 55 this.stackTraceLine = "-> at <<unknown line>>"; 56 this.sourceFile = "<unknown source file>"; 57 } else { 58 this.stackTraceLine = "-> at " + filtered; 59 this.sourceFile = filtered.getFileName(); 60 } 61 } 62 63 @Override getSourceFile()64 public String getSourceFile() { 65 return sourceFile; 66 } 67 } 68