1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * This library is free software; you can redistribute it and/or modify it under
5    * the terms of the GNU Lesser General Public License as published by the Free
6    * Software Foundation; either version 2.1 of the License, or (at your option)
7    * any later version.
8    *
9    * This library is distributed in the hope that it will be useful, but WITHOUT
10   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11   * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
12   * details.
13   */
14  
15  package com.liferay.portlet.webform.util;
16  
17  import com.liferay.counter.service.CounterLocalServiceUtil;
18  import com.liferay.mozilla.javascript.Context;
19  import com.liferay.mozilla.javascript.Scriptable;
20  import com.liferay.mozilla.javascript.ScriptableObject;
21  import com.liferay.portal.PortalException;
22  import com.liferay.portal.SystemException;
23  import com.liferay.portal.kernel.io.unsync.UnsyncBufferedReader;
24  import com.liferay.portal.kernel.io.unsync.UnsyncStringReader;
25  import com.liferay.portal.kernel.log.Log;
26  import com.liferay.portal.kernel.log.LogFactoryUtil;
27  import com.liferay.portal.kernel.util.StringPool;
28  import com.liferay.portal.kernel.util.Validator;
29  import com.liferay.portlet.expando.NoSuchTableException;
30  import com.liferay.portlet.expando.model.ExpandoColumnConstants;
31  import com.liferay.portlet.expando.model.ExpandoTable;
32  import com.liferay.portlet.expando.service.ExpandoColumnLocalServiceUtil;
33  import com.liferay.portlet.expando.service.ExpandoRowLocalServiceUtil;
34  import com.liferay.portlet.expando.service.ExpandoTableLocalServiceUtil;
35  
36  import java.io.IOException;
37  
38  import java.util.ArrayList;
39  import java.util.List;
40  import java.util.Map;
41  
42  import javax.portlet.PortletPreferences;
43  
44  /**
45   * <a href="WebFormUtil.java.html"><b><i>View Source</i></b></a>
46   *
47   * @author Daniel Weisser
48   * @author Jorge Ferrer
49   * @author Alberto Montero
50   * @author Julio Camarero
51   */
52  public class WebFormUtil {
53  
54      public static ExpandoTable addTable(String tableName)
55          throws PortalException, SystemException {
56  
57          try {
58              ExpandoTableLocalServiceUtil.deleteTable(
59                  WebFormUtil.class.getName(), tableName);
60          }
61          catch (NoSuchTableException nste) {
62          }
63  
64          return ExpandoTableLocalServiceUtil.addTable(
65              WebFormUtil.class.getName(), tableName);
66      }
67  
68      public static ExpandoTable checkTable(
69              String tableName, PortletPreferences preferences)
70          throws Exception {
71  
72          ExpandoTable expandoTable = null;
73  
74          try {
75              expandoTable = ExpandoTableLocalServiceUtil.getTable(
76                  WebFormUtil.class.getName(), tableName);
77          }
78          catch (NoSuchTableException nste) {
79              expandoTable = addTable(tableName);
80  
81              int i = 1;
82  
83              String fieldLabel = preferences.getValue(
84                  "fieldLabel" + i, StringPool.BLANK);
85  
86              while ((i == 1) || (Validator.isNotNull(fieldLabel))) {
87                  ExpandoColumnLocalServiceUtil.addColumn(
88                      expandoTable.getTableId(), fieldLabel,
89                      ExpandoColumnConstants.STRING);
90  
91                  i++;
92  
93                  fieldLabel = preferences.getValue(
94                      "fieldLabel" + i, StringPool.BLANK);
95              }
96          }
97  
98          return expandoTable;
99      }
100 
101     public static String getNewDatabaseTableName(String portletId)
102         throws SystemException {
103 
104         long formId = CounterLocalServiceUtil.increment(
105             WebFormUtil.class.getName());
106 
107         return portletId + StringPool.UNDERLINE + formId;
108     }
109 
110     public static int getTableRowsCount(String tableName)
111         throws SystemException {
112 
113         return ExpandoRowLocalServiceUtil.getRowsCount(
114             WebFormUtil.class.getName(), tableName);
115     }
116 
117     public static String[] split(String s) {
118         return split(s, StringPool.COMMA);
119     }
120 
121     public static String[] split(String s, String delimiter) {
122         if (s == null || delimiter == null) {
123             return new String[0];
124         }
125 
126         s = s.trim();
127 
128         if (!s.endsWith(delimiter)) {
129             StringBuilder sb = new StringBuilder();
130 
131             sb.append(s);
132             sb.append(delimiter);
133 
134             s = sb.toString();
135         }
136 
137         if (s.equals(delimiter)) {
138             return new String[0];
139         }
140 
141         List<String> nodeValues = new ArrayList<String>();
142 
143         if (delimiter.equals("\n") || delimiter.equals("\r")) {
144             try {
145                 UnsyncBufferedReader unsyncBufferedReader =
146                     new UnsyncBufferedReader(new UnsyncStringReader(s));
147 
148                 String line = null;
149 
150                 while ((line = unsyncBufferedReader.readLine()) != null) {
151                     nodeValues.add(line);
152                 }
153 
154                 unsyncBufferedReader.close();
155             }
156             catch (IOException ioe) {
157                 ioe.printStackTrace();
158             }
159         }
160         else {
161             int offset = 0;
162             int pos = s.indexOf(delimiter, offset);
163 
164             while (pos != -1) {
165                 nodeValues.add(new String(s.substring(offset, pos)));
166 
167                 offset = pos + delimiter.length();
168                 pos = s.indexOf(delimiter, offset);
169             }
170         }
171 
172         return nodeValues.toArray(new String[nodeValues.size()]);
173     }
174 
175     public static boolean validate(
176             String currentFieldValue, Map<String,String> fieldsMap,
177             String validationScript)
178         throws Exception {
179 
180         boolean validationResult = false;
181 
182         Context context = Context.enter();
183 
184         StringBuilder sb = new StringBuilder();
185 
186         sb.append("currentFieldValue = String('" + currentFieldValue + "');\n");
187 
188         sb.append("var fieldsMap = {};\n");
189 
190         for (String key : fieldsMap.keySet()) {
191             sb.append("fieldsMap['");
192             sb.append(key);
193             sb.append("'] = '");
194             sb.append(fieldsMap.get(key));
195             sb.append("';\n");
196         }
197 
198         sb.append("function validation(currentFieldValue, fieldsMap) {\n");
199         sb.append(validationScript);
200         sb.append("};\n");
201         sb.append("internalValidationResult = ");
202         sb.append("validation(currentFieldValue, fieldsMap);");
203 
204         String script = sb.toString();
205 
206         try {
207             Scriptable scope = context.initStandardObjects();
208 
209             Object jsFieldsMap = Context.javaToJS(fieldsMap, scope);
210 
211             ScriptableObject.putProperty(scope, "jsFieldsMap", jsFieldsMap);
212 
213             context.evaluateString(scope, script, "Validation Script", 1, null);
214 
215             Object obj = ScriptableObject.getProperty(
216                 scope, "internalValidationResult");
217 
218             if (obj instanceof Boolean) {
219                 validationResult = ((Boolean)obj).booleanValue();
220             }
221             else {
222                 throw new Exception("The script must return a boolean value");
223             }
224         }
225         catch (Exception e) {
226             String msg =
227                 "The following script has execution errors:\n" +
228                     validationScript + "\n" + e.getMessage();
229 
230             _log.error(msg);
231 
232             throw new Exception(msg, e);
233         }
234         finally {
235             Context.exit();
236         }
237 
238         return validationResult;
239     }
240 
241     private static Log _log = LogFactoryUtil.getLog(WebFormUtil.class);
242 
243 }