001package de.deepamehta.core.util;
002
003import de.deepamehta.core.DeepaMehtaObject;
004import de.deepamehta.core.Identifiable;
005import de.deepamehta.core.JSONEnabled;
006import de.deepamehta.core.Topic;
007import de.deepamehta.core.model.AssociationModel;
008import de.deepamehta.core.model.RoleModel;
009import de.deepamehta.core.model.TopicModel;
010import de.deepamehta.core.service.CoreService;
011
012import org.codehaus.jettison.json.JSONArray;
013import org.codehaus.jettison.json.JSONObject;
014
015import java.net.URL;
016import java.util.ArrayList;
017import java.util.Collection;
018import java.util.HashMap;
019import java.util.Iterator;
020import java.util.List;
021import java.util.Map;
022import java.util.logging.Logger;
023
024
025
026public class DeepaMehtaUtils {
027
028    private static final Logger logger = Logger.getLogger(DeepaMehtaUtils.class.getName());
029
030    private static final String DM4_HOST_URL = System.getProperty("dm4.host.url");  // ### TODO: default value (#734)
031    static {
032        logger.info("Host setting:\ndm4.host.url=\"" + DM4_HOST_URL + "\"");
033    }
034
035
036
037    // ************
038    // *** URLs ***
039    // ************
040
041
042
043    /**
044     * Checks if an URL refers to this DeepaMehta installation.
045     * The check relies on the "dm4.host.url" system property.
046     */
047    public static boolean isDeepaMehtaURL(URL url) {
048        try {
049            return url.toString().startsWith(DM4_HOST_URL);
050        } catch (Exception e) {
051            throw new RuntimeException("Checking for DeepaMehta URL failed (url=\"" + url + "\")", e);
052        }
053    }
054
055
056
057    // *******************
058    // *** Collections ***
059    // *******************
060
061
062
063    public static List<Long> idList(Iterable<? extends Identifiable> items) {
064        List<Long> ids = new ArrayList();
065        for (Identifiable item : items) {
066            ids.add(item.getId());
067        }
068        return ids;
069    }
070
071    public static List<TopicModel> toTopicModels(Iterable<? extends Topic> topics) {
072        List<TopicModel> topicModels = new ArrayList();
073        for (Topic topic : topics) {
074            topicModels.add(topic.getModel());
075        }
076        return topicModels;
077    }
078
079    public static String topicNames(Iterable<? extends Topic> topics) {
080        StringBuilder names = new StringBuilder();
081        Iterator<? extends Topic> i = topics.iterator();
082        while (i.hasNext()) {
083            Topic topic = i.next();
084            names.append('"').append(topic.getSimpleValue()).append('"');
085            if (i.hasNext()) {
086                names.append(", ");
087            }
088        }
089        return names.toString();
090    }
091
092    public static <T extends DeepaMehtaObject> List<T> loadChildTopics(List<T> objects) {
093        for (DeepaMehtaObject object : objects) {
094            object.loadChildTopics();
095        }
096        return objects;
097    }
098
099
100
101    // ************
102    // *** JSON ***
103    // ************
104
105
106
107    // === Generic ===
108
109    public static Map toMap(JSONObject o) {
110        return toMap(o, new HashMap());
111    }
112
113    public static Map toMap(JSONObject o, Map map) {
114        try {
115            Iterator<String> i = o.keys();
116            while (i.hasNext()) {
117                String key = i.next();
118                map.put(key, o.get(key));   // throws JSONException
119            }
120            return map;
121        } catch (Exception e) {
122            throw new RuntimeException("Converting JSONObject to Map failed", e);
123        }
124    }
125
126    // ---
127
128    public static List toList(JSONArray o) {
129        try {
130            List list = new ArrayList();
131            for (int i = 0; i < o.length(); i++) {
132                list.add(o.get(i));         // throws JSONException
133            }
134            return list;
135        } catch (Exception e) {
136            throw new RuntimeException("Converting JSONArray to List failed", e);
137        }
138    }
139
140    // === DeepaMehta specific ===
141
142    public static JSONArray toJSONArray(Iterable<? extends JSONEnabled> items) {
143        JSONArray array = new JSONArray();
144        for (JSONEnabled item : items) {
145            array.put(item.toJSON());
146        }
147        return array;
148    }
149
150
151
152    // *******************************
153    // *** Association Auto-Typing ***
154    // *******************************
155
156
157
158    public static RoleModel[] associationAutoTyping(AssociationModel assoc, String topicTypeUri1, String topicTypeUri2,
159                                       String assocTypeUri, String roleTypeUri1, String roleTypeUri2, CoreService dm4) {
160        if (!assoc.getTypeUri().equals("dm4.core.association")) {
161            return null;
162        }
163        RoleModel[] roles = getRoleModels(assoc, topicTypeUri1, topicTypeUri2, dm4);
164        if (roles != null) {
165            logger.info("### Auto typing association into \"" + assocTypeUri +
166                "\" (\"" + topicTypeUri1 + "\" <-> \"" + topicTypeUri2 + "\")");
167            assoc.setTypeUri(assocTypeUri);
168            roles[0].setRoleTypeUri(roleTypeUri1);
169            roles[1].setRoleTypeUri(roleTypeUri2);
170        }
171        return roles;
172    }
173
174    public static RoleModel[] getRoleModels(AssociationModel assoc, String topicTypeUri1, String topicTypeUri2,
175                                                                                          CoreService dm4) {
176        RoleModel r1 = assoc.getRoleModel1();
177        RoleModel r2 = assoc.getRoleModel2();
178        String t1 = (String) dm4.getProperty(r1.getPlayerId(), "type_uri");
179        String t2 = (String) dm4.getProperty(r2.getPlayerId(), "type_uri");
180        RoleModel roleModel1 = getRoleModel(r1, r2, t1, t2, topicTypeUri1, 1);
181        RoleModel roleModel2 = getRoleModel(r1, r2, t1, t2, topicTypeUri2, 2);
182        if (roleModel1 != null && roleModel2 != null) {
183            return new RoleModel[] {roleModel1, roleModel2};
184        }
185        return null;
186    }
187
188    // ------------------------------------------------------------------------------------------------- Private Methods
189
190    private static RoleModel getRoleModel(RoleModel r1, RoleModel r2, String t1, String t2, String topicTypeUri,
191                                                                                            int nr) {
192        boolean m1 = t1.equals(topicTypeUri);
193        boolean m2 = t2.equals(topicTypeUri);
194        if (m1 && m2) {
195            return nr == 1 ? r1 : r2;
196        }
197        return m1 ? r1 : m2 ? r2 : null;
198    }
199}