package archmapper.main.model.stylemapping;
import java.io.File;
import java.io.InputStream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import archmapper.main.exceptions.ArchMapperException;
/**
* Reads style mappings from an xml file and writes them back. Uses JAXB for
* this purpose.
*
* @author mg
*
*/
public class StyleMappingDAO {
public static void writeXmlToSystemOut(StyleMapping mapping) {
try {
JAXBContext jc = JAXBContext.newInstance(StyleMapping.class);
Marshaller m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.marshal(mapping, System.out);
} catch (JAXBException e) {
throw new ArchMapperException("Could not write style mapping file: "+
e.getMessage());
}
}
public static StyleMapping read(String filename) {
StyleMapping mapping = null;
try {
JAXBContext jc = JAXBContext.newInstance(StyleMapping.class);
Unmarshaller um = jc.createUnmarshaller();
mapping = (StyleMapping) um.unmarshal(new File(filename));
} catch (JAXBException e) {
throw new ArchMapperException("Could not read style mapping file: "+
e.getMessage());
}
return mapping;
}
public static StyleMapping read(InputStream fileInputStream) {
StyleMapping mapping = null;
try {
JAXBContext jc = JAXBContext.newInstance(StyleMapping.class);
Unmarshaller um = jc.createUnmarshaller();
mapping = (StyleMapping) um.unmarshal(fileInputStream);
} catch (JAXBException e) {
throw new ArchMapperException("Could not read style mapping file: "+
e.getMessage());
}
return mapping;
}
public static void main(String[] args) {
testReading();
}
public static void testWriting() {
StyleMapping mapping = new StyleMapping();
mapping.setStyleName("Super-Style");
mapping.setMappingName("Super-Mapping");
ComponentTypeMapping compMapping = new ComponentTypeMapping();
compMapping.setTypeName("Super-Comp-Typ");
mapping.getComponentTypeMapping().add(compMapping);
compMapping = new ComponentTypeMapping();
compMapping.setTypeName("CompTyp2");
mapping.getComponentTypeMapping().add(compMapping);
writeXmlToSystemOut(mapping);
}
public static void testReading() {
StyleMapping mapping = read("examples/stylemapping.xml");
System.out.println("Style: "+ mapping.getStyleName()+
" Mapping: "+ mapping.getMappingName()+
" Components: "+ mapping.getComponentTypeMapping().size()+
" first Comp: "+ mapping.getComponentTypeMapping().get(0).getTypeName());
}
}