Changeset 13094


Ignore:
Timestamp:
Jul 9, 2019 2:57:06 PM (5 months ago)
Author:
tgutzmann
Message:

#5804 Switch to java.nio.file.Path instead of File or String, where possible. Fixed some JavaDoc and formatting issues on the side.

Location:
branches/dev-tg-5804
Files:
17 edited

Legend:

Unmodified
Added
Removed
  • branches/dev-tg-5804/CHANGELOG.txt

    r13076 r13094  
    11================= Unreleased ==================
     2# Change ; Major ; Compiler ; #5804
     3Switch to "java.nio.file.Path" instead of "File" or "String"s representing paths in most places.
     4"Path" is more thought-through and more powerful, which will allow to implement advanced featuers in the future.
     5Note that while java.nio allows to access non-File resources with the same API, the internal workings of JModelica
     6currently make restrictions on only supporting file accesses.
     7
    28# Change ; Major; PyFMI ; #5802
    39Updated JModelica external to PyFMI 2.5.3
  • branches/dev-tg-5804/Compiler/ModelicaCompiler/src/jastadd/ModelicaCompiler.jrag

    r13060 r13094  
    3333import java.lang.StringBuilder;
    3434import java.nio.channels.FileChannel;
     35import java.nio.file.Path;
     36import java.nio.file.Paths;
    3537import java.util.Arrays;
    3638import java.util.ArrayList;
     
    669671    }
    670672   
     673    private static Path[] stringsToPaths(String[] s) {
     674        Path paths[] = new Path[s.length];
     675        for (int i = 0; i < s.length; i++) {
     676            paths[i] = Paths.get(s[i]);
     677        }
     678        return paths;
     679    }
     680   
    671681    /**
    672682     * Creates a target object.
    673683     *
    674684     * @param target The type of target: me, cs, ect. Use nocodegen for a NOCODEGEN target.
    675      * @param version The version in case of a fmu. Use null for a NOCODEGEN.
     685     * @param version The version in case of an fmu. Use null for a NOCODEGEN.
    676686     */
    677687    public TargetObject createTargetObject(String target, String version) {
     
    683693     * <p>
    684694     * Compiles a model (parsing, instantiating, flattening, code generation and
    685      * binary file compilation) and packs the result in a FMU.
     695     * binary file compilation) and packs the result in an FMU.
    686696     *
    687697     * @param className name of model class in the model file to compile.
     
    689699     * @param target    the compiler target. Valid options are 'me' or 'cs'.
    690700     * @param compileTo specify location of the compiled FMU. If a file is specified, the model will be renamed to this
    691      *                  name during the compilation. If directory, the model will keep its original name.
     701     *                  name during the compilation. If directory is specified, the model will keep its original name.
    692702     * @return          a {@link CompiledUnit} result object.
    693      */
     703     * @deprecated      Use {@link #compileFMU(String, Path[], String, Path)} instead
     704     */
     705    @Deprecated
    694706    public CompiledUnit compileFMU(String className, String fileName[], String target, String compileTo)
    695707            throws ModelicaException, FileNotFoundException, IOException, beaver.Parser.Exception {
    696708
    697         return compileUnit(className, fileName, target, "1.0" , compileTo);
     709        return compileFMU(className, stringsToPaths(fileName), target, Paths.get(compileTo));
     710    }
     711   
     712    /**
     713     * Compiles a model and creates an FMU, convenience method for compileUnit that uses default version.
     714     * <p>
     715     * Compiles a model (parsing, instantiating, flattening, code generation and
     716     * binary file compilation) and packs the result in an FMU.
     717     *
     718     * @param className name of model class in the model file to compile.
     719     * @param paths     array of model file or library paths.
     720     * @param target    the compiler target. Valid options are 'me' or 'cs'.
     721     * @param compileTo specify location of the compiled FMU. If a file is specified, the model will be renamed to this
     722     *                  name during the compilation. If directory is specified, the model will keep its original name.
     723     * @return          a {@link CompiledUnit} result object.
     724     * @deprecated      Use {@link #compileFMU(String, Path[], String, Path)} instead
     725     */
     726    public CompiledUnit compileFMU(String className, Path paths[], String target, Path compileTo)
     727            throws ModelicaException, FileNotFoundException, IOException, beaver.Parser.Exception {
     728   
     729        return compileUnit(className, paths, target, "1.0" , compileTo);
    698730    }
    699731
     
    702734     * <p>
    703735     * Compiles a model (parsing, instantiating, flattening and XML code
    704      * generation) and packs the result in a FMUX.
     736     * generation) and packs the result in an FMUX.
    705737     *
    706738     * @param className name of model class in the model file to compile.
     
    709741     *                  name during the compilation. If directory, the  model will keep its original name.
    710742     * @return          a {@link CompiledUnit} result object.
    711      */
     743     * @deprecated      Use {@link #compileFMUX(String, Path[], Path)} instead
     744     */
     745    @Deprecated
    712746    public CompiledUnit compileFMUX(String className, String fileName[], String compileTo)
    713747            throws ModelicaException, FileNotFoundException, IOException, beaver.Parser.Exception {
    714748
     749        return compileFMUX(className, stringsToPaths(fileName), Paths.get(compileTo));
     750    }
     751
     752    /**
     753     * Compiles a model and creates an FMUX, convenience method for compileUnit.
     754     * <p>
     755     * Compiles a model (parsing, instantiating, flattening and XML code
     756     * generation) and packs the result in an FMUX.
     757     *
     758     * @param className name of model class in the model file to compile.
     759     * @param fileName  array of model file or library paths.
     760     * @param compileTo specify location of the compiled FMUX. If a file is specified, the model will be renamed to this
     761     *                  name during the compilation. If directory, the  model will keep its original name.
     762     * @return          a {@link CompiledUnit} result object.
     763     */
     764    public CompiledUnit compileFMUX(String className, Path fileName[], Path compileTo)
     765            throws ModelicaException, FileNotFoundException, IOException, beaver.Parser.Exception {
     766
    715767        return compileUnit(className, fileName, "fmux", null , compileTo);
    716768    }
    717 
    718     /**
    719      * Compiles a FMU or FMUX. Is a wrapper.
     769    /**
     770     * Compiles an FMU or FMUX. Is a wrapper.
    720771     * <p>
    721772     * Compiles a model (parsing, instantiating, flattening, code generation and
    722      * binary file compilation) and packs the result in a FMU/FMUX.
     773     * binary file compilation) and packs the result in an FMU/FMUX.
    723774     *
    724775     * @param className name of model class in the model file to compile.
     
    729780     *                  this name during the compilation. If directory, the  model will keep its original name.
    730781     * @return          a {@link CompiledUnit} result object.
    731      */
     782     * @deprecated      Use {@link #compileUnit(String, Path[], String, String, String)} instead.
     783     */
     784    @Deprecated
    732785    public CompiledUnit compileUnit(String className, String fileName[], String target, String version, String compileTo)
    733786            throws ModelicaException, FileNotFoundException, IOException, beaver.Parser.Exception {
    734787
     788        return compileUnit(className, stringsToPaths(fileName), target, version, Paths.get(compileTo));
     789    }
     790   
     791    /**
     792     * Compiles an FMU or FMUX. Is a wrapper.
     793     * <p>
     794     * Compiles a model (parsing, instantiating, flattening, code generation and
     795     * binary file compilation) and packs the result in an FMU/FMUX.
     796     *
     797     * @param className name of model class in the model file to compile.
     798     * @param fileName  array of model file or library paths.
     799     * @param target    the compiler target. Valid options are 'me' or 'cs'.
     800     * @param version   the FMI version. Valid options are '1.0' or '2.0'.
     801     * @param compileTo specify location of the compiled FMU/FMUX. If a file is specified, the model will be renamed to
     802     *                  this name during the compilation. If directory, the  model will keep its original name.
     803     * @return          a {@link CompiledUnit} result object.
     804     */
     805    public CompiledUnit compileUnit(String className, Path fileName[], String target, String version, Path compileTo)
     806            throws ModelicaException, FileNotFoundException, IOException, beaver.Parser.Exception {
     807
    735808        TargetObject targetObject = TargetObject.getTarget(target, version);
    736809        return compileUnit(className, fileName, targetObject, compileTo);
     
    738811
    739812    /**
    740      * Compiles a FMU or FMUX.
     813     * Compiles an FMU or FMUX.
    741814     *
    742815     * @param className name of model class in the model file to compile.
     
    747820     * @return          a {@link CompiledUnit} result object.
    748821     */
    749     protected CompiledUnit compileUnit(String className, String fileName[], TargetObject target, String compileTo)
     822    protected CompiledUnit compileUnit(String className, Path fileName[], TargetObject target, Path compileTo)
    750823            throws ModelicaException, FileNotFoundException, IOException, beaver.Parser.Exception {
    751824
     
    776849    }
    777850
    778     protected CompiledUnit doCompileUnit(String className, String fileName[], TargetObject target, String compileTo)
     851    protected CompiledUnit doCompileUnit(String className, Path fileName[], TargetObject target, Path compileTo)
    779852        throws ModelicaException, FileNotFoundException, IOException, beaver.Parser.Exception {
    780853
     
    801874             */
    802875            String flatName = null;
    803             File compileToPath = new File(compileTo);
    804             if (!compileToPath.isDirectory()) {
    805                 flatName = compileToPath.getName();
     876            if (!Files.isDirectory(compileTo)) {
     877                flatName = compileTo.getFileName().toString();
    806878                int i = flatName.lastIndexOf('.');
    807                 if (i > 0)
     879                if (i > 0) {
    808880                    flatName = flatName.substring(0, i);
     881                }
    809882            }
    810883            FClass fc = compileModel(fileName, className, target, flatName, compileTo);
     
    841914    }
    842915
    843     protected void parseFiles(String[] paths) {
     916    protected void parseFiles(Path[] paths) throws IOException {
    844917        StepInfo.TimeItem time = new StepInfo.TimeItem();
    845918        time.begin();
    846         File[] files = new File[paths.length];
    847         for (int i = 0; i < paths.length; i++)
    848             files[i] = new File(paths[i]);
    849         parseFiles(files, true);
     919        parseFiles(Arrays.asList(paths), true);
    850920        time.end();
    851921        log.info("Total time: " + time);
    852922    }
    853923
    854     private void parseFiles(File[] files, boolean all) {
    855         for (File file : files) {
    856             if (file.isDirectory()) {
    857                 parseFiles(file.listFiles(), false);
     924    private void parseFiles(Iterable<Path> files, boolean all) throws IOException {
     925        for (Path file : files) {
     926            if (Files.isDirectory(file)) {
     927                try(DirectoryStream<Path> ds = Files.newDirectoryStream(file)) {
     928                    parseFiles(ds, false);
     929                }
    858930            } else {
    859                 String path = file.getPath();
     931                String path = file.toString();
    860932                try {
    861933                    if (all || hasModelicaFileExt(path)) {
    862                         parseModel(path);
     934                        parseModel(file);
    863935                        log.info(file + " parsed OK.");
    864936                    }
     
    9541026     *             If there was an error reading the model file. (Beaver exception.)
    9551027     */
    956     private SourceRoot parseModel(String name)
     1028    private SourceRoot parseModel(Path name)
    9571029      throws FileNotFoundException, IOException, beaver.Parser.Exception, CompilerException{
    9581030        return parserHandler.parseModel(createUtilInterface(), LoadInfo.create(name));
     
    9651037     * the parseModel method.
    9661038     *
    967      * @param names
     1039     * @param files
    9681040     *            An array of file names.
    9691041     *
     
    9751047     *             If errors have been found during the parsing.
    9761048     * @throws FileNotFoundException
    977      *             If the model file could not be found.
     1049     *             If any of the model files could not be found.
    9781050     * @throws IOException
    979      *             If there was an error reading the model file. (Beaver exception.)
    980      */
    981     public SourceRoot parseModel(String names[])
     1051     *             If there was an error reading any of the model files. (Beaver exception.)
     1052     * @deprecated use {@link #parseModel(Path[])} instead
     1053     */
     1054    @Deprecated
     1055    public SourceRoot parseModel(String files[])
     1056      throws FileNotFoundException, IOException, beaver.Parser.Exception, CompilerException {
     1057        return parseModel(stringsToPaths(files));
     1058    }
     1059
     1060    /**
     1061     *
     1062     * Parses a set of files and returns a reference to the root of a source tree
     1063     * where the content of all files is contained. Each file is parsed using
     1064     * the parseModel method.
     1065     *
     1066     * @param files
     1067     *            An array of file paths.
     1068     *
     1069     * @return The root of the source tree.
     1070     *
     1071     * @throws beaver.Parser.Exception
     1072     *             If there was a Beaver parsing exception.
     1073     * @throws CompilerException
     1074     *             If errors have been found during the parsing.
     1075     * @throws FileNotFoundException
     1076     *             If any of the model files could not be found.
     1077     * @throws IOException
     1078     *             If there was an error reading any of the model files. (Beaver exception.)
     1079     */
     1080    public SourceRoot parseModel(Path files[])
    9821081      throws FileNotFoundException, IOException, beaver.Parser.Exception, CompilerException {
    9831082        hookCheckAbort();
     
    9861085            doTearDown = trySetUp();
    9871086            Collection<LoadInfo> loadInfos = new ArrayList<>();
    988             for (String path : names) {
     1087            for (Path path : files) {
    9891088                loadInfos.add(LoadInfo.create(path));
    9901089            }
     
    10521151     *             If there was an Beaver parsing exception.
    10531152     */
    1054     private InstClassDecl instantiateModel(String name[], String cl, TargetObject target)
     1153    private InstClassDecl instantiateModel(Path name[], String cl, TargetObject target)
    10551154            throws ModelicaException, FileNotFoundException, IOException, beaver.Parser.Exception {
    10561155        // build source tree
     
    19132012     * can not be found or if the parsing fails. Supports multiple model files.
    19142013     *
    1915      * @param name
     2014     * @param files
    19162015     *            Array of model file or library paths.
    19172016     * @param cl
     
    19402039     *             If the Modelica class to parse, instantiate or flatten is not
    19412040     *             found.
    1942      *
    1943      */
    1944     public FClass ModelicaCompiler.compileModel(String name[], String cl, TargetObject target, String flatName, String compileTo)
     2041     * @deprecated Use {@link #compileModel(Path[], String, TargetObject, String, Path)} instead
     2042     */
     2043    public FClass ModelicaCompiler.compileModel(String files[], String cl, TargetObject target, String flatName, String compileTo)
     2044          throws ModelicaException, FileNotFoundException, IOException, beaver.Parser.Exception {
     2045        return compileModel(stringsToPaths(files), cl, target, flatName, Paths.get(compileTo));
     2046    }
     2047   
     2048    /**
     2049     * Compiles a Modelica model. A model file name and class must be provided.
     2050     * Prints an error and returns without completion if, for example, a file
     2051     * can not be found or if the parsing fails. Supports multiple model files.
     2052     *
     2053     * @param files
     2054     *            Array of model file or library paths.
     2055     * @param cl
     2056     *            The name of the class in the model file to compile.
     2057     * @param target
     2058     *            The target object for the compiler.
     2059     * @param flatName
     2060     *            Name of the unit/flat model supplied by the user, if any.
     2061     *
     2062     * @return A flat representation of the class specified by <code>cl</code>.
     2063     *            Returns null for some targets.
     2064     *
     2065     * @throws beaver.Parser.Exception
     2066     *             If there was an Beaver parsing exception.
     2067     * @throws CompilerException
     2068     *             If errors have been found during the parsing, instantiation
     2069     *             or flattening.
     2070     * @throws FileNotFoundException
     2071     *             If the model file can not be found.
     2072     * @throws IOException
     2073     *             If there was an error reading the model file. (Beaver
     2074     *             exception.)
     2075     * @throws IOException
     2076     *             If there was an error creating the .mof file.
     2077     * @throws ModelicaClassNotFoundException
     2078     *             If the Modelica class to parse, instantiate or flatten is not
     2079     *             found.
     2080     * @deprecated Use {@link #compileModel(Path[], String, TargetObject, String, Path)} instead
     2081     */
     2082     public FClass ModelicaCompiler.compileModel(Path files[], String cl, TargetObject target, String flatName, Path compileTo)
    19452083          throws ModelicaException, FileNotFoundException, IOException, beaver.Parser.Exception {
    19462084        boolean doTearDown = true;
    19472085        try {
    19482086            doTearDown = trySetUp();
    1949             return doCompileModel(name, cl, target, flatName, compileTo);
     2087            return doCompileModel(files, cl, target, flatName, compileTo);
    19502088        } finally {
    19512089            tryTearDown(doTearDown);
     
    19542092   
    19552093    public FClass ModelicaCompiler.doCompileModel(String name[], String cl, TargetObject target, String flatName, String compileTo)
     2094          throws ModelicaException, FileNotFoundException, IOException, beaver.Parser.Exception {
     2095        return doCompileModel(stringsToPaths(name), cl, target, flatName, Paths.get(compileTo));
     2096    }
     2097   
     2098   
     2099    public FClass ModelicaCompiler.doCompileModel(Path name[], String cl, TargetObject target, String flatName, Path compileTo)
    19562100          throws ModelicaException, FileNotFoundException, IOException, beaver.Parser.Exception {
    19572101        if (target.equals(TargetObject.PARSE)) {
     
    19782122           
    19792123            if (compileTo != null) {
    1980                 File unitFile = makePackagingDirs(cl, new File(compileTo), target);
     2124                File unitFile = makePackagingDirs(cl, compileTo.toFile(), target);
    19812125                icl.root().getUtilInterface().setCompilationOutputPath(unitFile);
    19822126            }
     
    21192263
    21202264    /**
    2121      * Packs a FMU (helper function for {@link #compileUnit()}).
     2265     * Packs an FMU (helper function for {@link #compileUnit()}).
    21222266     */
    21232267    protected File ModelicaCompiler.packUnit(String className,
     
    22102354syn boolean SourceRoot.isFileInLibrary() = findOutermostLibraryDir() != null;
    22112355
    2212 syn lazy String SourceRoot.findOutermostLibraryDir() {
     2356syn lazy Path SourceRoot.findOutermostLibraryDir() {
    22132357    if (getProgram().getNumUnstructuredEntity() != 1)
    22142358        return null;
     
    22172361}
    22182362
    2219 syn String SrcStoredDefinition.findOutermostLibraryDir() {
    2220     if (!hasSrcWithin() || !getSrcWithin().hasPackageName())
     2363syn Path SrcStoredDefinition.findOutermostLibraryDir() {
     2364    if (!hasSrcWithin() || !getSrcWithin().hasPackageName()) {
    22212365        return null;
    2222     File me = new File(fileName()).getAbsoluteFile();
    2223     if (SrcLibNode.isPackageFile(me))
    2224         me = me.getParentFile();
    2225     File lib = getSrcWithin().getPackageName().findOutermostLibraryDirForWithin(me);
    2226     return (lib != null) ? lib.getPath() : null;
     2366    }
     2367    Path me = Paths.get(fileName()).toAbsolutePath();
     2368    if (SrcLibNode.isPackageFile(me)) {
     2369        me = me.getParent();
     2370    }
     2371    Path lib = getSrcWithin().getPackageName().findOutermostLibraryDirForWithin(me);
     2372    return (lib != null) ? lib : null;
    22272373}
    22282374
    2229 syn File SrcAccess.findOutermostLibraryDirForWithin(File f) = null;
    2230 eq SrcDot.findOutermostLibraryDirForWithin(File f) {
     2375syn Path SrcAccess.findOutermostLibraryDirForWithin(Path f) = null;
     2376eq SrcDot.findOutermostLibraryDirForWithin(Path f) {
    22312377    for (int i = getNumSrcNamedAccess() - 1; i >= 0 && f != null; i--)
    22322378        f = getSrcNamedAccess(i).findOutermostLibraryDirForWithin(f);
    22332379    return f;
    22342380}
    2235 eq SrcNamedAccess.findOutermostLibraryDirForWithin(File f) {
    2236     f = f.getParentFile();
    2237     if (f != null && f.getName().equals(getID()) && SrcLibNode.isStructuredLib(f))
     2381eq SrcNamedAccess.findOutermostLibraryDirForWithin(Path f) {
     2382    f = f.getParent();
     2383    if (f != null && f.getFileName().toString().equals(getID()) && SrcLibNode.isStructuredLib(f))
    22382384        return f;
    22392385    else
  • branches/dev-tg-5804/Compiler/ModelicaFlatTree/src/jastadd/HtmlSourcePrettyPrint.jrag

    r12907 r13094  
    276276    }
    277277   
    278     public static String ASTNode.cropAbsolutePath(String path){
     278    private static String BaseNode.cropAbsolutePath(String path){
    279279        String p = path;
    280280        String dir = System.getProperty("user.dir");
  • branches/dev-tg-5804/Compiler/ModelicaFrontEnd/src/jastadd/flattening/Flattening.jrag

    r12975 r13094  
    774774        FExternalStmt stmt = new FExternalStmt();
    775775        SrcClassDecl scd = myTopSrcClassDecl();
    776         stmt.setLibTopPackagePath(scd == null ? "" : scd.myLibRootPath().getAbsolutePath()); // scd is null for builtins
     776        stmt.setLibTopPackagePath(scd == null ? "" : scd.myLibRootPath().toAbsolutePath().toString()); // scd is null for builtins
    777777        stmt.setFExternalLanguage(hasFExternalLanguage() ?
    778778                (FExternalLanguage) getFExternalLanguage().fullCopy() :
  • branches/dev-tg-5804/Compiler/ModelicaFrontEnd/src/jastadd/source/Library.jrag

    r12883 r13094  
    1919import java.io.File;
    2020import java.io.IOException;
     21import java.nio.file.DirectoryStream;
    2122import java.util.Set;
    2223import java.util.HashSet;
     
    8889            log.info("Reading file: " + fileName);
    8990            UtilInterface util = root().getUtilInterface();
    90             SourceRoot sr = util.getParserHandler().parseFile(util, getLoadInfo().withPath(fileName));
     91            SourceRoot sr = util.getParserHandler().parseFile(util, getLoadInfo().withPath(Paths.get(fileName)));
    9192            SrcStoredDefinition entity = sr.getProgram().getUnstructuredEntity(0);
    9293            SrcClassDecl cd = extractClassDecl(entity, name);
     
    103104                SrcFullClassDecl fcd = (SrcFullClassDecl) cd;
    104105                LibraryList ll = new LibraryList();
    105                 ll.addLibraryDirectory(getLoadInfo().withPath(dirName), getReason());
     106                ll.addLibraryDirectory(getLoadInfo().withPath(Paths.get(dirName)), getReason());
    106107
    107108                SrcLibClassDecl lcd = new SrcLibClassDecl(fcd, ll.createLibNodeList());
     
    130131        File orderFile = new File(baseDir, SrcLibNode.PACKAGE_ORDER_FILE);
    131132        if (orderFile.isFile()) {
    132             BufferedReader in = null;
    133             try {
    134                 in = new BufferedReader(util.getParserHandler().fileReader(util, orderFile));
     133            try(BufferedReader in = new BufferedReader(util.getParserHandler().fileReader(util, orderFile))){
    135134                java.util.List<String> order = new ArrayList<String>();
    136135                String line;
     
    140139            } catch (IOException e) {
    141140                // TODO: Add a warning about failing to load package.order
    142             } finally {
    143                 if (in != null) {
    144                     try {
    145                         in.close();
    146                     } catch (IOException e) {
    147                         // No action, nothing constructive to do here.
    148                     }
    149                 }
    150141            }
    151142        }
     
    260251     * Check if a path points to a structured library.
    261252     */
    262     public static boolean SrcLibNode.isStructuredLib(File f) {
    263         return f.isDirectory() && new File(f, PACKAGE_FILE).isFile();
    264     }
    265 
    266     public static boolean SrcLibNode.isUnstructuredLib(File f) {
    267         String name = f.getName();
    268         return f.isFile() && SrcLibNode.isUnstructuredLibName(name);
     253    public static boolean SrcLibNode.isStructuredLib(Path f) {
     254        return Files.isDirectory(f) && Files.isRegularFile(f.resolve(PACKAGE_FILE));
     255    }
     256
     257    public static boolean SrcLibNode.isUnstructuredLib(Path f) {
     258        String name = f.getFileName().toString();
     259        return Files.isRegularFile(f) && SrcLibNode.isUnstructuredLibName(name);
    269260    }
    270261
     
    273264    }
    274265
    275     private File SrcLibNode.myPackageFile() {
    276         return new File(dirName(), myPackageFileName());
     266    private Path SrcLibNode.myPackageFile() {
     267        return Paths.get(dirName(), myPackageFileName());
    277268    }
    278269   
     
    281272    }
    282273   
    283     public static String SrcLibNode.packageFile(File f) {
    284         File l = new File(f,SrcLibNode.PACKAGE_FILE);
    285         if (!l.exists()) {
     274    public static Path SrcLibNode.packageFile(Path f) {
     275        Path l = f.resolve(SrcLibNode.PACKAGE_FILE);
     276        if (!Files.exists(l)) {
    286277             return null;
    287278        }
    288         return l.getPath();
    289     }
    290    
    291     static boolean SrcLibNode.isPackageFile(File f) {
    292         return f.getName().equals(SrcLibNode.PACKAGE_FILE);
     279        return l;
     280    }
     281   
     282    static boolean SrcLibNode.isPackageFile(Path f) {
     283        return f.getFileName().toString().equals(SrcLibNode.PACKAGE_FILE);
    293284    }
    294285
     
    421412         */
    422413        protected boolean add(LoadInfo loadInfo, boolean directory, SrcLibNode.LoadReason reason) {
    423             File base = new File(loadInfo.getPath());
     414            Path base = loadInfo.getPathAsPath();
    424415            if (directory) {
    425416                boolean res = false;
    426                 try {
    427                     File[] files = base.listFiles();
    428                     if (files != null)
    429                         for (File file : files)
    430                             if (add(file, reason, loadInfo))
    431                                 res = true;
     417                try(DirectoryStream<Path> files = Files.newDirectoryStream(base)) {
     418                    for (Path file : files) {
     419                        if (add(file, reason, loadInfo)) {
     420                            res = true;
     421                        }
     422                    }
    432423                } catch (SecurityException e) {
    433424                    // TODO: should probably do something constructive here, log an error or something
     425                } catch (IOException e) {
     426                    // TODO: should probably do something constructive here as well
     427                    // Note: Cannot use "catch multiple", JastAdd doesn't support it yet
    434428                }
    435429                return res;
     
    439433        }
    440434
    441         protected boolean add(File path, SrcLibNode.LoadReason reason, LoadInfo loadInfo) {
     435        protected boolean add(Path path, SrcLibNode.LoadReason reason, LoadInfo loadInfo) {
    442436            try {
    443437                return add(LibraryDef.create(path, reason, loadInfo));
     
    463457    public class LoadInfo {
    464458
    465         private static final LoadInfo EMPTY = create("");
    466 
    467         private final String path;
    468 
     459        private static final LoadInfo EMPTY = create((Path)null);
     460
     461        private final Path path;
     462
     463        @Deprecated
    469464        public String getPath() {
     465            return path != null ? path.toString() : null;
     466        }
     467       
     468        public Path getPathAsPath() {
    470469            return path;
    471470        }
    472471       
     472        @Deprecated
    473473        public static LoadInfo create(String path) {
     474            return new LoadInfo(Paths.get(path));
     475        }
     476       
     477        public static LoadInfo create(Path path) {
    474478            return new LoadInfo(path);
    475479        }
     
    480484    }
    481485
    482     private LoadInfo.LoadInfo(String path) {
     486    private LoadInfo.LoadInfo(Path path) {
    483487        this.path = path;
    484488    }
    485489
    486     public LoadInfo LoadInfo.withPath(String path) {
     490    public LoadInfo LoadInfo.withPath(Path path) {
    487491        return new LoadInfo(path);
    488492    }
     
    529533    }
    530534
    531     public static LibraryDef LibraryDef.create(File path, SrcLibNode.LoadReason reason, LoadInfo loadInfo) {
     535    public static LibraryDef LibraryDef.create(Path path, SrcLibNode.LoadReason reason, LoadInfo loadInfo) {
    532536        boolean structured;
    533537        if (SrcLibNode.isStructuredLib(path)) {
     
    538542            return null;
    539543        }
    540         String name = path.getName();
     544        String name = path.getFileName().toString();
    541545        String version;
    542546        if (!structured) {
     
    550554            version = null;
    551555        }
    552         return new LibraryDef(name, version, structured, reason, loadInfo.withPath(path.getPath()));
     556        return new LibraryDef(name, version, structured, reason, loadInfo.withPath(path));
    553557    }
    554558
  • branches/dev-tg-5804/Compiler/ModelicaFrontEnd/src/jastadd/source/Parser.jrag

    r12761 r13094  
    7979        uif.transferRoot(sr);
    8080        for (LoadInfo loadInfo : loadInfos) {
    81             File f = new File(loadInfo.getPath());
     81            Path f = loadInfo.getPathAsPath();
    8282            LoadInfo tmpInfo = loadInfo;
    83             if (f.isDirectory())
     83            if (Files.isDirectory(f)) {
    8484                tmpInfo = loadInfo.withPath(SrcLibNode.packageFile(f));
    85             SourceRoot sr_tmp = (tmpInfo.getPath() != null) ? parseModel(uif, tmpInfo) : null;
     85            }
     86            SourceRoot sr_tmp = (tmpInfo.getPathAsPath() != null) ? parseModel(uif, tmpInfo) : null;
    8687            if (!uif.getOptionRegistry().getBooleanOption("ignore_within")) {
    87                 String lib = null;
    88                 if (sr_tmp != null && sr_tmp.isFileInLibrary())
     88                Path lib = null;
     89                if (sr_tmp != null && sr_tmp.isFileInLibrary()) {
    8990                    lib = sr_tmp.findOutermostLibraryDir();
    90                 else if (SrcLibNode.isPackageFile(f))
     91                }
     92                else if (SrcLibNode.isPackageFile(f)) {
    9193                    lib = f.getParent();
     94                }
    9295                if (lib != null) {
    93                     String type = f.isDirectory() ? "Directory" : "File";
    94                     ModelicaCompiler.log.warning("%s '%s' is part of library at '%s', using library instead.", type, loadInfo.getPath(), lib);
     96                    String type = Files.isDirectory(f) ? "Directory" : "File";
     97                    ModelicaCompiler.log.warning("%s '%s' is part of library at '%s', using library instead.", type, loadInfo.getPath(), lib.toString());
    9598                    loadInfo = loadInfo.withPath(lib);
    96                     f = new File(lib);
     99                    f = lib;
    97100                }
    98101            }
    99             if (f.isDirectory()) {
     102            if (Files.isDirectory(f)) {
    100103                if (!sr.getProgram().getLibraryList().addLibrary(loadInfo, SrcLibNode.LoadReason.COMMANDLINE))
    101104                    ModelicaCompiler.log.error(String.format("Error: The directory '%s' is not a Modelica library.", loadInfo.getPath()));
     
    213216    }
    214217   
    215     public static final LoadInfo ParserHandler.EXP_FILENAME = LoadInfo.create("<predefined string>");
     218    public static final LoadInfo ParserHandler.EXP_FILENAME = LoadInfo.create((Path)null);
    216219
    217220    public SrcExp ParserHandler.parseModelicaExpString(String str)
     
    231234    }
    232235
    233     public static final LoadInfo ParserHandler.ANONYMOUS_CLASS_FILENAME = LoadInfo.create("<command line argument>");
     236    public static final LoadInfo ParserHandler.ANONYMOUS_CLASS_FILENAME = LoadInfo.create((Path)null);
    234237
    235238    public SrcBaseClassDecl ParserHandler.parseModelicaAnonymousClassString(String code, SrcRestriction restriction, String targetName)
  • branches/dev-tg-5804/Compiler/ModelicaFrontEnd/src/jastadd/util/SrcUtil.jrag

    r13009 r13094  
    333333     * unstructured library is the modelica file it self.
    334334     */
    335     syn File SrcBaseNode.myLibRootPath() {
     335    syn Path SrcBaseNode.myLibRootPath() {
    336336        SrcClassDecl topClass = myTopSrcClassDecl();
    337         File fileRoot = new File(topClass.fileName());
    338         return topClass.isLibNode() ?  fileRoot.getParentFile() : fileRoot;
     337        Path fileRoot = Paths.get(topClass.fileName());
     338        return topClass.isLibNode() ?  fileRoot.getParent() : fileRoot;
    339339    }
    340340}
  • branches/dev-tg-5804/Compiler/ModelicaFrontEnd/src/jastadd/util/Util.jrag

    r13060 r13094  
    673673    }
    674674    public String SrcLibNode.fileName() {
    675         return getStructured() ? myPackageFile().getPath() : getLoadInfo().getPath();
     675        return getStructured() ? myPackageFile().toString() : getLoadInfo().getPath();
    676676    }
    677677    public String InstLibNode.fileName() {
  • branches/dev-tg-5804/Compiler/ModelicaFrontEnd/src/java/org/jmodelica/api/problemHandling/package-info.java

    r9345 r13094  
    11/**
    2  * This package contains classes representing {@link Problem}s, that is, issues
     2 * This package contains classes representing {@link org.jmodelica.api.problemHandling.Problem}s, that is, issues
    33 * with the source code detected during compilation.
    44 */
  • branches/dev-tg-5804/Compiler/ModelicaFrontEnd/src/java/org/jmodelica/common/evaluation/ExternalFunction.java

    r10912 r13094  
    88/**
    99 * Represents an external function that can be evaluated using
    10  * {@link ExternalFunction.evaluate}.
     10 * {@link #evaluate}.
    1111 */
    1212public interface ExternalFunction<K, V> {
  • branches/dev-tg-5804/Compiler/ModelicaFrontEnd/src/java/org/jmodelica/common/options/TestOptions.java

    r12940 r13094  
    11package org.jmodelica.common.options;
     2
     3import org.jmodelica.modelica.compiler.TestAnnotationizerHelper;
     4import org.jmodelica.modelica.compiler.TestCase;
    25
    36/**
     
    6770     * testing context.
    6871     * <p>
    69      * These methods retrieves options of the correct type via generics' magic.
     72     * These methods retrieve options of the correct type via generics-magic.
    7073     */
    7174
  • branches/dev-tg-5804/Compiler/ModelicaFrontEnd/src/java/org/jmodelica/junit/Util.java

    r12542 r13094  
    11package org.jmodelica.junit;
    22
    3 import java.io.UnsupportedEncodingException;
     3import java.net.URISyntaxException;
    44import java.net.URL;
    5 import java.net.URLDecoder;
     5import java.nio.file.Path;
     6import java.nio.file.Paths;
    67
    78import org.jmodelica.util.exceptions.InternalCompilerError;
     
    1920     * @return  the path to the resource.
    2021     */
    21     public static String resource(Object test, String name) {
     22    public static Path resource(Object test, String name) {
    2223        return resource(test.getClass(), name);
    2324    }
     
    3031     * @return  the path to the resource.
    3132     */
    32     public static String resource(Class<?> clazz, String name) {
     33    public static Path resource(Class<?> clazz, String name) {
    3334        try {
    3435            URL url = clazz.getResource(name);
     
    3738                        "\" from the class \"" + clazz.getSimpleName() + "\".");
    3839            }
    39 
    40             // This ensures that spaces are encoded correctly!
    41             return URLDecoder.decode(url.getPath(), "UTF-8");
    42         } catch (UnsupportedEncodingException e) {
     40            return Paths.get(url.toURI());
     41        } catch (URISyntaxException e) {
    4342            throw new InternalCompilerError("Unable to decode loaded resource URL; " + e.getMessage(), e);
    4443        }
  • branches/dev-tg-5804/Compiler/ModelicaFrontEnd/src/java/org/jmodelica/separateProcess/CompilerInstance.java

    r11731 r13094  
    1818import java.io.File;
    1919import java.io.IOException;
     20import java.nio.file.Path;
    2021import java.util.ArrayList;
    2122import java.util.Collection;
     
    2526import java.util.Map;
    2627
     28import org.jmodelica.util.StringUtil;
    2729import org.jmodelica.util.logging.IllegalLogStringException;
    28 import org.jmodelica.util.StringUtil;
    2930
    3031/**
     
    6061    public CompilerInstance(String jmodelicaHome) {
    6162        this.jmodelicaHome = jmodelicaHome;
    62         if (!new File(joinPath(jmodelicaHome, "lib", "ModelicaCompiler.jar")).exists())
     63        if (!new File(joinPath(jmodelicaHome, "lib", "ModelicaCompiler.jar")).exists()) {
    6364            throw new IllegalArgumentException("JMODELICA_HOME does not point to a valid jmodelica installation!");
     65        }
    6466        setJavaHome(System.getProperty("java.home"));
    6567        setClassPath(joinPath(jmodelicaHome, "lib", "ModelicaCompiler.jar"), joinPath(jmodelicaHome, "lib", "OptimicaCompiler.jar"), joinPath(jmodelicaHome, "lib", "util.jar"), joinPath(jmodelicaHome, "ThirdParty", "Beaver", "lib", "beaver-rt.jar"));
     
    99101    public void addClassPath(String... paths) {
    100102        if (paths != null) {
    101             for (String path : paths)
     103            for (String path : paths) {
    102104                classPath.add(path);
     105            }
    103106        }
    104107    }
     
    147150    public void addModelicaPath(String... paths) {
    148151        if (paths != null) {
    149             for (String path : paths)
     152            for (String path : paths) {
    150153                modelicaPath.add(path);
     154            }
    151155        }
    152156    }
     
    245249    }
    246250
    247     public Compilation compile(String modelName, String... sourceFiles) throws IOException {
     251    public Compilation compile(String modelName, String ... sourceFiles) throws IOException {
    248252        return new Compilation(buildArgs(modelName, sourceFiles), jmodelicaHome);
     253    }
     254   
     255    public Compilation compile(String modelName, Path ... sourceFiles) throws IOException {
     256        if (sourceFiles == null) {
     257            return compile(modelName, (String[])null);
     258        }
     259        String[] files = new String[sourceFiles.length];
     260        for (int i = 0; i < sourceFiles.length; i++) {
     261            files[i] = sourceFiles[i].toString();
     262        }
     263        return compile(modelName, files);
    249264    }
    250265
  • branches/dev-tg-5804/Compiler/ModelicaFrontEnd/src/java/org/jmodelica/util/SizeNode.java

    r13063 r13094  
    4040        BufferedReader in = new BufferedReader(new FileReader(file));
    4141        SizeNode root = new SizeNode(in.readLine());
    42         if (root.level == 0)
    43             root.fill(in);
    44         else
    45             root = fillRev(in, root, 1);
     42        if (root.level == 0) {
     43            root.fill(in);
     44        } else {
     45            root = fillRev(in, root, 1);
     46        }
    4647        return root;
    4748    }
     
    5859        ArrayList<SizeNode> siblings = new ArrayList<SizeNode>();
    5960        do {
    60             if (level < next.level)
    61                 next = fillRev(in, next, level + 1);
     61            if (level < next.level) {
     62                next = fillRev(in, next, level + 1);
     63            }
    6264            if (level == next.level) {
    6365                siblings.add(0, next);
     
    6567            }
    6668        } while (level <= next.level);
    67         if (next.children == null)
    68             next.children = siblings;
     69        if (next.children == null) {
     70            next.children = siblings;
     71        }
    6972        return next;
    7073    }
     
    9093    private static SizeNode readNode(BufferedReader in) throws IOException {
    9194        String line = in.readLine();
    92         if (line == null)
    93             return null;
     95        if (line == null) {
     96            return null;
     97        }
    9498        return new SizeNode(line);
    9599    }
    96100
    97101    private void add(SizeNode child) {
    98         if (children == null)
    99             children = new ArrayList<SizeNode>();
     102        if (children == null) {
     103            children = new ArrayList<SizeNode>();
     104        }
    100105        children.add(child);
    101106        child.parent = this;
    102107    }
    103108
    104     public TreeNode getChildAt(int childIndex) {
     109    @Override
     110    public TreeNode getChildAt(int childIndex) {
    105111        return children.get(childIndex);
    106112    }
    107113
    108     public int getChildCount() {
     114    @Override
     115    public int getChildCount() {
    109116        return children != null ? children.size() : 0;
    110117    }
    111118
    112     public TreeNode getParent() {
     119    @Override
     120    public TreeNode getParent() {
    113121        return parent;
    114122    }
    115123
    116     public int getIndex(TreeNode node) {
     124    @Override
     125    public int getIndex(TreeNode node) {
    117126        return children != null ? children.indexOf(node) : -1;
    118127    }
    119128
    120     public boolean getAllowsChildren() {
     129    @Override
     130    public boolean getAllowsChildren() {
    121131        return true;
    122132    }
    123133
    124     public boolean isLeaf() {
     134    @Override
     135    public boolean isLeaf() {
    125136        return getChildCount() == 0;
    126137    }
    127138
    128     public Enumeration<SizeNode> children() {
     139    @Override
     140    public Enumeration<SizeNode> children() {
    129141        return Collections.enumeration(children);
    130142    }
    131143   
    132     public String toString() {
     144    @Override
     145    public String toString() {
    133146        return size + " - " + node;
    134147    }
  • branches/dev-tg-5804/Compiler/ModelicaFrontEnd/src/java/org/jmodelica/util/SizeTree.java

    r13063 r13094  
    2929
    3030public class SizeTree extends JFrame {
    31     public SizeTree(String file) throws IOException {
     31    private static final long serialVersionUID = 1L;
     32
     33    public SizeTree(String file) throws IOException {
    3234        super("Profiler size file viewer - " + file);
    3335        SizeNode data = SizeNode.readTree(file);
  • branches/dev-tg-5804/Compiler/ModelicaFrontEnd/src/java/org/jmodelica/util/files/ModifiableFile.java

    r12940 r13094  
    232232     * Note that if the source file is also the destination file, as is the case
    233233     * when the constructor {@link #ModifiableFile(File)} is used, using
    234      * {@link #write()} will also update the point to which this method can
     234     * {@link #write} will also update the point to which this method can
    235235     * revert content.
    236236     *
  • branches/dev-tg-5804/Compiler/ModelicaFrontEnd/src/java/org/jmodelica/util/logging/ModelicaLogger.java

    r12984 r13094  
    2020import java.io.IOException;
    2121import java.io.OutputStream;
     22import java.nio.file.Path;
    2223import java.util.ArrayList;
    2324import java.util.Collection;
     
    8990
    9091    private void log(Level level, Object obj) {
    91         if (!getLevel().shouldLog(level))
     92        if (!getLevel().shouldLog(level)) {
    9293            return;
     94        }
    9395       
    9496        if (obj instanceof Throwable) {
     
    129131
    130132    private void log(Level level, String format, Object... args) {
    131         if (!getLevel().shouldLog(level))
     133        if (!getLevel().shouldLog(level)) {
    132134            return;
     135        }
    133136        write(level, new StringLoggingUnit(format, args));
    134137    }
     
    145148     */
    146149    public void logProblems(Collection<Problem> problems) {
    147         for (Problem problem : problems)
     150        for (Problem problem : problems) {
    148151            logProblem(problem);
     152        }
    149153    }
    150154
     
    170174     * @param numberOfComponents    the number of components in the FMU.
    171175     * @return                      an object representing the successful compilation.
    172      * @deprecated                  use {@link #logCompiledUnit(File, Collection, int)} instead.
     176     * @deprecated                  use {@link #logCompiledUnit(Path, Collection, int)} instead.
    173177     */
    174178    @Deprecated
     
    186190     * @param numberOfComponents    the number of components in the FMU.
    187191     * @return                      an object representing the successful compilation.
    188      */
     192     * @deprecated                  use {@link #logCompiledUnit(Path, Collection, int)} instead.
     193     */
     194    @Deprecated
    189195    public CompiledUnit logCompiledUnit(File unitFile, Collection<Problem> warnings, int numberOfComponents) {
    190         CompiledUnit unit = new CompiledUnit(unitFile, warnings, numberOfComponents);
     196        return logCompiledUnit(unitFile.toPath(), warnings, numberOfComponents);
     197    }
     198   
     199    /**
     200     * Log the compiled unit, it will be written on level info.
     201     *
     202     * @param unitPath              the path pointing to the compiled FMU.
     203     * @param warnings              the warnings generated during compilation.
     204     * @param numberOfComponents    the number of components in the FMU.
     205     * @return                      an object representing the successful compilation.
     206     */
     207    public CompiledUnit logCompiledUnit(Path unitPath, Collection<Problem> warnings, int numberOfComponents) {
     208        CompiledUnit unit = new CompiledUnit(unitPath.toFile(), warnings, numberOfComponents);
    191209        logCompiledUnit(unit);
    192210        return unit;
     
    254272
    255273    private OutputStream logStream(Level level) {
    256         if (getLevel().shouldLog(level))
     274        if (getLevel().shouldLog(level)) {
    257275            return new LogOutputStream(level);
    258         else
     276        } else {
    259277            return NullStream.OUTPUT;
     278        }
    260279    }
    261280
     
    288307        public void write(int b) throws IOException {
    289308            buf[n++] = (byte) b;
    290             if (lastR || b == N)
     309            if (lastR || b == N) {
    291310                logBuffer();
     311            }
    292312            lastR = (b == R);
    293313        }
     
    319339            while (nlpos >= 0) {
    320340                nlpos = -1;
    321                 for (int i = start; nlpos < 0 && i < n; i++)
    322                     if (buf[i] == N || buf[i] == R)
     341                for (int i = start; nlpos < 0 && i < n; i++) {
     342                    if (buf[i] == N || buf[i] == R) {
    323343                        nlpos = i;
     344                    }
     345                }
    324346                if (nlpos == n - 1 && buf[nlpos] == R && (start > 0 || n < buf.length)) {
    325347                    lastR = true;
     
    328350                    log(level, new String(buf, start, nlpos - start));
    329351                    start = nlpos + 1;
    330                     if (start < n && buf[start] == N && buf[start - 1] == R)
     352                    if (start < n && buf[start] == N && buf[start - 1] == R) {
    331353                        start++;
     354                    }
    332355                } else if (start == 0 && n == buf.length) {
    333356                    log(level, new String(buf, 0, n));
     
    337360
    338361            n -= start;
    339             if (n > 0 && start > 0)
     362            if (n > 0 && start > 0) {
    340363                System.arraycopy(buf, start, buf, 0, n);
     364            }
    341365        }
    342366
     
    360384        Collection<String> problems = new ArrayList<String>();
    361385        Map<String, LoggerProps> loggerMap = new HashMap<String, LoggerProps>();
    362         if (logString == null)
     386        if (logString == null) {
    363387            logString = "";
     388        }
    364389        logString = logString.trim();
    365390        // Step 1. Parse log string, put in map to remove duplicates
     
    439464            }
    440465        }
    441         if (loggers.size() == 0)
     466        if (loggers.size() == 0) {
    442467            loggers.add(new StreamingLogger(Level.ERROR, System.out));
     468        }
    443469        // Step 3. Create TeeLogger if necessary
    444470        ModelicaLogger logger;
    445         if (loggers.size() == 1)
     471        if (loggers.size() == 1) {
    446472            logger = loggers.get(0);
    447         else
     473        } else {
    448474            logger = new TeeLogger(loggers.toArray(new ModelicaLogger[loggers.size()]));
     475        }
    449476        if (problems.size() > 0) {
    450477            StringBuilder sb = new StringBuilder();
Note: See TracChangeset for help on using the changeset viewer.