com.sun.codemodel.JBlock Java Examples

The following examples show how to use com.sun.codemodel.JBlock. 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: 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 #2
Source File: BuilderGenerator.java    From jaxb2-rich-contract-plugin with MIT License 6 votes vote down vote up
final void generateCopyToMethod(final boolean partial) {
	if (this.implement) {
		final JDefinedClass typeDefinition = this.typeOutline.isInterface() && ((DefinedInterfaceOutline)this.typeOutline).getSupportInterface() != null ? ((DefinedInterfaceOutline)this.typeOutline).getSupportInterface() : this.definedClass;
		final JMethod copyToMethod = typeDefinition.method(JMod.PUBLIC, this.pluginContext.voidType, this.settings.getCopyToMethodName());
		final JTypeVar typeVar = copyToMethod.generify(BuilderGenerator.PARENT_BUILDER_TYPE_PARAMETER_NAME);
		final JVar otherParam = copyToMethod.param(JMod.FINAL, this.builderClass.raw.narrow(typeVar), BuilderGenerator.OTHER_PARAM_NAME);
		final CopyGenerator cloneGenerator = this.pluginContext.createCopyGenerator(copyToMethod, partial);
		final JBlock body = copyToMethod.body();
		final JVar otherRef;
		if (this.typeOutline.getSuperClass() != null) {
			body.add(cloneGenerator.generatePartialArgs(this.pluginContext.invoke(JExpr._super(), copyToMethod.name()).arg(otherParam)));
		}
		otherRef = otherParam;
		generateFieldCopyExpressions(cloneGenerator, body, otherRef, JExpr._this());
		copyToMethod.javadoc().append(JavadocUtils.hardWrapTextForJavadoc(getMessage("javadoc.method.copyTo")));
		copyToMethod.javadoc().addParam(otherParam).append(JavadocUtils.hardWrapTextForJavadoc(getMessage("javadoc.method.copyTo.param.other")));
	}
}
 
Example #3
Source File: FastDeserializerGenerator.java    From avro-util with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void processComplexType(JVar fieldSchemaVar, String name, Schema schema, Schema readerFieldSchema,
    JBlock methodBody, FieldAction action, BiConsumer<JBlock, JExpression> putExpressionIntoParent,
    Supplier<JExpression> reuseSupplier) {
  switch (schema.getType()) {
    case RECORD:
      processRecord(fieldSchemaVar, schema.getName(), schema, readerFieldSchema, methodBody, action,
          putExpressionIntoParent, reuseSupplier);
      break;
    case ARRAY:
      processArray(fieldSchemaVar, name, schema, readerFieldSchema, methodBody, action, putExpressionIntoParent,
          reuseSupplier);
      break;
    case MAP:
      processMap(fieldSchemaVar, name, schema, readerFieldSchema, methodBody, action, putExpressionIntoParent,
          reuseSupplier);
      break;
    case UNION:
      processUnion(fieldSchemaVar, name, schema, readerFieldSchema, methodBody, action, putExpressionIntoParent,
          reuseSupplier);
      break;
    default:
      throw new FastDeserializerGeneratorException("Incorrect complex type: " + action.getType());
  }
}
 
Example #4
Source File: FastSerializerGenerator.java    From avro-fastserde with Apache License 2.0 6 votes vote down vote up
private void processComplexType(Schema schema, JExpression valueExpr, JBlock body) {
    switch (schema.getType()) {
        case RECORD:
            processRecord(schema, valueExpr, body);
            break;
        case ARRAY:
            processArray(schema, valueExpr, body);
            break;
        case UNION:
            processUnion(schema, valueExpr, body);
            break;
        case MAP:
            processMap(schema, valueExpr, body);
            break;
        default:
            throw new FastSerializerGeneratorException("Not a complex schema type: " + schema.getType());
    }

}
 
Example #5
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 #6
Source File: ClassGenerator.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 * The code generator creates a method called __DRILL_INIT__ which takes the
 * place of the constructor when the code goes though the byte code merge.
 * For Plain-old Java, we call the method from a constructor created for
 * that purpose. (Generated code, fortunately, never includes a constructor,
 * so we can create one.) Since the init block throws an exception (which
 * should never occur), the generated constructor converts the checked
 * exception into an unchecked one so as to not require changes to the
 * various places that create instances of the generated classes.
 *
 * Example:<code><pre>
 * public StreamingAggregatorGen1() {
 *       try {
 *         __DRILL_INIT__();
 *     } catch (SchemaChangeException e) {
 *         throw new UnsupportedOperationException(e);
 *     }
 * }</pre></code>
 *
 * Note: in Java 8 we'd use the <tt>Parameter</tt> class defined in Java's
 * introspection package. But, Drill prefers Java 7 which only provides
 * parameter types.
 */

private void addCtor(Class<?>[] parameters) {
  JMethod ctor = clazz.constructor(JMod.PUBLIC);
  JBlock body = ctor.body();

  // If there are parameters, need to pass them to the super class.
  if (parameters.length > 0) {
    JInvocation superCall = JExpr.invoke("super");

    // This case only occurs for nested classes, and all nested classes
    // in Drill are inner classes. Don't pass along the (hidden)
    // this$0 field.

    for (int i = 1; i < parameters.length; i++) {
      Class<?> p = parameters[i];
      superCall.arg(ctor.param(model._ref(p), "arg" + i));
    }
    body.add(superCall);
  }
  JTryBlock tryBlock = body._try();
  tryBlock.body().invoke(SignatureHolder.DRILL_INIT_METHOD);
  JCatchBlock catchBlock = tryBlock._catch(model.ref(SchemaChangeException.class));
  catchBlock.body()._throw(JExpr._new(model.ref(UnsupportedOperationException.class)).arg(catchBlock.param("e")));
}
 
Example #7
Source File: MergeablePlugin.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 6 votes vote down vote up
protected JMethod generateMergeFrom$mergeFrom0(
		final ClassOutline classOutline, final JDefinedClass theClass) {

	JCodeModel codeModel = theClass.owner();
	final JMethod mergeFrom$mergeFrom = theClass.method(JMod.PUBLIC,
			codeModel.VOID, "mergeFrom");
	mergeFrom$mergeFrom.annotate(Override.class);
	{
		final JVar left = mergeFrom$mergeFrom.param(Object.class, "left");
		final JVar right = mergeFrom$mergeFrom.param(Object.class, "right");
		final JBlock body = mergeFrom$mergeFrom.body();

		final JVar mergeStrategy = body.decl(JMod.FINAL,
				codeModel.ref(MergeStrategy2.class), "strategy",
				createMergeStrategy(codeModel));

		body.invoke("mergeFrom").arg(JExpr._null()).arg(JExpr._null())
				.arg(left).arg(right).arg(mergeStrategy);
	}
	return mergeFrom$mergeFrom;
}
 
Example #8
Source File: CopyablePlugin.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 6 votes vote down vote up
protected JMethod generateCopyTo$createNewInstance(
		final ClassOutline classOutline, final JDefinedClass theClass) {

	final JMethod existingMethod = theClass.getMethod("createNewInstance",
			new JType[0]);
	if (existingMethod == null) {

		final JMethod newMethod = theClass.method(JMod.PUBLIC, theClass
				.owner().ref(Object.class), "createNewInstance");
		newMethod.annotate(Override.class);
		{
			final JBlock body = newMethod.body();
			body._return(JExpr._new(theClass));
		}
		return newMethod;
	} else {
		return existingMethod;
	}
}
 
Example #9
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 #10
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 #11
Source File: EqualsArguments.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public JBlock ifHasSetValue(JBlock block, boolean isAlwaysSet,
		boolean checkForNullRequired) {
	if (isAlwaysSet || !checkForNullRequired) {
		return block;
	} else {
		final JConditional ifLeftHasSetValue = block._if(leftHasSetValue());
		final JConditional ifLeftHasSetValueAndRightHasSetValue = ifLeftHasSetValue
				._then()._if(rightHasSetValue());
		final JBlock subBlock = ifLeftHasSetValueAndRightHasSetValue
				._then();
		ifLeftHasSetValueAndRightHasSetValue._else()._return(JExpr.FALSE);
		ifLeftHasSetValue._elseif(rightHasSetValue())._then()
				._return(JExpr.FALSE);
		return subBlock;
	}
}
 
Example #12
Source File: ClientGenerator.java    From raml-module-builder with Apache License 2.0 6 votes vote down vote up
private void addParameter(ParameterDetails details) {
  JBlock b = details.methodBody;
  if (Boolean.TRUE.equals(details.nullCheck)) {
    JConditional ifClause = details.methodBody._if(JExpr.ref(details.valueName).ne(JExpr._null()));
    b = ifClause._then();
  }
  b.invoke(details.queryParams, APPEND).arg(JExpr.lit(details.valueName + "="));
  switch (details.op) {
    case ENCODE:
      encodeParameter(b, details);
      break;
    case FORMAT_DATE:
      formatDateParameter(b, details);
      break;
    case PROCESS_LIST:
      processListParameter(b, details);
      break;
    case NONE:
      b.invoke(details.queryParams, APPEND).arg(JExpr.ref(details.valueName));
      break;
  }
  b.invoke(details.queryParams, APPEND).arg(JExpr.lit("&"));
}
 
Example #13
Source File: BaseFunctionHolder.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
protected void generateBody(ClassGenerator<?> g, BlockType bt, String body, HoldingContainer[] inputVariables,
    JVar[] workspaceJVars, boolean decConstantInputOnly) {
  if (!Strings.isNullOrEmpty(body) && !body.trim().isEmpty()) {
    JBlock sub = new JBlock(true, true);
    if (decConstantInputOnly) {
      addProtectedBlock(g, sub, body, inputVariables, workspaceJVars, true);
    } else {
      addProtectedBlock(g, sub, body, null, workspaceJVars, false);
    }
    g.getBlock(bt).directStatement(String.format("/** start %s for function %s **/ ", bt.name(), registeredNames[0]));
    g.getBlock(bt).add(sub);
    g.getBlock(bt).directStatement(String.format("/** end %s for function %s **/ ", bt.name(), registeredNames[0]));
  }
}
 
Example #14
Source File: PluginImpl.java    From immutable-xjc with MIT License 5 votes vote down vote up
private void generateSuperCall(JMethod method) {
    method.annotate(Override.class);
    JBlock block = method.body();
    JInvocation superInvocation = block.invoke(JExpr._super(), method);
    for (JVar param : method.params()) {
        superInvocation.arg(param);
    }
}
 
Example #15
Source File: FastSerializerGenerator.java    From avro-fastserde with Apache License 2.0 5 votes vote down vote up
private void processArray(final Schema arraySchema, JExpression arrayExpr, JBlock body) {
    final JClass arrayClass = schemaAssistant.classFromSchema(arraySchema);
    body.invoke(JExpr.direct(ENCODER), "writeArrayStart");

    final JExpression emptyArrayCondition = arrayExpr.eq(JExpr._null())
            .cor(JExpr.invoke(arrayExpr, "isEmpty"));

    final JConditional emptyArrayIf = body._if(emptyArrayCondition);
    final JBlock emptyArrayBlock = emptyArrayIf._then();
    emptyArrayBlock.invoke(JExpr.direct(ENCODER), "setItemCount").arg(JExpr.lit(0));

    final JBlock nonEmptyArrayBlock = emptyArrayIf._else();
    nonEmptyArrayBlock.invoke(JExpr.direct(ENCODER), "setItemCount")
            .arg(JExpr.invoke(arrayExpr, "size"));
    final JForLoop forLoop = nonEmptyArrayBlock._for();
    final JVar counter = forLoop.init(codeModel.INT, getVariableName("counter"), JExpr.lit(0));
    forLoop.test(counter.lt(JExpr.invoke(JExpr.cast(arrayClass, arrayExpr), "size")));
    forLoop.update(counter.incr());
    final JBlock forBody = forLoop.body();
    forBody.invoke(JExpr.direct(ENCODER), "startItem");

    final Schema elementSchema = arraySchema.getElementType();
    if (SchemaAssistant.isComplexType(elementSchema)) {
        JVar containerVar = declareValueVar(elementSchema.getName(), elementSchema, forBody);
        forBody.assign(containerVar, JExpr.invoke(JExpr.cast(arrayClass, arrayExpr), "get").arg(counter));
        processComplexType(elementSchema, containerVar, forBody);
    } else {
        processSimpleType(elementSchema, arrayExpr.invoke("get").arg(counter), forBody);
    }

    body.invoke(JExpr.direct(ENCODER), "writeArrayEnd");
}
 
Example #16
Source File: HashCodeCodeGenerationImplementor.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void onLong(HashCodeArguments arguments, JBlock block,
		boolean isAlwaysSet) {
	ifHasSetValueAssignPlusValueHashCode(
			arguments,
			block,
			JExpr.cast(
					getCodeModel().INT,
					arguments.value().xor(
							arguments.value().shrz(JExpr.lit(32)))),
			isAlwaysSet, true);
}
 
Example #17
Source File: AggrFunctionHolder.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private JBlock generateInitWorkspaceBlockHA(ClassGenerator<?> g, BlockType bt, String body, JVar[] workspaceJVars, JExpression wsIndexVariable){
  JBlock initBlock = new JBlock(true, true);
  if(!Strings.isNullOrEmpty(body) && !body.trim().isEmpty()){
    JBlock sub = new JBlock(true, true);
    addProtectedBlockHA(g, sub, body, null, workspaceJVars, wsIndexVariable);
    initBlock.directStatement(String.format("/** start %s for function %s **/ ", bt.name(), registeredNames[0]));
    initBlock.add(sub);
    initBlock.directStatement(String.format("/** end %s for function %s **/ ", bt.name(), registeredNames[0]));
  }
  return initBlock;
}
 
Example #18
Source File: CreateTraversingVisitorClass.java    From jaxb-visitor with Apache License 2.0 5 votes vote down vote up
private void addTraverseBlock(JMethod travViz, JVar beanVar, boolean flag) {
    JBlock travVizBloc = travViz.body();

    // case to traverse before the visit
    JBlock block = travVizBloc._if(JExpr.ref("traverseFirst").eq(JExpr.lit(flag)))._then();
    String traverseMethodName = traverseMethodNamer.apply(beanVar.type().name());
    block.invoke(JExpr.invoke("getTraverser"), traverseMethodName).arg(beanVar).arg(JExpr._this());
    block._if(JExpr.ref("progressMonitor").ne(JExpr._null()))._then().invoke(JExpr.ref("progressMonitor"), "traversed").arg(beanVar);
}
 
Example #19
Source File: ClientGenerator.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
public void generateCloseClient(){
  JMethod jmCreate = method(JMod.PUBLIC, void.class, "close");
  jmCreate.javadoc().add("Close the client. Closing will close down any "
      + "pooled connections. Clients should always be closed after use.");
  JBlock body = jmCreate.body();

  body.directStatement("httpClient.close();");
}
 
Example #20
Source File: BoundPropertiesPlugin.java    From jaxb2-rich-contract-plugin with MIT License 5 votes vote down vote up
private JInvocation invokeListener(final JBlock block, final JFieldVar field, final JVar oldValueVar, final JVar setterArg, final String aspectName) {
	final String aspectNameCap = aspectName.substring(0, 1).toUpperCase() + aspectName.substring(1);
	final JInvocation fvcInvoke = block.invoke(JExpr._this().ref(aspectName + BoundPropertiesPlugin.SUPPORT_FIELD_SUFFIX), "fire" + aspectNameCap);
	fvcInvoke.arg(JExpr.lit(field.name()));
	fvcInvoke.arg(oldValueVar);
	fvcInvoke.arg(setterArg);
	return fvcInvoke;
}
 
Example #21
Source File: FastDeserializerGenerator.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), getVariableName(StringUtils.uncapitalize(name)), JExpr._null());
    } else {
        throw new FastDeserializerGeneratorException("Only complex types allowed!");
    }
}
 
Example #22
Source File: AbstractWrapCollectionField.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected JMethod createGetter() {
	final MethodWriter writer = outline.createMethodWriter();
	final JMethod getter = writer.declareMethod(propertyListType,
			getGetterName());
	final JBlock body = getter.body();
	fix(body);
	body._return(propertyField);
	return getter;
}
 
Example #23
Source File: FastDeserializerGenerator.java    From avro-util with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void processPrimitive(final Schema schema, JBlock body, FieldAction action,
    BiConsumer<JBlock, JExpression> putValueIntoParent, Supplier<JExpression> reuseSupplier) {

  String readFunction;
  switch (schema.getType()) {
    case STRING:
      processString(schema, body, action, putValueIntoParent, reuseSupplier);
      return;
    case BYTES:
      processBytes(body, action, putValueIntoParent, reuseSupplier);
      return;
    case INT:
      readFunction = "readInt()";
      break;
    case LONG:
      readFunction = "readLong()";
      break;
    case FLOAT:
      readFunction = "readFloat()";
      break;
    case DOUBLE:
      readFunction = "readDouble()";
      break;
    case BOOLEAN:
      readFunction = "readBoolean()";
      break;
    default:
      throw new FastDeserializerGeneratorException("Unsupported primitive schema of type: " + schema.getType());
  }

  JExpression primitiveValueExpression = JExpr.direct("decoder." + readFunction);
  if (action.getShouldRead()) {
    putValueIntoParent.accept(body, primitiveValueExpression);
  } else {
    body.directStatement(DECODER + "." + readFunction + ";");
  }
}
 
Example #24
Source File: PluginImpl.java    From immutable-xjc with MIT License 5 votes vote down vote up
private void generatePropertyAssignment(final JMethod method, JFieldVar field, boolean wrapUnmodifiable) {
    JBlock block = method.body();
    JCodeModel codeModel = field.type().owner();
    String fieldName = field.name();
    JVar param = generateMethodParameter(method, field);
    if (isCollection(field) && !leaveCollectionsMutable && wrapUnmodifiable) {
        JConditional conditional = block._if(param.eq(JExpr._null()));
        conditional._then().assign(JExpr.refthis(fieldName), JExpr._null());
        conditional._else().assign(JExpr.refthis(fieldName),
                getDefensiveCopyExpression(codeModel, getJavaType(field), param));
    } else {
        block.assign(JExpr.refthis(fieldName), JExpr.ref(fieldName));
    }
}
 
Example #25
Source File: ClientGenerator.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
private void addConstructorOkapi3Args() {
  JMethod constructor = constructor();
  JVar okapiUrlVar = constructor.param(String.class, OKAPI_URL);
  JVar tenantIdVar = constructor.param(String.class, TENANT_ID);
  JVar tokenVar = constructor.param(String.class, TOKEN);
  JBlock conBody = constructor.body();
  conBody.invoke("this").arg(okapiUrlVar).arg(tenantIdVar).arg(tokenVar).arg(JExpr.TRUE)
    .arg(JExpr.lit(2000)).arg(JExpr.lit(5000));
}
 
Example #26
Source File: FastSerializerGenerator.java    From avro-util with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void processArray(final Schema arraySchema, JExpression arrayExpr, JBlock body) {
  final JClass arrayClass = schemaAssistant.classFromSchema(arraySchema);
  body.invoke(JExpr.direct(ENCODER), "writeArrayStart");

  final JExpression emptyArrayCondition = arrayExpr.eq(JExpr._null()).cor(JExpr.invoke(arrayExpr, "isEmpty"));

  ifCodeGen(body, emptyArrayCondition, then1 -> {
    then1.invoke(JExpr.direct(ENCODER), "setItemCount").arg(JExpr.lit(0));
  }, else1 -> {
    else1.invoke(JExpr.direct(ENCODER), "setItemCount").arg(JExpr.invoke(arrayExpr, "size"));

    if (SchemaAssistant.isPrimitive(arraySchema.getElementType())) {
      JClass primitiveListInterface = schemaAssistant.classFromSchema(arraySchema, true, false, true);
      final JExpression primitiveListCondition = arrayExpr._instanceof(primitiveListInterface);
      ifCodeGen(else1, primitiveListCondition, then2 -> {
        final JVar primitiveList = declareValueVar("primitiveList", arraySchema, then2, true, false, true);
        then2.assign(primitiveList, JExpr.cast(primitiveListInterface, arrayExpr));
        processArrayElementLoop(arraySchema, arrayClass, primitiveList, then2, "getPrimitive");
      }, else2 -> {
        processArrayElementLoop(arraySchema, arrayClass, arrayExpr, else2, "get");
      });
    } else {
      processArrayElementLoop(arraySchema, arrayClass, arrayExpr, else1, "get");
    }
  });
  body.invoke(JExpr.direct(ENCODER), "writeArrayEnd");
}
 
Example #27
Source File: HashCodeCodeGenerationImplementor.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void onDouble(HashCodeArguments arguments, JBlock block,
		boolean isAlwaysSet) {
	// long bits = doubleToLongBits(value);
	final JVar bits = block.decl(JMod.FINAL, getCodeModel().LONG, arguments
			.value().name() + "Bits", getCodeModel().ref(Double.class)
			.staticInvoke("doubleToLongBits").arg(arguments.value()));
	// return (int)(bits ^ (bits >>> 32));
	final JExpression valueHashCode = JExpr.cast(getCodeModel().INT,
			JOp.xor(bits, JOp.shrz(bits, JExpr.lit(32))));
	ifHasSetValueAssignPlusValueHashCode(arguments, block, valueHashCode,
			isAlwaysSet, true);
}
 
Example #28
Source File: SimpleToStringPlugin.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected JMethod generateToString$append(final ClassOutline classOutline,
		final JDefinedClass theClass) {
	final JCodeModel codeModel = theClass.owner();
	final JMethod toString$append = theClass.method(JMod.PUBLIC,
			codeModel.ref(StringBuilder.class), "append");
	toString$append.annotate(Override.class);
	{

		final JVar locator = toString$append.param(ObjectLocator.class,
				"locator");
		final JVar buffer = toString$append.param(StringBuilder.class,
				"buffer");
		final JVar toStringStrategy = toString$append.param(
				ToStringStrategy2.class, "strategy");

		final JBlock body = toString$append.body();

		body.invoke(toStringStrategy, "appendStart").arg(locator)
				.arg(JExpr._this()).arg(buffer);
		body.invoke("appendFields").arg(locator).arg(buffer)
				.arg(toStringStrategy);
		body.invoke(toStringStrategy, "appendEnd").arg(locator)
				.arg(JExpr._this()).arg(buffer);
		body._return(buffer);
	}
	return toString$append;
}
 
Example #29
Source File: FastDeserializerGeneratorBase.java    From avro-fastserde with Apache License 2.0 5 votes vote down vote up
protected static void assignBlockToBody(Object codeContainer, JBlock body) {
    try {
        Field field = codeContainer.getClass().getDeclaredField("body");

        field.setAccessible(true);
        field.set(codeContainer, body);
        field.setAccessible(false);

    } catch (ReflectiveOperationException e) {
        throw new FastDeserializerGeneratorException(e);
    }
}
 
Example #30
Source File: ReadReferenceVisitor.java    From parceler with Apache License 2.0 5 votes vote down vote up
@Override
public Void visit(MethodReference methodReference, ReadContext input) {
    JBlock body = input.getBody();

    body.add(invocationBuilder.buildMethodCall(
            input.getContainer(),
            methodReference.getRoot(),
            methodReference.getMethod(),
            Collections.singletonList(input.getGetExpression().getExpression()),
            input.getWrapped()));
    return null;
}