Java Code Examples for com.sun.codemodel.JMethod#_throws

The following examples show how to use com.sun.codemodel.JMethod#_throws . 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: FastDeserializerGenerator.java    From avro-util with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private JMethod createMethod(final Schema schema, boolean read) {
  if (!Schema.Type.RECORD.equals(schema.getType())) {
    throw new FastDeserializerGeneratorException("Methods are defined only for records, not for " + schema.getType());
  }
  if (methodAlreadyDefined(schema, read)) {
    throw new FastDeserializerGeneratorException("Method already exists for: " + schema.getFullName());
  }

  JClass schemaClass = schemaAssistant.classFromSchema(schema);
  JMethod method = generatedClass.method(JMod.PUBLIC, read ? schemaClass : codeModel.VOID,
      getUniqueName("deserialize" + schema.getName()));

  method._throws(IOException.class);
  method.param(Object.class, VAR_NAME_FOR_REUSE);
  method.param(Decoder.class, DECODER);

  (read ? deserializeMethodMap : skipMethodMap).put(schema.getFullName(), method);

  return method;
}
 
Example 2
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 3
Source File: CreateVisitableInterface.java    From jaxb-visitor with Apache License 2.0 6 votes vote down vote up
@Override
  protected void run(Set<ClassOutline> classes, Set<JClass> directClasses) {
      final JDefinedClass _interface = outline.getClassFactory().createInterface(jpackage, "Visitable", null);
setOutput( _interface );
final JMethod _method = getOutput().method(JMod.NONE, void.class, "accept");
final JTypeVar returnType = _method.generify("R");
final JTypeVar exceptionType = _method.generify("E", Throwable.class);
_method.type(returnType);
_method._throws(exceptionType);
final JClass narrowedVisitor = visitor.narrow(returnType, exceptionType);
_method.param(narrowedVisitor, "aVisitor");
      
      for(ClassOutline classOutline : classes) {
          classOutline.implClass._implements(getOutput());
      }
  }
 
Example 4
Source File: GroupInterfaceGenerator.java    From jaxb2-rich-contract-plugin with MIT License 6 votes vote down vote up
private FieldOutline generateProperty(final DefinedInterfaceOutline groupInterface, final FieldOutline implementedField) {
	if (implementedField != null) {
		final JMethod implementedGetter = PluginContext.findGetter(implementedField);
		if (implementedGetter != null) {
			if(this.overrideCollectionClass != null && implementedField.getPropertyInfo().isCollection()) {
				groupInterface.getImplClass().method(JMod.NONE, this.overrideCollectionClass.narrow(((JClass)implementedGetter.type()).getTypeParameters().get(0)), implementedGetter.name());
			} else {
				groupInterface.getImplClass().method(JMod.NONE, implementedGetter.type(), implementedGetter.name());
			}
			if (!this.immutable) {
				final JMethod implementedSetter = PluginContext.findSetter(implementedField);
				if (implementedSetter != null) {
					final JMethod newSetter = groupInterface.getImplClass().method(JMod.NONE, implementedSetter.type(),
							implementedSetter.name());
					newSetter.param(implementedSetter.listParamTypes()[0], implementedSetter.listParams()[0].name());
					if (this.throwsPropertyVetoException) {
						newSetter._throws(PropertyVetoException.class);
					}
				}
			}
			groupInterface.addField(implementedField);
		}
	}
	return implementedField;
}
 
Example 5
Source File: FastSerializerGenerator.java    From avro-fastserde with Apache License 2.0 6 votes vote down vote up
private JMethod createMethod(final Schema schema) {
    if (Schema.Type.RECORD.equals(schema.getType())) {
        if (!methodAlreadyDefined(schema)) {
            JMethod method = serializerClass.method(JMod.PUBLIC, codeModel.VOID,
                    "serialize" + schema.getName() + nextRandomInt());
            method._throws(IOException.class);
            method.param(schemaAssistant.classFromSchema(schema), "data");
            method.param(Encoder.class, ENCODER);

            method.annotate(SuppressWarnings.class).param("value", "unchecked");
            serializeMethodMap.put(schema.getFullName(), method);

            return method;
        } else {
            throw new FastSerializerGeneratorException("Method already exists for: " + schema.getFullName());
        }
    }
    throw new FastSerializerGeneratorException("No method for schema type: " + schema.getType());
}
 
Example 6
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 7
Source File: FastSerializerGenerator.java    From avro-util with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private JMethod createMethod(final Schema schema) {
  if (Schema.Type.RECORD.equals(schema.getType())) {
    if (!methodAlreadyDefined(schema)) {
      JMethod method = generatedClass.method(
          JMod.PUBLIC,
          codeModel.VOID,
          getUniqueName("serialize" + StringUtils.capitalize(schema.getName())));
      method._throws(IOException.class);
      method.param(schemaAssistant.classFromSchema(schema), "data");
      method.param(Encoder.class, ENCODER);

      method.annotate(SuppressWarnings.class).param("value", "unchecked");
      serializeMethodMap.put(schema.getFullName(), method);

      return method;
    } else {
      throw new FastSerdeGeneratorException("Method already exists for: " + schema.getFullName());
    }
  }
  throw new FastSerdeGeneratorException("No method for schema type: " + schema.getType());
}
 
Example 8
Source File: SourceGenerator.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
private void generateFieldAdderRemoverForImpl(final JDefinedClass impl, final JMethod interfaceMethod,
                                              final JDefinedClass interfaceClass, final boolean add) {
    if (impl.getMethod(interfaceMethod.name(), interfaceMethod.listParamTypes()) == null) {
        final JMethod method = impl.method(JMod.PUBLIC, interfaceMethod.type(), interfaceMethod.name());
        method.param(interfaceMethod.params().get(0).type(), "arg");
        method._throws(OrmException.class);
        method.annotate(Override.class);
        method.body()._return(JExpr.ref("this").invoke(add ? "addProperty" : "removeProperty").arg(JExpr.ref("valueConverterRegistry").invoke("convertType")
                .arg(interfaceMethod.params().get(0)).arg(JExpr._this()))
                .arg(JExpr.ref("valueFactory").invoke("createIRI")
                        .arg(interfaceClass.staticRef(classMethodIriMap.get(interfaceClass).get(interfaceMethod)))));
    } else {
        LOG.warn("Avoided duplicate adder method: " + interfaceMethod.name() + " on class: " + impl.name());
    }
}
 
Example 9
Source File: SourceGenerator.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
private void generateFieldSetterForImpl(final JDefinedClass impl, final JMethod interfaceMethod,
                                        final JDefinedClass interfaceClass) {
    if (impl.getMethod(interfaceMethod.name(), interfaceMethod.listParamTypes()) == null) {
        final JMethod method = impl.method(JMod.PUBLIC, interfaceMethod.type(), interfaceMethod.name());
        method.param(interfaceMethod.params().get(0).type(), "arg");
        method._throws(OrmException.class);
        method.annotate(Override.class);
        if (interfaceMethod.params().get(0).type().fullName().startsWith("java.util.Set")) {
            method.body().invoke("setProperties")
                    .arg(JExpr.ref("valueConverterRegistry").invoke("convertTypes")
                            .arg(interfaceMethod.params().get(0)).arg(JExpr._this()))
                    .arg(JExpr.ref("valueFactory").invoke("createIRI")
                            .arg(interfaceClass.staticRef(classMethodIriMap.get(interfaceClass).get(interfaceMethod))));
        } else {
            method.body().invoke("setProperty")
                    .arg(JExpr.ref("valueConverterRegistry").invoke("convertType")
                            .arg(interfaceMethod.params().get(0)).arg(JExpr._this()))
                    .arg(JExpr.ref("valueFactory").invoke("createIRI")
                            .arg(interfaceClass.staticRef(classMethodIriMap.get(interfaceClass).get(interfaceMethod))));
        }
        // TODO - add javadoc.
        // JDocComment jdoc = method.javadoc();
        // jdoc.add("");
    } else {
        LOG.warn("Avoided duplicate setter method: " + interfaceMethod.name() + " on class: " + impl.name());
    }
}
 
Example 10
Source File: SourceGenerator.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
private void generateFieldGetterForImpl(final JDefinedClass impl, final JMethod interfaceMethod,
                                        final JDefinedClass interfaceClass) {
    if (impl.getMethod(interfaceMethod.name(), interfaceMethod.listParamTypes()) == null) {
        final JMethod method = impl.method(JMod.PUBLIC, interfaceMethod.type(), interfaceMethod.name());
        method._throws(OrmException.class);
        method.annotate(Override.class);
        // TODO - add javadoc.
        // JDocComment jdoc = method.javadoc();
        // jdoc.add("");
        convertValueBody(interfaceClass, interfaceMethod, impl, method);
    } else {
        LOG.warn("Avoided duplicate getter method: " + interfaceMethod.name() + " on class: " + impl.name());
    }
}
 
Example 11
Source File: SourceGenerator.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
private JMethod generateGetterMethodForInterface(final JDefinedClass clazz, final IRI interfaceIri,
                                                 final String name, final String fieldName, final IRI propertyIri, final JClass type, final boolean thingResource) {
    final JMethod method = clazz.method(JMod.PUBLIC, type,
            generateMethodName(type.equals(boolean.class) ? "is" : "get", name) + (thingResource ? "_resource" : ""));
    method._throws(OrmException.class);
    final JDocComment comment = method.javadoc();
    comment.add("Get the " + fieldName + " property from this instance of a " + (interfaceIri != null ? interfaceIri.stringValue() : getOntologyName(this.packageName, this.ontologyName))
            + "' type.<br><br>" + getFieldComment(propertyIri));
    comment.addReturn().add("The " + fieldName + " {@link " + type.binaryName() + "} value for this instance");
    return method;
}
 
Example 12
Source File: SourceGenerator.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
private JMethod generateSetterMethodForInterface(final JDefinedClass clazz, final IRI interfaceIri,
                                                 final String name, final String fieldName, final IRI propertyIri, final JClass type) {
    final JMethod method = clazz.method(JMod.PUBLIC, codeModel.VOID, generateMethodName("set", name));
    method._throws(OrmException.class);
    method.param(type, "arg");
    // TODO - comments
    // final JDocComment comment = method.javadoc();
    // comment.add("Get the " + fieldName + " property from this instance of
    // a " + interfaceIri.stringValue()
    // + "' type.<br><br>" + getFieldComment(propertyIri));
    // comment.addReturn().add("The " + fieldName + " {@link " +
    // type.binaryName() + "} value for this instance");
    return method;
}
 
Example 13
Source File: SourceGenerator.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
private JMethod generateAddMethodForInterface(final JDefinedClass clazz, final IRI interfaceIri,
                                              final String name, final String fieldName, final IRI propertyIri, final JClass type) {
    final JMethod method = clazz.method(JMod.PUBLIC, boolean.class, generateMethodName("add", name));
    method._throws(OrmException.class);
    method.param(type, "arg");
    return method;
}
 
Example 14
Source File: SourceGenerator.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
private JMethod generateRemoveMethodForInterface(final JDefinedClass clazz, final IRI interfaceIri,
                                                 final String name, final String fieldName, final IRI propertyIri, final JClass type) {
    final JMethod method = clazz.method(JMod.PUBLIC, boolean.class, generateMethodName("remove", name));
    method._throws(OrmException.class);
    method.param(type, "arg");
    return method;
}
 
Example 15
Source File: FastDeserializerGenerator.java    From avro-fastserde with Apache License 2.0 5 votes vote down vote up
private void updateActualExceptions(JMethod method) {
    Set<Class<? extends Exception>> exceptionFromMethod = exceptionFromMethodMap.get(method);
    for (Class<? extends Exception> exceptionClass : exceptionFromMethod) {
        method._throws(exceptionClass);
        schemaAssistant.getExceptionsFromStringable().add(exceptionClass);
    }
}
 
Example 16
Source File: CreateTraverserInterface.java    From jaxb-visitor with Apache License 2.0 5 votes vote down vote up
private void implTraverse(JTypeVar exceptionType, JClass narrowedVisitor, JClass implClass) {
    JMethod traverseMethod;
    String methodName = traverseMethodNamer.apply(implClass.name());
    traverseMethod = getOutput().method(JMod.NONE, void.class, methodName);
    traverseMethod._throws(exceptionType);
    traverseMethod.param(implClass, "aBean");
    traverseMethod.param(narrowedVisitor, "aVisitor");
}
 
Example 17
Source File: CreateVisitorInterface.java    From jaxb-visitor with Apache License 2.0 5 votes vote down vote up
private void declareVisitMethod(JTypeVar returnType, JTypeVar exceptionType, JClass implClass) {
    JMethod vizMethod;
    String visitMethod = visitMethodNamer.apply(implClass.name());
    vizMethod = getOutput().method(JMod.NONE, returnType, visitMethod);
    vizMethod._throws(exceptionType);
    vizMethod.param(implClass, "aBean");
}
 
Example 18
Source File: CreateBaseVisitorClass.java    From jaxb-visitor with Apache License 2.0 5 votes vote down vote up
private void implementVisitMethod(JTypeVar returnType, JTypeVar exceptionType, JClass implClass) {
    JMethod _method;
    String methodName = visitMethodNamer.apply(implClass.name());
    _method = getOutput().method(JMod.PUBLIC, returnType, methodName);
    _method._throws(exceptionType);
    _method.param(implClass, "aBean");
    _method.body()._return(JExpr._null());
    _method.annotate(Override.class);
}
 
Example 19
Source File: FastDeserializerGenerator.java    From avro-util with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void updateActualExceptions(JMethod method) {
  Set<Class<? extends Exception>> exceptionFromMethod = exceptionFromMethodMap.get(method);
  if (exceptionFromMethod != null) {
    for (Class<? extends Exception> exceptionClass : exceptionFromMethod) {
      method._throws(exceptionClass);
      schemaAssistant.getExceptionsFromStringable().add(exceptionClass);
    }
  }
}
 
Example 20
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;
}