Convert to corresponding JDK exception. Warning, since there are synchronized method execution
please beware of the performance issue when calling this method
348117
public UnsupportedEncodingException toJDKException() {
        UnsupportedEncodingException e = new UnsupportedEncodingException() {
            @Override
            public synchronized Throwable fillInStackTrace() {
                return this;
            }
        };
        e.setStackTrace(getStackTrace());
        return e;
    }
177449
@SafeVarargs
	public static <T extends Exception> JoinPoint<T> fromSynchronizationPointsSimilarError(ISynchronizationPoint<T>... synchPoints) {
		JoinPoint<T> jp = new JoinPoint<>();
		for (int i = 0; i < synchPoints.length; ++i)
			if (synchPoints[i] != null)
				jp.addToJoin(synchPoints[i]);
		jp.start();
		return jp;
	}
1267892
public HashMap<String, Object> getJsonToken() throws Exception {

		HashMap<String, Object> obj = new HashMap<String, Object>();

		HashMap<String, Object> choiceThreads = null;
		for (Choice c : currentChoices) {
			c.originalThreadIndex = c.getThreadAtGeneration().threadIndex;

			if (callStack.getThreadWithIndex(c.originalThreadIndex) == null) {
				if (choiceThreads == null)
					choiceThreads = new HashMap<String, Object>();

				choiceThreads.put(Integer.toString(c.originalThreadIndex), c.getThreadAtGeneration().jsonToken());
			}
		}
		if (choiceThreads != null)
			obj.put("choiceThreads", choiceThreads);

		obj.put("callstackThreads", callStack.getJsonToken());
		obj.put("variablesState", variablesState.getjsonToken());

		obj.put("evalStack", Json.listToJArray(evaluationStack));

		obj.put("outputStream", Json.listToJArray(outputStream));

		obj.put("currentChoices", Json.listToJArray(currentChoices));

		if (!divertedPointer.isNull())
			obj.put("currentDivertTarget", getDivertedPointer().getPath().getComponentsString());

		obj.put("visitCounts", Json.intHashMapToJObject(visitCounts));
		obj.put("turnIndices", Json.intHashMapToJObject(turnIndices));
		obj.put("turnIdx", currentTurnIndex);
		obj.put("storySeed", storySeed);
		obj.put("previousRandom", previousRandom);

		obj.put("inkSaveVersion", kInkSaveStateVersion);

		// Not using this right now, but could do in future.
		obj.put("inkFormatVersion", Story.inkVersionCurrent);

		return obj;
	}
727509
public static boolean isFromOrSuppressedThrowable(Throwable throwable, Class<? extends Throwable> exceptionClass) {
		return convertFromOrSuppressedThrowable(throwable, exceptionClass, true) != null;
	}
1351491
@SuppressWarnings("unchecked")
    @Trivial
    private JSONObject toJSONObjectForThrowable(Map<String, ?> errorInfo, Throwable error) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            Tr.debug(this, tc, "toJSONObjectForThrowable", errorInfo, error);

        LinkedHashMap<String, List<?>> addedInfo = new LinkedHashMap<String, List<?>>();
        for (Map.Entry<String, ?> entry : errorInfo.entrySet()) {
            Object value = entry.getValue();
            if (value instanceof List)
                addedInfo.put(entry.getKey(), (List<?>) value);
        }

        JSONObject json = new OrderedJSONObject();

        int index = 0;
        JSONObject current = json;
        Set<Throwable> causes = new HashSet<Throwable>(); // avoid cycles in exception chain
        for (Throwable cause = error; cause != null && causes.add(cause); index++) {
            // custom attributes for position in exception chain (for example, sqlState and errorCode for dataSource)
            for (Map.Entry<String, List<?>> entry : addedInfo.entrySet()) {
                List<?> values = entry.getValue();
                if (values.size() > index) {
                    Object value = values.get(index);
                    if (value != null)
                        current.put(entry.getKey(), value);
                }
            }

            current.put("class", cause.getClass().getName());
            current.put("message", cause.getMessage());

            JSONArray stack = new JSONArray();
            for (StackTraceElement element : cause.getStackTrace())
                stack.add(element.toString());
            current.put("stack", stack);

            if ((cause = cause.getCause()) != null) {
                Map<String, Object> parent = current;
                parent.put("cause", current = new OrderedJSONObject());
            }
        }

        return json;
    }
1348188
protected <T> T processCheckRowCountError(Transaction t, Exception root, Throwable e, TxCallable<T> process) throws Exception {
        if (e == null) {
            throw root;
        }
        if (e instanceof OptimisticLockException) {
            if ("checkRowCount".equals(e.getStackTrace()[0].getMethodName())) {
                if (process != null)
                    return process.call(t);
            }
        }
        return processCheckRowCountError(t, root, e.getCause(), process);
    }
1017449
private boolean isJsonProcessingException(Exception e) {
        // Unfortunately Jackson doesn't have specific subclasses for each parse exception, so we have to use the
        // more brittle approach of checking the exception message.
        return e instanceof JsonProcessingException &&
                !(e instanceof JsonParseException &&
                    e.getMessage() != null &&
                    e.getMessage().startsWith("Unexpected end-of-input"));
    }
27047
@Benchmark
    public ExampleInterface benchmarkJdkProxy() throws Exception {
        return (ExampleInterface) Proxy.newProxyInstance(newClassLoader(),
                new Class<?>[]{baseClass},
                new InvocationHandler() {
                    public Object invoke(Object proxy, Method method, Object[] args) {
                        Class<?> returnType = method.getReturnType();
                        if (returnType.isPrimitive()) {
                            if (returnType == boolean.class) {
                                return defaultBooleanValue;
                            } else if (returnType == byte.class) {
                                return defaultByteValue;
                            } else if (returnType == short.class) {
                                return defaultShortValue;
                            } else if (returnType == char.class) {
                                return defaultCharValue;
                            } else if (returnType == int.class) {
                                return defaultIntValue;
                            } else if (returnType == long.class) {
                                return defaultLongValue;
                            } else if (returnType == float.class) {
                                return defaultFloatValue;
                            } else {
                                return defaultDoubleValue;
                            }
                        } else {
                            return defaultReferenceValue;
                        }
                    }
                }
        );
    }
704447
@SuppressWarnings("unchecked")
	public Object invoke(Object object) throws Exception {
		if (object == null) throw new NullPointerException("object");

		for (Invocation invocation : toChain()) {
			MethodDescriptor<Object, Object> unchecked =
					(MethodDescriptor<Object, Object>) invocation.method;
			object = unchecked.invoke(object, invocation.getArgsWithDefaults());
		}

		return object;
	}
197755
@Override
    public void isValid() throws Exception {
        if (numStmnts() >= 2) {
            if (primaryJoinableHooks.size() > 0) {
                for (String joinField:primaryJoinableHooks) {
                    if (joinField.equals("timestamp")) {// timestamp is implicitly present in the result.
                        continue;
                    }
                    for (QueryMeta query: getAllStmnts()) {
                        boolean isPresent = false;
                        if (query instanceof BaseAggQueryMeta) {// Since BaseAggQueryMeta is also a PlainDimQueryMeta we go with former first.
                            for (AggItem item:((BaseAggQueryMeta)query).aggregations) {
                                if (joinField.equals(item.fieldName) || (item.asName != null && joinField.equals(item.asName))) {
                                    isPresent = true;
                                }
                            }
                        }
                        if (query instanceof PlainDimQueryMeta) {
                            Map<String, String> dims = ((PlainDimQueryMeta)query).fetchDimensions;
                            for (Map.Entry<String, String> entry :dims.entrySet()) {
                                if (joinField.equals(entry.getKey()) || (entry.getValue() != null && joinField.equals(entry.getValue()))) {
                                    isPresent = true;
                                }
                            }
                        }
                        if (!isPresent) {
                            String error = joinField + " mentioned in the composite key should appear in all the data sources being queried and joined.";
                            throw new Exception(error);
                        }
                    }
                }
            } else {
                String error = "Need atleast one field to join on";
                throw new Exception(error);
            }
        }
    }
60283
public static String convertExceptionToMessage(Throwable ex)
  {
    StringBuilder sb = new StringBuilder();
    if(ex != null)
    {
      sb.append("Exception type: ").append(ex.getClass().getName()).append("\n");
      sb.append("Message: ").append(ex.getLocalizedMessage()).append("\n");
      sb.append("Stacktrace: \n");
      StackTraceElement[] st = ex.getStackTrace();
      for (int i = 0; i < st.length; i++)
      {
        sb.append(st[i].toString());
        sb.append("\n");
      }
    }
    return sb.toString();
  }
435597
@SuppressWarnings({ "unchecked", "rawtypes" })
	public static final <TO, FROM> TO convert(Class<TO> to, FROM from) {

		// Convert null value
		if (from == null || to == null) {
			return null;
		}

		// Convert "null" String to null
		if ("null".equals(from)) {
			return null;
		}

		// Class is same
		if (to == Object.class || from.getClass() == to) {
			return (TO) from;
		}

		// BSON conversion
		boolean isFromMap = from != null && from instanceof Map;
		if (isFromMap) {
			Object subValue = getSubValue((Map) from);
			if (subValue != null) {
				return convert(to, subValue);
			}
		}

		// Convert FROM -> TO
		DataConverterKey<TO, FROM> key = new DataConverterKey<TO, FROM>(to, (Class<FROM>) from.getClass());
		DataConverter<TO, FROM> converter = (DataConverter<TO, FROM>) converters.get(key);
		if (converter != null) {
			return converter.convert(from);
		}

		// Convert any -> TO
		converter = (DataConverter<TO, FROM>) defaultConverters.get(to);
		if (converter != null) {
			return converter.convert(from);
		}

		// Converter not found
		throw new IllegalArgumentException("Unable to convert " + from.getClass() + " to " + to
				+ ", converter not found in DataConverterRegistry!");
	}
1272404
private Exception mapEJBException(EJSDeployedSupport s, EJBException e) throws CSIException
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "mapEJBException: " + e);
        }

        Exception mappedException = null;
        String message = " ";

        // First map EJBException to a RemoteException.
        RemoteException rex;

        if (e instanceof TransactionRolledbackLocalException)
        {
            rex = new TransactionRolledbackException(message);
        }
        else if (e instanceof AccessLocalException)
        {
            rex = new AccessException(message);
        }
        else if (e instanceof InvalidTransactionLocalException)
        {
            rex = new InvalidTransactionException(message);
        }
        else if (e instanceof NoSuchObjectLocalException)
        {
            rex = new NoSuchObjectException(message);
        }
        else if (e instanceof TransactionRequiredLocalException)
        {
            rex = new TransactionRequiredException(message);
        }
        //        else if (e instanceof InvalidActivityLocalException)
//        {
//            rex = new InvalidActivityException(message);
//        }
//        else if (e instanceof ActivityRequiredLocalException)
//        {
//            rex = new ActivityRequiredException(message);
//        }
//        else if (e instanceof ActivityCompletedLocalException)
//        {
//            rex = new ActivityCompletedException(message);
//        }
        else
        {
            rex = new RemoteException(message);
        }

        // Now set detail in RemoteException.
        rex.detail = s.rootEx;

        // Since this code created the RemoteException being passed
        // to OrbUtilsImpl.mapException method, set the stack trace
        // in it to be the exception stack from the root exception
        // so that any exception chain the ORB returns to the
        // client (e.g. CORBA UnknownException case) does not point
        // to this code as being the root cause of the problem.
        rex.setStackTrace(s.rootEx.getStackTrace()); //180095

        // If the current method request came through the ORB, then the final
        // RemoteException must be mapped to the appropriate CORBA exception.
        // Otherwise, for example for WebService Endpoint methods, the
        // RemoteException does not need to be mapped to anything,
        // WebServices will do that.                                       d228774
        if (s.ivWrapper.ivInterface.ivORB)
        {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "mapEJBException calling OrbUtils.mapException: " + rex);
            }

            // Now have OrbUtils map to a CORBA exception for remote client stub.
            mappedException = getOrbUtils().mapException(rex);
        }
        else
        {
            mappedException = rex;
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "mapEJBException returning: " + mappedException);
        }
        return mappedException;
    }
159695
protected SQLException translateException(Exception e) {
        if (isAcquireTimeoutException(e)) {
            eventPublisher.publish(new ConnectionAcquireTimeoutEvent(configurationProperties.getUniqueName()));
            return new AcquireTimeoutException(e);
        } else if (e instanceof SQLException) {
            return (SQLException) e;
        }
        return new SQLException(e);
    }
215018
public static <E, T, X extends RuntimeException> List<E> parallelConvertIfNullThrow(List<T> source,
            Class<E> targetClass, Supplier<X> exceptionSupplier) {
        return BeansConvertStrategy.parallelConvertBeans(source, targetClass, exceptionSupplier, false);
    }
430159
private String toStringImpl() throws Exception {

        StringBuffer sb;
        Method[]     methods;
        Method       method;
        int          count;

        sb = new StringBuffer();

        sb.append(super.toString());

        count = getParameterCount();

        if (count == 0) {
            sb.append("[parameterCount=0]");

            return sb.toString();
        }
        methods = getClass().getDeclaredMethods();

        sb.append('[');

        int len = methods.length;

        for (int i = 0; i < count; i++) {
            sb.append('\n');
            sb.append("    parameter_");
            sb.append(i + 1);
            sb.append('=');
            sb.append('[');

            for (int j = 0; j < len; j++) {
                method = methods[j];

                if (!Modifier.isPublic(method.getModifiers())) {
                    continue;
                }

                if (method.getParameterTypes().length != 1) {
                    continue;
                }
                sb.append(method.getName());
                sb.append('=');
                sb.append(method.invoke(this,
                                        new Object[] { new Integer(i + 1) }));

                if (j + 1 < len) {
                    sb.append(',');
                    sb.append(' ');
                }
            }
            sb.append(']');

            if (i + 1 < count) {
                sb.append(',');
                sb.append(' ');
            }
        }
        sb.append('\n');
        sb.append(']');

        return sb.toString();
    }
1324406
public void convert() throws CompilationFailedException {
        if (this.phase == Phases.PARSING && this.phaseComplete) {
            gotoPhase(Phases.CONVERSION);
        }

        if (this.phase != Phases.CONVERSION) {
            throw new GroovyBugError("SourceUnit not ready for convert()");
        }

        //
        // Build the AST

        try {
            this.ast = parserPlugin.buildAST(this, this.classLoader, this.cst);
            this.ast.setDescription(this.name);
        } catch (SyntaxException e) {
            if (this.ast == null) {
                // Create a dummy ModuleNode to represent a failed parse - in case a later phase attempts to use the ast
                this.ast = new ModuleNode(this);
            }
            getErrorCollector().addError(new SyntaxErrorMessage(e, this));
        }

        String property = (String) AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                return System.getProperty("groovy.ast");
            }
        });

        if ("xml".equals(property)) {
            saveAsXML(name, ast);
        }
    }