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

The following examples show how to use org.apache.commons.lang.exception.ExceptionUtils. These examples are extracted from open source projects. 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
@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 2
Source Project: hbase-indexer   Source File: IndexerProcessRegistryImpl.java    License: 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 3
Source Project: opensoc-streaming   Source File: ErrorGenerator.java    License: 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 4
@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 5
Source Project: sinavi-jfw   Source File: ExceptionMessageExchanger.java    License: 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 6
Source Project: garmadon   Source File: HiveClient.java    License: 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 7
Source Project: camel-cookbook-examples   Source File: SignaturesTest.java    License: 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 8
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 9
Source Project: openbd-core   Source File: RedisCacheImpl.java    License: 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 10
@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 11
@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 12
Source Project: canal   Source File: LogEventConvert.java    License: 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 13
Source Project: api-mining   Source File: JavaTokenizer.java    License: 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 14
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 15
@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 16
@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 17
@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 18
@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 19
Source Project: Qualitis   Source File: OuterExecutionServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public GeneralResponse<?> generalExecution(GeneralExecutionRequest request) throws UnExpectedRequestException {
    // Generator application information
    GeneralExecutionRequest.checkRequest(request);
    Date date = new Date();
    Application newApplication = generateApplicationInfo(request.getCreateUser(), request.getExecutionUser(), date);

    try {
        if (request.getProjectId() != null) {
            ProjectExecutionRequest projectExecutionRequest = new ProjectExecutionRequest();
            BeanUtils.copyProperties(request, projectExecutionRequest);
            return projectExecution(projectExecutionRequest, newApplication, date);
        } else if (request.getRuleList() != null && !request.getRuleList().isEmpty()) {
            RuleListExecutionRequest ruleListExecutionRequest = new RuleListExecutionRequest();
            BeanUtils.copyProperties(request, ruleListExecutionRequest);
            return ruleListExecution(ruleListExecutionRequest, newApplication, date);
        } else if (request.getGroupId() != null) {
            GroupExecutionRequest groupExecutionRequest = new GroupExecutionRequest();
            BeanUtils.copyProperties(request, groupExecutionRequest);
            return groupExecution(groupExecutionRequest, newApplication, date);
        } else if (request.getCluster() != null) {
            DataSourceExecutionRequest dataSourceExecutionRequest = new DataSourceExecutionRequest();
            BeanUtils.copyProperties(request, dataSourceExecutionRequest);
            return dataSourceExecution(dataSourceExecutionRequest, newApplication, date);
        } else {
            throw new UnExpectedRequestException("{&CAN_NOT_RESOLVE_THE_REQUEST}, request: " + request);
        }
    } catch (UnExpectedRequestException e) {
        newApplication.setStatus(ApplicationStatusEnum.ARGUMENT_NOT_CORRECT.getCode());
        String exceptionMessage = localeParser.replacePlaceHolderByLocale(ExceptionUtils.getStackTrace(e), httpRequest.getHeader("Content-Language"));
        newApplication.setExceptionMessage(exceptionMessage);
        newApplication.setFinishTime(ExecutionManagerImpl.PRINT_TIME_FORMAT.format(new Date()));
        applicationDao.saveApplication(newApplication);
        LOGGER.info("Succeed to set application status to [{}], application_id: {}", newApplication.getStatus(), newApplication.getId());
        throw new UnExpectedRequestException(e.getMessage());
    }
}
 
Example 20
public static List<MethodDeclaration> getMethods(final File file, final ProjectTypeInformation pti)
		throws IOException {
	try {
		final JavaASTExtractor ex = new JavaASTExtractor(false);
		final MethodVisitor mv = new MethodVisitor(pti);
		final CompilationUnit cu = ex.getAST(file);
		cu.accept(mv);
		return mv.allMethods;
	} catch (Exception e) {
		System.err.println(ExceptionUtils.getFullStackTrace(e));
	}
	return new ArrayList<>();
}
 
Example 21
/**
 * Verify a specific dataset by following below steps
 *    1) Retrieve a tier-to-count mapping
 *    2) Read count from {@link CompactionAuditCountVerifier#gobblinTier}
 *    3) Read count from all other {@link CompactionAuditCountVerifier#referenceTiers}
 *    4) Compare count retrieved from steps 2) and 3), if any of (gobblin/refenence) >= threshold, return true, else return false
 * @param dataset Dataset needs to be verified
 * @return If verification is succeeded
 */
public Result verify (FileSystemDataset dataset) {
  if (!enabled) {
    return new Result(true, "");
  }
  if (auditCountClient == null) {
    log.debug("No audit count client specified, skipped");
    return new Result(true, "");
  }

  CompactionPathParser.CompactionParserResult result = new CompactionPathParser(state).parse(dataset);
  ZonedDateTime startTime = ZonedDateTime.ofInstant(Instant.ofEpochMilli(result.getTime().getMillis()), zone);
  ZonedDateTime endTime = TimeIterator.inc(startTime, granularity, 1);
  String datasetName = result.getDatasetName();
  try {
    Map<String, Long> countsByTier = auditCountClient.fetch(datasetName,
        startTime.toInstant().toEpochMilli(), endTime.toInstant().toEpochMilli());
    for (String tier: referenceTiers) {
      Result rst = passed (datasetName, countsByTier, tier);
      if (rst.isSuccessful()) {
        return new Result(true, "");
      }
    }
  } catch (IOException e) {
    return new Result(false, ExceptionUtils.getFullStackTrace(e));
  }

  return new Result(false, String.format("%s data is not complete between %s and %s", datasetName, startTime, endTime));
}
 
Example 22
Source Project: binlake   Source File: MySQLConnector.java    License: Apache License 2.0 5 votes vote down vote up
public void disconnect() throws IOException {
    if (connected.compareAndSet(true, false)) {
        try {
            if (channel != null) {
                channel.close();
            }

            logger.info("disConnect MysqlConnection to " + address);
        } catch (Exception e) {
            throw new IOException("disconnect " + this.address + " failure:" + ExceptionUtils.getStackTrace(e));
        }
    } else {
        logger.info("the channel " + address + " is not connected");
    }
}
 
Example 23
Source Project: youkefu   Source File: ReportDesignController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 组件设计
 * 
 * @param map
 * @param request
 * @param id
 * @return
 * @throws Exception
 */
@RequestMapping("/modeldesign")
@Menu(type = "report", subtype = "reportdesign")
public ModelAndView modeldesign(ModelMap map, HttpServletRequest request, @Valid String id, @Valid String tabid , HashMap<String,String> semap)
		throws Exception {
	List<SysDic> tpDicList = UKeFuDic.getInstance().getDic(UKDataContext.UKEFU_SYSTEM_DIC);
	for (SysDic sysDic : tpDicList) {
		 if (sysDic.getCode().equals("report")) {
			map.addAttribute("reportList",
					templateRes.findByTemplettypeAndOrgi(sysDic.getId(), super.getOrgi(request)));
		 }
	}
	
	ReportModel model = this.getModel(id, super.getOrgi(request));
	map.addAttribute("reportModel", model);
	map.addAttribute("element", model);
	if (model != null && !StringUtils.isBlank(model.getPublishedcubeid())) {
		PublishedCube cube = publishedCubeRepository.findOne(model.getPublishedcubeid());
		map.addAttribute("cube", cube);
		if (canGetReportData(model, cube.getCube())) {
			ReportData reportData = null ;
			try {
				reportData = reportCubeService.getReportData(model, cube.getCube(), request, true,semap) ;
				map.addAttribute("reportData",reportData);
			}catch(Exception ex) {
				map.addAttribute("msg",(ExceptionUtils.getMessage(ex).replaceAll("\r\n","") + ExceptionUtils.getRootCauseMessage(ex)).replaceAll("\"", "'"));
			}
		}
		map.addAttribute("eltemplet", templateRes.findByIdAndOrgi(model.getTempletid(), super.getOrgi(request)));
	} 
	map.addAttribute("organList", organRepository.findByOrgi(super.getOrgi(request)));
	map.addAttribute("tabid", tabid);
	return request(super.createRequestPageTempletResponse("/apps/business/report/design/modeldesign"));
}
 
Example 24
Source Project: youkefu   Source File: Fetcher.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 构建任务信息
 * @param job
 */
public Fetcher(JobDetail job) throws Exception{
	this.job = job;
	try {
		if(job!=null && job.getTasktype()!=null){
			resource = Resource.getResource(job);
		}
		/**
		 * 初始化资源
		 */
		
		if(resource!=null){
			resource.begin();
		}
		this.job.setLastindex(job.getStartindex()) ;
		this.pages = new AtomicInteger((int)job.getReport().getPages()); // total pages fetched
		processpages = this.pages.intValue() ;
		job.getReport().setDataid(this.job.getId());
	}catch (Exception e1) {
		String msg = "TaskID:"+job.getId() + " TaskName:"+job.getName()+" TaskType:"+job.getTasktype()+" Date:"+new Date()+" Exception:"+e1.getMessage() ;
		job.setExceptionMsg(ExceptionUtils.getMessage(e1));
		if(StringUtils.isBlank(job.getMemo())) {
			job.setMemo(msg);
		}
		/**
		 * 设置错误代码
		 */
		e1.printStackTrace();
		throw new Exception(msg , e1);
	}
}
 
Example 25
Source Project: tez   Source File: VertexImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public VertexState transition(VertexImpl vertex, VertexEvent event) {
  VertexEventRootInputInitialized liInitEvent = (VertexEventRootInputInitialized) event;
  VertexState state = vertex.getState();
  if (state == VertexState.INITIALIZING) {
    try {
      vertex.vertexManager.onRootVertexInitialized(liInitEvent.getInputName(), vertex
          .getAdditionalInputs().get(liInitEvent.getInputName()).getIODescriptor(),
          liInitEvent.getEvents());
    } catch (AMUserCodeException e) {
        String msg = "Exception in " + e.getSource() + ", vertex:" + vertex.getLogIdentifier();
        LOG.error(msg, e);
        vertex.finished(VertexState.FAILED,
            VertexTerminationCause.AM_USERCODE_FAILURE, msg
            + "," + ExceptionUtils.getStackTrace(e.getCause()));
        return VertexState.FAILED;
    }
  }

  vertex.numInitializedInputs++;
  if (vertex.numInitializedInputs == vertex.inputsWithInitializers.size()) {
    // All inputs initialized, shutdown the initializer.
    vertex.rootInputInitializerManager.shutdown();
    vertex.rootInputInitializerManager = null;
  }
  
  // the return of these events from the VM will complete initialization and move into 
  // INITED state if possible via InputDataInformationTransition

  return vertex.getState();
}
 
Example 26
Source Project: charging_pile_cloud   Source File: AuthSign.java    License: MIT License 5 votes vote down vote up
/**校验token
 *
 * @param token
 * @return
 */
public  static  boolean verify(String token) {
    try {
        Algorithm algorithm= Algorithm.HMAC256(SECRET);
        JWTVerifier verifier=JWT.require(algorithm).build();
        DecodedJWT jwt=verifier.verify(token);
        return true;
    } catch (Exception e) {
        log.info("token校验失败:"+ExceptionUtils.getStackTrace(e));
        return false;
    }

}
 
Example 27
Source Project: tassal   Source File: TokenCounter.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * @param args
 * @throws IOException
 * @throws ClassNotFoundException
 * @throws IllegalAccessException
 * @throws InstantiationException
 */
public static void main(final String[] args) throws IOException,
		InstantiationException, IllegalAccessException,
		ClassNotFoundException {
	if (args.length != 2) {
		System.err.println("Usage <codeDir> <TokenizerClass>");
		return;
	}

	long tokenCount = 0;

	final ITokenizer tokenizer = TokenizerUtils.tokenizerForClass(args[1]);

	for (final File fi : FileUtils.listFiles(new File(args[0]),
			tokenizer.getFileFilter(), DirectoryFileFilter.DIRECTORY)) {
		try {
			final char[] code = FileUtils.readFileToString(fi)
					.toCharArray();
			tokenCount += tokenizer.tokenListFromCode(code).size() - 2; // Remove
																		// sentence
																		// start/end
		} catch (final IOException e) {
			LOGGER.warning(ExceptionUtils.getFullStackTrace(e));
		}
	}

	System.out.println("Tokens: " + tokenCount);
}
 
Example 28
Source Project: charging_pile_cloud   Source File: AuthSign.java    License: MIT License 5 votes vote down vote up
/**
 * 获取用户信息
 */
public  static JSONObject  getUserObject(String token) {
    try {
        Algorithm algorithm= Algorithm.HMAC256(SECRET);
        JWTVerifier verifier=JWT.require(algorithm).build();
        DecodedJWT jwt=verifier.verify(token);
        return JSONObject.parseObject(jwt.getClaim(OBJECT).asString());
    } catch (Exception e) {
        log.info("获取用户id错误:%s", ExceptionUtils.getStackTrace(e));
    }
    return null;
}
 
Example 29
Source Project: rice   Source File: RoleServiceImpl.java    License: Educational Community License v2.0 5 votes vote down vote up
protected void logPrincipalHasRoleCheck(String principalId, List<String> roleIds,
        Map<String, String> roleQualifiers) {
    StringBuilder sb = new StringBuilder();
    sb.append('\n');
    sb.append("Has Role     : ").append(roleIds).append('\n');
    if (roleIds != null) {
        for (String roleId : roleIds) {
            Role role = getRole(roleId);
            if (role != null) {
                sb.append("        Name : ").append(role.getNamespaceCode()).append('/').append(role.getName());
                sb.append(" (").append(roleId).append(')');
                sb.append('\n');
            }
        }
    }
    sb.append("   Principal : ").append(principalId);
    if (principalId != null) {
        Principal principal = KimApiServiceLocator.getIdentityService().getPrincipal(principalId);
        if (principal != null) {
            sb.append(" (").append(principal.getPrincipalName()).append(')');
        }
    }
    sb.append('\n');
    sb.append("     Details :\n");
    if (roleQualifiers != null) {
        sb.append(roleQualifiers);
    } else {
        sb.append("               [null]\n");
    }
    if (LOG.isTraceEnabled()) {
        LOG.trace(sb.append(ExceptionUtils.getStackTrace(new Throwable())));
    } else {
        LOG.debug(sb.toString());
    }
}
 
Example 30
Source Project: canal-1.1.3   Source File: SessionHandler.java    License: Apache License 2.0 5 votes vote down vote up
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
    logger.error("something goes wrong with channel:{}, exception={}",
        ctx.getChannel(),
        ExceptionUtils.getStackTrace(e.getCause()));

    ctx.getChannel().close();
}