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