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) 

Source Link

Document

Returns either the passed in String, or if the String is null , an empty String ("").

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

Usage

From source file:com.discovery.darchrow.net.ParamUtil.java

/**
 * ??.//from w  w w. j av a2  s  .  com
 * 
 * <p>
 * ,??? {@code paramName=name}, {@code paramValues  zhangfei,guanyu},{@code name=zhangfei&name=guanyu}
 * </p>
 * 
 * <h3>?:</h3>
 * <blockquote>
 * <ol>
 * <li>paramName ?  {@link StringUtils#defaultString(String)}???</li>
 * </ol>
 * </blockquote>
 *
 * @param paramName
 *            ???
 * @param paramValues
 *            ?
 * @return the string
 * @see java.lang.AbstractStringBuilder#append(String)
 * @see org.apache.commons.lang3.StringUtils#defaultString(String)
 * @see "org.springframework.web.servlet.view.RedirectView#appendQueryProperties(StringBuilder,Map, String)"
 * @since 1.4.0
 */
private static String joinParamNameAndValues(String paramName, String[] paramValues) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0, j = paramValues.length; i < j; ++i) {
        //?: value null ,StringBuilder "null" , ?  java.lang.AbstractStringBuilder#append(String)
        sb.append(StringUtils.defaultString(paramName)).append("=")
                .append(StringUtils.defaultString(paramValues[i]));
        if (i != j - 1) {// ?& ?
            sb.append(URIComponents.AMPERSAND);
        }
    }
    return sb.toString();
}

From source file:com.mirth.connect.server.controllers.DefaultConfigurationController.java

@Override
public Properties getPropertiesForGroup(String category) {
    logger.debug("retrieving properties: category=" + category);
    Properties properties = new Properties();

    try {//from   w ww.  ja va  2 s  .c om
        List<KeyValuePair> result = SqlConfig.getSqlSessionManager()
                .selectList("Configuration.selectPropertiesForCategory", category);

        for (KeyValuePair pair : result) {
            properties.setProperty(pair.getKey(), StringUtils.defaultString(pair.getValue()));
        }
    } catch (Exception e) {
        logger.error("Could not retrieve properties: category=" + category, e);
    }

    return properties;
}

From source file:io.wcm.handler.url.impl.UrlHandlerImplTest.java

/**
 * Simulate mapping://from  w w w. j ava 2s  .  c  o  m
 * - /content/unittest/de_test/brand/de -> /de
 * - /content/* -> /*
 */
private static MockSlingHttpServletRequest applySimpleMapping(SlingHttpServletRequest request) {
    ResourceResolver spyResolver = spy(request.getResourceResolver());
    Answer<String> mappingAnswer = new Answer<String>() {
        @Override
        public String answer(InvocationOnMock invocation) {
            SlingHttpServletRequest mapRequest;
            String path;
            if (invocation.getArguments()[0] instanceof SlingHttpServletRequest) {
                mapRequest = (SlingHttpServletRequest) invocation.getArguments()[0];
                path = (String) invocation.getArguments()[1];
            } else {
                mapRequest = null;
                path = (String) invocation.getArguments()[0];
            }
            if (StringUtils.startsWith(path, "/content/unittest/de_test/brand/")) {
                path = "/" + StringUtils.substringAfter(path, "/content/unittest/de_test/brand/");
            }
            if (StringUtils.startsWith(path, "/content/")) {
                path = "/" + StringUtils.substringAfter(path, "/content/");
            }
            if (mapRequest != null) {
                path = StringUtils.defaultString(mapRequest.getContextPath()) + path;
            }
            path = Externalizer.mangleNamespaces(path);
            try {
                return URLEncoder.encode(path, CharEncoding.UTF_8);
            } catch (UnsupportedEncodingException ex) {
                throw new RuntimeException(ex);
            }
        }
    };
    when(spyResolver.map(anyString())).thenAnswer(mappingAnswer);
    when(spyResolver.map(any(SlingHttpServletRequest.class), anyString())).thenAnswer(mappingAnswer);
    MockSlingHttpServletRequest newRequest = new MockSlingHttpServletRequest(spyResolver);
    newRequest.setResource(request.getResource());
    newRequest.setContextPath(request.getContextPath());
    return newRequest;
}

From source file:com.sonicle.webtop.core.app.WebTopApp.java

public void sendEmail(javax.mail.Session session, boolean rich, InternetAddress from, InternetAddress[] to,
        InternetAddress[] cc, InternetAddress[] bcc, String subject, String body, MimeBodyPart[] parts)
        throws MessagingException {

    //Session session=getGlobalMailSession(pid.getDomainId());
    MimeMessage msg = new MimeMessage(session);
    try {//  w ww . j a va 2 s  .c om
        subject = MimeUtility.encodeText(subject);
    } catch (Exception exc) {
    }
    msg.setSubject(subject);
    msg.addFrom(new InternetAddress[] { from });

    if (to != null)
        for (InternetAddress addr : to) {
            msg.addRecipient(Message.RecipientType.TO, addr);
        }

    if (cc != null)
        for (InternetAddress addr : cc) {
            msg.addRecipient(Message.RecipientType.CC, addr);
        }

    if (bcc != null)
        for (InternetAddress addr : bcc) {
            msg.addRecipient(Message.RecipientType.BCC, addr);
        }

    body = StringUtils.defaultString(body);
    MimeMultipart mp = new MimeMultipart("mixed");
    if (rich) {
        MimeMultipart alternative = new MimeMultipart("alternative");
        MimeBodyPart mbp2 = new MimeBodyPart();
        mbp2.setContent(body, MailUtils.buildPartContentType("text/html", "UTF-8"));
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setContent(MailUtils.htmlToText(MailUtils.htmlunescapesource(body)),
                MailUtils.buildPartContentType("text/plain", "UTF-8"));
        alternative.addBodyPart(mbp1);
        alternative.addBodyPart(mbp2);
        MimeBodyPart altbody = new MimeBodyPart();
        altbody.setContent(alternative);
        mp.addBodyPart(altbody);
    } else {
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setContent(body, MailUtils.buildPartContentType("text/plain", "UTF-8"));
        mp.addBodyPart(mbp1);
    }

    if (parts != null) {
        for (MimeBodyPart part : parts)
            mp.addBodyPart(part);
    }

    msg.setContent(mp);

    msg.setSentDate(new java.util.Date());

    Transport.send(msg);
}

From source file:com.sonicle.webtop.core.app.WebTopApp.java

public void sendEmail(javax.mail.Session session, boolean rich, InternetAddress from,
        Collection<InternetAddress> to, Collection<InternetAddress> cc, Collection<InternetAddress> bcc,
        String subject, String body, Collection<MimeBodyPart> parts) throws MessagingException {
    MimeMultipart mp = new MimeMultipart("mixed");
    body = StringUtils.defaultString(body);

    // Adds text parts from passed body
    if (rich) {//from w ww.  j av a2s  .c o m
        MimeMultipart alternative = new MimeMultipart("alternative");
        MimeBodyPart mbp2 = new MimeBodyPart();
        mbp2.setContent(body, MailUtils.buildPartContentType("text/html", "UTF-8"));
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setContent(MailUtils.htmlToText(MailUtils.htmlunescapesource(body)),
                MailUtils.buildPartContentType("text/plain", "UTF-8"));
        alternative.addBodyPart(mbp1);
        alternative.addBodyPart(mbp2);
        MimeBodyPart altbody = new MimeBodyPart();
        altbody.setContent(alternative);
        mp.addBodyPart(altbody);
    } else {
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setContent(body, MailUtils.buildPartContentType("text/plain", "UTF-8"));
        mp.addBodyPart(mbp1);
    }

    // Adds remaining parts to the mixed one
    if (parts != null) {
        for (MimeBodyPart p : parts) {
            mp.addBodyPart(p);
        }
    }

    sendEmail(session, from, to, cc, bcc, subject, mp);
}

From source file:gtu._work.ui.DirectoryCompareUI.java

/**
 * TODO//from ww  w  .  java2 s . c  o m
 */
private void totalScanFiles(EventObject event) {
    try {
        // ?
        final Map<String, Object> searchTextMap = new HashMap<String, Object>();
        if (event != null && event.getSource() == searchText && //
                StringUtils.isNotBlank(searchText.getText()) && ((KeyEvent) event).getKeyCode() != 10)//
        {
            return;
        } else {
            String text = searchText.getText();
            Matcher matcher = SEARCHTEXTPATTERN.matcher(text);
            if (matcher.matches()) {
                final String left = StringUtils.trim(matcher.group(1));
                String operator = StringUtils.trim(matcher.group(2));
                String condition = StringUtils.trim(matcher.group(3));
                System.out.println("left = " + left);
                System.out.println("operator = " + operator);
                System.out.println("condition = " + condition);

                SearchTextEnum currentSearchType = null;
                for (SearchTextEnum e : SearchTextEnum.values()) {
                    if (StringUtils.equals(e.name(), left)) {
                        currentSearchType = e;
                        break;
                    }
                }
                Validate.notNull(currentSearchType, "??? : " + left);

                searchTextMap.put("currentSearchType", currentSearchType);
                searchTextMap.put("operator", operator);
                searchTextMap.put("condition", condition);
            } else if (event != null && event instanceof KeyEvent && ((KeyEvent) event).getKeyCode() == 10) {
                JCommonUtil._jOptionPane_showMessageDialog_error(
                        "?:" + SEARCHTEXTPATTERN.pattern());
            }
        }

        // ?
        final List<DiffMergeStatus> chkList = new ArrayList<DiffMergeStatus>();
        A: for (DiffMergeStatus diff2 : DiffMergeStatus.values()) {
            for (int ii = 0; ii < diffMergeChkBox.length; ii++) {
                if (StringUtils.equals(diffMergeChkBox[ii].getText(), diff2.toString())
                        && diffMergeChkBox[ii].isSelected()) {
                    chkList.add(diff2);
                    continue A;
                }
            }
        }

        // ???
        String extensionName = (String) extensionNameComboBox.getSelectedItem();
        SingletonMap extensionNameMessageMap = new SingletonMap();
        final SingletonMap extensionNameMap = new SingletonMap();
        if (StringUtils.equals(EXTENSION_CUSTOM, extensionName)) {
            String result = JCommonUtil._jOptionPane_showInputDialog("???",
                    EXTENSION_ALL);
            if (StringUtils.isNotBlank(result)) {
                String[] arry = result.split(",", -1);
                extensionNameMap.setValue(arry);
                extensionNameMessageMap.setValue(Arrays.toString(arry));
            } else {
                extensionNameMap.setValue(new String[] { EXTENSION_ALL });
                extensionNameMessageMap.setValue(EXTENSION_ALL);
            }
        } else {
            extensionNameMap.setValue(new String[] { extensionName });
            extensionNameMessageMap.setValue(extensionName);
        }
        if (extensionNameCache == null) {
            extensionNameCache = new ExtensionNameCache();
            extensionNameCache.extensionNameMap = extensionNameMap;
            extensionNameCache.extensionNameMessageMap = extensionNameMessageMap;
        }
        if (event != null && event.getSource() != extensionNameComboBox) {
            extensionNameMap.setValue(extensionNameCache.extensionNameMap.getValue());
            extensionNameMessageMap.setValue(extensionNameCache.extensionNameMessageMap.getValue());
        }

        FileSearch search = new FileSearch(DirectoryCompareUI.this) {
            @Override
            boolean isMatch(InfoObj infoObj) {
                boolean searchTextResult = true;
                if (searchTextMap.containsKey("currentSearchType") && searchTextMap.containsKey("operator")
                        && searchTextMap.containsKey("condition")) {
                    SearchTextEnum currentSearchType = (SearchTextEnum) searchTextMap.get("currentSearchType");
                    String operator = (String) searchTextMap.get("operator");
                    String condition = (String) searchTextMap.get("condition");
                    searchTextResult = currentSearchType.isMatch(infoObj, operator, condition);
                }
                boolean extensionNameResult = true;
                if (extensionNameMap.getValue() != null) {
                    String[] extensionNameArray = (String[]) extensionNameMap.getValue();
                    if (StringUtils.indexOfAny(EXTENSION_ALL, extensionNameArray) == -1) {
                        boolean findOk = false;
                        for (String extension : extensionNameArray) {
                            if ((infoObj.mainFile.isFile()
                                    && infoObj.mainFile.getName().toLowerCase().endsWith(extension))
                                    || (infoObj.compareToFile.isFile() && infoObj.compareToFile.getName()
                                            .toLowerCase().endsWith(extension))) {
                                findOk = true;
                                break;
                            }
                        }
                        if (!findOk) {
                            extensionNameResult = false;
                        }
                    }
                }

                boolean chkListResult = chkList.contains(infoObj.status2);
                return chkListResult && extensionNameResult && searchTextResult;
            }
        };
        search.execute(DirectoryCompareUI.this, //
                "?[?:" + StringUtils.defaultString(searchText.getText()) + "][??:"
                        + extensionNameMessageMap.getValue() + "][:" + chkList + "]");
    } catch (Exception ex) {
        JCommonUtil.handleException(ex, false);
    }
}

From source file:com.xpn.xwiki.XWiki.java

public void saveDocument(XWikiDocument doc, String comment, boolean isMinorEdit, XWikiContext context)
        throws XWikiException {
    String server = null, database = null;
    try {/*  w  w  w. j  a v  a  2s  .  co m*/
        server = doc.getDocumentReference().getWikiReference().getName();

        if (server != null) {
            database = context.getDatabase();
            context.setDatabase(server);
        }

        // Setting comment & minor edit before saving
        doc.setComment(StringUtils.defaultString(comment));
        doc.setMinorEdit(isMinorEdit);

        // We need to save the original document since saveXWikiDoc() will reset it and we
        // need that original document for the notification below.
        XWikiDocument originalDocument = doc.getOriginalDocument();
        // Always use an originalDocument, to provide a consistent behavior. The cases where
        // originalDocument is null are rare (specifically when the XWikiDocument object is
        // manually constructed, and not obtained using the API).
        if (originalDocument == null) {
            originalDocument = new XWikiDocument(doc.getDocumentReference());
        }

        ObservationManager om = Utils.getComponent(ObservationManager.class);

        // Notify listeners about the document about to be created or updated

        // Note that for the moment the event being send is a bridge event, as we are still passing around
        // an XWikiDocument as source and an XWikiContext as data.

        if (om != null) {
            if (originalDocument.isNew()) {
                om.notify(new DocumentCreatingEvent(doc.getDocumentReference()), doc, context);
            } else {
                om.notify(new DocumentUpdatingEvent(doc.getDocumentReference()), doc, context);
            }
        }

        getStore().saveXWikiDoc(doc, context);

        // Since the store#saveXWikiDoc resets originalDocument, we need to temporarily put it
        // back to send notifications.
        XWikiDocument newOriginal = doc.getOriginalDocument();

        try {
            doc.setOriginalDocument(originalDocument);

            // Notify listeners about the document having been created or updated

            // First the legacy notification mechanism

            // Then the new observation module
            // Note that for the moment the event being send is a bridge event, as we are still passing around
            // an XWikiDocument as source and an XWikiContext as data.
            // The old version is made available using doc.getOriginalDocument()

            if (om != null) {
                if (originalDocument.isNew()) {
                    om.notify(new DocumentCreatedEvent(doc.getDocumentReference()), doc, context);
                } else {
                    om.notify(new DocumentUpdatedEvent(doc.getDocumentReference()), doc, context);
                }
            }
        } catch (Exception ex) {
            LOGGER.error(
                    "Failed to send document save notification for document ["
                            + this.defaultEntityReferenceSerializer.serialize(doc.getDocumentReference()) + "]",
                    ex);
        } finally {
            doc.setOriginalDocument(newOriginal);
        }
    } finally {
        if ((server != null) && (database != null)) {
            context.setDatabase(database);
        }
    }
}

From source file:lineage2.gameserver.model.Creature.java

/**
 * Method getName.
 * @return String
 */
@Override
public String getName() {
    return StringUtils.defaultString(_name);
}

From source file:lineage2.gameserver.model.Creature.java

/**
 * Method getTitle.
 * @return String
 */
public String getTitle() {
    return StringUtils.defaultString(_title);
}

From source file:com.mirth.connect.client.ui.codetemplate.CodeTemplatePanel.java

private void printTreeTable(MutableTreeTableNode node, StringBuilder builder, int depth) {
    builder.append(StringUtils.repeat('\t', depth));
    if (node instanceof CodeTemplateLibraryTreeTableNode) {
        CodeTemplateLibraryTreeTableNode libraryNode = (CodeTemplateLibraryTreeTableNode) node;
        builder.append(libraryNode.getLibrary().getName()).append("\t\t\t\t")
                .append(libraryNode.getLibrary().getDescription().replaceAll("\r\n|\r|\n", " "));
    } else if (node instanceof CodeTemplateTreeTableNode) {
        CodeTemplateTreeTableNode codeTemplateNode = (CodeTemplateTreeTableNode) node;
        builder.append(codeTemplateNode.getCodeTemplate().getName()).append("\t\t\t\t")
                .append(StringUtils.defaultString(codeTemplateNode.getCodeTemplate().getDescription())
                        .replaceAll("\r\n|\r|\n", " "));
    }// www .java2  s. c o  m
    builder.append('\n');

    for (Enumeration<? extends MutableTreeTableNode> children = node.children(); children.hasMoreElements();) {
        printTreeTable(children.nextElement(), builder, depth + 1);
    }
}