com.crabshue.commons.xml.inputsource.InputSourceBuilder Maven / Gradle / Ivy
package com.crabshue.commons.xml.inputsource;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.xml.sax.InputSource;
import com.crabshue.commons.exceptions.SystemException;
import com.crabshue.commons.file.FileIOUtils;
import com.crabshue.commons.xml.exceptions.XmlErrorType;
/**
* Utility class for {@link InputSource}.
*
*/
public class InputSourceBuilder {
/**
* Build a new {@link InputSource} from a byte array.
*
* @param content the byte array
* @return the input source
*/
public static InputSource newInputSource(final byte[] content) {
try (InputStream is = new ByteArrayInputStream(content)) {
return new InputSource(is);
} catch (IOException e) {
throw new SystemException(XmlErrorType.ERROR_BUILDING_INPUT_SOURCE, e);
}
}
/**
* Build a new {@link InputSource} from a {@link File}.
*
* @param file the file
* @return the input source
*/
public static InputSource newInputSource(final File file) {
try (InputStream is = FileIOUtils.openInputStream(file)) {
return new InputSource(is);
} catch (IOException e) {
throw new SystemException(XmlErrorType.ERROR_BUILDING_INPUT_SOURCE, e);
}
}
/**
* Build a new {@link InputSource} from a {@link String}.
*
* @param content the content as {@link String}
* @return the input source
*/
public static InputSource newInputSource(final String content) {
try (InputStream is = IOUtils.toInputStream(content, StandardCharsets.UTF_8)) {
return new InputSource(is);
} catch (IOException e) {
throw new SystemException(XmlErrorType.ERROR_BUILDING_INPUT_SOURCE, e);
}
}
/**
* Build a new {@link InputSource} from a collection of{@link String}.
*
* @param content the content as a collection {@link String}
* @return the input source
*/
public static InputSource newInputSource(final Collection content) {
try (InputStream is = IOUtils.toInputStream(StringUtils.join(content, " "), StandardCharsets.UTF_8)) {
return new InputSource(is);
} catch (IOException e) {
throw new SystemException(XmlErrorType.ERROR_BUILDING_INPUT_SOURCE, e);
}
}
}