Exemple #1
0
 static Throwable wrapWithAddendum(Throwable ex, String addendum, boolean after) {
   if (ex instanceof AssertionFailedError) {
     AssertionFailedError ne = new AssertionFailedError(combineMessages(ex, addendum, after));
     if (ex.getCause() != null) {
       ne.initCause(ex.getCause());
     }
     ne.setStackTrace(ex.getStackTrace());
     return ne;
   }
   if (ex instanceof AssertionError) { // preferred in JUnit 4
     AssertionError ne = new AssertionError(combineMessages(ex, addendum, after));
     if (ex.getCause() != null) {
       ne.initCause(ex.getCause());
     }
     ne.setStackTrace(ex.getStackTrace());
     return ne;
   }
   if (ex instanceof IOException) { // #66208
     IOException ne = new IOException(combineMessages(ex, addendum, after));
     if (ex.getCause() != null) {
       ne.initCause(ex.getCause());
     }
     ne.setStackTrace(ex.getStackTrace());
     return ne;
   }
   if (ex instanceof Exception) {
     return new InvocationTargetException(ex, combineMessages(ex, addendum, after));
   }
   return ex;
 }
 private static String encode(String s) {
   try {
     return URLEncoder.encode(s, "UTF-8");
   } catch (UnsupportedEncodingException ex) {
     AssertionError ae = new AssertionError("UTF-8 isn't available");
     ae.initCause(ex);
     throw ae;
   }
 }
 private static <T> Object invoke(T actual, Method getter) {
   try {
     return getter.invoke(actual);
   } catch (Exception e) {
     AssertionError error =
         new AssertionError(String.format("Exception invoking %s", getter.toGenericString()));
     error.initCause(e);
     throw error;
   }
 }
 private static <T> T newDefaultInstance(Class<T> configClass) {
   try {
     return configClass.newInstance();
   } catch (Exception e) {
     AssertionError error =
         new AssertionError(
             String.format("Exception creating default instance of %s", configClass.getName()));
     error.initCause(e);
     throw error;
   }
 }
  @org.junit.Test
  public void parseTest() throws IOException {
    if (htmlExpectFile != null)
      assertNotNull("Missing expect file: " + htmlExpectFile.getAbsolutePath(), htmlFile);
    Object retVal = null;
    try {
      CreoleParser parser = new CreoleParser();
      parser.setPrivileges(EnumSet.allOf(JCreolePrivilege.class));
      /* Replace the statement above with something like this to test
       * privileges:
      parser.setPrivileges(EnumSet.of(
              JCreolePrivilege.ENUMFORMATS,
              JCreolePrivilege.TOC,
              JCreolePrivilege.RAWHTML,
              JCreolePrivilege.STYLESHEET,
              JCreolePrivilege.JCXBLOCK,
              JCreolePrivilege.JCXSPAN,
              JCreolePrivilege.STYLER
      ));
      */
      parser.setInterWikiMapper(
          new InterWikiMapper() {
            // Use wiki name of "nil" to force lookup failure for path.
            // Use wiki page of "nil" to force lookup failure for label.
            public String toPath(String wikiName, String wikiPage) {
              if (wikiName != null && wikiName.equals("nil")) return null;
              return "{WIKI-LINK to: " + wikiName + '|' + wikiPage + '}';
            }

            public String toLabel(String wikiName, String wikiPage) {
              if (wikiPage == null)
                throw new RuntimeException("Null page name sent to InterWikiMapper");
              if (wikiPage.equals("nil")) return null;
              return "{LABEL for: " + wikiName + '|' + wikiPage + '}';
            }
          });
      retVal = parser.parse(CreoleScanner.newCreoleScanner(creoleFile, false, null));
    } catch (Exception e) {
      if (!shouldSucceed) return; // A ok.  No output file to write.
      AssertionError ae = new AssertionError("Failed to parse '" + creoleFile + "'");
      ae.initCause(e);
      throw ae;
    }
    FileUtils.writeStringToFile(
        htmlFile, ((retVal == null) ? "" : (((WashedSymbol) retVal).toString())), "UTF-8");
    if (!shouldSucceed) fail("Should have failed, but generated '" + htmlFile + "'");
    assertTrue(
        "From '" + creoleFile + "':  '" + htmlFile + "' != '" + htmlExpectFile + "'",
        FileUtils.contentEquals(htmlExpectFile, htmlFile));
    htmlFile.delete();
  }
  /**
   * Used for an assertion. Returns true when the message is unconsumed, or otherwise throw an
   * exception.
   *
   * <p>Calling this method also marks the stream as 'consumed'
   */
  private boolean unconsumed() {
    if (payloadLocalName == null) {
      return true;
    } // no payload. can be consumed multiple times.

    if (reader.getEventType() != XMLStreamReader.START_ELEMENT) {
      AssertionError error =
          new AssertionError(
              "StreamMessage has been already consumed. See the nested exception for where it's consumed");
      error.initCause(consumedAt);
      throw error;
    }
    consumedAt = new Exception().fillInStackTrace();
    return true;
  }
  private void initProcessorIterator(Context context, Iterable<? extends Processor> processors) {
    Log log = Log.instance(context);
    Iterator<? extends Processor> processorIterator;

    if (options.isSet(XPRINT)) {
      try {
        Processor processor = PrintingProcessor.class.newInstance();
        processorIterator = List.of(processor).iterator();
      } catch (Throwable t) {
        AssertionError assertError = new AssertionError("Problem instantiating PrintingProcessor.");
        assertError.initCause(t);
        throw assertError;
      }
    } else if (processors != null) {
      processorIterator = processors.iterator();
    } else {
      String processorNames = options.get(PROCESSOR);
      JavaFileManager fileManager = context.get(JavaFileManager.class);
      try {
        // If processorpath is not explicitly set, use the classpath.
        processorClassLoader =
            fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH)
                ? fileManager.getClassLoader(ANNOTATION_PROCESSOR_PATH)
                : fileManager.getClassLoader(CLASS_PATH);

        /*
         * If the "-processor" option is used, search the appropriate
         * path for the named class.  Otherwise, use a service
         * provider mechanism to create the processor iterator.
         */
        if (processorNames != null) {
          processorIterator = new NameProcessIterator(processorNames, processorClassLoader, log);
        } else {
          processorIterator = new ServiceIterator(processorClassLoader, log);
        }
      } catch (SecurityException e) {
        /*
         * A security exception will occur if we can't create a classloader.
         * Ignore the exception if, with hindsight, we didn't need it anyway
         * (i.e. no processor was specified either explicitly, or implicitly,
         * in service configuration file.) Otherwise, we cannot continue.
         */
        processorIterator = handleServiceLoaderUnavailability("proc.cant.create.loader", e);
      }
    }
    discoveredProcs = new DiscoveredProcessors(processorIterator);
  }
  @Override
  @SuppressWarnings("UseOfSystemOutOrSystemErr")
  public void error(String message, @Nullable Throwable t, @NotNull String... details) {
    t = checkException(t);
    System.err.println("ERROR: " + message);
    if (t != null) t.printStackTrace(System.err);
    if (details.length > 0) {
      System.out.println("details: ");
      for (String detail : details) {
        System.out.println(detail);
      }
    }

    AssertionError error = new AssertionError(message);
    error.initCause(t);
    throw error;
  }
Exemple #9
0
  public void initialize(int myColor, long timeLimit) {
    String color = null;
    if (myColor == GameBoard.RED) {
      color = "Red";
    } else {
      color = "Green";
    }
    pattern = Pattern.compile(".*" + color + "move=(null|([0-9]+),([0-9]+))");

    String logfile =
        System.getProperty("user.home") + System.getProperty("file.separator") + "reversi.log";
    try {
      reader = new BufferedReader(new FileReader(logfile));
    } catch (FileNotFoundException e) {
      AssertionError ae = new AssertionError("Logfile not found");
      ae.initCause(e);
      throw ae;
    }
  }
 /**
  * Create a PropertyColumn from a property name, column name, row and column classes, and column
  * width. The render and editor default to null, and updateRow, updateSubsequentRows, and
  * updateTable all default to false.
  *
  * <p>This generates an editable column if a setter exists for this property, and a non-editable
  * property if the setter doesn't exist. For more complex behavior, override {@code
  * isEditable(_RowType)}
  *
  * @param pPropertyName The name of the property of instances of the specified row class
  * @param pColumnName The name of the column
  * @param pRowClass The class of the table row instances
  * @param pValueClass The class of the values of this column
  * @param pPrefWidth the preferred width of this column
  * @throws AssertionError if pRowClass doesn't have a getter for this property name.
  */
 public PropertyColumn(
     String pPropertyName,
     String pColumnName,
     Class pRowClass,
     Class pValueClass,
     int pPrefWidth) {
   super(pColumnName, getWrapper(pValueClass), pPrefWidth);
   try {
     mGetterMethod = generateGetter(pPropertyName, pRowClass, this);
   } catch (NoSuchMethodException e) {
     AssertionError err = new AssertionError(e.getMessage());
     err.initCause(e);
     throw err;
   }
   Method setter = null;
   try {
     setter = generateSetter(pPropertyName, pRowClass, this);
     setEditable(true);
   } catch (NoSuchMethodException nsme) {
     setEditable(false);
   }
   mSetterMethod = setter;
 }
Exemple #11
0
  public Coordinates nextMove(GameBoard gb) {
    while (true) {
      String line;
      try {
        line = reader.readLine();
      } catch (IOException e) {
        AssertionError ae = new AssertionError("Failed to read from logfile");
        ae.initCause(e);
        throw ae;
      }
      Matcher m = pattern.matcher(line);

      if (m.matches()) {
        if (m.group(1).equals("null")) {
          return null;
        } else {
          int x = Integer.parseInt(m.group(2));
          int y = Integer.parseInt(m.group(3));
          return new Coordinates(x, y);
        }
      }
    }
  }
 @Override
 public void close() throws ElasticsearchException {
   RuntimeException remove = INFLIGHT_ENGINE_SEARCHERS.remove(this);
   synchronized (lock) {
     // make sure we only get this once and store the stack of the first caller!
     if (remove == null) {
       assert firstReleaseStack != null;
       AssertionError error =
           new AssertionError(
               "Released Searcher more than once, source [" + wrappedSearcher.source() + "]");
       error.initCause(firstReleaseStack);
       throw error;
     } else {
       assert firstReleaseStack == null;
       firstReleaseStack =
           new RuntimeException(
               "Searcher Released first here, source [" + wrappedSearcher.source() + "]");
     }
   }
   final int refCount = wrappedSearcher.reader().getRefCount();
   // this assert seems to be paranoid but given LUCENE-5362 we better add some assertions here
   // to make sure we catch any potential
   // problems.
   assert refCount > 0
       : "IndexReader#getRefCount() was ["
           + refCount
           + "] expected a value > [0] - reader is already closed. Initial refCount was: ["
           + initialRefCount
           + "]";
   try {
     wrappedSearcher.close();
   } catch (RuntimeException ex) {
     logger.debug("Failed to release searcher", ex);
     throw ex;
   }
 }
  /**
   * Checks whether an exception matches the expected pattern. If <code>
   * sap</code> contains an error location, checks this too.
   *
   * @param ex Exception thrown
   * @param expectedMsgPattern Expected pattern
   * @param sap Query and (optional) position in query
   */
  public static void checkEx(
      Throwable ex, String expectedMsgPattern, SqlParserUtil.StringAndPos sap) {
    if (null == ex) {
      if (expectedMsgPattern == null) {
        // No error expected, and no error happened.
        return;
      } else {
        throw new AssertionError(
            "Expected query to throw exception, "
                + "but it did not; query ["
                + sap.sql
                + "]; expected ["
                + expectedMsgPattern
                + "]");
      }
    }
    Throwable actualException = ex;
    String actualMessage = actualException.getMessage();
    int actualLine = -1;
    int actualColumn = -1;
    int actualEndLine = 100;
    int actualEndColumn = 99;

    // Search for an CalciteContextException somewhere in the stack.
    CalciteContextException ece = null;
    for (Throwable x = ex; x != null; x = x.getCause()) {
      if (x instanceof CalciteContextException) {
        ece = (CalciteContextException) x;
        break;
      }
      if (x.getCause() == x) {
        break;
      }
    }

    // Search for a SqlParseException -- with its position set -- somewhere
    // in the stack.
    SqlParseException spe = null;
    for (Throwable x = ex; x != null; x = x.getCause()) {
      if ((x instanceof SqlParseException) && (((SqlParseException) x).getPos() != null)) {
        spe = (SqlParseException) x;
        break;
      }
      if (x.getCause() == x) {
        break;
      }
    }

    if (ece != null) {
      actualLine = ece.getPosLine();
      actualColumn = ece.getPosColumn();
      actualEndLine = ece.getEndPosLine();
      actualEndColumn = ece.getEndPosColumn();
      if (ece.getCause() != null) {
        actualException = ece.getCause();
        actualMessage = actualException.getMessage();
      }
    } else if (spe != null) {
      actualLine = spe.getPos().getLineNum();
      actualColumn = spe.getPos().getColumnNum();
      actualEndLine = spe.getPos().getEndLineNum();
      actualEndColumn = spe.getPos().getEndColumnNum();
      if (spe.getCause() != null) {
        actualException = spe.getCause();
        actualMessage = actualException.getMessage();
      }
    } else {
      final String message = ex.getMessage();
      if (message != null) {
        Matcher matcher = LINE_COL_TWICE_PATTERN.matcher(message);
        if (matcher.matches()) {
          actualLine = Integer.parseInt(matcher.group(1));
          actualColumn = Integer.parseInt(matcher.group(2));
          actualEndLine = Integer.parseInt(matcher.group(3));
          actualEndColumn = Integer.parseInt(matcher.group(4));
          actualMessage = matcher.group(5);
        } else {
          matcher = LINE_COL_PATTERN.matcher(message);
          if (matcher.matches()) {
            actualLine = Integer.parseInt(matcher.group(1));
            actualColumn = Integer.parseInt(matcher.group(2));
          }
        }
      }
    }

    if (null == expectedMsgPattern) {
      if (null != actualException) {
        actualException.printStackTrace();
        fail(
            "Validator threw unexpected exception"
                + "; query ["
                + sap.sql
                + "]; exception ["
                + actualMessage
                + "]; class ["
                + actualException.getClass()
                + "]; pos [line "
                + actualLine
                + " col "
                + actualColumn
                + " thru line "
                + actualLine
                + " col "
                + actualColumn
                + "]");
      }
    } else {
      if (null == actualException) {
        fail(
            "Expected validator to throw "
                + "exception, but it did not; query ["
                + sap.sql
                + "]; expected ["
                + expectedMsgPattern
                + "]");
      } else {
        String sqlWithCarets;
        if ((actualColumn <= 0)
            || (actualLine <= 0)
            || (actualEndColumn <= 0)
            || (actualEndLine <= 0)) {
          if (sap.pos != null) {
            AssertionError e =
                new AssertionError(
                    "Expected error to have position,"
                        + " but actual error did not: "
                        + " actual pos [line "
                        + actualLine
                        + " col "
                        + actualColumn
                        + " thru line "
                        + actualEndLine
                        + " col "
                        + actualEndColumn
                        + "]");
            e.initCause(actualException);
            throw e;
          }
          sqlWithCarets = sap.sql;
        } else {
          sqlWithCarets =
              SqlParserUtil.addCarets(
                  sap.sql, actualLine, actualColumn, actualEndLine, actualEndColumn + 1);
          if (sap.pos == null) {
            throw new AssertionError(
                "Actual error had a position, but expected error"
                    + " did not. Add error position carets to sql:\n"
                    + sqlWithCarets);
          }
        }
        if (actualMessage != null) {
          actualMessage = Util.toLinux(actualMessage);
        }
        if ((actualMessage == null) || !actualMessage.matches(expectedMsgPattern)) {
          actualException.printStackTrace();
          final String actualJavaRegexp =
              (actualMessage == null)
                  ? "null"
                  : TestUtil.quoteForJava(TestUtil.quotePattern(actualMessage));
          fail(
              "Validator threw different "
                  + "exception than expected; query ["
                  + sap.sql
                  + "];\n"
                  + " expected pattern ["
                  + expectedMsgPattern
                  + "];\n"
                  + " actual ["
                  + actualMessage
                  + "];\n"
                  + " actual as java regexp ["
                  + actualJavaRegexp
                  + "]; pos ["
                  + actualLine
                  + " col "
                  + actualColumn
                  + " thru line "
                  + actualEndLine
                  + " col "
                  + actualEndColumn
                  + "]; sql ["
                  + sqlWithCarets
                  + "]");
        } else if ((sap.pos != null)
            && ((actualLine != sap.pos.getLineNum())
                || (actualColumn != sap.pos.getColumnNum())
                || (actualEndLine != sap.pos.getEndLineNum())
                || (actualEndColumn != sap.pos.getEndColumnNum()))) {
          fail(
              "Validator threw expected "
                  + "exception ["
                  + actualMessage
                  + "];\nbut at pos [line "
                  + actualLine
                  + " col "
                  + actualColumn
                  + " thru line "
                  + actualEndLine
                  + " col "
                  + actualEndColumn
                  + "];\nsql ["
                  + sqlWithCarets
                  + "]");
        }
      }
    }
  }
Exemple #14
0
 /**
  * Throws an {@link AssertionError} with the given cause.
  *
  * <p>Declared to return AssertionError, so that calling code can look like "throw
  * Assertions.error("badness")". This helps the compiler know execution can't proceed.
  *
  * @param cause
  * @param message
  * @param parameters
  * @return does not return
  */
 public static AssertionError error(Throwable cause, String message, Object... parameters) {
   AssertionError error = new AssertionError(String.format(message, parameters));
   error.initCause(cause);
   throw error;
 }
Exemple #15
0
  /**
   * Fails a test with the given message and wrapping the original exception.
   *
   * @param message the assertion error message
   * @param realCause the original exception
   */
  private static void fail(String message, Throwable realCause) {
    AssertionError ae = new AssertionError(message);
    ae.initCause(realCause);

    throw ae;
  }
  public ApplicationDescriptor(Class<?> applicationClass) throws Exception {
    // Load config
    JSON config;
    InputStream in = null;
    try {
      in = applicationClass.getResourceAsStream("config.json");
      String s = Tools.read(in);
      config = (JSON) JSON.parse(s);
    } catch (IOException e) {
      throw new AssertionError(e);
    } finally {
      Tools.safeClose(in);
    }

    //
    Class<?> packageClass;
    try {
      packageClass =
          applicationClass
              .getClassLoader()
              .loadClass(applicationClass.getPackage().getName() + ".package-info");
    } catch (ClassNotFoundException e) {
      AssertionError ae = new AssertionError("Cannot load package class");
      ae.initCause(e);
      throw ae;
    }

    //
    HashMap<String, ApplicationPlugin> pluginMap = new HashMap<String, ApplicationPlugin>();
    for (ApplicationPlugin plugin : ServiceLoader.load(ApplicationPlugin.class)) {
      pluginMap.put(plugin.getName(), plugin);
    }

    //
    HashMap<String, Descriptor> pluginDescriptors = new HashMap<String, Descriptor>();
    for (String name : config.names()) {
      ApplicationPlugin plugin = pluginMap.get(name);
      if (plugin == null) {
        throw new UnsupportedOperationException("Handle me gracefully : missing plugin " + name);
      }
      JSON pluginConfig = config.getJSON(name);
      Descriptor pluginDescriptor = plugin.init(applicationClass.getClassLoader(), pluginConfig);
      pluginDescriptors.put(name, pluginDescriptor);
    }

    //
    for (Iterator<String> i = pluginMap.keySet().iterator(); i.hasNext(); ) {
      String name = i.next();
      if (!pluginDescriptors.containsKey(name)) {
        i.remove();
      }
    }

    //
    this.applicationClass = applicationClass;
    this.name = applicationClass.getSimpleName();
    this.packageName = applicationClass.getPackage().getName();
    this.templates = (TemplatesDescriptor) pluginDescriptors.get("template");
    this.packageClass = packageClass;
    this.controllers = (ControllersDescriptor) pluginDescriptors.get("controller");
    this.pluginDescriptors = pluginDescriptors;
    this.plugins = pluginMap;
  }
 /** Alternative to AssertionError(String, Throwable), which doesn't exist in Java 1.6 */
 private static AssertionError newAssertionError(String message, Throwable cause) {
   AssertionError e = new AssertionError(message);
   e.initCause(cause);
   return e;
 }