Example usage for java.lang Throwable getLocalizedMessage

List of usage examples for java.lang Throwable getLocalizedMessage

Introduction

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

Prototype

public String getLocalizedMessage() 

Source Link

Document

Creates a localized description of this throwable.

Usage

From source file:org.gflogger.log4j.Log4jEntry.java

@Override
public GFLogEntry append(Throwable e) {
    if (e != null) {
        try {//from w ww  .ja  v a  2 s .  c o m
            append(e.getClass().getName());
            String message = e.getLocalizedMessage();
            if (message != null) {
                append(": ").append(message);
            }
            append('\n');
            final StackTraceElement[] trace = e.getStackTrace();
            for (int i = 0; i < trace.length; i++) {
                append("\tat ").append(trace[i].getClassName()).append('.').append(trace[i].getMethodName());
                append('(');
                if (trace[i].isNativeMethod()) {
                    append("native");
                } else {
                    final String fileName = trace[i].getFileName();
                    final int lineNumber = trace[i].getLineNumber();
                    if (fileName != null) {
                        append(fileName);
                        if (lineNumber >= 0) {
                            append(':').append(lineNumber);
                        }

                        final Class clazz = loadClass(trace[i].getClassName());
                        if (clazz != null) {
                            append('[').append(getCodeLocation(clazz));
                            final String implVersion = getImplementationVersion(clazz);
                            if (implVersion != null) {
                                append(':').append(implVersion);
                            }
                            append(']');
                        }

                    } else {
                        append("unknown");
                    }
                }
                append(')').append('\n');
            }
        } catch (Throwable t) {
            //
            t.printStackTrace();
        }
    }
    return this;
}

From source file:org.apache.kylin.rest.controller.CubeController.java

private JobInstance buildInternal(String cubeName, long startTime, long endTime, //
        long startOffset, long endOffset, Map<Integer, Long> sourcePartitionOffsetStart,
        Map<Integer, Long> sourcePartitionOffsetEnd, String buildType, boolean force) {
    try {//from w  w  w.  ja  v  a  2  s  . c om
        String submitter = SecurityContextHolder.getContext().getAuthentication().getName();
        CubeInstance cube = jobService.getCubeManager().getCube(cubeName);

        if (cube == null) {
            throw new InternalErrorException("Cannot find cube " + cubeName);
        }
        return jobService.submitJob(cube, startTime, endTime, startOffset, endOffset, //
                sourcePartitionOffsetStart, sourcePartitionOffsetEnd, CubeBuildTypeEnum.valueOf(buildType),
                force, submitter);
    } catch (Throwable e) {
        logger.error(e.getLocalizedMessage(), e);
        throw new InternalErrorException(e.getLocalizedMessage(), e);
    }
}

From source file:export.notes.view.to.excel.ExportAction.java

private void error(final Throwable t) {
    UIJob uijob = new UIJob(Messages.ExportAction_5) {
        public IStatus runInUIThread(IProgressMonitor arg0) {
            // build the error message and include the current stack trace
            MultiStatus status = createMultiStatus(t.getMessage(), t);
            // show error dialog
            ErrorDialog.openError(PlatformUI.getWorkbench().getDisplay().getActiveShell(),
                    Messages.ExportAction_11, t.getLocalizedMessage(), status);

            return Status.OK_STATUS;
        }/*  w  ww .ja v  a2 s. c om*/

        private MultiStatus createMultiStatus(String msg, Throwable t) {

            List<Status> childStatuses = new ArrayList<Status>();
            StackTraceElement[] stackTraces = Thread.currentThread().getStackTrace();

            for (StackTraceElement stackTrace : stackTraces) {
                Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, stackTrace.toString());
                childStatuses.add(status);
            }

            MultiStatus ms = new MultiStatus(Activator.PLUGIN_ID, IStatus.ERROR,
                    childStatuses.toArray(new Status[] {}), t.toString(), t);
            return ms;
        }

    };
    uijob.schedule();
}

From source file:org.rhq.core.pc.inventory.AvailabilityExecutor.java

protected void checkInventory(Resource resource, AvailabilityReport availabilityReport,
        AvailabilityType parentAvailType, boolean isForced, Scan scan) {

    // Only report avail for committed Resources - that's all the Server cares about.
    if (resource.getId() == 0 || resource.getInventoryStatus() != InventoryStatus.COMMITTED) {
        return;/*from w w w  .java2 s . c  om*/
    }

    ResourceContainer resourceContainer = this.inventoryManager.getResourceContainer(resource);
    // Only report avail for synchronized Resources, otherwise the Server will likely know nothing of the Resource.
    if (resourceContainer == null || resourceContainer
            .getSynchronizationState() != ResourceContainer.SynchronizationState.SYNCHRONIZED) {
        return;
    }

    AvailabilityFacet resourceComponent;
    try {
        resourceComponent = resourceContainer.createResourceComponentProxy(AvailabilityFacet.class,
                FacetLockType.NONE, GET_AVAILABILITY_TIMEOUT, true, false);

    } catch (PluginContainerException e) {
        // TODO (ips): Why aren't we logging this as an error?
        if (log.isDebugEnabled()) {
            log.debug("Could not create resource component proxy for " + resource + ".", e);
        }
        return;
    }

    ++scan.numResources;

    // See if this resource is scheduled for an avail check
    boolean checkAvail = false;
    boolean deferToParent = false;
    Long availabilityScheduleTime = resourceContainer.getAvailabilityScheduleTime();
    MeasurementScheduleRequest availScheduleRequest = resourceContainer.getAvailabilitySchedule();

    // if no avail check is scheduled or we're forcing the check, schedule the next check. Note that a forcedCheck
    // is "off-schedule" so we need to push out the next check.  
    if ((null == availabilityScheduleTime) || isForced) {
        // if there is no availability schedule (platform) then just perform the avail check
        // (note, platforms always return UP anyway).
        if (null == availScheduleRequest) {
            checkAvail = true;

        } else {
            // if the schedule is enabled then schedule the next avail check, else just defer to the parent type
            if (availScheduleRequest.isEnabled()) {
                // Schedule the avail check at some time between now and (now + collectionInterval). By
                // doing this random assignment for the first scheduled collection, we'll spread out the actual
                // check times going forward. Do not check it on this pass (unless we're forced)
                int interval = (int) availScheduleRequest.getInterval(); // intervals are short enough for safe cast
                availabilityScheduleTime = scan.startTime + RANDOM.nextInt(interval + 1);
                resourceContainer.setAvailabilityScheduleTime(availabilityScheduleTime);

                ++scan.numScheduledRandomly;

            } else {
                deferToParent = true;
            }
        }
    } else {
        // check avail if this resource scheduled time has been reached
        checkAvail = scan.startTime >= availabilityScheduleTime;

        if (checkAvail) {
            long interval = availScheduleRequest.getInterval(); // intervals are short enough for safe cast
            resourceContainer.setAvailabilityScheduleTime(scan.startTime + interval);
            ++scan.numPushedByInterval;
        }
    }

    // find out what the avail was the last time we checked it. this may be null
    Availability previous = this.inventoryManager.getAvailabilityIfKnown(resource);
    AvailabilityType current = (null == previous) ? null : previous.getAvailabilityType();

    // regardless of whether the avail schedule is met, we still must check avail if isForce is true or if
    // it's a full report and we don't yet have an avail for the resource.
    if (!checkAvail && (isForced || (scan.isFull && null == previous))) {
        checkAvail = true;
    }

    if (checkAvail) {
        if (deferToParent || (AvailabilityType.UP != parentAvailType)) {
            // If the resource's parent is not up, the rules are that the resource and all of the parent's other
            // descendants, must also be of the parent avail type, so there's no need to even ask the resource component
            // for its current availability - its current avail is set to the parent avail type and that's that.
            current = parentAvailType;
            ++scan.numDeferToParent;

        } else {
            current = null;
            try {
                ++scan.numGetAvailabilityCalls;

                // if the component is started, ask what its current availability is as of right now;
                // if it's not started, then assume it's down, and the next time we check,
                // we'll see if it's started and check for real then - otherwise, keep assuming it's
                // down (this is for the case when a plugin component can't start for whatever reason
                // or is just slow to start)
                if (resourceContainer.getResourceComponentState() == ResourceComponentState.STARTED) {
                    current = resourceComponent.getAvailability();
                } else {
                    this.inventoryManager.activateResource(resource, resourceContainer, false);
                    if (resourceContainer.getResourceComponentState() == ResourceComponentState.STARTED) {
                        current = resourceComponent.getAvailability();
                    }
                }
            } catch (Throwable t) {
                ResourceError resourceError = new ResourceError(resource, ResourceErrorType.AVAILABILITY_CHECK,
                        t.getLocalizedMessage(), ThrowableUtil.getStackAsString(t), System.currentTimeMillis());
                this.inventoryManager.sendResourceErrorToServer(resourceError);
                if (log.isDebugEnabled()) {
                    if (t instanceof TimeoutException) {
                        // no need to log the stack trace for timeouts...
                        log.debug("Failed to collect availability on " + resource + " (call timed out)");
                    } else {
                        log.debug("Failed to collect availability on " + resource, t);
                    }
                }
            }
            if (current == null) {
                current = AvailabilityType.DOWN;
            }
        }
    }

    // Add the availability to the report if it changed from its previous state or if this is a full report.
    // Update the resource container only if the avail has changed.
    boolean availChanged = (previous == null) || (previous.getAvailabilityType() != current);

    if (availChanged || scan.isFull) {
        Availability availability = null;

        if (availChanged) {
            ++scan.numAvailabilityChanges;

            availability = this.inventoryManager.updateAvailability(resource, current);

            // if the resource avail changed to UP then we must perform avail checks for all
            // children, to ensure their avails are up to date. Note that if it changed to NOT UP
            // then the children will just get the parent avail type and there is no avail check anyway.
            if (!isForced && (AvailabilityType.UP == current)) {
                isForced = true;
            }
        } else {
            // avoid the overhead of updating the resource container, the avail type did not change
            availability = new Availability(resource, current);
        }

        // update the report
        availabilityReport.addAvailability(availability);
    }

    for (Resource child : resource.getChildResources()) {
        checkInventory(child, availabilityReport, current, isForced, scan);
    }

    return;
}

From source file:com.googlecode.bpmn_simulator.gui.BPMNSimulatorFrame.java

private void showException(final Throwable throwable) {
    LOG.catching(throwable);/*from  w ww . jav  a  2s .  co m*/
    final ErrorInfo errorInfo = new ErrorInfo(Messages.getString("error"), throwable.getLocalizedMessage(),
            null, null, throwable, null, null);
    JXErrorPane.showDialog(this, errorInfo);
}

From source file:com.jaspersoft.android.jaspermobile.network.RequestExceptionHandler.java

@Nullable
public String extractMessage(@Nullable Throwable exception) {
    if (exception == null) {
        throw new IllegalArgumentException("Exception should not be null");
    }//from   w  ww.  j  a  va2 s.  co m

    if (exception instanceof ServiceException) {
        ServiceException serviceException = ((ServiceException) exception);
        return adaptServiceMessage(serviceException);
    }
    if (exception.getCause() instanceof ServiceException) {
        ServiceException serviceException = (ServiceException) exception.getCause();
        return adaptServiceMessage(serviceException);
    }

    return exception.getLocalizedMessage();
}

From source file:org.apache.flex.compiler.internal.fxg.logging.SystemLogger.java

@Override
public void log(int level, Object message, Throwable t, String location, int line, int column) {
    if (level < getLevel())
        return;//from   w w w .  ja  v  a 2s  .c om

    PrintStream ps = level > INFO ? System.err : System.out;

    try {
        StringBuilder sb = new StringBuilder();

        if (location != null) {
            sb.append(location).append(":");
        }

        if (line > 0) {
            sb.append(" Line ").append(line);

            if (column > 0) {
                sb.append(", Column ").append(column);
            }
        }

        if (message != null) {
            sb.append(": ").append(message);
        }

        if (t != null) {
            sb.append(": ").append(t.getLocalizedMessage());
        }

        ps.println(sb.toString());
    } catch (Throwable ex) {
    } finally {
        IOUtils.closeQuietly(ps);
    }
}

From source file:it.geosolutions.geobatch.task.TaskExecutor.java

public Queue<FileSystemEvent> execute(Queue<FileSystemEvent> events) throws ActionException {

    listenerForwarder.started();//  w  ww  .j ava  2  s  .  co  m

    if (configuration == null) {
        final ActionException e = new ActionException(this, "DataFlowConfig is null.");
        listenerForwarder.failed(e);
        throw e;
    }

    if (events == null || events.size() == 0) {
        final ActionException e = new ActionException(this, "Empty or null incoming events list");
        listenerForwarder.failed(e);
        throw e;
    }

    Queue<FileSystemEvent> outEvents = new LinkedList<FileSystemEvent>();

    while (events.size() > 0) {
        // get the first event
        final FileSystemEvent event = events.remove();
        final File inputFile = event.getSource();
        if (inputFile == null) {
            final ActionException e = new ActionException(this, "Input File is null");
            listenerForwarder.failed(e);
            throw e;
        }
        if (!inputFile.exists()) {
            final ActionException e = new ActionException(this, "Input File doesn't exist");
            listenerForwarder.failed(e);
            throw e;
        }
        final String inputFilePath = inputFile.getAbsolutePath();

        final String inputFileExt = FilenameUtils.getExtension(inputFilePath);

        // Getting XSL file definition
        final String xslPath = configuration.getXsl();
        final boolean useDefaultScript;

        String defaultScriptPath = configuration.getDefaultScript();
        if (inputFileExt.equalsIgnoreCase("xml")) {
            if (LOGGER.isInfoEnabled())
                LOGGER.info("Using input file as script: " + inputFilePath);
            defaultScriptPath = inputFilePath;
            useDefaultScript = false;
        } else {
            if (LOGGER.isInfoEnabled())
                LOGGER.info("Using default script: " + configuration.getDefaultScript());
            useDefaultScript = true;
        }

        final String outputName = configuration.getOutputName();

        File xslFile = null;
        InputStream is = null;

        try {

            if (xslPath != null && xslPath.trim().length() > 0) {
                final String path = Path.findLocation(xslPath, getConfigDir().getAbsolutePath());
                if (path == null) {
                    final ActionException e = new ActionException(this, "XSL file not found: " + path);
                    listenerForwarder.failed(e);
                    throw e;
                }
                xslFile = new File(path);
            }
            if (!xslFile.exists()) {
                final ActionException e = new ActionException(this, "XSL file not found: " + xslPath);
                listenerForwarder.failed(e);
                throw e;
            }

            File xmlFile = null;
            String outputFile = null;
            if (useDefaultScript) {
                if (defaultScriptPath != null && defaultScriptPath.trim().length() > 0) {
                    final String path = Path.findLocation(xslPath, getConfigDir().getAbsolutePath());
                    if (path == null) {
                        final ActionException e = new ActionException(this, "XSL file not found: " + path);
                        listenerForwarder.failed(e);
                        throw e;
                    }
                    xmlFile = new File(path);

                    final File outXmlFile = File.createTempFile("script", ".xml", getTempDir());
                    //                  outXmlFile.deleteOnExit();
                    outputFile = setScriptArguments(xmlFile.getAbsolutePath(), inputFilePath, outputName,
                            outXmlFile);
                    xmlFile = outXmlFile;
                }

            } else {
                xmlFile = inputFile;
            }
            if (!xmlFile.exists()) {
                final ActionException e = new ActionException(this, "XML file not found: " + xmlFile);
                listenerForwarder.failed(e);
                throw e;
            }

            // Setup an XML source from the input XML file
            final Source xmlSource = new StreamSource(xmlFile);

            is = new FileInputStream(xslFile);

            // XML parsing to setup a command line
            final String argument = buildArgument(xmlSource, is);
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Arguments: " + argument);
            }

            final Project project = new Project();
            project.init();

            final ExecTask execTask = new ExecTask();
            execTask.setProject(project);

            // Setting environment variables coming from the configuration
            // as an instance: PATH, LD_LIBRARY_PATH and similar
            Map<String, String> variables = configuration.getVariables();
            if (variables != null && !variables.isEmpty()) {
                for (String key : variables.keySet()) {
                    Variable var = new Variable();
                    var.setKey(key);
                    final String value = variables.get(key);
                    if (value != null) {
                        var.setValue(variables.get(key));
                        execTask.addEnv(var);
                    }
                }
            }

            // Setting executable
            execTask.setExecutable(configuration.getExecutable());

            // Setting Error logging
            final String errorFileName = configuration.getErrorFile();
            if (errorFileName != null) {
                File errorFile = new File(errorFileName);
                if (!errorFile.exists()) {
                    errorFile = Path.findLocation(errorFileName, getTempDir());
                    if (errorFile != null && !errorFile.exists()) {
                        try {
                            errorFile.createNewFile();
                        } catch (Throwable t) {
                            final ActionException e = new ActionException(this, t.getLocalizedMessage(), t);
                            listenerForwarder.failed(e);
                            throw e;
                        }
                    }
                }
                if (errorFile.exists()) {
                    if (LOGGER.isDebugEnabled())
                        LOGGER.debug("Using error file: " + errorFile);
                    execTask.setLogError(true);
                    execTask.setAppend(true);
                    execTask.setError(errorFile);
                    execTask.setFailonerror(true);
                }
            }

            // Setting the timeout
            Long timeOut = configuration.getTimeOut();
            if (timeOut != null) {
                execTask.setTimeout(timeOut);
            }

            // Setting command line argument
            execTask.createArg().setLine(argument);

            File output = null;
            if (configuration.getOutput() != null) {
                output = new File(configuration.getOutput());
                if (output.exists() && output.isDirectory()) {
                    final File outXmlFile = File.createTempFile("script", ".xml", getTempDir()); // TODO CHECKME: is this var used?
                    //                  outXmlFile.deleteOnExit();
                    String destFile = getScriptArguments(xmlFile.getAbsolutePath(), "srcfile");
                    if (output.isAbsolute()) {
                        //                            String basename = 
                        output = new File(output, FilenameUtils.getBaseName(destFile) + configuration
                                .getOutputName().substring(configuration.getOutputName().indexOf(".")));
                    } else {
                        output = Path.findLocation(configuration.getOutput(), inputFile.getParentFile());
                        output = new File(output, FilenameUtils.getBaseName(inputFile.getName()) + configuration
                                .getOutputName().substring(configuration.getOutputName().indexOf(".")));
                    }
                }
                execTask.setOutput(output);
            }

            // Executing
            execTask.execute();

            File outFile = (outputFile != null ? new File(outputFile) : null);

            if (configuration.getOutput() != null) {
                if (new File(configuration.getOutput()).isAbsolute()) {
                    if (output.exists() && output.isFile()) {
                        // outFile = output;
                        final File outXmlFile = File.createTempFile("script", ".xml", getTempDir());
                        //                     outXmlFile.deleteOnExit();
                        outputFile = setScriptArguments(xmlFile.getAbsolutePath(), output.getAbsolutePath(),
                                outputName, outXmlFile);
                        outFile = new File(configuration.getOutput(),
                                FilenameUtils.getBaseName(outputFile) + ".xml");
                        FileUtils.copyFile(outXmlFile, outFile);
                    }
                } else {
                    if (outFile == null)
                        outFile = inputFile;
                }
            } else if (outFile == null) {
                outFile = inputFile;
            }

            outEvents.add(new FileSystemEvent(outFile, FileSystemEventType.FILE_ADDED));
        } catch (Exception e) {
            listenerForwarder.failed(e);
            throw new ActionException(this, e.getMessage(), e);
        } finally {
            if (is != null)
                org.apache.commons.io.IOUtils.closeQuietly(is);
        }
    }

    listenerForwarder.completed();
    return outEvents;
}

From source file:org.geotools.gce.imagemosaic.catalog.GTDataStoreGranuleCatalog.java

public void dispose() {
    final Lock l = rwLock.writeLock();
    try {//  w ww. j  a va  2s .  c  o  m
        l.lock();
        try {
            if (tileIndexStore != null) {
                tileIndexStore.dispose();
            }
            if (multiScaleROIProvider != null) {
                multiScaleROIProvider.dispose();
            }
        } catch (Throwable e) {
            if (LOGGER.isLoggable(Level.FINE)) {
                LOGGER.log(Level.FINE, e.getLocalizedMessage(), e);
            }
        } finally {
            tileIndexStore = null;
            multiScaleROIProvider = null;
        }

    } finally {
        l.unlock();
    }
}