private static void assertExceptionOccurred(
      boolean shouldOccur, AbstractExceptionCase exceptionCase, String expectedErrorMsg)
      throws Throwable {
    boolean wasThrown = false;
    try {
      exceptionCase.tryClosure();
    } catch (Throwable e) {
      if (shouldOccur) {
        wasThrown = true;
        final String errorMessage = exceptionCase.getAssertionErrorMessage();
        assertEquals(errorMessage, exceptionCase.getExpectedExceptionClass(), e.getClass());
        if (expectedErrorMsg != null) {
          assertEquals("Compare error messages", expectedErrorMsg, e.getMessage());
        }
      } else if (exceptionCase.getExpectedExceptionClass().equals(e.getClass())) {
        wasThrown = true;

        System.out.println("");
        e.printStackTrace(System.out);

        fail("Exception isn't expected here. Exception message: " + e.getMessage());
      } else {
        throw e;
      }
    } finally {
      if (shouldOccur && !wasThrown) {
        fail(exceptionCase.getAssertionErrorMessage());
      }
    }
  }
  /**
   * 运行时,添加JVM参数“-Dsun.net.http.retryPost=false”,可阻止自动重连。
   *
   * @see 'http://www.coderanch.com/t/490463/sockets/java/Timeout-retry-URLHTTPRequest'
   */
  @Test
  public void testConnectionResetByHttpURLConnection() throws IOException {
    testConnectionResetCount = 0;

    String resp = null;
    try {
      HttpURLConnection conn =
          (HttpURLConnection) new URL("http://localhost:65532/soso").openConnection();
      conn.setDoOutput(true);
      conn.setRequestMethod("POST");
      conn.getOutputStream().write("username".getBytes());
      resp = conn.getResponseCode() + "";
    } catch (IOException e) {
      Throwable ee = ExceptionUtils.getRootCause(e);
      if (ee == null) {
        ee = e;
      }
      Logger.error(this, "", ee);
      Assert.assertNotSame(NoHttpResponseException.class, ee.getClass());
      Assert.assertSame(SocketException.class, ee.getClass());
      Assert.assertTrue(
          "Connection reset".equals(ee.getMessage())
              || "Socket closed".equals(ee.getMessage())
              || "Unexpected end of file from server".equals(ee.getMessage()));
    } finally {
      Logger.info(
          this,
          "resp[HttpURLConnection]-["
              + testConnectionResetCount
              + "]=========["
              + resp
              + "]=========");
    }
    Assert.assertEquals(2, testConnectionResetCount);
  }
  @Test
  public void testConnectionResetByHttpClientUtils() throws IOException {
    testConnectionResetCount = 0;

    httpClientUtils = new HttpClientUtils();
    httpClientUtils.initHttpClient();
    Logger.info(this, "-------------- HttpClient initialized -------------");

    String resp = null;
    try {
      resp = httpClientUtils.get("http://localhost:65532/soso");
    } catch (IOException e) {
      Throwable ee = ExceptionUtils.getRootCause(e);
      if (ee == null) {
        ee = e;
      }
      Logger.error(this, "", ee);
      Assert.assertNotSame(NoHttpResponseException.class, ee.getClass());
      Assert.assertSame(SocketException.class, ee.getClass());
      Assert.assertTrue(
          "Connection reset".equals(ee.getMessage())
              || "Socket closed".equals(ee.getMessage())
              || "Unexpected end of file from server".equals(ee.getMessage()));
    } finally {
      Logger.info(
          this,
          "resp[HttpURLConnection]-["
              + testConnectionResetCount
              + "]=========["
              + resp
              + "]=========");
    }
    Assert.assertEquals(1, testConnectionResetCount);
  }
示例#4
0
  public static void expectException(Callable<?> callable, Class<?> exception) {
    boolean thrown = false;

    try {
      callable.call();
    } catch (Throwable e) {
      assert e.getClass().equals(exception)
          : e.getClass().getName() + " is not " + exception.getName();
      thrown = true;
    }

    assert thrown : exception.getName() + " not received";
  }
示例#5
0
 protected String getTitle(Throwable t) {
   String message = t.getMessage();
   String tit = message;
   if (tit == null) {
     StackTraceElement el = t.getStackTrace()[0];
     tit =
         t.getClass().getName().substring(t.getClass().getPackage().getName().length() + 1)
             + " "
             + el.getFileName()
             + ":"
             + el.getLineNumber();
   }
   return tit;
 }
  protected void initializeLogging() {
    if (settings.getGrailsHome() == null) {
      return;
    }

    try {
      Class<?> cls =
          Thread.currentThread()
              .getContextClassLoader()
              .loadClass("org.apache.log4j.PropertyConfigurator");
      Method configure = cls.getMethod("configure", URL.class);
      configure.setAccessible(true);
      File f =
          new File(settings.getGrailsHome() + "/grails-scripts/src/main/scripts/log4j.properties");
      if (f.exists()) {
        configure.invoke(cls, f.toURI().toURL());
      } else {
        f = new File(settings.getGrailsHome() + "/scripts/log4j.properties");
        configure.invoke(cls, f.toURI().toURL());
      }
    } catch (Throwable e) {
      console.verbose(
          "Log4j was not found on the classpath and will not be used for command line logging. Cause "
              + e.getClass().getName()
              + ": "
              + e.getMessage());
    }
  }
  /**
   * Calls the Callable and returns the value it returns. If an exception occurs, it is logged and a
   * new non-chained exception is thrown.
   *
   * @param <T> return type
   * @param callable code to call
   * @param message verbose description of operation
   * @return return value of Callable
   */
  private <T> T callLogThrow(final Callable<T> callable, final String message) {
    try {
      return callable.call();
    } catch (Exception e) {
      // generate reference #
      String refNum = UUID.randomUUID().toString();
      if (logger.isDebugEnabled()) {
        logger.debug(
            Messages.getInstance().getString("ExceptionLoggingDecorator.referenceNumber", refNum),
            e); //$NON-NLS-1$
      }

      // list all exceptions in stack
      @SuppressWarnings("unchecked")
      List<Throwable> throwablesInStack = ExceptionUtils.getThrowableList(e);
      // reverse them so most specific exception (root cause) comes first
      Collections.reverse(throwablesInStack);

      for (Throwable t : throwablesInStack) {
        String className = t.getClass().getName();
        if (exceptionConverterMap.containsKey(className)) {
          throw exceptionConverterMap
              .get(className)
              .convertException((Exception) t, message, refNum);
        }
      }

      // no converter; throw general exception
      throw new UnifiedRepositoryException(
          Messages.getInstance()
              .getString(
                  "ExceptionLoggingDecorator.generalException", message, refNum)); // $NON-NLS-1$
    }
  }
示例#8
0
  public static void testVariableSubstitution() {
    String val = "hello world", replacement;
    replacement = Util.substituteVariable(val);
    Assert.assertEquals(val, replacement);

    val = "my name is ${user.name}";
    replacement = Util.substituteVariable(val);
    Assert.assertNotSame(val, replacement);
    assert !(val.equals(replacement));

    val = "my name is ${user.name} and ${user.name}";
    replacement = Util.substituteVariable(val);
    assert !(val.equals(replacement));
    Assert.assertEquals(-1, replacement.indexOf("${"));

    val = "my name is ${unknown.var:Bela Ban}";
    replacement = Util.substituteVariable(val);
    assert replacement.contains("Bela Ban");
    Assert.assertEquals(-1, replacement.indexOf("${"));

    val = "my name is ${unknown.var}";
    replacement = Util.substituteVariable(val);
    assert replacement.contains("${");

    val = "here is an invalid ${argument because it doesn't contains a closing bracket";
    try {
      replacement = Util.substituteVariable(val);
      assert false : "should be an IllegalArgumentException";
    } catch (Throwable t) {
      Assert.assertEquals(IllegalArgumentException.class, t.getClass());
    }
  }
  /** Tests sending a request from a ClientTransaction. */
  public void testSendRequest() {
    try {
      Request invite = createTiInviteRequest(null, null, null);
      RequestEvent receivedRequestEvent = null;
      ClientTransaction tran = null;
      try {
        tran = tiSipProvider.getNewClientTransaction(invite);
        eventCollector.collectRequestEvent(riSipProvider);
        tran.sendRequest();
        waitForMessage();
        receivedRequestEvent = eventCollector.extractCollectedRequestEvent();
        assertNotNull("The sent request was not received by the RI!", receivedRequestEvent);
        assertNotNull(
            "The sent request was not received by the RI!", receivedRequestEvent.getRequest());
      } catch (TransactionUnavailableException exc) {
        throw new TiUnexpectedError(
            "A TransactionUnavailableException was thrown while trying to "
                + "create a new client transaction",
            exc);
      } catch (SipException exc) {
        exc.printStackTrace();
        fail("The SipException was thrown while trying to send the request.");
      } catch (TooManyListenersException exc) {
        throw new TckInternalError(
            "A  TooManyListenersException was thrown while trying "
                + "to add a SipListener to an RI SipProvider",
            exc);
      }
    } catch (Throwable exc) {
      exc.printStackTrace();
      fail(exc.getClass().getName() + ": " + exc.getMessage());
    }

    assertTrue(new Exception().getStackTrace()[0].toString(), true);
  }
示例#10
0
 /**
  * Convert logging event to map
  *
  * @param e
  * @return
  */
 public static Map<String, Object> toMap(LoggingEvent e) {
   final Map<String, Object> m =
       Objects.newHashMap(
           "name", e.getLoggerName(),
           "date", new Date(e.getTimeStamp()),
           "level", e.getLevel().toString(),
           "thread", e.getThreadName(),
           "message", "" + e.getMessage(),
           "fileName", e.getLocationInformation().getFileName(),
           "methodName", e.getLocationInformation().getMethodName(),
           "lineNumber", e.getLocationInformation().getLineNumber(),
           "requestId", e.getMDC("requestId"),
           "sessionId", e.getMDC("sessionId"),
           "freeMemory", Runtime.getRuntime().freeMemory(),
           "throwable", null);
   if (e.getThrowableInformation() != null && e.getThrowableInformation().getThrowable() != null) {
     Throwable t = e.getThrowableInformation().getThrowable();
     m.put(
         "throwable",
         Objects.newHashMap(
             "message", t.getMessage(),
             "class", t.getClass().getName(),
             "stackTrace", getStackTrace(t)));
   }
   return m;
 }
  private TestCase(Class<T> rtype, Function<Object, T> cast, ThrowMode throwMode, Throwable thrown)
      throws NoSuchMethodException, IllegalAccessException {
    this.cast = cast;
    filter =
        MethodHandles.lookup()
            .findVirtual(Function.class, "apply", MethodType.methodType(Object.class, Object.class))
            .bindTo(cast);
    this.rtype = rtype;
    this.throwMode = throwMode;
    this.throwableClass = thrown.getClass();
    switch (throwMode) {
      case NOTHING:
        this.thrown = null;
        break;
      case ADAPTER:
      case UNCAUGHT:
        this.thrown = new Error("do not catch this");
        break;
      default:
        this.thrown = thrown;
    }

    MethodHandle throwOrReturn = THROW_OR_RETURN;
    if (throwMode == ThrowMode.ADAPTER) {
      MethodHandle fakeIdentity = FAKE_IDENTITY.bindTo(this);
      for (int i = 0; i < 10; ++i) {
        throwOrReturn = MethodHandles.filterReturnValue(throwOrReturn, fakeIdentity);
      }
    }
    thrower = throwOrReturn.asType(MethodType.genericMethodType(2));
  }
 private XmlUIElement getXmlUIElementFor(String typeArg) {
   if (typeToClassMappingProp == null) {
     setUpMappingsHM();
   }
   String clsName = (String) typeToClassMappingProp.get(typeArg);
   if ((clsName != null) && !(clsName.equals("*NOTFOUND*")) && !(clsName.equals("*EXCEPTION*"))) {
     try {
       Class cls = Class.forName(clsName);
       return (XmlUIElement) cls.newInstance();
     } catch (Throwable th) {
       typeToClassMappingProp.put(typeArg, "*EXCEPTION*");
       showErrorMessage(
           MessageFormat.format(
               ProvClientUtils.getString(
                   "{0} occurred when trying to get the XmlUIElement for type : {1}"),
               new Object[] {th.getClass().getName(), typeArg}));
       th.printStackTrace();
       return null;
     }
   } else if (clsName == null) {
     typeToClassMappingProp.put(typeArg, "*NOTFOUND*");
     showErrorMessage(
         MessageFormat.format(
             ProvClientUtils.getString(
                 "The type {0} does not have the corresponding XMLUIElement specified in the TypeToUIElementMapping.txt file"),
             new Object[] {typeArg}));
   }
   return null;
 }
示例#13
0
  protected void addTest(Class<?> clazz, ITestResult result) {
    try {
      TestCase test_case =
          new TestCase(
              result.getStatus(),
              clazz.getName(),
              getMethodName(result),
              result.getStartMillis(),
              result.getEndMillis());
      switch (result.getStatus()) {
        case ITestResult.FAILURE:
        case ITestResult.SKIP:
          Throwable ex = result.getThrowable();
          if (ex != null) {
            String failure_type = ex.getClass().getName();
            String failure_msg = ex.getMessage();
            String stack_trace = printException(ex);
            test_case.setFailure(failure_type, failure_msg, stack_trace);
          } else test_case.setFailure("exception", "SKIPPED", null);
          break;
      }

      synchronized (
          this) { // handle concurrent access by different threads, if test methods are run in
        // parallel
        DataOutputStream output = tests.get(clazz);
        test_case.writeTo(output);
      }
    } catch (Exception e) {
      error(e.toString());
    }
  }
 /**
  * Method called to create a "default instance" of the bean, currently only needed for obtaining
  * default field values which may be used for suppressing serialization of fields that have "not
  * changed".
  *
  * @param fixAccess If true, method is allowed to fix access to the default constructor (to be
  *     able to call non-public constructor); if false, has to use constructor as is.
  * @return Instance of class represented by this descriptor, if suitable default constructor was
  *     found; null otherwise.
  */
 public Object instantiateBean(boolean fixAccess) {
   AnnotatedConstructor ac = _classInfo.getDefaultConstructor();
   if (ac == null) {
     return null;
   }
   if (fixAccess) {
     ac.fixAccess();
   }
   try {
     return ac.getAnnotated().newInstance();
   } catch (Exception e) {
     Throwable t = e;
     while (t.getCause() != null) {
       t = t.getCause();
     }
     if (t instanceof Error) throw (Error) t;
     if (t instanceof RuntimeException) throw (RuntimeException) t;
     throw new IllegalArgumentException(
         "Failed to instantiate bean of type "
             + _classInfo.getAnnotated().getName()
             + ": ("
             + t.getClass().getName()
             + ") "
             + t.getMessage(),
         t);
   }
 }
示例#15
0
 /** Sends a single invite request and checks whether it arrives normally at the other end. */
 public void testSendRequest() {
   try {
     // create an empty invite request.
     Request invite = createTiInviteRequest(null, null, null);
     Request receivedRequest = null;
     try {
       // Send using TI and collect using RI
       eventCollector.collectRequestEvent(riSipProvider);
       waitForMessage();
       tiSipProvider.sendRequest(invite);
       waitForMessage();
       RequestEvent receivedRequestEvent = eventCollector.extractCollectedRequestEvent();
       assertNotNull("The sent request was not received at the other end!", receivedRequestEvent);
       assertNotNull(
           "The sent request was not received at the other end!",
           receivedRequestEvent.getRequest());
     } catch (TooManyListenersException ex) {
       throw new TckInternalError(
           "The following exception was thrown while trying to add "
               + "a SipListener to an RI SipProvider",
           ex);
     } catch (SipException ex) {
       ex.printStackTrace();
       fail("A SipException exception was thrown while " + "trying to send a request.");
     }
   } catch (Throwable exc) {
     exc.printStackTrace();
     fail(exc.getClass().getName() + ": " + exc.getMessage());
   }
   assertTrue(new Exception().getStackTrace()[0].toString(), true);
 }
示例#16
0
 /* gets target VM version from the given VMVersionMismatchException.
  * Note that we need to reflectively call the method because of we may
  * have got this from different classloader's namespace */
 private static String getVMVersion(Throwable throwable)
     throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
   // assert isVMVersionMismatch(throwable), "not a VMVersionMismatch"
   Class expClass = throwable.getClass();
   Method targetVersionMethod = expClass.getMethod("getTargetVersion", new Class[0]);
   return (String) targetVersionMethod.invoke(throwable);
 }
示例#17
0
 public void setExceptionIntoValue(Throwable e, Commands.ValueObject value) {
   server.getIdentityID(e, value); // It should always create it so we don't need to know.
   int eID = value.objectID;
   Class eClass = e.getClass();
   server.getIdentityID(eClass, value);
   int eClassID = value.objectID;
   value.setException(eID, eClassID);
 }
示例#18
0
  /**
   * Sends a request from the TI, generates a response at the RI side, sends it back and checks
   * whether it arrives at the TI.
   */
  public void testReceiveResponse() {
    try {
      // 1. Create and send the original request

      Request invite = createTiInviteRequest(null, null, null);
      RequestEvent receivedRequestEvent = null;
      try {
        // Send using TI and collect using RI
        eventCollector.collectRequestEvent(riSipProvider);
        tiSipProvider.sendRequest(invite);
        waitForMessage();
        receivedRequestEvent = eventCollector.extractCollectedRequestEvent();
        if (receivedRequestEvent == null || receivedRequestEvent.getRequest() == null)
          throw new TckInternalError("The sent request was not received by the RI!");
      } catch (TooManyListenersException ex) {
        throw new TckInternalError(
            "A TooManyListenersException was thrown while trying to add "
                + "a SipListener to an RI SipProvider.",
            ex);
      } catch (SipException ex) {
        throw new TiUnexpectedError("The TI failed to send the request!", ex);
      }
      Request receivedRequest = receivedRequestEvent.getRequest();
      // 2. Create and send the response
      Response ok = null;
      try {
        ok = riMessageFactory.createResponse(Response.OK, receivedRequest);
        addStatus(receivedRequest, ok);
      } catch (ParseException ex) {
        throw new TckInternalError("Failed to create an OK response!", ex);
      }
      // Send the response using the RI and collect using TI
      try {
        eventCollector.collectResponseEvent(tiSipProvider);
      } catch (TooManyListenersException ex) {
        throw new TiUnexpectedError("Error while trying to add riSipProvider");
      }
      try {
        riSipProvider.sendResponse(ok);
      } catch (SipException ex) {
        throw new TckInternalError("Could not send back the response", ex);
      }
      waitForMessage();
      ResponseEvent responseEvent = eventCollector.extractCollectedResponseEvent();
      // 3. Now ... do we like what we got?
      assertNotNull("The TI failed to receive the response!", responseEvent);
      assertNotNull("The TI failed to receive the response!", responseEvent.getResponse());
      assertNull(
          "The TI had implicitly created a client transaction! "
              + "Transactions should only be created explicitly using "
              + "the SipProvider.getNewXxxTransaction() method.",
          responseEvent.getClientTransaction());
    } catch (Throwable exc) {
      exc.printStackTrace();
      fail(exc.getClass().getName() + ": " + exc.getMessage());
    }
    assertTrue(new Exception().getStackTrace()[0].toString(), true);
  }
  /**
   * Creates an invite request using the Tested Implementation and then tests creating a cancel for
   * the same invite request.
   */
  public void testCreateCancel() {
    try {
      Request invite = createTiInviteRequest(null, null, null);
      ClientTransaction tran = null;
      try {
        tran = tiSipProvider.getNewClientTransaction(invite);
      } catch (TransactionUnavailableException exc) {
        throw new TiUnexpectedError(
            "A TransactionUnavailableException was thrown while trying to "
                + "create a new client transaction",
            exc);
      }
      Request cancel = null;
      try {
        cancel = tran.createCancel();
      } catch (SipException ex) {
        ex.printStackTrace();
        fail("Failed to create cancel request!");
      }
      assertEquals(
          "The created request did not have a CANCEL method.", cancel.getMethod(), Request.CANCEL);
      assertEquals(
          "Request-URIs of the original and the cancel request do not match",
          cancel.getRequestURI(),
          invite.getRequestURI());
      assertEquals(
          "Call-IDs of the original and the cancel request do not match",
          cancel.getHeader(CallIdHeader.NAME),
          invite.getHeader(CallIdHeader.NAME));
      assertEquals(
          "ToHeaders of the original and the cancel request do not match",
          cancel.getHeader(ToHeader.NAME),
          invite.getHeader(ToHeader.NAME));
      assertTrue(
          "The CSeqHeader's sequence number of the original and "
              + "the cancel request do not match",
          ((CSeqHeader) cancel.getHeader(CSeqHeader.NAME)).getSequenceNumber()
              == ((CSeqHeader) invite.getHeader(CSeqHeader.NAME)).getSequenceNumber());
      assertEquals(
          "The CSeqHeader's method of the cancel request was not CANCEL",
          ((CSeqHeader) cancel.getHeader(CSeqHeader.NAME)).getMethod(),
          Request.CANCEL);
      assertTrue(
          "There was no ViaHeader in the cancel request",
          cancel.getHeaders(ViaHeader.NAME).hasNext());
      Iterator cancelVias = cancel.getHeaders(ViaHeader.NAME);
      ViaHeader cancelVia = ((ViaHeader) cancelVias.next());
      ViaHeader inviteVia = ((ViaHeader) invite.getHeaders(ViaHeader.NAME).next());
      assertEquals(
          "ViaHeaders of the original and the cancel request do not match!", cancelVia, inviteVia);
      assertFalse("Cancel request had more than one ViaHeader.", cancelVias.hasNext());
    } catch (Throwable exc) {
      exc.printStackTrace();
      fail(exc.getClass().getName() + ": " + exc.getMessage());
    }

    assertTrue(new Exception().getStackTrace()[0].toString(), true);
  }
 protected void assertNoThrowable(final Runnable closure) {
   String throwableName = null;
   try {
     closure.run();
   } catch (Throwable thr) {
     throwableName = thr.getClass().getName();
   }
   assertNull(throwableName);
 }
示例#21
0
 private static void tryCatch(String fs, Class<?> ex) {
   boolean caught = false;
   try {
     test(fs);
   } catch (Throwable x) {
     if (ex.isAssignableFrom(x.getClass())) caught = true;
   }
   if (!caught) fail(fs, ex);
   else pass();
 }
 public boolean hasNext() {
   try {
     return iterator.hasNext();
   } catch (Throwable t) {
     if ("ServiceConfigurationError".equals(t.getClass().getSimpleName())) {
       log.error("proc.bad.config.file", t.getLocalizedMessage());
     }
     throw new Abort(t);
   }
 }
  private void finishBuild(Throwable error, boolean hadBuildErrors, boolean markedUptodateFiles) {
    CmdlineRemoteProto.Message lastMessage = null;
    try {
      if (error != null) {
        Throwable cause = error.getCause();
        if (cause == null) {
          cause = error;
        }
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        final PrintStream stream = new PrintStream(out);
        try {
          cause.printStackTrace(stream);
        } finally {
          stream.close();
        }

        final StringBuilder messageText = new StringBuilder();
        messageText
            .append("Internal error: (")
            .append(cause.getClass().getName())
            .append(") ")
            .append(cause.getMessage());
        final String trace = out.toString();
        if (!trace.isEmpty()) {
          messageText.append("\n").append(trace);
        }
        lastMessage =
            CmdlineProtoUtil.toMessage(
                mySessionId, CmdlineProtoUtil.createFailure(messageText.toString(), cause));
      } else {
        CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status status =
            CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status.SUCCESS;
        if (myCanceled) {
          status = CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status.CANCELED;
        } else if (hadBuildErrors) {
          status = CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status.ERRORS;
        } else if (!markedUptodateFiles) {
          status = CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status.UP_TO_DATE;
        }
        lastMessage =
            CmdlineProtoUtil.toMessage(
                mySessionId, CmdlineProtoUtil.createBuildCompletedEvent("build completed", status));
      }
    } catch (Throwable e) {
      lastMessage =
          CmdlineProtoUtil.toMessage(
              mySessionId, CmdlineProtoUtil.createFailure(e.getMessage(), e));
    } finally {
      try {
        Channels.write(myChannel, lastMessage).await();
      } catch (InterruptedException e) {
        LOG.info(e);
      }
    }
  }
示例#24
0
 private static String safeToString(Object o) {
   try {
     return o.toString();
   } catch (Throwable e) {
     if (e.getClass().getName().equals("com.intellij.openapi.progress.ProcessCanceledException")) {
       //noinspection ConstantConditions
       throw (RuntimeException) e;
     }
     return "[Exception while computing toString(): " + e + "]";
   }
 }
 public Processor next() {
   try {
     return (Processor) (iterator.next());
   } catch (Throwable t) {
     if ("ServiceConfigurationError".equals(t.getClass().getSimpleName())) {
       log.error("proc.bad.config.file", t.getLocalizedMessage());
     } else {
       log.error("proc.processor.constructor.error", t.getLocalizedMessage());
     }
     throw new Abort(t);
   }
 }
示例#26
0
  public static String toMessage(Throwable t) {
    String message;
    if (t.getLocalizedMessage() == null) {
      message = "No description was provided";
    } else if (t.getLocalizedMessage().toLowerCase().indexOf("side location conflict") > -1) {
      message = t.getLocalizedMessage() + " -- Check for invalid geometries.";
    } else {
      message = t.getLocalizedMessage();
    }

    return message + " (" + StringUtil.toFriendlyName(t.getClass().getName()) + ")";
  }
示例#27
0
  // tries to get a message from a Throwable. Something there's a message and sometimes there's not.
  private static String getMessage(Throwable throwable) {
    String message = throwable.getMessage();
    if (!GUtil.isTrue(message)) {
      message = String.format("%s (no error message)", throwable.getClass().getName());
    }

    if (throwable.getCause() != null) {
      message += "\nCaused by: " + getMessage(throwable.getCause());
    }

    return message;
  }
示例#28
0
 protected static String printException(Throwable ex) throws IOException {
   if (ex == null) return null;
   StackTraceElement[] stack_trace = ex.getStackTrace();
   StringBuilder sb = new StringBuilder();
   sb.append("\n<" + CDATA + "\n");
   sb.append(ex.getClass().getName() + " \n");
   for (int i = 0; i < stack_trace.length; i++) {
     StackTraceElement frame = stack_trace[i];
     sb.append("at " + frame.toString() + " \n");
   }
   sb.append("\n]]>");
   return sb.toString();
 }
 void printException(Throwable tr) {
   CAT.error("exception", tr);
   // StringWriter sw = new StringWriter();
   // PrintWriter pw = new PrintWriter(sw);
   // tr.p rintStackTrace(pw);
   // pw.flush();
   // sw.flush();
   log(
       getMyLoginId()
           + " reports exception:\r\n  "
           + tr.getClass().getName()
           + "\r\n  "
           + tr.getMessage()); // sw.toString());
 }
示例#30
0
 public static void exec(Runnable toRun, String[] args, boolean exit, LogInterface logInterface) {
   // --Init
   log = logInterface;
   // (cleanup)
   ignoredClasspath = new String[0];
   runName = "<unnamed>";
   outputDB = null;
   dataDB = null;
   execDir = null;
   logger = null;
   // (bootstrap)
   Map<String, String> options = parseOptions(args); // get options
   fillOptions(BOOTSTRAP_CLASSES, options, false); // bootstrap
   log.bootstrap();
   log.startTrack("init");
   // (fill options)
   Class<?>[] visibleClasses = getVisibleClasses(options); // get classes
   Map<String, Field> optionFields = fillOptions(visibleClasses, options); // fill
   try {
     initDatabase(visibleClasses, options, optionFields); // database
   } catch (DatabaseException e) {
     log.warn(LOG_TAG, e.getMessage());
   }
   dumpOptions(options); // file dump
   log.endTrack("init");
   log.setup();
   // --Run Program
   try {
     log.startTrack("main");
     toRun.run();
     log.endTrack("main"); // ends main
     log.startTrack("flushing");
     if (logger != null) {
       logger.save();
     }
   } catch (Throwable e) { // catch everything
     log.exception(e);
     System.err.flush();
     if (logger != null) {
       exitMessage = e.getClass().getName() + ": " + e.getMessage();
       logger.suggestFlush(); // not a save!
     }
     log.exit(ExitCode.FATAL_EXCEPTION);
   }
   log.endTrack("flushing");
   if (exit) {
     log.exit(ExitCode.OK); // soft exit
   }
 }