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:adalid.util.io.FileBrowser.java

private void printDetail(String type) {
    if (detailAll || matches(type)) {
        Charset charset;/*from  w  w  w  .  j  av a 2  s.com*/
        String extension;
        String baseFolderPathString = baseFolderPath.toString();
        String tab = type.contains("/") ? "\t" : "";
        for (SmallFile sf : files.values()) {
            charset = sf.getCharset();
            extension = StringUtils.defaultIfBlank(sf.getExtension(), "?");
            if (charset != null && type.equals(charset + " / " + extension)) {
                logger.info(tab + "\t" + StringUtils.removeStartIgnoreCase(sf.getName(), baseFolderPathString));
            }
        }
    }
}

From source file:adalid.commons.velocity.VelocityEngineer.java

public static void write(VelocityContext context, String tempname, String filename, String charset1,
        String charset2) throws Exception {
    charset1 = StringUtils.defaultIfBlank(charset1, getTemplateEncoding(tempname));
    charset2 = StringUtils.defaultIfBlank(charset2, getDocumentEncoding(filename));
    //      if (!charset1.equals(VELOCITY_TEMPLATE_DEFAULT_ENCODING)) {
    //          log(Level.INFO, "write", "template=" + tempname, "template-encoding=" + charset1, "document-encoding=" + charset2);
    //      }/*from  w w  w . ja  v  a  2s .  c o  m*/
    //      if (!charset1.equals(charset2)) {
    //          log(Level.WARN, "write", "template=" + tempname, "template-encoding=" + charset1, "document-encoding=" + charset2);
    //      }
    StringWriter sw = merge(context, tempname, charset1);
    if (sw != null) {
        FileOutputStream fileOutputStream;
        OutputStreamWriter fileWriter = null;
        BufferedWriter bufferedWriter = null;
        try {
            fileOutputStream = new FileOutputStream(filename);
            fileWriter = new OutputStreamWriter(fileOutputStream, charset2);
            bufferedWriter = new BufferedWriter(fileWriter);
            bufferedWriter.write(sw.toString());
        } catch (IOException ex) {
            throw ex;
        } finally {
            if (bufferedWriter != null) {
                try {
                    bufferedWriter.close();
                } catch (IOException ex) {
                    logger.fatal(ThrowableUtils.getString(ex), ex);
                }
            }
            if (fileWriter != null) {
                try {
                    fileWriter.close();
                } catch (IOException ex) {
                    logger.fatal(ThrowableUtils.getString(ex), ex);
                }
            }
        }
    }
}

From source file:com.kibana.multitenancy.plugin.acl.DynamicACLFilter.java

private String getUser(RestRequest request) {

    //Sushant:Getting user in case of Basic Authentication
    String username = "";
    //Sushant:Scenario when user Authenticated at Proxy level itself
    String proxyAuthUser = (String) ObjectUtils.defaultIfNull(request.header(proxyUserHeader), "");
    //Sushant: Scenario when user Authenticated at Proxy level itself

    String basicAuthorizationHeader = StringUtils.defaultIfBlank(request.header("Authorization"), "");
    if (StringUtils.isNotEmpty(basicAuthorizationHeader)) {
        String decodedBasicHeader = new String(
                DatatypeConverter.parseBase64Binary(basicAuthorizationHeader.split(" ")[1]),
                StandardCharsets.US_ASCII);
        final String[] decodedBasicHeaderParts = decodedBasicHeader.split(":");
        username = decodedBasicHeaderParts[0];
        decodedBasicHeader = null;/* w ww. j a  v  a 2s.c om*/
        basicAuthorizationHeader = null;
        logger.debug("User '{}' is authenticated", username);
    }
    return username;

}

From source file:elaborate.editor.export.tei.TeiMaker.java

private int processEntry(int _pageno, Element body, String _currentFolio, ProjectEntry projectEntry) {
    int pageno = _pageno;
    String currentFolio = _currentFolio;
    String folio = StringUtils.defaultIfBlank(projectEntry.getMetadataValue("Folio number"), "")
            + StringUtils.defaultIfBlank(projectEntry.getMetadataValue("Folio side"), "");
    if (!currentFolio.equals(folio)) {
        pageno = addPb(body, pageno, projectEntry, folio);
    }//from ww  w  .  ja v a  2  s. com
    // addCb(body, projectEntry);
    currentFolio = folio;

    Element entryDiv = tei.createElement("div");
    entryDiv.setAttribute("xml:id", "e" + projectEntry.getId());
    entryDiv.setAttribute("n", projectEntry.getName());

    addEntryInterpGrp(entryDiv, projectEntry);

    List<Transcription> orderedTranscriptions = Lists.newArrayList(projectEntry.getTranscriptions());
    Collections.sort(orderedTranscriptions, ORDER_BY_TYPE);
    for (Transcription transcription : orderedTranscriptions) {
        HtmlTeiConverter htmlTeiConverter = new HtmlTeiConverter(transcription.getBody(), config,
                transcription.getTranscriptionType().getName(), entityManager);
        Node transcriptionNode = htmlTeiConverter.getContent();
        Node importedTranscriptionNode = tei.importNode(transcriptionNode, true);
        Node child = importedTranscriptionNode.getFirstChild();
        while (child != null) {
            Node nextSibling = child.getNextSibling();
            if (child.getNodeName().equals("div") && child.hasChildNodes()) {
                entryDiv.appendChild(child);
            }
            child = nextSibling;
        }
    }
    body.appendChild(entryDiv);
    return pageno;
}

From source file:com.adaptris.security.Config.java

public KeystoreLocation buildKeystore(String ksUrl, String cn, boolean overwrite) throws Exception {

    String commonName = StringUtils.defaultIfBlank(cn, config.getProperty(KEYSTORE_COMMON_PRIVKEY_ALIAS));
    KeystoreLocation ksc = KeystoreFactory.getDefault().create(ksUrl,
            config.getProperty(Config.KEYSTORE_COMMON_KEYSTORE_PW).toCharArray());
    KeystoreProxy ksp = KeystoreFactory.getDefault().create(ksc);
    if (ksc.exists() && overwrite == false) {
        ksp.load();//from ww  w  . java  2  s.  c om
    }
    CertificateBuilder builder = getBuilder(commonName);
    Certificate selfCert = builder.createSelfSignedCertificate();
    PrivateKey privkey = builder.getPrivateKey();
    char[] password = config.getProperty(KEYSTORE_COMMON_PRIVKEY_PW).toCharArray();
    Certificate[] certChain = new Certificate[1];
    certChain[0] = selfCert;
    ksp.setPrivateKey(commonName, privkey, password, certChain);
    ksp.commit();
    return ksc;
}

From source file:com.openshift.internal.restclient.model.BuildConfig.java

@Override
public void addBuildTrigger(IBuildTrigger trigger) {
    ModelNode triggers = get(BUILDCONFIG_TRIGGERS);
    ModelNode triggerNode = triggers.add();
    switch (trigger.getType()) {
    case BuildTriggerType.generic:
    case BuildTriggerType.GENERIC:
        if (!(trigger instanceof IWebhookTrigger)) {
            throw new IllegalArgumentException(
                    "IBuildTrigger of type generic does not implement IWebhookTrigger");
        }/*www .  j  a v a  2s  .c  o m*/
        IWebhookTrigger generic = (IWebhookTrigger) trigger;
        triggerNode.get(getPath(BUILD_CONFIG_WEBHOOK_GENERIC_SECRET)).set(generic.getSecret());
        break;
    case BuildTriggerType.github:
    case BuildTriggerType.GITHUB:
        if (!(trigger instanceof IWebhookTrigger)) {
            throw new IllegalArgumentException(
                    "IBuildTrigger of type github does not implement IWebhookTrigger");
        }
        IWebhookTrigger github = (IWebhookTrigger) trigger;
        triggerNode.get(getPath(BUILD_CONFIG_WEBHOOK_GITHUB_SECRET)).set(github.getSecret());
        break;
    case BuildTriggerType.imageChange:
    case BuildTriggerType.IMAGE_CHANGE:
        if (!(trigger instanceof IImageChangeTrigger)) {
            throw new IllegalArgumentException(
                    "IBuildTrigger of type imageChange does not implement IImageChangeTrigger");
        }
        IImageChangeTrigger image = (IImageChangeTrigger) trigger;
        triggerNode.get(getPath(BUILD_CONFIG_IMAGECHANGE_IMAGE)).set(defaultIfNull(image.getImage()));
        triggerNode.get(getPath(BUILD_CONFIG_IMAGECHANGE_NAME)).set(defaultIfNull(image.getFrom()));
        triggerNode.get(getPath(BUILD_CONFIG_IMAGECHANGE_TAG))
                .set(StringUtils.defaultIfBlank(image.getTag(), ""));
        break;
    }
    triggerNode.get("type").set(trigger.getType());
}

From source file:com.hack23.cia.web.impl.ui.application.views.common.chartfactory.impl.DocumentChartDataManagerImpl.java

/**
 * Adds the document history by org data.
 *
 * @param dataSeries//from w  w  w . java  2s  . c  om
 *            the data series
 * @param series
 *            the series
 * @param itemList
 *            the item list
 */
private static void addDocumentHistoryByOrgData(final DataSeries dataSeries, final Series series,
        final List<ViewRiksdagenOrgDocumentDailySummary> itemList) {
    final Map<String, List<ViewRiksdagenOrgDocumentDailySummary>> map = itemList.parallelStream()
            .filter(t -> t != null)
            .collect(Collectors.groupingBy(t -> StringUtils.defaultIfBlank(t.getDocumentType(), NO_INFO)));

    for (final Entry<String, List<ViewRiksdagenOrgDocumentDailySummary>> entry : map.entrySet()) {

        series.addSeries(new XYseries().setLabel(entry.getKey()));

        dataSeries.newSeries();
        if (entry.getValue() != null) {
            for (final ViewRiksdagenOrgDocumentDailySummary item : entry.getValue()) {
                if (item != null) {
                    dataSeries.add(item.getEmbeddedId().getPublicDate(), item.getTotal());
                }
            }
        } else {
            LOGGER.info(LOG_MSG_MISSING_DATA_FOR_KEY, entry);
        }

    }
}

From source file:io.kamax.mxisd.config.ldap.LdapConfig.java

@PostConstruct
public void build() {
    log.info("--- " + getConfigName() + " Config ---");
    log.info("Enabled: {}", isEnabled());

    if (!isEnabled()) {
        return;/*from   w w  w. j a v a 2  s . com*/
    }

    if (StringUtils.isBlank(connection.getHost())) {
        throw new IllegalStateException("LDAP Host must be configured!");
    }

    if (connection.getPort() < 1 || connection.getPort() > 65535) {
        throw new IllegalStateException("LDAP port is not valid");
    }

    if (StringUtils.isBlank(connection.getBaseDn())) {
        throw new ConfigurationException("ldap.connection.baseDn");
    }

    if (StringUtils.isBlank(attribute.getUid().getType())) {
        throw new IllegalStateException("Attribute UID Type cannot be empty");
    }

    if (StringUtils.isBlank(attribute.getUid().getValue())) {
        throw new IllegalStateException("Attribute UID value cannot be empty");
    }

    String uidType = attribute.getUid().getType();
    if (!StringUtils.equals(LdapBackend.UID, uidType) && !StringUtils.equals(LdapBackend.MATRIX_ID, uidType)) {
        throw new IllegalArgumentException("Unsupported LDAP UID type: " + uidType);
    }

    if (StringUtils.isBlank(identity.getToken())) {
        throw new ConfigurationException("ldap.identity.token");
    }

    // Build queries
    attribute.getThreepid().forEach((k, v) -> {
        if (StringUtils.isBlank(identity.getMedium().get(k))) {
            if (ThreePidMedium.PhoneNumber.is(k)) {
                identity.getMedium().put(k, LdapBackend.buildOrQuery("+" + getIdentity().getToken(), v));
            } else {
                identity.getMedium().put(k, LdapBackend.buildOrQuery(getIdentity().getToken(), v));
            }
        }
    });

    getAuth().setFilter(StringUtils.defaultIfBlank(getAuth().getFilter(), getFilter()));
    getDirectory().setFilter(StringUtils.defaultIfBlank(getDirectory().getFilter(), getFilter()));
    getIdentity().setFilter(StringUtils.defaultIfBlank(getIdentity().getFilter(), getFilter()));

    log.info("Host: {}", connection.getHost());
    log.info("Port: {}", connection.getPort());
    log.info("TLS: {}", connection.isTls());
    log.info("Bind DN: {}", connection.getBindDn());
    log.info("Base DN: {}", connection.getBaseDn());

    log.info("Attribute: {}", GsonUtil.get().toJson(attribute));
    log.info("Auth: {}", GsonUtil.get().toJson(auth));
    log.info("Directory: {}", GsonUtil.get().toJson(directory));
    log.info("Identity: {}", GsonUtil.get().toJson(identity));
}

From source file:com.iyonger.apm.web.controller.FileEntryController.java

/**
 * Provide new file creation form data./* w w  w .j  a v a 2 s.  co m*/
 *
 * @param user                  current user
 * @param path                  path in which a file will be added
 * @param testUrl               url which the script may use
 * @param fileName              fileName
 * @param scriptType            Type of script. optional
 * @param createLibAndResources true if libs and resources should be created as well.
 * @param redirectAttributes    redirect attributes storage
 * @param model                 model.
 * @return script/editor"
 */
@RequestMapping(value = "/new/**", params = "type=script", method = RequestMethod.POST)
public String createForm(@RemainedPath String path,
        @RequestParam(value = "testUrl", required = false) String testUrl,
        @RequestParam("fileName") String fileName,
        @RequestParam(value = "scriptType", required = false) String scriptType,
        @RequestParam(value = "createLibAndResource", defaultValue = "false") boolean createLibAndResources,
        @RequestParam(value = "options", required = false) String options,
        RedirectAttributes redirectAttributes, ModelMap model) throws Exception {
    User user = getCurrentUser();

    fileName = StringUtils.trimToEmpty(fileName);
    String name = "Test1";
    if (StringUtils.isEmpty(testUrl)) {
        testUrl = StringUtils.defaultIfBlank(testUrl, "http://please_modify_this.com");
    } else {
        name = UrlUtils.getHost(testUrl);
    }
    ScriptHandler scriptHandler = fileEntryService.getScriptHandler(scriptType);
    FileEntry entry = new FileEntry();
    entry.setPath(fileName);
    if (scriptHandler instanceof ProjectHandler) {
        if (!fileEntryService.hasFileEntry(user, PathUtils.join(path, fileName))) {
            fileEntryService.prepareNewEntry(user, path, fileName, name, testUrl, scriptHandler,
                    createLibAndResources, options);
            redirectAttributes.addFlashAttribute("message", fileName + " project is created.");
            return "redirect:/script/list/" + path + "/" + fileName;
        } else {
            redirectAttributes.addFlashAttribute("exception",
                    fileName + " is already existing. Please choose the different name");
            return "redirect:/script/list/" + path + "/";
        }

    } else {
        String fullPath = PathUtils.join(path, fileName);
        if (fileEntryService.hasFileEntry(user, fullPath)) {
            model.addAttribute("file", fileEntryService.getOne(user, fullPath));
        } else {
            model.addAttribute("file", fileEntryService.prepareNewEntry(user, path, fileName, name, testUrl,
                    scriptHandler, createLibAndResources, options));
        }
    }
    model.addAttribute("breadcrumbPath", getScriptPathBreadcrumbs(PathUtils.join(path, fileName)));
    model.addAttribute("scriptHandler", scriptHandler);
    model.addAttribute("createLibAndResource", createLibAndResources);
    return "/script/editor";
}

From source file:com.adaptris.core.mail.MailConsumerImp.java

String regularExpressionStyle() {
    return StringUtils.defaultIfBlank(getRegularExpressionStyle(), MatchProxyFactory.DEFAULT_REGEXP_STYLE);
}