001package io.ebeaninternal.xmlmapping;
002
003import io.avaje.classpath.scanner.Resource;
004import io.ebeaninternal.xmlmapping.model.XmEbean;
005
006import javax.xml.bind.JAXBContext;
007import javax.xml.bind.JAXBException;
008import javax.xml.bind.Unmarshaller;
009import java.io.IOException;
010import java.io.InputStream;
011import java.net.URL;
012import java.net.URLConnection;
013import java.util.ArrayList;
014import java.util.Enumeration;
015import java.util.List;
016
017public class XmlMappingReader {
018
019
020  /**
021   * Read and return a Migration from an xml document.
022   */
023  public static XmEbean read(InputStream is) {
024
025    try {
026      JAXBContext jaxbContext = JAXBContext.newInstance(XmEbean.class);
027      Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
028      return (XmEbean) unmarshaller.unmarshal(is);
029
030    } catch (JAXBException e) {
031      throw new RuntimeException(e);
032    }
033  }
034
035  /**
036   * Read the deployment XML for the given resource name.
037   */
038  public static List<XmEbean> readByResourceName(ClassLoader classLoader, String resourceName) {
039    try {
040      Enumeration<URL> resources = classLoader.getResources(resourceName);
041      List<XmEbean> mappings = new ArrayList<>();
042      while (resources.hasMoreElements()) {
043        URL url = resources.nextElement();
044        try (InputStream is = openNoCache(url)) {
045          mappings.add(XmlMappingReader.read(is));
046        }
047      }
048      return mappings;
049    } catch (IOException e) {
050      throw new RuntimeException("Error reading ebean xml mapping", e);
051    }
052  }
053
054  /**
055   * Read the deployment XML for the given resources.
056   */
057  public static List<XmEbean> readByResourceList(List<Resource> resourceList) {
058    try {
059      List<XmEbean> mappings = new ArrayList<>();
060      for (Resource xmlMappingRes : resourceList) {
061        try (InputStream is = xmlMappingRes.inputStream()) {
062          mappings.add(XmlMappingReader.read(is));
063        }
064      }
065      return mappings;
066    } catch (IOException e) {
067      throw new RuntimeException("Error reading ebean xml mapping", e);
068    }
069  }
070
071  private static InputStream openNoCache(URL url) throws IOException {
072    URLConnection urlConnection = url.openConnection();
073    urlConnection.setUseCaches(false);
074    return urlConnection.getInputStream();
075  }
076}