├── gradle.properties ├── src ├── main │ ├── resources │ │ ├── static │ │ │ ├── templates │ │ │ │ ├── footer.html │ │ │ │ ├── status.html │ │ │ │ ├── errors.html │ │ │ │ ├── header.html │ │ │ │ ├── albums.html │ │ │ │ ├── grid.html │ │ │ │ ├── list.html │ │ │ │ └── albumForm.html │ │ │ ├── img │ │ │ │ ├── glyphicons-halflings.png │ │ │ │ └── glyphicons-halflings-white.png │ │ │ ├── js │ │ │ │ ├── info.js │ │ │ │ ├── app.js │ │ │ │ ├── status.js │ │ │ │ ├── errors.js │ │ │ │ └── albums.js │ │ │ ├── css │ │ │ │ ├── app.css │ │ │ │ └── multi-columns-row.css │ │ │ └── index.html │ │ ├── application.yml │ │ └── albums.json │ └── java │ │ └── org │ │ └── cloudfoundry │ │ └── samples │ │ └── music │ │ ├── repositories │ │ ├── jpa │ │ │ └── JpaAlbumRepository.java │ │ ├── mongodb │ │ │ └── MongoAlbumRepository.java │ │ ├── AlbumRepositoryPopulator.java │ │ └── redis │ │ │ └── RedisAlbumRepository.java │ │ ├── domain │ │ ├── RandomIdGenerator.java │ │ ├── ApplicationInfo.java │ │ └── Album.java │ │ ├── Application.java │ │ ├── web │ │ ├── ErrorController.java │ │ ├── InfoController.java │ │ └── AlbumController.java │ │ └── config │ │ ├── data │ │ └── RedisConfig.java │ │ └── SpringApplicationContextInitializer.java └── test │ └── java │ └── org │ └── cloudfoundry │ └── samples │ └── music │ └── ApplicationTests.java ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .gitignore ├── manifest.yml ├── gradlew.bat ├── gradlew ├── README.md └── LICENSE /gradle.properties: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/main/resources/static/templates/footer.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scottfrederick/spring-music/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /src/main/resources/static/img/glyphicons-halflings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scottfrederick/spring-music/HEAD/src/main/resources/static/img/glyphicons-halflings.png -------------------------------------------------------------------------------- /src/main/resources/static/img/glyphicons-halflings-white.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scottfrederick/spring-music/HEAD/src/main/resources/static/img/glyphicons-halflings-white.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | *.ipr 3 | *.ids 4 | *.iws 5 | .idea/ 6 | 7 | .project 8 | .metadata 9 | local.properties 10 | .classpath 11 | .settings/ 12 | .loadpath 13 | 14 | 15 | target/ 16 | 17 | .gradle 18 | build/ 19 | 20 | *.log* 21 | /classes/ 22 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /src/main/resources/static/js/info.js: -------------------------------------------------------------------------------- 1 | angular.module('info', ['ngResource']). 2 | factory('Info', function ($resource) { 3 | return $resource('appinfo'); 4 | }); 5 | 6 | function InfoController($scope, Info) { 7 | $scope.info = Info.get(); 8 | } 9 | -------------------------------------------------------------------------------- /manifest.yml: -------------------------------------------------------------------------------- 1 | --- 2 | applications: 3 | - name: spring-music 4 | memory: 1G 5 | random-route: true 6 | path: build/libs/spring-music-1.0.jar 7 | env: 8 | JBP_CONFIG_SPRING_AUTO_RECONFIGURATION: '{enabled: false}' 9 | # JBP_CONFIG_OPEN_JDK_JRE: '{ jre: { version: 11.+ } }' 10 | 11 | -------------------------------------------------------------------------------- /src/main/resources/static/templates/status.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 | 5 |

{{status.message}}

6 |
7 |
8 |
-------------------------------------------------------------------------------- /src/test/java/org/cloudfoundry/samples/music/ApplicationTests.java: -------------------------------------------------------------------------------- 1 | package org.cloudfoundry.samples.music; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | 9 | @RunWith(SpringRunner.class) 10 | @SpringBootTest() 11 | public class ApplicationTests { 12 | 13 | @Test 14 | public void contextLoads() { 15 | } 16 | 17 | } -------------------------------------------------------------------------------- /src/main/java/org/cloudfoundry/samples/music/repositories/jpa/JpaAlbumRepository.java: -------------------------------------------------------------------------------- 1 | package org.cloudfoundry.samples.music.repositories.jpa; 2 | 3 | import org.cloudfoundry.samples.music.domain.Album; 4 | import org.springframework.context.annotation.Profile; 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | import org.springframework.stereotype.Repository; 7 | 8 | @Repository 9 | @Profile({"!mongodb", "!redis"}) 10 | public interface JpaAlbumRepository extends JpaRepository { 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/org/cloudfoundry/samples/music/repositories/mongodb/MongoAlbumRepository.java: -------------------------------------------------------------------------------- 1 | package org.cloudfoundry.samples.music.repositories.mongodb; 2 | 3 | import org.cloudfoundry.samples.music.domain.Album; 4 | import org.springframework.context.annotation.Profile; 5 | import org.springframework.data.mongodb.repository.MongoRepository; 6 | import org.springframework.stereotype.Repository; 7 | 8 | @Repository 9 | @Profile("mongodb") 10 | public interface MongoAlbumRepository extends MongoRepository { 11 | } -------------------------------------------------------------------------------- /src/main/resources/static/js/app.js: -------------------------------------------------------------------------------- 1 | angular.module('SpringMusic', ['albums', 'errors', 'status', 'info', 'ngRoute', 'ui.directives']). 2 | config(function ($locationProvider, $routeProvider) { 3 | // $locationProvider.html5Mode(true); 4 | 5 | $routeProvider.when('/errors', { 6 | controller: 'ErrorsController', 7 | templateUrl: 'templates/errors.html' 8 | }); 9 | $routeProvider.otherwise({ 10 | controller: 'AlbumsController', 11 | templateUrl: 'templates/albums.html' 12 | }); 13 | } 14 | ); 15 | -------------------------------------------------------------------------------- /src/main/java/org/cloudfoundry/samples/music/domain/RandomIdGenerator.java: -------------------------------------------------------------------------------- 1 | package org.cloudfoundry.samples.music.domain; 2 | 3 | import org.hibernate.HibernateException; 4 | import org.hibernate.engine.spi.SharedSessionContractImplementor; 5 | import org.hibernate.id.IdentifierGenerator; 6 | 7 | import java.io.Serializable; 8 | import java.util.UUID; 9 | 10 | public class RandomIdGenerator implements IdentifierGenerator { 11 | @Override 12 | public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException { 13 | return generateId(); 14 | } 15 | 16 | public String generateId() { 17 | return UUID.randomUUID().toString(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/org/cloudfoundry/samples/music/domain/ApplicationInfo.java: -------------------------------------------------------------------------------- 1 | package org.cloudfoundry.samples.music.domain; 2 | 3 | public class ApplicationInfo { 4 | private String[] profiles; 5 | private String[] services; 6 | 7 | public ApplicationInfo(String[] profiles, String[] services) { 8 | this.profiles = profiles; 9 | this.services = services; 10 | } 11 | 12 | public String[] getProfiles() { 13 | return profiles; 14 | } 15 | 16 | public void setProfiles(String[] profiles) { 17 | this.profiles = profiles; 18 | } 19 | 20 | public String[] getServices() { 21 | return services; 22 | } 23 | 24 | public void setServices(String[] services) { 25 | this.services = services; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/org/cloudfoundry/samples/music/Application.java: -------------------------------------------------------------------------------- 1 | package org.cloudfoundry.samples.music; 2 | 3 | import org.cloudfoundry.samples.music.config.SpringApplicationContextInitializer; 4 | import org.cloudfoundry.samples.music.repositories.AlbumRepositoryPopulator; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.boot.builder.SpringApplicationBuilder; 7 | 8 | @SpringBootApplication 9 | public class Application { 10 | 11 | public static void main(String[] args) { 12 | new SpringApplicationBuilder(Application.class) 13 | .initializers(new SpringApplicationContextInitializer()) 14 | .listeners(new AlbumRepositoryPopulator()) 15 | .application() 16 | .run(args); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | jpa: 3 | generate-ddl: true 4 | 5 | management: 6 | endpoints: 7 | web: 8 | exposure: 9 | include: "*" 10 | endpoint: 11 | health: 12 | show-details: always 13 | 14 | --- 15 | spring: 16 | profiles: mysql 17 | datasource: 18 | url: "jdbc:mysql://localhost/music" 19 | driver-class-name: com.mysql.jdbc.Driver 20 | username: 21 | password: 22 | jpa: 23 | properties: 24 | hibernate: 25 | dialect: org.hibernate.dialect.MySQL55Dialect 26 | 27 | --- 28 | spring: 29 | profiles: postgres 30 | datasource: 31 | url: "jdbc:postgresql://localhost/music" 32 | driver-class-name: org.postgresql.Driver 33 | username: postgres 34 | password: 35 | jpa: 36 | properties: 37 | hibernate: 38 | dialect: org.hibernate.dialect.ProgressDialect 39 | -------------------------------------------------------------------------------- /src/main/resources/static/templates/errors.html: -------------------------------------------------------------------------------- 1 |
2 | 5 | 6 |
7 |
8 |
9 | 10 |
11 |
12 |
13 |

Kill this instance of the application

14 | Kill 15 |
16 |
17 |

Force an exception to be thrown from the application

18 | Throw Exception 19 |
20 |
21 |
22 |
23 | -------------------------------------------------------------------------------- /src/main/resources/static/css/app.css: -------------------------------------------------------------------------------- 1 | #body { 2 | padding-top: 10px; 3 | } 4 | 5 | .navbar { 6 | background-color: white; 7 | border: 0; 8 | margin-bottom: 20px; 9 | } 10 | 11 | .navbar .container { 12 | background-color: #008a00; 13 | background-image: -moz-linear-gradient(top, #008a00, #006b00); 14 | background-image: -ms-linear-gradient(top, #008a00, #006b00); 15 | background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#008a00), to(#006b00)); 16 | background-image: -webkit-linear-gradient(top, #008a00, #006b00); 17 | background-image: -o-linear-gradient(top, #008a00, #006b00); 18 | background-image: linear-gradient(top, #008a00, #006b00); 19 | } 20 | 21 | .navbar .navbar-brand { 22 | color: white; 23 | } 24 | 25 | .navbar .navbar-brand:hover { 26 | color: white; 27 | } 28 | 29 | .btn { 30 | background-color: white; 31 | } 32 | 33 | .icon-white { 34 | color: white; 35 | } 36 | -------------------------------------------------------------------------------- /src/main/resources/static/js/status.js: -------------------------------------------------------------------------------- 1 | angular.module('status', []). 2 | factory("Status", function () { 3 | var status = null; 4 | 5 | var success = function (message) { 6 | this.status = { isError: false, message: message }; 7 | }; 8 | 9 | var error = function (message) { 10 | this.status = { isError: true, message: message }; 11 | }; 12 | 13 | var clear = function () { 14 | this.status = null; 15 | }; 16 | 17 | return { 18 | status: status, 19 | success: success, 20 | error: error, 21 | clear: clear 22 | } 23 | }); 24 | 25 | function StatusController($scope, Status) { 26 | $scope.$watch( 27 | function () { 28 | return Status.status; 29 | }, 30 | function (status) { 31 | $scope.status = status; 32 | }, 33 | true); 34 | 35 | $scope.clearStatus = function () { 36 | Status.clear(); 37 | }; 38 | } -------------------------------------------------------------------------------- /src/main/resources/static/templates/header.html: -------------------------------------------------------------------------------- 1 | 25 | -------------------------------------------------------------------------------- /src/main/java/org/cloudfoundry/samples/music/web/ErrorController.java: -------------------------------------------------------------------------------- 1 | package org.cloudfoundry.samples.music.web; 2 | 3 | import java.util.List; 4 | import java.util.ArrayList; 5 | 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | @RestController 12 | @RequestMapping("/errors") 13 | public class ErrorController { 14 | private static final Logger logger = LoggerFactory.getLogger(ErrorController.class); 15 | private List junk = new ArrayList<>(); 16 | 17 | @RequestMapping(value = "/kill") 18 | public void kill() { 19 | logger.info("Forcing application exit"); 20 | System.exit(1); 21 | } 22 | 23 | @RequestMapping(value = "/fill-heap") 24 | public void fillHeap() { 25 | logger.info("Filling heap with junk, to initiate a crash"); 26 | while (true) { 27 | junk.add(new int[9999999]); 28 | } 29 | } 30 | 31 | @RequestMapping(value = "/throw") 32 | public void throwException() { 33 | logger.info("Forcing an exception to be thrown"); 34 | throw new NullPointerException("Forcing an exception to be thrown"); 35 | } 36 | } -------------------------------------------------------------------------------- /src/main/resources/static/templates/albums.html: -------------------------------------------------------------------------------- 1 |
2 | 21 | 22 |
23 |
24 |
25 | 26 |
27 |
28 |
29 |
30 | -------------------------------------------------------------------------------- /src/main/resources/static/js/errors.js: -------------------------------------------------------------------------------- 1 | angular.module('errors', ['ngResource']). 2 | factory('Errors', function ($resource) { 3 | return $resource('errors', {}, { 4 | kill: { url: 'errors/kill' }, 5 | throw: { url: 'errors/throw' } 6 | }); 7 | }); 8 | 9 | function ErrorsController($scope, Errors, Status) { 10 | $scope.kill = function() { 11 | Errors.kill({}, 12 | function () { 13 | Status.error("The application should have been killed, but returned successfully instead."); 14 | }, 15 | function (result) { 16 | if (result.status === 502) 17 | Status.error("An error occurred as expected, the application backend was killed: " + result.status); 18 | else 19 | Status.error("An unexpected error occurred: " + result.status); 20 | } 21 | ); 22 | }; 23 | 24 | $scope.throwException = function() { 25 | Errors.throw({}, 26 | function () { 27 | Status.error("An exception should have been thrown, but was not."); 28 | }, 29 | function (result) { 30 | if (result.status === 500) 31 | Status.error("An error occurred as expected: " + result.status); 32 | else 33 | Status.error("An unexpected error occurred: " + result.status); 34 | } 35 | ); 36 | }; 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/org/cloudfoundry/samples/music/config/data/RedisConfig.java: -------------------------------------------------------------------------------- 1 | package org.cloudfoundry.samples.music.config.data; 2 | 3 | import org.cloudfoundry.samples.music.domain.Album; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.context.annotation.Profile; 7 | import org.springframework.data.redis.connection.RedisConnectionFactory; 8 | import org.springframework.data.redis.core.RedisTemplate; 9 | import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; 10 | import org.springframework.data.redis.serializer.RedisSerializer; 11 | import org.springframework.data.redis.serializer.StringRedisSerializer; 12 | 13 | @Configuration 14 | @Profile("redis") 15 | public class RedisConfig { 16 | 17 | @Bean 18 | public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) { 19 | RedisTemplate template = new RedisTemplate<>(); 20 | 21 | template.setConnectionFactory(redisConnectionFactory); 22 | 23 | RedisSerializer stringSerializer = new StringRedisSerializer(); 24 | RedisSerializer albumSerializer = new Jackson2JsonRedisSerializer<>(Album.class); 25 | 26 | template.setKeySerializer(stringSerializer); 27 | template.setValueSerializer(albumSerializer); 28 | template.setHashKeySerializer(stringSerializer); 29 | template.setHashValueSerializer(albumSerializer); 30 | 31 | return template; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/resources/static/templates/grid.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 |

5 | {{album.title}} 6 |

7 | 8 |

9 | {{album.artist}} 10 |

11 | 12 |
13 | {{album.releaseYear}} 14 |
15 | 16 |
17 | {{album.genre}} 18 |
19 | 20 | 29 |
30 |
31 |
32 | -------------------------------------------------------------------------------- /src/main/java/org/cloudfoundry/samples/music/web/InfoController.java: -------------------------------------------------------------------------------- 1 | package org.cloudfoundry.samples.music.web; 2 | 3 | import io.pivotal.cfenv.core.CfEnv; 4 | import io.pivotal.cfenv.core.CfService; 5 | import org.cloudfoundry.samples.music.domain.ApplicationInfo; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.core.env.Environment; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | 14 | @RestController 15 | public class InfoController { 16 | private final CfEnv cfEnv; 17 | 18 | private Environment springEnvironment; 19 | 20 | @Autowired 21 | public InfoController(Environment springEnvironment) { 22 | this.springEnvironment = springEnvironment; 23 | this.cfEnv = new CfEnv(); 24 | } 25 | 26 | @RequestMapping(value = "/appinfo") 27 | public ApplicationInfo info() { 28 | return new ApplicationInfo(springEnvironment.getActiveProfiles(), getServiceNames()); 29 | } 30 | 31 | @RequestMapping(value = "/service") 32 | public List showServiceInfo() { 33 | return cfEnv.findAllServices(); 34 | } 35 | 36 | private String[] getServiceNames() { 37 | List services = cfEnv.findAllServices(); 38 | 39 | List names = new ArrayList<>(); 40 | for (CfService service : services) { 41 | names.add(service.getName()); 42 | } 43 | return names.toArray(new String[0]); 44 | } 45 | } -------------------------------------------------------------------------------- /src/main/resources/static/templates/list.html: -------------------------------------------------------------------------------- 1 |
2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 17 | 20 | 23 | 26 | 35 | 36 | 37 |
Album TitleArtistYearGenre
15 | {{album.title}} 16 | 18 | {{album.artist}} 19 | 21 | {{album.releaseYear}} 22 | 24 | {{album.genre}} 25 |
38 |
39 | -------------------------------------------------------------------------------- /src/main/java/org/cloudfoundry/samples/music/web/AlbumController.java: -------------------------------------------------------------------------------- 1 | package org.cloudfoundry.samples.music.web; 2 | 3 | import org.cloudfoundry.samples.music.domain.Album; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.data.repository.CrudRepository; 8 | import org.springframework.web.bind.annotation.*; 9 | 10 | import javax.validation.Valid; 11 | 12 | @RestController 13 | @RequestMapping(value = "/albums") 14 | public class AlbumController { 15 | private static final Logger logger = LoggerFactory.getLogger(AlbumController.class); 16 | private CrudRepository repository; 17 | 18 | @Autowired 19 | public AlbumController(CrudRepository repository) { 20 | this.repository = repository; 21 | } 22 | 23 | @RequestMapping(method = RequestMethod.GET) 24 | public Iterable albums() { 25 | return repository.findAll(); 26 | } 27 | 28 | @RequestMapping(method = RequestMethod.PUT) 29 | public Album add(@RequestBody @Valid Album album) { 30 | logger.info("Adding album " + album.getId()); 31 | return repository.save(album); 32 | } 33 | 34 | @RequestMapping(method = RequestMethod.POST) 35 | public Album update(@RequestBody @Valid Album album) { 36 | logger.info("Updating album " + album.getId()); 37 | return repository.save(album); 38 | } 39 | 40 | @RequestMapping(value = "/{id}", method = RequestMethod.GET) 41 | public Album getById(@PathVariable String id) { 42 | logger.info("Getting album " + id); 43 | return repository.findById(id).orElse(null); 44 | } 45 | 46 | @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) 47 | public void deleteById(@PathVariable String id) { 48 | logger.info("Deleting album " + id); 49 | repository.deleteById(id); 50 | } 51 | } -------------------------------------------------------------------------------- /src/main/resources/static/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Spring Music 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 |
18 |
19 |
20 | 21 |
22 | 23 |
24 | 25 |
26 |
27 |
28 |
29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /src/main/java/org/cloudfoundry/samples/music/domain/Album.java: -------------------------------------------------------------------------------- 1 | package org.cloudfoundry.samples.music.domain; 2 | 3 | import org.hibernate.annotations.GenericGenerator; 4 | 5 | import javax.persistence.Column; 6 | import javax.persistence.Entity; 7 | import javax.persistence.GeneratedValue; 8 | import javax.persistence.Id; 9 | 10 | @Entity 11 | public class Album { 12 | @Id 13 | @Column(length=40) 14 | @GeneratedValue(generator="randomId") 15 | @GenericGenerator(name="randomId", strategy="org.cloudfoundry.samples.music.domain.RandomIdGenerator") 16 | private String id; 17 | 18 | private String title; 19 | private String artist; 20 | private String releaseYear; 21 | private String genre; 22 | private int trackCount; 23 | private String albumId; 24 | 25 | public Album() { 26 | } 27 | 28 | public Album(String title, String artist, String releaseYear, String genre) { 29 | this.title = title; 30 | this.artist = artist; 31 | this.releaseYear = releaseYear; 32 | this.genre = genre; 33 | } 34 | 35 | public String getId() { 36 | return id; 37 | } 38 | 39 | public void setId(String id) { 40 | this.id = id; 41 | } 42 | 43 | public String getTitle() { 44 | return title; 45 | } 46 | 47 | public void setTitle(String title) { 48 | this.title = title; 49 | } 50 | 51 | public String getArtist() { 52 | return artist; 53 | } 54 | 55 | public void setArtist(String artist) { 56 | this.artist = artist; 57 | } 58 | 59 | public String getReleaseYear() { 60 | return releaseYear; 61 | } 62 | 63 | public void setReleaseYear(String releaseYear) { 64 | this.releaseYear = releaseYear; 65 | } 66 | 67 | public String getGenre() { 68 | return genre; 69 | } 70 | 71 | public void setGenre(String genre) { 72 | this.genre = genre; 73 | } 74 | 75 | public int getTrackCount() { 76 | return trackCount; 77 | } 78 | 79 | public void setTrackCount(int trackCount) { 80 | this.trackCount = trackCount; 81 | } 82 | 83 | public String getAlbumId() { 84 | return albumId; 85 | } 86 | 87 | public void setAlbumId(String albumId) { 88 | this.albumId = albumId; 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/main/java/org/cloudfoundry/samples/music/repositories/AlbumRepositoryPopulator.java: -------------------------------------------------------------------------------- 1 | package org.cloudfoundry.samples.music.repositories; 2 | 3 | import com.fasterxml.jackson.databind.DeserializationFeature; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import org.cloudfoundry.samples.music.domain.Album; 6 | import org.springframework.beans.factory.BeanFactoryUtils; 7 | import org.springframework.boot.context.event.ApplicationReadyEvent; 8 | import org.springframework.context.ApplicationListener; 9 | import org.springframework.core.io.ClassPathResource; 10 | import org.springframework.core.io.Resource; 11 | import org.springframework.data.repository.CrudRepository; 12 | import org.springframework.data.repository.init.Jackson2ResourceReader; 13 | 14 | import java.util.Collection; 15 | 16 | public class AlbumRepositoryPopulator implements ApplicationListener { 17 | private final Jackson2ResourceReader resourceReader; 18 | private final Resource sourceData; 19 | 20 | public AlbumRepositoryPopulator() { 21 | ObjectMapper mapper = new ObjectMapper(); 22 | mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 23 | resourceReader = new Jackson2ResourceReader(mapper); 24 | sourceData = new ClassPathResource("albums.json"); 25 | } 26 | 27 | @Override 28 | public void onApplicationEvent(ApplicationReadyEvent event) { 29 | CrudRepository albumRepository = 30 | BeanFactoryUtils.beanOfTypeIncludingAncestors(event.getApplicationContext(), CrudRepository.class); 31 | 32 | if (albumRepository != null && albumRepository.count() == 0) { 33 | populate(albumRepository); 34 | } 35 | } 36 | 37 | @SuppressWarnings("unchecked") 38 | private void populate(CrudRepository repository) { 39 | Object entity = getEntityFromResource(sourceData); 40 | 41 | if (entity instanceof Collection) { 42 | for (Album album : (Collection) entity) { 43 | if (album != null) { 44 | repository.save(album); 45 | } 46 | } 47 | } else { 48 | repository.save(entity); 49 | } 50 | } 51 | 52 | private Object getEntityFromResource(Resource resource) { 53 | try { 54 | return resourceReader.readFrom(resource, this.getClass().getClassLoader()); 55 | } catch (Exception e) { 56 | throw new RuntimeException(e); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/resources/static/templates/albumForm.html: -------------------------------------------------------------------------------- 1 | 5 | 29 | 33 | -------------------------------------------------------------------------------- /src/main/resources/static/css/multi-columns-row.css: -------------------------------------------------------------------------------- 1 | /* From https://github.com/sixfootsixdesigns/Bootstrap-3-Grid-Columns-Clearing */ 2 | 3 | /* clear first in row in ie 8 or lower */ 4 | .multi-columns-row .first-in-row { 5 | clear: left; 6 | } 7 | 8 | /* clear the first in row for any block that has the class "multi-columns-row" */ 9 | .multi-columns-row .col-xs-6:nth-child(2n + 3) { clear: left; } 10 | .multi-columns-row .col-xs-4:nth-child(3n + 4) { clear: left; } 11 | .multi-columns-row .col-xs-3:nth-child(4n + 5) { clear: left; } 12 | .multi-columns-row .col-xs-2:nth-child(6n + 7) { clear: left; } 13 | .multi-columns-row .col-xs-1:nth-child(12n + 13) { clear: left; } 14 | 15 | @media (min-width: 768px) { 16 | /* reset previous grid */ 17 | .multi-columns-row .col-xs-6:nth-child(2n + 3) { clear: none; } 18 | .multi-columns-row .col-xs-4:nth-child(3n + 4) { clear: none; } 19 | .multi-columns-row .col-xs-3:nth-child(4n + 5) { clear: none; } 20 | .multi-columns-row .col-xs-2:nth-child(6n + 7) { clear: none; } 21 | .multi-columns-row .col-xs-1:nth-child(12n + 13) { clear: none; } 22 | 23 | /* clear first in row for small columns */ 24 | .multi-columns-row .col-sm-6:nth-child(2n + 3) { clear: left; } 25 | .multi-columns-row .col-sm-4:nth-child(3n + 4) { clear: left; } 26 | .multi-columns-row .col-sm-3:nth-child(4n + 5) { clear: left; } 27 | .multi-columns-row .col-sm-2:nth-child(6n + 7) { clear: left; } 28 | .multi-columns-row .col-sm-1:nth-child(12n + 13) { clear: left; } 29 | } 30 | @media (min-width: 992px) { 31 | /* reset previous grid */ 32 | .multi-columns-row .col-sm-6:nth-child(2n + 3) { clear: none; } 33 | .multi-columns-row .col-sm-4:nth-child(3n + 4) { clear: none; } 34 | .multi-columns-row .col-sm-3:nth-child(4n + 5) { clear: none; } 35 | .multi-columns-row .col-sm-2:nth-child(6n + 7) { clear: none; } 36 | .multi-columns-row .col-sm-1:nth-child(12n + 13) { clear: none; } 37 | 38 | /* clear first in row for medium columns */ 39 | .multi-columns-row .col-md-6:nth-child(2n + 3) { clear: left; } 40 | .multi-columns-row .col-md-4:nth-child(3n + 4) { clear: left; } 41 | .multi-columns-row .col-md-3:nth-child(4n + 5) { clear: left; } 42 | .multi-columns-row .col-md-2:nth-child(6n + 7) { clear: left; } 43 | .multi-columns-row .col-md-1:nth-child(12n + 13) { clear: left; } 44 | } 45 | @media (min-width: 1200px) { 46 | /* reset previous grid */ 47 | .multi-columns-row .col-md-6:nth-child(2n + 3) { clear: none; } 48 | .multi-columns-row .col-md-4:nth-child(3n + 4) { clear: none; } 49 | .multi-columns-row .col-md-3:nth-child(4n + 5) { clear: none; } 50 | .multi-columns-row .col-md-2:nth-child(6n + 7) { clear: none; } 51 | .multi-columns-row .col-md-1:nth-child(12n + 13) { clear: none; } 52 | 53 | /* clear first in row for large columns */ 54 | .multi-columns-row .col-lg-6:nth-child(2n + 3) { clear: left; } 55 | .multi-columns-row .col-lg-4:nth-child(3n + 4) { clear: left; } 56 | .multi-columns-row .col-lg-3:nth-child(4n + 5) { clear: left; } 57 | .multi-columns-row .col-lg-2:nth-child(6n + 7) { clear: left; } 58 | .multi-columns-row .col-lg-1:nth-child(12n + 13) { clear: left; } 59 | } -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 33 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 34 | 35 | @rem Find java.exe 36 | if defined JAVA_HOME goto findJavaFromJavaHome 37 | 38 | set JAVA_EXE=java.exe 39 | %JAVA_EXE% -version >NUL 2>&1 40 | if "%ERRORLEVEL%" == "0" goto init 41 | 42 | echo. 43 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 44 | echo. 45 | echo Please set the JAVA_HOME variable in your environment to match the 46 | echo location of your Java installation. 47 | 48 | goto fail 49 | 50 | :findJavaFromJavaHome 51 | set JAVA_HOME=%JAVA_HOME:"=% 52 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 53 | 54 | if exist "%JAVA_EXE%" goto init 55 | 56 | echo. 57 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 58 | echo. 59 | echo Please set the JAVA_HOME variable in your environment to match the 60 | echo location of your Java installation. 61 | 62 | goto fail 63 | 64 | :init 65 | @rem Get command-line arguments, handling Windows variants 66 | 67 | if not "%OS%" == "Windows_NT" goto win9xME_args 68 | 69 | :win9xME_args 70 | @rem Slurp the command line arguments. 71 | set CMD_LINE_ARGS= 72 | set _SKIP=2 73 | 74 | :win9xME_args_slurp 75 | if "x%~1" == "x" goto execute 76 | 77 | set CMD_LINE_ARGS=%* 78 | 79 | :execute 80 | @rem Setup the command line 81 | 82 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 83 | 84 | @rem Execute Gradle 85 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 86 | 87 | :end 88 | @rem End local scope for the variables with windows NT shell 89 | if "%ERRORLEVEL%"=="0" goto mainEnd 90 | 91 | :fail 92 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 93 | rem the _cmd.exe /c_ return code! 94 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 95 | exit /b 1 96 | 97 | :mainEnd 98 | if "%OS%"=="Windows_NT" endlocal 99 | 100 | :omega 101 | -------------------------------------------------------------------------------- /src/main/java/org/cloudfoundry/samples/music/repositories/redis/RedisAlbumRepository.java: -------------------------------------------------------------------------------- 1 | package org.cloudfoundry.samples.music.repositories.redis; 2 | 3 | import org.cloudfoundry.samples.music.domain.Album; 4 | import org.cloudfoundry.samples.music.domain.RandomIdGenerator; 5 | 6 | import org.springframework.context.annotation.Profile; 7 | import org.springframework.data.redis.core.HashOperations; 8 | import org.springframework.data.redis.core.RedisTemplate; 9 | import org.springframework.data.repository.CrudRepository; 10 | import org.springframework.stereotype.Repository; 11 | 12 | import java.util.ArrayList; 13 | import java.util.List; 14 | import java.util.Optional; 15 | import java.util.Set; 16 | 17 | @Repository 18 | @Profile("redis") 19 | public class RedisAlbumRepository implements CrudRepository { 20 | public static final String ALBUMS_KEY = "albums"; 21 | 22 | private final RandomIdGenerator idGenerator; 23 | private final HashOperations hashOps; 24 | 25 | public RedisAlbumRepository(RedisTemplate redisTemplate) { 26 | this.hashOps = redisTemplate.opsForHash(); 27 | this.idGenerator = new RandomIdGenerator(); 28 | } 29 | 30 | @Override 31 | public S save(S album) { 32 | if (album.getId() == null) { 33 | album.setId(idGenerator.generateId()); 34 | } 35 | 36 | hashOps.put(ALBUMS_KEY, album.getId(), album); 37 | 38 | return album; 39 | } 40 | 41 | @Override 42 | public Iterable saveAll(Iterable albums) { 43 | List result = new ArrayList<>(); 44 | 45 | for (S entity : albums) { 46 | save(entity); 47 | result.add(entity); 48 | } 49 | 50 | return result; 51 | } 52 | 53 | @Override 54 | public Optional findById(String id) { 55 | return Optional.ofNullable(hashOps.get(ALBUMS_KEY, id)); 56 | } 57 | 58 | @Override 59 | public boolean existsById(String id) { 60 | return hashOps.hasKey(ALBUMS_KEY, id); 61 | } 62 | 63 | @Override 64 | public Iterable findAll() { 65 | return hashOps.values(ALBUMS_KEY); 66 | } 67 | 68 | @Override 69 | public Iterable findAllById(Iterable ids) { 70 | return hashOps.multiGet(ALBUMS_KEY, convertIterableToList(ids)); 71 | } 72 | 73 | @Override 74 | public long count() { 75 | return hashOps.keys(ALBUMS_KEY).size(); 76 | } 77 | 78 | @Override 79 | public void deleteById(String id) { 80 | hashOps.delete(ALBUMS_KEY, id); 81 | } 82 | 83 | @Override 84 | public void delete(Album album) { 85 | hashOps.delete(ALBUMS_KEY, album.getId()); 86 | } 87 | 88 | @Override 89 | public void deleteAll(Iterable albums) { 90 | for (Album album : albums) { 91 | delete(album); 92 | } 93 | } 94 | 95 | @Override 96 | public void deleteAll() { 97 | Set ids = hashOps.keys(ALBUMS_KEY); 98 | for (String id : ids) { 99 | deleteById(id); 100 | } 101 | } 102 | 103 | private List convertIterableToList(Iterable iterable) { 104 | List list = new ArrayList<>(); 105 | for (T object : iterable) { 106 | list.add(object); 107 | } 108 | return list; 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | # Determine the Java command to use to start the JVM. 86 | if [ -n "$JAVA_HOME" ] ; then 87 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 88 | # IBM's JDK on AIX uses strange locations for the executables 89 | JAVACMD="$JAVA_HOME/jre/sh/java" 90 | else 91 | JAVACMD="$JAVA_HOME/bin/java" 92 | fi 93 | if [ ! -x "$JAVACMD" ] ; then 94 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 95 | 96 | Please set the JAVA_HOME variable in your environment to match the 97 | location of your Java installation." 98 | fi 99 | else 100 | JAVACMD="java" 101 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 102 | 103 | Please set the JAVA_HOME variable in your environment to match the 104 | location of your Java installation." 105 | fi 106 | 107 | # Increase the maximum file descriptors if we can. 108 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 109 | MAX_FD_LIMIT=`ulimit -H -n` 110 | if [ $? -eq 0 ] ; then 111 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 112 | MAX_FD="$MAX_FD_LIMIT" 113 | fi 114 | ulimit -n $MAX_FD 115 | if [ $? -ne 0 ] ; then 116 | warn "Could not set maximum file descriptor limit: $MAX_FD" 117 | fi 118 | else 119 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 120 | fi 121 | fi 122 | 123 | # For Darwin, add options to specify how the application appears in the dock 124 | if $darwin; then 125 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 126 | fi 127 | 128 | # For Cygwin or MSYS, switch paths to Windows format before running java 129 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 130 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 131 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 132 | JAVACMD=`cygpath --unix "$JAVACMD"` 133 | 134 | # We build the pattern for arguments to be converted via cygpath 135 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 136 | SEP="" 137 | for dir in $ROOTDIRSRAW ; do 138 | ROOTDIRS="$ROOTDIRS$SEP$dir" 139 | SEP="|" 140 | done 141 | OURCYGPATTERN="(^($ROOTDIRS))" 142 | # Add a user-defined pattern to the cygpath arguments 143 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 144 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 145 | fi 146 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 147 | i=0 148 | for arg in "$@" ; do 149 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 150 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 151 | 152 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 153 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 154 | else 155 | eval `echo args$i`="\"$arg\"" 156 | fi 157 | i=`expr $i + 1` 158 | done 159 | case $i in 160 | 0) set -- ;; 161 | 1) set -- "$args0" ;; 162 | 2) set -- "$args0" "$args1" ;; 163 | 3) set -- "$args0" "$args1" "$args2" ;; 164 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 165 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 166 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 167 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 168 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 169 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 170 | esac 171 | fi 172 | 173 | # Escape application args 174 | save () { 175 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 176 | echo " " 177 | } 178 | APP_ARGS=`save "$@"` 179 | 180 | # Collect all arguments for the java command, following the shell quoting and substitution rules 181 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 182 | 183 | exec "$JAVACMD" "$@" 184 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Spring Music 2 | ============ 3 | 4 | This is a sample application for using database services on [Cloud Foundry](http://cloudfoundry.org) with the [Spring Framework](http://spring.io) and [Spring Boot](http://projects.spring.io/spring-boot/). 5 | 6 | This application has been built to store the same domain objects in one of a variety of different persistence technologies - relational, document, and key-value stores. This is not meant to represent a realistic use case for these technologies, since you would typically choose the one most applicable to the type of data you need to store, but it is useful for testing and experimenting with different types of services on Cloud Foundry. 7 | 8 | The application use Spring Java configuration and [bean profiles](http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html) to configure the application and the connection objects needed to use the persistence stores. It also uses the [Spring Cloud Connectors](http://cloud.spring.io/spring-cloud-connectors/) library to inspect the environment when running on Cloud Foundry. See the [Cloud Foundry documentation](http://docs.cloudfoundry.org/buildpacks/java/spring-service-bindings.html) for details on configuring a Spring application for Cloud Foundry. 9 | 10 | ## Building 11 | 12 | This project requires Java 8 or later to compile. 13 | 14 | To build a runnable Spring Boot jar file, run the following command: 15 | 16 | ~~~ 17 | $ ./gradlew clean assemble 18 | ~~~ 19 | 20 | ## Running the application locally 21 | 22 | One Spring bean profile should be activated to choose the database provider that the application should use. The profile is selected by setting the system property `spring.profiles.active` when starting the app. 23 | 24 | The application can be started locally using the following command: 25 | 26 | ~~~ 27 | $ java -jar -Dspring.profiles.active= build/libs/spring-music.jar 28 | ~~~ 29 | 30 | where `` is one of the following values: 31 | 32 | * `mysql` 33 | * `postgres` 34 | * `mongodb` 35 | * `redis` 36 | 37 | If no profile is provided, an in-memory relational database will be used. If any other profile is provided, the appropriate database server must be started separately. Spring Boot will auto-configure a connection to the database using it's auto-configuration defaults. The connection parameters can be configured by setting the appropriate [Spring Boot properties](http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html). 38 | 39 | If more than one of these profiles is provided, the application will throw an exception and fail to start. 40 | 41 | ## Running the application on Cloud Foundry 42 | 43 | When running on Cloud Foundry, the application will detect the type of database service bound to the application (if any). If a service of one of the supported types (MySQL, Postgres, Oracle, MongoDB, or Redis) is bound to the app, the appropriate Spring profile will be configured to use the database service. The connection strings and credentials needed to use the service will be extracted from the Cloud Foundry environment. 44 | 45 | If no bound services are found containing any of these values in the name, an in-memory relational database will be used. 46 | 47 | If more than one service containing any of these values is bound to the application, the application will throw an exception and fail to start. 48 | 49 | After installing the 'cf' [command-line interface for Cloud Foundry](http://docs.cloudfoundry.org/cf-cli/), targeting a Cloud Foundry instance, and logging in, the application can be built and pushed using these commands: 50 | 51 | ~~~ 52 | $ cf push 53 | ~~~ 54 | 55 | The application will be pushed using settings in the provided `manifest.yml` file. The output from the command will show the URL that has been assigned to the application. 56 | 57 | ### Creating and binding services 58 | 59 | Using the provided manifest, the application will be created without an external database (in the `in-memory` profile). You can create and bind database services to the application using the information below. 60 | 61 | #### System-managed services 62 | 63 | Depending on the Cloud Foundry service provider, persistence services might be offered and managed by the platform. These steps can be used to create and bind a service that is managed by the platform: 64 | 65 | ~~~ 66 | # view the services available 67 | $ cf marketplace 68 | # create a service instance 69 | $ cf create-service 70 | # bind the service instance to the application 71 | $ cf bind-service 72 | # restart the application so the new service is detected 73 | $ cf restart 74 | ~~~ 75 | 76 | #### User-provided services 77 | 78 | Cloud Foundry also allows service connection information and credentials to be provided by a user. In order for the application to detect and connect to a user-provided service, a single `uri` field should be given in the credentials using the form `://:@:/`. 79 | 80 | These steps use examples for username, password, host name, and database name that should be replaced with real values. 81 | 82 | ~~~ 83 | # create a user-provided Oracle database service instance 84 | $ cf create-user-provided-service oracle-db -p '{"uri":"oracle://root:secret@dbserver.example.com:1521/mydatabase"}' 85 | # create a user-provided MySQL database service instance 86 | $ cf create-user-provided-service mysql-db -p '{"uri":"mysql://root:secret@dbserver.example.com:3306/mydatabase"}' 87 | # bind a service instance to the application 88 | $ cf bind-service 89 | # restart the application so the new service is detected 90 | $ cf restart 91 | ~~~ 92 | 93 | #### Changing bound services 94 | 95 | To test the application with different services, you can simply stop the app, unbind a service, bind a different database service, and start the app: 96 | 97 | ~~~ 98 | $ cf unbind-service 99 | $ cf bind-service 100 | $ cf restart 101 | ~~~ 102 | 103 | #### Database drivers 104 | 105 | Database drivers for MySQL, Postgres, Microsoft SQL Server, MongoDB, and Redis are included in the project. 106 | 107 | To connect to an Oracle database, you will need to download the appropriate driver (e.g. from http://www.oracle.com/technetwork/database/features/jdbc/index-091264.html). Then make a `libs` directory in the `spring-music` project, and move the driver, `ojdbc7.jar` or `ojdbc8.jar`, into the `libs` directory. 108 | In `build.gradle`, uncomment the line `compile files('libs/ojdbc8.jar')` or `compile files('libs/ojdbc7.jar')` and run `./gradle assemble` 109 | -------------------------------------------------------------------------------- /src/main/resources/albums.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "_class": "org.cloudfoundry.samples.music.domain.Album", 4 | "artist": "Nirvana", 5 | "title": "Nevermind", 6 | "releaseYear": "1991", 7 | "genre": "Rock" 8 | }, 9 | { 10 | "_class": "org.cloudfoundry.samples.music.domain.Album", 11 | "artist": "The Beach Boys", 12 | "title": "Pet Sounds", 13 | "releaseYear": "1966", 14 | "genre": "Rock" 15 | }, 16 | { 17 | "_class": "org.cloudfoundry.samples.music.domain.Album", 18 | "artist": "Marvin Gaye", 19 | "title": "What's Going On", 20 | "releaseYear": "1971", 21 | "genre": "Rock" 22 | }, 23 | { 24 | "_class": "org.cloudfoundry.samples.music.domain.Album", 25 | "artist": "Jimi Hendrix Experience", 26 | "title": "Are You Experienced?", 27 | "releaseYear": "1967", 28 | "genre": "Rock" 29 | }, 30 | { 31 | "_class": "org.cloudfoundry.samples.music.domain.Album", 32 | "artist": "U2", 33 | "title": "The Joshua Tree", 34 | "releaseYear": "1987", 35 | "genre": "Rock" 36 | }, 37 | { 38 | "_class": "org.cloudfoundry.samples.music.domain.Album", 39 | "artist": "The Beatles", 40 | "title": "Abbey Road", 41 | "releaseYear": "1969", 42 | "genre": "Rock" 43 | }, 44 | { 45 | "_class": "org.cloudfoundry.samples.music.domain.Album", 46 | "artist": "Fleetwood Mac", 47 | "title": "Rumours", 48 | "releaseYear": "1977", 49 | "genre": "Rock" 50 | }, 51 | { 52 | "_class": "org.cloudfoundry.samples.music.domain.Album", 53 | "artist": "Elvis Presley", 54 | "title": "Sun Sessions", 55 | "releaseYear": "1976", 56 | "genre": "Rock" 57 | }, 58 | { 59 | "_class": "org.cloudfoundry.samples.music.domain.Album", 60 | "artist": "Michael Jackson", 61 | "title": "Thriller", 62 | "releaseYear": "1982", 63 | "genre": "Pop" 64 | }, 65 | { 66 | "_class": "org.cloudfoundry.samples.music.domain.Album", 67 | "artist": "The Rolling Stones", 68 | "title": "Exile on Main Street", 69 | "releaseYear": "1972", 70 | "genre": "Rock" 71 | }, 72 | { 73 | "_class": "org.cloudfoundry.samples.music.domain.Album", 74 | "artist": "Bruce Springsteen", 75 | "title": "Born to Run", 76 | "releaseYear": "1975", 77 | "genre": "Rock" 78 | }, 79 | { 80 | "_class": "org.cloudfoundry.samples.music.domain.Album", 81 | "artist": "The Clash", 82 | "title": "London Calling", 83 | "releaseYear": "1980", 84 | "genre": "Rock" 85 | }, 86 | { 87 | "_class": "org.cloudfoundry.samples.music.domain.Album", 88 | "artist": "The Eagles", 89 | "title": "Hotel California", 90 | "releaseYear": "1976", 91 | "genre": "Rock" 92 | }, 93 | { 94 | "_class": "org.cloudfoundry.samples.music.domain.Album", 95 | "artist": "Led Zeppelin", 96 | "title": "Led Zeppelin", 97 | "releaseYear": "1969", 98 | "genre": "Rock" 99 | }, 100 | { 101 | "_class": "org.cloudfoundry.samples.music.domain.Album", 102 | "artist": "Led Zeppelin", 103 | "title": "IV", 104 | "releaseYear": "1971", 105 | "genre": "Rock" 106 | }, 107 | { 108 | "_class": "org.cloudfoundry.samples.music.domain.Album", 109 | "artist": "Police", 110 | "title": "Synchronicity", 111 | "releaseYear": "1983", 112 | "genre": "Rock" 113 | }, 114 | { 115 | "_class": "org.cloudfoundry.samples.music.domain.Album", 116 | "artist": "U2", 117 | "title": "Achtung Baby", 118 | "releaseYear": "1991", 119 | "genre": "Rock" 120 | }, 121 | { 122 | "_class": "org.cloudfoundry.samples.music.domain.Album", 123 | "artist": "The Rolling Stones", 124 | "title": "Let it Bleed", 125 | "releaseYear": "1969", 126 | "genre": "Rock" 127 | }, 128 | { 129 | "_class": "org.cloudfoundry.samples.music.domain.Album", 130 | "artist": "The Beatles", 131 | "title": "Rubber Soul", 132 | "releaseYear": "1965", 133 | "genre": "Rock" 134 | }, 135 | { 136 | "_class": "org.cloudfoundry.samples.music.domain.Album", 137 | "artist": "The Ramones", 138 | "title": "The Ramones", 139 | "releaseYear": "1976", 140 | "genre": "Rock" 141 | }, 142 | { 143 | "_class": "org.cloudfoundry.samples.music.domain.Album", 144 | "artist": "Queen", 145 | "title": "A Night At The Opera", 146 | "releaseYear": "1975", 147 | "genre": "Rock" 148 | }, 149 | { 150 | "_class": "org.cloudfoundry.samples.music.domain.Album", 151 | "artist": "Boston", 152 | "title": "Don't Look Back", 153 | "releaseYear": "1978", 154 | "genre": "Rock" 155 | }, 156 | { 157 | "_class": "org.cloudfoundry.samples.music.domain.Album", 158 | "artist": "BB King", 159 | "title": "Singin' The Blues", 160 | "releaseYear": "1956", 161 | "genre": "Blues" 162 | }, 163 | { 164 | "_class": "org.cloudfoundry.samples.music.domain.Album", 165 | "artist": "Albert King", 166 | "title": "Born Under A Bad Sign", 167 | "releaseYear": "1967", 168 | "genre": "Blues" 169 | }, 170 | { 171 | "_class": "org.cloudfoundry.samples.music.domain.Album", 172 | "artist": "Muddy Waters", 173 | "title": "Folk Singer", 174 | "releaseYear": "1964", 175 | "genre": "Blues" 176 | }, 177 | { 178 | "_class": "org.cloudfoundry.samples.music.domain.Album", 179 | "artist": "The Fabulous Thunderbirds", 180 | "title": "Rock With Me", 181 | "releaseYear": "1979", 182 | "genre": "Blues" 183 | }, 184 | { 185 | "_class": "org.cloudfoundry.samples.music.domain.Album", 186 | "artist": "Robert Johnson", 187 | "title": "King of the Delta Blues", 188 | "releaseYear": "1961", 189 | "genre": "Blues" 190 | }, 191 | { 192 | "_class": "org.cloudfoundry.samples.music.domain.Album", 193 | "artist": "Stevie Ray Vaughan", 194 | "title": "Texas Flood", 195 | "releaseYear": "1983", 196 | "genre": "Blues" 197 | }, 198 | { 199 | "_class": "org.cloudfoundry.samples.music.domain.Album", 200 | "artist": "Stevie Ray Vaughan", 201 | "title": "Couldn't Stand The Weather", 202 | "releaseYear": "1984", 203 | "genre": "Blues" 204 | } 205 | ] -------------------------------------------------------------------------------- /src/main/resources/static/js/albums.js: -------------------------------------------------------------------------------- 1 | angular.module('albums', ['ngResource', 'ui.bootstrap']). 2 | factory('Albums', function ($resource) { 3 | return $resource('albums'); 4 | }). 5 | factory('Album', function ($resource) { 6 | return $resource('albums/:id', {id: '@id'}); 7 | }). 8 | factory("EditorStatus", function () { 9 | var editorEnabled = {}; 10 | 11 | var enable = function (id, fieldName) { 12 | editorEnabled = { 'id': id, 'fieldName': fieldName }; 13 | }; 14 | 15 | var disable = function () { 16 | editorEnabled = {}; 17 | }; 18 | 19 | var isEnabled = function(id, fieldName) { 20 | return (editorEnabled['id'] == id && editorEnabled['fieldName'] == fieldName); 21 | }; 22 | 23 | return { 24 | isEnabled: isEnabled, 25 | enable: enable, 26 | disable: disable 27 | } 28 | }); 29 | 30 | function AlbumsController($scope, $modal, Albums, Album, Status) { 31 | function list() { 32 | $scope.albums = Albums.query(); 33 | } 34 | 35 | function clone (obj) { 36 | return JSON.parse(JSON.stringify(obj)); 37 | } 38 | 39 | function saveAlbum(album) { 40 | Albums.save(album, 41 | function () { 42 | Status.success("Album saved"); 43 | list(); 44 | }, 45 | function (result) { 46 | Status.error("Error saving album: " + result.status); 47 | } 48 | ); 49 | } 50 | 51 | $scope.addAlbum = function () { 52 | var addModal = $modal.open({ 53 | templateUrl: 'templates/albumForm.html', 54 | controller: AlbumModalController, 55 | resolve: { 56 | album: function () { 57 | return {}; 58 | }, 59 | action: function() { 60 | return 'add'; 61 | } 62 | } 63 | }); 64 | 65 | addModal.result.then(function (album) { 66 | saveAlbum(album); 67 | }); 68 | }; 69 | 70 | $scope.updateAlbum = function (album) { 71 | var updateModal = $modal.open({ 72 | templateUrl: 'templates/albumForm.html', 73 | controller: AlbumModalController, 74 | resolve: { 75 | album: function() { 76 | return clone(album); 77 | }, 78 | action: function() { 79 | return 'update'; 80 | } 81 | } 82 | }); 83 | 84 | updateModal.result.then(function (album) { 85 | saveAlbum(album); 86 | }); 87 | }; 88 | 89 | $scope.deleteAlbum = function (album) { 90 | Album.delete({id: album.id}, 91 | function () { 92 | Status.success("Album deleted"); 93 | list(); 94 | }, 95 | function (result) { 96 | Status.error("Error deleting album: " + result.status); 97 | } 98 | ); 99 | }; 100 | 101 | $scope.setAlbumsView = function (viewName) { 102 | $scope.albumsView = "templates/" + viewName + ".html"; 103 | }; 104 | 105 | $scope.init = function() { 106 | list(); 107 | $scope.setAlbumsView("grid"); 108 | $scope.sortField = "name"; 109 | $scope.sortDescending = false; 110 | }; 111 | } 112 | 113 | function AlbumModalController($scope, $modalInstance, album, action) { 114 | $scope.albumAction = action; 115 | $scope.yearPattern = /^[1-2]\d{3}$/; 116 | $scope.album = album; 117 | 118 | $scope.ok = function () { 119 | $modalInstance.close($scope.album); 120 | }; 121 | 122 | $scope.cancel = function () { 123 | $modalInstance.dismiss('cancel'); 124 | }; 125 | }; 126 | 127 | function AlbumEditorController($scope, Albums, Status, EditorStatus) { 128 | $scope.enableEditor = function (album, fieldName) { 129 | $scope.newFieldValue = album[fieldName]; 130 | EditorStatus.enable(album.id, fieldName); 131 | }; 132 | 133 | $scope.disableEditor = function () { 134 | EditorStatus.disable(); 135 | }; 136 | 137 | $scope.isEditorEnabled = function (album, fieldName) { 138 | return EditorStatus.isEnabled(album.id, fieldName); 139 | }; 140 | 141 | $scope.save = function (album, fieldName) { 142 | if ($scope.newFieldValue === "") { 143 | return false; 144 | } 145 | 146 | album[fieldName] = $scope.newFieldValue; 147 | 148 | Albums.save({}, album, 149 | function () { 150 | Status.success("Album saved"); 151 | list(); 152 | }, 153 | function (result) { 154 | Status.error("Error saving album: " + result.status); 155 | } 156 | ); 157 | 158 | $scope.disableEditor(); 159 | }; 160 | 161 | $scope.disableEditor(); 162 | } 163 | 164 | angular.module('albums'). 165 | directive('inPlaceEdit', function () { 166 | return { 167 | restrict: 'E', 168 | transclude: true, 169 | replace: true, 170 | 171 | scope: { 172 | ipeFieldName: '@fieldName', 173 | ipeInputType: '@inputType', 174 | ipeInputClass: '@inputClass', 175 | ipePattern: '@pattern', 176 | ipeModel: '=model' 177 | }, 178 | 179 | template: 180 | '
' + 181 | '' + 182 | '' + 183 | '' + 184 | '' + 185 | '
' + 186 | '' + 189 | '' + 193 | '
' + 194 | '
' + 195 | '
', 196 | 197 | controller: 'AlbumEditorController' 198 | }; 199 | }); 200 | -------------------------------------------------------------------------------- /src/main/java/org/cloudfoundry/samples/music/config/SpringApplicationContextInitializer.java: -------------------------------------------------------------------------------- 1 | package org.cloudfoundry.samples.music.config; 2 | 3 | import io.pivotal.cfenv.core.CfEnv; 4 | import io.pivotal.cfenv.core.CfService; 5 | import org.apache.commons.logging.Log; 6 | import org.apache.commons.logging.LogFactory; 7 | import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration; 8 | import org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration; 9 | import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; 10 | import org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration; 11 | import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; 12 | import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; 13 | import org.springframework.context.ApplicationContextInitializer; 14 | import org.springframework.context.ConfigurableApplicationContext; 15 | import org.springframework.core.env.ConfigurableEnvironment; 16 | import org.springframework.core.env.MapPropertySource; 17 | import org.springframework.core.env.Profiles; 18 | import org.springframework.core.env.PropertySource; 19 | import org.springframework.util.StringUtils; 20 | 21 | import java.util.ArrayList; 22 | import java.util.Arrays; 23 | import java.util.Collections; 24 | import java.util.HashMap; 25 | import java.util.List; 26 | import java.util.Map; 27 | import java.util.Set; 28 | import java.util.stream.Collectors; 29 | import java.util.stream.Stream; 30 | 31 | public class SpringApplicationContextInitializer implements ApplicationContextInitializer { 32 | 33 | private static final Log logger = LogFactory.getLog(SpringApplicationContextInitializer.class); 34 | 35 | private static final Map> profileNameToServiceTags = new HashMap<>(); 36 | static { 37 | profileNameToServiceTags.put("mongodb", Collections.singletonList("mongodb")); 38 | profileNameToServiceTags.put("postgres", Collections.singletonList("postgres")); 39 | profileNameToServiceTags.put("mysql", Collections.singletonList("mysql")); 40 | profileNameToServiceTags.put("redis", Collections.singletonList("redis")); 41 | profileNameToServiceTags.put("oracle", Collections.singletonList("oracle")); 42 | profileNameToServiceTags.put("sqlserver", Collections.singletonList("sqlserver")); 43 | } 44 | 45 | @Override 46 | public void initialize(ConfigurableApplicationContext applicationContext) { 47 | ConfigurableEnvironment appEnvironment = applicationContext.getEnvironment(); 48 | 49 | validateActiveProfiles(appEnvironment); 50 | 51 | addCloudProfile(appEnvironment); 52 | 53 | excludeAutoConfiguration(appEnvironment); 54 | } 55 | 56 | private void addCloudProfile(ConfigurableEnvironment appEnvironment) { 57 | CfEnv cfEnv = new CfEnv(); 58 | 59 | List profiles = new ArrayList<>(); 60 | 61 | List services = cfEnv.findAllServices(); 62 | List serviceNames = services.stream() 63 | .map(CfService::getName) 64 | .collect(Collectors.toList()); 65 | 66 | logger.info("Found services " + StringUtils.collectionToCommaDelimitedString(serviceNames)); 67 | 68 | for (CfService service : services) { 69 | for (String profileKey : profileNameToServiceTags.keySet()) { 70 | if (service.getTags().containsAll(profileNameToServiceTags.get(profileKey))) { 71 | profiles.add(profileKey); 72 | } 73 | } 74 | } 75 | 76 | if (profiles.size() > 1) { 77 | throw new IllegalStateException( 78 | "Only one service of the following types may be bound to this application: " + 79 | profileNameToServiceTags.values().toString() + ". " + 80 | "These services are bound to the application: [" + 81 | StringUtils.collectionToCommaDelimitedString(profiles) + "]"); 82 | } 83 | 84 | if (profiles.size() > 0) { 85 | logger.info("Setting service profile " + profiles.get(0)); 86 | appEnvironment.addActiveProfile(profiles.get(0)); 87 | } 88 | } 89 | 90 | private void validateActiveProfiles(ConfigurableEnvironment appEnvironment) { 91 | Set validLocalProfiles = profileNameToServiceTags.keySet(); 92 | 93 | List serviceProfiles = Stream.of(appEnvironment.getActiveProfiles()) 94 | .filter(validLocalProfiles::contains) 95 | .collect(Collectors.toList()); 96 | 97 | if (serviceProfiles.size() > 1) { 98 | throw new IllegalStateException("Only one active Spring profile may be set among the following: " + 99 | validLocalProfiles.toString() + ". " + 100 | "These profiles are active: [" + 101 | StringUtils.collectionToCommaDelimitedString(serviceProfiles) + "]"); 102 | } 103 | } 104 | 105 | private void excludeAutoConfiguration(ConfigurableEnvironment environment) { 106 | List exclude = new ArrayList<>(); 107 | if (environment.acceptsProfiles(Profiles.of("redis"))) { 108 | excludeDataSourceAutoConfiguration(exclude); 109 | excludeMongoAutoConfiguration(exclude); 110 | } else if (environment.acceptsProfiles(Profiles.of("mongodb"))) { 111 | excludeDataSourceAutoConfiguration(exclude); 112 | excludeRedisAutoConfiguration(exclude); 113 | } else { 114 | excludeMongoAutoConfiguration(exclude); 115 | excludeRedisAutoConfiguration(exclude); 116 | } 117 | 118 | Map properties = Collections.singletonMap("spring.autoconfigure.exclude", 119 | StringUtils.collectionToCommaDelimitedString(exclude)); 120 | 121 | PropertySource propertySource = new MapPropertySource("springMusicAutoConfig", properties); 122 | 123 | environment.getPropertySources().addFirst(propertySource); 124 | } 125 | 126 | private void excludeDataSourceAutoConfiguration(List exclude) { 127 | exclude.add(DataSourceAutoConfiguration.class.getName()); 128 | } 129 | 130 | private void excludeMongoAutoConfiguration(List exclude) { 131 | exclude.addAll(Arrays.asList( 132 | MongoAutoConfiguration.class.getName(), 133 | MongoDataAutoConfiguration.class.getName(), 134 | MongoRepositoriesAutoConfiguration.class.getName() 135 | )); 136 | } 137 | 138 | private void excludeRedisAutoConfiguration(List exclude) { 139 | exclude.addAll(Arrays.asList( 140 | RedisAutoConfiguration.class.getName(), 141 | RedisRepositoriesAutoConfiguration.class.getName() 142 | )); 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | --------------------------------------------------------------------------------