I have a custom annotation in Java, that uses ByteBuddy to generate a new class based on the annotated one. Since ByteBuddy is already compiling the class, I am outputting the bytecode directly, rather than source.
My gradle build compiles fine, with references to the generated class.
The problem is that in IntelliJ, the editor does not recognize the classes that are output directly. It does recognize classes generated as source.
My Annotation sub-project
gradle.build
plugins {
id 'java-library'
id 'maven-publish'
}
group 'org.example'
version 'unspecified'
repositories {
mavenCentral()
}
dependencies {
implementation 'net.bytebuddy:byte-buddy:1.12.23'
}
MyAnnotation.java
package org.example.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
#Target(ElementType.TYPE)
#Retention(RetentionPolicy.CLASS)
public #interface MyAnnotation {}
MyAnnotationProcessor.java
package org.example.annotation.processor;
import net.bytebuddy.ByteBuddy;
import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.TypeElement;
import java.io.IOException;
import java.util.Set;
#SupportedAnnotationTypes({"org.example.annotation.MyAnnotation"})
#SupportedSourceVersion(SourceVersion.RELEASE_11)
public class MyAnnotationProcessor extends AbstractProcessor {
Filer filer;
#Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
filer = processingEnv.getFiler();
}
#Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
annotations.forEach(a -> {
try {
// Generate a java source file
var className = a.getSimpleName()+"_source";
var fooFile = filer.createSourceFile(className);
var writer = fooFile.openWriter();
writer.write("package org.example.annotation; public class "+className+" {}");
writer.close();
// Generate a java class file
var otherClassName = a.getSimpleName()+"_bytecode";
var bb = new ByteBuddy();
var dtoClass = bb.subclass(Object.class)
.name(otherClassName)
.make();
var javaFileObject = filer.createClassFile(otherClassName);
var dtoOutStr = javaFileObject.openOutputStream();
dtoOutStr.write(dtoClass.getBytes());
dtoOutStr.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
});
return false;
}
}
Notice that I am outputting one class called MyAnnotation_source and one called MyAnnotation_bytecode
My sub-project that uses the annotation
gradle.build (NOTE that core is the name of the annotation sub-project)
plugins {
id 'java'
}
group 'org.example'
version 'unspecified'
repositories {
mavenCentral()
}
dependencies {
implementation project(':core')
annotationProcessor project(':core')
}
UserTest.java
import org.example.annotation.MyAnnotation;
import org.example.annotation.MyAnnotation_source;
import org.example.annotation.MyAnnotation_bytecode; //Cannot resolve symbol 'MyAnnotation_bytecode'
#MyAnnotation
public class UserTest {
public static void main(String[] args) {
MyAnnotation_source foo = new MyAnnotation_source();
MyAnnotation_bytecode other = new MyAnnotation_bytecode(); //Cannot resolve symbol 'MyAnnotation_bytecode'
}
}
The build directory ends up looking like this:
build/
├─ classes
│ └─ java
│ └─ main
│ ├─ MyAnnotation_bytecode.class <-- Generated
│ ├── UserTest.class
│ └── org
│ └─ example
│ └─ annotation
│ └─ MyAnnotation_source.class <-- Compiled
└─ generated
└─ sources
└─ annotationProcessor
└─ java
└─ main
└─ MyAnnotation_source.java <-- Generated
I have already tried various configurations of the annotation processor settings in IntelliJ, but I think the answer is somewhere else.
Related
I use mapstruct in my projects and it works fine for the straight forward way (All mapper in one package).
Now I have the requirement to move one mapper to another package, but this doesn't work well.
working package structure (1):
de.zinnchen
├── dto
│ └── Car.java
├── entity
│ └── CarEntity.java
└── mapper
└── a
├── CarMapper.java
└── DateMapper.java
NOT working package structure (2):
de.zinnchen
├── dto
│ └── Car.java
├── entity
│ └── CarEntity.java
└── mapper
├── a
│ └── CarMapper.java
└── b
└── DateMapper.java
my java files:
package de.zinnchen.dto;
import java.time.LocalDateTime;
public class Car {
private String manufacturer;
private String model;
private String color;
private LocalDateTime productionDate;
...
package de.zinnchen.entity;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDateTime;
public class CarEntity {
private String manufacturer;
private String model;
private String color;
private Instant productionDate;
...
package de.zinnchen.mapper.a;
import de.zinnchen.dto.Car;
import de.zinnchen.entity.CarEntity;
import de.zinnchen.mapper.b.DateMapper;
import org.mapstruct.Mapper;
#Mapper(
uses = DateMapper.class
)
public interface CarMapper {
Car asDto(CarEntity entity);
CarEntity asEntity(Car car);
}
package de.zinnchen.mapper.b;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
public class DateMapper {
LocalDateTime instantToLocalDateTime(Instant instant) {
return instant
.atZone(ZoneId.of("UTC"))
.toLocalDateTime();
}
Instant LocalDateTimeToInstant(LocalDateTime localDateTime) {
return localDateTime.toInstant(ZoneOffset.UTC);
}
}
Once I try to compile the variant with mappers in different packages I get the following error message:
Can't map property "Instant productionDate" to "LocalDateTime productionDate". Consider to declare/implement a mapping method: "LocalDateTime map(Instant value)".
Can you please help me for solving this problem?
Edit
Resulting CarMapperImpl.java of package structure 1:
package de.zinnchen.mapper.a;
import de.zinnchen.dto.Car;
import de.zinnchen.entity.CarEntity;
import javax.annotation.processing.Generated;
#Generated(
value = "org.mapstruct.ap.MappingProcessor",
date = "2021-01-06T09:36:43+0100",
comments = "version: 1.4.1.Final, compiler: javac, environment: Java 11.0.9.1 (AdoptOpenJDK)"
)
public class CarMapperImpl implements CarMapper {
private final DateMapper dateMapper = new DateMapper();
#Override
public Car asDto(CarEntity entity) {
if ( entity == null ) {
return null;
}
Car car = new Car();
car.setManufacturer( entity.getManufacturer() );
car.setModel( entity.getModel() );
car.setColor( entity.getColor() );
car.setProductionDate( dateMapper.instantToLocalDateTime( entity.getProductionDate() ) );
return car;
}
#Override
public CarEntity asEntity(Car car) {
if ( car == null ) {
return null;
}
CarEntity carEntity = new CarEntity();
carEntity.setManufacturer( car.getManufacturer() );
carEntity.setModel( car.getModel() );
carEntity.setColor( car.getColor() );
carEntity.setProductionDate( dateMapper.LocalDateTimeToInstant( car.getProductionDate() ) );
return carEntity;
}
}
The reason why it isn't working is due to the fact that the methods in the DateMapper are package protected and are not available from other packages.
So if you add public to the methods then it will work.
I want to expose an additional Rest endpoint along a Websocket endpoint.
The websocket endpoint is already implemented and works, but I have trouble hitting the Rest endpoint.
Any idea what I'm missing here?
I expect to run localhost:8080/hello with a text plain result of hello.
Btw, I'm using Quarkus if that matters.
Here is my project structure
│ │ ├── java
│ │ │ └── org
│ │ │ └── company
│ │ │ ├── chat
│ │ │ │ ├── boundary
│ │ │ │ ├── control
│ │ │ │ └── entity
│ │ │ ├── JAXRSConfiguration.java // Rest endpoint ???
│ │ │ └── websockets
│ │ │ └── ChatSocket.java // Websocket server endpoint (works)
│ │ └── resources
│ │ ├── application.properties
│ │ ├── application.properties.example
│ │ └── META-INF
│ │ └── resources
│ │ ├── index.html
JAXRSConfiguration.java
package org.company;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.MediaType;
#ApplicationPath("hello")
public class JAXRSConfiguration extends Application {
#GET
#Produces(MediaType.TEXT_PLAIN)
public String hello() {
return "hello";
}
}
ChatSocket.java
package org.company.websockets;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.time.LocalDateTime;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.company.chat.boundary.ChatResource;
import org.company.chat.entity.Chat;
import org.company.chat.entity.ChatGroup;
import org.company.chat.entity.ChatMessage;
import org.company.time.Time;
import org.jboss.logging.Logger;
#ServerEndpoint("/chat/websocket/{username}/{chatRoom}")
#ApplicationScoped
public class ChatSocket {
#Inject
Time time;
#Inject
ChatResource chatResource;
// Chatroom, user, session dictionary
final Dictionary<String, Map<String, Session>> chatRooms = new Hashtable<>();
#OnOpen
public void onOpen(final Session session, #PathParam("username") final String username, #PathParam("chatRoom") final String chatRoom) {
// ...
}
#OnClose
public void onClose(final Session session, #PathParam("username") final String username, #PathParam("chatRoom") final String chatRoom)
throws Exception {
// ...
}
#OnError
public void onError(final Session session, #PathParam("username") final String username, #PathParam("chatRoom") final String chatRoom,
final Throwable throwable) throws Exception {
// ...
}
#OnMessage
public void onMessage(String json, #PathParam("username") final String username, #PathParam("chatRoom") final String chatRoom)
throws Exception {
// ...
}
private void broadcast(final String event, final String chatRoom) {
// ...
}
The solution was simply to add another #Path annotation.
Here I changed JAXRSConfiguration.java as you can see in the following.
Works now, if I call the localhost:8080/api/hello endpoint.
#ApplicationPath("api") // Changed the basic route to 'api'
#Path("hello") // Added a new path
public class JAXRSConfiguration extends Application {
#GET
#Produces(MediaType.TEXT_PLAIN)
public String hello() {
return "hello";
}
}
Trying to move files from a sub-directory along with the structure to a parent directory. And am not able to accomplish this using Files.move(). To illustrate the issue please see the below directory structure.
$ tree
.
└── b
├── c
│ ├── cfile.gtxgt
│ └── d
│ ├── dfile.txt
│ └── e
└── x
└── y
└── z
├── 2.txt
└── p
├── file1.txt
└── q
├── file
├── file2.txt
└── r
└── 123.txt
I want to emulate the below move command via Java.
$ mv b/x/y/z/* b/c
b/x/y/z/2.txt -> b/c/2.txt
b/x/y/z/p -> b/c/p
And the output should be something similar to
$ tree
.
└── b
├── c
│ ├── 2.txt
│ ├── cfile.gtxgt
│ ├── d
│ │ ├── dfile.txt
│ │ └── e
│ └── p
│ ├── file1.txt
│ └── q
│ ├── file
│ ├── file2.txt
│ └── r
│ └── 123.txt
└── x
└── y
└── z
In this move all the files and directories under directory z have been moved to c.
I have tried to do this:
public static void main(String[] args) throws IOException{
String aPath = "/tmp/test/a/";
String relativePathTomove = "b/x/y/z/";
String relativePathToMoveTo = "b/c";
Files.move(Paths.get(aPath, relativePathTomove), Paths.get(aPath, relativePathToMoveTo), StandardCopyOption.REPLACE_EXISTING);
}
However this causes this exception to the thrown java.nio.file.DirectoryNotEmptyException: /tmp/test/a/b/c and if the the REPLACE_EXISTING option is taken out the code throws a java.nio.file.FileAlreadyExistsException: /tmp/test/a/b/c.
This question has an answer that uses a recursive function to solve this problem. But in my case it will involve further complexity as I need to even re-created the sub-dir structure in the new location.
I have not tried the option of using the commons-io utility method org.apache.commons.io.FileUtils#moveDirectoryToDirectory as this code seems to be first copying files and then deleting them from the original location. And In my case the files are huge and hence this is not a preferred option.
How can I achieve the the move functionality in java without resorting to copying. Is individual file move my only option?
TLDR: How can I emulate the mv functionality in java for moving sub dir with files and structure to parent directory.
I ended up doing this:
Create a FileVisitor Implementation like so:
package com.test.files;
import org.apache.log4j.Logger;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Objects;
import static java.nio.file.FileVisitResult.TERMINATE;
public class MoveFileVisitor implements FileVisitor<Path> {
private static final Logger LOGGER = Logger.getLogger(MoveFileVisitor.class);
private final Path target;
private final Path source;
public MoveFileVisitor(#NotNull Path source, #NotNull Path target) {
this.target = Objects.requireNonNull(target);
this.source = Objects.requireNonNull(source);
}
#Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
Path relativePath = source.relativize(dir);
Path finalPath = target.resolve(relativePath);
Files.createDirectories(finalPath);
return FileVisitResult.CONTINUE;
}
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Path relativePath = source.relativize(file);
Path finalLocation = target.resolve(relativePath);
Files.move(file, finalLocation);
return FileVisitResult.CONTINUE;
}
#Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
LOGGER.error("Failed to visit file during move" + file.toAbsolutePath(), exc);
return TERMINATE;
}
#Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
}
And then walking the path with this Visitor like so:
String source = "/temp/test/a/b/x/y/z";
String target = "/temp/test/a/b/c";
MoveFileVisitor visitor = new MoveFileVisitor(Paths.get(source), Paths.get(target));
Files.walkFileTree(Paths.get(source), visitor);
I have written a gradle plugin in Java, which I want to use in a multiproject gradle setup. The task which comes with the plugin is only executed once and I don't understand why.
The structure of the project looks like this:
Root project
|- settings.gradle
|- build.gradle
|- project1
| |- build.gradle
|- project2
| |- build.gradle
|- project3
| |- build.gradle
...
The root build.gradle looks like this
buildscript {
repositories {
jcenter()
maven { url "https://repo.spring.io/plugins-snapshot" }
maven { url "https://repo.spring.io/plugins-release" }
maven{
url = "https://my-personal-nexus.de/content/repositories/release/"
}
....
dependencies {
....
classpath "de.mystuff:myCustomPlugin:1.0.0"
}
}
}
subprojects {
apply plugin: "myCustomPlugin"
....
}
The plugin "myCustomPlugin" provides a Task called myTask. Since the Plugin is applied in die subprojects part of the build.gradle, I assumed that when I call:
./gradlew myTask
the task would be executed for project1, project2, project3.
In reality the task only executes in project1 and not in project2 or project3. If I call
./gradlew -p "project2" myTask
the task is executed in project 2 just fine.
Any hints on why the task is not executed for every subproject?
When I call
./gradlew tasks --all
The result shows the task for every subproject.
Thanks!
EDIT:
The Plugin code of the Task:
public class MyGeneratorTask extends DefaultTask {
#TaskAction
public void genMyCode() throws Exception {
MyGeneratorExtension extension = getProject().getExtensions().getByType(MyGeneratorExtension.class);
MyGeneratorConfig.setPath(extension.getPath());
MyGeneratorConfig.setGendir(extension.getGendir());
MyCodeGeneratorApplication.generateMyClasses();
}
}
And the plugin definition itself:
public class MyPlugin implements Plugin<Project> {
static final String GEN_TASK_CONFIG = "myConfig";
static final String GEN_TASK_NAME = "myTask";
#Override
public void apply(Project target) {
target.getExtensions().add(GEN_TASK_CONFIG, MyGeneratorExtension.class);
target.getTasks().create(GEN_TASK_NAME, MyGeneratorTask.class);
}
}
And the code of the extension:
import lombok.Data;
import lombok.EqualsAndHashCode;
#Data
#EqualsAndHashCode(callSuper = false)
public class MyGeneratorExtension {
private String path;
private String gendir;
}
Solution:
It Seems that gradle does not like it when you call a static Method in a Task.
After I switched to class-initialization it worked.
Thanks #M.Ricciuti
I'm trying to build a regression suite using Intellij and TestNG, not sure why this is happening. When I try to run it I get these:
My file structure is just:
AutoSuite/
|-.idea/
|- out/
|- src/
|-- com/
|--- site/
|------ data/
|--------- urlData.java
|------ homepage/
|--------- Homepage.java
|- tst/
|-- com/
|--- site/
|------ homepage/
|--------- HomepageTest.java
|- AutoSuite.iml
|- External Libraries/
The code inside the java files is as follows:
homepage.java
package com.site.homepage;
public class Homepage {
public String siteTitle() {
return "site.com/";
}
}
urlData.java
package com.site.data;
public class urlData {
private static String DEV_WEB = "site.com/";
public String returnPROD(){ return DEV_WEB; }
}
HomePageTest.java
package com.site.homepage;
import com.site.homepage.Homepage;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.*;
public class HomepageTest {
private WebDriver driver;
Homepage homepage;
String titleTag;
#AfterClass
public void afterClass() {
driver.quit();
}
#BeforeMethod
public void setUp() {
driver = new FirefoxDriver();
}
#AfterMethod
public void tearDown() {
driver.close();
}
#BeforeTest
public void initStringsAndObjects() {
homepage = new Homepage();
titleTag = "Site title tag";
}
#Test (priority = 1, groups={"Layout"})
public void testSiteTitle() {
driver.get(homepage.siteTitle());
Assert.assertTrue(driver.getTitle().equals(titleTag));
}
#AfterTest
public void cleanup() {
titleTag = null;
homepage = null;
}
}
I thought maybe I needed a testng.xml file at under AutoSuite/ but even after adding it under Edit Configuration > Suite > testng.xml I get the error. So I removed it.
Then I made sure I had testng in the dependencies it by selecting the file under Project Preferences > Modules > Dependencies and it's there.
What am I missing?
You are using selenium, which has its own dependencies.
To fix your missing dependencies you will either have to use a build system like Maven or Gradle that will handle these things for you, or use a selenium version with all dependencies included (called standalone):
https://www.seleniumhq.org/download/