Initial commit

This commit is contained in:
2021-02-13 11:47:33 +01:00
commit d075b14564
23 changed files with 541 additions and 0 deletions

6
.gitignore vendored Normal file
View File

@@ -0,0 +1,6 @@
/.gradle/
/.idea/
/build/
/gradle/
/gradlew.bat
/gradlew

21
LICENSE.md Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021 droideparanoico
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

38
README.md Normal file
View File

@@ -0,0 +1,38 @@
<h1>Code Sharing Platform</h1>
Web service to store syntax highlighted code snippets generating unique identifiers with the added possibility of configure its self-deletion based on time and views limitations.
There are two possible interfaces: API and web. The API interface returns data as `JSON`, while the web interface uses `HTML`, `JS`, and `CSS`.
<h2>Web interface endpoints</h2>
* `GET /` should return the starting page:
![](src/main/resources/img/index.png)
* `GET /code/new` should return the page that allows to save a new snippet:
![](src/main/resources/img/new_snippet.png)
* `GET /code/UUID` should return the page with associated code snippet:
![](src/main/resources/img/snippet.png)
* `GET /code/latest` should return the page with 10 most recently uploaded unrestricted code snippets:
![](src/main/resources/img/latest.png)
<h2>API interface endpoints</h2>
* `GET /api/code/new` should take a JSON object with a field `code` and two other fields:
&nbsp;&nbsp;&nbsp;&nbsp;1. `time` field containing the time (in seconds) during which the snippet is accessible.
&nbsp;&nbsp;&nbsp;&nbsp;2. `views` field containing a number of views allowed for this snippet.
And return JSON with a single field id:
![](src/main/resources/img/api_new_snippet.png)
* `GET /api/code/UUID` should return a JSON object with associated code snippet:
![](src/main/resources/img/api_snippet.png)
* `GET /api/code/latest` should return a JSON array the 10 most recently uploaded unrestricted code snippets:
![](src/main/resources/img/api_latest.png)

25
build.gradle Normal file
View File

@@ -0,0 +1,25 @@
plugins {
id 'org.springframework.boot' version '2.3.3.RELEASE'
id 'java'
}
apply plugin: 'io.spring.dependency-management'
sourceCompatibility = 11
repositories {
mavenCentral()
}
sourceSets.main.resources.srcDirs = ["src/main/resources"]
dependencies {
runtimeOnly 'com.h2database:h2'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter'
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'org.springframework.boot:spring-boot-starter-freemarker'
compile("org.springframework.boot:spring-boot-starter-web")
compile group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: '2.12.1'
testImplementation('org.springframework.boot:spring-boot-starter-test')
}

View File

@@ -0,0 +1,13 @@
package com.droideparanoico.codesharingplatform;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CodeSharingPlatform {
public static void main(String[] args) {
SpringApplication.run(CodeSharingPlatform.class, args);
}
}

View File

@@ -0,0 +1,39 @@
package com.droideparanoico.codesharingplatform.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import com.droideparanoico.codesharingplatform.model.CodeSnippet;
import com.droideparanoico.codesharingplatform.service.CodeSnippetService;
import java.util.Collection;
import java.util.Map;
@RestController
@RequestMapping("/api/code")
public class ApiController {
private CodeSnippetService codeSnippetService;
@Qualifier("codeSnippetService")
@Autowired
public void setService(CodeSnippetService service) {
this.codeSnippetService = service;
}
@GetMapping(path = "/{uuid}")
public CodeSnippet getCodeApi(@PathVariable String uuid) {
return codeSnippetService.getCodeSnippetById(uuid);
}
@GetMapping(path = "/latest")
public Collection<CodeSnippet> getLatestCodeApi() {
return codeSnippetService.findLatestUnrestricted();
}
@PostMapping(path = "/new", produces = "application/json;charset=UTF-8")
public Map<String, String> createNewCodeApi(@RequestBody CodeSnippet codeSnippet) {
CodeSnippet responseCode = codeSnippetService.saveCodeSnippet(codeSnippet);
return Map.of("id", responseCode.getUuid());
}
}

View File

@@ -0,0 +1,50 @@
package com.droideparanoico.codesharingplatform.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import com.droideparanoico.codesharingplatform.model.CodeSnippet;
import com.droideparanoico.codesharingplatform.service.CodeSnippetService;
import java.util.*;
@Controller
@RequestMapping("/")
public class WebController {
private CodeSnippetService codeSnippetService;
@Qualifier("codeSnippetService")
@Autowired
public void setService(CodeSnippetService service) {
this.codeSnippetService = service;
}
@GetMapping(path = "/", produces = "text/html")
public String index() {
return "index";
}
@GetMapping(path = "/code/{uuid}", produces = "text/html")
public String getCodeWeb(Model model, @PathVariable String uuid) {
model.addAttribute("codeSnippet", codeSnippetService.getCodeSnippetById(uuid));
return "snippet";
}
@GetMapping(path = "/code/latest", produces = "text/html")
public String getLatestCodeWeb(Model model) {
if (codeSnippetService.findLatestUnrestricted() != null) {
Collection<CodeSnippet> snippetCollection = codeSnippetService.findLatestUnrestricted();
List<CodeSnippet> snippetList = new ArrayList<>(snippetCollection);
model.addAttribute("codeSnippets",snippetList);
}
return "latest";
}
@GetMapping(path = "/code/new", produces = "text/html")
public String createNewCodeWeb() {
return "new_snippet";
}
}

View File

@@ -0,0 +1,96 @@
package com.droideparanoico.codesharingplatform.model;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
@Entity
@Table(name="snippets")
public class CodeSnippet {
@Id
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String uuid;
private LocalDateTime date;
@Lob
@Column
private String code;
private Long time = 0L;
private Integer views = 0;
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private boolean timeRestricted;
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private boolean viewRestricted;
static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public LocalDateTime getDate() {
return date;
}
@JsonProperty("date")
public String getFormattedDate() {
return date == null ? "" : formatter.format(date);
}
public void setDate(LocalDateTime date) {
this.date = date;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Long getTime() {
return time;
}
@JsonGetter("time")
public Long getTimeAvailable() {
return time == 0 ? 0 : time - date.until(LocalDateTime.now(), ChronoUnit.SECONDS);
}
public void setTime(Long time) {
this.time = time;
}
public Integer getViews() {
return views;
}
public void setViews(Integer views) {
this.views = views;
}
public boolean isTimeRestricted() {
return timeRestricted;
}
public void setTimeRestricted(boolean timeRestricted) {
this.timeRestricted = timeRestricted;
}
public boolean isViewRestricted() {
return viewRestricted;
}
public void setViewRestricted(boolean viewRestricted) {
this.viewRestricted = viewRestricted;
}
}

View File

@@ -0,0 +1,11 @@
package com.droideparanoico.codesharingplatform.repository;
import org.springframework.data.repository.CrudRepository;
import com.droideparanoico.codesharingplatform.model.CodeSnippet;
import java.util.Collection;
public interface CodeSnippetRepository extends CrudRepository<CodeSnippet, String> {
Collection<CodeSnippet> findTop10ByTimeEqualsAndViewsEqualsOrderByDateDesc(Long time, Integer views);
}

View File

@@ -0,0 +1,68 @@
package com.droideparanoico.codesharingplatform.service;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import com.droideparanoico.codesharingplatform.model.CodeSnippet;
import com.droideparanoico.codesharingplatform.repository.CodeSnippetRepository;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.UUID;
@Service("codeSnippetService")
public class CodeSnippetService {
private final CodeSnippetRepository codeSnippetRepository;
public CodeSnippetService(CodeSnippetRepository codeSnippetRepository) {
this.codeSnippetRepository = codeSnippetRepository;
}
public CodeSnippet getCodeSnippetById(final String uuid) {
CodeSnippet codeSnippet = codeSnippetRepository.findById(uuid).orElseThrow(
() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
if (codeSnippet.isViewRestricted()) {
checkViewsRestriction(codeSnippet);
}
if (codeSnippet.isTimeRestricted()) {
checkTimeRestriction(codeSnippet);
}
return codeSnippetRepository.save(codeSnippet);
}
public CodeSnippet saveCodeSnippet(final CodeSnippet codeSnippet) {
codeSnippet.setUuid(UUID.randomUUID().toString());
codeSnippet.setDate(LocalDateTime.now());
codeSnippet.setTimeRestricted(codeSnippet.getTime() > 0);
codeSnippet.setViewRestricted(codeSnippet.getViews() > 0);
return codeSnippetRepository.save(codeSnippet);
}
public Collection<CodeSnippet> findLatestUnrestricted() {
return codeSnippetRepository.findTop10ByTimeEqualsAndViewsEqualsOrderByDateDesc(0L, 0);
}
private void checkViewsRestriction(final CodeSnippet codeSnippet) {
if (codeSnippet.getViews() > 0) {
codeSnippet.setViews(codeSnippet.getViews() - 1);
} else {
deleteSnippet(codeSnippet);
}
}
private void checkTimeRestriction(final CodeSnippet codeSnippet) {
if (codeSnippet.getTimeAvailable() < 0) {
deleteSnippet(codeSnippet);
}
}
private void deleteSnippet(final CodeSnippet codeSnippet) {
codeSnippetRepository.delete(codeSnippet);
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
}
}

View File

@@ -0,0 +1,15 @@
server.port=8889
management.endpoints.web.exposure.include=*
management.endpoint.shutdown.enabled=true
spring.datasource.url=jdbc:h2:file:../snippets
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true
spring.h2.console.settings.trace=false
spring.h2.console.settings.web-allow-others=false

Binary file not shown.

After

Width:  |  Height:  |  Size: 137 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 138 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

View File

@@ -0,0 +1,26 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>Code sharing platform</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet"
href="//cdn.jsdelivr.net/gh/highlightjs/cdn-release@10.2.1/build/styles/default.min.css">
<script src="//cdn.jsdelivr.net/gh/highlightjs/cdn-release@10.2.1/build/highlight.min.js"></script>
</head>
<body>
<div class="jumbotron col-sm-8 mx-auto mt-4">
<h1 class="display-4">Code sharing platform</h1>
<p class="lead">Web service to store syntax highlighted code snippets generating unique identifiers with the added possibility of configure its self-deletion based on time and views limitations.</p>
<hr class="my-4">
<div class="row">
<div class="col">
<a class="btn btn-primary btn-lg d-flex justify-content-center" href="http://localhost:8889/code/new" role="button">Create new snippet</a>
</div>
<div class="col">
<a class="btn btn-primary btn-lg d-flex justify-content-center" href="http://localhost:8889/code/latest" role="button">See latest snippets</a>
</div>
</div>
</div>
</body>
</html>

View File

@@ -0,0 +1,27 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>Latest</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet"
href="//cdn.jsdelivr.net/gh/highlightjs/cdn-release@10.2.1/build/styles/default.min.css">
<script src="//cdn.jsdelivr.net/gh/highlightjs/cdn-release@10.2.1/build/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
</head>
<body>
<h1 class="col-sm-8 mx-auto mt-4">Latest snippets</h1>
<#if codeSnippets??>
<#list codeSnippets as codeSnippet>
<div class="col-sm-8 mx-auto mt-4 d-flex">
<div class="card">
<div class="card-body">
<span class="card-title" id="load_date">${codeSnippet.formattedDate}</span>
<pre id="code_snippet" class="card-text"><code>${codeSnippet.code}</code></pre>
</div>
</div>
</div>
</#list>
</#if>
</body>
</html>

View File

@@ -0,0 +1,63 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<title>Create</title>
</head>
<body>
<h1 class="col-sm-8 mx-auto mt-4">New snippet</h1>
<div class="col-sm-8 mx-auto mt-4 d-flex">
<div class="card" style="min-width: 100%">
<div class="card-body">
<form>
<div class="form-group">
<textarea class="form-control" rows="5" id="code_snippet" placeholder="// write your code here"></textarea>
</div>
<div class="container">
<div class="row align-items-end">
<div class="col">
<label for="time_restriction">Expiration seconds:</label>
<input type="number" min="0" class="form-control" style="max-width: 120px" id="time_restriction">
</div>
<div class="col">
<label for="views_restriction">Expiration views:</label>
<input type="number" min="0" class="form-control" style="max-width: 120px" id="views_restriction">
</div>
<div class="col">
<div class="float-right">
<button id="send_snippet" type="submit" class="btn btn-primary btn-lg" onclick="send();">Save snippet</button>
</div>
</div>
</div>
</div>
<script>
window.onload = function(){
document.getElementById("time_restriction").value=0
document.getElementById("views_restriction").value=0
};
function send() {
let object = {
"code": document.getElementById("code_snippet").value,
"time": document.getElementById("time_restriction").value,
"views": document.getElementById("views_restriction").value
};
let json = JSON.stringify(object);
let xhr = new XMLHttpRequest();
xhr.open("POST", '/api/code/new', false)
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
xhr.send(json);
if (xhr.status === 200) {
let uuid = xhr.responseText.substring(6, xhr.responseText.length - 1);
alert("Success! new snippet: " + uuid);
window.open("http://localhost:8889/code/" + uuid.replace(/"/g, ""));
}
}
</script>
</form>
</div>
</div>
</div>
</body>
</html>

View File

@@ -0,0 +1,31 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>Code</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet"
href="//cdn.jsdelivr.net/gh/highlightjs/cdn-release@10.2.1/build/styles/default.min.css">
<script src="//cdn.jsdelivr.net/gh/highlightjs/cdn-release@10.2.1/build/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
</head>
<body>
<div class="col-sm-8 mx-auto mt-4 d-flex">
<div class="card">
<div class="card-body">
<#if codeSnippet??>
<span class="card-title" id="load_date">${codeSnippet.formattedDate}</span>
<pre id="code_snippet" class="card-text"><code>${codeSnippet.code}</code></pre>
<#if (codeSnippet.isViewRestricted())>
<span id="views_restriction">${codeSnippet.views} more views allowed</span>
<br>
</#if>
<#if (codeSnippet.isTimeRestricted())>
<span id="time_restriction">This code will be available for ${codeSnippet.timeAvailable} seconds</span>
</#if>
</#if>
</div>
</div>
</div>
</body>
</html>

View File

@@ -0,0 +1,12 @@
package com.droideparanoico.codesharingplatform;
import org.springframework.boot.test.context.SpringBootTest;
import org.junit.Test;
@SpringBootTest
public class CodeSharingPlatformTest {
@Test
public void contextLoads() {
}
}