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

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

Introduction

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

Prototype

public static String defaultIfBlank(String str, String defaultStr) 

Source Link

Document

Returns either the passed in String, or if the String is whitespace, empty ("") or null, the value of defaultStr.

Usage

From source file:com.iyonger.apm.web.service.ScriptValidationService.java

@Override
public String validate(User user, IFileEntry scriptIEntry, boolean useScriptInSVN, String hostString) {
    FileEntry scriptEntry = TypeConvertUtils.cast(scriptIEntry);
    try {/*from   w w w. j  av a  2 s  .  c  om*/
        checkNotNull(scriptEntry, "scriptEntity should be not null");
        checkNotEmpty(scriptEntry.getPath(), "scriptEntity path should be provided");
        if (!useScriptInSVN) {
            checkNotEmpty(scriptEntry.getContent(), "scriptEntity content should be provided");
        }
        checkNotNull(user, "user should be provided");
        // String result = checkSyntaxErrors(scriptEntry.getContent());

        ScriptHandler handler = scriptHandlerFactory.getHandler(scriptEntry);
        if (config.getControllerProperties().getPropertyBoolean(PROP_CONTROLLER_VALIDATION_SYNTAX_CHECK)) {
            String result = handler.checkSyntaxErrors(scriptEntry.getPath(), scriptEntry.getContent());
            LOGGER.info("Perform Syntax Check by {} for {}", user.getUserId(), scriptEntry.getPath());
            if (result != null) {
                return result;
            }
        }
        File scriptDirectory = config.getHome().getScriptDirectory(user);
        FileUtils.deleteDirectory(scriptDirectory);
        Preconditions.checkTrue(scriptDirectory.mkdirs(), "Script directory {} creation is failed.");

        ProcessingResultPrintStream processingResult = new ProcessingResultPrintStream(
                new ByteArrayOutputStream());
        handler.prepareDist(0L, user, scriptEntry, scriptDirectory, config.getControllerProperties(),
                processingResult);
        if (!processingResult.isSuccess()) {
            return new String(processingResult.getLogByteArray());
        }
        File scriptFile = new File(scriptDirectory, FilenameUtils.getName(scriptEntry.getPath()));

        if (useScriptInSVN) {
            fileEntryService.writeContentTo(user, scriptEntry.getPath(), scriptDirectory);
        } else {
            FileUtils.writeStringToFile(scriptFile, scriptEntry.getContent(),
                    StringUtils.defaultIfBlank(scriptEntry.getEncoding(), "UTF-8"));
        }
        File doValidate = localScriptTestDriveService.doValidate(scriptDirectory, scriptFile, new Condition(),
                config.isSecurityEnabled(), hostString, getTimeout());
        List<String> readLines = FileUtils.readLines(doValidate);
        StringBuilder output = new StringBuilder();
        String path = config.getHome().getDirectory().getAbsolutePath();
        for (String each : readLines) {
            if (!each.startsWith("*sys-package-mgr")) {
                each = each.replace(path, "${NGRINDER_HOME}");
                output.append(each).append("\n");
            }
        }
        return output.toString();
    } catch (Exception e) {
        throw processException(e);
    }
}

From source file:com.xceptance.xlt.common.util.CSVBasedURLAction.java

/**
 * Constructor based upon read CSV data//from   w w w . ja va 2 s  . c  om
 * 
 * @param record
 *            the record to process
 * @param interpreter
 *            the bean shell interpreter to use
 * @throws UnsupportedEncodingException
 * @throws MalformedURLException
 */
public CSVBasedURLAction(final CSVRecord record, final ParamInterpreter interpreter)
        throws UnsupportedEncodingException, MalformedURLException {
    // no bean shell, so we do not do anything, satisfy final here
    this.interpreter = interpreter;

    // the header is record 1, so we have to subtract one, for autonaming
    this.name = StringUtils.defaultIfBlank(record.get(NAME), "Action-" + (record.getRecordNumber() - 1));

    // take care of type
    String _type = StringUtils.defaultIfBlank(record.get(TYPE), TYPE_ACTION);
    if (!_type.equals(TYPE_ACTION) && !_type.equals(TYPE_STATIC) && !_type.equals(TYPE_XHR_ACTION)) {
        XltLogger.runTimeLogger.warn(MessageFormat.format("Unknown type '{0}' in line {1}, defaulting to 'A'",
                _type, record.getRecordNumber()));
        _type = TYPE_ACTION;
    }
    this.type = _type;

    // we need at least an url, stop here of not given
    this.urlString = record.get(URL);
    if (this.urlString == null) {
        throw new IllegalArgumentException(MessageFormat
                .format("No url given in record in line {0}. Need at least that.", record.getRecordNumber()));
    }
    this.url = interpreter == null ? new URL(this.urlString) : null;

    // take care of method
    String _method = StringUtils.defaultIfBlank(record.get(METHOD), GET);
    if (!_method.equals(GET) && !_method.equals(POST)) {
        XltLogger.runTimeLogger.warn(MessageFormat.format(
                "Unknown method '{0}' in line {1}, defaulting to 'GET'", _method, record.getRecordNumber()));
        _method = GET;
    }
    this.method = _method;

    // get the response code validator
    this.httpResponseCodeValidator = StringUtils.isNotBlank(record.get(RESPONSECODE))
            ? new HttpResponseCodeValidator(Integer.parseInt(record.get(RESPONSECODE)))
            : HttpResponseCodeValidator.getInstance();

    // compile pattern only, if no interpreter shall be used
    this.regexpString = StringUtils.isNotEmpty(record.get(REGEXP)) ? record.get(REGEXP) : null;
    if (interpreter == null) {
        this.regexp = StringUtils.isNotEmpty(regexpString) ? RegExUtils.getPattern(regexpString) : null;
    } else {
        this.regexp = null;
    }

    this.xPath = StringUtils.isNotBlank(record.get(XPATH)) ? record.get(XPATH) : null;
    this.text = StringUtils.isNotEmpty(record.get(TEXT)) ? record.get(TEXT) : null;
    this.encoded = StringUtils.isNotBlank(record.get(ENCODED)) ? Boolean.parseBoolean(record.get(ENCODED))
            : false;

    // ok, get all the parameters
    for (int i = 1; i <= DYNAMIC_GETTER_COUNT; i++) {
        xpathGetterList.add(StringUtils.isNotBlank(record.get(XPATH_GETTER_PREFIX + i))
                ? record.get(XPATH_GETTER_PREFIX + i)
                : null);
        regexpGetterList.add(StringUtils.isNotBlank(record.get(REGEXP_GETTER_PREFIX + i))
                ? record.get(REGEXP_GETTER_PREFIX + i)
                : null);
    }

    // ok, this is the tricky part
    this.parameters = StringUtils.isNotBlank(record.get(PARAMETERS)) ? setupParameters(record.get(PARAMETERS))
            : null;
}

From source file:adalid.util.io.FileBrowser.java

private boolean readFiles() {
    Collection<File> list = FileUtils.listFiles(resourcesFolder, fileFilter(), dirFilter());
    SmallFile sf;/*from   w  ww .j a  v  a  2 s .c om*/
    Charset charset;
    String name;
    String extension;
    for (File file : list) {
        sf = new SmallFile(file.getPath());
        sf.read();
        charset = sf.getCharset();
        name = sf.getName();
        extension = StringUtils.defaultIfBlank(sf.getExtension().toLowerCase(), "?");
        if (charset == null) {
            readingErrors++;
            logger.error(name + " could not be read using any of the specified character sets ");
        } else if (sf.isEmpty()) {
            readingWarnings++;
            logger.warn(name + " is empty ");
        } else {
            files.put(sf.getPath(), sf);
            updateFileTypes(charset + "");
            updateFileTypes(charset + " / " + extension);
        }
    }
    return true;
}

From source file:io.fabric8.elasticsearch.plugin.KibanaUserReindexFilter.java

private String getRequestedIndex(RestRequest request) {
    String uri = StringUtils.defaultIfBlank(request.uri(), "");
    String[] splitUri = uri.split("/");

    if (splitUri.length > 0) {
        return uri.split("/")[1];
    } else {//from   w w w  .  ja va 2  s .  co  m
        return "";
    }
}

From source file:com.sonicle.webtop.core.bol.model.UserEntity.java

private String buildDisplayName() {
    String dn = StringUtils// w ww . ja  v a 2 s . c  om
            .trim(StringUtils.defaultIfBlank(firstName, "") + " " + StringUtils.defaultIfBlank(lastName, ""));
    return StringUtils.isBlank(dn) ? userId : dn;
}

From source file:net.di2e.ecdr.commons.query.QueryConfigurationImpl.java

@Override
public String getDefaultQueryLanguage() {
    return StringUtils.defaultIfBlank(defaultQueryLanguageCustom, defaultQueryLanguage);
}

From source file:io.kamax.mxisd.controller.DefaultExceptionHandler.java

@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(RuntimeException.class)
public String handle(HttpServletRequest req, RuntimeException e) {
    log.error("Unknown error when handling {}", req.getRequestURL(), e);
    return handle(req, "M_UNKNOWN", StringUtils.defaultIfBlank(e.getMessage(),
            "An internal server error occurred. If this error persists, please contact support with reference #"
                    + Instant.now().toEpochMilli()));
}

From source file:adalid.commons.util.TimeUtils.java

public static String getDateFormat() {
    String string = Bundle.getTrimmedToNullString(BUNDLE_KEY_PREFIX + "date.pattern");
    String format = StringUtils.defaultIfBlank(string, DEFAULT_DATE_FORMAT);
    return format;
}

From source file:adalid.commons.util.TimeUtils.java

public static String getTimeFormat() {
    String string = Bundle.getTrimmedToNullString(BUNDLE_KEY_PREFIX + "time.pattern");
    String format = StringUtils.defaultIfBlank(string, DEFAULT_TIME_FORMAT);
    return format;
}

From source file:adalid.commons.util.TimeUtils.java

public static String getTimestampFormat() {
    String string = Bundle.getTrimmedToNullString(BUNDLE_KEY_PREFIX + "both.pattern");
    String format = StringUtils.defaultIfBlank(string, DEFAULT_TIMESTAMP_FORMAT);
    return format;
}