001/*
002 * Units of Measurement Tools for Java
003 * Copyright (c) 2005-2023, Werner Keil and others.
004 *
005 * All rights reserved.
006 *
007 * Redistribution and use in source and binary forms, with or without modification, 
008 * are permitted provided that the following conditions are met:
009 *
010 * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
011 *
012 * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
013 *
014 * 3. Neither the name of JSR-363 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
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,
018 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
019 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
020 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
021 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
022 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
023 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
024 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
025 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
026 */
027package tech.uom.tools.obix;
028
029import java.io.BufferedWriter;
030import java.io.FileWriter;
031import java.io.InputStream;
032import java.io.OutputStream;
033import java.util.Arrays;
034import java.util.Collections;
035import java.util.HashSet;
036import java.util.List;
037import java.util.Map;
038import java.util.Set;
039import java.util.logging.Logger;
040
041import javax.lang.model.SourceVersion;
042import javax.measure.Unit;
043import javax.tools.Tool;
044
045import com.github.rvesse.airline.Cli;
046import com.github.rvesse.airline.annotations.Arguments;
047import com.github.rvesse.airline.annotations.Command;
048import com.github.rvesse.airline.annotations.Option;
049import com.github.rvesse.airline.annotations.OptionType;
050import com.github.rvesse.airline.builder.CliBuilder;
051import com.github.rvesse.airline.help.Help;
052
053import tech.uom.lib.common.function.DescriptionSupplier;
054
055/**
056 * @author Werner
057 * @version 0.5
058 */
059public class ObixImporter implements Tool {
060        // TODO factor out, e.g. into uom-lib-common
061        static enum ErrorCode {
062                OK, Failure
063                // For now we'll use ordinal, but should change to code or Id (e.g. using IntIdentifiable)
064        }
065        
066        protected static final Logger logger = Logger.getLogger(ObixImporter.class.getName());
067        
068    static class ToolCommand implements Runnable {
069        @Option(type = OptionType.GLOBAL, name = "-v", description = "Verbose mode")
070        public boolean verbose;
071
072        public void run() {
073            System.out.println(getClass().getSimpleName());
074        }
075    }
076    
077    @Command(name = "write", description = "Write to file")
078    public static final class Write extends ToolCommand {
079        @Option(name = "-q", description = "Quantities output file")
080        public String quantOutFile;
081
082        @Arguments(description = "Quantities to write")
083        public List<String> quantities;
084        
085        @SuppressWarnings("rawtypes")
086                @Override
087        public void run() {
088                if (quantOutFile!=null && quantOutFile.length()>0) {
089                        logger.info(getClass().getSimpleName() + " to " + quantOutFile);
090                } else {
091                        logger.info(getClass().getSimpleName());
092                }
093                        
094                if (quantities != null) {
095                        for (String q : quantities) {
096                                System.out.println(q);
097                        }
098                }
099                
100                if (verbose) {          
101                        List<Unit> units = ObixUnit.units();
102                        if (units != null && units.size() > 0) {
103                                for (Unit u : units) {
104                                        logger.fine("Unit: " + u + ", " + u.getName() + ",  " + u.getDimension() + " :: " + ((DescriptionSupplier)u).getDescription());
105                                }                                                       
106                        }
107                        
108                        final Map quantities = ObixUnit.quantities();
109                        for (Object key : quantities.keySet()) {
110                                logger.fine("Key: " + key + "; Value: " + quantities.get(key));
111                        }
112                        
113                                for (String q : ObixUnit.quantityNames()) {
114                                        logger.fine("Quantity: " + q);
115                                }
116                }
117                
118                        if (quantOutFile!=null && quantOutFile.length()>0) {
119                                writeToFile(ObixUnit.quantityNames(), quantOutFile);                            
120                        }
121        }
122        
123        private void writeToFile(final List<String> quantities, final String fileName) {
124                try (FileWriter fw = new FileWriter(fileName);
125                         BufferedWriter bw = new BufferedWriter(fw)){                           
126                        for (String q : quantities) {
127                                bw.write(q);
128                                bw.newLine();
129                        }                
130                                 }
131                            catch (Exception e) {
132                                logger.warning(e.getMessage());
133                            }
134        }
135    }
136        
137        /* (non-Javadoc)
138         * @see javax.tools.Tool#run(java.io.InputStream, java.io.OutputStream, java.io.OutputStream, java.lang.String[])
139         */
140        @Override
141        public int run(InputStream in, OutputStream out, OutputStream err,
142                        String... arguments) {
143                try {
144                        @SuppressWarnings("unchecked")
145                        CliBuilder<Runnable> builder = Cli.<Runnable>builder(getClass().getSimpleName())
146                                .withDescription("oBIX Importer Tool")
147                                .withDefaultCommand(Help.class)
148                                .withCommands(Help.class, Write.class);
149        
150        //              builder.withGroup("unit")
151        //                      .withDescription("Manage set of tracked units")
152        //                      .withDefaultCommand(Load.class)
153        //                      .withCommands(UnitShow.class, UnitAdd.class);
154        
155                        Cli<Runnable> toolParser = builder.build();
156                        toolParser.parse(arguments).run();      
157                                
158                                return ErrorCode.OK.ordinal();
159                } catch (Exception e) {
160                        logger.severe(e.getMessage());
161                        return ErrorCode.Failure.ordinal();
162                }
163        }
164
165        /* (non-Javadoc)
166         * @see javax.tools.Tool#getSourceVersions()
167         */
168        @Override
169        public Set<SourceVersion> getSourceVersions() {
170                return Collections.unmodifiableSet(new HashSet<SourceVersion>(Arrays.asList(
171                                new SourceVersion[]{SourceVersion.RELEASE_5, SourceVersion.RELEASE_6, 
172                                                SourceVersion.RELEASE_7 }
173                                )));
174        }
175
176        /**
177         * @param args
178         */
179        public static void main(String[] args) {
180                final Tool importer = new ObixImporter();
181                int errorCode = importer.run(System.in, System.out, System.err, args);
182                if (errorCode == ErrorCode.OK.ordinal()) {
183                        System.out.println("Success.");
184                } else {
185                        System.err.println("Error!");
186                }
187        }
188}