Java Code Examples for com.sun.codemodel.JBlock#assign()

The following examples show how to use com.sun.codemodel.JBlock#assign() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ClientGenerator.java    From raml-module-builder with Apache License 2.0 6 votes vote down vote up
private void addConstructorOkapi6Args(JFieldVar tokenVar, JFieldVar options, JFieldVar httpClient) {
  /* constructor, init the httpClient - allow to pass keep alive option */
  JMethod constructor = constructor();
  JVar okapiUrlVar = constructor.param(String.class, OKAPI_URL);
  JVar tenantIdVar = constructor.param(String.class, TENANT_ID);
  JVar token = constructor.param(String.class, TOKEN);
  JVar keepAlive = constructor.param(boolean.class, KEEP_ALIVE);
  JVar connTimeout = constructor.param(int.class, "connTO");
  JVar idleTimeout = constructor.param(int.class, "idleTO");

  /* populate constructor */
  JBlock conBody = constructor.body();
  conBody.assign(JExpr._this().ref(tenantId), tenantIdVar);
  conBody.assign(JExpr._this().ref(tokenVar), token);
  conBody.assign(JExpr._this().ref(okapiUrl), okapiUrlVar);
  conBody.assign(options, JExpr._new(jcodeModel.ref(HttpClientOptions.class)));
  conBody.invoke(options, "setLogActivity").arg(JExpr.TRUE);
  conBody.invoke(options, "setKeepAlive").arg(keepAlive);
  conBody.invoke(options, "setConnectTimeout").arg(connTimeout);
  conBody.invoke(options, "setIdleTimeout").arg(idleTimeout);

  JExpression vertx = jcodeModel
      .ref("org.folio.rest.tools.utils.VertxUtils")
      .staticInvoke("getVertxFromContextOrNew");
  conBody.assign(httpClient, vertx.invoke("createHttpClient").arg(options));
}
 
Example 2
Source File: ClassGenerator.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
public JVar declareVectorValueSetupAndMember(DirectExpression batchName, TypedFieldId fieldId) {
  final ValueVectorSetup setup = new ValueVectorSetup(batchName, fieldId);

  final Class<?> valueVectorClass = fieldId.getIntermediateClass();
  final JClass vvClass = model.ref(valueVectorClass);
  final JClass retClass = fieldId.isHyperReader() ? vvClass.array() : vvClass;

  final JVar vv = declareClassField("vv", retClass);
  final JBlock b = getSetupBlock();
  int[] fieldIndices = fieldId.getFieldIds();
  JInvocation invoke = model.ref(VectorResolver.class).staticInvoke(fieldId.isHyperReader() ? "hyper" : "simple")
      .arg(batchName)
      .arg(vvClass.dotclass());

  for(int i = 0; i < fieldIndices.length; i++){
    invoke.arg(JExpr.lit(fieldIndices[i]));
  }

  // we have to cast here since Janino doesn't handle generic inference well.
  JExpression casted = JExpr.cast(retClass, invoke);
  b.assign(vv, casted);
  vvDeclaration.put(setup, vv);

  return vv;
}
 
Example 3
Source File: CreateTraversingVisitorClass.java    From jaxb-visitor with Apache License 2.0 6 votes vote down vote up
private void generateForDirectClass(JDefinedClass traversingVisitor, JTypeVar returnType, JTypeVar exceptionType, JClass implClass) {
    // add method impl to traversing visitor
    JMethod travViz;
    String visitMethodName = visitMethodNamer.apply(implClass.name());
    travViz = traversingVisitor.method(JMod.PUBLIC, returnType, visitMethodName);
    travViz._throws(exceptionType);
    JVar beanVar = travViz.param(implClass, "aBean");
    travViz.annotate(Override.class);
    JBlock travVizBloc = travViz.body();

    addTraverseBlock(travViz, beanVar, true);

    JVar retVal = travVizBloc.decl(returnType, "returnVal");

    travVizBloc.assign(retVal, JExpr.invoke(JExpr.invoke("getVisitor"), visitMethodName).arg(beanVar));

    travVizBloc._if(JExpr.ref("progressMonitor").ne(JExpr._null()))._then().invoke(JExpr.ref("progressMonitor"), "visited").arg(beanVar);

    addTraverseBlock(travViz, beanVar, false);

    travVizBloc._return(retVal);
}
 
Example 4
Source File: CreateTraversingVisitorClass.java    From jaxb-visitor with Apache License 2.0 6 votes vote down vote up
private void generate(JDefinedClass traversingVisitor, JTypeVar returnType, JTypeVar exceptionType, JClass implClass) {
    // add method impl to traversing visitor
    JMethod travViz;
    travViz = traversingVisitor.method(JMod.PUBLIC, returnType, visitMethodNamer.apply(implClass.name()));
    travViz._throws(exceptionType);
    JVar beanVar = travViz.param(implClass, "aBean");
    travViz.annotate(Override.class);
    JBlock travVizBloc = travViz.body();

    addTraverseBlock(travViz, beanVar, true);

    JVar retVal = travVizBloc.decl(returnType, "returnVal");
    travVizBloc.assign(retVal,
            JExpr.invoke(beanVar, "accept").arg(JExpr.invoke("getVisitor")));
    travVizBloc._if(JExpr.ref("progressMonitor").ne(JExpr._null()))._then().invoke(JExpr.ref("progressMonitor"), "visited").arg(beanVar);

    // case to traverse after the visit
    addTraverseBlock(travViz, beanVar, false);
    travVizBloc._return(retVal);
}
 
Example 5
Source File: AbstractWrappingField.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void setCore(JBlock block, JExpression value) {
	if (coreField != null) {
		block.assign(coreField, value);
	} else {
		block.invoke("set" + core.getName(true)).arg(value);
	}
}
 
Example 6
Source File: SingleElementField.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected JMethod createSetter() {
	final MethodWriter writer = outline.createMethodWriter();

	final JMethod setter = writer.declareMethod(codeModel.VOID,
			getSetterName());
	final JVar var = writer.addParameter(exposedType, prop.getName(false));
	final JBlock block = setter.body();
	block.assign(field, var);
	block.assign(nameField, codeModel.ref(JAXBElementUtils.class)
			.staticInvoke("getName").arg(var));
	block.assign(valueField, codeModel.ref(JAXBElementUtils.class)
			.staticInvoke("getValue").arg(var));
	return setter;
}
 
Example 7
Source File: EvaluationVisitor.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public HoldingContainer visitQuotedStringConstant(QuotedString e, ClassGenerator<?> generator)
    throws RuntimeException {
  CompleteType completeType = CompleteType.VARCHAR;
  JBlock setup = generator.getBlock(BlockType.SETUP);
  JType holderType = CodeModelArrowHelper.getHolderType(completeType, generator.getModel());
  JVar var = generator.declareClassField("string", holderType);
  JExpression stringLiteral = JExpr.lit(e.value);
  JExpression buffer = JExpr.direct("context").invoke("getManagedBuffer");
  setup.assign(var,
      generator.getModel().ref(ValueHolderHelper.class).staticInvoke("getNullableVarCharHolder").arg(buffer).arg(stringLiteral));
  return new HoldingContainer((completeType), var, var.ref("value"), var.ref("isSet"));
}
 
Example 8
Source File: BoundPropertiesPlugin.java    From jaxb2-rich-contract-plugin with MIT License 4 votes vote down vote up
@Override
public boolean run(final Outline outline, final Options opt, final ErrorHandler errorHandler) throws SAXException {

	if (!this.constrained && !this.bound) {
		return true;
	}

	final PluginContext pluginContext = PluginContext.get(outline, opt, errorHandler);

	final JCodeModel m = outline.getCodeModel();

	if (this.generateTools) {
		// generate bound collection helper classes
		pluginContext.writeSourceFile(BoundList.class);
		pluginContext.writeSourceFile(BoundListProxy.class);
		pluginContext.writeSourceFile(CollectionChangeEventType.class);
		pluginContext.writeSourceFile(CollectionChangeEvent.class);
		pluginContext.writeSourceFile(CollectionChangeListener.class);
		pluginContext.writeSourceFile(VetoableCollectionChangeListener.class);
	}

	if(pluginContext.hasPlugin(ImmutablePlugin.class)) {
		errorHandler.error(new SAXParseException(getMessage("error.immutableAndConstrainedProperties"), outline.getModel().getLocator()));
	}

	final int setterAccess = JMod.PUBLIC;

	for (final ClassOutline classOutline : outline.getClasses()) {
		final JDefinedClass definedClass = classOutline.implClass;

		// Create bound collection proxies
		for (final FieldOutline fieldOutline : classOutline.getDeclaredFields()) {
			if (fieldOutline.getPropertyInfo().isCollection() && !definedClass.fields().get(fieldOutline.getPropertyInfo().getName(false)).type().isArray()) {
				generateProxyField(classOutline, fieldOutline);
				generateLazyProxyInitGetter(classOutline, fieldOutline);
			}
		}


		if (this.constrained && this.setterThrows) {
			for (final JMethod method : definedClass.methods()) {
				if (method.name().startsWith("with")
						&& !"withVetoableChangeListener".equals(method.name())
						&& !"withPropertyChangeListener".equals(method.name())
						) {
					method._throws(PropertyVetoException.class);
				}
			}
		}

		if (this.constrained)
			createSupportProperty(outline, classOutline, VetoableChangeSupport.class, VetoableChangeListener.class, "vetoableChange");
		if (this.bound)
			createSupportProperty(outline, classOutline, PropertyChangeSupport.class, PropertyChangeListener.class, "propertyChange");


		for (final JFieldVar field : definedClass.fields().values()) {
			//final JFieldVar field = definedClass.fields().get(fieldOutline.getPropertyInfo().getName(false));
			final JMethod oldSetter = definedClass.getMethod("set" + outline.getModel().getNameConverter().toPropertyName(field.name()), new JType[]{field.type()});
			if (oldSetter != null && !field.type().isArray()) {
				definedClass.methods().remove(oldSetter);
				final JMethod setter = definedClass.method(setterAccess, m.VOID, "set" + outline.getModel().getNameConverter().toPropertyName(field.name()));
				final JVar setterArg = setter.param(JMod.FINAL, field.type(), "value");
				final JBlock body = setter.body();
				final JVar oldValueVar = body.decl(JMod.FINAL, field.type(), BoundPropertiesPlugin.OLD_VALUE_VAR_NAME, JExpr._this().ref(field));

				if (this.constrained) {
					final JTryBlock tryBlock;
					final JBlock block;
					if (this.setterThrows) {
						block = body;
						setter._throws(PropertyVetoException.class);
					} else {
						tryBlock = body._try();
						block = tryBlock.body();
						final JCatchBlock catchBlock = tryBlock._catch(m.ref(PropertyVetoException.class));
						final JVar exceptionVar = catchBlock.param("x");
						catchBlock.body()._throw(JExpr._new(m.ref(RuntimeException.class)).arg(exceptionVar));
					}
					invokeListener(block, field, oldValueVar, setterArg, "vetoableChange");
				}

				body.assign(JExpr._this().ref(field), setterArg);

				if (this.bound) {
					invokeListener(body, field, oldValueVar, setterArg, "propertyChange");
				}
			}
		}
	}
	return true;
}
 
Example 9
Source File: HiveFuncHolder.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
private HoldingContainer generateEval(ClassGenerator<?> g, HoldingContainer[] inputVariables, JVar[] workspaceJVars) {

    HoldingContainer out = g.declare(returnType);

    JCodeModel m = g.getModel();
    JBlock sub = new JBlock(true, true);

    // initialize DeferredObject's. For an optional type, assign the value holder only if it is not null
    for(int i=0; i<argTypes.length; i++) {
      sub.assign(workspaceJVars[3].component(JExpr.lit(i)), workspaceJVars[2].component(JExpr.lit(i)));
      JBlock conditionalBlock = new JBlock(false, false);
      JConditional jc = conditionalBlock._if(inputVariables[i].getIsSet().ne(JExpr.lit(0)));
      jc._then().assign(JExpr.ref(workspaceJVars[3].component(JExpr.lit(i)), "valueHolder"), inputVariables[i].getHolder());
      jc._else().assign(JExpr.ref(workspaceJVars[3].component(JExpr.lit(i)), "valueHolder"), JExpr._null());
      sub.add(conditionalBlock);
    }

    // declare generic object for storing return value from GenericUDF.evaluate
    JVar retVal = sub.decl(m._ref(Object.class), "ret");

    // create try..catch block to call the GenericUDF instance with given input
    JTryBlock udfEvalTry = sub._try();
    udfEvalTry.body().assign(retVal,
      workspaceJVars[1].invoke("evaluate").arg(workspaceJVars[3]));

    JCatchBlock udfEvalCatch = udfEvalTry._catch(m.directClass(Exception.class.getCanonicalName()));
    JVar exVar = udfEvalCatch.param("ex");
    udfEvalCatch.body()
      ._throw(JExpr._new(m.directClass(RuntimeException.class.getCanonicalName()))
        .arg(JExpr.lit(String.format("GenericUDF.evaluate method failed"))).arg(exVar));

    // get the ValueHolder from retVal and return ObjectInspector
    sub.add(ObjectInspectorHelper.getObject(m, returnOI, workspaceJVars[0], workspaceJVars[4], retVal));
    sub.assign(out.getHolder(), workspaceJVars[4]);

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

    return out;
  }
 
Example 10
Source File: DrillSimpleFuncHolder.java    From Bats with Apache License 2.0 4 votes vote down vote up
protected HoldingContainer generateEvalBody(ClassGenerator<?> g, HoldingContainer[] inputVariables, String body,
                                            JVar[] workspaceJVars, FieldReference ref) {

  g.getEvalBlock().directStatement(String.format("//---- start of eval portion of %s function. ----//", getRegisteredNames()[0]));

  JBlock sub = new JBlock(true, true);
  JBlock topSub = sub;
  HoldingContainer out = null;
  MajorType returnValueType = getReturnType();

  // add outside null handling if it is defined.
  if (getNullHandling() == NullHandling.NULL_IF_NULL) {
    JExpression e = null;
    for (HoldingContainer v : inputVariables) {
      if (v.isOptional()) {
        JExpression isNullExpr;
        if (v.isReader()) {
         isNullExpr = JOp.cond(v.getHolder().invoke("isSet"), JExpr.lit(1), JExpr.lit(0));
        } else {
          isNullExpr = v.getIsSet();
        }
        if (e == null) {
          e = isNullExpr;
        } else {
          e = e.mul(isNullExpr);
        }
      }
    }

    if (e != null) {
      // if at least one expression must be checked, set up the conditional.
      returnValueType = getReturnType().toBuilder().setMode(DataMode.OPTIONAL).build();
      out = g.declare(returnValueType);
      e = e.eq(JExpr.lit(0));
      JConditional jc = sub._if(e);
      jc._then().assign(out.getIsSet(), JExpr.lit(0));
      sub = jc._else();
    }
  }

  if (out == null) {
    out = g.declare(returnValueType);
  }

  // add the subblock after the out declaration.
  g.getEvalBlock().add(topSub);


  JVar internalOutput = sub.decl(JMod.FINAL, g.getHolderType(returnValueType), getReturnValue().getName(), JExpr._new(g.getHolderType(returnValueType)));
  addProtectedBlock(g, sub, body, inputVariables, workspaceJVars, false);

  List<String> holderFields = ValueHolderHelper.getHolderParams(returnValueType);
  for (String holderField : holderFields) {
    sub.assign(out.f(holderField), internalOutput.ref(holderField));
  }

  if (sub != topSub) {
    sub.assign(out.f("isSet"),JExpr.lit(1));  // Assign null if NULL_IF_NULL mode
  }

  g.getEvalBlock().directStatement(String.format("//---- end of eval portion of %s function. ----//", getRegisteredNames()[0]));

  return out;
}
 
Example 11
Source File: AbstractWrapCollectionField.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void unsetValues(JBlock body) {
	body.assign(propertyField, JExpr._null());
}
 
Example 12
Source File: AbstractWrapCollectionField.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public final void toRawValue(JBlock block, JVar $var) {
	block.assign($var, $target.invoke(getter));
}
 
Example 13
Source File: FastDeserializerGenerator.java    From avro-fastserde with Apache License 2.0 4 votes vote down vote up
private void processArray(JVar arraySchemaVar, final String name, final Schema arraySchema,
        final Schema readerArraySchema, JBlock parentBody, FieldAction action,
        BiConsumer<JBlock, JExpression> putArrayIntoParent) {

    if (action.getShouldRead()) {
        Symbol valuesActionSymbol = null;
        for (Symbol symbol : action.getSymbol().production) {
            if (Symbol.Kind.REPEATER.equals(symbol.kind)
                    && "array-end".equals(getSymbolPrintName(((Symbol.Repeater) symbol).end))) {
                valuesActionSymbol = symbol;
                break;
            }
        }

        if (valuesActionSymbol == null) {
            throw new FastDeserializerGeneratorException("Unable to determine action for array: " + name);
        }

        action = FieldAction.fromValues(arraySchema.getElementType().getType(), action.getShouldRead(),
                valuesActionSymbol);
    } else {
        action = FieldAction.fromValues(arraySchema.getElementType().getType(), false, EMPTY_SYMBOL);
    }

    final JVar arrayVar = action.getShouldRead() ? declareValueVar(name, readerArraySchema, parentBody) : null;
    JVar chunkLen = parentBody.decl(codeModel.LONG, getVariableName("chunkLen"),
            JExpr.direct(DECODER + ".readArrayStart()"));

    JConditional conditional = parentBody._if(chunkLen.gt(JExpr.lit(0)));
    JBlock ifBlock = conditional._then();

    JClass arrayClass = schemaAssistant.classFromSchema(action.getShouldRead() ? readerArraySchema : arraySchema, false);

    if (action.getShouldRead()) {
        JInvocation newArrayExp = JExpr._new(arrayClass);
        if (useGenericTypes) {
            newArrayExp = newArrayExp.arg(JExpr.cast(codeModel.INT, chunkLen)).arg(getSchemaExpr(arraySchema));
        }
        ifBlock.assign(arrayVar, newArrayExp);
        JBlock elseBlock = conditional._else();
        if (useGenericTypes) {
            elseBlock.assign(arrayVar, JExpr._new(arrayClass).arg(JExpr.lit(0)).arg(getSchemaExpr(arraySchema)));
        } else {
            elseBlock.assign(arrayVar, codeModel.ref(Collections.class).staticInvoke("emptyList"));
        }
    }

    JDoLoop doLoop = ifBlock._do(chunkLen.gt(JExpr.lit(0)));
    JForLoop forLoop = doLoop.body()._for();
    JVar counter = forLoop.init(codeModel.INT, getVariableName("counter"), JExpr.lit(0));
    forLoop.test(counter.lt(chunkLen));
    forLoop.update(counter.incr());
    JBlock forBody = forLoop.body();

    JVar elementSchemaVar = null;
    BiConsumer<JBlock, JExpression> putValueInArray = null;
    if (action.getShouldRead()) {
        putValueInArray = (block, expression) -> block.invoke(arrayVar, "add").arg(expression);
        if (useGenericTypes) {
            elementSchemaVar = declareSchemaVar(arraySchema.getElementType(), name + "ArrayElemSchema",
                    arraySchemaVar.invoke("getElementType"));
        }
    }

    if (SchemaAssistant.isComplexType(arraySchema.getElementType())) {
        String elemName = name + "Elem";
        Schema readerArrayElementSchema = action.getShouldRead() ? readerArraySchema.getElementType() : null;
        processComplexType(elementSchemaVar, elemName, arraySchema.getElementType(), readerArrayElementSchema,
                forBody, action, putValueInArray);
    } else {
        // to preserve reader string specific options use reader array schema
        if (action.getShouldRead() && Schema.Type.STRING.equals(arraySchema.getElementType().getType())) {
            processSimpleType(readerArraySchema.getElementType(), forBody, action, putValueInArray);
        } else {
            processSimpleType(arraySchema.getElementType(), forBody, action, putValueInArray);
        }
    }
    doLoop.body().assign(chunkLen, JExpr.direct(DECODER + ".arrayNext()"));

    if (action.getShouldRead()) {
        putArrayIntoParent.accept(parentBody, arrayVar);
    }
}
 
Example 14
Source File: ConstantPropertyOutline.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void get(JBlock block, JVar variable) {
	block.assign(variable, ConstantPropertyOutline.this.referenceClass
			.staticRef(ConstantPropertyOutline.this.field));
}
 
Example 15
Source File: GetSetVectorHelper.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
public static void read(CompleteType ct, JExpression vector, JBlock eval, HoldingContainer out, JCodeModel model,
                        JExpression indexVariable) {

  MinorType type = ct.toMinorType();

    eval.assign(out.getIsSet(), vector.invoke("isSet").arg(indexVariable));
    eval = eval._if(out.getIsSet().eq(JExpr.lit(1)))._then();
    switch (type) {
    case BIGINT:
    case FLOAT4:
    case FLOAT8:
    case INT:
    case MONEY:
    case SMALLINT:
    case TINYINT:
    case UINT1:
    case UINT2:
    case UINT4:
    case UINT8:
    case INTERVALYEAR:
    case DATE:
    case TIME:
    case TIMESTAMP:
    case BIT:
      eval.assign(out.getValue(), vector.invoke("get").arg(indexVariable));
      return;
    case DECIMAL:
      eval.assign(out.getHolder().ref("scale"), JExpr.lit(ct.getType(Decimal.class).getScale()));
      eval.assign(out.getHolder().ref("precision"), JExpr.lit(ct.getType(Decimal.class).getPrecision()));
      eval.assign(out.getHolder().ref("start"), JExpr.lit(TypeHelper.getSize(getArrowMinorType(type))).mul(indexVariable));
      eval.assign(out.getHolder().ref("buffer"), vector.invoke("getDataBuffer"));
      return;
    case INTERVALDAY: {
      JVar start = eval.decl(model.INT, "start", JExpr.lit(TypeHelper.getSize(getArrowMinorType(type))).mul(indexVariable));
      eval.assign(out.getHolder().ref("days"), vector.invoke("getDataBuffer").invoke("getInt").arg(start));
      eval.assign(out.getHolder().ref("milliseconds"), vector.invoke("getDataBuffer").invoke("getInt").arg(start.plus(JExpr.lit(4))));
      return;
    }
    case VARBINARY:
    case VARCHAR:
       eval.assign(out.getHolder().ref("buffer"), vector.invoke("getDataBuffer"));
       JVar se = eval.decl(model.LONG, "startEnd", vector.invoke("getStartEnd").arg(indexVariable));
       eval.assign(out.getHolder().ref("start"), JExpr.cast(model._ref(int.class), se));
       eval.assign(out.getHolder().ref("end"), JExpr.cast(model._ref(int.class), se.shr(JExpr.lit(32))));
      return;

    }

  // fallback.
  eval.add(vector.invoke("get").arg(indexVariable).arg(out.getHolder()));
}
 
Example 16
Source File: ImmutablePlugin.java    From jaxb2-rich-contract-plugin with MIT License 4 votes vote down vote up
public void immutableInit(final PluginContext pluginContext, final JBlock body, final JExpression instanceRef, final JFieldVar declaredField) {
	if(!this.fake) {
		body.assign(instanceRef.ref(getImmutableFieldName(declaredField)), PluginUtil.nullSafe(declaredField, generateImmutableListInstantiation(pluginContext, instanceRef.ref(declaredField), ((JClass)declaredField.type()).getTypeParameters().get(0))));
	}
}
 
Example 17
Source File: SingleField.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void unsetValues(JBlock body) {
	body.assign($ref, JExpr._null());
}
 
Example 18
Source File: EvaluationVisitor.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
private HoldingContainer visitBooleanAnd(BooleanOperator op,
    ClassGenerator<?> generator) {

  HoldingContainer out = generator.declare(op.getCompleteType());

  JLabel label = generator.getEvalBlockLabel("AndOP");
  JBlock eval = generator.createInnerEvalBlock();
  generator.nestEvalBlock(eval);  // enter into nested block

  HoldingContainer arg = null;

  JExpression e = null;

  //  value of boolean "and" when one side is null
  //    p       q     p and q
  //    true    null     null
  //    false   null     false
  //    null    true     null
  //    null    false    false
  //    null    null     null
  for (int i = 0; i < op.args.size(); i++) {
    arg = op.args.get(i).accept(this, generator);

    JBlock earlyExit = null;
      earlyExit = eval._if(arg.getIsSet().eq(JExpr.lit(1)).cand(arg.getValue().ne(JExpr.lit(1))))._then();
      if (e == null) {
        e = arg.getIsSet();
      } else {
        e = e.mul(arg.getIsSet());
      }
    earlyExit.assign(out.getIsSet(), JExpr.lit(1));

    earlyExit.assign(out.getValue(),  JExpr.lit(0));
    earlyExit._break(label);
  }

  assert (e != null);

  JConditional notSetJC = eval._if(e.eq(JExpr.lit(0)));
  notSetJC._then().assign(out.getIsSet(), JExpr.lit(0));

  JBlock setBlock = notSetJC._else().block();
  setBlock.assign(out.getIsSet(), JExpr.lit(1));
  setBlock.assign(out.getValue(), JExpr.lit(1));

  generator.unNestEvalBlock();     // exit from nested block

  return out;
}
 
Example 19
Source File: AbstractWrappingField.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public final void toRawValue(JBlock block, JVar $var) {
	block.assign($var, $target.invoke(getter));
}
 
Example 20
Source File: EvaluationVisitor.java    From Bats with Apache License 2.0 4 votes vote down vote up
private HoldingContainer visitBooleanAnd(BooleanOperator op,
    ClassGenerator<?> generator) {

  HoldingContainer out = generator.declare(op.getMajorType());

  JLabel label = generator.getEvalBlockLabel("AndOP");
  JBlock eval = generator.createInnerEvalBlock();
  generator.nestEvalBlock(eval);  // enter into nested block

  HoldingContainer arg = null;

  JExpression e = null;

  //  value of boolean "and" when one side is null
  //    p       q     p and q
  //    true    null     null
  //    false   null     false
  //    null    true     null
  //    null    false    false
  //    null    null     null
  for (int i = 0; i < op.args.size(); i++) {
    arg = op.args.get(i).accept(this, generator);

    JBlock earlyExit = null;
    if (arg.isOptional()) {
      earlyExit = eval._if(arg.getIsSet().eq(JExpr.lit(1)).cand(arg.getValue().ne(JExpr.lit(1))))._then();
      if (e == null) {
        e = arg.getIsSet();
      } else {
        e = e.mul(arg.getIsSet());
      }
    } else {
      earlyExit = eval._if(arg.getValue().ne(JExpr.lit(1)))._then();
    }

    if (out.isOptional()) {
      earlyExit.assign(out.getIsSet(), JExpr.lit(1));
    }

    earlyExit.assign(out.getValue(),  JExpr.lit(0));
    earlyExit._break(label);
  }

  if (out.isOptional()) {
    assert (e != null);

    JConditional notSetJC = eval._if(e.eq(JExpr.lit(0)));
    notSetJC._then().assign(out.getIsSet(), JExpr.lit(0));

    JBlock setBlock = notSetJC._else().block();
    setBlock.assign(out.getIsSet(), JExpr.lit(1));
    setBlock.assign(out.getValue(), JExpr.lit(1));
  } else {
    assert (e == null);
    eval.assign(out.getValue(), JExpr.lit(1));
  }

  generator.unNestEvalBlock();     // exit from nested block

  return out;
}