Example usage for org.apache.commons.lang3.exception ExceptionUtils getRootCauseMessage

List of usage examples for org.apache.commons.lang3.exception ExceptionUtils getRootCauseMessage

Introduction

In this page you can find the example usage for org.apache.commons.lang3.exception ExceptionUtils getRootCauseMessage.

Prototype

public static String getRootCauseMessage(final Throwable th) 

Source Link

Document

Gets a short message summarising the root cause exception.

Usage

From source file:org.xwiki.component.wiki.internal.DefaultWikiComponentManagerEventListener.java

/**
 * Helper method to unregister a wiki component.
 * /*from   www  .  ja  va  2  s  .c o m*/
 * @param documentReference the reference to the document for which to unregister the held wiki component.
 */
private void unregisterComponents(DocumentReference documentReference) {
    try {
        this.wikiComponentManager.unregisterWikiComponents(documentReference);
    } catch (WikiComponentException e) {
        this.logger.warn("Unable to unregister component(s) from document [{}]: {}", documentReference,
                ExceptionUtils.getRootCauseMessage(e));
    }
}

From source file:org.xwiki.component.wiki.internal.WikiComponentManagerEventListenerHelper.java

/**
 * Register every given {@link WikiComponent} against the {@link WikiComponentManager}.
 *
 * @param components a list of components that should be registered
 *///from  w w  w  . j a v a 2s.  co  m
public void registerComponentList(List<WikiComponent> components) {
    for (WikiComponent component : components) {
        // Register the component
        try {
            this.wikiComponentManager.registerWikiComponent(component);
        } catch (WikiComponentException e) {
            this.logger.warn("Unable to register component(s) from document [{}]: {}",
                    component.getDocumentReference(), ExceptionUtils.getRootCauseMessage(e));
        }
    }
}

From source file:org.xwiki.component.wiki.internal.WikiComponentManagerEventListenerHelper.java

/**
 * Helper method to unregister a wiki component.
 *
 * @param entityReference the reference to the entity for which to unregister the held wiki component.
 *///  w w w  .j  a v  a2s.  c  o  m
public void unregisterComponents(EntityReference entityReference) {
    try {
        this.wikiComponentManager.unregisterWikiComponents(entityReference);
    } catch (WikiComponentException e) {
        this.logger.warn("Unable to unregister component(s) from the entity [{}]: {}", entityReference,
                ExceptionUtils.getRootCauseMessage(e));
    }
}

From source file:org.xwiki.contrib.githubstats.internal.DefaultGitHubStatsManager.java

private GHUser locateUserInGitHub(GitHub gitHub, String authorId, String emailAddress) {
    try {/*from  ww w.j  a  va2  s.c om*/
        // Search for a user with the passed login
        // Note: We don't use "gitHub.getUser(authorId)" because if the authorId is a simple one (like "Gabriela")
        // then it's very likely that it'll return the wrong user. Doing a search is likely to return more than one
        // user and thus we'll search with the email address and full name.
        PagedSearchIterable<GHUser> matchingUsers = gitHub.searchUsers().q(escapeQueryTerm(authorId))
                .type("user").in("login").list();
        if (matchingUsers.getTotalCount() == 1) {
            return matchingUsers.iterator().next();
        }

        // Search for a user with a matching email address
        matchingUsers = gitHub.searchUsers().q(escapeQueryTerm(emailAddress)).type("user").in("email").list();
        if (matchingUsers.getTotalCount() == 1) {
            return matchingUsers.iterator().next();
        }

        // Search for a user with a full name matching the passed login (since on git, sometimes users set their
        // name as their git id).
        matchingUsers = gitHub.searchUsers().q(escapeQueryTerm(authorId)).type("user").in("fullname").list();
        if (matchingUsers.getTotalCount() == 1) {
            return matchingUsers.iterator().next();
        }
    } catch (Throwable e) {
        // It failed to locate the user. The most likely reason is that the API rate limit has been reached.
        // Continue so that the users for which it has worked can be saved and so that the user can reimport the
        // rest later on.
        this.logger.warn("Failed to locate user [{}] (email [{}]). Reason: [{}]", authorId, emailAddress,
                ExceptionUtils.getRootCauseMessage(e));
    }

    return null;
}

From source file:org.xwiki.contrib.mailarchive.timeline.internal.TimeLineGenerator.java

/**
 * {@inheritDoc}/*w w  w . j  ava  2  s.c  o  m*/
 * 
 * @see org.xwiki.contrib.mailarchive.timeline.ITimeLineGenerator#compute()
 */
@Override
public String compute(int maxItems) {
    try {
        config.reloadConfiguration();
    } catch (MailArchiveException e) {
        logger.error("Could not load mail archive configuration", e);
        return null;
    }
    Map<String, IMailingList> mailingLists = config.getMailingLists();
    Map<String, IType> types = config.getMailTypes();

    try {
        this.userStatsUrl = xwiki.getDocument(docResolver.resolve("MailArchive.ViewUserMessages"), context)
                .getURL("view", context);
    } catch (XWikiException e1) {
        logger.warn("Could not retrieve user stats url {}", ExceptionUtils.getRootCauseMessage(e1));
    }

    TreeMap<Long, TimeLineEvent> sortedEvents = new TreeMap<Long, TimeLineEvent>();

    // Set loading user in context (for rights)
    String loadingUser = config.getLoadingUser();
    context.setUserReference(docResolver.resolve(loadingUser));

    try {
        // Search topics
        String xwql = "select doc.fullName, topic.author, topic.subject, topic.topicid, topic.startdate, topic.lastupdatedate from Document doc, doc.object("
                + XWikiPersistence.CLASS_TOPICS + ") as topic order by topic.lastupdatedate desc";
        List<Object[]> result = queryManager.createQuery(xwql, Query.XWQL).setLimit(maxItems).execute();

        for (Object[] item : result) {
            XWikiDocument doc = null;
            try {
                String docurl = (String) item[0];
                String author = (String) item[1];
                String subject = (String) item[2];
                String topicId = (String) item[3];
                Date date = (Date) item[4];
                Date end = (Date) item[5];

                String action = "";

                // Retrieve associated emails
                TreeMap<Long, TopicEventBubble> emails = getTopicMails(topicId, subject);

                if (emails == null || emails.isEmpty()) {
                    // Invalid topic, not emails attached, do not show it
                    logger.warn("Invalid topic, no emails attached " + doc);
                } else {
                    if (date != null && end != null && date.equals(end)) {
                        // Add 10 min just to see the tape
                        end.setTime(end.getTime() + 600000);
                    }

                    doc = xwiki.getDocument(docResolver.resolve(docurl), context);
                    final List<String> tagsList = doc.getTagsList(context);
                    List<String> topicTypes = doc.getListValue(XWikiPersistence.CLASS_TOPICS, "type");

                    // Email type icon
                    List<String> icons = new ArrayList<String>();
                    for (String topicType : topicTypes) {
                        IType type = types.get(topicType);
                        if (type != null && !StringUtils.isEmpty(type.getIcon())) {
                            icons.add(xwiki.getSkinFile("icons/silk/" + type.getIcon() + ".png", context));
                            // http://localhost:8080/xwiki/skins/colibri/icons/silk/bell
                            // http://localhost:8080/xwiki/resources/icons/silk/bell.png

                        }
                    }

                    // Author and avatar
                    final IMAUser wikiUser = mailUtils.parseUser(author, config.isMatchLdap());
                    final String authorAvatar = getAuthorAvatar(wikiUser.getWikiProfile());

                    final TimeLineEvent timelineEvent = new TimeLineEvent();
                    TimeLineEvent additionalEvent = null;
                    timelineEvent.beginDate = date;
                    timelineEvent.title = subject;
                    timelineEvent.icons = icons;
                    timelineEvent.lists = doc.getListValue(XWikiPersistence.CLASS_TOPICS, "list");
                    timelineEvent.author = wikiUser.getDisplayName();
                    timelineEvent.authorAvatar = authorAvatar;
                    timelineEvent.extract = getExtract(topicId);

                    if (emails.size() == 1) {
                        logger.debug("Adding instant event for email '" + subject + "'");
                        // Unique email, we show a punctual email event
                        timelineEvent.url = emails.firstEntry().getValue().link;
                        timelineEvent.action = "New Email ";

                    } else {
                        // For email with specific type icon, and a duration, both a band and a point should be added (so 2 events)
                        // because no icon is displayed for duration events.
                        if (CollectionUtils.isNotEmpty(icons)) {
                            logger.debug(
                                    "Adding additional instant event to display type icon for first email in topic");
                            additionalEvent = new TimeLineEvent(timelineEvent);
                            additionalEvent.url = emails.firstEntry().getValue().link;
                            additionalEvent.action = "New Email ";
                        }

                        // Email thread, we show a topic event (a range)
                        logger.debug("Adding duration event for topic '" + subject + "'");
                        timelineEvent.endDate = end;
                        timelineEvent.url = doc.getURL("view", context);
                        timelineEvent.action = "New Topic ";
                        timelineEvent.messages = emails;
                    }

                    // Add the generated Event to the list
                    if (sortedEvents.containsKey(date.getTime())) {
                        // Avoid having more than 1 event at exactly the same time, because some timeline don't like it
                        date.setTime(date.getTime() + 1);
                    }
                    sortedEvents.put(date.getTime(), timelineEvent);
                    if (additionalEvent != null) {
                        sortedEvents.put(date.getTime() + 1, additionalEvent);
                    }
                }

            } catch (Throwable t) {
                logger.warn("Exception for " + doc, t);
            }

        }

    } catch (Throwable e) {
        logger.warn("could not compute timeline data", e);
    }

    return printEvents(sortedEvents);

}

From source file:org.xwiki.contrib.oidc.auth.internal.OIDCUserManager.java

private Principal updateUser(IDTokenClaimsSet idToken, UserInfo userInfo)
        throws XWikiException, QueryException {
    XWikiDocument userDocument = this.store.searchDocument(idToken.getIssuer().getValue(),
            userInfo.getSubject().toString());

    XWikiDocument modifiableDocument;/*from w ww  . j  av a2s. co m*/
    boolean newUser;
    if (userDocument == null) {
        userDocument = getNewUserDocument(idToken, userInfo);

        newUser = true;
        modifiableDocument = userDocument;
    } else {
        // Don't change the document author to not change document execution right

        newUser = false;
        modifiableDocument = userDocument.clone();
    }

    XWikiContext xcontext = this.xcontextProvider.get();

    // Set user fields
    BaseObject userObject = modifiableDocument
            .getXObject(xcontext.getWiki().getUserClass(xcontext).getDocumentReference(), true, xcontext);

    // Address
    Address address = userInfo.getAddress();
    if (address != null) {
        userObject.set("address", address.getFormatted(), xcontext);
    }

    // Email
    if (userInfo.getEmail() != null) {
        userObject.set("email", userInfo.getEmail().toUnicodeString(), xcontext);
    }

    // Last name
    if (userInfo.getFamilyName() != null) {
        userObject.set("last_name", userInfo.getFamilyName(), xcontext);
    }

    // First name
    if (userInfo.getGivenName() != null) {
        userObject.set("first_name", userInfo.getGivenName(), xcontext);
    }

    // Phone
    if (userInfo.getPhoneNumber() != null) {
        userObject.set("phone", userInfo.getPhoneNumber(), xcontext);
    }

    // Default locale
    if (userInfo.getLocale() != null) {
        userObject.set("default_language", Locale.forLanguageTag(userInfo.getLocale()).toString(), xcontext);
    }

    // Time Zone
    if (userInfo.getZoneinfo() != null) {
        userObject.set("timezone", userInfo.getZoneinfo(), xcontext);
    }

    // Website
    if (userInfo.getWebsite() != null) {
        userObject.set("blog", userInfo.getWebsite().toString(), xcontext);
    }

    // Avatar
    if (userInfo.getPicture() != null) {
        try {
            String filename = FilenameUtils.getName(userInfo.getPicture().toString());
            URLConnection connection = userInfo.getPicture().toURL().openConnection();
            connection.setRequestProperty("User-Agent", this.getClass().getPackage().getImplementationTitle()
                    + '/' + this.getClass().getPackage().getImplementationVersion());
            try (InputStream content = connection.getInputStream()) {
                modifiableDocument.addAttachment(filename, content, xcontext);
            }
            userObject.set("avatar", filename, xcontext);
        } catch (IOException e) {
            this.logger.warn("Failed to get user avatar from URL [{}]: {}", userInfo.getPicture(),
                    ExceptionUtils.getRootCauseMessage(e));
        }
    }

    // XWiki claims
    updateXWikiClaims(modifiableDocument, userObject.getXClass(xcontext), userObject, userInfo, xcontext);

    // Set OIDC fields
    this.store.updateOIDCUser(modifiableDocument, idToken.getIssuer().getValue(),
            userInfo.getSubject().getValue());

    // Prevent data to send with the event
    OIDCUserEventData eventData = new OIDCUserEventData(new NimbusOIDCIdToken(idToken),
            new NimbusOIDCUserInfo(userInfo));

    // Notify
    this.observation.notify(new OIDCUserUpdating(modifiableDocument.getDocumentReference()), modifiableDocument,
            eventData);

    // Apply the modifications
    if (newUser || userDocument.apply(modifiableDocument)) {
        String comment;
        if (newUser) {
            comment = "Create user from OpenID Connect";
        } else {
            comment = "Update user from OpenID Connect";
        }

        xcontext.getWiki().saveDocument(userDocument, comment, xcontext);

        // Now let's add new the user to XWiki.XWikiAllGroup
        if (newUser) {
            xcontext.getWiki().setUserDefaultGroup(userDocument.getFullName(), xcontext);
        }

        // Notify
        this.observation.notify(new OIDCUserUpdated(userDocument.getDocumentReference()), userDocument,
                eventData);
    }

    return new SimplePrincipal(userDocument.getPrefixedFullName());
}

From source file:org.xwiki.contrib.oidc.provider.internal.endpoint.UserInfoOIDCEndpoint.java

@Override
public Response handle(HTTPRequest httpRequest, OIDCResourceReference reference) throws Exception {
    // Parse the request
    UserInfoRequest request = UserInfoRequest.parse(httpRequest);

    // Get the token associated to the user
    AccessToken accessToken = request.getAccessToken();

    OIDCConsent consent = this.store.getConsent(accessToken);

    if (consent == null) {
        return new UserInfoErrorResponse(BearerTokenError.INVALID_TOKEN);
    }// w  ww.  j av  a2  s .  c o  m

    ClaimsRequest claims = consent.getClaims();

    DocumentReference userReference = consent.getUserReference();

    UserInfo userInfo = new UserInfo(this.manager.getSubject(userReference));

    XWikiContext xcontext = this.xcontextProvider.get();

    if (claims != null) {
        BaseObject userObject = this.store.getUserObject(consent);
        XWikiDocument userDocument = userObject.getOwnerDocument();

        for (Entry claim : claims.getUserInfoClaims()) {
            try {
                switch (claim.getClaimName()) {
                // OIDC core

                case OIDCUserInfo.CLAIM_ADDRESS:
                    String addressString = userObject.getLargeStringValue("address");
                    if (StringUtils.isNotEmpty(addressString)) {
                        Address address = new Address();
                        address.setFormatted(addressString);
                        userInfo.setAddress(address);
                    }
                    break;
                case OIDCUserInfo.CLAIM_EMAIL:
                    String email = userObject.getStringValue("email");
                    if (StringUtils.isNotEmpty(email)) {
                        userInfo.setEmail(new InternetAddress(email));
                    }
                    break;
                case OIDCUserInfo.CLAIM_EMAIL_VERIFIED:
                    if (userInfo.getEmail() != null) {
                        userInfo.setEmailVerified(true);
                    }
                    break;
                case OIDCUserInfo.CLAIM_FAMILY_NAME:
                    userInfo.setFamilyName(getStringValue(userObject, "last_name"));
                    break;
                case OIDCUserInfo.CLAIM_GIVEN_NAME:
                    userInfo.setGivenName(getStringValue(userObject, "first_name"));
                    break;
                case OIDCUserInfo.CLAIM_PHONE_NUMBER:
                    userInfo.setPhoneNumber(getStringValue(userObject, "phone"));
                    break;
                case OIDCUserInfo.CLAIM_PHONE_NUMBER_VERIFIED:
                    if (userInfo.getPhoneNumber() != null) {
                        userInfo.setPhoneNumberVerified(true);
                    }
                    break;
                case OIDCUserInfo.CLAIM_PICTURE:
                    userInfo.setPicture(this.store.getUserAvatarURI(userDocument));
                    break;
                case OIDCUserInfo.CLAIM_PROFILE:
                    userInfo.setProfile(this.store.getUserProfileURI(userDocument));
                    break;
                case OIDCUserInfo.CLAIM_UPDATED_AT:
                    userInfo.setUpdatedTime(userDocument.getDate());
                    break;
                case OIDCUserInfo.CLAIM_WEBSITE:
                    String blog = userObject.getStringValue("blog");
                    if (StringUtils.isNotEmpty(blog)) {
                        userInfo.setWebsite(new URI(blog));
                    }
                    break;
                case OIDCUserInfo.CLAIM_NAME:
                    userInfo.setName(xcontext.getWiki().getPlainUserName(userReference, xcontext));
                    break;
                case OIDCUserInfo.CLAIM_PREFERRED_NAME:
                    userInfo.setPreferredUsername(xcontext.getWiki().getPlainUserName(userReference, xcontext));
                    break;
                case OIDCUserInfo.CLAIM_ZONEINFO:
                    String timezone = userObject.getStringValue("timezone");
                    if (StringUtils.isNotEmpty(timezone)) {
                        userInfo.setZoneinfo(timezone);
                    }
                    break;
                case OIDCUserInfo.CLAIM_LOCALE:
                    String locale = userObject.getStringValue("default_language");
                    if (StringUtils.isNotEmpty(locale)) {
                        userInfo.setLocale(LocaleUtils.toLocale(locale).toLanguageTag());
                    }
                    break;
                case OIDCUserInfo.CLAIM_MIDDLE_NAME:
                case OIDCUserInfo.CLAIM_NICKNAME:
                case OIDCUserInfo.CLAIM_GENDER:
                case OIDCUserInfo.CLAIM_BIRTHDATE:
                    // TODO
                    break;

                // XWiki core
                // Note: most of the XWiki core fields are handled by #setCustomUserInfoClaim

                case OIDCUserInfo.CLAIM_XWIKI_GROUPS:
                    userInfo.setClaim(OIDCUserInfo.CLAIM_XWIKI_GROUPS, getUserGroups(userDocument, xcontext));
                    break;

                default:
                    setCustomUserInfoClaim(userInfo, claim, userObject, userDocument, xcontext);
                    break;
                }
            } catch (Exception e) {
                // Failed to set one of the claims
                this.logger.warn("Failed to get claim [{}] for user [{}]: {}", claim.getClaimName(),
                        userReference, ExceptionUtils.getRootCauseMessage(e));
            }
        }
    }

    return new UserInfoSuccessResponse(userInfo);
}

From source file:org.xwiki.edit.internal.EditorWikiComponent.java

@Override
public EditorDescriptor getDescriptor() {
    try {//from   w w  w  .  j av a 2  s  .c  o  m
        XWikiContext xcontext = this.xcontextProvider.get();
        XWikiDocument editorDocument = xcontext.getWiki().getDocument(this.getDocumentReference(), xcontext);
        XWikiDocument translatedEditorDocument = editorDocument.getTranslatedDocument(xcontext);
        this.descriptorBuilder.setName(translatedEditorDocument.getRenderedTitle(Syntax.PLAIN_1_0, xcontext));
        this.descriptorBuilder
                .setDescription(translatedEditorDocument.getRenderedContent(Syntax.PLAIN_1_0, xcontext));

    } catch (XWikiException e) {
        this.logger.warn("Failed to read the editor name and description. Root cause: "
                + ExceptionUtils.getRootCauseMessage(e));
    }
    return this.descriptorBuilder.build();
}

From source file:org.xwiki.edit.internal.EditorWikiComponentBuilder.java

@Override
public List<DocumentReference> getDocumentReferences() {
    List<DocumentReference> editorReferences = new ArrayList<>();
    try {/*  w ww .  j  ava  2  s  .  c o  m*/
        // NOTE: We use HQL and not XWQL here because the conversion from XWQL to HQL requires the class definition
        // (XWiki.EditorClass) to be present in order to determine which column to join (StringProperty here), and
        // the class definition might not be available yet (it is initialized by EditorClassDocumentInitializer). We
        // noticed this problem at build time when the XWiki package is created for functional tests.
        Query query = this.queryManager.createQuery(", BaseObject as editorObject, StringProperty as roleHint "
                + "where doc.fullName = editorObject.name and editorObject.className = 'XWiki.EditorClass' and "
                + "editorObject.id = roleHint.id.id and roleHint.id.name='roleHint' and "
                + "(roleHint.value <> '' or (roleHint.value is not null and '' is null))", Query.HQL);
        for (Object result : query.execute()) {
            editorReferences.add(this.currentDocumentReferenceResolver.resolve(result.toString()));
        }
    } catch (QueryException e) {
        this.logger.warn("Failed to query the editors defined in wiki pages. Root cause: [{}]",
                ExceptionUtils.getRootCauseMessage(e));
    }
    return editorReferences;
}

From source file:org.xwiki.extension.internal.DefaultExtensionManagerConfiguration.java

@Override
public Collection<ExtensionRepositoryDescriptor> getExtensionRepositoryDescriptors() {
    Collection<ExtensionRepositoryDescriptor> repositories;

    List<String> repositoryStrings = this.configuration.get().getProperty(CK_PREFIX + "repositories",
            Collections.<String>emptyList());

    if (repositoryStrings.isEmpty()) {
        repositories = null;//from   ww  w . jav a2  s.  c o m
    } else {
        Map<String, ExtensionRepositoryDescriptor> repositoriesMap = new LinkedHashMap<String, ExtensionRepositoryDescriptor>();
        for (String repositoryString : repositoryStrings) {
            if (StringUtils.isNotBlank(repositoryString)) {
                try {
                    DefaultExtensionRepositoryDescriptor extensionRepositoryId = parseRepository(
                            repositoryString);
                    if (repositoriesMap.containsKey(extensionRepositoryId.getId())) {
                        this.logger.warn(
                                "Duplicated repository id in [{}] first found in [{}]. The last one will be used.",
                                extensionRepositoryId, repositoriesMap.get(extensionRepositoryId.getId()));
                    }
                    repositoriesMap.put(extensionRepositoryId.getId(), extensionRepositoryId);
                } catch (Exception e) {
                    this.logger.warn("Ignoring invalid repository configuration [{}]. " + "Root cause [{}]",
                            repositoryString, ExceptionUtils.getRootCauseMessage(e));
                }
            } else {
                this.logger.debug("Empty repository id found in the configuration");
            }
        }

        repositories = repositoriesMap.values();

        // Get extended properties

        for (ExtensionRepositoryDescriptor descriptor : repositories) {
            setRepositoryProperties((DefaultExtensionRepositoryDescriptor) descriptor);
        }
    }

    return repositories;
}