ClassLoader.getSystemResources(String name) cannot find file in Maven managed project - java

I'm doing a project managed with Maven. The purpose of the project is to access a .csv file and read specific columns from it. I have just started, but run into trouble with the ClassLoader.getSystemResources(String name) method which cannot find the resource specified with the name argument. I put the .csv file in a the Maven project's resources directory.
I think the problem is caused by using Maven to manage the project because I tested the ClassLoader.getSystemResources(String name) method in a test program with a working result. I've also tried using other methods to obtain the path of the `.csv' file in my project, but got the same failing result.
Please help me find out what has gone wrong and how to resolve the problem.
Thank you for your help!
The Error message:
[WARNING]
java.lang.NullPointerException: Cannot invoke "java.net.URL.toURI()" because the return value of "java.lang.ClassLoader.getSystemResource(String)" is null
at com.wordbankbuilder.NamedColumnBean.getNamedColumnBean (WordbankBuilder.java:80)
at com.wordbankbuilder.WordbankBuilder.main (WordbankBuilder.java:23)
at org.codehaus.mojo.exec.ExecJavaMojo$1.run (ExecJavaMojo.java:254)
at java.lang.Thread.run (Thread.java:832)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.879 s
[INFO] Finished at: 2021-10-04T11:52:03+11:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:3.0.0:java (default-cli) on project WordbankBuilder: An exception occured while executing the Java class. Cannot invoke "java.net.URL.toURI()" because the return value of "java.lang.ClassLoader.getSystemResource(String)" is null -> [Help 1]
[ERROR]
The code and POM file are as follows:
The main class - WordbankBuilder:
package com.wordbankbuilder;
import java.io.Reader;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import com.opencsv.*;
import com.opencsv.bean.*;
public class WordbankBuilder {
public static void main(String[] args) {
NamedColumnBean ncb = new NamedColumnBean();
ncb.getNamedColumnBean();
System.out.println("SUCCESS!");
}
}
class CsvBean {}
class NamedColumnBean extends CsvBean {
#CsvBindByName(column = "word")
private String name;
#CsvBindByName(column = "phonetic")
private String phonetic;
#CsvBindByName(column = "translation")
private String translation;
public String getName () {
return this.name;
}
public String getPhonetic () {
return this.phonetic;
}
public String getTranslation () {
return this.translation;
}
public void setName(String name) {
this.name = name;
}
public void setPhonetic(String phonetic) {
this.phonetic = phonetic;
}
public void setTranslation(String translation) {
this.translation = translation;
}
public List<CsvBean> namedColumnBeanBuilder (Path path, Class clazz) {
// read and parse ecdict.mini.csv
CsvTransfer csvTransfer = new CsvTransfer();
ColumnPositionMappingStrategy ms = new ColumnPositionMappingStrategy();
ms.setType(clazz);
try (Reader reader = Files.newBufferedReader(path)) {
CsvToBean cb = new CsvToBeanBuilder(reader).withType(clazz).withMappingStrategy(ms).build();
csvTransfer.setCsvList(cb.parse());
} catch (IOException ioEx) {
ioEx.printStackTrace();
}
return csvTransfer.getCsvList();
}
public List<CsvBean> getNamedColumnBean () {
Path path = null;
try {
URI resURI = ClassLoader.getSystemResource("/src/main/resources/ecdict.mini.csv").toURI();
path = Paths.get(resURI);
path = Paths.get("ecdict.mini.csv");
} catch (URISyntaxException uriEx) {
uriEx.printStackTrace();
System.exit(1);
}
return namedColumnBeanBuilder(path, NamedColumnBean.class);
}
}
The CsvTransfer class - CsvTransfer.java
package com.wordbankbuilder;
import java.util.ArrayList;
import java.util.List;
public class CsvTransfer {
private List<String[]> csvStringList;
private List<CsvBean> csvList;
public CsvTransfer() {}
public List<String[]> getCsvStringList() {
if (csvStringList != null) return csvStringList;
return new ArrayList<String[]>();
}
public void addLine(String[] line) {
if (this.csvList == null) this.csvStringList = new ArrayList<>();
this.csvStringList.add(line);
}
public void setCsvStringList(List<String[]> csvStringList) {
this.csvStringList = csvStringList;
}
public void setCsvList(List<CsvBean> csvList) {
this.csvList = csvList;
}
public List<CsvBean> getCsvList() {
if (csvList != null) return csvList;
return new ArrayList<CsvBean>();
}
}
The POM.xml file:
<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>com.wordbankbuilder</groupId>
<artifactId>WordbankBuilder</artifactId>
<version>1.0.0</version>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<mainClass>com.wordbankbuilder.WordbankBuilder</mainClass>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources/</directory>
</resource>
</resources>
</build>
<dependencies>
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>4.1</version>
</dependency>
</dependencies>
</project>

Related

annotation to generate source code for same file in java

I am trying to define a simple annotation and use it during compile time only to add a simple method to the consumed source file/class file but nothing is getting added.
I am using maven and java 1.8.
Below is the code and not sure where it is going wrong
Annotation class definition:
package com.test.annotations;
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.SOURCE)
public #interface AddMethod {
}
Processor for the annotation
package com.test.annotations;
import com.google.auto.service.AutoService;
import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.util.ElementFilter;
import javax.tools.JavaFileObject;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import java.util.stream.Collectors;
#SupportedAnnotationTypes("com.test.annotations.AddMethod")
#SupportedSourceVersion(SourceVersion.RELEASE_8)
#AutoService(Processor.class)
public class AddMethodProcessor extends AbstractProcessor {
#Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
// get all the classes annotated with ToJsonString class
Collection<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(AddMethod.class);
annotatedElements.forEach(e -> {
// some code to get the class name
try {
writeBuilderFile(qualifiedClassName);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
});
return true;
}
private void writeBuilderFile(String qualifiedClassName) throws IOException {
String packageName = null;
int lastDot = qualifiedClassName.lastIndexOf('.');
if (lastDot > 0) {
packageName = qualifiedClassName.substring(0, lastDot);
}
String simpleClassName = qualifiedClassName.substring(lastDot + 1);
JavaFileObject generatedSourceFile = processingEnv.getFiler()
.createSourceFile(qualifiedClassName);
try (PrintWriter out = new PrintWriter(generatedSourceFile.openWriter())) {
if (packageName != null) {
out.print("package ");
out.print(packageName);
out.println(";");
out.println();
}
out.print("public class ");
out.print(simpleClassName);
out.println(" {");
out.println();
out.print(" public ");
out.print("String");
out.println(" testMethod() {");
out.println(" return \"this is a test method\" ");
out.println(" }");
out.println();
out.println("}");
}
}
}
After this, I am running mvn install to install the jar in my .m2 repository so that the consumer can use it.
consumer project:
pom.xml
<dependencies>
<dependency>
<groupId>com.test</groupId>
<artifactId>add-method</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
<forceJavacCompilerUse>true</forceJavacCompilerUse>
<generatedSourcesDirectory>${project.build.directory}
/generated-sources/</generatedSourcesDirectory>
<annotationProcessors>
<annotationProcessor>
com.test.annotations.AddMethodProcessor
</annotationProcessor>
</annotationProcessors>
</configuration>
</plugin>
</plugins>
</build>
</project>
Test class using the annotation
package org.example;
import com.test.annotations.AddMethod;
#AddMethod
public class Test {
private String x;
}
On running build in intellij, I could not see the source file or class file having the auto generated method.

maven test fails with nullpointer but junit 5 ok

I'm having a strange problem with maven test with Junit 5.
I'd created the test suites with junit tools for each method, every test starts like this.
private Class2Test createTestSubject() {
return new Class2Test();
}
public void test1() throws Exception {
Class2Test testSubject;
String result;
// default test
testSubject = createTestSubject();
result = testSubject.getData();
//testing, assert
}
The line
result = testSubject.getData();
returns a NullPointerException
When I execute the same test via eclipse finish ok. The surefire plugin are defined
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.7.0</version>
</dependency>
</dependencies>
<configuration>
<systemPropertyVariables>
<entorno>${project.basedir}\resources\maqueta.properties</entorno>
<hibernate>${project.basedir}\resources\hibernate.cfg.xml</hibernate>
</systemPropertyVariables>
<parallel>classes</parallel>
<threadCount>10</threadCount>
</configuration>
</plugin>
I'd tried to change the declaration of the object to dogde the nullpointer but it fails.
Class2Test() is the default constructor, doesn't requiere parameters or read files.
package test.com.my.myself;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import javax.annotation.Generated;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.tools.configuration.base.MethodRef;
import com.my.myself.Class2Test;
import com.google.gson.Gson;
import junitparams.JUnitParamsRunner;
#Generated(value = "org.junit-tools-1.1.0")
#RunWith(JUnitParamsRunner.class)
public class Tester1{
private Class2Test createTestSubject() {
return new Class2Test();
}
#DisplayName("TEST1")
#MethodRef(name = "test1", signature = "()QString;")
#Test
public void test1() throws Exception {
Class2Test testSubject;
String result;
// default test
testSubject = createTestSubject();
result = testSubject.test1();
}
}
and the class to test
public class Class2Test{
private Connection conn = new Connector();
private static final Logger logger = Logger.getLogger(Class2Test.class);
public String test1() {
PrepareStatement pstm = conn.prepareStatement("select 1 from dual");
ResultSet rs = pstm.executeQuery();
...
return 1;
}
}
There was a problem with pom.xml the resources folder was wrong setted. :(

I doing an assigment which require me to create a telegram bot bot

package org.example;
import org.telegram.telegrambots.meta.TelegramBotsApi;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.updatesreceivers.DefaultBotSession;
public class App {
public static void main( String[] args ) {
try {
TelegramBotsApi botsApi = new TelegramBotsApi(DefaultBotSession.class);
botsApi.registerBot(new s261251Bot());
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
}
package org.example;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
public class s261251Bot extends TelegramLongPollingBot {
#Override
public String getBotUsername() {
return "username";
}
#Override
public String getBotToken() {
return "..............";
}
#Override
public void onUpdateReceived(Update update) {
SendMessage message = new SendMessage();
message.setChatId(String.valueOf((update.getMessage().getChatId())));
message.setText("hello " + update.getMessage().getFrom().getFirstName() +" " + "\nInsert your matric number." + update.getMessage().getText());
try {
execute(message);
}catch (TelegramApiException e){
e.printStackTrace();
}
}
}
I put the right username and token but in here I replace it with other
I keep getting this error:
C:\Users\safwa\Documents\IntelliJ\assignment-2-safwan0908\src\main\java\my\assignment2\src\main\java\org\example\s261251Bot.java:9:8
java: cannot access java.util.concurrent.CompletableFuture class
file for java.util.concurrent.CompletableFuture not found
I had the same problem.
Make sure you use the correct or the same java version in your project and frameworks.
For more details read this article
In my case, I updated my maven version, using these properties (as described in the article):
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
or
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>LATEST</version>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
</plugins>
</build>

Eclipse cannot find main class of maven project

Before you flag this as a duplicate, please note that I have read several other similar questions, but none of them fixed the issue.
I have an Eclipse project using maven. It uses Java 15, with Javafx 13.
When I try to run the app, it has the error message:
Error: Could not find or load main class app.cleancode.Start
I have tried:
refreshing the project,
rebuilding from the maven project,
and even deleting all of the eclipse files and reimporting the project.
None of them made any difference.
I can run any other project in Eclipse, but this one is just not working.
I am doing this on Windows 10 home.
My pom file:
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>app.cleancode</groupId>
<artifactId>javafx-app</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>15</java.version>
<javafx.version>13</javafx.version>
</properties>
<dependencies>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-media</artifactId>
<version>${javafx.version}</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>${javafx.version}</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-swing</artifactId>
<version>${javafx.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<release>${java.version}</release>
<source>${java.version}</source>
<target>${java.version}</target>
<compilerArgs>--enable-preview</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.openjfx</groupId>
<artifactId>javafx-maven-plugin</artifactId>
<version>0.0.3</version>
<configuration>
<mainClass>app.cleancode.Start</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
app.cleancode.Start:
package app.cleancode;
import app.cleancode.game.GameListener;
import app.cleancode.game.GameLoop;
import app.cleancode.game.GameObject;
import app.cleancode.game.PhysicalLaw;
import app.cleancode.game.physics.Gravity;
import app.cleancode.game.physics.Movement;
import javafx.application.Application;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.input.KeyCombination;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class Start extends Application {
private static GameListener[] gameListeners = new GameListener[] {
};
#SuppressWarnings("unchecked")
private static GameObject<Node> [] gameObjects = new GameObject[] {
};
private static PhysicalLaw[] laws = new PhysicalLaw[] {
new Movement(),
new Gravity()
};
public static void main(String[] args) {
launch(args);
}
private Pane nodes = new Pane();
private Pane gamePane = new Pane();
#Override
public void start(Stage primaryStage) throws Exception {
Scene scene = new Scene(gamePane);
scene.getStylesheets().add("/app/cleancode/app.css");
nodes.getChildren().add(new Text("Loading"));
primaryStage.setTitle("Game");
primaryStage.setFullScreen(true);
primaryStage.setFullScreenExitKeyCombination(KeyCombination.NO_MATCH);
primaryStage.setScene(new Scene(nodes));
primaryStage.show();
for(GameListener listener : gameListeners) {
for(String gameObjectName : listener.getGameObjects()) {
for(GameObject<Node> gameObject : gameObjects) {
gameObject.addNode = this::addNode;
if(gameObject.getName().equalsIgnoreCase(gameObjectName)) {
try {
var gameObjectField = listener.getClass().getDeclaredField(gameObjectName);
gameObjectField.set(listener, gameObject);
break;
}catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
listener.startup();
}
scene.setFill(Color.BLACK);
primaryStage.setScene(scene);
primaryStage.setFullScreen(true);
GameLoop loop = new GameLoop(this::tick);
loop.start();
}
public void tick() {
for(GameListener gameListener : gameListeners) {
gameListener.update();
}
for(PhysicalLaw law : laws) {
for(GameObject<Node> gameObject : gameObjects) {
law.handle(gameObject);
}
}
}
public void addNode(Node node) {
gamePane.getChildren().add(node);
}
}
** module-info.java **:
module app.cleancode.javafx-app {
exports app.cleancode.axis;
exports app.cleancode.animation;
exports app.cleancode;
exports app.cleancode.sound;
exports app.cleancode.game.physics;
exports app.cleancode.bounds;
exports app.cleancode.game.snake;
exports app.cleancode.map;
exports app.cleancode.sprite;
exports app.cleancode.game;
requires java.desktop;
requires javafx.base;
requires javafx.graphics;
requires javafx.media;
requires javafx.swing;
}
Another piece of information I just found out is that if i create a new Start.java with just a main method, it works fine. Not sure why.
To answer my own question, the easiest solution is to create a new main class that calls the main of the original start.
First, rename Start.java to Starter.java (or whatever you want to call it)
finally, create a new Start.java in the place of the old one:
Start.java:
package app.cleancode;
public class Start {
public static void main(String[] args) {
Starter.main(args);
}
}
Then you can just run the new Start.java.

Can't get Active Objects to work in Jira

I am currently doing an internship that involves creating Jira plugins to solve some problems the users at the company experience with Jira. For the first extension I need to create a new section on the view issue page where users can put input and edit the input. In order to do this I've created a web-panel which contains a input. But no matter what I try (And I've been trying different things for the last 3 weeks) I can't get active objects to work.
Currently the moment the plugin tries to load in jira it shows the error: "Error rendering 'tig.jira.extension.tigPasswordExtension:issue-page-input'. Please contact your JIRA administrators." and when I try to test the REST API call in the restbrowser it shows the error:
""message": "AOP configuration seems to be invalid: tried calling method [public abstract net.java.ao.RawEntity[] com.atlassian.activeobjects.external.ActiveObjects.find(java.lang.Class,net.java.ao.Query)] on target [com.atlassian.activeobjects.osgi.TenantAwareActiveObjects#12bfb51b]; nested exception is java.lang.IllegalArgumentException: object is not an instance of declaring class",
_ "status-code": 500,"_
Is there anyone here that can replicate my problem and pinpoint what I am screwing up?
My current files are as follows:
Atlassian-plugin.xml
<atlassian-plugin key="${atlassian.plugin.key}" name="${project.name}" plugins-version="2">
<plugin-info>
<description>${project.description}</description>
<version>${project.version}</version>
<vendor name="${project.organization.name}" url="${project.organization.url}"/>
<param name="plugin-icon">images/pluginIcon.png</param>
<param name="plugin-logo">images/pluginLogo.png</param>
</plugin-info>
<!-- add our i18n resource -->
<resource type="i18n" name="i18n" location="tigPasswordExtension"/>
<!-- add our web resources -->
<web-resource key="tigPasswordExtension-resources" name="tigPasswordExtension Web Resources">
<dependency>com.atlassian.auiplugin:ajs</dependency>
<resource type="download" name="tigPasswordExtension.css" location="/css/tigPasswordExtension.css"/>
<resource type="download" name="tigPasswordExtension.js" location="/js/tigPasswordExtension.js"/>
<resource type="download" name="images/" location="/images"/>
<context>tigPasswordExtension.resource</context>
</web-resource>
<web-panel name="IssuePageInput" i18n-name-key="issue-page-input.name" key="issue-page-input" location="atl.jira.view.issue.right.context" weight="1">
<description key="issue-page-input.description">Passwords en SSH</description>
<context-provider class="tig.jira.extension.tigPasswordExtension.PasswordContextProvider"/>
<component-import key="appProps" interface="com.atlassian.sal.api.ApplicationProperties"/>
<resource name="view" type="velocity" location="/vm/password-input.vm"/>
<label key="issue-page-input.title"/>
</web-panel>
<!-- Active Objects module -->
<ao key="password-ao">
<description>The configuration of the Active Objects service</description>
<entity>tig.jira.extension.tigPasswordExtension.ao.PasswordModel</entity>
</ao>
<rest name="Password Resource" i18n-name-key="password-resource.name" key="password-resource" path="/passwordresource" version="1.0">
<description key="password-resource.description">The Password Resource Plugin</description>
</rest>
</atlassian-plugin>
tigPasswordExtension.js
AJS.toInit(function($) {
AJS.$('#searchButton2').click(function (){
var test = "lol";
AJS.$.ajax({
url:"jira/rest/passwordresource/1.0/password",
type: "post",
dataType: 'json',
async: false,
data: ({issueKey : document.getElementById("issueKeyInput").value, content: document.getElementById("passwordInput").value}),
success: function(data)
{
test = data;
console.log(test);
}
})
});
});
PasswordDto
package tig.jira.extension.tigPasswordExtension.dto;
public class PasswordDto {
private String issueKey;
private String content;
public PasswordDto(){}
public String getIssueKey(){return this.issueKey;}
public void setIssueKey(String issueKey){this.issueKey = issueKey;}
public String getContent(){return this.content;}
public void setContent(String content){this.content = content;}
}
PasswordModel
package tig.jira.extension.tigPasswordExtension.ao;
import net.java.ao.Entity;
import net.java.ao.Preload;
#Preload
public interface PasswordModel extends Entity {
String getIssue();
void setIssue(String issue);
String getContent();
void setContent(String content);
}
PasswordDao
package tig.jira.extension.tigPasswordExtension.ao;
import com.atlassian.activeobjects.external.ActiveObjects;
import com.atlassian.plugin.spring.scanner.annotation.imports.ComponentImport;
import com.google.common.collect.ImmutableMap.Builder;
import net.java.ao.Query;
import javax.inject.Inject;
import javax.inject.Named;
import java.util.Map;
#Named
public class PasswordDao {
private final ActiveObjects activeObjects;
#Inject
public PasswordDao(#ComponentImport ActiveObjects activeObjects){this.activeObjects = activeObjects;}
public PasswordModel getByIssueKey(String issueKey){
Query query = this.buildIssueQuery(issueKey);
PasswordModel[] passwordModels = this.activeObjects.find(PasswordModel.class, query);
return passwordModels.length > 0 ? passwordModels[0] : null;
}
public void update(String issueKey, String content){
PasswordModel passwordModel = this.getByIssueKey(issueKey);
if (passwordModel == null){
Map<String, Object> params = (new Builder()).put("ISSUE_KEY", issueKey).put("CONTENT", content).build();
this.activeObjects.create(PasswordModel.class, params);
} else {
passwordModel.setContent(content);
passwordModel.save();
}
}
private Query buildIssueQuery(String issueKey){
return Query.select().where("ISSUE_KEY = ?", issueKey);
}
}
PasswordResource
package tig.jira.extension.tigPasswordExtension.rest;
import tig.jira.extension.tigPasswordExtension.service.PasswordService;
import javax.ws.rs.*;
#Path("/password")
public class PasswordResource{
private final PasswordService passwordService;
public PasswordResource(PasswordService passwordService){this.passwordService = passwordService;}
#POST
public void update(#QueryParam("issue") String issueKey, #QueryParam("content") String content) {
this.passwordService.update(issueKey, content);
}
}
PasswordService
package tig.jira.extension.tigPasswordExtension.service;
import tig.jira.extension.tigPasswordExtension.ao.PasswordDao;
import tig.jira.extension.tigPasswordExtension.ao.PasswordModel;
import tig.jira.extension.tigPasswordExtension.dto.PasswordDto;
import javax.inject.Inject;
import javax.inject.Named;
#Named
public class PasswordService {
private final PasswordDao passwordDao;
#Inject
public PasswordService(PasswordDao passwordDao){
this.passwordDao = passwordDao;
}
public void update(String issueKey, String content){
this.passwordDao.update(issueKey, content);
}
public PasswordDto getByIssueKey(String issueKey){
PasswordModel passwordModel = this.passwordDao.getByIssueKey(issueKey);
if (passwordModel == null){
return null;
} else {
PasswordDto dto = new PasswordDto();
dto.setIssueKey(issueKey);
dto.setContent(passwordModel.getContent());
return dto;
}
}
}
PasswordContextProvider
package tig.jira.extension.tigPasswordExtension;
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.plugin.webfragment.contextproviders.AbstractJiraContextProvider;
import com.atlassian.jira.plugin.webfragment.model.JiraHelper;
import com.atlassian.jira.user.ApplicationUser;
import tig.jira.extension.tigPasswordExtension.dto.PasswordDto;
import tig.jira.extension.tigPasswordExtension.service.PasswordService;
import java.util.HashMap;
import java.util.Map;
public class PasswordContextProvider extends AbstractJiraContextProvider {
Map contextMap = new HashMap();
private String issueKey;
private final PasswordService passwordService;
public PasswordContextProvider(PasswordService passwordRepository){
this.passwordService = passwordRepository;
}
public Map getContextMap(ApplicationUser user, JiraHelper jiraHelper) {
Issue currentIssue = (Issue) jiraHelper.getContextParams().get("issue");
issueKey = currentIssue.getKey();
//passwordService.update(issueKey, "klote");
PasswordDto passwordDto = this.passwordService.getByIssueKey(issueKey);
if (passwordDto != null){
contextMap.put("AO", "1");
contextMap.put("content", "Staat nog niks in gek");
if (passwordDto.getContent() != null) {
contextMap.put("content", passwordDto.getContent());
}
}
contextMap.put("issueKey", issueKey);
return contextMap;
}
}
The only problem I could find after a quick look is in the class PasswordDao. If I replace the variable query by it's value then it will look like below.
activeObjects.find(PasswordModel.class, Query.select().where("ISSUE_KEY = ?", issueKey));
Whereas your entity class PasswordModel.java does not have any such method String xxxIssueKey(). Refer Offical document for column name of table created using ActiveObjects.
Best practice documentation can be a good start for you when working with Active Objects.
Update the method as given below (change ISSUE_KEY to ISSUE).
private Query buildIssueQuery(String issueKey){
return Query.select().where(" ISSUE = ? ", issueKey);
}
I hope this helps you.

Categories

Resources