Repository: jhipster/generator-jhipster (ts)

Issue:
TestCase error when generating  microservice project with oauth2 authentication type
<!--
- Please follow the issue template below for bug reports and feature requests.
- If you have a support request rather than a bug, please use [Stack Overflow](http://stackoverflow.com/questions/tagged/jhipster) with the JHipster tag.
- For bug reports it is mandatory to run the command `jhipster info` in your project's root folder, and paste the result here.
- Tickets opened without any of these pieces of information will be **closed** without any explanation.
-->

##### **Overview of the issue**
TestCase error when generating  microservice project with oauth2 authentication type
<!-- Explain the bug or feature request, if an error is being thrown a stack trace helps -->

##### **Motivation for or Use Case**

<!-- Explain why this is a bug or a new feature for you -->
When running jhpack on new generated project,can't pass the test.
##### **Reproduce the error**

<!-- For bug reports, an unambiguous set of steps to reproduce the error -->

##### **Related issues**

<!-- Has a similar issue been reported before? Please search both closed & open issues -->
TestCase error when using ODIC.See below:
[ERROR] Failures:
[ERROR]   AccountResourceIntTest.testGetExistingAccount:116 Status expected:<200> but was:<500>
[INFO]
[ERROR] Tests run: 95, Failures: 1, Errors: 0, Skipped: 0
##### **Suggest a Fix**

<!-- For bug reports, if you can't fix the bug yourself, perhaps you can point to what might be
  causing the problem (line of code or commit) -->

##### **JHipster Version(s)**

<!--
Which version of JHipster are you using, is it a regression?
-->
5.0.0@beta.0


##### **JHipster configuration**

<!--
To provide all information we need, you should run `jhipster info` in the project root folder, and
copy/paste the result here.
The `.yo-rc.json` file generated in the root folder is mandatory for bug reports. This will help us to replicate the scenario.
You should remove any sensitive information like the rememberMe key or the jwtSecretKey key.
-->
<details>
<summary>.yo-rc.json file</summary>
<pre>
{
  "generator-jhipster": {
    "promptValues": {
      "packageName": "com.gzs.audit",
      "nativeLanguage": "zh-cn"
    },
    "jhipsterVersion": "5.0.0-beta.0",
    "baseName": "onlineshop",
    "reactive": false,
    "packageName": "com.gzs.audit",
    "packageFolder": "com/gzs/audit",
    "serverPort": "8081",
    "authenticationType": "oauth2",
    "cacheProvider": "hazelcast",
    "enableHibernateCache": true,
    "websocket": false,
    "databaseType": "sql",
    "devDatabaseType": "h2Disk",
    "prodDatabaseType": "mysql",
    "searchEngine": false,
    "messageBroker": false,
    "serviceDiscoveryType": "eureka",
    "buildTool": "maven",
    "enableSwaggerCodegen": true,
    "jwtSecretKey": "replaced-by-jhipster-info",
    "enableTranslation": true,
    "applicationType": "microservice",
    "testFrameworks": [],
    "jhiPrefix": "jhi",
    "nativeLanguage": "zh-cn",
    "languages": [
      "zh-cn"
    ],
    "clientPackageManager": "yarn",
    "skipClient": true,
    "skipUserManagement": true
  }
}
</pre>
</details>
##### **Entity configuration(s) `entityName.json` files generated in the `.jhipster` directory**

<!--
If the error is during an entity creation or associated with a specific entity.
If you are using JDL, please share that configuration as well.
-->
[simple-online-shop.jh.zip](https://github.com/jhipster/generator-jhipster/files/1910456/simple-online-shop.jh.zip)

##### **Browsers and Operating System**

<!-- What OS are you on? is this a problem with all browsers or only IE8? -->
macos 10.13.4
 [-] Checking this box is mandatory (this is just to show you read everything)

<!-- Love JHipster? Please consider supporting our collective:
👉  https://opencollective.com/generator-jhipster/donate -->


Pull request description:
Remove AccountResource and test for microservice
Fixes #7487 since `AccountResource`, and its test, are never used by the UI when the app is a microservice. 

Also sets `eureka.client.enabled` to false for tests to avoid stacktraces like the following when testing.

```
2018-04-17 08:51:29.420 ERROR 84830 --- [      Thread-10] com.netflix.discovery.DiscoveryClient    : DiscoveryClient_BLOG/blog:555c1d1d2470cd0cb69b74fc7c9a058d - de-registration failedCannot execute request on any known server

com.netflix.discovery.shared.transport.TransportException: Cannot execute request on any known server
	at com.netflix.discovery.shared.transport.decorator.RetryableEurekaHttpClient.execute(RetryableEurekaHttpClient.java:112)
	at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.cancel(EurekaHttpClientDecorator.java:71)
	at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator$2.execute(EurekaHttpClientDecorator.java:74)
	at com.netflix.discovery.shared.transport.decorator.SessionedEurekaHttpClient.execute(SessionedEurekaHttpClient.java:77)
	at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.cancel(EurekaHttpClientDecorator.java:71)
	at com.netflix.discovery.DiscoveryClient.unregister(DiscoveryClient.java:923)
	at com.netflix.discovery.DiscoveryClient.shutdown(DiscoveryClient.java:901)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:223)
	at org.springframework.cloud.context.scope.GenericScope$LockedScopedProxyFactoryBean.invoke(GenericScope.java:482)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
	at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
	at com.sun.proxy.$Proxy153.shutdown(Unknown Source)
	at org.springframework.cloud.netflix.eureka.serviceregistry.EurekaRegistration.close(EurekaRegistration.java:207)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.springframework.beans.factory.support.DisposableBeanAdapter.invokeCustomDestroyMethod(DisposableBeanAdapter.java:337)
	at org.springframework.beans.factory.support.DisposableBeanAdapter.destroy(DisposableBeanAdapter.java:271)
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroyBean(DefaultSingletonBeanRegistry.java:577)
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingleton(DefaultSingletonBeanRegistry.java:549)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingleton(DefaultListableBeanFactory.java:957)
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingletons(DefaultSingletonBeanRegistry.java:510)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingletons(DefaultListableBeanFactory.java:964)
	at org.springframework.context.support.AbstractApplicationContext.destroyBeans(AbstractApplicationContext.java:1041)
	at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:1017)
	at org.springframework.context.support.AbstractApplicationContext$1.run(AbstractApplicationContext.java:937)
```


Patch:
diff --git a/generators/server/files.js b/generators/server/files.js
index 9094e8a01b..222abe5767 100644
--- a/generators/server/files.js
+++ b/generators/server/files.js
@@ -534,7 +534,7 @@ const serverFiles = {
             condition: generator => !(generator.applicationType !== 'microservice' && !(generator.applicationType === 'gateway' && (generator.authenticationType === 'uaa' || generator.authenticationType === 'oauth2'))),
             path: SERVER_MAIN_SRC_DIR,
             templates: [
-                { file: 'package/config/MicroserviceSecurityConfiguration.java', renameTo: generator => `${generator.javaDir}config/MicroserviceSecurityConfiguration.java` }
+                { file: 'package/config/MicroserviceSecurityConfiguration.java', renameTo: generator => `${generator.javaDir}config/SecurityConfiguration.java` }
             ]
         },
         {
@@ -557,10 +557,18 @@ const serverFiles = {
                 { file: 'package/client/AuthorizedFeignClient.java', renameTo: generator => `${generator.javaDir}client/AuthorizedFeignClient.java` },
                 { file: 'package/client/OAuth2InterceptedFeignConfiguration.java', renameTo: generator => `${generator.javaDir}client/OAuth2InterceptedFeignConfiguration.java` },
                 { file: 'package/client/AuthorizedUserFeignClient.java', renameTo: generator => `${generator.javaDir}client/AuthorizedUserFeignClient.java` },
-                { file: 'package/client/UserFeignClientInterceptor.java', renameTo: generator => `${generator.javaDir}client/UserFeignClientInterceptor.java` },
+                { file: 'package/client/OAuth2_UserFeignClientInterceptor.java', renameTo: generator => `${generator.javaDir}client/UserFeignClientInterceptor.java` },
                 { file: 'package/client/OAuth2UserClientFeignConfiguration.java', renameTo: generator => `${generator.javaDir}client/OAuth2UserClientFeignConfiguration.java` }
             ]
         },
+        {
+            condition: generator => generator.applicationType === 'microservice' && generator.authenticationType === 'jwt',
+            path: SERVER_MAIN_SRC_DIR,
+            templates: [
+                { file: 'package/config/FeignConfiguration.java', renameTo: generator => `${generator.javaDir}config/FeignConfiguration.java` },
+                { file: 'package/client/JWT_UserFeignClientInterceptor.java', renameTo: generator => `${generator.javaDir}client/UserFeignClientInterceptor.java` }
+            ]
+        },
         {
             condition: generator => !(generator.applicationType !== 'microservice' && !(generator.applicationType === 'gateway' && (generator.authenticationType === 'uaa' || generator.authenticationType === 'oauth2')))
                 && generator.authenticationType === 'oauth2',
@@ -947,7 +955,6 @@ const serverFiles = {
             condition: generator => generator.skipUserManagement && generator.authenticationType === 'oauth2',
             path: SERVER_MAIN_SRC_DIR,
             templates: [
-                { file: 'package/web/rest/AccountResource.java', renameTo: generator => `${generator.javaDir}web/rest/AccountResource.java` },
                 { file: 'package/domain/User.java', renameTo: generator => `${generator.javaDir}domain/User.java` },
                 { file: 'package/domain/Authority.java', renameTo: generator => `${generator.javaDir}domain/Authority.java` },
                 { file: 'package/service/UserService.java', renameTo: generator => `${generator.javaDir}service/UserService.java` },
@@ -961,16 +968,29 @@ const serverFiles = {
                 { file: 'package/web/rest/vm/ManagedUserVM.java', renameTo: generator => `${generator.javaDir}web/rest/vm/ManagedUserVM.java` },
             ]
         },
+        {
+            condition: generator => generator.skipUserManagement && generator.authenticationType === 'oauth2' && ['monolith', 'gateway'].includes(generator.applicationType),
+            path: SERVER_MAIN_SRC_DIR,
+            templates: [
+                { file: 'package/web/rest/AccountResource.java', renameTo: generator => `${generator.javaDir}web/rest/AccountResource.java` },
+            ]
+        },
         {
             condition: generator => generator.skipUserManagement && generator.authenticationType === 'oauth2',
             path: SERVER_TEST_SRC_DIR,
             templates: [
-                { file: 'package/web/rest/AccountResourceIntTest.java', renameTo: generator => `${generator.testDir}web/rest/AccountResourceIntTest.java` },
                 { file: 'package/security/SecurityUtilsUnitTest.java', renameTo: generator => `${generator.testDir}security/SecurityUtilsUnitTest.java` },
                 { file: 'package/service/UserServiceIntTest.java', renameTo: generator => `${generator.testDir}service/UserServiceIntTest.java` },
                 { file: 'package/web/rest/UserResourceIntTest.java', renameTo: generator => `${generator.testDir}web/rest/UserResourceIntTest.java` },
             ]
         },
+        {
+            condition: generator => generator.skipUserManagement && generator.authenticationType === 'oauth2' && ['monolith', 'gateway'].includes(generator.applicationType),
+            path: SERVER_TEST_SRC_DIR,
+            templates: [
+                { file: 'package/web/rest/AccountResourceIntTest.java', renameTo: generator => `${generator.testDir}web/rest/AccountResourceIntTest.java` },
+            ]
+        },
         {
             condition: generator => generator.skipUserManagement && generator.authenticationType === 'oauth2' && generator.searchEngine === 'elasticsearch',
             path: SERVER_MAIN_SRC_DIR,
diff --git a/generators/server/templates/src/main/java/package/client/JWT_UserFeignClientInterceptor.java.ejs b/generators/server/templates/src/main/java/package/client/JWT_UserFeignClientInterceptor.java.ejs
new file mode 100644
index 0000000000..8ff41f3403
--- /dev/null
+++ b/generators/server/templates/src/main/java/package/client/JWT_UserFeignClientInterceptor.java.ejs
@@ -0,0 +1,36 @@
+<%#
+ Copyright 2013-2018 the original author or authors from the JHipster project.
+
+ This file is part of the JHipster project, see https://jhipster.github.io/
+ for more information.
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+      http://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.
+-%>
+package <%=packageName%>.client;
+
+import <%=packageName%>.security.SecurityUtils;
+import feign.RequestInterceptor;
+import feign.RequestTemplate;
+import org.springframework.stereotype.Component;
+
+@Component
+public class UserFeignClientInterceptor implements RequestInterceptor {
+    private static final String AUTHORIZATION_HEADER = "Authorization";
+    private static final String BEARER = "Bearer";
+
+    @Override
+    public void apply(RequestTemplate template) {
+        SecurityUtils.getCurrentUserJWT()
+            .ifPresent(s -> template.header(AUTHORIZATION_HEADER,String.format("%s %s", BEARER, s)));
+    }
+}
diff --git a/generators/server/templates/src/main/java/package/client/UserFeignClientInterceptor.java.ejs b/generators/server/templates/src/main/java/package/client/OAuth2_UserFeignClientInterceptor.java.ejs
similarity index 100%
rename from generators/server/templates/src/main/java/package/client/UserFeignClientInterceptor.java.ejs
rename to generators/server/templates/src/main/java/package/client/OAuth2_UserFeignClientInterceptor.java.ejs
diff --git a/generators/server/templates/src/main/java/package/config/FeignConfiguration.java.ejs b/generators/server/templates/src/main/java/package/config/FeignConfiguration.java.ejs
index 42479cac05..b589785733 100644
--- a/generators/server/templates/src/main/java/package/config/FeignConfiguration.java.ejs
+++ b/generators/server/templates/src/main/java/package/config/FeignConfiguration.java.ejs
@@ -19,10 +19,18 @@
 package <%=packageName%>.config;
 
 import org.springframework.cloud.openfeign.EnableFeignClients;
+import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
 
 @Configuration
 @EnableFeignClients(basePackages = "<%=packageName%>")
 public class FeignConfiguration {
 
+    /**
+     * Set the Feign specific log level to log client REST requests
+     */
+    @Bean
+    feign.Logger.Level feignLoggerLevel() {
+        return feign.Logger.Level.BASIC;
+    }
 }
diff --git a/generators/server/templates/src/main/java/package/config/MicroserviceSecurityConfiguration.java.ejs b/generators/server/templates/src/main/java/package/config/MicroserviceSecurityConfiguration.java.ejs
index e60544b080..5b8b0b1158 100644
--- a/generators/server/templates/src/main/java/package/config/MicroserviceSecurityConfiguration.java.ejs
+++ b/generators/server/templates/src/main/java/package/config/MicroserviceSecurityConfiguration.java.ejs
@@ -37,13 +37,13 @@ import org.zalando.problem.spring.web.advice.security.SecurityProblemSupport;
 @Import(SecurityProblemSupport.class)
 @EnableWebSecurity
 @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
-public class MicroserviceSecurityConfiguration extends WebSecurityConfigurerAdapter {
+public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
 
     private final TokenProvider tokenProvider;
 
     private final SecurityProblemSupport problemSupport;
 
-    public MicroserviceSecurityConfiguration(TokenProvider tokenProvider, SecurityProblemSupport problemSupport) {
+    public SecurityConfiguration(TokenProvider tokenProvider, SecurityProblemSupport problemSupport) {
         this.tokenProvider = tokenProvider;
         this.problemSupport = problemSupport;
     }
@@ -119,14 +119,14 @@ import org.springframework.web.client.RestTemplate;
 @Configuration
 @EnableResourceServer
 @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
-public class MicroserviceSecurityConfiguration extends ResourceServerConfigurerAdapter {
+public class SecurityConfiguration extends ResourceServerConfigurerAdapter {
     private final OAuth2Properties oAuth2Properties;
 
     <%_ if (applicationType === 'gateway') { _%>
     private final CorsFilter corsFilter;
 
     <%_ } _%>
-    public MicroserviceSecurityConfiguration(OAuth2Properties oAuth2Properties<%_ if (applicationType === 'gateway') { _%>, CorsFilter corsFilter<%_ } _%>) {
+    public SecurityConfiguration(OAuth2Properties oAuth2Properties<%_ if (applicationType === 'gateway') { _%>, CorsFilter corsFilter<%_ } _%>) {
         this.oAuth2Properties = oAuth2Properties;
         <%_ if (applicationType === 'gateway') { _%>
         this.corsFilter = corsFilter;
@@ -204,7 +204,7 @@ import org.zalando.problem.spring.web.advice.security.SecurityProblemSupport;
 @Import(SecurityProblemSupport.class)
 @EnableResourceServer
 @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
-public class MicroserviceSecurityConfiguration extends ResourceServerConfigurerAdapter {
+public class SecurityConfiguration extends ResourceServerConfigurerAdapter {
 
     private static final String OAUTH2_PRINCIPAL_ATTRIBUTE = "preferred_username";
 
@@ -214,7 +214,7 @@ public class MicroserviceSecurityConfiguration extends ResourceServerConfigurerA
 
     private final SecurityProblemSupport problemSupport;
 
-    public MicroserviceSecurityConfiguration(ResourceServerProperties resourceServerProperties,
+    public SecurityConfiguration(ResourceServerProperties resourceServerProperties,
         SecurityProblemSupport problemSupport) {
         this.resourceServerProperties = resourceServerProperties;
         this.problemSupport = problemSupport;
diff --git a/generators/server/templates/src/main/resources/config/application.yml.ejs b/generators/server/templates/src/main/resources/config/application.yml.ejs
index eb495bc3e5..e17659f61d 100644
--- a/generators/server/templates/src/main/resources/config/application.yml.ejs
+++ b/generators/server/templates/src/main/resources/config/application.yml.ejs
@@ -80,21 +80,26 @@ hystrix:
 
 <%_ } _%>
 <%_ if (applicationType === 'microservice') { _%>
-# See https://github.com/Netflix/Hystrix/wiki/Configuration
-#hystrix:
-#    command:
-#        default:
-#            execution:
-#                isolation:
-#                    thread:
-#                        timeoutInMilliseconds: 10000
-# See https://github.com/spring-cloud/spring-cloud-netflix/issues/1330
 feign:
     hystrix:
         enabled: true
+#    client:
+#        config:
+#            default:
+#                connectTimeout: 5000
+#                readTimeout: 5000
 
+# See https://github.com/Netflix/Hystrix/wiki/Configuration
 hystrix:
-    share-security-context: true
+    command:
+        default:
+            execution:
+                isolation:
+                    strategy: SEMAPHORE
+# See https://github.com/spring-cloud/spring-cloud-netflix/issues/1330
+#                    thread:
+#                        timeoutInMilliseconds: 10000
+    shareSecurityContext: true
 
 <%_ } _%>
 management:


Test patch:
diff --git a/generators/server/templates/src/test/resources/config/application.yml.ejs b/generators/server/templates/src/test/resources/config/application.yml.ejs
index 53a0e7db47..d8453d7d97 100644
--- a/generators/server/templates/src/test/resources/config/application.yml.ejs
+++ b/generators/server/templates/src/test/resources/config/application.yml.ejs
@@ -34,7 +34,7 @@
 <%_ if (serviceDiscoveryType === 'eureka') { _%>
 eureka:
     client:
-        enabled: true
+        enabled: false
     instance:
         appname: <%= baseName %>
         instanceId: <%= baseName %>:${spring.application.instance-id:${random.value}}
diff --git a/test/utils/expected-files.js b/test/utils/expected-files.js
index 332406654e..7a234ca9d0 100644
--- a/test/utils/expected-files.js
+++ b/test/utils/expected-files.js
@@ -455,7 +455,9 @@ const expectedFiles = {
 
     microservice: [
         `${SERVER_MAIN_RES_DIR}static/index.html`,
-        `${SERVER_MAIN_SRC_DIR}com/mycompany/myapp/config/MicroserviceSecurityConfiguration.java`,
+        `${SERVER_MAIN_SRC_DIR}com/mycompany/myapp/config/SecurityConfiguration.java`,
+        `${SERVER_MAIN_SRC_DIR}com/mycompany/myapp/config/FeignConfiguration.java`,
+        `${SERVER_MAIN_SRC_DIR}com/mycompany/myapp/client/UserFeignClientInterceptor.java`,
         'package.json'
     ],