1   /**
2    * Copyright (c) 2000-2009 Liferay, Inc. All rights reserved.
3    *
4    * Permission is hereby granted, free of charge, to any person obtaining a copy
5    * of this software and associated documentation files (the "Software"), to deal
6    * in the Software without restriction, including without limitation the rights
7    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8    * copies of the Software, and to permit persons to whom the Software is
9    * furnished to do so, subject to the following conditions:
10   *
11   * The above copyright notice and this permission notice shall be included in
12   * all copies or substantial portions of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
22  
23  package com.liferay.portlet.webform.util;
24  
25  import com.liferay.counter.service.CounterLocalServiceUtil;
26  import com.liferay.mozilla.javascript.Context;
27  import com.liferay.mozilla.javascript.Scriptable;
28  import com.liferay.mozilla.javascript.ScriptableObject;
29  import com.liferay.portal.PortalException;
30  import com.liferay.portal.SystemException;
31  import com.liferay.portal.kernel.log.Log;
32  import com.liferay.portal.kernel.log.LogFactoryUtil;
33  import com.liferay.portal.kernel.util.StringPool;
34  import com.liferay.portal.kernel.util.Validator;
35  import com.liferay.portlet.expando.NoSuchTableException;
36  import com.liferay.portlet.expando.model.ExpandoColumnConstants;
37  import com.liferay.portlet.expando.model.ExpandoTable;
38  import com.liferay.portlet.expando.service.ExpandoColumnLocalServiceUtil;
39  import com.liferay.portlet.expando.service.ExpandoRowLocalServiceUtil;
40  import com.liferay.portlet.expando.service.ExpandoTableLocalServiceUtil;
41  
42  import java.io.BufferedReader;
43  import java.io.IOException;
44  import java.io.StringReader;
45  
46  import java.util.ArrayList;
47  import java.util.List;
48  import java.util.Map;
49  
50  import javax.portlet.PortletPreferences;
51  
52  /**
53   * <a href="WebFormUtil.java.html"><b><i>View Source</i></b></a>
54   *
55   * @author Daniel Weisser
56   * @author Jorge Ferrer
57   * @author Alberto Montero
58   * @author Julio Camarero
59   */
60  public class WebFormUtil {
61  
62      public static ExpandoTable addTable(String tableName)
63          throws PortalException, SystemException {
64  
65          try {
66              ExpandoTableLocalServiceUtil.deleteTable(
67                  WebFormUtil.class.getName(), tableName);
68          }
69          catch (NoSuchTableException nste) {
70          }
71  
72          return ExpandoTableLocalServiceUtil.addTable(
73              WebFormUtil.class.getName(), tableName);
74      }
75  
76      public static ExpandoTable checkTable(
77              String tableName, PortletPreferences preferences)
78          throws Exception {
79  
80          ExpandoTable expandoTable = null;
81  
82          try {
83              expandoTable = ExpandoTableLocalServiceUtil.getTable(
84                  WebFormUtil.class.getName(), tableName);
85          }
86          catch (NoSuchTableException nste) {
87              expandoTable = addTable(tableName);
88  
89              int i = 1;
90  
91              String fieldLabel = preferences.getValue(
92                  "fieldLabel" + i, StringPool.BLANK);
93  
94              while ((i == 1) || (Validator.isNotNull(fieldLabel))) {
95                  ExpandoColumnLocalServiceUtil.addColumn(
96                      expandoTable.getTableId(), fieldLabel,
97                      ExpandoColumnConstants.STRING);
98  
99                  i++;
100 
101                 fieldLabel = preferences.getValue(
102                     "fieldLabel" + i, StringPool.BLANK);
103             }
104         }
105 
106         return expandoTable;
107     }
108 
109     public static String getNewDatabaseTableName(String portletId)
110         throws SystemException {
111 
112         long formId = CounterLocalServiceUtil.increment(
113             WebFormUtil.class.getName());
114 
115         return portletId + StringPool.UNDERLINE + formId;
116     }
117 
118     public static int getTableRowsCount(String tableName)
119         throws SystemException {
120 
121         return ExpandoRowLocalServiceUtil.getRowsCount(
122             WebFormUtil.class.getName(), tableName);
123     }
124 
125     public static String[] split(String s) {
126         return split(s, StringPool.COMMA);
127     }
128 
129     public static String[] split(String s, String delimiter) {
130         if (s == null || delimiter == null) {
131             return new String[0];
132         }
133 
134         s = s.trim();
135 
136         if (!s.endsWith(delimiter)) {
137             StringBuilder sb = new StringBuilder();
138 
139             sb.append(s);
140             sb.append(delimiter);
141 
142             s = sb.toString();
143         }
144 
145         if (s.equals(delimiter)) {
146             return new String[0];
147         }
148 
149         List<String> nodeValues = new ArrayList<String>();
150 
151         if (delimiter.equals("\n") || delimiter.equals("\r")) {
152             try {
153                 BufferedReader br = new BufferedReader(new StringReader(s));
154 
155                 String line = null;
156 
157                 while ((line = br.readLine()) != null) {
158                     nodeValues.add(line);
159                 }
160 
161                 br.close();
162             }
163             catch (IOException ioe) {
164                 ioe.printStackTrace();
165             }
166         }
167         else {
168             int offset = 0;
169             int pos = s.indexOf(delimiter, offset);
170 
171             while (pos != -1) {
172                 nodeValues.add(new String(s.substring(offset, pos)));
173 
174                 offset = pos + delimiter.length();
175                 pos = s.indexOf(delimiter, offset);
176             }
177         }
178 
179         return nodeValues.toArray(new String[nodeValues.size()]);
180     }
181 
182     public static boolean validate(
183             String currentFieldValue, Map<String,String> fieldsMap,
184             String validationScript)
185         throws Exception {
186 
187         boolean validationResult = false;
188 
189         Context context = Context.enter();
190 
191         StringBuilder sb = new StringBuilder();
192 
193         sb.append("currentFieldValue = String('" + currentFieldValue + "');\n");
194 
195         sb.append("var fieldsMap = {};\n");
196 
197         for (String key : fieldsMap.keySet()) {
198             sb.append("fieldsMap['");
199             sb.append(key);
200             sb.append("'] = '");
201             sb.append(fieldsMap.get(key));
202             sb.append("';\n");
203         }
204 
205         sb.append("function validation(currentFieldValue, fieldsMap) {\n");
206         sb.append(validationScript);
207         sb.append("};\n");
208         sb.append("internalValidationResult = ");
209         sb.append("validation(currentFieldValue, fieldsMap);");
210 
211         String script = sb.toString();
212 
213         try {
214             Scriptable scope = context.initStandardObjects();
215 
216             Object jsFieldsMap = Context.javaToJS(fieldsMap, scope);
217 
218             ScriptableObject.putProperty(scope, "jsFieldsMap", jsFieldsMap);
219 
220             context.evaluateString(scope, script, "Validation Script", 1, null);
221 
222             Object obj = ScriptableObject.getProperty(
223                 scope, "internalValidationResult");
224 
225             if (obj instanceof Boolean) {
226                 validationResult = ((Boolean)obj).booleanValue();
227             }
228             else {
229                 throw new Exception("The script must return a boolean value");
230             }
231         }
232         catch (Exception e) {
233             String msg =
234                 "The following script has execution errors:\n" +
235                     validationScript + "\n" + e.getMessage();
236 
237             _log.error(msg);
238 
239             throw new Exception(msg, e);
240         }
241         finally {
242             Context.exit();
243         }
244 
245         return validationResult;
246     }
247 
248     private static Log _log = LogFactoryUtil.getLog(WebFormUtil.class);
249 
250 }