com.intellij.util.ExceptionUtil Java Examples

The following examples show how to use com.intellij.util.ExceptionUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HttpUtils.java    From EasyCode with MIT License 6 votes vote down vote up
/**
 * post json请求
 *
 * @param uri   地址
 * @param param 参数
 * @return 请求返回结果
 */
public static String postJson(String uri, Map<String, Object> param) {
    HttpPost httpPost = new HttpPost(HOST_URL + uri);
    httpPost.setHeader(HttpHeaders.USER_AGENT, USER_AGENT);
    httpPost.setHeader(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE);
    httpPost.setConfig(getDefaultConfig());
    ObjectMapper objectMapper = new ObjectMapper();
    try {
        if (!CollectionUtil.isEmpty(param)) {
            httpPost.setEntity(new StringEntity(objectMapper.writeValueAsString(param), "utf-8"));
        }
        return handlerRequest(httpPost);
    } catch (JsonProcessingException e) {
        Messages.showWarningDialog("JSON解析出错!", MsgValue.TITLE_INFO);
        ExceptionUtil.rethrow(e);
    }
    return null;
}
 
Example #2
Source File: SnapshotInputMappings.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public InputData<Key, Value> putData(@Nullable Input content, @Nonnull InputData<Key, Value> data) throws IOException {
  int hashId;
  InputData<Key, Value> result;
  if (data instanceof HashedInputData) {
    hashId = ((HashedInputData<Key, Value>)data).getHashId();
    result = data;
  }
  else {
    hashId = getHashId(content);
    result = hashId == 0 ? InputData.empty() : new HashedInputData<>(data.getKeyValues(), hashId);
  }
  boolean saved = savePersistentData(data.getKeyValues(), hashId);
  if (DebugAssertions.EXTRA_SANITY_CHECKS) {
    if (saved) {
      try {
        myIndexingTrace.put(hashId, getContentDebugData(content) + "," + ExceptionUtil.getThrowableText(new Throwable()));
      }
      catch (IOException ex) {
        LOG.error(ex);
      }
    }
  }
  return result;
}
 
Example #3
Source File: ConsoleHistoryController.java    From consulo with Apache License 2.0 6 votes vote down vote up
public boolean loadHistoryOld(String id) {
  File file = new File(PathUtil.toSystemDependentName(getOldHistoryFilePath(id)));
  if (!file.exists()) return false;
  try {
    Element rootElement = JDOMUtil.load(file);
    String text = loadHistory(rootElement, id);
    if (text != null) {
      myContent = text;
      return true;
    }
  }
  catch (Exception ex) {
    //noinspection ThrowableResultOfMethodCallIgnored
    Throwable cause = ExceptionUtil.getRootCause(ex);
    if (cause instanceof EOFException) {
      LOG.warn("Failed to load " + myRootType.getId() + " history from: " + file.getPath(), ex);
      return false;
    }
    else {
      LOG.error(ex);
    }
  }
  return false;
}
 
Example #4
Source File: CloneUtils.java    From EasyCode with MIT License 6 votes vote down vote up
/**
 * 复制属性
 *
 * @param oldEntity 就实体
 * @param newEntity 新实例
 */
private static void copyIgnoreProp(Object oldEntity, Object newEntity) {
    // 类型不一样直接返回
    if (!Objects.equals(oldEntity.getClass(), newEntity.getClass())) {
        return;
    }
    // 获取所有字段
    List<Field> fieldList = ReflectionUtil.collectFields(oldEntity.getClass());
    if (CollectionUtil.isEmpty(fieldList)) {
        return;
    }
    fieldList.forEach(field -> {
        if (field.getAnnotation(JsonIgnore.class) != null) {
            // 设置允许访问
            field.setAccessible(true);
            // 复制字段
            try {
                field.set(newEntity, field.get(oldEntity));
            } catch (IllegalAccessException e) {
                ExceptionUtil.rethrow(e);
            }
        }
    });
}
 
Example #5
Source File: AbstractLayoutCodeProcessor.java    From consulo with Apache License 2.0 6 votes vote down vote up
public FutureTask<Boolean> preprocessFile(@Nonnull PsiFile file, boolean processChangedTextOnly) throws IncorrectOperationException {
  final FutureTask<Boolean> previousTask = getPreviousProcessorTask(file, processChangedTextOnly);
  final FutureTask<Boolean> currentTask = prepareTask(file, processChangedTextOnly);

  return new FutureTask<>(() -> {
    try {
      if (previousTask != null) {
        previousTask.run();
        if (!previousTask.get() || previousTask.isCancelled()) return false;
      }

      ApplicationManager.getApplication().runWriteAction(currentTask);

      return currentTask.get() && !currentTask.isCancelled();
    }
    catch (ExecutionException e) {
      ExceptionUtil.rethrowUnchecked(e.getCause());
      throw e;
    }
  });
}
 
Example #6
Source File: PsiToDocumentSynchronizer.java    From consulo with Apache License 2.0 6 votes vote down vote up
public boolean commitTransaction(@Nonnull Document document) {
  ApplicationManager.getApplication().assertIsWriteThread();
  final DocumentChangeTransaction documentChangeTransaction = removeTransaction(document);
  if (documentChangeTransaction == null) return false;
  final PsiFile changeScope = documentChangeTransaction.myChangeScope;
  try {
    mySyncDocument = document;

    final PsiTreeChangeEventImpl fakeEvent = new PsiTreeChangeEventImpl(changeScope.getManager());
    fakeEvent.setParent(changeScope);
    fakeEvent.setFile(changeScope);
    checkPsiModificationAllowed(fakeEvent);
    doSync(fakeEvent, true, (document1, event) -> doCommitTransaction(document1, documentChangeTransaction));
    myBus.syncPublisher(PsiDocumentTransactionListener.TOPIC).transactionCompleted(document, changeScope);
  }
  catch (Throwable e) {
    myPsiDocumentManager.forceReload(changeScope.getViewProvider().getVirtualFile(), changeScope.getViewProvider());
    ExceptionUtil.rethrowAllAsUnchecked(e);
  }
  finally {
    mySyncDocument = null;
  }
  return true;
}
 
Example #7
Source File: Log4J2DialogAppender.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private static IdeaLoggingEvent extractLoggingEvent(@Nonnull Message message, @Nonnull Throwable throwable) {
  //noinspection ThrowableResultOfMethodCallIgnored
  Throwable rootCause = ExceptionUtil.getRootCause(throwable);
  if (rootCause instanceof LogEventException) {
    return ((LogEventException)rootCause).getLogMessage();
  }

  String strMessage = message.getFormattedMessage();
  ExceptionWithAttachments withAttachments = ExceptionUtil.findCause(throwable, ExceptionWithAttachments.class);
  if (withAttachments != null) {
    return LogMessageEx.createEvent(strMessage, ExceptionUtil.getThrowableText(throwable), withAttachments.getAttachments());
  }

  return new IdeaLoggingEvent(strMessage, throwable);
}
 
Example #8
Source File: ErrorReportBean.java    From consulo with Apache License 2.0 5 votes vote down vote up
public ErrorReportBean(Throwable throwable, String lastAction) {
  if (throwable != null) {
    message = throwable.getMessage();
    stackTrace = ExceptionUtil.getThrowableText(throwable);
  }
  this.lastAction = lastAction;
}
 
Example #9
Source File: LaterInvocator.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void invokeAndWait(@Nonnull final Runnable runnable, @Nonnull ModalityState modalityState) {
  LOG.assertTrue(!isDispatchThread());

  final Semaphore semaphore = new Semaphore();
  semaphore.down();
  final Ref<Throwable> exception = Ref.create();
  Runnable runnable1 = new Runnable() {
    @Override
    public void run() {
      try {
        runnable.run();
      }
      catch (Throwable e) {
        exception.set(e);
      }
      finally {
        semaphore.up();
      }
    }

    @Override
    @NonNls
    public String toString() {
      return "InvokeAndWait[" + runnable + "]";
    }
  };
  invokeLaterWithCallback(runnable1, modalityState, Conditions.FALSE, null);
  semaphore.waitFor();
  if (!exception.isNull()) {
    Throwable cause = exception.get();
    if (SystemProperties.getBooleanProperty("invoke.later.wrap.error", true)) {
      // wrap everything to keep the current thread stacktrace
      // also TC ComparisonFailure feature depends on this
      throw new RuntimeException(cause);
    }
    else {
      ExceptionUtil.rethrow(cause);
    }
  }
}
 
Example #10
Source File: GitHubErrorBean.java    From IntelliJDeodorant with MIT License 5 votes vote down vote up
GitHubErrorBean(Throwable throwable, String lastAction) {
    this.stackTrace = throwable != null ? ExceptionUtil.getThrowableText(throwable) : null;
    this.lastAction = lastAction;
    if (throwable != null) {
        setMessage(throwable.getMessage());
        myExceptionHash = Integer.toHexString(stackTrace.hashCode());
    }
}
 
Example #11
Source File: FileDocumentManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void unwrapAndRethrow(@Nonnull Exception e) {
  Throwable unwrapped = e;
  if (e instanceof InvocationTargetException) {
    unwrapped = e.getCause() == null ? e : e.getCause();
  }
  ExceptionUtil.rethrowUnchecked(unwrapped);
  LOG.error(unwrapped);
}
 
Example #12
Source File: CommandProcessorImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void finishCommand(@Nonnull final CommandToken command, @Nullable final Throwable throwable) {
  if (myCurrentCommand != command) return;
  final boolean failed;
  try {
    if (throwable != null) {
      failed = true;
      ExceptionUtil.rethrowUnchecked(throwable);
      CommandLog.LOG.error(throwable);
    }
    else {
      failed = false;
    }
  }
  finally {
    try {
      super.finishCommand(command, throwable);
    }
    catch (Throwable e) {
      if (throwable != null) {
        e.addSuppressed(throwable);
      }
      throw e;
    }
  }
  if (failed) {
    Project project = command.getProject();
    if (project != null) {
      FileEditor editor = new FocusBasedCurrentEditorProvider().getCurrentEditor();
      final UndoManager undoManager = UndoManager.getInstance(project);
      if (undoManager.isUndoAvailable(editor)) {
        undoManager.undo(editor);
      }
    }
    Messages.showErrorDialog(project, "Cannot perform operation. Too complex, sorry.", "Failed to Perform Operation");
  }
}
 
Example #13
Source File: LogMessageEx.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void error(@Nonnull Logger logger,
                         @Nonnull String message,
                         @Nonnull Throwable cause,
                         @Nonnull String... attachmentText) {
  StringBuilder detailsBuffer = new StringBuilder();
  for (String detail : attachmentText) {
    detailsBuffer.append(detail).append(",");
  }
  if (attachmentText.length > 0 && detailsBuffer.length() > 0) {
    detailsBuffer.setLength(detailsBuffer.length() - 1);
  }
  Attachment attachment = detailsBuffer.length() > 0 ? AttachmentFactory.get().create("current-context.txt", detailsBuffer.toString()) : null;
  logger.error(createEvent(message, ExceptionUtil.getThrowableText(cause), null, null, attachment));
}
 
Example #14
Source File: LogUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static String getProcessList() {
  try {
    @SuppressWarnings("SpellCheckingInspection") Process process = new ProcessBuilder()
            .command(SystemInfo.isWindows ? new String[]{System.getenv("windir") + "\\system32\\tasklist.exe", "/v"} : new String[]{"ps", "a"})
            .redirectErrorStream(true)
            .start();
    return FileUtil.loadTextAndClose(process.getInputStream());
  }
  catch (IOException e) {
    return ExceptionUtil.getThrowableText(e);
  }
}
 
Example #15
Source File: FrequentErrorLogger.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void report(@Nonnull Throwable t, @Nonnull Runnable writeToLog) {
  int hash = ExceptionUtil.getThrowableText(t).hashCode();
  Integer reportedTimes = ourReportedIssues.get(hash);
  if (reportedTimes == null || reportedTimes > REPORT_EVERY_NUM) {
    writeToLog.run();
    ourReportedIssues.put(hash, 1);
  }
  else {
    ourReportedIssues.put(hash, reportedTimes + 1);
  }
}
 
Example #16
Source File: CompoundRuntimeException.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void throwIfNotEmpty(@Nullable List<? extends Throwable> throwables) {
  if (ContainerUtil.isEmpty(throwables)) {
    return;
  }

  if (throwables.size() == 1) {
    ExceptionUtil.rethrow(throwables.get(0));
  }
  else {
    throw new CompoundRuntimeException(throwables);
  }
}
 
Example #17
Source File: ApplicationUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Allows to interrupt a process which does not performs checkCancelled() calls by itself.
 * Note that the process may continue to run in background indefinitely - so <b>avoid using this method unless absolutely needed</b>.
 */
public static <T> T runWithCheckCanceled(@Nonnull final Callable<T> callable, @Nonnull final ProgressIndicator indicator) throws Exception {
  final Ref<T> result = Ref.create();
  final Ref<Throwable> error = Ref.create();

  Future<?> future = PooledThreadExecutor.INSTANCE.submit(() -> ProgressManager.getInstance().executeProcessUnderProgress(() -> {
    try {
      result.set(callable.call());
    }
    catch (Throwable t) {
      error.set(t);
    }
  }, indicator));

  while (true) {
    try {
      indicator.checkCanceled();
    }
    catch (ProcessCanceledException e) {
      future.cancel(true);
      throw e;
    }

    try {
      future.get(200, TimeUnit.MILLISECONDS);
      ExceptionUtil.rethrowAll(error.get());
      return result.get();
    }
    catch (TimeoutException ignored) {
    }
  }
}
 
Example #18
Source File: LookupOffsets.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void documentChanged(@Nonnull DocumentEvent e) {
  if (myStartMarkerDisposeInfo == null && !myLookupStartMarker.isValid()) {
    Throwable throwable = new Throwable();
    String eString = e.toString();
    myStartMarkerDisposeInfo = () -> eString + "\n" + ExceptionUtil.getThrowableText(throwable);
  }
}
 
Example #19
Source File: LookupOffsets.java    From consulo with Apache License 2.0 5 votes vote down vote up
int getLookupStart(@Nullable Throwable disposeTrace) {
  if (!myLookupStartMarker.isValid()) {
    throw new AssertionError("Invalid lookup start: " +
                             myLookupStartMarker +
                             ", " +
                             myEditor +
                             ", disposeTrace=" +
                             (disposeTrace == null ? null : ExceptionUtil.getThrowableText(disposeTrace)) +
                             "\n================\n start dispose trace=" +
                             (myStartMarkerDisposeInfo == null ? null : myStartMarkerDisposeInfo.get()));
  }
  return myLookupStartMarker.getStartOffset();
}
 
Example #20
Source File: RemoteProcessSupport.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void startProcess(Target target, Parameters configuration, Pair<Target, Parameters> key) {
  ProgramRunner runner = new DefaultProgramRunner() {
    @Override
    @Nonnull
    public String getRunnerId() {
      return "MyRunner";
    }

    @Override
    public boolean canRun(@Nonnull String executorId, @Nonnull RunProfile profile) {
      return true;
    }
  };
  Executor executor = DefaultRunExecutor.getRunExecutorInstance();
  ProcessHandler processHandler = null;
  try {
    RunProfileState state = getRunProfileState(target, configuration, executor);
    ExecutionResult result = state.execute(executor, runner);
    //noinspection ConstantConditions
    processHandler = result.getProcessHandler();
  }
  catch (Exception e) {
    dropProcessInfo(key, e instanceof ExecutionException? e.getMessage() : ExceptionUtil.getUserStackTrace(e, LOG), processHandler);
    return;
  }
  processHandler.addProcessListener(getProcessListener(key));
  processHandler.startNotify();
}
 
Example #21
Source File: RunIdeConsoleAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void executeQuery(@Nonnull Project project, @Nonnull VirtualFile file, @Nonnull Editor editor, @Nonnull IdeScriptEngine engine) {
  String command = getCommandText(project, editor);
  if (StringUtil.isEmptyOrSpaces(command)) return;
  String profile = getProfileText(file);
  RunContentDescriptor descriptor = getConsoleView(project, file);
  ConsoleViewImpl consoleView = (ConsoleViewImpl)descriptor.getExecutionConsole();

  prepareEngine(project, engine, descriptor);
  try {
    long ts = System.currentTimeMillis();
    //myHistoryController.getModel().addToHistory(command);
    consoleView.print("> " + command, ConsoleViewContentType.USER_INPUT);
    consoleView.print("\n", ConsoleViewContentType.USER_INPUT);
    String script = profile == null ? command : profile + "\n" + command;
    Object o = engine.eval(script);
    String prefix = "[" + (StringUtil.formatDuration(System.currentTimeMillis() - ts)) + "]";
    consoleView.print(prefix + "=> " + o, ConsoleViewContentType.NORMAL_OUTPUT);
    consoleView.print("\n", ConsoleViewContentType.NORMAL_OUTPUT);
  }
  catch (Throwable e) {
    //noinspection ThrowableResultOfMethodCallIgnored
    Throwable ex = ExceptionUtil.getRootCause(e);
    consoleView.print(ex.getClass().getSimpleName() + ": " + ex.getMessage(), ConsoleViewContentType.ERROR_OUTPUT);
    consoleView.print("\n", ConsoleViewContentType.ERROR_OUTPUT);
  }
  selectContent(descriptor);
}
 
Example #22
Source File: UiInspectorAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void processContainerEvent(ContainerEvent event) {
  Component child = event.getID() == ContainerEvent.COMPONENT_ADDED ? event.getChild() : null;
  if (child instanceof JComponent && !(event.getSource() instanceof CellRendererPane)) {
    String text = ExceptionUtil.getThrowableText(new Throwable());
    int first = text.indexOf("at com.intellij", text.indexOf("at java.awt"));
    int last = text.indexOf("at java.awt.EventQueue");
    if (last == -1) last = text.length();
    String val = last > first && first > 0 ?  text.substring(first, last): null;
    ((JComponent)child).putClientProperty("uiInspector.addedAt", val);
  }
}
 
Example #23
Source File: TreeState.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
  Element st = new Element("TreeState");
  String content;
  try {
    writeExternal(st);
    content = JDOMUtil.writeChildren(st, "\n");
  }
  catch (IOException e) {
    content = ExceptionUtil.getThrowableText(e);
  }
  return "TreeState(" + myScrollToSelection + ")\n" + content;
}
 
Example #24
Source File: Settings.java    From EasyCode with MIT License 5 votes vote down vote up
/**
 * 加载模板文件
 *
 * @param filePath 模板路径
 * @return 模板文件内容
 */
private static String loadTemplate(String filePath) {
    try {
        return UrlUtil.loadText(Settings.class.getResource(filePath)).replace("\r", "");
    } catch (IOException e) {
        ExceptionUtil.rethrow(e);
    }
    return "";
}
 
Example #25
Source File: TemplateEditPane.java    From CodeMaker with Apache License 2.0 5 votes vote down vote up
private void testTemplate() {
    CodeTemplate template = new CodeTemplate(getTemplateName(), getClassName(), getTemplate(),
            getClassNumber(), getFileEncoding(), getTemplateLanguage(), getTargetLanguage());

    final List<ClassEntry> classEntries = inputClassIndices()
            .map(i ->
                 getSelectedTestInput().createInput("SomeClass" + i)
            )
            .collect(Collectors.toList());

    Object result;
    try {
        result = templateEngine.evaluate(template, classEntries, classEntries.get(0));
    } catch (Throwable e) {
        result = e;
    }

    final DialogBuilder builder = new DialogBuilder(this.templateEdit);
    builder.addCloseButton().setText("Close");

    if(result instanceof GeneratedSource) {
        builder.setTitle(((GeneratedSource) result).getClassName());
        builder.setCenterPanel(
                Editors.createSourceEditor(null, getTargetLanguage(), ((GeneratedSource) result).getContent(), true).getComponent());
    } else {
        Throwable error = (Throwable) result;
        builder.setTitle("Failed!");
        builder.setCenterPanel(
              Editors.createSourceEditor(null, "txt",
                      error.getMessage() + "\n\n" + ExceptionUtil.getThrowableText(error), true)
                      .getComponent());
    }
    builder.show();
}
 
Example #26
Source File: GraphQLSchemaErrorNode.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
@Override
public void handleDoubleClickOrEnter(SimpleTree tree, InputEvent inputEvent) {
    final SourceLocation location = getLocation();
    if (location != null && location.getSourceName() != null) {
        GraphQLTreeNodeNavigationUtil.openSourceLocation(myProject, location, false);
    } else if (error instanceof GraphQLInternalSchemaError) {
        String stackTrace = ExceptionUtil.getThrowableText(((GraphQLInternalSchemaError) error).getException());
        PsiFile file = PsiFileFactory.getInstance(myProject).createFileFromText("graphql-error.txt", PlainTextLanguage.INSTANCE, stackTrace);
        new OpenFileDescriptor(myProject, file.getVirtualFile()).navigate(true);
    }
}
 
Example #27
Source File: MainSetting.java    From EasyCode with MIT License 5 votes vote down vote up
/**
 * 覆盖配置
 *
 * @param jsonNode json节点对象
 * @param name     配置组名称
 * @param cls      配置组类
 * @param srcGroup 源分组
 */
private <T extends AbstractGroup> void coverConfig(@NotNull JsonNode jsonNode, @NotNull String name, Class<T> cls, @NotNull Map<String, T> srcGroup) {
    ObjectMapper objectMapper = new ObjectMapper();
    if (!jsonNode.has(name)) {
        return;
    }
    try {
        JsonNode node = jsonNode.get(name);
        if (node.size() == 0) {
            return;
        }
        // 覆盖配置
        Iterator<String> names = node.fieldNames();
        while (names.hasNext()) {
            String key = names.next();
            String value = node.get(key).toString();
            T group = objectMapper.readValue(value, cls);
            if (srcGroup.containsKey(key)) {
                if (!MessageDialogBuilder.yesNo(MsgValue.TITLE_INFO, String.format("是否覆盖%s配置中的%s分组?", name, key)).isYes()) {
                    continue;
                }
            }
            srcGroup.put(key, group);
        }
    } catch (IOException e) {
        Messages.showWarningDialog("JSON解析错误!", MsgValue.TITLE_INFO);
        ExceptionUtil.rethrow(e);
    }
}
 
Example #28
Source File: VfsTestUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void deleteFile(VirtualFile virtualFile) {
  Ref<Exception> exceptionRef = Ref.create();
  UIUtil.invokeAndWaitIfNeeded((Runnable)() -> {
    try {
      WriteAction.run(() -> virtualFile.delete(null));
    }
    catch (IOException e) {
      exceptionRef.set(e);
    }
  });

  ExceptionUtil.rethrowAllAsUnchecked(exceptionRef.get());
}
 
Example #29
Source File: TableInfoServiceImpl.java    From EasyCode with MIT License 5 votes vote down vote up
/**
 * 对象还原
 *
 * @param str 原始JSON字符串
 * @return 解析结果
 */
private TableInfo parser(String str) {
    try {
        return objectMapper.readValue(str, TableInfo.class);
    } catch (IOException e) {
        Messages.showWarningDialog("读取配置失败,JSON反序列化异常。", MsgValue.TITLE_INFO);
        ExceptionUtil.rethrow(e);
    }
    return null;
}
 
Example #30
Source File: CloneUtils.java    From EasyCode with MIT License 5 votes vote down vote up
/**
 * 通过JSON序列化方式进行克隆
 *
 * @param entity        实例对象
 * @param copy          是否复制被忽略的属性
 * @param typeReference 返回类型
 * @return 克隆后的实体对象
 */
public static <E, T extends E> E cloneByJson(E entity, TypeReference<T> typeReference, boolean copy) {
    if (entity == null) {
        return null;
    }
    ObjectMapper objectMapper = new ObjectMapper();
    try {
        // 进行序列化
        String json = objectMapper.writeValueAsString(entity);
        // 进行反序列化
        E result;
        if (typeReference == null) {
            result = (E) objectMapper.readValue(json, entity.getClass());
        } else {
            result = objectMapper.readValue(json, typeReference);
        }
        // 复制被忽略的属性
        if (copy) {
            copyIgnoreProp(entity, result);
            // 针对TableInfo对象做特殊处理
            if (entity instanceof TableInfo) {
                handlerTableInfo((TableInfo) entity, (TableInfo) result);
            }
        }
        return result;
    } catch (IOException e) {
        ExceptionUtil.rethrow(e);
    }
    return null;
}