org.apache.commons.lang.exception.ExceptionUtils Java Examples

The following examples show how to use org.apache.commons.lang.exception.ExceptionUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JavaTokenizer.java    From api-mining with GNU General Public License v3.0 6 votes vote down vote up
@Override
public SortedMap<Integer, String> tokenListWithPos(final char[] code) {
	final PublicScanner scanner = prepareScanner();
	final SortedMap<Integer, String> tokens = Maps.newTreeMap();
	tokens.put(-1, SENTENCE_START);
	tokens.put(Integer.MAX_VALUE, SENTENCE_END);
	scanner.setSource(code);
	while (!scanner.atEnd()) {
		do {
			try {
				final int token = scanner.getNextToken();
				if (token == ITerminalSymbols.TokenNameEOF) {
					break;
				}
				final String nxtToken = transformToken(token,
						scanner.getCurrentTokenString());
				final int position = scanner.getCurrentTokenStartPosition();
				tokens.put(position, stripTokenIfNeeded(nxtToken));
			} catch (final InvalidInputException e) {
				LOGGER.warning(ExceptionUtils.getFullStackTrace(e));
			}
		} while (!scanner.atEnd());

	}
	return tokens;
}
 
Example #2
Source File: IdempotentConsumerInTransactionSpringTest.java    From camel-cookbook-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testTransactedExceptionThrown() throws InterruptedException {
    AuditLogDao auditLogDao = getMandatoryBean(AuditLogDao.class, "auditLogDao");
    String message = "this message will explode";
    assertEquals(0, auditLogDao.getAuditCount(message));

    MockEndpoint mockCompleted = getMockEndpoint("mock:out");
    mockCompleted.setExpectedMessageCount(1);
    mockCompleted.whenAnyExchangeReceived(new ExceptionThrowingProcessor());

    try {
        template.sendBodyAndHeader("direct:transacted", message, "messageId", "foo");
        fail();
    } catch (CamelExecutionException cee) {
        assertEquals("boom!", ExceptionUtils.getRootCause(cee).getMessage());
    }

    assertMockEndpointsSatisfied();
    assertEquals(0, auditLogDao.getAuditCount(message)); // the insert was rolled back

    @SuppressWarnings("unchecked")
    IdempotentRepository<String> idempotentRepository = getMandatoryBean(IdempotentRepository.class, "jdbcIdempotentRepository");

    // even though the transaction rolled back, the repository should still contain an entry for this messageId
    assertTrue(idempotentRepository.contains("foo"));
}
 
Example #3
Source File: HiveClient.java    From garmadon with Apache License 2.0 6 votes vote down vote up
protected void execute(String query) throws SQLException {
    LOGGER.debug("Execute hql: {}", query);
    int maxAttempts = 5;
    for (int retry = 1; retry <= maxAttempts; ++retry) {
        try {
            stmt.execute(query);
        } catch (SQLException sqlException) {
            if (ExceptionUtils.indexOfThrowable(sqlException, TTransportException.class) != -1) {
                String exMsg = String.format("Retry connecting to hive (%d/%d)", retry, maxAttempts);
                if (retry <= maxAttempts) {
                    LOGGER.warn(exMsg, sqlException);
                    try {
                        Thread.sleep(1000 * retry);
                        connect();
                    } catch (Exception ignored) {
                    }
                } else {
                    LOGGER.error(exMsg, sqlException);
                    throw sqlException;
                }
            } else {
                throw sqlException;
            }
        }
    }
}
 
Example #4
Source File: ExceptionMessageExchanger.java    From sinavi-jfw with Apache License 2.0 6 votes vote down vote up
/**
 * メッセージヘッダに必要な情報を付与し、例外用のキューへメッセージを転送します。
 * @param message 例外が発生したメッセージ
 * @param throwable 発生した例外
 */
@Override
public void recover(Message message, Throwable throwable) {
    Args.checkNotNull(exchange, R.getObject("E-AMQP-RETRY#0004"));
    Map<String, Object> headers = message.getMessageProperties().getHeaders();
    headers.put(HEADER_KEY_EXCEPTION_STACKTRACE, ExceptionUtils.getStackTrace(throwable));
    headers.put(HEADER_KEY_EXCEPTION_MESSAGE, throwable.getMessage());
    headers.put(HEADER_KEY_ORIGINAL_EXCHANGE, message.getMessageProperties().getReceivedExchange());
    headers.put(HEADER_KEY_ORIGINAL_ROUTING_KEY, message.getMessageProperties().getReceivedRoutingKey());
    String rk = defaultRoutingKey;
    Throwable cause = throwable;
    if (throwable instanceof ListenerExecutionFailedException) {
        cause = throwable.getCause();
    }
    if (cause instanceof AbstractAmqpException) {
        headers.put(HEADER_KEY_EXCEPTION_ID, ((AbstractAmqpException) cause).getId());
        rk = ((AbstractAmqpException) cause).getRoutingKey();
    }
    amqpTemplate.send(exchange, rk, message);
    logging(exchange, rk, message);
}
 
Example #5
Source File: SignaturesTest.java    From camel-cookbook-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testMessageModificationAfterSigning() throws InterruptedException {
    MockEndpoint mockSigned = getMockEndpoint("mock:signed");
    mockSigned.whenAnyExchangeReceived(new Processor() {
        @Override
        public void process(Exchange exchange) throws Exception {
            Message in = exchange.getIn();
            in.setBody(in.getBody(String.class) + "modified");
        }
    });

    MockEndpoint mockVerified = getMockEndpoint("mock:verified");
    mockVerified.setExpectedMessageCount(0);

    try {
        template.sendBody("direct:sign", "foo");
        fail();
    } catch (CamelExecutionException cex) {
        assertTrue(ExceptionUtils.getRootCause(cex) instanceof SignatureException);
        assertEquals("SignatureException: Cannot verify signature of exchange",
            ExceptionUtils.getRootCauseMessage(cex));
    }

    assertMockEndpointsSatisfied();
}
 
Example #6
Source File: JavaWhitespaceTokenizer.java    From api-mining with GNU General Public License v3.0 6 votes vote down vote up
@Override
public List<String> tokenListFromCode(final char[] code) {
	final List<String> tokens = Lists.newArrayList();
	tokens.add(SENTENCE_START);
	final PublicScanner scanner = prepareScanner(code);
	do {
		try {
			final int token = scanner.getNextToken();
			if (token == ITerminalSymbols.TokenNameEOF) {
				break;
			}
			tokens.addAll(getConvertedToken(scanner, token));
		} catch (final InvalidInputException e) {
			LOGGER.warning(ExceptionUtils.getFullStackTrace(e));
		}
	} while (!scanner.atEnd());
	tokens.add(SENTENCE_END);
	return tokens;
}
 
Example #7
Source File: JavaTokenizer.java    From codemining-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public SortedMap<Integer, String> tokenListWithPos(final char[] code) {
	final PublicScanner scanner = prepareScanner();
	final SortedMap<Integer, String> tokens = Maps.newTreeMap();
	tokens.put(-1, SENTENCE_START);
	tokens.put(Integer.MAX_VALUE, SENTENCE_END);
	scanner.setSource(code);
	while (!scanner.atEnd()) {
		do {
			try {
				final int token = scanner.getNextToken();
				if (token == ITerminalSymbols.TokenNameEOF) {
					break;
				}
				final String nxtToken = transformToken(token,
						scanner.getCurrentTokenString());
				final int position = scanner.getCurrentTokenStartPosition();
				tokens.put(position, stripTokenIfNeeded(nxtToken));
			} catch (final InvalidInputException e) {
				LOGGER.warning(ExceptionUtils.getFullStackTrace(e));
			}
		} while (!scanner.atEnd());

	}
	return tokens;
}
 
Example #8
Source File: LogEventConvert.java    From canal with Apache License 2.0 6 votes vote down vote up
private TableMeta getTableMeta(String dbName, String tbName, boolean useCache, EntryPosition position) {
    try {
        return tableMetaCache.getTableMeta(dbName, tbName, useCache, position);
    } catch (Throwable e) {
        String message = ExceptionUtils.getRootCauseMessage(e);
        if (filterTableError) {
            if (StringUtils.contains(message, "errorNumber=1146") && StringUtils.contains(message, "doesn't exist")) {
                return null;
            } else if (StringUtils.contains(message, "errorNumber=1142")
                       && StringUtils.contains(message, "command denied")) {
                return null;
            }
        }

        throw new CanalParseException(e);
    }
}
 
Example #9
Source File: TransactionPolicyTest.java    From camel-cookbook-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testFailureMock2() throws InterruptedException {
    String message = "ping";
    assertEquals(0, auditLogDao.getAuditCount(message));

    MockEndpoint mockOut1 = getMockEndpoint("mock:out1");
    mockOut1.setExpectedMessageCount(1);
    mockOut1.message(0).body().isEqualTo(message);

    MockEndpoint mockOut2 = getMockEndpoint("mock:out2");
    mockOut2.whenAnyExchangeReceived(new ExceptionThrowingProcessor());

    try {
        template.sendBody("direct:policies", message);
        fail();
    } catch (Exception e) {
        assertEquals("boom!", ExceptionUtils.getRootCause(e).getMessage());
    }

    assertMockEndpointsSatisfied();
    assertEquals(1, auditLogDao.getAuditCount(message));
    assertEquals(0, messageDao.getMessageCount(message));
}
 
Example #10
Source File: IdempotentConsumerInTransactionTest.java    From camel-cookbook-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testWebserviceExceptionRollsBackTransactionAndIdempotentRepository() throws InterruptedException {
    String message = "this message will be OK";
    assertEquals(0, auditLogDao.getAuditCount(message));

    MockEndpoint mockCompleted = getMockEndpoint("mock:out");
    mockCompleted.setExpectedMessageCount(0);

    MockEndpoint mockWs = getMockEndpoint("mock:ws");
    mockWs.whenAnyExchangeReceived(new ExceptionThrowingProcessor("ws is down"));

    try {
        template.sendBodyAndHeader("direct:transacted", message, "messageId", "foo");
        fail();
    } catch (CamelExecutionException cee) {
        assertEquals("ws is down", ExceptionUtils.getRootCause(cee).getMessage());
    }

    assertMockEndpointsSatisfied();
    assertEquals(0, auditLogDao.getAuditCount(message)); // the insert was successful

    // the repository has not seen this messageId
    assertTrue(!idempotentRepository.contains("foo"));
}
 
Example #11
Source File: TransactionPolicyNestedTest.java    From camel-cookbook-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testFailureMock1() throws InterruptedException {
    String message = "ping";
    assertEquals(0, auditLogDao.getAuditCount(message));

    MockEndpoint mockOut1 = getMockEndpoint("mock:out1");
    mockOut1.whenAnyExchangeReceived(new ExceptionThrowingProcessor());
    mockOut1.message(0).body().isEqualTo(message);

    MockEndpoint mockOut2 = getMockEndpoint("mock:out2");
    mockOut2.setExpectedMessageCount(1);

    try {
        template.sendBody("direct:policies", message);
        fail();
    } catch (Exception e) {
        assertEquals("boom!", ExceptionUtils.getRootCause(e).getMessage());
    }

    assertMockEndpointsSatisfied();
    assertEquals(1, auditLogDao.getAuditCount(message));
    assertEquals(0, messageDao.getMessageCount(message));
}
 
Example #12
Source File: ExceptionNotificationServiceImpl.java    From telekom-workflow-engine with MIT License 6 votes vote down vote up
public void handleException( Exception exception ){
    if( isServiceEnabled() ){
        Date now = new Date();
        newExceptionsCount.incrementAndGet();

        if( nextPossibleNotification.before( now ) ){
            int count = newExceptionsCount.getAndSet( 0 );

            String subject = count + " exception(s) occured in " + mailEnvironment + " Workflow Engine";
            String body = ""
                    + count + " exception(s) occured with ip " + getHostIpAddress() + ". \n"
                    + "\n"
                    + "The most recent exception occured at " + format( now ) + " with the following stacktrace:\n"
                    + "\n"
                    + ExceptionUtils.getFullStackTrace( exception );

            sendEmail( mailFrom, recipients, subject, body );

            nextPossibleNotification = DateUtils.addMinutes( now, notificationIntervalMinutes );
        }
    }
}
 
Example #13
Source File: JavascriptTokenizer.java    From codemining-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public SortedMap<Integer, String> tokenListWithPos(final char[] code) {
	final PublicScanner scanner = prepareScanner();
	final SortedMap<Integer, String> tokens = Maps.newTreeMap();
	tokens.put(-1, SENTENCE_START);
	tokens.put(Integer.MAX_VALUE, SENTENCE_END);
	scanner.setSource(code);
	while (!scanner.atEnd()) {
		do {
			try {
				final int token = scanner.getNextToken();
				if (token == ITerminalSymbols.TokenNameEOF) {
					break;
				}
				final String nxtToken = transformToken(token,
						scanner.getCurrentTokenString());
				final int position = scanner.getCurrentTokenStartPosition();
				tokens.put(position, stripTokenIfNeeded(nxtToken));
			} catch (final InvalidInputException e) {
				LOGGER.warning(ExceptionUtils.getFullStackTrace(e));
			}
		} while (!scanner.atEnd());

	}
	return tokens;
}
 
Example #14
Source File: ErrorGenerator.java    From opensoc-streaming with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static JSONObject generateErrorMessage(String message, Exception e)
{
	JSONObject error_message = new JSONObject();
	
	/*
	 * Save full stack trace in object.
	 */
	String stackTrace = ExceptionUtils.getStackTrace(e);
	
	String exception = e.toString();
	
	error_message.put("time", System.currentTimeMillis());
	try {
		error_message.put("hostname", InetAddress.getLocalHost().getHostName());
	} catch (UnknownHostException ex) {
		// TODO Auto-generated catch block
		ex.printStackTrace();
	}
	
	error_message.put("message", message);
	error_message.put("exception", exception);
	error_message.put("stack", stackTrace);
	
	return error_message;
}
 
Example #15
Source File: IndexerProcessRegistryImpl.java    From hbase-indexer with Apache License 2.0 6 votes vote down vote up
@Override
public void setErrorStatus(final String indexerProcessId, Throwable error) {
    final String stackTrace = ExceptionUtils.getStackTrace(error);

    try {
        zk.retryOperation(new ZooKeeperOperation<Integer>() {

            @Override
            public Integer execute() throws KeeperException, InterruptedException {
                zk.setData(indexerProcessId, Bytes.toBytes(stackTrace), -1);
                return 0;
            }
        });
    } catch (Exception e) {
        throw new RuntimeException("Error while setting error status on indexer node " + indexerProcessId, e);
    }
}
 
Example #16
Source File: TransactionPolicyNestedSpringTest.java    From camel-cookbook-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testFailureMock1() throws InterruptedException {
    AuditLogDao auditLogDao = getMandatoryBean(AuditLogDao.class, "auditLogDao");
    MessageDao messageDao = getMandatoryBean(MessageDao.class, "messageDao");

    String message = "ping";
    assertEquals(0, auditLogDao.getAuditCount(message));

    MockEndpoint mockOut1 = getMockEndpoint("mock:out1");
    mockOut1.whenAnyExchangeReceived(new ExceptionThrowingProcessor());
    mockOut1.message(0).body().isEqualTo(message);

    MockEndpoint mockOut2 = getMockEndpoint("mock:out2");
    mockOut2.setExpectedMessageCount(1);

    try {
        template.sendBody("direct:policies", message);
        fail();
    } catch (Exception e) {
        assertEquals("boom!", ExceptionUtils.getRootCause(e).getMessage());
    }

    assertMockEndpointsSatisfied();
    assertEquals(1, auditLogDao.getAuditCount(message));
    assertEquals(0, messageDao.getMessageCount(message));
}
 
Example #17
Source File: JavaVariableNameTypeDistribution.java    From naturalize with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static JavaVariableNameTypeDistribution buildFromFiles(
		final Collection<File> files) {
	final JavaVariableNameTypeDistribution tp = new JavaVariableNameTypeDistribution();
	for (final File f : files) {
		try {
			final JavaASTExtractor ex = new JavaASTExtractor(false);
			final CompilationUnit cu = ex.getAST(f);
			final JavaApproximateTypeInferencer typeInf = new JavaApproximateTypeInferencer(
					cu);
			typeInf.infer();
			final Map<String, String> varTypes = typeInf.getVariableTypes();
			for (final Entry<String, String> variable : varTypes.entrySet()) {
				tp.typePrior.addElement(variable.getKey(),
						variable.getValue());
			}
		} catch (final IOException e) {
			LOGGER.warning(ExceptionUtils.getFullStackTrace(e));
		}
	}

	return tp;
}
 
Example #18
Source File: RedisCacheImpl.java    From openbd-core with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Delete all the keys in the region data store, and its respective TTLs.
 * 
 * Time Complexity is O(2N), where N is the number of keys in the region.
 * This N is multiplied by 2 since there are N ttls for N keys.
 */
@Override
public void deleteAll() {

	try {

		/*
		 * Delete the data store for the region,
		 * and the respective ttls data store,
		 * in a fire&forget fashion.
		 * 
		 */
		asyncCommands.del( region );
		asyncCommands.del( ttls );
		
		// cfEngine.log( getName() + ":" + region +":" + server + " >> deleteAll" );

	} catch ( Exception e ) {
		cfEngine.log( logPrefix  + " deleteAll failed:\n" + ExceptionUtils.getStackTrace(e));
	}
}
 
Example #19
Source File: CompactionThresholdVerifier.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * There are two record count we are comparing here
 *    1) The new record count in the input folder
 *    2) The record count we compacted previously from last run
 * Calculate two numbers difference and compare with a predefined threshold.
 *
 * (Alternatively we can save the previous record count to a state store. However each input
 * folder is a dataset. We may end up with loading too many redundant job level state for each
 * dataset. To avoid scalability issue, we choose a stateless approach where each dataset tracks
 * record count by themselves and persist it in the file system)
 *
 * @return true iff the difference exceeds the threshold or this is the first time compaction
 */
public Result verify(FileSystemDataset dataset) {

  Map<String, Double> thresholdMap = RecompactionConditionBasedOnRatio.
      getDatasetRegexAndRecompactThreshold(
          state.getProp(MRCompactor.COMPACTION_LATEDATA_THRESHOLD_FOR_RECOMPACT_PER_DATASET, StringUtils.EMPTY));

  CompactionPathParser.CompactionParserResult result = new CompactionPathParser(state).parse(dataset);

  double threshold =
      RecompactionConditionBasedOnRatio.getRatioThresholdByDatasetName(result.getDatasetName(), thresholdMap);
  log.debug("Threshold is {} for dataset {}", threshold, result.getDatasetName());

  InputRecordCountHelper helper = new InputRecordCountHelper(state);
  try {
    double newRecords = 0;
    if (!dataset.isVirtual()) {
      newRecords = helper.calculateRecordCount(Lists.newArrayList(new Path(dataset.datasetURN())));
    }
    double oldRecords = helper.readRecordCount(new Path(result.getDstAbsoluteDir()));

    if (oldRecords == 0) {
      return new Result(true, "");
    }
    if (newRecords < oldRecords) {
      return new Result(false, "Illegal state: Current records count should old be smaller.");
    }

    if ((newRecords - oldRecords) / oldRecords > threshold) {
      log.debug("Dataset {} records exceeded the threshold {}", dataset.datasetURN(), threshold);
      return new Result(true, "");
    }

    return new Result(false, String
        .format("%s is failed for dataset %s. Prev=%f, Cur=%f, not reaching to threshold %f", this.getName(),
            result.getDatasetName(), oldRecords, newRecords, threshold));
  } catch (IOException e) {
    return new Result(false, ExceptionUtils.getFullStackTrace(e));
  }
}
 
Example #20
Source File: GeneralRegion.java    From AreaShop with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Run commands as the CommandsSender, replacing all tags with the relevant values.
 * @param sender   The sender that should perform the command
 * @param commands A list of the commands to run (without slash and with tags)
 */
public void runCommands(CommandSender sender, List<String> commands) {
	if(commands == null || commands.isEmpty()) {
		return;
	}

	for(String command : commands) {
		if(command == null || command.isEmpty()) {
			continue;
		}
		// It is not ideal we have to disable language replacements here, but otherwise giving language variables
		// to '/areashop message' by a command in the config gets replaced and messes up the fancy formatting.
		command = Message.fromString(command).replacements(this).noLanguageReplacements().getSingle();

		boolean result;
		String error = null;
		String stacktrace = null;
		try {
			result = plugin.getServer().dispatchCommand(sender, command);
		} catch(CommandException e) {
			result = false;
			error = e.getMessage();
			stacktrace = ExceptionUtils.getStackTrace(e);
		}
		boolean printed = false;
		if(!result) {
			printed = true;
			if(error != null) {
				AreaShop.warn("Command execution failed, command=" + command + ", error=" + error + ", stacktrace:");
				AreaShop.warn(stacktrace);
				AreaShop.warn("--- End of stacktrace ---");
			} else {
				AreaShop.warn("Command execution failed, command=" + command);
			}
		}
		if(!printed) {
			AreaShop.debug("Command run, executor=" + sender.getName() + ", command=" + command);
		}
	}
}
 
Example #21
Source File: DefaultGmlImportService.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private String createNotifierErrorMessage( Throwable throwable )
{
    StringBuilder sb = new StringBuilder( "GML import failed: " );

    Throwable rootThrowable = ExceptionUtils.getRootCause( throwable );

    if ( rootThrowable == null )
    {
        rootThrowable = throwable;
    }

    if ( rootThrowable instanceof SAXParseException )
    {
        SAXParseException e = (SAXParseException) rootThrowable;
        sb.append( e.getMessage() );

        if ( e.getLineNumber() >= 0 )
        {
            sb.append( " On line " ).append( e.getLineNumber() );

            if ( e.getColumnNumber() >= 0 )
            {
                sb.append( " column " ).append( e.getColumnNumber() );
            }
        }
    }
    else
    {
        sb.append( rootThrowable.getMessage() );
    }

    if ( sb.charAt( sb.length() - 1 ) != '.' )
    {
        sb.append( '.' );
    }

    return HtmlUtils.htmlEscape( sb.toString() );
}
 
Example #22
Source File: RuleCompatibleHelperTest.java    From tddl with Apache License 2.0 5 votes vote down vote up
@Test
public void testCompatible_le() {
    try {
        Resource resource = new PathMatchingResourcePatternResolver().getResource("classpath:compatible/le-spring-context.xml");
        String ruleStr = StringUtils.join(IOUtils.readLines(resource.getInputStream()), SystemUtils.LINE_SEPARATOR);
        ApplicationContext context = new StringXmlApplicationContext(RuleCompatibleHelper.compatibleRule(ruleStr));
        VirtualTableRoot vtr1 = (VirtualTableRoot) context.getBean("vtabroot");
        Assert.assertNotNull(vtr1);
    } catch (IOException e) {
        Assert.fail(ExceptionUtils.getFullStackTrace(e));
    }
}
 
Example #23
Source File: Utils.java    From soundwave with Apache License 2.0 5 votes vote down vote up
public static Response responseException(Exception e, Logger logger,
                                         OperationStats opStats, Map<String, String> tags) {

  logger.error(ExceptionUtils.getFullStackTrace(e));
  logger.error(ExceptionUtils.getRootCauseMessage(e));

  tags.put("status", String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
  tags.put("message", e.getClass().getSimpleName());

  opStats.failed(tags);

  return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
      .type(MediaType.APPLICATION_JSON)
      .build();
}
 
Example #24
Source File: Log.java    From aws-codecommit-trigger-plugin with Apache License 2.0 5 votes vote down vote up
private void write(final Level level, final String message, final String jobName, final Object... args) {
    for (int i = 0; i < args.length; i++) {
        if (args[i] instanceof SQSTriggerQueue) {
            args[i] = ((SQSTriggerQueue) args[i]).getUrl();
        }
        else if (args[i] instanceof Throwable) {
            args[i] = ExceptionUtils.getStackTrace((Throwable)args[i]);
        }
    }

    StringBuilder source = new StringBuilder();
    if (this.autoFormat) {
        final String id = String.format("%06X", Thread.currentThread().getId());
        source
            .append("[").append(this.clazz.getCanonicalName()).append("]")
            .append("[thread-").append(id).append("]");
        if (StringUtils.isNotBlank(jobName)) {
            source.append("[job-").append(jobName).append("]");
        }
    }

    String msg = String.format(message, args);
    if (level == Level.CONFIG) {
        msg = "[DEBUG] " + msg;
    } else if (level == Level.SEVERE) {
        msg = "[ERROR] " + msg;
    }

    this.logger.logp(level, source.toString(), "", msg);
    if (this.streamHandler != null) {
        this.streamHandler.flush();
    }
}
 
Example #25
Source File: Query.java    From incubator-tajo with Apache License 2.0 5 votes vote down vote up
private void finalizeQuery(Query query, QueryCompletedEvent event) {
  MasterPlan masterPlan = query.getPlan();

  ExecutionBlock terminal = query.getPlan().getTerminalBlock();
  DataChannel finalChannel = masterPlan.getChannel(event.getExecutionBlockId(), terminal.getId());
  Path finalOutputDir = commitOutputData(query);

  QueryHookExecutor hookExecutor = new QueryHookExecutor(query.context.getQueryMasterContext());
  try {
    hookExecutor.execute(query.context.getQueryContext(), query, event.getExecutionBlockId(),
        finalOutputDir);
  } catch (Exception e) {
    query.eventHandler.handle(new QueryDiagnosticsUpdateEvent(query.id, ExceptionUtils.getStackTrace(e)));
  }
}
 
Example #26
Source File: ZAProxyBuilder.java    From zaproxy-plugin with MIT License 5 votes vote down vote up
/**
    * Replace macro with environment variable if it exists
    * @param build
    * @param listener
    * @param macro
    * @return
    * @throws InterruptedException
    */
   @SuppressWarnings({ "unchecked", "rawtypes" })
public static String applyMacro(AbstractBuild build, BuildListener listener, String macro)
           throws InterruptedException{
       try {
           EnvVars envVars = new EnvVars(Computer.currentComputer().getEnvironment());
           envVars.putAll(build.getEnvironment(listener));
           envVars.putAll(build.getBuildVariables());
           return Util.replaceMacro(macro, envVars);
       } catch (IOException e) {
       	listener.getLogger().println("Failed to apply macro " + macro);
        listener.error(ExceptionUtils.getStackTrace(e));
       }
       return macro;
   }
 
Example #27
Source File: JavaWhitespaceTokenizer.java    From api-mining with GNU General Public License v3.0 5 votes vote down vote up
@Override
public SortedMap<Integer, String> tokenListWithPos(final char[] code) {
	final SortedMap<Integer, String> tokens = Maps.newTreeMap();
	tokens.put(-1, SENTENCE_START);
	tokens.put(Integer.MAX_VALUE, SENTENCE_END);
	final PublicScanner scanner = prepareScanner(code);

	while (!scanner.atEnd()) {
		do {
			try {
				final int token = scanner.getNextToken();
				final int position = scanner
						.getCurrentTokenStartPosition();
				if (token == ITerminalSymbols.TokenNameEOF) {
					break;
				}
				int i = 0;
				final List<String> cTokens = getConvertedToken(scanner,
						token);
				for (final String cToken : cTokens) {
					tokens.put(position + i, cToken);
					i++;
				}
			} catch (final InvalidInputException e) {
				LOGGER.warning(ExceptionUtils.getFullStackTrace(e));
			}
		} while (!scanner.atEnd());
	}
	return tokens;
}
 
Example #28
Source File: SpringSecuritySpringTest.java    From camel-cookbook-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void testBadPassword() {
    Map<String, Object> headers = new HashMap<String, Object>();
    headers.put("username", "jakub");
    headers.put("password", "iforgotmypassword");
    try {
        template.sendBodyAndHeaders("direct:in", "foo", headers);
        fail();
    } catch (CamelExecutionException ex) {
        CamelAuthorizationException cax = (CamelAuthorizationException) ex.getCause();
        assertTrue(ExceptionUtils.getRootCause(cax) instanceof BadCredentialsException);
    }
}
 
Example #29
Source File: NettyClientBase.java    From tajo with Apache License 2.0 5 votes vote down vote up
private void doReconnect(final InetSocketAddress address, ChannelFuture future, int retries)
    throws ConnectException {

  for (; ; ) {
    if (maxRetryNum > retries) {
      retries++;

      if(getChannel().eventLoop().isShuttingDown()) {
        LOG.warn("RPC is shutting down");
        return;
      }

      LOG.warn(getErrorMessage(ExceptionUtils.getMessage(future.cause())) + "\nTry to reconnect : " + getKey().addr);
      try {
        Thread.sleep(RpcConstants.DEFAULT_PAUSE);
      } catch (InterruptedException e) {
      }

      this.channelFuture = doConnect(address).awaitUninterruptibly();
      if (this.channelFuture.isDone() && this.channelFuture.isSuccess()) {
        break;
      }
    } else {
      LOG.error("Max retry count has been exceeded. attempts=" + retries + " caused by: " + future.cause());
      throw makeConnectException(address, future);
    }
  }
}
 
Example #30
Source File: NettyClientBase.java    From tajo with Apache License 2.0 5 votes vote down vote up
/**
 * Send an error to callback
 */
private void sendException(RecoverableException e) {
  T callback = requests.remove(e.getSeqId());

  if (callback != null) {
    handleException(e.getSeqId(), callback, ExceptionUtils.getRootCauseMessage(e));
  }
}