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

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

Introduction

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

Prototype

public static int length(final CharSequence cs) 

Source Link

Document

Gets a CharSequence length or 0 if the CharSequence is null .

Usage

From source file:com.adguard.commons.web.UrlUtils.java

/**
 * Sends a post request/*w ww .  j a  v a  2  s  .  c o m*/
 *
 * @param url           url
 * @param postData      data to post
 * @param encoding      response encoding
 * @param contentType   content type
 * @param readTimeout   socket read timeout
 * @param socketTimeout socket connect timeout
 * @return downloaded string
 */
public static String postRequest(String url, String postData, String encoding, String contentType,
        int readTimeout, int socketTimeout) {

    try {
        return postRequest(new URL(url), postData, encoding, contentType, readTimeout, socketTimeout);
    } catch (MalformedURLException ex) {
        LOG.error("Error posting request to {}, post data length={}", url, StringUtils.length(postData), ex);
        return null;
    }
}

From source file:com.adguard.commons.web.UrlUtils.java

/**
 * Sends a POST request/*from   w ww  .  jav  a  2  s. c  o m*/
 *
 * @param url           URL
 * @param postData      Post request body
 * @param encoding      Post request body encoding
 * @param contentType   Body content type
 * @param compress      If true - compress bod
 * @param readTimeout   Read timeout
 * @param socketTimeout Socket timeout
 * @return Response
 */
public static String postRequest(URL url, String postData, String encoding, String contentType,
        boolean compress, int readTimeout, int socketTimeout) {
    HttpURLConnection connection = null;
    OutputStream outputStream = null;

    try {
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        if (contentType != null) {
            connection.setRequestProperty("Content-Type", contentType);
        }
        if (compress) {
            connection.setRequestProperty("Content-Encoding", "gzip");
        }
        connection.setConnectTimeout(socketTimeout);
        connection.setReadTimeout(readTimeout);
        connection.setDoOutput(true);
        connection.connect();
        if (postData != null) {
            outputStream = connection.getOutputStream();

            if (compress) {
                outputStream = new GZIPOutputStream(outputStream);
            }

            if (encoding != null) {
                IOUtils.write(postData, outputStream, encoding);
            } else {
                IOUtils.write(postData, outputStream);
            }

            if (compress) {
                ((GZIPOutputStream) outputStream).finish();
            } else {
                outputStream.flush();
            }
        }

        return IOUtils.toString(connection.getInputStream(), encoding);
    } catch (Exception ex) {
        LOG.error("Error posting request to {}, post data length={}\r\n", url, StringUtils.length(postData),
                ex);
        // Ignoring exception
        return null;
    } finally {
        IOUtils.closeQuietly(outputStream);

        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:com.neophob.sematrix.core.properties.ApplicationConfigurationHelper.java

/**
 * Parses the art net devices./* www.j  a va2  s.  co  m*/
 *
 * @return the int
 */
private int parseArtNetDevices() {
    artNetDevice = new ArrayList<DeviceConfig>();

    //minimal ip length 1.1.1.1
    if (StringUtils.length(getArtNetIp()) > 6 && parseOutputXResolution() > 0 && parseOutputYResolution() > 0) {
        this.deviceXResolution = parseOutputXResolution();
        this.deviceYResolution = parseOutputYResolution();

        String value = config.getProperty(ConfigConstant.ARTNET_ROW1);
        if (StringUtils.isNotBlank(value)) {

            devicesInRow1 = 0;
            devicesInRow2 = 0;

            for (String s : value.split(ConfigConstant.DELIM)) {
                try {
                    DeviceConfig cfg = DeviceConfig.valueOf(StringUtils.strip(s));
                    artNetDevice.add(cfg);
                    devicesInRow1++;
                } catch (Exception e) {
                    LOG.log(Level.WARNING, FAILED_TO_PARSE, s);
                }
            }
        }

        value = config.getProperty(ConfigConstant.ARTNET_ROW2);
        if (StringUtils.isNotBlank(value)) {
            for (String s : value.split(ConfigConstant.DELIM)) {
                try {
                    DeviceConfig cfg = DeviceConfig.valueOf(StringUtils.strip(s));
                    artNetDevice.add(cfg);
                    devicesInRow2++;
                } catch (Exception e) {
                    LOG.log(Level.WARNING, FAILED_TO_PARSE, s);
                }
            }
        }
    }

    return artNetDevice.size();
}

From source file:com.neophob.sematrix.core.properties.ApplicationConfigurationHelper.java

/**
  * Parses the e131 devices./*from w w w.  j a v a2  s . com*/
  *
  * @return the int
  */
private int parseE131Devices() {
    e131Device = new ArrayList<DeviceConfig>();

    if (StringUtils.length(getE131Ip()) > 6 && parseOutputXResolution() > 0 && parseOutputYResolution() > 0) {

        this.deviceXResolution = parseOutputXResolution();
        this.deviceYResolution = parseOutputYResolution();

        String value = config.getProperty(ConfigConstant.E131_ROW1);
        if (StringUtils.isNotBlank(value)) {

            devicesInRow1 = 0;
            devicesInRow2 = 0;

            for (String s : value.split(ConfigConstant.DELIM)) {
                try {
                    DeviceConfig cfg = DeviceConfig.valueOf(StringUtils.strip(s));
                    e131Device.add(cfg);
                    devicesInRow1++;
                } catch (Exception e) {
                    LOG.log(Level.WARNING, FAILED_TO_PARSE, s);
                }
            }
        }

        value = config.getProperty(ConfigConstant.E131_ROW2);
        if (StringUtils.isNotBlank(value)) {
            for (String s : value.split(ConfigConstant.DELIM)) {
                try {
                    DeviceConfig cfg = DeviceConfig.valueOf(StringUtils.strip(s));
                    e131Device.add(cfg);
                    devicesInRow2++;
                } catch (Exception e) {
                    LOG.log(Level.WARNING, FAILED_TO_PARSE, s);
                }
            }
        }
    }

    return e131Device.size();
}

From source file:com.neophob.sematrix.core.properties.ApplicationConfigurationHelper.java

/**
  * /*  w  w w. jav  a2s.com*/
  * @return
  */
private int parseUdpDevices() {
    if (StringUtils.length(getUdpIp()) > 6 && parseOutputXResolution() > 0 && parseOutputYResolution() > 0) {
        this.devicesInRow1 = 1;
        this.devicesInRow2 = 0;
        this.deviceXResolution = parseOutputXResolution();
        this.deviceYResolution = parseOutputYResolution();
        return 1;
    }

    return 0;
}

From source file:ch.cyberduck.ui.cocoa.controller.InfoController.java

/**
 * Permission value from input field.//from  w w  w .  java  2  s . c o  m
 *
 * @return Null if invalid string has been entered entered,
 */
private Permission getPermissionFromOctalField() {
    if (StringUtils.isNotBlank(octalField.stringValue())) {
        if (StringUtils.length(octalField.stringValue()) >= 3) {
            if (StringUtils.isNumeric(octalField.stringValue())) {
                return new Permission(Integer.valueOf(octalField.stringValue()).intValue());
            }
        }
    }
    log.warn(String.format("Invalid octal field input %s", octalField.stringValue()));
    return null;
}

From source file:nl.sidn.pcap.parquet.DNSParquetPacketWriter.java

/**
 * Write EDNS0 option (if any are present) to file. 
 * @param message/* ww  w  .  ja  va2 s  . c o m*/
 * @param builder
 */
private void writeRequestOptions(Message message, GenericRecordBuilder builder) {
    if (message == null) {
        return;
    }

    OPTResourceRecord opt = message.getPseudo();
    if (opt != null) {
        builder.set("edns_udp", (int) opt.getUdpPlayloadSize()).set("edns_version", (int) opt.getVersion())
                .set("edns_do", opt.getDnssecDo()).set("edns_padding", -1); //use default no padding found

        String other = null;
        for (EDNS0Option option : opt.getOptions()) {
            if (option instanceof PingOption) {
                builder.set("edns_ping", true);
            } else if (option instanceof DNSSECOption) {
                if (option.getCode() == DNSSECOption.OPTION_CODE_DAU) {
                    builder.set("edns_dnssec_dau", ((DNSSECOption) option).export());
                } else if (option.getCode() == DNSSECOption.OPTION_CODE_DHU) {
                    builder.set("edns_dnssec_dhu", ((DNSSECOption) option).export());
                } else { //N3U
                    builder.set("edns_dnssec_n3u", ((DNSSECOption) option).export());
                }
            } else if (option instanceof ClientSubnetOption) {
                ClientSubnetOption scOption = (ClientSubnetOption) option;
                //get client country and asn
                String clientCountry = null;
                String clientASN = null;
                if (scOption.getAddress() != null) {
                    if (scOption.isIPv4()) {
                        try {
                            byte[] addrBytes = IPUtil.ipv4tobytes(scOption.getAddress());
                            clientCountry = geoLookup.lookupCountry(addrBytes);
                            clientASN = geoLookup.lookupASN(addrBytes, true);
                        } catch (Exception e) {
                            LOGGER.error("Could not convert IPv4 addr to bytes, invalid address? :"
                                    + scOption.getAddress());
                        }
                    } else {
                        try {
                            byte[] addrBytes = IPUtil.ipv6tobytes(scOption.getAddress());
                            clientCountry = geoLookup.lookupCountry(addrBytes);
                            clientASN = geoLookup.lookupASN(addrBytes, false);
                        } catch (Exception e) {
                            LOGGER.error("Could not convert IPv6 addr to bytes, invalid address? :"
                                    + scOption.getAddress());
                        }
                    }
                }
                builder.set("edns_client_subnet", scOption.export()).set("edns_client_subnet_asn", clientASN)
                        .set("edns_client_subnet_country", clientCountry);

            } else if (option instanceof PaddingOption) {
                builder.set("edns_padding", ((PaddingOption) option).getLength());
            } else if (option instanceof KeyTagOption) {
                KeyTagOption kto = (KeyTagOption) option;
                builder.set("edns_keytag_count", kto.getKeytags().size());
                builder.set("edns_keytag_list", Joiner.on(",").join(kto.getKeytags()));
            } else {
                //other
                if (StringUtils.length(other) > 0) {
                    other = other + "," + option.getCode();
                } else {
                    other = String.valueOf(option.getCode());
                }
            }
        }

        if (other != null) {
            builder.set("edns_other", other);
        }
    }
}

From source file:org.apache.metron.stellar.common.shell.specials.MagicDefineGlobal.java

@Override
public StellarResult execute(String command, StellarShellExecutor executor) {

    // grab the expression in '%define <assign-expression>'
    String assignExpr = StringUtils.trimToEmpty(command.substring(MAGIC_DEFINE.length()));
    if (StringUtils.length(assignExpr) < 1) {
        return error(MAGIC_DEFINE + " missing assignment expression");
    }// www  .j ava2s  .c o m

    // the expression must be an assignment
    if (!StellarAssignment.isAssignment(assignExpr)) {
        return error(MAGIC_DEFINE + " expected assignment expression");
    }

    // execute the expression
    StellarAssignment expr = StellarAssignment.from(assignExpr);
    StellarResult result = executor.execute(expr.getStatement());

    // execution must be successful
    if (!result.isSuccess()) {
        return error(MAGIC_DEFINE + " expression execution failed");
    }

    // expression should have a result
    if (!result.getValue().isPresent()) {
        return error(MAGIC_DEFINE + " expression produced no result");
    }

    // alter the global configuration
    Object value = result.getValue().get();
    executor.getGlobalConfig().put(expr.getVariable(), value);

    return success(value);
}

From source file:org.apache.rave.portal.web.controller.admin.AdminControllerUtil.java

public static void checkTokens(String sessionToken, String token, SessionStatus status) {
    if (StringUtils.length(sessionToken) != TOKEN_LENGTH || !(sessionToken.equals(token))) {
        status.setComplete();/*from  w ww.j a va  2  s .  c  o  m*/
        throw new SecurityException("Token does not match");
    }
}

From source file:org.blocks4j.reconf.client.constructors.SimpleConstructor.java

public Object construct(MethodData data) throws Throwable {
    Class<?> returnClass = (Class<?>) data.getReturnType();

    String trimmed = StringUtils.defaultString(StringUtils.trim(data.getValue()));
    if (!trimmed.startsWith("'") || !trimmed.endsWith("'")) {
        throw new RuntimeException(msg.format("error.invalid.string", data.getValue(), data.getMethod()));
    }//  w  w w.j a  va 2 s  . c om

    String wholeValue = StringUtils.substring(trimmed, 1, trimmed.length() - 1);

    if (String.class.equals(returnClass)) {
        return wholeValue;
    }

    if (null == data.getValue()) {
        return null;
    }

    if (Object.class.equals(returnClass)) {
        returnClass = String.class;
    }

    if (char.class.equals(data.getReturnType()) || Character.class.equals(data.getReturnType())) {
        if (StringUtils.length(wholeValue) == 1) {
            return CharUtils.toChar(wholeValue);
        }
        return CharUtils.toChar(StringUtils.replace(wholeValue, " ", ""));
    }

    if (primitiveBoxing.containsKey(returnClass)) {
        if (StringUtils.isBlank(wholeValue)) {
            return null;
        }
        Method parser = primitiveBoxing.get(returnClass).getMethod(
                "parse" + StringUtils.capitalize(returnClass.getSimpleName()), new Class<?>[] { String.class });
        return parser.invoke(primitiveBoxing.get(returnClass), new Object[] { StringUtils.trim(wholeValue) });
    }

    Method valueOf = null;
    try {
        valueOf = returnClass.getMethod("valueOf", new Class<?>[] { String.class });
    } catch (NoSuchMethodException ignored) {
    }

    if (valueOf == null) {
        try {

            valueOf = returnClass.getMethod("valueOf", new Class<?>[] { Object.class });
        } catch (NoSuchMethodException ignored) {
        }
    }

    if (null != valueOf) {
        if (StringUtils.isEmpty(wholeValue)) {
            return null;
        }
        return valueOf.invoke(data.getReturnType(), new Object[] { StringUtils.trim(wholeValue) });
    }

    Constructor<?> constructor = null;

    try {
        constructor = returnClass.getConstructor(String.class);
        constructor.setAccessible(true);

    } catch (NoSuchMethodException ignored) {
        throw new IllegalStateException(
                msg.format("error.string.constructor", returnClass.getSimpleName(), data.getMethod()));
    }

    try {
        return constructor.newInstance(wholeValue);

    } catch (Exception e) {
        if (e.getCause() != null && e.getCause() instanceof NumberFormatException) {
            return constructor.newInstance(StringUtils.trim(wholeValue));
        }
        throw e;
    }
}