Example usage for java.lang AssertionError initCause

List of usage examples for java.lang AssertionError initCause

Introduction

In this page you can find the example usage for java.lang AssertionError initCause.

Prototype

public synchronized Throwable initCause(Throwable cause) 

Source Link

Document

Initializes the cause of this throwable to the specified value.

Usage

From source file:org.marketcetera.util.test.SerializableAssert.java

/**
 * Asserts that the given object serializes correctly, i.e. the
 * deserialized version of the object is equal to the original
 * object. If the assertion does not hold, the {@link
 * AssertionError} thrown starts with the given message, which may
 * be null if no such custom message prefix is desired.
 *
 * @param message The message./*from  w  w w  . ja  v a2  s. co  m*/
 * @param o The object.
 */

public static void assertSerializable(String message, Serializable o) {
    String content = null;
    SerializationException cause = null;
    try {
        Object oNew = SerializationUtils.deserialize(SerializationUtils.serialize(o));
        if (ObjectUtils.equals(o, oNew)) {
            return;
        }
        content = "expected object is '" + o + //$NON-NLS-1$
                "' actual is '" + oNew + "'"; //$NON-NLS-1$ //$NON-NLS-2$
    } catch (SerializationException ex) {
        content = "de/serialization failed"; //$NON-NLS-1$
        cause = ex;
    }
    if (message != null) {
        content = message + " " + content; //$NON-NLS-1$
    }
    AssertionError error = new AssertionError(content);
    if (cause != null) {
        error.initCause(cause);
    }
    throw error;
}

From source file:eu.swiec.bearballin.common.io.FileIO.java

public static void getTestParamsFromCSVFile(File paramsFile, List<List<String>> paramsList,
        List<String> jobsNames) throws IOException {

    BufferedReader bufRdr;//from w  w w.j a  v a  2  s .  c o  m

    try {
        bufRdr = new BufferedReader(new FileReader(paramsFile));
        String TestType = paramsFile.getParentFile().getName();
        List<String> singleTestCaseParameters;

        String line = null;
        String[] splitedLine;
        while ((line = bufRdr.readLine()) != null) {
            splitedLine = line.split(",");
            singleTestCaseParameters = new ArrayList<String>(10);
            singleTestCaseParameters.add(TestType);
            for (String sp : splitedLine) {
                singleTestCaseParameters.add(sp);
            }
            jobsNames.add(singleTestCaseParameters.get(0) + "_" + singleTestCaseParameters.get(1));
            paramsList.add(singleTestCaseParameters);
        }
        bufRdr.close();
    } catch (Exception e) {
        e.printStackTrace();
        AssertionError ae = new AssertionError("RB system failed to generate end-user message");
        ae.initCause(e);
        throw ae;
    }
}

From source file:com.googlecode.fightinglayoutbugs.helpers.TestHelper.java

/**
 * Repetitively runs the given <code>runnableAssert</code> until it
 * succeeds without throwing an exception or error or until the
 * given <code>timeout</code> is reached.
 *
 * @throws TimeoutException if the given <code>runnableAssert</code> could not be executed successfully in the given time
 *///from  ww w  .ja  v  a2s. c  om
public static void waitFor(long timeout, TimeUnit timeoutUnit, RunnableAssert runnableAssert) {
    boolean success = false;
    final long timeoutReached = System.currentTimeMillis() + timeoutUnit.toMillis(timeout);
    do {
        try {
            runnableAssert.run();
            success = true;
        } catch (Exception e) {
            if (System.currentTimeMillis() > timeoutReached) {
                AssertionError assertionError = new AssertionError(
                        "Timeout while waiting for: " + runnableAssert + ".");
                assertionError.initCause(e);
                throw assertionError;
            }
            try {
                Thread.sleep(25);
            } catch (InterruptedException e2) {
                Thread.currentThread().interrupt();
                throw new RuntimeException("Got interrupted while waiting for: " + runnableAssert + ".", e2);
            }
        }
    } while (!success);
}

From source file:com.appsimobile.appsii.SimpleJsonTest.java

public void testPathParsing() throws ResponseParserException {
    StringBuilder sb = new StringBuilder();

    String testData = AssetUtils.readAssetToString(getContext().getAssets(),
            "parser_test_data/parser_json_object_test_restaurant.json", sb);

    JSONObject jsonObject;/*w  w w .  j a v a 2  s .co  m*/
    try {
        jsonObject = new JSONObject(testData);
    } catch (JSONException e) {
        AssertionError error = new AssertionError("Unexpected error");
        error.initCause(e);
        throw error;
    }

    final SimpleJson simpleJson = new SimpleJson(jsonObject);

    SimpleJson test = simpleJson.childForPath("id");
    assertEquals(simpleJson, test);

    SimpleJson location = simpleJson.childForPath("location.lat");
    assertNotNull(location);
    assertNotSame(simpleJson, location);

    SimpleJson test2 = simpleJson.childForPath("location.long");
    assertTrue(location == test2);

    SimpleJson streetName1 = simpleJson.childForPath("location.streetname.id");
    SimpleJson streetName2 = location.childForPath("streetname.id");

    assertTrue(streetName1 == streetName2);

    assertEquals("E-sites cafe", simpleJson.getString("name"));
    assertEquals("4814", location.getString("zipcode"));
    assertEquals("4814", simpleJson.getString("location.zipcode"));
    assertEquals("NL", simpleJson.getString("location.country.code"));
    assertNull(simpleJson.getString("location.country.codexxx"));

    try {
        assertEquals("", simpleJson.getString("xxx_does_not_exist.zipcode"));
        assertTrue(false);
    } catch (ResponseParserException ignore) {
        // expected to get here
    }

    double latitude = simpleJson.getDouble("location.lat", Double.MIN_VALUE);
    assertEquals(51.5906127, latitude);

    double longitude = simpleJson.getDouble("location.long", Double.MIN_VALUE);
    assertEquals(4.7622492, longitude);

}

From source file:com.admc.jcreole.CreoleParseTest.java

@org.junit.Test
public void parseTest() throws IOException {
    if (htmlExpectFile != null)
        assertNotNull("Missing expect file: " + htmlExpectFile.getAbsolutePath(), htmlFile);
    Object retVal = null;//from  w  w w  . j  av a  2s  . c o m
    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();
}

From source file:org.opennms.core.db.C3P0ConnectionFactoryIT.java

public void testMarshalDataSourceFromConfig() throws Exception {
    C3P0ConnectionFactory factory1 = null;
    C3P0ConnectionFactory factory2 = null;

    try {/*from   ww w  . ja  v a2 s .com*/
        factory1 = makeFactory("opennms");
        factory2 = makeFactory("opennms2");

        Connection conn = null;
        Statement s = null;
        try {
            conn = factory2.getConnection();
            s = conn.createStatement();
            s.execute("select * from pg_proc");
        } finally {
            if (s != null) {
                s.close();
            }
            if (conn != null) {
                conn.close();
            }
        }
    } finally {
        Throwable t1 = null;
        Throwable t2 = null;

        if (factory1 != null) {
            try {
                factory1.close();
                factory1 = null;
            } catch (Throwable e1) {
                t1 = e1;
            }
        }

        if (factory2 != null) {
            try {
                factory2.close();
                factory2 = null;
            } catch (Throwable e2) {
                t2 = e2;
            }
        }

        if (t1 != null || t2 != null) {
            StringBuffer message = new StringBuffer();
            message.append("Could not successfully close both C3P0 factories.  Future tests might fail.");

            Throwable choice;
            if (t1 != null) {
                message.append("  First factory failed with: " + t1.getMessage() + "; see stack back trace.");
                choice = t1;

                if (t2 != null) {
                    System.err.println(
                            "  Both factories failed to close.  See stderr for second stack back trace.");
                    t2.printStackTrace(System.err);
                }
            } else {
                choice = t2;
            }
            AssertionError e = new AssertionError(message.toString());
            e.initCause(choice);
            throw e;
        }
    }
}

From source file:org.opennms.core.db.HikariCPConnectionFactoryIT.java

@Test
public void testMarshalDataSourceFromConfig() throws Exception {
    HikariCPConnectionFactory factory1 = null;
    HikariCPConnectionFactory factory2 = null;

    try {//from  w  w  w. ja  v a  2 s  . c  o m
        factory1 = makeFactory("opennms");
        factory2 = makeFactory("opennms2");

        Connection conn = null;
        Statement s = null;
        try {
            conn = factory2.getConnection();
            s = conn.createStatement();
            s.execute("select * from pg_proc");
        } finally {
            if (s != null) {
                s.close();
            }
            if (conn != null) {
                conn.close();
            }
        }
    } finally {
        Throwable t1 = null;
        Throwable t2 = null;

        if (factory1 != null) {
            try {
                factory1.close();
                factory1 = null;
            } catch (Throwable e1) {
                t1 = e1;
            }
        }

        if (factory2 != null) {
            try {
                factory2.close();
                factory2 = null;
            } catch (Throwable e2) {
                t2 = e2;
            }
        }

        if (t1 != null || t2 != null) {
            StringBuffer message = new StringBuffer();
            message.append("Could not successfully close both C3P0 factories.  Future tests might fail.");

            Throwable choice;
            if (t1 != null) {
                message.append("  First factory failed with: " + t1.getMessage() + "; see stack back trace.");
                choice = t1;

                if (t2 != null) {
                    System.err.println(
                            "  Both factories failed to close.  See stderr for second stack back trace.");
                    t2.printStackTrace(System.err);
                }
            } else {
                choice = t2;
            }
            AssertionError e = new AssertionError(message.toString());
            e.initCause(choice);
            throw e;
        }
    }
}

From source file:com.brightcove.test.upload.MediaAPIcreateVideoParameterizedIntegrationTest.java

@Ignore("Until BC-24245 gets fixed")
@Test/*  w w  w. j a v  a  2  s . c  o  m*/
public void createVideo_funnyFilenames()
        throws Throwable, MediaAPIError, URISyntaxException, JSONException, BadEnvironmentException {
    try {
        for (Account a : mAccountHelper.getAllAccounts()) {
            uploadViaAPIandCheckExists(a, mVideoFile);
        }
    } catch (AssertionError ae) {
        AssertionError parameterizedAssertionError = new AssertionError(
                "Caught AssertionError for parameterized case: mRenamedFilename = " + mRenamedFilename);
        parameterizedAssertionError.initCause((AssertionError) ae);
        throw parameterizedAssertionError;
    } catch (Throwable t) {
        throw new Throwable("Caught throwable for parameterized case: mRenamedFilename = " + mRenamedFilename,
                t);
    }
}

From source file:org.opennms.core.db.ConnectionFactoryIT.java

public void testMarshalDataSourceFromConfig() throws Exception {
    DaoTestConfigBean bean = new DaoTestConfigBean();
    bean.afterPropertiesSet();/*from  www .j  a va  2 s . co m*/

    AtomikosDataSourceFactory factory1 = null;
    AtomikosDataSourceFactory factory2 = null;

    try {
        factory1 = makeFactory("opennms");
        factory1.setUniqueResourceName("opennms");
        factory2 = makeFactory("opennms2");
        factory2.setUniqueResourceName("opennms2");

        Connection conn = null;
        Statement s = null;
        try {
            conn = factory2.getConnection();
            s = conn.createStatement();
            s.execute("select * from pg_proc");
        } finally {
            if (s != null) {
                s.close();
            }
            if (conn != null) {
                conn.close();
            }
        }
    } finally {
        Throwable t1 = null;
        Throwable t2 = null;

        if (factory1 != null) {
            try {
                factory1.close();
                factory1 = null;
            } catch (Throwable e1) {
                t1 = e1;
            }
        }

        if (factory2 != null) {
            try {
                factory2.close();
                factory2 = null;
            } catch (Throwable e2) {
                t2 = e2;
            }
        }

        if (t1 != null || t2 != null) {
            StringBuffer message = new StringBuffer();
            message.append("Could not successfully close both C3P0 factories.  Future tests might fail.");

            Throwable choice;
            if (t1 != null) {
                message.append("  First factory failed with: " + t1.getMessage() + "; see stack back trace.");
                choice = t1;

                if (t2 != null) {
                    System.err.println(
                            "  Both factories failed to close.  See stderr for second stack back trace.");
                    t2.printStackTrace(System.err);
                }
            } else {
                choice = t2;
            }
            AssertionError e = new AssertionError(message.toString());
            e.initCause(choice);
            throw e;
        }
    }
}

From source file:com.aoindustries.website.signup.SignupTechnicalForm.java

@Override
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
    ActionErrors errors = super.validate(mapping, request);
    if (errors == null)
        errors = new ActionErrors();
    try {/*from www  .j  av  a  2  s .c  o  m*/
        if (GenericValidator.isBlankOrNull(baName))
            errors.add("baName", new ActionMessage("signupTechnicalForm.baName.required"));
        if (GenericValidator.isBlankOrNull(baWorkPhone))
            errors.add("baWorkPhone", new ActionMessage("signupTechnicalForm.baWorkPhone.required"));
        if (GenericValidator.isBlankOrNull(baEmail)) {
            errors.add("baEmail", new ActionMessage("signupTechnicalForm.baEmail.required"));
        } else if (!GenericValidator.isEmail(baEmail)) {
            errors.add("baEmail", new ActionMessage("signupTechnicalForm.baEmail.invalid"));
        }
        if (GenericValidator.isBlankOrNull(baUsername))
            errors.add("baUsername", new ActionMessage("signupTechnicalForm.baUsername.required"));
        else {
            ActionServlet myServlet = getServlet();
            if (myServlet != null) {
                AOServConnector rootConn = SiteSettings.getInstance(myServlet.getServletContext())
                        .getRootAOServConnector();
                String lowerUsername = baUsername.toLowerCase();
                ValidationResult check = UserId.validate(lowerUsername);
                if (!check.isValid()) {
                    errors.add("baUsername", new ActionMessage(check.toString(), false));
                } else {
                    UserId userId;
                    try {
                        userId = UserId.valueOf(lowerUsername);
                    } catch (ValidationException e) {
                        AssertionError ae = new AssertionError("Already validated");
                        ae.initCause(e);
                        throw ae;
                    }
                    if (!rootConn.getUsernames().isUsernameAvailable(userId))
                        errors.add("baUsername",
                                new ActionMessage("signupTechnicalForm.baUsername.unavailable"));
                }
            }
        }
        return errors;
    } catch (IOException err) {
        throw new WrappedException(err);
    } catch (SQLException err) {
        throw new WrappedException(err);
    }
}