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