List of usage examples for java.lang Throwable Throwable
public Throwable(Throwable cause)
From source file:de.tudarmstadt.ukp.dkpro.spelling.experiments.errormining.SpellingErrorFilter.java
@Override public void process(JCas jcas) throws AnalysisEngineProcessException { // RevisionSentencePair annotations are added to the second view try {// ww w. ja v a 2s . c om revView1 = jcas.getView(WikipediaRevisionPairReader.REVISION_1); revView2 = jcas.getView(WikipediaRevisionPairReader.REVISION_2); } catch (CASException e) { throw new AnalysisEngineProcessException(e); } DocumentMetaData dmd = DocumentMetaData.get(revView1); // heuristics in this loop should be loosely ordered by their computation time // "heavy" computing should come last for (RevisionSentencePair pair : JCasUtil.select(revView2, RevisionSentencePair.class)) { Sentence s1 = (Sentence) pair.getSentence1(); Sentence s2 = (Sentence) pair.getSentence2(); // do not consider very long sentences (usually parsing errors) if (s1.getCoveredText().length() > maxSentenceLength) { continue; } List<ChangedToken> changedList1 = JCasUtil.selectCovered(revView1, ChangedToken.class, s1); List<ChangedToken> changedList2 = JCasUtil.selectCovered(revView2, ChangedToken.class, s2); // only consider changes where there was a single token change if (changedList1.size() != 1 || changedList2.size() != 1) { continue; } ChangedToken changedToken1 = changedList1.iterator().next(); ChangedToken changedToken2 = changedList2.iterator().next(); String token1 = changedToken1.getCoveredText(); String token2 = changedToken2.getCoveredText(); // same token is definitely not what we want if (token1.toLowerCase().equals(token2.toLowerCase())) { continue; } // sentence may not contains line breaks -> this indicates wrong sentence splitting if (containsLinebreak(s1.getCoveredText()) || containsLinebreak(s2.getCoveredText())) { continue; } // check that the changed token is in the same position in the sentence // this avoids situations where "a b c" is changed into "a c b" // which often also leads to low distance / high similarity if (changedToken1.getPosition() != changedToken2.getPosition()) { continue; } // should not start with a number // (we are not looking for numbers) if (Character.isDigit(token1.charAt(0)) || Character.isDigit(token2.charAt(0))) { continue; } // should not be all uppercase letters if (token1.toUpperCase().equals(token1) || token2.toUpperCase().equals(token2)) { continue; } // should not change case if (!haveFirstLettersSameCase(token1.charAt(0), token2.charAt(0))) { continue; } // certain words should not be target words if (blackList.contains(token1.toLowerCase()) || blackList.contains(token2.toLowerCase())) { continue; } //deactivated as this check also removes a lot of interesting cases // // quick check for substitutions of whole words // // if letter at the beginning an letter at the end is different // if (text1.charAt(0) != text2.charAt(0) && // text1.charAt(text1.length()-1) != text2.charAt(text2.length()-1)) // { // continue; // } long freq1; long freq2; double distance; double ratio; try { freq1 = frequencyProvider.getFrequency(token1); freq2 = frequencyProvider.getFrequency(token2); ratio = (double) freq1 / freq2; distance = levenshteinComparator.getSimilarity(token1, token2); } catch (Exception e) { throw new AnalysisEngineProcessException(e); } // zero frequencies - definitely not a word if (freq1 == 0 || freq2 == 0) { continue; } // low frequencies - probably not a word if (freq1 < lowFreq || freq2 < lowFreq) { continue; } // distance should not be greater than a threshold if (distance > levenshteinDistance) { continue; } // low ratio and low levenshtein indicate normal spelling mistake // FIXME no magic numbers if (ratio < 0.0001 && distance < 4) { continue; } // if both token share the same lemma - probably not an error List<Lemma> lemmas1 = JCasUtil.selectCovered(revView1, Lemma.class, changedToken1); List<Lemma> lemmas2 = JCasUtil.selectCovered(revView2, Lemma.class, changedToken2); if (lemmas1.size() == 0 || lemmas2.size() == 0) { throw new AnalysisEngineProcessException(new Throwable("could not get lemma for token")); } Lemma lemma1 = lemmas1.get(0); Lemma lemma2 = lemmas2.get(0); if (lemma1.getValue().equals(lemma2.getValue())) { System.out.println("SAME LEMMA"); System.out.println(token1 + " - " + token2); System.out.println(); continue; } List<POS> tags1 = JCasUtil.selectCovered(revView1, POS.class, changedToken1); List<POS> tags2 = JCasUtil.selectCovered(revView2, POS.class, changedToken2); if (tags1.size() == 0 || tags2.size() == 0) { throw new AnalysisEngineProcessException(new Throwable("could not get lemma for token")); } POS tag1 = tags1.get(0); POS tag2 = tags2.get(0); //################################# // check for POS class if (!hasAllowableTag(tag2)) { System.out.println("Unallowed Tag"); System.out.println(token1 + " - " + token2); System.out.println(); continue; } //################################# // Is currently covered by the more general allowed tags rule // changes in Named Entities are most likely to be due to semantic errors if (isNamedEntity(tag1) && isNamedEntity(tag2)) { System.out.println("NAMED ENTITY"); System.out.println(token1 + " - " + token2); System.out.println(); continue; } // whether the probably wrong token1 would be detected by a spell checker boolean detectable; try { detectable = isDetectableSpellingError(changedToken1, changedToken2, s1, JCasUtil.selectCovered(revView1, Token.class, s1)); } catch (ResourceInitializationException e) { throw new AnalysisEngineProcessException(e); } catch (UIMAException e) { throw new AnalysisEngineProcessException(e); } if (detectable) { System.out.println("DETECTED SPELLING ERROR"); System.out.println(token1 + " - " + token2); System.out.println(); continue; } try { if (isInCloseRelation(lemma1.getValue(), lemma2.getValue())) { System.out.println("CLOSE RELATION"); System.out.println(token1 + " - " + token2); System.out.println(); continue; } } catch (LexicalSemanticResourceException e) { throw new AnalysisEngineProcessException(e); } System.out.println(token1 + " - " + token2); System.out.println(freq1 + " - " + freq2); System.out.println(s1.getCoveredText()); System.out.println(s2.getCoveredText()); System.out.println(); String leftContext = getContextSentences(revView1, s1, NR_OF_CONTEXT_SENTENCES, true); String rightContext = getContextSentences(revView1, s1, NR_OF_CONTEXT_SENTENCES, false); // write remaining errors in file using correct formatting DatasetItem item = new DatasetItem(token1, token2, leftContext.length() + changedToken1.getBegin() - s1.getBegin(), leftContext + s1.getCoveredText() + rightContext, new Integer(dmd.getCollectionId()).intValue(), new Integer(dmd.getDocumentId()).intValue()); // both token should have the same POS, otherwise it is more likely a grammatical error if (tag1.getClass().getName().equals(tag2.getClass().getName())) { if (!alreadySeenErrors.contains(item.getWrong() + "-" + item.getCorrect())) { alreadySeenErrors.add(item.getWrong() + "-" + item.getCorrect()); writeItem(semanticErrorWriter, item); } } else { if (!alreadySeenErrors.contains(item.getWrong() + "-" + item.getCorrect())) { alreadySeenErrors.add(item.getWrong() + "-" + item.getCorrect()); writeItem(syntacticErrorWriter, item); } } } }
From source file:org.apache.nifi.web.dao.impl.StandardConnectionDAO.java
@Override public DropFlowFileStatus createFlowFileDropRequest(String id, String dropRequestId) { final Connection connection = locateConnection(id); final FlowFileQueue queue = connection.getFlowFileQueue(); final NiFiUser user = NiFiUserUtils.getNiFiUser(); if (user == null) { throw new WebApplicationException(new Throwable("Unable to access details for current user.")); }/*w w w . j av a 2 s. c o m*/ return queue.dropFlowFiles(dropRequestId, user.getIdentity()); }
From source file:com.tesora.dve.sql.logfile.LogFileTest.java
protected void configMTTest(final TestName tn, BackingSchema leftType, BackingSchema rightType) throws Throwable { aborted = false;/*w w w . j a va 2 s . c o m*/ // first off, mt tests cannot run if both backing types are pe int npet = 0; if ((leftType != null) && (leftType != BackingSchema.NATIVE)) { npet++; } if ((rightType != null) && (rightType != BackingSchema.NATIVE)) { npet++; } if (npet > 1) { throw new Throwable("Misconfiguration of configMTTest. Only one side is allowed to be PE"); } lastRan = new LastRunConfig(tn, leftType, rightType); // mt single, native mt single mirror, mt multi, native mt multi mirror final TestResource firstResource = getTestResource(tn, leftType); final TestResource secondResource = getTestResource(tn, rightType); try { TestResource rootResource = null; TestResource nativeResource = null; if (secondResource == null) { // either mt single or mt multi - in this case we don't need to worry about setting up the native connection rootResource = firstResource; } else if (firstResource.getDDL() != getNativeDDL()) { throw new Throwable( "Misconfiguration of configMTTest. Mirror test configured but lhs is not native"); } else { nativeResource = firstResource; rootResource = secondResource; } if (useThreads(tn) && (nativeResource != null)) { throw new Throwable( "Misconveriguration of configMTTest. Thread use requested but native resource present"); } // first up, remove any existing mt user removeUser(rootResource.getConnection(), mtUserName, mtUserAccess); // now put the system in mt mode // now we're going to load the database. note that this is done as the root user. if (mtLoadDatabase()) { preTest(tn, nativeResource, rootResource, getFile(tn, 0), 1); } // now we're going to run the actual test for the root user MultitenantMode mm = null; if (rootResource.getDDL() instanceof PEDDL) { final PEDDL peddl = (PEDDL) rootResource.getDDL(); mm = peddl.getMultitenantMode(); } if (!skipInitialMTLoad(tn)) { if (nativeResource != null) { runTest(tn, nativeResource, rootResource, getFile(tn, 0), createSchema(tn), verifyUpdates(tn), getSkipStatements(tn, 0), getBreakpoints(tn), ignoreResults(tn), compareUnordered(tn), verifyTempTables(tn), TestPart.BODY); } else { runTest(tn, rootResource, null, getFile(tn, 0), createSchema(tn), verifyUpdates(tn), getSkipStatements(tn, 0), getBreakpoints(tn), ignoreResults(tn), compareUnordered(tn), verifyTempTables(tn), TestPart.BODY); } } else if (createSchema(tn)) { if (nativeResource != null) { runDDL(true, nativeResource); } runDDL(true, rootResource); } maybeConnect(rootResource); // create the second user - have to delay because we don't yet add users upon new site rootResource.getConnection().execute( "create user '" + mtUserName + "'@'" + mtUserAccess + "' identified by '" + mtUserName + "'"); if (useThreads(tn)) { final LogFileTest me = this; final ArrayList<Thread> threads = new ArrayList<Thread>(); for (int i = 0; i < maxTenants(tn); i++) { final FileResource log = getFile(tn, i); if (log != null) { System.out.println("MT tenant " + i + " running log " + log.getFileName()); } // set perms final String ctenant = tenantKernel + i; rootResource.getConnection() .execute("create tenant " + ctenant + " '" + tn.toString() + " " + ctenant + "'"); rootResource.getConnection().execute("grant all on " + ctenant + ".* to '" + mtUserName + "'@'" + mtUserAccess + "' identified by '" + mtUserName + "'"); final long[] skips = getSkipStatements(tn, i); final TestResource tenantResource = new TestResource( new ProxyConnectionResource(mtUserName, mtUserName), getSingleSiteDDL().buildTenantDDL(ctenant)); if (shouldCreateUserForTenant()) { createUserForTenant(rootResource, ctenant, ctenant); } // dup our resources threads.add(new Thread(ctenant) { @Override public void run() { try { if (!mtLoadDatabase()) { // if we didn't run the pretest earlier then // we want to do it for each tenant preTest(tn, tenantResource, null, log, 1); } runTest(tn, tenantResource, null, log, false, verifyUpdates(tn), skips, getBreakpoints(tn), ignoreResults(tn), compareUnordered(tn), verifyTempTables(tn), TestPart.BODY); } catch (final Throwable t) { if ("Aborting log file run".equals(t.getMessage())) { // don't overreport, just get out return; } System.err.println("Tenant: " + ctenant + " FAILED"); t.printStackTrace(); me.aborted = true; fail(t.getMessage()); throw new RuntimeException(t); } finally { maybeDisconnect(tenantResource); } } }); } for (final Thread t : threads) { t.start(); } while (!threads.isEmpty()) { for (final Iterator<Thread> iter = threads.iterator(); iter.hasNext();) { final Thread thr = iter.next(); try { thr.join(); iter.remove(); } catch (final InterruptedException ie) { // ignore } } } } else { for (int i = 0; i < maxTenants(tn); i++) { final FileResource log = getFile(tn, i); if (log != null) { System.out.println("MT tenant " + i + " running log " + log.getFileName()); } // make sure everything is connected maybeConnect(nativeResource); maybeConnect(rootResource); if (nativeResource != null) { nativeResource.getConnection() .execute("drop database if exists " + nativeResource.getDDL().getDatabaseName()); nativeResource.getConnection() .execute(nativeResource.getDDL().getCreateDatabaseStatement()); } final String ctenant = tenantKernel + i; rootResource.getConnection() .execute("create tenant " + ctenant + " '" + tn.toString() + " " + ctenant + "'"); rootResource.getConnection().execute("grant all on " + ctenant + ".* to '" + mtUserName + "'@'" + mtUserAccess + "' identified by '" + mtUserName + "'"); final TestResource tenantResource = new TestResource( new ProxyConnectionResource(mtUserName, mtUserName), getSingleSiteDDL().buildTenantDDL(ctenant)); // the tenant does not need to create schema, but if we're doing native we just tossed the backing database. // add that in now. if (nativeResource != null) { preTest(tn, nativeResource, tenantResource, log, i + 1); } // now run again if (nativeResource != null) { runTest(tn, nativeResource, tenantResource, log, false, verifyUpdates(tn), getSkipStatements(tn, i), getBreakpoints(tn), ignoreResults(tn), compareUnordered(tn), verifyTempTables(tn), TestPart.BODY); } else { runTest(tn, tenantResource, null, log, false, verifyUpdates(tn), getSkipStatements(tn, i), getBreakpoints(tn), ignoreResults(tn), compareUnordered(tn), verifyTempTables(tn), TestPart.BODY); } maybeDisconnect(nativeResource); maybeDisconnect(rootResource); maybeDisconnect(tenantResource); } } // report on private/public tables if (getNoisyInterval() != null) { try { System.out.println("Sleeping for 2 seconds to collect adaptive garbage"); Thread.sleep(2000); } catch (final InterruptedException ie) { // ignore } try (DBHelperConnectionResource dbh = new DBHelperConnectionResource()) { dbh.execute("use " + PEConstants.CATALOG); System.out.println("Multitenant mode: " + (mm != null ? mm.getPersistentValue() : "null MM")); System.out.println("number of table scopes:"); System.out.println(dbh.printResults("select count(*) from scope")); System.out.println("private tables:"); // System.out.println(dbh.printResults("select count(*) from user_table ut, user_database ud where ut.user_database_id = ud.user_database_id and ud.multitenant_mode != 'off' and ut.privtab_ten_id is not null")); System.out.println(dbh.printResults( "select ut.name, s.local_name, t.ext_tenant_id from user_table ut, scope s, tenant t where ut.privtab_ten_id is not null and ut.table_id = s.scope_table_id and s.scope_tenant_id = t.tenant_id")); System.out.println("number of shared tables:"); System.out.println(dbh.printResults( "select count(*) from user_table ut, user_database ud where ut.user_database_id = ud.user_database_id and ud.multitenant_mode != 'off' and ut.privtab_ten_id is null")); // System.out.println("Compression:"); // System.out.println(dbh.printResults("select coalesce(local_name,ut.name), count(distinct scope_table_id), count(scope_table_id) from scope, user_table ut where scope_table_id = ut.table_id group by local_name order by local_name")); } } } finally { maybeDisconnect(firstResource); maybeDisconnect(secondResource); } // allow someone to do something after the test run postTest(tn, firstResource, secondResource, getFile(tn, 0), 1); }
From source file:com.microsoft.tfs.core.TFSConnection.java
/** * Creates a {@link TFSConnection}. Both a {@link URI} and a * {@link ConnectionAdvisor} are specified. * <p>/*from w w w. j a v a 2 s . c om*/ * The URI in the profile must be the fully qualified URI to the server; it * should not point to a project collection. * * @param serverURI * the {@link URI} to connect to (must not be <code>null</code>). * This URI must be properly URI encoded. * @param credentialsHolder * an {@link AtomicReference} to the {@link Credentials} to connect * with (must not be <code>null</code>) * @param advisor * the {@link ConnectionAdvisor} to use (must not be * <code>null</code>) * @param locationServiceRelativePath * the URI path (relative to the scheme, host, and port of the main * URI computed from the profile data) where the location service can * be reached for this connection (must not be <code>null</code> or * empty) */ protected TFSConnection(URI serverURI, final AtomicReference<Credentials> credentialsHolder, final ConnectionAdvisor advisor, final String locationServiceRelativePath) { Check.notNull(serverURI, "serverURI"); //$NON-NLS-1$ Check.notNull(advisor, "advisor"); //$NON-NLS-1$ Check.notNullOrEmpty(locationServiceRelativePath, "locationServiceRelativePath"); //$NON-NLS-1$ this.locationServiceRelativePath = locationServiceRelativePath; /* * Build a new server URL in the short format. * * getBaseURI() must use a similar rewrite rule because it defers to the * ConnectionAdvisor's URI provider, which may decide to return a * different URI even though the server URL has already been shortened. */ final String serverURIShortFormat = serverURI.toString(); if (serverURIShortFormat != null && serverURIShortFormat.toLowerCase().endsWith(this.locationServiceRelativePath.toLowerCase())) { try { /* * Note that the input URI is literal (already encoded, if * necessary) so we use the URI ctor instead of URIUtils#newURI * method (which would doubly encode). */ serverURI = new URI(serverURIShortFormat.substring(0, serverURIShortFormat.length() - this.locationServiceRelativePath.length())); } catch (final URISyntaxException e) { throw new IllegalArgumentException(e.getLocalizedMessage(), e); } } this.advisor = advisor; this.sessionId = GUID.newGUID(); this.instanceData = new ConnectionInstanceData(serverURI, credentialsHolder, sessionId); if (log.isDebugEnabled()) { log.debug(MessageFormat.format("Created a new TFSConnection, sessionId: [{0}], server URI: [{1}]", //$NON-NLS-1$ sessionId, serverURI)); } shutdownEventListener = new ShutdownEventListener() { final Throwable creationStack = isSDK() ? new Throwable( "The TFSConnection was closed during JVM shutdown because it was not properly closed by the creator. The creator of the TFSConnection should close the connection when finished with it.") //$NON-NLS-1$ : null; @Override public void onShutdown() { if (isClosed()) { /** * During shutdown it is possible for * TFSConfigurationServers to be closed by their owning * TFSTeamProjectCollections, but the shutdown listener is * already iterating, so it will attempt to close it again; * we don't want this. */ return; } if (creationStack != null) { /** * Warn SDK users that they should have closed the * connection. */ log.warn(creationStack.getMessage(), creationStack); } log.debug("Shutdown: close TFSConnection."); //$NON-NLS-1$ close(); log.debug("Shutdown: TFSCconnection closed."); //$NON-NLS-1$ } }; ShutdownManager.getInstance().addShutdownEventListener(shutdownEventListener, Priority.MIDDLE); /* Preview expiration enforcement */ // checkPreviewExpiration(); }
From source file:com.pyj.http.AsyncHttpClient.java
/** * Perform a HTTP GET request and track the Android Context which initiated * the request./*from www . j av a 2s. c om*/ * * @param context * the Android Context which initiated the request. * @param url * the URL to send the request to. * @param params * additional GET parameters to send with the request. * @param responseHandler * the response handler instance that should handle the response. */ public void get(Context context, String url, RequestParams params, BaseHttpResponseHandler responseHandler) { if (url == null) ((AsyncHttpResponseHandler) responseHandler).sendFailureMessage(new Throwable("??"), "??", ((AsyncHttpResponseHandler) responseHandler).reqCode); else sendRequest(httpClient, httpContext, new HttpGet(getUrlWithQueryString(url, params)), null, (AsyncHttpResponseHandler) responseHandler, context); }
From source file:org.apache.ode.bpel.rtrep.v1.ASSIGN.java
@Override Node fetchVariableData(VariableInstance variable, boolean forWriting) throws FaultException { try {/* w w w .j av a 2 s .com*/ return super.fetchVariableData(variable, forWriting); } catch (FaultException fe) { if (forWriting) { fe = new FaultException(fe.getQName(), fe.getMessage(), new Throwable("throwUninitializedToVariable")); } throw fe; } }
From source file:com.thoughtworks.selenium.SeleneseTestNgHelperVir.java
/** * Reportresult.//from w ww.jav a2s .c om * * @param isAssert * the is assert * @param step * the step * @param result * the result * @param messageString * the message string */ public final void reportresult(final boolean isAssert, final String step, final String result, final String messageString) { String message = messageString; StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace(); callingClassName = stackTraceElements[0].getClassName().toString().toString(); String callingMethod = ""; // System.out.println("-----superman-----"); for (int i = 0; i < stackTraceElements.length; i++) { callingClassName = stackTraceElements[i].getClassName().toString(); if (callingClassName.startsWith(testPackageName)) { callingMethod = stackTraceElements[i].getMethodName(); lineNumber = stackTraceElements[i].getLineNumber(); break; } } System.out.println(callingClassName); // System.out.println("-----superman-----"); Class callingClass = null; try { callingClass = Class.forName(callingClassName); } catch (ClassNotFoundException e) { e.printStackTrace(); } getLogger(callingClass); if (!currentMethod.equals(callingMethod)) { getLog().info("Executing : " + callingClass.getName() + " : " + callingMethod); currentMethod = callingMethod; } getLog().info("Step : " + step + "\t|\tResult : " + result + "\t|\tMessage : " + message); logTime(step, getCommandStartTime(), getCurrentTime(), getLog()); reporter.reportResult(step, result, message); // Adding data to the new reporter try { String testStep = step.substring(0, step.indexOf(":")); // replace xml special characters in the message. message = replaceXMLSpecialCharacters(message); if (result.equals("PASSED")) { String testMessage = message; if (message.equals("") || message == null) { testMessage = "Passed"; } if (callingClassName.contains("LIBRARY_RECOVERY")) { resultReporter.reportStepResults(true, "RECOVERY : " + testStep, testMessage, "Success", ""); } else { resultReporter.reportStepResults(true, testStep, testMessage, "Success", ""); } } else { if (callingClassName.contains("LIBRARY_RECOVERY")) { resultReporter.reportStepResults(false, "RECOVERY : " + testStep, message, "Error", getSourceLines(new Throwable(message).getStackTrace())); } else { resultReporter.reportStepResults(false, testStep, message, "Error", getSourceLines(new Throwable(message).getStackTrace())); } } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.pyj.http.AsyncHttpClient.java
/** * Perform a HTTP GET request and track the Android Context which initiated * the request with customized headers/*from w ww. ja v a 2 s. com*/ * * @param url * the URL to send the request to. * @param headers * set headers only for this request * @param params * additional GET parameters to send with the request. * @param responseHandler * the response handler instance that should handle the response. */ public void get(Context context, String url, Header[] headers, RequestParams params, AsyncHttpResponseHandler responseHandler) { if (url == null) responseHandler.sendFailureMessage(new Throwable("??"), "??", responseHandler.reqCode); else { HttpUriRequest request = new HttpGet(getUrlWithQueryString(url, params)); if (headers != null) request.setHeaders(headers); sendRequest(httpClient, httpContext, request, null, responseHandler, context); } }
From source file:com.couchbase.lite.replicator.ChangeTracker.java
public void setUpstreamError(String message) { Log.w(Log.TAG_CHANGE_TRACKER, "Server error: %s", message); this.error = new Throwable(message); }
From source file:org.apache.hadoop.hbase.procedure2.Procedure.java
/** * Called by the ProcedureExecutor on procedure-load to restore the latch state *//*from ww w.j a va 2s . c o m*/ @InterfaceAudience.Private protected synchronized void setChildrenLatch(final int numChildren) { this.childrenLatch = numChildren; if (LOG.isTraceEnabled()) { LOG.trace("CHILD LATCH INCREMENT SET " + this.childrenLatch, new Throwable(this.toString())); } }