MCPDUtil.java

/**
 * Copyright 2021 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.gringlobal.util;

import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class MCPDUtil {
	static Pattern mcpdSplit = Pattern.compile("\\s*;\\s*");

	/**
	 * Convert a List to MCPD "array string" with semicolon as separator.
	 *
	 */
	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());
	}

}