0001: /*
0002: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
0003: *
0004: * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
0005: *
0006: * The contents of this file are subject to the terms of either the GNU
0007: * General Public License Version 2 only ("GPL") or the Common
0008: * Development and Distribution License("CDDL") (collectively, the
0009: * "License"). You may not use this file except in compliance with the
0010: * License. You can obtain a copy of the License at
0011: * http://www.netbeans.org/cddl-gplv2.html
0012: * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
0013: * specific language governing permissions and limitations under the
0014: * License. When distributing the software, include this License Header
0015: * Notice in each file and include the License file at
0016: * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
0017: * particular file as subject to the "Classpath" exception as provided
0018: * by Sun in the GPL Version 2 section of the License file that
0019: * accompanied this code. If applicable, add the following below the
0020: * License Header, with the fields enclosed by brackets [] replaced by
0021: * your own identifying information:
0022: * "Portions Copyrighted [year] [name of copyright owner]"
0023: *
0024: * Contributor(s):
0025: *
0026: * The Original Software is NetBeans. The Initial Developer of the Original
0027: * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
0028: * Microsystems, Inc. All Rights Reserved.
0029: *
0030: * If you wish your version of this file to be governed by only the CDDL
0031: * or only the GPL Version 2, indicate your decision by adding
0032: * "[Contributor] elects to include this software in this distribution
0033: * under the [CDDL or GPL Version 2] license." If you do not indicate a
0034: * single choice of license, a recipient has the option to distribute
0035: * your version of this file under either the CDDL, the GPL Version 2 or
0036: * to extend the choice of license to its licensees as provided above.
0037: * However, if you add GPL Version 2 code and therefore, elected the GPL
0038: * Version 2 license, then the option applies only if the new code is
0039: * made subject to such option by the copyright holder.
0040: */
0041:
0042: package org.netbeans.modules.websvc.rest.codegen;
0043:
0044: import java.io.BufferedInputStream;
0045: import java.io.BufferedOutputStream;
0046: import java.io.BufferedReader;
0047: import java.io.File;
0048: import java.io.FileInputStream;
0049: import java.io.FileNotFoundException;
0050: import java.io.FileOutputStream;
0051: import java.io.FileReader;
0052: import java.io.FilenameFilter;
0053: import java.io.IOException;
0054: import java.io.InputStream;
0055: import java.io.OutputStream;
0056: import java.io.OutputStreamWriter;
0057: import java.util.HashSet;
0058: import java.util.List;
0059: import java.util.Set;
0060: import java.util.logging.Level;
0061: import java.util.logging.Logger;
0062: import java.util.zip.ZipEntry;
0063: import java.util.zip.ZipInputStream;
0064: import java.util.zip.ZipOutputStream;
0065: import org.netbeans.api.progress.ProgressHandle;
0066: import org.netbeans.api.project.Project;
0067: import org.openide.filesystems.FileLock;
0068: import org.openide.filesystems.FileObject;
0069: import org.netbeans.api.project.ProjectUtils;
0070: import org.netbeans.modules.websvc.rest.RestUtils;
0071: import org.openide.filesystems.FileUtil;
0072: import org.netbeans.modules.websvc.rest.codegen.model.ClientStubModel;
0073: import org.netbeans.modules.websvc.rest.codegen.model.ClientStubModel.*;
0074: import org.openide.filesystems.FileSystem;
0075: import org.openide.loaders.DataObject;
0076: import org.openide.util.NbBundle;
0077:
0078: /**
0079: * Code generator for plain REST resource class.
0080: * The generator takes as paramenters:
0081: * - target directory
0082: * - REST resource bean meta model.
0083: *
0084: * @author Ayub Khan
0085: */
0086: public class ClientStubsGenerator extends AbstractGenerator {
0087:
0088: public static final String RESOURCES = "resources"; //NOI18N
0089: public static final String TEMPLATES = "templates"; //NOI18N
0090: public static final String DOJO = "dojo"; //NOI18N
0091: public static final String REST = "rest"; //NOI18N
0092: public static final String RDJ = "rdj"; //NOI18N
0093: public static final String DATA = "data"; //NOI18N
0094: public static final String WIDGET = "widget"; //NOI18N
0095: public static final String RJS = "rjs"; //NOI18N
0096: public static final String TABLE = "table"; //NOI18N
0097: public static final String STORE = "Store"; //NOI18N
0098: public static final String CSS = "css"; //NOI18N
0099: public static final String JS = "js"; //NOI18N
0100: public static final String HTML = "html"; //NOI18N
0101: public static final String HTM = "htm"; //NOI18N
0102: public static final String JSON = "json"; //NOI18N
0103: public static final String GIF = "gif"; //NOI18N
0104: public static final String JSP = "jsp"; //NOI18N
0105: public static final String PHP = "php"; //NOI18N
0106: public static final String RHTML = "rhtml"; //NOI18N
0107: public static final String EJS = "ejs"; //NOI18N
0108: public static final String IMAGES = "images"; //NOI18N
0109: public static final String BUNDLE = "Bundle"; //NOI18N
0110: public static final String PROPERTIES = "properties"; //NOI18N
0111: public static final String LIBS = "libs"; //NOI18N
0112: public static final String DJD43 = "djd43"; //NOI18N
0113: public static final String JMAKI_DOJO = "jmaki-dojo"; //NOI18n
0114: public static final String JMAKI_COMP_LIB = "jmakicomplib"; //NOI18n
0115:
0116: public static final String JS_SUPPORT = "Support"; //NOI18N
0117: public static final String JS_TESTSTUBS = "TestStubs"; //NOI18N
0118: public static final String JS_README = "Readme"; //NOI18N
0119: public static final String JS_TESTSTUBS_TEMPLATE = "Templates/WebServices/JsTestStubs.html"; //NOI18N
0120: public static final String JS_STUBSUPPORT_TEMPLATE = "Templates/WebServices/JsStubSupport.js"; //NOI18N
0121: public static final String JS_PROJECTSTUB_TEMPLATE = "Templates/WebServices/JsProjectStub.js"; //NOI18N
0122: public static final String JS_CONTAINERSTUB_TEMPLATE = "Templates/WebServices/JsContainerStub.js"; //NOI18N
0123: public static final String JS_CONTAINERITEMSTUB_TEMPLATE = "Templates/WebServices/JsContainerItemStub.js"; //NOI18N
0124: public static final String JS_GENERICSTUB_TEMPLATE = "Templates/WebServices/JsGenericStub.js"; //NOI18N
0125: public static final String JS_README_TEMPLATE = "Templates/WebServices/JsReadme.html"; //NOI18N
0126:
0127: //Dojo templates
0128: public static final String DOJO_RESTSTORE = "RestStore";//NOI18N
0129: public static final String DOJO_COLLECTIONSTORE = "CollectionStore";//NOI18N
0130: public static final String DOJO_RESOURCESTABLE = "ResourcesTable";//NOI18N
0131: public static final String DOJO_TESTRESOURCESTABLE = "TestResourcesTable"; //NOI18N
0132: public static final String DOJO_SUPPORT = "Support"; //NOI18N
0133: public static final String DOJO_RESTSTORE_TEMPLATE = "Templates/WebServices/DojoRestStore.js"; //NOI18N
0134: public static final String DOJO_COLLECTIONSTORE_TEMPLATE = "Templates/WebServices/DojoCollectionStore.js"; //NOI18N
0135: public static final String DOJO_RESOURCESTABLE_TEMPLATE = "Templates/WebServices/DojoResourcesTable.js"; //NOI18N
0136: public static final String DOJO_SUPPORT_TEMPLATE = "Templates/WebServices/DojoSupport.js"; //NOI18N
0137: public static final String DOJO_TESTRESOURCESTABLE_TEMPLATE = "Templates/WebServices/DojoTestResourcesTable.html"; //NOI18N
0138:
0139: //jMaki templates
0140: public static final String JMAKI_README = "Readme"; //NOI18N
0141: public static final String JMAKI_COMPONENT = "component"; //NOI18N
0142: public static final String JMAKI_TESTRESOURCESTABLE = "TestResourcesTable"; //NOI18N
0143: public static final String JMAKI_RESOURCESTABLE_SRC = "JmakiResourcesTable"; //NOI18N
0144: public static final String JMAKI_RESOURCESTABLEUP_SRC = "JmakiResourcesTableUp"; //NOI18N
0145: public static final String JMAKI_RESOURCESTABLEDOWN_SRC = "JmakiResourcesTableDown"; //NOI18N
0146: public static final String JMAKI_RESOURCESTABLE_DEST = "rtable"; //NOI18N
0147: public static final String JMAKI_RESOURCESTABLEUP_DEST = "rtableUp"; //NOI18N
0148: public static final String JMAKI_RESOURCESTABLEDOWN_DEST = "rtableDown"; //NOI18N
0149: public static final String JMAKI_README_TEMPLATE = "Templates/WebServices/JmakiReadme.html"; //NOI18N
0150: public static final String JMAKI_COMPONENTCSS_TEMPLATE = "Templates/WebServices/JmakiComponent.css"; //NOI18N
0151: public static final String JMAKI_COMPONENTHTM_TEMPLATE = "Templates/WebServices/JmakiComponent.htm"; //NOI18N
0152: public static final String JMAKI_COMPONENTJS_TEMPLATE = "Templates/WebServices/JmakiComponent.js"; //NOI18N
0153: public static final String JMAKI_RESTBUNDLE_TEMPLATE = "Templates/WebServices/JmakiRestBundle.properties"; //NOI18N
0154: public static final String JMAKI_TEMPLATESBUNDLE_TEMPLATE = "Templates/WebServices/JmakiTemplatesBundle.properties"; //NOI18N
0155: public static final String JMAKI_TEMPLATESEJS_TEMPLATE = "Templates/WebServices/JmakiTemplates.ejs"; //NOI18N
0156: public static final String JMAKI_TEMPLATESJSP_TEMPLATE = "Templates/WebServices/JmakiTemplates.jsp"; //NOI18N
0157: public static final String JMAKI_TEMPLATESPHP_TEMPLATE = "Templates/WebServices/JmakiTemplates.php"; //NOI18N
0158: public static final String JMAKI_TEMPLATESRHTML_TEMPLATE = "Templates/WebServices/JmakiTemplates.rhtml"; //NOI18N
0159: public static final String JMAKI_TESTRESOURCESTABLE_TEMPLATE = "Templates/WebServices/JmakiTestResourcesTable.jsp"; //NOI18N
0160: public static final String JMAKI_WIDGETJSON_TEMPLATE = "Templates/WebServices/JmakiWidget.json"; //NOI18N
0161:
0162: private FileObject root;
0163: private Project p;
0164: private boolean createJmaki;
0165: private boolean overwrite;
0166: private String projectName;
0167: private ClientStubModel model;
0168: private FileObject resourcesDir;
0169: private FileObject dojoDir;
0170: private FileObject restDir;
0171: private FileObject rdjDir;
0172: private FileObject dataDir;
0173: private FileObject rjsDir;
0174: private FileObject templatesDir;
0175: private String includeJs = "";
0176: private String libsJs = "";
0177: private String resourcesDojo = "";
0178: private String requireDojo = "";
0179: protected String dojoResSelList = "";
0180: protected String jmakiResSelList = "";
0181: protected String jmakiResTagList = "";
0182: private static final int READ_BUF_SIZE = 65536;
0183: private static final int WRITE_BUF_SIZE = 65536;
0184: private FileObject wadlFile;
0185:
0186: public ClientStubsGenerator(FileObject root, Project p,
0187: boolean createJmaki, boolean overwrite) throws IOException {
0188: assert root != null;
0189: assert p != null;
0190: this .root = root;
0191: this .p = p;
0192: this .createJmaki = createJmaki;
0193: this .overwrite = overwrite;
0194: this .projectName = ProjectUtils.getInformation(getProject())
0195: .getName();
0196: }
0197:
0198: public ClientStubsGenerator(FileObject root, String folderName,
0199: Project p, boolean createJmaki, boolean overwrite)
0200: throws IOException {
0201: assert root != null;
0202: assert p != null;
0203: this .root = root.getFileObject(folderName);
0204: if (this .root == null)
0205: this .root = root.createFolder(folderName);
0206: this .p = p;
0207: this .createJmaki = createJmaki;
0208: this .overwrite = overwrite;
0209: this .projectName = ProjectUtils.getInformation(getProject())
0210: .getName();
0211: }
0212:
0213: public ClientStubsGenerator(FileObject root, String folderName,
0214: FileObject wadlFile, boolean createJmaki, boolean overwrite)
0215: throws IOException {
0216: assert root != null;
0217: assert wadlFile != null;
0218: this .root = root.getFileObject(folderName);
0219: if (this .root == null)
0220: this .root = root.createFolder(folderName);
0221: this .wadlFile = wadlFile;
0222: this .createJmaki = createJmaki;
0223: this .overwrite = overwrite;
0224: this .projectName = "NewProject";
0225: }
0226:
0227: public FileObject getRootDir() {
0228: return root;
0229: }
0230:
0231: public Project getProject() {
0232: return p;
0233: }
0234:
0235: public boolean canOverwrite() {
0236: return overwrite;
0237: }
0238:
0239: public boolean createJmaki() {
0240: return createJmaki;
0241: }
0242:
0243: public String getProjectName() {
0244: return projectName;
0245: }
0246:
0247: public ClientStubModel getModel() {
0248: return model;
0249: }
0250:
0251: public Set<FileObject> generate(ProgressHandle pHandle)
0252: throws IOException {
0253: if (pHandle != null)
0254: initProgressReporting(pHandle, false);
0255:
0256: this .model = new ClientStubModel();
0257: if (p != null)
0258: this .model.buildModel(p);
0259: else if (wadlFile != null) {
0260: String appName = this .model.buildModel(wadlFile);
0261: if (appName != null)
0262: this .projectName = appName;
0263: }
0264: List<Resource> resourceList = model.getResources();
0265:
0266: includeJs = " " + RDJ + ".includeJS('../" + RJS + "/"
0267: + getProjectName().toLowerCase() + "/"
0268: + getProjectName() + "." + JS + "');\n";
0269: libsJs = " '../" + RJS + "/"
0270: + getProjectName().toLowerCase() + "/"
0271: + getProjectName() + "." + JS + "',\n";
0272: ;
0273: resourcesDojo = "";
0274: requireDojo = "";
0275: //Prepare include list
0276: for (Resource r : resourceList) {
0277: includeJs += " " + RDJ + ".includeJS('../" + RJS + "/"
0278: + getProjectName().toLowerCase() + "/"
0279: + r.getName() + "." + JS + "');\n";
0280: libsJs += " '../" + RJS + "/"
0281: + getProjectName().toLowerCase() + "/"
0282: + r.getName() + "." + JS + "',\n";
0283: if (r.isContainer()) {
0284: resourcesDojo += " '../" + RDJ + "/"
0285: + DATA + "/" + r.getName() + STORE + "." + JS
0286: + "',\n";
0287: requireDojo += DJD43 + ".require(\"" + RDJ + "." + DATA
0288: + "." + r.getName() + STORE + "\");\n";
0289: }
0290: }
0291:
0292: if (createJmaki()) {
0293: resourcesDir = getRootDir();
0294: dojoDir = createFolder(resourcesDir, DOJO);
0295: restDir = createFolder(dojoDir, REST);
0296: rjsDir = createFolder(restDir, RJS);
0297: rdjDir = createFolder(restDir, RDJ);
0298: templatesDir = createFolder(getRootDir().getParent(),
0299: TEMPLATES);
0300: initJs(p);
0301: initDojo(p, resourceList);
0302: initJmaki(p, resourceList);
0303: } else {
0304: rjsDir = createFolder(getRootDir().getParent(), REST);
0305: initJs(p);
0306: }
0307:
0308: FileObject prjStubDir = createFolder(rjsDir, getProjectName()
0309: .toLowerCase());
0310: createDataObjectFromTemplate(JS_PROJECTSTUB_TEMPLATE,
0311: prjStubDir, getProjectName(), JS, canOverwrite());
0312: updateProjectStub(prjStubDir
0313: .getFileObject(getProjectName(), JS), getProjectName(),
0314: "");
0315:
0316: for (Resource r : resourceList) {
0317: if (pHandle != null)
0318: reportProgress(NbBundle.getMessage(
0319: ClientStubsGenerator.class,
0320: "MSG_GeneratingClass", r.getName(), JS));
0321: FileObject fo = new ResourceJavaScript(r, prjStubDir)
0322: .generate();
0323:
0324: //Generate the resource dojo and jmaki script
0325: if (createJmaki()) {
0326: new ResourceDojoComponents(r, rdjDir).generate();
0327: new ResourceJmakiComponent(r, restDir).generate();
0328: File dir = new File(FileUtil.toFile(templatesDir), DOJO
0329: + File.separator + REST);
0330: dir.mkdirs();
0331: new ResourceJmakiTemplate(r, FileUtil.toFileObject(dir))
0332: .generate();
0333: }
0334: }
0335: updateRestStub(rjsDir.getFileObject(JS_TESTSTUBS, HTML),
0336: resourceList, "");
0337:
0338: Set<FileObject> files = new HashSet<FileObject>();
0339: if (createJmaki()) {
0340: //copy dojo libs
0341: if (pHandle != null)
0342: reportProgress(NbBundle.getMessage(
0343: ClientStubsGenerator.class, "MSG_CopyLibs",
0344: DJD43, JS));//NoI18n
0345: copyDojoLibs();
0346:
0347: // Create the ZIP file
0348: if (pHandle != null)
0349: reportProgress(NbBundle.getMessage(
0350: ClientStubsGenerator.class,
0351: "MSG_GeneratingZip", getProjectName(), "zip"));
0352: File projectDir = FileUtil.toFile(resourcesDir.getParent()
0353: .getParent());
0354: File dojoLibs = FileUtil.toFile(dojoDir
0355: .getFileObject(RESOURCES));
0356: File zipFile = new File(projectDir, getProjectName()
0357: + ".zip");
0358: String[] sources = {
0359: FileUtil.toFile(restDir).getAbsolutePath(),
0360: FileUtil.toFile(templatesDir).getAbsolutePath(),
0361: FileUtil.toFile(resourcesDir.getParent())
0362: .getAbsolutePath()
0363: + File.separator
0364: + BUNDLE
0365: + "."
0366: + PROPERTIES, dojoLibs.getAbsolutePath() };
0367: String[] paths = {
0368: File.separator + RESOURCES + File.separator + DOJO,
0369: "", "",
0370: File.separator + RESOURCES + File.separator + DOJO };
0371: zip(zipFile, sources, paths);
0372:
0373: FileObject testFile = restDir.getFileObject(
0374: JMAKI_TESTRESOURCESTABLE, JSP);
0375: if (testFile != null) {
0376: files.add(testFile);
0377: }
0378: FileObject readme = restDir.getFileObject(JMAKI_README,
0379: HTML);
0380: if (readme != null)
0381: files.add(readme);
0382: } else {
0383: FileObject rjsTest = rjsDir.getFileObject(JS_TESTSTUBS,
0384: HTML);
0385: if (rjsTest != null)
0386: files.add(rjsTest);
0387: FileObject readme = rjsDir.getFileObject(JS_README, HTML);
0388: if (readme != null)
0389: files.add(readme);
0390: }
0391:
0392: return files;
0393: }
0394:
0395: private FileObject rF0 = null;
0396:
0397: private FileObject createDataObjectFromTemplate(
0398: final String template, final FileObject dir,
0399: final String fileName, final String ext,
0400: final boolean overwrite) throws IOException {
0401: FileSystem targetFS = dir.getFileSystem();
0402: targetFS.runAtomicAction(new FileSystem.AtomicAction() {
0403: public void run() throws IOException {
0404: try {
0405: rF0 = dir.getFileObject(fileName, ext);
0406: if (rF0 != null) {
0407: if (overwrite) {
0408: rF0.delete();
0409: } else {
0410: return;
0411: }
0412: }
0413: DataObject d0 = RestUtils
0414: .createDataObjectFromTemplate(template,
0415: dir, fileName);
0416: rF0 = d0.getPrimaryFile();
0417: } finally {
0418: }
0419: }
0420: });
0421: return rF0;
0422: }
0423:
0424: private void copyDojoLibs() throws FileNotFoundException,
0425: IOException {
0426: String userPath = System.getProperty("netbeans.user");
0427: if (userPath == null || userPath.length() == 0) {
0428: throw new RuntimeException(
0429: "Cannot locate netbeans user folder.");
0430: }
0431:
0432: File userDir = new File(userPath);
0433: if (!userDir.exists()) {
0434: throw new RuntimeException("NetBeans user folder ("
0435: + userDir.getPath() + ") does not exist.");
0436: }
0437:
0438: File jmakiCompDir = new File(userDir, JMAKI_COMP_LIB);
0439: if (!jmakiCompDir.exists()) {
0440: throw new RuntimeException(
0441: "Cannot find jMaki component folder ("
0442: + jmakiCompDir + ").");
0443: }
0444:
0445: File dojoLib = findDojoLibrary(jmakiCompDir);
0446: if (dojoLib != null) {
0447: unzip(new FileInputStream(dojoLib), resourcesDir
0448: .getParent(), canOverwrite());
0449: } else {
0450: File src = new File(jmakiCompDir, RESOURCES
0451: + File.separator + DOJO + File.separator
0452: + RESOURCES);
0453: File dst = FileUtil.toFile(dojoDir);
0454: FileSystem fs = FileUtil.toFileObject(dst).getFileSystem();
0455: copyDirectory(fs, src, dst);
0456: }
0457: if (dojoDir.getFileObject(RESOURCES) == null)
0458: throw new IOException("Copying dojo libs from :"
0459: + jmakiCompDir.getAbsolutePath() + " to "
0460: + resourcesDir.getParent() + " failed.");
0461: }
0462:
0463: private File findDojoLibrary(File jmakiCompDir) {
0464: File dojoLib = null;
0465: FilenameFilter filter = new FilenameFilter() {
0466: public boolean accept(File dir, String name) {
0467: if (name != null && name.startsWith("jmaki-dojo")
0468: && name.endsWith(".zip"))
0469: return true;
0470: else
0471: return false;
0472: }
0473: };
0474: File[] dojoLibs = jmakiCompDir.listFiles(filter);
0475: if (dojoLibs != null && dojoLibs.length > 0)
0476: dojoLib = dojoLibs[0];
0477: return dojoLib;
0478: }
0479:
0480: public void copyDirectory(final FileSystem fs, final File src,
0481: final File dst) throws IOException {
0482: if (src.isDirectory()) {
0483: if (!dst.exists()) {
0484: dst.mkdir();
0485: }
0486: String files[] = src.list();
0487: for (int i = 0; i < files.length; i++) {
0488: copyDirectory(fs, new File(src, files[i]), new File(
0489: dst, files[i]));
0490: }
0491: } else {
0492: if (!src.exists()) {
0493: throw new IOException(
0494: "File or directory does not exist.");
0495: } else {
0496: fs.runAtomicAction(new FileSystem.AtomicAction() {
0497: public void run() throws IOException {
0498: InputStream in = new FileInputStream(src);
0499: OutputStream out = new FileOutputStream(dst);
0500: try {
0501: byte[] buf = new byte[1024];
0502: int len;
0503: while ((len = in.read(buf)) > 0) {
0504: out.write(buf, 0, len);
0505: }
0506: } finally {
0507: in.close();
0508: out.close();
0509: }
0510: }
0511: });
0512: }
0513: }
0514: }
0515:
0516: private void initJs(Project p) throws IOException {
0517: createDataObjectFromTemplate(JS_TESTSTUBS_TEMPLATE, rjsDir,
0518: JS_TESTSTUBS, HTML, false);
0519: createDataObjectFromTemplate(JS_STUBSUPPORT_TEMPLATE, rjsDir,
0520: JS_SUPPORT, JS, canOverwrite());
0521: createDataObjectFromTemplate(JS_README_TEMPLATE, rjsDir,
0522: JS_README, HTML, canOverwrite());
0523: }
0524:
0525: private void initDojo(Project p, List<Resource> resourceList)
0526: throws IOException {
0527: dataDir = createFolder(rdjDir, DATA);//NoI18n
0528: FileObject widgetDir = createFolder(rdjDir, WIDGET);//NoI18n
0529: Resource c = null;
0530: for (Resource r : resourceList) {
0531: if (r.isContainer()) {
0532: c = r;
0533: break;
0534: }
0535: }
0536:
0537: dojoResSelList = createDojoResourceSelectList(resourceList);
0538: jmakiResSelList = createJmakiResourceSelectList(resourceList);
0539: jmakiResTagList = createJmakiResourceTagList(resourceList);
0540:
0541: createDataObjectFromTemplate(DOJO_RESOURCESTABLE_TEMPLATE,
0542: widgetDir, DOJO_RESOURCESTABLE, JS, canOverwrite());
0543: FileObject fo = createDataObjectFromTemplate(
0544: DOJO_SUPPORT_TEMPLATE, rdjDir, DOJO_SUPPORT, JS, false);
0545: if (c != null)
0546: new ResourceDojoComponents(c, rdjDir).replaceTokens(fo);
0547:
0548: fo = createDataObjectFromTemplate(
0549: DOJO_TESTRESOURCESTABLE_TEMPLATE, rdjDir,
0550: DOJO_TESTRESOURCESTABLE, HTML, false);
0551: if (c != null)
0552: new ResourceDojoComponents(c, rdjDir).replaceTokens(fo);
0553: }
0554:
0555: private void initJmaki(Project p, List<Resource> resourceList)
0556: throws IOException {
0557: createDataObjectFromTemplate(JMAKI_README_TEMPLATE, restDir,
0558: JMAKI_README, HTML, canOverwrite());
0559: createDataObjectFromTemplate(JMAKI_RESTBUNDLE_TEMPLATE,
0560: getRootDir().getParent(), BUNDLE, PROPERTIES,
0561: canOverwrite());
0562:
0563: //find first container
0564: Resource c = null;
0565: for (Resource r : resourceList) {
0566: if (r.isContainer()) {
0567: c = r;
0568: break;
0569: }
0570: }
0571: FileObject fo = createDataObjectFromTemplate(
0572: JMAKI_TESTRESOURCESTABLE_TEMPLATE, restDir,
0573: JMAKI_TESTRESOURCESTABLE, JSP, false);
0574: if (c != null)
0575: new ResourceDojoComponents(c, restDir).replaceTokens(fo);
0576: }
0577:
0578: protected String createDojoResourceSelectList(
0579: List<Resource> resourceList) {
0580: String str = "";
0581: for (Resource r : resourceList) {
0582: if (r.isContainer()) {
0583: str += " <option value='http://localhost:8080/"
0584: + getProjectName()
0585: + "/resources/"
0586: + r.getRepresentation().getRoot().getName()
0587: + "/;"
0588: + r.getName()
0589: + "'>"
0590: + r.getName()
0591: + "</option>\n";
0592: }
0593: }
0594: return str;
0595: }
0596:
0597: protected String createJmakiResourceSelectList(
0598: List<Resource> resourceList) {
0599: String str = "";
0600: for (Resource r : resourceList) {
0601: if (r.isContainer()) {
0602: str += " <option value='" + r.getName()
0603: + "' <%=p.equals(\"" + r.getName()
0604: + "\")?\"selected\":\"\"%>>" + r.getName()
0605: + "</option>\n";
0606: }
0607: }
0608: return str;
0609: }
0610:
0611: protected String createJmakiResourceTagList(
0612: List<Resource> resourceList) {
0613: String str = "";
0614: int count = 0;
0615: for (Resource r : resourceList) {
0616: if (r.isContainer()) {
0617: String name = r.getName();
0618: String pathName = r.getRepresentation().getRoot()
0619: .getName();
0620: if (count++ == 0) {
0621: str += " <% if(p.equals(\""
0622: + name
0623: + "\")) {%>\n"
0624: + " <a:widget name=\"dojo.rest."
0625: + pathName
0626: + "table\" service=\"http://localhost:8080/"
0627: + getProjectName() + "/resources/"
0628: + pathName + "/\" />\n";
0629: } else {
0630: str += " <% } else if(p.equals(\""
0631: + name
0632: + "\")) {%>\n"
0633: + " <a:widget name=\"dojo.rest."
0634: + pathName
0635: + "table\" service=\"http://localhost:8080/"
0636: + getProjectName() + "/resources/"
0637: + pathName + "/\" />\n";
0638: }
0639: }
0640: }
0641: str += "<% }%>";
0642: return str;
0643: }
0644:
0645: /*
0646: * Copy File only
0647: */
0648: private void copyFile(String resourceName, File destFile)
0649: throws IOException {
0650: String path = "resources/" + resourceName;
0651: if (!destFile.exists()) {
0652: InputStream is = null;
0653: OutputStream os = null;
0654: try {
0655: is = ClientStubsGenerator.class
0656: .getResourceAsStream(path);
0657: os = new FileOutputStream(destFile);
0658: int c;
0659: while ((c = is.read()) != -1) {
0660: os.write(c);
0661: }
0662: } finally {
0663: if (os != null) {
0664: os.flush();
0665: os.close();
0666: }
0667: if (is != null)
0668: is.close();
0669: }
0670: }
0671: }
0672:
0673: private FileObject createFolder(FileObject parent, String folderName)
0674: throws IOException {
0675: FileObject folder = parent.getFileObject(folderName);
0676: if (folder == null)
0677: folder = parent.createFolder(folderName);
0678: return folder;
0679: }
0680:
0681: private static void zip(File zipFile, String[] sources,
0682: String[] paths) {
0683: try {
0684:
0685: FileOutputStream dest = new FileOutputStream(zipFile);
0686: ZipOutputStream out = new ZipOutputStream(
0687: new BufferedOutputStream(dest));
0688:
0689: for (int i = 0; i < sources.length; i++) {
0690: File f = new File(sources[i]);
0691: addEntry(f, paths[i], out);
0692: }
0693: out.close();
0694: } catch (Exception e) {
0695: e.printStackTrace();
0696: }
0697: }
0698:
0699: private static void addEntry(File file, String path,
0700: ZipOutputStream out) throws FileNotFoundException,
0701: IOException {
0702: if (file.isDirectory()) {
0703: String[] files = file.list();
0704: for (int i = 0; i < files.length; i++) {
0705: File f = new File(file + File.separator + files[i]);
0706: addEntry(f, path + File.separator + file.getName(), out);
0707: }
0708: } else {
0709: byte[] data = new byte[WRITE_BUF_SIZE];
0710: BufferedInputStream origin = null;
0711: //System.out.println("Adding: " + file);
0712: FileInputStream fi = new FileInputStream(file);
0713: origin = new BufferedInputStream(fi, READ_BUF_SIZE);
0714: ZipEntry entry = new ZipEntry(path + File.separator
0715: + file.getName());
0716: out.putNextEntry(entry);
0717: int count;
0718: while ((count = origin.read(data, 0, WRITE_BUF_SIZE)) != -1) {
0719: out.write(data, 0, count);
0720: }
0721: origin.close();
0722: }
0723: }
0724:
0725: private static boolean unzip(final InputStream source,
0726: final FileObject targetFolderFO, boolean overwrite)
0727: throws IOException {
0728: boolean result = true;
0729: FileSystem targetFS = targetFolderFO.getFileSystem();
0730: File targetFolder = FileUtil.toFile(targetFolderFO);
0731: ZipInputStream zip = null;
0732: try {
0733: final byte[] buffer = new byte[WRITE_BUF_SIZE];
0734: zip = new ZipInputStream(new BufferedInputStream(source,
0735: READ_BUF_SIZE));
0736: final InputStream in = zip;
0737: ZipEntry entry;
0738: while ((entry = zip.getNextEntry()) != null) {
0739: if (!(entry.getName().startsWith(
0740: RESOURCES + "/" + DOJO + "/" + RESOURCES + "/"
0741: + LIBS) || entry.getName().startsWith(
0742: RESOURCES + File.separator + DOJO
0743: + File.separator + RESOURCES
0744: + File.separator + LIBS))) {
0745: continue;
0746: }
0747: final File entryFile = new File(targetFolder, entry
0748: .getName());
0749: if (entry.isDirectory()) {
0750: if (!entryFile.exists() && !entryFile.mkdirs()) {
0751: throw new RuntimeException(
0752: "Failed to create folder: "
0753: + entryFile.getName()
0754: + ". Terminating archive installation.");
0755: }
0756: } else {
0757: if (entryFile.exists() && overwrite) {
0758: if (!entryFile.delete()) {
0759: throw new RuntimeException(
0760: "Failed to delete file: "
0761: + entryFile.getName()
0762: + ". Terminating archive installation.");
0763: }
0764: }
0765: File parentFile = entryFile.getParentFile();
0766: if (!parentFile.exists() && !parentFile.mkdirs()) {
0767: throw new RuntimeException(
0768: "Failed to create folder: "
0769: + parentFile.getName()
0770: + ". Terminating archive installation.");
0771: }
0772: targetFS
0773: .runAtomicAction(new FileSystem.AtomicAction() {
0774: public void run() throws IOException {
0775: FileOutputStream os = null;
0776: try {
0777: os = new FileOutputStream(
0778: entryFile);
0779: int len;
0780: while ((len = in.read(buffer)) >= 0) {
0781: os.write(buffer, 0, len);
0782: }
0783: } finally {
0784: if (os != null) {
0785: try {
0786: os.close();
0787: } catch (IOException ex) {
0788: }
0789: }
0790: }
0791: }
0792: });
0793: }
0794: }
0795: } finally {
0796: if (zip != null) {
0797: try {
0798: zip.close();
0799: } catch (IOException ex) {
0800: }
0801: }
0802: }
0803:
0804: return result;
0805: }
0806:
0807: private void updateProjectStub(FileObject projectStub,
0808: String prjName, String pkg) throws IOException {
0809: FileLock lock = projectStub.lock();
0810: try {
0811: BufferedReader reader = new BufferedReader(new FileReader(
0812: FileUtil.toFile(projectStub)));
0813: String line;
0814: StringBuffer sb = new StringBuffer();
0815: while ((line = reader.readLine()) != null) {
0816: if (line.contains("__BASE_URL__")) {
0817: sb.append(line.replaceAll("__BASE_URL__",
0818: "http://localhost:8080/" + prjName
0819: + "/resources"));
0820: } else if (line.contains("__PROJECT_NAME__")) {
0821: sb.append(line.replaceAll("__PROJECT_NAME__",
0822: prjName));
0823: } else if (line.contains("__PROJECT_INIT_BODY__")) {
0824: String initBody = "";
0825: int count = 0;
0826: List<Resource> resourceList = model.getResources();
0827: for (Resource r : resourceList) {
0828: if (r.isContainer()) {
0829: initBody += " this.resources["
0830: + count++ + "] = new " + pkg
0831: + r.getName() + "(this.uri+'"
0832: + r.getPath() + "');\n";
0833: }
0834: }
0835: sb.append(initBody);
0836: } else {
0837: sb.append(line);
0838: }
0839: sb.append("\n");
0840: }
0841: OutputStreamWriter writer = new OutputStreamWriter(
0842: projectStub.getOutputStream(lock), "UTF-8");
0843: try {
0844: writer.write(sb.toString());
0845: } finally {
0846: writer.close();
0847: }
0848: } finally {
0849: lock.releaseLock();
0850: }
0851: }
0852:
0853: private void updateRestStub(FileObject restStub,
0854: List<Resource> resourceList, String pkg) throws IOException {
0855: String prjName = getProjectName();
0856: String prjStubDir = prjName.toLowerCase();
0857: StringBuffer sb1 = new StringBuffer();
0858: sb1.append("\t<script type='text/javascript' src='./"
0859: + prjStubDir + "/" + prjName + "." + JS
0860: + "'></script>\n");
0861: for (Resource r : resourceList) {
0862: sb1.append("\t<script type='text/javascript' src='./"
0863: + prjStubDir + "/" + r.getName() + "." + JS
0864: + "'></script>\n");
0865: }
0866: StringBuffer sb2 = new StringBuffer();
0867: sb2.append("\n\t<!-- Using JavaScript files for project "
0868: + prjName + "-->\n");
0869: sb2.append("\t<script language='Javascript'>\n");
0870: sb2.append("\t\tvar str = '';\n");
0871: sb2.append("\t\t//Example test code for " + prjName + "\n");
0872: sb2.append("\t\tstr = '<h2>Resources for " + prjName
0873: + ":</h2><br><table border=\"1\">';\n");
0874: sb2.append("\t\tvar app = new " + pkg + prjName + "();\n");
0875: sb2.append("\t\tvar resources = app.getResources();\n");
0876: sb2.append("\t\tfor(i=0;i<resources.length;i++) {\n");
0877: sb2.append("\t\t var resource = resources[i];\n");
0878: sb2.append("\t\t var uri = resource.getUri();\n");
0879: sb2
0880: .append("\t\t str += '<tr><td valign=\"top\"><a href=\"'+uri+'\" target=\"_blank\">'+uri+'</a></td><td>';\n");
0881: sb2.append("\t\t var items = resource.getItems();\n");
0882: sb2.append("\t\t if(items != undefined) {\n");
0883: sb2.append("\t\t for(j=0;j<items.length;j++) {\n");
0884: sb2.append("\t\t var item = items[j];\n");
0885: sb2.append("\t\t var uri2 = item.getUri();\n");
0886: sb2
0887: .append("\t\t str += '<a href=\"'+uri2+'\" target=\"_blank\">'+uri2+'</a><br/>';\n");
0888: sb2
0889: .append("\t\t str += ' <font size=\"-3\">'+item.toString()+'</font><br/>';\n");
0890: sb2.append("\t\t }\n");
0891: sb2.append("\t\t }\n");
0892: sb2.append("\t\t str += '</td></tr>';\n");
0893: sb2.append("\t\t}\n");
0894: sb2.append("\t\tstr += '</table><br>';\n");
0895: sb2
0896: .append("\t\tvar n = document.getElementById('containerContent');\n");
0897: sb2.append("\t\tn.innerHTML = n.innerHTML + str;\n\n");
0898: sb2.append("\t</script>\n");
0899: FileLock lock = restStub.lock();
0900: try {
0901: BufferedReader reader = new BufferedReader(new FileReader(
0902: FileUtil.toFile(restStub)));
0903: String line;
0904: StringBuffer sb = new StringBuffer();
0905: while ((line = reader.readLine()) != null) {
0906: if (line.contains("JS_DECLARE_END")) {
0907: sb.append(sb1.toString());
0908: } else if (line.contains("JS_USAGE_END")) {
0909: sb.append(sb2.toString());
0910: }
0911: sb.append(line);
0912: sb.append("\n");
0913: }
0914: OutputStreamWriter writer = new OutputStreamWriter(restStub
0915: .getOutputStream(lock), "UTF-8");
0916: try {
0917: writer.write(sb.toString());
0918: } finally {
0919: writer.close();
0920: }
0921: } finally {
0922: lock.releaseLock();
0923: }
0924: }
0925:
0926: public class ResourceJavaScript {
0927:
0928: protected Resource r;
0929: protected FileObject jsFolder;
0930:
0931: public ResourceJavaScript(Resource r, FileObject jsFolder) {
0932: this .r = r;
0933: this .jsFolder = jsFolder;
0934: }
0935:
0936: public FileObject getFolder() {
0937: return jsFolder;
0938: }
0939:
0940: public FileObject generate() throws IOException {
0941: String fileName = r.getName();
0942: String fileNameExt = r.getName() + "." + JS;
0943: FileObject fo = jsFolder.getFileObject(fileNameExt);
0944: if (fo != null) {
0945: if (canOverwrite()) {
0946: fo.delete();
0947: } else {
0948: Logger.getLogger(this .getClass().getName()).log(
0949: Level.INFO,
0950: NbBundle.getMessage(
0951: ClientStubsGenerator.class,
0952: "MSG_SkippingStubGeneration",
0953: jsFolder.getPath() + File.separator
0954: + fileNameExt));
0955: }
0956: }
0957:
0958: if (r.isContainer())
0959: createDataObjectFromTemplate(JS_CONTAINERSTUB_TEMPLATE,
0960: jsFolder, fileName, JS, canOverwrite());
0961: else if (r.getRepresentation().getRoot() != null)
0962: createDataObjectFromTemplate(
0963: JS_CONTAINERITEMSTUB_TEMPLATE, jsFolder,
0964: fileName, JS, canOverwrite());
0965: else
0966: //generate only stub for no representation
0967: createDataObjectFromTemplate(JS_GENERICSTUB_TEMPLATE,
0968: jsFolder, fileName, JS, canOverwrite());
0969: fo = jsFolder.getFileObject(fileNameExt);
0970: replaceTokens(fo);
0971: return fo;
0972: }
0973:
0974: protected void replaceTokens(FileObject fo) throws IOException {
0975: FileLock lock = fo.lock();
0976: try {
0977: BufferedReader reader = new BufferedReader(
0978: new FileReader(FileUtil.toFile(fo)));
0979: String line;
0980: StringBuffer sb = new StringBuffer();
0981: while ((line = reader.readLine()) != null) {
0982: line = replaceTokens(line, "", "");
0983: sb.append(line);
0984: sb.append("\n");
0985: }
0986: OutputStreamWriter writer = new OutputStreamWriter(fo
0987: .getOutputStream(lock), "UTF-8");
0988: try {
0989: writer.write(sb.toString());
0990: } finally {
0991: writer.close();
0992: }
0993: } finally {
0994: lock.releaseLock();
0995: }
0996: }
0997:
0998: protected String replaceTokens(String line, String object,
0999: String pkg) {
1000: RepresentationNode root = r.getRepresentation().getRoot();
1001: String replacedLine = line;
1002: String[] containerStubTokens = { "__CONTAINER_NAME__",
1003: "__CONTAINER_PATH_NAME__",
1004: "__CONTAINER_ITEM_NAME__",
1005: "__CONTAINER_ITEM_PATH_NAME__", "__STUB_METHODS__",
1006: "__PROJECT_NAME__",
1007: "<!-- __DOJO_RESOURCE_SELECT_LIST__ -->",
1008: "<!-- __JMAKI_RESOURCE_SELECT_LIST__ -->",
1009: "<!-- __JMAKI_RESOURCE_TAG_LIST__ -->" };
1010: String[] genericStubTokens = { "__GENERIC_NAME__",
1011: "__GENERIC_PATH_NAME__", "__FIELDS_DEFINITION__",
1012: "__GETTER_SETTER_METHODS__", "__FIELDS_INIT__",
1013: "__SUB_RESOURCE_NAME__",
1014: "__SUB_RESOURCE_PATH_NAME__",
1015: "__FIELDS_TOSTRING__", "__FIELD_NAMES_TOSTRING__",
1016: "__STUB_METHODS__" };
1017: String[] stubOnlyTokens = { "__RESOURCE_NAME__",
1018: "__STUB_METHODS__" };
1019: if (r.isContainer() && root != null) {
1020: String containerName = r.getName();
1021: String containerRepName = root.getName();
1022: //TODO
1023: String containerItemRepName = root.getChildren().get(0)
1024: .getName();
1025: if (containerItemRepName.indexOf("Ref") != -1)
1026: containerItemRepName = containerItemRepName
1027: .substring(0, containerItemRepName
1028: .indexOf("Ref"));
1029: String containerItemName = containerItemRepName
1030: .substring(0, 1).toUpperCase()
1031: + containerItemRepName.substring(1);
1032: for (String token : containerStubTokens) {
1033: if ("__CONTAINER_NAME__".equals(token))
1034: replacedLine = replacedLine.replaceAll(
1035: "__CONTAINER_NAME__", containerName);
1036: else if ("__CONTAINER_PATH_NAME__".equals(token))
1037: replacedLine = replacedLine.replaceAll(
1038: "__CONTAINER_PATH_NAME__",
1039: containerRepName);
1040: else if ("__CONTAINER_ITEM_NAME__".equals(token))
1041: replacedLine = replacedLine.replaceAll(
1042: "__CONTAINER_ITEM_NAME__",
1043: containerItemName);
1044: else if ("__CONTAINER_ITEM_PATH_NAME__"
1045: .equals(token))
1046: replacedLine = replacedLine.replaceAll(
1047: "__CONTAINER_ITEM_PATH_NAME__",
1048: containerItemRepName);
1049: else if ("__STUB_METHODS__".equals(token))
1050: replacedLine = replacedLine.replace(
1051: "__STUB_METHODS__",
1052: createStubJSMethods(r, object, pkg));
1053: else if ("__PROJECT_NAME__".equals(token))
1054: replacedLine = replacedLine.replaceAll(
1055: "__PROJECT_NAME__", getProjectName());
1056: else if ("<!-- __DOJO_RESOURCE_SELECT_LIST__ -->"
1057: .equals(token))
1058: replacedLine = replacedLine
1059: .replaceAll(
1060: "<!-- __DOJO_RESOURCE_SELECT_LIST__ -->",
1061: dojoResSelList
1062: + "\n<!-- __DOJO_RESOURCE_SELECT_LIST__ -->");
1063: else if ("<!-- __JMAKI_RESOURCE_SELECT_LIST__ -->"
1064: .equals(token))
1065: replacedLine = replacedLine
1066: .replaceAll(
1067: "<!-- __JMAKI_RESOURCE_SELECT_LIST__ -->",
1068: jmakiResSelList
1069: + "\n<!-- __JMAKI_RESOURCE_SELECT_LIST__ -->");
1070: else if ("<!-- __JMAKI_RESOURCE_TAG_LIST__ -->"
1071: .equals(token))
1072: replacedLine = replacedLine
1073: .replaceAll(
1074: "<!-- __JMAKI_RESOURCE_TAG_LIST__ -->",
1075: jmakiResTagList
1076: + "\n<!-- __JMAKI_RESOURCE_TAG_LIST__ -->");
1077: }
1078: } else if (root != null) {
1079: String resourceName = r.getName();
1080: String resourceRepName = root.getName();
1081: for (String token : genericStubTokens) {
1082: if ("__GENERIC_NAME__".equals(token)) {
1083: replacedLine = replacedLine.replaceAll(
1084: "__GENERIC_NAME__", resourceName);
1085: } else if ("__GENERIC_PATH_NAME__".equals(token)) {
1086: replacedLine = replacedLine.replaceAll(
1087: "__GENERIC_PATH_NAME__",
1088: resourceRepName);
1089: } else if ("__FIELDS_DEFINITION__".equals(token)) {
1090: replacedLine = replacedLine.replaceAll(
1091: "__FIELDS_DEFINITION__",
1092: createFieldsDefinition(root, true));
1093: } else if ("__GETTER_SETTER_METHODS__"
1094: .equals(token)) {
1095: replacedLine = replacedLine.replace(
1096: "__GETTER_SETTER_METHODS__",
1097: createGetterSetterMethods(root, true));
1098: } else if ("__FIELDS_INIT__".equals(token)) {
1099: replacedLine = replacedLine.replace(
1100: "__FIELDS_INIT__",
1101: createFieldsInitBody(root, true, pkg));
1102: } else if ("__SUB_RESOURCE_NAME__".equals(token)) {
1103: replacedLine = replacedLine.replaceAll(
1104: "__SUB_RESOURCE_NAME__", "");
1105: } else if ("__SUB_RESOURCE_PATH_NAME__"
1106: .equals(token)) {
1107: replacedLine = replacedLine.replaceAll(
1108: "__SUB_RESOURCE_PATH_NAME__", "");
1109: } else if ("__FIELDS_TOSTRING__".equals(token)) {
1110: String fieldsToString = createFieldsToStringBody(
1111: root, true);
1112: if (fieldsToString.endsWith(",'+\n"))
1113: fieldsToString = fieldsToString.substring(
1114: 0, fieldsToString.length() - 4)
1115: + "'+\n";
1116: replacedLine = replacedLine.replace(
1117: "__FIELDS_TOSTRING__", fieldsToString);
1118: } else if ("__FIELD_NAMES_TOSTRING__".equals(token)) {
1119: String fieldsToString = createFieldNamesBody(
1120: root, true);
1121: replacedLine = replacedLine.replace(
1122: "__FIELD_NAMES_TOSTRING__",
1123: fieldsToString);
1124: } else if ("__STUB_METHODS__".equals(token)) {
1125: replacedLine = replacedLine.replace(
1126: "__STUB_METHODS__",
1127: createStubJSMethods(r, object, pkg));
1128: }
1129: }
1130: } else {
1131: String resourceName = r.getName();
1132: for (String token : stubOnlyTokens) {
1133: if ("__RESOURCE_NAME__".equals(token))
1134: replacedLine = replacedLine.replaceAll(
1135: "__RESOURCE_NAME__", resourceName);
1136: else if ("__STUB_METHODS__".equals(token))
1137: replacedLine = replacedLine.replace(
1138: "__STUB_METHODS__",
1139: createStubJSMethods(r, object, pkg));
1140: }
1141: }
1142: return replacedLine;
1143: }
1144:
1145: public static final String RJSSUPPORT = "rjsSupport";
1146:
1147: protected String createStubJSMethods(Resource r, String object,
1148: String pkg) {
1149: StringBuffer sb = new StringBuffer();
1150: Method getMethod = null;
1151: for (Method m : r.getMethods()) {
1152: if (m.getType() == MethodType.GET) {
1153: getMethod = m;
1154: }
1155: }
1156: if (getMethod != null) {
1157: String defaultGetMethod = createDefaultGetMethod(
1158: getMethod, RJSSUPPORT + ".");
1159: if (defaultGetMethod != null)
1160: sb.append(defaultGetMethod + ",\n\n");
1161: }
1162: for (Method m : r.getMethods()) {
1163: sb.append(createMethod(m, RJSSUPPORT + ".", pkg)
1164: + ",\n\n");
1165: }
1166: String s = sb.toString();
1167: if (s.length() > 3)
1168: return s.substring(0, s.length() - 3) + "\n";
1169: else
1170: return s;
1171: }
1172:
1173: private String createGetterSetterMethods(
1174: RepresentationNode root, boolean skipUri) {
1175: StringBuffer sb = new StringBuffer();
1176:
1177: //create getter and setter for attributes
1178: sb.append(createGetterSetterMethods(root.getAttributes(),
1179: skipUri));
1180:
1181: //create getter and setter for elements
1182: sb.append(createGetterSetterMethods(root.getChildren(),
1183: skipUri));
1184:
1185: return sb.toString();
1186: }
1187:
1188: private String createGetterSetterMethods(
1189: List<RepresentationNode> nodes, boolean skipUri) {
1190: StringBuffer sb = new StringBuffer();
1191: for (RepresentationNode child : nodes) {
1192: String childName = child.getName();
1193: if (!(skipUri && childName.equals("uri"))) {
1194: sb.append(createGetterMethod(child) + ",\n\n");
1195: sb.append(createSetterMethod(child) + ",\n\n");
1196: }
1197: }
1198: return sb.toString();
1199: }
1200:
1201: private String createFieldsDefinition(RepresentationNode root,
1202: boolean skipUri) {
1203: StringBuffer sb = new StringBuffer();
1204: for (RepresentationNode child : root.getAttributes()) {
1205: String childName = child.getName();
1206: if (!(skipUri && childName.equals("uri")))
1207: sb.append(" this." + childName + " = '';\n");
1208: }
1209: for (RepresentationNode child : root.getChildren()) {
1210: String name = child.getName();
1211: if (child.isRoot()) {
1212: sb.append(" this." + name + " = new Array();\n");
1213: } else {
1214: sb.append(" this." + name + " = '';\n");
1215: }
1216: }
1217: return sb.toString();
1218: }
1219:
1220: private String createFieldsInitBody(RepresentationNode root,
1221: boolean skipUri, String pkg) {
1222: String repName = root.getName();
1223: StringBuffer sb = new StringBuffer();
1224: for (RepresentationNode child : root.getAttributes()) {
1225: String childName = child.getName();
1226: if (!(skipUri && childName.equals("uri")))
1227: sb.append(" this." + childName + " = "
1228: + repName + "['@" + childName + "'];\n");
1229: }
1230: for (RepresentationNode child : root.getChildren()) {
1231: String childName = child.getName();
1232: if (child.isReference() || child.isRoot()) {
1233: String childRepName = findRepresentationName(childName);
1234: sb.append(" this." + childName + " = new "
1235: + pkg + findResourceName(childName) + "("
1236: + repName + "['" + childName
1237: + "']['@uri']);\n");
1238: } else {
1239: //this.vehiclePK = this.findValue(this.vehiclePK , vehicle['vehiclePK']);
1240: sb.append(" this." + childName
1241: + " = this.findValue(this." + childName
1242: + ", " + repName + "['" + childName
1243: + "']);\n");
1244: }
1245: }
1246: return sb.toString();
1247: }
1248:
1249: private String createFieldsToStringBody(
1250: RepresentationNode root, boolean skipUri) {
1251: StringBuffer sb = new StringBuffer();
1252: for (RepresentationNode child : root.getAttributes()) {
1253: String childName = child.getName();
1254: if (!(skipUri && childName.equals("uri")))
1255: sb.append(" '\"@" + childName
1256: + "\":\"'+this." + childName + "+'\",'+\n");
1257: }
1258: for (RepresentationNode child : root.getChildren()) {
1259: String childName = child.getName();
1260: if (child.isReference()) {
1261: String childRepName = findRepresentationName(childName);
1262: if (child.isEntity()) //child is a Entity and has a non-generic converter
1263: sb
1264: .append(" '\""
1265: + childName
1266: + "\":{\"@uri\":\"'+"
1267: + "this."
1268: + childName
1269: + ".getUri()+'\", \""
1270: + childRepName
1271: + "\":"
1272: + "{\"$\":\"'+eval(\"this."
1273: + childName
1274: + ".get\"+this."
1275: + childName
1276: + ".getFields()[0].substring(0,1).toUpperCase()+this."
1277: + childName
1278: + ".getFields()[0].substring(1)+\"()\")+'\"}},'+\n");
1279: else
1280: sb.append(" '\"" + childName
1281: + "\":{\"@uri\":\"'+this." + childName
1282: + ".getUri()+'\"},'+\n");
1283: } else if (child.isRoot()) {
1284: sb.append(" this." + childName
1285: + ".toString()+','+\n");
1286: } else
1287: sb.append(" '\"" + childName
1288: + "\":{\"$\":\"'+this." + childName
1289: + "+'\"},'+\n");
1290: }
1291: return sb.toString();
1292: }
1293:
1294: private String createFieldNamesBody(RepresentationNode root,
1295: boolean skipUri) {
1296: StringBuffer sb = new StringBuffer();
1297: for (RepresentationNode child : root.getAttributes()) {
1298: String childName = child.getName();
1299: if (!(skipUri && childName.equals("uri")))
1300: sb.append(" fields.push('" + childName
1301: + "');\n");// fields.push('customerId');
1302: }
1303: for (RepresentationNode child : root.getChildren()) {
1304: String childName = child.getName();
1305: if (!(child.isReference() || child.isRoot())) {
1306: sb.append(" fields.push('" + childName
1307: + "');\n");// fields.push('customerId');
1308: }
1309: }
1310: return sb.toString();
1311: }
1312:
1313: private String findResourceName(String repName) {
1314: if (repName.contains("Ref"))
1315: repName = repName.substring(0, repName.indexOf("Ref"));
1316: return repName.substring(0, 1).toUpperCase()
1317: + repName.substring(1);
1318: }
1319:
1320: private String findRepresentationName(String repName) {
1321: if (repName.contains("Ref"))
1322: return repName.substring(0, repName.indexOf("Ref"));
1323: return repName;
1324: }
1325:
1326: private String createGetterMethod(RepresentationNode n) {
1327: String mName = RestUtils.createGetterMethodName(n);
1328: String fieldName = n.getName();
1329: return " " + mName + " : function() {\n"
1330: + " if(!this.initialized)\n"
1331: + " this.init();\n" + " return this."
1332: + fieldName + ";\n" + " }";
1333: }
1334:
1335: private String createSetterMethod(RepresentationNode n) {
1336: String mName = createSetterMethodName(n);
1337: String fieldName = n.getName();
1338: return " " + mName + " : function(" + fieldName
1339: + "_) {\n" + " this." + fieldName + " = "
1340: + fieldName + "_;\n" + " }";
1341: }
1342:
1343: private String createSetterMethodName(RepresentationNode n) {
1344: String mName = "set";
1345: if (n.getLink() != null) {
1346: mName = RestUtils.escapeJSReserved(n.getLink()
1347: .getName().toString());
1348: mName = "set" + mName.substring(3);
1349: } else {
1350: mName = n.getName();
1351: mName = "set" + mName.substring(0, 1).toUpperCase()
1352: + mName.substring(1);
1353: }
1354: return mName;
1355: }
1356:
1357: private String createMethod(Method m, final String object,
1358: String pkg) {
1359: if (m.getType() == MethodType.GET) {
1360: return createGetMethod(m, object);
1361: } else if (m.getType() == MethodType.POST) {
1362: return createPostMethod(m, object);
1363: } else if (m.getType() == MethodType.PUT) {
1364: return createPutMethod(m, object);
1365: } else if (m.getType() == MethodType.DELETE) {
1366: return createDeleteMethod(m, object);
1367: } else if (m instanceof NavigationMethod) {
1368: return createNavigationMethod((NavigationMethod) m, pkg);
1369: } else {
1370: return "";
1371: }
1372: }
1373:
1374: private String createMethodName(Method m, String mimeType,
1375: int length) {
1376: if (length > 1) {
1377: for (Constants.MimeType mime : Constants.MimeType
1378: .values())
1379: if (mime.value().equals(mimeType))
1380: return m.getName() + mime.suffix();
1381: }
1382: return m.getName();
1383: }
1384:
1385: private String createDefaultGetMethod(Method m, String object) {
1386: StringBuffer sb = new StringBuffer();
1387: String jsonMethod = null;
1388: for (Representation rep : m.getResponse()
1389: .getRepresentation()) {
1390: String mimeType = rep.getMime();
1391: mimeType = mimeType.replaceAll("\"", "").trim();
1392: if (mimeType.equals(Constants.MimeType.JSON.value()))
1393: jsonMethod = mimeType;
1394: }
1395: //Add a default getJson() method used by Container/Containee init() methods
1396: if (jsonMethod != null) {
1397: sb
1398: .append("/* Default getJson() method used by Container/Containee init() methods. Do not remove. */\n");
1399: sb.append(" getJson : function() {\n"
1400: + " return " + object + "get(this.uri, '"
1401: + jsonMethod + "');\n" + " }");
1402: }
1403: if (sb.length() > 0)
1404: return sb.toString();
1405: else
1406: return null;
1407: }
1408:
1409: private String createGetMethod(Method m, String object) {
1410: StringBuffer sb = new StringBuffer();
1411: int length = m.getResponse().getRepresentation().size();
1412: for (Representation rep : m.getResponse()
1413: .getRepresentation()) {
1414: String mimeType = rep.getMime();
1415: mimeType = mimeType.replaceAll("\"", "").trim();
1416: sb.append(" " + createMethodName(m, mimeType, length)
1417: + " : function() {\n" + " return "
1418: + object + "get(this.uri, '" + mimeType
1419: + "');\n" + " },\n\n");
1420: }
1421: String s = sb.toString();
1422: if (s.length() > 3)
1423: return s.substring(0, s.length() - 3);
1424: else
1425: return s;
1426: }
1427:
1428: private String createPostMethod(Method m, String object) {
1429: StringBuffer sb = new StringBuffer();
1430: int length = m.getRequest().getRepresentation().size();
1431: for (Representation rep : m.getRequest()
1432: .getRepresentation()) {
1433: String mimeType = rep.getMime();
1434: mimeType = mimeType.replaceAll("\"", "").trim();
1435: sb.append(" " + createMethodName(m, mimeType, length)
1436: + " : function(content) {\n" + " return "
1437: + object + "post(this.uri, '" + mimeType
1438: + "', content);\n" + " },\n\n");
1439: }
1440: String s = sb.toString();
1441: if (s.length() > 3)
1442: return s.substring(0, s.length() - 3);
1443: else
1444: return s;
1445: }
1446:
1447: private String createPutMethod(Method m, String object) {
1448: StringBuffer sb = new StringBuffer();
1449: int length = m.getRequest().getRepresentation().size();
1450: for (Representation rep : m.getRequest()
1451: .getRepresentation()) {
1452: String mimeType = rep.getMime();
1453: mimeType = mimeType.replaceAll("\"", "").trim();
1454: sb.append(" " + createMethodName(m, mimeType, length)
1455: + " : function(content) {\n" + " return "
1456: + object + "put(this.uri, '" + mimeType
1457: + "', content);\n" + " },\n\n");
1458: }
1459: String s = sb.toString();
1460: if (s.length() > 3)
1461: return s.substring(0, s.length() - 3);
1462: else
1463: return s;
1464: }
1465:
1466: private String createDeleteMethod(Method m, String object) {
1467: return " " + RestUtils.escapeJSReserved(m.getName())
1468: + " : function() {\n" + " return " + object
1469: + "delete_(this.uri);\n" + " }";
1470: }
1471:
1472: private String createNavigationMethod(NavigationMethod m,
1473: String pkg) {
1474: String s = "";
1475: String fs = "";
1476: if (m.getNavigationUri().contains(",")) {
1477: String[] ss = m.getNavigationUri().split(",");
1478: for (String s1 : ss) {
1479: if (s1.startsWith("{"))
1480: s1 = s1.substring(1);
1481: else if (s1.endsWith("}"))
1482: s1 = s1.substring(0, s1.length() - 1);
1483: s += s1 + "+','+";
1484: fs += s1 + ",";
1485: }
1486: s = s.substring(0, s.length() - 5);
1487: fs = fs.substring(0, fs.length() - 1);
1488: } else {
1489: s = m.getNavigationUri();
1490: fs = s;
1491: }
1492: return " " + m.getName() + " : function(" + fs + ") {\n"
1493: + " var link = new " + pkg + m.getLinkName()
1494: + "(this.uri+'/'+" + s + ")()\n"
1495: + " return link;\n" + " }";
1496: }
1497:
1498: }
1499:
1500: public class ResourceDojoComponents extends ResourceJavaScript {
1501:
1502: public ResourceDojoComponents(Resource r, FileObject rdjDir) {
1503: super (r, rdjDir);
1504: }
1505:
1506: public FileObject generate() throws IOException {
1507: if (r.isContainer()) {
1508: String name = r.getName();
1509: FileObject dataDir = getFolder().getFileObject(DATA);
1510: FileObject fo = createDataObjectFromTemplate(
1511: DOJO_COLLECTIONSTORE_TEMPLATE, dataDir, name
1512: + STORE, JS, canOverwrite());
1513: replaceTokens(fo);
1514: } else {
1515: return null;
1516: }
1517: return rdjDir;
1518: }
1519:
1520: protected String replaceTokens(String line, String object,
1521: String pkg) {
1522: String replacedLine = line;
1523: replacedLine = replacedLine.replaceAll(
1524: "//__INCLUDE_JS_SCRIPTS__", includeJs
1525: + "\n//__INCLUDE_JS_SCRIPTS__");
1526: replacedLine = replacedLine.replaceAll(
1527: "//__LIBS_JS_SCRIPTS__", libsJs
1528: + "\n//__LIBS_JS_SCRIPTS__");
1529: replacedLine = replacedLine.replaceAll(
1530: "//__RESOURCES_DOJO_SCRIPTS__", resourcesDojo
1531: + "\n//__RESOURCES_DOJO_SCRIPTS__");
1532: replacedLine = replacedLine.replaceAll(
1533: "//__REQUIRE_DOJO_SCRIPTS__", requireDojo
1534: + "\n//__REQUIRE_DOJO_SCRIPTS__");
1535: return super .replaceTokens(replacedLine, object, pkg);
1536: }
1537: }
1538:
1539: public class ResourceJmakiComponent extends ResourceDojoComponents {
1540:
1541: public ResourceJmakiComponent(Resource r, FileObject restDir) {
1542: super (r, restDir);
1543: }
1544:
1545: public FileObject generate() throws IOException {
1546: if (r.isContainer()) {
1547: String name = r.getRepresentation().getRoot().getName();
1548: FileObject compDir = createFolder(getFolder(), name
1549: + TABLE);
1550: createDataObjectFromTemplate(
1551: JMAKI_COMPONENTCSS_TEMPLATE, compDir,
1552: JMAKI_COMPONENT, CSS, canOverwrite());
1553: createDataObjectFromTemplate(
1554: JMAKI_COMPONENTHTM_TEMPLATE, compDir,
1555: JMAKI_COMPONENT, HTM, canOverwrite());
1556: FileObject fo = createDataObjectFromTemplate(
1557: JMAKI_COMPONENTJS_TEMPLATE, compDir,
1558: JMAKI_COMPONENT, JS, canOverwrite());
1559: replaceTokens(fo);
1560: fo = createDataObjectFromTemplate(
1561: JMAKI_WIDGETJSON_TEMPLATE, compDir, WIDGET,
1562: JSON, canOverwrite());
1563: replaceTokens(fo);
1564:
1565: FileObject imagesDir = createFolder(compDir, IMAGES);//NoI18n
1566: File imgDir = FileUtil.toFile(imagesDir);
1567: copyFile(JMAKI_RESOURCESTABLE_SRC + "." + GIF,
1568: new File(imgDir, JMAKI_RESOURCESTABLE_DEST
1569: + "." + GIF));
1570: copyFile(JMAKI_RESOURCESTABLEUP_SRC + "." + GIF,
1571: new File(imgDir, JMAKI_RESOURCESTABLEUP_DEST
1572: + "." + GIF));
1573: copyFile(JMAKI_RESOURCESTABLEDOWN_SRC + "." + GIF,
1574: new File(imgDir, JMAKI_RESOURCESTABLEDOWN_DEST
1575: + "." + GIF));
1576: } else {
1577: return null;
1578: }
1579: return getFolder();
1580: }
1581: }
1582:
1583: public class ResourceJmakiTemplate extends ResourceJavaScript {
1584:
1585: public ResourceJmakiTemplate(Resource r, FileObject tRestDir) {
1586: super (r, tRestDir);
1587: }
1588:
1589: public FileObject generate() throws IOException {
1590: if (r.isContainer()) {
1591: String templateName = r.getRepresentation().getRoot()
1592: .getName()
1593: + TABLE;
1594: FileObject tDir = createFolder(getFolder(),
1595: templateName);
1596: FileObject fo = createDataObjectFromTemplate(
1597: JMAKI_TEMPLATESBUNDLE_TEMPLATE, tDir, BUNDLE,
1598: PROPERTIES, canOverwrite());
1599: replaceTokens(fo);
1600: fo = createDataObjectFromTemplate(
1601: JMAKI_TEMPLATESJSP_TEMPLATE, tDir,
1602: templateName, JSP, canOverwrite());
1603: replaceTokens(fo);
1604: fo = createDataObjectFromTemplate(
1605: JMAKI_TEMPLATESPHP_TEMPLATE, tDir,
1606: templateName, PHP, canOverwrite());
1607: replaceTokens(fo);
1608: fo = createDataObjectFromTemplate(
1609: JMAKI_TEMPLATESEJS_TEMPLATE, tDir,
1610: templateName, EJS, canOverwrite());
1611: replaceTokens(fo);
1612: fo = createDataObjectFromTemplate(
1613: JMAKI_TEMPLATESRHTML_TEMPLATE, tDir,
1614: templateName, RHTML, canOverwrite());
1615: replaceTokens(fo);
1616: } else {
1617: return null;
1618: }
1619: return getFolder();
1620: }
1621: }
1622: }
|