cz.jalasoft.util.text.Fragment Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of JalasoftUtils Show documentation
Show all versions of JalasoftUtils Show documentation
A collection of utility classes that might be useful.
package cz.jalasoft.util.text;
import com.google.common.base.Optional;
import cz.jalasoft.util.converter.ConversionException;
import cz.jalasoft.util.converter.Converter;
import cz.jalasoft.util.converter.StringConverter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static cz.jalasoft.util.ArgumentAssertion.*;
/**
* Created by Honza Lastovicka on 17.4.15.
*/
public abstract class Fragment> {
/**
* Creates a new fragment from plain text.
*
* @param text a source of a new fragment, must not be null or empty.
* @return never null
* @throws java.lang.IllegalArgumentException if text is null or empty.
*/
public static TextFragment fromText(String text) {
mustNotBeNullOrEmpty(text, "Text fragment");
return new TextFragment(text);
}
public static TextFragment fromInputStream(InputStream input) throws IOException {
mustNotBeNull(input, "Input Stream");
InputStreamReader reader = new InputStreamReader(input);
BufferedReader buffReader = new BufferedReader(reader);
String line;
StringBuilder bldr = new StringBuilder();
while((line = buffReader.readLine()) != null) {
bldr.append(line);
}
return fromText(bldr.toString());
}
/**
* Gets a string representation of this fragment.
*
* @return never null or empty;
*/
public abstract String text();
/**
* Converts this fragment to a value that is distinguished by
* a converter.
*
* @param converter must not be null
* @param resulting type from th converter.
* @return nvr null
* @throws ConversionException if an error occurs during conversion
* @throws java.lang.IllegalArgumentException if converter isnull
*/
public T convertValue(StringConverter converter) throws ConversionException {
return converter.convert(text());
}
public U convert(Converter converter) throws ConversionException {
return converter.convert(getThis());
}
abstract T getThis();
public Optional asMatchingFragment(Pattern pattern) {
Matcher matcher = pattern.matcher(text());
if (!matcher.matches()) {
return Optional.absent();
}
return Optional.of(new RegexFragment(matcher));
}
}