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

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

Introduction

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

Prototype

public static String defaultString(String str, String defaultStr) 

Source Link

Document

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

Usage

From source file:io.wcm.tooling.netbeans.sightly.completion.classLookup.MemberLookupCompleter.java

/**
 * This method tries to find the class which is defined for the given filter and returns a set with all methods and fields of the class
 *
 * @param variableName//w  w  w .  j  a va 2 s  .c o m
 * @param text
 * @param document
 * @return Set of methods and fields, never null
 */
private Set<String> resolveClass(String variableName, String text, Document document) {
    Set<String> items = new LinkedHashSet<>();
    FileObject fo = getFileObject(document);
    ClassPath sourcePath = ClassPath.getClassPath(fo, ClassPath.SOURCE);
    ClassPath compilePath = ClassPath.getClassPath(fo, ClassPath.COMPILE);
    ClassPath bootPath = ClassPath.getClassPath(fo, ClassPath.BOOT);
    if (sourcePath == null) {
        return items;
    }
    ClassPath cp = ClassPathSupport.createProxyClassPath(sourcePath, compilePath, bootPath);
    MemberLookupResolver resolver = new MemberLookupResolver(text, cp);
    Set<MemberLookupResult> results = resolver.performMemberLookup(
            StringUtils.defaultString(StringUtils.substringBeforeLast(variableName, "."), variableName));
    for (MemberLookupResult result : results) {
        Matcher m = GETTER_PATTERN.matcher(result.getMethodName());
        if (m.matches() && m.groupCount() >= 2) {
            items.add(result.getVariableName() + "." + WordUtils.uncapitalize(m.group(2)));
        } else {
            items.add(result.getVariableName() + "." + WordUtils.uncapitalize(result.getMethodName()));
        }
    }
    return items;
}

From source file:com.baasbox.db.Evolution_0_8_4.java

/***
 * creates new records for new push settings and migrates the old ones into the profile n.1
 * @param db/*from  w w  w  .  j a v a 2 s.c om*/
 */
private void multiPushProfileSettings(ODatabaseRecordTx db) {
    IndexPushConfiguration idx;
    try {
        idx = new IndexPushConfiguration();
    } catch (IndexNotFoundException e) {
        throw new RuntimeException(e);
    }

    //load the old settings
    String sandbox = null;
    if (idx.get("push.sandbox.enable") == null)
        sandbox = "true";
    else
        sandbox = idx.get("push.sandbox.enable").toString();
    //String sandbox = StringUtils.defaultString(()idx.get("push.sandbox.enable"),"true");
    String appleTimeout = null;
    if (idx.get("push.apple.timeout") == null)
        appleTimeout = "0";
    else
        appleTimeout = idx.get("push.apple.timeout").toString();

    //StringUtils.defaultString((String)idx.get("push.apple.timeout"),null);

    String sandboxAndroidApiKey = StringUtils.defaultString((String) idx.get("sandbox.android.api.key"), null);
    String sandBoxIosCertificatePassword = StringUtils
            .defaultString((String) idx.get("sandbox.ios.certificate.password"), null);

    String prodAndroidApiKey = StringUtils.defaultString((String) idx.get("production.android.api.key"), null);
    String prodBoxIosCertificatePassword = StringUtils
            .defaultString((String) idx.get("production.ios.certificate.password"), null);

    //Houston we have a problem. Here we have to handle the iOS certificates that are files!
    Object sandBoxIosCertificate = getValueAsFileContainer(idx.get("sandbox.ios.certificate"));
    Object prodBoxIosCertificate = getValueAsFileContainer(idx.get("production.ios.certificate"));

    try {
        //set the new profile1 settings
        Push.PROFILE1_PRODUCTION_ANDROID_API_KEY._setValue(prodAndroidApiKey);
        if (prodBoxIosCertificate != null)
            Push.PROFILE1_PRODUCTION_IOS_CERTIFICATE._setValue(prodBoxIosCertificate);
        Push.PROFILE1_PRODUCTION_IOS_CERTIFICATE_PASSWORD._setValue(prodBoxIosCertificatePassword);
        Push.PROFILE1_PUSH_APPLE_TIMEOUT._setValue(appleTimeout);
        Push.PROFILE1_SANDBOX_ANDROID_API_KEY._setValue(sandboxAndroidApiKey);
        if (sandBoxIosCertificate != null)
            Push.PROFILE1_SANDBOX_IOS_CERTIFICATE._setValue(sandBoxIosCertificate);
        Push.PROFILE1_SANDBOX_IOS_CERTIFICATE_PASSWORD._setValue(sandBoxIosCertificatePassword);
        Push.PROFILE1_PUSH_SANDBOX_ENABLE._setValue(sandbox);

        Push.PROFILE1_PUSH_PROFILE_ENABLE.setValue(false);
        try {
            Push.PROFILE1_PUSH_PROFILE_ENABLE.setValue(true);
        } catch (Exception e) {
            Push.PROFILE1_PUSH_PROFILE_ENABLE.setValue(false);
        }

        //disable other profiles
        Push.PROFILE2_PUSH_PROFILE_ENABLE._setValue(false);
        Push.PROFILE3_PUSH_PROFILE_ENABLE._setValue(false);

        //default value other profiles
        Push.PROFILE2_PUSH_SANDBOX_ENABLE._setValue(true);
        Push.PROFILE2_PRODUCTION_ANDROID_API_KEY._setValue("");
        //Push.PROFILE2_PRODUCTION_IOS_CERTIFICATE
        Push.PROFILE2_PRODUCTION_IOS_CERTIFICATE_PASSWORD._setValue("");
        Push.PROFILE2_PUSH_APPLE_TIMEOUT._setValue(0);
        Push.PROFILE2_SANDBOX_ANDROID_API_KEY._setValue("");
        //Push.PROFILE2_SANDBOX_IOS_CERTIFICATE
        Push.PROFILE2_SANDBOX_IOS_CERTIFICATE_PASSWORD._setValue("");

        Push.PROFILE3_PUSH_SANDBOX_ENABLE._setValue(true);
        Push.PROFILE3_PRODUCTION_ANDROID_API_KEY._setValue("");
        //Push.PROFILE3_PRODUCTION_IOS_CERTIFICATE
        Push.PROFILE3_PRODUCTION_IOS_CERTIFICATE_PASSWORD._setValue("");
        Push.PROFILE3_PUSH_APPLE_TIMEOUT._setValue(0);
        Push.PROFILE3_SANDBOX_ANDROID_API_KEY._setValue("");
        //Push.PROFILE3_SANDBOX_IOS_CERTIFICATE
        Push.PROFILE3_SANDBOX_IOS_CERTIFICATE_PASSWORD._setValue("");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.flexive.shared.ContentLinkFormatter.java

protected String format(String formatString, FxPaths.Item item) {
    final String result = format(StringUtils.defaultString(formatString, DEFAULT_ITEM),
            new FxPK(item.getReferenceId())).replace("%{nodeId}", String.valueOf(item.getNodeId()));
    return result.replace("%{caption20}", StringUtils.abbreviate(item.getCaption(), MAX_CAPTION_LEN))
            .replace("%{caption}", item.getCaption());
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.nettoExport.SpreadsheetReportColumnStructure.java

/**{@inheritDoc}**/
@Override//from   w w  w  .j  a v a  2  s  .  c  o m
public String resolveValue(Object bean) {

    // Use same logic like in ResultPageTile.jsp:

    BeanWrapperImpl wrapper = new BeanWrapperImpl(false);
    wrapper.setWrappedInstance(bean);
    Object resolvedObject = wrapper.getPropertyValue(beanPath);

    switch (colType) {

    case ATTRIBUTE:
        return resolveAttributeValue(resolvedObject);

    case LIST:
        if (resolvedObject instanceof Iterable<?>) {
            List<String> valuesList = Lists.newArrayList();
            for (Object obj : (Iterable<?>) resolvedObject) {
                valuesList.add(String.valueOf(obj));
            }
            if (valuesList.size() > 0) {
                return Joiner.on(MULTIVALUE_SEPARATOR).join(valuesList);
            }
        }
        break;

    case SEAL:
        if (resolvedObject instanceof SealState) {
            SealState sealState = (SealState) resolvedObject;
            return MessageAccess.getString(sealState.toString());
        }
        break;

    case AVAILABLE_FOR_INTERFACES:
        if (resolvedObject instanceof Boolean) {
            boolean availableForInterfaces = ((Boolean) resolvedObject).booleanValue();
            if (availableForInterfaces) {
                return MessageAccess.getString("global.yes");
            } else {
                return MessageAccess.getString("global.no");
            }
        }
        break;

    case DIRECTION:
        if (resolvedObject instanceof String) {
            Direction directionForValue = Direction.getDirectionForValue(String.valueOf(resolvedObject));
            if (directionForValue != null) {
                return SHOW_DIRECTION_ARROWS ? directionForValue.toString() : directionForValue.name();
            }
        }
        return StringUtils.defaultString(String.valueOf(resolvedObject), NOT_FOUND);

    case DATE:
        if (resolvedObject instanceof Date) {
            return getDateFormat().format((Date) resolvedObject);
        }
        break;

    case TYPE_OF_STATUS:
        if (resolvedObject instanceof de.iteratec.iteraplan.model.InformationSystemRelease.TypeOfStatus) {
            de.iteratec.iteraplan.model.InformationSystemRelease.TypeOfStatus statusISR = (de.iteratec.iteraplan.model.InformationSystemRelease.TypeOfStatus) resolvedObject;
            return MessageAccess.getString(statusISR.toString());
        } else if (resolvedObject instanceof de.iteratec.iteraplan.model.TechnicalComponentRelease.TypeOfStatus) {
            de.iteratec.iteraplan.model.TechnicalComponentRelease.TypeOfStatus statusTCR = (de.iteratec.iteraplan.model.TechnicalComponentRelease.TypeOfStatus) resolvedObject;
            return MessageAccess.getString(statusTCR.toString());
        }
        break;

    default:
        if (resolvedObject != null) {
            return String.valueOf(resolvedObject);
        }
        break;
    }
    return NOT_FOUND;
}

From source file:com.frameworkset.orm.engine.model.Domain.java

/**
 * Replaces the size if the new value is not null.
 * /* w  ww  .jav a2s .  co  m*/
 * @param value The size to set.
 */
public void replaceSize(String value) {
    this.size = StringUtils.defaultString(value, getSize());
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.nettoExport.OverviewPageColumnStructure.java

/**{@inheritDoc}**/
@Override//ww w .  jav  a 2 s.  c o m
public Object resolveValue(Object bean) {

    // Same logic like in Results.jsp here:

    BeanWrapperImpl wrapper = new BeanWrapperImpl(false);
    wrapper.setWrappedInstance(bean);
    Object resolvedObject = wrapper.getPropertyValue(columnDefinition.getBeanPropertyPath());

    AttributeType attrType = columnDefinition.getAttributeType();
    boolean multiValueType = (attrType instanceof MultiassignementType)
            && ((MultiassignementType) attrType).isMultiassignmenttype();

    if (attrType != null) {

        if (resolvedObject instanceof List<?>) {
            List<?> allValues = (List<?>) resolvedObject;

            if (multiValueType) {
                List<String> attributeValues = Lists.newArrayList();
                for (Object attrObj : allValues) {
                    if (attrObj instanceof DateAV) {
                        Date dateValue = ((DateAV) attrObj).getValue();
                        attributeValues.add(dateValue.toString());
                    } else if (attrObj instanceof ResponsibilityAV) {
                        attributeValues.add(((ResponsibilityAV) attrObj).getName());
                    } else {
                        attributeValues.add(((AttributeValue) attrObj).getValueString());
                    }
                }

                return Joiner.on(MULTIVALUE_SEPARATOR).join(attributeValues);
            } else {
                if (allValues == null || allValues.size() == 0) {
                    return NOT_FOUND;
                }

                Object singleValue = allValues.get(0);
                if (singleValue instanceof ResponsibilityAV) {
                    return ((ResponsibilityAV) singleValue).getName();
                } else {
                    return ((AttributeValue) singleValue).getValue();
                }
            }
        }

    } else {
        if ("direction".equals(columnDefinition.getModelPath()) && (resolvedObject instanceof String)) {
            Direction directionForValue = Direction.getDirectionForValue(String.valueOf(resolvedObject));
            if (directionForValue != null) {
                return SHOW_DIRECTION_ARROWS ? directionForValue.toString() : directionForValue.name();
            }
        }

        if (columnDefinition.isInternationalized()) {
            return MessageAccess.getString(String.valueOf(resolvedObject));
        }

        return String.valueOf(resolvedObject);
    }

    return StringUtils.defaultString(String.valueOf(resolvedObject), NOT_FOUND);
}

From source file:gtu._work.etc.GoogleContactUI.java

void googleTableMouseClicked(MouseEvent evt) {
    try {//from   w  ww. j  a  v  a  2 s .  com
        JPopupMenuUtil popupUtil = JPopupMenuUtil.newInstance(googleTable).applyEvent(evt);

        //CHANGE ENCODE
        popupUtil.addJMenuItem("set encode", new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    String code = StringUtils.defaultString(JOptionPaneUtil.newInstance().iconPlainMessage()
                            .showInputDialog("input file encode", "ENCODE"), "UTF8");
                    encode = Charset.forName(code).displayName();
                } catch (Exception ex) {
                    JCommonUtil.handleException(ex);
                }
                System.err.println("encode : " + encode);
            }
        });

        //SIMPLE LOAD GOOGLE CSV FILE
        popupUtil.addJMenuItem("open Google CSV file", new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                File file = JFileChooserUtil.newInstance().selectFileOnly().addAcceptFile("csv", ".csv")
                        .showOpenDialog().getApproveSelectedFile();
                if (file == null) {
                    errorMessage("file is not correct!");
                    return;
                }
                try {
                    if (file.getName().endsWith(".csv")) {
                        DefaultTableModel model = (DefaultTableModel) googleTable.getModel();
                        LineNumberReader reader = new LineNumberReader(
                                new InputStreamReader(new FileInputStream(file), GOOGLE_CVS_ENCODE));
                        for (String line = null; (line = reader.readLine()) != null;) {
                            if (reader.getLineNumber() == 1) {
                                continue;
                            }
                            model.addRow(line.split(","));
                        }
                        reader.close();
                        googleTable.setModel(model);
                        JTableUtil.newInstance(googleTable).hiddenAllEmptyColumn();
                    }
                } catch (Exception ex) {
                    JCommonUtil.handleException(ex);
                }
            }
        });

        //SAVE CSV FILE FOR GOOGLE
        popupUtil.addJMenuItem("save to Google CVS file", new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                File file = JFileChooserUtil.newInstance().selectFileOnly().addAcceptFile(".csv", ".csv")
                        .showSaveDialog().getApproveSelectedFile();
                if (file == null) {
                    errorMessage("file is not correct!");
                    return;
                }
                file = FileUtil.getIndicateFileExtension(file, ".csv");
                try {
                    BufferedWriter writer = new BufferedWriter(
                            new OutputStreamWriter(new FileOutputStream(file), GOOGLE_CVS_ENCODE));
                    StringBuilder sb = new StringBuilder();
                    for (Object title : googleColumns) {
                        sb.append(title + ",");
                    }
                    sb.deleteCharAt(sb.length() - 1);
                    System.out.println(sb);
                    writer.write(sb.toString());
                    writer.newLine();
                    DefaultTableModel model = (DefaultTableModel) googleTable.getModel();
                    for (int row = 0; row < model.getRowCount(); row++) {
                        sb = new StringBuilder();
                        for (int col = 0; col < model.getColumnCount(); col++) {
                            String colVal = StringUtils.defaultString((String) model.getValueAt(row, col), "");
                            if (colVal.equalsIgnoreCase("null")) {
                                colVal = "";
                            }
                            sb.append(colVal + ",");
                        }
                        sb.deleteCharAt(sb.length() - 1);
                        System.out.println(sb);
                        writer.write(sb.toString());
                        writer.newLine();
                    }
                    writer.flush();
                    writer.close();
                } catch (Exception ex) {
                    JCommonUtil.handleException(ex);
                }
            }
        });

        //PASTE CLIPBOARD
        popupUtil.addJMenuItem("paste clipboard", new ActionListener() {
            public void actionPerformed(ActionEvent paramActionEvent) {
                JTableUtil.newInstance(googleTable).pasteFromClipboard_multiRowData(true);
            }
        });

        popupUtil.addJMenuItem("paste clipboard to selected cell", new ActionListener() {
            public void actionPerformed(ActionEvent paramActionEvent) {
                JTableUtil.newInstance(googleTable).pasteFromClipboard_singleValueToSelectedCell();
            }
        });

        JMenuItem addEmptyRowItem = JTableUtil.newInstance(googleTable).jMenuItem_addRow(false,
                "add row count?");
        addEmptyRowItem.setText("add row");
        JMenuItem removeColumnItem = JTableUtil.newInstance(googleTable).jMenuItem_removeColumn(null);
        removeColumnItem.setText("remove column");
        JMenuItem removeRowItem = JTableUtil.newInstance(googleTable).jMenuItem_removeRow(null);
        removeRowItem.setText("remove row");
        JMenuItem removeAllRowItem = JTableUtil.newInstance(googleTable)
                .jMenuItem_removeAllRow("remove all row?");
        removeAllRowItem.setText("remove all row");
        JMenuItem clearSelectedCellItem = JTableUtil.newInstance(googleTable)
                .jMenuItem_clearSelectedCell("are you sure clear selected area?");
        clearSelectedCellItem.setText("clear selected area");
        popupUtil.addJMenuItem(addEmptyRowItem, removeColumnItem, removeRowItem, removeAllRowItem,
                clearSelectedCellItem);
        popupUtil.show();
    } catch (Exception ex) {
        JCommonUtil.handleException(ex);
    }
}

From source file:com.frameworkset.orm.engine.model.Domain.java

/**
 * Replaces the default value if the new value is not null.
 * //from   w w  w  .  jav  a  2s  . c o  m
 * @param value The defaultValue to set.
 */
public void replaceType(String value) {
    this.torqueType = SchemaType.getEnum(StringUtils.defaultString(value, getType().getName()));
}

From source file:info.magnolia.templating.jsp.taglib.Breadcrumb.java

@Override
public int doStartTag() throws JspException {
    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
    int endLevel = 0;

    try {/*  ww  w  .java2 s.  co  m*/
        Node node = MgnlContext.getJCRSession(MgnlContext.getAggregationState().getRepository())
                .getNode(MgnlContext.getAggregationState().getHandle());
        endLevel = node.getDepth();

        if (this.excludeCurrent) {
            endLevel--;
        }
        int addedcount = 0;

        JspWriter out = pageContext.getOut();
        for (int j = this.startLevel; j <= endLevel; j++) {
            Node ancestor = (Node) node.getAncestor(j);

            if (StringUtils.isNotEmpty(hideProperty) && ancestor.getProperty(hideProperty).getBoolean()) {
                continue;
            }

            String title = null;

            if (StringUtils.isNotEmpty(titleProperty)) {
                title = ancestor.getProperty(titleProperty).getString();
            }

            if (StringUtils.isEmpty(title)) {
                title = ancestor.getName();
            }

            if (StringUtils.isNotEmpty(title)) {
                if (addedcount != 0) {
                    out.print(StringUtils.defaultString(this.delimiter, " &gt; "));
                }
                if (this.link && !(endLevel == j && nolinkCurrent)) {
                    out.print("<a href=\"");
                    out.print(request.getContextPath());
                    out.print(ancestor.getPath());
                    out.print(".");
                    out.print(ServerConfiguration.getInstance().getDefaultExtension());
                    if (node.getPath().equals(ancestor.getPath())) {
                        out.print("\" class=\"");
                        out.print(activeCss);
                    }

                    out.print("\">");

                }
                out.print(title);
                if (this.link && !(endLevel == j && nolinkCurrent)) {
                    out.print("</a>");
                }
                addedcount++;
            }
        }
    } catch (RepositoryException e) {
        log.debug("Exception caught: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new NestableRuntimeException(e);
    }

    return super.doStartTag();
}

From source file:com.bstek.dorado.idesupport.StandaloneRuleSetExporter.java

private void exportRuleSet(PrintWriter writer) throws Exception {
    // ?/*w ww . j ava  2 s. c  o  m*/
    ConsoleUtils.outputLoadingInfo("Initializing " + DoradoAbout.getProductTitle() + " engine...");
    ConsoleUtils.outputLoadingInfo("[Vendor: " + DoradoAbout.getVendor() + "]");

    ConfigureStore configureStore = Configure.getStore();

    // ?DoradoHome
    configureStore.set(HOME_PROPERTY, doradoHome);
    ConsoleUtils.outputLoadingInfo("[Home: " + StringUtils.defaultString(doradoHome, "<not assigned>") + "]");

    // ResourceLoader
    ResourceLoader resourceLoader = new BaseResourceLoader();

    if (StringUtils.isNotEmpty(doradoHome)) {
        String configureLocation = HOME_LOCATION_PREFIX + "configure.properties";
        loadConfigureProperties(configureStore, resourceLoader, configureLocation, false);
    }

    configureStore.set("core.runMode", RUN_MODE);

    loadConfigureProperties(configureStore, resourceLoader,
            CORE_PROPERTIES_LOCATION_PREFIX + "configure-" + RUN_MODE + ".properties", true);

    if (StringUtils.isNotEmpty(doradoHome)) {
        loadConfigureProperties(configureStore, resourceLoader,
                HOME_LOCATION_PREFIX + "configure-" + RUN_MODE + ".properties", true);
    }

    List<String> contextLocations = new ArrayList<String>();
    // findPackages
    for (PackageInfo packageInfo : PackageManager.getPackageInfoMap().values()) {
        String packageName = packageInfo.getName();
        ConsoleUtils
                .outputLoadingInfo("Package [" + packageName + " - " + packageInfo.getVersion() + "] found.");

        // ?Spring?
        String addonVersion = packageInfo.getAddonVersion();
        if (StringUtils.isEmpty(addonVersion) || "2.0".compareTo(addonVersion) > 0) {
            pushLocations(contextLocations, packageInfo.getContextLocations());
        } else {
            pushLocations(contextLocations, packageInfo.getComponentLocations());
        }
    }

    String contextLocationsFromProperties = configureStore.getString(CONTEXT_CONFIG_PROPERTY);
    if (contextLocationsFromProperties != null) {
        pushLocations(contextLocations, contextLocationsFromProperties);
    }

    Resource resource;
    resource = resourceLoader.getResource(getRealResourcePath(HOME_COMPONENT_CONTEXT_FILE));
    if (resource.exists()) {
        pushLocations(contextLocations, HOME_COMPONENT_CONTEXT_FILE);
    }

    configureStore.set(CONTEXT_CONFIG_PROPERTY, StringUtils.join(getRealResourcesPath(contextLocations), ';'));
    ConsoleUtils.outputConfigureItem(CONTEXT_CONFIG_PROPERTY);

    CommonContext.init();
    try {
        // TODO: ??
        EngineStartupListenerManager.notifyStartup();

        RuleTemplateManager ruleTemplateManager = getRuleTemplateBuilder().getRuleTemplateManager();
        getRuleSetOutputter().output(writer, ruleTemplateManager);
    } finally {
        CommonContext.dispose();
    }
}