Example usage for org.apache.commons.lang UnhandledException UnhandledException

List of usage examples for org.apache.commons.lang UnhandledException UnhandledException

Introduction

In this page you can find the example usage for org.apache.commons.lang UnhandledException UnhandledException.

Prototype

public UnhandledException(Throwable cause) 

Source Link

Document

Constructs the exception using a cause.

Usage

From source file:hr.fer.zemris.vhdllab.platform.ui.command.DevFloodWithCompliationRequestsCommand.java

private void floodWithCompilationRequests(final Integer fileId, final String name) {
    String input = JOptionPane.showInputDialog("How many?", "30");
    int floodCount = Integer.parseInt(input);

    final List<String> results = Collections.synchronizedList(new ArrayList<String>(floodCount));
    final CyclicBarrier barrier = new CyclicBarrier(floodCount);
    List<Thread> threads = new ArrayList<Thread>(floodCount);
    long start = System.currentTimeMillis();
    for (int i = 0; i < floodCount; i++) {
        Thread thread = new Thread(new Runnable() {
            @SuppressWarnings("synthetic-access")
            @Override//w ww  .  j a  va  2s.c  om
            public void run() {
                try {
                    barrier.await();
                } catch (Exception e) {
                    throw new UnhandledException(e);
                }
                logger.info("sending at: " + System.currentTimeMillis());
                List<CompilationMessage> messages;
                try {
                    messages = simulator.compile(fileId);
                } catch (SimulatorTimeoutException e) {
                    String message = localizationSource.getMessage("simulator.compile.timout",
                            new Object[] { name });
                    messages = Collections.singletonList(new CompilationMessage(message));
                } catch (NoAvailableProcessException e) {
                    String message = localizationSource.getMessage("simulator.compile.no.processes",
                            new Object[] { name });
                    messages = Collections.singletonList(new CompilationMessage(message));
                }

                if (messages.isEmpty()) {
                    results.add("Successful");
                } else {
                    results.add(messages.get(0).getText());
                }
            }
        });
        thread.start();
        threads.add(thread);
    }

    logger.info("waiting for threads to complete...");
    for (Thread thread : threads) {
        try {
            thread.join();
        } catch (InterruptedException e) {
            throw new UnhandledException(e);
        }
    }
    long end = System.currentTimeMillis();
    logger.info("ended in " + (end - start) + " ms");
    showResults(results);
}

From source file:ar.com.zauber.commons.web.transformation.processors.impl.XalanXSLTScraper.java

/**
 *
 * Propiedades que recibe un tranformer.
 * {@link javax.xml.transform.Transformer#setOutputProperties(Properties)}
 * utiliza estas opciones://  w w w.j a  v a  2 s . c o m
 *      javax.xml.transform.OutputKeys
 * @param node
 * @param model
 * @param writer
 * @param oformat siguiendo las specs linkeadas mas arriba
 *
 *
 * @throws TransformerFactoryConfigurationError
 */
public void scrap(final Node node, final Map<String, Object> model, final Writer writer, Properties oformat)
        throws TransformerFactoryConfigurationError {
    Validate.notNull(node);
    Validate.notNull(model);
    Validate.notNull(writer);
    try {
        final TransformerFactory factory = TransformerFactory.newInstance();
        final Transformer transformer = factory.newTransformer(xsltSource);
        Validate.notNull(transformer);
        for (final Entry<String, Object> entry : model.entrySet()) {
            transformer.setParameter(entry.getKey(), entry.getValue());
        }
        Properties options;
        if (oformat != null) {
            options = new Properties(oformat);
        } else {
            options = new Properties();
        }
        if (encoding != null) {
            options.setProperty(OutputKeys.ENCODING, encoding);
        }
        transformer.setOutputProperties(options);
        transformer.transform(new DOMSource(node), new StreamResult(writer));
    } catch (TransformerException e) {
        throw new UnhandledException(e);
    }
}

From source file:ar.com.zauber.commons.xmpp.message.XMPPMessageTest.java

/** carga un archivo del classpath local como string */
public static String getResult(final String name) {
    final InputStream is = XMPPMessageTest.class.getResourceAsStream(name);
    final StringWriter sw = new StringWriter();
    try {//from  w  w  w  .jav  a2s .  co m
        IOUtils.copy(is, sw);
        return sw.toString();
    } catch (final IOException e) {
        throw new UnhandledException(e);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:ch.admin.suis.msghandler.util.XMLValidator.java

private static String readFile(File file) {
    try {/*from   w  w  w . ja v a 2 s.co m*/
        try (FileInputStream inputStream = new FileInputStream(file)) {
            return IOUtils.toString(inputStream);
        }
    } catch (Exception ex) {
        throw new UnhandledException(new IOException(ex));
    }
}

From source file:ar.com.zauber.garfio.modules.mantis.model.actions.AddNoteToIssueAction.java

/** @see AbstractIssueAction#preExecutionValidation(List) */
@Override/*from  w  w  w.  ja  va 2 s .c o  m*/
public final void preExecutionValidation(final List<Action> allActions) throws MustNotExecuteException {
    super.preExecutionValidation(allActions);

    try {
        boolean canComment = false;

        if (mantisIssue.isFixed()) {
            final BigInteger projId = mantisIssue.getIssueData().getProject().getId();

            final ObjectRef manager = session.getManagerAccess();
            final AccountData[] accounts = session.getSession().getProjectUsers(projId.longValue(),
                    manager.getId().intValue());

            for (final AccountData account : accounts) {
                if (account.getName().equals(session.getUsername())) {
                    canComment = true;
                    break;
                }
            }

            if (!canComment) {
                throw new MustNotExecuteException(
                        "only managers users can add " + "a comment on a closed issue...");
            }
        } else {
            canComment = true;
        }
    } catch (final JMTException e) {
        throw new UnhandledException(e);
    }

}

From source file:hr.fer.zemris.vhdllab.platform.ui.wizard.schema.NewSchemaWizard.java

private String createSchema(CircuitInterface ci) throws Exception {
    ISchemaInfo info = new SchemaInfo();

    Caseless cname = new Caseless(ci.getName());
    info.getEntity().getParameters().setValue(SchemaEntity.KEY_NAME, cname);
    HashSet<Object> allowed = new HashSet<Object>();
    allowed.add(cname);//ww  w  . j  a va2  s.c  o m
    info.getEntity().getParameters().getParameter(SchemaEntity.KEY_NAME).getConstraint()
            .setPossibleValues(allowed);

    int ly = MARGIN_OFFSET, ry = MARGIN_OFFSET;
    ISchemaComponentCollection components = info.getComponents();
    for (Port p : ci.getPorts()) {
        InOutSchemaComponent inout = new InOutSchemaComponent(p);
        if (p.isIN()) {
            components.addComponent(MARGIN_OFFSET, ly, inout);
            ly += inout.getHeight() + MARGIN_OFFSET;
        } else { // else isOUT
            components.addComponent(Constants.DEFAULT_SCHEMA_WIDTH, ry, inout);
            ry += inout.getHeight() + MARGIN_OFFSET;
        }
    }

    SchemaSerializer ss = new SchemaSerializer();
    StringWriter writer = new StringWriter(1000 + 1000 * ci.getPorts().size());
    try {
        ss.serializeSchema(writer, info);
    } catch (IOException e) {
        throw new UnhandledException(e);
    }
    return writer.toString();
}

From source file:ar.com.zauber.commons.web.uri.factory.RelativePathUriFactory.java

/**
 * Genera el path hasta la ruta de la aplicacin.
 * @param request/*  ww w  . j av a 2 s .  c  o  m*/
 * @return path
 */
private String generarPath(final HttpServletRequest request, final String destination) {
    try {
        String encoding = request.getCharacterEncoding();
        if (StringUtils.isBlank(encoding)) {
            encoding = defaultEncoding;
        }
        // si estamos en un jsp...
        String uri = (String) request.getAttribute("javax.servlet.forward.request_uri");

        if (uri == null) {
            uri = request.getRequestURI();
        }
        uri = URLDecoder.decode(uri, encoding);

        // Saco el contexto
        uri = uri.substring(URLDecoder.decode(request.getContextPath(), encoding).length());

        final String[] ret = comunDenominador(uri, destination);
        uri = ret[0];
        // cuento los subs
        int slashes = StringUtils.countMatches(uri, "/");

        // si empezaba en barra resto 1
        if (uri.startsWith("/")) {
            slashes--;
        }

        final StringBuilder sb = new StringBuilder();
        boolean empty = true;
        for (int i = 0; i < slashes; i++) {
            empty = false;
            sb.append("..");
            if (i + 1 < slashes) {
                sb.append('/');
            }
        }
        if (empty) {
            sb.append('.');
        }

        sb.append(ret[1]);
        return sb.toString();
    } catch (UnsupportedEncodingException e) {
        throw new UnhandledException(e);
    }
}

From source file:de.awtools.xml.TransformerUtils.java

/**
 * Transformiert ein dom4j Dokument anhand eines Transfomators in einen
 * OutputStream./*  w w w  .  j  a va  2s.co m*/
 *
 * @param out Der zu verwendende Ausgabestrom.
 * @param transe Ein Transformator.
 * @param dom4jDocument Ein dom4j Dokument.
 */
public static void transform(final OutputStream out, final Transformer transe, final Document dom4jDocument) {

    Validate.notNull(out, "out not set");
    Validate.notNull(transe, "transe not set");
    Validate.notNull(dom4jDocument, "dom4jDocument not set");

    DocumentSource ds = new DocumentSource(dom4jDocument.getDocument());
    Result result = new StreamResult(out);

    try {
        transe.transform(ds, result);
    } catch (TransformerException ex) {
        log.debug("Catched an TransformerException", ex);
        throw new UnhandledException(ex);
    }
}

From source file:ar.com.zauber.commons.gis.street.impl.GMapsStreetDao.java

/** @see StreetsDAO#getStreets(String) */
public final List<Result> getStreets(final String query) {
    Validate.isTrue(!StringUtils.isEmpty(query));
    final List<Result> results = new LinkedList<Result>();
    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);//  ww  w .j a va 2  s . c o  m

    try {
        final String uri = "http://maps.google.com/maps/geo?" + "q=" + URLEncoder.encode(query, "UTF-8")
                + "&output=xml" + "&sensor=true_or_false" + "&oe=utf8" + "&key=" + apiKey;

        final DocumentBuilder parser = factory.newDocumentBuilder();
        final Document document = parser.parse(uri);
        GMapsResultGenerator resultGenerator = new GMapsResultGenerator(precision);
        results.addAll(resultGenerator.getResults(document));
    } catch (final IOException e) {
        results.addAll(streetsDAO.getStreets(query));
        throw new UnhandledException(e);
    } catch (final ParserConfigurationException e) {
        throw new UnhandledException(e);
    } catch (final SAXException e) {
        throw new UnhandledException(e);
    } catch (final DOMException e) {
        throw new UnhandledException(e);
    }

    return results;
}

From source file:ar.com.zauber.commons.repository.closures.OpenEntityManagerClosure.java

/** @see Closure#execute(Object) */
public final void execute(final T t) {
    if (dryrun) {
        //permite evitar que se hagan commit() en el ambiente de test
        target.execute(t);//from   w  ww.  j av a2 s .  c o m
    } else {
        boolean participate = false;
        EntityTransaction transaction = null;

        if (TransactionSynchronizationManager.hasResource(emf)) {
            // Do not modify the EntityManager: just set the participate flag.
            participate = true;
        } else {
            try {
                final EntityManager em = emf.createEntityManager();
                if (openTx) {
                    if (!warningPrinted) {
                        logger.warn(
                                "The OpenEntityManagerClosure has Transactions enabled and is not recommended"
                                        + ". This behaviour will change in the future. Check setOpenTx(), ");
                    }
                    transaction = em.getTransaction();
                    transaction.begin();
                }

                TransactionSynchronizationManager.bindResource(emf, new EntityManagerHolder(em));
            } catch (PersistenceException ex) {
                throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex);
            }
        }

        if (transaction != null) {
            try {
                target.execute(t);
                if (transaction.getRollbackOnly()) {
                    transaction.rollback();
                } else {
                    transaction.commit();
                }
            } catch (final Throwable e) {
                if (transaction != null && transaction.isActive()) {
                    transaction.rollback();
                }
                throw new UnhandledException(e);
            } finally {
                if (!participate) {
                    final EntityManagerHolder emHolder = (EntityManagerHolder) TransactionSynchronizationManager
                            .unbindResource(emf);
                    EntityManagerFactoryUtils.closeEntityManager(emHolder.getEntityManager());
                }
            }
        } else {
            try {
                target.execute(t);
            } finally {
                if (!participate) {
                    final EntityManagerHolder emHolder = (EntityManagerHolder) TransactionSynchronizationManager
                            .unbindResource(emf);
                    EntityManagerFactoryUtils.closeEntityManager(emHolder.getEntityManager());
                }
            }

        }
    }
}