package de.ivu.elect.nl.eml;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.commons.io.IOUtils;
import org.w3c.dom.ls.LSInput;
import org.w3c.dom.ls.LSResourceResolver;

public class ClasspathResourceResolver implements LSResourceResolver {
  @Override
  public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) {

    try {
      try (InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(systemId)) {
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
          IOUtils.copy(stream, bos);
          LSInputImpl input = new LSInputImpl();
          input.setPublicId(publicId);
          input.setSystemId(systemId);
          input.setBaseURI(baseURI);
          input.setCharacterStream(new InputStreamReader(new ByteArrayInputStream(bos.toByteArray())));
          return input;
        }

      }
    } catch (IOException e) {
      throw new RuntimeException(e.getMessage(), e);
    }

  }
}
