下面列出了org.apache.commons.lang3.exception.ExceptionUtils#getRootCauseMessage ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void onComplete(ListenableFuture<Object> future) throws Exception {
if (context.session.isClosed()) {
return;
}
final RpcErrorCode errorCode;
final Object body;
if (future.isCompletedExceptionally()) {
errorCode = RpcErrorCode.SERVER_EXCEPTION;
// 不返回完整信息,意义不大
body = ExceptionUtils.getRootCauseMessage(future.cause());
} else {
errorCode = RpcErrorCode.SUCCESS;
body = future.getNow();
}
// 此时已经在网络线程,直接write,但还是需要流经整个管道
final RpcResponseMessage responseMessage = new RpcResponseMessage(context.requestGuid, context.sync, errorCode, body);
context.session.fireWrite(responseMessage);
}
@GET
@Path("delete")
@Produces(MediaType.APPLICATION_XML)
public Response deleteMatrix() {
String errorMessage = null;
String rootCause = null;
try {
SFLocalContext.getDefault().getMatrixStorage().deleteAllMatrix();
XmlResponse xmlResponse = new XmlResponse();
xmlResponse.setMessage("All matrices was successfully removed");
xmlResponse.setRootCause("");
return Response.
status(Status.OK).
entity(xmlResponse).
build();
} catch (Exception e) {
logger.error(e.getMessage() , e);
errorMessage = e.getMessage();
rootCause = ExceptionUtils.getRootCauseMessage(e);
}
return errorMessage != null ? createBadResponse(errorMessage, rootCause) : null;
}
private SensorParserConfig readFromZookeeper(Context context, String sensorType) throws ParseException {
SensorParserConfig config;
try {
CuratorFramework zkClient = getZookeeperClient(context);
config = readSensorParserConfigFromZookeeper(sensorType, zkClient);
} catch(Exception e) {
throw new ParseException(ExceptionUtils.getRootCauseMessage(e), e);
}
if(config == null) {
throw new ParseException("Unable to read configuration from Zookeeper; sensorType = " + sensorType);
}
return config;
}
/**
* Generates an error message that is shown to the user.
*
* @param e An optional exception that occurred.
* @param input The user input that led to the error condition.
* @return An error message for the user.
*/
private String getErrorMessage(Optional<Throwable> e, String input) {
String message;
if(e.isPresent()) {
// base the error message on the exception
String error = ExceptionUtils.getRootCauseMessage(e.get());
String trace = ExceptionUtils.getStackTrace(e.get());
message = error + System.lineSeparator() + trace;
} else {
// no exception provided; create generic error message
message = "Invalid expression: " + input;
}
return message;
}
private void createResourceGroup(EnvironmentDto environmentDto, String resourceGroupName) {
try {
Optional<Setup> setupOptional = getSetupConnector(environmentDto.getCloudPlatform());
if (setupOptional.isEmpty()) {
LOGGER.debug("No setup defined for platform {}, resource group not created.", environmentDto.getCloudPlatform());
return;
}
EnvironmentPrerequisitesCreateRequest environmentPrerequisitesCreateRequest = new EnvironmentPrerequisitesCreateRequest(
credentialToCloudCredentialConverter.convert(environmentDto.getCredential()),
AzurePrerequisiteCreateRequest.builder()
.withResourceGroupName(resourceGroupName)
.withLocation(environmentDto.getLocation().getName())
.withTags(environmentDto.mergeTags(costTagging))
.build());
setupOptional.get().createEnvironmentPrerequisites(environmentPrerequisitesCreateRequest);
} catch (Exception e) {
throw new CloudConnectorException("Could not create resource group" + ExceptionUtils.getRootCauseMessage(e), e);
}
}
@Override
public ExecutionResult executeScript(String source, RequestContainer request, ResponseContainer response, RequestExecutionContext context) {
ByteArrayOutputStream logStream = new ByteArrayOutputStream();
initGlobalBindings();
Bindings bindings = engine.createBindings();
engine.setContext(new SimpleScriptContext());
//we need to use globalBindings as engnine bindings and the normal bindings as globalBindings, otherwise things like chai dont work
//bc they modify object prototype and this change is not resolved if in global scope
engine.getContext().setBindings(bindings, ScriptContext.GLOBAL_SCOPE);
engine.getContext().setBindings(globalBindings, ScriptContext.ENGINE_SCOPE);
engine.getContext().setErrorWriter(new OutputStreamWriter(logStream));
engine.getContext().setWriter(new OutputStreamWriter(logStream));
var facade = new MilkmanNashornFacade(request, response, context, toaster);
bindings.put("milkman", facade);
bindings.put("mm", facade);
try {
Object eval = engine.eval(source);
return new ExecutionResult(logStream.toString(), Optional.ofNullable(eval));
} catch (Exception e) {
String causeMessage = ExceptionUtils.getRootCauseMessage(e);
toaster.showToast("Failed to execute script: " + causeMessage);
log.error("failed to execute script", e);
}
return new ExecutionResult(logStream.toString(), Optional.empty());
}
public void initGlobalBindings() {
List<String> preloadScripts = ScriptOptionsProvider.options().getPreloadScripts();
int currentHash = preloadScripts.hashCode();
if (preloadScriptCacheHash == currentHash){
return;
}
try {
Bindings bindings = engine.createBindings();
engine.setContext(new SimpleScriptContext());
engine.eval(new InputStreamReader(getClass().getResourceAsStream("/nashorn-polyfill.js")), bindings);
engine.eval(new InputStreamReader(getClass().getResourceAsStream("/jsHashes.js")), bindings);
engine.eval(new InputStreamReader(getClass().getResourceAsStream("/custom-script-setup.js")), bindings);
for (String preloadScriptUrl : preloadScripts) {
URI uri = new URI(preloadScriptUrl);
String path = uri.getPath();
String filename = path.substring(path.lastIndexOf('/') + 1);
String libSrc = IOUtils.toString(uri); //"with (global){" + IOUtils.toString(uri) + "}";
engine.eval(libSrc, bindings);
}
// ((ScriptObjectMirror)bindings).freeze();
this.globalBindings = bindings;
this.preloadScriptCacheHash = currentHash;
return;
} catch (Exception e) {
String causeMessage = ExceptionUtils.getRootCauseMessage(e);
toaster.showToast("Failed to initialize preloader scripts: " + causeMessage);
log.error("failed to execute script", e);
}
}
/**
* Renders the specified HTML code. Removes unsafe HTML constructs.
*
* @param html
* the HTML to render
*
* @return safe HTML
*/
public String render(final String html) {
try {
return formatter.translate(html);
}
catch (IOException e) {
return ExceptionUtils.getRootCauseMessage(e);
}
}
protected String getExceptionCauseMessage(Exception exception) {
for (Throwable throwable : ExceptionUtils.getThrowableList(exception)) {
if (throwable instanceof RemoteAccessException) {
return throwable.toString() +
"\n\nDue to this error, 'web' block cannot connect to the remote 'core' block.\n" +
"First, check the 'core' server log for exceptions to ensure it has started properly.\n" +
"If there are no exceptions in the 'core' log, check that 'cuba.connectionUrlList' property value " +
"contains the valid address of the 'core' server and ends with the web context name of the 'core' block, " +
"e.g. 'cuba.connectionUrlList = http://somehost:8080/app-core'";
} else if (throwable instanceof LocalServiceAccessException) {
return throwable.getMessage();
}
}
return ExceptionUtils.getRootCauseMessage(exception);
}
@ExceptionHandler(RestException.class)
@ResponseBody
ResponseEntity<?> handleControllerException(HttpServletRequest request, Throwable ex) {
HttpStatus status = getStatus(request);
LOG.error("Encountered error: " + ex.getMessage(), ex);
return new ResponseEntity<>(new RestError(status.value(), ex.getMessage(), ExceptionUtils.getRootCauseMessage(ex)), status);
}
/**
* With Ajax calls we need to send a 200 OK response with a status of success: false.
*/
@ExceptionHandler(Exception.class)
public ModelAndView handleException(Exception ex) {
log.error("Caught Exception - returning error response: {}", ex.getMessage());
log.error("Root cause: {}", ExceptionUtils.getRootCauseMessage(ex));
ex.printStackTrace();
Map<String, Object> model = Maps.newHashMap();
Response response = new Response(false, ex.getMessage() + " Root Cause: " + ExceptionUtils.getRootCauseMessage(ex));
model.put("response", response);
return new ModelAndView("error", model);
//return new ResponseEntity<Response>(response, HttpStatus.INTERNAL_SERVER_ERROR);
}
private void deletePrerequisites(EnvironmentDto environmentDto, Environment environment) {
try {
Optional<Setup> setupOptional = getSetupConnector(environmentDto.getCloudPlatform());
if (setupOptional.isEmpty()) {
LOGGER.debug("No setup defined for platform {}, resource group has not been deleted.", environmentDto.getCloudPlatform());
return;
}
setupOptional.get().deleteEnvironmentPrerequisites(environmentDtoToPrerequisiteDeleteRequestConverter.convert(environmentDto));
} catch (Exception e) {
throw new CloudConnectorException("Could not delete resource group" + ExceptionUtils.getRootCauseMessage(e), e);
}
}
private JavaSource parseSource(String aSourceFile) throws MojoExecutionException {
try {
return Util.parseSource(aSourceFile, encoding);
} catch (IOException e) {
throw new MojoExecutionException("Unable to parse source file [" + aSourceFile + "]: "
+ ExceptionUtils.getRootCauseMessage(e), e);
}
}
/**
* Write a report on any meta data missing from components.
*/
private void writeMissingMetaDataReport(File aReportFile, Multimap<String, String> aReportData)
throws MojoExecutionException {
String[] classes = aReportData.keySet().toArray(new String[aReportData.keySet().size()]);
Arrays.sort(classes);
PrintWriter out = null;
FileUtils.mkdir(aReportFile.getParent());
try {
out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(aReportFile), encoding));
if (classes.length > 0) {
for (String clazz : classes) {
out.printf("%s %s%n", MARK_CLASS, clazz);
Collection<String> messages = aReportData.get(clazz);
if (messages.isEmpty()) {
out.printf(" No problems");
} else {
for (String message : messages) {
out.printf(" %s%n", message);
}
}
out.printf("%n");
}
} else {
out.printf("%s%n", MARK_NO_MISSING_META_DATA);
}
} catch (IOException e) {
throw new MojoExecutionException("Unable to write missing meta data report to ["
+ aReportFile + "]" + ExceptionUtils.getRootCauseMessage(e), e);
} finally {
IOUtils.closeQuietly(out);
}
}
/**
* Read the missing meta data report from a previous run.
*/
private void readMissingMetaDataReport(File aReportFile, Multimap<String, String> aReportData)
throws MojoExecutionException {
if (!aReportFile.exists()) {
// Ignore if the file is missing
return;
}
LineIterator i = null;
try {
String clazz = null;
i = IOUtils.lineIterator(new FileInputStream(aReportFile), encoding);
while (i.hasNext()) {
String line = i.next();
// Report say there is no missing meta data
if (line.startsWith(MARK_NO_MISSING_META_DATA)) {
return;
}
// Line containing class name
if (line.startsWith(MARK_CLASS)) {
clazz = line.substring(MARK_CLASS.length()).trim();
} else if (StringUtils.isBlank(line)) {
// Empty line, ignore
} else {
// Line containing a missing meta data instance
if (clazz == null) {
throw new MojoExecutionException("Missing meta data report has invalid format.");
}
aReportData.put(clazz, line.trim());
}
}
} catch (IOException e) {
throw new MojoExecutionException("Unable to read missing meta data report: "
+ ExceptionUtils.getRootCauseMessage(e), e);
} finally {
LineIterator.closeQuietly(i);
}
}
private static String getRootCauseMessage(Throwable e) {
final String msg = ExceptionUtils.getRootCauseMessage(e);
return translateExceptionMsgToBeMoreUserReadableIfPossible(msg);
}
@POST
@Path("upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
@FormDataParam("file") InputStream uploadedInputStream,
@FormDataParam("file") FormDataContentDisposition fileDetail) {
IMatrix uploaded = null;
String errorMessage = null;
String rootCause = null;
Response reqResponse = null;
try {
uploaded = SFLocalContext.getDefault()
.getMatrixStorage()
.addMatrix(uploadedInputStream,
fileDetail.getFileName(), null, "Unknown creator", null, null, null);
XmlMatrixUploadResponse matrixUploadResponse = new XmlMatrixUploadResponse();
matrixUploadResponse.setId(uploaded.getId());
reqResponse = Response.ok(matrixUploadResponse).build();
} catch (Exception e) {
logger.error("Could not store matrice [{}]", (fileDetail != null) ? fileDetail.getFileName() : "null", e);
errorMessage = e.getMessage();
rootCause = ExceptionUtils.getRootCauseMessage(e);
}
if (errorMessage != null) {
XmlResponse xmlResponse = new XmlResponse();
xmlResponse.setMessage(errorMessage);
xmlResponse.setRootCause(rootCause);
return Response.status(Status.BAD_REQUEST)
.entity(xmlResponse).build();
}
return reqResponse;
}
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_XML)
public Response executeAction(
@PathParam("id") long id,
@QueryParam("action") String actionName,
@QueryParam("range") String rangeParam,
@DefaultValue(ServiceName.DEFAULT_ENVIRONMENT) @QueryParam("environment") String environmentParam,
@DefaultValue("ISO-8859-1") @QueryParam("encoding") String fileEncodingParam,
@DefaultValue("3") @QueryParam("aml") int amlParam,
@DefaultValue("false") @QueryParam("continueonfailed") boolean continueOnFailed,
@DefaultValue("false") @QueryParam("autostart") boolean autoStart,
@DefaultValue("true") @QueryParam("autorun") boolean autoRun,
@DefaultValue("true") @QueryParam("ignoreaskforcontinue") boolean ignoreAskForContinue,
@DefaultValue("true") @QueryParam("runnetdumper") boolean runNetDumper,
@DefaultValue("false") @QueryParam("skipoptional") boolean skipOptional,
@QueryParam("tag") List<String> tags,
@DefaultValue("{}") @QueryParam("staticvariables") String staticVariables,
@DefaultValue("") @QueryParam("subfolder") String subFolder,
@DefaultValue("") @QueryParam("language") String language) {
ISFContext context = SFLocalContext.getDefault();
String errorMessage = null;
String rootCause = null;
try {
if ( actionName == null ) {
errorMessage = "action is null";
} else if("start".equals(actionName)) {
IMatrix matrix = context.getMatrixStorage().getMatrixById(id);
if(matrix != null) {
List<Tag> tagsList = null;
if(tags != null && !tags.isEmpty()) {
tagsList = tagNamesToInstances(tags);
}
logger.debug("Before adding matrix {} to queue...", matrix);
language = StringUtils.isNotBlank(language) ? language.trim() : "AML_v" + amlParam; //workaround
SailfishURI languageURI = SailfishURI.parse(language);
if(!SFLocalContext.getDefault().getLanguageManager().containsLanguage(languageURI)) {
throw new EPSCommonException("Invalid language: " + language);
}
long enqueuedID = TestToolsAPI.getInstance().executeMatrix(
matrix, languageURI, rangeParam,
fileEncodingParam, environmentParam,
RESTUtil.getSystemUser(RESTUtil.REST_USER), continueOnFailed, autoStart,
autoRun, ignoreAskForContinue, runNetDumper, skipOptional, tagsList,
getStaticVariablesMap(staticVariables), null, subFolder);
logger.info("Test Script {} was enqueued under {}", matrix, enqueuedID );
XmlTestscriptActionResponse response = new XmlTestscriptActionResponse();
response.setId(enqueuedID);
return Response.status(Status.OK).
entity(response).
build();
} else {
errorMessage = "Matrix with id = [" + id + "] not found";
}
} else if("stop".equals(actionName)) {
if(TestToolsAPI.getInstance().containsScriptRun(id)) {
TestToolsAPI.getInstance().stopScriptRun(id);
return Response.noContent().status(Status.OK).build();
} else {
errorMessage = "Script run with id = [" + id + "] not found";
}
} else {
errorMessage = "unknown action";
}
}
catch ( Exception e ) {
logger.error(e.getMessage() , e);
errorMessage = e.getMessage();
rootCause = ExceptionUtils.getRootCauseMessage(e);
}
return errorMessage != null ? createBadResponse(errorMessage, rootCause) : null;
}
public List<JXNode> selN(String xpath){
List<JXNode> finalRes = new LinkedList<>();
try{
CharStream input = CharStreams.fromString(xpath);
XpathLexer lexer = new XpathLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
XpathParser parser = new XpathParser(tokens);
parser.setErrorHandler(new DoFailOnErrorHandler());
ParseTree tree = parser.main();
XpathProcessor processor = new XpathProcessor(elements);
XValue calRes = processor.visit(tree);
if (calRes.isElements()){
for (Element el:calRes.asElements()){
finalRes.add(JXNode.create(el));
}
return finalRes;
}
if (calRes.isList()){
for (String str:calRes.asList()){
finalRes.add(JXNode.create(str));
}
return finalRes;
}
if (calRes.isString()){
finalRes.add(JXNode.create(calRes.asString()));
return finalRes;
}
if (calRes.isNumber()) {
finalRes.add(JXNode.create(calRes.asDouble()));
return finalRes;
}
if (calRes.isBoolean()){
finalRes.add(JXNode.create(calRes.asBoolean()));
return finalRes;
}
if(calRes.isDate()){
finalRes.add(JXNode.create(calRes.asDate()));
return finalRes;
}
finalRes.add(JXNode.create(calRes.asString()));
} catch (Exception e){
String msg = "Please check the syntax of your xpath expr or commit a ";
throw new XpathSyntaxErrorException(msg+ExceptionUtils.getRootCauseMessage(e),e);
}
return finalRes;
}
/**
* Enhance descriptions in configuration parameters.
*/
private void enhanceConfigurationParameter(JavaSource aAST, Class<?> aClazz, CtClass aCtClazz,
Multimap<String, String> aReportData) throws MojoExecutionException {
// Get the parameter name constants
Map<String, String> parameterNameFields = getParameterConstants(aClazz,
parameterNameConstantPrefixes);
Map<String, String> resourceNameFields = getParameterConstants(aClazz,
externalResourceNameConstantPrefixes);
// Fetch configuration parameters from the @ConfigurationParameter annotations in the
// compiled class. We only need the fields in the class itself. Superclasses should be
// enhanced by themselves.
for (Field field : aClazz.getDeclaredFields()) {
final String pname;
final String type;
final String pdesc;
// Is this a configuration parameter?
if (ConfigurationParameterFactory.isConfigurationParameterField(field)) {
type = "parameter";
// Extract configuration parameter information from the uimaFIT annotation
pname = ConfigurationParameterFactory.createPrimitiveParameter(field).getName();
// Extract JavaDoc for this resource from the source file
pdesc = Util.getParameterDocumentation(aAST, field.getName(),
parameterNameFields.get(pname));
}
// Is this an external resource?
else if (ExternalResourceFactory.isExternalResourceField(field)) {
type = "external resource";
// Extract resource key from the uimaFIT annotation
pname = ExternalResourceFactory.createResourceDependency(field).getKey();
// Extract JavaDoc for this resource from the source file
pdesc = Util.getParameterDocumentation(aAST, field.getName(),
resourceNameFields.get(pname));
} else {
continue;
}
if (pdesc == null) {
String msg = "No description found for " + type + " [" + pname + "]";
getLog().debug(msg);
aReportData.put(aClazz.getName(), msg);
continue;
}
// Update the "description" field of the annotation
try {
CtField ctField = aCtClazz.getField(field.getName());
AnnotationsAttribute annoAttr = (AnnotationsAttribute) ctField.getFieldInfo().getAttribute(
AnnotationsAttribute.visibleTag);
// Locate and update annotation
if (annoAttr != null) {
Annotation[] annotations = annoAttr.getAnnotations();
// Update existing annotation
for (Annotation a : annotations) {
if (a.getTypeName().equals(
org.apache.uima.fit.descriptor.ConfigurationParameter.class.getName())
|| a.getTypeName().equals(
org.apache.uima.fit.descriptor.ExternalResource.class.getName())
|| a.getTypeName().equals("org.uimafit.descriptor.ConfigurationParameter")
|| a.getTypeName().equals("org.uimafit.descriptor.ExternalResource")) {
if (a.getMemberValue("description") == null) {
a.addMemberValue("description", new StringMemberValue(pdesc, aCtClazz
.getClassFile().getConstPool()));
getLog().debug("Enhanced description of " + type + " [" + pname + "]");
// Replace updated annotation
annoAttr.addAnnotation(a);
} else {
// Extract configuration parameter information from the uimaFIT annotation
// We only want to override if the description is not set yet.
getLog().debug("Not overwriting description of " + type + " [" + pname + "] ");
}
}
}
}
// Replace annotations
ctField.getFieldInfo().addAttribute(annoAttr);
} catch (NotFoundException e) {
throw new MojoExecutionException("Field [" + field.getName() + "] not found in byte code: "
+ ExceptionUtils.getRootCauseMessage(e), e);
}
}
}