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

The following examples show how to use com.sun.codemodel.JBlock#decl() . 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: JaxRsEnumRule.java    From apicurio-studio with Apache License 2.0 6 votes vote down vote up
private void addFactoryMethod(JDefinedClass _enum, JType backingType) {
    JFieldVar quickLookupMap = addQuickLookupMap(_enum, backingType);

    JMethod fromValue = _enum.method(JMod.PUBLIC | JMod.STATIC, _enum, "fromValue");
    JVar valueParam = fromValue.param(backingType, "value");

    JBlock body = fromValue.body();
    JVar constant = body.decl(_enum, "constant");
    constant.init(quickLookupMap.invoke("get").arg(valueParam));

    JConditional _if = body._if(constant.eq(JExpr._null()));

    JInvocation illegalArgumentException = JExpr._new(_enum.owner().ref(IllegalArgumentException.class));
    JExpression expr = valueParam;

    // if string no need to add ""
    if(!isString(backingType)){
        expr = expr.plus(JExpr.lit(""));
    }
    
    illegalArgumentException.arg(expr);
    _if._then()._throw(illegalArgumentException);
    _if._else()._return(constant);

    ruleFactory.getAnnotator().enumCreatorMethod(_enum, fromValue);
}
 
Example 2
Source File: CopyablePlugin.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 6 votes vote down vote up
protected JMethod generateCopyTo$copyTo(final ClassOutline classOutline,
		final JDefinedClass theClass) {

	final JCodeModel codeModel = theClass.owner();
	final JMethod copyTo$copyTo = theClass.method(JMod.PUBLIC,
			codeModel.ref(Object.class), "copyTo");
	copyTo$copyTo.annotate(Override.class);
	{
		final JVar target = copyTo$copyTo.param(Object.class, "target");

		final JBlock body = copyTo$copyTo.body();
		final JVar copyStrategy = body.decl(JMod.FINAL,
				codeModel.ref(CopyStrategy2.class), "strategy",
				createCopyStrategy(codeModel));

		body._return(JExpr.invoke("copyTo").arg(JExpr._null()).arg(target)
				.arg(copyStrategy));
	}
	return copyTo$copyTo;
}
 
Example 3
Source File: EqualsArguments.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public EqualsArguments element(JBlock subBlock, JType elementType) {
	final JVar leftElementValue = subBlock.decl(JMod.FINAL, elementType,
			leftValue().name() + "Element", leftValue().invoke("next"));
	final JVar rightElementValue = subBlock.decl(JMod.FINAL, elementType,
			rightValue().name() + "Element", rightValue().invoke("next"));
	// if (!(o1==null ? o2==null : o1.equals(o2)))
	// return false;
	final boolean isElementAlwaysSet = elementType.isPrimitive();
	final JExpression leftElementHasSetValue = isElementAlwaysSet ? JExpr.TRUE
			: leftElementValue.ne(JExpr._null());
	final JExpression rightElementHasSetValue = isElementAlwaysSet ? JExpr.TRUE
			: rightElementValue.ne(JExpr._null());
	return spawn(leftElementValue, leftElementHasSetValue,
			rightElementValue, rightElementHasSetValue);

}
 
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: DeepCopyGenerator.java    From jaxb2-rich-contract-plugin with MIT License 6 votes vote down vote up
JMethod generateCreateCopyMethod(final boolean partial) {
	final JDefinedClass definedClass = this.classOutline.implClass;

	final JMethod cloneMethod = definedClass.method(JMod.PUBLIC, definedClass, this.pluginContext.copyMethodName);
	final CopyGenerator cloneGenerator = this.pluginContext.createCopyGenerator(cloneMethod, partial);
	cloneMethod.annotate(Override.class);

	final JBlock body = cloneMethod.body();

	final JVar newObjectVar;
	final boolean superPartialCopyable = this.pluginContext.partialCopyableInterface.isAssignableFrom(definedClass._extends());
	final boolean superCopyable = this.pluginContext.copyableInterface.isAssignableFrom(definedClass._extends());
	if (superPartialCopyable) {
		newObjectVar = body.decl(JMod.FINAL, definedClass, this.pluginContext.newObjectVarName, JExpr.cast(definedClass, cloneGenerator.generatePartialArgs(this.pluginContext.invoke(JExpr._super(), this.pluginContext.copyMethodName))));
	} else if(superCopyable) {
		newObjectVar = body.decl(JMod.FINAL, definedClass, this.pluginContext.newObjectVarName, JExpr.cast(definedClass, JExpr._super().invoke(this.pluginContext.copyMethodName)));
	} else {
		newObjectVar = body.decl(JMod.FINAL, definedClass, this.pluginContext.newObjectVarName, null);
		final JBlock maybeTryBlock = this.pluginContext.catchCloneNotSupported(body, definedClass._extends());
		maybeTryBlock.assign(newObjectVar, JExpr.cast(definedClass, JExpr._super().invoke(this.pluginContext.cloneMethodName)));
	}
	generateFieldCopyExpressions(cloneGenerator, body, newObjectVar, JExpr._this());
	body._return(newObjectVar);
	return cloneMethod;
}
 
Example 6
Source File: EqualsPlugin.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 6 votes vote down vote up
protected JMethod generateObject$equals(final ClassOutline classOutline,
		final JDefinedClass theClass) {
	final JCodeModel codeModel = theClass.owner();
	final JMethod objectEquals = theClass.method(JMod.PUBLIC,
			codeModel.BOOLEAN, "equals");
	objectEquals.annotate(Override.class);
	{
		final JVar object = objectEquals.param(Object.class, "object");
		final JBlock body = objectEquals.body();
		final JVar equalsStrategy = body.decl(JMod.FINAL,
				codeModel.ref(EqualsStrategy2.class), "strategy",
				createEqualsStrategy(codeModel));
		body._return(JExpr.invoke("equals").arg(JExpr._null())
				.arg(JExpr._null()).arg(object).arg(equalsStrategy));
	}
	return objectEquals;
}
 
Example 7
Source File: PluginImpl.java    From immutable-xjc with MIT License 6 votes vote down vote up
private void replaceCollectionGetter(JDefinedClass ownerClass, JFieldVar field, final JMethod getter) {
    // remove the old getter
    ownerClass.methods().remove(getter);
    // and create a new one
    JMethod newGetter = ownerClass.method(getter.mods().getValue(), getter.type(), getter.name());
    JBlock block = newGetter.body();

    JVar ret = block.decl(getJavaType(field), "ret");
    JCodeModel codeModel = field.type().owner();
    JVar param = generateMethodParameter(getter, field);
    JConditional conditional = block._if(param.eq(JExpr._null()));
    conditional._then().assign(ret, getEmptyCollectionExpression(codeModel, param));
    conditional._else().assign(ret, getUnmodifiableWrappedExpression(codeModel, param));
    block._return(ret);

    getter.javadoc().append("Returns unmodifiable collection.");
}
 
Example 8
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 9
Source File: BaseFunctionHolder.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
protected void addProtectedBlock(ClassGenerator<?> g, JBlock sub, String body, HoldingContainer[] inputVariables,
    JVar[] workspaceJVars, boolean decConstInputOnly) {
  if (inputVariables != null) {
    for (int i = 0; i < inputVariables.length; i++) {
      if (decConstInputOnly && !inputVariables[i].isConstant()) {
        continue;
      }

      ValueReference parameter = parameters[i];
      HoldingContainer inputVariable = inputVariables[i];
      if (parameter.isFieldReader && !inputVariable.isReader() && inputVariable.getCompleteType().isScalar()) {
        JType singularReaderClass = g.getModel()._ref(TypeHelper.getHolderReaderImpl(getArrowMinorType(inputVariable.getCompleteType().toMinorType())));
        JType fieldReadClass = g.getModel()._ref(FieldReader.class);
        sub.decl(fieldReadClass, parameter.name, JExpr._new(singularReaderClass).arg(inputVariable.getHolder()));
      } else {
        sub.decl(inputVariable.getHolder().type(), parameter.name, inputVariable.getHolder());
      }
    }
  }

  JVar[] internalVars = new JVar[workspaceJVars.length];
  for (int i = 0; i < workspaceJVars.length; i++) {
    if (decConstInputOnly) {
      internalVars[i] = sub.decl(g.getModel()._ref(workspaceVars[i].type), workspaceVars[i].name, workspaceJVars[i]);
    } else {
      internalVars[i] = sub.decl(g.getModel()._ref(workspaceVars[i].type), workspaceVars[i].name, workspaceJVars[i]);
    }

  }

  Preconditions.checkNotNull(body);
  sub.directStatement(body);

  // reassign workspace variables back to global space.
  for (int i = 0; i < workspaceJVars.length; i++) {
    sub.assign(workspaceJVars[i], internalVars[i]);
  }
}
 
Example 10
Source File: OperationProcessor.java    From jpmml-evaluator with GNU Affero General Public License v3.0 5 votes vote down vote up
static
private void createReportMethod(JDefinedClass clazz){
	JCodeModel codeModel = clazz.owner();

	JMethod method = clazz.method(JMod.PRIVATE, void.class, "report");

	JVar expressionParameter = method.param(String.class, "expression");

	JBlock body = method.body();

	if((clazz.name()).endsWith("Value")){
		JClass reportClazz = codeModel.ref(Report.class);
		JClass reportEntryClazz = codeModel.ref(Report.Entry.class);

		JVar reportVariable = body.decl(reportClazz, "report", JExpr.invoke("getReport"));
		JVar entryVariable = body.decl(reportEntryClazz, "entry", JExpr._new(reportEntryClazz).arg(expressionParameter).arg(JExpr.invoke("getValue")));

		body.add(reportVariable.invoke("add").arg(entryVariable));
	} else

	if((clazz.name()).endsWith("Vector")){
		body.add(JExpr.invoke("setExpression").arg(expressionParameter));
	} else

	{
		throw new RuntimeException();
	}
}
 
Example 11
Source File: HashCodeArguments.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public HashCodeArguments iterator(JBlock block, JType elementType) {
	final JVar listIterator = block
			.decl(JMod.FINAL, getCodeModel().ref(ListIterator.class)
					.narrow(elementType), value().name() + "ListIterator",
					value().invoke("listIterator"));

	return spawn(listIterator, JExpr.TRUE);
}
 
Example 12
Source File: FastSerializerGenerator.java    From avro-fastserde with Apache License 2.0 5 votes vote down vote up
private JVar declareValueVar(final String name, final Schema schema, JBlock block) {
    if (SchemaAssistant.isComplexType(schema)) {
        return block.decl(schemaAssistant.classFromSchema(schema, true),
                getVariableName(StringUtils.uncapitalize(name)), JExpr._null());
    } else {
        throw new FastDeserializerGeneratorException("Incorrect container variable: " + schema.getType().getName());
    }
}
 
Example 13
Source File: SimpleHashCodePlugin.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
	protected void generate(ClassOutline classOutline, JDefinedClass theClass) {

		final JCodeModel codeModel = theClass.owner();
		final JMethod object$hashCode = theClass.method(JMod.PUBLIC,
				codeModel.INT, "hashCode");
		object$hashCode.annotate(Override.class);
		{
			final JBlock body = object$hashCode.body();

			final JExpression currentHashCodeExpression = JExpr.lit(1);

			final JVar currentHashCode = body.decl(codeModel.INT,
					"currentHashCode", currentHashCodeExpression);

			final Boolean superClassImplementsHashCode = StrategyClassUtils
					.superClassNotIgnored(classOutline, getIgnoring());

			if (superClassImplementsHashCode != null) {
				body.assign(
						currentHashCode,
						currentHashCode.mul(JExpr.lit(getMultiplier())).plus(
								JExpr._super().invoke("hashCode")));
			}

			final FieldOutline[] declaredFields = FieldOutlineUtils.filter(
					classOutline.getDeclaredFields(), getIgnoring());

			if (declaredFields.length > 0) {

				for (final FieldOutline fieldOutline : declaredFields) {
					final FieldAccessorEx fieldAccessor = getFieldAccessorFactory()
							.createFieldAccessor(fieldOutline, JExpr._this());
					if (fieldAccessor.isConstant()) {
						continue;
					}
					final JBlock block = body.block();
					block.assign(currentHashCode,
							currentHashCode.mul(JExpr.lit(getMultiplier())));

					String propertyName = fieldOutline.getPropertyInfo()
							.getName(true);
					final JVar value = block.decl(fieldAccessor.getType(),
							"the" + propertyName);

					fieldAccessor.toRawValue(block, value);
					final JType exposedType = fieldAccessor.getType();

					final Collection<JType> possibleTypes = FieldUtils
							.getPossibleTypes(fieldOutline, Aspect.EXPOSED);
					final boolean isAlwaysSet = fieldAccessor.isAlwaysSet();
//					final JExpression hasSetValue = exposedType.isPrimitive() ? JExpr.TRUE
//							: value.ne(JExpr._null());
					
					final JExpression hasSetValue = (fieldAccessor.isAlwaysSet() || fieldAccessor
							.hasSetValue() == null) ? JExpr.TRUE
							: fieldAccessor.hasSetValue();					
					getCodeGenerator().generate(
							block,
							exposedType,
							possibleTypes,
							isAlwaysSet,
							new HashCodeArguments(codeModel, currentHashCode,
									getMultiplier(), value, hasSetValue));
				}
			}
			body._return(currentHashCode);
		}
	}
 
Example 14
Source File: ClassGenerator.java    From Bats with Apache License 2.0 4 votes vote down vote up
/**
   * Creates class variable for the value vector using metadata from {@code fieldId}
   * and initializes it using setup blocks.
   *
   * @param batchName expression for invoking {@code getValueAccessorById} method
   * @param fieldId   metadata of the field that should be declared
   * @return a newly generated class field
   */
  public JVar declareVectorValueSetupAndMember(DirectExpression batchName, TypedFieldId fieldId) {
    // declares field in the inner class if innerClassGenerator has been created
    if (innerClassGenerator != null) {
      return innerClassGenerator.declareVectorValueSetupAndMember(batchName, fieldId);
    }
    final ValueVectorSetup setup = new ValueVectorSetup(batchName, fieldId);
//    JVar var = this.vvDeclaration.get(setup);
//    if(var != null) return var;

    Class<?> valueVectorClass = fieldId.getIntermediateClass();
    JClass vvClass = model.ref(valueVectorClass);
    JClass retClass = vvClass;
    String vectorAccess = "getValueVector";
    if (fieldId.isHyperReader()) {
      retClass = retClass.array();
      vectorAccess = "getValueVectors";
    }

    JVar vv = declareClassField("vv", retClass);
    JClass t = model.ref(SchemaChangeException.class);
    JType objClass = model.ref(Object.class);
    JBlock b = getSetupBlock();
    //JExpr.newArray(model.INT).

    JVar fieldArr = b.decl(model.INT.array(), "fieldIds" + index++, JExpr.newArray(model.INT, fieldId.getFieldIds().length));
    int[] fieldIndices = fieldId.getFieldIds();
    for (int i = 0; i < fieldIndices.length; i++) {
       b.assign(fieldArr.component(JExpr.lit(i)), JExpr.lit(fieldIndices[i]));
    }

    JInvocation invoke = batchName
        .invoke("getValueAccessorById") //
        .arg(vvClass.dotclass())
        .arg(fieldArr);

    JVar obj = b.decl(
        objClass,
        getNextVar("tmp"),
        invoke.invoke(vectorAccess));

    b._if(obj.eq(JExpr._null()))._then()._throw(JExpr._new(t).arg(JExpr.lit(String.format("Failure while loading vector %s with id: %s.", vv.name(), fieldId.toString()))));
    //b.assign(vv, JExpr.cast(retClass, ((JExpression) JExpr.cast(wrapperClass, obj)).invoke(vectorAccess)));
    b.assign(vv, JExpr.cast(retClass, obj));
    vvDeclaration.put(setup, vv);

    return vv;
  }
 
Example 15
Source File: FastSerializerGenerator.java    From avro-fastserde with Apache License 2.0 4 votes vote down vote up
private void processMap(final Schema mapSchema, JExpression mapExpr, JBlock body) {

        final JClass mapClass = schemaAssistant.classFromSchema(mapSchema);
        JClass keyClass = schemaAssistant.keyClassFromMapSchema(mapSchema);

        body.invoke(JExpr.direct(ENCODER), "writeMapStart");

        final JExpression emptyMapCondition = mapExpr.eq(JExpr._null())
                .cor(JExpr.invoke(mapExpr, "isEmpty"));
        final JConditional emptyMapIf = body._if(emptyMapCondition);
        final JBlock emptyMapBlock = emptyMapIf._then();
        emptyMapBlock.invoke(JExpr.direct(ENCODER), "setItemCount").arg(JExpr.lit(0));

        final JBlock nonEmptyMapBlock = emptyMapIf._else();
        nonEmptyMapBlock.invoke(JExpr.direct(ENCODER), "setItemCount")
                .arg(JExpr.invoke(mapExpr, "size"));

        final JForEach mapKeysLoop = nonEmptyMapBlock.forEach(keyClass, getVariableName("key"),
                JExpr.invoke(JExpr.cast(mapClass, mapExpr), "keySet"));

        final JBlock forBody = mapKeysLoop.body();
        forBody.invoke(JExpr.direct(ENCODER), "startItem");

        JVar keyStringVar;
        if (SchemaAssistant.hasStringableKey(mapSchema)) {
            keyStringVar = forBody.decl(string, getVariableName("keyString"),
                    mapKeysLoop.var().invoke("toString"));
        } else {
            keyStringVar = mapKeysLoop.var();
        }

        final Schema valueSchema = mapSchema.getValueType();

        forBody.invoke(JExpr.direct(ENCODER), "writeString").arg(keyStringVar);

        JVar containerVar;
        if (SchemaAssistant.isComplexType(valueSchema)) {
            containerVar = declareValueVar(valueSchema.getName(), valueSchema, forBody);
            forBody.assign(containerVar, JExpr.invoke(JExpr.cast(mapClass, mapExpr), "get").arg(mapKeysLoop.var()));

            processComplexType(valueSchema, containerVar, forBody);
        } else {
            processSimpleType(valueSchema, mapExpr.invoke("get").arg(mapKeysLoop.var()), forBody);
        }
        body.invoke(JExpr.direct(ENCODER), "writeMapEnd");
    }
 
Example 16
Source File: FastDeserializerGenerator.java    From avro-fastserde with Apache License 2.0 4 votes vote down vote up
private void processEnum(final Schema schema, final JBlock body, FieldAction action,
        BiConsumer<JBlock, JExpression> putEnumIntoParent) {

    if (action.getShouldRead()) {

        Symbol.EnumAdjustAction enumAdjustAction = null;
        if (action.getSymbol() instanceof Symbol.EnumAdjustAction) {
            enumAdjustAction = (Symbol.EnumAdjustAction) action.getSymbol();
        } else {
            for (Symbol symbol : action.getSymbol().production) {
                if (symbol instanceof Symbol.EnumAdjustAction) {
                    enumAdjustAction = (Symbol.EnumAdjustAction) symbol;
                }
            }
        }

        boolean enumOrderCorrect = true;
        for (int i = 0; i < enumAdjustAction.adjustments.length; i++) {
            Object adjustment = enumAdjustAction.adjustments[i];
            if (adjustment instanceof String) {
                throw new FastDeserializerGeneratorException(
                        schema.getName() + " enum label impossible to deserialize: " + adjustment.toString());
            } else if (!adjustment.equals(i)) {
                enumOrderCorrect = false;
            }
        }

        JExpression newEnum;
        JExpression enumValueExpr = JExpr.direct(DECODER + ".readEnum()");

        if (enumOrderCorrect) {
            newEnum = schemaAssistant.getEnumValueByIndex(schema, enumValueExpr, getSchemaExpr(schema));
        } else {
            JVar enumIndex = body.decl(codeModel.INT, getVariableName("enumIndex"), enumValueExpr);
            JClass enumClass = schemaAssistant.classFromSchema(schema);
            newEnum = body.decl(enumClass, getVariableName("enumValue"), JExpr._null());

            for (int i = 0; i < enumAdjustAction.adjustments.length; i++) {
                JExpression ithVal = schemaAssistant
                        .getEnumValueByIndex(schema, JExpr.lit((Integer) enumAdjustAction.adjustments[i]),
                                getSchemaExpr(schema));
                body._if(enumIndex.eq(JExpr.lit(i)))._then().assign((JVar) newEnum, ithVal);
            }
        }
        putEnumIntoParent.accept(body, newEnum);
    } else {
        body.directStatement(DECODER + ".readEnum();");
    }

}
 
Example 17
Source File: FastDeserializerGenerator.java    From avro-fastserde with Apache License 2.0 4 votes vote down vote up
private void processMap(JVar mapSchemaVar, final String name, final Schema mapSchema, final Schema readerMapSchema,
        JBlock parentBody, FieldAction action, BiConsumer<JBlock, JExpression> putMapIntoParent) {

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

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

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

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

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

    if (action.getShouldRead()) {
        ifBlock.assign(mapVar, JExpr._new(schemaAssistant.classFromSchema(readerMapSchema, false)));
        JBlock elseBlock = conditional._else();
        elseBlock.assign(mapVar, codeModel.ref(Collections.class).staticInvoke("emptyMap"));
    }

    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();

    JClass keyClass = schemaAssistant.keyClassFromMapSchema(action.getShouldRead() ? readerMapSchema : mapSchema);
    JExpression keyValueExpression = (string.equals(keyClass)) ?
            JExpr.direct(DECODER + ".readString()")
            : JExpr.direct(DECODER + ".readString(null)");

    if (SchemaAssistant.hasStringableKey(mapSchema)) {
        keyValueExpression = JExpr._new(keyClass).arg(keyValueExpression.invoke("toString"));
    }

    JVar key = forBody.decl(keyClass, getVariableName("key"), keyValueExpression);
    JVar mapValueSchemaVar = null;
    if (action.getShouldRead() && useGenericTypes) {
        mapValueSchemaVar = declareSchemaVar(mapSchema.getValueType(), name + "MapValueSchema",
                mapSchemaVar.invoke("getValueType"));
    }

    BiConsumer<JBlock, JExpression> putValueInMap = null;
    if (action.getShouldRead()) {
        putValueInMap = (block, expression) -> block.invoke(mapVar, "put").arg(key).arg(expression);
    }

    if (SchemaAssistant.isComplexType(mapSchema.getValueType())) {
        String valueName = name + "Value";
        Schema readerMapValueSchema = null;
        if (action.getShouldRead()) {
            readerMapValueSchema = readerMapSchema.getValueType();
        }
        processComplexType(mapValueSchemaVar, valueName, mapSchema.getValueType(), readerMapValueSchema, forBody,
                action, putValueInMap);
    } else {
        // to preserve reader string specific options use reader map schema
        if (action.getShouldRead() && Schema.Type.STRING.equals(mapSchema.getValueType().getType())) {
            processSimpleType(readerMapSchema.getValueType(), forBody, action, putValueInMap);
        } else {
            processSimpleType(mapSchema.getValueType(), forBody, action, putValueInMap);
        }
    }
    doLoop.body().assign(chunkLen, JExpr.direct(DECODER + ".mapNext()"));

    if (action.getShouldRead()) {
        putMapIntoParent.accept(parentBody, mapVar);
    }
}
 
Example 18
Source File: ToStringPlugin.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 4 votes vote down vote up
protected JMethod generateToString$appendFields(ClassOutline classOutline,
		final JDefinedClass theClass) {
	final JCodeModel codeModel = theClass.owner();

	final JMethod toString$appendFields = theClass.method(JMod.PUBLIC,
			codeModel.ref(StringBuilder.class), "appendFields");
	toString$appendFields.annotate(Override.class);
	{
		final JVar locator = toString$appendFields.param(
				ObjectLocator.class, "locator");
		final JVar buffer = toString$appendFields.param(
				StringBuilder.class, "buffer");
		final JVar toStringStrategy = toString$appendFields.param(
				ToStringStrategy2.class, "strategy");
		final JBlock body = toString$appendFields.body();

		final Boolean superClassImplementsToString = StrategyClassUtils
				.superClassImplements(classOutline, ignoring,
						ToString2.class);

		if (superClassImplementsToString == null) {
			// No superclass
		} else if (superClassImplementsToString.booleanValue()) {
			body.invoke(JExpr._super(), "appendFields").arg(locator)
					.arg(buffer).arg(toStringStrategy);
		} else {
			// Superclass does not implement ToString
		}

		final FieldOutline[] declaredFields = FieldOutlineUtils.filter(
				classOutline.getDeclaredFields(), getIgnoring());

		if (declaredFields.length > 0) {

			for (final FieldOutline fieldOutline : declaredFields) {
				final JBlock block = body.block();
				final FieldAccessorEx fieldAccessor = getFieldAccessorFactory()
						.createFieldAccessor(fieldOutline, JExpr._this());
				final JVar theValue = block.decl(
						fieldAccessor.getType(),
						"the"
								+ fieldOutline.getPropertyInfo().getName(
										true));

				final JExpression valueIsSet = (fieldAccessor.isAlwaysSet() || fieldAccessor
						.hasSetValue() == null) ? JExpr.TRUE
						: fieldAccessor.hasSetValue();

				fieldAccessor.toRawValue(block, theValue);

				block.invoke(toStringStrategy, "appendField")
						.arg(locator)
						.arg(JExpr._this())
						.arg(JExpr.lit(fieldOutline.getPropertyInfo()
								.getName(false))).arg(buffer).arg(theValue)
						.arg(valueIsSet);
			}
		}
		body._return(buffer);
	}
	return toString$appendFields;
}
 
Example 19
Source File: HiveFuncHolder.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
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(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("getObjectInspector")
        .arg(mode.staticInvoke("valueOf").arg(JExpr.lit("OPTIONAL")))
        .arg(mt.staticInvoke("valueOf").arg(JExpr.lit(argTypes[i].toMinorType().name())))
        .arg((((PrimitiveObjectInspector) returnOI).getPrimitiveCategory() ==
            PrimitiveObjectInspector.PrimitiveCategory.STRING) ? JExpr.lit(true) : JExpr.lit(false)));
  }

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

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

  // declare empty array for argument deferred objects
  sub.assign(workspaceJVars[3], JExpr.newArray(m._ref(DeferredObject.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.toMinorType()));

  // 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+")" : "")));
}
 
Example 20
Source File: OperationProcessor.java    From jpmml-evaluator with GNU Affero General Public License v3.0 3 votes vote down vote up
static
private void createCopyMethod(JDefinedClass clazz){
	JCodeModel codeModel = clazz.owner();

	JClass reportClazz = codeModel.ref(Report.class);

	JMethod method = clazz.method(JMod.PUBLIC, clazz, "copy");
	method.annotate(Override.class);

	JBlock body = method.body();

	JVar reportVariable = body.decl(reportClazz, "report", JExpr.invoke("getReport"));

	body._return(JExpr._new(clazz).arg(JExpr._super().ref("value")).arg(reportVariable.invoke("copy")).arg(JExpr._null()));
}