diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e70bd83 --- /dev/null +++ b/.gitignore @@ -0,0 +1,25 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +nbproject/private/ +build/ +nbbuild/ +dist/ +nbdist/ +.nb-gradle/ +.gitignore diff --git a/README.md b/README.md new file mode 100644 index 0000000..716a284 --- /dev/null +++ b/README.md @@ -0,0 +1,48 @@ +# SpringBoot - Spotify API - ReactJS +###### This is a web application developed using Spotify API with React. +###### There are two modules in the project. +###### spotify-api-server is a Spring Boot application with using Spotify Search API. +###### spotify-api-ui is a ReactJS application. + +![alt tag](./example-min.png) + +## spotify-api-server + +For use Spotify API you need to take authorization token from Spotify. +You can take authorization token from [Here](https://developer.spotify.com/web-api/console/get-search-item/) + +In the ``` + application.yml + ```, you can set token here. + +This token looks like this; +``` +token: "BQDYNZJKRPp271pXIiMRrRbx77TSo5BuQKMZeBXFlD9FwwRP4VjbkKxTfwKOvZSS_kZCQYSGK9QA7dKFl63tXo4taPItG6ya0AL-7L2zvOlI8IDrRwoF4yEws8AJjXtf2-PKJqj3hmaz765w_A" +``` + +The project is a Spring Boot project. For this reason, you can run the Application class by running it. + +## spotify-api-ui + +###### This module uses React and React-Bootstrap. Includes paging and limiting features about Spotify response. + +In the project folder ``` + $ cd spotify-api-ui + ``` use the following command. +``` +$ npm install +``` + +then + +``` +$ npm start +``` + +and project will start at ``` + http://127.0.0.1:3000 + ``` + +## License + +The MIT License (MIT) Copyright (c) 2017 Fatih Totrakanlı \ No newline at end of file diff --git a/example-min.png b/example-min.png new file mode 100644 index 0000000..1fb18a4 Binary files /dev/null and b/example-min.png differ diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..a0772f1 --- /dev/null +++ b/pom.xml @@ -0,0 +1,20 @@ + + 4.0.0 + + com.spotify.api + com.spotify.api + 1.0-SNAPSHOT + + spotify-api-server + + pom + + com.spotify.api + http://maven.apache.org + + + UTF-8 + + + diff --git a/spotify-api-server/pom.xml b/spotify-api-server/pom.xml new file mode 100644 index 0000000..f57d24c --- /dev/null +++ b/spotify-api-server/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + + com.spotify.api + jar + + com.spotify.api + http://maven.apache.org + + + UTF-8 + + + + org.springframework.boot + spring-boot-starter-parent + 1.5.2.RELEASE + + + + + + org.apache.httpcomponents + httpclient + 4.5.2 + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-web + + + junit + junit + 3.8.1 + test + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/spotify-api-server/src/main/java/com/spotify/api/controller/Application.java b/spotify-api-server/src/main/java/com/spotify/api/controller/Application.java new file mode 100644 index 0000000..a794f3d --- /dev/null +++ b/spotify-api-server/src/main/java/com/spotify/api/controller/Application.java @@ -0,0 +1,20 @@ +package com.spotify.api.controller; + +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +import java.io.IOException; + +@SpringBootApplication +public class Application implements CommandLineRunner { + + public static void main(String[] args) throws IOException { + SpringApplication.run(Application.class, args); + } + + @Override + public void run(String... strings) throws Exception { + + } +} diff --git a/spotify-api-server/src/main/java/com/spotify/api/controller/controller/SearchController.java b/spotify-api-server/src/main/java/com/spotify/api/controller/controller/SearchController.java new file mode 100644 index 0000000..98b3802 --- /dev/null +++ b/spotify-api-server/src/main/java/com/spotify/api/controller/controller/SearchController.java @@ -0,0 +1,72 @@ +package com.spotify.api.controller.controller; + +import com.spotify.api.controller.helper.SearchModel; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.HttpClientBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.bind.annotation.*; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +import static org.apache.http.HttpHeaders.USER_AGENT; + +/** + * Created by Fatih Totrakanli on 31/05/2017. + */ + +@RestController +@RequestMapping(value = "search") +public class SearchController { + + private static Logger logger = LoggerFactory.getLogger(SearchController.class.getName()); + + @Value("${token}") + private String token; + + @PostMapping(value = "/api") + public StringBuffer searchQ(@RequestBody SearchModel search) throws IOException { + + String query = search.getQuery().equals("") ? "%2B" : search.getQuery().replaceAll("\\s+", "%2B"); + logger.info(query + " search started..."); + + String url = "https://api.spotify.com/v1/search?q=" + query + "&type=track&limit=" + search.getLimit() + "&offset=" + search.getOffset(); + + HttpClient client = HttpClientBuilder.create().build(); + HttpGet request = new HttpGet(url); + + request.addHeader("User-Agent", USER_AGENT); + request.addHeader("Authorization", "Bearer " + token); + request.addHeader("Accept", "application/json"); + HttpResponse response = client.execute(request); + + logger.info("Response Code : " + response.getStatusLine().getStatusCode()); + + if (response.getStatusLine().getStatusCode() == 401) { + String error = "The server did not respond properly. Please check spotify authorization token from application.yml or get new token from (https://developer.spotify.com/web-api/console/get-search-item/)."; + logger.error(error); + throw new RuntimeException(error); + } else { + if (response.getStatusLine().getStatusCode() != 200) + throw new RuntimeException("Something went wrong."); + } + + BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); + + StringBuffer result = new StringBuffer(); + String line = ""; + logger.info("Reading response..."); + while ((line = rd.readLine()) != null) { + result.append(line); + } + + logger.info("Reading response completed successfully."); + + return result; + } +} diff --git a/spotify-api-server/src/main/java/com/spotify/api/controller/helper/CorsFilter.java b/spotify-api-server/src/main/java/com/spotify/api/controller/helper/CorsFilter.java new file mode 100644 index 0000000..7b08e1f --- /dev/null +++ b/spotify-api-server/src/main/java/com/spotify/api/controller/helper/CorsFilter.java @@ -0,0 +1,32 @@ +package com.spotify.api.controller.helper; + +import org.springframework.stereotype.Component; + +import javax.servlet.*; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +/** + * Created by Fatih Totrakanli on 31/05/2017. + */ + +@Component +public class CorsFilter implements Filter { + + + public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { + HttpServletResponse response = (HttpServletResponse) res; + response.setHeader("Access-Control-Allow-Origin", "*"); + response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE"); + response.setHeader("Access-Control-Max-Age", "3600"); + response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type"); + chain.doFilter(req, res); + } + + public void init(FilterConfig filterConfig) { + } + + public void destroy() { + } + +} diff --git a/spotify-api-server/src/main/java/com/spotify/api/controller/helper/SearchModel.java b/spotify-api-server/src/main/java/com/spotify/api/controller/helper/SearchModel.java new file mode 100644 index 0000000..e799000 --- /dev/null +++ b/spotify-api-server/src/main/java/com/spotify/api/controller/helper/SearchModel.java @@ -0,0 +1,37 @@ +package com.spotify.api.controller.helper; + +/** + * Created by Fatih Totrakanli on 31/05/2017. + */ +public class SearchModel { + + private String query; + + private int limit = 20; + + private int offset = 0; + + public String getQuery() { + return query; + } + + public void setQuery(String query) { + this.query = query; + } + + public int getOffset() { + return offset; + } + + public void setOffset(int offset) { + this.offset = offset; + } + + public int getLimit() { + return limit; + } + + public void setLimit(int limit) { + this.limit = limit; + } +} diff --git a/spotify-api-server/src/main/resources/application.yml b/spotify-api-server/src/main/resources/application.yml new file mode 100644 index 0000000..b0b75ce --- /dev/null +++ b/spotify-api-server/src/main/resources/application.yml @@ -0,0 +1,5 @@ +server: + servlet-path: /rest/ + port: 8081 + +token: "BQC_DprHnxDYM3SwDFmL3rb63RuWdwmqmq3sEAXnpNYgf0OcWZcusYIC9eqaGk1t1iJJcyzx1j6LQx5usMrm0cK4NDjiF5_tvajqsbTxHDL6z03GPncnksjGMtp7tAaJbw3SBB1wr0vYurAFnQ" \ No newline at end of file diff --git a/spotify-api-server/src/test/java/com/spotify/api/AppTest.java b/spotify-api-server/src/test/java/com/spotify/api/AppTest.java new file mode 100644 index 0000000..acbf2c4 --- /dev/null +++ b/spotify-api-server/src/test/java/com/spotify/api/AppTest.java @@ -0,0 +1,38 @@ +package com.spotify.api; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +/** + * Unit test for simple App. + */ +public class AppTest + extends TestCase +{ + /** + * Create the test case + * + * @param testName name of the test case + */ + public AppTest( String testName ) + { + super( testName ); + } + + /** + * @return the suite of tests being tested + */ + public static Test suite() + { + return new TestSuite( AppTest.class ); + } + + /** + * Rigourous Test :-) + */ + public void testApp() + { + assertTrue( true ); + } +} diff --git a/spotify-api-ui/.gitignore b/spotify-api-ui/.gitignore new file mode 100644 index 0000000..d30f40e --- /dev/null +++ b/spotify-api-ui/.gitignore @@ -0,0 +1,21 @@ +# See https://help.github.com/ignore-files/ for more about ignoring files. + +# dependencies +/node_modules + +# testing +/coverage + +# production +/build + +# misc +.DS_Store +.env.local +.env.development.local +.env.test.local +.env.production.local + +npm-debug.log* +yarn-debug.log* +yarn-error.log* diff --git a/spotify-api-ui/config/env.js b/spotify-api-ui/config/env.js new file mode 100644 index 0000000..7c6133b --- /dev/null +++ b/spotify-api-ui/config/env.js @@ -0,0 +1,93 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const paths = require('./paths'); + +// Make sure that including paths.js after env.js will read .env variables. +delete require.cache[require.resolve('./paths')]; + +const NODE_ENV = process.env.NODE_ENV; +if (!NODE_ENV) { + throw new Error( + 'The NODE_ENV environment variable is required but was not specified.' + ); +} + +// https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use +var dotenvFiles = [ + `${paths.dotenv}.${NODE_ENV}.local`, + `${paths.dotenv}.${NODE_ENV}`, + // Don't include `.env.local` for `test` environment + // since normally you expect tests to produce the same + // results for everyone + NODE_ENV !== 'test' && `${paths.dotenv}.local`, + paths.dotenv, +].filter(Boolean); + +// Load environment variables from .env* files. Suppress warnings using silent +// if this file is missing. dotenv will never modify any environment variables +// that have already been set. +// https://github.com/motdotla/dotenv +dotenvFiles.forEach(dotenvFile => { + if (fs.existsSync(dotenvFile)) { + require('dotenv').config({ + path: dotenvFile, + }); + } +}); + +// We support resolving modules according to `NODE_PATH`. +// This lets you use absolute paths in imports inside large monorepos: +// https://github.com/facebookincubator/create-react-app/issues/253. +// It works similar to `NODE_PATH` in Node itself: +// https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders +// Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored. +// Otherwise, we risk importing Node.js core modules into an app instead of Webpack shims. +// https://github.com/facebookincubator/create-react-app/issues/1023#issuecomment-265344421 +// We also resolve them to make sure all tools using them work consistently. +const appDirectory = fs.realpathSync(process.cwd()); +process.env.NODE_PATH = (process.env.NODE_PATH || '') + .split(path.delimiter) + .filter(folder => folder && !path.isAbsolute(folder)) + .map(folder => path.resolve(appDirectory, folder)) + .join(path.delimiter); + +// Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be +// injected into the application via DefinePlugin in Webpack configuration. +const REACT_APP = /^REACT_APP_/i; + +function getClientEnvironment(publicUrl) { + const raw = Object.keys(process.env) + .filter(key => REACT_APP.test(key)) + .reduce( + (env, key) => { + env[key] = process.env[key]; + return env; + }, + { + // Useful for determining whether we’re running in production mode. + // Most importantly, it switches React into the correct mode. + NODE_ENV: process.env.NODE_ENV || 'development', + // Useful for resolving the correct path to static assets in `public`. + // For example, . + // This should only be used as an escape hatch. Normally you would put + // images into the `src` and `import` them in code to get their paths. + PUBLIC_URL: publicUrl, + } + ); + // Stringify all values so we can feed into Webpack DefinePlugin + const stringified = { + 'process.env': Object.keys(raw).reduce( + (env, key) => { + env[key] = JSON.stringify(raw[key]); + return env; + }, + {} + ), + }; + + return { raw, stringified }; +} + +module.exports = getClientEnvironment; diff --git a/spotify-api-ui/config/jest/cssTransform.js b/spotify-api-ui/config/jest/cssTransform.js new file mode 100644 index 0000000..f1534f6 --- /dev/null +++ b/spotify-api-ui/config/jest/cssTransform.js @@ -0,0 +1,14 @@ +'use strict'; + +// This is a custom Jest transformer turning style imports into empty objects. +// http://facebook.github.io/jest/docs/tutorial-webpack.html + +module.exports = { + process() { + return 'module.exports = {};'; + }, + getCacheKey() { + // The output is always the same. + return 'cssTransform'; + }, +}; diff --git a/spotify-api-ui/config/jest/fileTransform.js b/spotify-api-ui/config/jest/fileTransform.js new file mode 100644 index 0000000..ffce0da --- /dev/null +++ b/spotify-api-ui/config/jest/fileTransform.js @@ -0,0 +1,12 @@ +'use strict'; + +const path = require('path'); + +// This is a custom Jest transformer turning file imports into filenames. +// http://facebook.github.io/jest/docs/tutorial-webpack.html + +module.exports = { + process(src, filename) { + return `module.exports = ${JSON.stringify(path.basename(filename))};`; + }, +}; diff --git a/spotify-api-ui/config/paths.js b/spotify-api-ui/config/paths.js new file mode 100644 index 0000000..2efd3b7 --- /dev/null +++ b/spotify-api-ui/config/paths.js @@ -0,0 +1,55 @@ +'use strict'; + +const path = require('path'); +const fs = require('fs'); +const url = require('url'); + +// Make sure any symlinks in the project folder are resolved: +// https://github.com/facebookincubator/create-react-app/issues/637 +const appDirectory = fs.realpathSync(process.cwd()); +const resolveApp = relativePath => path.resolve(appDirectory, relativePath); + +const envPublicUrl = process.env.PUBLIC_URL; + +function ensureSlash(path, needsSlash) { + const hasSlash = path.endsWith('/'); + if (hasSlash && !needsSlash) { + return path.substr(path, path.length - 1); + } else if (!hasSlash && needsSlash) { + return `${path}/`; + } else { + return path; + } +} + +const getPublicUrl = appPackageJson => + envPublicUrl || require(appPackageJson).homepage; + +// We use `PUBLIC_URL` environment variable or "homepage" field to infer +// "public path" at which the app is served. +// Webpack needs to know it to put the right