Java
Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible.
Before adding any code, make sure to follow the Initial Setup at the start of this section to set up your content in Cosmic. Then take the following steps to add Cosmic-powered content to your Java apps:
1. Downloading the essentials
- Download and Install Java 1.8 JDK on your computer. You can follow this guide or any other material on the web for the installation.
- Download and install the IntelliJ Community edition. We will be using IntelliJ IDE for this guide.
2. Create a new Java Spring Boot Project
- Go to https://start.spring.io where you can see the spring Initializer page to create spring Boot application
- The only things you want to change in this form is the artifact name, you can call this “cosmicapp” in Artifact. Also, select Java 8 at the bottom of the page.
- Click Generate the project and you will get a zip file named
cosmicapp.zip
. - Unzip anywhere on your computer, and you can find a folder named
cosmicapp
. - Open your IntelliJ IDE and select “Import Project” option in the welcome screen.
- Change folder path to your cosmicapp folder which you just extracted, and click OK.
- Select “Import Project from external model”, and select Maven. (if you don’t see Maven, make sure you install IntelliJ Maven plugin, link: https://www.jetbrains.com/help/idea/maven-support.html).
3. Configure the pom.xml
file to manage the dependencies
We now need to add the following dependencies into maven’s configuration file. Copy the below content into your pom.xml
file.
#pom.xml<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.3.3.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.example</groupId><artifactId>demo1</artifactId><version>0.0.1-SNAPSHOT</version><name>demo1</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope><exclusions><exclusion><groupId>org.junit.vintage</groupId><artifactId>junit-vintage-engine</artifactId></exclusion></exclusions></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
Right-Click on pom.xml
file and Select (Maven -> Reimport) to import all the dependencies in your project.
4. Adding Cosmic Credentials to Java Spring Boot Project
Inside the folder src/main/resources
, add the Cosmic credentials to the application.properties
file. You can find your Bucket slug and API read key in Bucket Settings > API Access after logging in.
#src/main/resources/application.propertiesslug = <add cosmic bucket slug here>read_key = <add cosmic bucket read key here>
5. Create the service component of Java Spring Boot App
Inside the folder src/main/java
, right-click on com.example.cosmicapp
package and add a new package named service
by selecting (New -> Package).
Now right-click on com.example.cosmicapp.service
package, select (New -> Class) and add a Java class named JsonParsingService.java
.
# src/main/java/com/example/cosmicapp/service/JsonParsingService.javapackage com.example.cosmicapp.service;import org.springframework.stereotype.Service;import org.springframework.web.client.RestTemplate;@Servicepublic class JsonParsingService {private RestTemplate restTemplate = new RestTemplate();public Object parse(String url) {return restTemplate.getForObject(url, Object.class);}}
6. Create the domain component of Java Spring Boot App
Inside the folder src/main/java
, right-click on com.example.cosmicapp
package and add a new package named domain
by selecting (New -> Package).
- Right click on
com.example.cosmicapp.domain
package, select (New -> Class), and add Java Class namedBucket.java
.
#src/main/java/com/example/cosmicapp/domain/Bucket.javapackage com.example.cosmicapp.domain;import com.fasterxml.jackson.annotation.JsonIgnoreProperties;import java.util.List;@JsonIgnoreProperties(ignoreUnknown = true)public class Bucket {public List<Object> objects;}
- Create another Java class
Object.java
inside the packagecom.example.cosmicapp.domain
in a similar way as above.
#src/main/java/com/example/cosmicapp/domain/Object.javapackage com.example.cosmicapp.domain;import com.fasterxml.jackson.annotation.JsonIgnoreProperties;@JsonIgnoreProperties(ignoreUnknown = true)public class Object {public String slug;public String title;public String content;public Metadata metadata;public Metadata getMetadata() {return metadata;}public void setMetadata(Metadata metadata) {this.metadata = metadata;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getContent() {return content;}public void setContent(String content) {this.content = content;}public String getSlug() {return slug;}public void setSlug(String slug) {this.slug = slug;}}
- Add another Java class
Metadata.java
inside the packagecom.example.cosmicapp.domain
in a similar way as above.
#src/main/java/com/example/cosmicapp/domain/Metadata.javapackage com.example.cosmicapp.domain;import com.fasterxml.jackson.annotation.JsonIgnoreProperties;@JsonIgnoreProperties(ignoreUnknown = true)public class Metadata {public Hero hero;public Hero getHero() {return hero;}public void setHero(Hero hero) {this.hero = hero;}}
- Add the last Java class
Hero.java
inside the packagecom.example.cosmicapp.domain
in a similar way as above.
#src/main/java/com/example/cosmicapp/domain/Hero.javapackage com.example.cosmicapp.domain;import com.fasterxml.jackson.annotation.JsonIgnoreProperties;@JsonIgnoreProperties(ignoreUnknown = true)public class Hero {public String url;public String imgix_url;public String getUrl() {return url;}public void setUrl(String url) {this.url = url;}public String getImgix_url() {return imgix_url;}public void setImgix_url(String imgix_url) {this.imgix_url = imgix_url;}}
7. Add the Controller component to the Java Spring Boot App
Inside the folder src/main/java
, right-click on com.example.cosmicapp
package and add a new package named controller
by selecting (New -> Package).
Now right-click on com.example.cosmicapp.controller
package, select (New -> Class), and add Java class named Bucket.java
.
#src/main/java/com/example/cosmicapp/controller/MainController.javapackage com.example.cosmicapp.controller;import com.example.cosmicapp.domain.Bucket;import com.example.cosmicapp.domain.Object;import com.example.cosmicapp.service.JsonParsingService;import com.fasterxml.jackson.databind.ObjectMapper;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.core.env.Environment;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.util.UriComponentsBuilder;import java.util.LinkedHashMap;@Controllerpublic class MainController {@Autowiredprivate Environment env;private static final String MAIN_PAGE = "main";private static final String baseURL = "https://api.cosmicjs.com/v1/";private static final String type = "posts";private static final String props = "slug,title,content,metadata,";@AutowiredJsonParsingService jsonParsingService;@GetMappingpublic String main(final Model model) {String url = baseURL + env.getProperty("slug") + "/objects";UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url).queryParam("type", type).queryParam("read_key", env.getProperty("read_key")).queryParam("props", props);LinkedHashMap<String, Object> objectsLinkedHashMap = (LinkedHashMap<String, Object>) jsonParsingService.parse(builder.toUriString());ObjectMapper mapper = new ObjectMapper();Bucket bucket = mapper.convertValue(objectsLinkedHashMap, Bucket.class);model.addAttribute("objects", bucket.objects);return MAIN_PAGE;}}
8. Update Views
Render your posts in the src/main/resources/templates/main.html
with the following code:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"><head><title>List of Posts</title><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"></link></head><body><h1> List of Posts</h1><div class="container"><div th:each="post : ${objects}"><div th:if="${post.metadata != null && post.metadata.hero != null} "><img th:src="${post.metadata.hero.url}" width='500px' /></div><div th:text="${post.title}"></div><br><br></div></div><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script><script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script></body></html>
9. Start your app
Start your Spring Boot application by running the command below, and go to http://localhost:8080. Dance 🎉
mvn spring-boot:run