View Javadoc
1   /*
2    * Copyright 2008 FatWire Corporation. All Rights Reserved.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *    http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package tools.gsf.facade.assetapi.code;
18  
19  import COM.FutureTense.Interfaces.ICS;
20  import com.fatwire.assetapi.common.AssetAccessException;
21  import com.fatwire.assetapi.def.AssetAssociationDef;
22  import com.fatwire.assetapi.def.AssetTypeDef;
23  import com.fatwire.assetapi.def.AssetTypeDefManager;
24  import com.fatwire.assetapi.def.AssetTypeDefProperties;
25  import com.fatwire.assetapi.def.AttributeDef;
26  import com.fatwire.assetapi.def.AttributeDefProperties;
27  import com.fatwire.assetapi.def.AttributeTypeEnum;
28  import com.fatwire.system.Session;
29  import com.fatwire.system.SessionFactory;
30  import org.apache.commons.lang3.StringEscapeUtils;
31  import tools.gsf.runtime.DebugHelper;
32  
33  import javax.servlet.jsp.JspWriter;
34  import java.io.IOException;
35  import java.io.PrintWriter;
36  import java.io.StringWriter;
37  import java.io.Writer;
38  import java.util.Arrays;
39  import java.util.HashSet;
40  import java.util.List;
41  import java.util.Set;
42  
43  public class CodeGen {
44  
45      static Set<String> KEYWORDS = new HashSet<String>(
46              Arrays.asList(("abstract,assert,boolean,break,byte,case,catch,char,class,const,continue"
47                      + ",default,do,double,else,enum,extends,final,finally,float"
48                      + ",for,goto,if,implements,import,instanceof,int,interface,long,native,new,"
49                      + "ackage,private,protected,public,return,short,static,strictfp,super,switch,"
50                      + "synchronized,this,throw,throws,transient,try,void,volatile,while").split(",")));
51      static Set<String> USELESS_ATTRIBUTES = new HashSet<String>(
52              Arrays.asList(("urlexternaldoc,externaldoctype,urlexternaldocxml").split(",")));
53  
54      interface Generator {
55  
56          void printAssetTypeDef(AssetTypeDef def);
57  
58      }
59  
60      static class DefPrint implements Generator {
61          PrintWriter out;
62  
63          public DefPrint(Writer out2) {
64              out = new PrintWriter(out2);
65          }
66  
67          public void printAssetTypeDef(AssetTypeDef def) {
68              if (def == null) {
69                  return;
70              }
71              if (def.getSubtype() == null && def.getProperties().getIsFlexAsset()) {
72                  return;
73              }
74              String s = def.getSubtype() == null ? "" : ("/" + def.getSubtype());
75  
76              out.print(def.getName() + s);
77              out.print("   // description: '" + def.getDescription() + "'");
78              out.print(" plural: '" + def.getPlural() + "'");
79              out.print(" canbechild: " + def.getCanBeChild() + "");
80              AssetTypeDefProperties p = def.getProperties();
81  
82              out.print(" canAddSubtypes: " + p.getCanAddSubtypes());
83              String type = p.getIsAssetmakerAsset() ? "AssetmakerAsset" : "Unknown Type";
84              if (p.getIsCoreAsset()) {
85                  type = "CoreAsset";
86              }
87              if (p.getIsFlexAsset()) {
88                  type = "FlexAsset";
89              }
90              out.print(" type: '" + type + "'");
91              out.println(" nameMustUnique: " + p.getIsNameMustUnique());
92  
93              printAttributes(def.getAttributeDefs());
94              printParentDefs(def.getParentDefs());
95              printAssocations(def.getAssociations());
96  
97              out.println();
98              out.println();
99          }
100 
101         private void printParentDefs(List<AttributeDef> list) {
102             printAttributeList(list, "parents");
103 
104         }
105 
106         private void printAssocations(List<AssetAssociationDef> assocs) {
107             if (assocs != null && !assocs.isEmpty()) {
108                 out.println("associations: ");
109                 for (AssetAssociationDef assoc : assocs) {
110 
111                     out.println("assoc name: '" + assoc.getName() + "'");
112                     out.println("description: '" + assoc.getDescription() + "'");
113                     out.println("multiple: '" + assoc.isMultiple() + "'");
114                     out.println("legalChildAssetTypes: '" + assoc.getLegalChildAssetTypes() + "'");
115                     out.println("childAssetType: '" + assoc.getChildAssetType() + "'");
116                     out.println("subTypes: '" + assoc.getSubTypes() + "'");
117                     out.println();
118                 }
119             }
120 
121         }
122 
123         private void printAttributes(List<AttributeDef> list) {
124             printAttributeList(list, "attributes");
125         }
126 
127         private void printAttributeList(List<AttributeDef> attributes, String label) {
128 
129             if (attributes != null && !attributes.isEmpty()) {
130                 out.println(label + ": ");
131 
132                 for (AttributeDef a : attributes) {
133 
134                     out.print("name: '" + a.getName() + "'");
135                     out.print(" description: '" + a.getDescription() + "'");
136                     out.print(" type: '" + a.getType() + "'");
137 
138                     AttributeDefProperties p = a.getProperties();
139                     out.print(" size: '" + p.getSize() + "'");
140                     out.print(" count: '" + p.getValueCount() + "'");
141                     if (a.getType() == AttributeTypeEnum.ASSET) {
142                         out.print(" assettype: '" + p.getAssetType() + "'");
143                         out.print(" assettype: '" + p.getAssetType() + "'");
144                     }
145                     if (a.isDataMandatory()) {
146                         out.print(" mandatory");
147                     }
148                     if (a.isMetaDataAttribute()) {
149                         out.print(" meta");
150                     }
151 
152                     if (p.isAllowEmbeddedLinks()) {
153                         out.print(" allow embedded");
154                     }
155                     if (p.isDerivedFlexAttribute()) {
156                         out.print(" derived");
157                     }
158                     if (p.isInheritedFlexAttribute()) {
159                         out.print(" inherited");
160                     }
161 
162                     if (p.getMultiple() != null) {
163                         out.print(" multiple: '" + p.getMultiple() + "'");
164                     }
165                     if (p.getOrdinal() != null) {
166                         out.print(" ordinal: '" + p.getOrdinal() + "'");
167                     }
168                     if (p.getRequired() != null) {
169                         out.print(" required: '" + p.getRequired() + "'");
170                     }
171                     out.println();
172                 }
173             }
174         }
175 
176     }
177 
178     static class AssetApiGen implements Generator {
179         protected PrintWriter out;
180 
181         public AssetApiGen(Writer writer) {
182             out = new PrintWriter(writer);
183         }
184 
185         public void printAssetTypeDef(AssetTypeDef def) {
186             if (def == null) {
187                 return;
188             }
189             if (def.getSubtype() == null && def.getProperties().getIsFlexAsset()) {
190                 return;
191             }
192             String s = def.getSubtype() == null ? "" : def.getSubtype() + "/";
193 
194             out.print(def.getName() + "/" + s + "Detail");
195             out.print("   // description: '" + def.getDescription() + "'");
196             out.print(" plural: '" + def.getPlural() + "'");
197             out.print(" canbechild: " + def.getCanBeChild() + "");
198             AssetTypeDefProperties p = def.getProperties();
199             out.print(" canAddSubtypes: " + p.getCanAddSubtypes());
200             String type = p.getIsAssetmakerAsset() ? "AssetmakerAsset" : "Unknown Type";
201             if (p.getIsCoreAsset()) {
202                 type = "CoreAsset";
203             }
204             if (p.getIsFlexAsset()) {
205                 type = "FlexAsset";
206             }
207             out.print(" type: '" + type + "'");
208             out.println(" nameMustUnique: " + p.getIsNameMustUnique());
209 
210             printAttributes(def);
211             printParentDefs(def.getParentDefs());
212             printAssocations(def.getAssociations());
213             out.println();
214             out.println();
215         }
216 
217         private void printAssocations(List<AssetAssociationDef> associations) {
218             // TODO Auto-generated method stub
219 
220         }
221 
222         private void printParentDefs(List<AttributeDef> parentDefs) {
223             // TODO Auto-generated method stub
224 
225         }
226 
227         protected String toVarName(String name) {
228             if (name == null || name.length() == 0) {
229                 return "noname";
230             }
231             if (KEYWORDS.contains(name)) {
232                 return name + "_";
233             }
234             char[] t = name.replace("-", "_").toCharArray();
235             t[0] = Character.toLowerCase(t[0]);
236             return new String(t);
237         }
238 
239         protected void printAttributes(AssetTypeDef def) {
240             StringWriter sw = new StringWriter();
241             PrintWriter pw = new PrintWriter(sw);
242 
243             pw.println("//sample copy/paste code");
244             pw.println("public void read" + def.getName() + (def.getSubtype() != null ? "_" + def.getSubtype() : "")
245                     + "(ICS ics) throws AssetNotExistException, AssetAccessException {");
246             pw.println();
247             pw.println("    Session ses = SessionFactory.getSession(ics);");
248             pw.println("    AssetDataManager mgr = (AssetDataManager) ses.getManager(AssetDataManager.class.getName());");
249             pw.println("    AssetId id = new AssetIdImpl(ics.GetVar(\"c\"), Long.parseLong(ics.GetVar(\"cid\")));");
250             pw.println("    Iterable<AssetData> assets = mgr.read(Collections.singletonList(id));");
251 
252             pw.println("    for (AssetData asset : assets) {");
253             pw.println("");
254 
255             List<AttributeDef> attributes = def.getAttributeDefs();
256             if (attributes != null) {
257                 pw.println("        // attributes: ");
258                 pw.println("        AttributeData attribute = null;");
259 
260                 for (AttributeDef a : attributes) {
261                     if (USELESS_ATTRIBUTES.contains(a.getName())) {
262                         continue;
263                     }
264                     AttributeTypeEnum t = a.getType();
265                     String cast = toCastType(t);
266                     String name = toVarName(a.getName());
267                     pw.println("       attribute = asset.getAttributeData(\"" + a.getName() + "\", "
268                             + a.isMetaDataAttribute() + ");");
269                     pw.println("       if (attribute != null){");
270                     pw.println("            // type = " + t + ", valueCount = " + a.getProperties().getValueCount());
271                     boolean singleValued = AttributeDefProperties.ValueCount.SINGLE.equals(a.getProperties()
272                             .getValueCount());
273                     if (singleValued) {
274                         pw.println("           " + cast + " " + name + " = (" + cast + ")attribute.getData();");
275                     } else {
276                         pw.println("           List<?> " + name + " = attribute.getDataAsList();");
277                     }
278                     if (a.getProperties().getMultiple() != null) {
279                         pw.println("           multiple " + a.getProperties().getMultiple());
280 
281                     }
282                     // List<?> valueList = attribute.getDataAsList();
283                     // for (Object o : valueList)
284                     // {
285 
286                     // }
287                     switch (t) {
288                         case BLOB:
289                         case URL:
290                             pw.println("           BlobAddress address = " + name + ".getBlobAddress();");
291                             pw.println("           String blobcol = address.getColumnName();");
292                             pw.println("           Object blobid = address.getIdentifier();");
293                             pw.println("           String idcol = address.getIdentifierColumnName();");
294                             pw.println("           String blobtable = address.getTableName();");
295                             pw.println("           //InputStream stream = " + name + ".getBinaryStream();");
296                             break;
297                         default:
298                             break;
299 
300                     }
301 
302                     pw.println("        }");
303                 }
304                 pw.println("    }");
305                 pw.println("}");
306                 out.print(org.apache.commons.lang3.StringEscapeUtils.escapeHtml4(sw.toString()));
307             }
308         }
309 
310         String toCastType(AttributeTypeEnum t) {
311 
312             switch (t) {
313                 case INT:
314                     return "Integer";
315                 case FLOAT:
316                     return "Double";
317                 case STRING:
318                     return "String";
319                 case LONG:
320                     return "Long";
321                 case DATE:
322                     return "Date";
323                 case MONEY:
324                     return "Double";
325                 case LARGE_TEXT:
326                     return "String";
327                 case ASSET:
328                     return "AssetId";
329                 case ASSETREFERENCE:
330                     return "AssetId";
331                 case BLOB:
332                     return "BlobObject";
333                 case URL:
334                     return "BlobObject";
335                 case ARRAY:
336                     return "List<?>";
337                 case STRUCT:
338                     return "Map<?,?>";
339                 case LIST:
340                     return "List<?>";
341                 case ONEOF:
342                     return "Object";
343             }
344             throw new IllegalArgumentException("Don't know about " + t);
345         }
346     }
347 
348     static class HtmlWriter extends Writer {
349 
350         final Writer writer;
351 
352         /**
353          * @param writer
354          */
355         private HtmlWriter(Writer writer) {
356             super();
357             this.writer = writer;
358         }
359 
360         @Override
361         public void close() throws IOException {
362             writer.close();
363 
364         }
365 
366         @Override
367         public void flush() throws IOException {
368             writer.flush();
369 
370         }
371 
372         @Override
373         public void write(char[] cbuf, int off, int len) throws IOException {
374             writer.write(StringEscapeUtils.escapeHtml4(new String(cbuf, off, len)));
375         }
376 
377     }
378 
379     static public class GsfJavaGen extends AssetApiGen {
380 
381         public GsfJavaGen(Writer writer) {
382             super(writer);
383         }
384 
385         protected void printAttributes(List<AttributeDef> attributes) {
386             StringWriter sw = new StringWriter();
387             PrintWriter pw = new PrintWriter(sw);
388 
389             if (attributes != null) {
390                 // pw.println("    // attributes: ");
391 
392                 for (AttributeDef a : attributes) {
393                     if (USELESS_ATTRIBUTES.contains(a.getName())) {
394                         continue;
395                     }
396                     AttributeTypeEnum t = a.getType();
397                     String cast = toCastType(t);
398                     String name = toVarName(a.getName());
399                     String method = toMethodName(a.getType());
400                     pw.println("");
401                     // pw.println("    // type = " + t + ", valueCount = " +
402                     // a.getProperties().getValueCount());
403                     boolean singleValued = AttributeDefProperties.ValueCount.SINGLE.equals(a.getProperties()
404                             .getValueCount());
405                     if (singleValued) {
406                         pw.println("    " + cast + " " + name + " = asset." + method + "(\"" + a.getName() + "\");");
407                     } else {
408                         pw.println("    List<?> " + name + " = asset.asList(\"" + a.getName() + "\");");
409                     }
410 
411                     switch (t) {
412                         case BLOB:
413                         case URL:
414                             pw.println("");
415                             pw.println("    /*");
416                             pw.println("    BlobAddress address = asset.asBlobAddress(\"" + a.getName() + "\");");
417                             pw.println("    String blobcol = address.getColumnName();");
418                             pw.println("    Object blobid = address.getIdentifier();");
419                             pw.println("    String idcol = address.getIdentifierColumnName();");
420                             pw.println("    String blobtable = address.getTableName();");
421                             pw.println("");
422                             pw.println("    String uri =new BlobUriBuilder(address).mimeType(\"image/jpeg\").toURI(ics);");
423 
424                             pw.println("    */");
425                             pw.println("    //InputStream stream = " + name + ".getBinaryStream();");
426                             break;
427 
428                     }
429 
430                 }
431 
432                 // org.apache.commons.lang.StringEscapeUtils.escapeHtml(out,
433                 // sw.toString());
434             }
435         }
436 
437         private String toMethodName(AttributeTypeEnum t) {
438 
439             switch (t) {
440                 case INT:
441                     return "asInt";
442                 case FLOAT:
443                     return "asDouble";
444                 case STRING:
445                     return "asString";
446                 case LONG:
447                     return "asLong";
448                 case DATE:
449                     return "asDate";
450                 case MONEY:
451                     return "asDouble";
452                 case LARGE_TEXT:
453                     return "asString";
454                 case ASSET:
455                     return "asAssetId";
456                 case ASSETREFERENCE:
457                     return "asAssetId";
458                 case BLOB:
459                     return "asBlob";
460                 case URL:
461                     return "asBlob";
462                 case ARRAY:
463                     return "asList";
464                 case STRUCT:
465                     return "asMap";
466                 case LIST:
467                     return "asList";
468                 case ONEOF:
469                     return "asObject";
470             }
471             throw new IllegalArgumentException("Don't know about " + t);
472         }
473 
474         /*
475          * (non-Javadoc)
476          * 
477          * @see
478          * tools.gsf.facade.assetapi.code.CodeGen.AssetApiGen
479          * #printAssetTypeDef(com.fatwire.assetapi.def.AssetTypeDef)
480          */
481         @Override
482         public void printAssetTypeDef(AssetTypeDef def) {
483 
484             out.println("//sample copy/paste code");
485             out.println("public void read" + def.getName() + (def.getSubtype() != null ? "_" + def.getSubtype() : "")
486                     + "(ICS ics) throws AssetNotExistException, AssetAccessException {");
487             out.println();
488             out.println("    AssetAccessTemplate aat = new AssetAccessTemplate(ics);");
489             out.println("    TemplateAsset asset = aat.readAsset(ics.GetVar(\"c\"), ics.GetVar(\"cid\"), new TemplateAssetMapper());");
490             out.println("");
491             printAttributes(def.getAttributeDefs());
492             out.println("}");
493 
494         }
495 
496     }
497 
498     static public class GsfJspGen implements Generator {
499         PrintWriter out;
500 
501         public GsfJspGen(Writer writer) {
502             out = new PrintWriter(writer);
503         }
504 
505         String getAttributeNames(List<AttributeDef> list) {
506             StringBuilder b = new StringBuilder();
507             for (AttributeDef def : list) {
508                 if (b.length() > 0) {
509                     b.append(",");
510                 }
511                 b.append(def.getName());
512             }
513             return b.toString();
514 
515         }
516 
517         public void printAssetTypeDef(AssetTypeDef def) {
518             out.println("<%@ taglib prefix=\"cs\" uri=\"futuretense_cs/ftcs1_0.tld\"");
519             out.println("%><%@ taglib uri=\"http://java.sun.com/jsp/jstl/core\" prefix=\"c\"");
520             out.println("%><%@ taglib uri=\"http://gst.fatwire.com/foundation/tags/gsf\" prefix=\"gsf\"");
521             out.println("%><cs:ftcs><gsf:root>");
522 
523             out.println("<gsf:asset-load name=\"asset\" attributes=\"" + getAttributeNames(def.getAttributeDefs())
524                     + "\" />");
525 
526             printAttributes(def.getAttributeDefs());
527             out.println("%></gsf:root></cs:ftcs>");
528         }
529 
530         private void printAttributes(List<AttributeDef> list) {
531             for (AttributeDef def : list) {
532                 if (def.getType() == AttributeTypeEnum.BLOB || def.getType() == AttributeTypeEnum.URL) {
533 
534                     // x.getVariableResolver().resolveVariable("asset." +
535                     // def.getName());
536                     // <gsf:link assetname="asset" field="" mimetype="" var="" >
537                 } else {
538                     out.println(def.getName() + ": ${asset." + def.getName() + "} <br/>");
539                 }
540 
541             }
542 
543         }
544     }
545 
546     void gen(ICS ics, JspWriter out) throws AssetAccessException, IOException {
547 
548         Session s = SessionFactory.getSession(ics);
549         AssetTypeDefManager mgr = (AssetTypeDefManager) s.getManager(com.fatwire.assetapi.def.AssetTypeDefManager.class
550                 .getName());
551 
552         String ats = ics.GetVar("assettype");
553         Generator generator = null;
554         String what = ics.GetVar("what");
555         if ("assetapicode".equals(what)) {
556             generator = new AssetApiGen(out);
557         } else if ("def".equals(what)) {
558             generator = new DefPrint(out);
559         } else if ("gsfjspcode".equals(what)) {
560             generator = new GsfJspGen(out);
561         } else if ("gsfjavacode".equals(what)) {
562             generator = new GsfJavaGen(out);
563         }
564 
565         if (ats != null && generator != null) {
566             for (String at : ats.split(";")) {
567                 String[] p = at.split(":");
568                 String a = p[0];
569                 String st = p.length == 2 ? p[1] : null;
570                 try {
571                     out.write("<pre>");
572                     AssetTypeDef def = mgr.findByName(a, st);
573                     if (def != null) {
574                         generator.printAssetTypeDef(def);
575                     }
576                 } catch (Exception e) {
577                     out.println(e.getMessage() + " on " + a + "/" + st);
578                     e.printStackTrace(new PrintWriter(out));
579                 }
580                 out.write("</pre>");
581 
582             }
583 
584         }
585 
586         for (String assetType : mgr.getAssetTypes()) {
587             for (String subtype : mgr.getSubTypes(assetType)) {
588                 // %><input type="checkbox" name="assettype"
589                 // value="<%=assetType%>:<%=subtype%>" /><%=assetType%> /
590                 // <%=subtype%><br/><%
591             }
592             try {
593                 AssetTypeDef def = mgr.findByName(assetType, null);
594                 if (!def.getProperties().getIsFlexAsset()) {
595                     // %><input type="checkbox" name="assettype"
596                     // value="<%=assetType%>" /><%=assetType%><br/><%
597                 }
598             } catch (Exception e) {
599                 out.println(e.getMessage());
600                 DebugHelper.printStackTrace(out, e);
601             }
602 
603         }
604     }
605 
606 }