Commit 728cd7d2 authored by Yecid Guerrero's avatar Yecid Guerrero

Initial commit

parents
HELP.md
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
# springboot-sample-app
[![Build Status](https://travis-ci.org/codecentric/springboot-sample-app.svg?branch=master)](https://travis-ci.org/codecentric/springboot-sample-app)
[![Coverage Status](https://coveralls.io/repos/github/codecentric/springboot-sample-app/badge.svg?branch=master)](https://coveralls.io/github/codecentric/springboot-sample-app?branch=master)
[![License](http://img.shields.io/:license-apache-blue.svg)](http://www.apache.org/licenses/LICENSE-2.0.html)
Minimal [Spring Boot](http://projects.spring.io/spring-boot/) sample app.
## Requirements
For building and running the application you need:
- [Java 16](https://www.oracle.com/java/technologies/javase-jdk16-downloads.html)
- [Maven 3](https://maven.apache.org)
## Running the application locally
There are several ways to run a Spring Boot application on your local machine. One way is to execute the `main` method in the `de.codecentric.springbootsample.Application` class from your IDE.
Alternatively you can use the [Spring Boot Maven plugin](https://docs.spring.io/spring-boot/docs/current/reference/html/build-tool-plugins-maven-plugin.html) like so:
```shell
mvn spring-boot:run
```
## Deploying the application to OpenShift
The easiest way to deploy the sample application to OpenShift is to use the [OpenShift CLI](https://docs.openshift.org/latest/cli_reference/index.html):
```shell
oc new-app codecentric/springboot-maven3-centos~https://github.com/codecentric/springboot-sample-app
```
This will create:
* An ImageStream called "springboot-maven3-centos"
* An ImageStream called "springboot-sample-app"
* A BuildConfig called "springboot-sample-app"
* DeploymentConfig called "springboot-sample-app"
* Service called "springboot-sample-app"
If you want to access the app from outside your OpenShift installation, you have to expose the springboot-sample-app service:
```shell
oc expose springboot-sample-app --hostname=www.example.com
```
## Copyright
Released under the Apache License 2.0. See the [LICENSE](https://github.com/codecentric/springboot-sample-app/blob/master/LICENSE) file.
<img src="https://upload.wikimedia.org/wikipedia/commons/c/cb/Gradle_logo.png" width="350px" alt="Gradle Logo" />
[![Revved up by Gradle Enterprise](https://img.shields.io/badge/Revved%20up%20by-Gradle%20Enterprise-06A0CE?logo=Gradle&labelColor=02303A)](https://ge.gradle.org/scans)
[![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/4898/badge)](https://bestpractices.coreinfrastructure.org/projects/4898)
[Gradle](https://gradle.org/) is a build tool with a focus on build automation and support for multi-language development. If you are building, testing, publishing, and deploying software on any platform, Gradle offers a flexible model that can support the entire development lifecycle from compiling and packaging code to publishing web sites. Gradle has been designed to support build automation across multiple languages and platforms including Java, Scala, Android, Kotlin, C/C++, and Groovy, and is closely integrated with development tools and continuous integration servers including Eclipse, IntelliJ, and Jenkins.
**For more information, please visit the [official project homepage](https://gradle.org)**
\ No newline at end of file
plugins {
id 'org.springframework.boot' version '2.5.3'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
id 'war'
}
group = 'com.git'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '16'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
// https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient
implementation group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.13'
// https://mvnrepository.com/artifact/com.google.code.gson/gson
implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.6'
}
test {
useJUnitPlatform()
}
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.1.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MSYS* | MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
rootProject.name = 'files'
package com.git.files;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class FilesApplication {
public static void main(String[] args) {
SpringApplication.run(FilesApplication.class, args);
}
}
package com.git.files;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(FilesApplication.class);
}
}
package com.git.files.controllers;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import com.git.files.model.FileInfo;
import com.git.files.model.Tree;
import com.git.files.util.RestFullClient;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.http.MediaType;
// REFERENCIAS
// https://docs.gitlab.com/ee/api/repository_files.html
// https://itsallbinary.com/github-rest-api-get-remote-github-repo-files-list-download-file-content-programmatically-without-cloning-in-local/
@Controller
@RequestMapping("/api")
public class FilesController {
public static final String HOST = "gitlab.com/api/v4";
public static final String TOKEN = "KKtS27izRvyuMkemR_hN";
public static final String PROJECT_ID = "28780914";
public static final String BRANCH = "main";
public static final String FOLDER = "plantillas";
@GetMapping(path = "/files/dowload", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
@ResponseBody
public ResponseEntity<byte[]> dowloadFile(@RequestParam("file_name") String file_name, @RequestParam("ref") String ref, HttpServletResponse response) throws Exception {
try {
// respuesta send headers
response.addHeader("Content-Disposition", "attachment; filename=" + file_name + "; filename*=UTF-8''" + file_name);
// send header peticion
RestFullClient rfc = new RestFullClient();
String file_path = URLEncoder.encode(file_name, StandardCharsets.UTF_8);
String URI = "https://" + HOST + "/projects/" + PROJECT_ID + "/repository/files/{file_path}/raw?ref={ref}";
Map<String, String> params = new HashMap<String, String>();
params.put("ref", ref);
params.put("file_path", file_path);
byte[] resp = rfc.dowload(URI, params);
return ResponseEntity.status(HttpStatus.OK ).body(resp);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(null);
}
}
// ******************************************************************************************************
// LISTAR LOS ARCHIVOS
// ******************************************************************************************************
@GetMapping("/files/v2/get")
@ResponseBody
public ResponseEntity<Tree[]> getAllByName(@RequestParam("ref") String ref) throws Exception {
try {
String URI = "https://" + HOST + "/projects/" + PROJECT_ID + "/repository/tree?ref={ref}";
RestFullClient rfc = new RestFullClient();
Map<String, String> params = new HashMap<String, String>();
params.put("ref", ref);
Tree[] resp = rfc.getList(URI, params);
return ResponseEntity.status(HttpStatus.OK ).body(resp);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(null);
}
}
// ******************************************************************************************************
// CREAR EL ARCHIVO
// ******************************************************************************************************
@PostMapping("files/v2/store")
public ResponseEntity<FileInfo> createFilev2(@RequestBody FileInfo file) {
try {
String URI = "https://" + HOST + "/projects/" + PROJECT_ID + "/repository/files/" + file.getFile_name();
RestFullClient rfc = new RestFullClient();
FileInfo resp = rfc.post(file, URI);
return ResponseEntity.status(HttpStatus.OK ).body(resp);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(null);
}
}
// ******************************************************************************************************
// ACTUALIZAR EL ARCHIVO
// ******************************************************************************************************
@PutMapping("files/v2/update")
public ResponseEntity<FileInfo> updateFilev2(@RequestBody FileInfo file) {
try {
//String file_path = URLEncoder.encode(file.getFile_name(), StandardCharsets.UTF_8);
String URI = "https://" + HOST + "/projects/" + PROJECT_ID + "/repository/files/" + file.getFile_name();
RestFullClient rfc = new RestFullClient();
FileInfo resp = rfc.put(file, URI);
return ResponseEntity.status(HttpStatus.OK ).body(resp);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(null);
}
}
// ******************************************************************************************************
// ELIMINAR EL ARCHIVO
// ******************************************************************************************************
@DeleteMapping("files/v2/delete")
public ResponseEntity<String> deleteFilev2(@RequestBody FileInfo file) {
try {
//String file_path = URLEncoder.encode(file.getFile_name(), StandardCharsets.UTF_8);
String URI = "https://" + HOST + "/projects/" + PROJECT_ID + "/repository/files/" + file.getFile_name();
RestFullClient rfc = new RestFullClient();
rfc.delete(file, URI);
return ResponseEntity.status(HttpStatus.OK).body("Deleted!");
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(e.getMessage());
}
}
}
package com.git.files.controllers;
import com.git.files.model.FileInfo;
import com.google.gson.Gson;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/")
public class HomeController {
/**
*
*/
private static final String file = "{'file_name':'Prueba.docx','file_path':'plantillas/Prueba.docx','size':35908,'encoding':'base64','content_sha256':'b1fc4f15c61d9c0a254f90d48599021fb33fe2bac500b9dfc0665c2ae00110b3','ref':'main','blob_id':'895547486ac85b7f8f38d23ef906b535a44527fa','commit_id':'eb8de36c8c9c59452cd390565a4d8fe095820085','last_commit_id':'eb8de36c8c9c59452cd390565a4d8fe095820085'}";
@GetMapping("")
public FileInfo findAll(){
Gson g = new Gson();
FileInfo p = g.fromJson(file, FileInfo.class);
return p;
}
}
package com.git.files.model;
public class FileInfo {
private String file_name;
private String file_path;
private int size;
private String encoding = "base64";
private String content;
private String content_sha256;
private String ref;
private String blob_id;
private String commit_id;
private String last_commit_id;
// Campos adicionales
private String branch;
private String author_email;
private String author_name;
private String commit_message;
public String getFile_name() {
return this.file_name;
}
public void setFile_name(String file_name) {
this.file_name = file_name;
}
public String getFile_path() {
return this.file_path;
}
public void setFile_path(String file_path) {
this.file_path = file_path;
}
public int getSize() {
return this.size;
}
public void setSize(int size) {
this.size = size;
}
public String getEncoding() {
return this.encoding;
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public String getContent() {
return this.content;
}
public void setContent(String content) {
this.content = content;
}
public String getContent_sha256() {
return this.content_sha256;
}
public void setContent_sha256(String content_sha256) {
this.content_sha256 = content_sha256;
}
public String getRef() {
return this.ref;
}
public void setRef(String ref) {
this.ref = ref;
}
public String getBlob_id() {
return this.blob_id;
}
public void setBlob_id(String blob_id) {
this.blob_id = blob_id;
}
public String getCommit_id() {
return this.commit_id;
}
public void setCommit_id(String commit_id) {
this.commit_id = commit_id;
}
public String getLast_commit_id() {
return this.last_commit_id;
}
public void setLast_commit_id(String last_commit_id) {
this.last_commit_id = last_commit_id;
}
public String getAuthor_email() {
return this.author_email;
}
public void setAuthor_email(String author_email) {
this.author_email = author_email;
}
public String getAuthor_name() {
return this.author_name;
}
public void setAuthor_name(String author_name) {
this.author_name = author_name;
}
public String getCommit_message() {
return this.commit_message;
}
public void setCommit_message(String commit_message) {
this.commit_message = commit_message;
}
public String getBranch() {
return this.branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
}
\ No newline at end of file
package com.git.files.model;
public class Tree {
private String id;
private String name;
private String type;
private String path;
private String mode;
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
}
public String getPath() {
return this.path;
}
public void setPath(String path) {
this.path = path;
}
public String getMode() {
return this.mode;
}
public void setMode(String mode) {
this.mode = mode;
}
}
\ No newline at end of file
package com.git.files.util;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.git.files.model.FileInfo;
import com.git.files.model.Tree;
import com.google.gson.Gson;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
public class RestFullClient {
public static final String TOKEN = "KKtS27izRvyuMkemR_hN";
RestTemplate restTemplate;
public RestFullClient() {
this.restTemplate = new RestTemplate();
}
public HttpHeaders createHttpHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setBearerAuth(TOKEN);
return headers;
}
public Tree[] getList(String urlApi, Map<String, String> params) throws JsonProcessingException {
ResponseEntity<Tree[]> response = restTemplate.exchange(urlApi, HttpMethod.GET,
new HttpEntity<>(createHttpHeaders()), Tree[].class, params);
if (response.getStatusCodeValue() == 200 || response.getStatusCodeValue() == 201
|| response.getStatusCodeValue() == 202) {
return response.getBody();
} else {
return null;
}
}
public byte[] dowload(String urlApi, Map<String, String> params) throws JsonProcessingException {
ResponseEntity<byte[]> response = restTemplate.exchange(urlApi, HttpMethod.GET,
new HttpEntity<>(createHttpHeaders()), byte[].class, params);
if (response.getStatusCodeValue() == 200 || response.getStatusCodeValue() == 201
|| response.getStatusCodeValue() == 202) {
return response.getBody();
} else {
return null;
}
}
public FileInfo post(FileInfo requestDTO, String urlApi) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
String jsonInString = mapper.writeValueAsString(requestDTO);
ResponseEntity<FileInfo> response = restTemplate.exchange(urlApi, HttpMethod.POST,
new HttpEntity<>(jsonInString, createHttpHeaders()), FileInfo.class);
if (response.getStatusCodeValue() == 200 || response.getStatusCodeValue() == 201
|| response.getStatusCodeValue() == 202) {
return response.getBody();
} else {
return null;
}
}
public FileInfo put(FileInfo requestDTO, String urlApi) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
String jsonInString = mapper.writeValueAsString(requestDTO);
ResponseEntity<FileInfo> response = restTemplate.exchange(urlApi, HttpMethod.PUT,
new HttpEntity<>(jsonInString, createHttpHeaders()), FileInfo.class);
if (response.getStatusCodeValue() == 200 || response.getStatusCodeValue() == 201
|| response.getStatusCodeValue() == 202) {
return response.getBody();
} else {
return new FileInfo();
}
}
public Boolean delete(FileInfo requestDTO, String urlApi) throws JsonProcessingException {
Gson gson = new Gson();
String jsonPayload = gson.toJson(requestDTO);
HttpEntity<String> entity = new HttpEntity<String>(jsonPayload.toString(), createHttpHeaders());
ResponseEntity<String> response = restTemplate.exchange(urlApi, HttpMethod.DELETE, entity, String.class);
if (response.getStatusCodeValue() == 204 || response.getStatusCodeValue() == 200
|| response.getStatusCodeValue() == 201 || response.getStatusCodeValue() == 202) {
return true;
} else {
return false;
}
}
}
package com.git.files;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class FilesApplicationTests {
@Test
void contextLoads() {
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment