The application works fine when running Ng serve but when I run a maven install that runs my build, I get the following error.
'app-comparisons' is not a known element:
[INFO] 1. If 'app-comparisons' is an Angular component, then verify that it is part of this module.
[INFO] 2. If 'app-comparisons' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '#NgModule.schemas' of this component to suppress this message. ("
[INFO] </table>
[INFO] </div>
[INFO] [ERROR ->]<app-comparisons></app-comparisons>
[INFO] </div>
[INFO] <div id="goals-2" class="spot-tabs__content">
My selector is the same in my html as in my component.ts
Here's is the component, comparisons.component.ts
import { Component, OnInit } from '#angular/core';
import {ComparisonsService} from '../services/comparisons.service';
import {Region} from '../models/region';
import {VetCount} from '../models/vetcount';
#Component({
selector: 'app-comparisons',
templateUrl: './comparisons.component.html',
styleUrls: ['./comparisons.component.scss']
})
export class ComparisonsComponent implements OnInit {
regions: Region [];
vetcounts: VetCount [];
similarCount = 245;
constructor(private comparisonsService: ComparisonsService) { }
ngOnInit() {
this.getRegions();
this.getVetCounts();
}
getRegions(): void {
this.regions = this.comparisonsService.getRegions();
}
getVetCounts(): void {
this.vetcounts = this.comparisonsService.getVetCounts();
}
}
And finally here is my app.module.ts which has my component imported and declared. I am not sure what I am missing.
import { ComparisonsComponent } from './comparisons/comparisons.component';
#NgModule({
declarations: [
AppComponent,
LoginComponent,
HomeComponent,
VdcComponent,
PracticeComponent,
IconComponent,
ComparisonsComponent,
GoalsComponent,
ReportsComponent,
],
imports: [
BrowserModule,
FormsModule,
HttpClientModule,
routing,
ChartsModule,
],
providers: [
AuthGuardService,
AuthenticationService,
DataRequestService,
ComparisonsService,
ReportsService,
],
bootstrap: [AppComponent]
})
export class AppModule { }
Again the application works fine locally running ng serve but soon as it do a mvn install and it starts running Yarn and karma test it breaks with that error.
Related
I have initialized the socket channel in the Netty server but I have faced an issue with the handler, when I want to save the received data from the client to MySQL through JPA it can not be saved.
package com.servernetty.server;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class ServerApplication {
public static void main(String[] args) throws InterruptedException {
SpringApplication.run(ServerApplication.class, args);
}
}
#Service
public class ServerService {
private static final Logger logger = LoggerFactory.getLogger(ServerService.class);
private final TestRepo testRepo;
#Autowired
public ServerService(#Value("${hs.host}") String host, #Value("${hs.port}") int port, TestRepo testRepo) throws Exception {
this.testRepo = testRepo;
EventLoopGroup booGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap().
group(booGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.DEBUG))
.handler(new LoggingHandler(LogLevel.INFO))
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.localAddress("127.0.0.1", port).childHandler(new ChannelInitializer<SocketChannel>() {
#Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new NettyServerHandler());
}
});
logger.info("You are here in message server port no: " + port);
ChannelFuture channel = bootstrap.bind(port).sync().channel().closeFuture().sync();
} finally {
logger.info("finallllllll: " + port);
booGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
private final TestRepo testrepo;
public NettyServerHandler(TestRepo testrepo) {
this.testrepo = testrepo;
}
/**
* The message sent by the client will trigger
*/
#Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
TestModel trans = new TestModel();
trans.setId(11);
trans.setTestf("d11");
trans.setTransactionType("test");
log.info("before save");
try {
testrepo.save(trans);
} catch (Exception e) {
log.info("tttttttttttttt" + e.toString());
e.printStackTrace();
}
log.info("after save");
}
}
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
#Entity
#Table(name = "test", uniqueConstraints = #UniqueConstraint(columnNames = { "id" }, name = "TEST_UNIQUE_ID"))
public class TestModel {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", columnDefinition = "bigint unsigned")
private Integer id;
String testf;
#Column(name = "transaction_type")
String transactionType;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTestf() {
return testf;
}
public void setTestf(String testf) {
this.testf = testf;
}
public String getTransactionType() {
return transactionType;
}
public void setTransactionType(String transactionType) {
this.transactionType = transactionType;
}
}
import javax.transaction.Transactional;
import com.servernetty.server.model.TestModel;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TestRepo extends JpaRepository<TestModel, Integer> {
}
The folder structure
The exception that I receive
java.lang.NullPointerException
at com.servernetty.server.handlers.NettyServerHandler.channelRead(NettyServerHandler.java:105)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357)
at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919)
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:166)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:719)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:655)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:581)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:493)
at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:986)
at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.base/java.lang.Thread.run(Thread.java:829)
In logger I receive the "before save" but nothing after that, the application stacks.
Appreciate your help
I took your code and removed all (new) and all (Constructors). It is best to let Springboot Autowire everything for you:
Pay attention to how ServerService and NettyServerHandler are implemented.
package com.example.socketchannel;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SocketchannelApplication {
public static void main(String[] args) {
SpringApplication.run(SocketchannelApplication.class, args);
}
}
package com.example.socketchannel.controller;
import com.example.socketchannel.service.NettyServerHandler;
import com.example.socketchannel.service.ServerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class ServerController {
private static final Logger logger = LoggerFactory.getLogger(NettyServerHandler.class);
#Autowired
private ServerService serverService;
}
package com.example.socketchannel.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.*;
import io.netty.channel.socket.*;
import io.netty.channel.socket.nio.*;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
#Service
public class ServerService {
private static final Logger logger = LoggerFactory.getLogger(ServerService.class);
//You need to add hs.host to your properties
#Value("${hs.host:127:0.0.1}")
private String host;
//You need to add hs.port to your properties.
#Value("${hs.port:9090}")
private Integer port;
#Autowired
private NettyServerHandler nettyServerHandler;
#PostConstruct
private void init() {
EventLoopGroup booGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap().
group(booGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.DEBUG))
.handler(new LoggingHandler(LogLevel.INFO))
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.localAddress("127.0.0.1", port).childHandler(new ChannelInitializer<SocketChannel>() {
#Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(nettyServerHandler);
}
});
logger.info("You are here in message server port no {}", port);
ChannelFuture channel = bootstrap.bind(port).sync().channel().closeFuture().sync();
} catch (InterruptedException e) {
logger.error("Encounterd Exception", e);
} finally {
logger.info("finallllllll: {} ", port);
booGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
package com.example.socketchannel.service;
import com.example.socketchannel.model.TestModel;
import com.example.socketchannel.repository.TestRepo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
#Service
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
private static final Logger logger = LoggerFactory.getLogger(NettyServerHandler.class);
#Autowired
private TestRepo testRepo;
/**
* The message sent by the client will trigger
*/
#Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
TestModel trans = new TestModel();
trans.setId(11);
trans.setTestf("d11");
trans.setTransactionType("test");
logger.info("before save");
try {
testRepo.save(trans);
} catch (Exception e) {
logger.info("tttttttttttttt" + e.toString());
e.printStackTrace();
}
logger.info("after save");
}
}
package com.example.socketchannel.repository;
import com.example.socketchannel.model.TestModel;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TestRepo extends JpaRepository<TestModel, Integer> {
}
package com.example.socketchannel.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
#Entity
#Table(name = "test", uniqueConstraints = #UniqueConstraint(columnNames = { "id" }, name = "TEST_UNIQUE_ID"))
public class TestModel {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", columnDefinition = "bigint unsigned")
private Integer id;
String testf;
#Column(name = "transaction_type")
String transactionType;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTestf() {
return testf;
}
public void setTestf(String testf) {
this.testf = testf;
}
public String getTransactionType() {
return transactionType;
}
public void setTransactionType(String transactionType) {
this.transactionType = transactionType;
}
}
<?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.5.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>socketchannel</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>socketchannel</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</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-web</artifactId>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty</artifactId>
<version>1.41.0</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>5.0.0.Alpha2</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Validating that the springboot context runs, if you do mvn clean install
package com.example.socketchannel;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
#SpringBootTest
class SocketchannelApplicationTests {
#Test
void contextLoads() {
}
}
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building socketchannel 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
Downloading: https://arm.lmera.ericsson.se/artifactory/proj-cv-dev-local/io/grpc/grpc-core/maven-metadata.xml
Downloading: https://arm.lmera.ericsson.se/artifactory/proj-cv-dev/io/grpc/grpc-core/maven-metadata.xml
Downloaded: https://arm.lmera.ericsson.se/artifactory/proj-cv-dev/io/grpc/grpc-core/maven-metadata.xml (0 B at 0.0 KB/sec)
Downloading: https://arm.lmera.ericsson.se/artifactory/proj-cv-dev-local/io/grpc/grpc-api/maven-metadata.xml
Downloading: https://arm.lmera.ericsson.se/artifactory/proj-cv-dev/io/grpc/grpc-api/maven-metadata.xml
Downloaded: https://arm.lmera.ericsson.se/artifactory/proj-cv-dev/io/grpc/grpc-api/maven-metadata.xml (2 KB at 10.5 KB/sec)
[INFO]
[INFO] --- maven-resources-plugin:3.2.0:resources (default-resources) # socketchannel ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Using 'UTF-8' encoding to copy filtered properties files.
[INFO] Copying 1 resource
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) # socketchannel ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 6 source files to C:\UCA-Development\cvc-clones\services\socketchannel\target\classes
[INFO]
[INFO] --- maven-resources-plugin:3.2.0:testResources (default-testResources) # socketchannel ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Using 'UTF-8' encoding to copy filtered properties files.
[INFO] skip non existing resourceDirectory C:\UCA-Development\cvc-clones\services\socketchannel\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) # socketchannel ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to C:\UCA-Development\cvc-clones\services\socketchannel\target\test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.22.2:test (default-test) # socketchannel ---
[INFO]
[INFO] -------------------------------------------------------
[INFO] T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.example.socketchannel.SocketchannelApplicationTests
14:01:36.120 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
14:01:36.140 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
14:01:36.228 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.example.socketchannel.SocketchannelApplicationTests] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
14:01:36.251 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither #ContextConfiguration nor #ContextHierarchy found for test class [com.example.socketchannel.SocketchannelApplicationTests], using SpringBootContextLoader
14:01:36.260 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.example.socketchannel.SocketchannelApplicationTests]: class path resource [com/example/socketchannel/SocketchannelApplicationTests-context.xml] does not exist
14:01:36.261 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.example.socketchannel.SocketchannelApplicationTests]: class path resource [com/example/socketchannel/SocketchannelApplicationTestsContext.groovy] does not exist
14:01:36.261 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.example.socketchannel.SocketchannelApplicationTests]: no resource found for suffixes {-context.xml, Context.groovy}.
14:01:36.262 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [com.example.socketchannel.SocketchannelApplicationTests]: SocketchannelApplicationTests does not declare any static, non-private, non-final, nested classes annotated with #Configuration.
14:01:36.351 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [com.example.socketchannel.SocketchannelApplicationTests]
14:01:36.542 [main] DEBUG org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider - Identified candidate component class: file [C:\UCA-Development\cvc-clones\services\socketchannel\target\classes\com\example\socketchannel\SocketchannelApplication.class]
14:01:36.544 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Found #SpringBootConfiguration com.example.socketchannel.SocketchannelApplication for test class com.example.socketchannel.SocketchannelApplicationTests
14:01:36.788 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - #TestExecutionListeners is not present for class [com.example.socketchannel.SocketchannelApplicationTests]: using defaults.
14:01:36.788 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.event.ApplicationEventsTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener, org.springframework.test.context.event.EventPublishingTestExecutionListener]
14:01:36.823 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener#38f116f6, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener#5286c33a, org.springframework.test.context.event.ApplicationEventsTestExecutionListener#6e6d5d29, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener#5c530d1e, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener#6c25e6c4, org.springframework.test.context.support.DirtiesContextTestExecutionListener#85e6769, org.springframework.test.context.transaction.TransactionalTestExecutionListener#c5ee75e, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener#48a12036, org.springframework.test.context.event.EventPublishingTestExecutionListener#bf1ec20, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener#70efb718, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener#b70da4c, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener#4a11eb84, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener#4e858e0a, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener#435fb7b5, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener#4e70a728]
14:01:36.829 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext#3f07b12c testClass = SocketchannelApplicationTests, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration#4bd1f8dd testClass = SocketchannelApplicationTests, locations = '{}', classes = '{class com.example.socketchannel.SocketchannelApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer#4bbf6d0e, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer#2415fc55, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer#0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer#5e21e98f, org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer#7b993c65, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer#0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer#6692b6c6, org.springframework.boot.test.context.SpringBootTestArgs#1, org.springframework.boot.test.context.SpringBootTestWebEnvironment#192d43ce], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true]], class annotated with #DirtiesContext [false] with mode [null].
14:01:36.903 [main] DEBUG org.springframework.test.context.support.TestPropertySourceUtils - Adding inlined properties to environment: {spring.jmx.enabled=false, org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.5.6)
2021-10-31 14:01:38.142 INFO 6128 --- [ main] c.e.s.SocketchannelApplicationTests : Starting SocketchannelApplicationTests using Java 11.0.7 on SE-00018098 with PID 6128 (started by ezsusmu in C:\UCA-Development\cvc-clones\services\socketchannel)
2021-10-31 14:01:38.150 INFO 6128 --- [ main] c.e.s.SocketchannelApplicationTests : No active profile set, falling back to default profiles: default
2021-10-31 14:01:41.285 INFO 6128 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2021-10-31 14:01:41.439 INFO 6128 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 135 ms. Found 1 JPA repository interfaces.
2021-10-31 14:01:46.495 INFO 6128 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2021-10-31 14:01:47.188 INFO 6128 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2021-10-31 14:01:47.567 INFO 6128 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2021-10-31 14:01:47.852 INFO 6128 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.32.Final
2021-10-31 14:01:48.528 INFO 6128 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-10-31 14:01:49.292 INFO 6128 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2021-10-31 14:01:51.596 INFO 6128 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2021-10-31 14:01:51.617 INFO 6128 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2021-10-31 14:01:53.868 INFO 6128 --- [ main] c.e.socketchannel.service.ServerService : You are here in message server port no 9090
2021-10-31 14:01:57.647 INFO 6128 --- [ntLoopGroup-2-1] io.netty.handler.logging.LoggingHandler : [id: 0x23fb4903] REGISTERED
2021-10-31 14:01:57.651 INFO 6128 --- [ntLoopGroup-2-1] io.netty.handler.logging.LoggingHandler : [id: 0x23fb4903] BIND: 0.0.0.0/0.0.0.0:9090
2021-10-31 14:01:57.655 INFO 6128 --- [ntLoopGroup-2-1] io.netty.handler.logging.LoggingHandler : [id: 0x23fb4903, L:/0:0:0:0:0:0:0:0:9090] ACTIVE
try to use spring-boot-starter-jdbc, you will not face the issue.
I'm getting an error when I try to start Spring Boot using a Java bean mapper. I'm using Eclipse on Windows, Gradle to build. This is just a learning project I'm using to learn these components.
I'm listening to an ActiveMQ Artemis queue, using the incoming data to call a web service, then saving the order response in a MondoDB. All the components are working with the exception of the mapper converting the api response to a MongoDB entity.
Can anyone see what I'm doing wrong here? It's something with how I'm injecting the OrderMapper, but I'm not sure at this point. This is the Spring output:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.4.5)
2021-04-30 14:16:15.860 INFO 2320 --- [ main] c.b.R.RestClientPocApplication : Starting RestClientPocApplication using Java 11.0.9 on PSPLT-F7VYYY2 with PID 2320 (C:\Users\Bwarrick\Workspaces\Java\RESTClientPOC\bin\main started by Bwarrick in C:\Users\Bwarrick\Workspaces\Java\RESTClientPOC)
2021-04-30 14:16:15.863 INFO 2320 --- [ main] c.b.R.RestClientPocApplication : No active profile set, falling back to default profiles: default
2021-04-30 14:16:16.405 INFO 2320 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data MongoDB repositories in DEFAULT mode.
2021-04-30 14:16:16.567 INFO 2320 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 157 ms. Found 1 MongoDB repository interfaces.
2021-04-30 14:16:16.991 INFO 2320 --- [ main] org.mongodb.driver.cluster : Cluster created with settings {hosts=[192.168.56.102:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms'}
2021-04-30 14:16:17.064 INFO 2320 --- [68.56.102:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:1, serverValue:49}] to 192.168.56.102:27017
2021-04-30 14:16:17.064 INFO 2320 --- [68.56.102:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:2, serverValue:50}] to 192.168.56.102:27017
2021-04-30 14:16:17.065 INFO 2320 --- [68.56.102:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=192.168.56.102:27017, type=STANDALONE, state=CONNECTED, ok=true, minWireVersion=0, maxWireVersion=9, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=23420200}
2021-04-30 14:16:17.332 WARN 2320 --- [ main] onfigReactiveWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'artemisConsumer' defined in file [C:\Users\Bwarrick\Workspaces\Java\RESTClientPOC\bin\main\com\benwarrick\RESTClientPOC\jms\ArtemisConsumer.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.benwarrick.RESTClientPOC.service.OrderMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
2021-04-30 14:16:17.355 INFO 2320 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-04-30 14:16:17.370 ERROR 2320 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 1 of constructor in com.benwarrick.RESTClientPOC.jms.ArtemisConsumer required a bean of type 'com.benwarrick.RESTClientPOC.service.OrderMapper' that could not be found.
Action:
Consider defining a bean of type 'com.benwarrick.RESTClientPOC.service.OrderMapper' in your configuration.
Here is my component:
package com.benwarrick.RESTClientPOC.jms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
import com.benwarrick.RESTClientPOC.persistance.OrderEntity;
import com.benwarrick.RESTClientPOC.persistance.OrderRepository;
import com.benwarrick.RESTClientPOC.service.CoinBaseClientServiceImpl;
import com.benwarrick.RESTClientPOC.service.OrderMapper;
import com.benwarrick.RESTClientPOC.service.OrderResponse;
import com.benwarrick.RESTClientPOC.service.Price;
import com.benwarrick.RESTClientPOC.service.Prices;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Flux;
#Component
public class ArtemisConsumer {
private final OrderRepository orderRepository;
private final OrderMapper orderMapper;
#Autowired
public ArtemisConsumer(OrderRepository orderRepository, OrderMapper orderMapper) {
this.orderRepository = orderRepository;
this.orderMapper = orderMapper;
}
#JmsListener(destination = "test.topic::test.queue")
public void receive(String msg){
System.out.println("Got Message: " + msg);
CoinBaseClientServiceImpl client = new CoinBaseClientServiceImpl();
Mono<OrderResponse>orderCreate = client.createOrder("market", "USD", "BTC", "5");
orderCreate.log().subscribe(
successValue -> processResponse(successValue),
error -> System.err.println(error.getMessage()),
() -> System.out.println("mono consumed")
);
}
public void processResponse(OrderResponse orderResponse) {
System.out.println(orderResponse.getOrderID() + " " + orderResponse.getSellingCurrency() + orderResponse.getBuyingCurrency() + " Qty: "
+ orderResponse.getBoughtQty() + " Type: " + orderResponse.getOrderType()) ;
try {
OrderEntity entity = orderMapper.apiResponseToEntity(orderResponse);
OrderEntity newEntity = orderRepository.save(entity);
System.out.println("Test: " + newEntity.getBoughtQuantity());
}
catch(Exception e) {
System.out.println("Exception: " + e.toString()) ;
}
}
}
Here is my main process:
package com.benwarrick.RESTClientPOC;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.scheduling.annotation.EnableAsync;
#SpringBootApplication
#EnableAsync
public class RestClientPocApplication {
private static final Logger LOG = LoggerFactory.getLogger(RestClientPocApplication.class);
public static void main(String[] args) {
ConfigurableApplicationContext ctx =
SpringApplication.run(RestClientPocApplication.class, args);
String mongoDBHost = ctx.getEnvironment().getProperty("spring.data.mongodb.host");
String mongoDbPort = ctx.getEnvironment().getProperty("spring.data.mongodb.port");
LOG.info("Connected to MongoDb: " + mongoDBHost + ":" + mongoDbPort);
}
}
And here is the bean that isn't being found:
package com.benwarrick.RESTClientPOC.service;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import com.benwarrick.RESTClientPOC.persistance.OrderEntity;
#Mapper (componentModel = "spring")
public interface OrderMapper {
#Mappings({
#Mapping(target = "id", ignore = true),
#Mapping(target = "version", ignore = true),
#Mapping(target = "orderId", source="orderID"),
#Mapping(target = "orderID", source="boughtQty")
})
OrderEntity apiResponseToEntity(OrderResponse api);
}
And my build.graddle
plugins {
id 'org.springframework.boot' version '2.4.5'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'com.benwarrick'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
repositories {
mavenCentral()
}
ext {
mapstructVersion = "1.4.2.Final"
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-artemis'
implementation 'org.springframework.boot:spring-boot-starter-webflux'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'io.projectreactor:reactor-test'
implementation("org.mapstruct:mapstruct:${mapstructVersion}")
compileOnly "org.mapstruct:mapstruct-processor:${mapstructVersion}"
annotationProcessor "org.mapstruct:mapstruct-processor:${mapstructVersion}"
testAnnotationProcessor "org.mapstruct:mapstruct-processor:${mapstructVersion}"
implementation('org.springframework.boot:spring-boot-starter-data-mongodb')
testImplementation('de.flapdoodle.embed:de.flapdoodle.embed.mongo')
}
test {
useJUnitPlatform()
}
For MapStruct you need to correctly set up annotation processor so that IDE (Eclipse in your case) and build tool, Gradle that is play well together.
You can read on MapStruct page uder IDE support about it. Now I didn't manage to get it working without issues that way.
Plugin to the rescue! Now what I recommend you is that you use following Gradle plugin that can set up Eclipse IDE in a proper way for you. The plugin: https://plugins.gradle.org/plugin/com.diffplug.eclipse.apt
I see you know already how to include the plugin, just in case the code that you have to add to build.gradle:
plugins {
...
id 'com.diffplug.eclipse.apt' version "3.29.1"
}
And then run the command from your project that will set up Eclipse:
./gradlew eclipseJdtApt eclipseFactorypath eclipseJdt
From within Eclipse, you now have to run right-click the project and select Gradle / Refresh Gradle Project.
Afterwards, Project / Clean. With this clean build, the annotation-processor should be running.
I hope Eclipse Buildship will pick this up and make it easier to support his feature.
I am making a Web Application Server with Spring boot.
In the early days of development, I used the settings http.csrf().disable() and the web page worked well.
But errors have been occurring ONLY at host address page ever since the disable setting was erased. When I requested GET, it works totally fine, however, it doesn't work with POST, PUT, DELETE... When I test at my localhost, all requests works including those methods.
Already, I used csrf token header, hidden csrf inputs of forms, and beforeSend that set csrf header in ajax. I even changed the nginx setting (error_page 405 =200 $uri;), but it remains the same.
This is my environment.
jdk 11
spring 2.3.5
AWS EC2 - Amazon Linux 2 AMI
AWS RDS - PostgreSQL 13
AWS S3
Nginx 1.18.0
gradle 5.6.4
thymeleaf
Is there anyone who can help me, please?
My Github Repository Link
# aws server- nohup.out
[ec2-user#teamcoder-webservice ~]$ vim ~/app/step3/nohup.out
2020-12-01 23:24:18.953 INFO 3697 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: any request, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#3ad85136, org.springframework.security.web.context.SecurityContextPersistenceFilter#2bc426f0, org.springframework.security.web.header.HeaderWriterFilter#176f7f3b, org.springframework.security.web.csrf.CsrfFilter#7d3c09ec, org.springframework.security.web.authentication.logout.LogoutFilter#1f53481b, org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestRedirectFilter#7f93dd4e, org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter#5ad5be4a, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#33425811, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#4cb2918c, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#737d100a, org.springframework.security.web.session.SessionManagementFilter#58740366, org.springframework.security.web.access.ExceptionTranslationFilter#4af45442, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#671c4166]
2020-12-01 23:24:20.068 INFO 3697 --- [ main] o.s.b.a.w.s.WelcomePageHandlerMapping : Adding welcome page template: index
2020-12-01 23:24:20.550 INFO 3697 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8081 (http) with context path ''
2020-12-01 23:24:20.552 INFO 3697 --- [ main] DeferredRepositoryInitializationListener : Triggering deferred initialization of Spring Data repositories…
2020-12-01 23:24:21.474 INFO 3697 --- [ main] DeferredRepositoryInitializationListener : Spring Data repositories initialized!
2020-12-01 23:24:21.499 INFO 3697 --- [ main] s.a.ScheduledAnnotationBeanPostProcessor : No TaskScheduler/ScheduledExecutorService bean found for scheduled processing
2020-12-01 23:24:21.527 INFO 3697 --- [ main] c.j.team.teamcoder.TeamCoderApplication : Started TeamCoderApplication in 17.806 seconds (JVM running for 19.458)
2020-12-01 23:24:23.438 INFO 3697 --- [nio-8081-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-12-01 23:24:23.443 INFO 3697 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-12-01 23:24:23.460 INFO 3697 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 17 ms
2020-12-02 03:05:22.223 WARN 3697 --- [nio-8081-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported]
# /etc/nginx/nginx.conf
http {
...
server {
listen 80;
listen [::]:80;
server_name _;
root /usr/share/nginx/html;
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
include /etc/nginx/conf.d/service-url.inc;
location / {
limit_except GET POST PUT DELETE {
deny all;
}
proxy_pass $service_url;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
}
error_page 405 =200 $uri;
error_page 404 /404.html;
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
}
#after change upper configuration
[ec2-user#teamcoder-webservice nginx]$ sudo /usr/sbin/nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
Plus, the following code is java spring boot code.
<!--ajax non-used request in "user_info.html"-->
<form th:action="#{'/api/v1/user/pic/' + ${user.id}}" method="post" enctype="multipart/form-data" name="pictureForm">
<table>
<tr><td><label th:for="picture">Profile Image</label></td>
<td><input type="file" id="picture" name="picture" accept="image/png, image/jpeg" /></td></tr>
<tr><td><img th:src="#{${user.picture}}" id="picture_img" alt="put your image"></td>
<td><input type="button" name="Upload" value="Upload" onclick="submit_file_form(document.forms['pictureForm'].picture, 'pictureForm');" class="btn btn-info"/></td></tr>
</table>
<input type="hidden" name="pastPath" id="pastPath" th:value="${user.picture}"/>
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />
</form>
//ajax used request in "user_info.html" -> "userInfo.js"
...
const csrfToken = $('#_csrf').attr('content');
const csrfHeader = $('#_csrf_header').attr('content');
var user_info = {
init : function () {
var _this = this;
$('#btn-update').on('click', function () {
_this.update();
});
$('#btn-delete').on('click', function () {
_this.delete();
});
},
update : function () {
var data = {
name: $('#name').val(),
tags: commaToArray(convertTags($('#tags').val())),
email: $('#email').val(),
birth: $('#birth').val(),
education: $('#education').val().toUpperCase(),
location: $('#location').val()
};
var id = $('#id').val();
$.ajax({
type: 'PUT',
url: '/api/v1/user/'+id,
dataType: 'json',
contentType:'application/json; charset=utf-8',
data: JSON.stringify(data),
beforeSend: function (xhr){
xhr.setRequestHeader(csrfHeader, csrfToken);
}
}).done(function() {
alert('your information is modified');
window.location.href = '/';
}).fail(function (error) {
alert(JSON.stringify(error));
});
},
...
<!-- in html header -->
<meta id="_csrf" th:name="${_csrf.parameterName}" th:content="${_csrf.token}"/>
<meta id="_csrf_header" name="_csrf_header" th:content="${_csrf.headerName}"/>
#RequiredArgsConstructor
#RestController
public class UserApiController {
private final UserService userService;
private final RoleService roleService;
#PutMapping("/api/v1/user/{id}")
public Long update(#PathVariable String id,
#RequestBody UserUpdateRequestDto requestDto){
roleService.reloadRolesForAuthenticatedUser(Role.USER.getKey());
return userService.update(Long.valueOf(id), requestDto);
}
}
#RequiredArgsConstructor
#RestController
public class FileController {
private final UserService userService;]
private final S3Service s3Service;
#PostMapping("/api/v1/user/pic/{id}")
public String updateUserPic(#PathVariable String id,
#RequestParam("pastPath") String pastPath,
#RequestPart("picture") MultipartFile multipartFile) throws IOException {
String uploadDir = s3Service.upload(pastPath, multipartFile,"users/");
userService.updatePic(Long.valueOf(id), uploadDir);
return "You successfully uploaded " + uploadDir + "!";
}
}
//SecurityConfig.java
#Configuration
#RequiredArgsConstructor
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final CustomOAuth2UserService customOAuth2UserService;
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/css/**", "/js/**", "/assets/img/**", "/lib/**", "/user-photos/**", "/group-files/**");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.and()
.authorizeRequests()
.antMatchers("/", "/logoption","/user/denied", "/search/**", "/privacy/rule","/profile").permitAll()
.antMatchers("/api/v1/user/**", "/api/v1/**").hasRole("GUEST")
.antMatchers("/api/v1/group/**", "/group/**", "/api/v1/participate/**").hasRole("USER")
.anyRequest().authenticated()
.and()
.logout().logoutSuccessUrl("/")
.deleteCookies("JSESSIONID")
.invalidateHttpSession(true)
.and()
.exceptionHandling()
.accessDeniedPage("/user/denied")
.and()
.oauth2Login()
.loginPage("/logoption")
.defaultSuccessUrl("/")
.userInfoEndpoint()// after oauth2 login
.userService(customOAuth2UserService);
}
//for Spring Security
#Bean
public ServletListenerRegistrationBean<HttpSessionEventPublisher> httpSessionEventPublisher() {
return new ServletListenerRegistrationBean<>(new HttpSessionEventPublisher());
}
}
Try adding these to your SecurityConfig :
http.cors().and()....
And CORS config:
#Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*"); // TODO: lock down before deploying
config.addAllowedHeader("*");
config.addExposedHeader(HttpHeaders.AUTHORIZATION);
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
I am running sample spring boot application in spring tool suite tool.
After configuring the port I am unable to start application from browser. I am getting 404 Not found error.
Spring boot is running properly on tomcat.
application.properties
hello.greeting= nice to see you
server.port=9874
Could some one please help me to correct the problem.
package demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class HelloBootApplication {
public static void main(String[] args) {
SpringApplication.run(HelloBootApplication.class, args);
}
}
package demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class HelloController {
#Autowired
HelloProperties props;
#RequestMapping("/hello")
public String hello(#RequestParam String name) {
return props.getGreeting()+name;
}
}
package demo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
#Component
#ConfigurationProperties("hello")
public class HelloProperties {
private String greeting = "Welcome ";
public String getGreeting() {
return greeting;
}
public void setGreeting(String greeting) {
this.greeting = greeting;
}
}
2018-07-22 17:17:32.798 INFO 11824 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-07-22 17:17:32.952 INFO 11824 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-07-22 17:17:33.000 INFO 11824 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 9874 (http) with context path ''
2018-07-22 17:17:33.006 INFO 11824 --- [ main] demo.HelloBootApplication : Started HelloBootApplication in 2.083 seconds (JVM running for 2.862)
This is spring boot application, getting 404 Not Found on below link
http://localhost:9874/
Your url is wrong . You have to call the url with RequestParam name.
use this url http://localhost:9874/hello?name=test
I am trying to recreate the spring-boot angularjs example application from here.
When I run the application using ./mnvw spring-boot:run the following error shows:
[ERROR] ERROR in src/app/app.component.html(6,18): : Property 'id' does not exist on type '{}'.
[ERROR] src/app/app.component.html(7,23): : Property 'content' does not exist on type '{}'.
My source code is the same as the link provided above but for clarity, the typescript file:
import { Component } from '#angular/core';
import {HttpClient} from '#angular/common/http';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Demo';
data = {};
constructor(private http: HttpClient) {
http.get('resource').subscribe(data => this.data = data);
}
}
The html file:
<div style="text-align:center"class="container">
<h1>
Welcome {{title}}!
</h1>
<div class="container">
<p>Id: <span>{{data.id}}</span></p>
<p>Message: <span>{{data.content}}</span></p>
</div>
</div>
And the java controller:
#SpringBootApplication
#Controller
public class AngularApplication {
public static void main(String[] args) {
SpringApplication.run(AngularApplication.class, args);
}
#GetMapping("/resource")
#ResponseBody
public Map<String, Object> home() {
Map<String, Object> model = new HashMap<String, Object>();
model.put("id", UUID.randomUUID().toString());
model.put("content", "Hello World");
return model;
}
}
The app.module.ts file imports HttpClientModule. When I ng serve the application to localhost:4200 the site loads but without data.
The idea is to service the /resource request and return an object with the right keys for the client, but the keys do not exist and/or are not being recognized by the client.
How do I correctly pass the generated id and hello world content to the data object?
There was a tiny difference in package.json that was causing the issue. The one from the provided link uses "build": "ng build" and the default generated one from CLI uses "build": "ng build --prod". After changing this the example is working.