├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── README.md ├── src ├── test │ ├── resources │ │ └── application.yml │ └── java │ │ └── org │ │ └── openpaas │ │ └── paasta │ │ └── portal │ │ └── log │ │ └── api │ │ ├── config │ │ └── TestConfig.java │ │ └── service │ │ ├── AppAutoscalingServiceTest.java │ │ ├── AlarmServiceTest.java │ │ └── BuildPackServiceTest.java └── main │ ├── java │ └── org │ │ └── openpaas │ │ └── paasta │ │ └── portal │ │ └── log │ │ └── api │ │ ├── LogApplication.java │ │ ├── config │ │ ├── cloudfoundry │ │ │ ├── provider │ │ │ │ ├── TokenGrantTokenProvider.java │ │ │ │ └── CfConfigProvider.java │ │ │ └── RestConfig.java │ │ ├── ApplicationConfig.java │ │ ├── InfluxDBProperties.java │ │ ├── InfluxDBConfiguration.java │ │ └── security │ │ │ └── SecurityConfig.java │ │ ├── common │ │ ├── ChatObject.java │ │ ├── TailSocket.java │ │ └── Common.java │ │ ├── controller │ │ └── LoggingController.java │ │ ├── service │ │ ├── LoggingService.java │ │ └── AppService.java │ │ ├── util │ │ ├── SSLUtils.java │ │ └── RestUtil.java │ │ └── exception │ │ └── GlobalControllerExceptionHandler.java │ ├── resources │ ├── certs │ │ └── influx_cert.crt │ └── application.yml │ └── webapp │ └── messages │ └── message.properties ├── .gitignore ├── manifest.yml ├── gradlew.bat ├── gradlew └── LICENSE /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PaaS-TA/PAAS-TA-PORTAL-LOG-API/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.3-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PAAS-TA-PORTAL-LOG-API 2 | ## Portal LOG API 3 | Portal LOG API 란? CF Tail 및 APP 로그 서비스를 위해 구현한 서비스이다. 4 | - CF Tail - 각각의 API 서비스로 제공(CF, DB, OBJECT STORAGE, LOG) 5 | - App log - InfluxDB 접속 및 쿼리를 위한 API 제공 6 | 7 | ## 유의사항 8 | - java 1.8 9 | - SpringCloud Edgware.RELEASE 10 | - TomcatEmded 8.5.14 11 | - Gradle 4.10.3 12 | - Spring-boot 1.5.10 13 | - Soket IO 1.7.14 14 | - influxdb-java 2.14 15 | -------------------------------------------------------------------------------- /src/test/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | application: 3 | name: PortalApi 4 | cloud: 5 | config: 6 | uri: http://10.30.80.50:8004 7 | 8 | server: 9 | port: ${PORT:2221} 10 | 11 | # Discovery Server Access 12 | eureka: 13 | client: 14 | serviceUrl: 15 | defaultZone: http://127.0.0.1:2221/eureka/ 16 | registry-fetch-interval-seconds: 5 17 | instance: 18 | hostname: ${spring.cloud.client.hostname} 19 | lease-expiration-duration-in-seconds: 5 20 | lease-renewal-interval-in-seconds: 10 -------------------------------------------------------------------------------- /src/main/java/org/openpaas/paasta/portal/log/api/LogApplication.java: -------------------------------------------------------------------------------- 1 | package org.openpaas.paasta.portal.log.api; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 6 | import org.springframework.context.annotation.ComponentScan; 7 | 8 | 9 | @EnableDiscoveryClient 10 | @SpringBootApplication 11 | public class LogApplication { 12 | public static void main(String[] args) { 13 | SpringApplication.run(LogApplication.class, args); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/org/openpaas/paasta/portal/log/api/config/cloudfoundry/provider/TokenGrantTokenProvider.java: -------------------------------------------------------------------------------- 1 | package org.openpaas.paasta.portal.log.api.config.cloudfoundry.provider; 2 | 3 | import org.cloudfoundry.reactor.ConnectionContext; 4 | import org.cloudfoundry.reactor.TokenProvider; 5 | import reactor.core.publisher.Mono; 6 | 7 | 8 | public class TokenGrantTokenProvider implements TokenProvider{ 9 | 10 | private String token; 11 | 12 | public TokenGrantTokenProvider(String token) { 13 | this.token = token; 14 | } 15 | 16 | @Override 17 | public Mono getToken(ConnectionContext connectionContext) { 18 | 19 | return Mono.just(token); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # ignore output and build directories 14 | build/** 15 | bin/** 16 | out/** 17 | 18 | # Package Files # 19 | *.jar 20 | *.war 21 | *.ear 22 | *.zip 23 | *.tar.gz 24 | *.rar 25 | 26 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 27 | hs_err_pid* 28 | 29 | # generated gradle directories and files 30 | .gradle 31 | .settings 32 | 33 | # eclise settings 34 | .classpath 35 | .project 36 | 37 | # idea settings 38 | *.iml 39 | *.idea 40 | .idea/** 41 | 42 | # remove spring bean configuration 43 | .spring* 44 | 45 | -------------------------------------------------------------------------------- /src/main/resources/certs/influx_cert.crt: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIICDDCCAXUCFDjE4wNHu2FzZMx/QR4V65XqVyzMMA0GCSqGSIb3DQEBCwUAMEUx 3 | CzAJBgNVBAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRl 4 | cm5ldCBXaWRnaXRzIFB0eSBMdGQwHhcNMjMwNjE0MDgwNjM3WhcNMjQwNjEzMDgw 5 | NjM3WjBFMQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UE 6 | CgwYSW50ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIGfMA0GCSqGSIb3DQEBAQUAA4GN 7 | ADCBiQKBgQC8Fjkya/dEAjZcjvV4ORpL8/cafVwk4pljRql+8TSvUSqh2C/Ay6ql 8 | ys8J1HrGs4+KkTUJ2xOrxyZj8OqiWwUx6a+2+oSZ9iJYlwOxAwk4IwnYaMj2pqM0 9 | CZVLnRqG9aQy0a0r3jwR4SpQnbDOaith3eUcJYjdaoMgy24cZK5ExQIDAQABMA0G 10 | CSqGSIb3DQEBCwUAA4GBAKd83Jj4gNogVbJPfFW/O+Hn/Vzcmx5fBGh7UZ4tNoKs 11 | 1k52MBf/OLurQsxFp9xi2tAj+DSBDh3nsS730jfCvqF5u+Q+Sd7vUzJ/rL7Ob1z+ 12 | ioFqWzjykU5BRnsiOqaJgimaAPDm8MKg4mOTW46fExcCVRlZO66TgppeUn4nz2fw 13 | -----END CERTIFICATE----- 14 | -------------------------------------------------------------------------------- /src/main/java/org/openpaas/paasta/portal/log/api/common/ChatObject.java: -------------------------------------------------------------------------------- 1 | package org.openpaas.paasta.portal.log.api.common; 2 | 3 | /** 4 | * Created by indra on 2018-05-09. 5 | */ 6 | public class ChatObject { 7 | 8 | private String userName; 9 | private String message; 10 | 11 | public ChatObject() { 12 | super(); 13 | } 14 | public ChatObject(String userName, String message) { 15 | super(); 16 | this.userName = userName; 17 | this.message = message; 18 | } 19 | public String getUserName() { 20 | return userName; 21 | } 22 | public void setUserName(String userName) { 23 | this.userName = userName; 24 | } 25 | public String getMessage() { 26 | return message; 27 | } 28 | public void setMessage(String message) { 29 | this.message = message; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/test/java/org/openpaas/paasta/portal/log/api/config/TestConfig.java: -------------------------------------------------------------------------------- 1 | //package org.openpaas.paasta.portal.api.config; 2 | // 3 | //import org.junit.FixMethodOrder; 4 | //import org.junit.runners.MethodSorters; 5 | //import org.slf4j.Logger; 6 | //import org.slf4j.LoggerFactory; 7 | //import org.springframework.boot.test.context.SpringBootTest; 8 | //import org.springframework.test.context.ActiveProfiles; 9 | //import org.springframework.test.context.TestPropertySource; 10 | // 11 | ////@ActiveProfiles("local") 12 | ////@TestPropertySource(properties = {"eureka.client.enabled=false"}) //Local용 13 | //@ActiveProfiles("dev") 14 | //@TestPropertySource(properties = {"spring.config.location = classpath:/application.yml","eureka.client.enabled=false"}) // Push 용 15 | //@SpringBootTest 16 | //@FixMethodOrder(MethodSorters.NAME_ASCENDING) 17 | // 18 | //public class TestConfig { 19 | // private static final Logger LOGGER = LoggerFactory.getLogger(TestConfig.class); 20 | //} 21 | // 22 | // 23 | -------------------------------------------------------------------------------- /src/main/java/org/openpaas/paasta/portal/log/api/config/ApplicationConfig.java: -------------------------------------------------------------------------------- 1 | package org.openpaas.paasta.portal.log.api.config; 2 | 3 | import org.springframework.context.MessageSource; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.context.support.ReloadableResourceBundleMessageSource; 7 | //import org.springframework.web.servlet.config.annotation.EnableWebMvc; 8 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 9 | 10 | /** 11 | * The type Application config. 12 | */ 13 | @Configuration 14 | public class ApplicationConfig extends WebMvcConfigurerAdapter { 15 | 16 | @Bean 17 | public MessageSource messageSource() { 18 | ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); 19 | messageSource.setBasename("/messages/message"); 20 | messageSource.setDefaultEncoding("UTF-8"); 21 | return messageSource; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/org/openpaas/paasta/portal/log/api/config/cloudfoundry/provider/CfConfigProvider.java: -------------------------------------------------------------------------------- 1 | package org.openpaas.paasta.portal.log.api.config.cloudfoundry.provider; 2 | 3 | 4 | import org.cloudfoundry.reactor.DefaultConnectionContext; 5 | import org.cloudfoundry.reactor.tokenprovider.PasswordGrantTokenProvider; 6 | import org.openpaas.paasta.portal.log.api.common.Common; 7 | import org.openpaas.paasta.portal.log.api.common.Common; 8 | import org.springframework.beans.factory.annotation.Value; 9 | import org.springframework.context.annotation.Bean; 10 | import org.springframework.context.annotation.Configuration; 11 | 12 | @Configuration 13 | public class CfConfigProvider { 14 | 15 | 16 | 17 | @Bean 18 | DefaultConnectionContext connectionContext(@Value("${cloudfoundry.cc.api.url}") String apiHost, @Value("${cloudfoundry.cc.api.sslSkipValidation}") Boolean sslSkipValidation) { 19 | return Common.crateConnectionContext(apiHost, sslSkipValidation); 20 | } 21 | 22 | @Bean 23 | PasswordGrantTokenProvider tokenProvider(@Value("${cloudfoundry.user.admin.username}") String username, 24 | @Value("${cloudfoundry.user.admin.password}") String password) { 25 | return PasswordGrantTokenProvider.builder() 26 | .password(password) 27 | .username(username) 28 | .build(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/org/openpaas/paasta/portal/log/api/controller/LoggingController.java: -------------------------------------------------------------------------------- 1 | package org.openpaas.paasta.portal.log.api.controller; 2 | 3 | import org.openpaas.paasta.portal.log.api.service.LoggingService; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.web.bind.annotation.GetMapping; 8 | import org.springframework.web.bind.annotation.PathVariable; 9 | import org.springframework.web.bind.annotation.RequestParam; 10 | import org.springframework.web.bind.annotation.RestController; 11 | 12 | import java.util.List; 13 | 14 | @RestController 15 | public class LoggingController { 16 | 17 | private static final Logger LOGGER = LoggerFactory.getLogger(LoggingController.class); 18 | 19 | @Autowired 20 | private LoggingService loggingService; 21 | 22 | /** 23 | * 해당 조직에 대한 앱 로그를 조회한다. 24 | * 25 | * @return Map(자바클래스) 26 | */ 27 | @GetMapping("/logs/app/{guid}") 28 | public List getLogData( 29 | @PathVariable String guid, 30 | @RequestParam(name = "stime", required = false) String startTime, 31 | @RequestParam(name = "etime", required = false) String endTime, 32 | @RequestParam(name = "keyword", required = false, defaultValue = "") String keyword) { 33 | 34 | LOGGER.debug("getLogData() :: appGuid = " + guid + ", startTime = " + startTime + ", endTime = " + endTime + ", keyword = " + keyword); 35 | 36 | return loggingService.getLogData(guid, startTime, endTime, keyword); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/org/openpaas/paasta/portal/log/api/config/cloudfoundry/RestConfig.java: -------------------------------------------------------------------------------- 1 | package org.openpaas.paasta.portal.log.api.config.cloudfoundry; 2 | 3 | import org.apache.http.conn.ssl.SSLConnectionSocketFactory; 4 | import org.apache.http.impl.client.CloseableHttpClient; 5 | import org.apache.http.impl.client.HttpClients; 6 | import org.apache.http.ssl.TrustStrategy; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; 10 | import org.springframework.web.client.RestTemplate; 11 | 12 | import javax.net.ssl.SSLContext; 13 | import java.security.KeyManagementException; 14 | import java.security.KeyStoreException; 15 | import java.security.NoSuchAlgorithmException; 16 | import java.security.cert.X509Certificate; 17 | 18 | @Configuration 19 | public class RestConfig { 20 | 21 | @Bean 22 | public RestTemplate restTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { 23 | TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true; 24 | 25 | SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom() 26 | .loadTrustMaterial(null, acceptingTrustStrategy) 27 | .build(); 28 | 29 | SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext); 30 | 31 | CloseableHttpClient httpClient = HttpClients.custom() 32 | .setSSLSocketFactory(csf) 33 | .build(); 34 | 35 | HttpComponentsClientHttpRequestFactory requestFactory = 36 | new HttpComponentsClientHttpRequestFactory(); 37 | 38 | requestFactory.setHttpClient(httpClient); 39 | RestTemplate restTemplate = new RestTemplate(requestFactory); 40 | return restTemplate; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/org/openpaas/paasta/portal/log/api/config/InfluxDBProperties.java: -------------------------------------------------------------------------------- 1 | package org.openpaas.paasta.portal.log.api.config; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | 5 | @ConfigurationProperties(prefix = "influxdb") 6 | public class InfluxDBProperties { 7 | 8 | private String ip; 9 | private String url; 10 | private String username; 11 | private String password; 12 | private String database; 13 | private String measurement; 14 | private String limit; 15 | private boolean httpsEnabled; 16 | 17 | 18 | public String getIp() { 19 | return ip; 20 | } 21 | public void setIp(String ip) { 22 | this.ip = ip; 23 | } 24 | 25 | public String getUrl() { 26 | return url; 27 | } 28 | public void setUrl(String url) { 29 | this.url = url; 30 | } 31 | 32 | public String getUsername() { 33 | return username; 34 | } 35 | public void setUsername(String username) { 36 | this.username = username; 37 | } 38 | 39 | public String getPassword() { 40 | return password; 41 | } 42 | public void setPassword(String password) { 43 | this.password = password; 44 | } 45 | 46 | public String getDatabase() { 47 | return database; 48 | } 49 | public void setDatabase(String database) { 50 | this.database = database; 51 | } 52 | 53 | public String getMeasurement() { 54 | return measurement; 55 | } 56 | public void setMeasurement(String measurement) { 57 | this.measurement = measurement; 58 | } 59 | 60 | public String getLimit() { 61 | return limit; 62 | } 63 | public void setLimit(String limit) { 64 | this.limit = limit; 65 | } 66 | 67 | public boolean getHttpsEnabled() { 68 | return httpsEnabled; 69 | } 70 | public void setHttpsEnabled(boolean httpsEnabled) { 71 | this.httpsEnabled = httpsEnabled; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/test/java/org/openpaas/paasta/portal/log/api/service/AppAutoscalingServiceTest.java: -------------------------------------------------------------------------------- 1 | //package org.openpaas.paasta.portal.api.service; 2 | // 3 | //import org.junit.Assert; 4 | //import org.junit.Before; 5 | //import org.junit.FixMethodOrder; 6 | //import org.junit.Test; 7 | //import org.junit.runner.RunWith; 8 | //import org.junit.runners.MethodSorters; 9 | //import org.mockito.MockitoAnnotations; 10 | //import org.springframework.boot.test.context.SpringBootTest; 11 | //import org.springframework.boot.test.mock.mockito.MockBean; 12 | //import org.springframework.test.context.junit4.SpringRunner; 13 | // 14 | //import java.util.HashMap; 15 | //import java.util.Map; 16 | // 17 | //import static org.mockito.Mockito.any; 18 | //import static org.mockito.Mockito.when; 19 | // 20 | //@RunWith(SpringRunner.class) 21 | //@SpringBootTest 22 | //@FixMethodOrder(MethodSorters.NAME_ASCENDING) 23 | //public class AppAutoscalingServiceTest { 24 | // 25 | // @MockBean 26 | // AppAutoscalingService appAutoscalingService; 27 | // 28 | // @Before 29 | // public void setUp() { 30 | // MockitoAnnotations.initMocks(this); 31 | // } 32 | // 33 | // @Test 34 | // public void testGetAutoscaling() throws Exception { 35 | // Map map = new HashMap() {{ 36 | // put("String", "String"); 37 | // }}; 38 | // 39 | // when(appAutoscalingService.getAutoscaling(any())).thenReturn(map); 40 | // 41 | // Map result = appAutoscalingService.getAutoscaling("appGuid"); 42 | // Assert.assertEquals(map, result); 43 | // } 44 | // 45 | // @Test 46 | // public void testUpdateAutoscaling() throws Exception { 47 | // Map map = new HashMap() {{ 48 | // put("String", "String"); 49 | // }}; 50 | // when(appAutoscalingService.updateAutoscaling(any())).thenReturn(map); 51 | // 52 | // Map result = appAutoscalingService.updateAutoscaling(new HashMap() {{ 53 | // put("String", "String"); 54 | // }}); 55 | // Assert.assertEquals(map, result); 56 | // } 57 | //} 58 | // 59 | -------------------------------------------------------------------------------- /src/main/java/org/openpaas/paasta/portal/log/api/service/LoggingService.java: -------------------------------------------------------------------------------- 1 | package org.openpaas.paasta.portal.log.api.service; 2 | 3 | import org.influxdb.InfluxDB; 4 | import org.influxdb.dto.Query; 5 | import org.influxdb.dto.QueryResult; 6 | import org.openpaas.paasta.portal.log.api.config.InfluxDBProperties; 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.stereotype.Service; 11 | 12 | import java.util.ArrayList; 13 | import java.util.List; 14 | 15 | @Service 16 | public class LoggingService { 17 | 18 | private static final Logger LOGGER = LoggerFactory.getLogger(LoggingService.class); 19 | 20 | @Autowired 21 | private InfluxDB influxDB; 22 | 23 | @Autowired 24 | private InfluxDBProperties influxDBProperties; 25 | 26 | public List getLogData(String guid, String sTime, String eTime, String keyword) { 27 | String measurement = influxDBProperties.getMeasurement(); 28 | String limit = influxDBProperties.getLimit(); 29 | String dbName = influxDBProperties.getDatabase(); 30 | 31 | String sql = "SELECT time, message FROM " + measurement + " WHERE time >= '" + sTime + "' AND time <= '" + eTime + "' AND message =~ /\"cf_app_id\":\"" + guid + "\"/"; 32 | 33 | if(keyword != null && !keyword.isEmpty() && keyword != "") { 34 | sql += " AND message =~ /" + keyword + "*/"; 35 | } 36 | 37 | sql += " ORDER BY time DESC LIMIT " + limit; 38 | 39 | List logList = new ArrayList<>(); 40 | 41 | try { 42 | QueryResult queryResult = influxDB.query(new Query(sql, dbName)); 43 | List resultList = queryResult.getResults().get(0).getSeries(); 44 | if(resultList != null) { 45 | logList.addAll(resultList.get(0).getValues()); 46 | } 47 | } catch (Exception e) { 48 | LOGGER.error(e.getMessage()); 49 | } 50 | 51 | return logList; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /manifest.yml: -------------------------------------------------------------------------------- 1 | applications: 2 | - name: portal-log-api 3 | memory: 1G 4 | instances: 1 5 | buildpacks: 6 | - java_buildpack 7 | path: build/libs/paas-ta-portal-log-api.jar 8 | env: 9 | server_port: 8080 10 | 11 | BP_JVM_VERSION: 8 12 | BP_SPRING_CLOUD_BINDINGS_DISABLED: true 13 | 14 | spring_application_name: PortalLogApi 15 | 16 | spring_security_username: admin 17 | spring_security_password: openpaasta 18 | 19 | tailsocket_port: 5555 20 | 21 | ### paasta info 22 | cloudfoundry_cc_api_url: https://api. 23 | cloudfoundry_cc_api_uaaUrl: https://uaa. 24 | cloudfoundry_cc_api_sslSkipValidation: true 25 | cloudfoundry_user_admin_username: # (e.g. admin) 26 | cloudfoundry_user_admin_password: # (e.g. admin) 27 | cloudfoundry_user_uaaClient_clientId: # (e.g. login) 28 | cloudfoundry_user_uaaClient_clientSecret: # (e.g. login-secret) 29 | cloudfoundry_user_uaaClient_adminClientId: # (e.g. admin) 30 | cloudfoundry_user_uaaClient_adminClientSecret: # (e.g. admin-secret) 31 | cloudfoundry_user_uaaClient_skipSSLValidation: true 32 | cloudfoundry_authorization: cf-Authorization 33 | 34 | eureka_client_serviceUrl_defaultZone: http://portal-registration./eureka/ 35 | eureka_instance_hostname: ${vcap.application.uris[0]} 36 | eureka_instance_nonSecurePort: 80 37 | 38 | ### logging info (InfluxDB) 39 | influxdb_ip: 40 | influxdb_url: https://: 41 | influxdb_username: 42 | influxdb_password: 43 | influxdb_database: 44 | influxdb_measurement: 45 | influxdb_limit: 46 | influxdb_httpsEnabled: 47 | -------------------------------------------------------------------------------- /src/main/java/org/openpaas/paasta/portal/log/api/service/AppService.java: -------------------------------------------------------------------------------- 1 | package org.openpaas.paasta.portal.log.api.service; 2 | 3 | 4 | import com.corundumstudio.socketio.SocketIOClient; 5 | import org.cloudfoundry.client.v2.applications.ApplicationStatisticsResponse; 6 | import org.cloudfoundry.client.v2.applicationusageevents.GetApplicationUsageEventResponse; 7 | import org.cloudfoundry.doppler.LogMessage; 8 | import org.cloudfoundry.operations.DefaultCloudFoundryOperations; 9 | import org.cloudfoundry.operations.applications.LogsRequest; 10 | import org.openpaas.paasta.portal.log.api.common.Common; 11 | import org.slf4j.Logger; 12 | import org.slf4j.LoggerFactory; 13 | import org.springframework.stereotype.Service; 14 | 15 | /** 16 | * 앱 서비스 - 애플리케이션 정보 조회, 구동, 정지 등의 API 를 호출 하는 서비스이다. 17 | * 18 | * @author 조민구 19 | * @version 1.0 20 | * @since 2016.4.4 최초작성 21 | */ 22 | @Service 23 | public class AppService extends Common { 24 | 25 | private static final Logger LOGGER = LoggerFactory.getLogger(AppService.class); 26 | 27 | 28 | 29 | 30 | private void printLog(LogMessage msg) { 31 | LOGGER.info(" [" + msg.getSourceType() + "/" + msg.getSourceInstance() + "] [" + msg.getMessageType() + msg.getMessageType() + "] " + msg.getMessage()); 32 | } 33 | 34 | 35 | public SocketIOClient socketTailLogs(SocketIOClient client, String appName, String orgName, String spaceName) { 36 | DefaultCloudFoundryOperations cloudFoundryOperations = cloudFoundryOperations(connectionContext(), tokenProvider(adminUserName,adminPassword), orgName, spaceName); 37 | cloudFoundryOperations.applications() 38 | .logs(LogsRequest.builder() 39 | .name(appName) 40 | .build() 41 | ).subscribe((msg) -> { 42 | printLog(msg); 43 | client.sendEvent("message", " [" + msg.getSourceType() + "/" + msg.getSourceInstance() + "] [" + msg.getMessageType() + msg.getMessageType() + "] " + msg.getMessage()); 44 | }, 45 | (error) -> { 46 | error.printStackTrace(); 47 | } 48 | ); 49 | return client; 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/org/openpaas/paasta/portal/log/api/util/SSLUtils.java: -------------------------------------------------------------------------------- 1 | package org.openpaas.paasta.portal.log.api.util; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | 6 | import javax.net.ssl.*; 7 | import java.security.*; 8 | import java.security.cert.X509Certificate; 9 | /** 10 | * Created by Dojun on 2016-10-05. 11 | */ 12 | 13 | /* 14 | resttemplate로 api 요청시 SSL 유효성 체크를 건너뜀 15 | */ 16 | public final class SSLUtils { 17 | //private static final Logger LOGGER = LoggerFactory.getLogger(SSLUtils.class); 18 | static { 19 | //for localhost testing only 20 | javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier( 21 | new javax.net.ssl.HostnameVerifier(){ 22 | 23 | public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) { 24 | if (hostname.equals("localhost")) { 25 | return true; 26 | } 27 | return false; 28 | } 29 | }); 30 | } 31 | 32 | private static final TrustManager[] UNQUESTIONING_TRUST_MANAGER = new TrustManager[]{ 33 | new X509TrustManager() { 34 | public java.security.cert.X509Certificate[] getAcceptedIssuers(){ 35 | return null; 36 | } 37 | public void checkClientTrusted( X509Certificate[] certs, String authType ){} 38 | public void checkServerTrusted( X509Certificate[] certs, String authType ){} 39 | } 40 | }; 41 | 42 | public static void turnOffSslChecking() throws NoSuchAlgorithmException, KeyManagementException { 43 | // Install the all-trusting trust manager 44 | final SSLContext sc = SSLContext.getInstance("SSL"); 45 | sc.init( null, UNQUESTIONING_TRUST_MANAGER, null ); 46 | HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); 47 | } 48 | 49 | public static void turnOnSslChecking() throws KeyManagementException, NoSuchAlgorithmException { 50 | // Return it to the initial state (discovered by reflection, now hardcoded) 51 | SSLContext.getInstance("SSL").init( null, null, null ); 52 | } 53 | 54 | private SSLUtils(){ 55 | throw new UnsupportedOperationException( "Do not instantiate libraries."); 56 | } 57 | } -------------------------------------------------------------------------------- /src/test/java/org/openpaas/paasta/portal/log/api/service/AlarmServiceTest.java: -------------------------------------------------------------------------------- 1 | //package org.openpaas.paasta.portal.api.service; 2 | // 3 | //import org.junit.Assert; 4 | //import org.junit.Before; 5 | //import org.junit.FixMethodOrder; 6 | //import org.junit.Test; 7 | //import org.junit.runner.RunWith; 8 | //import org.junit.runners.MethodSorters; 9 | //import org.mockito.MockitoAnnotations; 10 | //import org.openpaas.paasta.portal.api.config.TestConfig; 11 | //import org.springframework.boot.test.context.SpringBootTest; 12 | //import org.springframework.boot.test.mock.mockito.MockBean; 13 | //import org.springframework.test.context.junit4.SpringRunner; 14 | // 15 | //import java.util.HashMap; 16 | //import java.util.Map; 17 | // 18 | //import static org.mockito.Mockito.any; 19 | //import static org.mockito.Mockito.when; 20 | // 21 | //@RunWith(SpringRunner.class) 22 | //@SpringBootTest 23 | //@FixMethodOrder(MethodSorters.NAME_ASCENDING) 24 | //public class AlarmServiceTest extends TestConfig { 25 | // 26 | // @MockBean 27 | // AlarmService alarmService; 28 | // 29 | // @Before 30 | // public void setUp() { 31 | // MockitoAnnotations.initMocks(this); 32 | // } 33 | // 34 | // @Test 35 | // public void testGetAlarmList() throws Exception { 36 | // Map map = new HashMap() {{ 37 | // put("String", "String"); 38 | // }}; 39 | // when(alarmService.getAlarmList(any(), any(), any(), any(), any())).thenReturn(map); 40 | // 41 | // Map result = alarmService.getAlarmList("appGuid", "pageItems", "pageIndex", "resourceType", "alarmLevel"); 42 | // Assert.assertEquals(map, result); 43 | // } 44 | // 45 | // @Test 46 | // public void testGetAlarm() throws Exception { 47 | // Map map = new HashMap() {{ 48 | // put("String", "String"); 49 | // }}; 50 | // when(alarmService.getAlarm(any())).thenReturn(map); 51 | // 52 | // Map result = alarmService.getAlarm("appGuid"); 53 | // Assert.assertEquals(map, result); 54 | // } 55 | // 56 | // @Test 57 | // public void testUpdateAlarm() throws Exception { 58 | // Map map = new HashMap() {{ 59 | // put("String", "String"); 60 | // }}; 61 | // when(alarmService.updateAlarm(any())).thenReturn(map); 62 | // 63 | // Map result = alarmService.updateAlarm(new HashMap() {{ 64 | // put("String", "String"); 65 | // }}); 66 | // Assert.assertEquals(map, result); 67 | // } 68 | //} 69 | // 70 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | # Spring properties 2 | spring: 3 | application: 4 | name: PortalLogApi # Service registers under this name 5 | security: 6 | username: admin 7 | password: openpaasta 8 | flyway: 9 | enabled: false 10 | 11 | # HTTP Server 12 | server: 13 | port: ${PORT:2230} # HTTP (Tomcat) port 14 | 15 | tailsocket: 16 | port: 5555 17 | 18 | management: # If you set off security... 19 | security: 20 | enabled: false 21 | 22 | # CloudFoundry API Url 23 | cloudfoundry: 24 | cc: 25 | api: 26 | url: https://api. 27 | uaaUrl: https://uaa. 28 | sslSkipValidation: true 29 | # CloudFoundry Login information 30 | user: 31 | admin: 32 | username: # (e.g. admin) 33 | password: # (e.g. admin) 34 | uaaClient: 35 | clientId: # (e.g. login) 36 | clientSecret: # (e.g. login-secret) 37 | adminClientId: # (e.g. admin) 38 | adminClientSecret: # (e.g. admin-secret) 39 | skipSSLValidation: true 40 | 41 | # Discovery Server Access 42 | eureka: 43 | client: 44 | serviceUrl: 45 | defaultZone: http://:/eureka/ 46 | registry-fetch-interval-seconds: 5 47 | instance: 48 | hostname: ${spring.cloud.client.hostname} 49 | lease-expiration-duration-in-seconds: 5 50 | lease-renewal-interval-in-seconds: 10 51 | 52 | # InfluxDB Access Info 53 | influxdb: 54 | ip: 10.0.1.115 55 | url: http://10.0.1.115:8086 56 | username: admin 57 | password: PaaS-TA2022 58 | database: logging_db 59 | measurement: logging_measurement 60 | retention-policy: autogen 61 | limit: 50 62 | httpsEnabled: false 63 | 64 | #Spring config setting (current version not used) 65 | # boot: 66 | # #Spring boot admin settings 67 | # admin: 68 | # routes: 69 | # endpoints: env,metrics,trace,info,trace,heapdump,hystrix.stream,docs 70 | # #Timeintervalin ms to update the status of App 71 | # monitor: 72 | # perio: 10000 73 | # #LifeTime of App status in ms. 74 | # status-lifetime: 10000 75 | # #Connection Timeout in ms when App's status and info 76 | # connect-timeout: 2000 77 | # #Read Timeout in ms when App's status and info 78 | # read-timeout: 5000 79 | # metadata-keys-to-sanitize: .password$,.*secret$,.*key$,.$token$,.credentials.,.*vcap_services$ 80 | -------------------------------------------------------------------------------- /src/main/webapp/messages/message.properties: -------------------------------------------------------------------------------- 1 | #BAD_REQUEST 2 | 400=실행 중 오류가 발생했습니다. 3 | 4 | #UNAUTHORIZED 5 | 401=실행할 권한이 없습니다. 6 | 7 | #CONFLICT 8 | 409=중복된 데이터입니다. 9 | 10 | #INTERNAL_SERVER_ERROR 11 | 500=실행 중 오류가 발생했습니다. 12 | 13 | 14 | #CLOUD FOUNDRY 15 | 401_Unauthorized=요청을 실행할 권한이 없습니다 16 | Please_delete_the_spaces_associations_for_your_organizations.=공간을 먼저 삭제해 주십시오. 17 | You_are_not_authorized_to_perform_the_requested_action.=요청을 실행할 권한이 없습니다. 18 | You_are_not_authorized_to_perform_the_requested_action=요청을 실행할 권한이 없습니다. 19 | Please_delete_the_apps,_routes_associations_for_your_spaces.=앱이나 라우트를 먼저 삭제해 주십시요! 20 | Space_name_already_exists=공간이 이미 존재합니다. 21 | Application_not_found=앱이 존재하지 않습니다. 22 | The_organization_name_is_taken=조직 이름이 이미 존재합니다. 23 | The_app_space_binding_to_service_is_taken=서비스가 이미 연결되어 있습니다. 24 | Organization_not_found=조직이 존재하지 않습니다. 25 | User_not_found.=사용자를 찾을 수 없습니다. 26 | User_already_exist.=이미 존재하는 사용자 입니다. 27 | Your_new_password_cannot_be_the_same_as_the_old_password.=이전 패스워드와 동일한 패스워드는 사용할 수 없습니다. 28 | Old_password_is_incorrect=이전 패스워드가 일치하지 않습니다. 29 | Invalid_Auth_Token=토큰 권한이 없습니다. 30 | #조직 또는 스페이스가 존재하지 않거나, 해당 유저에게 권한이 없는 경우임. 31 | No_matching_organization_and_space_found_for_org=요청된 조직 또는 공간이 적절하지 않습니다. 32 | Domain_not_found_for_URI=도메인이 존재하지 않습니다. 33 | The_service_instance_could_not_be_found=서비스 인스턴스를 찾을 수 없습니다. 34 | No_value_present=파라미터 값이 적절하지 않습니다. 35 | 36 | #UAA 37 | Duplicated_group_display_name=이미 존재하는 권한 그룹 이름입니다. 38 | 39 | common.info.result.success=요청한 작업을 성공적으로 완료했습니다. 40 | common.info.result.fail=요청한 작업을 실패했습니다. 41 | common.info.result.fail.duplicated=중복된 값이 존재합니다. 42 | common.info.result.fail.duplicated.service.instance.name=중복된 서비스 이름이 존재합니다. 43 | common.info.result.fail.starter.delete=사용 중인 앱 템플릿 카탈로그가 존재합니다. 44 | common.info.empty.req.data=입력값이 부족합니다. 45 | common.system.error.message=시스템 에러가 발생했습니다. 관리자에게 문의하시기 바랍니다. 46 | The_app_space_could_not_be_found=스페이스가 존재하지 않습니다. 47 | The_app_could_not_be_found=앱이 존재하지 않습니다. 48 | Required_request_body_content_is_missing=요청 파라미터가 부족합니다. 49 | Unknown_request=앱이 존재하지 않습니다. 50 | Space_not_found=공간이 존재하지 않습니다. 51 | The_host_is_taken=라우트가 이미 존재합니다. 52 | Host_not_found_for_domain=라우트가 존재하지 않습니다. 53 | Please_delete_the_routes_associations_for_your_spaces.=라우트를 먼저 삭제해 주십시오. 54 | The_domain_is_invalid=적절하지 않은 도메인 이름입니다. 55 | Invalid_status='status' 값이 잘못 되었습니다. 56 | Domain_name_already_exist.=이미 존재하는 도메인 이름입니다. 57 | Can_not_remove_brokers_that_have_associated_service_instances=연결된 인스턴스가 있어 브로커를 삭제할수 없습니다. 58 | Service_broker_is_invalid=서비스 브로커가 유효하지 않습니다. 59 | _is_not_a_valid_URL=URL이 유효하지 않습니다. 60 | invite.info.success=초대에 성공하였습니다. 61 | invite.info.noCnt=초대할 정보가 없습니다. 62 | # -- 상 메세지들은 정상작동되지 않음 63 | 64 | 00000=테스트 65 | 66 | #신규등록(2018.5.25 CISS) 67 | 10001=호스트 라우트가 존재하지 않습니다. 68 | 270003=다른 서비스 브로커에서 사용중인 URL 입니다. 69 | 270010=연관된 서비스 인스턴스가 있는 브로커는 제거 할 수 없습니다. 70 | 71 | -------------------------------------------------------------------------------- /src/main/java/org/openpaas/paasta/portal/log/api/config/InfluxDBConfiguration.java: -------------------------------------------------------------------------------- 1 | package org.openpaas.paasta.portal.log.api.config; 2 | 3 | import okhttp3.OkHttpClient; 4 | import org.influxdb.InfluxDB; 5 | import org.influxdb.InfluxDBFactory; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 9 | import org.springframework.context.annotation.Bean; 10 | import org.springframework.context.annotation.Configuration; 11 | import org.springframework.core.io.ClassPathResource; 12 | 13 | import javax.net.ssl.SSLContext; 14 | import javax.net.ssl.TrustManager; 15 | import javax.net.ssl.TrustManagerFactory; 16 | import javax.net.ssl.X509TrustManager; 17 | import java.io.InputStream; 18 | import java.security.KeyStore; 19 | import java.security.cert.Certificate; 20 | import java.security.cert.CertificateFactory; 21 | 22 | @Configuration 23 | @EnableConfigurationProperties(InfluxDBProperties.class) 24 | public class InfluxDBConfiguration { 25 | 26 | private static final Logger LOGGER = LoggerFactory.getLogger(InfluxDBConfiguration.class); 27 | 28 | private final InfluxDBProperties properties; 29 | 30 | public InfluxDBConfiguration(InfluxDBProperties properties) { 31 | this.properties = properties; 32 | } 33 | 34 | @Bean 35 | public InfluxDB influxDB() throws Exception { 36 | InfluxDB influxDB = null; 37 | String url = properties.getUrl(); 38 | String username = properties.getUsername(); 39 | String password = properties.getPassword(); 40 | 41 | 42 | try { 43 | if(properties.getHttpsEnabled()) { 44 | ClassPathResource certificateResource = new ClassPathResource("certs/influx_cert.crt"); 45 | InputStream certificateInputStream = certificateResource.getInputStream(); 46 | 47 | TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); 48 | KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); 49 | keyStore.load(null); 50 | 51 | CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); 52 | Certificate certificate = certificateFactory.generateCertificate(certificateInputStream); 53 | keyStore.setCertificateEntry("influxdb", certificate); 54 | trustManagerFactory.init(keyStore); 55 | 56 | TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); 57 | 58 | SSLContext sslContext = SSLContext.getInstance("TLS"); 59 | sslContext.init(null, trustManagers, null); 60 | 61 | OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder(); 62 | okHttpClientBuilder.sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustManagers[0]); 63 | okHttpClientBuilder.hostnameVerifier((hostname, session) -> hostname.equalsIgnoreCase(properties.getIp())); 64 | 65 | influxDB = InfluxDBFactory.connect(url, username, password, okHttpClientBuilder); 66 | } 67 | else { 68 | influxDB = InfluxDBFactory.connect(url, username, password); 69 | } 70 | } catch (Exception e) { 71 | LOGGER.error(e.getMessage()); 72 | } 73 | 74 | influxDB.setDatabase(properties.getDatabase()); 75 | 76 | return influxDB; 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/org/openpaas/paasta/portal/log/api/config/security/SecurityConfig.java: -------------------------------------------------------------------------------- 1 | package org.openpaas.paasta.portal.log.api.config.security; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.beans.factory.annotation.Value; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.http.HttpMethod; 8 | import org.springframework.security.authentication.AuthenticationManager; 9 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 10 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 11 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 12 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 13 | import org.springframework.security.config.http.SessionCreationPolicy; 14 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 15 | 16 | /** 17 | * The type Security config. 18 | */ 19 | @Configuration 20 | @EnableWebSecurity 21 | public class SecurityConfig extends WebSecurityConfigurerAdapter { 22 | 23 | @Value("${spring.security.username}") 24 | String username; 25 | 26 | @Value("${spring.security.password}") 27 | String password; 28 | 29 | /** 30 | * Configure global. 31 | * 32 | * @throws Exception the exception 33 | */ 34 | 35 | @Bean 36 | public BCryptPasswordEncoder passwordEncoder() { 37 | return new BCryptPasswordEncoder(); 38 | } 39 | 40 | @Autowired 41 | protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 42 | auth 43 | .inMemoryAuthentication() 44 | .withUser(username).password(password).roles("USER"); 45 | } 46 | 47 | @Bean 48 | @Override 49 | public AuthenticationManager authenticationManagerBean() throws Exception { 50 | return super.authenticationManagerBean(); 51 | } 52 | 53 | @Override 54 | protected void configure(HttpSecurity http) throws Exception { 55 | http 56 | .csrf().disable() 57 | .sessionManagement() 58 | .sessionCreationPolicy(SessionCreationPolicy.STATELESS) 59 | .and() 60 | .authorizeRequests() 61 | .antMatchers("/external/**").permitAll() 62 | //Spring boot Admin 정보 접근 URL - 시작 63 | .antMatchers("/").permitAll() 64 | .antMatchers("/index").permitAll() 65 | .antMatchers("/info**").permitAll() 66 | .antMatchers("/env**").permitAll() 67 | .antMatchers("/metrics**").permitAll() 68 | .antMatchers("/trace**").permitAll() 69 | .antMatchers("/dump**").permitAll() 70 | .antMatchers("/jolokia**").permitAll() 71 | .antMatchers("/configprops**").permitAll() 72 | .antMatchers("/logfile**").permitAll() 73 | .antMatchers("/logging**").permitAll() 74 | .antMatchers("/refresh**").permitAll() 75 | .antMatchers("/flyway**").permitAll() 76 | .antMatchers("/liquibase**").permitAll() 77 | .antMatchers("/httptrace**").permitAll() 78 | .antMatchers("/threaddump**").permitAll() 79 | .antMatchers("/heapdump**").permitAll() 80 | .antMatchers("/loggers**").permitAll() 81 | .antMatchers("/auditevents**").permitAll() 82 | .antMatchers("/hystrix.stream**").permitAll() 83 | .antMatchers("/docs**").permitAll() 84 | .antMatchers("/jmx**").permitAll() 85 | .antMatchers("/management/**").permitAll() 86 | .antMatchers("/applications/**").permitAll() 87 | .antMatchers("/applications/**/**").permitAll() 88 | .antMatchers("/applications/**/**/**").permitAll() 89 | .antMatchers("/health**").permitAll() 90 | .antMatchers("/health/**").permitAll() 91 | //Spring boot Admin 정보 접근 URL - 끝 92 | .antMatchers("/**").hasRole("USER") 93 | .anyRequest().authenticated() 94 | .and() 95 | .httpBasic() 96 | .and() 97 | .csrf().disable().cors().disable(); 98 | // http 99 | // 100 | // .authorizeRequests() 101 | // .antMatchers("/external/**").permitAll() 102 | // .antMatchers("/**") 103 | // .permitAll() 104 | // .and() 105 | // .csrf().disable(); 106 | } 107 | 108 | } 109 | -------------------------------------------------------------------------------- /src/main/java/org/openpaas/paasta/portal/log/api/exception/GlobalControllerExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package org.openpaas.paasta.portal.log.api.exception; 2 | 3 | import org.apache.commons.io.IOUtils; 4 | import org.cloudfoundry.client.v2.ClientV2Exception; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.context.MessageSource; 9 | import org.springframework.http.HttpStatus; 10 | import org.springframework.web.bind.annotation.ControllerAdvice; 11 | import org.springframework.web.bind.annotation.ExceptionHandler; 12 | import org.springframework.web.bind.annotation.ResponseBody; 13 | 14 | import javax.servlet.http.HttpServletResponse; 15 | import java.io.IOException; 16 | import java.io.PrintWriter; 17 | import java.io.StringWriter; 18 | import java.util.Locale; 19 | 20 | /** 21 | * org.openpaas.paasta.portal.api.exception 22 | * 23 | * @author 김도준 24 | * @version 1.0 25 | * @since 2016.07.07 26 | */ 27 | @ControllerAdvice 28 | public class GlobalControllerExceptionHandler { 29 | 30 | private static final Logger LOGGER = LoggerFactory.getLogger(GlobalControllerExceptionHandler.class); 31 | 32 | private static final Locale DEFAULT_LOCALE = Locale.US; 33 | //private static final Locale DEFAULT_LOCALE = Locale.KOREA; 34 | 35 | @Autowired 36 | public MessageSource messageSource; 37 | 38 | 39 | @ExceptionHandler({IllegalArgumentException.class}) 40 | @ResponseBody 41 | public boolean handleCloudFoundryException(IllegalArgumentException ex, HttpServletResponse response) throws IOException { 42 | LOGGER.error("IllegalArgumentException : " + ex); 43 | String msg = ""; 44 | if (ex.getMessage().contains("Organization") && ex.getMessage().contains("not found")) { 45 | msg = messageSource.getMessage("Organization_not_found", null, DEFAULT_LOCALE); 46 | } else if (ex.getMessage().contains("Domain not found for URI")) { 47 | msg = messageSource.getMessage("Domain_not_found_for_URI", null, DEFAULT_LOCALE); 48 | } else if (ex.getMessage().contains("No matching organization and space found for org")) { 49 | msg = messageSource.getMessage("No_matching_organization_and_space_found_for_org", null, DEFAULT_LOCALE); 50 | } else if (ex.getMessage().contains("Host") && ex.getMessage().contains("not found for domain")) { 51 | msg = messageSource.getMessage("Host_not_found_for_domain", null, DEFAULT_LOCALE); 52 | } else { 53 | msg = messageSource.getMessage(HttpStatus.BAD_REQUEST.toString(), null, DEFAULT_LOCALE); 54 | } 55 | response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); 56 | return false; 57 | } 58 | 59 | @ExceptionHandler({ClientV2Exception.class}) 60 | @ResponseBody 61 | public void handleClientV2Exception(ClientV2Exception ex, HttpServletResponse response) throws Exception { 62 | 63 | LOGGER.error("CloudFoundryException : " + ex); 64 | 65 | //String[] message; 66 | String msg; 67 | try { 68 | msg = messageSource.getMessage(String.valueOf(ex.getCode()), null, "Not Found Message.", response.getLocale()); 69 | } catch (Exception e) { 70 | msg = getStackTraceString(e); 71 | } 72 | 73 | String message = "{\"message\":\"" + msg + "\"" + ",\"status\":\"" + HttpServletResponse.SC_BAD_REQUEST + "\"" + ",\"code\":\"" + ex.getCode() + "\"}"; 74 | 75 | response.resetBuffer(); 76 | response.setStatus(HttpServletResponse.SC_OK); 77 | response.setHeader("Content-Type", "application/json;charset=utf-8"); 78 | response.setContentType("application/json; charset=UTF-8"); 79 | response.getWriter().print(message); 80 | response.flushBuffer(); 81 | } 82 | 83 | 84 | 85 | 86 | @ResponseBody 87 | public boolean handleUnauthenticationException(Exception e, HttpServletResponse response) throws IOException { 88 | return errorResponse(e, HttpStatus.BAD_REQUEST, response); 89 | } 90 | 91 | 92 | @ExceptionHandler({Exception.class}) 93 | @ResponseBody 94 | public boolean handleAnyException(Exception e, HttpServletResponse response) throws IOException { 95 | return errorResponse(e, HttpStatus.INTERNAL_SERVER_ERROR, response); 96 | } 97 | 98 | private String getStackTraceString(Throwable t) { 99 | final StringWriter swriter = new StringWriter(); 100 | final PrintWriter pwriter = new PrintWriter(swriter); 101 | t.printStackTrace(pwriter); 102 | pwriter.flush(); 103 | 104 | final String result = swriter.toString(); 105 | IOUtils.closeQuietly(pwriter); 106 | IOUtils.closeQuietly(swriter); 107 | 108 | return result; 109 | } 110 | 111 | //common message 112 | private boolean errorResponse(Throwable throwable, HttpStatus status, HttpServletResponse response) throws IOException { 113 | LOGGER.info(response.toString()); 114 | //response.sendError(status.value(), messageSource.getMessage(status.toString(), null, DEFAULT_LOCALE)); 115 | final StringBuffer buffer = new StringBuffer(); 116 | buffer.append("Response : ").append(response.toString()).append('\n').append("Occured an exception : ").append(throwable.getMessage()).append('\n').append("Caused by... ").append('\n').append(getStackTraceString(throwable)); 117 | 118 | 119 | response.sendError(status.value(), buffer.toString()); 120 | LOGGER.error("Http status : {}", status.value()); 121 | LOGGER.error("Error message : {}", buffer.toString()); 122 | 123 | return false; 124 | } 125 | 126 | } 127 | 128 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /src/main/java/org/openpaas/paasta/portal/log/api/util/RestUtil.java: -------------------------------------------------------------------------------- 1 | package org.openpaas.paasta.portal.log.api.util; 2 | 3 | import org.apache.http.HttpHost; 4 | import org.apache.http.auth.AuthScope; 5 | import org.apache.http.auth.UsernamePasswordCredentials; 6 | import org.apache.http.client.HttpClient; 7 | import org.apache.http.conn.routing.HttpRoutePlanner; 8 | import org.apache.http.conn.ssl.SSLContextBuilder; 9 | import org.apache.http.conn.ssl.TrustSelfSignedStrategy; 10 | import org.apache.http.impl.client.BasicCredentialsProvider; 11 | import org.apache.http.impl.client.HttpClientBuilder; 12 | import org.apache.http.impl.client.HttpClients; 13 | import org.apache.http.impl.conn.DefaultProxyRoutePlanner; 14 | import org.cloudfoundry.client.lib.HttpProxyConfiguration; 15 | import org.cloudfoundry.client.lib.rest.*; 16 | import org.cloudfoundry.client.lib.util.JsonUtil; 17 | import org.springframework.http.client.ClientHttpRequestFactory; 18 | import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; 19 | import org.springframework.http.converter.*; 20 | import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; 21 | import org.springframework.web.client.RestTemplate; 22 | 23 | import java.security.GeneralSecurityException; 24 | import java.util.ArrayList; 25 | import java.util.Collections; 26 | import java.util.List; 27 | 28 | import static org.apache.http.conn.ssl.SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER; 29 | 30 | /** 31 | * Some helper utilities for creating classes used for the REST support. 32 | * 33 | * @author Thomas Risberg 34 | */ 35 | public class RestUtil { 36 | 37 | public RestTemplate createRestTemplate(HttpProxyConfiguration httpProxyConfiguration, boolean trustSelfSignedCerts) { 38 | RestTemplate restTemplate = new LoggingRestTemplate(); 39 | restTemplate.setRequestFactory(createRequestFactory(httpProxyConfiguration, trustSelfSignedCerts)); 40 | restTemplate.setErrorHandler(new CloudControllerResponseErrorHandler()); 41 | restTemplate.setMessageConverters(getHttpMessageConverters()); 42 | 43 | return restTemplate; 44 | } 45 | 46 | public ClientHttpRequestFactory createRequestFactory(HttpProxyConfiguration httpProxyConfiguration, boolean trustSelfSignedCerts) { 47 | HttpClientBuilder httpClientBuilder = HttpClients.custom().useSystemProperties(); 48 | 49 | if (trustSelfSignedCerts) { 50 | httpClientBuilder.setSslcontext(buildSslContext()); 51 | httpClientBuilder.setHostnameVerifier(BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); 52 | } 53 | 54 | if (httpProxyConfiguration != null) { 55 | HttpHost proxy = new HttpHost(httpProxyConfiguration.getProxyHost(), httpProxyConfiguration.getProxyPort()); 56 | httpClientBuilder.setProxy(proxy); 57 | 58 | if (httpProxyConfiguration.isAuthRequired()) { 59 | BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); 60 | credentialsProvider.setCredentials( 61 | new AuthScope(httpProxyConfiguration.getProxyHost(), httpProxyConfiguration.getProxyPort()), 62 | new UsernamePasswordCredentials(httpProxyConfiguration.getUsername(), httpProxyConfiguration.getPassword())); 63 | httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); 64 | } 65 | 66 | HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); 67 | httpClientBuilder.setRoutePlanner(routePlanner); 68 | } 69 | 70 | HttpClient httpClient = httpClientBuilder.build(); 71 | HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); 72 | 73 | return requestFactory; 74 | } 75 | 76 | // public CustomOauthClient createOauthClient(URL authorizationUrl, HttpProxyConfiguration httpProxyConfiguration, boolean trustSelfSignedCerts) { 77 | // return new CustomOauthClient(authorizationUrl, createRestTemplate(httpProxyConfiguration, trustSelfSignedCerts)); 78 | // } 79 | 80 | private javax.net.ssl.SSLContext buildSslContext() { 81 | try { 82 | return new SSLContextBuilder().useSSL().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(); 83 | } catch (GeneralSecurityException gse) { 84 | throw new RuntimeException("An error occurred setting up the SSLContext", gse); 85 | } 86 | } 87 | 88 | private List> getHttpMessageConverters() { 89 | List> messageConverters = new ArrayList>(); 90 | messageConverters.add(new ByteArrayHttpMessageConverter()); 91 | messageConverters.add(new StringHttpMessageConverter()); 92 | messageConverters.add(new ResourceHttpMessageConverter()); 93 | messageConverters.add(new UploadApplicationPayloadHttpMessageConverter()); 94 | messageConverters.add(getFormHttpMessageConverter()); 95 | messageConverters.add(new MappingJackson2HttpMessageConverter()); 96 | messageConverters.add(new LoggregatorHttpMessageConverter()); 97 | return messageConverters; 98 | } 99 | 100 | private FormHttpMessageConverter getFormHttpMessageConverter() { 101 | FormHttpMessageConverter formPartsMessageConverter = new CloudFoundryFormHttpMessageConverter(); 102 | formPartsMessageConverter.setPartConverters(getFormPartsMessageConverters()); 103 | return formPartsMessageConverter; 104 | } 105 | 106 | private List> getFormPartsMessageConverters() { 107 | List> partConverters = new ArrayList>(); 108 | StringHttpMessageConverter stringConverter = new StringHttpMessageConverter(); 109 | stringConverter.setSupportedMediaTypes(Collections.singletonList(JsonUtil.JSON_MEDIA_TYPE)); 110 | stringConverter.setWriteAcceptCharset(false); 111 | partConverters.add(stringConverter); 112 | partConverters.add(new ResourceHttpMessageConverter()); 113 | partConverters.add(new UploadApplicationPayloadHttpMessageConverter()); 114 | return partConverters; 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /src/main/java/org/openpaas/paasta/portal/log/api/common/TailSocket.java: -------------------------------------------------------------------------------- 1 | package org.openpaas.paasta.portal.log.api.common; 2 | 3 | import com.corundumstudio.socketio.AckRequest; 4 | import com.corundumstudio.socketio.Configuration; 5 | import com.corundumstudio.socketio.SocketIOClient; 6 | import com.corundumstudio.socketio.SocketIOServer; 7 | import com.corundumstudio.socketio.listener.ConnectListener; 8 | import com.corundumstudio.socketio.listener.DataListener; 9 | import com.corundumstudio.socketio.listener.DisconnectListener; 10 | import org.openpaas.paasta.portal.log.api.service.AppService; 11 | import org.slf4j.Logger; 12 | import org.slf4j.LoggerFactory; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.beans.factory.annotation.Value; 15 | import org.springframework.boot.CommandLineRunner; 16 | import org.springframework.core.env.Environment; 17 | import org.springframework.stereotype.Component; 18 | 19 | import java.net.*; 20 | import java.util.Enumeration; 21 | 22 | /** 23 | * Created by indra on 2018-05-09. 24 | */ 25 | @Component 26 | public class TailSocket implements CommandLineRunner { 27 | 28 | 29 | private static final Logger LOGGER = LoggerFactory.getLogger(TailSocket.class); 30 | 31 | @Autowired 32 | public Environment env; 33 | 34 | 35 | @Value("${tailsocket.port}") 36 | public Integer tailPort; 37 | 38 | 39 | @Autowired 40 | private AppService appService; 41 | 42 | @Override 43 | public void run(String... args) throws Exception { 44 | startServer(); 45 | } 46 | 47 | 48 | public void startServer() { 49 | String active = ""; 50 | String hostName = ""; 51 | 52 | Configuration config = new Configuration(); 53 | try { 54 | for (String str : env.getActiveProfiles()) { 55 | active = str; 56 | } 57 | LOGGER.info("active=" + active); 58 | 59 | if (active.equals("local")) { 60 | hostName = "localhost"; 61 | } else if (active.equals("dev")) { 62 | 63 | hostName = InetAddress.getLocalHost().getHostAddress(); 64 | try { 65 | 66 | Enumeration nienum = NetworkInterface.getNetworkInterfaces(); 67 | while (nienum.hasMoreElements()) { 68 | NetworkInterface ni = nienum.nextElement(); 69 | Enumeration kk = ni.getInetAddresses(); 70 | while (kk.hasMoreElements()) { 71 | InetAddress inetAddress = kk.nextElement(); 72 | if (!inetAddress.isLoopbackAddress() && 73 | !inetAddress.isLinkLocalAddress() && 74 | inetAddress.isSiteLocalAddress()) { 75 | 76 | hostName = inetAddress.getHostAddress().toString(); 77 | } 78 | } 79 | } 80 | } catch (SocketException e) { 81 | e.printStackTrace(); 82 | } 83 | 84 | LOGGER.info("InetAddress.getLocalHost().getHostAddress()=" + hostName); 85 | 86 | 87 | } else { 88 | hostName = "0.0.0.0"; 89 | } 90 | 91 | } catch (UnknownHostException e) { 92 | e.printStackTrace(); 93 | hostName = "localhost"; 94 | } 95 | 96 | LOGGER.info("Host ::: " + hostName); 97 | 98 | config.setHostname(hostName); 99 | config.setPort(tailPort); 100 | config.setContext("/tailLog"); 101 | final SocketIOServer server = new SocketIOServer(config); 102 | 103 | server.addConnectListener(new ConnectListener() { 104 | @Override 105 | public void onConnect(SocketIOClient client) { 106 | 107 | LOGGER.info("onConnected"); 108 | //String referer = client.getHandshakeData().getHttpHeaders().get("Referer"); 109 | String appName = client.getHandshakeData().getSingleUrlParam("name"); 110 | String orgName = client.getHandshakeData().getSingleUrlParam("org"); 111 | String spaceName = client.getHandshakeData().getSingleUrlParam("space"); 112 | 113 | try { 114 | appName = URLDecoder.decode(appName, "UTF-8"); 115 | orgName = URLDecoder.decode(orgName, "UTF-8"); 116 | spaceName = URLDecoder.decode(spaceName, "UTF-8"); 117 | }catch (Exception e){ 118 | 119 | } 120 | LOGGER.info(appName); 121 | LOGGER.info(spaceName); 122 | LOGGER.info(orgName); 123 | 124 | appService.socketTailLogs(client, appName, orgName, spaceName); 125 | } 126 | }); 127 | server.addDisconnectListener(new DisconnectListener() { 128 | @Override 129 | public void onDisconnect(SocketIOClient client) { 130 | 131 | LOGGER.info("onDisconnected"); 132 | } 133 | }); 134 | server.addEventListener("send", ChatObject.class, new DataListener() { 135 | 136 | @Override 137 | public void onData(SocketIOClient client, ChatObject data, AckRequest ackSender) throws Exception { 138 | LOGGER.info("onSend: " + data.toString()); 139 | server.getBroadcastOperations().sendEvent("message", data); 140 | } 141 | }); 142 | LOGGER.info("Starting server..."); 143 | serverInfo(server); 144 | server.start(); 145 | LOGGER.info("Server started..."); 146 | } 147 | 148 | public void serverInfo(SocketIOServer server){ 149 | LOGGER.info("HostName :::: " +server.getConfiguration().getHostname()); 150 | LOGGER.info("Context :::: " +server.getConfiguration().getContext()); 151 | LOGGER.info("Port :::: " + server.getConfiguration().getPort()); 152 | LOGGER.info("PingInterval :::: " +server.getConfiguration().getPingInterval()); 153 | LOGGER.info("PingTimeout :::: " +server.getConfiguration().getPingTimeout()); 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/main/java/org/openpaas/paasta/portal/log/api/common/Common.java: -------------------------------------------------------------------------------- 1 | package org.openpaas.paasta.portal.log.api.common; 2 | 3 | import org.cloudfoundry.client.lib.CloudCredentials; 4 | import org.cloudfoundry.client.lib.CloudFoundryClient; 5 | import org.cloudfoundry.doppler.DopplerClient; 6 | import org.cloudfoundry.operations.DefaultCloudFoundryOperations; 7 | import org.cloudfoundry.reactor.ConnectionContext; 8 | import org.cloudfoundry.reactor.DefaultConnectionContext; 9 | import org.cloudfoundry.reactor.TokenProvider; 10 | import org.cloudfoundry.reactor.client.ReactorCloudFoundryClient; 11 | import org.cloudfoundry.reactor.doppler.ReactorDopplerClient; 12 | import org.cloudfoundry.reactor.tokenprovider.ClientCredentialsGrantTokenProvider; 13 | import org.cloudfoundry.reactor.tokenprovider.PasswordGrantTokenProvider; 14 | import org.cloudfoundry.reactor.uaa.ReactorUaaClient; 15 | import org.cloudfoundry.uaa.UaaClient; 16 | import org.cloudfoundry.uaa.tokens.GetTokenByClientCredentialsRequest; 17 | import org.cloudfoundry.uaa.tokens.GetTokenByClientCredentialsResponse; 18 | import org.codehaus.jackson.map.ObjectMapper; 19 | import org.openpaas.paasta.portal.log.api.config.cloudfoundry.provider.TokenGrantTokenProvider; 20 | import org.slf4j.Logger; 21 | import org.slf4j.LoggerFactory; 22 | import org.springframework.beans.factory.annotation.Autowired; 23 | import org.springframework.beans.factory.annotation.Value; 24 | import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails; 25 | import org.springframework.security.oauth2.common.AuthenticationScheme; 26 | import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; 27 | 28 | import java.io.InputStream; 29 | import java.net.MalformedURLException; 30 | import java.net.URI; 31 | import java.net.URISyntaxException; 32 | import java.net.URL; 33 | import java.util.*; 34 | 35 | public class Common { 36 | 37 | private static final Logger LOGGER = LoggerFactory.getLogger(Common.class); 38 | 39 | public static final String NONE_VALUE = "NONE"; 40 | 41 | @Value("${cloudfoundry.cc.api.url}") 42 | public String apiTarget; 43 | 44 | @Value("${cloudfoundry.cc.api.uaaUrl}") 45 | public String uaaTarget; 46 | 47 | @Value("${cloudfoundry.cc.api.sslSkipValidation}") 48 | public boolean cfskipSSLValidation; 49 | 50 | @Value("${cloudfoundry.user.admin.username}") 51 | public String adminUserName; 52 | 53 | @Value("${cloudfoundry.user.admin.password}") 54 | public String adminPassword; 55 | 56 | public static final String AUTHORIZATION_HEADER_KEY = "cf-Authorization"; 57 | 58 | @Value("${cloudfoundry.user.uaaClient.clientId}") 59 | public String uaaClientId; 60 | 61 | @Value("${cloudfoundry.user.uaaClient.clientSecret}") 62 | public String uaaClientSecret; 63 | 64 | @Value("${cloudfoundry.user.uaaClient.adminClientId}") 65 | public String uaaAdminClientId; 66 | 67 | @Value("${cloudfoundry.user.uaaClient.adminClientSecret}") 68 | public String uaaAdminClientSecret; 69 | 70 | @Value("${cloudfoundry.user.uaaClient.skipSSLValidation}") 71 | public boolean skipSSLValidation; 72 | 73 | 74 | 75 | 76 | @Autowired 77 | DefaultConnectionContext connectionContext; 78 | 79 | @Autowired 80 | PasswordGrantTokenProvider tokenProvider; 81 | 82 | 83 | public ObjectMapper objectMapper = new ObjectMapper(); 84 | 85 | 86 | 87 | public URL getTargetURL(String target) throws MalformedURLException, URISyntaxException { 88 | return getTargetURI(target).toURL(); 89 | } 90 | 91 | private URI getTargetURI(String target) throws URISyntaxException { 92 | return new URI(target); 93 | } 94 | 95 | /** 96 | * get CloudFoundryClinet Object from token String 97 | * 98 | * @param token 99 | * @return CloudFoundryClinet 100 | */ 101 | public CloudFoundryClient getCloudFoundryClient(String token) throws MalformedURLException, URISyntaxException { 102 | 103 | return new CloudFoundryClient(getCloudCredentials(token), getTargetURL(apiTarget), true); 104 | } 105 | 106 | 107 | /** 108 | * get CloudCredentials Object from token String 109 | * 110 | * @param token 111 | * @return CloudCredentials 112 | */ 113 | public CloudCredentials getCloudCredentials(String token) { 114 | return new CloudCredentials(getOAuth2AccessToken(token), false); 115 | } 116 | 117 | /** 118 | * get CloudCredentials Object from id, password 119 | * 120 | * @param id 121 | * @param password 122 | * @return CloudCredentials 123 | */ 124 | public CloudCredentials getCloudCredentials(String id, String password) { 125 | 126 | LOGGER.info("============getCloudCredentials=============="); 127 | CloudCredentials test = new CloudCredentials(id, password); 128 | LOGGER.info("getToken :" + test.getToken()); 129 | LOGGER.info("getClientId :" + test.getClientId()); 130 | LOGGER.info("getClientSecret:" + test.getClientSecret()); 131 | LOGGER.info("getEmail :" + test.getEmail()); 132 | LOGGER.info("getPassword :" + test.getPassword()); 133 | LOGGER.info("getProxyUser :" + test.getProxyUser()); 134 | return test; 135 | 136 | } 137 | 138 | /** 139 | * get DefailtOAuth2AccessToken Object from token String 140 | * 141 | * @param token 142 | * @return 143 | */ 144 | private DefaultOAuth2AccessToken getOAuth2AccessToken(String token) { 145 | return new DefaultOAuth2AccessToken(token); 146 | } 147 | 148 | 149 | //credentials 세팅 150 | private ResourceOwnerPasswordResourceDetails getCredentials(String uaaClientId) { 151 | ResourceOwnerPasswordResourceDetails credentials = new ResourceOwnerPasswordResourceDetails(); 152 | credentials.setAccessTokenUri(uaaTarget + "/oauth/token?grant_type=client_credentials&response_type=token"); 153 | credentials.setClientAuthenticationScheme(AuthenticationScheme.header); 154 | 155 | credentials.setClientId(uaaClientId); 156 | 157 | if (uaaClientId.equals(uaaAdminClientId)) { 158 | credentials.setClientSecret(uaaAdminClientSecret); 159 | } 160 | return credentials; 161 | } 162 | 163 | 164 | /** 165 | * 요청 파라미터들의 빈값 또는 null값 확인을 하나의 메소드로 처리할 수 있도록 생성한 메소드 166 | * 요청 파라미터 중 빈값 또는 null값인 파라미터가 있는 경우, false를 리턴한다. 167 | * 168 | * @param params 169 | * @return 170 | */ 171 | public boolean stringNullCheck(String... params) { 172 | return Arrays.stream(params).allMatch(param -> null != param && !param.equals("")); 173 | } 174 | 175 | //요청 문자열 파라미터 중, 공백을 포함하고 있는 파라미터가 있을 경우 false를 리턴 176 | public boolean stringContainsSpaceCheck(String... params) { 177 | return Arrays.stream(params).allMatch(param -> !param.contains(" ")); 178 | } 179 | 180 | /** 181 | * Gets property value. 182 | * 183 | * @param key the key 184 | * @return property value 185 | * @throws Exception the exception 186 | */ 187 | public static String getPropertyValue(String key) throws Exception { 188 | return getPropertyValue(key, "/config.properties"); 189 | } 190 | 191 | 192 | /** 193 | * Gets process property value. 194 | * 195 | * @param key the key 196 | * @param configFileName the config file name 197 | * @return property value 198 | * @throws Exception the exception 199 | */ 200 | private static String getProcPropertyValue(String key, String configFileName) throws Exception { 201 | if (NONE_VALUE.equals(configFileName)) return ""; 202 | 203 | Properties prop = new Properties(); 204 | 205 | try (InputStream inputStream = ClassLoader.class.getResourceAsStream(configFileName)) { 206 | prop.load(inputStream); 207 | } catch (Exception e) { 208 | e.printStackTrace(); 209 | } 210 | 211 | return prop.getProperty(key); 212 | } 213 | 214 | /** 215 | * Gets property value. 216 | * 217 | * @param key the key 218 | * @param configFileName the config file name 219 | * @return property value 220 | * @throws Exception the exception 221 | */ 222 | public static String getPropertyValue(String key, String configFileName) throws Exception { 223 | return getProcPropertyValue(key, Optional.ofNullable(configFileName).orElse(NONE_VALUE)); 224 | } 225 | 226 | 227 | public static String convertApiUrl(String url) { 228 | return url.replace("https://", "").replace("http://", ""); 229 | } 230 | 231 | 232 | /** 233 | * DefaultCloudFoundryOperations을 생성하여, 반환한다. 234 | * 235 | * @param connectionContext 236 | * @param tokenProvider 237 | * @return DefaultCloudFoundryOperations 238 | */ 239 | public static DefaultCloudFoundryOperations cloudFoundryOperations(ConnectionContext connectionContext, TokenProvider tokenProvider) { 240 | return cloudFoundryOperations(cloudFoundryClient(connectionContext, tokenProvider), dopplerClient(connectionContext, tokenProvider), uaaClient(connectionContext, tokenProvider)); 241 | } 242 | 243 | /** 244 | * DefaultCloudFoundryOperations을 생성하여, 반환한다. 245 | * 246 | * @param cloudFoundryClient 247 | * @param dopplerClient 248 | * @param uaaClient 249 | * @return DefaultCloudFoundryOperations 250 | */ 251 | public static DefaultCloudFoundryOperations cloudFoundryOperations(org.cloudfoundry.client.CloudFoundryClient cloudFoundryClient, DopplerClient dopplerClient, UaaClient uaaClient) { 252 | return DefaultCloudFoundryOperations.builder().cloudFoundryClient(cloudFoundryClient).dopplerClient(dopplerClient).uaaClient(uaaClient).build(); 253 | } 254 | 255 | /** 256 | * DefaultCloudFoundryOperations을 생성하여, 반환한다. 257 | * 258 | * @param connectionContext 259 | * @param tokenProvider 260 | * @param org 261 | * @param space 262 | * @return DefaultCloudFoundryOperations 263 | */ 264 | public static DefaultCloudFoundryOperations cloudFoundryOperations(ConnectionContext connectionContext, TokenProvider tokenProvider, String org, String space) { 265 | return cloudFoundryOperations(cloudFoundryClient(connectionContext, tokenProvider), dopplerClient(connectionContext, tokenProvider), uaaClient(connectionContext, tokenProvider), org, space); 266 | } 267 | 268 | /** 269 | * DefaultCloudFoundryOperations을 생성하여, 반환한다. 270 | * 271 | * @param cloudFoundryClient 272 | * @param dopplerClient 273 | * @param uaaClient 274 | * @param org 275 | * @param space 276 | * @return DefaultCloudFoundryOperations 277 | */ 278 | public static DefaultCloudFoundryOperations cloudFoundryOperations(org.cloudfoundry.client.CloudFoundryClient cloudFoundryClient, DopplerClient dopplerClient, UaaClient uaaClient, String org, String space) { 279 | return DefaultCloudFoundryOperations.builder().cloudFoundryClient(cloudFoundryClient).dopplerClient(dopplerClient).uaaClient(uaaClient).organization(org).space(space).build(); 280 | } 281 | 282 | /** 283 | * ReactorCloudFoundryClient 생성하여, 반환한다. 284 | * 285 | * @param connectionContext 286 | * @param tokenProvider 287 | * @return DefaultCloudFoundryOperations 288 | */ 289 | public static ReactorCloudFoundryClient cloudFoundryClient(ConnectionContext connectionContext, TokenProvider tokenProvider) { 290 | return ReactorCloudFoundryClient.builder().connectionContext(connectionContext).tokenProvider(tokenProvider).build(); 291 | } 292 | 293 | 294 | public static ReactorDopplerClient dopplerClient(ConnectionContext connectionContext, TokenProvider tokenProvider) { 295 | return ReactorDopplerClient.builder().connectionContext(connectionContext).tokenProvider(tokenProvider).build(); 296 | } 297 | 298 | public static ReactorUaaClient uaaClient(ConnectionContext connectionContext, TokenProvider tokenProvider) { 299 | return ReactorUaaClient.builder().connectionContext(connectionContext).tokenProvider(tokenProvider).build(); 300 | } 301 | 302 | public static ReactorUaaClient uaaClient(ConnectionContext connectionContext, String clientId, String clientSecret) { 303 | return ReactorUaaClient.builder().connectionContext(connectionContext).tokenProvider(ClientCredentialsGrantTokenProvider.builder().clientId(clientId).clientSecret(clientSecret).build()).build(); 304 | } 305 | 306 | // UAA Admin Client 307 | public static ReactorUaaClient uaaAdminClient(ConnectionContext connectionContext, String apiTarget, String token, String uaaAdminClientId, String uaaAdminClientSecret) { 308 | ReactorUaaClient reactorUaaClient = Common.uaaClient(connectionContext, tokenProvider(token)); 309 | GetTokenByClientCredentialsResponse getTokenByClientCredentialsResponse = reactorUaaClient.tokens().getByClientCredentials(GetTokenByClientCredentialsRequest.builder().clientId(uaaAdminClientId).clientSecret(uaaAdminClientSecret).build()).block(); 310 | return Common.uaaClient(connectionContext, tokenProvider(getTokenByClientCredentialsResponse.getAccessToken())); 311 | } 312 | 313 | private static final ThreadLocal connectionContextThreadLocal = new ThreadLocal<>(); 314 | 315 | 316 | 317 | public DefaultConnectionContext connectionContext() { 318 | return connectionContext; 319 | } 320 | 321 | public static DefaultConnectionContext crateConnectionContext(String apiUrl, boolean skipSSLValidation) { 322 | DefaultConnectionContext connectionContext = peekConnectionContext(); 323 | if (null != connectionContext) { 324 | boolean isEqual = connectionContext.getApiHost().equals(convertApiUrl(apiUrl)) && connectionContext.getSkipSslValidation().get() == skipSSLValidation; 325 | if (!isEqual) { 326 | removeConnectionContext(); 327 | connectionContext = null; 328 | } 329 | } 330 | 331 | if (null == connectionContext) { 332 | connectionContext = DefaultConnectionContext.builder().apiHost(convertApiUrl(apiUrl)).skipSslValidation(skipSSLValidation).build(); 333 | pushConnectionContext(connectionContext); 334 | } 335 | 336 | return connectionContext; 337 | } 338 | 339 | 340 | 341 | 342 | private static DefaultConnectionContext peekConnectionContext() { 343 | return connectionContextThreadLocal.get(); 344 | } 345 | 346 | private static void pushConnectionContext(DefaultConnectionContext connectionContext) { 347 | connectionContextThreadLocal.set(connectionContext); 348 | LOGGER.info("Create connection context and push thread local : DefalutConnectionContext@{}", Integer.toHexString(connectionContext.hashCode())); 349 | } 350 | 351 | private static void removeConnectionContext() { 352 | disposeConnectionContext(connectionContextThreadLocal.get()); 353 | connectionContextThreadLocal.remove(); 354 | } 355 | 356 | 357 | 358 | private static void disposeConnectionContext(DefaultConnectionContext connectionContext) { 359 | try { 360 | if (null != connectionContext) connectionContext.dispose(); 361 | } catch (Exception ignore) { 362 | } 363 | } 364 | 365 | public static TokenGrantTokenProvider tokenProvider(String token) { 366 | try { 367 | if (token.indexOf("bearer") < 0) { 368 | token = "bearer " + token; 369 | } 370 | return new TokenGrantTokenProvider(token); 371 | } catch (Exception e) { 372 | return null; 373 | } 374 | } 375 | 376 | public static TokenProvider tokenProviderWithDefault(String token, TokenProvider defaultTokenProvider) { 377 | if (null == token) return defaultTokenProvider; 378 | else if (token.trim().length() <= 0) return defaultTokenProvider; 379 | 380 | return tokenProvider(token); 381 | } 382 | 383 | /** 384 | * token을 제공하는 클레스 사용자 임의의 clientId를 사용하며, 385 | * user token, client token을 모두 얻을 수 있다. 386 | * 387 | * @param username 388 | * @param password 389 | * @return 390 | */ 391 | public static PasswordGrantTokenProvider tokenProvider(String username, String password) { 392 | return PasswordGrantTokenProvider.builder().password(password).username(username).build(); 393 | } 394 | 395 | public PasswordGrantTokenProvider tokenProvider() { 396 | return tokenProvider; 397 | } 398 | } 399 | -------------------------------------------------------------------------------- /src/test/java/org/openpaas/paasta/portal/log/api/service/BuildPackServiceTest.java: -------------------------------------------------------------------------------- 1 | //package org.openpaas.paasta.portal.api.service; 2 | // 3 | //import org.cloudfoundry.client.lib.CloudCredentials; 4 | //import org.cloudfoundry.client.CloudFoundryClient; 5 | //import org.cloudfoundry.operations.CloudFoundryOperations; 6 | //import org.cloudfoundry.client.v2.applications.ApplicationsV2; 7 | //import org.cloudfoundry.client.v2.buildpacks.Buildpacks; 8 | //import org.cloudfoundry.client.v2.buildpacks.UpdateBuildpackRequest; 9 | //import org.cloudfoundry.client.v2.buildpacks.UpdateBuildpackResponse; 10 | //import org.cloudfoundry.identity.uaa.api.client.UaaClientOperations; 11 | //import org.cloudfoundry.identity.uaa.api.group.UaaGroupOperations; 12 | //import org.cloudfoundry.identity.uaa.api.user.UaaUserOperations; 13 | //import org.cloudfoundry.operations.DefaultCloudFoundryOperations; 14 | //import org.cloudfoundry.reactor.ConnectionContext; 15 | //import org.cloudfoundry.reactor.DefaultConnectionContext; 16 | //import org.cloudfoundry.reactor.TokenProvider; 17 | //import org.cloudfoundry.reactor.client.ReactorCloudFoundryClient; 18 | //import org.cloudfoundry.reactor.doppler.ReactorDopplerClient; 19 | //import org.cloudfoundry.reactor.tokenprovider.PasswordGrantTokenProvider; 20 | //import org.cloudfoundry.reactor.uaa.ReactorUaaClient; 21 | //import org.codehaus.jackson.map.ObjectMapper; 22 | //import org.junit.Assert; 23 | //import org.junit.Before; 24 | //import org.junit.FixMethodOrder; 25 | //import org.junit.Test; 26 | //import org.junit.runner.RunWith; 27 | //import org.junit.runners.MethodSorters; 28 | //import org.mockito.InjectMocks; 29 | //import org.mockito.Mock; 30 | //import org.mockito.Mockito; 31 | //import org.mockito.MockitoAnnotations; 32 | //import org.openpaas.paasta.portal.api.common.Common; 33 | //import org.openpaas.paasta.portal.api.config.TestConfig; 34 | //import org.openpaas.paasta.portal.api.config.cloudfoundry.provider.TokenGrantTokenProvider; 35 | //import org.openpaas.paasta.portal.api.model.BuildPack; 36 | //import org.powermock.api.mockito.PowerMockito; 37 | //import org.powermock.core.classloader.annotations.PowerMockIgnore; 38 | //import org.powermock.core.classloader.annotations.PrepareForTest; 39 | //import org.powermock.modules.junit4.PowerMockRunner; 40 | //import org.powermock.reflect.Whitebox; 41 | //import org.slf4j.Logger; 42 | //import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 43 | //import org.springframework.boot.test.context.SpringBootTest; 44 | //import org.springframework.boot.test.mock.mockito.MockBean; 45 | //import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 46 | //import org.springframework.cloud.netflix.feign.EnableFeignClients; 47 | //import org.springframework.context.annotation.Bean; 48 | //import org.springframework.context.annotation.Configuration; 49 | //import org.springframework.context.expression.EnvironmentAccessor; 50 | //import org.springframework.test.context.junit4.SpringRunner; 51 | //import reactor.core.publisher.Mono; 52 | // 53 | //import java.net.URL; 54 | //import java.util.HashMap; 55 | //import java.util.Map; 56 | //import java.util.UUID; 57 | // 58 | //import static org.mockito.Mockito.*; 59 | // 60 | ////@RunWith(SpringRunner.class) 61 | //@PowerMockIgnore({"org.apache.http.conn.ssl.*", "javax.net.ssl.*" , "javax.crypto.*"}) 62 | //@PrepareForTest({Common.class}) 63 | //@RunWith(PowerMockRunner.class) 64 | //@SpringBootTest 65 | //@FixMethodOrder(MethodSorters.NAME_ASCENDING) 66 | //public class BuildPackServiceTest extends TestConfig { 67 | // @Mock 68 | // Logger LOGGER; 69 | // @Mock 70 | // LoginService loginService; 71 | // @Mock 72 | // ObjectMapper objectMapper; 73 | // @Mock 74 | // ThreadLocal connectionContextThreadLocal; 75 | // @InjectMocks 76 | // private final BuildPackService buildPackService = new BuildPackService(); 77 | // 78 | // private final CloudFoundryOperations cloudFoundryOperations = mock(CloudFoundryOperations.class); 79 | // 80 | //// private final CloudFoundryApplication application; 81 | // 82 | //// @Mock 83 | //// private CloudFoundryClient cloudFoundryClient; 84 | // 85 | //// @Mock 86 | // Common common; 87 | // 88 | // @Mock 89 | // Buildpacks buildpacks; 90 | // 91 | // private final ApplicationsV2 applications = mock(ApplicationsV2.class, RETURNS_SMART_NULLS); 92 | // 93 | // private final CloudFoundryClient cloudFoundryClient = mock(CloudFoundryClient.class, RETURNS_SMART_NULLS); 94 | // 95 | //// private final ReactorCloudFoundryClient reactorCloudFoundryClient = mock(ReactorCloudFoundryClient.class, RETURNS_SMART_NULLS); 96 | // 97 | // private CloudFoundryClient cfClient; 98 | // private CloudFoundryOperations cfOps; 99 | // 100 | // ConnectionContext connectionContext; 101 | // 102 | // @Before 103 | // public void setUp() { 104 | // MockitoAnnotations.initMocks(this); 105 | // 106 | // common = PowerMockito.spy(new Common()); 107 | // 108 | //// ConnectionContext connectionContext = DefaultConnectionContext.builder().apiHost("apiHost").skipSslValidation(true).build(); 109 | //// TokenProvider tokenProvider = PasswordGrantTokenProvider.builder().username("admin").password("admin").build(); 110 | //// cfClient = ReactorCloudFoundryClient.builder().connectionContext(connectionContext).tokenProvider(tokenProvider).build(); 111 | //// cfOps = DefaultCloudFoundryOperations.builder().cloudFoundryClient(cfClient).build(); 112 | // } 113 | // 114 | //// @Test 115 | //// public void testGetBuildPacks() throws Exception { 116 | //// when(loginService.cloudFoundryClient(any(), any())).thenReturn(null); 117 | //// when(loginService.connectionContext()).thenReturn(null); 118 | //// when(loginService.tokenProvider(any(), any())).thenReturn(null); 119 | //// 120 | //// Map result = buildPackService.getBuildPacks(); 121 | //// Assert.assertEquals(new HashMap() {{ 122 | //// put("String", null); 123 | //// }}, result); 124 | //// } 125 | // 126 | // @Test 127 | // public void testUpdateBuildPack() throws Exception { 128 | // BuildPack buildPack = new BuildPack(); 129 | // buildPack.setGuid(UUID.fromString("f89b1ef6-7416-4d12-b492-c10fdaaff632")); 130 | // buildPack.setPosition(1); 131 | // buildPack.setEnable(true); 132 | // buildPack.setLock(true); 133 | // 134 | // 135 | // 136 | // BuildPackService service = mock(BuildPackService.class); 137 | //// Common com = Whitebox.invokeConstructor(Common.class); 138 | //// Common com = mock(Common.class); 139 | // PowerMockito.mockStatic(Common.class); 140 | // System.out.println("==1"); 141 | // DefaultConnectionContext defaultConnectionContext = DefaultConnectionContext.builder().apiHost("api.115.68.46.187.xip.io").build(); 142 | // System.out.println("==2"); 143 | // PowerMockito.when(common.connectionContext()).thenReturn(defaultConnectionContext); 144 | // 145 | // 146 | // System.out.println("==3"); 147 | // when(service.updateBuildPack(buildPack)).thenReturn(true); 148 | // System.out.println("==4"); 149 | // 150 | // PowerMockito.when(service.updateBuildPack(buildPack)).thenReturn(true); 151 | // System.out.println("==5"); 152 | // boolean result = service.updateBuildPack(buildPack); 153 | // System.out.println("==6"); 154 | // Assert.assertEquals(true, result); 155 | // System.out.println("==7"); 156 | // 157 | // 158 | //// Mono response = Mono.just(UpdateBuildpackResponse.builder().build()); 159 | //// 160 | //// when(cfClient.buildpacks().update(UpdateBuildpackRequest.builder() 161 | //// .buildpackId("f89b1ef6-7416-4d12-b492-c10fdaaff632") 162 | //// .position(1) 163 | //// .enabled(true) 164 | //// .locked(true) 165 | //// .build())).thenReturn(response); 166 | // 167 | // 168 | // 169 | //// when(buildpacks.update(UpdateBuildpackRequest.builder() 170 | //// .buildpackId("f89b1ef6-7416-4d12-b492-c10fdaaff632") 171 | //// .position(1) 172 | //// .enabled(true) 173 | //// .locked(true) 174 | //// .build() 175 | //// )); 176 | //// BuildPackService service = mock(BuildPackService.class); 177 | //// when(service.updateBuildPack(buildPack)).thenReturn(true); 178 | //// 179 | //// boolean result = service.updateBuildPack(buildPack); 180 | //// Assert.assertEquals(true, result); 181 | // 182 | // 183 | // 184 | // 185 | //// when(loginService.cloudFoundryClient(any(), any())).thenReturn(null); 186 | //// when(loginService.connectionContext()).thenReturn(null); 187 | //// when(loginService.tokenProvider(any(), any())).thenReturn(null); 188 | //// 189 | //// boolean result = buildPackService.updateBuildPack(new BuildPack()); 190 | //// Assert.assertEquals(true, result); 191 | // } 192 | // 193 | //// @Test 194 | //// public void testGetToken() throws Exception { 195 | //// when(loginService.login(any(), any())).thenReturn(null); 196 | //// 197 | //// String result = buildPackService.getToken(); 198 | //// Assert.assertEquals("replaceMeWithExpectedResult", result); 199 | //// } 200 | //// 201 | //// @Test 202 | //// public void testGetTargetURL() throws Exception { 203 | //// when(loginService.getTargetURI(any())).thenReturn(null); 204 | //// 205 | //// URL result = buildPackService.getTargetURL("target"); 206 | //// Assert.assertEquals(null, result); 207 | //// } 208 | //// 209 | //// @Test 210 | //// public void testGetCloudFoundryClient() throws Exception { 211 | //// when(loginService.getTargetURL(any())).thenReturn(null); 212 | //// when(loginService.getTargetURI(any())).thenReturn(null); 213 | //// when(loginService.getCloudCredentials(any())).thenReturn(null); 214 | //// when(loginService.getOAuth2AccessToken(any())).thenReturn(null); 215 | //// 216 | //// CloudFoundryClient result = buildPackService.getCloudFoundryClient("token"); 217 | //// Assert.assertEquals(null, result); 218 | //// } 219 | //// 220 | //// @Test 221 | //// public void testGetCloudFoundryClient2() throws Exception { 222 | //// when(loginService.getTargetURL(any())).thenReturn(null); 223 | //// when(loginService.getTargetURI(any())).thenReturn(null); 224 | //// when(loginService.getCloudCredentials(any())).thenReturn(null); 225 | //// when(loginService.getOAuth2AccessToken(any())).thenReturn(null); 226 | //// 227 | //// CloudFoundryClient result = buildPackService.getCloudFoundryClient("token", "organization", "space"); 228 | //// Assert.assertEquals(null, result); 229 | //// } 230 | //// 231 | //// @Test 232 | //// public void testGetCloudFoundryClient3() throws Exception { 233 | //// when(loginService.getTargetURL(any())).thenReturn(null); 234 | //// when(loginService.getTargetURI(any())).thenReturn(null); 235 | //// when(loginService.getCloudCredentials(any(), any())).thenReturn(null); 236 | //// 237 | //// CloudFoundryClient result = buildPackService.getCloudFoundryClient("id", "password"); 238 | //// Assert.assertEquals(null, result); 239 | //// } 240 | //// 241 | //// @Test 242 | //// public void testGetCloudFoundryClient4() throws Exception { 243 | //// when(loginService.getTargetURL(any())).thenReturn(null); 244 | //// when(loginService.getTargetURI(any())).thenReturn(null); 245 | //// when(loginService.getCloudCredentials(any(), any())).thenReturn(null); 246 | //// 247 | //// CloudFoundryClient result = buildPackService.getCloudFoundryClient("id", "password", "organization", "space"); 248 | //// Assert.assertEquals(null, result); 249 | //// } 250 | //// 251 | //// @Test 252 | //// public void testGetCloudCredentials() throws Exception { 253 | //// when(loginService.getOAuth2AccessToken(any())).thenReturn(null); 254 | //// 255 | //// CloudCredentials result = buildPackService.getCloudCredentials("token"); 256 | //// Assert.assertEquals(null, result); 257 | //// } 258 | //// 259 | //// @Test 260 | //// public void testGetCloudCredentials2() throws Exception { 261 | //// CloudCredentials result = buildPackService.getCloudCredentials("id", "password"); 262 | //// Assert.assertEquals(null, result); 263 | //// } 264 | //// 265 | //// @Test 266 | //// public void testGetUaaUserOperations() throws Exception { 267 | //// when(loginService.getUaaConnection(any())).thenReturn(null); 268 | //// when(loginService.getCredentials(any())).thenReturn(null); 269 | //// 270 | //// UaaUserOperations result = buildPackService.getUaaUserOperations("uaaClientId"); 271 | //// Assert.assertEquals(null, result); 272 | //// } 273 | //// 274 | //// @Test 275 | //// public void testGetUaaGroupOperations() throws Exception { 276 | //// when(loginService.getUaaConnection(any())).thenReturn(null); 277 | //// when(loginService.getCredentials(any())).thenReturn(null); 278 | //// 279 | //// UaaGroupOperations result = buildPackService.getUaaGroupOperations("uaaClientId"); 280 | //// Assert.assertEquals(null, result); 281 | //// } 282 | //// 283 | //// @Test 284 | //// public void testGetUaaClientOperations() throws Exception { 285 | //// when(loginService.getUaaConnection(any())).thenReturn(null); 286 | //// when(loginService.getCredentials(any())).thenReturn(null); 287 | //// 288 | //// UaaClientOperations result = buildPackService.getUaaClientOperations("uaaClientId"); 289 | //// Assert.assertEquals(null, result); 290 | //// } 291 | //// 292 | //// @Test 293 | //// public void testStringNullCheck() throws Exception { 294 | //// boolean result = buildPackService.stringNullCheck("params"); 295 | //// Assert.assertEquals(true, result); 296 | //// } 297 | //// 298 | //// @Test 299 | //// public void testStringContainsSpaceCheck() throws Exception { 300 | //// boolean result = buildPackService.stringContainsSpaceCheck("params"); 301 | //// Assert.assertEquals(true, result); 302 | //// } 303 | //// 304 | //// @Test 305 | //// public void testGetPropertyValue() throws Exception { 306 | //// when(loginService.getProcPropertyValue(any(), any())).thenReturn("getProcPropertyValueResponse"); 307 | //// when(loginService.getPropertyValue(any(), any())).thenReturn("getPropertyValueResponse"); 308 | //// 309 | //// String result = BuildPackService.getPropertyValue("key"); 310 | //// Assert.assertEquals("replaceMeWithExpectedResult", result); 311 | //// } 312 | //// 313 | //// @Test 314 | //// public void testGetPropertyValue2() throws Exception { 315 | //// when(loginService.getProcPropertyValue(any(), any())).thenReturn("getProcPropertyValueResponse"); 316 | //// 317 | //// String result = BuildPackService.getPropertyValue("key", "configFileName"); 318 | //// Assert.assertEquals("replaceMeWithExpectedResult", result); 319 | //// } 320 | //// 321 | //// @Test 322 | //// public void testConvertApiUrl() throws Exception { 323 | //// String result = BuildPackService.convertApiUrl("url"); 324 | //// Assert.assertEquals("replaceMeWithExpectedResult", result); 325 | //// } 326 | //// 327 | //// @Test 328 | //// public void testCloudFoundryOperations() throws Exception { 329 | //// when(loginService.cloudFoundryOperations(any(), any(), any())).thenReturn(null); 330 | //// when(loginService.cloudFoundryClient(any(), any())).thenReturn(null); 331 | //// when(loginService.dopplerClient(any(), any())).thenReturn(null); 332 | //// when(loginService.uaaClient(any(), any())).thenReturn(null); 333 | //// 334 | //// DefaultCloudFoundryOperations result = BuildPackService.cloudFoundryOperations(null, new TokenGrantTokenProvider("token")); 335 | //// Assert.assertEquals(null, result); 336 | //// } 337 | //// 338 | //// @Test 339 | //// public void testCloudFoundryOperations2() throws Exception { 340 | //// DefaultCloudFoundryOperations result = BuildPackService.cloudFoundryOperations(null, null, null); 341 | //// Assert.assertEquals(null, result); 342 | //// } 343 | //// 344 | //// @Test 345 | //// public void testCloudFoundryOperations3() throws Exception { 346 | //// when(loginService.cloudFoundryOperations(any(), any(), any(), any(), any())).thenReturn(null); 347 | //// when(loginService.cloudFoundryClient(any(), any())).thenReturn(null); 348 | //// when(loginService.dopplerClient(any(), any())).thenReturn(null); 349 | //// when(loginService.uaaClient(any(), any())).thenReturn(null); 350 | //// 351 | //// DefaultCloudFoundryOperations result = BuildPackService.cloudFoundryOperations(null, new TokenGrantTokenProvider("token"), "org", "space"); 352 | //// Assert.assertEquals(null, result); 353 | //// } 354 | //// 355 | //// @Test 356 | //// public void testCloudFoundryOperations4() throws Exception { 357 | //// DefaultCloudFoundryOperations result = BuildPackService.cloudFoundryOperations(null, null, null, "org", "space"); 358 | //// Assert.assertEquals(null, result); 359 | //// } 360 | //// 361 | //// @Test 362 | //// public void testCloudFoundryClient() throws Exception { 363 | //// ReactorCloudFoundryClient result = BuildPackService.cloudFoundryClient(null, new TokenGrantTokenProvider("token")); 364 | //// Assert.assertEquals(null, result); 365 | //// } 366 | //// 367 | //// @Test 368 | //// public void testDopplerClient() throws Exception { 369 | //// ReactorDopplerClient result = BuildPackService.dopplerClient(null, new TokenGrantTokenProvider("token")); 370 | //// Assert.assertEquals(null, result); 371 | //// } 372 | //// 373 | //// @Test 374 | //// public void testUaaClient() throws Exception { 375 | //// ReactorUaaClient result = BuildPackService.uaaClient(null, new TokenGrantTokenProvider("token")); 376 | //// Assert.assertEquals(null, result); 377 | //// } 378 | //// 379 | //// @Test 380 | //// public void testUaaClient2() throws Exception { 381 | //// ReactorUaaClient result = BuildPackService.uaaClient(null, "clientId", "clientSecret"); 382 | //// Assert.assertEquals(null, result); 383 | //// } 384 | //// 385 | //// @Test 386 | //// public void testUaaAdminClient() throws Exception { 387 | //// when(loginService.convertApiUrl(any())).thenReturn("convertApiUrlResponse"); 388 | //// when(loginService.uaaClient(any(), any())).thenReturn(null); 389 | //// when(loginService.peekConnectionContext()).thenReturn(null); 390 | //// when(loginService.connectionContext(any(), anyBoolean())).thenReturn(null); 391 | //// when(loginService.tokenProvider(any())).thenReturn(new TokenGrantTokenProvider("token")); 392 | //// 393 | //// ReactorUaaClient result = BuildPackService.uaaAdminClient("apiTarget", "token", "uaaAdminClientId", "uaaAdminClientSecret"); 394 | //// Assert.assertEquals(null, result); 395 | //// } 396 | //// 397 | //// @Test 398 | //// public void testConnectionContext() throws Exception { 399 | //// when(loginService.convertApiUrl(any())).thenReturn("convertApiUrlResponse"); 400 | //// when(loginService.peekConnectionContext()).thenReturn(null); 401 | //// when(loginService.connectionContext(any(), anyBoolean())).thenReturn(null); 402 | //// 403 | //// DefaultConnectionContext result = buildPackService.connectionContext(); 404 | //// Assert.assertEquals(null, result); 405 | //// } 406 | //// 407 | //// @Test 408 | //// public void testConnectionContext2() throws Exception { 409 | //// when(loginService.convertApiUrl(any())).thenReturn("convertApiUrlResponse"); 410 | //// when(loginService.peekConnectionContext()).thenReturn(null); 411 | //// 412 | //// DefaultConnectionContext result = BuildPackService.connectionContext("apiUrl", true); 413 | //// Assert.assertEquals(null, result); 414 | //// } 415 | //// 416 | //// @Test 417 | //// public void testTokenProvider() throws Exception { 418 | //// TokenGrantTokenProvider result = BuildPackService.tokenProvider("token"); 419 | //// Assert.assertEquals(new TokenGrantTokenProvider("token"), result); 420 | //// } 421 | //// 422 | //// @Test 423 | //// public void testTokenProviderWithDefault() throws Exception { 424 | //// when(loginService.tokenProvider(any())).thenReturn(new TokenGrantTokenProvider("token")); 425 | //// 426 | //// TokenProvider result = BuildPackService.tokenProviderWithDefault("token", new TokenGrantTokenProvider("token")); 427 | //// Assert.assertEquals(new TokenGrantTokenProvider("token"), result); 428 | //// } 429 | //// 430 | //// @Test 431 | //// public void testTokenProvider2() throws Exception { 432 | //// PasswordGrantTokenProvider result = BuildPackService.tokenProvider("username", "password"); 433 | //// Assert.assertEquals(null, result); 434 | //// } 435 | //// 436 | //// @Test 437 | //// public void testPreDestroy() throws Exception { 438 | //// when(loginService.peekConnectionContext()).thenReturn(null); 439 | //// 440 | //// buildPackService.preDestroy(); 441 | //// } 442 | //} 443 | // 444 | ////Generated with love by TestMe :) Please report issues and submit feature requests at: http://weirddev.com/forum#!/testme --------------------------------------------------------------------------------