-
Hi, I am new in this, and I want to create a new recipe. In this case, I need a recipe for creating a class with a method implemented. I have done the code in java but i do not know how i can create the .jar for using it in my project. This is my code: /*
* Copyright 2023 the original author or authors.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openrewrite.Java;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.EqualsAndHashCode;
import lombok.Value;
import org.jspecify.annotations.Nullable;
import org.openrewrite.*;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.JavaParser;
import org.openrewrite.java.tree.J;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.Collections.emptyList;
@Value
@EqualsAndHashCode(callSuper = false)
public class CreateFullJavaClass extends ScanningRecipe<AtomicBoolean> {
@JsonIgnore
private static final String NEW_CLASS_TEMPLATE = "package %s;\n\n%sclass %s {\n%s\n}";
@Option(displayName = "Source root",
description = "The source root of the new class file.",
example = "src/main/java")
String sourceRoot;
@Option(displayName = "Package name",
description = "The package of the new class.",
example = "org.openrewrite.example")
String packageName;
@Option(displayName = "Modifier",
description = "The class modifier.",
valid = {"public", "private", "protected", "package-private"},
example = "public")
String modifier;
@Option(displayName = "Class name",
description = "File path of new file.",
example = "ExampleClass")
String className;
@Option(displayName = "Method name",
description = "Name of the method to be added.",
example = "exampleMethod")
String methodName;
@Option(displayName = "Method body",
description = "Body of the method to be added.",
example = "System.out.println(\"Hello, World!\");")
String methodBody;
@Option(displayName = "Overwrite existing file",
description = "If there is an existing file, should it be overwritten.",
required = false)
@Nullable
Boolean overwriteExisting;
@Option(displayName = "Relative directory path",
description = "Directory path of new class.",
required = false,
example = "foo/bar")
@Nullable
String relativePath;
@Override
public String getDisplayName() {
return "Create Java class with method";
}
@Override
public String getDescription() {
return "Create a new Java class with a method.";
}
@Override
public AtomicBoolean getInitialValue(ExecutionContext ctx) {
return new AtomicBoolean(true);
}
@Override
public TreeVisitor<?, ExecutionContext> getScanner(AtomicBoolean shouldCreate) {
return new CreateFileVisitor(getSourcePath(), shouldCreate);
}
@Override
public Collection<SourceFile> generate(AtomicBoolean shouldCreate, ExecutionContext ctx) {
if (shouldCreate.get()) {
return createFullClass().collect(Collectors.toList());
}
return emptyList();
}
@Override
public TreeVisitor<?, ExecutionContext> getVisitor(AtomicBoolean created) {
Path path = getSourcePath();
return new JavaIsoVisitor<ExecutionContext>() {
@Override
public J.CompilationUnit visitCompilationUnit(J.CompilationUnit cu, ExecutionContext ctx) {
if ((created.get() || Boolean.TRUE.equals(overwriteExisting)) && path.equals(cu.getSourcePath())) {
Optional<SourceFile> sourceFile = createFullClass().findFirst();
if (sourceFile.isPresent() && sourceFile.get() instanceof J.CompilationUnit) {
J.CompilationUnit newCu = (J.CompilationUnit) sourceFile.get();
return cu.withClasses(newCu.getClasses()).withSourcePath(path);
}
}
return cu;
}
};
}
private Stream<SourceFile> createFullClass() {
String packageModifier = "package-private".equals(modifier) ? "" : modifier + " ";
String method = String.format("public void %s() {\n%s\n}", methodName, methodBody);
return JavaParser.fromJavaVersion().build()
.parse(String.format(CreateFullJavaClass.NEW_CLASS_TEMPLATE, packageName, packageModifier, className, method))
.map(brandNewFile -> brandNewFile.withSourcePath(getSourcePath()));
}
@SuppressWarnings("java:S1075")
private Path getSourcePath() {
String path = relativePath;
if (path == null) {
path = "";
}
if (!path.isEmpty() && !path.endsWith("/")) {
path = path + "/";
}
return Paths.get(String.format(
"%s%s/%s/%s.java",
path,
sourceRoot,
packageName.replace('.', '/'),
className));
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 18 replies
-
hi! You'll likely want to fork the rewrite-recipe-starter project, copy your recipe there, potentially remove the example recipes in there, and then package and release that starter as your would any other library. From there you should then be able to use that recipe module, as described here: https://docs.moderne.io/user-documentation/workshops/recipe-authoring/#exercise-2-create-and-test-your-own-recipe-module |
Beta Was this translation helpful? Give feedback.
-
The recipe is a .jar file that I include as a dependency of another project. file .yml type: specs.openrewrite.org/v1beta/recipe
name: com.myrecipe.CreateFullJavaClass
displayName: Crea clase Java completa con método
recipeList:
- com.myrecipe.CreateFullJavaClass:
sourceRoot: src/main/java
packageName: org.example
modifier: public
className: ExampleClass
methodName: SaludoMethod
methodBody: System.out.println("Hello, World!"); pom.xml <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>Pruebaopen</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.yourorg</groupId>
<artifactId>rewrite-recipe-starter</artifactId>
<version>1.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.openrewrite</groupId>
<artifactId>rewrite-java</artifactId>
<version>8.45.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.openrewrite.maven</groupId>
<artifactId>rewrite-maven-plugin</artifactId>
<version>6.1.1</version>
<configuration>
<exportDatatables>true</exportDatatables>
<activeRecipes>
<recipe>com.myrecipe.CreateFullJavaClass</recipe>
<configLocation>${project.basedir}/src/main/resources/Createclassmethod.yml</configLocation>
</activeRecipes>
</configuration>
</plugin>
</plugins>
</build>
</project> |
Beta Was this translation helpful? Give feedback.
hi! You'll likely want to fork the rewrite-recipe-starter project, copy your recipe there, potentially remove the example recipes in there, and then package and release that starter as your would any other library. From there you should then be able to use that recipe module, as described here: https://docs.moderne.io/user-documentation/workshops/recipe-authoring/#exercise-2-create-and-test-your-own-recipe-module