Преглед на файлове

fixes for #1, #2 and #3.
Error messages clarified
Better handling for relative paths
Upgrade ways added for cachestate files

LH преди 7 години
родител
ревизия
65f49bfbe1

+ 37 - 1
ToolKit/src/main/java/de/nplusc/izc/tools/IOtools/FileTK.java

@@ -19,6 +19,8 @@ package de.nplusc.izc.tools.IOtools;
 
 import de.nplusc.izc.tools.baseTools.Tools;
 import java.io.*;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
 import java.nio.CharBuffer;
 import java.nio.channels.FileChannel;
 import java.nio.charset.StandardCharsets;
@@ -428,6 +430,11 @@ public class FileTK
         return ret;
     }
 
+    /**
+     * internal flag that caches that a catch block triggered and disables the reflection on the path class
+     */
+    private static boolean blockNewpathMethod=false;
+    
     /**
      * Erzeugt den relativen Pfad einer datei/eines Ordners zu eienm Basispfad
      *
@@ -437,9 +444,38 @@ public class FileTK
      */
     public static String getRelativePath(String absolutePath, String basePath)//Initializer für Hack!
     {
+        String rpath =null;
+        if(!blockNewpathMethod)
+        {
+            //reflection für neuere Java-Klassen
+            try
+            {
+                Class pathclass = Class.forName("java.nio.file.Path");
+                Object basepath = null;
+                File magix = new File(basePath);
+                Method pfadheraberdalli = File.class.getMethod("toPath");
+                basepath =  pfadheraberdalli.invoke(magix);
+                
+                Method rel=pathclass.getMethod("relativize", (Class)pathclass);
+                File current = new File(absolutePath);
+                Object pa = pfadheraberdalli.invoke(current);
+                l.trace("pa-Class:"+pa.getClass());
+                rpath = rel.invoke(basepath, pa)+"";
+            }
+            catch(ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException| InvocationTargetException ex)
+            {
+                blockNewpathMethod=true; //abklemmen der klassentestung.
+            }
+        }
+        
+        //continue with fallback incase the new method doesn't work.
+        if(rpath!=null)
+        {
+            return rpath;
+        }
         absolutePath = absolutePath.replace("/", "\\");
         basePath = basePath.replace("/", "\\");
-        String rpath = getRelativePath(absolutePath, basePath, 0);
+        rpath = getRelativePath(absolutePath, basePath, 0);
         return rpath==null?rpath:rpath.replace("\\", File.separator);
     }
 

+ 14 - 1
WPCMGr/src/main/java/de/nplusc/izc/Utilities/WPCMgr/CacheState.java

@@ -30,12 +30,13 @@ public class CacheState
     private List<String> processedPackages;
     private HashMap<String,PackageState> packages;
     private List<ResultWallpaper> processedWallpapersMappings;
+    private int version;
     public CacheState()
     {
         processedPackages=new ArrayList<>();
         packages = new LinkedHashMap<>();
         processedWallpapersMappings = new ArrayList<>();
-        
+        version = -1;
     }
 
     public List<ResultWallpaper> getProcessedWallpapersMappings()
@@ -74,4 +75,16 @@ public class CacheState
         }*/
         this.packages = packages;
     }
+
+    public int getVersion()
+    {
+        return version;
+    }
+
+    public void setVersion(int version)
+    {
+        this.version = version;
+    }
+    
+    
 }

+ 34 - 0
WPCMGr/src/main/java/de/nplusc/izc/Utilities/WPCMgr/CacheStateParsingException.java

@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2018 iZc
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program 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 General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+package de.nplusc.izc.Utilities.WPCMgr;
+
+/**
+ *
+ * @author iZc <nplusc.de>
+ */
+public class CacheStateParsingException extends RuntimeException
+{
+
+    public CacheStateParsingException()
+    {
+    }
+    
+    public CacheStateParsingException(String msg)
+    {
+        super(msg);
+    }
+}

+ 6 - 4
WPCMGr/src/main/java/de/nplusc/izc/Utilities/WPCMgr/Main.java

@@ -17,7 +17,9 @@
 
 package de.nplusc.izc.Utilities.WPCMgr;
 
+import java.io.File;
 import java.io.FileNotFoundException;
+import java.nio.file.Path;
 import java.util.Arrays;
 import java.util.HashMap;
 import java.util.List;
@@ -129,6 +131,8 @@ public class Main
             if (cl.hasOption("folder"))
             {
                 folder = cl.getOptionValue("folder");
+                // normalizing path to a absolute path. should  fix #3
+                folder = new File(folder).getAbsolutePath();
             }
             else
             {
@@ -137,6 +141,7 @@ public class Main
                     throw new ParseException("Folder undefined");
                 }
             }
+            
             l.trace(folder);
             
             if (cl.hasOption("profile"))
@@ -186,6 +191,7 @@ public class Main
                             throw new ParseException("Malformed screen string: Invalid number giveen @ "+screendef);
                         }
                     }
+                    
                     WPCUtils.saveConfig(folder, cfg);
                 }
                 else
@@ -278,16 +284,12 @@ public class Main
                                                 }
                                             }
                                         }
-
-
                                     };
-
                                 }
                             }
                         }
                     }
                 }
-               
             }
         }
         catch (ParseException ex)

+ 107 - 43
WPCMGr/src/main/java/de/nplusc/izc/Utilities/WPCMgr/Synchronizer.java

@@ -39,6 +39,7 @@ import org.apache.logging.log4j.LogManager;
 import org.apache.logging.log4j.Logger;
 import org.apache.logging.log4j.io.IoBuilder;
 import org.yaml.snakeyaml.Yaml;
+import org.yaml.snakeyaml.error.YAMLException;
 
 /**
  *
@@ -71,44 +72,53 @@ public class Synchronizer
     
     public static void wpcToFlatFolder(String targetCache, boolean debugmode,boolean dryRun,String profile) throws FileNotFoundException
     {
-        final LinkedHashMap<String, Object> data = (LinkedHashMap<String, Object>) WPCUtils.getConfig(targetCache);
-            HashMap<String,Object> profiles_storage = (HashMap<String,Object>) data.get("profiles");
-            Set<String> profile_ids = profiles_storage.keySet();
-        
-        
-        
-        if(dryRun)
-        {
-            l.info("DRY");
-        }
-        
-        List<String> profiles = new ArrayList<>();
-        
-        if(profile.equals("__ALL__"))
-        {
-            profiles.addAll(profile_ids);
-        }
-        else
+        try
         {
-            if(profile_ids.contains(profile))
+            final LinkedHashMap<String, Object> data = (LinkedHashMap<String, Object>) WPCUtils.getConfig(targetCache);
+                HashMap<String,Object> profiles_storage = (HashMap<String,Object>) data.get("profiles");
+                Set<String> profile_ids = profiles_storage.keySet();
+            if(dryRun)
             {
-                 profiles.add(profile);
+                l.info("DRY");
+            }
+
+            List<String> profiles = new ArrayList<>();
+
+            if(profile.equals("__ALL__"))
+            {
+                profiles.addAll(profile_ids);
             }
             else
             {
-                l.error("Invalid ProfileID, profile not existing");
+                if(profile_ids.contains(profile))
+                {
+                     profiles.add(profile);
+                }
+                else
+                {
+                    l.error("Invalid ProfileID, profile not existing");
+                }
+            }
+            int i=1;
+            int count = profiles.size();
+            l.trace(new Yaml().dump(profiles));
+            for(String id:profiles)
+            {
+                l.info("Converting Profile {} ({}/{})",id,i,count);
+                new Synchronizer().handleWPC(targetCache, debugmode, dryRun,id); 
+                i++;
             }
         }
-        int i=1;
-        int count = profiles.size();
-        l.trace(new Yaml().dump(profiles));
-        for(String id:profiles)
+        catch(YAMLException ex)
         {
-            l.info("Converting Profile {} ({}/{})",id,i,count);
-            new Synchronizer().handleWPC(targetCache, debugmode, dryRun,id); 
-            i++;
+            l.error("Invalid Configuration file detected:");
+            l.error(ex.getMessage());
+        }
+        catch(CacheStateParsingException ex)
+        {
+            l.error("Invalid CacheState, cannot continue:");
+            l.error(ex.getMessage());
         }
-        
     }
     
     public static void getSourcePathForID(String targetCache,String wallpaperID) throws ParseException, FileNotFoundException
@@ -270,13 +280,16 @@ public class Synchronizer
             if(gravity!=null&&gravity.containsKey(k))
             {
                 s.setAlternativeMode(true);
+                String orientationstring = gravity.get(k).toLowerCase();  // #1
+                String firstCharacter = orientationstring.substring(0,1).toUpperCase();
+                orientationstring = firstCharacter+orientationstring.substring(1);
                 try{
-                    Orientation o = Orientation.valueOf(gravity.get(k));
+                    Orientation o = Orientation.valueOf(orientationstring);
                     s.setOrientation(o);
                 }
                 catch(IllegalArgumentException e)
                 {
-                    l.error("Ungültige Konstante für die Ausrichtung des Monitorstrips {}. {} ist nicht North,Center,South",k,gravity.get(k));
+                    l.error("Ungültige Konstante für die Ausrichtung des Monitorstrips {}. {} ist nicht Top,Middle,Bottom",k,gravity.get(k));
                     s.setOrientation(Orientation.Center);
                 }
             }
@@ -306,7 +319,7 @@ public class Synchronizer
         l.trace("ScreenHash:{}", screenHash);
 
         CacheState theState = WPCUtils.getCacheState(cachedir);
-
+        upgradeCacheState(theState); //another fix for #3 and future cacheState modifications
         final int[] attr =
         {
             0, 0, 0, 0
@@ -405,7 +418,6 @@ public class Synchronizer
             currentFile = 1;
             final String destFolder = (String) profile_data.get("Outdir") + File.separator;
             FileTK.ensuredirExistence(destFolder+File.separator+"dummy.txt");
-            theState.getProcessedWallpapersMappings().addAll(copylist);
             copylist.forEach((v) ->
             {
                 progressBar.setMessage("Kopieren:" + currentFile + "/" + totalFiles);
@@ -467,6 +479,7 @@ public class Synchronizer
                 l.trace(wpp);
                 wpp = path + File.separator + "proc" + File.separator + FileTK.getFileName(wpp);
             }
+            wpp=FileTK.getRelativePath(wpp, cachedir);
             l.trace(wpp);
             Wallpaper wp = new Wallpaper(screenHash - 1, wpp);
             //int wpi = existingWPsN.indexOf(wp);
@@ -487,6 +500,7 @@ public class Synchronizer
             {
                 wpp = path + File.separator + "k-i-p" + File.separator + FileTK.getFileName(wpp);
             }
+            wpp=FileTK.getRelativePath(wpp, cachedir);
             Wallpaper wp = new Wallpaper(screenHash - 1, wpp);
             //int wpi = existingWPsN.indexOf(wp);
             if (!existingWPsF.contains(wp))
@@ -506,6 +520,7 @@ public class Synchronizer
             {
                 wpp = path + File.separator + "b-frames" + File.separator + FileTK.getFileName(wpp);
             }
+            wpp=FileTK.getRelativePath(wpp, cachedir);
             Wallpaper wp = new Wallpaper(screenHash - 1, wpp);
             //int wpi = existingWPsN.indexOf(wp);
             if (!existingWPsB.contains(wp))
@@ -615,27 +630,46 @@ public class Synchronizer
     }
 
     private void identifyAll(CacheState st)
+    {
+        identifyAll(st, "Analysisere: ");
+    }
+    
+    
+    
+    private void identifyAll(CacheState st, String progressBase)
     {
         progressBar = progressBar.withTotalSteps(totalFiles + 1);
-        progressBar.setMessage("Analysisere:0/" + totalFiles);
+        progressBar.setMessage(progressBase+"0/" + totalFiles);
         progressBar.start();
         currentFile=1;
         HashMap<String,PackageState> packages = st.getPackages();
         packages.forEach((id,pkg)->{
-            pkg.getB_frames().forEach(this::identify);
-            pkg.getFixedRatioPics().forEach(this::identify);
-            pkg.getStretchablePics().forEach(this::identify);
+            pkg.getB_frames().forEach((w)->{identify(w, progressBase);});
+            pkg.getFixedRatioPics().forEach((w)->{identify(w, progressBase);});
+            pkg.getStretchablePics().forEach((w)->{identify(w, progressBase);});
         });
         progressBar.complete();
     }
     
-    private void identify(Wallpaper wallpaper)
+    private void identify(Wallpaper wallpaper,String progressBase)
     {
-        progressBar.setMessage("Analysiere:" + currentFile + "/" + totalFiles);
+        progressBar.setMessage(progressBase+ currentFile + "/" + totalFiles);
         progressBar.tickOne();
         currentFile++;
-        File wallpaperfile = new File(wallpaper.getFilepath());
+        String wallpaperpath = wallpaper.getFilepath();
+        File wallpaperfile = new File(wallpaperpath);
+        if(wallpaperfile.isAbsolute())
+        {
+            String relativizedFilePath = FileTK.getRelativePath(wallpaper.getFilepath(), cachedir);
+            wallpaper.setFilepath(relativizedFilePath);
+        }
+        else
+        {
+            wallpaperfile = new File(cachedir+File.separator+wallpaperpath);
+        }
+         
         long wallpapersize = wallpaperfile.length();
+        
         if(wallpaper.isValid()
                 &&wallpaperfile.exists()
                 &&wallpapersize==wallpaper.getFilesize()
@@ -651,7 +685,7 @@ public class Synchronizer
 
             Tools.runCmdWithPassthru(ps, new String[]
             {
-                imagemagickPath+File.separator+"identify.exe", "-quiet", "-format", "%w %h", wallpaper.getFilepath()
+                imagemagickPath+File.separator+"identify.exe", "-quiet", "-format", "%w %h", cachedir+File.separator+wallpaper.getFilepath()
             });
             content = new String(baos.toByteArray(), StandardCharsets.UTF_8);
             l.trace(content);
@@ -711,7 +745,7 @@ public class Synchronizer
             {
                 String[] convertFiles =
                 {
-                    wallpaper.getFilepath(),"+write","mpr:wallpaper","+delete"
+                    cachedir+File.separator+wallpaper.getFilepath(),"+write","mpr:wallpaper","+delete"
                 };
                 convertCmd.addAll(Arrays.asList(convertFiles));
 
@@ -719,7 +753,7 @@ public class Synchronizer
                 {
                     String[] convertFallback =
                     {
-                        fallback.getFilepath(),"+write","mpr:fallback","+delete"
+                        cachedir+File.separator+fallback.getFilepath(),"+write","mpr:fallback","+delete"
                     };
                     convertCmd.addAll(Arrays.asList(convertFallback));
                 }
@@ -1187,6 +1221,36 @@ public class Synchronizer
         convertCmd.addAll(Arrays.asList(convertFiles));
     }
     
+    private void upgradeCacheState(CacheState state)
+    {
+        int cachestateversion = state.getVersion();
+        switch(cachestateversion)
+        {
+            default:
+                throw new CacheStateParsingException("Unknown CacheState version detected. Cannot continue");
+            case -1:
+            case 0:
+            case 1:
+                l.info("Fixing paths to be relative to the cachebase");
+                int oldtotalfiles = totalFiles;
+                totalFiles = 0;
+                for(String pid:state.getPackages().keySet())
+                {
+                    totalFiles+=state.getPackages().get(pid).getStretchablePics().size();
+                    totalFiles+=state.getPackages().get(pid).getFixedRatioPics().size();
+                    totalFiles+=state.getPackages().get(pid).getB_frames().size();
+                }
+                identifyAll(state,"Fixing paths");
+                state.setVersion(2);
+                state.setProcessedWallpapersMappings(new ArrayList<>()); //zapping a unused data structure
+                totalFiles = oldtotalfiles;
+                l.info("Upgrade to Version 2 successfull");
+            case 2:
+                l.info("Nothing to upgrade");
+        }
+    }
+    
+    
     
     
     private Synchronizer(){};