protected String toStringExpression(JParameter arg) {
   Attribute attribute = arg.getAnnotation(Attribute.class);
   if (attribute != null) {
     return arg.getName() + "." + attribute.value();
   }
   return toStringExpression(arg.getType(), arg.getName());
 }
  protected String toFormStringExpression(JParameter argument, Style classStyle)
      throws UnableToCompleteException {
    JType type = argument.getType();
    String expr = argument.getName();

    if (type.isPrimitive() != null) {
      return "\"\"+" + expr;
    }
    if (STRING_TYPE == type) {
      return expr;
    }
    if (type.isClass() != null && isOverlayArrayType(type.isClass())) {
      return "(new " + JSON_ARRAY_CLASS + "(" + expr + ")).toString()";
    }
    if (type.isClass() != null && OVERLAY_VALUE_TYPE.isAssignableFrom(type.isClass())) {
      return "(new " + JSON_OBJECT_CLASS + "(" + expr + ")).toString()";
    }
    if (type.getQualifiedBinaryName().startsWith("java.lang.")) {
      return String.format("(%s != null ? %s.toString() : null)", expr, expr);
    }

    Json jsonAnnotation = argument.getAnnotation(Json.class);
    final Style style = jsonAnnotation != null ? jsonAnnotation.style() : classStyle;

    return locator.encodeExpression(type, expr, style) + ".toString()";
  }
Example #3
0
  /**
   * Adds the given parameter to this JConstructor's list of parameters.
   *
   * @param parameter The parameter to add to the this JConstructor's list of parameters.
   */
  public void addParameter(final JParameter parameter) {
    if (parameter == null) {
      return;
    }

    // -- check current params
    if (_params.get(parameter.getName()) != null) {
      StringBuilder err = new StringBuilder(64);
      err.append("A parameter already exists for the constructor, ");
      err.append(this._declaringClass.getName());
      err.append(", with the name: ");
      err.append(parameter.getName());
      throw new IllegalArgumentException(err.toString());
    }

    _params.put(parameter.getName(), parameter);

    // -- be considerate and add the class name to the
    // -- declaring class's list of imports
    if (_declaringClass != null) {
      JType jType = parameter.getType();
      if (!jType.isPrimitive()) {
        _declaringClass.addImport(jType.getName());
      }
    }
  }
  private void writeSubresourceLocatorImpl(JMethod method) throws UnableToCompleteException {
    JClassType iface = method.getReturnType().isInterface();
    if (iface == null || !REST_SERVICE_TYPE.isAssignableFrom(iface)) {
      getLogger()
          .log(
              ERROR,
              "Invalid subresource locator method. Method must have return type of an interface that extends RestService: "
                  + method.getReadableDeclaration());
      throw new UnableToCompleteException();
    }

    Path pathAnnotation = method.getAnnotation(Path.class);
    if (pathAnnotation == null) {
      getLogger()
          .log(
              ERROR,
              "Invalid subresource locator method. Method must have @Path annotation: "
                  + method.getReadableDeclaration());
      throw new UnableToCompleteException();
    }
    String pathExpression = wrap(pathAnnotation.value());

    for (JParameter arg : method.getParameters()) {
      PathParam paramPath = arg.getAnnotation(PathParam.class);
      if (paramPath != null) {
        pathExpression = pathExpression(pathExpression, arg, paramPath);
      }
    }

    p(method.getReadableDeclaration(false, false, false, false, true) + " {").i(1);
    {
      JType type = method.getReturnType();
      String name;
      if (type instanceof JClassType) {
        JClassType restService = (JClassType) type;
        RestServiceClassCreator generator =
            new RestServiceClassCreator(getLogger(), context, restService);
        name = generator.create();
      } else {
        throw new UnsupportedOperationException("Subresource method may not return: " + type);
      }
      p(method.getReturnType().getQualifiedSourceName() + " __subresource = new " + name + "();");
      p(
          "(("
              + RestServiceProxy.class.getName()
              + ")__subresource).setResource(getResource().resolve("
              + pathExpression
              + "));");
      p("return __subresource;");
    }
    i(-1).p("}");
  }
    private void emitBody(SourceWriter w) throws NotFoundException {
      JClassType baseClass =
          context_.getTypeOracle().getType("org.rstudio.core.client.js.JsObjectInjector");
      JClassType c = baseType_.asParameterizationOf(baseClass.isGenericType());
      JType typeToInject = c.isParameterized().getTypeArgs()[0];

      w.print("public native final void injectObject(");
      w.print(typeToInject.getQualifiedSourceName());
      w.println(" value) /*-{");
      w.indent();

      w.println(baseExpression_ + " = {");
      w.indent();

      JMethod[] methods = typeToInject.isClassOrInterface().getMethods();
      for (int i = 0; i < methods.length; i++) {
        JMethod method = methods[i];
        final JParameter[] jParameters = method.getParameters();

        StringBuilder argString = new StringBuilder();
        for (int j = 0; j < jParameters.length; j++) {
          argString.append("_").append(j);
          if (j < jParameters.length - 1) argString.append(", ");
        }

        w.println(method.getName() + ": function(" + argString + ") {");
        w.indent();

        if (!method.getReturnType().getQualifiedSourceName().equals("void")) w.print("return ");
        w.print("value.@");
        w.print(typeToInject.getQualifiedSourceName());
        w.print("::");
        w.print(method.getName());
        w.print("(");
        for (JParameter param : jParameters) w.print(param.getType().getJNISignature());
        w.print(")(");
        w.print(argString.toString());
        w.println(");");

        w.outdent();
        w.print("}");
        w.println((i < methods.length - 1) ? "," : "");
      }

      w.outdent();
      w.println("};");

      w.outdent();
      w.println("}-*/;");
    }
Example #6
0
  /** {@inheritDoc} */
  public String toString() {
    StringBuilder sb = new StringBuilder(32);
    sb.append(_declaringClass.getName());
    sb.append('(');

    // -- print parameters
    for (int i = 0; i < _params.size(); i++) {
      JParameter jp = _params.get(i);
      if (i > 0) {
        sb.append(", ");
      }
      sb.append(jp.getType().getName());
    }
    sb.append(')');
    return sb.toString();
  }
  protected String toIteratedStringExpression(JParameter arg) {
    StringBuilder result = new StringBuilder();
    result
        .append("new org.fusesource.restygwt.client.StringIterable (")
        .append(arg.getName())
        .append(")");

    return result.toString();
  }
  private void writeMethodImpl(JMethod method) throws UnableToCompleteException {
    boolean returnRequest = false;
    if (method.getReturnType() != JPrimitiveType.VOID) {
      if (!method.getReturnType().getQualifiedSourceName().equals(Request.class.getName())
          && !method
              .getReturnType()
              .getQualifiedSourceName()
              .equals(JsonpRequest.class.getName())) {
        getLogger()
            .log(
                ERROR,
                "Invalid rest method. Method must have void, Request or JsonpRequest return types: "
                    + method.getReadableDeclaration());
        throw new UnableToCompleteException();
      } else {
        returnRequest = true;
      }
    }

    Json jsonAnnotation = source.getAnnotation(Json.class);
    final Style classStyle = jsonAnnotation != null ? jsonAnnotation.style() : Style.DEFAULT;

    Options classOptions = source.getAnnotation(Options.class);
    Options options = method.getAnnotation(Options.class);

    p(method.getReadableDeclaration(false, false, false, false, true) + " {").i(1);
    {
      String restMethod = getRestMethod(method);
      LinkedList<JParameter> args =
          new LinkedList<JParameter>(Arrays.asList(method.getParameters()));

      // the last arg should be the callback.
      if (args.isEmpty()) {
        getLogger()
            .log(
                ERROR,
                "Invalid rest method. Method must declare at least a callback argument: "
                    + method.getReadableDeclaration());
        throw new UnableToCompleteException();
      }
      JParameter callbackArg = args.removeLast();
      JClassType callbackType = callbackArg.getType().isClassOrInterface();
      JClassType methodCallbackType = METHOD_CALLBACK_TYPE;
      if (callbackType == null || !callbackType.isAssignableTo(methodCallbackType)) {
        getLogger()
            .log(
                ERROR,
                "Invalid rest method. Last argument must be a "
                    + methodCallbackType.getName()
                    + " type: "
                    + method.getReadableDeclaration());
        throw new UnableToCompleteException();
      }
      JClassType resultType = getCallbackTypeGenericClass(callbackType);

      String pathExpression = null;
      Path pathAnnotation = method.getAnnotation(Path.class);
      if (pathAnnotation != null) {
        pathExpression = wrap(pathAnnotation.value());
      }

      JParameter contentArg = null;
      HashMap<String, JParameter> queryParams = new HashMap<String, JParameter>();
      HashMap<String, JParameter> formParams = new HashMap<String, JParameter>();
      HashMap<String, JParameter> headerParams = new HashMap<String, JParameter>();

      for (JParameter arg : args) {
        PathParam paramPath = arg.getAnnotation(PathParam.class);
        if (paramPath != null) {
          if (pathExpression == null) {
            getLogger()
                .log(
                    ERROR,
                    "Invalid rest method.  Invalid @PathParam annotation. Method is missing the @Path annotation: "
                        + method.getReadableDeclaration());
            throw new UnableToCompleteException();
          }
          pathExpression = pathExpression(pathExpression, arg, paramPath);
          // .replaceAll(Pattern.quote("{" + paramPath.value() + "}"),
          // "\"+com.google.gwt.http.client.URL.encodePathSegment(" + toStringExpression(arg) +
          // ")+\"");
          if (arg.getAnnotation(Attribute.class) != null) {
            // allow part of the arg-object participate in as PathParam and the object goes over the
            // wire
            contentArg = arg;
          }
          continue;
        }

        QueryParam queryParam = arg.getAnnotation(QueryParam.class);
        if (queryParam != null) {
          queryParams.put(queryParam.value(), arg);
          continue;
        }

        FormParam formParam = arg.getAnnotation(FormParam.class);
        if (formParam != null) {
          formParams.put(formParam.value(), arg);
          continue;
        }

        HeaderParam headerParam = arg.getAnnotation(HeaderParam.class);
        if (headerParam != null) {
          headerParams.put(headerParam.value(), arg);
          continue;
        }

        if (!formParams.isEmpty()) {
          getLogger()
              .log(
                  ERROR,
                  "You can not have both @FormParam parameters and a content parameter: "
                      + method.getReadableDeclaration());
          throw new UnableToCompleteException();
        }

        if (contentArg != null) {
          getLogger()
              .log(
                  ERROR,
                  "Invalid rest method. Only one content parameter is supported: "
                      + method.getReadableDeclaration());
          throw new UnableToCompleteException();
        }
        contentArg = arg;
      }

      String acceptTypeBuiltIn = null;
      if (callbackType.equals(TEXT_CALLBACK_TYPE)) {
        acceptTypeBuiltIn = "CONTENT_TYPE_TEXT";
      } else if (callbackType.equals(JSON_CALLBACK_TYPE)) {
        acceptTypeBuiltIn = "CONTENT_TYPE_JSON";
      } else if (callbackType.isAssignableTo(OVERLAY_CALLBACK_TYPE)) {
        acceptTypeBuiltIn = "CONTENT_TYPE_JSON";
      } else if (callbackType.equals(XML_CALLBACK_TYPE)) {
        acceptTypeBuiltIn = "CONTENT_TYPE_XML";
      }

      p("final " + METHOD_CLASS + " __method =");

      p("getResource()");
      if (pathExpression != null) {
        p(".resolve(" + pathExpression + ")");
      }
      for (Map.Entry<String, JParameter> entry : queryParams.entrySet()) {
        String expr = entry.getValue().getName();
        JClassType type = entry.getValue().getType().isClassOrInterface();
        if (type != null && isQueryParamListType(type)) {
          p(
              ".addQueryParams("
                  + wrap(entry.getKey())
                  + ", "
                  + toIteratedStringExpression(entry.getValue())
                  + ")");
        } else {
          p(
              ".addQueryParam("
                  + wrap(entry.getKey())
                  + ", "
                  + toStringExpression(entry.getValue().getType(), expr)
                  + ")");
        }
      }
      // example: .get()
      p("." + restMethod + "();");

      // Handle JSONP specific configuration...
      JSONP jsonpAnnotation = method.getAnnotation(JSONP.class);

      final boolean isJsonp = restMethod.equals(METHOD_JSONP) && jsonpAnnotation != null;
      if (isJsonp) {
        if (returnRequest
            && !method
                .getReturnType()
                .getQualifiedSourceName()
                .equals(JsonpRequest.class.getName())) {
          getLogger()
              .log(
                  ERROR,
                  "Invalid rest method. JSONP method must have void or JsonpRequest return types: "
                      + method.getReadableDeclaration());
          throw new UnableToCompleteException();
        }
        if (jsonpAnnotation.callbackParam().length() > 0) {
          p(
              "(("
                  + JSONP_METHOD_CLASS
                  + ")__method).callbackParam("
                  + wrap(jsonpAnnotation.callbackParam())
                  + ");");
        }
        if (jsonpAnnotation.failureCallbackParam().length() > 0) {
          p(
              "(("
                  + JSONP_METHOD_CLASS
                  + ")__method).failureCallbackParam("
                  + wrap(jsonpAnnotation.failureCallbackParam())
                  + ");");
        }
      } else {
        if (returnRequest
            && !method.getReturnType().getQualifiedSourceName().equals(Request.class.getName())) {
          getLogger()
              .log(
                  ERROR,
                  "Invalid rest method. Non JSONP method must have void or Request return types: "
                      + method.getReadableDeclaration());
          throw new UnableToCompleteException();
        }
      }

      // configure the dispatcher
      if (options != null && options.dispatcher() != Dispatcher.class) {
        // use the dispatcher configured for the method.
        p("__method.setDispatcher(" + options.dispatcher().getName() + ".INSTANCE);");
      } else {
        // use the default dispatcher configured for the service..
        p("__method.setDispatcher(this.dispatcher);");
      }

      // configure the expected statuses..
      if (options != null && options.expect().length != 0) {
        // Using method level defined expected status
        p("__method.expect(" + join(options.expect(), ", ") + ");");
      } else if (classOptions != null && classOptions.expect().length != 0) {
        // Using class level defined expected status
        p("__method.expect(" + join(classOptions.expect(), ", ") + ");");
      }

      // configure the timeout
      if (options != null && options.timeout() >= 0) {
        // Using method level defined value
        p("__method.timeout(" + options.timeout() + ");");
      } else if (classOptions != null && classOptions.timeout() >= 0) {
        // Using class level defined value
        p("__method.timeout(" + classOptions.timeout() + ");");
      }

      if (jsonpAnnotation == null) {
        Produces producesAnnotation = findAnnotationOnMethodOrEnclosingType(method, Produces.class);
        if (producesAnnotation != null) {
          p(
              "__method.header("
                  + RESOURCE_CLASS
                  + ".HEADER_ACCEPT, "
                  + wrap(producesAnnotation.value()[0])
                  + ");");
        } else {
          // set the default accept header....
          if (acceptTypeBuiltIn != null) {
            p(
                "__method.header("
                    + RESOURCE_CLASS
                    + ".HEADER_ACCEPT, "
                    + RESOURCE_CLASS
                    + "."
                    + acceptTypeBuiltIn
                    + ");");
          } else {
            p(
                "__method.header("
                    + RESOURCE_CLASS
                    + ".HEADER_ACCEPT, "
                    + RESOURCE_CLASS
                    + ".CONTENT_TYPE_JSON);");
          }
        }

        Consumes consumesAnnotation = findAnnotationOnMethodOrEnclosingType(method, Consumes.class);
        if (consumesAnnotation != null) {
          p(
              "__method.header("
                  + RESOURCE_CLASS
                  + ".HEADER_CONTENT_TYPE, "
                  + wrap(consumesAnnotation.value()[0])
                  + ");");
        }

        // and set the explicit headers now (could override the accept header)
        for (Map.Entry<String, JParameter> entry : headerParams.entrySet()) {
          String expr = entry.getValue().getName();
          p(
              "__method.header("
                  + wrap(entry.getKey())
                  + ", "
                  + toStringExpression(entry.getValue().getType(), expr)
                  + ");");
        }
      }

      if (!formParams.isEmpty()) {
        p(FORM_POST_CONTENT_CLASS + " __formPostContent = new " + FORM_POST_CONTENT_CLASS + "();");

        for (Map.Entry<String, JParameter> entry : formParams.entrySet()) {
          p(
              "__formPostContent.addParameter("
                  + wrap(entry.getKey())
                  + ", "
                  + toFormStringExpression(entry.getValue(), classStyle)
                  + ");");
        }

        p("__method.form(__formPostContent.getTextContent());");
      }

      if (contentArg != null) {
        if (contentArg.getType() == STRING_TYPE) {
          p("__method.text(" + contentArg.getName() + ");");
        } else if (contentArg.getType() == JSON_VALUE_TYPE) {
          p("__method.json(" + contentArg.getName() + ");");
        } else if (contentArg.getType().isClass() != null
            && isOverlayArrayType(contentArg.getType().isClass())) {
          p("__method.json(new " + JSON_ARRAY_CLASS + "(" + contentArg.getName() + "));");
        } else if (contentArg.getType().isClass() != null
            && contentArg.getType().isClass().isAssignableTo(OVERLAY_VALUE_TYPE)) {
          p("__method.json(new " + JSON_OBJECT_CLASS + "(" + contentArg.getName() + "));");
        } else if (contentArg.getType() == DOCUMENT_TYPE) {
          p("__method.xml(" + contentArg.getName() + ");");
        } else {
          JClassType contentClass = contentArg.getType().isClass();
          if (contentClass == null) {
            contentClass = contentArg.getType().isClassOrInterface();
            if (!locator.isCollectionType(contentClass)) {
              getLogger().log(ERROR, "Content argument must be a class.");
              throw new UnableToCompleteException();
            }
          }

          jsonAnnotation = contentArg.getAnnotation(Json.class);
          Style style = jsonAnnotation != null ? jsonAnnotation.style() : classStyle;

          // example:
          // .json(Listings$_Generated_JsonEncoder_$.INSTANCE.encode(arg0)
          // )
          p(
              "__method.json("
                  + locator.encodeExpression(contentClass, contentArg.getName(), style)
                  + ");");
        }
      }

      List<AnnotationResolver> annotationResolvers = getAnnotationResolvers(context, getLogger());
      getLogger()
          .log(
              TreeLogger.DEBUG,
              "found " + annotationResolvers.size() + " additional AnnotationResolvers");

      for (AnnotationResolver a : annotationResolvers) {
        getLogger()
            .log(
                TreeLogger.DEBUG,
                "("
                    + a.getClass().getName()
                    + ") resolve `"
                    + source.getName()
                    + "#"
                    + method.getName()
                    + "ยด ...");
        final Map<String, String[]> addDataParams =
            a.resolveAnnotation(getLogger(), source, method, restMethod);

        if (addDataParams != null) {
          for (String s : addDataParams.keySet()) {
            final StringBuilder sb = new StringBuilder();
            final List<String> classList = Arrays.asList(addDataParams.get(s));

            sb.append("[");
            for (int i = 0; i < classList.size(); ++i) {
              sb.append("\\\"").append(classList.get(i)).append("\\\"");

              if ((i + 1) < classList.size()) {
                sb.append(",");
              }
            }
            sb.append("]");

            getLogger()
                .log(TreeLogger.DEBUG, "add call with (\"" + s + "\", \"" + sb.toString() + "\")");
            p("__method.addData(\"" + s + "\", \"" + sb.toString() + "\");");
          }
        }
      }

      if (acceptTypeBuiltIn != null) {
        // TODO: shouldn't we also have a cach in here?
        p(returnRequest(returnRequest, isJsonp) + "__method.send(" + callbackArg.getName() + ");");
      } else if (isJsonp) {
        p(returnRequest(returnRequest, isJsonp)
                + "(("
                + JSONP_METHOD_CLASS
                + ")__method).send(new "
                + ABSTRACT_ASYNC_CALLBACK_CLASS
                + "<"
                + resultType.getParameterizedQualifiedSourceName()
                + ">(("
                + JSONP_METHOD_CLASS
                + ")__method, "
                + callbackArg.getName()
                + ") {")
            .i(1);
        {
          p("protected "
                  + resultType.getParameterizedQualifiedSourceName()
                  + " parseResult("
                  + JSON_VALUE_CLASS
                  + " result) throws Exception {")
              .i(1);
          {
            if (resultType.getParameterizedQualifiedSourceName().equals("java.lang.Void")) {
              p("return (java.lang.Void) null;");
            } else {
              p("try {").i(1);
              {
                if (resultType.isAssignableTo(locator.LIST_TYPE)) {
                  p("result = new " + JSON_ARRAY_CLASS + "(result.getJavaScriptObject());");
                }
                jsonAnnotation = method.getAnnotation(Json.class);
                Style style = jsonAnnotation != null ? jsonAnnotation.style() : classStyle;
                p("return " + locator.decodeExpression(resultType, "result", style) + ";");
              }
              i(-1).p("} catch (Throwable __e) {").i(1);
              {
                p(
                    "throw new "
                        + RESPONSE_FORMAT_EXCEPTION_CLASS
                        + "(\"Response was NOT a valid JSON document\", __e);");
              }
              i(-1).p("}");
            }
          }
          i(-1).p("}");
        }
        i(-1).p("});");
      } else {
        p("try {").i(1);
        {
          p(returnRequest(returnRequest, isJsonp)
                  + "__method.send(new "
                  + ABSTRACT_REQUEST_CALLBACK_CLASS
                  + "<"
                  + resultType.getParameterizedQualifiedSourceName()
                  + ">(__method, "
                  + callbackArg.getName()
                  + ") {")
              .i(1);
          {
            p("protected "
                    + resultType.getParameterizedQualifiedSourceName()
                    + " parseResult() throws Exception {")
                .i(1);
            {
              if (resultType.getParameterizedQualifiedSourceName().equals("java.lang.Void")) {
                p("return (java.lang.Void) null;");
              } else {
                p("try {").i(1);
                {
                  jsonAnnotation = method.getAnnotation(Json.class);
                  Style style = jsonAnnotation != null ? jsonAnnotation.style() : classStyle;
                  p(
                      "return "
                          + locator.decodeExpression(
                              resultType,
                              JSON_PARSER_CLASS + ".parse(__method.getResponse().getText())",
                              style)
                          + ";");
                }
                i(-1).p("} catch (Throwable __e) {").i(1);
                {
                  p(
                      "throw new "
                          + RESPONSE_FORMAT_EXCEPTION_CLASS
                          + "(\"Response was NOT a valid JSON document\", __e);");
                }
                i(-1).p("}");
              }
            }
            i(-1).p("}");
          }
          i(-1).p("});");
        }
        i(-1).p("} catch (" + REQUEST_EXCEPTION_CLASS + " __e) {").i(1);
        {
          p(callbackArg.getName() + ".onFailure(__method,__e);");
          if (returnRequest) {
            p("return null;");
          }
        }
        i(-1).p("}");
      }
    }
    i(-1).p("}");
  }
Example #9
0
  private void checkJClass() {
    JClass testClass = new JClass("org.acme.JClassTest");

    testClass.addSourceCode("// source code");
    testClass.addSourceCode("// source code 2");

    testClass.addImport("java.util.Vector");
    testClass.appendAnnotation("@SuppressWarnings( \"all\" )");
    testClass.appendAnnotation("@Deprecated");
    testClass.addMember(new JField(JType.INT, "x"));
    JClass jcString = new JClass("String");

    JField field = null;
    field = new JField(JType.INT, "_z");
    field.appendAnnotation("@Deprecated");
    field.getModifiers().setStatic(true);
    testClass.addField(field);

    testClass.getStaticInitializationCode().add("_z = 75;");

    field = new JField(jcString, "myString");
    field.getModifiers().makePrivate();
    testClass.addMember(field);

    // generics test
    JType type = new JCollectionType("java.util.List", jcString, true);
    field = new JField(type, "generics");
    testClass.addMember(field);

    type = new JCollectionType("java.util.List", jcString, false);
    field = new JField(type, "noGenerics");
    testClass.addMember(field);

    // -- create constructor
    JConstructor cons = testClass.createConstructor();
    cons.appendAnnotation("@Deprecated");
    cons.getSourceCode().add("this.x = 6;");

    JMethod jMethod = new JMethod("getX", JType.INT, null);
    jMethod.appendAnnotation("@Deprecated");
    jMethod.setSourceCode("return this.x;");
    testClass.addMethod(jMethod);

    jMethod = new JMethod("setX", null, null);
    JParameter param = new JParameter(JType.INT, "x");
    jMethod.addParameter(param);
    jMethod.setSourceCode("this.x = x;");
    testClass.addMethod(jMethod);

    jMethod = new JMethod("checkParameterAnotation", JType.INT, null);
    param = new JParameter(JType.LONG, "param");
    param.appendAnnotation("@Test");
    param.appendAnnotation("@Test2");
    jMethod.addParameter(param);
    jMethod.setSourceCode("return param;");
    testClass.addMethod(jMethod);

    // -- create inner-class
    JClass innerClass = testClass.createInnerClass("Foo");
    innerClass.appendAnnotation("@Deprecated");
    innerClass.addImport("java.util.Hashtable");
    innerClass.addMember(new JField(JType.INT, "_type"));

    field = new JField(jcString, "_name");
    field.getModifiers().makePrivate();
    innerClass.addMember(field);

    testClass.createInnerClass("Bar");

    // -- create constructor
    cons = innerClass.createConstructor();
    cons.getSourceCode().add("_name = \"foo\";");

    jMethod = new JMethod("getName", jcString, null);
    jMethod.setSourceCode("return _name;");
    innerClass.addMethod(jMethod);

    testClass.print(getOutputDirectory().toString(), null);

    assertTrue(new File(getOutputDirectory(), "org/acme/JClassTest.java").exists());
  }
Example #10
0
  /**
   * Prints this JConstructor to the provided JSourceWriter.
   *
   * @param jsw The JSourceWriter to print the constructor to.
   */
  public void print(final JSourceWriter jsw) {
    // -- print annotations
    printAnnotations(jsw);

    if (_modifiers.isPrivate()) {
      jsw.write("private");
    } else if (_modifiers.isProtected()) {
      jsw.write("protected");
    } else {
      jsw.write("public");
    }
    jsw.write(' ');
    jsw.write(_declaringClass.getLocalName());
    jsw.write('(');

    // -- any parameter annotations?
    boolean parameterAnnotations = false;
    for (JParameter jParameter : _params.values()) {
      if (jParameter.hasAnnotations()) {
        parameterAnnotations = true;
        break;
      }
    }

    // -- print parameters
    if (parameterAnnotations) {
      jsw.indent();
    }
    int parameterCount = 0;
    for (JParameter jParameter : _params.values()) {
      if (parameterCount > 0) {
        jsw.write(", ");
      }
      if (parameterAnnotations) {
        jsw.writeln();
      }
      jParameter.printAnnotations(jsw);
      String typeAndName = jParameter.toString();
      jsw.write(typeAndName);
      parameterCount++;
    }
    if (parameterAnnotations) {
      jsw.unindent();
    }

    jsw.write(")");
    if (_exceptions.size() > 0) {
      jsw.writeln();
      jsw.write("throws ");
      for (int i = 0; i < _exceptions.size(); i++) {
        if (i > 0) {
          jsw.write(", ");
        }
        JClass jClass = _exceptions.elementAt(i);
        jsw.write(jClass.getName());
      }
    }
    jsw.writeln(" {");

    _sourceCode.print(jsw);

    if (!jsw.isNewline()) {
      jsw.writeln();
    }
    jsw.writeln("}");
  }