Example #1
0
  private void genConstructor(
      Refs r,
      JDefinedClass clazz,
      Collection<Ref> refs,
      Map<Ref, JFieldVar> fieldVarMap,
      JFieldVar holderListener,
      Map<Listener.Type, ListenerType> listenerTypeMap) {
    // private MyLayoutViewModel(View view) {
    JMethod constructor = clazz.constructor(PUBLIC);
    JVar viewVar = constructor.param(r.viewClass, "view");
    JBlock body = constructor.body();

    // super(view);
    body.invoke("super").arg(viewVar);

    // myLinearLayout = (LinearLayout) view.findViewById(R.id.my_linear_layout);
    // myTextView = (TextView) myLinearLayout.findViewById(R.id.my_text_view);
    genInitFields(r, fieldVarMap, viewVar, refs, body);

    // myButton.setOnClickListener((view) -> { if (_holderListener != null)
    // _holderListener.onMyButtonClick(myButton); });
    genListeners(r, fieldVarMap, holderListener, refs, body, listenerTypeMap);

    JDocComment doc = constructor.javadoc();
    doc.append(
        "Constructs a new {@link me.tatarka.holdr.Holdr} for {@link "
            + r.packageName
            + ".R.layout#"
            + r.layoutName
            + "}.");
    doc.addParam(viewVar).append("The root view to search for the holdr's views.");
  }
 private JDocComment addBaseJavaDoc(final Action action, final JMethod method) {
   final JDocComment javadoc = method.javadoc();
   if (isNotBlank(action.getDescription())) {
     javadoc.add(action.getDescription());
   }
   return javadoc;
 }
 private static void addSetterDeclaration(
     Names names, JDefinedClass paramType, JDefinedClass setterReturnType) {
   JMethod method = setterReturnType.method(JMod.NONE, setterReturnType, names.getSetterName());
   method.param(paramType, names.getParamName());
   JDocComment javadoc = method.javadoc();
   javadoc.append(names.getJavadoc());
 }
  public static void addGetterSetterDeclaration(
      Names names, JClass type, JDefinedClass jDefinedClass) {
    addGetterDeclaration(names, type, jDefinedClass);

    JMethod method = jDefinedClass.method(JMod.NONE, jDefinedClass, names.getSetterName());
    method.param(type, names.getParamName());

    JDocComment javadoc = method.javadoc();
    javadoc.append(names.getJavadoc());
  }
Example #5
0
  /**
   * メソッドレベルのJavaDoc追加
   *
   * @param method メソッド
   * @param doc コメント
   * @param params パラメータ
   */
  private JDocComment addMethodDoc(JMethod method, String doc, JVar... params) {
    /* Addign java doc for method */
    JDocComment jDoc = method.javadoc();
    jDoc.add(doc);

    for (JVar param : params) {
      JCommentPart paramDoc = jDoc.addParam(param);
    }

    return jDoc;
  }
Example #6
0
  private void getter(JDefinedClass clazz, JFieldVar field, String fieldName, String remarks) {
    // getter
    JMethod getter = clazz.method(JMod.PUBLIC, field.type(), "get" + fieldName);

    /* Addign java doc for method */
    JDocComment jDoc = addMethodDoc(getter, remarks + "取得");
    JCommentPart rtn = jDoc.addReturn();
    rtn.add(remarks);

    JBlock block = getter.body();
    block._return(field);
  }
  private static void processPacket(
      PacketType packet, JPackage dirPackage, JCodeModel codeModel, boolean fromClient)
      throws JClassAlreadyExistsException {
    // get the packet info
    String packetName =
        (packet.getInfo() == null || packet.getInfo().getName() == null)
            ? "Unknown"
            : packet.getInfo().getName();
    String packetNamePrefixed = "P" + String.format("%03d", packet.getHeader()) + "_" + packetName;
    String packetDescription =
        (packet.getInfo() == null
                || packet.getInfo().getDescription() == null
                || packet.getInfo().getDescription().isEmpty())
            ? ""
            : "\n" + WordUtils.wrap(packet.getInfo().getDescription(), /* maximumLength */ 50);

    JDefinedClass packetClass =
        dirPackage._class(JMod.FINAL | JMod.PUBLIC, packetNamePrefixed)._extends(GWMessage.class);

    LOGGER.info("+-Processing packet: {}", packetNamePrefixed);
    LOGGER.debug("|+-Packet description: {}", packetDescription);

    StringBuilder packetJavadoc =
        new StringBuilder("Auto-generated by PacketCodeGen.").append(packetDescription);

    JDocComment jDocComment = packetClass.javadoc();
    jDocComment.add(packetJavadoc.toString());

    AtomicInteger numberOfUnknowns = new AtomicInteger(); // unknown field number

    // get all fields in this packet
    for (FieldType field : packet.getField()) {
      processField(field, packetClass, codeModel, numberOfUnknowns, fromClient);
    }

    // generate the header method
    JMethod headerMeth = packetClass.method(JMod.PUBLIC, short.class, "getHeader");
    headerMeth.annotate(Override.class);
    headerMeth.body()._return(JExpr.lit(packet.getHeader().intValue()));

    // generate getters, setters
    for (JFieldVar fieldVar : packetClass.fields().values()) {
      processAccessors(fieldVar, packetClass, fromClient);
    }

    // generate the toString method
    processToString(packetClass, codeModel);
  }
Example #8
0
 protected void addJavadoc(JDocComment jdoc) {
   jdoc.add(
       " Operations for service \""
           + this.serviceDefinition.getServiceId()
           + "\"\n"
           + StringUtils.getFormattedDate());
 }
 private void addParameterJavaDoc(
     final AbstractParam parameter, final String parameterName, final JDocComment javadoc) {
   javadoc
       .addParam(parameterName)
       .add(
           defaultString(parameter.getDescription())
               + getPrefixedExampleOrBlank(parameter.getExample()));
 }
  private void addPlainBodyArgument(
      final MimeType bodyMimeType, final JMethod method, final JDocComment javadoc)
      throws IOException {

    method.param(types.getRequestEntityClass(bodyMimeType), GENERIC_PAYLOAD_ARGUMENT_NAME);

    javadoc
        .addParam(GENERIC_PAYLOAD_ARGUMENT_NAME)
        .add(getPrefixedExampleOrBlank(bodyMimeType.getExample()));
  }
  private void addCatchAllFormParametersArgument(
      final MimeType bodyMimeType,
      final JMethod method,
      final JDocComment javadoc,
      final JType argumentType) {
    method.param(argumentType, GENERIC_PAYLOAD_ARGUMENT_NAME);

    // build a javadoc text out of all the params
    for (final Entry<String, List<FormParameter>> namedFormParameters :
        bodyMimeType.getFormParameters().entrySet()) {
      final StringBuilder sb = new StringBuilder();
      sb.append(namedFormParameters.getKey()).append(": ");

      for (final FormParameter formParameter : namedFormParameters.getValue()) {
        appendParameterJavadocDescription(formParameter, sb);
      }

      javadoc.addParam(GENERIC_PAYLOAD_ARGUMENT_NAME).add(sb.toString());
    }
  }
Example #12
0
  public GeneratedClass createElement(String namespace, String name)
      throws JClassAlreadyExistsException {
    String className = NameConverter.smart.toClassName(name);
    String qualifiedClassName = targetPackage + "." + NameConverter.smart.toClassName(className);
    GeneratedClass generatedClass = generatedClasses.get(qualifiedClassName);
    if (generatedClass != null) {
      return generatedClass;
    }
    JDefinedClass jDefinedClass = codeModel._class(qualifiedClassName);
    generatedClass = new GeneratedClass(codeModel, jDefinedClass);
    jDefinedClass.annotate(Root.class).param("name", name);
    jDefinedClass.annotate(Namespace.class).param("reference", namespace);
    jDefinedClass.constructor(JMod.PUBLIC);

    JDocComment jDocComment = jDefinedClass.javadoc();
    jDocComment.add(className);
    jDocComment.add("<br>\n");
    jDocComment.add("Generated using Android JAXB");
    jDocComment.add("<br>\n");
    jDocComment.add("@link https://github.com/yeshodhan/android-jaxb");

    generatedClasses.put(qualifiedClassName, generatedClass);
    return generatedClass;
  }
  private static void processField(
      FieldType field,
      JDefinedClass packetClass,
      JCodeModel codeModel,
      AtomicInteger numberOfUnknowns,
      boolean fromClient)
      throws JClassAlreadyExistsException {
    boolean isNested =
        (field.getType() == PacketSimpleTypes.OPTIONAL)
            || (field.getType() == PacketSimpleTypes.ARRAY_STATIC)
            || (field.getType() == PacketSimpleTypes.ARRAY_VAR_SMALL)
            || (field.getType() == PacketSimpleTypes.ARRAY_VAR_BIG);

    boolean isArray =
        (field.getType() == PacketSimpleTypes.BUFFER_STATIC)
            || (field.getType() == PacketSimpleTypes.BUFFER_VAR_SMALL)
            || (field.getType() == PacketSimpleTypes.BUFFER_VAR_BIG)
            || (isNested && (field.getType() != PacketSimpleTypes.OPTIONAL));

    boolean isStaticLength =
        (isArray)
            && ((field.getType() == PacketSimpleTypes.ARRAY_STATIC)
                || (field.getType() == PacketSimpleTypes.BUFFER_STATIC));

    // length is either not set for non arrays and static arrays,
    // its 1byte for small stuff and 2bytes for big stuff.
    int prefixLength =
        (!isArray || isStaticLength)
            ? -1
            : (field.getType() == PacketSimpleTypes.ARRAY_VAR_SMALL)
                    || (field.getType() == PacketSimpleTypes.BUFFER_VAR_SMALL)
                ? 1
                : 2;

    String name = "";

    if (field.getInfo() == null || field.getInfo().getName() == null) {
      // check if we got special fields...
      if (field.getType() == PacketSimpleTypes.AGENTID) {
        name = "AgentID";
      } else if (field.getType() == PacketSimpleTypes.OPTIONAL) {
        name = "Optional";
      } else {
        name = "Unknown";
      }

      name += numberOfUnknowns.incrementAndGet();
    } else {
      name = field.getInfo().getName();
    }

    String fieldName = WordUtils.uncapitalize(name);
    String fieldDescription =
        (field.getInfo() == null
                || field.getInfo().getDescription() == null
                || field.getInfo().getDescription().isEmpty())
            ? ""
            : "\n" + WordUtils.wrap(field.getInfo().getDescription(), /* maximumLength */ 50);

    JType fieldType;

    if (isNested) {
      JDefinedClass nestedClass =
          packetClass
              ._class(JMod.FINAL | JMod.STATIC | JMod.PUBLIC, "Nested" + name)
              ._implements(NestedMarker.class);

      AtomicInteger numberOfUnknownsNested = new AtomicInteger();

      for (FieldType nested : field.getField()) {
        processField(nested, nestedClass, codeModel, numberOfUnknownsNested, fromClient);
      }

      // generate getters, setters
      for (JFieldVar fieldVar : nestedClass.fields().values()) {
        processAccessors(fieldVar, nestedClass, fromClient);
      }

      processToString(nestedClass, codeModel);

      // nested classes are either arrays or optional...
      // meaning we will later have to test if they are null before reading/writing
      fieldType = isArray ? nestedClass.array() : nestedClass;
    } else {
      Class<?> fieldClass = convertFieldTypeToClass(field);
      fieldType = codeModel._ref(fieldClass);
    }

    LOGGER.debug("|+-Processing field: {}, of type: {}", fieldName, fieldType);

    // add the field
    JFieldVar packetField = packetClass.field(JMod.PRIVATE, fieldType, fieldName);

    if (fieldDescription != null && !fieldDescription.trim().equals("")) {
      JDocComment jDocComment = packetField.javadoc();
      jDocComment.add(fieldDescription);
    }

    // and dont forget array annotations if necessary
    if (isArray) {
      int size = (int) (field.getElements() == null ? -1 : field.getElements());

      packetField
          .annotate(IsArray.class)
          .param("constant", isStaticLength)
          .param("size", size)
          .param("prefixLength", prefixLength);
    }

    // or any special annotations
    if (field.getType() == PacketSimpleTypes.LONG) {
      packetField.annotate(IsInt64.class);
    }
    if (field.getType() == PacketSimpleTypes.VARINT) {
      packetField.annotate(IsVarInt.class);
    }
    if (field.getType() == PacketSimpleTypes.ASCII) {
      packetField.annotate(IsASCII.class);
    }
  }
Example #14
0
  /**
   * Generates a class for each configured object class. See {@link #objectClasses}. {@link
   * #write(String)} must be invoked to write the classes to disk.
   */
  public void generate() {
    for (String objectClass : objectClasses) {
      final JDefinedClass definedClass = createClass(packageName, objectClass);
      final JDocComment jDocComment = definedClass.javadoc();
      jDocComment.add(String.format("Ldaptive generated bean for objectClass '%s'", objectClass));

      final ObjectClass oc = schema.getObjectClass(objectClass);
      final Set<String> attributeNames = getAttributeNames(oc);
      if (useOperationalAttributes) {
        for (AttributeType type : schema.getAttributeTypes()) {
          if (AttributeUsage.DIRECTORY_OPERATION.equals(type.getUsage())) {
            attributeNames.add(type.getName());
          }
        }
      }

      final Map<String, AttributeType> mutators = new TreeMap<>();
      for (String name : attributeNames) {
        final AttributeType type = schema.getAttributeType(name);
        if (!isNameExcluded(type)) {
          if (nameMappings.containsKey(type.getName())) {
            mutators.put(nameMappings.get(type.getName()), type);
          } else {
            mutators.put(formatAttributeName(type.getName()), type);
          }
        }
      }

      // add entry annotation
      final JAnnotationUse entryAnnotation =
          definedClass.annotate(codeModel.ref(org.ldaptive.beans.Entry.class));
      entryAnnotation.param("dn", "dn");

      final JAnnotationArrayMember attrArray = entryAnnotation.paramArray("attributes");

      // add mutator for the DN
      createMutators(definedClass, "dn", String.class, false);

      // add mutators for each attribute
      for (Map.Entry<String, AttributeType> mutator : mutators.entrySet()) {
        final Class<?> syntaxType =
            getSyntaxType(
                mutator.getValue(), schema.getSyntax(mutator.getValue().getSyntaxOID(false)));
        if (mutator.getValue().isSingleValued()) {
          createMutators(definedClass, mutator.getKey(), syntaxType, false);
        } else {
          createMutators(definedClass, mutator.getKey(), syntaxType, true);
        }

        // add attribute annotation
        final JAnnotationUse attrAnnotation =
            attrArray.annotate(org.ldaptive.beans.Attribute.class);
        attrAnnotation.param("name", mutator.getValue().getName());
        if (!mutator.getKey().equals(mutator.getValue().getName())) {
          attrAnnotation.param("property", mutator.getKey());
        }
        if (byte[].class.equals(syntaxType)) {
          attrAnnotation.param("binary", true);
        }
      }

      // create additional methods
      createHashCode(definedClass);
      createEquals(definedClass);
      createToString(definedClass);
    }
  }
  private void createResponseBuilderInResourceMethodReturnType(
      final JDefinedClass responseClass,
      final int statusCode,
      final Response response,
      final MimeType responseMimeType)
      throws Exception {
    final String responseBuilderMethodName =
        Names.buildResponseMethodName(statusCode, responseMimeType);

    final JMethod responseBuilderMethod =
        responseClass.method(PUBLIC + STATIC, responseClass, responseBuilderMethodName);

    final JDocComment javadoc = responseBuilderMethod.javadoc();

    if (isNotBlank(response.getDescription())) {
      javadoc.add(response.getDescription());
    }

    if ((responseMimeType != null) && (isNotBlank(responseMimeType.getExample()))) {
      javadoc.add(EXAMPLE_PREFIX + responseMimeType.getExample());
    }

    JInvocation builderArgument =
        types
            .getGeneratorClass(javax.ws.rs.core.Response.class)
            .staticInvoke("status")
            .arg(JExpr.lit(statusCode));

    if (responseMimeType != null) {
      builderArgument =
          builderArgument
              .invoke("header")
              .arg(HttpHeaders.CONTENT_TYPE)
              .arg(responseMimeType.getType());
    }

    final StringBuilder freeFormHeadersDescription = new StringBuilder();

    for (final Entry<String, Header> namedHeaderParameter : response.getHeaders().entrySet()) {
      final String headerName = namedHeaderParameter.getKey();
      final Header header = namedHeaderParameter.getValue();

      if (headerName.contains(RESPONSE_HEADER_WILDCARD_SYMBOL)) {
        appendParameterJavadocDescription(header, freeFormHeadersDescription);
        continue;
      }

      final String argumentName = Names.buildVariableName(headerName);

      builderArgument =
          builderArgument.invoke("header").arg(headerName).arg(JExpr.ref(argumentName));

      addParameterJavaDoc(header, argumentName, javadoc);

      responseBuilderMethod.param(types.buildParameterType(header, argumentName), argumentName);
    }

    final JBlock responseBuilderMethodBody = responseBuilderMethod.body();

    final JVar builderVariable =
        responseBuilderMethodBody.decl(
            types.getGeneratorType(ResponseBuilder.class), "responseBuilder", builderArgument);

    if (freeFormHeadersDescription.length() > 0) {
      // generate a Map<String, List<Object>> argument for {?} headers
      final JClass listOfObjectsClass = types.getGeneratorClass(List.class).narrow(Object.class);
      final JClass headersArgument =
          types
              .getGeneratorClass(Map.class)
              .narrow(types.getGeneratorClass(String.class), listOfObjectsClass);

      builderArgument =
          responseBuilderMethodBody
              .invoke("headers")
              .arg(JExpr.ref(MULTIPLE_RESPONSE_HEADERS_ARGUMENT_NAME))
              .arg(builderVariable);

      final JVar param =
          responseBuilderMethod.param(headersArgument, MULTIPLE_RESPONSE_HEADERS_ARGUMENT_NAME);

      javadoc.addParam(param).add(freeFormHeadersDescription.toString());
    }

    if (responseMimeType != null) {
      responseBuilderMethodBody
          .invoke(builderVariable, "entity")
          .arg(JExpr.ref(GENERIC_PAYLOAD_ARGUMENT_NAME));
      responseBuilderMethod.param(
          types.getResponseEntityClass(responseMimeType), GENERIC_PAYLOAD_ARGUMENT_NAME);
      javadoc
          .addParam(GENERIC_PAYLOAD_ARGUMENT_NAME)
          .add(defaultString(responseMimeType.getExample()));
    }

    responseBuilderMethodBody._return(
        JExpr._new(responseClass).arg(builderVariable.invoke("build")));
  }
Example #16
0
 private void addClassComment(JDefinedClass clazz, String javaDoc) {
   /* Adding class level coment */
   JDocComment jDocComment = clazz.javadoc();
   jDocComment.add(javaDoc);
 }
 public static void addGetterDeclaration(Names names, Class<?> type, JDefinedClass jDefinedClass) {
   JMethod method = jDefinedClass.method(JMod.NONE, type, names.getGetterName());
   JDocComment javadoc = method.javadoc();
   javadoc.append(names.getJavadoc());
 }