Java Code Examples for org.apache.commons.lang.StringUtils#defaultString()

The following examples show how to use org.apache.commons.lang.StringUtils#defaultString() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
/**
 * Get the card type values based on available imported expenses
 *
 * Always include actual expense as the first option on the type
 *
 * @see org.kuali.rice.kns.lookup.keyvalues.KeyValuesFinder#getKeyValues()
 */
@Override
public List<KeyValue> getKeyValues() {

    TravelDocument document = ((TravelFormBase)KNSGlobalVariables.getKualiForm()).getTravelDocument();
    List<ImportedExpense> importedExpenses = document.getImportedExpenses();
    Map<String,KeyValue> map = new LinkedHashMap<String, KeyValue>();

    String defaultCardType = document.getDefaultAccountingLineCardAgencyType();

    //default to always include actual expense type
    map.put(defaultCardType, new ConcreteKeyValue(defaultCardType, defaultCardType));

    for (ImportedExpense expense : importedExpenses) {
        String cardType = StringUtils.defaultString(expense.getCardType());
        if (!map.containsKey(cardType)){
            map.put(cardType, new ConcreteKeyValue(cardType,cardType));
            //remove the default card type (if its blank) - since there is a new default
            if (map.containsKey(defaultCardType) && StringUtils.isBlank(defaultCardType)){
                map.remove(defaultCardType);
            }
        }
    }
    return new ArrayList<KeyValue>(map.values());
}
 
Example 2
/**
 * Create ExtraOptions string
 * @return extraOptions that will be appended to the Kickstart.
 */
public String getExtraOptions() {
    StringBuilder retval = new StringBuilder();
    String kOptions = StringUtils.defaultString(kernelOptions);
    /** Some examples:
    dhcp:eth0 , dhcp:eth2, static:10.1.4.75
    static:146.108.30.184, static:auto, static:eth0
     */
    if (!StringUtils.isBlank(networkInterface)) {
        if (!LINK_NETWORK_TYPE.equals(networkInterface)) {
            // Get rid of the dhcp:
            String params = " ksdevice=" + networkInterface;
            if (!kOptions.contains("ksdevice")) {
                retval.append(params);
            }
        }
    }
    else if (!kOptions.contains("ksdevice")) {
        retval.append("ksdevice=" +
                ConfigDefaults.get().getDefaultKickstartNetworkInterface());
    }
    retval.append(" ").append(kOptions);
    return retval.toString();
}
 
Example 3
private void buildParameterBuilders(final ApplicationContext applicationContext) {
    final Environment environment = applicationContext.getEnvironment();
    final String builders = StringUtils.defaultString(environment.getProperty("shibcas.parameterBuilders", ""));
    for (final String parameterBuilder : StringUtils.split(builders, ";")) {
        try {
            logger.debug("Loading parameter builder class {}", parameterBuilder);
            final Class clazz = Class.forName(parameterBuilder);
            final IParameterBuilder builder = IParameterBuilder.class.cast(clazz.newInstance());
            if (builder instanceof ApplicationContextAware) {
                ((ApplicationContextAware) builder).setApplicationContext(applicationContext);
            }
            this.parameterBuilders.add(builder);
            logger.debug("Added parameter builder {}", parameterBuilder);
        } catch (final Throwable e) {
            logger.error("Error building parameter builder with name: " + parameterBuilder, e);
        }
    }
}
 
Example 4
public static IdGenerator getIdGenerator(String type) throws TechnicalConnectorException {
   if (!cachedInstance.containsKey(type)) {
      String defaultimpl = StringUtils.defaultString((String)defaultGeneratorClasses.get(type), DEFAULT_INPUT_REF_GENERATOR_CHECKER_CLASS);
      ConfigurableFactoryHelper<IdGenerator> helper = new ConfigurableFactoryHelper("be.ehealth.technicalconnector.idgenerator." + type + ".classname", defaultimpl);
      cachedInstance.put(type, helper.getImplementation());
   }

   return (IdGenerator)cachedInstance.get(type);
}
 
Example 5
public static IdGenerator getIdGenerator(String type) throws TechnicalConnectorException {
   if (!cachedInstance.containsKey(type)) {
      String defaultimpl = StringUtils.defaultString((String)defaultGeneratorClasses.get(type), DEFAULT_INPUT_REF_GENERATOR_CHECKER_CLASS);
      ConfigurableFactoryHelper<IdGenerator> helper = new ConfigurableFactoryHelper("be.ehealth.technicalconnector.idgenerator." + type + ".classname", defaultimpl);
      cachedInstance.put(type, helper.getImplementation());
   }

   return (IdGenerator)cachedInstance.get(type);
}
 
Example 6
/**
 * @see java.lang.Object#toString()
 */
@Override
public String toString()
{
  if (StringUtils.isBlank(filename) == true) {
    return String.valueOf(getId());
  }
  return StringUtils.defaultString(this.filename);
}
 
Example 7
/**
 * Return the value for a specific column as string; the string is empty if
 * the value is SQL NULL.
 */
public static String getString(ResultSet r, String columnLabel){
    String s;
    try {
        s = r.getString(columnLabel);
    } catch (SQLException ex) {
        LOGGER.log(Level.WARNING, "can't get string from db", ex);
        return "";
    }
    return StringUtils.defaultString(s);
}
 
Example 8
private String getContactXMLChunk(String addressType,
                                  PurchaseOrderDocument po){
    
    String returnXML =          
    
    "                  <Contact addressID=\"" + RandomUtils.nextInt() + "\" role=\"" + addressType + "\"> <!-- addressId=Random Unique Id -->\n" +
    "                      <Name xml:lang=\"en\">" + po.getDeliveryCampusCode() + " - " + po.getDeliveryBuildingName() + "</Name> <!-- Format:CampusCode - Bldg Nm -->\n" +
    "                      <PostalAddress>\n" +
    "                          <Street>" + StringUtils.defaultString(po.getDeliveryBuildingLine1Address()) + "</Street>\n" +
    "                          <Street>" + StringUtils.defaultString(po.getDeliveryBuildingLine2Address()) + "</Street>\n" +
    "                          <City>" + StringUtils.defaultString(po.getDeliveryCityName()) + "</City>\n" +
    "                          <State>" + StringUtils.defaultString(po.getDeliveryStateCode()) + "</State>\n" +
    "                          <PostalCode>" + StringUtils.defaultString(po.getDeliveryPostalCode()) + "</PostalCode>\n" +
    "                          <Country isoCountryCode=\"" + StringUtils.defaultString(po.getDeliveryCountryCode()) + "\">\n" +
    "                              " + StringUtils.defaultString(po.getDeliveryCountryName()) + "\n" +
    "                          </Country>\n" +
    "                      </PostalAddress>\n";
    
    if (StringUtils.isNotEmpty(po.getDeliveryToEmailAddress())){
        returnXML += "                      <Email name=\"" + po.getDeliveryToEmailAddress() + "\">" + po.getDeliveryToEmailAddress() + "</Email>\n";
    }
    
    if (StringUtils.isNotEmpty(po.getDeliveryToPhoneNumber())){
        returnXML +=  
        "                      <Phone name=\"" + po.getDeliveryToPhoneNumber() + "\">\n" +
        "                          <TelephoneNumber>\n" +
        "                              <CountryCode isoCountryCode=\"US\">1</CountryCode>\n" +
        "                              <AreaOrCityCode>" + getPhoneNumber(AREA_C0DE, po.getDeliveryToPhoneNumber()) + "</AreaOrCityCode>\n" +
        "                              <Number>" + getPhoneNumber(PHONE_NUMBER, po.getDeliveryToPhoneNumber()) + "</Number>\n" +
        "                          </TelephoneNumber>\n" +
        "                      </Phone>\n";
    }    
    
    returnXML += "                  </Contact>\n";                
    return returnXML;        
}
 
Example 9
Source Project: APM   File: SummaryRedirectServlet.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
  String mode = StringUtils.defaultString(request.getRequestPathInfo().getSelectorString());
  String scriptPath = request.getRequestPathInfo().getSuffix();
  ScriptHistory scriptHistory = Optional.ofNullable(scriptFinder.find(scriptPath, request.getResourceResolver()))
      .map(script -> history.findScriptHistory(request.getResourceResolver(), script))
      .orElse(ScriptHistoryImpl.empty(scriptPath));
  String lastSummaryPath = getLastSummaryPath(scriptHistory, mode);
  if (!lastSummaryPath.isEmpty()) {
    response.sendRedirect("/apm/summary.html" + lastSummaryPath);
  } else {
    response.sendRedirect("/apm/history.html");
  }
}
 
Example 10
public static JID full(String jid) {
    jid = StringUtils.defaultString(jid);
    return escape(XmppStringUtils.parseLocalpart(jid),
            XmppStringUtils.parseDomain(jid),
            XmppStringUtils.parseResource(jid));
}
 
Example 11
Source Project: rice   File: FieldUtils.java    License: Educational Community License v2.0 4 votes vote down vote up
private static List<Field> constructFieldsForAttributeDefinition(RemotableAttributeField remotableAttributeField) {
    List<Field> fields = new ArrayList<Field>();
    if (remotableAttributeField.getAttributeLookupSettings() != null
            && remotableAttributeField.getAttributeLookupSettings().isRanged()) {
        // create two fields, one for the "from" and one for the "to"
        AttributeLookupSettings lookupSettings = remotableAttributeField.getAttributeLookupSettings();
        // Create a pair of range input fields for a ranged attribute
        // the lower bound is prefixed to distinguish it from the upper bound, which retains the original field name
        String attrLabel;
        if (StringUtils.isBlank(remotableAttributeField.getLongLabel())) {
            attrLabel =  remotableAttributeField.getShortLabel();
        } else {
            attrLabel =  remotableAttributeField.getLongLabel();
        }
        String label = StringUtils.defaultString(lookupSettings.getLowerLabel(), attrLabel
            + " " + KewApiConstants.SearchableAttributeConstants.DEFAULT_RANGE_SEARCH_LOWER_BOUND_LABEL);
        Field lowerField = new Field(KRADConstants.LOOKUP_RANGE_LOWER_BOUND_PROPERTY_PREFIX + remotableAttributeField.getName(), label);
        lowerField.setMemberOfRange(true);
        lowerField.setAllowInlineRange(false);
        lowerField.setRangeFieldInclusive(lookupSettings.isLowerBoundInclusive());
        if (lookupSettings.isLowerDatePicker() != null) {
            lowerField.setDatePicker(lookupSettings.isLowerDatePicker());
        }
        if (!remotableAttributeField.getDataType().equals(DataType.CURRENCY)) {
            lowerField.setFieldDataType(remotableAttributeField.getDataType().name().toLowerCase());
        }
        fields.add(lowerField);

        label = StringUtils.defaultString(lookupSettings.getUpperLabel(), attrLabel
            + " " + KewApiConstants.SearchableAttributeConstants.DEFAULT_RANGE_SEARCH_UPPER_BOUND_LABEL);
        Field upperField = new Field(remotableAttributeField.getName(), label);
        upperField.setMemberOfRange(true);
        upperField.setAllowInlineRange(false);
        upperField.setRangeFieldInclusive(lookupSettings.isUpperBoundInclusive());
        if (lookupSettings.isUpperDatePicker() != null) {
            upperField.setDatePicker(lookupSettings.isUpperDatePicker());
        }
        if (!remotableAttributeField.getDataType().equals(DataType.CURRENCY)) {
            upperField.setFieldDataType(remotableAttributeField.getDataType().name().toLowerCase());
        }
        fields.add(upperField);
    } else {
        //this ain't right....
        Field tempField = new Field(remotableAttributeField.getName(), remotableAttributeField.getLongLabel());
        if (remotableAttributeField.getMaxLength() != null) {
            tempField.setMaxLength(remotableAttributeField.getMaxLength());
        }

        if (remotableAttributeField.getShortLabel() != null) {
            tempField.setFieldLabel(remotableAttributeField.getShortLabel());
        }

        if (!remotableAttributeField.getDataType().equals(DataType.CURRENCY)) {
            tempField.setFieldDataType(remotableAttributeField.getDataType().name().toLowerCase());
        } else {
            tempField.setFieldDataType(KewApiConstants.SearchableAttributeConstants.DATA_TYPE_FLOAT);
        }

        tempField.setMainFieldLabel(remotableAttributeField.getLongLabel());
        tempField.setFieldHelpSummary(remotableAttributeField.getHelpSummary());
        tempField.setUpperCase(remotableAttributeField.isForceUpperCase());
        if (remotableAttributeField.getMaxLength() != null) {
            if (remotableAttributeField.getMaxLength().intValue() > 0) {
                tempField.setMaxLength(remotableAttributeField.getMaxLength().intValue());
            } else {
                tempField.setMaxLength(100);
            }
        }
        tempField.setFieldRequired(remotableAttributeField.isRequired());

        fields.add(tempField);
    }
    return fields;
}
 
Example 12
private static Properties buildConfiguration(final String systemKeystorePassword, final String systemKeystorePath, final String systemKeystoreDirectory, final String systemKeystoreRizivKBO) throws IOException{
    final String configFileName = StringUtils.defaultString(System.getProperty("config"));
    final String validationFileName = StringUtils.defaultString(System.getProperty("configValidation"));

    if ((StringUtils.isBlank(configFileName) || !new File(configFileName).isFile())) {
        throw new IllegalStateException("Unable to create session: config file is not provided or invalid");
    }
    if ((StringUtils.isBlank(validationFileName) || !new File(validationFileName).isFile())) {
        throw new IllegalStateException("Unable to create session: validation file is not provided or invalid");
    }

    final Properties configuration = new Properties();
    final File configFile = new File(configFileName);
    final File validationFile = new File(configFileName);
    configuration.load(FileUtils.openInputStream(configFile));
    configuration.load(FileUtils.openInputStream(validationFile));
    String configPath = configFile.getParent().replace("\\", "/");
    for (String propertyName : configuration.stringPropertyNames()) {
        String propertyValue = configuration.getProperty(propertyName);
        configuration.setProperty(propertyName, propertyValue.replaceAll("%CONF%", configPath));
    }

    if (StringUtils.isNotBlank(systemKeystorePassword)) {
        configuration.put(EncryptionUtils.PROP_KEYSTORE_PASSWORD, systemKeystorePassword);
    }
    if (StringUtils.isNotBlank(systemKeystorePath)) {
        final File keystorePathFile = new File(systemKeystorePath);
        if (!keystorePathFile.exists() || !keystorePathFile.isFile()) {
            throw new IllegalStateException("Unable to create session: Provided systemKeystorePath is invalid");
        }
        configuration.put(EncryptionUtils.PROP_KEYSTORE_P12_FOLDER, keystorePathFile.getParentFile().getAbsolutePath() + File.separator);
        configuration.put(EncryptionUtils.PROP_KEYSTORE_FILE, keystorePathFile.getName());
    }
    if (StringUtils.isNotBlank(systemKeystoreDirectory) && StringUtils.isNotBlank(systemKeystoreRizivKBO)) {
        File matchingFile = null;
        final File directory = new File(systemKeystoreDirectory);
        if (directory.exists() && directory.isDirectory()) {
            File[] matchingFiles = directory.listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return name.contains(systemKeystoreRizivKBO) && name.endsWith(".p12");
                }
            });
            if(matchingFiles.length == 1){
                matchingFile = matchingFiles[0];
            }
        }

        if(matchingFile == null){
            throw new IllegalStateException("Unable to create session: Unable to find unique keystore file based on provided combination of keystore directory and riziv/kbo number.");
        }
        configuration.put(EncryptionUtils.PROP_KEYSTORE_P12_FOLDER, new File(systemKeystoreDirectory).getAbsolutePath() + File.separator);
        configuration.put(EncryptionUtils.PROP_KEYSTORE_FILE, matchingFile.getName());
    }
    return configuration;

}
 
Example 13
Source Project: webtester-core   File: PageObjectModel.java    License: Apache License 2.0 4 votes vote down vote up
public String getName() {
    return StringUtils.defaultString(name);
}
 
Example 14
@Override
public String currentUrl() {
    return StringUtils.defaultString(webDriver().getCurrentUrl());
}
 
Example 15
@SuppressWarnings("serial")
public void init(final Set<AuftragsPositionVO> orderPositions)
{
  final RepeatingView positionsRepeater = new RepeatingView("pos");
  add(positionsRepeater);
  if (orderPositions != null) {
    final Iterator<AuftragsPositionVO> it = orderPositions.iterator();
    int orderNumber = -1;
    StringBuffer buf = new StringBuffer();
    Link<String> link = null;
    BigDecimal totalPersonDays = BigDecimal.ZERO;
    AuftragsPositionVO previousOrderPosition = null;
    while (it.hasNext() == true) {
      final AuftragsPositionVO orderPosition = it.next();
      if (orderPosition.getAuftragNummer() != null && orderNumber != orderPosition.getAuftragNummer().intValue()) {
        orderNumber = orderPosition.getAuftragNummer();
        final WebMarkupContainer item = new WebMarkupContainer(positionsRepeater.newChildId());
        positionsRepeater.add(item);
        final Label separatorLabel = new Label("separator", ", ");
        if (previousOrderPosition != null) {
          // Previous order position finished.
          addTitleAttribute(link, previousOrderPosition, totalPersonDays, buf);
          buf = new StringBuffer();
          totalPersonDays = BigDecimal.ZERO;
        } else {
          separatorLabel.setVisible(false); // Invisible for first entry.
        }
        previousOrderPosition = orderPosition;
        item.add(separatorLabel);
        link = new Link<String>("link") {
          @Override
          public void onClick()
          {
            final PageParameters params = new PageParameters();
            params.add(AbstractEditPage.PARAMETER_KEY_ID, String.valueOf(orderPosition.getAuftragId()));
            final AuftragEditPage page = new AuftragEditPage(params);
            page.setReturnToPage((AbstractSecuredPage) getPage());
            setResponsePage(page);
          };
        };
        item.add(link);
        link.add(new Label("label", String.valueOf(orderPosition.getAuftragNummer())));
      } else {
        buf.append("\n");
      }
      buf.append("#").append(orderPosition.getNumber()).append(" (");
      if (orderPosition.getPersonDays() != null) {
        buf.append(NumberFormatter.format(orderPosition.getPersonDays()));
        totalPersonDays = totalPersonDays.add(orderPosition.getPersonDays());
      } else {
        buf.append("??");
      }
      final String title = StringUtils.defaultString(orderPosition.getTitel());
      buf.append(" ").append(getString("projectmanagement.personDays.short")).append("): ").append(title);
      if (orderPosition.getStatus() != null) {
        if (StringUtils.isNotBlank(title) == true) {
          buf.append(", ");
        }
        buf.append(getString(orderPosition.getStatus().getI18nKey()));
      }
      if (it.hasNext() == false && link != null) {
        addTitleAttribute(link, orderPosition, totalPersonDays, buf);
      }
    }
  }
}
 
Example 16
private static ClientUtils.KonRosterEntry clientToModel(RosterEntry entry) {
    return new ClientUtils.KonRosterEntry(JID.fromSmack(entry.getJid()),
            StringUtils.defaultString(entry.getName()),
            entry.getType(),
            entry.isSubscriptionPending());
}
 
Example 17
/**
 * Gets a short message summarising the exception.
 * <p>
 * The message returned is of the form
 * {ClassNameWithoutPackage}: {ThrowableMessage}
 *
 * @param th  the throwable to get a message for, null returns empty string
 * @return the message, non-null
 * @since Commons Lang 2.2
 */
public static String getMessage(Throwable th) {
    if (th == null) {
        return "";
    }
    String clsName = ClassUtils.getShortClassName(th, null);
    String msg = th.getMessage();
    return clsName + ": " + StringUtils.defaultString(msg);
}
 
Example 18
Source Project: webtester-core   File: Button.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Retrieves the value of the {@link Button button}. If no value is set an
 * empty string is returned.
 *
 * @return the value of the button
 * @since 0.9.7
 */
@Override
public String getValue() {
    this.markAsRead();
    return StringUtils.defaultString(getAttribute("value"));
}
 
Example 19
Source Project: webtester-core   File: IFrame.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Returns the complete path to the source file e.g. "../frames/menu.html".
 * If no source path is set an empty string is returned.
 *
 * @return the source path
 * @since 0.9.0
 */
@Override
public String getSourcePath() {
    return StringUtils.defaultString(getAttribute("src"));
}
 
Example 20
Source Project: webtester2-core   File: PageFragment.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Returns the visible (displayed) textual representation of this {@link PageFragment}.
 * For invisible fragments this returns an empty string.
 *
 * @return the visible text
 * @see WebElement#getText()
 * @see PageFragment
 * @since 2.0
 */
@Mark(As.READ)
default String getVisibleText() {
    return StringUtils.defaultString(webElement().getText());
}