Mercurial > hg > thermostat-tools-eclipse
view com.redhat.thermostat.tools.eclipse.plugin/src/com/redhat/thermostat/tools/eclipse/plugin/editor/Converters.java @ 111:6369d2282c1d
Add an EmptyStringToNullConverter
Add unit test for all inner classes of Converters.
author | Omair Majid <omajid@redhat.com> |
---|---|
date | Fri, 28 Feb 2014 11:09:26 -0500 |
parents | 4dfa549ca00c |
children |
line wrap: on
line source
package com.redhat.thermostat.tools.eclipse.plugin.editor; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.eclipse.core.databinding.conversion.Converter; public class Converters { /** * Converts a {@link List}{@code <String>} to a single {@code String} by * joining all the items in the list with a single space. */ public static class ListToStringConverter extends Converter { public ListToStringConverter() { super(List.class, String.class); } @Override public String convert(Object fromObject) { if (!(fromObject instanceof List)) { throw new AssertionError("Only List objects can be converted"); } List<String> list = (List<String>) fromObject; if (list.size() == 0) { return ""; } StringBuilder result = new StringBuilder(); for (String item : list) { result.append(item).append(" "); } // return everything except the last " " return result.substring(0, result.length() - 1); } } /** * Converts a {@link String} to a {@link List}{@code <String>} by splitting * the {@code String} along spaces. */ public static class StringToListConverter extends Converter { public StringToListConverter() { super(String.class, List.class); } @Override public List<String> convert(Object fromObject) { if (!(fromObject instanceof String)) { throw new AssertionError("Only String objects can be converted"); } String from = (String) fromObject; if (from.trim().isEmpty()) { return Collections.emptyList(); } String[] parts = from.trim().split(" +"); List<String> result = Arrays.asList(parts); return result; } } /** Converts an empty String to {@code null}. */ public static class EmptyStringToNullConverter extends Converter { public EmptyStringToNullConverter() { super(String.class, String.class); } @Override public String convert(Object fromObject) { if (!(fromObject instanceof String)) { throw new IllegalArgumentException("Only strings can be converted. Got a " + fromObject.getClass() + " type"); } String in = (String) fromObject; if (in == null || in.trim().isEmpty()) { return null; } return in; } } }