Example usage for java.lang AssertionError AssertionError

List of usage examples for java.lang AssertionError AssertionError

Introduction

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

Prototype

public AssertionError(String message, Throwable cause) 

Source Link

Document

Constructs a new AssertionError with the specified detail message and cause.

Usage

From source file:Test.java

public static void main(String[] args) {

    try {/*from   w w  w .jav  a 2  s.c om*/
        System.out.print("Enter a number: ");
        int number = 100;
        if (number < 0) {
            throw new InvalidParameter();
        }
        if (number > 10) {
            throw new AssertionError("Number was too big", new Throwable("Throwable assertion message"));
        }
    } catch (InputMismatchException | InvalidParameter e) {
        e.addSuppressed(new Throwable());
        System.out.println("Invalid input, try again");
    } catch (final Exception e) {
        System.out.println("Invalid input, try again");
    }
}

From source file:org.tommy.stationery.moracle.core.client.load.StompWebSocketLoadTestClient.java

public static void main(String[] args) throws Exception {

    // Modify host and port below to match wherever StompWebSocketServer.java is running!!
    // When StompWebSocketServer starts it prints the selected available

    String host = "localhost";
    if (args.length > 0) {
        host = args[0];//from   w ww. j a  v  a  2s.  com
    }

    int port = 59984;
    if (args.length > 1) {
        port = Integer.valueOf(args[1]);
    }

    String url = "http://" + host + ":" + port + "/home";
    logger.debug("Sending warm-up HTTP request to " + url);
    HttpStatus status = new RestTemplate().getForEntity(url, Void.class).getStatusCode();
    Assert.state(status == HttpStatus.OK);

    final CountDownLatch connectLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch subscribeLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch messageLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch disconnectLatch = new CountDownLatch(NUMBER_OF_USERS);

    final AtomicReference<Throwable> failure = new AtomicReference<Throwable>();

    Executor executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
    org.eclipse.jetty.websocket.client.WebSocketClient jettyClient = new WebSocketClient(executor);
    JettyWebSocketClient webSocketClient = new JettyWebSocketClient(jettyClient);
    webSocketClient.start();

    HttpClient jettyHttpClient = new HttpClient();
    jettyHttpClient.setMaxConnectionsPerDestination(1000);
    jettyHttpClient.setExecutor(new QueuedThreadPool(1000));
    jettyHttpClient.start();

    List<Transport> transports = new ArrayList<>();
    transports.add(new WebSocketTransport(webSocketClient));
    transports.add(new JettyXhrTransport(jettyHttpClient));

    SockJsClient sockJsClient = new SockJsClient(transports);

    try {
        URI uri = new URI("ws://" + host + ":" + port + "/stomp");
        WebSocketStompClient stompClient = new WebSocketStompClient(uri, null, sockJsClient);
        stompClient.setMessageConverter(new StringMessageConverter());

        logger.debug("Connecting and subscribing " + NUMBER_OF_USERS + " users ");
        StopWatch stopWatch = new StopWatch("STOMP Broker Relay WebSocket Load Tests");
        stopWatch.start();

        List<ConsumerStompMessageHandler> consumers = new ArrayList<>();
        for (int i = 0; i < NUMBER_OF_USERS; i++) {
            consumers.add(new ConsumerStompMessageHandler(BROADCAST_MESSAGE_COUNT, connectLatch, subscribeLatch,
                    messageLatch, disconnectLatch, failure));
            stompClient.connect(consumers.get(i));
        }

        if (failure.get() != null) {
            throw new AssertionError("Test failed", failure.get());
        }
        if (!connectLatch.await(5000, TimeUnit.MILLISECONDS)) {
            logger.info("Not all users connected, remaining: " + connectLatch.getCount());
        }
        if (!subscribeLatch.await(5000, TimeUnit.MILLISECONDS)) {
            logger.info("Not all users subscribed, remaining: " + subscribeLatch.getCount());
        }

        stopWatch.stop();
        logger.debug("Finished: " + stopWatch.getLastTaskTimeMillis() + " millis");

        logger.debug("Broadcasting " + BROADCAST_MESSAGE_COUNT + " messages to " + NUMBER_OF_USERS + " users ");
        stopWatch.start();

        ProducerStompMessageHandler producer = new ProducerStompMessageHandler(BROADCAST_MESSAGE_COUNT,
                failure);
        stompClient.connect(producer);

        if (failure.get() != null) {
            throw new AssertionError("Test failed", failure.get());
        }
        if (!messageLatch.await(1 * 60 * 1000, TimeUnit.MILLISECONDS)) {
            for (ConsumerStompMessageHandler consumer : consumers) {
                if (consumer.messageCount.get() < consumer.expectedMessageCount) {
                    logger.debug(consumer);
                }
            }
        }
        if (!messageLatch.await(1 * 60 * 1000, TimeUnit.MILLISECONDS)) {
            logger.info("Not all handlers received every message, remaining: " + messageLatch.getCount());
        }

        producer.session.disconnect();
        if (!disconnectLatch.await(5000, TimeUnit.MILLISECONDS)) {
            logger.info("Not all disconnects completed, remaining: " + disconnectLatch.getCount());
        }

        stopWatch.stop();
        logger.debug("Finished: " + stopWatch.getLastTaskTimeMillis() + " millis");

        System.out.println("\nPress any key to exit...");
        System.in.read();
    } catch (Throwable t) {
        t.printStackTrace();
    } finally {
        webSocketClient.stop();
        jettyHttpClient.stop();
    }

    logger.debug("Exiting");
    System.exit(0);
}

From source file:Main.java

public static String encodeUrlParam(String s) {
    try {/* w  w w.ja v a 2s . c  o  m*/
        return URLEncoder.encode(s, "UTF-8");
    } catch (UnsupportedEncodingException ex) {
        throw new AssertionError("UTF-8 should always be supported", ex);
    }
}

From source file:Main.java

public static String buildUri(String host, String path) {
    try {//  w w  w .  ja v a 2  s . c  o m
        return new URI("https", host, "/" + path, null).toASCIIString();
    } catch (URISyntaxException ex) {
        throw new AssertionError("URI creation failed, host=" + host + ", path=" + path, ex);
    }
}

From source file:com.squarespace.template.JsonLoader.java

public static Map<String, JsonNode> loadJson(Class<?> relativeCls, String path) {
    try {/*from   w  w  w  .  j a  v a 2s.  c o m*/
        String source = GeneralUtils.loadResource(relativeCls, path);
        Map<String, String> sections = TestCaseParser.parseSections(source);
        Map<String, JsonNode> result = new HashMap<>();
        for (Map.Entry<String, String> entry : sections.entrySet()) {
            result.put(entry.getKey(), JsonUtils.decode(entry.getValue()));
        }
        return result;
    } catch (CodeException e) {
        throw new AssertionError("Failed to load JSON from resource '" + path + "'", e);
    }
}

From source file:Main.java

public static String nodeToString(final Node node, final boolean omitXMLDecl) {
    final StringWriter writer = new StringWriter();
    final Transformer transformer;
    try {/* w  w w.j a  v  a2s. c  o  m*/
        transformer = TransformerFactory.newInstance().newTransformer();
    } catch (final TransformerException e) {
        throw new AssertionError("No errors expected when creating an identity transformer", e);
    }

    if (omitXMLDecl) {
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    } else {
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    }

    try {
        transformer.transform(new DOMSource(node), new StreamResult(writer));
    } catch (final TransformerException e) {
        throw new AssertionError("No errors expected during identity transformation", e);
    }

    return writer.toString();
}

From source file:com.hp.autonomy.frontend.find.hod.converter.StringToResourceIdentifierConverter.java

private String decodeUriComponent(final String part) {
    try {//from   w w  w  . j a  v  a2 s  .  c o m
        return URLDecoder.decode(part, "UTF-8");
    } catch (final UnsupportedEncodingException e) {
        throw new AssertionError("All JVMs must support UTF-8", e);
    }
}

From source file:fi.luontola.cqrshotel.JsonSerializationTest.java

private static void assertSerializable(Class<?> type, ObjectMapper objectMapper) {
    try {/*w w w.  j ava2s .c  o m*/
        Object original = newDummy(type);
        String json = objectMapper.writeValueAsString(original);
        Object deserialized = objectMapper.readValue(json, type);
        assertThat(deserialized, is(original));
    } catch (Exception e) {
        throw new AssertionError("Not serializable: " + type, e);
    }
}

From source file:com.google.i18n.addressinput.testing.InMemoryAsyncRequest.java

public InMemoryAsyncRequest(String urlPrefix, Map<String, String> keyToJsonMap) {
    try {//from   ww  w . j  av a 2 s  . com
        for (Map.Entry<String, String> e : keyToJsonMap.entrySet()) {
            responseMap.put(urlPrefix + "/" + e.getKey(), JsoMap.buildJsoMap(e.getValue()));
        }
    } catch (JSONException e) {
        throw new AssertionError("Invalid test JSON data: " + keyToJsonMap, e);
    }
}

From source file:com.magnet.tools.tests.FileSystemStepDefs.java

@Then("^the directory structure for \"([^\"]*)\" should be:$")
public static void the_directory_should_be(String directory, List<String> entries) throws Throwable {
    the_directory_should_exist(directory);
    List<AssertionError> errors = new ArrayList<AssertionError>();
    for (String entry : entries) {
        try {/*from  w  w  w . ja  va2 s. c o  m*/
            if (entry.endsWith("/") || entry.endsWith("\\")) {
                ScenarioUtils.the_directory_under_directory_should_exist(directory, entry);
            } else {
                ScenarioUtils.the_file_under_directory_should_exist(directory, entry);
            }
        } catch (AssertionError e) {
            errors.add(e);
        }
    }
    if (!errors.isEmpty()) {
        String dir = ScenarioUtils.expandVariables(directory);
        StringBuilder tree = new StringBuilder();
        for (AssertionError e : errors) {
            tree.append("Entry not found: ").append(e.getMessage()).append("\n");
        }
        tree.append("\n").append("The directory structure for ").append(dir).append(" was:").append("\n");
        for (File f : FileUtils.listFilesAndDirs(new File(dir), TrueFileFilter.INSTANCE,
                TrueFileFilter.INSTANCE)) {
            tree.append(f).append("\n");
        }
        throw new AssertionError(tree.toString(), errors.get(0));
    }
}