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.bedework.util.http.BasicHttpClient.java

/** Send a request to the server
 *
 * @param methodName the method, GET, PUT etc
 * @param url the url//from ww w.j  ava2  s  .c  o  m
 * @param hdrs may be null
 * @param contentType
 * @param contentLen
 * @param content
 * @return int    status code
 * @throws HttpException
 */
public int sendRequest(final String methodName, final String url, final List<Header> hdrs,
        final String contentType, final int contentLen, final byte[] content) throws HttpException {
    int sz = 0;
    if (content != null) {
        sz = content.length;
    }

    if (debug()) {
        debug("About to send request: method=" + methodName + " url=" + url + " contentLen=" + contentLen
                + " content.length=" + sz + " contentType=" + contentType);
    }

    try {
        URI u = new URI(url);

        if (!hostSpecified && (u.getHost() == null)) {
            if ((baseURI == null) && (baseURIValue != null)) {
                baseURI = new URI(baseURIValue);
            }

            if (baseURI == null) {
                throw new HttpException("No base URI specified for non-absolute URI " + url);
            }

            if (baseURI.getHost() == null) {
                throw new HttpException("Base URI must be absolute: " + baseURI);
            }

            u = baseURI.resolve(u);
        }

        if (debug()) {
            debug("      url resolves to " + u);
        }

        method = findMethod(methodName, u);

        if (credentials != null) {
            getCredentialsProvider().setCredentials(new AuthScope(u.getHost(), u.getPort()), credentials);
        }

        if (!Util.isEmpty(hdrs)) {
            for (final Header hdr : hdrs) {
                method.addHeader(hdr);
            }
        }

        if (method instanceof HttpEntityEnclosingRequestBase) {
            if (content != null) {
                if (contentType == null) {
                    setContent(content, "text/xml");
                } else {
                    setContent(content, contentType);
                }
            }
        }

        response = execute(method);
    } catch (final HttpException he) {
        throw he;
    } catch (final Throwable t) {
        throw new HttpException(t.getLocalizedMessage(), t);
    }
    status = response.getStatusLine().getStatusCode();

    return status;
}

From source file:org.opencms.workplace.tools.modules.CmsCloneModuleThread.java

/**
 * @see java.lang.Thread#run()// w w w  .  j ava 2 s .  c o m
 */
@Override
public void run() {

    CmsModule sourceModule = OpenCms.getModuleManager().getModule(m_cloneInfo.getSourceModuleName());

    // clone the module object
    CmsModule targetModule = (CmsModule) sourceModule.clone();
    targetModule.setName(m_cloneInfo.getName());
    targetModule.setNiceName(m_cloneInfo.getNiceName());
    targetModule.setDescription(m_cloneInfo.getDescription());
    targetModule.setAuthorEmail(m_cloneInfo.getAuthorEmail());
    targetModule.setAuthorName(m_cloneInfo.getAuthorName());
    targetModule.setGroup(m_cloneInfo.getGroup());
    targetModule.setActionClass(m_cloneInfo.getActionClass());

    CmsObject cms = getCms();
    CmsProject currentProject = cms.getRequestContext().getCurrentProject();
    try {
        CmsProject workProject = cms.createProject("Clone_module_work_project", "Clone modulee work project",
                OpenCms.getDefaultUsers().getGroupAdministrators(),
                OpenCms.getDefaultUsers().getGroupAdministrators(), CmsProject.PROJECT_TYPE_TEMPORARY);
        cms.getRequestContext().setCurrentProject(workProject);

        // store the module paths
        String sourceModulePath = CmsWorkplace.VFS_PATH_MODULES + sourceModule.getName() + "/";
        String targetModulePath = CmsWorkplace.VFS_PATH_MODULES + targetModule.getName() + "/";

        // store the package name as path part
        String sourcePathPart = sourceModule.getName().replaceAll("\\.", "/");
        String targetPathPart = targetModule.getName().replaceAll("\\.", "/");

        // store the classes folder paths
        String sourceClassesPath = targetModulePath + PATH_CLASSES + sourcePathPart + "/";
        String targetClassesPath = targetModulePath + PATH_CLASSES + targetPathPart + "/";

        // copy the resources
        cms.copyResource(sourceModulePath, targetModulePath);

        // check if we have to create the classes folder
        if (cms.existsResource(sourceClassesPath)) {
            // in the source module a classes folder was defined,
            // now create all sub-folders for the package structure in the new module folder
            createTargetClassesFolder(targetModule, sourceClassesPath, targetModulePath + PATH_CLASSES);
            // delete the origin classes folder
            deleteSourceClassesFolder(targetModulePath, sourcePathPart, targetPathPart);
        }

        // TODO: clone module dependencies

        // adjust the export points
        cloneExportPoints(sourceModule, targetModule, sourcePathPart, targetPathPart);

        // adjust the resource type names and IDs
        Map<String, String> descKeys = new HashMap<String, String>();
        Map<I_CmsResourceType, I_CmsResourceType> resTypeMap = cloneResourceTypes(sourceModule, targetModule,
                sourcePathPart, targetPathPart, descKeys);

        // adjust the explorer type names and store referred icons and message keys
        Map<String, String> iconPaths = new HashMap<String, String>();
        cloneExplorerTypes(targetModule, iconPaths, descKeys);

        // rename the icon file names
        cloneExplorerTypeIcons(iconPaths);

        // adjust the module resources
        adjustModuleResources(sourceModule, targetModule, sourcePathPart, targetPathPart, iconPaths);

        // search and replace the localization keys
        if (getCms().existsResource(targetClassesPath)) {
            List<CmsResource> props = cms.readResources(targetClassesPath, CmsResourceFilter.DEFAULT_FILES);
            replacesMessages(descKeys, props);
        }

        int type = OpenCms.getResourceManager().getResourceType(CmsVfsBundleManager.TYPE_XML_BUNDLE)
                .getTypeId();
        CmsResourceFilter filter = CmsResourceFilter.requireType(type);
        List<CmsResource> resources = cms.readResources(targetModulePath, filter);
        replacesMessages(descKeys, resources);
        renameXmlVfsBundles(resources, targetModule, sourceModule.getName());

        List<CmsResource> allModuleResources = cms.readResources(targetModulePath, CmsResourceFilter.ALL);
        replacePath(sourceModulePath, targetModulePath, allModuleResources);

        // search and replace paths
        replaceModuleName();

        // replace formatter paths
        if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(m_cloneInfo.getFormatterTargetModule())
                && !targetModule.getResourceTypes().isEmpty()) {
            replaceFormatterPaths(targetModule);
        }

        adjustConfigs(targetModule, resTypeMap);

        // now unlock and publish the project
        getReport().println(Messages.get().container(Messages.RPT_PUBLISH_PROJECT_BEGIN_0),
                I_CmsReport.FORMAT_HEADLINE);
        cms.unlockProject(workProject.getUuid());
        OpenCms.getPublishManager().publishProject(cms, getReport());
        OpenCms.getPublishManager().waitWhileRunning();

        getReport().println(Messages.get().container(Messages.RPT_PUBLISH_PROJECT_END_0),
                I_CmsReport.FORMAT_HEADLINE);

        //  add the imported module to the module manager
        OpenCms.getModuleManager().addModule(cms, targetModule);

        // reinitialize the resource manager with additional module resource types if necessary
        if (targetModule.getResourceTypes() != Collections.EMPTY_LIST) {
            OpenCms.getResourceManager().initialize(cms);
        }
        // reinitialize the workplace manager with additional module explorer types if necessary
        if (targetModule.getExplorerTypes() != Collections.EMPTY_LIST) {
            OpenCms.getWorkplaceManager().addExplorerTypeSettings(targetModule);
        }

        // re-initialize the workplace
        OpenCms.getWorkplaceManager().initialize(cms);
        // fire "clear caches" event to reload all cached resource bundles
        OpenCms.fireCmsEvent(I_CmsEventListener.EVENT_CLEAR_CACHES, new HashMap<String, Object>());

        // following changes will not be published right now, switch back to previous project
        cms.getRequestContext().setCurrentProject(currentProject);

        // change resource types and schema locations
        if (isTrue(m_cloneInfo.getChangeResourceTypes())) {
            changeResourceTypes(resTypeMap);
        }
        // adjust container pages
        CmsObject cloneCms = OpenCms.initCmsObject(cms);
        if (isTrue(m_cloneInfo.getApplyChangesEverywhere())) {
            cloneCms.getRequestContext().setSiteRoot("/");
        }

        if (m_cloneInfo.isRewriteContainerPages()) {
            CmsResourceFilter f = CmsResourceFilter
                    .requireType(CmsResourceTypeXmlContainerPage.getContainerPageTypeId());
            List<CmsResource> allContainerPages = cloneCms.readResources("/", f);
            replacePath(sourceModulePath, targetModulePath, allContainerPages);
        }
    } catch (Throwable e) {
        LOG.error(e.getLocalizedMessage(), e);
        getReport().addError(e);
    } finally {
        cms.getRequestContext().setCurrentProject(currentProject);
    }
}

From source file:org.opencms.importexport.CmsImportVersion4.java

/**
 * Rewrites all parseable files, to assure link check.<p>
 *///from  ww  w .  j a va  2s. c  o m
protected void rewriteParseables() {

    if (m_parseables.isEmpty()) {
        return;
    }

    m_report.println(Messages.get().container(Messages.RPT_START_PARSE_LINKS_0), I_CmsReport.FORMAT_HEADLINE);

    int i = 0;
    Iterator it = m_parseables.iterator();
    while (it.hasNext()) {
        CmsResource res = (CmsResource) it.next();

        m_report.print(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_SUCCESSION_2,
                String.valueOf(i + 1), String.valueOf(m_parseables.size())), I_CmsReport.FORMAT_NOTE);

        m_report.print(Messages.get().container(Messages.RPT_PARSE_LINKS_FOR_1, m_cms.getSitePath(res)),
                I_CmsReport.FORMAT_NOTE);
        m_report.print(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_DOTS_0));

        try {
            // make sure the date last modified is kept...
            CmsFile file = m_cms.readFile(res);
            file.setDateLastModified(res.getDateLastModified());
            m_cms.writeFile(file);

            m_report.println(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_OK_0),
                    I_CmsReport.FORMAT_OK);
        } catch (Throwable e) {
            m_report.addWarning(e);
            m_report.println(
                    org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_FAILED_0),
                    I_CmsReport.FORMAT_ERROR);
            if (LOG.isWarnEnabled()) {
                LOG.warn(Messages.get().getBundle().key(Messages.LOG_IMPORTEXPORT_REWRITING_1,
                        res.getRootPath()));
            }
            if (LOG.isDebugEnabled()) {
                LOG.debug(e.getLocalizedMessage(), e);
            }
        }
        i++;
    }

    m_report.println(Messages.get().container(Messages.RPT_END_PARSE_LINKS_0), I_CmsReport.FORMAT_HEADLINE);
}

From source file:com.google.enterprise.connector.otex.LivelinkConnectorType.java

/**
 * Returns the exception's message, or the exception class
 * name if no message is present./*from  ww  w  .ja  va2s .c  o  m*/
 *
 * @param t the exception
 * @return a message
 */
private String getExceptionMessage(Throwable t) {
    String message = t.getLocalizedMessage();
    if (message != null)
        return message;
    return t.getClass().getName();
}

From source file:im.ene.lab.attiq.ui.activities.ItemDetailActivity.java

@Override
public void onFailure(Call<Article> call, Throwable error) {
    EventBus.getDefault().post(new ItemDetailEvent(getClass().getSimpleName(), false,
            new Event.Error(Event.Error.ERROR_UNKNOWN, error.getLocalizedMessage()), null));
}

From source file:im.ene.lab.attiq.ui.activities.ItemDetailActivity.java

private void buildArticleComments(@NonNull final Article article) {
    ApiClient.itemComments(article.getId()).enqueue(new Callback<ArrayList<Comment>>() {
        @Override/* w  ww.  j  a va  2s  .  c  o  m*/
        public void onResponse(Call<ArrayList<Comment>> call, Response<ArrayList<Comment>> response) {
            mComments = response.body();
            Collections.sort(mComments, new Comparator<Comment>() {
                @Override
                public int compare(Comment lhs, Comment rhs) {
                    return (int) (TimeUtil.itemTimeEpochV2(lhs.getCreatedAt())
                            - TimeUtil.itemTimeEpochV2(rhs.getCreatedAt()));
                }
            });

            if (mComments != null) {
                EventBus.getDefault().post(new ItemCommentsEvent(true, null, mComments));
            } else {
                mComments = new ArrayList<>();
                EventBus.getDefault().post(new ItemCommentsEvent(false,
                        new Event.Error(response.code(), response.message()), null));
            }
        }

        @Override
        public void onFailure(Call<ArrayList<Comment>> call, Throwable error) {
            EventBus.getDefault().post(new ItemCommentsEvent(false,
                    new Event.Error(Event.Error.ERROR_UNKNOWN, error.getLocalizedMessage()), null));
        }
    });
}

From source file:org.hippoecm.frontend.plugins.cms.admin.updater.UpdaterEditor.java

protected IModel<String> getExceptionTranslation(final Throwable t, final Object... parameters) {
    String key = "exception,type=${type},message=${message}";
    HashMap<String, String> details = new HashMap<>();
    details.put("type", t.getClass().getName());
    details.put("message", t.getMessage());
    return new StringResourceModel(key, UpdaterEditor.this, new Model<>(details), t.getLocalizedMessage(),
            parameters);//from  w  w w.  j  a  v  a  2 s . c o m
}

From source file:com.microsoft.alm.plugin.idea.git.ui.vcsimport.ImportPageModelImpl.java

private void doImport(final Project project, final ServerContext context, final String repositoryName) {
    new Task.Backgroundable(project, TfPluginBundle.message(TfPluginBundle.KEY_IMPORT_IMPORTING_PROJECT), true,
            PerformInBackgroundOption.DEAF) {
        @Override/*w  w  w.j  av  a 2  s  .c o  m*/
        public void run(@NotNull final ProgressIndicator indicator) {
            // Local context can change if the creation of the repo succeeds
            ServerContext localContext = context;
            String remoteUrlForDisplay = "";

            try {
                if (!projectSupportsGitRepos(project, context, indicator)) {
                    logger.error(
                            "doImport: the team project {} on collection {} , "
                                    + "server {} does not support Git repositories or is not a hybrid project",
                            localContext.getTeamProjectReference().getName(),
                            localContext.getTeamProjectCollectionReference().getName(), localContext.getUri());
                    return;
                }

                final GitRepository repo = getRepositoryForProject(project);
                final VirtualFile rootVirtualFile = repo != null ? repo.getRoot() : project.getBaseDir();

                final GitRepository localRepository = repo != null ? repo
                        : setupGitRepositoryForProject(project, rootVirtualFile, localContext, indicator);
                if (localRepository == null) {
                    logger.error("doImport: current project {} is not in a Git repository", project.getName());
                    return;
                }

                if (!doFirstCommitIfRequired(project, localRepository, rootVirtualFile, localContext,
                        indicator)) {
                    logger.error("doImport: failed to do first commit on the local repository at: {}",
                            localRepository.getRoot().getUrl());
                    return;
                }

                final com.microsoft.alm.sourcecontrol.webapi.model.GitRepository remoteRepository = createRemoteGitRepo(
                        project, context, localContext, indicator);
                if (remoteRepository != null) {
                    //remote repo creation succeeded, save active context with the repository information
                    localContext = new ServerContextBuilder(localContext).uri(remoteRepository.getRemoteUrl())
                            .repository(remoteRepository).build();
                    ServerContextManager.getInstance().add(localContext);
                } else {
                    logger.error(
                            "doImport: failed to create remote repository with name: {} on server: {}, collection: {}",
                            repositoryName, localContext.getUri(),
                            localContext.getTeamProjectCollectionReference().getName());
                    return;
                }

                if (!setupRemoteOnLocalRepo(project, localRepository, remoteRepository, localContext,
                        indicator)) {
                    logger.error(
                            "doImport: failed to setup remote origin on local repository at: {} to point to remote repository: {}",
                            localRepository.getRoot().getUrl(), remoteRepository.getRemoteUrl());
                    return;
                }

                if (!pushChangesToRemoteRepo(project, localRepository, remoteRepository, localContext,
                        indicator)) {
                    logger.error("doImport: failed to push changes to remote repository: {}",
                            remoteRepository.getRemoteUrl());
                    return;
                }

                //all steps completed successfully
                remoteUrlForDisplay = remoteRepository.getRemoteUrl();

            } catch (Throwable unexpectedError) {
                remoteUrlForDisplay = "";
                logger.error("doImport: Unexpected error during import");
                logger.warn("doImport", unexpectedError);
                notifyImportError(project,
                        TfPluginBundle.message(TfPluginBundle.KEY_IMPORT_ERRORS_UNEXPECTED,
                                unexpectedError.getLocalizedMessage()),
                        TfPluginBundle.message(TfPluginBundle.KEY_IMPORT_FAILED), localContext);

            } finally {
                if (StringUtils.isNotEmpty(remoteUrlForDisplay)) {
                    // Notify the user that we are done and provide a link to the repo
                    VcsNotifier.getInstance(project).notifyImportantInfo(
                            TfPluginBundle.message(TfPluginBundle.KEY_IMPORT_SUCCEEDED),
                            TfPluginBundle.message(TfPluginBundle.KEY_IMPORT_SUCCEEDED_MESSAGE,
                                    project.getName(), remoteUrlForDisplay, repositoryName),
                            NotificationListener.URL_OPENING_LISTENER);

                    // Add Telemetry for a successful import
                    TfsTelemetryHelper.getInstance().sendEvent(ACTION_NAME,
                            new TfsTelemetryHelper.PropertyMapBuilder().currentOrActiveContext(localContext)
                                    .actionName(ACTION_NAME).success(true).build());
                }
            }
        }

    }.queue();

}

From source file:com.microsoft.tfs.core.checkinpolicies.PolicyEvaluator.java

/**
 * Returns a text error message (with newlines) suitable for printing in a
 * console window, log file, or other text area that describes a problem
 * loading a check-in policy implementation so the user can fix the problem.
 * Things like policy type ID, installation instructions, and sometimes
 * stack traces are formatted into the message.
 *
 * @param throwable//from w  ww  .j  a v  a2 s.  co  m
 *        the problem that caused the load failure, usually these are
 *        {@link PolicyLoaderException}, but they can be any kind of
 *        {@link Throwable} and the error message will be as descriptive as
 *        possible (must not be <code>null</code>)
 * @return the formatted error text.
 */
public static String makeTextErrorForLoadException(final Throwable throwable) {
    Check.notNull(throwable, "throwable"); //$NON-NLS-1$

    final StringBuffer sb = new StringBuffer();

    if (throwable instanceof PolicyLoaderException
            && ((PolicyLoaderException) throwable).getPolicyType() != null) {
        /*
         * Additional details for policy loader exceptions with policy type
         * information.
         */

        sb.append(Messages.getString("PolicyEvaluator.RequiredCheckinPolicyFailedToLoad")); //$NON-NLS-1$

        final PolicyLoaderException ple = (PolicyLoaderException) throwable;
        sb.append(Messages.getString("PolicyEvaluator.NameColon") + ple.getPolicyType().getName() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
        sb.append(Messages.getString("PolicyEvaluator.IDColon") + ple.getPolicyType().getID() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
        sb.append(Messages.getString("PolicyEvaluator.InstallationInstructionsColon") //$NON-NLS-1$
                + ple.getPolicyType().getInstallationInstructions() + "\n"); //$NON-NLS-1$

        sb.append(Messages.getString("PolicyEvaluator.ErrorColon") + throwable.getLocalizedMessage() + "\n\n"); //$NON-NLS-1$ //$NON-NLS-2$
    } else {
        /*
         * Run-time errors and other problems not handled during policy
         * loading are wrapped in TECoreException, but some other exception
         * types may come through (very rare).
         */

        sb.append(Messages.getString("PolicyEvaluator.AnErrorOccurredInThePolicyFramework")); //$NON-NLS-1$

        final StringWriter sw = new StringWriter();
        final PrintWriter pw = new PrintWriter(sw, true);
        throwable.printStackTrace(pw);
        pw.flush();
        sw.flush();

        sb.append(Messages.getString("PolicyEvaluator.ErrorColon") + sw.toString() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
    }

    sb.append(Messages.getString("PolicyEvaluator.MoreDetailsMayBeAvailableInPlatformLogs")); //$NON-NLS-1$

    return sb.toString();
}

From source file:org.jboss.processFlow.knowledgeService.BaseKnowledgeSessionBean.java

private SessionTemplate parseSessionTemplateString(StatefulKnowledgeSession ksession) {
    ParserConfiguration pconf = new ParserConfiguration();
    pconf.addImport("SessionTemplate", SessionTemplate.class);
    ParserContext context = new ParserContext(pconf);
    Serializable s = MVEL.compileExpression(templateString.trim(), context);
    try {// www  . j  a  va2s. c  o m
        Map vars = new HashMap();
        vars.put(IKnowledgeSession.KSESSION, ksession);
        SessionTemplate sTemplate = (SessionTemplate) MVEL.executeExpression(s, vars);
        sessionTemplateInstantiationAttempts = 1;
        return sTemplate;
    } catch (Throwable x) {
        sessionTemplateInstantiationAttempts = -1;
        x.printStackTrace();
        log.error("newSessionTemplate() following exception thrown \n\t" + x.getLocalizedMessage()
                + "\n : with session template string = \n\n" + templateString);
        return null;
    }
}