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

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

Introduction

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

Prototype

public static <T extends CharSequence> T defaultIfEmpty(final T str, final T defaultStr) 

Source Link

Document

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

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

Usage

From source file:com.pennassurancesoftware.tutum.client.TutumClient.java

private String evaluateResponse(HttpRequestBase request, HttpResponse httpResponse) throws TutumException {
    int statusCode = httpResponse.getStatusLine().getStatusCode();
    String response = "";

    if (HttpStatus.SC_OK == statusCode || HttpStatus.SC_CREATED == statusCode
            || HttpStatus.SC_ACCEPTED == statusCode) {
        response = httpResponseToString(httpResponse);
        if (LOG.isDebugEnabled()) {
            String jsonStr = response;
            jsonStr = jsonStr == null || "".equals(jsonStr) ? "{}" : jsonStr;
            LOG.debug("Target URL: {}", request.getURI());
            LOG.debug("JSON Message: {}", StringUtils.defaultIfEmpty(getRequestMessage(request), "N/A"));
            LOG.debug("JSON Response: {}", jsonStr);
        }/*from   ww  w .  j ava2 s . c om*/
    } else if (HttpStatus.SC_NO_CONTENT == statusCode) {
        // in a way its always true from client perspective if there is no exception.
        response = String.format(Constants.NO_CONTENT_JSON_STRUCT, statusCode);
    }

    if ((statusCode >= 400 && statusCode < 510)) {
        String jsonStr = httpResponseToString(httpResponse);
        jsonStr = jsonStr == null || "".equals(jsonStr) ? "{}" : jsonStr;
        LOG.error("Target URL: {}", request.getURI());
        LOG.error("JSON Message: {}", getRequestMessage(request));
        LOG.error("JSON Response: {}", jsonStr);

        final JsonObject jsonObj = jsonParser.parse(jsonStr).getAsJsonObject();
        final String message = jsonObj.has("error") ? jsonObj.get("error").getAsString() : jsonStr;
        String errorMsg = String.format("\nHTTP Status Code: %s\nError Message: %s", statusCode, message);
        LOG.debug(errorMsg);

        throw new TutumException(errorMsg, "N/A", statusCode);
    }

    return response;
}

From source file:no.kantega.publishing.common.ao.ContentAOHelper.java

public static void addAttributeFromRS(Content content, ResultSet rs) throws SQLException, SystemException {

    String attributeType = StringUtils.defaultIfEmpty(rs.getString("AttributeType"), "Text");

    AttributeDataType attributeDataType = AttributeDataType.getDataTypeAsEnum(rs.getInt("DataType"));

    String attributeNameIncludingPath = rs.getString("Name");
    String value = rs.getString("Value");

    List<Attribute> attributes = content.getAttributes(attributeDataType);
    Attribute parentAttribute = null;

    String path[] = REPEATER_PATTERN.split(attributeNameIncludingPath);
    for (String pathElement : path) {
        if (pathElement.contains("[")) {
            // Repeater attribute
            String rowStr = pathElement.substring(pathElement.indexOf("[") + 1, pathElement.length());
            int row = Integer.parseInt(rowStr, 10);
            pathElement = pathElement.substring(0, pathElement.indexOf("["));

            // Check if repeater has been created
            RepeaterAttribute repeater = createOrGetExistingRepeaterAttributeByName(attributes, pathElement,
                    attributeDataType);/*from w  w  w .j a  va  2  s .c  om*/
            repeater.setParent(parentAttribute);

            parentAttribute = repeater;

            addCorrectNumberOfRows(row, repeater);

            // Get correct row
            attributes = repeater.getRow(row);
        } else {
            // Normal attribute
            Attribute attribute = null;
            try {
                attribute = attributeFactory.newAttribute(attributeType);
            } catch (Exception e) {
                log.error("Error instantiating attribute " + attributeType, e);
                throw new SystemException("Feil ved oppretting av klasse for attributt " + attributeType, e);
            }
            attribute.setParent(parentAttribute);

            attributes.add(attribute);

            value = removeExtraCharsFromListAttribute(value, attribute);
            attribute.setValue(value);
            attribute.setName(pathElement);

            UnPersistAttributeBehaviour behaviour = attribute.getFetchBehaviour();
            behaviour.unpersistAttribute(rs, attribute);

        }
    }

}

From source file:objective.taskboard.controller.FollowUpController.java

@RequestMapping
public ResponseEntity<Object> download(@RequestParam("project") String projectKey,
        @RequestParam("template") String template, @RequestParam("date") Optional<LocalDate> date,
        @RequestParam("timezone") String zoneId) {

    if (ObjectUtils.isEmpty(projectKey))
        return new ResponseEntity<>("You must provide the project", BAD_REQUEST);
    if (ObjectUtils.isEmpty(template))
        return new ResponseEntity<>("Template not selected", BAD_REQUEST);

    Template templateFollowup = templateService.getTemplate(template);

    if (templateFollowup == null
            || !authorizer.hasAnyRoleInProjects(templateFollowup.getRoles(), asList(projectKey)))
        return new ResponseEntity<>("Template or project doesn't exist", HttpStatus.NOT_FOUND);

    ZoneId timezone = determineTimeZoneId(zoneId);

    try {/* ww w.j  a  v a 2 s .c o m*/
        Resource resource = followUpFacade.generateReport(template, date, timezone, projectKey);
        String filename = "Followup_" + template + "_" + projectKey + "_" + templateDate(date, timezone)
                + ".xlsm";

        return ResponseEntity.ok().contentLength(resource.contentLength())
                .header("Content-Disposition", "attachment; filename=\"" + filename + "\"")
                .header("Set-Cookie", "fileDownload=true; path=/").body(resource);
    } catch (InvalidTableRangeException e) {//NOSONAR
        return ResponseEntity.badRequest().body(format(
                "The selected template is invalid. The range of table %s? in sheet %s? is smaller than the available data. "
                        + "Please increase the range to cover at least row %s.",
                e.getTableName(), e.getSheetName(), e.getMinRows()));

    } catch (ClusterNotConfiguredException e) {//NOSONAR
        return ResponseEntity.badRequest()
                .body("No cluster configuration found for project " + projectKey + ".");

    } catch (ProjectDatesNotConfiguredException e) {//NOSONAR
        return ResponseEntity.badRequest()
                .body("The project " + projectKey + " has no start or delivery date.");

    } catch (Exception e) {
        log.warn("Error generating followup spreadsheet", e);
        return ResponseEntity.status(INTERNAL_SERVER_ERROR).header("Content-Type", "text/html; charset=utf-8")
                .body(StringUtils.defaultIfEmpty(e.getMessage(), e.toString()));
    }
}

From source file:org.apache.fineract.infrastructure.scheduledemail.domain.EmailCampaign.java

public Map<String, Object> update(JsonCommand command) {

    final Map<String, Object> actualChanges = new LinkedHashMap<>(5);

    if (command.isChangeInStringParameterNamed(EmailCampaignValidator.campaignName, this.campaignName)) {
        final String newValue = command.stringValueOfParameterNamed(EmailCampaignValidator.campaignName);
        actualChanges.put(EmailCampaignValidator.campaignName, newValue);
        this.campaignName = StringUtils.defaultIfEmpty(newValue, null);
    }/*  w  w  w  . j av a  2 s  . c om*/
    if (command.isChangeInStringParameterNamed(EmailCampaignValidator.emailMessage, this.emailMessage)) {
        final String newValue = command.stringValueOfParameterNamed(EmailCampaignValidator.emailMessage);
        actualChanges.put(EmailCampaignValidator.emailMessage, newValue);
        this.emailMessage = StringUtils.defaultIfEmpty(newValue, null);
    }
    if (command.isChangeInStringParameterNamed(EmailCampaignValidator.paramValue, this.paramValue)) {
        final String newValue = command.stringValueOfParameterNamed(EmailCampaignValidator.paramValue);
        actualChanges.put(EmailCampaignValidator.paramValue, newValue);
        this.paramValue = StringUtils.defaultIfEmpty(newValue, null);
    }
    if (command.isChangeInIntegerParameterNamed(EmailCampaignValidator.campaignType, this.campaignType)) {
        final Integer newValue = command.integerValueOfParameterNamed(EmailCampaignValidator.campaignType);
        actualChanges.put(EmailCampaignValidator.campaignType, EmailCampaignType.fromInt(newValue));
        this.campaignType = EmailCampaignType.fromInt(newValue).getValue();
    }
    if (command.isChangeInLongParameterNamed(EmailCampaignValidator.businessRuleId,
            (this.businessRuleId != null) ? this.businessRuleId.getId() : null)) {
        final String newValue = command.stringValueOfParameterNamed(EmailCampaignValidator.businessRuleId);
        actualChanges.put(EmailCampaignValidator.businessRuleId, newValue);
    }
    if (command.isChangeInStringParameterNamed(EmailCampaignValidator.recurrenceParamName, this.recurrence)) {
        final String newValue = command.stringValueOfParameterNamed(EmailCampaignValidator.recurrenceParamName);
        actualChanges.put(EmailCampaignValidator.recurrenceParamName, newValue);
        this.recurrence = StringUtils.defaultIfEmpty(newValue, null);
    }
    final String dateFormatAsInput = command.dateFormat();
    final String localeAsInput = command.locale();
    final Locale locale = command.extractLocale();
    final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale);

    if (command.isChangeInLocalDateParameterNamed(EmailCampaignValidator.recurrenceStartDate,
            getRecurrenceStartDate())) {
        final String valueAsInput = command
                .stringValueOfParameterNamed(EmailCampaignValidator.recurrenceStartDate);
        actualChanges.put(EmailCampaignValidator.recurrenceStartDate, valueAsInput);
        actualChanges.put(ClientApiConstants.dateFormatParamName, dateFormatAsInput);
        actualChanges.put(ClientApiConstants.localeParamName, localeAsInput);

        final LocalDateTime newValue = LocalDateTime.parse(valueAsInput, fmt);

        this.recurrenceStartDate = newValue.toDate();
    }

    return actualChanges;
}

From source file:org.apache.fineract.infrastructure.scheduledemail.domain.EmailMessage.java

public Map<String, Object> update(final JsonCommand command) {

    final Map<String, Object> actualChanges = new LinkedHashMap<>(1);

    if (command.isChangeInStringParameterNamed(EmailApiConstants.messageParamName, this.message)) {
        final String newValue = command.stringValueOfParameterNamed(EmailApiConstants.messageParamName);
        actualChanges.put(EmailApiConstants.messageParamName, newValue);
        this.message = StringUtils.defaultIfEmpty(newValue, null);
    }//from w  ww .j a va2s .  c  o m

    return actualChanges;
}

From source file:org.apache.fineract.infrastructure.sms.domain.SmsCampaign.java

public Map<String, Object> update(JsonCommand command) {

    final Map<String, Object> actualChanges = new LinkedHashMap<>(5);

    if (command.isChangeInStringParameterNamed(SmsCampaignValidator.campaignName, this.campaignName)) {
        final String newValue = command.stringValueOfParameterNamed(SmsCampaignValidator.campaignName);
        actualChanges.put(SmsCampaignValidator.campaignName, newValue);
        this.campaignName = StringUtils.defaultIfEmpty(newValue, null);
    }/* ww w  .jav a2 s  . co m*/
    if (command.isChangeInStringParameterNamed(SmsCampaignValidator.message, this.message)) {
        final String newValue = command.stringValueOfParameterNamed(SmsCampaignValidator.message);
        actualChanges.put(SmsCampaignValidator.message, newValue);
        this.message = StringUtils.defaultIfEmpty(newValue, null);
    }
    if (command.isChangeInStringParameterNamed(SmsCampaignValidator.paramValue, this.paramValue)) {
        final String newValue = command.stringValueOfParameterNamed(SmsCampaignValidator.paramValue);
        actualChanges.put(SmsCampaignValidator.paramValue, newValue);
        this.paramValue = StringUtils.defaultIfEmpty(newValue, null);
    }
    if (command.isChangeInIntegerParameterNamed(SmsCampaignValidator.campaignType, this.campaignType)) {
        final Integer newValue = command.integerValueOfParameterNamed(SmsCampaignValidator.campaignType);
        actualChanges.put(SmsCampaignValidator.campaignType, SmsCampaignType.fromInt(newValue));
        this.campaignType = SmsCampaignType.fromInt(newValue).getValue();
    }
    if (command.isChangeInLongParameterNamed(SmsCampaignValidator.runReportId,
            (this.businessRuleId != null) ? this.businessRuleId.getId() : null)) {
        final String newValue = command.stringValueOfParameterNamed(SmsCampaignValidator.runReportId);
        actualChanges.put(SmsCampaignValidator.runReportId, newValue);
    }
    if (command.isChangeInStringParameterNamed(SmsCampaignValidator.recurrenceParamName, this.recurrence)) {
        final String newValue = command.stringValueOfParameterNamed(SmsCampaignValidator.recurrenceParamName);
        actualChanges.put(SmsCampaignValidator.recurrenceParamName, newValue);
        this.recurrence = StringUtils.defaultIfEmpty(newValue, null);
    }
    final String dateFormatAsInput = command.dateFormat();
    final String localeAsInput = command.locale();
    final Locale locale = command.extractLocale();
    final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale);

    if (command.isChangeInLocalDateParameterNamed(SmsCampaignValidator.recurrenceStartDate,
            getRecurrenceStartDate())) {
        final String valueAsInput = command
                .stringValueOfParameterNamed(SmsCampaignValidator.recurrenceStartDate);
        actualChanges.put(SmsCampaignValidator.recurrenceStartDate, valueAsInput);
        actualChanges.put(ClientApiConstants.dateFormatParamName, dateFormatAsInput);
        actualChanges.put(ClientApiConstants.localeParamName, localeAsInput);

        final LocalDateTime newValue = LocalDateTime.parse(valueAsInput, fmt);

        this.recurrenceStartDate = newValue.toDate();
    }

    return actualChanges;
}

From source file:org.apache.jena.arq.querybuilder.handlers.PrologHandler.java

/**
 * Add the settings from the prolog handler argument.
 * @param pfxHandler The PrologHandler to read from
 *///  ww  w  .  ja v  a2  s.c  om
public void addAll(PrologHandler pfxHandler) {
    String val = StringUtils.defaultIfEmpty(pfxHandler.query.getBaseURI(), query.getBaseURI());
    if (val != null) {
        setBase(val);
    }
    addPrefixes(pfxHandler.query.getPrefixMapping());
}

From source file:org.apache.zeppelin.hopshive.HopsHiveInterpreter.java

private SqlCompleter createOrUpdateSqlCompleter(SqlCompleter sqlCompleter, final Connection connection,
        String propertyKey, final String buf, final int cursor) {
    String schemaFiltersKey = String.format("%s.%s", propertyKey, COMPLETER_SCHEMA_FILTERS_KEY);
    String sqlCompleterTtlKey = String.format("%s.%s", propertyKey, COMPLETER_TTL_KEY);
    final String schemaFiltersString = getProperty(schemaFiltersKey);
    int ttlInSeconds = Integer
            .valueOf(StringUtils.defaultIfEmpty(getProperty(sqlCompleterTtlKey), DEFAULT_COMPLETER_TTL));
    final SqlCompleter completer;
    if (sqlCompleter == null) {
        completer = new SqlCompleter(ttlInSeconds);
    } else {/* ww  w.  j a v a  2  s . co m*/
        completer = sqlCompleter;
    }
    ExecutorService executorService = Executors.newFixedThreadPool(1);
    executorService.execute(new Runnable() {
        @Override
        public void run() {
            completer.createOrUpdateFromConnection(connection, schemaFiltersString, buf, cursor);
        }
    });

    executorService.shutdown();

    try {
        // protection to release connection
        executorService.awaitTermination(3, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
    }
    return completer;
}

From source file:org.apache.zeppelin.util.Util.java

/**
 * Get Zeppelin version//  www .  j ava  2 s. com
 *
 * @return Current Zeppelin version
 */
public static String getVersion() {
    return StringUtils.defaultIfEmpty(projectProperties.getProperty(PROJECT_PROPERTIES_VERSION_KEY),
            StringUtils.EMPTY);
}

From source file:org.biokoframework.http.routing.impl.RouteMatcherImpl.java

private String extractParameter(String group) {
    String parameterName = group.replaceAll("\\{(<.*>)?", "").replaceAll("\\}", "");
    fParameterNames.add(parameterName);// w  w  w  . j a  va2s.  c om
    String paramRegexp = group.replaceAll("\\{<?", "").replaceAll(">?" + parameterName + "\\}", "");
    return "(" + StringUtils.defaultIfEmpty(paramRegexp, "[^\\{\\}/\\.]*") + ")";
}