Example usage for org.apache.commons.lang3 StringUtils defaultString

List of usage examples for org.apache.commons.lang3 StringUtils defaultString

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils defaultString.

Prototype

public static String defaultString(final String str, final String defaultStr) 

Source Link

Document

Returns either the passed in String, or if the String is null , the value of defaultStr .

 StringUtils.defaultString(null, "NULL")  = "NULL" StringUtils.defaultString("", "NULL")    = "" StringUtils.defaultString("bat", "NULL") = "bat" 

Usage

From source file:models.NotificationEvent.java

@Transient
public String getMessage(Lang lang) {
    switch (eventType) {
    case ISSUE_STATE_CHANGED:
        if (newValue.equals(State.CLOSED.state())) {
            return Messages.get(lang, "notification.issue.closed");
        } else {//from   ww w  .jav  a 2 s.  c  o m
            return Messages.get(lang, "notification.issue.reopened");
        }
    case ISSUE_ASSIGNEE_CHANGED:
        if (newValue == null) {
            return Messages.get(lang, "notification.issue.unassigned");
        } else {
            return Messages.get(lang, "notification.issue.assigned", newValue);
        }
    case NEW_ISSUE:
    case NEW_POSTING:
    case NEW_COMMENT:
    case NEW_PULL_REQUEST:
    case NEW_COMMIT:
    case ISSUE_BODY_CHANGED:
        return newValue;
    case NEW_REVIEW_COMMENT:
        try {
            ReviewComment reviewComment = ReviewComment.find.byId(Long.valueOf(this.resourceId));
            if (reviewComment != null) {
                return buildCommentedCodeMessage(reviewComment, lang);
            }
        } catch (Exception e) {
            play.Logger.error("Failed to generate a notification " + "message for a review comment", e);
        }

        return newValue;
    case PULL_REQUEST_STATE_CHANGED:
        if (State.OPEN.state().equals(newValue)) {
            return Messages.get(lang, "notification.pullrequest.reopened");
        } else {
            return Messages.get(lang, "notification.pullrequest." + newValue);
        }
    case PULL_REQUEST_COMMIT_CHANGED:
        return newValue;
    case PULL_REQUEST_MERGED:
        return Messages.get(lang, "notification.type.pullrequest.merged." + newValue) + "\n"
                + StringUtils.defaultString(oldValue, StringUtils.EMPTY);
    case MEMBER_ENROLL_REQUEST:
        if (RequestState.REQUEST.name().equals(newValue)) {
            return Messages.get(lang, "notification.member.enroll.request");
        } else if (RequestState.ACCEPT.name().equals(newValue)) {
            return Messages.get(lang, "notification.member.enroll.accept");
        } else {
            return Messages.get(lang, "notification.member.enroll.cancel");
        }
    case ORGANIZATION_MEMBER_ENROLL_REQUEST:
        if (RequestState.REQUEST.name().equals(newValue)) {
            return Messages.get(lang, "notification.organization.member.enroll.request");
        } else if (RequestState.ACCEPT.name().equals(newValue)) {
            return Messages.get(lang, "notification.organization.member.enroll.accept");
        } else {
            return Messages.get(lang, "notification.organization.member.enroll.cancel");
        }
    case PULL_REQUEST_REVIEW_STATE_CHANGED:
        if (PullRequestReviewAction.DONE.name().equals(newValue)) {
            return Messages.get(lang, "notification.pullrequest.reviewed", User.find.byId(senderId).loginId);
        } else {
            return Messages.get(lang, "notification.pullrequest.unreviewed", User.find.byId(senderId).loginId);
        }
    case REVIEW_THREAD_STATE_CHANGED:
        if (newValue.equals(CommentThread.ThreadState.CLOSED.name())) {
            return Messages.get(lang, "notification.reviewthread.closed");
        } else {
            return Messages.get(lang, "notification.reviewthread.reopened");
        }
    default:
        return null;
    }
}

From source file:io.wcm.samples.handler.business.navigation.NavigationManagerImpl.java

private String getItemTitle(final Page page) {
    return StringUtils.defaultString(page.getNavigationTitle(), page.getTitle());
}

From source file:cn.calm.osgi.conter.FelixOsgiHost.java

/**
 * Gets a param from the ServletContext, returning the default value if the
 * param is not set/*from   w ww.  j a  va  2s  .c om*/
 * 
 * @param paramName
 *            the name of the param to get from the ServletContext
 * @param defaultValue
 *            value to return if the param is not set
 * @return
 */
private String getServletContextParam(String paramName, String defaultValue) {
    return StringUtils.defaultString(this.servletContext.getInitParameter(paramName), defaultValue);
}

From source file:edu.sabanciuniv.sentilab.sare.controllers.aspect.AspectLexiconFactory.java

@Override
protected AspectLexiconFactory addTextPacket(AspectLexicon lexicon, InputStream input, String delimiter)
        throws IOException {
    Validate.notNull(lexicon, CannedMessages.NULL_ARGUMENT, "lexicon");
    Validate.notNull(input, CannedMessages.NULL_ARGUMENT, "input");

    delimiter = StringUtils.defaultString(delimiter, "\t");

    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
    String line;//  w w w . j  av  a  2 s. c o m

    while ((line = reader.readLine()) != null) {
        StrTokenizer tokenizer = new StrTokenizer(line, StrMatcher.stringMatcher(delimiter),
                StrMatcher.quoteMatcher());
        List<String> columns = tokenizer.getTokenList();
        if (columns.size() < 1) {
            continue;
        }

        String aspectStr = columns.get(0);
        Matcher matcher = Pattern.compile("^<(.*)>$").matcher(aspectStr);
        if (matcher.matches()) {
            aspectStr = matcher.group(1);
        } else {
            continue;
        }

        AspectLexicon aspect = lexicon.addAspect(aspectStr);
        for (int i = 1; i < columns.size(); i++) {
            aspect.addExpression(columns.get(i));
        }
    }

    return this;
}

From source file:io.wcm.handler.link.type.helpers.InternalLinkResolver.java

/**
 * Resolves a link and stores the result in the link object.
 * Primary it sets the property "linkReferenceInvalid" and the URL is link resolving was successful.
 * @param link Link/*from  ww w . ja v a 2  s  .co  m*/
 * @param options Options to influence the link resolution process
 * @return Resolved link object
 */
public Link resolveLink(Link link, InternalLinkResolverOptions options) {
    LinkRequest linkRequest = link.getLinkRequest();
    ValueMap props = linkRequest.getResourceProperties();

    // flag to indicate whether any link reference parameter set
    boolean referenceSet = false;

    // first try to get direct link target page
    Page targetPage = link.getLinkRequest().getPage();
    if (targetPage != null) {
        referenceSet = true;
    }

    // if no target page is set get internal path that points to target page
    if (targetPage == null) {
        String targetPath = props.get(options.getPrimaryLinkRefProperty(), String.class);
        if (StringUtils.isNotEmpty(targetPath)) {
            referenceSet = true;
        }
        targetPage = getTargetPage(targetPath, options);
    }

    UrlHandlerConfig resolvingUrlHandlerConfig = urlHandlerConfig;
    UrlHandler resolvingUrlHandler = urlHandler;

    // use URL handler from target context for link URL building
    if (targetPage != null && options.isUseTargetContext() && !options.isRewritePathToContext()) {
        Resource resource = targetPage.getContentResource();
        resolvingUrlHandlerConfig = AdaptTo.notNull(resource, UrlHandlerConfig.class);
        resolvingUrlHandler = AdaptTo.notNull(resource, UrlHandler.class);
    }

    // if target page is a redirect or integrator page recursively resolve link to which the redirect points to
    // (skip this redirection if edit mode is active)
    if (targetPage != null
            && (linkHandlerConfig.isRedirect(targetPage) || resolvingUrlHandlerConfig.isIntegrator(targetPage))
            && wcmMode != WCMMode.EDIT) {
        return recursiveResolveLink(targetPage, link);
    }

    // build link url
    String linkUrl = null;
    if (targetPage != null) {
        link.setTargetPage(targetPage);

        LinkArgs linkArgs = linkRequest.getLinkArgs();
        String selectors = linkArgs.getSelectors();
        String fileExtension = StringUtils.defaultString(linkArgs.getExtension(), FileExtension.HTML);
        String suffix = linkArgs.getSuffix();
        String queryString = linkArgs.getQueryString();
        String fragment = linkArgs.getFragment();

        // optionally override query parameters and fragment from link resource
        queryString = props.get(LinkNameConstants.PN_LINK_QUERY_PARAM, queryString);
        fragment = props.get(LinkNameConstants.PN_LINK_FRAGMENT, fragment);

        // build link url
        linkUrl = resolvingUrlHandler.get(targetPage).selectors(selectors).extension(fileExtension)
                .suffix(suffix).queryString(queryString).fragment(fragment).urlMode(linkArgs.getUrlMode())
                .buildExternalLinkUrl(targetPage);
    }

    // mark link as invalid if a reference was set that could not be resolved
    if (linkUrl == null && referenceSet) {
        link.setLinkReferenceInvalid(true);
    }

    // set link url
    link.setUrl(linkUrl);

    return link;
}

From source file:com.navercorp.pinpoint.web.vo.callstacks.RecordFactory.java

private String getArgumentFromParameter(String argument) {
    return StringUtils.defaultString(argument, "null");
}

From source file:io.wcm.config.editor.impl.EditorParameterProvider.java

private void addLabel(JSONObject jsonParameter, Parameter parameter) throws JSONException {
    ValueMap properties = parameter.getProperties();
    jsonParameter.put(EditorProperties.LABEL, StringUtils
            .defaultString(properties.get(EditorProperties.LABEL, String.class), parameter.getName()));
}

From source file:com.thinkbiganalytics.discovery.parsers.csv.CSVFileSchemaParser.java

private DefaultFileSchema populateSchema(CSVParser parser) {
    DefaultFileSchema fileSchema = new DefaultFileSchema();
    int i = 0;//from w  w w.  j  av a  2s.c  o  m
    ArrayList<Field> fields = new ArrayList<>();
    for (CSVRecord record : parser) {
        if (i > 9) {
            break;
        }
        int size = record.size();
        for (int j = 0; j < size; j++) {
            DefaultField field = null;
            if (i == 0) {
                field = new DefaultField();
                if (headerRow) {
                    field.setName(record.get(j));
                } else {
                    field.setName("Col_" + (j + 1));
                }
                fields.add(field);
            } else {
                try {
                    field = (DefaultField) fields.get(j);
                    field.getSampleValues().add(StringUtils.defaultString(record.get(j), ""));

                } catch (IndexOutOfBoundsException e) {
                    LOG.warn("Sample file has potential sparse column problem at row [?] field [?]", i + 1,
                            j + 1);
                }
            }
        }
        i++;
    }
    fileSchema.setFields(fields);
    return fileSchema;
}

From source file:com.xpn.xwiki.pdf.impl.PdfURLFactory.java

/**
 * Store the requested attachment on the filesystem and return a {@code file://} URL where FOP can access that file.
 * /*from ww w. j a  v a2s  .  c o m*/
 * @param wiki the name of the owner document's wiki
 * @param space the name of the owner document's space
 * @param name the name of the owner document
 * @param filename the name of the attachment
 * @param revision an optional attachment version
 * @param context the current request context
 * @return a {@code file://} URL where the attachment has been stored
 * @throws Exception if the attachment can't be retrieved from the database and stored on the filesystem
 */
private URL getURL(String wiki, String space, String name, String filename, String revision,
        XWikiContext context) throws Exception {
    Map<String, File> usedFiles = getFileMapping(context);
    String key = getAttachmentKey(space, name, filename, revision);
    if (!usedFiles.containsKey(key)) {
        File file = getTemporaryFile(key, context);
        XWikiDocument doc = context.getWiki().getDocument(
                new DocumentReference(StringUtils.defaultString(wiki, context.getDatabase()), space, name),
                context);
        XWikiAttachment attachment = doc.getAttachment(filename);
        if (StringUtils.isNotEmpty(revision)) {
            attachment = attachment.getAttachmentRevision(revision, context);
        }
        FileOutputStream fos = new FileOutputStream(file);
        IOUtils.copy(attachment.getContentInputStream(context), fos);
        fos.close();
        usedFiles.put(key, file);
    }
    return usedFiles.get(key).toURI().toURL();
}

From source file:com.sonicle.webtop.vfs.PublicService.java

@Override
public void processDefaultAction(HttpServletRequest request, HttpServletResponse response) throws Exception {
    PublicPath path = new PublicPath(request.getPathInfo());
    WebTopSession wts = getWts();// ww w.ja  v a  2  s .c om

    try {
        try {
            if (path.getContext().equals(PUBPATH_CONTEXT_LINK)) {
                FileUrlPath fileUrlPath = new FileUrlPath(path.getRemainingPath());

                SharingLink link = null;
                if (!StringUtils.isBlank(fileUrlPath.getLinkId())) {
                    link = manager.getSharingLink(fileUrlPath.getLinkId());
                }

                if (link == null) { // Link not found
                    logger.trace("Link not found [{}]", fileUrlPath.getLinkId());
                    writeErrorPage(request, response, wts, "linknotfound");

                } else if (link.isExpired(DateTimeUtils.now())) { // Link expired
                    logger.trace("Link expired [{}]", fileUrlPath.getLinkId());
                    writeErrorPage(request, response, wts, "linkexpired");

                } else if (!isLinkAuthorized(link)) { // Link not authorized
                    writeLinkPage(request, response, wts, "Authorize", link);

                } else if (link.getType().equals(SharingLink.TYPE_DOWNLOAD)) {
                    if (PathUtils.isFolder(link.getFilePath())) {
                        Integer dl = ServletUtils.getIntParameter(request, "dl", 0);

                        if (dl == 1) { // Download file request
                            String fileId = ServletUtils.getStringParameter(request, "fileId", true);

                            String outName;
                            if (PathUtils.isFolder(fileId)) {
                                if (PathUtils.isRootFolder(fileId)) {
                                    outName = StringUtils.defaultString(
                                            PathUtils.getFileName(link.getFilePath()), link.getLinkId());
                                } else {
                                    outName = PathUtils.getFileName(fileId);
                                }
                                outName += ".zip";
                            } else {
                                outName = PathUtils.getFileName(fileId);
                            }

                            String servicePublicUrl = WT.getServicePublicUrl(wts.getProfileDomainId(),
                                    SERVICE_ID);
                            String url = buildPublicLinkPathGetUrl(servicePublicUrl, link, outName, fileId);
                            ServletUtils.setLocationHeader(response, url);
                            response.setStatus(HttpServletResponse.SC_FOUND);

                        } else if (fileUrlPath.isGet()) { // Real binary stream
                            String p = ServletUtils.getStringParameter(request, "p", true);

                            String filePath = PathUtils.concatPaths(link.getFilePath(), p);
                            writeStoreFile(response, link.getStoreId(), filePath, fileUrlPath.getOutFileName());
                            manager.notifySharingLinkUsage(link.getLinkId(), filePath, wts.getRemoteIP(),
                                    wts.getPlainUserAgent());

                        } else {
                            writeLinkPage(request, response, wts, "DownloadLink", link);
                        }

                    } else {
                        Integer raw = ServletUtils.getIntParameter(request, "raw", 0);
                        if (raw == 1) { // Link points directly to raw data (no preview)
                            String servicePublicUrl = WT.getServicePublicUrl(wts.getProfileDomainId(),
                                    SERVICE_ID);
                            String url = VfsManager.buildLinkPublicGetUrl(servicePublicUrl, link);
                            ServletUtils.setLocationHeader(response, url);
                            response.setStatus(HttpServletResponse.SC_FOUND);

                        } else if (fileUrlPath.isGet()) { // Real binary stream
                            writeStoreFile(response, link.getStoreId(), link.getFilePath(),
                                    fileUrlPath.getOutFileName());
                            manager.notifySharingLinkUsage(link.getLinkId(), link.getFilePath(),
                                    wts.getRemoteIP(), wts.getPlainUserAgent());

                        } else {
                            logger.trace("Invalid request");
                            writeErrorPage(request, response, wts, "badrequest");
                        }
                    }

                } else if (link.getType().equals(SharingLink.TYPE_UPLOAD)) {
                    Integer maxUpload = WT.getCoreServiceSettings(SERVICE_ID).getUploadMaxFileSize();
                    VfsUserSettings us = new VfsUserSettings(SERVICE_ID, link.getProfileId());

                    JsWTSPublic.Vars vars = new JsWTSPublic.Vars();
                    vars.put("uploadMaxFileSize",
                            LangUtils.coalesce(us.getPublicUploadMaxFileSize(), maxUpload));
                    writeLinkPage(request, response, wts, "UploadLink", link, vars);
                }

            } else {
                logger.trace("Invalid context [{}]", path.getContext());
                writeErrorPage(request, response, wts, "badrequest");
            }

        } catch (Exception ex) {
            writeErrorPage(request, response, wts, "badrequest");
            //logger.trace("Error", t);
        }
    } catch (Throwable t) {
        logger.error("Unexpected error", t);
    }
}