001/**
002 * ////////////////////////////////////////////////////////////////////////////////
003 * //
004 * //  D SOFTWARE INCORPORATED
005 * //  Copyright 2007-2014 D Software Incorporated
006 * //  All Rights Reserved.
007 * //
008 * //  NOTICE: D Software permits you to use, modify, and distribute this file
009 * //  in accordance with the terms of the license agreement accompanying it.
010 * //
011 * //  Unless required by applicable law or agreed to in writing, software
012 * //  distributed under the License is distributed on an "AS IS" BASIS,
013 * //  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * //
015 * ////////////////////////////////////////////////////////////////////////////////
016 */
017package com.thed.util;
018
019import org.apache.commons.configuration.ConfigurationException;
020import org.apache.commons.configuration.PropertiesConfiguration;
021import org.apache.commons.configuration.reloading.ManagedReloadingStrategy;
022import org.apache.commons.lang.StringUtils;
023
024import java.io.File;
025import java.io.FileInputStream;
026import java.io.FileNotFoundException;
027import java.net.URI;
028import java.net.URISyntaxException;
029import java.text.ParseException;
030import java.text.SimpleDateFormat;
031import java.util.*;
032import java.util.logging.Logger;
033
034
035/**
036 * @serial exclude
037 * @author zephyrDev
038 */
039public class Utils {
040        private static Logger logger = Logger.getLogger(Utils.class.getName());
041        private static PropertiesConfiguration propsConfig;
042        private static ManagedReloadingStrategy reloadingStrategy;
043
044        public static final String ENC_PWD_KEY = "encPwd";
045        public static final String PASSWORD_KEY = "password";
046        public static final String USERNAME_KEY = "username";
047        public static final String URL_CONTEXT_FRAGMENT_KEY = "urlfragment";
048        public static final String DESKTOP_ALERT_ENABLED = "desktop.alert.enabled";
049    public static final String APITOKEN_KEY="apitoken";
050
051        static {
052                try {
053                        propsConfig = new PropertiesConfiguration(getZBotPropertiesFile());
054                        reloadingStrategy = new ManagedReloadingStrategy();
055                        propsConfig.setReloadingStrategy(reloadingStrategy);
056                } catch (ConfigurationException e) {
057                        logger.severe("Error in loading property configuration " +  e.getMessage());
058                        throw new RuntimeException("Error in Properties ");
059                } catch (URISyntaxException e) {
060                        logger.severe("Error in loading property configuration " +  e.getMessage());
061                        throw new RuntimeException("Error in Properties ");
062                }
063        }
064
065        public static PropertiesConfiguration getZbotProperties(){
066                return getZbotProperties(false);
067        }
068
069        public static PropertiesConfiguration getZbotProperties(Boolean reload){
070                if(reload){
071                        reloadingStrategy.refresh();
072                }
073                return propsConfig;
074        }
075
076        public static String getZBotPropertiesFile() throws URISyntaxException {
077                File parentFolder = Utils.getLoadedJarFile("messagehandlers.properties");
078                String zbot = "" + parentFolder.getParentFile()+ File.separator +"conf"+ File.separator + "zbot.properties";
079                System.out.println("Zbot.properties: " + zbot);
080                return zbot;
081        }
082        
083        public static String getLogPropertiesFile() throws URISyntaxException{
084                File parentFolder = Utils.getLoadedJarFile("messagehandlers.properties");
085                String log = "";
086                try {
087                        log = """
088                                        %s%sconf%szbot_logging.properties""".formatted(parentFolder.getParentFile(), File.separator, File.separator);
089                }catch (Exception e) {
090                        //not handling this exception for now as discussed with Pravin Bansal
091                }
092                System.out.println("logging.properties: " + log);
093                return log;
094        }
095        
096        public static File getLoadedJarFile(String resourceName) throws URISyntaxException {
097            System.out.println(ClassLoader.getSystemClassLoader());
098            System.out.println(ClassLoader.getSystemClassLoader().getResource(resourceName));
099            System.out.println(ClassLoader.getSystemClassLoader().getResource(resourceName).toString());
100            String pathStr = ClassLoader.getSystemClassLoader().getResource(resourceName).toString();
101
102                System.out.println("Path " + pathStr);
103                String infoFilePath = "";
104
105                if(pathStr.contains("!")) {
106                        infoFilePath = pathStr.substring(pathStr.indexOf("file:/") + 6,
107                                        pathStr.indexOf("!"));
108                } else {
109                        infoFilePath = pathStr.substring(pathStr.indexOf("file:/") + 6);
110                }
111
112                infoFilePath = new URI("file:///" + infoFilePath).getPath();
113                System.out.println("infoFilePath  " + infoFilePath);
114                File infoFile = new File(infoFilePath);
115                System.out.println("""
116                                infoFile  %s %s""".formatted(infoFile, infoFile.exists()));
117                System.out.println("""
118                                infoFile  %s %s""".formatted(infoFile.getParent(), infoFile.getParentFile().exists()));
119                if (infoFile != null && infoFile.exists()
120                                && infoFile.getParentFile() != null
121                                && infoFile.getParentFile().exists()) {
122                        return infoFile.getParentFile();
123                }
124                return null;
125        }
126
127        public static FileInputStream getFileAsStream(String resourceName) {
128                try {
129                        URI url = Utils.class.getResource("/" + resourceName).toURI();
130                        if (url != null) {
131                                File infoFile = new File(url.getPath());
132                                if (infoFile != null && infoFile.exists()) {
133                                        System.out.println(infoFile);
134                                        return new FileInputStream(infoFile);
135                                }
136                        }
137                } catch (FileNotFoundException e) {
138                        e.printStackTrace();
139                } catch (URISyntaxException e) {
140                        e.printStackTrace();
141                }
142                return null;
143        }
144
145        /**
146         *
147         * <b>Description</b>: Returns last modified time of given file.
148         * @param filename
149         * @return
150         */
151        public static long lastModifiedTimeOfMonitorFile(String filename) {
152                File f = new File(filename);
153                return f.lastModified();
154        }
155
156        /**
157         * checks if all the chars are *
158         * @param password
159         * @return
160         */
161        public static boolean isEncrypted(String password) {
162                String nullPwd = StringUtils.leftPad("", password.length(), '*');
163                return StringUtils.equals(password, nullPwd);
164        }
165        
166        
167         public static final String convertStringToDate(String aMask, Date date2)
168                      throws ParseException {
169                        SimpleDateFormat df = null;
170                        String date = null;
171                        df = new SimpleDateFormat(aMask);
172                        date = df.format(date2);
173                        return (date);
174        }
175
176        public static Set<String> getSet(String value, String splitStr) {
177                if(value == null || splitStr == null) {
178                        return new HashSet<>();
179                }
180                return new HashSet<>(Arrays.asList(value.split(splitStr)));
181        }
182
183        public static <T> List<List<T>> partition(List<T> list, int size) {
184                List<List<T>> resultList = new ArrayList<>();
185                for (int page = 0; page * size < list.size(); page++) {
186                        if((page+1)*size > list.size()) {
187                                //this is last iteration of page, sublist till end of list
188                                resultList.add(list.subList(page * size, list.size()));
189                        } else {
190                                resultList.add(list.subList(page * size, (page + 1) * size));
191                        }
192                }
193                return resultList;
194        }
195
196}