Java Code Examples for lombok.javac.JavacTreeMaker#Apply

The following examples show how to use lombok.javac.JavacTreeMaker#Apply . 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: HandleLog.java    From EasyMPermission with MIT License 6 votes vote down vote up
private static boolean createField(LoggingFramework framework, JavacNode typeNode, JCFieldAccess loggingType, JCTree source, String logFieldName, boolean useStatic, String loggerTopic) {
	JavacTreeMaker maker = typeNode.getTreeMaker();
	
	// private static final <loggerType> log = <factoryMethod>(<parameter>);
	JCExpression loggerType = chainDotsString(typeNode, framework.getLoggerTypeName());
	JCExpression factoryMethod = chainDotsString(typeNode, framework.getLoggerFactoryMethodName());

	JCExpression loggerName;
	if (loggerTopic == null || loggerTopic.trim().length() == 0) {
		loggerName = framework.createFactoryParameter(typeNode, loggingType);
	} else {
		loggerName = maker.Literal(loggerTopic);
	}

	JCMethodInvocation factoryMethodCall = maker.Apply(List.<JCExpression>nil(), factoryMethod, List.<JCExpression>of(loggerName));

	JCVariableDecl fieldDecl = recursiveSetGeneratedBy(maker.VarDef(
			maker.Modifiers(Flags.PRIVATE | Flags.FINAL | (useStatic ? Flags.STATIC : 0)),
			typeNode.toName(logFieldName), loggerType, factoryMethodCall), source, typeNode.getContext());
	
	injectFieldAndMarkGenerated(typeNode, fieldDecl);
	return true;
}
 
Example 2
Source File: JavacJavaUtilListSingularizer.java    From EasyMPermission with MIT License 6 votes vote down vote up
private List<JCStatement> createListCopy(JavacTreeMaker maker, SingularData data, JavacNode builderType, JCTree source) {
	List<JCExpression> jceBlank = List.nil();
	Name thisName = builderType.toName("this");
	
	JCExpression argToUnmodifiable; {
		 // new java.util.ArrayList<Generics>(this.pluralName);
		List<JCExpression> constructorArgs = List.nil();
		JCExpression thisDotPluralName = maker.Select(maker.Ident(thisName), data.getPluralName());
		constructorArgs = List.<JCExpression>of(thisDotPluralName);
		JCExpression targetTypeExpr = chainDots(builderType, "java", "util", "ArrayList");
		targetTypeExpr = addTypeArgs(1, false, builderType, targetTypeExpr, data.getTypeArgs(), source);
		argToUnmodifiable = maker.NewClass(null, jceBlank, targetTypeExpr, constructorArgs, null);
	}
	
	JCStatement unmodifiableStat; {
		// pluralname = Collections.unmodifiableInterfaceType(-newlist-);
		JCExpression invoke = maker.Apply(jceBlank, chainDots(builderType, "java", "util", "Collections", "unmodifiableList"), List.of(argToUnmodifiable));
		unmodifiableStat = maker.Exec(maker.Assign(maker.Ident(data.getPluralName()), invoke));
	}
	
	return List.of(unmodifiableStat);
}
 
Example 3
Source File: JavacJavaUtilListSetSingularizer.java    From EasyMPermission with MIT License 6 votes vote down vote up
void generateSingularMethod(JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean fluent) {
	List<JCTypeParameter> typeParams = List.nil();
	List<JCExpression> thrown = List.nil();
	
	JCModifiers mods = maker.Modifiers(Flags.PUBLIC);
	ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
	statements.append(createConstructBuilderVarIfNeeded(maker, data, builderType, false, source));
	JCExpression thisDotFieldDotAdd = chainDots(builderType, "this", data.getPluralName().toString(), "add");
	JCExpression invokeAdd = maker.Apply(List.<JCExpression>nil(), thisDotFieldDotAdd, List.<JCExpression>of(maker.Ident(data.getSingularName())));
	statements.append(maker.Exec(invokeAdd));
	if (returnStatement != null) statements.append(returnStatement);
	JCBlock body = maker.Block(0, statements.toList());
	Name name = data.getSingularName();
	long paramFlags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, builderType.getContext());
	if (!fluent) name = builderType.toName(HandlerUtil.buildAccessorName("add", name.toString()));
	JCExpression paramType = cloneParamType(0, maker, data.getTypeArgs(), builderType, source);
	JCVariableDecl param = maker.VarDef(maker.Modifiers(paramFlags), data.getSingularName(), paramType, null);
	JCMethodDecl method = maker.MethodDef(mods, name, returnType, typeParams, List.of(param), thrown, body, null);
	injectMethod(builderType, method);
}
 
Example 4
Source File: JavacJavaUtilListSetSingularizer.java    From EasyMPermission with MIT License 6 votes vote down vote up
void generatePluralMethod(JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean fluent) {
	List<JCTypeParameter> typeParams = List.nil();
	List<JCExpression> thrown = List.nil();
	
	JCModifiers mods = maker.Modifiers(Flags.PUBLIC);
	ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
	statements.append(createConstructBuilderVarIfNeeded(maker, data, builderType, false, source));
	JCExpression thisDotFieldDotAdd = chainDots(builderType, "this", data.getPluralName().toString(), "addAll");
	JCExpression invokeAdd = maker.Apply(List.<JCExpression>nil(), thisDotFieldDotAdd, List.<JCExpression>of(maker.Ident(data.getPluralName())));
	statements.append(maker.Exec(invokeAdd));
	if (returnStatement != null) statements.append(returnStatement);
	JCBlock body = maker.Block(0, statements.toList());
	Name name = data.getPluralName();
	long paramFlags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, builderType.getContext());
	if (!fluent) name = builderType.toName(HandlerUtil.buildAccessorName("addAll", name.toString()));
	JCExpression paramType = chainDots(builderType, "java", "util", "Collection");
	paramType = addTypeArgs(1, true, builderType, paramType, data.getTypeArgs(), source);
	JCVariableDecl param = maker.VarDef(maker.Modifiers(paramFlags), data.getPluralName(), paramType, null);
	JCMethodDecl method = maker.MethodDef(mods, name, returnType, typeParams, List.of(param), thrown, body, null);
	injectMethod(builderType, method);
}
 
Example 5
Source File: JavacHandlerUtil.java    From EasyMPermission with MIT License 5 votes vote down vote up
static JCExpression createFieldAccessor(JavacTreeMaker maker, JavacNode field, FieldAccess fieldAccess, JCExpression receiver) {
	boolean lookForGetter = lookForGetter(field, fieldAccess);
	
	GetterMethod getter = lookForGetter ? findGetter(field) : null;
	JCVariableDecl fieldDecl = (JCVariableDecl) field.get();
	
	if (getter == null) {
		if (receiver == null) {
			if ((fieldDecl.mods.flags & Flags.STATIC) == 0) {
				receiver = maker.Ident(field.toName("this"));
			} else {
				JavacNode containerNode = field.up();
				if (containerNode != null && containerNode.get() instanceof JCClassDecl) {
					JCClassDecl container = (JCClassDecl) field.up().get();
					receiver = maker.Ident(container.name);
				}
			}
		}
		
		return receiver == null ? maker.Ident(fieldDecl.name) : maker.Select(receiver, fieldDecl.name);
	}
	
	if (receiver == null) receiver = maker.Ident(field.toName("this"));
	JCMethodInvocation call = maker.Apply(List.<JCExpression>nil(),
			maker.Select(receiver, getter.name), List.<JCExpression>nil());
	return call;
}
 
Example 6
Source File: JavacSingularsRecipes.java    From EasyMPermission with MIT License 5 votes vote down vote up
/** Generates 'this.<em>name</em>.size()' as an expression; if nullGuard is true, it's this.name == null ? 0 : this.name.size(). */
protected JCExpression getSize(JavacTreeMaker maker, JavacNode builderType, Name name, boolean nullGuard) {
	Name thisName = builderType.toName("this");
	JCExpression fn = maker.Select(maker.Select(maker.Ident(thisName), name), builderType.toName("size"));
	JCExpression sizeInvoke = maker.Apply(List.<JCExpression>nil(), fn, List.<JCExpression>nil());
	if (nullGuard) {
		JCExpression isNull = maker.Binary(CTC_EQUAL, maker.Select(maker.Ident(thisName), name), maker.Literal(CTC_BOT, 0));
		return maker.Conditional(isNull, maker.Literal(CTC_INT, 0), sizeInvoke);
	}
	return sizeInvoke;
}
 
Example 7
Source File: HandleCleanup.java    From EasyMPermission with MIT License 5 votes vote down vote up
public JCExpression preventNullAnalysis(JavacTreeMaker maker, JavacNode node, JCExpression expression) {
	if (LombokOptionsFactory.getDelombokOptions(node.getContext()).getFormatPreferences().danceAroundIdeChecks()) {
		JCMethodInvocation singletonList = maker.Apply(List.<JCExpression>nil(), chainDotsString(node, "java.util.Collections.singletonList"), List.of(expression));
		JCMethodInvocation cleanedExpr = maker.Apply(List.<JCExpression>nil(), maker.Select(singletonList, node.toName("get")) , List.<JCExpression>of(maker.Literal(CTC_INT, 0)));
		return cleanedExpr;
	} else {
		return expression;
	}
}
 
Example 8
Source File: JavacJavaUtilMapSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
private void generatePluralMethod(JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean fluent) {
	List<JCTypeParameter> typeParams = List.nil();
	List<JCExpression> jceBlank = List.nil();
	JCModifiers mods = maker.Modifiers(Flags.PUBLIC);
	ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
	statements.append(createConstructBuilderVarIfNeeded(maker, data, builderType, true, source));
	long paramFlags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, builderType.getContext());
	long baseFlags = JavacHandlerUtil.addFinalIfNeeded(0, builderType.getContext());
	Name entryName = builderType.toName("$lombokEntry");
	
	JCExpression forEachType = chainDots(builderType, "java", "util", "Map", "Entry");
	forEachType = addTypeArgs(2, true, builderType, forEachType, data.getTypeArgs(), source);
	JCExpression keyArg = maker.Apply(List.<JCExpression>nil(), maker.Select(maker.Ident(entryName), builderType.toName("getKey")), List.<JCExpression>nil());
	JCExpression valueArg = maker.Apply(List.<JCExpression>nil(), maker.Select(maker.Ident(entryName), builderType.toName("getValue")), List.<JCExpression>nil());
	JCExpression addKey = maker.Apply(List.<JCExpression>nil(), chainDots(builderType, "this", data.getPluralName() + "$key", "add"), List.of(keyArg));
	JCExpression addValue = maker.Apply(List.<JCExpression>nil(), chainDots(builderType, "this", data.getPluralName() + "$value", "add"), List.of(valueArg));
	JCBlock forEachBody = maker.Block(0, List.<JCStatement>of(maker.Exec(addKey), maker.Exec(addValue)));
	JCExpression entrySetInvocation = maker.Apply(jceBlank, maker.Select(maker.Ident(data.getPluralName()), builderType.toName("entrySet")), jceBlank);
	JCStatement forEach = maker.ForeachLoop(maker.VarDef(maker.Modifiers(baseFlags), entryName, forEachType, null), entrySetInvocation, forEachBody);
	statements.append(forEach);
	
	if (returnStatement != null) statements.append(returnStatement);
	JCBlock body = maker.Block(0, statements.toList());
	Name name = data.getPluralName();
	if (!fluent) name = builderType.toName(HandlerUtil.buildAccessorName("putAll", name.toString()));
	JCExpression paramType = chainDots(builderType, "java", "util", "Map");
	paramType = addTypeArgs(2, true, builderType, paramType, data.getTypeArgs(), source);
	JCVariableDecl param = maker.VarDef(maker.Modifiers(paramFlags), data.getPluralName(), paramType, null);
	JCMethodDecl method = maker.MethodDef(mods, name, returnType, typeParams, List.of(param), jceBlank, body, null);
	injectMethod(builderType, method);
}
 
Example 9
Source File: JavacGuavaSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
void generateSingularMethod(JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean fluent) {
	List<JCTypeParameter> typeParams = List.nil();
	List<JCExpression> thrown = List.nil();
	boolean mapMode = isMap();
	
	Name keyName = !mapMode ? data.getSingularName() : builderType.toName(data.getSingularName() + "$key");
	Name valueName = !mapMode ? null : builderType.toName(data.getSingularName() + "$value");
	
	JCModifiers mods = maker.Modifiers(Flags.PUBLIC);
	ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
	statements.append(createConstructBuilderVarIfNeeded(maker, data, builderType, mapMode, source));
	JCExpression thisDotFieldDotAdd = chainDots(builderType, "this", data.getPluralName().toString(), mapMode ? "put" : "add");
	List<JCExpression> invokeAddExpr;
	if (mapMode) {
		invokeAddExpr = List.<JCExpression>of(maker.Ident(keyName), maker.Ident(valueName));
	} else {
		invokeAddExpr = List.<JCExpression>of(maker.Ident(keyName));
	}
	JCExpression invokeAdd = maker.Apply(List.<JCExpression>nil(), thisDotFieldDotAdd, invokeAddExpr);
	statements.append(maker.Exec(invokeAdd));
	if (returnStatement != null) statements.append(returnStatement);
	JCBlock body = maker.Block(0, statements.toList());
	Name methodName = data.getSingularName();
	long paramFlags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, builderType.getContext());
	if (!fluent) methodName = builderType.toName(HandlerUtil.buildAccessorName(mapMode ? "put" : "add", methodName.toString()));
	List<JCVariableDecl> params;
	if (mapMode) {
		JCExpression keyType = cloneParamType(0, maker, data.getTypeArgs(), builderType, source);
		JCExpression valueType = cloneParamType(1, maker, data.getTypeArgs(), builderType, source);
		JCVariableDecl paramKey = maker.VarDef(maker.Modifiers(paramFlags), keyName, keyType, null);
		JCVariableDecl paramValue = maker.VarDef(maker.Modifiers(paramFlags), valueName, valueType, null);
		params = List.of(paramKey, paramValue);
	} else {
		JCExpression paramType = cloneParamType(0, maker, data.getTypeArgs(), builderType, source);
		params = List.of(maker.VarDef(maker.Modifiers(paramFlags), data.getSingularName(), paramType, null));
	}
	JCMethodDecl method = maker.MethodDef(mods, methodName, returnType, typeParams, params, thrown, body, null);
	injectMethod(builderType, method);
}
 
Example 10
Source File: JavacGuavaSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
protected void generatePluralMethod(JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean fluent) {
	List<JCTypeParameter> typeParams = List.nil();
	List<JCExpression> thrown = List.nil();
	boolean mapMode = isMap();
	
	JCModifiers mods = maker.Modifiers(Flags.PUBLIC);
	ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
	statements.append(createConstructBuilderVarIfNeeded(maker, data, builderType, mapMode, source));
	JCExpression thisDotFieldDotAddAll = chainDots(builderType, "this", data.getPluralName().toString(), mapMode ? "putAll" : "addAll");
	JCExpression invokeAddAll = maker.Apply(List.<JCExpression>nil(), thisDotFieldDotAddAll, List.<JCExpression>of(maker.Ident(data.getPluralName())));
	statements.append(maker.Exec(invokeAddAll));
	if (returnStatement != null) statements.append(returnStatement);
	JCBlock body = maker.Block(0, statements.toList());
	Name methodName = data.getPluralName();
	long paramFlags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, builderType.getContext());
	if (!fluent) methodName = builderType.toName(HandlerUtil.buildAccessorName(mapMode ? "putAll" : "addAll", methodName.toString()));
	JCExpression paramType;
	if (mapMode) {
		paramType = chainDots(builderType, "java", "util", "Map");
	} else {
		paramType = genJavaLangTypeRef(builderType, "Iterable");
	}
	paramType = addTypeArgs(mapMode ? 2 : 1, true, builderType, paramType, data.getTypeArgs(), source);
	JCVariableDecl param = maker.VarDef(maker.Modifiers(paramFlags), data.getPluralName(), paramType, null);
	JCMethodDecl method = maker.MethodDef(mods, methodName, returnType, typeParams, List.of(param), thrown, body, null);
	injectMethod(builderType, method);
}
 
Example 11
Source File: JavacGuavaSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
@Override public void appendBuildCode(SingularData data, JavacNode builderType, JCTree source, ListBuffer<JCStatement> statements, Name targetVariableName) {
	JavacTreeMaker maker = builderType.getTreeMaker();
	List<JCExpression> jceBlank = List.nil();
	boolean mapMode = isMap();
	
	JCExpression varType = chainDotsString(builderType, data.getTargetFqn());
	varType = addTypeArgs(mapMode ? 2 : 1, false, builderType, varType, data.getTypeArgs(), source);
	
	JCExpression empty; {
		//ImmutableX.of()
		JCExpression emptyMethod = chainDots(builderType, "com", "google", "common", "collect", getSimpleTargetTypeName(data), "of");
		List<JCExpression> invokeTypeArgs = createTypeArgs(mapMode ? 2 : 1, false, builderType, data.getTypeArgs(), source);
		empty = maker.Apply(invokeTypeArgs, emptyMethod, jceBlank);
	}
	
	JCExpression invokeBuild; {
		//this.pluralName.build();
		invokeBuild = maker.Apply(jceBlank, chainDots(builderType, "this", data.getPluralName().toString(), "build"), jceBlank);
	}
	
	JCExpression isNull; {
		//this.pluralName == null
		isNull = maker.Binary(CTC_EQUAL, maker.Select(maker.Ident(builderType.toName("this")), data.getPluralName()), maker.Literal(CTC_BOT, null));
	}
	
	JCExpression init = maker.Conditional(isNull, empty, invokeBuild); // this.pluralName == null ? ImmutableX.of() : this.pluralName.build()
	
	JCStatement jcs = maker.VarDef(maker.Modifiers(0), data.getPluralName(), varType, init);
	statements.append(jcs);
}
 
Example 12
Source File: JavacGuavaSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
protected JCStatement createConstructBuilderVarIfNeeded(JavacTreeMaker maker, SingularData data, JavacNode builderType, boolean mapMode, JCTree source) {
	List<JCExpression> jceBlank = List.nil();
	
	JCExpression thisDotField = maker.Select(maker.Ident(builderType.toName("this")), data.getPluralName());
	JCExpression thisDotField2 = maker.Select(maker.Ident(builderType.toName("this")), data.getPluralName());
	JCExpression cond = maker.Binary(CTC_EQUAL, thisDotField, maker.Literal(CTC_BOT, null));
	
	JCExpression create = maker.Apply(jceBlank, chainDots(builderType, "com", "google", "common", "collect", getSimpleTargetTypeName(data), getBuilderMethodName(data)), jceBlank);
	JCStatement thenPart = maker.Exec(maker.Assign(thisDotField2, create));
	
	return maker.If(cond, thenPart, null);
}
 
Example 13
Source File: HandleRuntimePermission.java    From EasyMPermission with MIT License 4 votes vote down vote up
private JCBlock createPermissionCheckedBlock(JavacNode typeNode, PermissionAnnotatedItem permissionAnnotatedItem) {
    JavacTreeMaker treeMaker = typeNode.getTreeMaker();

    // Create permission list
    ListBuffer<JCExpression> permissionArgs = new ListBuffer<JCExpression>();
    for (String permission : permissionAnnotatedItem.getPermissions()) {
        permissionArgs.append(treeMaker.Literal(permission));
    }

    String permissionVarName = "_permissions_" + permissionAnnotatedItem.getMethod().getName();
    JCExpression v = treeMaker.NewArray(null,
            List.<JCExpression>nil(),
            permissionArgs.toList());
    JCVariableDecl permissions = Variable(typeNode)
            .modifiers(Flags.PRIVATE)
            .name(permissionVarName)
            .type(treeMaker.TypeArray(genJavaLangTypeRef(typeNode, "String")))
            .value(v)
            .build();
    injectField(typeNode, permissions);

    JCExpression checkMethod = JavacHandlerUtil.chainDots(typeNode, "this", IS_PERMISSION_GRANTED_METHOD);
    List<JCExpression> checkArgs = List.<JCExpression>of(treeMaker.Ident(typeNode.toName(permissionVarName)));
    JCMethodInvocation checkInvocation = treeMaker.Apply(List.<JCExpression>nil(), checkMethod, checkArgs);
    JCExpression permissionCmp = treeMaker.Binary(CTC_EQUAL,
            checkInvocation,
            treeMaker.Literal(CTC_BOOLEAN, 1));

    JCExpression requestMethod = JavacHandlerUtil.chainDots(typeNode, "this", "requestPermissions");
    List<JCExpression> requestArgs = List.<JCExpression>of(
            treeMaker.Ident(typeNode.toName(permissionVarName)),
            treeMaker.Literal(CTC_INT, permissionAnnotatedItem.getRequestCode()));
    JCMethodInvocation requestInvocation = treeMaker.Apply(List.<JCExpression>nil(), requestMethod, requestArgs);
    JCBlock body = Block(typeNode)
            .last(treeMaker.Exec(requestInvocation))
            .build();

    JCIf jcCheckPermissionIf = If(typeNode)
            .condition(permissionCmp)
            .withThen(permissionAnnotatedItem.getMethod().getBody())
            .withElse(body)
            .build();
    JCBlock checkPermissionBlock = Block(typeNode)
            .last(jcCheckPermissionIf)
            .build();

    JCExpression versionCmp = treeMaker.Binary(CTC_LESS_THAN,
            JavacHandlerUtil.chainDots(typeNode, "android", "os", "Build", "VERSION", "SDK_INT"),
            treeMaker.Literal(CTC_INT, 23));
    JCIf jcIf = If(typeNode)
            .condition(versionCmp)
            .withThen(permissionAnnotatedItem.getMethod().getBody())
            .withElse(checkPermissionBlock)
            .build();

    return Block(typeNode)
            .last(jcIf)
            .build();
}
 
Example 14
Source File: HandleRuntimePermission.java    From EasyMPermission with MIT License 4 votes vote down vote up
private JCMethodDecl createIsPermissionGrantedMethod(JavacNode typeNode) {
    JavacTreeMaker treeMaker = typeNode.getTreeMaker();

    ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();

    statements.append(Variable(typeNode)
            .modifiers(0)
            .name("ok")
            .type(treeMaker.TypeIdent(CTC_BOOLEAN))
            .value(treeMaker.Literal(CTC_BOOLEAN, 1))
            .build());

    statements.append(Variable(typeNode)
            .modifiers(0)
            .name("failed")
            .type(treeMaker.TypeIdent(CTC_BOOLEAN))
            .value(treeMaker.Literal(CTC_BOOLEAN, 0))
            .build());

    JCTree.JCExpression returnType = treeMaker.TypeIdent(CTC_BOOLEAN);

    List<JCTypeParameter> typleList = List.nil();

    List<JCVariableDecl> paramList = List.of(
            Variable(typeNode)
                    .modifiers(Flags.PARAMETER)
                    .name("permissions")
                    .type(treeMaker.TypeArray(genJavaLangTypeRef(typeNode, "String")))
                    .value(null)
                    .build()
    );

    JCVariableDecl v = Variable(typeNode)
            .modifiers(Flags.PARAMETER)
            .name("permission")
            .type(genJavaLangTypeRef(typeNode, "String"))
            .value(null)
            .build();

    JCExpression checkMethod = JavacHandlerUtil.chainDots(typeNode, "this", "checkSelfPermission");
    List<JCExpression> checkArgs = List.<JCExpression>of(treeMaker.Ident(typeNode.toName("permission")));
    JCMethodInvocation checkInvocation = treeMaker.Apply(List.<JCExpression>nil(), checkMethod, checkArgs);
    JCExpression cmp = treeMaker.Binary(CTC_NOT_EQUAL,
            checkInvocation,
            JavacHandlerUtil.chainDots(typeNode, "android", "content", "pm", "PackageManager", "PERMISSION_GRANTED"));

    JCBlock body = Block(typeNode)
            .last(treeMaker.Return(treeMaker.Ident(typeNode.toName("failed"))))
            .build();

    JCIf jcIf = If(typeNode)
            .condition(cmp)
            .onlyThen(body)
            .build();

    JCEnhancedForLoop block = treeMaker.ForeachLoop(v,
            treeMaker.Ident(typeNode.toName("permissions")),
            jcIf);
    statements.append(block);

    statements.append(treeMaker.Return(treeMaker.Ident(typeNode.toName("ok"))));

    body = Block(typeNode)
            .last(statements.toList())
            .build();

    return Method(typeNode)
            .modifiers(Flags.PRIVATE)
            .returnType(returnType)
            .name(IS_PERMISSION_GRANTED_METHOD)
            .paramType(typleList)
            .parameters(paramList)
            .thrown()
            .body(body)
            .build();
}
 
Example 15
Source File: HandleRuntimePermission.java    From EasyMPermission with MIT License 4 votes vote down vote up
private JCMethodDecl createOnRequestPermissionMethod(JavacNode typeNode, List<PermissionAnnotatedItem> permissionList) {
    JavacTreeMaker treeMaker = typeNode.getTreeMaker();

    ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();

    JCTree.JCExpression returnType = treeMaker.Type(Javac.createVoidType(treeMaker, CTC_VOID));

    List<JCVariableDecl> paramList = List.of(
        Variable(typeNode)
                .modifiers(Flags.PARAMETER)
                .name("requestCode")
                .type(treeMaker.TypeIdent(CTC_INT))
                .value(null)
                .build(),
        Variable(typeNode)
                .modifiers(Flags.PARAMETER)
                .name("permissions")
                .type(treeMaker.TypeArray(genJavaLangTypeRef(typeNode, "String")))
                .value(null)
                .build(),
        Variable(typeNode)
                .modifiers(Flags.PARAMETER)
                .name("grantResults")
                .type(treeMaker.TypeArray(treeMaker.TypeIdent(CTC_INT)))
                .value(null)
                .build()
    );

    for (PermissionAnnotatedItem item : permissionList) {

        JCReturn jcReturn = treeMaker.Return(null);

        JCBinary cmpRequestCode = treeMaker.Binary(CTC_EQUAL,
                treeMaker.Ident(typeNode.toName("requestCode")),
                treeMaker.Literal(CTC_INT, item.getRequestCode()));

        JCBinary cmpGrantResult = treeMaker.Binary(CTC_NOT_EQUAL,
                treeMaker.Indexed(treeMaker.Ident(typeNode.toName("grantResults")), treeMaker.Literal(CTC_INT, 0)),
                JavacHandlerUtil.chainDots(typeNode, "android", "content", "pm", "PackageManager", "PERMISSION_GRANTED"));

        JCExpression toastMethod =
                JavacHandlerUtil.chainDots(typeNode, "android", "widget", "Toast", "makeText");
        List<JCExpression> toastArgs = List.<JCTree.JCExpression>of(
                treeMaker.Ident(typeNode.toName("this")),
                treeMaker.Literal(MESSAGE_PERMISSIONS_WERE_NOT_GRANTED),
                treeMaker.Literal(CTC_INT, 1));
        JCMethodInvocation printlnInvocation =
                treeMaker.Apply(List.<JCTree.JCExpression>nil(), toastMethod, toastArgs);
        JCExpressionStatement thenPart = treeMaker.Exec(
                treeMaker.Apply(List.<JCTree.JCExpression>nil(), treeMaker.Select(printlnInvocation, typeNode.toName("show")), List.<JCExpression>nil()));

        toastArgs = List.<JCTree.JCExpression>of(
                treeMaker.Ident(typeNode.toName("this")),
                treeMaker.Literal(MESSAGE_PERMISSIONS_HAVE_BEEN_GRANTED),
                treeMaker.Literal(CTC_INT, 1));
        printlnInvocation =
                treeMaker.Apply(List.<JCTree.JCExpression>nil(), toastMethod, toastArgs);
        JCExpressionStatement elsePart = treeMaker.Exec(
                treeMaker.Apply(List.<JCTree.JCExpression>nil(), treeMaker.Select(printlnInvocation, typeNode.toName("show")), List.<JCExpression>nil()));

        JCIf jcIfGrantResult = If(typeNode)
                .condition(cmpGrantResult)
                .withThen(Block(typeNode).last(thenPart).build())
                .withElse(Block(typeNode).last(elsePart).build())
                .build();

        JCIf jcIfRequestCode = If(typeNode)
                .condition(cmpRequestCode)
                .onlyThen(Block(typeNode).add(jcIfGrantResult).last(jcReturn).build())
                .build();

        statements.append(jcIfRequestCode);
    }

    JCBlock body = Block(typeNode)
            .last(statements.toList())
            .build();

    return Method(typeNode)
            .modifiers(Flags.PUBLIC)
            .returnType(returnType)
            .name("onRequestPermissionsResult")
            .paramType()
            .parameters(paramList)
            .thrown()
            .body(body)
            .build();
}
 
Example 16
Source File: JavacJavaUtilSingularizer.java    From EasyMPermission with MIT License 4 votes vote down vote up
protected List<JCStatement> createJavaUtilSimpleCreationAndFillStatements(JavacTreeMaker maker, SingularData data, JavacNode builderType, boolean mapMode, boolean defineVar, boolean addInitialCapacityArg, boolean nullGuard, String targetType, JCTree source) {
	List<JCExpression> jceBlank = List.nil();
	Name thisName = builderType.toName("this");
	
	JCStatement createStat; {
		 // pluralName = new java.util.TargetType(initialCap);
		List<JCExpression> constructorArgs = List.nil();
		if (addInitialCapacityArg) {
			Name varName = mapMode ? builderType.toName(data.getPluralName() + "$key") : data.getPluralName();
			// this.varName.size() < MAX_POWER_OF_2 ? 1 + this.varName.size() + (this.varName.size() - 3) / 3 : Integer.MAX_VALUE;
			// lessThanCutOff = this.varName.size() < MAX_POWER_OF_2
			JCExpression lessThanCutoff = maker.Binary(CTC_LESS_THAN, getSize(maker, builderType, varName, nullGuard), maker.Literal(CTC_INT, 0x40000000));
			JCExpression integerMaxValue = genJavaLangTypeRef(builderType, "Integer", "MAX_VALUE");
			JCExpression sizeFormulaLeft = maker.Binary(CTC_PLUS, maker.Literal(CTC_INT, 1), getSize(maker, builderType, varName, nullGuard));
			JCExpression sizeFormulaRightLeft = maker.Binary(CTC_MINUS, getSize(maker, builderType, varName, nullGuard), maker.Literal(CTC_INT, 3));
			JCExpression sizeFormulaRight = maker.Binary(CTC_DIV, sizeFormulaRightLeft, maker.Literal(CTC_INT, 3));
			JCExpression sizeFormula = maker.Binary(CTC_PLUS, sizeFormulaLeft, sizeFormulaRight);
			constructorArgs = List.<JCExpression>of(maker.Conditional(lessThanCutoff, sizeFormula, integerMaxValue));
		}
		
		JCExpression targetTypeExpr = chainDots(builderType, "java", "util", targetType);
		targetTypeExpr = addTypeArgs(mapMode ? 2 : 1, false, builderType, targetTypeExpr, data.getTypeArgs(), source);
		JCExpression constructorCall = maker.NewClass(null, jceBlank, targetTypeExpr, constructorArgs, null);
		if (defineVar) {
			JCExpression localShadowerType = chainDotsString(builderType, data.getTargetFqn());
			localShadowerType = addTypeArgs(mapMode ? 2 : 1, false, builderType, localShadowerType, data.getTypeArgs(), source);
			createStat = maker.VarDef(maker.Modifiers(0), data.getPluralName(), localShadowerType, constructorCall);
		} else {
			createStat = maker.Exec(maker.Assign(maker.Ident(data.getPluralName()), constructorCall));
		}
	}
	
	JCStatement fillStat; {
		if (mapMode) {
			// for (int $i = 0; $i < this.pluralname$key.size(); i++) pluralname.put(this.pluralname$key.get($i), this.pluralname$value.get($i));
			Name ivar = builderType.toName("$i");
			Name keyVarName = builderType.toName(data.getPluralName() + "$key");
			JCExpression pluralnameDotPut = maker.Select(maker.Ident(data.getPluralName()), builderType.toName("put"));
			JCExpression arg1 = maker.Apply(jceBlank, chainDots(builderType, "this", data.getPluralName() + "$key", "get"), List.<JCExpression>of(maker.Ident(ivar)));
			JCExpression arg2 = maker.Apply(jceBlank, chainDots(builderType, "this", data.getPluralName() + "$value", "get"), List.<JCExpression>of(maker.Ident(ivar)));
			JCStatement putStatement = maker.Exec(maker.Apply(jceBlank, pluralnameDotPut, List.of(arg1, arg2)));
			JCStatement forInit = maker.VarDef(maker.Modifiers(0), ivar, maker.TypeIdent(CTC_INT), maker.Literal(CTC_INT, 0));
			JCExpression checkExpr = maker.Binary(CTC_LESS_THAN, maker.Ident(ivar), getSize(maker, builderType, keyVarName, nullGuard));
			JCExpression incrementExpr = maker.Unary(CTC_POSTINC, maker.Ident(ivar));
			fillStat = maker.ForLoop(List.of(forInit), checkExpr, List.of(maker.Exec(incrementExpr)), putStatement);
		} else {
			// pluralname.addAll(this.pluralname);
			JCExpression thisDotPluralName = maker.Select(maker.Ident(thisName), data.getPluralName());
			fillStat = maker.Exec(maker.Apply(jceBlank, maker.Select(maker.Ident(data.getPluralName()), builderType.toName("addAll")), List.of(thisDotPluralName)));
		}
		if (nullGuard) {
			JCExpression thisDotField = maker.Select(maker.Ident(thisName), mapMode ? builderType.toName(data.getPluralName() + "$key") : data.getPluralName());
			JCExpression nullCheck = maker.Binary(CTC_NOT_EQUAL, thisDotField, maker.Literal(CTC_BOT, null));
			fillStat = maker.If(nullCheck, fillStat, null);
		}
	}
	JCStatement unmodifiableStat; {
		// pluralname = Collections.unmodifiableInterfaceType(pluralname);
		JCExpression arg = maker.Ident(data.getPluralName());
		JCExpression invoke = maker.Apply(jceBlank, chainDots(builderType, "java", "util", "Collections", "unmodifiable" + data.getTargetSimpleType()), List.of(arg));
		unmodifiableStat = maker.Exec(maker.Assign(maker.Ident(data.getPluralName()), invoke));
	}
	
	return List.of(createStat, fillStat, unmodifiableStat);
}
 
Example 17
Source File: HandleDelegate.java    From EasyMPermission with MIT License 4 votes vote down vote up
public JCExpression get(final JavacNode node, final Name name) {
	com.sun.tools.javac.util.List<JCExpression> nilExprs = com.sun.tools.javac.util.List.nil();
	final JavacTreeMaker maker = node.getTreeMaker();
	return maker.Apply(nilExprs, maker.Select(maker.Ident(node.toName("this")), name), nilExprs);
}
 
Example 18
Source File: HandleToString.java    From EasyMPermission with MIT License 4 votes vote down vote up
static JCMethodDecl createToString(JavacNode typeNode, Collection<JavacNode> fields, boolean includeFieldNames, boolean callSuper, FieldAccess fieldAccess, JCTree source) {
	JavacTreeMaker maker = typeNode.getTreeMaker();
	
	JCAnnotation overrideAnnotation = maker.Annotation(genJavaLangTypeRef(typeNode, "Override"), List.<JCExpression>nil());
	JCModifiers mods = maker.Modifiers(Flags.PUBLIC, List.of(overrideAnnotation));
	JCExpression returnType = genJavaLangTypeRef(typeNode, "String");
	
	boolean first = true;
	
	String typeName = getTypeName(typeNode);
	String infix = ", ";
	String suffix = ")";
	String prefix;
	if (callSuper) {
		prefix = typeName + "(super=";
	} else if (fields.isEmpty()) {
		prefix = typeName + "()";
	} else if (includeFieldNames) {
		prefix = typeName + "(" + ((JCVariableDecl)fields.iterator().next().get()).name.toString() + "=";
	} else {
		prefix = typeName + "(";
	}
	
	JCExpression current = maker.Literal(prefix);
	
	if (callSuper) {
		JCMethodInvocation callToSuper = maker.Apply(List.<JCExpression>nil(),
				maker.Select(maker.Ident(typeNode.toName("super")), typeNode.toName("toString")),
				List.<JCExpression>nil());
		current = maker.Binary(CTC_PLUS, current, callToSuper);
		first = false;
	}
	
	for (JavacNode fieldNode : fields) {
		JCExpression expr;
		
		JCExpression fieldAccessor = createFieldAccessor(maker, fieldNode, fieldAccess);
		
		JCExpression fieldType = getFieldType(fieldNode, fieldAccess);
		
		// The distinction between primitive and object will be useful if we ever add a 'hideNulls' option.
		boolean fieldIsPrimitive = fieldType instanceof JCPrimitiveTypeTree;
		boolean fieldIsPrimitiveArray = fieldType instanceof JCArrayTypeTree && ((JCArrayTypeTree) fieldType).elemtype instanceof JCPrimitiveTypeTree;
		boolean fieldIsObjectArray = !fieldIsPrimitiveArray && fieldType instanceof JCArrayTypeTree;
		@SuppressWarnings("unused")
		boolean fieldIsObject = !fieldIsPrimitive && !fieldIsPrimitiveArray && !fieldIsObjectArray;
		
		if (fieldIsPrimitiveArray || fieldIsObjectArray) {
			JCExpression tsMethod = chainDots(typeNode, "java", "util", "Arrays", fieldIsObjectArray ? "deepToString" : "toString");
			expr = maker.Apply(List.<JCExpression>nil(), tsMethod, List.<JCExpression>of(fieldAccessor));
		} else expr = fieldAccessor;
		
		if (first) {
			current = maker.Binary(CTC_PLUS, current, expr);
			first = false;
			continue;
		}
		
		if (includeFieldNames) {
			current = maker.Binary(CTC_PLUS, current, maker.Literal(infix + fieldNode.getName() + "="));
		} else {
			current = maker.Binary(CTC_PLUS, current, maker.Literal(infix));
		}
		
		current = maker.Binary(CTC_PLUS, current, expr);
	}
	
	if (!first) current = maker.Binary(CTC_PLUS, current, maker.Literal(suffix));
	
	JCStatement returnStatement = maker.Return(current);
	
	JCBlock body = maker.Block(0, List.of(returnStatement));
	
	return recursiveSetGeneratedBy(maker.MethodDef(mods, typeNode.toName("toString"), returnType,
			List.<JCTypeParameter>nil(), List.<JCVariableDecl>nil(), List.<JCExpression>nil(), body, null), source, typeNode.getContext());
}
 
Example 19
Source File: HandleGetter.java    From EasyMPermission with MIT License 4 votes vote down vote up
public JCMethodInvocation callGet(JavacNode source, JCExpression receiver) {
	JavacTreeMaker maker = source.getTreeMaker();
	return maker.Apply(NIL_EXPRESSION, maker.Select(receiver, source.toName("get")), NIL_EXPRESSION);
}
 
Example 20
Source File: HandleLog.java    From EasyMPermission with MIT License 4 votes vote down vote up
@Override public JCExpression createFactoryParameter(JavacNode typeNode, JCFieldAccess loggingType) {
	JavacTreeMaker maker = typeNode.getTreeMaker();
	JCExpression method = maker.Select(loggingType, typeNode.toName("getName"));
	return maker.Apply(List.<JCExpression>nil(), method, List.<JCExpression>nil());
}