Java Code Examples for org.apache.commons.lang3.StringUtils.trimToNull()

The following are Jave code examples for showing how to use trimToNull() of the org.apache.commons.lang3.StringUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: yadaframework   File: YadaSqlBuilder.java   View Source Code Vote up 6 votes
private String buildConditions(String prefix, List<String> conditions, List<String> operators) {
	StringBuilder builder = new StringBuilder();
	if (conditions.size()>0) {
		if (StringUtils.trimToNull(prefix)!=null) {
			builder.append(" ").append(prefix).append(" ");
		}
		for (int i=0; i<conditions.size(); i++) {
			String condition = conditions.get(i);
			builder.append(condition).append(" ");
			if (i<conditions.size()-1) {
				String operator = StringUtils.trimToNull(operators.get(i));
				if (operator!=null) {
					builder.append(operator).append(" ");
				}
			}
		}
	}
	return builder.toString();
}
 
Example 2
Project: My-Blog   File: TaleUtils.java   View Source Code Vote up 6 votes
public static String getFileKey(String name) {
    String prefix = "/upload/" + DateKit.dateFormat(new Date(), "yyyy/MM");
    if (!new File(AttachController.CLASSPATH + prefix).exists()) {
        new File(AttachController.CLASSPATH + prefix).mkdirs();
    }

    name = StringUtils.trimToNull(name);
    if (name == null) {
        return prefix + "/" + UUID.UU32() + "." + null;
    } else {
        name = name.replace('\\', '/');
        name = name.substring(name.lastIndexOf("/") + 1);
        int index = name.lastIndexOf(".");
        String ext = null;
        if (index >= 0) {
            ext = StringUtils.trimToNull(name.substring(index + 1));
        }
        return prefix + "/" + UUID.UU32() + "." + (ext == null ? null : (ext));
    }
}
 
Example 3
Project: Alpine   File: TrimmedStringArrayDeserializer.java   View Source Code Vote up 6 votes
@Override
public String[] deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException {
    final List<String> list = new ArrayList<>();
    final JsonNode node = jsonParser.readValueAsTree();
    if (node.isArray()) {
        final Iterator elements = node.elements();
        while (elements.hasNext()) {
            final JsonNode childNode = (JsonNode) elements.next();
            final String value = StringUtils.trimToNull(childNode.asText());
            if (value != null) {
                list.add(value);
            }
        }
    }
    if (list.size() == 0) {
        return null;
    } else {
        return list.toArray(new String[list.size()]);
    }
}
 
Example 4
Project: coodoo-listing   File: ListingParameters.java   View Source Code Vote up 6 votes
public Map<String, String> getFilterAttributes() {

        if (uriInfo != null) {
            MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();

            for (Map.Entry<String, List<String>> queryParam : queryParams.entrySet()) {
                String queryParamAttribute = queryParam.getKey();
                if (StringUtils.isBlank(queryParamAttribute) || !queryParamAttribute.startsWith("filter-")) {
                    continue;
                }
                queryParamAttribute = queryParamAttribute.substring("filter-".length(), queryParamAttribute.length());
                String filterVal = StringUtils.trimToNull(queryParam.getValue().get(0));
                if (filterVal != null) {
                    filterAttributes.put(queryParamAttribute, filterVal);
                }
            }
        }
        return filterAttributes;
    }
 
Example 5
Project: yadaframework   File: YadaHttpUtil.java   View Source Code Vote up 6 votes
/**
 * Returms the content type of a response given the content-type
 * @param fullContentType the content-type (from request.getContentType()), also with charset or other attributes like "text/html; charset=UTF-8"
 * @return an integer for the type of the content
 */
public int getDocumentType(String fullContentType) {
	if (StringUtils.trimToNull(fullContentType)==null) {
		return CONTENT_UNKNOWN;
	}
	String[] parts = fullContentType.toLowerCase().split("[; ]", 2);
	String contentType = parts[0];
	// TODO application/x-www-form-urlencoded could actually ask for an image, so it isn't strictly correct !
	if ("text/html".equals(contentType) || "application/xhtml+xml".equals(contentType) || "application/x-www-form-urlencoded".equals(contentType)) {
		return CONTENT_DOCUMENT;
	}
	if ("text/xml".equals(contentType)) {
		return CONTENT_XML;
	}
	if ("application/javascript".equals(contentType) || "application/x-javascript".equals(contentType) || "text/javascript".equals(contentType)) {
		return CONTENT_JAVASCRIPT;
	}
	if ("text/css".equals(contentType)) {
		return CONTENT_CSS;
	}
	if (contentType.startsWith("image/")) {
		return CONTENT_IMAGE;
	}
	return CONTENT_OTHER;
}
 
Example 6
Project: iab-spiders-and-robots-java-client   File: IpRanges.java   View Source Code Vote up 5 votes
private void parseRecords(InputStream stream) throws IOException {
    LineIterator it = IOUtils.lineIterator(buffer(stream), IabFile.CHARSET);
    while (it.hasNext()) {
        String record = StringUtils.trimToNull(it.nextLine());
        if (record != null) {
            if (isCidrNotation(record)) {
                cidrAddresses.add(subnetInfo(record));
            } else {
                plainAddresses.add(record);
            }
        }
    }
}
 
Example 7
Project: newblog   File: IndexController.java   View Source Code Vote up 5 votes
@RequestMapping("/savezhoubao")
@SuppressWarnings("unchecked")
public void savezhoubao(String content) {
    if (StringUtils.isNotEmpty(content)) {
        content = StringUtils.trimToNull(content);
    }
    redisTemplate.opsForValue().set("zhoubao", content);
}
 
Example 8
Project: mongo-trek   File: MigrationCommand.java   View Source Code Vote up 5 votes
@JsonCreator
public MigrationCommand(@JsonProperty("version") String version,
                        @JsonProperty("description") String description,
                        @JsonProperty("author") String author,
                        @JsonProperty("command") Map<String, Object> command) {
    if (StringUtils.trimToNull(version) == null || StringUtils.trimToNull(description) == null || command == null)
        throw new IllegalStateException("A migration command requires at least a version, description and a command!");

    this.version = version;
    this.description = description;
    this.author = Optional.ofNullable(author).orElse(Migration.DEFAULT_AUTHOR);
    this.command = new BasicDBObject(command);
}
 
Example 9
Project: plugin-km-confluence   File: ConfluencePluginResource.java   View Source Code Vote up 5 votes
@Override
public String getVersion(final Map<String, String> parameters) throws Exception {
	final String page = StringUtils.trimToEmpty(getConfluencePublicResource(parameters, "/forgotuserpassword.action"));
	final String ajsMeta = "ajs-version-number\" content=";
	final int versionIndex = Math.min(page.length(), page.indexOf(ajsMeta) + ajsMeta.length() + 1);
	return StringUtils.trimToNull(page.substring(versionIndex, Math.max(versionIndex, page.indexOf('\"', versionIndex))));
}
 
Example 10
Project: plugin-qa-sonarqube   File: SonarPluginResource.java   View Source Code Vote up 5 votes
/**
 * Search the SonarQube's projects matching to the given criteria. Name, display name and description are
 * considered.
 * 
 * @param node
 *            the node to be tested with given parameters.
 * @param criteria
 *            the search criteria.
 * @return project names matching the criteria.
 */
@GET
@Path("{node}/{criteria}")
@Consumes(MediaType.APPLICATION_JSON)
public List<SonarProject> findAllByName(@PathParam("node") final String node, @PathParam("criteria") final String criteria) throws IOException {

	// Prepare the context, an ordered set of projects
	final Format format = new NormalizeFormat();
	final String formatCriteria = format.format(criteria);
	final Map<String, String> parameters = pvResource.getNodeParameters(node);

	// Get the projects and parse them
	final List<SonarProject> projectsRaw = getProjects(parameters);
	final Map<String, SonarProject> result = new TreeMap<>();
	for (final SonarProject project : projectsRaw) {
		final String name = StringUtils.trimToNull(project.getName());
		final String key = project.getKey();

		// Check the values of this project
		if (format.format(name).contains(formatCriteria) || format.format(key).contains(formatCriteria)) {

			// Retrieve description and display name
			result.put(project.getName(), project);
		}
	}
	return new ArrayList<>(result.values());
}
 
Example 11
Project: yadaframework   File: YadaLocalePathVariableFilter.java   View Source Code Vote up 5 votes
private boolean isLocale(String locale) {
    if (StringUtils.trimToNull(locale)==null) {
    	return false;
    }
    List<String> locales = config.getLocaleStrings();
    return locales.contains(locale);
}
 
Example 12
Project: yadaframework   File: YadaSqlBuilder.java   View Source Code Vote up 5 votes
public String getSql() {
	StringBuilder builder = new StringBuilder();
	if (select!=null) {
		builder.append(select).append(" ");
		if (from!=null) {
			builder.append("from ").append(from).append(" ");
		}
	} else if (update!=null) {
		builder.append(update).append(" ");
		if (set!=null) {
			builder.append(set).append(" ");
		}
	}
	builder.append(joins);
	builder.append(buildConditions("where", whereConditions, whereOperators));
	if (StringUtils.trimToNull(groupby)!=null) {
		builder.append(" ").append(groupby);
	}
	builder.append(buildConditions("having", havingConditions, havingOperators));
	if (StringUtils.trimToNull(orderAndLimit)!=null) {
		builder.append(" ").append(orderAndLimit);
	}
	if (log.isDebugEnabled()) {
		log.debug(builder.toString());
	}
	return builder.toString();
}
 
Example 13
Project: yadaframework   File: YadaHttpUtil.java   View Source Code Vote up 5 votes
/**
 * Extract the address from a url, without schema and path but with port
 * @param url an url like http://www.myserver.net:8080/context/path or //www.myserver.net:8080/context/path
 * @return the host[:port] like www.myserver.net:8080, or ""
 */
public String extractAddress(String url) {
	if (StringUtils.trimToNull(url)!=null) {
		try {
			int pos = url.indexOf("//");
			pos = (pos<0?0:pos+2);
			int pos2 = url.indexOf("/", pos);
			pos2 = (pos2<0?url.length():pos2);
			return url.substring(pos, pos2);
		} catch (Exception e) {
			log.error("Can't extract address from {}", url);
		}
	}
	return "";
}
 
Example 14
Project: yadaframework   File: YadaDatatablesColumn.java   View Source Code Vote up 5 votes
/**
 * Returns the column name if any, the column data otherwise.
 * @return name or data or null
 */
public String getNameOrData() {
	String result = StringUtils.trimToNull(getName());
	if (result==null) {
		result = StringUtils.trimToNull(getData());
	}
	return result;
}
 
Example 15
Project: mybatis-generator-tool   File: StatusTextPlugin.java   View Source Code Vote up 4 votes
/**
 * 解析处理注释,增加 getXxxText() 方法
 *    注释格式范例:
 *      @enum 0: 有效期; 1: 无效
 */
@Override
public boolean modelGetterMethodGenerated(Method method, TopLevelClass topLevelClass,
                                          IntrospectedColumn introspectedColumn,
                                          IntrospectedTable introspectedTable,
                                          ModelClassType modelClassType) {

    String remarks = introspectedColumn.getRemarks();
    int jdbcType = introspectedColumn.getJdbcType();

    remarks = StringUtils.trimToNull(remarks);

    if (remarks == null) {
        return true;
    }

    if (!remarks.contains("@enum")) {
        return true;
    }

    String annotation = remarks.substring(remarks.indexOf("@enum") + 5);
    String[] items = StringUtils.split(annotation, ';');

    StringBuilder mapInitSb = new StringBuilder("new HashMap<Object, String>(){{");
    for (String item : items) {
        if (!item.contains(":")) {
            continue;
        }
        String[] kv = item.split(":");
        String k = StringUtils.trim(kv[0]);
        String v = StringUtils.trim(kv[1]);
        mapInitSb.append("put(");
        if (jdbcType == Types.TINYINT) {
            mapInitSb.append("(byte)");
        }
        mapInitSb.append(k).append(",")
                .append("\"").append(v).append("\");");
    }
    mapInitSb.append("}}");

    // 增加常量
    String fieldName = String.format("%sMap", introspectedColumn.getJavaProperty());

    Field field = new Field(
            fieldName,
            new FullyQualifiedJavaType("java.util.HashMap<Object, String>")
    );
    field.setVisibility(JavaVisibility.PRIVATE);
    field.setStatic(true);
    field.setFinal(true);
    field.setInitializationString(mapInitSb.toString());

    topLevelClass.addField(field);


    // 增加方法
    Method textMethod = new Method(String.format("%sText", method.getName()));
    textMethod.setReturnType(new FullyQualifiedJavaType(String.class.getCanonicalName()));
    textMethod.setVisibility(JavaVisibility.PUBLIC);
    if (jdbcType == Types.TINYINT) {
        textMethod.addBodyLine(String.format("return %s.get((byte)this.%s);", fieldName, introspectedColumn.getJavaProperty()));
    } else {
        textMethod.addBodyLine(String.format("return %s.get(this.%s);", fieldName, introspectedColumn.getJavaProperty()));
    }

    remarks = remarks.replaceAll("\n", "\\\\n").replaceAll("\"", "\\\\\"");
    textMethod.addAnnotation(
        String.format("@ApiModelProperty(value = \"%s\")", remarks)
    );

    topLevelClass.addImportedType(new FullyQualifiedJavaType(HashMap.class.getCanonicalName()));
    topLevelClass.addMethod(textMethod);

    return true;
}
 
Example 16
Project: plugin-vm-vcloud   File: VCloudPluginResource.java   View Source Code Vote up 4 votes
@Override
public String getVersion(final Map<String, String> parameters) throws Exception {
	return StringUtils.trimToNull(
			getTags(ObjectUtils.defaultIfNull(getVCloudResource(parameters, "/admin"), "<a><Description/></a>"), "Description").item(0)
					.getTextContent());
}
 
Example 17
Project: azeroth   File: TopicProducerSpringProvider.java   View Source Code Vote up 4 votes
@Override
public void afterPropertiesSet() throws Exception {

    Validate.notEmpty(this.configs, "configs is required");

    routeEnv = StringUtils.trimToNull(ResourceUtils.get(KafkaConst.PROP_ENV_ROUTE));

    if (routeEnv != null)
        log.info("current route Env value is:", routeEnv);
    //移除错误的或者未定义变量的配置
    Set<String> propertyNames = configs.stringPropertyNames();
    for (String propertyName : propertyNames) {
        String value = configs.getProperty(propertyName);
        if (StringUtils.isBlank(value) || value.trim().startsWith("$")) {
            configs.remove(propertyName);
            log.warn("remove prop[{}],value is:{}", propertyName, value);
        }
    }

    if (!configs.containsKey(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG)) {
        configs.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
            StringSerializer.class.getName()); // key serializer
    }

    if (!configs.containsKey(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG)) {
        configs.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
            KyroMessageSerializer.class.getName());
    }

    if (!configs.containsKey(ProducerConfig.PARTITIONER_CLASS_CONFIG)) {
        configs.put(ProducerConfig.PARTITIONER_CLASS_CONFIG,
            DefaultPartitioner.class.getName());
    }

    //默认重试一次
    if (!configs.containsKey(ProducerConfig.RETRIES_CONFIG)) {
        configs.put(ProducerConfig.RETRIES_CONFIG, "1");
    }

    if (!configs.containsKey(ProducerConfig.COMPRESSION_TYPE_CONFIG)) {
        configs.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, "snappy");
    }

    if (!configs.containsKey("client.id")) {
        configs.put("client.id",
            (producerGroup == null ? "" : "_" + producerGroup) + NodeNameHolder.getNodeId());
    }

    KafkaProducer<String, Object> kafkaProducer = new KafkaProducer<String, Object>(configs);

    this.producer = new DefaultTopicProducer(kafkaProducer, defaultAsynSend);

    //hanlder
    if (StringUtils.isNotBlank(monitorZkServers)) {
        Validate.notBlank(producerGroup,
            "enable producer monitor property[producerGroup] is required");
        this.producer.addEventHandler(new SendCounterHandler(producerGroup, monitorZkServers));
    }
    if (delayRetries > 0) {
        this.producer.addEventHandler(
            new SendErrorDelayRetryHandler(producerGroup, kafkaProducer, delayRetries));
    }
}
 
Example 18
Project: azeroth   File: TopicConsumerSpringProvider.java   View Source Code Vote up 4 votes
@Override
public void afterPropertiesSet() throws Exception {

    Validate.isTrue(topicHandlers != null && topicHandlers.size() > 0, "at latest one topic");
    // 当前状态
    if (status.get() > 0)
        return;

    routeEnv = StringUtils.trimToNull(ResourceUtils.get(KafkaConst.PROP_ENV_ROUTE));

    if (routeEnv != null) {
        logger.info("current route Env value is:", routeEnv);
        Map<String, MessageHandler> newTopicHandlers = new HashMap<>();
        for (String origTopicName : topicHandlers.keySet()) {
            newTopicHandlers.put(routeEnv + "." + origTopicName,
                topicHandlers.get(origTopicName));
        }
        topicHandlers = newTopicHandlers;
    }

    // make sure that rebalance.max.retries * rebalance.backoff.ms >
    // zookeeper.session.timeout.ms.
    configs.put("rebalance.max.retries", "5");
    configs.put("rebalance.backoff.ms", "1205");
    configs.put("zookeeper.session.timeout.ms", "6000");

    configs.put("key.deserializer", StringDeserializer.class.getName());

    if (!configs.containsKey("value.deserializer")) {
        configs.put("value.deserializer", KyroMessageDeserializer.class.getName());
    }

    if (useNewAPI) {
        if ("smallest".equals(configs.getProperty("auto.offset.reset"))) {
            configs.put("auto.offset.reset", "earliest");
        } else if ("largest".equals(configs.getProperty("auto.offset.reset"))) {
            configs.put("auto.offset.reset", "latest");
        }
    } else {
        // 强制自动提交
        configs.put("enable.auto.commit", "true");
    }

    // 同步节点信息
    groupId = configs.get(org.apache.kafka.clients.consumer.ConsumerConfig.GROUP_ID_CONFIG)
        .toString();

    logger.info("\n===============KAFKA Consumer group[{}] begin start=================\n",
        groupId);

    consumerId = NodeNameHolder.getNodeId();
    //
    configs.put("consumer.id", consumerId);

    // kafka 内部处理 consumerId = groupId + "_" + consumerId
    consumerId = groupId + "_" + consumerId;
    //
    if (!configs.containsKey("client.id")) {
        configs.put("client.id", consumerId);
    }
    //
    start();

    logger.info(
        "\n===============KAFKA Consumer group[{}],consumerId[{}] start finished!!=================\n",
        groupId, consumerId);
}
 
Example 19
Project: redirector   File: DataServiceInfo.java   View Source Code Vote up 4 votes
static String getString(Configuration config, String key) {
    String value = StringUtils.trimToNull(config.getString(key));
    return value == null ? NA : value;
}
 
Example 20
Project: coodoo-listing   File: ListingParameters.java   View Source Code Vote up 4 votes
public String getFilter() {
    return StringUtils.trimToNull(filter);
}