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:net.sf.jsignpdf.InstallCert.java

/**
 * The main - whole logic of Install Cert Tool.
 * /* w w w.j  a  v a2s . c  o m*/
 * @param args
 * @throws Exception
 */
public static void main(String[] args) {
    String host;
    int port;
    char[] passphrase;

    System.out.println("InstallCert - Install CA certificate to Java Keystore");
    System.out.println("=====================================================");

    final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    try {
        if ((args.length == 1) || (args.length == 2)) {
            String[] c = args[0].split(":");
            host = c[0];
            port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
            String p = (args.length == 1) ? "changeit" : args[1];
            passphrase = p.toCharArray();
        } else {
            String tmpStr;
            do {
                System.out.print("Enter hostname or IP address: ");
                tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null);
            } while (tmpStr == null);
            host = tmpStr;
            System.out.print("Enter port number [443]: ");
            tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null);
            port = tmpStr == null ? 443 : Integer.parseInt(tmpStr);
            System.out.print("Enter keystore password [changeit]: ");
            tmpStr = reader.readLine();
            String p = "".equals(tmpStr) ? "changeit" : tmpStr;
            passphrase = p.toCharArray();
        }

        char SEP = File.separatorChar;
        final File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security");
        final File file = new File(dir, "cacerts");

        System.out.println("Loading KeyStore " + file + "...");
        InputStream in = new FileInputStream(file);
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(in, passphrase);
        in.close();

        SSLContext context = SSLContext.getInstance("TLS");
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
        SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
        context.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory factory = context.getSocketFactory();

        System.out.println("Opening connection to " + host + ":" + port + "...");
        SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
        socket.setSoTimeout(10000);
        try {
            System.out.println("Starting SSL handshake...");
            socket.startHandshake();
            socket.close();
            System.out.println();
            System.out.println("No errors, certificate is already trusted");
        } catch (SSLException e) {
            System.out.println();
            System.out.println("Certificate is not yet trusted.");
            //        e.printStackTrace(System.out);
        }

        X509Certificate[] chain = tm.chain;
        if (chain == null) {
            System.out.println("Could not obtain server certificate chain");
            return;
        }

        System.out.println();
        System.out.println("Server sent " + chain.length + " certificate(s):");
        System.out.println();
        MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        for (int i = 0; i < chain.length; i++) {
            X509Certificate cert = chain[i];
            System.out.println(" " + (i + 1) + " Subject " + cert.getSubjectDN());
            System.out.println("   Issuer  " + cert.getIssuerDN());
            sha1.update(cert.getEncoded());
            System.out.println("   sha1    " + toHexString(sha1.digest()));
            md5.update(cert.getEncoded());
            System.out.println("   md5     " + toHexString(md5.digest()));
            System.out.println();
        }

        System.out.print("Enter certificate to add to trusted keystore or 'q' to quit [1]: ");
        String line = reader.readLine().trim();
        int k = -1;
        try {
            k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
        } catch (NumberFormatException e) {
        }

        if (k < 0 || k >= chain.length) {
            System.out.println("KeyStore not changed");
        } else {
            try {
                System.out.println("Creating keystore backup");
                final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                final File backupFile = new File(dir,
                        CACERTS_KEYSTORE + "." + dateFormat.format(new java.util.Date()));
                final FileInputStream fis = new FileInputStream(file);
                final FileOutputStream fos = new FileOutputStream(backupFile);
                IOUtils.copy(fis, fos);
                fis.close();
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("Installing certificate...");

            X509Certificate cert = chain[k];
            String alias = host + "-" + (k + 1);
            ks.setCertificateEntry(alias, cert);

            OutputStream out = new FileOutputStream(file);
            ks.store(out, passphrase);
            out.close();

            System.out.println();
            System.out.println(cert);
            System.out.println();
            System.out.println("Added certificate to keystore '" + file + "' using alias '" + alias + "'");
        }
    } catch (Exception e) {
        System.out.println();
        System.out.println("----------------------------------------------");
        System.out.println("Problem occured during installing certificate:");
        e.printStackTrace();
        System.out.println("----------------------------------------------");
    }
    System.out.println("Press Enter to finish...");
    try {
        reader.readLine();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.esri.geoportal.harvester.api.base.SimpleScrambler.java

/**
 * Encodes string./*from w  ww. j  a  v  a 2s . c o m*/
 * @param txt string to encode
 * @return encoded string or <code>null</code> if error encoding string
 */
public static String encode(String txt) {
    txt = StringUtils.defaultIfEmpty(txt, "");
    try {
        CRC32 crC32 = new CRC32();
        crC32.update(txt.getBytes("UTF-8"));
        long crc = crC32.getValue();
        String crctxt = String.format("%10d%s", crc, txt);
        Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(crctxt.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException ex) {
        return null;
    }
}

From source file:controllers.base.LoggedAction.java

public static String getLogEntry(Context ctx, String message) {
    if (ctx == null) {
        ctx = Context.current();//from  w  ww .j  ava 2s  . c  om
        Validate.notNull(ctx);
    }

    return String.format(
            "%s - { request-method: %s, request-uri: %s, username: %s, remote-address: %s, session: %s }",
            message, ctx.request().method(), ctx.request().uri(),
            StringUtils.defaultIfEmpty(SessionedAction.getUsername(ctx), "anonymous"),
            ctx.request().remoteAddress(),
            StringUtils.defaultIfEmpty(SessionedAction.getSessionKey(ctx), "none"));
}

From source file:edu.sabanciuniv.sentilab.utils.text.nlp.base.PosTag.java

/**
 * Splits a tags string into its constituents.
 * @param tagsString the {@code string} containing tags separating by an accepted separator.
 * @return an {@link Iterable} of tags./*  ww  w .ja  v a 2s.c om*/
 */
public static Iterable<String> splitTagsString(String tagsString) {
    return Splitter.on(Pattern.compile("\\||,|;|\\s+")).split(StringUtils.defaultIfEmpty(tagsString, ""));
}

From source file:com.esri.geoportal.harvester.api.base.SimpleScrambler.java

/**
 * Decodes string.//from w  w  w  . j a  v  a 2s.  c  o  m
 * @param encoded encoded string to decode
 * @return decoded string or <code>null</code> if error decoding string
 */
public static String decode(String encoded) {
    try {
        encoded = StringUtils.defaultIfEmpty(encoded, "");
        Base64.Decoder decoder = Base64.getDecoder();
        String crctxt = new String(decoder.decode(encoded), "UTF-8");
        if (crctxt.length() < 10) {
            return null;
        }
        long crc = Long.parseLong(StringUtils.trimToEmpty(crctxt.substring(0, 10)));
        String txt = crctxt.substring(10);
        CRC32 crC32 = new CRC32();
        crC32.update(txt.getBytes("UTF-8"));
        if (crc != crC32.getValue()) {
            return null;
        }
        return txt;
    } catch (NumberFormatException | UnsupportedEncodingException ex) {
        return null;
    }
}

From source file:badminton.common.Util.StringUtil.java

/**
 * <p>/* w  w w.  ja va2s .c  o m*/
 * Returns either the passed in String, or if the String is empty or
 * <code>null</code>, the value of <code>defaultStr</code>.
 * </p>
 *
 * @param str
 *            the String to check, may be null
 * @param defaultStr
 *            the default String to return if the input is empty
 * @return the passed in String, or the default
 */
public static String defaultIfEmpty(final String str, final String defaultStr) {
    return StringUtils.defaultIfEmpty(str, defaultStr);
}

From source file:kenh.expl.functions.DefaultIfEmpty.java

public String process(String str, String defaultStr) {
    return StringUtils.defaultIfEmpty(str, defaultStr);
}

From source file:com.github.ferstl.depgraph.graph.style.StyleKey.java

private StyleKey(String[] parts) {
    if (parts.length > NUM_ELEMENTS) {
        throw new IllegalArgumentException(
                "Too many parts. Expecting '<groupId>:<artifactId>:<version>:<scope>:<type>'");
    }//from w w w . jav  a2 s. c o m

    String[] expanded = new String[NUM_ELEMENTS];
    for (int i = 0; i < parts.length; i++) {
        expanded[i] = StringUtils.defaultIfEmpty(parts[i], null);
    }

    this.groupId = expanded[0];
    this.artifactId = expanded[1];
    this.scope = expanded[2];
    this.type = expanded[3];
    this.version = expanded[4];
}

From source file:com.thinkbiganalytics.util.TableRegisterConfiguration.java

public TableRegisterConfiguration(String feedRoot, String profileRoot, String masterRoot) {
    super();//from  www .  j a va  2 s .  c o m
    this.feedRoot = StringUtils.defaultIfEmpty(feedRoot, DEFAULT_FEED);
    this.profileRoot = StringUtils.defaultIfEmpty(profileRoot, DEFAULT_PROFILE);
    this.masterRoot = StringUtils.defaultIfEmpty(masterRoot, DEFAULT_MASTER);
}

From source file:com.yqboots.initializer.core.ProjectMetadata.java

public String getDescription() {
    return StringUtils.defaultIfEmpty(this.description, StringUtils.EMPTY);
}