org.openscada.configurator.sec.utils.JSScriptParser.java Source code

Java tutorial

Introduction

Here is the source code for org.openscada.configurator.sec.utils.JSScriptParser.java

Source

/*
 * This file is part of the openSCADA project
 * 
 * Copyright (C) 2013 Jens Reimann (ctron@dentrassi.de)
 *
 * openSCADA is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * openSCADA is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with openSCADA. If not, see
 * <http://opensource.org/licenses/lgpl-3.0.html> for a copy of the LGPLv3 License.
 */

package org.openscada.configurator.sec.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Map;

import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.impl.ResourceImpl;
import org.openscada.configurator.sec.JavaScript;
import org.openscada.configurator.sec.SecurityFactory;

import com.google.common.io.CharStreams;

public class JSScriptParser implements Resource.Factory {

    @Override
    public Resource createResource(final URI uri) {
        return new ResourceImpl(uri) {
            @Override
            protected void doLoad(final InputStream inputStream, final Map<?, ?> options) throws IOException {
                final InputStreamReader stream = new InputStreamReader(inputStream);
                try {
                    getContents().add(parseContent(stream));
                } finally {
                    stream.close();
                }
            }

            @Override
            protected void doSave(final OutputStream outputStream, final Map<?, ?> options) throws IOException {
                final PrintStream ps = new PrintStream(outputStream);
                try {
                    ps.print(((JavaScript) getContents().get(0)).getSource());
                } finally {
                    ps.close();
                }
            }
        };
    }

    protected EObject parseContent(final InputStreamReader stream) throws IOException {
        final String value = CharStreams.toString(stream);

        final JavaScript script = SecurityFactory.eINSTANCE.createJavaScript();
        script.setSource(value);

        return script;
    }

}