Package com.sun.codemodel

Examples of com.sun.codemodel.JBlock


        // List getXXX() {
        //     return <ref>;
        // }
        $get = writer.declareMethod(listT,"get"+prop.getName(true));
        writer.javadoc().append(prop.javadoc);
        JBlock block = $get.body();
        fixNullRef(block)// avoid using an internal getter
        block._return(acc.ref(true));

        String pname = NameConverter.standard.toVariableName(prop.getName(true));
        writer.javadoc().append(
            "Gets the value of the "+pname+" property.\n\n"+
            "<p>\n" +
View Full Code Here


   
    public void generateAccessors() {
       
        MethodWriter writer = outline.createMethodWriter();
        Accessor acc = create(JExpr._this());
        JVar $idx,$value; JBlock body;

        // [RESULT] T[] getX() {
        //     if( <var>==null )    return new T[0];
        //     T[] retVal = new T[this._return.length] ;
        //     System.arraycopy(this._return, 0, "retVal", 0, this._return.length);
        //     return (retVal);
        // }
        $getAll = writer.declareMethod( exposedType.array(),"get"+prop.getName(true));
        writer.javadoc().append(prop.javadoc);
        body = $getAll.body();

        body._if( acc.ref(true).eq(JExpr._null()) )._then()
            ._return(JExpr.newArray(exposedType,0));
        JVar var = body.decl(exposedType.array(), "retVal", JExpr.newArray(implType,acc.ref(true).ref("length")));
        body.add(codeModel.ref(System.class).staticInvoke("arraycopy")
                        .arg(acc.ref(true)).arg(JExpr.lit(0))
                        .arg(var)
                        .arg(JExpr.lit(0)).arg(acc.ref(true).ref("length")));
        body._return(JExpr.direct("retVal"));

        List<Object> returnTypes = listPossibleTypes(prop);
        writer.javadoc().addReturn().append("array of\n").append(returnTypes);

        // [RESULT]
        // ET getX(int idx) {
        //     if( <var>==null )    throw new IndexOutOfBoundsException();
        //     return unbox(<var>.get(idx));
        // }
        JMethod $get = writer.declareMethod(exposedType,"get"+prop.getName(true));
        $idx = writer.addParameter(codeModel.INT,"idx");

        $get.body()._if(acc.ref(true).eq(JExpr._null()))._then()
            ._throw(JExpr._new(codeModel.ref(IndexOutOfBoundsException.class)));

        writer.javadoc().append(prop.javadoc);
        $get.body()._return(acc.ref(true).component($idx));

        writer.javadoc().addReturn().append("one of\n").append(returnTypes);

        // [RESULT] int getXLength() {
        //     if( <var>==null )    throw new IndexOutOfBoundsException();
        //     return <ref>.length;
        // }
        JMethod $getLength = writer.declareMethod(codeModel.INT,"get"+prop.getName(true)+"Length");
        $getLength.body()._if(acc.ref(true).eq(JExpr._null()))._then()
                ._return(JExpr.lit(0));
        $getLength.body()._return(acc.ref(true).ref("length"));

        // [RESULT] void setX(ET[] values) {
        //     int len = values.length;
        //     for( int i=0; i<len; i++ )
        //         <ref>[i] = values[i];
        // }
        $setAll = writer.declareMethod(
            codeModel.VOID,
            "set"+prop.getName(true));

        writer.javadoc().append(prop.javadoc);
        $value = writer.addParameter(exposedType.array(),"values");
        JVar $len = $setAll.body().decl(codeModel.INT,"len", $value.ref("length"));

        $setAll.body().assign(
                (JAssignmentTarget) acc.ref(true),
                castToImplTypeArray(JExpr.newArray(
                    codeModel.ref(exposedType.erasure().fullName()),
                    $len)));

        JForLoop _for = $setAll.body()._for();
        JVar $i = _for.init( codeModel.INT, "i", JExpr.lit(0) );
        _for.test( JOp.lt($i,$len) );
        _for.update( $i.incr() );
        _for.body().assign(acc.ref(true).component($i), castToImplType(acc.box($value.component($i))));

        writer.javadoc().addParam($value)
            .append("allowed objects are\n")
            .append(returnTypes);

        // [RESULT] ET setX(int idx, ET value)
        // <ref>[idx] = value
        JMethod $set = writer.declareMethod(
            exposedType,
            "set"+prop.getName(true));
        $idx = writer.addParameter( codeModel.INT, "idx" );
        $value = writer.addParameter( exposedType, "value" );

        writer.javadoc().append(prop.javadoc);

        body = $set.body();
        body._return( JExpr.assign(acc.ref(true).component($idx),
                                   castToImplType(acc.box($value))));

        writer.javadoc().addParam($value)
            .append("allowed object is\n")
            .append(returnTypes);
View Full Code Here

      requestOptionsOverrideConstructor.body().invoke(SUPER).arg(originalResourceField).arg(requestOptionsOverrideOptionsParam);
    }
    else
    {
      requestOptionsOverrideConstructor.body().assign(baseUriField, originalResourceField);
      final JInvocation requestOptionsOverrideAssignRequestOptions = new JBlock().invoke("assignRequestOptions").arg(requestOptionsOverrideOptionsParam);
      requestOptionsOverrideConstructor.body().assign(requestOptionsField, requestOptionsOverrideAssignRequestOptions);
    }

    // primary resource name override constructor, delegates to the main constructor
    JVar resourceNameOverrideResourceNameParam = resourceNameOverrideConstructor.param(_stringClass, "primaryResourceName");
    resourceNameOverrideConstructor.body().invoke(THIS).arg(resourceNameOverrideResourceNameParam).arg(defaultOptionsField);

    // main constructor
    JVar mainConsResourceNameParam = mainConstructor.param(_stringClass, "primaryResourceName");
    JVar mainConsOptionsParam = mainConstructor.param(RestliRequestOptions.class, "requestOptions");

    JExpression baseUriExpr;
    if (resourcePath.contains("/"))
    {
      baseUriExpr = originalResourceField.invoke("replaceFirst").arg(JExpr.lit("[^/]*/")).arg(mainConsResourceNameParam.plus(JExpr.lit("/")));
    }
    else
    {
      baseUriExpr = mainConsResourceNameParam;
    }

    if (_config.isRestli2Format())
    {
      mainConstructor.body().invoke(SUPER).arg(baseUriExpr).arg(mainConsOptionsParam);
    }
    else
    {
      final JInvocation mainAssignRequestOptions = new JBlock().invoke("assignRequestOptions").arg(mainConsOptionsParam);
      mainConstructor.body().assign(baseUriField, baseUriExpr);
      mainConstructor.body().assign(requestOptionsField, mainAssignRequestOptions);
    }

    JMethod primaryResourceGetter = facadeClass.method(JMod.PUBLIC | JMod.STATIC, String.class, "getPrimaryResource");
    primaryResourceGetter.body()._return(originalResourceField);

    List<String> pathKeys = getPathKeys(resourcePath, pathToAssocKeys);

    JClass keyTyperefClass = null;
    JClass keyClass;
    JClass keyKeyClass = null;
    JClass keyParamsClass = null;
    Class<?> resourceSchemaClass;
    Map<String, AssocKeyTypeInfo> assocKeyTypeInfos = Collections.emptyMap();
    StringArray supportsList=null;
    RestMethodSchemaArray restMethods = null;
    FinderSchemaArray finders = null;
    ResourceSchemaArray subresources = null;
    ActionSchemaArray resourceActions = null;
    ActionSchemaArray entityActions = null;

    if (resource.getCollection() != null)
    {
      resourceSchemaClass = CollectionSchema.class;
      CollectionSchema collection = resource.getCollection();
      String keyName = collection.getIdentifier().getName();
      // In case of collection with a simple key, return the one specified by "type" in
      // the "identifier". Otherwise, get both "type" and "params", and return
      // ComplexKeyResource parameterized by those two.
      if (collection.getIdentifier().getParams() == null)
      {
        keyClass = getJavaBindingType(collection.getIdentifier().getType(), facadeClass).valueClass;
        JClass declaredClass = getClassRefForSchema(RestSpecCodec.textToSchema(collection.getIdentifier().getType(), getSchemaResolver()), facadeClass);
        if(!declaredClass.equals(keyClass))
        {
          keyTyperefClass = declaredClass;
        }
      }
      else
      {
        keyKeyClass = getJavaBindingType(collection.getIdentifier().getType(), facadeClass).valueClass;
        keyParamsClass = getJavaBindingType(collection.getIdentifier().getParams(), facadeClass).valueClass;
        keyClass = getCodeModel().ref(ComplexResourceKey.class).narrow(keyKeyClass, keyParamsClass);
      }
      pathKeyTypes.put(keyName, keyClass);
      supportsList = collection.getSupports();
      restMethods = collection.getMethods();
      finders = collection.getFinders();
      subresources = collection.getEntity().getSubresources();
      resourceActions = collection.getActions();
      entityActions = collection.getEntity().getActions();
    }
    else if (resource.getAssociation() != null)
    {
      resourceSchemaClass = AssociationSchema.class;
      AssociationSchema association = resource.getAssociation();
      keyClass = getCodeModel().ref(CompoundKey.class);
      supportsList = association.getSupports();
      restMethods = association.getMethods();
      finders = association.getFinders();
      subresources = association.getEntity().getSubresources();
      resourceActions = association.getActions();
      entityActions = association.getEntity().getActions();

      assocKeyTypeInfos = generateAssociationKey(facadeClass, association);

      String keyName = getAssociationKey(resource, association);
      pathKeyTypes.put(keyName, keyClass);

      List<String> assocKeys = new ArrayList<String>(4);
      for(Map.Entry<String, AssocKeyTypeInfo> entry: assocKeyTypeInfos.entrySet())
      {
        assocKeys.add(entry.getKey());
        assocKeyTypes.put(entry.getKey(), entry.getValue().getBindingType());
      }
      pathToAssocKeys.put(keyName, assocKeys);
    }
    else if (resource.getSimple() != null)
    {
      resourceSchemaClass = SimpleSchema.class;
      SimpleSchema simpleSchema = resource.getSimple();
      keyClass = _voidClass;
      supportsList = simpleSchema.getSupports();
      restMethods = simpleSchema.getMethods();
      subresources = simpleSchema.getEntity().getSubresources();
      resourceActions = simpleSchema.getActions();
    }
    else if (resource.getActionsSet() != null)
    {
      resourceSchemaClass = ActionsSetSchema.class;
      ActionsSetSchema actionsSet = resource.getActionsSet();
      resourceActions = actionsSet.getActions();

      keyClass = _voidClass;
    }
    else
    {
      throw new IllegalArgumentException("unsupported resource type for resource: '" + resourceName + '\'');
    }

    generateOptions(facadeClass, baseUriGetter, requestOptionsGetter);

    JFieldVar resourceSpecField = facadeClass.field(JMod.PRIVATE | JMod.STATIC | JMod.FINAL, _resourceSpecClass, "_resourceSpec");
    if (resourceSchemaClass == CollectionSchema.class ||
        resourceSchemaClass == AssociationSchema.class ||
        resourceSchemaClass == SimpleSchema.class)
    {
      JClass schemaClass = getJavaBindingType(resource.getSchema(), null).schemaClass;

      Set<ResourceMethod> supportedMethods = getSupportedMethods(supportsList);
      JInvocation supportedMethodsExpr;
      if (supportedMethods.isEmpty())
      {
        supportedMethodsExpr = _enumSetClass.staticInvoke("noneOf").arg(_resourceMethodClass.dotclass());
      }
      else
      {
        supportedMethodsExpr = _enumSetClass.staticInvoke("of");
        for (ResourceMethod resourceMethod: supportedMethods)
        {
          validateResourceMethod(resourceSchemaClass, resourceName, resourceMethod);
          supportedMethodsExpr.arg(_resourceMethodClass.staticRef(resourceMethod.name()));
        }
      }

      JBlock staticInit = facadeClass.init();

      JVar methodSchemaMap = methodMetadataMapInit(facadeClass, resourceActions, entityActions,
                                                   staticInit);
      JVar responseSchemaMap = responseMetadataMapInit(facadeClass, resourceActions, entityActions,
                                                       staticInit);

      if (resourceSchemaClass == CollectionSchema.class ||
          resourceSchemaClass == AssociationSchema.class)
      {
        JClass assocKeyClass = getCodeModel().ref(TypeInfo.class);
        JClass hashMapClass = getCodeModel().ref(HashMap.class).narrow(_stringClass, assocKeyClass);
        JVar keyPartsVar = staticInit.decl(hashMapClass, "keyParts").init(JExpr._new(hashMapClass));
        for (Map.Entry<String, AssocKeyTypeInfo> typeInfoEntry : assocKeyTypeInfos.entrySet())
        {
          AssocKeyTypeInfo typeInfo = typeInfoEntry.getValue();
          JInvocation typeArg = JExpr._new(assocKeyClass)
            .arg(typeInfo.getBindingType().dotclass())
            .arg(typeInfo.getDeclaredType().dotclass());
          staticInit.add(keyPartsVar.invoke("put").arg(typeInfoEntry.getKey()).arg(typeArg));
        }

        staticInit.assign(resourceSpecField,
                          JExpr._new(_resourceSpecImplClass)
                                  .arg(supportedMethodsExpr)
                                  .arg(methodSchemaMap)
                                  .arg(responseSchemaMap)
                                  .arg(keyTyperefClass == null ? keyClass.dotclass() : keyTyperefClass.dotclass())
                                  .arg(keyKeyClass == null ? JExpr._null() : keyKeyClass.dotclass())
                                  .arg(keyKeyClass == null ? JExpr._null() : keyParamsClass.dotclass())
                                  .arg(schemaClass.dotclass())
                                  .arg(keyPartsVar));
      }
      else //simple schema
      {
        staticInit.assign(resourceSpecField,
                          JExpr._new(_resourceSpecImplClass)
                              .arg(supportedMethodsExpr)
                              .arg(methodSchemaMap)
                              .arg(responseSchemaMap)
                              .arg(schemaClass.dotclass()));
      }

      generateBasicMethods(facadeClass,
                           baseUriGetter,
                           keyClass,
                           schemaClass,
                           supportedMethods,
                           restMethods,
                           resourceSpecField,
                           resourceName,
                           pathKeys,
                           pathKeyTypes,
                           assocKeyTypes,
                           pathToAssocKeys,
                           requestOptionsGetter);

      if (resourceSchemaClass == CollectionSchema.class ||
          resourceSchemaClass == AssociationSchema.class)
      {
        generateFinders(facadeClass,
                        baseUriGetter,
                        finders,
                        keyClass,
                        schemaClass,
                        assocKeyTypeInfos,
                        resourceSpecField,
                        resourceName,
                        pathKeys,
                        pathKeyTypes,
                        assocKeyTypes,
                        pathToAssocKeys,
                        requestOptionsGetter);
      }

      generateSubResources(sourceFile, subresources, pathKeyTypes, assocKeyTypes, pathToAssocKeys);
    }
    else //action set
    {
      JBlock staticInit = facadeClass.init();
      JInvocation supportedMethodsExpr = _enumSetClass.staticInvoke("noneOf").arg(_resourceMethodClass.dotclass());
      JVar methodSchemaMap = methodMetadataMapInit(facadeClass, resourceActions, entityActions,
                                                   staticInit);
      JVar responseSchemaMap = responseMetadataMapInit(facadeClass, resourceActions, entityActions,
                                                       staticInit);
      staticInit.assign(resourceSpecField,
                        JExpr._new(_resourceSpecImplClass)
                                .arg(supportedMethodsExpr)
                                .arg(methodSchemaMap)
                                .arg(responseSchemaMap)
                                .arg(keyClass.dotclass())
View Full Code Here

    createMethod.body()._return(newUnionVar);

    // Is method.

    JMethod is = unionClass.method(JMod.PUBLIC, getCodeModel().BOOLEAN, "is" + capitalizedName);
    JBlock isBody = is.body();
    JExpression res = JExpr.invoke("memberIs").arg(memberKey);
    isBody._return(res);

    // Getter method.

    String getterName = "get" + capitalizedName;
    JMethod getter = unionClass.method(JMod.PUBLIC, memberClass, getterName);
    JBlock getterBody = getter.body();
    res = JExpr.invoke("obtain" + wrappedOrDirect).arg(memberField).arg(JExpr.dotclass(memberClass)).arg(memberKey);
    getterBody._return(res);

    // Setter method.

    JMethod setter = unionClass.method(JMod.PUBLIC, Void.TYPE, setterName);
    param = setter.param(memberClass, "value");
View Full Code Here

    // Generate has method.
    JMethod has = templateClass.method(JMod.PUBLIC, getCodeModel().BOOLEAN, "has" + capitalizedName);
    addAccessorDoc(has, field, "Existence checker");
    setDeprecatedAnnotationAndJavadoc(has, field);
    JBlock hasBody = has.body();
    JExpression res = JExpr.invoke("contains").arg(fieldField);
    hasBody._return(res);

    // Generate remove method.
    String removeName = "remove" + capitalizedName;
    JMethod remove = templateClass.method(JMod.PUBLIC, getCodeModel().VOID, removeName);
    addAccessorDoc(remove, field, "Remover");
    setDeprecatedAnnotationAndJavadoc(remove, field);
    JBlock removeBody = remove.body();
    removeBody.invoke("remove").arg(fieldField);

    // Getter method with mode.
    String getterName = getGetterName(type, capitalizedName);
    JMethod getterWithMode = templateClass.method(JMod.PUBLIC, type, getterName);
    addAccessorDoc(getterWithMode, field, "Getter");
    setDeprecatedAnnotationAndJavadoc(getterWithMode, field);
    JVar modeParam = getterWithMode.param(_getModeClass, "mode");
    JBlock getterWithModeBody = getterWithMode.body();
    res = JExpr.invoke("obtain" + wrappedOrDirect).arg(fieldField).arg(JExpr.dotclass(type)).arg(modeParam);
    getterWithModeBody._return(res);

    // Getter method without mode.
    JMethod getterWithoutMode = templateClass.method(JMod.PUBLIC, type, getterName);
    addAccessorDoc(getterWithoutMode, field, "Getter");
    setDeprecatedAnnotationAndJavadoc(getterWithoutMode, field);
View Full Code Here

         */
        JClass objectType = model.ref(Object.class);
        getEndpoint = servCls.method(JMod.PUBLIC, objectType, "getEndpoint");
        JVar epVar = getEndpoint.param(Endpoint.class, "endpoint");
       
        JBlock geBody = getEndpoint.body();
        JTryBlock tryBlock = geBody._try();
       
        JInvocation createProxy = pfVar.invoke("create");
        createProxy.arg(JExpr.direct(epVar.name()).invoke("getBinding"));
        createProxy.arg(JExpr.direct(epVar.name()).invoke("getUrl"));
       
        tryBlock.body()._return(createProxy);

        JCatchBlock catchBlock = tryBlock._catch(model.ref(MalformedURLException.class));
        JType xreType = model._ref(XFireRuntimeException.class);
        JInvocation xreThrow = JExpr._new(xreType);
        xreThrow.arg("Invalid URL");
        xreThrow.arg(catchBlock.param("e"));
       
        catchBlock.body()._throw(xreThrow);
       

        /**
         * T getEndpoint(QName)
         */
        JMethod getEndpointByName = servCls.method(JMod.PUBLIC, objectType, "getEndpoint");
        JVar epname = getEndpointByName.param(QName.class, "name");
       
        geBody = getEndpointByName.body();
       
        // Endpoint endpoint = (Endpoint) service.getEndpoint(name);
        JType endpointType = model._ref(Endpoint.class);
        JInvocation getEndpointInv = endpointsVar.invoke("get");
        getEndpointInv.arg(JExpr.direct(epname.name()));

        epVar = geBody.decl(endpointType, "endpoint", JExpr.cast(endpointType, getEndpointInv));
       
        // if (endpoint == null)
        JBlock noEPBlock = geBody._if(JExpr.direct(epVar.name()).eq(JExpr._null()))._then();
       
        // throw IllegalStateException
        JType iseType = model._ref(IllegalStateException.class);
        JInvocation iseThrow = JExpr._new(iseType);
        iseThrow.arg("No such endpoint!");
        noEPBlock._throw(iseThrow);
       
        // return endpoint
       
        JInvocation geInvoke = JExpr.invoke(getEndpoint);
        geInvoke.arg(JExpr.direct(epVar.name()));
View Full Code Here

            Binding binding = (Binding) itr.next();
            if (!(binding instanceof AbstractSoapBinding)) continue;
           
            AbstractSoapBinding soapBinding = (AbstractSoapBinding) binding;

            JBlock block = create.body().block();
           
            JInvocation createBinding;
            if (soapBinding instanceof Soap12Binding)
            {
                createBinding = asfVar.invoke("createSoap12Binding");
            }
            else
            {
                createBinding = asfVar.invoke("createSoap11Binding");
            }
           
            createBinding.arg(serviceVar);
           
            JInvocation newQN = JExpr._new(qnameType);
            newQN.arg(soapBinding.getName().getNamespaceURI());
            newQN.arg(soapBinding.getName().getLocalPart());
            createBinding.arg(newQN);
            createBinding.arg(soapBinding.getBindingId());

            JVar sbVar = block.decl(abSoapBindingType, "soapBinding", createBinding);
        }

        constructor.body().invoke(create);

        return serviceVar;
View Full Code Here

        JCodeModel model = context.getCodeModel();
       
        /*
         * Add endpoints to constructor
         */
        JBlock consBody = constructor.body();
        JType qnameType = model.ref(QName.class);
       
        JDefinedClass serviceIntf = (JDefinedClass) service.getProperty(ServiceInterfaceGenerator.SERVICE_INTERFACE);

        JInvocation addEndpointInv = serviceVar.invoke("addEndpoint");
        JInvocation newQN = JExpr._new(qnameType);
        newQN.arg(endpoint.getName().getNamespaceURI());
        newQN.arg(endpoint.getName().getLocalPart());

        JInvocation bindingQN = JExpr._new(qnameType);
        bindingQN.arg(endpoint.getBinding().getName().getNamespaceURI());
        bindingQN.arg(endpoint.getBinding().getName().getLocalPart());

        addEndpointInv.arg(newQN);
        addEndpointInv.arg(bindingQN);
        addEndpointInv.arg(endpoint.getUrl());

        JType endpointType = model.ref(Endpoint.class);
        JVar epVar = consBody.decl(endpointType, javify(endpoint.getName().getLocalPart()) + "EP", addEndpointInv);

        JInvocation addEndpoint = endpointsVar.invoke("put").arg(newQN).arg(epVar);
        consBody.add(addEndpoint);
       
        // Add a getFooEndpointMethod
        JMethod getFooEndpoint = servCls.method(JMod.PUBLIC, serviceIntf, "get"
                + javify(endpoint.getName().getLocalPart()));
        JBlock geBody = getFooEndpoint.body();

        geBody._return(JExpr.cast(serviceIntf, JExpr.direct("this").invoke(getEndpoint).arg(newQN)));

        JMethod getFooEndpoint1 = servCls.method(JMod.PUBLIC, serviceIntf, "get"
                + javify(endpoint.getName().getLocalPart()));
        getFooEndpoint1.param(String.class,"url");
        JBlock geBody1 = getFooEndpoint1.body();
        JInvocation getEndp = JExpr.invoke(getFooEndpoint);
        JVar tpe = geBody1.decl(serviceIntf, "var", getEndp );
       
        geBody1.directStatement("org.codehaus.xfire.client.Client.getInstance(var).setUrl(url);");
        geBody1._return(tpe);
    }
View Full Code Here

        JInvocation superService = JExpr.invoke("super").arg(newURL).arg(newSN);
        constructor.body().add(superService);
       
        boolean addedLocal = false;
       
        JBlock staticBlock = servCls.init();
       
        JType hashMapType = model._ref(HashMap.class);
        JType mapType = model._ref(Map.class);
        JVar portsVar = servCls.field(JMod.PRIVATE + JMod.STATIC,
                                      mapType, "ports", JExpr._new(hashMapType));

        JMethod method = servCls.method(JMod.PUBLIC + JMod.STATIC, mapType, "getPortClassMap");
        method.body()._return(JExpr.ref("ports"));
       
        for (Service service : services)
        {
            JClass serviceIntf = (JClass) service.getProperty(ServiceInterfaceGenerator.SERVICE_INTERFACE);

            JFieldVar intfClass = servCls.field(JMod.STATIC + JMod.PUBLIC,
                                                Class.class,
                                                javify(serviceIntf.name()),
                                                JExpr.dotclass(serviceIntf));

            // hack to get local support
            if (!addedLocal)
            {
                Soap11Binding localBind = new Soap11Binding(new QName(ns, name + "LocalBinding"),
                                                            LocalTransport.BINDING_ID,
                                                            service);
                service.addBinding(localBind);
                service.addEndpoint(new QName(ns, name + "LocalPort"), localBind, "xfire.local://" + name);
               
                addedLocal = true;
            }
           
            for (Iterator itr = service.getEndpoints().iterator(); itr.hasNext();)
            {
                Endpoint endpoint = (Endpoint) itr.next();
   
                JInvocation newQN = JExpr._new(qnameType);
                newQN.arg(endpoint.getName().getNamespaceURI());
                newQN.arg(endpoint.getName().getLocalPart());
               
                JInvocation bindingQN = JExpr._new(qnameType);
                bindingQN.arg(endpoint.getBinding().getName().getNamespaceURI());
                bindingQN.arg(endpoint.getBinding().getName().getLocalPart());

                // Add a getFooEndpointMethod
                JMethod getFooEndpoint = servCls.method(JMod.PUBLIC, serviceIntf, javify("get" + endpoint.getName().getLocalPart()));
                JBlock geBody = getFooEndpoint.body();
   
                geBody._return(JExpr.cast(serviceIntf, JExpr.direct("this").invoke("getPort").arg(newQN).arg(intfClass)));
               
                JAnnotationUse weAnn = getFooEndpoint.annotate(WebEndpoint.class);
                weAnn.param("name", endpoint.getName().getLocalPart());
               
                staticBlock.add(portsVar.invoke("put").arg(newQN).arg(intfClass));
View Full Code Here

    return new HiveFuncHolderExpr(name, this, args, pos);
  }

  private void generateSetup(ClassGenerator<?> g, JVar[] workspaceJVars) {
    JCodeModel m = g.getModel();
    JBlock sub = new JBlock(true, true);

    // declare and instantiate argument ObjectInspector's
    JVar oiArray = sub.decl(
      m._ref(ObjectInspector[].class),
      "argOIs",
      JExpr.newArray(m._ref(ObjectInspector.class), argTypes.length));

    JClass oih = m.directClass(ObjectInspectorHelper.class.getCanonicalName());
    JClass mt = m.directClass(TypeProtos.MinorType.class.getCanonicalName());
    JClass mode = m.directClass(DataMode.class.getCanonicalName());
    for(int i=0; i<argTypes.length; i++) {
      sub.assign(
        oiArray.component(JExpr.lit(i)),
        oih.staticInvoke("getDrillObjectInspector")
          .arg(mode.staticInvoke("valueOf").arg(JExpr.lit(argTypes[i].getMode().getNumber())))
          .arg(mt.staticInvoke("valueOf").arg(JExpr.lit(argTypes[i].getMinorType().getNumber()))));
    }

    // declare and instantiate DeferredObject array
    sub.assign(workspaceJVars[2], JExpr.newArray(m._ref(DrillDeferredObject.class), argTypes.length));

    for(int i=0; i<argTypes.length; i++) {
      sub.assign(
        workspaceJVars[2].component(JExpr.lit(i)),
        JExpr._new(m.directClass(DrillDeferredObject.class.getCanonicalName())));
    }

    // declare empty array for argument deferred objects
    sub.assign(workspaceJVars[3], JExpr.newArray(m._ref(DrillDeferredObject.class), argTypes.length));

    // create new instance of the UDF class
    sub.assign(workspaceJVars[1], getUDFInstance(m));

    // create try..catch block to initialize the UDF instance with argument OIs
    JTryBlock udfInitTry = sub._try();
    udfInitTry.body().assign(
      workspaceJVars[0],
      workspaceJVars[1].invoke("initialize")
      .arg(oiArray));

    JCatchBlock udfInitCatch = udfInitTry._catch(m.directClass(Exception.class.getCanonicalName()));
    JVar exVar = udfInitCatch.param("ex");
    udfInitCatch.body()
      ._throw(JExpr._new(m.directClass(RuntimeException.class.getCanonicalName()))
        .arg(JExpr.lit(String.format("Failed to initialize GenericUDF"))).arg(exVar));

    sub.add(ObjectInspectorHelper.initReturnValueHolder(g, m, workspaceJVars[4], returnOI, returnType.getMinorType()));

    // now add it to the doSetup block in Generated class
    JBlock setup = g.getBlock(ClassGenerator.BlockType.SETUP);
    setup.directStatement(String.format("/** start %s for function %s **/ ",
      ClassGenerator.BlockType.SETUP.name(), genericUdfClazz.getName() + (!isGenericUDF ? "("+udfName+")" : "")));

    setup.add(sub);

    setup.directStatement(String.format("/** end %s for function %s **/ ",
      ClassGenerator.BlockType.SETUP.name(), genericUdfClazz.getName() + (!isGenericUDF ? "("+udfName+")" : "")));
  }
View Full Code Here

TOP

Related Classes of com.sun.codemodel.JBlock

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.