Can maven tell eclipse to ignore warnings in generated code? - java

I have a collection of Java projects. It is a series of APIs. I am generating much of the server code from the swagger definition using swagger codegen. I'm using spring-boot with the delegate pattern, so my generated code all goes to src/gen/java/main and I can write my implementation code in src/main/java. The generated code is not version controlled, but re-generated as needed by the maven swagger codegen plugin. All this works nicely :)
However, when I first import the projects into Eclipse (using "import existing maven project" on the parent project to import them all) I get a bunch of "unused function" type warnings from the generated code. (I add the src/gen/java/main folder as a source folder using the build-helper-maven-plugin.) If I select the src/gen/java/main folder in each project, right-click, choose properties and say Ignore optional compile problems then this goes away (I also mark it as a derived resource)
Question: is there some way to mark this folder in the pom so that when I (or a colleague) imports the project into Eclipse, these settings are already set on that folder? Alternatively, some way to tell eclipse to always treat folders with the name (relative to project route) in that fashion?
Additional Info
I was asked for the pom file in a comment. I have done a fairly minimal example:
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example.api</groupId>
<artifactId>com.example.api</artifactId>
<packaging>jar</packaging>
<name>Example</name>
<version>1.0-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<springfox-version>2.7.0</springfox-version>
<swagger.codegen.version>2.4.0-SNAPSHOT</swagger.codegen.version>
<jetty-version>9.2.15.v20160210</jetty-version>
<slf4j-version>1.7.21</slf4j-version>
<junit-version>4.12</junit-version>
<servlet-api-version>2.5</servlet-api-version>
<springfox-version>2.7.0</springfox-version>
<jackson-version>2.8.9</jackson-version>
<jackson-threetenbp-version>2.6.4</jackson-threetenbp-version>
<spring-version>4.3.9.RELEASE</spring-version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>io.swagger</groupId>
<artifactId>swagger-codegen-maven-plugin</artifactId>
<versionRange>${swagger.codegen.version}</versionRange>
<goals>
<goal>generate</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore></ignore>
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
<mainClass>${start-class}</mainClass>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.example.api.Swagger2SpringBoot</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>assemble-all</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- Needed to create swagger bits in asynch manner -->
<plugin>
<groupId>io.swagger</groupId>
<artifactId>swagger-codegen-maven-plugin</artifactId>
<version>${swagger.codegen.version}</version>
<executions>
<execution>
<id>foo</id>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<inputSpec>${project.basedir}/src/spec/foo.yaml</inputSpec>
<modelPackage>com.example.api.models</modelPackage>
<apiPackage>com.example.api</apiPackage>
<language>spring</language>
<invokerPackage>com.example.api</invokerPackage>
<basePackage>com.example.api</basePackage>
<withXml>true</withXml>
<configOptions>
<artifactId>bookings</artifactId>
<artifactDescription>Bookings API</artifactDescription>
<title>Bookings API</title>
<artifactUrl>https://api.example.com/foo</artifactUrl>
<groupId>com.example.api</groupId>
<artifactVersion>1.0</artifactVersion>
<configPackage>com.example.api.config</configPackage>
<serializableModel>true</serializableModel>
<dateLibrary>java8</dateLibrary>
<java8>true</java8>
<async>true</async>
<library>spring-boot</library>
<delegatePattern>true</delegatePattern>
<useBeanValidation>true</useBeanValidation>
<useOptional>true</useOptional>
<hideGenerationTimestamp>true</hideGenerationTimestamp>
</configOptions>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>${jetty-version}</version>
<configuration>
<webAppConfig>
<contextPath>/v2</contextPath>
</webAppConfig>
<webAppSourceDirectory>target/${project.artifactId}-${project.version}</webAppSourceDirectory>
<stopPort>8079</stopPort>
<stopKey>stopit</stopKey>
<httpConnector>
<port>8002</port>
<idleTimeout>60000</idleTimeout>
</httpConnector>
</configuration>
<executions>
<execution>
<id>start-jetty</id>
<phase>pre-integration-test</phase>
<goals>
<goal>start</goal>
</goals>
<configuration>
<scanIntervalSeconds>0</scanIntervalSeconds>
<daemon>true</daemon>
</configuration>
</execution>
<execution>
<id>stop-jetty</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!--SpringFox dependencies -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${springfox-version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${springfox-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
<!-- Bean Validation API support -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.0</version>
</dependency>
</dependencies>
</project>
This uses a minimal foo.yaml:
swagger: '2.0'
info:
title: Foo API
description: Test case
version: 1.0
host: api.example.com
basePath: /
schemes:
- https
consumes:
- application/json
produces:
- application/json
tags:
- name: foo
parameters:
message:
name: message
in: body
description: Foo
schema:
$ref: '#/definitions/Message'
required: true
definitions:
Message:
type: object
description: Foo
properties:
heading:
type: string
description: heading
body:
type: string
description: body
paths:
/foo:
post:
summary: foo
operationId: postFoo
tags:
- foo
parameters:
- $ref: '#/parameters/message'
responses:
'202':
description: Messages will be sent
default:
description: An unexpected error occurred
If I just mvn clean compile then import this the it's fine. However, if I add any implementation code that uses the generated code then it isn't.
For example, I added a package com.example.api.implementation to src/main/java containing a file FooApi.java which was:
package com.example.api.implementation;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import com.example.api.FooApiDelegate;
import com.example.api.models.Message;
import com.fasterxml.jackson.databind.ObjectMapper;
#Component
public class FooApi implements FooApiDelegate {
private final ObjectMapper objectMapper;
private final HttpServletRequest request;
public Optional<ObjectMapper> getObjectMapper() {
return Optional.ofNullable(objectMapper);
}
public Optional<HttpServletRequest> getRequest() {
return Optional.ofNullable(request);
}
#org.springframework.beans.factory.annotation.Autowired
public FooApi(ObjectMapper objectMapper, HttpServletRequest request) {
this.objectMapper = objectMapper;
this.request = request;
}
#Override
public CompletableFuture<ResponseEntity<Void>> postFoo( Message message) {
return new CompletableFuture<ResponseEntity<Void>>();
}
}
If I now import, I get errors FooApiDelegate cannot be resolved to a type and Message cannot be resolved to a type (and for the corresponding imports) from my non.generated file.

There are at least two issues. The first thing is that you explicitly suppressed the execution of the code generation by using org.eclipse.m2e.. this will suppress any kind of generation you might have. Furthermore you are using a 2.4.0-SNAPSHOT where you should use 3.0.0-rc0 instead. Unfortunately the 3.0.0-rc0 has failured so you should stick with 2.3.1 which is a release instead of SNAPSHOT's.
Apart from that the plugin is missing also things are not correctly handled...If you cleanly import the project in Eclipse you will get a dialog about Setup Maven Plugin Connectors. Furthermore the plugin does not correctly handle the update in Eclipse context which can be done...
If you import the project and manually add the source folders from target/generated-sources this will work but unfortunately not allways...

Related

Errors with deeplearning4j and Maven

Here is the tutorial I'm following.
The pom.xml file is the default one that comes with the dl4j examples folder so there shouldn't be issues there but it still has errors.
Here's the code:
package org.deeplearning4j.self;
import org.deeplearning4j.datasets.iterator.impl.EmnistDataSetIterator;
import org.deeplearning4j.nn.conf.MultiLayerConfiguration;
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.nn.conf.layers.DenseLayer;
import org.deeplearning4j.nn.conf.layers.OutputLayer;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.deeplearning4j.nn.weights.WeightInit;
import org.nd4j.linalg.activations.Activation;
import org.nd4j.linalg.learning.config.Adam;
import org.nd4j.linalg.lossfunctions.LossFunctions;
import java.io.IOException;
public class first {
int batchSize = 128; // how many examples to simultaneously train in the network
EmnistDataSetIterator.Set emnistSet = EmnistDataSetIterator.Set.BALANCED;
EmnistDataSetIterator emnistTrain;
{ try { emnistTrain = new EmnistDataSetIterator(emnistSet, batchSize, true); } catch (IOException e) { e.printStackTrace(); } }
EmnistDataSetIterator emnistTest;
{ try { emnistTest = new EmnistDataSetIterator(emnistSet, batchSize, false); } catch (IOException e) { e.printStackTrace(); } }
int outputNum = EmnistDataSetIterator.numLabels(emnistSet);// total output classes
int rngSeed = 123; // integer for reproducability of a random number generator
int numRows = 28; // number of "pixel rows" in an mnist digit
int numColumns = 28;
MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder()
.seed(rngSeed)
.updater(new Adam())
.l2(1e-4)
.list()
.layer(new DenseLayer.Builder()
.nIn(numRows * numColumns) // Number of input datapoints.
.nOut(1000) // Number of output datapoints.
.activation(Activation.RELU) // Activation function.
.weightInit(WeightInit.XAVIER) // Weight initialization.
.build())
.layer(new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD)
.nIn(1000)
.nOut(outputNum)
.activation(Activation.SOFTMAX)
.weightInit(WeightInit.XAVIER)
.build())
.build();
MultiLayerNetwork network = new MultiLayerNetwork(conf);
network.init();
// pass a training listener that reports score every 10 iterations
int eachIterations = 10;
network.addListeners(new ScoreIterationListener(eachIterations));
}
I'm using IntelliJ.
The errors I'm getting in the class is:
Both methods called on "network" aren't recognized, both "init()" and "addListeners()" have "Cannot resolve symbol" on them. It also says on "network" that the "Field network is never used".
Additionally the int "eachIterations" has an "Unknown class" error inside of the addListeners() method.
Here's the pom.xml file:
<?xml version="1.0" encoding="UTF-8"?> <!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~ Copyright (c) 2020 Konduit K.K. ~ Copyright (c) 2015-2019 Skymind, Inc. ~ ~ This program and the accompanying materials are made available under the ~ terms of the Apache License, Version 2.0 which is available at ~ https://www.apache.org/licenses/LICENSE-2.0. ~ ~ 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. ~ ~ SPDX-License-Identifier: Apache-2.0 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-->
<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.deeplearning4j</groupId>
<artifactId>dl4j-examples</artifactId>
<version>1.0.0-beta7</version>
<name>Introduction to DL4J</name>
<description>A set of examples introducing the DL4J framework</description>
<properties>
<dl4j-master.version>1.0.0-beta7</dl4j-master.version>
<!-- Change the nd4j.backend property to nd4j-cuda-X-platform to use CUDA GPUs -->
<!-- <nd4j.backend>nd4j-cuda-10.2-platform</nd4j.backend> -->
<nd4j.backend>nd4j-native</nd4j.backend>
<java.version>1.8</java.version>
<maven-compiler-plugin.version>3.6.1</maven-compiler-plugin.version>
<maven.minimum.version>3.3.1</maven.minimum.version>
<exec-maven-plugin.version>1.4.0</exec-maven-plugin.version>
<maven-shade-plugin.version>2.4.3</maven-shade-plugin.version>
<jcommon.version>1.0.23</jcommon.version>
<jfreechart.version>1.0.13</jfreechart.version>
<logback.version>1.1.7</logback.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.29</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-common</artifactId>
<version>4.1.48.Final</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.nd4j</groupId>
<artifactId>${nd4j.backend}</artifactId>
<version>${dl4j-master.version}</version>
</dependency>
<dependency>
<groupId>org.datavec</groupId>
<artifactId>datavec-api</artifactId>
<version>${dl4j-master.version}</version>
</dependency>
<dependency>
<groupId>org.datavec</groupId>
<artifactId>datavec-data-image</artifactId>
<version>${dl4j-master.version}</version>
</dependency>
<dependency>
<groupId>org.datavec</groupId>
<artifactId>datavec-local</artifactId>
<version>${dl4j-master.version}</version>
</dependency>
<dependency>
<groupId>org.deeplearning4j</groupId>
<artifactId>deeplearning4j-datasets</artifactId>
<version>${dl4j-master.version}</version>
</dependency>
<dependency>
<groupId>org.deeplearning4j</groupId>
<artifactId>deeplearning4j-core</artifactId>
<version>${dl4j-master.version}</version>
</dependency>
<dependency>
<groupId>org.deeplearning4j</groupId>
<artifactId>deeplearning4j-ui</artifactId>
<version>${dl4j-master.version}</version>
</dependency>
<dependency>
<groupId>org.deeplearning4j</groupId>
<artifactId>deeplearning4j-zoo</artifactId>
<version>${dl4j-master.version}</version>
</dependency>
<!-- ParallelWrapper & ParallelInference live here -->
<dependency>
<groupId>org.deeplearning4j</groupId>
<artifactId>deeplearning4j-parallel-wrapper</artifactId>
<version>${dl4j-master.version}</version>
</dependency>
<!-- Used in the feedforward/classification/MLP* and feedforward/regression/RegressionMathFunctions example -->
<dependency>
<groupId>jfree</groupId>
<artifactId>jfreechart</artifactId>
<version>${jfreechart.version}</version>
</dependency>
<dependency>
<groupId>org.jfree</groupId>
<artifactId>jcommon</artifactId>
<version>${jcommon.version}</version>
</dependency>
<!-- Used for downloading data in some of the examples -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.5</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>org.datavec</groupId>
<artifactId>datavec-data-codec</artifactId>
<version>${dl4j-master.version}</version>
</dependency>
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>javacv-platform</artifactId>
<version>1.5.2</version>
</dependency>
</dependencies>
<!-- Maven Enforcer: Ensures user has an up to date version of Maven before building -->
<build>
<plugins>
<plugin>
<artifactId>maven-enforcer-plugin</artifactId>
<version>1.0.1</version>
<executions>
<execution>
<id>enforce-default</id>
<goals>
<goal>enforce</goal>
</goals>
<configuration>
<rules>
<requireMavenVersion>
<version>[${maven.minimum.version},)</version>
<message>********** Minimum Maven Version is ${maven.minimum.version}. Please upgrade Maven before continuing (run "mvn --version" to check). **********</message>
</requireMavenVersion>
</rules>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>com.lewisd</groupId>
<artifactId>lint-maven-plugin</artifactId>
<version>0.0.11</version>
<configuration>
<failOnViolation>true</failOnViolation>
<onlyRunRules>
<rule>DuplicateDep</rule>
<rule>RedundantPluginVersion</rule>
<!-- Rules incompatible with Java 9
<rule>VersionProp</rule>
<rule>DotVersionProperty</rule> -->
</onlyRunRules>
</configuration>
<executions>
<execution>
<id>pom-lint</id>
<phase>validate</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${exec-maven-plugin.version}</version>
<executions>
<execution>
<goals>
<goal>exec</goal>
</goals>
</execution>
</executions>
<configuration>
<executable>java</executable>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${maven-shade-plugin.version}</version>
<configuration>
<shadedArtifactAttached>true</shadedArtifactAttached>
<shadedClassifierName>${shadedClassifier}</shadedClassifierName>
<createDependencyReducedPom>true</createDependencyReducedPom>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>org/datanucleus/**</exclude>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>reference.conf</resource>
</transformer>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>com.lewisd</groupId>
<artifactId>lint-maven-plugin</artifactId>
<versionRange>[0.0.11,)</versionRange>
<goals>
<goals><goal>check</goal></goals>
</goals>
</pluginExecutionFilter>
<action>
<ignore/>
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build> </project>
The error here is "${shadedClassifier}" shadedClassifier is red and the error is: "Cannot resolve symbol 'shadedClassifier'"
So I reinstalled maven with "mvn clean install" but it still doesn't work.
Maven has installed correctly with clean install but still I have these errors.
Please any help would be appriciated. I've been stuck on this for a week and I really want to learn machine learning.
I'm guessing maven isn't setup properly. I would ensure the IDE is up to date. Right clicking on the project in intellij and hitting reload is something I would consider doing. Same answer as here: Force Intellij IDEA to reread all maven dependencies

How to package React front end with Spring Boot and run the executable jar?

I have a Java Spring Boot back end app containing REST services. Just inside the main Spring Boot project folder I have a React app for the front end. I can run the Spring Boot app and successfully access all the end points. I can run the React app and it works too. But now I want to create an executable jar file and run that as a single application, not two.
I create an executable fat jar file like this:
mvn clean install
It creates a jar file. When I run it with
java -jar target/medaverter-0.0.1-SNAPSHOT.jar
the back end starts up ok but the front end does not pop up in a browser window like it does if I run it separately with
npm start
I've followed these tutorials to get where I'm at. Apparently I'm missing something.
https://medium.com/#mukundmadhav/build-and-deploy-react-app-with-spring-boot-and-mysql-6f888eb0c600#37fa
https://blogg.kantega.no/webapp-with-create-react-app-and-spring-boot/
Here is the pom.xml file. The plugins section does the magic of merging in the React app:
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>net.tekknow</groupId>
<artifactId>medaverter</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>medaverter</name>
<description>Demo project for Spring Security</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20190722</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>com.github.eirslett</groupId>
<artifactId>frontend-maven-plugin</artifactId>
<version>1.6</version>
<configuration>
<workingDirectory>medaverter-front</workingDirectory>
<installDirectory>target</installDirectory>
</configuration>
<executions>
<execution>
<id>install node and npm</id>
<goals>
<goal>install-node-and-npm</goal>
</goals>
<configuration>
<nodeVersion>v8.9.4</nodeVersion>
<npmVersion>5.6.0</npmVersion>
</configuration>
</execution>
<execution>
<id>npm install</id>
<goals>
<goal>npm</goal>
</goals>
<configuration>
<arguments>install</arguments>
</configuration>
</execution>
<execution>
<id>npm run build</id>
<goals>
<goal>npm</goal>
</goals>
<configuration>
<arguments>run build</arguments>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<phase>generate-resources</phase>
<configuration>
<target>
<copy todir="${project.build.directory}/classes/public">
<fileset dir="${project.basedir}/medaverter-front/build"/>
</copy>
</target>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.-->
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>
org.apache.maven.plugins
</groupId>
<artifactId>
maven-antrun-plugin
</artifactId>
<versionRange>
[1.8,)
</versionRange>
<goals>
<goal>run</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore></ignore>
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
I have verified that the same files that are in the react folder, called medaverter-front, get copied over to the target/classes/public folder.
I have the following proxy set in my package.json file:
"proxy": {
"/api": {
"target": "http://localhost:8080",
"ws": true
}
},
If I enter into a browser:
http://localhost:8080/api/test/all
I see in the browser:
"Public Content"
as I should if I were accessing the back end directly, but the terminal shows:
n.t.m.security.jwt.AuthEntryPointJwt : Unauthorized error: Full
authentication is required to access this resource
If I enter into the browser:
http://localhost:8080/home
it returns "There was an unexpected error (type=Unauthorized, status=401)."
Clearly Spring Security JWT is interfering somehow but I just can't figure it out. The home page does not require any authentication, yet something is acting like it does. Here is the backend tree:
I should also mention that during app startup, I see several of these Exceptions:
java.sql.SQLNonTransientConnectionException: Public Key Retrieval is
not allowed
But that doesn't stop it from running. I solved that problem by adding "&allowPublicKeyRetrieval=true" to the spring.datasource.url in application.properties file.
I finally found the problem. I added
.antMatchers("/home/**").permitAll()
.antMatchers("/**").permitAll()
to the configure method in the WebSecurityConfig.java file. It now looks like this:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests().antMatchers("/api/auth/**").permitAll()
.antMatchers("/api/test/**").permitAll()
.antMatchers("/home/**").permitAll()
.antMatchers("/**").permitAll()
.anyRequest().authenticated();
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
I was confused about this method (and still am). I had thought that if /api/test/all was handled, that was all I needed. Apparently not. Why did I think that? The React flow starts at App.js which contains
<Route exact path={["/", "/home"]} component={Home} />
home.component.js contains:
componentDidMount() {
UserService.getPublicContent().then(
response => {
this.setState({
content: response.data
});
},
user.service.js contains:
const API_URL = 'http://localhost:8080/api/test/';
class UserService {
getPublicContent() {
return axios.get(API_URL + 'all');
}
The SpringBoot TestController.java handles the backend calls:
#RequestMapping("/api/test")
public class TestController {
#GetMapping("/all")
public String allAccess() {
return "Public Content.";
}
Hence, / or /home ultimately calls http://localhost:8080/api/test/all which returns "Public Content".

maven plugin components injection null

I'm trying to write my own custom maven plugin which extends AbstractDependencyMojo.
Problem is that all the AbstractDependencyMojo components are null on code execution of my plugin.
#goal generate-dependencies
#phase install
#requiresProject false
See code below, overriding method execute()
public void execute() throws MojoExecutionException {
List<Dependency> dependencies = project.getModel().getDependencies();
for (Dependency dependency : dependencies) {
try {
Artifact a = factory.createArtifact(dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion(), dependency.getScope(), dependency.getType());
resolver.resolve(a, remoteRepos, getLocal());
}
catch (ArtifactResolutionException e) {
throw new MojoExecutionException("Implicit artifact resolution failed", e);
}
catch (ArtifactNotFoundException e) {
// Do nothing
}
}
While debugging, project is null, factory is null, well everything is .. null.
Obviously the components injection is not working at all for some reasons, and I can't figure out why ....
The plugin is being called this way:
<plugin>
<groupId>com.me.framework</groupId>
<artifactId>plugin-dependency-plugin</artifactId>
<version>0.0.1-SNAPSHOT</version>
<executions>
<execution>
<id>plugin-dependencies</id>
<phase>install</phase>
<goals>
<goal>generate-dependencies</goal>
</goals>
</execution>
</executions>
</plugin>
Do you have any idea ? Thanks
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.me.framework</groupId>
<artifactId>plugin-dependency-plugin</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>maven-plugin</packaging>
<dependencies>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-model-builder</artifactId>
<version>3.0.4</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-plugin-api</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-project</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.maven.plugin-tools</groupId>
<artifactId>maven-plugin-annotations</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<type>maven-plugin</type>
<version>2.5.1</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.-->
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-plugin-plugin</artifactId>
<versionRange>[3.2,)</versionRange>
<goals>
<goal>descriptor</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore></ignore>
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
Calling plugin pom
<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>
<artifactId>TheArtifact</artifactId>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<executions>
<execution>
<id>clean-generated-sources</id>
<phase>clean</phase>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<!-- Package project as artifact (for apidoc) -->
<execution>
<id>package-project</id>
<phase>prepare-package</phase>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.me.framework</groupId>
<artifactId>plugin-dependency-plugin</artifactId>
<version>0.0.1-SNAPSHOT</version>
<executions>
<execution>
<id>plugin-dependencies</id>
<phase>install</phase>
<goals>
<goal>generate-dependencies</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- Install project resources as artifact (for apidoc) -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
<execution>
<id>install-project</id>
<phase>prepare-package</phase>
</execution>
</executions>
</plugin>
</plugins>
</build>
First the documentation based markups are obsolete, it's better to use #Mojo annotation to provide all plugin details:
#Mojo(
name = "generate-dependencies",
defaultPhase = LifecyclePhase.INSTALL,
requiresDependencyResolution = ResolutionScope.COMPILE
// ...
)
Secondly, I would check the #requiresProject being set to false and try setting to true instead, could be the cause as well.

Generate .jasper with maven plugin

I´m looking to improve the performance of my application, which has two types of reports, and compile then at execution time like this :
final JasperDesign design = JRXmlLoader.load(input);
final JasperReport compiledReport = JasperCompileManager.compileReport(design);
This code executes every time when the user wants to see the report on the app.
To avoid this, I´m trying to execute the compilation of the .jrxml through maven jasperreports plugin, but it doesn't work, and there isn't an error on console.
The .jasper files don't appear in my directory "outputDirectory".
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jasperreports-maven-plugin</artifactId>
<executions>
<execution>
<phase>compile</phase>
<inherited>false</inherited>
<goals>
<goal>compile-reports</goal>
</goals>
</execution>
</executions>
<configuration>
<sourceDirectory>src/main/resources/reports</sourceDirectory>
<outputDirectory>src/main/resources/reports/jasper</outputDirectory>
<compiler>net.sf.jasperreports.engine.design.JRJdtCompiler</compiler>
</configuration>
</plugin>
I know this is old, but this happened to me when I defined the plugin in the <pluginManagement> section of the POM instead of in <plugins>.
This was the pom config I used
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jasperreports-maven-plugin</artifactId>
<version>1.0-beta-2</version>
<executions>
<execution>
<goals>
<goal>compile-reports</goal>
</goals>
<configuration>
<!-- jrxml file directory-->
<sourceDirectory>src\\main\\resources\\reports\\template</sourceDirectory>
<sourceFileExt>.jrxml</sourceFileExt>
<compiler>net.sf.jasperreports.engine.design.JRJavacCompiler</compiler>
<!-- Destination for jasper file -->
<outputDirectory>src\\main\\resources\\reports\\jasper</outputDirectory>
</configuration>
</execution>
</executions>
<dependencies>
<!-- These plugins are used to specify correct version for jrxml xml validation -->
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>4.5.0</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>

running standalone java executable in eclipse results in NoClassDefFound

Hi I've got a basic Jersey Client that I'm trying to run with a main() in my "main" java class. It compiles fine in Eclipse, but when I try to run it as java application, I get:
Caused by: java.lang.ClassNotFoundException: org.glassfish.jersey.client.JerseyClientBuilder
Can anyone tell me what I'm doing wrong? Here's my pom.xml:
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>ca.ubc.iamwsClient</groupId>
<artifactId>iamwsClient</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>iamwsClient</name>
<properties>
<jersey.version>2.5.1</jersey.version>
<target.dir>target</target.dir>
<project.build.directory>target</project.build.directory>
</properties>
<repositories>
<repository>
<id>JBoss Repository</id>
<url>https://repository.jboss.org/nexus/content/groups/public</url>
</repository>
</repositories>
<dependencies>
<!-- jackson dependencies for pojo/json support -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-processing</artifactId>
<version>${jersey.version}</version>
</dependency>
<!-- end jackson deps -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.9</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey.version}</version>
</dependency>
<!-- <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-client</artifactId>
<version>1.8</version> </dependency> -->
<dependency>
<groupId>org.glassfish.jersey.connectors</groupId>
<artifactId>jersey-apache-connector</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0</version>
</dependency>
<!-- <dependency> <groupId>javax.ws.rs</groupId> <artifactId>jsr311-api</artifactId>
<version>1.1</version> </dependency> -->
</dependencies>
<build>
<finalName>iamwsClient</finalName>
<outputDirectory>${basedir}/${target.dir}/classes</outputDirectory>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<inherited>true</inherited>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>prepare-package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/classes/lib</outputDirectory>
<overWriteReleases>false</overWriteReleases>
<overWriteSnapshots>false</overWriteSnapshots>
<overWriteIfNewer>true</overWriteIfNewer>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<!-- copy-dependency plugin -->
<pluginExecution>
<pluginExecutionFilter>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<versionRange>[0.0,)</versionRange>
<goals>
<goal>copy-dependencies</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore />
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
<!-- <plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>ca.ubc.iamwsClient.IamwsClient</mainClass>
</configuration>
</plugin> -->
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>ca.ubc.iamwsClient.IamwsClient</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<!--This plugin's configuration is used to store Eclipse m2e settings
only. It has no influence on the Maven build itself. -->
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>
org.apache.maven.plugins
</groupId>
<artifactId>
maven-dependency-plugin
</artifactId>
<versionRange>
[2.1,)
</versionRange>
<goals>
<goal>
copy-dependencies
</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore></ignore>
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
Client that I'm trying to run:
package ca.ubc.iamwsClient;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.jackson.JacksonFeature;
import ca.ubc.iamwsClient.json.CreateEmployeeBean;
import ca.ubc.iamwsClient.json.CreateEmployeeResponseBean;
/**
* Main class.
*
*/
public class IamwsClient {
private WebTarget getTarget(String targetUrl) throws Exception {
// create the client
Client c = ClientBuilder.newClient().register(JacksonFeature.class);
return c.target(targetUrl);
}
public CreateEmployeeResponseBean sendCreateEmployeeRequest(CreateEmployeeBean createBean, String url) {
CreateEmployeeResponseBean rb = null;
try {
WebTarget target = getTarget(url);
WebTarget wt = target.path("employeeAutoCreate");
WebTarget generateTarget = wt.path("generate");
rb = generateTarget.request(MediaType.APPLICATION_JSON_TYPE).post(Entity.entity(createBean,MediaType.APPLICATION_FORM_URLENCODED_TYPE),
CreateEmployeeResponseBean.class);
System.out.println("CreateEmployee: generate response: success=" + rb.getSuccess() + " message=" + rb.getMessage());
} catch (Throwable t) {
t.printStackTrace();
System.out.println("*********EXCEPTION THROWN: " + t.getMessage());
}
return rb;
}
public static void main(String[] args) {
String testUrl="http://localhost:9090/iamws";
CreateEmployeeBean bean = new CreateEmployeeBean();
// ... set some details on bean....
IamwsClient client = new IamwsClient();
CreateEmployeeResponseBean response = client.sendCreateEmployeeRequest(bean, testUrl);
if (response != null) {
System.out.println("*********server responded with flag: " + response.getSuccess() + " message: " + response.getMessage());
}
}
}
You need to make sure that the JAR dependency containing org.glassfish.jersey.client.JerseyClientBuilder class is available on your application's classpath during the run time. There's really no other explanation to NoClassDefFound error.
From what I can google on this class, it should be available in
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.0-m04</version>
</dependency>
In other words your com.sun.jersey dependency may be missing it.
EDIT
This is the actual answer which the OP added to the Question afterwards:
<jersey.version>2.5.1</jersey.version>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-processing</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0</version>
</dependency>
He already had org.glassfish.jersey.core and org.glassfish.jersey.connectors. He removed com.sun.jersey dependency.
I am going to try this myself shortly.

Categories

Resources