KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > dotmarketing > viewtools > WebAPI


1 package com.dotmarketing.viewtools;
2
3 import java.io.IOException JavaDoc;
4 import java.io.StringWriter JavaDoc;
5 import java.text.SimpleDateFormat JavaDoc;
6 import java.util.ArrayList JavaDoc;
7 import java.util.Calendar JavaDoc;
8 import java.util.Date JavaDoc;
9 import java.util.GregorianCalendar JavaDoc;
10 import java.util.List JavaDoc;
11 import java.util.StringTokenizer JavaDoc;
12
13 import javax.servlet.http.HttpServletRequest JavaDoc;
14 import javax.servlet.http.HttpServletResponse JavaDoc;
15
16 import org.apache.commons.logging.LogFactory;
17 import org.apache.velocity.app.Velocity;
18 import org.apache.velocity.context.Context;
19 import org.apache.velocity.tools.view.context.ViewContext;
20 import org.apache.velocity.tools.view.tools.ViewTool;
21
22 import com.dotmarketing.beans.Host;
23 import com.dotmarketing.beans.Identifier;
24 import com.dotmarketing.beans.Inode;
25 import com.dotmarketing.beans.UserProxy;
26 import com.dotmarketing.cache.IdentifierCache;
27 import com.dotmarketing.cache.LiveCache;
28 import com.dotmarketing.db.DotConnect;
29 import com.dotmarketing.factories.HostFactory;
30 import com.dotmarketing.factories.IdentifierFactory;
31 import com.dotmarketing.factories.InodeFactory;
32 import com.dotmarketing.factories.UserProxyFactory;
33 import com.dotmarketing.portlets.categories.factories.CategoryFactory;
34 import com.dotmarketing.portlets.categories.model.Category;
35 import com.dotmarketing.portlets.contentlet.model.Contentlet;
36 import com.dotmarketing.portlets.files.factories.FileFactory;
37 import com.dotmarketing.portlets.files.model.File;
38 import com.dotmarketing.util.Config;
39 import com.dotmarketing.util.Logger;
40 import com.dotmarketing.util.UtilMethods;
41 import com.dotmarketing.util.WebKeys;
42 import com.dotmarketing.util.XMLUtils;
43 import com.liferay.portal.model.User;
44 import com.dotmarketing.portlets.discountcode.model.DiscountCode;
45 import com.dotmarketing.portlets.order_manager.struts.OrderForm;
46 import com.dotmarketing.portlets.order_manager.struts.OrderItemForm;
47 import com.dotmarketing.portlets.organization.model.Organization;
48
49 public class WebAPI implements ViewTool {
50
51     private HttpServletRequest JavaDoc request;
52
53     Context ctx;
54
55     /**
56      * @param obj the ViewContext that is automatically passed on view tool initialization, either in the request or the application
57      * @return
58      * @see ViewTool, ViewContext
59      */

60     public void init(Object JavaDoc obj) {
61         ViewContext context = (ViewContext) obj;
62         this.request = context.getRequest();
63         ctx = context.getVelocityContext();
64     }
65     /**
66      * This method returns a list of the 10 HTMLPages that have most recently been published by modificatation date desc.
67      * @return a list of HTMLPage objects
68      * @see HTMLPage, ViewContext
69      */

70     public List JavaDoc getRecentlyPublished() {
71         Host host = (Host) HostFactory.getCurrentHost(request);
72         DotConnect db = new DotConnect();
73         db.setMaxRows(10);
74         db
75                 .setSQL("select uri, mod_date, title from identifier, tree, htmlpage where identifier.inode = tree.parent and tree.child = htmlpage.inode and htmlpage.live = "
76                         + com.dotmarketing.db.DbConnectionFactory.getDBTrue()
77                         + " and show_on_menu= "
78                         + com.dotmarketing.db.DbConnectionFactory.getDBTrue()
79                         + " and host_inode= "
80                         + host.getInode()
81                         + " order by mod_date desc");
82         return db.getResults();
83     }
84
85     // Utility Methods
86
public int parseInt(String JavaDoc num) {
87         try {
88             return Integer.parseInt(num);
89         } catch (Exception JavaDoc e) {
90             return 0;
91         }
92     }
93
94     public long parseLong(String JavaDoc num) {
95         try {
96             return Long.parseLong(num);
97         } catch (Exception JavaDoc e) {
98             return 0;
99         }
100     }
101
102     public int castToInt(long num) {
103         return (int) num;
104     }
105
106     public String JavaDoc toString(long num) {
107         try {
108             return Long.toString(num);
109         } catch (Exception JavaDoc e) {
110             return "0";
111         }
112     }
113
114     static final String JavaDoc[] WEEKDAY_NAME = { "None", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
115             "Saturday" };
116
117     public String JavaDoc dateToHTMLPrettyDay(int year, int month, int day) {
118         GregorianCalendar JavaDoc cal = new GregorianCalendar JavaDoc(year, month, day);
119         String JavaDoc dayName = WEEKDAY_NAME[cal.get(java.util.Calendar.DAY_OF_WEEK)] + " " + day;
120         return dayName;
121     }
122
123     public String JavaDoc dateToHTML(Date JavaDoc myDate) {
124         return UtilMethods.dateToHTMLDate(myDate);
125     }
126
127     public String JavaDoc dateToHTMLDateTimeRange(Date JavaDoc from, Date JavaDoc to) {
128         return UtilMethods.dateToHTMLDateTimeRange(from, to, GregorianCalendar.getInstance().getTimeZone());
129     }
130
131     public String JavaDoc dateToHTMLTimeRange(Date JavaDoc from, Date JavaDoc to) {
132
133         String JavaDoc ret = UtilMethods.dateToHTMLTime(from, GregorianCalendar.getInstance().getTimeZone());
134         if (from.compareTo(to) != 0) {
135             ret += " - " + UtilMethods.dateToHTMLTime(to, GregorianCalendar.getInstance().getTimeZone());
136         }
137         return ret;
138     }
139
140     public String JavaDoc dateToHTML(Date JavaDoc myDate, String JavaDoc format) {
141         return UtilMethods.dateToHTMLDate(myDate, format);
142     }
143
144     public String JavaDoc trimToUpper(String JavaDoc input) {
145         return input.trim().toUpperCase();
146     }
147     
148     public String JavaDoc trim(String JavaDoc input) {
149         return input.trim();
150     }
151
152     public String JavaDoc htmlLineBreak(String JavaDoc input) {
153         return UtilMethods.htmlLineBreak(input);
154     }
155
156     public boolean isSet(String JavaDoc input) {
157         return UtilMethods.isSet(input);
158     }
159
160     public String JavaDoc obfuscateCreditCard(String JavaDoc ccnum) {
161         return UtilMethods.obfuscateCreditCard(ccnum);
162     }
163
164     public String JavaDoc capitalize(String JavaDoc str) {
165         if (str.length() > 1) {
166             return str.substring(0, 1).toUpperCase() + str.substring(1);
167         }
168         return str;
169     }
170
171     public List JavaDoc splitString(String JavaDoc str, String JavaDoc sep) {
172         ArrayList JavaDoc<String JavaDoc> list = new ArrayList JavaDoc<String JavaDoc>();
173         String JavaDoc[] splitArr = str.split(sep);
174         for (int i = 0; i < splitArr.length; i++) {
175             list.add(splitArr[i]);
176         }
177         return list;
178     }
179
180     public String JavaDoc encodeURL(String JavaDoc url) {
181         return UtilMethods.encodeURL(url);
182     }
183
184     public long getIdentifierInode(String JavaDoc childInode) {
185         try {
186             return IdentifierCache.getIdentifierByInodeFromCache(Long.parseLong(childInode)).getInode();
187         } catch (NumberFormatException JavaDoc e) {
188             return 0;
189         }
190     }
191
192     public String JavaDoc getShortMonthName(int month) {
193         return UtilMethods.getShortMonthName(month);
194     }
195
196     public String JavaDoc getShortMonthName(String JavaDoc month) {
197         return UtilMethods.getShortMonthName(month);
198     }
199
200     /**
201      *
202      * @param catInode
203      * Can use either the category inode or the name
204      * @return
205      */

206     public List JavaDoc getContentletsByCategory(String JavaDoc catInode) {
207
208         long myCat = 0;
209         try {
210             myCat = Long.parseLong(catInode);
211         } catch (Exception JavaDoc e) {
212
213         }
214         int limit = 10;
215         return InodeFactory.getChildrenClassByConditionAndOrderBy(myCat, Contentlet.class, " live ", "idate desc",
216                 limit, 0);
217
218     }
219
220     public String JavaDoc prettyShortenString(String JavaDoc text, String JavaDoc maxLength) {
221         return UtilMethods.prettyShortenString(text, Integer.parseInt(maxLength));
222     }
223
224     public String JavaDoc dateToLongPrettyHTMLDate(Date JavaDoc myDate) {
225         return UtilMethods.dateToLongPrettyHTMLDate(myDate);
226     }
227
228     public boolean canParseContent(String JavaDoc parsePath) {
229         try {
230             Velocity.init();
231             StringWriter JavaDoc w = new StringWriter JavaDoc();
232             Velocity.mergeTemplate(parsePath, "UTF-8", ctx, w);
233         } catch (Exception JavaDoc e) {
234             LogFactory.getLog(WebAPI.class).debug("Velocity Error: " + e);
235             e.printStackTrace();
236             return false;
237         }
238         return true;
239     }
240
241     public String JavaDoc getContentIdentifier(String JavaDoc parsePath) {
242         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(parsePath, "/.");
243         String JavaDoc x = "0";
244         while (st.hasMoreTokens()) {
245             String JavaDoc y = st.nextToken();
246             if (st.hasMoreTokens()) {
247                 x = y;
248             }
249         }
250         String JavaDoc language = "";
251         if (x.indexOf("_") > -1) {
252             Logger.debug(this, "x=" + x);
253             language = x.substring(x.indexOf("_") + 1, x.length());
254             Logger.debug(this, "language=" + language);
255             x = x.substring(0, x.indexOf("_"));
256             Logger.debug(this, "x=" + x);
257         }
258         return x;
259     }
260
261     /*
262      * Use only in preview mode, this methods hits the db!!
263      */

264     public String JavaDoc getContentInode(String JavaDoc parsePath) {
265         String JavaDoc id = getContentIdentifier(parsePath);
266         Identifier iden = (Identifier) InodeFactory.getInode(id, Identifier.class);
267         Contentlet cont = (Contentlet) IdentifierFactory.getWorkingChildOfClass(iden, Contentlet.class);
268         return ((Long JavaDoc) cont.getInode()).toString();
269     }
270
271     public String JavaDoc getContentPermissions(String JavaDoc parsePath) {
272         String JavaDoc id = getContentIdentifier(parsePath);
273         return (String JavaDoc) ctx.get("EDIT_CONTENT_PERMISSION" + id);
274     }
275     
276     
277     public String JavaDoc xmlEscape(String JavaDoc x){
278         
279         return XMLUtils.xmlEscape(x);
280         
281     }
282     
283     public int stringLenght(String JavaDoc text){
284         
285         if(UtilMethods.isSet(text)){
286             return text.length();
287         }
288         return 0;
289     }
290
291     public String JavaDoc subString(String JavaDoc text, int begin, int end){
292         
293         if(UtilMethods.isSet(text)){
294             text = text.substring(begin, end);
295         }
296         
297         return text;
298     }
299     
300     public boolean isImage(String JavaDoc text){
301         
302         return UtilMethods.isImage(text);
303     }
304     
305     public String JavaDoc getAssetPath(String JavaDoc path){
306         if(path == null ) return null;
307         path = path.replaceAll("\\.\\.", "");
308         path = path.replaceAll("WEB-INF", "");
309         
310         while(path.indexOf("//") > -1){
311             path = path.replaceAll("//", "/");
312         }
313         Host host = HostFactory.getCurrentHost(request);
314         String JavaDoc logicalFilePath = LiveCache.getPathFromCache(path , host);
315         StringTokenizer JavaDoc _st = new StringTokenizer JavaDoc(logicalFilePath, "/\\");
316         String JavaDoc fileName = null;
317         while(_st.hasMoreElements()){
318             fileName = _st.nextToken();
319         }
320         if (fileName.contains("."))
321             fileName = fileName.substring(0, fileName.lastIndexOf("."));
322         String JavaDoc ext = UtilMethods.getFileExtension(logicalFilePath);
323         String JavaDoc realPath = FileFactory.getRealAssetPath(fileName, ext);
324         return realPath;
325
326     }
327
328     public int getAssetInode(String JavaDoc path){
329         if(path == null ) return 0;
330         path = path.replaceAll("\\.\\.", "");
331         path = path.replaceAll("WEB-INF", "");
332         
333         while(path.indexOf("//") > -1){
334             path = path.replaceAll("//", "/");
335         }
336         Host host = HostFactory.getCurrentHost(request);
337         File f = FileFactory.getFileByURI(path, host, false);
338         return (int)f.getInode();
339     }
340     
341     /**
342      * This method gives to you the sub URI of a complete request URI given the deepness desired.
343      * E.G. URI = /alumni/relations/aaa/index.dot then getSubURI(2) = /alumni/relations/
344      * @param deepness
345      * @return
346      */

347     public String JavaDoc getSubURIByDepth (int depth) {
348         String JavaDoc subURI = "/";
349         String JavaDoc completeURI = request.getRequestURI();
350         String JavaDoc[] splittedURI = completeURI.split("\\/");
351         for (int i = 1; i <= depth; i++)
352             if(i < splittedURI.length)
353                 subURI += splittedURI[i] + "/";
354         return subURI;
355     }
356     
357     public String JavaDoc getConfigVar(String JavaDoc varName) {
358         return Config.getStringProperty(varName);
359     }
360     
361     public static String JavaDoc formatDate(Date JavaDoc date,String JavaDoc format)
362     {
363         try
364         {
365             SimpleDateFormat JavaDoc sdf = new SimpleDateFormat JavaDoc(format);
366             String JavaDoc returnValue = sdf.format(date);
367             return returnValue;
368         }
369         catch(Exception JavaDoc ex)
370         {
371             Logger.debug(WebAPI.class,ex.toString());
372             return "error date";
373         }
374     }
375     
376     public static void isCreateFormEmpty(Object JavaDoc form, HttpServletResponse JavaDoc response){
377         
378         
379             try {
380                 
381                 if(form == null){
382                     response.sendRedirect("/dotCMS/createAccount");
383                 }
384             } catch (IOException JavaDoc e) {
385                 // TODO Auto-generated catch block
386
e.printStackTrace();
387             }
388         
389     }
390     
391     public String JavaDoc toMonthFormat(int month)
392     {
393         return UtilMethods.getMonthName(month);
394     }
395
396     public boolean isPartner()
397     {
398         boolean isPartner = false;
399         if (request.getSession().getAttribute("isPartner") != null &&
400                 request.getSession().getAttribute("isPartner").equals("true"))
401         {
402             isPartner = true;
403         }
404         return isPartner;
405     }
406     
407     public boolean equalsNumbers(float one,float two)
408     {
409         return one == two;
410     }
411
412     public String JavaDoc toPriceFormat(double price)
413     {
414         return UtilMethods.toPriceFormat(price);
415     }
416     
417     public String JavaDoc toPriceFormat(float price)
418     {
419         return UtilMethods.toPriceFormat(price);
420     }
421     
422     public String JavaDoc getUserFullName()
423     {
424         String JavaDoc fullName = "";
425         if (request.getSession().getAttribute(WebKeys.CMS_USER) != null)
426         {
427             User user = (User) request.getSession().getAttribute(WebKeys.CMS_USER);
428             fullName = user.getFullName();
429         }
430         return fullName;
431     }
432     
433     public String JavaDoc getUserEmail()
434     {
435         String JavaDoc email = "";
436         if (request.getSession().getAttribute(WebKeys.CMS_USER) != null)
437         {
438             User user = (User) request.getSession().getAttribute(WebKeys.CMS_USER);
439             email = UtilMethods.getUserEmail(user);
440         }
441         return email;
442     }
443     
444     public String JavaDoc getUserCompanyName()
445     {
446         try
447         {
448             String JavaDoc companyName = "";
449             if (request.getSession().getAttribute(WebKeys.CMS_USER) != null)
450             {
451                 User user = (User) request.getSession().getAttribute(WebKeys.CMS_USER);
452                 UserProxy userProxy = UserProxyFactory.getUserProxy(user);
453                 Organization organization = (Organization) InodeFactory.getParentOfClass(userProxy,Organization.class);
454                 if(organization.getInode() != 0)
455                 {
456                     companyName = organization.getTitle();
457                 }
458             }
459             return companyName;
460         }
461         catch(Exception JavaDoc ex)
462         {
463             Logger.debug(this,ex.toString());
464             return "";
465         }
466     }
467     public String JavaDoc toCCFormat(String JavaDoc creditCard)
468     {
469         String JavaDoc shortCreditCard = "";
470         shortCreditCard = UtilMethods.obfuscateCreditCard(creditCard);
471         return shortCreditCard;
472     }
473     
474     public static float getItemPriceWithDiscount(OrderItemForm orderItemForm, List JavaDoc<DiscountCode> discounts){
475         return UtilMethods.getItemPriceWithDiscount(orderItemForm, discounts);
476     }
477     
478     public static List JavaDoc<DiscountCode> getDiscountsByOrder(OrderForm orderForm){
479         return UtilMethods.getDiscountsByOrder(orderForm);
480     }
481
482     public Inode getLiveFileAsset (Identifier id) {
483         return (Inode) IdentifierFactory.getLiveChildOfClass(id, File.class);
484     }
485
486     public Inode getLiveFileAsset (long identifierInode) {
487         return getLiveFileAsset((Identifier)InodeFactory.getInode(identifierInode, Identifier.class));
488     }
489     
490     public Inode getLiveFileAsset (String JavaDoc identifierInode) {
491         return getLiveFileAsset((Identifier)InodeFactory.getInode(identifierInode, Identifier.class));
492     }
493
494     public static String JavaDoc javaScriptify(String JavaDoc fixme) {
495         fixme = UtilMethods.javaScriptify(fixme);
496         return UtilMethods.escapeSingleQuotes(fixme);
497     }
498
499     public int getActualYear () {
500         Calendar JavaDoc cal = new GregorianCalendar JavaDoc ();
501         return cal.get(Calendar.YEAR);
502     }
503     
504 }
Popular Tags