private void generateMethodParamToHeaderCodeForSimpleType(
     SourcePrinter srcWriter,
     String builderVarName,
     String headerName,
     JType parameterType,
     String parameterexpression,
     String parameterCheckExpression) {
   JClassType jClassType = parameterType.isClassOrInterface();
   srcWriter.println("if (" + parameterCheckExpression + "){");
   if (jClassType != null) {
     if (jClassType.isAssignableTo(stringType)) {
       srcWriter.println(
           builderVarName
               + ".setHeader("
               + EscapeUtils.quote(headerName)
               + ", URL.encodePathSegment("
               + parameterexpression
               + "));");
     } else if (jClassType.isAssignableTo(dateType)) {
       srcWriter.println(
           builderVarName
               + ".setHeader("
               + EscapeUtils.quote(headerName)
               + ", URL.encodePathSegment("
               + "Long.toString("
               + parameterexpression
               + ".getTime())));");
     } else {
       srcWriter.println(
           builderVarName
               + ".setHeader("
               + EscapeUtils.quote(headerName)
               + ", URL.encodePathSegment("
               + "\"\"+"
               + parameterexpression
               + "));");
     }
   } else {
     srcWriter.println(
         builderVarName
             + ".setHeader("
             + EscapeUtils.quote(headerName)
             + ", URL.encodePathSegment("
             + "\"\"+"
             + parameterexpression
             + "));");
   }
   srcWriter.println("}");
 }
  protected void generateObjectStoresCreation(SourcePrinter srcWriter, String callback) {
    srcWriter.println("deleteDBTables(tx, new DatabaseCallback(){");
    srcWriter.println("public void onSuccess(){");

    ObjectStoreDef[] objectStores = databaseMetadata.objectStores();
    Set<String> addedObjectStores = new HashSet<String>();

    String objectStoreVar = "objectStore";
    String indexNamesVar = "indexNames";
    srcWriter.println("WSQLAbstractObjectStore " + objectStoreVar + ";");
    srcWriter.println("Array<String> " + indexNamesVar + ";");
    for (ObjectStoreDef objectStoreMetadata : objectStores) {
      JClassType objectStoreTarget = getObjectStoreTarget(objectStoreMetadata);
      String objectStoreName = getObjectStoreName(objectStoreMetadata, objectStoreTarget);
      if (addedObjectStores.contains(objectStoreName)) {
        throw new CruxGeneratorException(
            "Duplicated objectstore declared on Datasource [" + databaseMetadata.name() + "]");
      }
      addedObjectStores.add(objectStoreName);

      srcWriter.println(
          objectStoreVar + " = getObjectStore(" + EscapeUtils.quote(objectStoreName) + ", null);");

      srcWriter.println(objectStoreVar + ".createTable(tx, null);");
    }

    srcWriter.println("createFileStore(tx);");

    srcWriter.println("}");
    srcWriter.println("}, getDeleteErrorHandler(callback), false);");
  }
Esempio n. 3
0
 @SuppressWarnings("deprecation")
 private static String getFieldInjectionExpression(
     JField field, String iocContainerVariable, Map<String, IocConfig<?>> configurations) {
   Inject inject = field.getAnnotation(Inject.class);
   if (inject != null) {
     JType fieldType = field.getType();
     if (!field.isStatic()) {
       if (fieldType.isClassOrInterface() != null) {
         String fieldTypeName = fieldType.getQualifiedSourceName();
         IocConfigImpl<?> iocConfig = (IocConfigImpl<?>) configurations.get(fieldTypeName);
         if (iocConfig != null) {
           if (inject
               .scope()
               .equals(org.cruxframework.crux.core.client.ioc.Inject.Scope.DEFAULT)) {
             return iocContainerVariable
                 + ".get"
                 + fieldTypeName.replace('.', '_')
                 + "("
                 + Scope.class.getCanonicalName()
                 + "."
                 + iocConfig.getScope().name()
                 + ", null)";
           }
           return iocContainerVariable
               + ".get"
               + fieldTypeName.replace('.', '_')
               + "("
               + Scope.class.getCanonicalName()
               + "."
               + getScopeName(inject.scope())
               + ", "
               + EscapeUtils.quote(inject.subscope())
               + ")";
         } else {
           return "GWT.create(" + fieldTypeName + ".class)";
         }
       } else {
         throw new IoCException(
             "Error injecting field ["
                 + field.getName()
                 + "] from type ["
                 + field.getEnclosingType().getQualifiedSourceName()
                 + "]. Primitive fields can not be handled by ioc container.");
       }
     } else {
       throw new IoCException(
           "Error injecting field ["
               + field.getName()
               + "] from type ["
               + field.getEnclosingType().getQualifiedSourceName()
               + "]. Static fields can not be handled by ioc container.");
     }
   }
   return null;
 }
    /**
     * Sets the item attributes before adding it to the parent.
     *
     * @param out
     * @param context
     * @param item
     */
    private void setItemAttributes(SourcePrinter out, StackMenuContext context, String item) {
      String open = context.readChildProperty("open");
      if (!StringUtils.isEmpty(open)) {
        out.println(item + ".setOpen(" + Boolean.parseBoolean(open) + ");");
      }

      String style = context.readChildProperty("style");
      if (!StringUtils.isEmpty(style)) {
        if (styleProcessor == null) {
          styleProcessor = new StyleProcessor(getWidgetCreator());
        }
        styleProcessor.processAttribute(out, context, style);
      }

      String styleName = context.readChildProperty("styleName");
      if (!StringUtils.isEmpty(styleName)) {
        out.println(item + ".setStyleName(" + EscapeUtils.quote(styleName) + ");");
      }

      String tooltip = context.readChildProperty("tooltip");
      if (!StringUtils.isEmpty(tooltip)) {
        out.println(item + ".setTitle(" + EscapeUtils.quote(tooltip) + ");");
      }
    }
  protected void generateGetIndexNamesMethod(SourcePrinter srcWriter) {
    srcWriter.println("public String[] getIndexNames(){");
    srcWriter.print("return new String[]{");

    boolean first = true;
    for (IndexData index : indexes) {
      if (!first) {
        srcWriter.print(",");
      }
      first = false;
      srcWriter.print(EscapeUtils.quote(index.indexName));
    }

    srcWriter.println("};");
    srcWriter.println("}");
    srcWriter.println();
  }
    @Override
    public void processChildren(SourcePrinter out, StackMenuContext context)
        throws CruxGeneratorException {
      String item = getWidgetCreator().createVariableName("item");
      String className = StackMenuItem.class.getCanonicalName();

      String label = context.getChildElement().optString("label");
      label = getWidgetCreator().resolveI18NString(label);

      String key = context.getChildElement().optString("key");
      key = EscapeUtils.quote(key);

      out.println(className + " " + item + " = new " + className + "(" + key + ", " + label + ");");
      setItemAttributes(out, context, item);
      String parentWidget = context.itemStack.getFirst();
      out.println(parentWidget + ".add(" + item + ");");

      context.itemStack.addFirst(item);
    }
  protected void generateGetObjectStoreMethod(SourcePrinter srcWriter) {
    srcWriter.println(
        "protected <K, V> WSQLAbstractObjectStore<K, V> getObjectStore(String storeName, WSQLTransaction transaction){");

    boolean first = true;
    ObjectStoreDef[] objectStores = databaseMetadata.objectStores();

    for (ObjectStoreDef objectStoreMetadata : objectStores) {
      JClassType objectStoreTarget = getObjectStoreTarget(objectStoreMetadata);
      String objectStoreName = getObjectStoreName(objectStoreMetadata, objectStoreTarget);
      if (!first) {
        srcWriter.print("else ");
      }
      first = false;
      Set<IndexData> indexes =
          getIndexes(objectStoreMetadata.indexes(), objectStoreTarget, objectStoreName);
      srcWriter.println(
          "if (StringUtils.unsafeEquals(storeName, " + EscapeUtils.quote(objectStoreName) + ")){");
      String[] keyPath = getKeyPath(objectStoreMetadata, objectStoreTarget);
      String objectStore =
          new SQLObjectStoreProxyCreator(
                  context,
                  logger,
                  objectStoreTarget,
                  objectStoreName,
                  keyPath,
                  isAutoIncrement(objectStoreTarget),
                  indexes)
              .create();
      srcWriter.println(
          "return (WSQLAbstractObjectStore<K, V>) new "
              + objectStore
              + "(this, storeName, transaction);");
      srcWriter.println("}");
    }

    srcWriter.println("return null;");
    srcWriter.println("}");
    srcWriter.println();
  }
  protected void generateGetIndexMethod(SourcePrinter srcWriter) {
    srcWriter.println(
        "public <I> Index<"
            + getKeyTypeName()
            + ", I, "
            + getTargetObjectClassName()
            + "> getIndex(String name){");
    for (IndexData index : indexes) {
      srcWriter.println(
          "if (StringUtils.unsafeEquals(name, " + EscapeUtils.quote(index.indexName) + ")){");
      String indexClassName =
          new SQLIndexProxyCreator(
                  context,
                  targetObjectType,
                  objectStoreName,
                  autoIncrement,
                  index.keyPath,
                  index.indexName,
                  keyPath,
                  getIndexColumns(),
                  index.unique)
              .create();
      srcWriter.println(
          "return (Index<"
              + getKeyTypeName()
              + ", I, "
              + getTargetObjectClassName()
              + ">) new "
              + indexClassName
              + "("
              + dbVariable
              + ", transaction);");
      srcWriter.println("}");
    }

    srcWriter.println("return null;");
    srcWriter.println("}");
    srcWriter.println();
  }
  @Override
  protected void generateProxyContructor(SourcePrinter srcWriter) throws CruxGeneratorException {
    srcWriter.println("public " + getProxySimpleName() + "(){");

    String viewVariable = ViewFactoryCreator.createVariableName("view");
    srcWriter.println(
        viewClassName
            + " "
            + viewVariable
            + " = new "
            + viewClassName
            + "("
            + EscapeUtils.quote(baseIntf.getSimpleSourceName())
            + "+(_idGen++));");
    createController(srcWriter, viewVariable);
    srcWriter.println(viewVariable + ".setController(this._controller);");

    srcWriter.println("initWidget(viewContainer.asWidget());");
    srcWriter.println("viewContainer.add(" + viewVariable + ", true, null);");
    srcWriter.println(
        "((" + DeviceAdaptiveController.class.getCanonicalName() + ")this._controller).init();");
    srcWriter.println("}");
  }
Esempio n. 10
0
  /**
   * @param srcWriter
   * @param className
   */
  private void generateContainerInstatiationMethod(SourcePrinter srcWriter, String className) {
    try {
      srcWriter.println(
          "public  "
              + className
              + " get"
              + className.replace('.', '_')
              + "("
              + Scope.class.getCanonicalName()
              + " scope, String subscope){");
      JClassType type =
          JClassUtils.getType(context.getGeneratorContext().getTypeOracle(), className);

      IocConfigImpl<?> iocConfig = (IocConfigImpl<?>) configurations.get(className);
      Class<?> providerClass = iocConfig.getProviderClass();
      if (providerClass != null) {
        srcWriter.println(
            className
                + " result = _getScope(scope).getValue(GWT.create("
                + providerClass.getCanonicalName()
                + ".class), "
                + EscapeUtils.quote(className)
                + ", subscope, ");
        generateFieldsPopulationCallback(srcWriter, type);
        srcWriter.println(");");
      } else if (iocConfig.getToClass() != null) {
        srcWriter.println(
            className
                + " result = _getScope(scope).getValue(new "
                + IocProvider.class.getCanonicalName()
                + "<"
                + className
                + ">(){");
        srcWriter.println("public " + className + " get(){");
        srcWriter.println(
            "return GWT.create(" + iocConfig.getToClass().getCanonicalName() + ".class);");
        srcWriter.println("}");
        srcWriter.println("}, " + EscapeUtils.quote(className) + ", subscope, ");
        generateFieldsPopulationCallback(srcWriter, type);
        srcWriter.println(");");
      } else {
        srcWriter.println(
            className
                + " result = _getScope(scope).getValue(new "
                + IocProvider.class.getCanonicalName()
                + "<"
                + className
                + ">(){");
        srcWriter.println("public " + className + " get(){");
        String instantiationClass = getInstantiationClass(className);
        JClassType instantiationType =
            context.getGeneratorContext().getTypeOracle().findType(instantiationClass);
        if (instantiationType == null) {
          throw new CruxGeneratorException("Can not found type: " + instantiationClass);
        }
        if (instantiationType.isAssignableTo(remoteServiceType)
            && ConfigurationFactory.getConfigurations()
                .sendCruxViewNameOnClientRequests()
                .equals("true")) {
          srcWriter.println(className + " ret = GWT.create(" + instantiationClass + ".class);");
          srcWriter.println(
              "(("
                  + ServiceDefTarget.class.getCanonicalName()
                  + ")ret).setRpcRequestBuilder(new "
                  + CruxRpcRequestBuilder.class.getCanonicalName()
                  + "(getBoundCruxViewId()));");
          srcWriter.println("return ret;");
        } else {
          srcWriter.println("return GWT.create(" + instantiationClass + ".class);");
        }
        srcWriter.println("}");
        srcWriter.println("}, " + EscapeUtils.quote(className) + ", subscope, ");
        generateFieldsPopulationCallback(srcWriter, type);
        srcWriter.println(");");
      }

      if (type.isAssignableTo(viewBindableType)) {
        srcWriter.println(
            "if (scope != "
                + Scope.class.getCanonicalName()
                + "."
                + Scope.SINGLETON.name()
                + " && result.getBoundCruxViewId() == null){");
        srcWriter.println("result.bindCruxView(this.getBoundCruxViewId());");
        srcWriter.println("}");
      }
      srcWriter.println("return result;");
      srcWriter.println("}");
    } catch (NotFoundException e) {
      throw new IoCException("IoC Error Class [" + className + "] not found.", e);
    }
  }
  public void generateMethodParamToBodyCode(
      SourcePrinter srcWriter, RestMethodInfo methodInfo, String builder, String httpMethod) {
    JParameter[] parameters = methodInfo.method.getParameters();
    boolean formEncoded = false;
    boolean hasBodyObject = false;

    String formString = getFormString(methodInfo);
    if (!StringUtils.isEmpty(formString)) {
      srcWriter.println("String requestData = " + EscapeUtils.quote(formString) + ";");
    }
    for (int i = 0; i < methodInfo.parameterAnnotations.length; i++) {
      Annotation[] annotations = methodInfo.parameterAnnotations[i];
      if (annotations == null || annotations.length == 0) { // JSON on body
        if (hasBodyObject) {
          throw new CruxGeneratorException(
              "Invalid Method: "
                  + methodInfo.method.getEnclosingType().getName()
                  + "."
                  + methodInfo.method.getName()
                  + "(). "
                  + "Request body can not contain more than one body parameter (JSON serialized object).");
        }

        hasBodyObject = true;
        String serializerName =
            new JSonSerializerProxyCreator(context, logger, parameters[i].getType()).create();
        srcWriter.println(
            builder
                + ".setHeader(\""
                + HttpHeaderNames.CONTENT_TYPE
                + "\", \"application/json\");");
        srcWriter.println(
            "JSONValue serialized = new "
                + serializerName
                + "().encode("
                + parameters[i].getName()
                + ");");
        srcWriter.println(
            "String requestData = (serialized==null||serialized.isNull()!=null)?null:serialized.toString();");
      } else {
        for (Annotation annotation : annotations) {
          JParameter parameter = parameters[i];
          JType parameterType = parameter.getType();
          String parameterName = parameter.getName();
          formEncoded =
              generateMethodParamToBodyCodeForAnnotatedParameter(
                  srcWriter,
                  builder,
                  parameters,
                  formEncoded,
                  i,
                  annotation,
                  parameterType,
                  parameterName);
        }
      }
    }
    if (hasBodyObject && formEncoded) {
      throw new CruxGeneratorException(
          "Invalid Method: "
              + methodInfo.method.getEnclosingType().getName()
              + "."
              + methodInfo.method.getName()
              + "(). "
              + "Request body can not contain form parameters and a JSON serialized object.");
    }
    if (hasBodyObject || formEncoded) {
      if (httpMethod.equals("GET")) {
        throw new CruxGeneratorException(
            "Invalid Method: "
                + methodInfo.method.getEnclosingType().getName()
                + "."
                + methodInfo.method.getName()
                + "(). "
                + "Can not use request body parameters on a GET operation.");
      }
      srcWriter.println(builder + ".setRequestData(requestData);");
    }
  }
 private void generateMethodParamToCookieCodeForSimpleType(
     SourcePrinter srcWriter,
     String cookieName,
     JType parameterType,
     String parameterexpression,
     String parameterCheckExpression) {
   JClassType jClassType = parameterType.isClassOrInterface();
   if (jClassType != null) {
     if (jClassType.isAssignableTo(stringType)) {
       srcWriter.println(
           Cookies.class.getCanonicalName()
               + ".setCookie("
               + EscapeUtils.quote(cookieName)
               + ", "
               + "("
               + parameterCheckExpression
               + "?"
               + parameterexpression
               + ":\"\"), new "
               + Date.class.getCanonicalName()
               + "(2240532000000L), null, \"/\", false);");
     } else if (jClassType.isAssignableTo(dateType)) {
       srcWriter.println(
           Cookies.class.getCanonicalName()
               + ".setCookie("
               + EscapeUtils.quote(cookieName)
               + ", "
               + "("
               + parameterCheckExpression
               + "?Long.toString("
               + parameterexpression
               + ".getTime()):\"\"), new "
               + Date.class.getCanonicalName()
               + "(2240532000000L), null, \"/\", false);");
     } else {
       srcWriter.println(
           Cookies.class.getCanonicalName()
               + ".setCookie("
               + EscapeUtils.quote(cookieName)
               + ", "
               + "("
               + parameterCheckExpression
               + "?(\"\"+"
               + parameterexpression
               + "):\"\"), new "
               + Date.class.getCanonicalName()
               + "(2240532000000L), null, \"/\", false);");
     }
   } else {
     srcWriter.println(
         Cookies.class.getCanonicalName()
             + ".setCookie("
             + EscapeUtils.quote(cookieName)
             + ", "
             + "("
             + parameterCheckExpression
             + "?(\"\"+"
             + parameterexpression
             + "):\"\"), new "
             + Date.class.getCanonicalName()
             + "(2240532000000L), null, \"/\", false);");
   }
 }
    @Override
    public void processChildren(SourcePrinter out, WidgetCreatorContext context)
        throws CruxGeneratorException {
      if (beforeFocusEvtBind == null)
        beforeFocusEvtBind = new BeforeFocusEvtBind(getWidgetCreator());
      if (beforeBlurEvtBind == null) beforeBlurEvtBind = new BeforeBlurEvtBind(getWidgetCreator());

      String name = context.readChildProperty("name");
      String id = context.readChildProperty("id");
      if (StringUtils.isEmpty(id)) {
        id = name;
      }
      boolean closeable = true;
      String strCloseable = context.readChildProperty("closeable");
      if (strCloseable != null && strCloseable.trim().length() > 0) {
        closeable = Boolean.parseBoolean(strCloseable);
      }
      boolean lazy = true;
      String strLazy = context.readChildProperty("lazy");
      if (strLazy != null && strLazy.trim().length() > 0) {
        lazy = Boolean.parseBoolean(strLazy);
      }
      String beforeFocusEvt = context.readChildProperty(beforeFocusEvtBind.getEventName());
      String beforeBlurEvt = context.readChildProperty(beforeBlurEvtBind.getEventName());

      String rootWidget = context.getWidget();
      out.println(
          TabContainer.class.getCanonicalName()
              + ".createView("
              + EscapeUtils.quote(name)
              + ", "
              + EscapeUtils.quote(id)
              + ", new "
              + CreateCallback.class.getCanonicalName()
              + "(){");
      out.println("public void onViewCreated(View view){");
      boolean hasEvents =
          !StringUtils.isEmpty(beforeFocusEvt) || !StringUtils.isEmpty(beforeBlurEvt);
      if (hasEvents) {
        out.print("if (");
      }
      out.print(rootWidget + ".add(view, " + lazy + ", " + closeable + ", true)");
      if (hasEvents) {
        out.print("){");
      } else {
        out.println(";");
      }
      String tab = ViewFactoryCreator.createVariableName("tab");
      out.print(
          Tab.class.getCanonicalName()
              + " "
              + tab
              + " = "
              + rootWidget
              + ".getTab("
              + EscapeUtils.quote(id)
              + ");");

      if (!StringUtils.isEmpty(beforeFocusEvt)) {
        beforeFocusEvtBind.processEvent(out, beforeFocusEvt, tab, null);
      }
      if (!StringUtils.isEmpty(beforeBlurEvt)) {
        beforeBlurEvtBind.processEvent(out, beforeBlurEvt, tab, null);
      }
      if (hasEvents) {
        out.println("}");
      }
      out.println("}");
      out.print("});");
    }
 protected void generateGetObjectStoreNameMethod(SourcePrinter srcWriter) {
   srcWriter.println("public String getObjectStoreName(){");
   srcWriter.println("return " + EscapeUtils.quote(objectStoreName) + ";");
   srcWriter.println("}");
   srcWriter.println();
 }
  @Override
  public void postProcess(SourcePrinter out, C context) throws CruxGeneratorException {
    String widget = context.getWidget();

    if (context.animationDuration > 0) {
      String onAnimationComplete = context.readWidgetProperty("onAnimationComplete");
      String onAnimationStep = context.readWidgetProperty("onAnimationStep");

      if (!StringUtils.isEmpty(onAnimationComplete) || !StringUtils.isEmpty(onAnimationStep)) {
        String layoutAnimationEvent = createVariableName("evt");
        String eventClassName =
            LayoutAnimationEvent.class.getCanonicalName() + "<" + getWidgetClassName() + ">";

        String widgetClassName = getWidgetClassName();
        printlnPostProcessing(
            "final "
                + widgetClassName
                + " "
                + widget
                + " = ("
                + widgetClassName
                + ")"
                + getViewVariable()
                + ".getWidget("
                + EscapeUtils.quote(context.getWidgetId())
                + ");");
        printlnPostProcessing(
            eventClassName
                + " "
                + layoutAnimationEvent
                + " = new "
                + eventClassName
                + "("
                + widget
                + ", "
                + context.getWidgetId()
                + ");");

        runChildProcessingAnimations(context.childProcessingAnimations);

        printlnPostProcessing(
            widget
                + ".animate("
                + context.animationDuration
                + ", new "
                + AnimationCallback.class.getCanonicalName()
                + "(){");
        printlnPostProcessing("public void onAnimationComplete(){");
        printlnPostProcessing("if (onAnimationComplete != null){");
        EvtProcessor.printPostProcessingEvtCall(
            onAnimationComplete,
            "onAnimationComplete",
            LayoutAnimationEvent.class,
            layoutAnimationEvent,
            this);
        printlnPostProcessing("}");
        printlnPostProcessing("}");
        printlnPostProcessing("public void onLayout(Layer layer, double progress){");
        printlnPostProcessing("if (onAnimationStep != null){");
        EvtProcessor.printPostProcessingEvtCall(
            onAnimationStep,
            "onAnimationStep",
            LayoutAnimationEvent.class,
            layoutAnimationEvent,
            this);
        printlnPostProcessing("}");
        printlnPostProcessing("}");
        printlnPostProcessing("});");
      } else {
        runChildProcessingAnimations(context.childProcessingAnimations);
        printlnPostProcessing(widget + ".animate(" + context.animationDuration + ");");
      }
    }
  }