Example usage for java.lang Throwable Throwable

List of usage examples for java.lang Throwable Throwable

Introduction

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

Prototype

public Throwable(Throwable cause) 

Source Link

Document

Constructs a new throwable with the specified cause and a detail message of (cause==null ?

Usage

From source file:gov.nih.nci.integration.invoker.CaTissueParticipantStrategyTest.java

/**
 * Tests registerParticipant using the ServiceInvocationStrategy class for the failure scenario
 * //from w  w  w.  j  a  v  a 2s .  c  om
 * @throws IntegrationException - IntegrationException
 * @throws JAXBException - JAXBException
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void registerParticipantFailure() throws IntegrationException, JAXBException {
    final Date stTime = new Date(new java.util.Date().getTime());

    xsltTransformer.transform(null, null, null);
    EasyMock.expectLastCall().andAnswer(new IAnswer() {

        public Object answer() {
            return getSpecimenXMLStr();
        }
    }).anyTimes();

    final ServiceInvocationResult clientResult = new ServiceInvocationResult();
    clientResult.setDataChanged(false);
    clientResult.setOriginalData(getSpecimenXMLStr());

    final IntegrationException ie = new IntegrationException(IntegrationError._1034, new Throwable( // NOPMD
            "Participant does not contain the unique identifier SSN"),
            "Participant does not contain the unique identifier SSN");
    clientResult.setInvocationException(ie);

    EasyMock.expect(caTissueParticipantClient.registerParticipant((String) EasyMock.anyObject()))
            .andReturn(clientResult);
    EasyMock.replay(caTissueParticipantClient);
    final ServiceInvocationMessage serviceInvocationMessage = prepareServiceInvocationMessage(REFMSGID,
            getSpecimenXMLStr(), stTime, caTissueRegistrationStrategy.getStrategyIdentifier());
    final ServiceInvocationResult strategyResult = caTissueRegistrationStrategy
            .invoke(serviceInvocationMessage);
    Assert.assertNotNull(strategyResult);
}

From source file:de.tudarmstadt.ukp.dkpro.spelling.experiments.hoo2012.hoo2011.FixedCandidateTrigramProbabilityDetector.java

@Override
public void process(JCas jcas) throws AnalysisEngineProcessException {

    this.jcas = jcas;

    countCache = new HashMap<String, Long>();

    // sanity check
    if (JCasUtil.select(jcas, RWSECandidate.class).size() == 0) {
        getContext().getLogger().log(Level.WARNING,
                "No RWSECandidate annotations present. Probably the pipeline is not properly configured.");
        getContext().getLogger().log(Level.WARNING, jcas.getDocumentText());
        return;//from   ww w .  ja v  a2  s . c o m
    }

    for (Sentence s : JCasUtil.select(jcas, Sentence.class)) {
        List<RWSECandidate> candidates = JCasUtil.selectCovered(jcas, RWSECandidate.class, s);

        // nothing to do, if there are no candidates in the sentence, 
        if (candidates.size() == 0) {
            continue;
        }

        List<Token> tokens = JCasUtil.selectCovered(jcas, Token.class, s);
        List<String> words = JCasUtil.toText(tokens);

        double targetSentenceProb = getSentenceProbability(words) * alpha;
        //            System.out.println(words);
        //            System.out.println(targetSentenceProb);

        double maxSentenceProb = targetSentenceProb;
        SpellingAnomaly anomaly = null;
        double oneMinusAlpha = 1 - alpha;
        for (RWSECandidate candidate : candidates) {

            int candidatePosition = getCandidatePosition(candidate, tokens);

            if (candidatePosition == -1) {
                throw new AnalysisEngineProcessException(
                        new Throwable("Could not find matching token for candidate: " + candidate));
            }

            // do not consider candidates shorter than minLength
            if ((candidate.getEnd() - candidate.getBegin()) < minLength) {
                continue;
            }

            Set<String> spellingVariations = new HashSet<String>(candidateSet);
            spellingVariations.remove(candidate.getCoveredText());
            int nrOfSpellingVariations = spellingVariations.size();
            for (String variation : spellingVariations) {

                List<String> changedWords = getChangedWords(variation, words, candidatePosition);

                double changedSentenceProb = getSentenceProbability(changedWords)
                        * (oneMinusAlpha / nrOfSpellingVariations);

                //                    System.out.println(changedWords.get(candidatePosition));
                //                    System.out.println(changedSentenceProb);

                if (changedSentenceProb > maxSentenceProb) {
                    maxSentenceProb = changedSentenceProb;
                    anomaly = getAnomaly(tokens.get(candidatePosition), changedWords.get(candidatePosition));
                }
            }
        }

        // we found a sentence that has a higher probability
        if (maxSentenceProb > targetSentenceProb) {
            // add spelling anomaly 
            anomaly.addToIndexes();
            System.out.println(s.getCoveredText());
            System.out.println(anomaly);
            System.out.println(anomaly.getSuggestions(0));
        }

        // TODO if we aggregate all sentences with probability higher than we can use the same "permitting multiple corrections" variant from WOH_H_B
    }

}

From source file:cz.muni.fi.sport.club.sport.club.rest.AgeGroupsResource.java

@PUT
@Path("{id}")
public void update(@PathParam("id") String id, @FormParam("eldest") String eldest,
        @FormParam("youngest") String youngest, @FormParam("groupLevel") String groupLevel)
        throws WebApplicationException {
    try {//  www .j  a v a2s .  c o m
        AgeGroupDTO agDTO = ageGroupService.getAgeGroupById(Long.parseLong(id));
        if (agDTO == null) {
            throw new WebApplicationException(Response.Status.NOT_FOUND);
        }
        agDTO.setEldest(Date.valueOf(eldest));
        agDTO.setYoungest(Date.valueOf(youngest));
        agDTO.setGroupLevel(AgeGroupLevel.valueOf(groupLevel));
        ageGroupService.updateAgeGroup(agDTO);
    } catch (NumberFormatException ex) {
        throw new WebApplicationException(new Throwable("You put wrong request"), Response.Status.BAD_REQUEST);
    } catch (WebApplicationException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new WebApplicationException(new Throwable("We apologize for internal server error"),
                Response.Status.INTERNAL_SERVER_ERROR);
    }
}

From source file:com.qubole.quark.sql.QueryContext.java

public QueryContext(Properties info) throws QuarkException {
    try {//from   w  ww . j  a  v  a 2 s.  c om
        Class schemaFactoryClazz = Class.forName(info.getProperty("schemaFactory"));
        if (!info.contains(CalciteConnectionProperty.FUN.camelName())) {
            info.put(CalciteConnectionProperty.FUN.camelName(), "standard,hive");
        }
        this.cfg = new CalciteConnectionConfigImpl(info);
        final RelDataTypeSystem typeSystem = cfg.typeSystem(RelDataTypeSystem.class, RelDataTypeSystem.DEFAULT);
        this.typeFactory = new JavaTypeFactoryImpl(typeSystem);
        this.unitTestMode = Boolean.parseBoolean(info.getProperty("unitTestMode", "false"));

        Object obj = schemaFactoryClazz.newInstance();
        if (obj instanceof QuarkFactory) {
            final QuarkFactory schemaFactory = (QuarkFactory) schemaFactoryClazz.newInstance();
            QuarkFactoryResult factoryResult = schemaFactory.create(info);
            for (DataSourceSchema schema : factoryResult.dataSourceSchemas) {
                SchemaPlus schemaPlus = rootSchema.add(schema.getName(), schema);
                schema.setSchemaPlus(schemaPlus);
            }

            SchemaPlus metadataPlus = rootSchema.add(factoryResult.metadataSchema.getName(),
                    factoryResult.metadataSchema);
            factoryResult.metadataSchema.setSchemaPlus(metadataPlus);

            for (DataSourceSchema dataSourceSchema : factoryResult.dataSourceSchemas) {
                dataSourceSchema.initialize(this);
            }
            factoryResult.metadataSchema.initialize(this);

            this.defaultDataSource = factoryResult.defaultSchema;
            defaultSchema = parseDefaultSchema(info);
        } else {
            final TestFactory schemaFactory = (TestFactory) schemaFactoryClazz.newInstance();
            List<QuarkSchema> schemas = schemaFactory.create(info);
            for (QuarkSchema schema : schemas) {
                SchemaPlus schemaPlus = rootSchema.add(schema.getName(), schema);
                schema.setSchemaPlus(schemaPlus);
            }
            for (QuarkSchema schema : schemas) {
                schema.initialize(this);
            }
            if (info.getProperty("defaultSchema") == null) {
                throw new QuarkException(new Throwable("Default schema has to be specified"));
            }
            final ObjectMapper mapper = new ObjectMapper();
            defaultSchema = Arrays.asList(mapper.readValue(info.getProperty("defaultSchema"), String[].class));
        }
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IOException e) {
        throw new QuarkException(e);
    }
}

From source file:org.apache.brooklyn.util.http.HttpTool.java

/**
 * Connects to the given url and returns the connection.
 * Caller should {@code connection.getInputStream().close()} the result of this
 * (especially if they are making heavy use of this method).
 *//*from w  w w. ja  v a  2s .c o  m*/
public static URLConnection connectToUrl(String u) throws Exception {
    final URL url = new URL(u);
    final AtomicReference<Exception> exception = new AtomicReference<Exception>();

    // sometimes openConnection hangs, so run in background
    Future<URLConnection> f = executor.submit(new Callable<URLConnection>() {
        public URLConnection call() {
            try {
                HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String s, SSLSession sslSession) {
                        return true;
                    }
                });
                URLConnection connection = url.openConnection();
                TrustingSslSocketFactory.configure(connection);
                connection.connect();

                connection.getContentLength(); // Make sure the connection is made.
                return connection;
            } catch (Exception e) {
                exception.set(e);
                LOG.debug("Error connecting to url " + url + " (propagating): " + e, e);
            }
            return null;
        }
    });
    try {
        URLConnection result = null;
        try {
            result = f.get(60, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw e;
        } catch (Exception e) {
            LOG.debug("Error connecting to url " + url + ", probably timed out (rethrowing): " + e);
            throw new IllegalStateException(
                    "Connect to URL not complete within 60 seconds, for url " + url + ": " + e);
        }
        if (exception.get() != null) {
            LOG.debug("Error connecting to url " + url + ", thread caller of " + exception,
                    new Throwable("source of rethrown error " + exception));
            throw exception.get();
        } else {
            return result;
        }
    } finally {
        f.cancel(true);
    }
}

From source file:ch.sebastienzurfluh.swissmuseumguides.contentprovider.model.io.connectors.RemoteConnector.java

@Override
protected void onPostExecute(String result) {
    if (result != null)
        asyncCallback.onSuccess(result);
    asyncCallback.onFailure(new Throwable("Data result is empty"));
    client.close();/*w w  w.j  a  v a 2 s.  c om*/
    client = null;
}

From source file:com.greenpepper.runner.CommandLineRunnerTest.java

@Test
public void testThatDebugModeAllowToSeeWholeStackTrace() throws Exception {

    String input = getResourcePath("/specs/ABankSample.html");
    File outputFile = outputFile("report.html");

    CommandLineRunner commandLineRunner = new CommandLineRunner();
    commandLineRunner.run("--debug", input, outputFile.getAbsolutePath());

    try {//www.  j a v a2s.  co  m
        throw new Exception(new Throwable(""));
    } catch (Exception e) {
        assertTrue(countLines(ExceptionUtils.stackTrace(e.getCause(), "\n", 2)) > 2 + 1);
    }

}

From source file:org.apache.nifi.registry.web.api.AccessResource.java

/**
 * Gets the current client's identity and authorized permissions.
 *
 * @param httpServletRequest the servlet request
 * @return An object describing the current client identity, as determined by the server, and it's permissions.
 *//*from   ww  w .j  ava 2s.c  om*/
@GET
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Returns the current client's authenticated identity and permissions to top-level resources", response = CurrentUser.class, authorizations = {
        @Authorization(value = "Authorization") })
@ApiResponses({ @ApiResponse(code = 409, message = HttpStatusMessages.MESSAGE_409
        + " The NiFi Registry might be running unsecured.") })
public Response getAccessStatus(@Context HttpServletRequest httpServletRequest) {

    final NiFiUser user = NiFiUserUtils.getNiFiUser();
    if (user == null) {
        // Not expected to happen unless the nifi registry server has been seriously misconfigured.
        throw new WebApplicationException(new Throwable("Unable to access details for current user."));
    }

    final CurrentUser currentUser = authorizationService.getCurrentUser();

    return generateOkResponse(currentUser).build();
}

From source file:com.ppp.prm.portal.server.service.gwt.HibernateDetachUtility.java

public static void nullOutUninitializedFields(Object value, SerializationType serializationType)
        throws Exception {
    long start = System.currentTimeMillis();
    Map<Integer, Object> checkedObjectMap = new HashMap<Integer, Object>();
    Map<Integer, List<Object>> checkedObjectCollisionMap = new HashMap<Integer, List<Object>>();
    nullOutUninitializedFields(value, checkedObjectMap, checkedObjectCollisionMap, 0, serializationType);
    long duration = System.currentTimeMillis() - start;

    if (dumpStackOnThresholdLimit) {
        int numObjectsProcessed = checkedObjectMap.size();
        if (duration > millisThresholdLimit || numObjectsProcessed > sizeThresholdLimit) {
            String rootObjectString = (value != null) ? value.getClass().toString() : "null";
            LOG.warn("Detached [" + numObjectsProcessed + "] objects in [" + duration + "]ms from root object ["
                    + rootObjectString + "]", new Throwable("HIBERNATE DETACH UTILITY STACK TRACE"));
        }/*from w w  w  .j  a  va  2  s. c o m*/
    } else {
        // 10s is really long, log SOMETHING
        if (duration > 10000L && LOG.isDebugEnabled()) {
            LOG.debug("Detached [" + checkedObjectMap.size() + "] objects in [" + duration + "]ms");
        }
    }

    // help the garbage collector be clearing these before we leave
    checkedObjectMap.clear();
    checkedObjectCollisionMap.clear();
}

From source file:dkpro.similarity.uima.io.RTECorpusReader.java

@Override
public void getNext(CAS aCAS) throws IOException, CollectionException {
    super.getNext(aCAS);

    String entailmentOutcome1 = ((EntailmentPair) this.currentPair1).getEntailmentOutcome();
    String entailmentOutcome2 = ((EntailmentPair) this.currentPair1).getEntailmentOutcome();

    if (!entailmentOutcome1.equals(entailmentOutcome2)) {
        throw new CollectionException(new Throwable("Paring strategy is not valid for entailment pairs."));
    }/*from   w  ww  .ja  va 2 s.c  om*/

    try {
        JCas jcas = aCAS.getJCas();
        EntailmentClassificationOutcome outcome = new EntailmentClassificationOutcome(jcas);
        outcome.setOutcome(entailmentOutcome1);
        outcome.addToIndexes();
    } catch (CASException e) {
        throw new CollectionException(e);
    }
}