001/*
002 * Copyright (c) 2021, Oracle and/or its affiliates.
003 *
004 * Licensed under the 2-clause BSD license.
005 *
006 * Redistribution and use in source and binary forms, with or without
007 * modification, are permitted provided that the following conditions are met:
008 *
009 * 1. Redistributions of source code must retain the above copyright notice,
010 *    this list of conditions and the following disclaimer.
011 *
012 * 2. Redistributions in binary form must reproduce the above copyright notice,
013 *    this list of conditions and the following disclaimer in the documentation
014 *    and/or other materials provided with the distribution.
015 *
016 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
017 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
018 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
019 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
020 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
021 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
022 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
023 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
024 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
025 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
026 * POSSIBILITY OF SUCH DAMAGE.
027 */
028
029package com.oracle.labs.mlrg.olcut.config.protobuf;
030
031import com.oracle.labs.mlrg.olcut.config.SerializedObject;
032import com.oracle.labs.mlrg.olcut.config.io.ConfigLoader;
033import com.oracle.labs.mlrg.olcut.config.io.ConfigWriter;
034import com.oracle.labs.mlrg.olcut.config.io.ConfigWriterException;
035import com.oracle.labs.mlrg.olcut.config.property.ListProperty;
036import com.oracle.labs.mlrg.olcut.config.property.MapProperty;
037import com.oracle.labs.mlrg.olcut.config.property.Property;
038import com.oracle.labs.mlrg.olcut.config.property.SimpleProperty;
039import com.oracle.labs.mlrg.olcut.config.protobuf.protos.ComponentProto;
040import com.oracle.labs.mlrg.olcut.config.protobuf.protos.ConfigProto;
041import com.oracle.labs.mlrg.olcut.config.protobuf.protos.PropertyListProto;
042import com.oracle.labs.mlrg.olcut.config.protobuf.protos.PropertyMapProto;
043import com.oracle.labs.mlrg.olcut.config.protobuf.protos.SerializedObjectProto;
044
045import java.io.IOException;
046import java.io.OutputStream;
047import java.io.PrintStream;
048import java.util.Map;
049
050/**
051 * A {@link ConfigWriter} for protobuf format config files.
052 */
053public final class ProtoConfigWriter implements ConfigWriter {
054
055    private final OutputStream writer;
056    private final boolean writeAsText;
057
058    private final ConfigProto.Builder builder;
059
060    /**
061     * Constructs a writer for a protobuf config file.
062     *
063     * @param writer      The writer to write to.
064     * @param writeAsText Write as text instead of binary.
065     */
066    public ProtoConfigWriter(OutputStream writer, boolean writeAsText) {
067        this.writer = writer;
068        this.writeAsText = writeAsText;
069        this.builder = ConfigProto.newBuilder();
070    }
071
072    @Override
073    public void writeStartDocument() throws ConfigWriterException {
074        // No-op
075    }
076
077    @Override
078    public void writeEndDocument() throws ConfigWriterException {
079        // No-op
080    }
081
082    @Override
083    public void writeGlobalProperties(Map<String, String> props) throws ConfigWriterException {
084        builder.putAllProperties(props);
085    }
086
087    @Override
088    public void writeSerializedObjects(Map<String, SerializedObject> map) throws ConfigWriterException {
089        for (Map.Entry<String, SerializedObject> e : map.entrySet()) {
090            SerializedObject<?> serObj = e.getValue();
091            SerializedObjectProto.Builder serObjBuilder = SerializedObjectProto.newBuilder();
092            serObjBuilder.setName(serObj.getName());
093            serObjBuilder.setType(serObj.getClassName());
094            serObjBuilder.setLocation(serObj.getLocation());
095            builder.addSerializedObject(serObjBuilder.build());
096        }
097    }
098
099    @Override
100    public void writeStartComponents() throws ConfigWriterException {
101        // No-op
102    }
103
104    @Override
105    public void writeComponent(Map<String, String> attributes, Map<String, Property> properties) {
106        ComponentProto.Builder componentBuilder = ComponentProto.newBuilder();
107        componentBuilder.setName(attributes.get(ConfigLoader.NAME));
108        componentBuilder.setType(attributes.get(ConfigLoader.TYPE));
109        if (attributes.get(ConfigLoader.EXPORT).equalsIgnoreCase("true")) {
110            componentBuilder.setExportable(true);
111        }
112        if (attributes.get(ConfigLoader.IMPORT).equalsIgnoreCase("true")) {
113            componentBuilder.setImportable(true);
114        }
115        if (attributes.containsKey(ConfigLoader.ENTRIES)) {
116            componentBuilder.setEntries(attributes.get(ConfigLoader.ENTRIES));
117        }
118        if (attributes.containsKey(ConfigLoader.LEASETIME)) {
119            componentBuilder.setLeaseTime(Long.parseLong(attributes.get(ConfigLoader.LEASETIME)));
120        }
121        if (attributes.containsKey(ConfigLoader.SERIALIZED)) {
122            componentBuilder.setSerialized(attributes.get(ConfigLoader.SERIALIZED));
123        }
124
125        for (Map.Entry<String, Property> property : properties.entrySet()) {
126            String key = property.getKey();
127            Property value = property.getValue();
128            if (value instanceof ListProperty) {
129                //
130                // Must be a string/component list
131                PropertyListProto.Builder listBuilder = PropertyListProto.newBuilder();
132                listBuilder.setName(key);
133                for (SimpleProperty s : ((ListProperty) value).getSimpleList()) {
134                    listBuilder.addItem(s.getValue());
135                }
136                for (Class<?> c : ((ListProperty) value).getClassList()) {
137                    listBuilder.addType(c.getName());
138                }
139                componentBuilder.addListProperty(listBuilder.build());
140            } else if (value instanceof MapProperty) {
141                //
142                // Must be a string,string map
143                PropertyMapProto.Builder mapBuilder = PropertyMapProto.newBuilder();
144                mapBuilder.setName(key);
145                for (Map.Entry<String, SimpleProperty> e : ((MapProperty) value).getMap().entrySet()) {
146                    mapBuilder.putElements(e.getKey(), e.getValue().getValue());
147                }
148                componentBuilder.addMapProperty(mapBuilder.build());
149            } else {
150                //
151                // Standard property
152                componentBuilder.putProperties(key, value.toString());
153            }
154        }
155        builder.addComponents(componentBuilder.build());
156    }
157
158    @Override
159    public void writeEndComponents() throws ConfigWriterException {
160        // No-op
161    }
162
163    @Override
164    public void close() throws ConfigWriterException {
165        ConfigProto proto = builder.build();
166        try {
167            if (writeAsText) {
168                PrintStream stream = new PrintStream(writer);
169                stream.println(proto.toString());
170                stream.close();
171            } else {
172                proto.writeTo(writer);
173                writer.close();
174            }
175        } catch (IOException e) {
176            throw new ConfigWriterException(e);
177        }
178    }
179}