001    package de.deepamehta.core.util;
002    
003    import de.deepamehta.core.Identifiable;
004    import de.deepamehta.core.JSONEnabled;
005    import de.deepamehta.core.RelatedTopic;
006    import de.deepamehta.core.Topic;
007    import de.deepamehta.core.model.AssociationModel;
008    import de.deepamehta.core.model.AssociationTypeModel;
009    import de.deepamehta.core.model.TopicModel;
010    import de.deepamehta.core.model.TopicTypeModel;
011    import de.deepamehta.core.service.DeepaMehtaService;
012    
013    import org.codehaus.jettison.json.JSONArray;
014    import org.codehaus.jettison.json.JSONObject;
015    
016    import java.io.InputStream;
017    import java.net.InetAddress;
018    import java.net.URL;
019    import java.util.ArrayList;
020    import java.util.Collection;
021    import java.util.HashMap;
022    import java.util.Iterator;
023    import java.util.List;
024    import java.util.Map;
025    import java.util.logging.Logger;
026    
027    
028    
029    public class DeepaMehtaUtils {
030    
031        private static Logger logger = Logger.getLogger("de.deepamehta.core.util.DeepaMehtaUtils");
032    
033        private static final String DM4_HOST_URL = System.getProperty("dm4.host.url");
034        static {
035            logger.info("Host setting:\n    dm4.host.url=\""+ DM4_HOST_URL + "\"");
036        }
037    
038    
039    
040        // ************
041        // *** URLs ***
042        // ************
043    
044    
045    
046        /**
047         * Checks if an URL refers to this DeepaMehta installation.
048         * The check relies on the "dm4.host.url" system property.
049         */
050        public static boolean isDeepaMehtaURL(URL url) {
051            try {
052                return url.toString().startsWith(DM4_HOST_URL);
053            } catch (Exception e) {
054                throw new RuntimeException("Checking for DeepaMehta URL failed (url=\"" + url + "\")", e);
055            }
056        }
057    
058    
059    
060        // *******************
061        // *** Collections ***
062        // *******************
063    
064    
065    
066        public static List<Long> idList(Collection objects) {
067            List<Long> ids = new ArrayList();
068            for (Object object : objects) {
069                ids.add(((Identifiable) object).getId());
070            }
071            return ids;
072        }
073    
074        public static List<TopicModel> toTopicModels(List<RelatedTopic> relTopics) {
075            List<TopicModel> topicModels = new ArrayList();
076            for (Topic topic : relTopics) {
077                topicModels.add(topic.getModel());
078            }
079            return topicModels;
080        }
081    
082        public static String topicNames(Collection<? extends Topic> topics) {
083            StringBuilder names = new StringBuilder();
084            Iterator<? extends Topic> i = topics.iterator();
085            while (i.hasNext()) {
086                Topic topic = i.next();
087                names.append('"').append(topic.getSimpleValue()).append('"');
088                if (i.hasNext()) {
089                    names.append(", ");
090                }
091            }
092            return names.toString();
093        }
094    
095    
096    
097        // ************
098        // *** JSON ***
099        // ************
100    
101    
102    
103        // === Generic ===
104    
105        public static Map toMap(JSONObject o) {
106            return toMap(o, new HashMap());
107        }
108    
109        public static Map toMap(JSONObject o, Map map) {
110            try {
111                Iterator<String> i = o.keys();
112                while (i.hasNext()) {
113                    String key = i.next();
114                    map.put(key, o.get(key));   // throws JSONException
115                }
116                return map;
117            } catch (Exception e) {
118                throw new RuntimeException("Converting JSONObject to Map failed", e);
119            }
120        }
121    
122        // ---
123    
124        public static List toList(JSONArray o) {
125            try {
126                List list = new ArrayList();
127                for (int i = 0; i < o.length(); i++) {
128                    list.add(o.get(i));         // throws JSONException
129                }
130                return list;
131            } catch (Exception e) {
132                throw new RuntimeException("Converting JSONArray to List failed", e);
133            }
134        }
135    
136        // ---
137    
138        public static JSONArray stringsToJson(Collection<String> strings) {
139            JSONArray array = new JSONArray();
140            for (String string : strings) {
141                array.put(string);
142            }
143            return array;
144        }
145    
146        // === DeepaMehta specific ===
147    
148        public static JSONArray objectsToJSON(Collection<? extends JSONEnabled> objects) {
149            JSONArray array = new JSONArray();
150            for (JSONEnabled object : objects) {
151                array.put(object.toJSON());
152            }
153            return array;
154        }
155    
156        // ---
157    
158        /**
159         * Creates types and topics from a JSON formatted input stream.
160         *
161         * @param   migrationFileName   The origin migration file. Used for logging only.
162         */
163        public static void readMigrationFile(InputStream is, String migrationFileName, DeepaMehtaService dms) {
164            try {
165                logger.info("Reading migration file \"" + migrationFileName + "\"");
166                String fileContent = JavaUtils.readText(is);
167                //
168                JSONObject o = new JSONObject(fileContent);
169                JSONArray topicTypes = o.optJSONArray("topic_types");
170                if (topicTypes != null) {
171                    createTopicTypes(topicTypes, dms);
172                }
173                JSONArray assocTypes = o.optJSONArray("assoc_types");
174                if (assocTypes != null) {
175                    createAssociationTypes(assocTypes, dms);
176                }
177                JSONArray topics = o.optJSONArray("topics");
178                if (topics != null) {
179                    createTopics(topics, dms);
180                }
181                JSONArray assocs = o.optJSONArray("associations");
182                if (assocs != null) {
183                    createAssociations(assocs, dms);
184                }
185            } catch (Exception e) {
186                throw new RuntimeException("Reading migration file \"" + migrationFileName + "\" failed", e);
187            }
188        }
189    
190        public static void createTopicTypes(JSONArray topicTypes, DeepaMehtaService dms) throws Exception {
191            for (int i = 0; i < topicTypes.length(); i++) {
192                TopicTypeModel topicTypeModel = new TopicTypeModel(topicTypes.getJSONObject(i));
193                dms.createTopicType(topicTypeModel, null);          // clientState=null
194            }
195        }
196    
197        public static void createAssociationTypes(JSONArray assocTypes, DeepaMehtaService dms) throws Exception {
198            for (int i = 0; i < assocTypes.length(); i++) {
199                AssociationTypeModel assocTypeModel = new AssociationTypeModel(assocTypes.getJSONObject(i));
200                dms.createAssociationType(assocTypeModel, null);    // clientState=null
201            }
202        }
203    
204        public static void createTopics(JSONArray topics, DeepaMehtaService dms) throws Exception {
205            for (int i = 0; i < topics.length(); i++) {
206                TopicModel topicModel = new TopicModel(topics.getJSONObject(i));
207                dms.createTopic(topicModel, null);                  // clientState=null
208            }
209        }
210    
211        public static void createAssociations(JSONArray assocs, DeepaMehtaService dms) throws Exception {
212            for (int i = 0; i < assocs.length(); i++) {
213                AssociationModel assocModel = new AssociationModel(assocs.getJSONObject(i));
214                dms.createAssociation(assocModel, null);            // clientState=null
215            }
216        }
217    }