view com.redhat.thermostat.tools.eclipse.plugin/src/com/redhat/thermostat/tools/eclipse/plugin/model/PluginModelReaderWriter.java @ 94:146a0704ba68

Include a schemaLocation attribute This will make eclipse automatically validate the thermostat-plugin.xml file whenever possible.
author Omair Majid <omajid@redhat.com>
date Thu, 06 Feb 2014 10:37:06 -0500
parents 8f2dd0dbdb87
children
line wrap: on
line source

package com.redhat.thermostat.tools.eclipse.plugin.model;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;

import com.redhat.thermostat.tools.eclipse.plugin.Messages;

/**
 * Reads and writes the plugin model to/from input streams.
 */
public class PluginModelReaderWriter {

    private String name;
    private IFile file;

    public PluginModelReaderWriter(IFile file) throws CoreException {
        this(file, file.getFullPath().makeAbsolute().removeLastSegments(1).lastSegment());
    }

    public PluginModelReaderWriter(IFile file, String name) {
        this.file = file;
        this.name = name;
    }

    public String getPluginName() {
        return name;
    }

    public Plugin loadModel(String contents) {
        return loadModel(new StringReader(contents));
    }


    public Plugin loadModel(InputStream inputStream) {
        JAXBContext context;
        try {
            context = JAXBContext.newInstance(Plugin.class);
            Unmarshaller um = context.createUnmarshaller();
            Plugin plugin = (Plugin) um.unmarshal(inputStream);
            return plugin;
        } catch (JAXBException e) {
            throw new RuntimeException(Messages.PluginModelReaderWriter_errorLoadingModel, e);
        }
    }

    public Plugin loadModel(Reader reader) {
        JAXBContext context;
        try {
            context = JAXBContext.newInstance(Plugin.class);
            Unmarshaller um = context.createUnmarshaller();
            Plugin plugin = (Plugin) um.unmarshal(reader);
            return plugin;
        } catch (JAXBException e) {
            throw new RuntimeException(Messages.PluginModelReaderWriter_errorLoadingModel, e);
        }
    }

    public void saveModel(Plugin plugin, OutputStream out) {
        try {
            JAXBContext context = JAXBContext.newInstance(Plugin.class);
            Marshaller m = context.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, SchemaConstants.getSchemaLocation());

            m.marshal(plugin, out);
        } catch (JAXBException e) {
            throw new RuntimeException(Messages.PluginModelReaderWriter_errorSavingFile, e);
        }
    }

}