MCPDUtil.java
/**
* Copyright 2014 Global Crop Diversity Trust
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package org.genesys.util;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
public class MCPDUtil {
static Pattern mcpdSplit = Pattern.compile("\\s*;\\s*");
public static final Pattern MCPDDATE_PATTERN = Pattern.compile("^(?:(?:[1-9]\\d{3})|(?:----)|(?:0000))(?:--|(?:0[0-9])|(?:1[0-2]))(?:--|(?:0[0-9])|(?:[1-2][0-9])|(?:3[0-1]))$");
public static final Pattern WIEWSCODE_PATTERN = Pattern.compile("^\\p{Upper}{3}(\\d){3,4}$");
/**
* Convert a List to MCPD "array string" with semicolon as separator.
*
* @param integers
* @return
*/
public static String toMcpdArray(Collection<?> objects) {
if (objects == null || objects.size() == 0)
return null;
StringBuilder sb = new StringBuilder();
objects.stream().filter(i -> i != null).forEach(i -> {
if (sb.length() > 0)
sb.append(";");
sb.append(i);
});
return StringUtils.defaultIfBlank(sb.toString(), null);
}
/**
* Convert an MCPD "array" (e.g. "10;20") to a {@link List} of Integers,
* excluding blank and null elements.
*
* @throws NumberFormatException
* if the input string contains non-numeric elements.
*/
public static List<Integer> toIntegers(String ints) {
if (StringUtils.isBlank(ints))
return null;
return Arrays.stream(mcpdSplit.split(ints)).filter(str -> StringUtils.isNotBlank(str)).map(i -> Integer.parseInt(i)).collect(Collectors.toList());
}
/**
* Convert an MCPD "array string" (e.g. "NOR051;AUS033") to a {@link List},
* excluding blank and null elements.
*
* @param strings
* @return
*/
public static List<String> toList(String strings) {
if (StringUtils.isBlank(strings))
return null;
return Arrays.stream(mcpdSplit.split(strings)).filter(str -> StringUtils.isNotBlank(str)).collect(Collectors.toList());
}
public static boolean isMcpdDate(String date) {
return date == null ? false : MCPDDATE_PATTERN.matcher(date).matches();
}
public static boolean isWiewsCode(String code) {
return code == null ? false : WIEWSCODE_PATTERN.matcher(code).matches();
}
}