View Javadoc
1   /*
2    * Copyright 2018-2022 Medical Information Systems Research Group (https://medical.zcu.cz),
3    * Department of Computer Science and Engineering, University of West Bohemia.
4    * Address: Univerzitni 8, 306 14 Plzen, Czech Republic.
5    *
6    * Author Petr Vcelak (vcelak@kiv.zcu.cz).
7    *
8    * This file is part of MRECore project.
9    *
10   * MRECore is free software: you can redistribute it and/or modify
11   * it under the terms of the GNU General Public License as published by
12   * the Free Software Foundation, either version 3 of the License.
13   *
14   * MRECore is distributed in the hope that it will be useful,
15   * but WITHOUT ANY WARRANTY; without even the implied warranty of
16   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17   * GNU General Public License for more details.
18   *
19   * You should have received a copy of the GNU General Public License
20   * along with MRECore. If not, see <http://www.gnu.org/licenses/>.
21   */
22  package cz.zcu.mre.data.datatable;
23  
24  import com.google.gson.Gson;
25  import cz.zcu.mre.vocab.NS;
26  import cz.zcu.mre.vocab.Prefix;
27  import java.util.Collection;
28  import java.util.Iterator;
29  import java.util.List;
30  import java.util.Map;
31  import org.apache.jena.arq.querybuilder.ExprFactory;
32  import org.apache.jena.arq.querybuilder.Order;
33  import org.apache.jena.arq.querybuilder.SelectBuilder;
34  import org.apache.jena.sparql.expr.E_Function;
35  import org.apache.jena.sparql.lang.sparql_11.ParseException;
36  import org.apache.jena.vocabulary.XSD;
37  import org.slf4j.Logger;
38  import org.slf4j.LoggerFactory;
39  
40  /**
41   * @author Petr Vcelak (vcelak@kiv.zcu.cz)
42   *
43   */
44  public class DataTableUtils {
45  
46      private static final Logger LOG = LoggerFactory.getLogger(DataTableUtils.class);
47  
48      /**
49       * Checks if is collection empty.
50       *
51       * @param collection the collection
52       * @return true, if is collection empty
53       */
54      private static boolean isCollectionEmpty(Collection<?> collection) {
55          return collection == null || collection.isEmpty();
56      }
57  
58      /**
59       * Checks if is object empty.
60       *
61       * @param object the object
62       * @return true, if is object empty
63       */
64      public static boolean isObjectEmpty(Object object) {
65          if (object == null) {
66              return true;
67          } else if (object instanceof String) {
68              if (((String) object).trim().length() == 0) {
69                  return true;
70              }
71          } else if (object instanceof Collection) {
72              return isCollectionEmpty((Collection<?>) object);
73          }
74          return false;
75      }
76  
77      /**
78       * Gets the bean to json string.
79       *
80       * @param beanClass the bean class
81       * @return the bean to json string
82       */
83      public static String getBeanToJsonString(Object beanClass) {
84          return new Gson().toJson(beanClass);
85      }
86  
87      /**
88       * Gets the bean to json string.
89       *
90       * @param beanClasses the bean classes
91       * @return the bean to json string
92       */
93      public static String getBeanToJsonString(Object... beanClasses) {
94          StringBuilder stringBuilder = new StringBuilder();
95          for (Object beanClass : beanClasses) {
96              stringBuilder.append(getBeanToJsonString(beanClass));
97              stringBuilder.append(", ");
98          }
99          return stringBuilder.toString();
100     }
101 
102     /**
103      * Concatenate.
104      *
105      * @param listOfItems the list of items
106      * @param separator the separator
107      * @return the string
108      */
109     public String concatenate(List<String> listOfItems, String separator) {
110         StringBuilder sb = new StringBuilder();
111         Iterator<String> stit = listOfItems.iterator();
112 
113         while (stit.hasNext()) {
114             sb.append(stit.next());
115             if (stit.hasNext()) {
116                 sb.append(separator);
117             }
118         }
119 
120         return sb.toString();
121     }
122 
123     public static void appendQuerySort(SelectBuilder builder, DataTableQuerySortBy dtqsb) {
124 
125         Map<String, DataTableQuerySortOrder> sortby = dtqsb.getSortBys();
126         sortby.forEach((k, v) -> {
127 
128             Order order = v.value().equals("ASC") ? Order.ASCENDING : Order.DESCENDING;
129 
130             if (k.equals("id")) {
131                 builder.addPrefix(Prefix.XSD, NS.XSD);
132                 ExprFactory exprFact = builder.getExprFactory();
133                 E_Function func = exprFact.function(XSD.integer.toString(), exprFact.asList(exprFact.asVar(k)));
134                 builder.addOrderBy(func, order);
135 
136             } else {
137                 builder.addOrderBy(k, order);
138             }
139         });
140     }
141 
142     public static void appendQueryFilter(SelectBuilder builder, DataTableQueryFilterBy dtqfb) {
143 
144         Map<String, String> filterby = dtqfb.getMapOfFilters();
145 
146         if (filterby.isEmpty()) {
147             return;
148         }
149 
150         // build filter part
151         StringBuilder sb = new StringBuilder("(");
152         filterby.forEach((k, v) -> {
153 
154             // OR regexps
155             if (sb.length() > 1) {
156                 sb.append(" || ");
157             }
158 
159             String filter = "fn:matches(str(?" + k + "), \"" + v + "\", \"iq\")";
160 
161             LOG.debug("Filter by column={} and value={} in SPARQL: {}", k, v, filter);
162             sb.append(filter);
163         });
164         sb.append(")");
165 
166         LOG.debug("Query filter for SelectBuilder is {}", sb);
167 //        try {
168             // add required prefixes
169             builder.addPrefix(Prefix.FN, NS.FN);
170 
171             // add FILTER part to SelectBuilder
172             builder.addFilter(sb.toString());
173 //        } catch (ParseException ex) {
174 //            LOG.error("Exception when parsing FILTER part of SelectBuilder", ex);
175 //        }
176     }
177 }