001 /* 002 * Copyright 2010-2015 JetBrains s.r.o. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017 package org.jetbrains.kotlin.utils; 018 019 import org.jetbrains.annotations.NotNull; 020 import org.jetbrains.annotations.Nullable; 021 022 public class WrappedValues { 023 private static final Object NULL_VALUE = new Object() { 024 @Override 025 public String toString() { 026 return "NULL_VALUE"; 027 } 028 }; 029 public static volatile boolean throwWrappedProcessCanceledException = false; 030 031 private final static class ThrowableWrapper { 032 private final Throwable throwable; 033 034 private ThrowableWrapper(@NotNull Throwable throwable) { 035 this.throwable = throwable; 036 } 037 038 @NotNull 039 public Throwable getThrowable() { 040 return throwable; 041 } 042 043 @Override 044 public String toString() { 045 return throwable.toString(); 046 } 047 } 048 049 private WrappedValues() { 050 } 051 052 @Nullable 053 @SuppressWarnings("unchecked") 054 public static <V> V unescapeNull(@NotNull Object value) { 055 if (value == NULL_VALUE) return null; 056 return (V) value; 057 } 058 059 @NotNull 060 public static <V> Object escapeNull(@Nullable V value) { 061 if (value == null) return NULL_VALUE; 062 return value; 063 } 064 065 @NotNull 066 public static Object escapeThrowable(@NotNull Throwable throwable) { 067 return new ThrowableWrapper(throwable); 068 } 069 070 @Nullable 071 public static <V> V unescapeExceptionOrNull(@NotNull Object value) { 072 return unescapeNull(unescapeThrowable(value)); 073 } 074 075 @Nullable 076 public static <V> V unescapeThrowable(@Nullable Object value) { 077 if (value instanceof ThrowableWrapper) { 078 Throwable originThrowable = ((ThrowableWrapper) value).getThrowable(); 079 080 if (throwWrappedProcessCanceledException && 081 originThrowable.getClass().getName().equals("com.intellij.openapi.progress.ProcessCanceledException")) { 082 throw new WrappedProcessCanceledException(originThrowable); 083 } 084 085 throw ExceptionUtilsKt.rethrow(originThrowable); 086 } 087 088 //noinspection unchecked 089 return (V) value; 090 } 091 092 public static class WrappedProcessCanceledException extends RuntimeException { 093 public WrappedProcessCanceledException(Throwable cause) { 094 super("Rethrow stored exception", cause); 095 } 096 } 097 }