1   /**
2    * Copyright (c) 2000-2008 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.portal.PortalException;
27  import com.liferay.portal.SystemException;
28  import com.liferay.portal.kernel.util.StringPool;
29  import com.liferay.portal.kernel.util.Validator;
30  import com.liferay.portlet.expando.NoSuchTableException;
31  import com.liferay.portlet.expando.model.ExpandoColumnConstants;
32  import com.liferay.portlet.expando.model.ExpandoTable;
33  import com.liferay.portlet.expando.service.ExpandoColumnLocalServiceUtil;
34  import com.liferay.portlet.expando.service.ExpandoRowLocalServiceUtil;
35  import com.liferay.portlet.expando.service.ExpandoTableLocalServiceUtil;
36  
37  import java.io.BufferedReader;
38  import java.io.IOException;
39  import java.io.StringReader;
40  
41  import java.util.ArrayList;
42  import java.util.List;
43  import java.util.Map;
44  
45  import javax.portlet.PortletPreferences;
46  
47  import org.apache.commons.logging.Log;
48  import org.apache.commons.logging.LogFactory;
49  
50  import org.mozilla.javascript.Context;
51  import org.mozilla.javascript.Scriptable;
52  import org.mozilla.javascript.ScriptableObject;
53  
54  /**
55   * <a href="WebFormUtil.java.html"><b><i>View Source</i></b></a>
56   *
57   * @author Daniel Weisser
58   * @author Jorge Ferrer
59   * @author Alberto Montero
60   * @author Julio Camarero
61   *
62   */
63  public class WebFormUtil {
64  
65      public static ExpandoTable addTable(String tableName)
66          throws PortalException, SystemException {
67  
68          try {
69              ExpandoTableLocalServiceUtil.deleteTable(
70                  WebFormUtil.class.getName(), tableName);
71          }
72          catch (NoSuchTableException nste) {
73          }
74  
75          return ExpandoTableLocalServiceUtil.addTable(
76              WebFormUtil.class.getName(), tableName);
77      }
78  
79      public static ExpandoTable checkTable(
80              String tableName, PortletPreferences preferences)
81          throws Exception {
82  
83          ExpandoTable expandoTable = null;
84  
85          try {
86              expandoTable = ExpandoTableLocalServiceUtil.getTable(
87                  WebFormUtil.class.getName(), tableName);
88          }
89          catch (NoSuchTableException nste) {
90              expandoTable = addTable(tableName);
91  
92              int i = 1;
93  
94              String fieldLabel = preferences.getValue(
95                  "fieldLabel" + i, StringPool.BLANK);
96  
97              while ((i == 1) || (Validator.isNotNull(fieldLabel))) {
98                  ExpandoColumnLocalServiceUtil.addColumn(
99                      expandoTable.getTableId(), fieldLabel,
100                     ExpandoColumnConstants.STRING);
101 
102                 i++;
103 
104                 fieldLabel = preferences.getValue(
105                     "fieldLabel" + i, StringPool.BLANK);
106             }
107         }
108 
109         return expandoTable;
110     }
111 
112     public static String getNewDatabaseTableName(String portletId)
113         throws SystemException {
114 
115         long formId = CounterLocalServiceUtil.increment(
116             WebFormUtil.class.getName());
117 
118         return portletId + StringPool.UNDERLINE + formId;
119     }
120 
121     public static int getTableRowsCount(String tableName)
122         throws SystemException {
123 
124         return ExpandoRowLocalServiceUtil.getRowsCount(
125             WebFormUtil.class.getName(), tableName);
126     }
127 
128     public static String[] split(String s) {
129         return split(s, StringPool.COMMA);
130     }
131 
132     public static String[] split(String s, String delimiter) {
133         if (s == null || delimiter == null) {
134             return new String[0];
135         }
136 
137         s = s.trim();
138 
139         if (!s.endsWith(delimiter)) {
140             StringBuilder sb = new StringBuilder();
141 
142             sb.append(s);
143             sb.append(delimiter);
144 
145             s = sb.toString();
146         }
147 
148         if (s.equals(delimiter)) {
149             return new String[0];
150         }
151 
152         List<String> nodeValues = new ArrayList<String>();
153 
154         if (delimiter.equals("\n") || delimiter.equals("\r")) {
155             try {
156                 BufferedReader br = new BufferedReader(new StringReader(s));
157 
158                 String line = null;
159 
160                 while ((line = br.readLine()) != null) {
161                     nodeValues.add(line);
162                 }
163 
164                 br.close();
165             }
166             catch (IOException ioe) {
167                 ioe.printStackTrace();
168             }
169         }
170         else {
171             int offset = 0;
172             int pos = s.indexOf(delimiter, offset);
173 
174             while (pos != -1) {
175                 nodeValues.add(new String(s.substring(offset, pos)));
176 
177                 offset = pos + delimiter.length();
178                 pos = s.indexOf(delimiter, offset);
179             }
180         }
181 
182         return nodeValues.toArray(new String[nodeValues.size()]);
183     }
184 
185     public static boolean validate(
186             String currentFieldValue, Map<String,String> fieldsMap,
187             String validationScript)
188         throws Exception {
189 
190         boolean validationResult = false;
191 
192         Context context = Context.enter();
193 
194         StringBuilder sb = new StringBuilder();
195 
196         sb.append("currentFieldValue = String('" + currentFieldValue + "');\n");
197 
198         sb.append("var fieldsMap = {};\n");
199 
200         for (String key : fieldsMap.keySet()) {
201             sb.append("fieldsMap['");
202             sb.append(key);
203             sb.append("'] = '");
204             sb.append(fieldsMap.get(key));
205             sb.append("';\n");
206         }
207 
208         sb.append("function validation(currentFieldValue, fieldsMap) {\n");
209         sb.append(validationScript);
210         sb.append("};\n");
211         sb.append("internalValidationResult = ");
212         sb.append("validation(currentFieldValue, fieldsMap);");
213 
214         String script = sb.toString();
215 
216         try {
217             Scriptable scope = context.initStandardObjects();
218 
219             Object jsFieldsMap = Context.javaToJS(fieldsMap, scope);
220 
221             ScriptableObject.putProperty(scope, "jsFieldsMap", jsFieldsMap);
222 
223             context.evaluateString(scope, script, "Validation Script", 1, null);
224 
225             Object obj = ScriptableObject.getProperty(
226                 scope, "internalValidationResult");
227 
228             if (obj instanceof Boolean) {
229                 validationResult = ((Boolean)obj).booleanValue();
230             }
231             else {
232                 throw new Exception("The script must return a boolean value");
233             }
234         }
235         catch (Exception e) {
236             String msg =
237                 "The following script has execution errors:\n" +
238                     validationScript + "\n" + e.getMessage();
239 
240             _log.error(msg);
241 
242             throw new Exception(msg, e);
243         }
244         finally {
245             Context.exit();
246         }
247 
248         return validationResult;
249     }
250 
251     private static Log _log = LogFactory.getLog(WebFormUtil.class);
252 
253 }