Commit c7b14f08 by 敖文武

Initial commit

parents
.idea/
DSM-JAW.iml
target/
\ No newline at end of file
language: java
jdk:
- openjdk8
before_install:
- mkdir src/main/resources/
- touch src/main/resources/env.properties
- printf 'host=%s\nport=%s\nusername=%s\npassword=%s'
$host $port $username $password > src/main/resources/env.properties
- mvn clean
## Release 1.2.1 - 2020-10-08
- Add support for FileStation tasks: `Search`, `Favorite`, `DirSize`
## Release 1.1.2 - 2020-10-01
- Add support for FileStation tasks: `createFolder`, `share`, `rename`
`copy`, `move`
- Refactoring the code, put some classes into new packages
## Release 1.0.2 - 2020-09-24
### Added
- Add support for FileStation basic tasks: `login`, `logout`, `upload`, `download`
`delete`, `ls`
- Add README, Licence and documentations
- Add stable maven pom.xml and Travis CI configuration for tests
MIT License
Copyright (c) 2020 cenyo medewou
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.
# DSM4J
[![Build Status](https://travis-ci.com/ccenyo/DSM4J.svg?branch=master)](https://travis-ci.com/github/ccenyo/DSM4J)
[![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.github.ccenyo/DSM4J/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.github.ccenyo/DSM4J)
Dsm for java is an open source java library for Synology DSM Api, it's basically a wrapper for the API.
you can find all information about the api [here](https://global.download.synology.com/download/Document/Software/DeveloperGuide/Package/FileStation/All/enu/Synology_File_Station_API_Guide.pdf) available for developers who want's to know how the api works.
If you find yourself on this page, it means that you have a java project and you need to communicate with your Nas Synology.
This wrapper can be a great startup for that.
I am trying to build the most complete wrapper for synology.
You are welcome if you want to help me, I will be greatfull.
##Prerequisites
This project is written in java 8. you can only use it in a project that uses java 8 and above.
if you want to use it in any environment, make sure you the right JVM installed on the machine.
##Integration tests
Most of the tests need an actual Synology Nas.
Make sure you have the Synology in the same network as your server, or set a DDNS to access your synology easily from internet. Look at this official tutorial : [How to make Synology NAS accessible over the Internet](https://www.synology.com/en-global/knowledgebase/DSM/tutorial/Network/How_to_make_Synology_NAS_accessible_over_the_Internet)
Don't forget to use the firewall to restrict unknown ip from accessing your portal.
you have to define an environment file in your resource folder``env.properties`` in which you have to put this lines :
| host=http://example.diskstation.me |
| --- |
| port=5000 |
| username=user |
| password=passwd |
## How to use it
add the maven repository to your pom.xml
```java
<dependency>
<groupId>com.github.ccenyo</groupId>
<artifactId>DSM4J</artifactId>
<version>1.2.1</version>
</dependency>
```
##Basic usage
```java
DsmAuth auth = DsmAuth.fromResource("env.properties");
DsmFileStationClient client = DsmFileStationClient.login(auth);
//get the list of all folders in a ROOT_FOLDER = /homes
Response<DsmListFolderResponse> response = client.ls(ROOT_HOME).call();
//Files
response.getData().getFiles();
```
you can create an ``auth`` object in different ways
```java
DsmAuth auth = DsmAuth.fromResource("env.properties");
```
or
```java
DsmAuth dsmAuth = DsmAuth.fromFile(file);
```
or
```java
DsmAuth dsmAuth = DsmAuth.of(host, port, username, password);
```
## Non blocking usage
Some features are non-blocking you have to start the request and then check the status before getting the result
```java
Response<DsmDeleteResponse> deleteResponse = client.advancedDelete()
.addFileToDelete(ROOT_FOLDER+"/"+fileToDownload.getName())
.start();
Response<DsmDeleteResponse> statusResponse = client.advancedDelete()
.taskId(deleteResponse.getData().getTaskid())
.status();
// you can stop the request if you don't want the result anymore
client.advancedDelete()
.taskId(deleteResponse.getData().getTaskid())
.stop();
```
## Features
#### FileStation features
| Feature | API | method | Description
| --- | --- |--- |---
| Login session | `SYNO.API.Auth` | login | Login to synology dsm
| Logout session | `SYNO.API.Auth` | logout | Logout
| List all shared folders | `SYNO.FileStation.List` | list_share | List all shared folders, and get detailed file information
| List of folders/files | `SYNO.FileStation.List` | list | Enumerate files in a shared folder, and get detailed file information
| upload file | `SYNO.FileStation.Upload` | upload | Upload content to the cloud.
| Download files | `SYNO.FileStation.Download` | download | Download files/folders. If only one file is specified, the file content is responded. If more than one file/folder is given, binary content in ZIP format which they are compressed to is responded.
| Delete a file or folder | `SYNO.FileStation.Delete` | delete | Delete file synchoniously
| Delete a file or folder | `SYNO.FileStation.Delete` | start/status/stop | Delete file asynchoniously, non-blocking method
| Rename a file or folder | `SYNO.FileStation.Rename` | rename | rename files or folders
| Copy or move file/folder | `SYNO.FileStation.CopyMove` | start/status/stop | copy or move folder or file asynchroniously
| Create folder |`SYNO.FileStation.CreateFolder`| create | Create new Folder
| Favorite to file/folder |`SYNO.FileStation.Favorite` | add,edit,delete, replace, clrear | add favorite on folder or file
| Share file of folder |`SYNO.FileStation.Sharing` | create,edit,delete, info, clear_invalid | Share a file of folder ans get a link
| Get file or folder size |`SYNO.FileStation.DirSize` | start/status/stop | get the size of file or folder
| Search for file of folder |`SYNO.FileStation.Search` | start/list/stop | look for file or folder and get all informations
If you don't know how to use the methods, feel free to look at the tests, i always make sure to use the methods in different ways in the tests.
##RoadMap
I will be completing new methods regularely
* Adding rest of methods for FileStation : Thumb, VirtualFolder, MD5, CheckPermission, Extract, Compress, BackgroundTask
* Adding features for DownloadStation
* Adding features for AudioStation
## Built With
* [Java SDK 8](https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html) - Java™ Platform
* [Maven](https://maven.apache.org/) - Dependency Management
## Author
* **Cenyo Medewou** - [medewou@gmail.com](mailto:medewou@gmail.com).
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sw.common</groupId>
<artifactId>DSM4J-SW</artifactId>
<version>1.2.2</version>
<description>A java wrapper for Synology DSM API</description>
<name>DSM for Java in chaocai</name>
<url>https://github.com/ccenyo/DSM4J</url>
<licenses>
<license>
<name>MIT License</name>
<url>https://github.com/ccenyo/DSM4J/blob/master/LICENSE</url>
</license>
</licenses>
<developers>
<developer>
<name>Cenyo Medewou</name>
<email>medewou@gmail.com</email>
</developer>
</developers>
<properties>
<sonar.core.codeCoveragePlugin>jacoco</sonar.core.codeCoveragePlugin>
<sonar.jacoco.reportPath>${project.basedir}/../target/jacoco.exec</sonar.jacoco.reportPath>
<sonar.language>java</sonar.language>
</properties>
<distributionManagement>
<snapshotRepository>
<id>ossrh</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
</snapshotRepository>
<repository>
<id>ossrh</id>
<url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
</repository>
</distributionManagement>
<scm>
<connection>scm:git:https://github.com/ccenyo/DSM4J.git</connection>
<developerConnection>scm:git:ssh://git@github.com/ccenyo/DSM4J.git</developerConnection>
<url>https://github.com/ccenyo/DSM4J</url>
<tag>DSM4J-1.1.0</tag>
</scm>
<profiles>
<profile>
<id>release</id>
<build>
<plugins>
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.6.8</version>
<extensions>true</extensions>
<configuration>
<serverId>ossrh</serverId>
<nexusUrl>https://oss.sonatype.org/</nexusUrl>
<autoReleaseAfterClose>true</autoReleaseAfterClose>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.1</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>1.6</version>
<executions>
<execution>
<id>sign-artifacts</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.9.1</version>
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.2.201409121644</version>
<configuration>
<append>true</append>
</configuration>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>post-unit-test</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>2.5.3</version>
<configuration>
<autoVersionSubmodules>true</autoVersionSubmodules>
<useReleaseProfile>false</useReleaseProfile>
<releaseProfiles>release</releaseProfiles>
<goals>deploy</goals>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.0.pr2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.10</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.11</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
package clients;
import exeptions.DsmLoginException;
import requests.DsmAuth;
import requests.filestation.action.DsmCopyMoveRequest;
import requests.filestation.action.DsmCreateFolderRequest;
import requests.filestation.action.DsmDirSizeRequest;
import requests.filestation.action.DsmRenameRequest;
import requests.filestation.delete.DsmAdvancedDeleteRequest;
import requests.filestation.delete.DsmSimpleDeleteRequest;
import requests.filestation.favorite.DsmListFavoriteRequest;
import requests.filestation.favorite.DsmManageFavoriteRequest;
import requests.filestation.lists.DsmListFolderRequest;
import requests.filestation.lists.DsmSharedFolderRequest;
import requests.filestation.login.DsmLoginRequest;
import requests.filestation.login.DsmLogoutRequest;
import requests.filestation.search.DsmSearchResultRequest;
import requests.filestation.search.DsmSearchStartRequest;
import requests.filestation.search.DsmSearchStopRequest;
import requests.filestation.share.DsmShareCreateOrEditRequest;
import requests.filestation.share.DsmShareDeleteRequest;
import requests.filestation.share.DsmShareInfoRequest;
import requests.filestation.share.DsmShareListRequest;
import requests.filestation.transfert.DsmDownloadRequest;
import requests.filestation.transfert.DsmUploadRequest;
import responses.Response;
import responses.filestation.login.DsmLoginResponse;
import responses.filestation.DsmResponseFields;
import responses.filestation.DsmSimpleResponse;
import utils.DsmUtils;
import java.io.InputStream;
import java.util.Optional;
/**
* this is the principal client of fileStation
* all the functions are specified here
*/
public class DsmFileStationClient {
private DsmAuth dsmAuth;
public DsmFileStationClient(DsmAuth dsmAuth) {
this.dsmAuth = dsmAuth;
}
public DsmAuth getDsmAuth() {
return dsmAuth;
}
/**
* login to the server
* @param auth information about the server and user to connect
* @return DsmFileStationClient
*/
public static DsmFileStationClient login(DsmAuth auth) {
Response<DsmLoginResponse> response = new DsmLoginRequest(Optional.ofNullable(auth).orElseThrow(() -> new DsmLoginException("DsmAuth can't be null"))).call();
response = Optional.ofNullable(response).orElseThrow(() -> new DsmLoginException("An error occurred while trying to connect"));
if(!response.isSuccess()) {
throw new DsmLoginException(response.getError());
}
auth = auth.setSid(response.getData().getSid());
return new DsmFileStationClient(auth);
}
/**
* logout from server
* @return boolean
*/
public boolean logout() {
Response<DsmSimpleResponse> response = new DsmLogoutRequest(
Optional.ofNullable(this.dsmAuth).orElseThrow(() -> new DsmLoginException("You are already logged out"))
)
.call();
this.dsmAuth = null;
response = Optional.ofNullable(response).orElseThrow(() -> new DsmLoginException("The request generates no response"));
if(!response.isSuccess()) {
throw new DsmLoginException(response.getError());
}
return response.isSuccess();
}
public DsmSharedFolderRequest getAllSharedFolders() {
return new DsmSharedFolderRequest(dsmAuth);
}
/**
* get the list of the files and folder in a folder
* @param folderPath the path to the folder
* @return DsmListFolderRequest
*/
public DsmListFolderRequest ls(String folderPath) {
return new DsmListFolderRequest(dsmAuth)
.setFolderPath(folderPath);
}
/**
* upload a file to the server
* @param destinationPath the destination path
* @param filePath the file to upload
* @return DsmUploadRequest
*/
public DsmUploadRequest upload(String destinationPath, String filePath) {
return new DsmUploadRequest(dsmAuth)
.setDestinationFolderPath(destinationPath)
.setFilePath(filePath);
}
/**
* upload a file to the server
* @param destinationPath the destination path
* @param filePath the file to upload
* @param filePath the destination file name
* @return DsmUploadRequest
*/
public DsmUploadRequest upload(String destinationPath, String filePath, String destinationFileName) {
return new DsmUploadRequest(dsmAuth)
.setDestinationFolderPath(destinationPath)
.setFilePath(filePath)
.setDestinationFileName(destinationFileName);
}
/**
* upload a file to the server
* @param destinationPath the destination path
* @param fileContent the file to upload
* @param filePath the destination file name
* @return DsmUploadRequest
*/
public DsmUploadRequest upload(String destinationPath, InputStream fileContent, String destinationFileName) {
return new DsmUploadRequest(dsmAuth)
.setDestinationFolderPath(destinationPath)
.setFileContent(fileContent)
.setDestinationFileName(destinationFileName);
}
/**
* download a file
* @param fileOrFolderToDownload the path of the file to download
* @param destinationPath the destination path
* @return DsmDownloadRequest
*/
public DsmDownloadRequest download(String fileOrFolderToDownload, String destinationPath) {
return new DsmDownloadRequest(dsmAuth)
.setFileToDownload(fileOrFolderToDownload)
.setDestinationPath(destinationPath);
}
/**
* download a file
* @param destinationPath the destination path
* @return DsmDownloadRequest
*/
public DsmDownloadRequest download(String destinationPath) {
return new DsmDownloadRequest(dsmAuth)
.setDestinationPath(destinationPath);
}
/**
*
* @param filePath the path of the file to delete
* @return DsmSimpleDeleteRequest
*/
public DsmSimpleDeleteRequest simpleDelete(String filePath) {
return new DsmSimpleDeleteRequest(dsmAuth)
.addFileToDelete(filePath);
}
/**
* delete folder of file asynchroniously
* @return DsmAdvancedDeleteRequest
*/
public DsmAdvancedDeleteRequest advancedDelete() {
return new DsmAdvancedDeleteRequest(dsmAuth);
}
/**
* check if the file or folder exits
* @param filePath the path of the file or folder
* @return boolean
*/
public boolean exists(String filePath) {
return this.ls(DsmUtils.extractRootFolderPath(filePath))
.call()
.getData()
.getFiles()
.stream()
.anyMatch(f -> f.getName().equals(DsmUtils.extractFileName(filePath)));
}
/**
* rename a file or folder
* @param path the path of the folder or dile
* @param newName the new name of the folder or file
* @return DsmRenameRequest
*/
public DsmRenameRequest rename(String path, String newName) {
return new DsmRenameRequest(dsmAuth).addFileOrFolderToRename(path).addNewNames(newName);
}
/**
* copy or move a file or folder
* @param pathToCopy the path of the file or folder to move or copy
* @param destination the destination where to copy or move the file
* @return DsmCopyMoveRequest
*/
public DsmCopyMoveRequest copyOrMove(String pathToCopy, String destination) {
return new DsmCopyMoveRequest(dsmAuth)
.addPathToCopy(pathToCopy)
.setDestinationFolderPath(destination);
}
/**
* create a new folder
* @param parentPath the path of the parent folder
* @param newFolderName the name of the new folder
* @return DsmCreateFolderRequest
*/
public DsmCreateFolderRequest createFolder(String parentPath, String newFolderName) {
return new DsmCreateFolderRequest(dsmAuth)
.addNewFolder(parentPath, newFolderName);
}
/**
* get the information about the share links
* @param id the id of the shared link
* @return DsmResponseFields.SharingLink
*/
public Response<DsmResponseFields.SharingLink> getShareLinkInfo(String id) {
return new DsmShareInfoRequest(dsmAuth).getInfo(id);
}
/**
* get all shared links
* @return DsmShareListRequest
*/
public DsmShareListRequest getAllShareLinks() {
return new DsmShareListRequest(dsmAuth);
}
/**
* delete a shared link
* @param id the id of the share link to delete
* @return DsmSimpleResponse
*/
public Response<DsmSimpleResponse> deleteShareLink(String id) {
return new DsmShareDeleteRequest(dsmAuth).delete(id);
}
/**
* clear invalid links
* @return DsmSimpleResponse
*/
public Response<DsmSimpleResponse> clearInvalidShareLinks() {
return new DsmShareDeleteRequest(dsmAuth).clearInvalidLinks();
}
/**
* edit the shared link
* @param id the id of the shared link to edit
* @return DsmShareCreateOrEditRequest
*/
public DsmShareCreateOrEditRequest editShareLink(String id) {
return new DsmShareCreateOrEditRequest(dsmAuth)
.setId(id);
}
/**
* create a new shared link
* @param fileOrFilePath the path of the file or folder to share
* @return DsmShareCreateOrEditRequest
*/
public DsmShareCreateOrEditRequest createShareLink(String fileOrFilePath) {
return new DsmShareCreateOrEditRequest(dsmAuth)
.addFileOrFolder(fileOrFilePath);
}
/**
* Search for file or directory
*
* @param fileName the file or directoru to search
* @return DsmSearchStartRequest
*/
public DsmSearchStartRequest startSearch(String fileName) {
return new DsmSearchStartRequest(dsmAuth)
.addPattern(fileName);
}
/**
* get the search result
*
* @param id the search task id
* @return DsmSearchResultRequest
*/
public DsmSearchResultRequest getSearchResult(String id) {
return new DsmSearchResultRequest(dsmAuth)
.setTaskId(id);
}
/**
* stop the search task
* @param id the it of the search task
* @return DsmSearchStopRequest
*/
public DsmSearchStopRequest stopSearch(String id) {
return new DsmSearchStopRequest(dsmAuth).addTaskId(id);
}
/**
* @param path the path of file or folder for favorite
* @param name the favorite name
* @return DsmManageFavoriteRequest
*/
public DsmManageFavoriteRequest favoriteManager(String path, String name) {
return new DsmManageFavoriteRequest(dsmAuth)
.addPath(path, name);
}
/**
* get favorite manager
* @return DsmManageFavoriteRequest
*/
public DsmManageFavoriteRequest favoriteManager() {
return new DsmManageFavoriteRequest(dsmAuth);
}
/**
* the list of all favorite
* @return DsmListFavoriteRequest
*/
public DsmListFavoriteRequest listFavorite() {
return new DsmListFavoriteRequest(dsmAuth);
}
/**
* get the size of directory or file
* @param path the path the file or folder
* @return DsmDirSizeRequest
*/
public DsmDirSizeRequest getSize(String path) {
return new DsmDirSizeRequest(dsmAuth)
.addPath(path);
}
}
package exeptions;
public class DsmCopyMoveException extends DsmException{
public DsmCopyMoveException(String errorMessage) {
super(errorMessage);
}
}
package exeptions;
public class DsmCreateFolderException extends DsmException{
public DsmCreateFolderException(String errorMessage) {
super(errorMessage);
}
}
package exeptions;
public class DsmDeleteException extends DsmException{
public DsmDeleteException(String errorMessage) {
super(errorMessage);
}
}
package exeptions;
public class DsmDirSizeException extends DsmException{
public DsmDirSizeException(String errorMessage) {
super(errorMessage);
}
}
package exeptions;
public class DsmDownloadException extends DsmException{
public DsmDownloadException(String errorMessage) {
super(errorMessage);
}
public DsmDownloadException(Exception e) {
super(e);
}
}
package exeptions;
import responses.Response;
public class DsmException extends RuntimeException {
public DsmException(String errorMessage) {
super(errorMessage);
}
public DsmException(String errorMessage, Object... args) {
super(String.format(errorMessage, args));
}
public DsmException(String errorMessage, Throwable errCause) {
super(errorMessage, errCause);
}
public DsmException(Exception e) {
super(e);
}
public DsmException(Response.Error error) {
super("MainErrorCode= "+error.getCode()+" Desciption= "+ error.getDescription().orElse("") + " Error= "+error.getErrors());
}
}
package exeptions;
public class DsmFavoriteException extends DsmException{
public DsmFavoriteException(String errorMessage) {
super(errorMessage);
}
}
package exeptions;
public class DsmListFolderException extends DsmException{
public DsmListFolderException(String errorMessage) {
super(errorMessage);
}
}
package exeptions;
import responses.Response;
public class DsmLoginException extends DsmException{
public DsmLoginException(String errorMessage) {
super(errorMessage);
}
public DsmLoginException(Exception e) {
super(e);
}
public DsmLoginException(Response.Error error) {
super(error);
}
}
package exeptions;
public class DsmRenameException extends DsmException {
public DsmRenameException(String errorMessage) {
super(errorMessage);
}
}
package exeptions;
public class DsmSearchException extends DsmException{
public DsmSearchException(String errorMessage) {
super(errorMessage);
}
}
package exeptions;
public class DsmShareException extends DsmException {
public DsmShareException(String errorMessage) {
super(errorMessage);
}
}
package exeptions;
public class DsmUploadException extends DsmException{
public DsmUploadException(String errorMessage) {
super(errorMessage);
}
}
package requests;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import exeptions.DsmException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import responses.Response;
import utils.JacksonFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Optional;
public abstract class DsmAbstractRequest<T> {
private static final Logger LOG = LoggerFactory.getLogger(DsmAbstractRequest.class.getName());
private static final ObjectMapper mapper = JacksonFactory.getMapper();
protected String apiName;
protected Integer version;
protected String path;
protected String method;
protected DsmAuth auth;
private final HashMap<String, String> params = new HashMap<>();
public DsmAbstractRequest(DsmAuth auth) {
this.auth = auth;
}
public String getApiName() {
return apiName;
}
public Integer getVersion() {
return version;
}
public String getPath() {
return path;
}
public String getMethod() {
return method;
}
protected String build() {
addParameter("format", "sid");
StringBuilder request = new StringBuilder();
request.append(auth.getHost())
.append(auth.getPort() == null? "" : ":"+auth.getPort())
.append("/")
.append(getPath())
.append("?")
.append("api=")
.append(getApiName())
.append("&")
.append("version=")
.append(getVersion())
.append("&")
.append("method=")
.append(getMethod());
Optional.ofNullable(auth.getSid()).ifPresent( sid -> request.append("&").append("_sid").append("=").append(sid));
params
.forEach((key, value) -> request.append("&")
.append(key)
.append("=")
.append(value));
return request.toString();
}
protected String escape(String source) {
source = source.replace(",", "\\");
source = source.replace("\\", "\\\\");
source = source.replace("/", "%2F");
return source;
}
protected Response<T> deserialize(String resp) throws JsonProcessingException {
return (Response<T>) mapper.readValue(resp , getClassForMapper());
}
protected abstract TypeReference<T> getClassForMapper();
public Response<T> call() {
try {
String url = build();
HttpURLConnection conn = handleRequest(url);
int responseCode = conn.getResponseCode();
LOG.info("POST Response Code : {}", responseCode );
LOG.info("POST Response Message : {}", conn.getResponseMessage() );
StringBuilder respBuf = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
respBuf.append(line);
}
String resp = respBuf.toString();
LOG.trace("Response received: {}", resp);
return deserialize(resp);
}
catch (IOException e) {
throw new DsmException(e);
}
}
protected HttpURLConnection handleRequest(String url) throws IOException {
LOG.debug("Calling URL: {}", url);
HttpURLConnection conn = (HttpURLConnection) (new URL(url)).openConnection();
conn.setRequestMethod("GET");
return conn;
}
protected void addParameter(String key, String value) {
params.put(key, value);
}
}
package requests;
import exeptions.DsmException;
import exeptions.DsmLoginException;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
public class DsmAuth {
private static final String HOST_KEY = "host";
private static final String PORT_KEY = "port";
private static final String USERNAME_KEY = "username";
private static final String PASSWORD_KEY = "password";
private String host;
private Integer port;
private String userName;
private String password;
private String sid;
public String getHost() {
return host;
}
public DsmAuth setHost(String host) {
this.host = host;
return this;
}
public String getSid() {
return sid;
}
public DsmAuth setSid(String sid) {
this.sid = sid;
return this;
}
public Integer getPort() {
return port;
}
public DsmAuth setPort(Integer port) {
this.port = port;
return this;
}
public String getUserName() {
return userName;
}
public DsmAuth setUserName(String userName) {
this.userName = userName;
return this;
}
public String getPassword() {
return password;
}
public DsmAuth setPassword(String password) {
this.password = password;
return this;
}
public static DsmAuth of(String host, Integer port, String userName, String password) {
DsmAuth dsmAuth = new DsmAuth()
.setHost(Optional.ofNullable(host).orElseThrow(() -> new DsmLoginException("Unable to find property : host")))
.setUserName(Optional.ofNullable(userName).orElseThrow(() -> new DsmLoginException("Unable to find property : userName")))
.setPassword(Optional.ofNullable(password).orElseThrow(() -> new DsmLoginException("Unable to find property : password")));
Optional.ofNullable(port).ifPresent(dsmAuth::setPort);
return dsmAuth;
}
public static DsmAuth fromResource(String fileName) {
try {
Map<String, String> properties = getPropertiesFromResource(fileName);
validate(properties);
return DsmAuth.of(properties.get(HOST_KEY), properties.get(PORT_KEY) == null ? null : Integer.valueOf(properties.get(PORT_KEY)), properties.get(USERNAME_KEY), properties.get(PASSWORD_KEY));
} catch (Exception exception) {
throw new DsmException(exception);
}
}
public static DsmAuth fromFile(File file) {
try {
Map<String, String> properties = getPropertiesFromFile(file);
validate(properties);
return DsmAuth.of(properties.get(HOST_KEY), Integer.valueOf(properties.get(PORT_KEY)), properties.get(USERNAME_KEY), properties.get(PASSWORD_KEY));
} catch (Exception exception) {
throw new DsmLoginException(exception);
}
}
public static Map<String, String> getPropertiesFromFile(File file) throws IOException {
return Files.readAllLines(file.toPath(), StandardCharsets.UTF_8).stream()
.filter(l -> !l.isEmpty())
.collect(Collectors.
toMap(
l -> l.substring(0,l.indexOf('=')),
l -> l.substring(l.indexOf('=')+1)
)
);
}
private static Map<String, String> getPropertiesFromResource(String fileName) throws IOException, URISyntaxException {
ClassLoader classLoader = DsmAuth.class.getClassLoader();
URL resource = classLoader.getResource(fileName);
File file = new File(Optional.ofNullable(resource).orElseThrow(() -> new IllegalArgumentException("file not found! " + fileName)).toURI());
return getPropertiesFromFile(file);
}
private static void validate(Map<String, String> properties) {
String host = properties.get(HOST_KEY) != null && !properties.get(HOST_KEY).isEmpty() ? properties.get(HOST_KEY) : null;
Integer port = properties.get(PORT_KEY) != null && !properties.get(PORT_KEY).isEmpty() ? Integer.valueOf(Optional.ofNullable(properties.get(PORT_KEY)).orElse(null)) : null;
String userName = properties.get(USERNAME_KEY) != null && !properties.get(USERNAME_KEY).isEmpty() ? properties.get(USERNAME_KEY) : null;
String password = properties.get(PASSWORD_KEY) != null && !properties.get(PASSWORD_KEY).isEmpty() ? properties.get(PASSWORD_KEY) : null;
if(host != null && userName != null && password != null) {
return;
}
throw new DsmLoginException("None of the properties can't be empty : host="+ host +", port="+ port + ", username=" +userName+ ", password="+password);
}
}
package requests.filestation;
import responses.Response;
public interface DsmNonBlockingProcess<T> {
Response<T> start();
Response<T> status();
Response<T> stop();
}
package requests.filestation;
import responses.filestation.DsmResponseFields;
import java.util.List;
public class DsmRequestParameters {
public enum Sort {
/**
* file name
*/
NAME,
/**
* file owner
*/
USER,
/**
* file group
*/
GROUP,
/**
* last modified time
*/
MTIME,
/**
* last access time
*/
ATIME,
/**
* last change time
*/
CTIME,
/**
* create time
*/
CRTIME,
/**
* POSIX permission
*/
POSIX,
/**
* file extension
*/
TYPE
}
public enum ShareSort {
/**
* a unique ID of sharing a
* file/folder
*/
id,
/**
* file name
*/
name,
/**
* if it’s a folder or not
*/
isFolder,
/**
* file path
*/
path,
/**
* the expiration
* date for the sharing link
*/
date_expired,
/**
* the available
* date for the sharing link start
* effective
*/
date_available,
/**
* the link accessibility
* status
*/
status,
/**
* If the sharing
* link is protected or not
*/
has_password,
/**
* a URL of a sharing link
*/
url,
/**
* the user name of
* the sharing link owner
*/
link_owner
}
public enum SortDirection {
/**
* sort ascending
*/
ASC,
/**
* sort descending
*/
DESC
}
public enum Additional {
/**
* return a real path in volume
*/
REAL_PATH,
/**
* return information about file owner including user name, group name, UID and GID
*/
OWNER,
/**
* return information about time including last access time, last modified time, last change time and create time
*/
TIME,
/**
* return information about file permission
*/
PERM,
/**
* return a type of a virtual file system of a mount point
*/
MOUNT_POINT_TYPE,
/**
* return volume statuses including free space, total space and read-only status
*/
VOLUME_STATUS,
/**
* return a file extension
*/
TYPE
}
public enum FileType {
ALL,
FILE,
DIR
}
public enum Mode {
OPEN,
DOWNLOAD
}
public enum OverwriteBehaviour {
SKIP(false),
OVERWRITE(true),
ERROR(null);
OverwriteBehaviour(Boolean value) {
this.value = value;
}
private final Boolean value;
public Boolean getValue() {
return value;
}
}
public enum StatusFilter {
VALID,
BROKEN,
ALL
}
}
package requests.filestation.action;
import com.fasterxml.jackson.core.type.TypeReference;
import exeptions.DsmCopyMoveException;
import exeptions.DsmDeleteException;
import requests.DsmAbstractRequest;
import requests.DsmAuth;
import requests.filestation.DsmNonBlockingProcess;
import requests.filestation.DsmRequestParameters;
import responses.Response;
import responses.filestation.action.DsmCopyMoveResponse;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
public class DsmCopyMoveRequest extends DsmAbstractRequest<DsmCopyMoveResponse> implements DsmNonBlockingProcess<DsmCopyMoveResponse> {
/**
* One or more copied/moved
* file/folder path(s) starting with a
* shared folder, separated by
* commas
*/
private List<String> paths = new LinkedList<>();
/**
* A desitination folder path where
* files/folders are copied/moved.
*/
private String destinationFolderPath;
/**
* Optional. true: overwrite all
* existing files with the same
* name; false: skip all existing
* files with the same name;
* (None): do not overwrite or skip
* existed files. If there is any
* existing files, an error occurs
* (error code: 1003).
*/
private DsmRequestParameters.OverwriteBehaviour overwrite = DsmRequestParameters.OverwriteBehaviour.ERROR;
/**
* Optional. true: move
* filess/folders; false: copy
* files/folders
*/
private boolean removeSrc = false;
/**
* Optional true: calculate the
* progress by each
* moved/copied file within subfolder. false: calculate the
* progress by files which you give
* in path parameters. This
* calculates the progress faster,
* but is less precise.
*/
private boolean accurateProgress = true;
/**
* Optional. A unique ID for the
* search task which is gotten
* from SYNO.FileSation.Search
* API with start method. This
* is used to update the search
* result.
*/
private String searchTaskId;
/**
* A unique ID for the delete task which is
* gotten from start method.
*/
private String taskId;
public DsmCopyMoveRequest(DsmAuth auth) {
super(auth);
this.apiName = "SYNO.FileStation.CopyMove";
this.version = 1;
this.path = "webapi/entry.cgi";
}
public DsmCopyMoveRequest addPathToCopy(String path) {
this.paths.add(path);
return this;
}
public DsmCopyMoveRequest setDestinationFolderPath(String destinationFolderPath) {
this.destinationFolderPath = destinationFolderPath;
return this;
}
public DsmCopyMoveRequest setOverwriteBehaviour(DsmRequestParameters.OverwriteBehaviour overwrite) {
this.overwrite = overwrite;
return this;
}
public DsmCopyMoveRequest setRemoveSrc(boolean removeSrc) {
this.removeSrc = removeSrc;
return this;
}
public DsmCopyMoveRequest setAccurateProgress(boolean accurateProgress) {
this.accurateProgress = accurateProgress;
return this;
}
public DsmCopyMoveRequest setSearchTaskId(String searchTaskId) {
this.searchTaskId = searchTaskId;
return this;
}
public DsmCopyMoveRequest setTaskId(String taskId) {
this.taskId = taskId;
return this;
}
@Override
protected TypeReference getClassForMapper() {
return new TypeReference<Response<DsmCopyMoveResponse>>() {};
}
@Override
public Response<DsmCopyMoveResponse> start() {
String path = String.join(",", this.paths);
String destinationPath = Optional.ofNullable(this.destinationFolderPath).orElseThrow(() -> new DsmCopyMoveException("You have to set destination path"));
if(path.isEmpty()) {
throw new DsmCopyMoveException("The paths to copy or move cannot be empty");
}
if(!this.overwrite.equals(DsmRequestParameters.OverwriteBehaviour.ERROR)) {
addParameter("overwrite", String.valueOf(this.overwrite.getValue()));
}
addParameter("path", path);
addParameter("dest_folder_path", destinationPath);
this.method = "start";
return this.call();
}
@Override
public Response<DsmCopyMoveResponse> status() {
if(this.taskId == null) {
throw new DsmDeleteException("You have to set taskId");
}
this.method = "status";
return this.call();
}
@Override
public Response<DsmCopyMoveResponse> stop() {
if(this.taskId == null) {
throw new DsmDeleteException("You have to set task id");
}
this.method = "stop";
return this.call();
}
@Override
public Response<DsmCopyMoveResponse> call() {
addParameter("accurate_progress", String.valueOf(this.accurateProgress));
addParameter("remove_src", String.valueOf(this.removeSrc));
Optional.ofNullable(this.searchTaskId).ifPresent(s -> addParameter("search_taskid", s));
Optional.ofNullable(this.taskId).ifPresent(s -> addParameter("taskid", s));
return super.call();
}
}
package requests.filestation.action;
import com.fasterxml.jackson.core.type.TypeReference;
import exeptions.DsmCreateFolderException;
import requests.DsmAbstractRequest;
import requests.DsmAuth;
import requests.filestation.DsmRequestParameters;
import responses.Response;
import responses.filestation.action.DsmCreateFolderResponse;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
public class DsmCreateFolderRequest extends DsmAbstractRequest<DsmCreateFolderResponse> {
public DsmCreateFolderRequest(DsmAuth auth) {
super(auth);
this.apiName = "SYNO.FileStation.CreateFolder";
this.version = 1;
this.method = "create";
this.path = "webapi/entry.cgi";
}
/**
* One or more shared folder paths,
* separated by commas. If
* force_parent is true and
* folder_path does not exist, the
* folder_path will be created. If
* force_parent is false,
* folder_path must exist or a
* false value will be returned. The
* number of paths must be the same
* as the number of names in the
* name parameter. The first
* folder_path parameter
* corresponds to the first name
* parameter
*/
private final List<String> folderPaths = new LinkedList<>();
/**
* One or more new folder names,
* separated by commas. The
* number of names must be the
* same as the number of folder paths
* in the folder_path parameter.
* The first name parameter
* corresponding to the first
* folder_path parameter
*/
private final List<String> names = new LinkedList<>();
/**
* Optional. true: no error occurs if a
* folder exists and make parent
* folders as needed; false: parent
* folders are not created.
*/
private boolean forceParent = false;
/**
* Optional. Additional requested file
* information, separated by commas. When an additional option is
* requested, responded objects will
* be provided in the specified
* additional option.
* Options include:
* real_path: return a real path
* in volume
* size: return file byte size
* owner: return information
* about file owner including
* user name, group name, UID
* and GID
* time: return information about
* time including last access
* time, last modified time, last
* change time and create time
* perm: return information
* about file permission
* type: return a file extension
*/
private final List<DsmRequestParameters.Additional> additionals = new LinkedList<>();
@Override
protected TypeReference getClassForMapper() {
return new TypeReference<Response<DsmCreateFolderResponse>>() {};
}
public DsmCreateFolderRequest addNewFolder(String parentPath, String name) {
this.folderPaths.add(parentPath);
this.names.add(name);
return this;
}
public DsmCreateFolderRequest forceCreateParentFolder(boolean forceParent) {
this.forceParent = forceParent;
return this;
}
public DsmCreateFolderRequest addAdditional(DsmRequestParameters.Additional additional) {
this.additionals.add(additional);
return this;
}
@Override
public Response<DsmCreateFolderResponse> call() {
String parentPaths = String.join(",", this.folderPaths);
String newFolderNames = String.join(",", this.names);
if(parentPaths.isEmpty()) {
throw new DsmCreateFolderException("The parent path cannot be empty");
}
if(newFolderNames.isEmpty()) {
throw new DsmCreateFolderException("You have to specify the folder to create");
}
addParameter("folder_path", parentPaths);
addParameter("name", newFolderNames);
addParameter("force_parent", String.valueOf(this.forceParent));
if(!additionals.isEmpty()) {
addParameter("additional", additionals.stream().map(DsmRequestParameters.Additional::name).collect(Collectors.joining(",")));
}
return super.call();
}
}
package requests.filestation.action;
import com.fasterxml.jackson.core.type.TypeReference;
import exeptions.DsmDirSizeException;
import requests.DsmAbstractRequest;
import requests.DsmAuth;
import requests.filestation.DsmNonBlockingProcess;
import responses.Response;
import responses.filestation.action.DsmDirSizeResponse;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
public class DsmDirSizeRequest extends DsmAbstractRequest<DsmDirSizeResponse> implements DsmNonBlockingProcess<DsmDirSizeResponse> {
public DsmDirSizeRequest(DsmAuth auth) {
super(auth);
this.apiName = "SYNO.FileStation.DirSize";
this.version = 1;
this.path = "webapi/entry.cgi";
}
/**
* One or more file/folder paths starting with
* a shared folder for calculating cumulative
* size, separated by a comma.
*/
private final List<String> paths = new LinkedList<>();
private String taskId;
public DsmDirSizeRequest addPath(String path) {
this.paths.add(path);
return this;
}
public DsmDirSizeRequest setTaskId(String taskId) {
this.taskId = taskId;
return this;
}
@Override
protected TypeReference getClassForMapper() {
return new TypeReference<Response<DsmDirSizeResponse>>() {};
}
@Override
public Response<DsmDirSizeResponse> start() {
this.method = "start";
if(paths.isEmpty()) {
throw new DsmDirSizeException("You have to specify at least one path");
}
addParameter("path", String.join(",", this.paths));
return super.call();
}
@Override
public Response<DsmDirSizeResponse> status() {
this.method = "status";
Optional.ofNullable(this.taskId).orElseThrow(() -> new DsmDirSizeException("taskId is null"));
addParameter("taskid", this.taskId);
return super.call();
}
public Response<DsmDirSizeResponse> status(String taskId) {
this.method = "status";
this.taskId = taskId;
return this.status();
}
public Response<DsmDirSizeResponse> stop(String taskId) {
this.method = "stop";
this.taskId = taskId;
return this.stop();
}
@Override
public Response<DsmDirSizeResponse> stop() {
this.method = "stop";
Optional.ofNullable(this.taskId).orElseThrow(() -> new DsmDirSizeException("taskId is null"));
addParameter("taskid", this.taskId);
return super.call();
}
}
package requests.filestation.action;
import com.fasterxml.jackson.core.type.TypeReference;
import exeptions.DsmRenameException;
import requests.DsmAbstractRequest;
import requests.DsmAuth;
import requests.filestation.DsmRequestParameters;
import responses.Response;
import responses.filestation.action.DsmRenameResponse;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
public class DsmRenameRequest extends DsmAbstractRequest<DsmRenameResponse> {
/**
* One or more paths of files/folders to
* be renamed, separated by commas . The number of paths must be the
* same as the number of names in the
* name parameter. The first path
* parameter corresponds to the first
* name parameter.
*/
private final List<String> paths = new LinkedList<>();
/**
* One or more new names, separated
* by commas. The number of
* names must be the same as the
* number of folder paths in the path
* parameter. The first name parameter
* corresponding to the first path
* parameter
*/
private List<String> names = new LinkedList<>();
/**
* Optional. Additional requested file
* information, separated by commas
* . When an additional option is
* requested, responded objects will be
* provided in the specified additional
* option.
* Options include:
*
* real_path: return a real path in
* volume
*size: return file byte size
*
* owner: return information
* about file owner including user
* name, group name, UID and
* GID
*
* time: return information about
* time including last access time,
* last modified time, last change
* time and create time
*
* perm: return information about
* file permission
*
* type: return a file extension
*/
private final List<DsmRequestParameters.Additional> additionals = new LinkedList<>();
public DsmRenameRequest(DsmAuth auth) {
super(auth);
this.apiName = "SYNO.FileStation.Rename";
this.version = 1;
this.method = "rename";
this.path = "webapi/entry.cgi";
}
public DsmRenameRequest addFileOrFolderToRename(String path) {
this.paths.add(path);
return this;
}
public DsmRenameRequest addNewNames(String name) {
this.names.add(name);
return this;
}
public DsmRenameRequest addAdditionalInfo(DsmRequestParameters.Additional additional) {
this.additionals.add(additional);
return this;
}
@Override
protected TypeReference getClassForMapper() {
return new TypeReference<Response<DsmRenameResponse>>() {};
}
@Override
public Response<DsmRenameResponse> call() {
if(this.paths.isEmpty()) {
throw new DsmRenameException("You have to add at least one path to rename");
}
if(this.names.isEmpty()) {
throw new DsmRenameException("You have to add names to rename elements in paths");
}
if(this.paths.size() > this.names.size()) {
throw new DsmRenameException("You have to add new names to all your paths to rename");
}
this.names = this.names.stream().limit(this.paths.size()).collect(Collectors.toList());
addParameter("path", String.join(",", this.paths));
addParameter("name", String.join(",", this.names));
if(!additionals.isEmpty()) {
addParameter("additional", additionals.stream().map(DsmRequestParameters.Additional::name).collect(Collectors.joining(",")));
}
return super.call();
}
}
package requests.filestation.delete;
import com.fasterxml.jackson.core.type.TypeReference;
import exeptions.DsmDeleteException;
import requests.DsmAbstractRequest;
import requests.DsmAuth;
import requests.filestation.DsmNonBlockingProcess;
import responses.filestation.delete.DsmDeleteResponse;
import responses.Response;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
public class DsmAdvancedDeleteRequest extends DsmAbstractRequest<DsmDeleteResponse> implements DsmNonBlockingProcess<DsmDeleteResponse> {
/**
* One or more deleted file/folder
* paths starting with a shared
* folder, separated by commas
*/
private List<String> filePaths = new LinkedList<>();
/**
* Optional. true: calculates the
* progress of each deleted file with
* the sub-folder recursively; false:
* calculates the progress of files
* which you give in path
* parameters. The latter is faster
* than recursively, but less precise.
*
* Note: Only non-blocking methods
* suits using the status method
* to get progress.
*/
private boolean accurateProgress = true;
/**
* Optional. true: Recursively
* delete files within a folder. false:
* Only delete first-level file/folder. If
* a deleted folder contains any file,
* an error occurs because the
* folder can’t be directly deleted.
*/
private boolean recursive = true;
/**
* Optional. A unique ID for the
* search task which is gotten from
* start method. It’s used to
* delete the file in the search
* result.
*/
private String searchTaskId;
/**
* A unique ID for the delete task which is
* gotten from start method.
*/
private String taskid;
public DsmAdvancedDeleteRequest(DsmAuth auth) {
super(auth);
this.apiName = "SYNO.FileStation.Delete";
this.version = 1;
this.method = "start";
this.path = "webapi/entry.cgi";
}
@Override
protected TypeReference getClassForMapper() {
return new TypeReference<Response<DsmDeleteResponse>>() {};
}
public DsmAdvancedDeleteRequest addFileToDelete(String path) {
this.filePaths.add(path);
return this;
}
public DsmAdvancedDeleteRequest removeFileToDelete(String path) {
this.filePaths.remove(path);
return this;
}
public DsmAdvancedDeleteRequest showAccurateProgress(boolean accurateProgress) {
this.accurateProgress = accurateProgress;
return this;
}
public DsmAdvancedDeleteRequest recursive(boolean recursive) {
this.recursive = recursive;
return this;
}
public DsmAdvancedDeleteRequest setSearchTaskId(String searchTaskId) {
this.searchTaskId = searchTaskId;
return this;
}
public DsmAdvancedDeleteRequest taskId(String taskid) {
this.taskid = taskid;
return this;
}
@Override
public Response<DsmDeleteResponse> start() {
String paths = String.join(",", this.filePaths);
if(paths.isEmpty()) {
throw new DsmDeleteException("The files to delete cannot be empty");
}
addParameter("path", paths);
this.method = "start";
return this.call();
}
@Override
public Response<DsmDeleteResponse> status() {
if(this.taskid == null) {
throw new DsmDeleteException("You have to set taskid");
}
this.method = "status";
return this.call();
}
@Override
public Response<DsmDeleteResponse> stop() {
if(this.taskid == null) {
throw new DsmDeleteException("You have to set taskid");
}
this.method = "stop";
return this.call();
}
@Override
public Response<DsmDeleteResponse> call() {
addParameter("accurate_progress", String.valueOf(this.accurateProgress));
addParameter("recursive", String.valueOf(this.recursive));
Optional.ofNullable(this.searchTaskId).ifPresent(s -> addParameter("search_taskid", s));
Optional.ofNullable(this.taskid).ifPresent(s -> addParameter("taskid", s));
return super.call();
}
}
package requests.filestation.delete;
import com.fasterxml.jackson.core.type.TypeReference;
import exeptions.DsmDeleteException;
import requests.DsmAbstractRequest;
import requests.DsmAuth;
import responses.filestation.delete.DsmDeleteResponse;
import responses.Response;
import java.util.Optional;
/**
* Delete files/folders. This is a blocking method. The response is not returned until the deletion
* operation is completed.
*/
public class DsmSimpleDeleteRequest extends DsmAbstractRequest<DsmDeleteResponse> {
private String filePath;
private boolean recursive = true;
private Boolean searchTaskId;
public DsmSimpleDeleteRequest(DsmAuth auth) {
super(auth);
this.apiName = "SYNO.FileStation.Delete";
this.version = 2;
this.method = "delete";
this.path = "webapi/entry.cgi";
}
/**
* One or more deleted file/folder path(s)
* started with a shared folder, separated by
* a comma.
* @param filePath the path
* @return DsmSimpleDeleteRequest
*/
public DsmSimpleDeleteRequest addFileToDelete(String filePath) {
this.filePath = filePath;
return this;
}
/**
* Optional. true: Recursively delete files
* within a folder. false: Only delete firstlevel file/folder. If a deleted folder contains
* any file, an error will occur because the
* folder can’t be directly deleted.
* @param recursive recursive or not
* @return DsmSimpleDeleteRequest
*/
public DsmSimpleDeleteRequest setRecursive(boolean recursive) {
this.recursive = recursive;
return this;
}
/**
* Optional. A unique ID for the search task
* which is gotten from start method. It’s
* used to delete the file in the search result.
* @param searchTaskId searchId should be set
* @return DsmSimpleDeleteRequest
*/
public DsmSimpleDeleteRequest useSearchTaskId(boolean searchTaskId) {
this.searchTaskId = searchTaskId;
return this;
}
@Override
protected TypeReference getClassForMapper() {
return new TypeReference<Response<DsmDeleteResponse>>() {};
}
@Override
public Response<DsmDeleteResponse> call() {
addParameter("path", Optional.ofNullable(this.filePath).orElseThrow(() -> new DsmDeleteException("the files to delete can't be empty")));
addParameter("recursive", String.valueOf(this.recursive));
Optional.ofNullable(this.searchTaskId).ifPresent(taskId -> addParameter("search_taskid", taskId.toString()));
return super.call();
}
}
package requests.filestation.favorite;
import com.fasterxml.jackson.core.type.TypeReference;
import requests.DsmAbstractRequest;
import requests.DsmAuth;
import requests.filestation.DsmRequestParameters;
import responses.Response;
import responses.filestation.favorite.DsmListFavoriteResponse;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* Add a folder to user’s favorites or perform operations on user’s favorites.
*/
public class DsmListFavoriteRequest extends DsmAbstractRequest<DsmListFavoriteResponse> {
public DsmListFavoriteRequest(DsmAuth auth) {
super(auth);
this.apiName = "SYNO.FileStation.Favorite";
this.version = 1;
this.method = "list";
this.path = "webapi/entry.cgi";
}
/**
* Optional. Specify how many
* favorites are skipped before
* beginning to return user’s
* favorites.
*/
private Integer offset;
/**
* Optional. Number of favorites
* requested. 0 indicates to list all
* favorites.
*/
private Integer limit;
/**
* Optional. Show favorites with a
* given favorite status.
* Options of favorite statuses
* include:
* valid: A folder which a favorite
* links to exists
* broken: A folder which a favorite
* links to doesn’t exist or doesn’t be
* permitted to access it
* all: Both valid and broken statuses
*/
private DsmRequestParameters.StatusFilter statusFilter = DsmRequestParameters.StatusFilter.ALL;
/**
* Optional. Additional requested
* information of a folder which a
* favorite links to, separated by a
* comma. When an additional
* option is requested, responded
* objects will be provided in the
* specified additional option
*
* Options include:
*
* real_path: return a real path
* in volume
*
* owner: return information
* about file owner including
* user name, group name, UID
* and GID
*
* time: return information
* about time including last
* access time, last modified
* time, last change time and
* create time
*
* perm: return information
* about file permission
*
* mount_point_type: return a
* type of a virtual file system of
* a mount point
*/
List<DsmRequestParameters.Additional> additionals = new LinkedList<>();
public DsmListFavoriteRequest setOffset(Integer offset) {
this.offset = offset;
return this;
}
public DsmListFavoriteRequest setLimit(Integer limit) {
this.limit = limit;
return this;
}
public DsmListFavoriteRequest setStatusFilter(DsmRequestParameters.StatusFilter statusFilter) {
this.statusFilter = statusFilter;
return this;
}
public DsmListFavoriteRequest addAdditionalInformation(DsmRequestParameters.Additional additional) {
this.additionals.add(additional);
return this;
}
@Override
protected TypeReference getClassForMapper() {
return new TypeReference<Response<DsmListFavoriteResponse>>() {};
}
@Override
public Response<DsmListFavoriteResponse> call() {
Optional.ofNullable(this.offset).ifPresent(o -> addParameter("offset", String.valueOf(o)));
Optional.ofNullable(this.limit).ifPresent(o -> addParameter("limit", String.valueOf(o)));
addParameter("status_filter", this.statusFilter.name().toLowerCase());
if(!additionals.isEmpty()) {
addParameter("additional", additionals.stream().map(DsmRequestParameters.Additional::name).collect(Collectors.joining(",")));
}
return super.call();
}
}
package requests.filestation.favorite;
import com.fasterxml.jackson.core.type.TypeReference;
import exeptions.DsmFavoriteException;
import requests.DsmAbstractRequest;
import requests.DsmAuth;
import responses.Response;
import responses.filestation.DsmSimpleResponse;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
public class DsmManageFavoriteRequest extends DsmAbstractRequest<DsmSimpleResponse> {
public DsmManageFavoriteRequest(DsmAuth auth) {
super(auth);
this.apiName = "SYNO.FileStation.Favorite";
this.version = 1;
this.path = "webapi/entry.cgi";
}
/**
* A folder path starting with a shared folder
* is added to the user’s favorites.
*
* One or more folder paths starting with
* a shared folder, separated by a
* comma is added to the user’s
* favorites. The number of paths must
* be the same as the number of favorite
* names in the name parameter. The
* first path parameter corresponds to
* the first name parameter
*/
private final List<String> paths = new LinkedList<>();
/**
* A favorite name.
*
* One or more new favrorite names,
* separated by a comma. The
* number of favorite names must be the
* same as the number of folder paths in
* the path parameter. The first name
* parameter corresponding to the first
* path parameter.
*/
private final List<String> names = new LinkedList<>();
/**
* Optional. Index of location of an added
* favorite. If it’s equal to -1, the favorite will
* be added to the last one in user’s
* favorite. If it’s between 0 ~ total number
* of favorites-1, the favorite will be inserted
* into user’s favorites by the index.
*/
private Integer index;
public DsmManageFavoriteRequest addPath(String path, String name) {
this.paths.add(path);
this.names.add(name);
return this;
}
public DsmManageFavoriteRequest setIndex(Integer index) {
this.index = index;
return this;
}
public Response<DsmSimpleResponse> add() {
if(this.paths.isEmpty() || this.names.isEmpty()) {
throw new DsmFavoriteException("You have to add path or names to make favorite");
}
this.method = "add";
prepareDate();
return super.call();
}
public Response<DsmSimpleResponse> delete() {
if(this.paths.isEmpty()) {
throw new DsmFavoriteException("You have to add path to delete favorite");
}
this.method = "delete";
prepareDate();
return super.call();
}
public Response<DsmSimpleResponse> clear() {
this.method = "clear_broken";
prepareDate();
return super.call();
}
public Response<DsmSimpleResponse> edit() {
if(this.paths.size() > 1) {
throw new DsmFavoriteException("use replaceAll function to edit multiple favorites");
}
this.method = "edit";
prepareDate();
return super.call();
}
public Response<DsmSimpleResponse> replaceAll() {
if(this.paths.isEmpty()) {
throw new DsmFavoriteException("You have to add path to edit favorite");
}
this.method = "replace_all";
prepareDate();
return super.call();
}
private void prepareDate() {
if(!names.isEmpty()) {
addParameter("name", String.join(",", names));
}
if(!paths.isEmpty()) {
addParameter("path", String.join(",", paths));
}
Optional.ofNullable(this.index).ifPresent(o -> addParameter("index", String.valueOf(o)));
}
@Override
protected TypeReference getClassForMapper() {
return new TypeReference<Response<DsmSimpleResponse>>() {};
}
}
package requests.filestation.lists;
import exeptions.DsmListFolderException;
import requests.DsmAbstractRequest;
import requests.DsmAuth;
import requests.filestation.DsmRequestParameters;
import responses.filestation.lists.DsmListFolderResponse;
import responses.Response;
import com.fasterxml.jackson.core.type.TypeReference;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public class DsmListFolderRequest extends DsmAbstractRequest<DsmListFolderResponse> {
/**
* A listed folder path started with a
* shared folder.
*/
private String folderPath;
/**
* Optional. Specify how many files
* are skipped before beginning to
* return listed files.
*/
private Integer offset;
/**
* Optional. Number of files
* requested. 0 indicates to list all
* files with a given folder
*/
private Integer limit;
/**
* Optional. Specify which file
* information to sort on.
*
*Options include:
* name: file name
* size: file size
* user: file owner
* group: file group
* mtime: last modified time
* atime: last access time
* ctime: last change time
* crtime: create time
* posix: POSIX permission
* type: file extension
*/
private List<DsmRequestParameters.Sort> sorts = new LinkedList<>();
/**
* Optional. Specify to sort ascending
* or to sort descending
*
* Options include:
* asc: sort ascending
* desc: sort descending
*/
private DsmRequestParameters.SortDirection sortDirection;
/**
* Optional. Given glob pattern(s) to
* find files whose names and
* extensions match a caseinsensitive glob pattern.
*
* Note:
* 1. If the pattern doesn’t contain
* any glob syntax (? and *), * of
* glob syntax will be added at
* begin and end of the string
* automatically for partially
* matching the pattern.
*
* 2. You can use commas to separate
* multiple glob patterns.
*/
private List<String> patterns = new LinkedList<>();
/**
* Optional. file: only enumerate
* regular files; dir: only enumerate
* folders; all enumerate regular
* files and folders
*/
private DsmRequestParameters.FileType fileType;
/**
* Optional. Folder path started with a
* shared folder. Return all files and
* sub-folders within folder_path
* path until goto_path path
* recursively.
*/
private String goToPath;
/**
* Optional. Additional requested file
* information, separated by a
* comma. When an additional
* option is requested, responded
* objects will be provided in the
* specified additional option.
* Options include:
*
* real_path: return a real path
* in volume
*
* size: return file byte size
*
* owner: return information
* about file owner including
* user name, group name, UID
* and GID
*
* time: return information
* about time including last
* access time, last modified
* time, last change time and
* create time
*
* perm: return information
* about file permission
*
* mount_point_type: return a
* type of a virtual file system of
* a mount point
*
* type: return a file extension
*/
private List<DsmRequestParameters.Additional> additionals = new LinkedList<>();
public DsmListFolderRequest(DsmAuth auth) {
super(auth);
this.apiName = "SYNO.FileStation.List";
this.version = 1;
this.method = "list";
this.path = "webapi/entry.cgi";
}
@Override
protected TypeReference getClassForMapper() {
return new TypeReference<Response<DsmListFolderResponse>>() {};
}
/**
* A listed folder path started with a
* shared folder.
* @param folderPath the root path
* @return DsmListFolderRequest
*/
public DsmListFolderRequest setFolderPath(String folderPath) {
this.folderPath = folderPath;
return this;
}
/**
* Optional. Specify how many files
* are skipped before beginning to
* return listed files.
* @param offset the offset
* @return DsmListFolderRequest
*/
public DsmListFolderRequest setOffset(Integer offset) {
this.offset = offset;
return this;
}
/**
* Optional. Number of files
* requested. 0 indicates to list all
* files with a given folder.
* @param limit max number of files returned
* @return DsmListFolderRequest
*/
public DsmListFolderRequest setLimit(Integer limit) {
this.limit = limit;
return this;
}
/**
* Optional. Specify which file
* information to sort on.
* @param sort sorts
* @return DsmListFolderRequest
*/
public DsmListFolderRequest addSort(DsmRequestParameters.Sort sort) {
this.sorts.add(sort);
return this;
}
/**
* delete sort
* @param sort sorts
* @return DsmListFolderRequest
*/
public DsmListFolderRequest removeSort(DsmRequestParameters.Sort sort) {
this.sorts.remove(sort);
return this;
}
/**
* Optional. Specify to sort ascending
* or to sort descending
* @param sortDirection direction sort
* @return DsmListFolderRequest
*/
public DsmListFolderRequest setSortDirection(DsmRequestParameters.SortDirection sortDirection) {
this.sortDirection = sortDirection;
return this;
}
/**
* Optional. Given glob pattern(s) to
* find files whose names and
* extensions match a caseinsensitive glob pattern
* @param pattern pattern
* @return DsmListFolderRequest
*/
public DsmListFolderRequest addPattern(String pattern) {
this.patterns.add(pattern);
return this;
}
/**
* remove pattern
* @param pattern pattern
* @return DsmListFolderRequest
*/
public DsmListFolderRequest removePattern(String pattern) {
this.patterns.remove(pattern);
return this;
}
/**
* Optional. file: only enumerate
* regular files; dir: only enumerate
* folders; all enumerate regular
* files and folders
* @param fileType type of file
* @return DsmListFolderRequest
*/
public DsmListFolderRequest setFileType(DsmRequestParameters.FileType fileType) {
this.fileType = fileType;
return this;
}
/**
* Optional. Folder path started with a
* shared folder. Return all files and
* sub-folders within folder_path
* path until goto_path path
* recursively.
* @param goToPath go to path
* @return DsmListFolderRequest
*/
public DsmListFolderRequest setGoToPath(String goToPath) {
this.goToPath = goToPath;
return this;
}
/**
* Optional. Additional requested file
* information, separated by a
* comma. When an additional
* option is requested, responded
* objects will be provided in the
* specified additional option
* @param additional additional
* @return DsmListFolderRequest
*/
public DsmListFolderRequest addAdditionalInfo(DsmRequestParameters.Additional additional) {
this.additionals.add(additional);
return this;
}
/**
* remove additional
* @param additional additional
* @return DsmListFolderRequest
*/
public DsmListFolderRequest removeAdditional(DsmRequestParameters.Additional additional) {
this.additionals.remove(additional);
return this;
}
@Override
public Response<DsmListFolderResponse> call() {
addParameter("folder_path", escape(Optional.ofNullable(this.folderPath).orElseThrow(() -> new DsmListFolderException("the root folder path can not be null"))));
Optional.ofNullable(this.offset).ifPresent(of -> addParameter("offset", String.valueOf(of)));
Optional.ofNullable(this.limit).ifPresent(lm -> addParameter("limit", String.valueOf(lm)));
Optional.ofNullable(this.sortDirection).ifPresent(direction -> addParameter("sort_direction", direction.name()));
Optional.ofNullable(this.fileType).ifPresent(type -> addParameter("filetype", type.name()));
Optional.ofNullable(this.goToPath).ifPresent(gtp -> addParameter("goto_path", gtp));
if(!sorts.isEmpty()) {
addParameter("sort_by", sorts.stream().map(DsmRequestParameters.Sort::name).collect(Collectors.joining(",")));
}
if(!patterns.isEmpty()) {
addParameter("pattern", String.join(",", patterns));
}
if(!additionals.isEmpty()) {
addParameter("additional", additionals.stream().map(DsmRequestParameters.Additional::name).collect(Collectors.joining(",")));
}
return super.call();
}
}
package requests.filestation.lists;
import requests.DsmAbstractRequest;
import requests.DsmAuth;
import requests.filestation.DsmRequestParameters;
import responses.filestation.lists.DsmSharedFolderResponse;
import responses.Response;
import com.fasterxml.jackson.core.type.TypeReference;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public class DsmSharedFolderRequest extends DsmAbstractRequest<DsmSharedFolderResponse> {
/**
* Optional. Specify how many shared
* folders are skipped before beginning
* to return listed shared folders.
*/
private Integer offset;
/**
* Optional. Number of shared folders
* requested. 0 lists all shared folders
*/
private Integer limit;
/**
* Optional. Specify which file
* information to sort on.
*
* Options include:
* name: file name
* user: file owner
* group: file group
* mtime: last modified time
* atime: last access time
* ctime: last change time
* crtime: create time
* posix: POSIX permission
*/
private List<DsmRequestParameters.Sort> sorts = new LinkedList<>();
/**
* Optional. Specify to sort ascending
* or to sort descending.
*
* Options include:
* asc: sort ascending
* desc: sort descending
*/
private DsmRequestParameters.SortDirection sortDirection;
/**
* Optional. true: List writable shared
* folders; false: List writable and
* read-only shared folders.
*/
private boolean onlyWritable =false;
/**
* Optional. Additional requested file
* information, separated by commas
* . When an additional option is
* requested, responded objects will be
* provided in the specified additional
* option.
*
* Options include:
* real_path: return a real path in
* volume
*
* size: return file byte size
*
* owner: return information
* about file owner including user
* name, group name, UID and
* GID
*
* time: return information about
* time including last access time,
* last modified time, last change
* time and create time
*
* perm: return information about
* file permission
*
* mount_point_type: return a
* type of a virtual file system of a
* mount point
*
* volume_status: return volume
* statuses including free space,
* total space and read-only
* status
*/
private List<DsmRequestParameters.Additional> additionals = new LinkedList<>();
public DsmSharedFolderRequest(DsmAuth auth) {
super(auth);
this.apiName = "SYNO.FileStation.List";
this.version = 1;
this.method = "list_share";
this.path = "webapi/entry.cgi";
}
@Override
protected TypeReference getClassForMapper() {
return new TypeReference<Response<DsmSharedFolderResponse>>() {};
}
/**
* Optional. Specify how many shared
* folders are skipped before beginning
* to return listed shared folders
* @param offset offset
* @return DsmSharedFolderRequest
*/
public DsmSharedFolderRequest setOffset(Integer offset) {
this.offset = offset;
return this;
}
/**
* Optional. Number of shared folders
* requested. 0 lists all shared folders.
* I
* @param limit number
* @return DsmSharedFolderRequest
*/
public DsmSharedFolderRequest setLimit(Integer limit) {
this.limit = limit;
return this;
}
/**
* Optional. Specify to sort ascending
* or to sort descending.
*
* Options include:
* asc: sort ascending
* desc: sort descending
* @param sortDirection asc or desc
* @return DsmSharedFolderRequest
*/
public DsmSharedFolderRequest setSortDirection(DsmRequestParameters.SortDirection sortDirection) {
this.sortDirection = sortDirection;
return this;
}
/**
* Optional. true: List writable shared
* folders; false: List writable and
* read-only shared folders.
* @param onlyWritable onlyWritable
* @return DsmSharedFolderRequest
*/
public DsmSharedFolderRequest setOnlyWritable(boolean onlyWritable) {
this.onlyWritable = onlyWritable;
return this;
}
public DsmSharedFolderRequest addAdditionalInfo(DsmRequestParameters.Additional additional) {
this.additionals.add(additional);
return this;
}
public DsmSharedFolderRequest removeAdditionalInfo(DsmRequestParameters.Additional additional) {
this.additionals.remove(additional);
return this;
}
public DsmSharedFolderRequest addSort(DsmRequestParameters.Sort sort) {
this.sorts.add(sort);
return this;
}
public DsmSharedFolderRequest removeSort(DsmRequestParameters.Sort sort) {
this.sorts.remove(sort);
return this;
}
@Override
public Response<DsmSharedFolderResponse> call() {
Optional.ofNullable(this.offset).ifPresent(of -> addParameter("offset", String.valueOf(of)));
Optional.ofNullable(this.limit).ifPresent(lm -> addParameter("limit", String.valueOf(lm)));
Optional.ofNullable(this.sortDirection).ifPresent(direction -> addParameter("sort_direction", direction.name()));
addParameter("onlywritable", String.valueOf(onlyWritable));
if(!sorts.isEmpty()) {
addParameter("sort_by", sorts.stream().map(DsmRequestParameters.Sort::name).collect(Collectors.joining(",")));
}
if(!additionals.isEmpty()) {
addParameter("additional", additionals.stream().map(DsmRequestParameters.Additional::name).collect(Collectors.joining(",")));
}
return super.call();
}
}
package requests.filestation.login;
import com.fasterxml.jackson.core.type.TypeReference;
import requests.DsmAbstractRequest;
import requests.DsmAuth;
import responses.filestation.login.DsmLoginResponse;
import responses.Response;
public class DsmLoginRequest extends DsmAbstractRequest<DsmLoginResponse> {
public DsmLoginRequest(DsmAuth auth) {
super(auth);
this.apiName = "SYNO.API.Auth";
this.version = 3;
this.method = "login";
this.path = "webapi/auth.cgi";
addParameter("account", auth.getUserName());
addParameter("passwd", auth.getPassword());
}
@Override
protected TypeReference getClassForMapper() {
return new TypeReference<Response<DsmLoginResponse>>() {};
}
}
package requests.filestation.login;
import com.fasterxml.jackson.core.type.TypeReference;
import requests.DsmAbstractRequest;
import requests.DsmAuth;
import responses.filestation.DsmSimpleResponse;
import responses.Response;
public class DsmLogoutRequest extends DsmAbstractRequest<DsmSimpleResponse> {
public DsmLogoutRequest(DsmAuth auth) {
super(auth);
this.apiName = "SYNO.API.Auth";
this.version = 1;
this.method = "logout";
this.path = "webapi/auth.cgi";
}
@Override
protected TypeReference getClassForMapper() {
return new TypeReference<Response<DsmSimpleResponse>>() {};
}
}
package requests.filestation.search;
import com.fasterxml.jackson.core.type.TypeReference;
import exeptions.DsmSearchException;
import requests.DsmAbstractRequest;
import requests.DsmAuth;
import requests.filestation.DsmRequestParameters;
import responses.Response;
import responses.filestation.search.DsmSearchResultResponse;
import responses.filestation.search.DsmSearchStartResponse;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* List matched files in a search temporary database. You can check the finished value in response to
* know if the search operation is processing or has been finished.
*/
public class DsmSearchResultRequest extends DsmAbstractRequest<DsmSearchResultResponse> {
public DsmSearchResultRequest(DsmAuth auth) {
super(auth);
this.apiName = "SYNO.FileStation.Search";
this.version = 1;
this.method="list";
this.path = "webapi/entry.cgi";
}
/**
* A unique ID for the search task
* which is gotten from start
* method.
*/
private String taskId;
/**
* Optional. Specify how many
* matched files are skipped before
* beginning to return listed
* matched files.
*/
private Integer offset;
/**
* Optional. Number of matched
* files requested. 0 indicates to list
* all matched files
*/
private Integer limit;
/**
* Optional. Specify which file
* information to sort on.
* Options include:
* name: file name
* size: file size
* user: file owner
* group: file group
* mtime: last modified time
* atime: last access time
* ctime: last change time
* crtime: create time
* posix: POSIX permission
* type: file extension
*/
private List<DsmRequestParameters.Sort> sorts = new LinkedList<>();
/**
* Optional. Specify to sort
* ascending or to sort descending.
* Options include:
* asc: sort ascending
* desc: sort descending
*/
private DsmRequestParameters.SortDirection sortDirection;
/**
* Optional. Given glob pattern(s) to
* find files whose names and
* extensions match a caseinsensitive glob pattern.
* Note:
* 1. If the pattern doesn’t contain
* any glob syntax (? and *), *
* of glob syntax will be added
* at begin and end of the string
* automatically for partially
* matching the pattern.
* 2. You can use commas to separate
* multiple glob patterns.
*/
private List<String> patterns = new LinkedList<>();
/**
* Optional. file: enumerate
* regular files; dir: enumerate
* folders; all enumerate regular
* files and folders.
*/
private DsmRequestParameters.FileType fileType = DsmRequestParameters.FileType.ALL;
/**
* Optional. Additional requested
* file information, separated by a
* comma. When an additional
* option is requested, responded
* objects will be provided in the
* specified additional option.
* Options include:
*
* real_path: return a real
* path in volume
*
* size: return file byte size
*
* owner: returns information
* about file owner including
* user name, group name,
* UID and GID
*
* time: return information
* about time including last
* access time, last modified
* time, last change time and
* create time
*
* perm: return information
* about file permission
*
* type: return a file extension
*/
private List<DsmRequestParameters.Additional> additionals = new LinkedList<>();
public DsmSearchResultRequest setTaskId(String taskId) {
this.taskId = taskId;
return this;
}
public DsmSearchResultRequest setOffset(Integer offset) {
this.offset = offset;
return this;
}
public DsmSearchResultRequest setLimit(Integer limit) {
this.limit = limit;
return this;
}
public DsmSearchResultRequest addSorts(DsmRequestParameters.Sort sort) {
this.sorts.add(sort);
return this;
}
public DsmSearchResultRequest setSortDirection(DsmRequestParameters.SortDirection sortDirection) {
this.sortDirection = sortDirection;
return this;
}
public DsmSearchResultRequest addPattern(String pattern) {
this.patterns.add(pattern);
return this;
}
public DsmSearchResultRequest setFileType(DsmRequestParameters.FileType fileType) {
this.fileType = fileType;
return this;
}
public DsmSearchResultRequest addAdditionalInformation(DsmRequestParameters.Additional additional) {
this.additionals.add(additional);
return this;
}
@Override
protected TypeReference getClassForMapper() {
return new TypeReference<Response<DsmSearchResultResponse>>() {};
}
@Override
public Response<DsmSearchResultResponse> call() {
addParameter("taskid", Optional.ofNullable(taskId).orElseThrow(() -> new DsmSearchException("taskId must not be null")));
Optional.ofNullable(this.offset).ifPresent(o -> addParameter("offset", String.valueOf(o)));
Optional.ofNullable(this.limit).ifPresent(o -> addParameter("limit", String.valueOf(o)));
if(!sorts.isEmpty()) {
addParameter("sort_by", sorts.stream().map(DsmRequestParameters.Sort::name).collect(Collectors.joining(",")));
}
Optional.ofNullable(this.sortDirection).ifPresent(direction -> addParameter("sort_direction", direction.name()));
if(!patterns.isEmpty()) {
addParameter("pattern", String.join(",", patterns));
}
if(!additionals.isEmpty()) {
addParameter("additional", additionals.stream().map(DsmRequestParameters.Additional::name).collect(Collectors.joining(",")));
}
addParameter("filetype", this.fileType.name().toLowerCase());
return super.call();
}
}
package requests.filestation.search;
import com.fasterxml.jackson.core.type.TypeReference;
import requests.DsmAbstractRequest;
import requests.DsmAuth;
import requests.filestation.DsmRequestParameters;
import responses.Response;
import responses.filestation.search.DsmSearchStartResponse;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
public class DsmSearchStartRequest extends DsmAbstractRequest<DsmSearchStartResponse> {
public DsmSearchStartRequest(DsmAuth auth) {
super(auth);
this.apiName = "SYNO.FileStation.Search";
this.version = 1;
this.method="start";
this.path = "webapi/entry.cgi";
}
/**
* A searched folder path starting
* with a shared folder.
*/
private String rootFolderPath;
/**
*Optional. If searching files within a
* folder and subfolders recursively or
* not
*/
private boolean recursive = true;
/**
* Optional. Search for files whose
* names and extensions match a
* case-insensitive glob pattern.
* Note:
* 1. If the pattern doesn’t contain
* any glob syntax (? and *), * of
* glob syntax will be added at
* begin and end of the string
* automatically for partially
* matching the pattern.
* 2. You can use commas to separate
* multiple glob patterns.
*/
private List<String> patterns = new LinkedList<>();
/**
* Optional. Search for files whose
* extensions match a file type
* pattern in a case-insensitive glob
* pattern. If you give this criterion,
* folders aren’t matched
*
* Note: You can use commas to
* separate multiple glob patterns.
*/
private String extension;
/**
* Optional. file: enumerate regular
* files; dir: enumerate folders; all
* enumerate regular files and
* folders.
*/
private DsmRequestParameters.FileType fileType = DsmRequestParameters.FileType.ALL;
/**
* Optional. Search for files whose
* sizes are greater than the given
* byte size.
*/
private Long minimumSize;
/**
* Optional. Search for files whose
* sizes are less than the given byte
* size.
*/
private Long maximumSize;
/**
* Optional. Search for files whose
* last modified time after the given
* Linux timestamp in second.
*/
private Long modifiedTimeAfter;
/**
* Optional. Search for files whose
* last modified time before the given
* Linux timestamp in second.
*/
private Long modifiedTimeBefore;
/**
* Optional. Search for files whose
* create time after the given Linux
* timestamp in second.
*/
private Long createdTimeAfter;
/**
* Optional. Search for files whose
* create time before the given Linux
* timestamp in second.
*/
private Long createdTimeBefore;
/**
* Optional. Search for files whose
* last access time after the given
* Linux timestamp in second.
*/
private Long lastAccessTimeAfter;
/**
* Optional. Search for files whose
* last access time before the given
* Linux timestamp in second.
*/
private Long lastAccessTimeBefore;
/**
* Optional. Search for files whose
* user name matches this criterion.
* This criterion is case-insensitive.
*/
private String owner;
/**
* Optional. Search for files whose
* group name matches this criterion.
* This criterion is case-insensitive
*/
private String group;
public DsmSearchStartRequest setRootFolderPath(String rootFolderPath) {
this.rootFolderPath = rootFolderPath;
return this;
}
public DsmSearchStartRequest setRecursive(boolean recursive) {
this.recursive = recursive;
return this;
}
public DsmSearchStartRequest addPattern(String pattern) {
this.patterns.add(pattern) ;
return this;
}
public DsmSearchStartRequest setExtension(String extension) {
this.extension = extension;
return this;
}
public DsmSearchStartRequest setFileType(DsmRequestParameters.FileType fileType) {
this.fileType = fileType;
return this;
}
public DsmSearchStartRequest setMinimumSize(Long minimumSize) {
this.minimumSize = minimumSize;
return this;
}
public DsmSearchStartRequest setMaximumSize(Long maximumSize) {
this.maximumSize = maximumSize;
return this;
}
public DsmSearchStartRequest setModifiedTimeAfter(Long modifiedTimeAfter) {
this.modifiedTimeAfter = modifiedTimeAfter;
return this;
}
public DsmSearchStartRequest setModifiedTimeBefore(Long modifiedTimeBefore) {
this.modifiedTimeBefore = modifiedTimeBefore;
return this;
}
public DsmSearchStartRequest setCreatedTimeAfter(Long createdTimeAfter) {
this.createdTimeAfter = createdTimeAfter;
return this;
}
public DsmSearchStartRequest setCreatedTimeBefore(Long createdTimeBefore) {
this.createdTimeBefore = createdTimeBefore;
return this;
}
public DsmSearchStartRequest setLastAccessTimeAfter(Long lastAccessTimeAfter) {
this.lastAccessTimeAfter = lastAccessTimeAfter;
return this;
}
public DsmSearchStartRequest setLastAccessTimeBefore(Long lastAccessTimeBefore) {
this.lastAccessTimeBefore = lastAccessTimeBefore;
return this;
}
public DsmSearchStartRequest setOwner(String owner) {
this.owner = owner;
return this;
}
public DsmSearchStartRequest setGroup(String group) {
this.group = group;
return this;
}
@Override
protected TypeReference getClassForMapper() {
return new TypeReference<Response<DsmSearchStartResponse>>() {};
}
@Override
public Response<DsmSearchStartResponse> call() {
Optional.ofNullable(this.rootFolderPath).ifPresent(root -> addParameter("folder_path", root));
addParameter("recursive", String.valueOf(this.recursive));
if(!this.patterns.isEmpty()) {
addParameter("pattern", String.join(",", this.patterns));
}
Optional.ofNullable(this.extension).ifPresent(s -> addParameter("extension", s));
addParameter("filetype", this.fileType.name().toLowerCase());
Optional.ofNullable(this.minimumSize).ifPresent(s -> addParameter("size_from", String.valueOf(s)));
Optional.ofNullable(this.maximumSize).ifPresent(s -> addParameter("size_to", String.valueOf(s)));
Optional.ofNullable(this.modifiedTimeAfter).ifPresent(s -> addParameter("mtime_from", String.valueOf(s)));
Optional.ofNullable(this.modifiedTimeBefore).ifPresent(s -> addParameter("mtime_to", String.valueOf(s)));
Optional.ofNullable(this.createdTimeAfter).ifPresent(s -> addParameter("crtime_from", String.valueOf(s)));
Optional.ofNullable(this.createdTimeBefore).ifPresent(s -> addParameter("crtime_to", String.valueOf(s)));
Optional.ofNullable(this.lastAccessTimeAfter).ifPresent(s -> addParameter("atime_from", String.valueOf(s)));
Optional.ofNullable(this.lastAccessTimeBefore).ifPresent(s -> addParameter("atime_to", String.valueOf(s)));
Optional.ofNullable(this.owner).ifPresent(s -> addParameter("owner", s));
Optional.ofNullable(this.group).ifPresent(s -> addParameter("group", s));
return super.call();
}
}
package requests.filestation.search;
import com.fasterxml.jackson.core.type.TypeReference;
import exeptions.DsmSearchException;
import requests.DsmAbstractRequest;
import requests.DsmAuth;
import responses.Response;
import responses.filestation.DsmSimpleResponse;
import java.util.LinkedList;
import java.util.List;
public class DsmSearchStopRequest extends DsmAbstractRequest<DsmSimpleResponse> {
public DsmSearchStopRequest(DsmAuth auth) {
super(auth);
this.apiName = "SYNO.FileStation.Search";
this.version = 1;
this.method="stop";
this.path = "webapi/entry.cgi";
}
/**
* Unique ID(s) for the search task which are
* gotten from start method. Specify
* multiple search task IDs by commas.
*/
private final List<String> taskIds = new LinkedList<>();
public DsmSearchStopRequest addTaskId(String taskId) {
this.taskIds.add(taskId);
return this;
}
@Override
protected TypeReference getClassForMapper() {
return new TypeReference<Response<DsmSimpleResponse>>() {};
}
@Override
public Response<DsmSimpleResponse> call() {
if(this.taskIds.isEmpty()) {
throw new DsmSearchException("You have to specify at least one taskId");
}
addParameter("taskid", String.join(",", this.taskIds));
return super.call();
}
}
package requests.filestation.share;
import com.fasterxml.jackson.core.type.TypeReference;
import exeptions.DsmCreateFolderException;
import requests.DsmAbstractRequest;
import requests.DsmAuth;
import responses.Response;
import responses.filestation.share.DsmShareCreateResponse;
import utils.DateUtils;
import java.time.LocalDateTime;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
public class DsmShareCreateOrEditRequest extends DsmAbstractRequest<DsmShareCreateResponse> {
public DsmShareCreateOrEditRequest(DsmAuth auth) {
super(auth);
this.apiName = "SYNO.FileStation.Sharing";
this.version = 1;
this.path = "webapi/entry.cgi";
}
/**
* Unique ID(s) of sharing link(s) to edit,
* separated by a comma
*/
private String id;
/**
* One or more file/folder paths with which to
* generate sharing links, separated by
* commas
*/
private final List<String> paths = new LinkedList<>();
/**
* Optional The password for the sharing link
* when accessing it. The max password
* length are 16 characters.
*/
private String password;
/**
* Optional. The expiration date for the
* sharing link, written in the format YYYYMM-DD hh:mm:ss. When set to 0 (default), the
* sharing link is permanent.
*/
private LocalDateTime dateExpired;
/**
* Optional. The available date for the sharing
* link to become effective, written in the
* format YYYY-MM-DD hh:mm:ss. When set to 0
* (default), the sharing link is valid
* immediately after creation.
*/
private LocalDateTime dateAvailable;
public DsmShareCreateOrEditRequest setId(String id) {
this.id = id;
return this;
}
public DsmShareCreateOrEditRequest addFileOrFolder(String path) {
this.paths.add(path);
return this;
}
public DsmShareCreateOrEditRequest setPassword(String password) {
this.password = password;
return this;
}
public DsmShareCreateOrEditRequest setDateExpired(LocalDateTime dateExpired) {
this.dateExpired = dateExpired;
return this;
}
public DsmShareCreateOrEditRequest setDateAvailable(LocalDateTime dateAvailable) {
this.dateAvailable = dateAvailable;
return this;
}
@Override
protected TypeReference getClassForMapper() {
return new TypeReference<Response<DsmShareCreateResponse>>() {};
}
@Override
public Response<DsmShareCreateResponse> call() {
if(paths.isEmpty() && !Optional.ofNullable(this.id).isPresent()) {
throw new DsmCreateFolderException("You have to specify at least one content to share");
}
if (Optional.ofNullable(this.id).isPresent()) {
this.method = "edit";
} else {
this.method = "create";
}
if(!paths.isEmpty()) {
addParameter("path", String.join(",", this.paths));
}
Optional.ofNullable(this.password).ifPresent(p -> addParameter("password", p));
Optional.ofNullable(this.dateExpired).ifPresent(date -> addParameter("date_expired", DateUtils.convertDateToString(date)));
Optional.ofNullable(this.dateAvailable).ifPresent(date -> addParameter("date_available", DateUtils.convertDateToString(date)));
return super.call();
}
}
package requests.filestation.share;
import com.fasterxml.jackson.core.type.TypeReference;
import exeptions.DsmShareException;
import requests.DsmAbstractRequest;
import requests.DsmAuth;
import responses.Response;
import responses.filestation.DsmSimpleResponse;
import java.util.Optional;
public class DsmShareDeleteRequest extends DsmAbstractRequest<DsmSimpleResponse> {
public DsmShareDeleteRequest(DsmAuth auth) {
super(auth);
this.apiName = "SYNO.FileStation.Sharing";
this.version = 1;
this.path = "webapi/entry.cgi";
}
public Response<DsmSimpleResponse> delete(String id) {
addParameter("id", Optional.ofNullable(id).orElseThrow(() -> new DsmShareException("You have to provide an id")));
this.method = "delete";
return call();
}
public Response<DsmSimpleResponse> clearInvalidLinks() {
this.method = "clear_invalid";
return call();
}
@Override
protected TypeReference getClassForMapper() {
return new TypeReference<Response<DsmSimpleResponse>>() {};
}
}
package requests.filestation.share;
import com.fasterxml.jackson.core.type.TypeReference;
import exeptions.DsmShareException;
import requests.DsmAbstractRequest;
import requests.DsmAuth;
import responses.Response;
import responses.filestation.DsmResponseFields;
import java.util.Optional;
public class DsmShareInfoRequest extends DsmAbstractRequest<DsmResponseFields.SharingLink> {
public DsmShareInfoRequest(DsmAuth auth) {
super(auth);
this.apiName = "SYNO.FileStation.Sharing";
this.version = 1;
this.method = "getinfo";
this.path = "webapi/entry.cgi";
}
@Override
protected TypeReference getClassForMapper() {
return new TypeReference<Response<DsmResponseFields.SharingLink>>() {};
}
public Response<DsmResponseFields.SharingLink> getInfo(String id) {
addParameter("id", Optional.ofNullable(id).orElseThrow(() -> new DsmShareException("You have to specify an id")));
this.method = "getinfo";
return call();
}
}
package requests.filestation.share;
import com.fasterxml.jackson.core.type.TypeReference;
import requests.DsmAbstractRequest;
import requests.DsmAuth;
import requests.filestation.DsmRequestParameters;
import responses.Response;
import responses.filestation.share.DsmShareListResponse;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public class DsmShareListRequest extends DsmAbstractRequest<DsmShareListResponse> {
public DsmShareListRequest(DsmAuth auth) {
super(auth);
this.apiName = "SYNO.FileStation.Sharing";
this.version = 3;
this.method = "list";
this.path = "webapi/entry.cgi";
}
/**
* Optional. Specify how many
* sharing links are skipped before
* beginning to return listed sharing
* links.
*/
private Integer offset;
/**
* Optional. Number of sharing links
* requested. 0 means to list all
* sharing links.
*/
private Integer limit;
/**
* Optional. Specify information of
* the sharing link to sort on.
* Options include:
* id: a unique ID of sharing a
* file/folder
* name: file name
* isFolder: if it’s a folder or not
* path: file path
* date_expired: the expiration
* date for the sharing link
* date_available: the available
* date for the sharing link start
* effective
* status: the link accessibility
* status
* has_password: If the sharing
* link is protected or not
* url: a URL of a sharing link
* link_owner: the user name of
* the sharing link owner
*/
private final List<DsmRequestParameters.ShareSort> sorts = new LinkedList<>();
/**
* Optional. Specify to sort
* ascending or to sort descending.
* Options include:
* asc: sort ascending
* desc: sort descending
*/
private DsmRequestParameters.SortDirection direction;
/**
* Optional. If set to false, the data
* will be retrieval from cache
* database rapidly. If set to true, all
* sharing information including
* sharing statuses and user name
* of sharing owner will be
* synchronized. It consumes some
* time
*/
boolean forceClean = false;
public DsmShareListRequest setOffset(Integer offset) {
this.offset = offset;
return this;
}
public DsmShareListRequest setLimit(Integer limit) {
this.limit = limit;
return this;
}
public DsmShareListRequest addSort(DsmRequestParameters.ShareSort sort) {
this.sorts.add(sort);
return this;
}
public DsmShareListRequest setDirection(DsmRequestParameters.SortDirection direction) {
this.direction = direction;
return this;
}
public DsmShareListRequest setForceClean(boolean forceClean) {
this.forceClean = forceClean;
return this;
}
@Override
protected TypeReference getClassForMapper() {
return new TypeReference<Response<DsmShareListResponse>>() {};
}
@Override
public Response<DsmShareListResponse> call() {
addParameter("offset", String.valueOf(Optional.ofNullable(offset).orElse(0)));
addParameter("limit", String.valueOf(Optional.ofNullable(limit).orElse(0)));
if(!sorts.isEmpty()) {
addParameter("sort_by", sorts.stream().map(DsmRequestParameters.ShareSort::name).collect(Collectors.joining(",")));
}
Optional.ofNullable(this.direction).ifPresent(d -> addParameter("sort_direction", d.name()));
addParameter("force_clean", String.valueOf(forceClean));
return super.call();
}
}
package requests.filestation.transfert;
import com.fasterxml.jackson.core.type.TypeReference;
import exeptions.DsmDownloadException;
import java.io.OutputStream;
import requests.DsmAbstractRequest;
import requests.DsmAuth;
import requests.filestation.DsmRequestParameters;
import requests.filestation.DsmRequestParameters.Mode;
import responses.filestation.transfert.DsmDownloadResponse;
import responses.Response;
import responses.filestation.transfert.DsmDownloadStreamResponse;
import utils.DsmUtils;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.Optional;
/**
* Download files/folders. If only one file is specified, the file content is responded. If more than one
* file/folder is given, binary content in ZIP format which they are compressed to is responded.
*/
public class DsmDownloadRequest extends DsmAbstractRequest<DsmDownloadStreamResponse> {
/**
* One or more file/folder paths starting with a
* shared folder to be downloaded, separated
* by a commas. When more than one file
* is to be downloaded, files/folders will be
* compressed as a zip file.
*/
private String filePath;
/**
* Mode used to download files/folders, value
* could be:
* (1) open: try to trigger the application,
* such as a web browser, to open it.
* Content-Type of the HTTP header of
* the response is set to MIME type
* according to file extension.
* (2) download: try to trigger the application,
* such as a web browser, to download it.
* Content-Type of the HTTP header of
* response is set to application/octetstream and Content-Disposition of the
* HTTP header of the response is set to
* attachment.
*/
private Mode mode = Mode.OPEN;
/**
* the destination where to save the downloaded file
*/
private String destinationPath;
public DsmDownloadRequest(DsmAuth auth) {
super(auth);
this.apiName = "SYNO.FileStation.Download";
this.version = 1;
this.method = "download";
this.path = "webapi/entry.cgi";
}
@Override
protected TypeReference getClassForMapper() {
return new TypeReference<Response<DsmDownloadResponse>>() {};
}
public DsmDownloadRequest setFileToDownload(String filePath) {
this.filePath = filePath;
return this;
}
public DsmDownloadRequest setMode(Mode mode) {
this.mode = mode;
return this;
}
public DsmDownloadRequest setDestinationPath(String destinationPath) {
this.destinationPath = destinationPath;
return this;
}
//
// @Override
// public Response<DsmDownloadResponse> call() {
//
// addParameter("path", escape(Optional.ofNullable(this.filePath).orElseThrow(() -> new DsmDownloadException("You have to add a folder or file to download"))));
// addParameter("mode", this.mode.name());
//
// try {
// HttpURLConnection conn = handleRequest(build());
// File downloadedFile = DsmUtils.downloadFile(conn.getInputStream(), Optional.ofNullable(this.destinationPath).orElseThrow(() -> new DsmDownloadException("You have to set a destination path"))+"/"+DsmUtils.extractFileName(this.filePath));
//
// Response<DsmDownloadResponse> response = new Response<>();
// response.setSuccess(true);
// response.setData(new DsmDownloadResponse(downloadedFile));
// return response;
// } catch (IOException e) {
// throw new DsmDownloadException("the file does not exist on the server");
// }
// }
@Override
public Response<DsmDownloadStreamResponse> call() {
addParameter("path", escape(Optional.ofNullable(this.filePath).orElseThrow(() -> new DsmDownloadException("You have to add a folder or file to download"))));
addParameter("mode", this.mode.name());
try {
HttpURLConnection conn = handleRequest(build());
//File downloadedFile = DsmUtils.downloadFile(conn.getInputStream(), Optional.ofNullable(this.destinationPath).orElseThrow(() -> new DsmDownloadException("You have to set a destination path"))+"/"+DsmUtils.extractFileName(this.filePath));
Response<DsmDownloadStreamResponse> response = new Response<>();
response.setSuccess(true);
response.setData(new DsmDownloadStreamResponse(conn.getInputStream(), conn.getContentType(), conn.getContentLength()));
return response;
} catch (IOException e) {
throw new DsmDownloadException("the file does not exist on the server");
}
}
}
package requests.filestation.transfert;
import com.fasterxml.jackson.core.type.TypeReference;
import exeptions.DsmException;
import exeptions.DsmUploadException;
import requests.DsmAbstractRequest;
import requests.DsmAuth;
import requests.filestation.DsmRequestParameters;
import responses.filestation.transfert.DsmUploadResponse;
import responses.Response;
import utils.DateUtils;
import utils.DsmUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
/**
* Upload a file by RFC 1867, http://tools.ietf.org/html/rfc1867.
* Note that each parameter is passed within each part but binary file data must be the last part.
*/
public class DsmUploadRequest extends DsmAbstractRequest<DsmUploadResponse> {
private String destinationFolderPath;
private Boolean createParents;
private DsmRequestParameters.OverwriteBehaviour overwrite = DsmRequestParameters.OverwriteBehaviour.ERROR;
private String filePath;
private String destinationFileName;
private InputStream fileContent;
private LocalDateTime lastModifiedTime;
private LocalDateTime createdTime;
private LocalDateTime lastAccessedTime;
public DsmUploadRequest(DsmAuth auth) {
super(auth);
this.apiName = "SYNO.FileStation.Upload";
this.version = 2;
this.method = "upload";
this.path = "webapi/entry.cgi";
}
@Override
protected TypeReference getClassForMapper() {
return new TypeReference<Response<DsmUploadResponse>>() {};
}
public DsmUploadRequest setDestinationFolderPath(String destinationFolderPath) {
this.destinationFolderPath = destinationFolderPath;
return this;
}
public DsmUploadRequest createParentFolders(Boolean createParents) {
this.createParents = createParents;
return this;
}
public DsmUploadRequest overwrite(DsmRequestParameters.OverwriteBehaviour overwrite) {
this.overwrite = overwrite;
return this;
}
public DsmUploadRequest setFilePath(String filePath) {
this.filePath = filePath;
return this;
}
public DsmUploadRequest setDestinationFileName(String destinationFileName) {
this.destinationFileName = destinationFileName;
return this;
}
public DsmUploadRequest setFileContent(InputStream fileContent) {
this.fileContent = fileContent;
return this;
}
public DsmUploadRequest setLastModifiedTime(LocalDateTime lastModifiedTime) {
this.lastModifiedTime = lastModifiedTime;
return this;
}
public DsmUploadRequest setCreatedTime(LocalDateTime createdTime) {
this.createdTime = createdTime;
return this;
}
public DsmUploadRequest setLastAccessedTime(LocalDateTime lastAccessedTime) {
this.lastAccessedTime = lastAccessedTime;
return this;
}
@Override
public Response<DsmUploadResponse> call() {
Map<String, String> params = new HashMap<>();
params.put("path", Optional.ofNullable(this.destinationFolderPath).orElseThrow(() -> new DsmException("you must define destination folder")));
Optional.ofNullable(this.createParents).ifPresent(c -> params.put("create_parents", c.toString()));
if(!this.overwrite.equals(DsmRequestParameters.OverwriteBehaviour.ERROR)) {
params.put("overwrite", String.valueOf(this.overwrite.getValue()));
}
if (Optional.ofNullable(this.fileContent).isPresent()) {
if (Optional.ofNullable(this.filePath).isPresent()) {
throw new DsmException("you can't specify both file path and file content stream to upload");
}
if (!Optional.ofNullable(this.destinationFileName).isPresent()) {
throw new DsmException("you musy define destination file name when using an upload stream");
}
} else {
if (!new File(Optional.ofNullable(this.filePath).orElseThrow(() -> new DsmException("you must define source file to upload"))).exists()) {
throw new DsmUploadException("File does not exist");
}
}
addDatesToRequest("atime", params, this.lastAccessedTime);
addDatesToRequest("crtime", params, this.createdTime);
addDatesToRequest("mtime", params, this.lastModifiedTime);
try {
String resp;
if (Optional.ofNullable(this.fileContent).isPresent()) {
resp = DsmUtils.makePostRequest(
build(),
this.fileContent,
this.destinationFileName,
params
);
} else if (Optional.ofNullable(this.destinationFileName).isPresent()) {
resp = DsmUtils.makePostRequest(
build(),
this.filePath,
this.destinationFileName,
params
);
} else {
resp = DsmUtils.makePostRequest(
build(),
this.filePath,
params
);
}
return deserialize(resp);
} catch (IOException e) {
throw new DsmException(e);
}
}
private void addDatesToRequest(String key, Map<String, String> params, LocalDateTime time) {
Optional.ofNullable(time).ifPresent(c -> params.put(key, String.valueOf(DateUtils.convertLocalDateTimeToUnixTimestamp(c))));
}
@Override
protected String build() {
return auth.getHost() +
(auth.getPort() == null ? "" : ":" + auth.getPort()) +
"/" +
getPath()+
"?_sid="+
auth.getSid()+"&"+
"api="+getApiName()+"&"+
"method="+getMethod()+"&"+
"version="+getVersion();
}
}
package responses;
import utils.DsmUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class Response<T> {
private boolean success;
private T data;
private Error error;
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public Error getError() {
return error;
}
public static class Error {
private String code;
private final List<ErrorDetail> errors = new ArrayList<>();
public String getCode() {
return code;
}
public Optional<String> getDescription() {
if(Optional.ofNullable(code).isPresent()) {
return Optional.of(DsmUtils.manageErrorMessage(Integer.valueOf(code)));
}
return Optional.empty();
}
public List<ErrorDetail> getErrors() {
return errors;
}
public static class ErrorDetail {
String code;
String path;
public String getCode() {
return code;
}
public String getPath() {
return path;
}
@Override
public String toString() {
return "ErrorDetail{" +
"code='" + code + '\'' +
", path='" + path + '\'' +
'}';
}
}
@Override
public String toString() {
return "Error{" +
"code='" + code + '\'' +
", errors=" + errors +
'}';
}
}
}
package responses.filestation;
import requests.filestation.DsmRequestParameters;
import java.util.List;
public class DsmResponseFields {
private DsmResponseFields() { }
public static class Owner {
/**
* User name of file owner.
*/
private String user;
/**
* Group name of file group.
*/
private String group;
/**
* File UID.
*/
private Long uid;
/**
* File GID.
*/
private Long gid;
public String getUser() {
return user;
}
public String getGroup() {
return group;
}
public Long getUid() {
return uid;
}
public Long getGid() {
return gid;
}
}
public static class VolumeStatus {
/**
* Byte size of free space of a volume where a shared
* folder is located.
*/
private Long freespace;
/**
* Byte size of total space of a volume where a shared
* folder is located.
*/
private Long totalspace;
/**
* true: A volume where a shared folder is located is
* read-only; false: It’s writable.
*/
private boolean readonly;
public Long getFreespace() {
return freespace;
}
public Long getTotalspace() {
return totalspace;
}
public boolean isReadonly() {
return readonly;
}
}
public static class Acl {
/**
* If a logged-in user has a privilege to append data or
* create folders within this folder or not.
*/
boolean append;
/**
* If a logged-in user has a privilege to delete a file/a
* folder within this folder or not.
*/
boolean del;
/**
* If a logged-in user has a privilege to execute
* files/traverse folders within this folder or not.
*/
boolean exec;
/**
* If a logged-in user has a privilege to read data or list
* folder within this folder or not.
*/
boolean read;
/**
* If a logged-in user has a privilege to write data or
* create files within this folder or not.
*/
boolean write;
public boolean isAppend() {
return append;
}
public boolean isDel() {
return del;
}
public boolean isExec() {
return exec;
}
public boolean isRead() {
return read;
}
public boolean isWrite() {
return write;
}
}
public static class AdvanceRight {
/**
* If a non-administrator user can download files in this
* shared folder through SYNO.FileStation.Download
* API or not.
*/
boolean disable_down_load;
/**
* If a non-administrator user can enumerate files in
* this shared folder though SYNO.FileStation.List API
* with list method or not.
*/
boolean disable_list;
/**
* If a non-administrator user can modify or overwrite
* files in this shared folder or not.
*/
boolean disable_modify;
public boolean isDisable_down_load() {
return disable_down_load;
}
public boolean isDisable_list() {
return disable_list;
}
public boolean isDisable_modify() {
return disable_modify;
}
}
public static class Perm {
/**
* “RW: The shared folder is writable; RO: the shared
* folder is read-only.
*/
private String share_right;
/**
* POSIX file permission, For example, 777 means
* owner, group or other has all permission; 764 means
* owner has all permission, group has read/write
* permission, other has read permission.
*/
private Integer posix;
/**
* Specail privelge of the shared folder
*/
private AdvanceRight adv_right;
/**
* If the configure of Windows ACL privilege of the
* shared folder is enabled or not
*/
boolean acl_enable;
/**
* true: The privilege of the shared folder is set to be
* ACL-mode. false: The privilege of the shared folder
* is set to be POSIX-mode.
*/
boolean is_acl_mode;
/**
* Windows ACL privilege. If a shared folder is set to be
* POSIX-mode, these values of Windows ACL
* privileges are derived from the POSIX privilege.
*/
private Acl acl;
public String getShare_right() {
return share_right;
}
public Integer getPosix() {
return posix;
}
public AdvanceRight getAdv_right() {
return adv_right;
}
public boolean isAcl_enable() {
return acl_enable;
}
public boolean isIs_acl_mode() {
return is_acl_mode;
}
public Acl getAcl() {
return acl;
}
}
public static class Time {
/**
* Linux timestamp of last access in second
*/
private Long atime;
/**
* Linux timestamp of last modification in second.
*/
private Long mtime;
/**
* Linux timestamp of last change in second.
*/
private Long ctime;
/**
* Linux timestamp of create time in second.
*/
private Long crtime;
public Long getAtime() {
return atime;
}
public Long getMtime() {
return mtime;
}
public Long getCtime() {
return ctime;
}
public Long getCrtime() {
return crtime;
}
}
public static class AdditionalListShare {
/**
* Real path of a shared folder in a volume space
*/
String real_path;
private Owner owner;
/**
* Time information of file including last access time,
* last modified time, last change time, and creation
* time.
*/
private Time time;
/**
* File permission information
*/
private Perm perm;
/**
* Type of a virtual file system of a mount point.
*/
private String mount_point_type;
/**
* Volume status including free space, total space and
* read-only status.
*/
private DsmResponseFields.VolumeStatus volume_status;
public String getReal_path() {
return real_path;
}
public Owner getOwner() {
return owner;
}
public Time getTime() {
return time;
}
public Perm getPerm() {
return perm;
}
public String getMount_point_type() {
return mount_point_type;
}
public VolumeStatus getVolume_status() {
return volume_status;
}
}
public static class Share {
/**
* Path of a shared folder.
*/
private String path;
/**
* Name of a shared folder.
*/
private String name;
private AdditionalListShare additional;
public String getPath() {
return path;
}
public String getName() {
return name;
}
public AdditionalListShare getAdditional() {
return additional;
}
}
public static class AdditionalListFolder {
/**
* Real path started with a volume path.
*/
private String real_path;
/**
* File size.
*/
private Long size;
/**
* File owner information including user name, group name, UID and GID.
*/
private DsmResponseFields.Owner owner;
/**
* Time information of file including last access time,
* last modified time, last change time and create time.
*/
private DsmResponseFields.Time time;
/**
* File permission information.
*/
private DsmResponseFields.Perm perm;
/**
* A type of a virtual file system of a mount point.
*/
private String mount_point_type;
/**
* File extension.
*/
private String type;
public String getReal_path() {
return real_path;
}
public Long getSize() {
return size;
}
public Owner getOwner() {
return owner;
}
public Time getTime() {
return time;
}
public Perm getPerm() {
return perm;
}
public String getMount_point_type() {
return mount_point_type;
}
public String getType() {
return type;
}
}
public static class Children {
/**
* Total number of files.
*/
private Integer total;
/**
* Requested offset
*/
private Integer offset;
/**
* Array of <file> objects.
*/
private Files files;
public Integer getTotal() {
return total;
}
public Integer getOffset() {
return offset;
}
public Files getFiles() {
return files;
}
}
public static class Favorite {
public enum Status {
valid,
broken
}
private String path;
private String name;
private DsmResponseFields.SharingLink.Status status;
private DsmResponseFields.AdditionalListFolder additional;
public String getPath() {
return path;
}
public String getName() {
return name;
}
public DsmResponseFields.SharingLink.Status getStatus() {
return status;
}
public DsmResponseFields.AdditionalListFolder getAdditional() {
return additional;
}
}
public static class Files {
/**
* Folder/file path started with a shared folder.
*/
private String path;
/**
* File name.
*/
private String name;
/**
* If this file is folder or not.
*/
private boolean isdir;
/**
* File list within a folder which is described by a <file>
* object. The value is returned, only if goto_path
* parameter is given.
*/
private List<DsmResponseFields.Children> children;
/**
* File additional object.
*/
private DsmResponseFields.AdditionalListFolder additional;
public String getPath() {
return path;
}
public String getName() {
return name;
}
public boolean isIsdir() {
return isdir;
}
public List<Children> getChildren() {
return children;
}
public DsmResponseFields.AdditionalListFolder getAdditional() {
return additional;
}
}
public static class SharingLink {
/**
* The accessibility status of the sharing link might be
* one of the following:
*/
public enum Status {
valid, // the sharing link is active
invalid, // the sharing link is not active because the available date has not arrived yet
expired, // the sharing link expired.
broken, //the sharing link broke due to a change in the file path or access permission
inactive
}
/**
* A unique ID of a sharing link.
*/
private String id;
/**
* A URL of a sharing link.
*/
private String url;
/**
* A user name of a sharing link owner
*/
private String link_owner;
/**
* A file or folder path of a sharing link.
*/
private String path;
/**
* Whether the sharing link is for a folder
*/
private String isFolder;
/**
* Whether the sharing link has password.
*/
private boolean has_password;
/**
* The expiration date of the sharing link in the format
* YYYY-MM-DD. If the value is set to 0, the link will
* be permanent.
*/
private String date_expired;
/**
* The date when the sharing link becomes active in
* the format YYYY-MM-DD. If the value is set to 0,
* the file sharing link will be active immediately after
* creation.
*/
private String date_available;
/**
* The accessibility status of the sharing link might be
* one of the following:
* (1) valid: the sharing link is active.
* (2) invalid: the sharing link is not active because
* the available date has not arrived yet.
* (3) expired: the sharing link expired.
* (4) broken: the sharing link broke due to a change
* in the file path or access permission.
*/
private Status status;
public String getId() {
return id;
}
public String getUrl() {
return url;
}
public String getLink_owner() {
return link_owner;
}
public String getPath() {
return path;
}
public String getIsFolder() {
return isFolder;
}
public boolean isHas_password() {
return has_password;
}
public String getDate_expired() {
return date_expired;
}
public String getDate_available() {
return date_available;
}
public Status getStatus() {
return status;
}
}
public static class SharedLink {
/**
* A file/folder path of the sharing link.
*/
private String path;
/**
* A created URL of the sharing link.
*/
private String url;
/**
* A created unique ID of the sharing link.
*/
private String id;
/**
* Base64-encoded image of QR code describing
* the URL of the sharing link
*/
private String qrcode;
/**
* 0 for creating it successfully, otherwise is the
* error code for failed to create it.
*/
private Integer error;
public String getPath() {
return path;
}
public String getUrl() {
return url;
}
public String getId() {
return id;
}
public String getQrcode() {
return qrcode;
}
public Integer getError() {
return error;
}
}
}
package responses.filestation;
public interface DsmSimpleResponse { }
package responses.filestation.action;
public class DsmCopyMoveResponse {
//start
/**
* A unique ID for the delete task which is
* gotten from start method.
*/
private String taskid;
/**
* If accurate_progress parameter is true, byte
* sizes of all copied/moved files will be accumulated. If
* false, only byte sizes of the file you give in path
* parameter is accumulated.
*/
private Integer processed_size;
/**
* If accurate_progress parameter is true, the
* value indicates total byte sizes of files including
* subfolders will be copied/moved. If false, it
* indicates total byte sizes of files you give in path
* parameter excluding files within subfolders.
* Otherwise, when the total number is calculating,
* the value is -1.
*/
private Integer total;
/**
* A copying/moving path which you give in path
* parameter.
*/
private String path;
/**
* If the copy/move task is finished or not.
*/
private Boolean finished;
/**
* A progress value is between 0~1. It is equal to
* processed_size parameter divided by total
* parameter.
*/
private Double progress;
/**
* A desitination folder path where files/folders are
* copied/moved.
*/
private String dest_folder_path;
public String getTaskid() {
return taskid;
}
public Integer getProcessed_size() {
return processed_size;
}
public Integer getTotal() {
return total;
}
public String getPath() {
return path;
}
public Boolean getFinished() {
return finished;
}
public Double getProgress() {
return progress;
}
public String getDest_folder_path() {
return dest_folder_path;
}
}
package responses.filestation.action;
import responses.filestation.DsmResponseFields;
import java.util.List;
public class DsmCreateFolderResponse {
private List<DsmResponseFields.Files> folders;
public List<DsmResponseFields.Files> getFolders() {
return folders;
}
}
package responses.filestation.action;
public class DsmDirSizeResponse {
private String taskid;
/**
* If the task is finished or not.
*/
private boolean finished;
/**
* Number of directories in the queried path(s)
*/
private Long num_dir;
/**
* Number of files in the queried path(s).
*/
private Long num_file;
/**
* Accumulated byte size of the queried path(s).
*/
private Long total_size;
public String getTaskid() {
return taskid;
}
public boolean isFinished() {
return finished;
}
public Long getNum_dir() {
return num_dir;
}
public Long getNum_file() {
return num_file;
}
public Long getTotal_size() {
return total_size;
}
}
package responses.filestation.action;
import responses.filestation.DsmResponseFields;
import java.util.List;
public class DsmRenameResponse {
private List<DsmResponseFields.Files> files;
public List<DsmResponseFields.Files> getFiles() {
return files;
}
}
package responses.filestation.delete;
public class DsmDeleteResponse {
//start
/**
* A unique ID for the delete task which is
* gotten from start method.
*/
private String taskid;
//status
/**
* If accurate_progress parameter is true the
* number of all deleted files will be accumulated. If
* false only the number of file you give in path
* parameter is accumulated.
*/
private Integer processed_num;
/**
* If accurate_progress parameter is true the
* value indicates how many files including subfolders
* will be deleted. If false it indicates how many files
* you give in path parameter. When the total number
* is calculating, the value is -1.
*/
private Integer total;
/**
* A deletion path which you give in path parameter.
*/
private String path;
/**
* A deletion path which could be located at a
* subfolder.
*/
private String processing_path;
/**
* Whether or not the deletion task is finished.
*/
private boolean finished;
/**
* Progress value whose range between 0~1 is equal
* to processed_num parameter divided by total
* parameter
*/
private Double progress;
public String getTaskid() {
return taskid;
}
public Integer getProcessed_num() {
return processed_num;
}
public Integer getTotal() {
return total;
}
public String getPath() {
return path;
}
public String getProcessing_path() {
return processing_path;
}
public boolean isFinished() {
return finished;
}
public Double getProgress() {
return progress;
}
}
package responses.filestation.favorite;
import responses.filestation.DsmResponseFields;
import java.util.List;
public class DsmListFavoriteResponse {
private Integer total;
private Integer offset;
private List<DsmResponseFields.Favorite> favorites;
public Integer getTotal() {
return total;
}
public Integer getOffset() {
return offset;
}
public List<DsmResponseFields.Favorite> getFavorites() {
return favorites;
}
}
package responses.filestation.lists;
import responses.filestation.DsmResponseFields;
import java.util.List;
public class DsmListFolderResponse {
private Integer total;
private Integer offset;
private List<DsmResponseFields.Files> files;
public Integer getTotal() {
return total;
}
public Integer getOffset() {
return offset;
}
public List<DsmResponseFields.Files> getFiles() {
return files;
}
}
package responses.filestation.lists;
import responses.filestation.DsmResponseFields;
import java.util.List;
public class DsmSharedFolderResponse {
/**
* Total number of shared folders.
*/
Integer total;
/**
* Requested offset.
*/
Integer offset;
List<DsmResponseFields.Share> shares;
public Integer getTotal() {
return total;
}
public Integer getOffset() {
return offset;
}
public List<DsmResponseFields.Share> getShares() {
return shares;
}
}
package responses.filestation.login;
public class DsmLoginResponse {
private String sid;
public String getSid() {
return sid;
}
}
package responses.filestation.search;
import responses.filestation.DsmResponseFields;
import java.util.List;
public class DsmSearchResultResponse {
/**
* Total number of matched files.
*/
private Integer total;
/**
* Requested offset.
*/
private Integer offset;
/**
* If the searching task is finished or not.
*/
private boolean finished;
private List<DsmResponseFields.Files> files;
public Integer getTotal() {
return total;
}
public Integer getOffset() {
return offset;
}
public boolean isFinished() {
return finished;
}
public List<DsmResponseFields.Files> getFiles() {
return files;
}
}
package responses.filestation.search;
public class DsmSearchStartResponse {
private String taskid;
public String getTaskid() {
return taskid;
}
}
package responses.filestation.share;
import responses.filestation.DsmResponseFields;
import java.util.List;
public class DsmShareCreateResponse {
List<DsmResponseFields.SharedLink> links;
public List<DsmResponseFields.SharedLink> getLinks() {
return links;
}
}
package responses.filestation.share;
import responses.filestation.DsmResponseFields;
import java.util.List;
public class DsmShareListResponse {
private Integer total;
private Integer offset;
private List<DsmResponseFields.SharingLink> links;
public Integer getTotal() {
return total;
}
public Integer getOffset() {
return offset;
}
public List<DsmResponseFields.SharingLink> getLinks() {
return links;
}
}
package responses.filestation.transfert;
import java.io.File;
public class DsmDownloadResponse {
private final File file;
public DsmDownloadResponse(File downloadedFile) {
file = downloadedFile;
}
public File getFile() {
return file;
}
}
package responses.filestation.transfert;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
public class DsmDownloadStreamResponse {
private final InputStream inputStream;
private final String contentType;
private final int contentLength;
public DsmDownloadStreamResponse(InputStream inputStream, String contentType, int contentLength) {
this.inputStream = inputStream;
this.contentType = contentType;
this.contentLength = contentLength;
}
public InputStream getInputStream() {
return inputStream;
}
public String getContentType() {
return contentType;
}
public int getContentLength() {
return contentLength;
}
}
package responses.filestation.transfert;
public class DsmUploadResponse {
private boolean blSki;
private String file;
private Long pid;
protected Long progress;
public boolean isBlSki() {
return blSki;
}
public String getFile() {
return file;
}
public Long getPid() {
return pid;
}
public Long getProgress() {
return progress;
}
}
package utils;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
public class DateUtils {
private static final String dsmDateFormat = "YYYY-MM-dd hh:mm:ss";
private DateUtils(){}
public static Long convertLocalDateTimeToUnixTimestamp(LocalDateTime time) {
Instant instant = time.atZone(ZoneId.systemDefault()).toInstant();
return instant.toEpochMilli();
}
public static String convertDateToString(LocalDateTime localDate) {
return localDate.format(DateTimeFormatter.ofPattern(dsmDateFormat));
}
}
package utils;
import exeptions.DsmException;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class DsmUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(DsmUtils.class);
private static final Map<Integer, String> codeErrors = new HashMap<>();
static {
codeErrors.put(101, "No parameter of API, method or version");
codeErrors.put(102, "The requested API does not exist");
codeErrors.put(103, "The requested method does not exist");
codeErrors.put(104, "The requested version does not support the functionality");
codeErrors.put(105, "The logged in session does not have permission");
codeErrors.put(106, "Session timeout");
codeErrors.put(107, "Session interrupted by duplicate login");
codeErrors.put(400, "Invalid parameter of file operation");
codeErrors.put(401, "Unknown error of file operation");
codeErrors.put(402, "System is too busy");
codeErrors.put(403, "Invalid user does this file operation");
codeErrors.put(404, "Invalid group does this file operation");
codeErrors.put(405, "Invalid user and group does this file operation");
codeErrors.put(406, "Can’t get user/group information from the account server");
codeErrors.put(407, "Operation not permitted");
codeErrors.put(408, "No such file or directory");
codeErrors.put(409, "Non-supported file system");
codeErrors.put(410, "Failed to connect internet-based file system (ex: CIFS)");
codeErrors.put(411, "Read-only file system");
codeErrors.put(412, "Filename too long in the non-encrypted file system");
codeErrors.put(413, "Filename too long in the encrypted file system");
codeErrors.put(414, "File already exists");
codeErrors.put(415, "Disk quota exceeded");
codeErrors.put(416, "No space left on device");
codeErrors.put(417, "Input/output error");
codeErrors.put(418, "Illegal name or path");
codeErrors.put(419, "Illegal file name");
codeErrors.put(420, "Illegal file name on FAT file system");
codeErrors.put(421, "Device or resource busy");
codeErrors.put(599, "No such task of the file operation");
codeErrors.put(1800, "There is no Content-Length information in the HTTP header or the received\n" +
"size does not match the value of Content-Length information in the HTTP\n" +
"header.");
codeErrors.put(1801, "Wait too long, no date can be received from client (Default maximum wait time is 3600 seconds)");
codeErrors.put(1802, "No filename information in the last part of file content.\n");
codeErrors.put(1803, "Upload connection is cancelled.");
codeErrors.put(1804, "Failed to upload too big file to FAT file system.");
codeErrors.put(1805, "Can’t overwrite or skip the existed file, if no overwrite parameter is given.");
codeErrors.put(900, "Failed to delete file(s)/folder(s). More information in <errors> object.");
codeErrors.put(1200, "Failed to rename it. More information in <errors> object.");
codeErrors.put(1000, "Failed to copy files/folders. More information in <errors> object.");
codeErrors.put(1001, "Failed to move files/folders. More information in <errors> object.");
codeErrors.put(1002, "An error occurred at the destination. More information in <errors> object.");
codeErrors.put(1003, "Cannot overwrite or skip the existing file because no overwrite parameter is given.");
codeErrors.put(1004, "File cannot overwrite a folder with the same name, or folder cannot overwrite a file with the same name.");
codeErrors.put(1006, "Cannot copy/move file/folder with special characters to a FAT32 file system.");
codeErrors.put(1007, "Cannot copy/move a file bigger than 4G to a FAT32 file system.");
codeErrors.put(1100, "Failed to create a folder. More information in <errors> object");
codeErrors.put(1101, "The number of folders to the parent folder would exceed the system limitation");
codeErrors.put(2000, "Sharing link does not exist");
codeErrors.put(2001, "Cannot generate sharing link because too many sharing links exist.");
codeErrors.put(800, "A folder path of favorite folder is already added to user’s favorites");
codeErrors.put(801, "A name of favorite folder conflicts with an existing folder path in the user’s favorites.");
codeErrors.put(802, "There are too many favorites to be added");
codeErrors.put(2002, "Failed to access sharing links.");
}
private DsmUtils(){}
public static String manageErrorMessage(Integer code) {
return Optional.ofNullable(codeErrors.get(code)).orElse("Unknown error");
}
public static String makePostRequest(String url, InputStream fileContent, String fileName, Map<String, String> params) throws IOException {
InputStreamBody inputStreamBody = new InputStreamBody(fileContent, ContentType.DEFAULT_BINARY, fileName);
return makePostRequest(url, inputStreamBody, params);
}
public static String makePostRequest(String url, String filePath, String fileName, Map<String, String> params) throws IOException {
FileBody fileBody = new FileBody(new File(filePath), ContentType.DEFAULT_BINARY, fileName);
return makePostRequest(url, fileBody, params);
}
public static String makePostRequest(String url, String filePath, Map<String, String> params) throws IOException {
FileBody fileBody = new FileBody(new File(filePath), ContentType.DEFAULT_BINARY, new File(filePath).getName());
return makePostRequest(url, fileBody, params);
}
private static String makePostRequest(String url, ContentBody body, Map<String, String> params) throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
String result = "";
try {
HttpPost httppost = new HttpPost(url);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
params.forEach((key, value) -> multipartEntityBuilder.addPart(key, new StringBody(value, ContentType.TEXT_PLAIN)));
multipartEntityBuilder.addPart("file", body);
HttpEntity reqEntity = multipartEntityBuilder
.setLaxMode()
.build();
httppost.setEntity(reqEntity);
LOGGER.debug("executing request {}", httppost.getRequestLine());
try (CloseableHttpResponse response = httpclient.execute(httppost)) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity);
LOGGER.debug(result);
}
EntityUtils.consume(resEntity);
}
} finally {
httpclient.close();
}
return result;
}
public static File downloadFile(InputStream inputStream, String destinationPath) throws IOException {
File file = new File(destinationPath);
try(FileOutputStream fos = new FileOutputStream(file) ) {
int inByte;
while((inByte = inputStream.read()) != -1)
fos.write(inByte);
}
return file;
}
public static String extractFileName(String path) {
String completePath = Optional.ofNullable(path).orElseThrow(() -> new DsmException("Unable to get file name"));
return completePath.substring(completePath.lastIndexOf('/')+1);
}
public static String extractRootFolderPath(String filePath) {
return Optional.of(filePath).orElse("").replace("/"+extractFileName(filePath), "");
}
}
package utils;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonFactory {
private static final ObjectMapper mapper;
private JacksonFactory() { }
static {
mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
public static ObjectMapper getMapper() {
return mapper;
}
}
import exeptions.DsmLoginException;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import requests.DsmAuth;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class DsmAuthTest {
@Rule
public TemporaryFolder folder= new TemporaryFolder();
@Test
public void createAuthFromResourceSuccess() throws IOException {
//Given
String fileSuccess = "env-success.properties";
List<String> properties = new ArrayList<>();
properties.add("host=dummyHost");
properties.add("port=2000");
properties.add("username=dummyUsername");
properties.add("password=dummyPassword");
File file = Utils.makeFile(folder, properties, fileSuccess);
DsmAuth dsmAuth = DsmAuth.fromFile(file);
Assert.assertNotNull(dsmAuth);
Assert.assertEquals("dummyHost", dsmAuth.getHost() );
Assert.assertEquals(Integer.valueOf(2000), dsmAuth.getPort());
Assert.assertEquals("dummyUsername", dsmAuth.getUserName());
Assert.assertEquals("dummyPassword", dsmAuth.getPassword());
}
@Test(expected = DsmLoginException.class)
public void createAuthFromResourceEmptyLineInFile() throws IOException {
//Given
String fileSuccess = "env-wrong.properties";
List<String> properties = new ArrayList<>();
properties.add("host=dummyHost");
properties.add("");
properties.add("username=dummyUsername");
properties.add("password=dummyPassword");
File file = Utils.makeFile(folder, properties, fileSuccess);
DsmAuth.fromFile(file);
}
@Test(expected = DsmLoginException.class)
public void createAuthFromResourceEmptyValue() throws IOException {
//Given
String fileSuccess = "env-wrong.properties";
List<String> properties = new ArrayList<>();
properties.add("host=dummyHost");
properties.add("port=");
properties.add("username=dummyUsername");
properties.add("password=dummyPassword");
File file = Utils.makeFile(folder, properties, fileSuccess);
DsmAuth.fromFile(file);
}
@Test(expected = DsmLoginException.class)
public void createAuthFromResourceFileNotExist() {
//Given
String fileSuccess = "env-wrong.properties";
File file = new File(fileSuccess);
DsmAuth.fromFile(file);
}
@Test(expected = DsmLoginException.class)
public void createAuthFromResourceParameterMissing() throws IOException {
//Given
String fileSuccess = "env-wrong.properties";
List<String> properties = new ArrayList<>();
properties.add("host=dummyHost");
properties.add("username=dummyUsername");
properties.add("password=dummyPassword");
File file = Utils.makeFile(folder, properties, fileSuccess);
DsmAuth.fromFile(file);
}
@Test
public void createAuthOfParameters() {
//Given
String host = "http://host";
Integer port = 5000;
String username = "username";
String password = "password";
DsmAuth dsmAuth = DsmAuth.of(host, port, username, password);
Assert.assertNotNull(dsmAuth);
Assert.assertEquals("http://host", dsmAuth.getHost() );
Assert.assertEquals(Integer.valueOf(5000), dsmAuth.getPort());
Assert.assertEquals("username", dsmAuth.getUserName());
Assert.assertEquals("password", dsmAuth.getPassword());
}
@Test(expected = DsmLoginException.class)
public void createAuthOfHostIsNull() {
//Given
Integer port = 5000;
String username = "username";
String password = "password";
DsmAuth.of(null, port, username, password);
}
@Test
public void createAuthOfPortIsNull() {
//Given
String host = "http://host";
String username = "username";
String password = "password";
Assert.assertNotNull(DsmAuth.of(host, null, username, password));
}
@Test(expected = DsmLoginException.class)
public void createAuthOfUserNameIsNull() {
//Given
String host = "http://host";
Integer port = 5000;
String password = "password";
DsmAuth.of(host, port, null, password);
}
@Test(expected = DsmLoginException.class)
public void createAuthOfPasswordIsNull() {
//Given
String host = "http://host";
Integer port = 5000;
String username = "username";
DsmAuth.of(host, port, username, null);
}
}
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import clients.DsmFileStationClient;
import org.junit.*;
import org.junit.rules.TemporaryFolder;
import org.slf4j.LoggerFactory;
import requests.DsmAuth;
import requests.filestation.action.DsmCopyMoveRequest;
import requests.filestation.DsmRequestParameters;
import responses.Response;
import responses.filestation.action.DsmCopyMoveResponse;
import java.io.File;
import java.io.IOException;
public class DsmCopyMoveTest extends DsmTest{
private final String ROOT_FOLDER = "/homes/testResource";
private DsmFileStationClient client;
private File fileToUpload;
@Rule
public TemporaryFolder folder= new TemporaryFolder();
@Before
public void initTest() throws IOException {
super.initTest();
fileToUpload = createNewFile();
client = DsmFileStationClient.login(DsmAuth.fromResource("env.properties"));
client.upload(ROOT_FOLDER, fileToUpload.getAbsolutePath())
.createParentFolders(true)
.overwrite(DsmRequestParameters.OverwriteBehaviour.OVERWRITE)
.call();
}
@After
public void postTest() {
client.simpleDelete(ROOT_FOLDER).setRecursive(true).call();
}
@Test
public void copyFileToNewDestination() {
Assert.assertTrue(client.exists(ROOT_FOLDER+"/"+ fileToUpload.getName()));
client.createFolder(ROOT_FOLDER, "copied").call();
Response<DsmCopyMoveResponse> copyOrMoveResponse = client.copyOrMove(ROOT_FOLDER+"/"+ fileToUpload.getName(), ROOT_FOLDER+"/copied")
.start();
Assert.assertTrue(client.exists(ROOT_FOLDER+"/copied/"+ fileToUpload.getName()));
Assert.assertTrue(copyOrMoveResponse.isSuccess());
Assert.assertNotNull(copyOrMoveResponse.getData());
}
@Test
public void copyFileToNewDestinationFileAlreadyExist() {
Assert.assertTrue(client.exists(ROOT_FOLDER+"/"+ fileToUpload.getName()));
client.createFolder(ROOT_FOLDER, "copied").call();
client.copyOrMove(ROOT_FOLDER+"/"+ fileToUpload.getName(), ROOT_FOLDER+"/copied")
.start();
Response<DsmCopyMoveResponse> copyOrMoveResponse = client.copyOrMove(ROOT_FOLDER+"/"+ fileToUpload.getName(), ROOT_FOLDER+"/copied")
.start();
Assert.assertFalse(copyOrMoveResponse.isSuccess());
Assert.assertNull(copyOrMoveResponse.getData());
Assert.assertNotNull(copyOrMoveResponse.getError());
Assert.assertEquals("1000", copyOrMoveResponse.getError().getCode());
Assert.assertNotNull(copyOrMoveResponse.getError().getErrors());
Assert.assertEquals("1003", copyOrMoveResponse.getError().getErrors().get(0).getCode());
}
@Test
public void copyFileToNewDestinationFileAlreadyExistOverwrite() {
Assert.assertTrue(client.exists(ROOT_FOLDER+"/"+ fileToUpload.getName()));
client.createFolder(ROOT_FOLDER, "copied").call();
client.copyOrMove(ROOT_FOLDER+"/"+ fileToUpload.getName(), ROOT_FOLDER+"/copied")
.start();
Response<DsmCopyMoveResponse> copyOrMoveResponse = client.copyOrMove(ROOT_FOLDER+"/"+ fileToUpload.getName(), ROOT_FOLDER+"/copied")
.setOverwriteBehaviour(DsmRequestParameters.OverwriteBehaviour.OVERWRITE)
.start();
Assert.assertTrue(copyOrMoveResponse.isSuccess());
Assert.assertNotNull(copyOrMoveResponse.getData());
Assert.assertTrue(client.exists(ROOT_FOLDER+"/copied/"+ fileToUpload.getName()));
}
@Test
public void copyFileToNewDestinationFileAlreadyExistSkip() {
Assert.assertTrue(client.exists(ROOT_FOLDER+"/"+ fileToUpload.getName()));
client.createFolder(ROOT_FOLDER, "copied").call();
client.copyOrMove(ROOT_FOLDER+"/"+ fileToUpload.getName(), ROOT_FOLDER+"/copied")
.start();
Response<DsmCopyMoveResponse> copyOrMoveResponse = client.copyOrMove(ROOT_FOLDER+"/"+ fileToUpload.getName(), ROOT_FOLDER+"/copied")
.setOverwriteBehaviour(DsmRequestParameters.OverwriteBehaviour.SKIP)
.start();
Assert.assertTrue(copyOrMoveResponse.isSuccess());
Assert.assertNotNull(copyOrMoveResponse.getData());
Assert.assertTrue(client.exists(ROOT_FOLDER+"/copied/"+ fileToUpload.getName()));
}
@Test
public void copyFileToNewDestinationStatus() {
Assert.assertTrue(client.exists(ROOT_FOLDER+"/"+ fileToUpload.getName()));
client.createFolder(ROOT_FOLDER, "copied").call();
DsmCopyMoveRequest dsmCopyMoveRequest = client.copyOrMove(ROOT_FOLDER+"/"+ fileToUpload.getName(), ROOT_FOLDER+"/copied");
Response<DsmCopyMoveResponse> copyOrMoveResponse = dsmCopyMoveRequest.start();
Assert.assertTrue(copyOrMoveResponse.isSuccess());
Assert.assertNotNull(copyOrMoveResponse.getData());
Assert.assertNotNull(copyOrMoveResponse.getData().getTaskid());
dsmCopyMoveRequest.setTaskId(copyOrMoveResponse.getData().getTaskid());
Response<DsmCopyMoveResponse> copyOrMoveStatus = dsmCopyMoveRequest.status();
Assert.assertTrue(copyOrMoveStatus.isSuccess());
Assert.assertNotNull(copyOrMoveStatus.getData());
Assert.assertNotNull(copyOrMoveStatus.getData().getDest_folder_path());
Assert.assertNotNull(copyOrMoveStatus.getData().getFinished());
Assert.assertNotNull(copyOrMoveStatus.getData().getProcessed_size());
Assert.assertNotNull(copyOrMoveStatus.getData().getProgress());
Assert.assertNotNull(copyOrMoveStatus.getData().getTotal());
Response<DsmCopyMoveResponse> copyOrMoveStop = dsmCopyMoveRequest.stop();
Assert.assertTrue(copyOrMoveStop.isSuccess());
Assert.assertTrue(client.exists(ROOT_FOLDER+"/copied/"+ fileToUpload.getName()));
}
@Test
public void moveFileToNewDestinationStatus() {
Assert.assertTrue(client.exists(ROOT_FOLDER+"/"+ fileToUpload.getName()));
client.createFolder(ROOT_FOLDER, "copied").call();
DsmCopyMoveRequest dsmCopyMoveRequest = client.copyOrMove(ROOT_FOLDER+"/"+ fileToUpload.getName(), ROOT_FOLDER+"/copied");
Response<DsmCopyMoveResponse> copyOrMoveResponse = dsmCopyMoveRequest.setRemoveSrc(true).start();
Assert.assertTrue(copyOrMoveResponse.isSuccess());
Assert.assertNotNull(copyOrMoveResponse.getData());
Assert.assertNotNull(copyOrMoveResponse.getData().getTaskid());
dsmCopyMoveRequest.setTaskId(copyOrMoveResponse.getData().getTaskid());
Response<DsmCopyMoveResponse> copyOrMoveStatus = dsmCopyMoveRequest.status();
Assert.assertTrue(copyOrMoveStatus.isSuccess());
Assert.assertNotNull(copyOrMoveStatus.getData());
Assert.assertNotNull(copyOrMoveStatus.getData().getDest_folder_path());
Assert.assertNotNull(copyOrMoveStatus.getData().getFinished());
Assert.assertNotNull(copyOrMoveStatus.getData().getProcessed_size());
Assert.assertNotNull(copyOrMoveStatus.getData().getProgress());
Assert.assertNotNull(copyOrMoveStatus.getData().getTotal());
Response<DsmCopyMoveResponse> copyOrMoveStop = dsmCopyMoveRequest.stop();
Assert.assertTrue(copyOrMoveStop.isSuccess());
Assert.assertTrue(client.exists(ROOT_FOLDER+"/copied/"+ fileToUpload.getName()));
Assert.assertFalse(client.exists(ROOT_FOLDER+"/"+ fileToUpload.getName()));
}
private File createNewFile() throws IOException {
String fileSuccess = "dummy-upload-file"+System.currentTimeMillis()+".txt";
String content = "success content";
return Utils.makeFile(folder, content, fileSuccess);
}
}
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import clients.DsmFileStationClient;
import org.junit.*;
import org.junit.rules.TemporaryFolder;
import org.slf4j.LoggerFactory;
import requests.DsmAuth;
import requests.filestation.DsmRequestParameters;
import responses.Response;
import responses.filestation.action.DsmCreateFolderResponse;
import java.io.IOException;
public class DsmCreateFolderTest extends DsmTest{
private final String ROOT_FOLDER = "/homes/testResource";
private DsmFileStationClient client;
@Rule
public TemporaryFolder folder= new TemporaryFolder();
@Before
public void initTest() throws IOException {
super.initTest();
client = DsmFileStationClient.login(DsmAuth.fromResource("env.properties"));
}
@After
public void postTest() {
client.simpleDelete(ROOT_FOLDER).setRecursive(true).call();
}
@Test
public void createNewFolderForceParentAndSuccess() {
Response<DsmCreateFolderResponse> createFolderResponse = client.createFolder(ROOT_FOLDER, "newFolder")
.forceCreateParentFolder(true)
.call();
Assert.assertTrue(createFolderResponse.isSuccess());
Assert.assertNotNull(createFolderResponse.getData());
Assert.assertNotNull(createFolderResponse.getData().getFolders());
Assert.assertEquals(1, createFolderResponse.getData().getFolders().size());
}
@Test
public void createNewFolderAndSuccess() {
client.createFolder(ROOT_FOLDER, "newFolder")
.forceCreateParentFolder(true)
.call();
Response<DsmCreateFolderResponse> createFolderResponse = client.createFolder(ROOT_FOLDER, "newFolder2")
.call();
Assert.assertTrue(createFolderResponse.isSuccess());
Assert.assertNotNull(createFolderResponse.getData());
Assert.assertNotNull(createFolderResponse.getData().getFolders());
Assert.assertEquals(1, createFolderResponse.getData().getFolders().size());
}
@Test
public void createNewFolderAndWithAdditionalsSuccess() {
Response<DsmCreateFolderResponse> createFolderResponse = client.createFolder(ROOT_FOLDER, "newFolder")
.forceCreateParentFolder(true)
.addAdditional(DsmRequestParameters.Additional.OWNER)
.call();
Assert.assertTrue(createFolderResponse.isSuccess());
Assert.assertNotNull(createFolderResponse.getData());
Assert.assertNotNull(createFolderResponse.getData().getFolders());
Assert.assertEquals(1, createFolderResponse.getData().getFolders().size());
Assert.assertNotNull(createFolderResponse.getData().getFolders().get(0).getAdditional());
}
@Test
public void createMultipleNewFoldersAndSuccess() {
Response<DsmCreateFolderResponse> createFolderResponse = client.createFolder(ROOT_FOLDER, "newFolder")
.addNewFolder(ROOT_FOLDER,"newFolder2")
.addNewFolder(ROOT_FOLDER,"newFolder3")
.forceCreateParentFolder(true)
.call();
Assert.assertTrue(createFolderResponse.isSuccess());
Assert.assertNotNull(createFolderResponse.getData());
Assert.assertNotNull(createFolderResponse.getData().getFolders());
Assert.assertEquals(3, createFolderResponse.getData().getFolders().size());
}
@Test
public void createNewFolderParentNotExistAndFailed() {
Response<DsmCreateFolderResponse> createFolderResponse = client.createFolder(ROOT_FOLDER, "newFolder")
.call();
Assert.assertFalse(createFolderResponse.isSuccess());
Assert.assertNull(createFolderResponse.getData());
Assert.assertNotNull(createFolderResponse.getError());
Assert.assertEquals("1100", createFolderResponse.getError().getCode());
Assert.assertEquals("408", createFolderResponse.getError().getErrors().get(0).getCode());
}
}
import clients.DsmFileStationClient;
import exeptions.DsmDeleteException;
import org.junit.*;
import org.junit.rules.TemporaryFolder;
import requests.DsmAuth;
import requests.filestation.DsmRequestParameters;
import responses.Response;
import responses.filestation.delete.DsmDeleteResponse;
import utils.DsmUtils;
import java.io.File;
import java.io.IOException;
public class DsmDeleteTest extends DsmTest{
private final String ROOT_FOLDER = "/homes/testResource";
private DsmFileStationClient client;
private File fileToDownload;
@Rule
public TemporaryFolder folder= new TemporaryFolder();
@Before
public void initTest() throws IOException {
super.initTest();
fileToDownload = createNewFile();
client = DsmFileStationClient.login(DsmAuth.fromResource("env.properties"));
client.upload(ROOT_FOLDER, fileToDownload.getAbsolutePath())
.createParentFolders(true)
.overwrite(DsmRequestParameters.OverwriteBehaviour.OVERWRITE)
.call();
}
@After
public void postTest() {
client.simpleDelete(ROOT_FOLDER).setRecursive(true).call();
}
@Test
public void deleteOneFileAndSuccess() {
Assert.assertTrue(client.exists(ROOT_FOLDER+"/"+fileToDownload.getName()));
Response<DsmDeleteResponse> deleteResponse = client.simpleDelete(ROOT_FOLDER+"/"+fileToDownload.getName())
.call();
Assert.assertTrue(deleteResponse.isSuccess());
Assert.assertFalse(client.exists(ROOT_FOLDER+"/"+fileToDownload.getName()));
}
@Test
public void deleteAdvancedOneFileAndSuccess() {
Assert.assertTrue(client.exists(ROOT_FOLDER+"/"+fileToDownload.getName()));
Response<DsmDeleteResponse> deleteResponse = client.advancedDelete()
.addFileToDelete(ROOT_FOLDER+"/"+fileToDownload.getName())
.start();
Assert.assertTrue(deleteResponse.isSuccess());
Assert.assertNotNull(deleteResponse.getData());
Assert.assertNotNull(deleteResponse.getData().getTaskid());
Response<DsmDeleteResponse> statusResponse = client.advancedDelete()
.taskId(deleteResponse.getData().getTaskid())
.status();
Assert.assertTrue(statusResponse.isSuccess());
Assert.assertNotNull(statusResponse.getData());
Assert.assertNotNull(statusResponse.getData().getPath());
Assert.assertNotNull(statusResponse.getData().getProcessed_num());
Assert.assertNotNull(statusResponse.getData().getProcessing_path());
Assert.assertNotNull(statusResponse.getData().getTotal());
Assert.assertNotNull(statusResponse.getData().getProgress());
}
@Test
public void deleteFileNotExistAndFail() throws IOException {
File fileToUpload = createNewFile();
Response<DsmDeleteResponse> deleteResponse = client.advancedDelete()
.addFileToDelete(ROOT_FOLDER+"/"+fileToUpload.getName())
.start();
Assert.assertTrue(deleteResponse.isSuccess());
Assert.assertNotNull(deleteResponse.getData());
Assert.assertNotNull(deleteResponse.getData().getTaskid());
Response<DsmDeleteResponse> statusResponse = client.advancedDelete()
.taskId(deleteResponse.getData().getTaskid())
.status();
Assert.assertTrue(statusResponse.isSuccess());
Assert.assertNotNull(statusResponse.getData());
Assert.assertEquals("",statusResponse.getData().getPath());
Assert.assertNotNull(statusResponse.getData().getProcessed_num());
Assert.assertEquals("",statusResponse.getData().getProcessing_path());
Assert.assertEquals(Integer.valueOf("-1"), statusResponse.getData().getTotal());
Assert.assertNotNull(statusResponse.getData().getProgress());
}
@Test(expected = DsmDeleteException.class)
public void deleteFileNotSetAndFail() {
client.advancedDelete()
.start();
}
@Test(expected = DsmDeleteException.class)
public void getStatusWithoutTakId() {
client.advancedDelete()
.status();
}
@Test(expected = DsmDeleteException.class)
public void getStopWithoutTakId() {
client.advancedDelete()
.status();
}
@Test
public void getStatusWithDummyTaskId() {
Response<DsmDeleteResponse> statusResponse = client.advancedDelete()
.taskId("TaskId")
.status();
Assert.assertFalse(statusResponse.isSuccess());
Assert.assertNull(statusResponse.getData());
Assert.assertNotNull(statusResponse.getError());
Assert.assertNotNull(statusResponse.getError().getCode());
Assert.assertEquals("No such task of the file operation", DsmUtils.manageErrorMessage(Integer.valueOf(statusResponse.getError().getCode())));
}
@Test
public void deleteAdvancedMultipleFilesAndSuccess() throws IOException {
File fileToDownload2 = createNewFile();
client.upload(ROOT_FOLDER, fileToDownload2.getAbsolutePath())
.createParentFolders(true)
.overwrite(DsmRequestParameters.OverwriteBehaviour.OVERWRITE)
.call();
Assert.assertTrue(client.exists(ROOT_FOLDER+"/"+fileToDownload.getName()));
Assert.assertTrue(client.exists(ROOT_FOLDER+"/"+fileToDownload2.getName()));
Response<DsmDeleteResponse> deleteResponse = client.advancedDelete()
.addFileToDelete(ROOT_FOLDER+"/"+fileToDownload.getName())
.addFileToDelete(ROOT_FOLDER+"/"+fileToDownload2.getName())
.start();
Assert.assertTrue(deleteResponse.isSuccess());
Assert.assertNotNull(deleteResponse.getData());
Assert.assertNotNull(deleteResponse.getData().getTaskid());
Response<DsmDeleteResponse> statusResponse = client.advancedDelete()
.taskId(deleteResponse.getData().getTaskid())
.status();
Assert.assertTrue(statusResponse.isSuccess());
Assert.assertNotNull(statusResponse.getData());
Assert.assertNotNull(statusResponse.getData().getPath());
Assert.assertNotNull(statusResponse.getData().getProcessed_num());
Assert.assertNotNull(statusResponse.getData().getProcessing_path());
Assert.assertNotNull(statusResponse.getData().getTotal());
Assert.assertNotNull(statusResponse.getData().getProgress());
}
@Test
public void deleteFolderAndSuccess() throws IOException {
File fileToUpload = createNewFile();
File fileToUpload2 = createNewFile();
File fileToUpload3 = createNewFile();
client.upload(ROOT_FOLDER+"/folder1", fileToUpload.getAbsolutePath())
.createParentFolders(true)
.overwrite(DsmRequestParameters.OverwriteBehaviour.OVERWRITE)
.call();
client.upload(ROOT_FOLDER+"/folder1", fileToUpload2.getAbsolutePath())
.createParentFolders(true)
.overwrite(DsmRequestParameters.OverwriteBehaviour.OVERWRITE)
.call();
client.upload(ROOT_FOLDER+"/folder1", fileToUpload3.getAbsolutePath())
.createParentFolders(true)
.overwrite(DsmRequestParameters.OverwriteBehaviour.OVERWRITE)
.call();
Assert.assertTrue(client.exists(ROOT_FOLDER+"/folder1/"+fileToUpload.getName()));
Assert.assertTrue(client.exists(ROOT_FOLDER+"/folder1/"+fileToUpload2.getName()));
Assert.assertTrue(client.exists(ROOT_FOLDER+"/folder1/"+fileToUpload3.getName()));
Response<DsmDeleteResponse> deleteResponse = client.advancedDelete()
.addFileToDelete(ROOT_FOLDER+"/folder1")
.start();
Assert.assertTrue(deleteResponse.isSuccess());
Assert.assertNotNull(deleteResponse.getData());
Assert.assertNotNull(deleteResponse.getData().getTaskid());
Response<DsmDeleteResponse> statusResponse = client.advancedDelete()
.taskId(deleteResponse.getData().getTaskid())
.status();
Assert.assertTrue(statusResponse.isSuccess());
Assert.assertNotNull(statusResponse.getData());
Assert.assertNotNull(statusResponse.getData().getPath());
Assert.assertNotNull(statusResponse.getData().getProcessed_num());
Assert.assertNotNull(statusResponse.getData().getProcessing_path());
Assert.assertNotNull(statusResponse.getData().getTotal());
Assert.assertNotNull(statusResponse.getData().getProgress());
}
@Test
public void checkFileExist() {
Assert.assertTrue(client.exists(ROOT_FOLDER+"/"+fileToDownload.getName()));
}
@Test
public void checkFileNotExist() {
Assert.assertFalse(client.exists(ROOT_FOLDER+"/not"+fileToDownload.getName()));
}
private File createNewFile() throws IOException {
String fileSuccess = "dummy-upload-file"+System.currentTimeMillis()+".txt";
String content = "success content";
return Utils.makeFile(folder, content, fileSuccess);
}
}
import clients.DsmFileStationClient;
import exeptions.DsmDirSizeException;
import org.junit.*;
import org.junit.rules.TemporaryFolder;
import requests.DsmAuth;
import requests.filestation.action.DsmDirSizeRequest;
import responses.Response;
import responses.filestation.action.DsmDirSizeResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class DsmDirSizeTest extends DsmTest{
private final String ROOT_FOLDER = "/homes/testResource";
@Rule
public TemporaryFolder folder= new TemporaryFolder();
public DsmFileStationClient client;
public List<String> fileNames = new ArrayList<>();
@Before
public void initTest() throws IOException {
super.initTest();
client = DsmFileStationClient.login(DsmAuth.fromResource("env.properties"));
for(int i =0; i < 30; i++) {
String fileSuccess = "dummy-upload-file"+System.currentTimeMillis()+".txt";
String content = "success";
File file = Utils.makeFile(folder, content, fileSuccess);
client.upload(ROOT_FOLDER, file.getAbsolutePath())
.createParentFolders(true)
.call();
fileNames.add(fileSuccess);
}
}
@After
public void postTest() {
client.simpleDelete(ROOT_FOLDER).setRecursive(true).call();
}
@Test
public void getMainDirSizeAndSuccess() {
DsmDirSizeRequest dsmDirSizeRequest = client.getSize(ROOT_FOLDER);
Response<DsmDirSizeResponse> dirSizeResponse = dsmDirSizeRequest.start();
Assert.assertNotNull(dirSizeResponse);
Assert.assertTrue(dirSizeResponse.isSuccess());
Assert.assertNotNull(dirSizeResponse.getData());
Assert.assertNotNull(dirSizeResponse.getData().getTaskid());
Assert.assertNull(dirSizeResponse.getData().getNum_dir());
Assert.assertNull(dirSizeResponse.getData().getNum_file());
Assert.assertNull(dirSizeResponse.getData().getTotal_size());
Response<DsmDirSizeResponse> resultResponse;
do {
resultResponse = dsmDirSizeRequest.status(dirSizeResponse.getData().getTaskid());
} while (!resultResponse.getData().isFinished());
Assert.assertNotNull(resultResponse);
Assert.assertTrue(resultResponse.isSuccess());
Assert.assertNotNull(resultResponse.getData());
Assert.assertNotNull(resultResponse.getData().getNum_dir());
Assert.assertNotNull(resultResponse.getData().getNum_file());
Assert.assertNotNull(resultResponse.getData().getTotal_size());
}
@Test
public void getMultipleAndFolderFileSizeAndSuccess() {
DsmDirSizeRequest dsmDirSizeRequest = client.getSize(ROOT_FOLDER+"/"+fileNames.get(0))
.addPath(ROOT_FOLDER)
.addPath(ROOT_FOLDER+"/"+fileNames.get(1));
Response<DsmDirSizeResponse> dirSizeResponse = dsmDirSizeRequest.start();
Assert.assertNotNull(dirSizeResponse);
Assert.assertTrue(dirSizeResponse.isSuccess());
Assert.assertNotNull(dirSizeResponse.getData());
Assert.assertNotNull(dirSizeResponse.getData().getTaskid());
Assert.assertNull(dirSizeResponse.getData().getNum_dir());
Assert.assertNull(dirSizeResponse.getData().getNum_file());
Assert.assertNull(dirSizeResponse.getData().getTotal_size());
Response<DsmDirSizeResponse> resultResponse;
do {
resultResponse = dsmDirSizeRequest.status(dirSizeResponse.getData().getTaskid());
} while (!resultResponse.getData().isFinished());
Assert.assertNotNull(resultResponse);
Assert.assertTrue(resultResponse.isSuccess());
Assert.assertNotNull(resultResponse.getData());
Assert.assertEquals(Long.valueOf(1), resultResponse.getData().getNum_dir());
Assert.assertEquals(Long.valueOf(32), resultResponse.getData().getNum_file());
}
@Test
public void getFileSizeAndSuccess() {
DsmDirSizeRequest dsmDirSizeRequest = client.getSize(ROOT_FOLDER+"/"+fileNames.get(0));
Response<DsmDirSizeResponse> dirSizeResponse = dsmDirSizeRequest.start();
Assert.assertNotNull(dirSizeResponse);
Assert.assertTrue(dirSizeResponse.isSuccess());
Assert.assertNotNull(dirSizeResponse.getData());
Assert.assertNotNull(dirSizeResponse.getData().getTaskid());
Assert.assertNull(dirSizeResponse.getData().getNum_dir());
Assert.assertNull(dirSizeResponse.getData().getNum_file());
Assert.assertNull(dirSizeResponse.getData().getTotal_size());
Response<DsmDirSizeResponse> resultResponse;
do {
resultResponse = dsmDirSizeRequest.status(dirSizeResponse.getData().getTaskid());
} while (!resultResponse.getData().isFinished());
Assert.assertNotNull(resultResponse);
Assert.assertTrue(resultResponse.isSuccess());
Assert.assertNotNull(resultResponse.getData());
Assert.assertEquals(Long.valueOf(0), resultResponse.getData().getNum_dir());
Assert.assertEquals(Long.valueOf(1), resultResponse.getData().getNum_file());
}
@Test
public void stopGetFileSizeAndSuccess() {
DsmDirSizeRequest dsmDirSizeRequest = client.getSize(ROOT_FOLDER+"/"+fileNames.get(0));
Response<DsmDirSizeResponse> dirSizeResponse = dsmDirSizeRequest.start();
Assert.assertNotNull(dirSizeResponse);
Assert.assertTrue(dirSizeResponse.isSuccess());
Assert.assertNotNull(dirSizeResponse.getData());
Assert.assertNotNull(dirSizeResponse.getData().getTaskid());
Assert.assertNull(dirSizeResponse.getData().getNum_dir());
Assert.assertNull(dirSizeResponse.getData().getNum_file());
Assert.assertNull(dirSizeResponse.getData().getTotal_size());
Response<DsmDirSizeResponse> stopResponse = dsmDirSizeRequest.stop(dirSizeResponse.getData().getTaskid());
Assert.assertNotNull(stopResponse);
Assert.assertTrue(stopResponse.isSuccess());
}
@Test(expected = DsmDirSizeException.class)
public void stopWithoutTaskId() {
DsmDirSizeRequest dsmDirSizeRequest = client.getSize(ROOT_FOLDER+"/"+fileNames.get(0));
dsmDirSizeRequest.stop();
}
@Test(expected = DsmDirSizeException.class)
public void statusWithoutTaskId() {
DsmDirSizeRequest dsmDirSizeRequest = client.getSize(ROOT_FOLDER+"/"+fileNames.get(0));
dsmDirSizeRequest.status();
}
}
import clients.DsmFileStationClient;
import exeptions.DsmDownloadException;
import org.junit.*;
import org.junit.rules.TemporaryFolder;
import requests.DsmAuth;
import requests.filestation.DsmRequestParameters;
import responses.Response;
import responses.filestation.transfert.DsmDownloadResponse;
import java.io.File;
import java.io.IOException;
public class DsmDownloadTest extends DsmTest{
private final String ROOT_FOLDER = "/homes/testResource";
private DsmFileStationClient client;
private File fileToDownload;
@Rule
public TemporaryFolder folder= new TemporaryFolder();
@Before
public void initTest() throws IOException {
super.initTest();
String fileSuccess = "dummy-upload-file"+System.currentTimeMillis()+".txt";
String content = "success content";
fileToDownload = Utils.makeFile(folder, content, fileSuccess);
client = DsmFileStationClient.login(DsmAuth.fromResource("env.properties"));
client.upload(ROOT_FOLDER, fileToDownload.getAbsolutePath())
.createParentFolders(true)
.overwrite(DsmRequestParameters.OverwriteBehaviour.OVERWRITE)
.call();
}
@After
public void postTest() {
client.simpleDelete(ROOT_FOLDER).setRecursive(true).call();
}
@Test
public void downloadOneFileAndSuccess() {
Response<DsmDownloadResponse> response = client.download(ROOT_FOLDER+"/"+fileToDownload.getName(), folder.getRoot().getAbsolutePath()).call();
Assert.assertNotNull(response);
Assert.assertTrue(response.isSuccess());
Assert.assertNotNull(response.getData());
Assert.assertNotNull(response.getData().getFile());
Assert.assertTrue(response.getData().getFile().exists());
}
@Test(expected = DsmDownloadException.class)
public void downloadWithoutDestinationPathAndFail() {
client.download(ROOT_FOLDER+"/"+fileToDownload.getName(), null).call();
}
@Test(expected = DsmDownloadException.class)
public void downloadWithoutSourcePathAndFail() {
client.download(null, folder.getRoot().getAbsolutePath()).call();
}
@Test(expected = DsmDownloadException.class)
public void downloadFileDoesNotExistShouldFail() {
client.download(ROOT_FOLDER+"/file55252.txt", folder.getRoot().getAbsolutePath()).call();
}
@Test(expected = DsmDownloadException.class)
public void downloadFileDestinationFolderDoesNotExistShouldFail() {
client.download(ROOT_FOLDER+"/"+fileToDownload.getName(), "Z:\\").call();
}
}
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import clients.DsmFileStationClient;
import exeptions.DsmFavoriteException;
import org.junit.*;
import org.junit.rules.TemporaryFolder;
import org.slf4j.LoggerFactory;
import requests.DsmAuth;
import requests.filestation.DsmRequestParameters;
import responses.Response;
import responses.filestation.DsmSimpleResponse;
import responses.filestation.favorite.DsmListFavoriteResponse;
import java.io.File;
import java.io.IOException;
public class DsmFavoriteTest extends DsmTest{
private final String ROOT_FOLDER = "/homes/testResource";
private DsmFileStationClient client;
private File uploadedFile;
private File uploadedFile2;
private String favorite;
private String favorite2;
@Rule
public TemporaryFolder folder= new TemporaryFolder();
@Before
public void initTest() throws IOException {
super.initTest();
favorite = "favorite"+System.currentTimeMillis();
favorite2 = "favorite"+System.currentTimeMillis();
uploadedFile = createNewFile();
uploadedFile2 = createNewFile();
client = DsmFileStationClient.login(DsmAuth.fromResource("env.properties"));
client.upload(ROOT_FOLDER, uploadedFile.getAbsolutePath())
.createParentFolders(true)
.overwrite(DsmRequestParameters.OverwriteBehaviour.OVERWRITE)
.call();
client.upload(ROOT_FOLDER, uploadedFile2.getAbsolutePath())
.createParentFolders(true)
.overwrite(DsmRequestParameters.OverwriteBehaviour.OVERWRITE)
.call();
}
@After
public void postTest() {
client.simpleDelete(ROOT_FOLDER).setRecursive(true).call();
client.favoriteManager().clear();
}
@Test
public void addFavoriteToFile() {
Response<DsmSimpleResponse> dsmSimpleResponse = client.favoriteManager(ROOT_FOLDER+"/"+uploadedFile.getName(), favorite).add();
Assert.assertNotNull(dsmSimpleResponse);
Assert.assertTrue(dsmSimpleResponse.isSuccess());
Response<DsmListFavoriteResponse> dsmListFavoriteResponse = client.listFavorite()
.addAdditionalInformation(DsmRequestParameters.Additional.OWNER).call();
Assert.assertNotNull(dsmListFavoriteResponse);
Assert.assertTrue(dsmListFavoriteResponse.isSuccess());
Assert.assertNotNull(dsmListFavoriteResponse.getData());
Assert.assertNotNull(dsmListFavoriteResponse.getData().getFavorites());
Assert.assertNotNull(dsmListFavoriteResponse.getData().getFavorites().get(0).getAdditional());
Assert.assertTrue( dsmListFavoriteResponse.getData().getFavorites().stream().anyMatch(f -> f.getName().equals(favorite)));
}
@Test
public void addMultipleFavoritesToFile() {
Response<DsmSimpleResponse> dsmSimpleResponse = client.favoriteManager(ROOT_FOLDER+"/"+uploadedFile.getName(), favorite)
.addPath(ROOT_FOLDER+"/"+uploadedFile2.getName(), favorite2).add();
Assert.assertNotNull(dsmSimpleResponse);
Assert.assertTrue(dsmSimpleResponse.isSuccess());
Response<DsmListFavoriteResponse> dsmListFavoriteResponse = client.listFavorite().call();
Assert.assertNotNull(dsmListFavoriteResponse);
Assert.assertTrue(dsmListFavoriteResponse.isSuccess());
Assert.assertNotNull(dsmListFavoriteResponse.getData());
Assert.assertNotNull(dsmListFavoriteResponse.getData().getFavorites());
Assert.assertTrue(dsmListFavoriteResponse.getData().getFavorites().stream().anyMatch(f -> f.getName().equals(favorite)));
Assert.assertTrue(dsmListFavoriteResponse.getData().getFavorites().stream().anyMatch(favorite -> favorite.getName().equals(favorite2)));
}
@Test
public void deleteFavoriteToFile() {
Response<DsmSimpleResponse> dsmSimpleResponse = client.favoriteManager(ROOT_FOLDER+"/"+uploadedFile.getName(), favorite).add();
Assert.assertNotNull(dsmSimpleResponse);
Assert.assertTrue(dsmSimpleResponse.isSuccess());
Response<DsmSimpleResponse> dsmSimpleResponse2 = client.favoriteManager(ROOT_FOLDER+"/"+uploadedFile.getName(), favorite).delete();
Assert.assertNotNull(dsmSimpleResponse2);
Assert.assertTrue(dsmSimpleResponse2.isSuccess());
Response<DsmListFavoriteResponse> dsmListFavoriteResponse = client.listFavorite()
.addAdditionalInformation(DsmRequestParameters.Additional.OWNER).call();
Assert.assertNotNull(dsmListFavoriteResponse);
Assert.assertTrue(dsmListFavoriteResponse.isSuccess());
Assert.assertNotNull(dsmListFavoriteResponse.getData());
Assert.assertNotNull(dsmListFavoriteResponse.getData().getFavorites());
Assert.assertFalse(dsmListFavoriteResponse.getData().getFavorites().stream().anyMatch(f -> f.getName().equals(favorite)));
}
@Test
public void editFavoriteToFile() {
String favorite3 = "favorite"+System.currentTimeMillis();
Response<DsmSimpleResponse> dsmSimpleResponse = client.favoriteManager(ROOT_FOLDER+"/"+uploadedFile.getName(), favorite).add();
Assert.assertNotNull(dsmSimpleResponse);
Assert.assertTrue(dsmSimpleResponse.isSuccess());
Response<DsmSimpleResponse> dsmSimpleResponse2 = client.favoriteManager(ROOT_FOLDER+"/"+uploadedFile.getName(), favorite3).edit();
Assert.assertNotNull(dsmSimpleResponse2);
Assert.assertTrue(dsmSimpleResponse2.isSuccess());
Response<DsmListFavoriteResponse> dsmListFavoriteResponse = client.listFavorite().call();
Assert.assertNotNull(dsmListFavoriteResponse);
Assert.assertTrue(dsmListFavoriteResponse.isSuccess());
Assert.assertNotNull(dsmListFavoriteResponse.getData());
Assert.assertNotNull(dsmListFavoriteResponse.getData().getFavorites());
Assert.assertTrue(dsmListFavoriteResponse.getData().getFavorites().stream().noneMatch(f -> f.getName().equals(favorite)));
Assert.assertTrue(dsmListFavoriteResponse.getData().getFavorites().stream().anyMatch(f -> f.getName().equals(favorite3)));
}
@Test
public void replaceAllFavoriteToFile() {
String favorite3 = "favorite"+System.currentTimeMillis();
String favorite4 = "favorite2"+System.currentTimeMillis();
Response<DsmSimpleResponse> dsmSimpleResponse = client.favoriteManager(ROOT_FOLDER+"/"+uploadedFile.getName(), favorite)
.addPath(ROOT_FOLDER+"/"+uploadedFile2.getName(), favorite2)
.add();
Assert.assertNotNull(dsmSimpleResponse);
Assert.assertTrue(dsmSimpleResponse.isSuccess());
Response<DsmSimpleResponse> dsmSimpleResponse2 = client.favoriteManager(ROOT_FOLDER+"/"+uploadedFile.getName(), favorite3)
.addPath(ROOT_FOLDER+"/"+uploadedFile2.getName(), favorite4)
.replaceAll();
Assert.assertNotNull(dsmSimpleResponse2);
Assert.assertTrue(dsmSimpleResponse2.isSuccess());
Response<DsmListFavoriteResponse> dsmListFavoriteResponse = client.listFavorite().call();
Assert.assertNotNull(dsmListFavoriteResponse);
Assert.assertTrue(dsmListFavoriteResponse.isSuccess());
Assert.assertNotNull(dsmListFavoriteResponse.getData());
Assert.assertNotNull(dsmListFavoriteResponse.getData().getFavorites());
Assert.assertTrue(dsmListFavoriteResponse.getData().getFavorites().stream().noneMatch(f -> f.getName().equals(favorite)));
Assert.assertTrue(dsmListFavoriteResponse.getData().getFavorites().stream().anyMatch(f -> f.getName().equals(favorite3)));
Assert.assertTrue(dsmListFavoriteResponse.getData().getFavorites().stream().noneMatch(f -> f.getName().equals(favorite2)));
Assert.assertTrue(dsmListFavoriteResponse.getData().getFavorites().stream().anyMatch(f -> f.getName().equals(favorite4)));
}
@Test(expected = DsmFavoriteException.class)
public void editFavoriteToFileWithNoPath() {
Response<DsmSimpleResponse> dsmSimpleResponse = client.favoriteManager(ROOT_FOLDER+"/"+uploadedFile.getName(), favorite)
.addPath(ROOT_FOLDER+"/"+uploadedFile2.getName(), favorite2)
.add();
Assert.assertNotNull(dsmSimpleResponse);
Assert.assertTrue(dsmSimpleResponse.isSuccess());
client.favoriteManager()
.replaceAll();
}
@Test(expected = DsmFavoriteException.class)
public void deleteFavoriteToFileWithNoPath() {
Response<DsmSimpleResponse> dsmSimpleResponse = client.favoriteManager(ROOT_FOLDER+"/"+uploadedFile.getName(), favorite)
.add();
Assert.assertNotNull(dsmSimpleResponse);
Assert.assertTrue(dsmSimpleResponse.isSuccess());
client.favoriteManager()
.delete();
}
private File createNewFile() throws IOException {
String fileSuccess = "dummy-upload-file"+System.currentTimeMillis()+".txt";
String content = "success content";
return Utils.makeFile(folder, content, fileSuccess);
}
}
import clients.DsmFileStationClient;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import requests.DsmAuth;
import requests.filestation.DsmRequestParameters;
import responses.Response;
import responses.filestation.lists.DsmListFolderResponse;
import java.io.IOException;
public class DsmListFolderTest extends DsmTest{
DsmAuth auth;
private static final String ROOT_HOME = "/homes";
private static final String NOT_ROOT_HOME = "/NotExist";
private static final String NOT_ROOT_HOME_ERROR_CODE = "408";
@Before
public void initTest() throws IOException {
super.initTest();
auth = DsmAuth.fromResource("env.properties");
}
@Test
public void testDefaultFolderList() {
DsmFileStationClient client = DsmFileStationClient.login(auth);
Response<DsmListFolderResponse> response = client.ls(ROOT_HOME).call();
Assert.assertNotNull(response);
Assert.assertTrue(response.isSuccess());
Assert.assertNull(response.getError());
Assert.assertNotNull(response.getData());
}
@Test
public void testGetListFoldersSort() {
DsmFileStationClient client = DsmFileStationClient.login(auth);
Response<DsmListFolderResponse> response = client.ls(ROOT_HOME)
.addSort(DsmRequestParameters.Sort.ATIME)
.addSort(DsmRequestParameters.Sort.NAME)
.setSortDirection(DsmRequestParameters.SortDirection.DESC)
.call();
Assert.assertTrue(response.isSuccess());
Assert.assertNotNull(response.getData().getOffset());
Assert.assertNotNull(response.getData().getTotal());
Assert.assertNotNull(response.getData().getFiles());
Assert.assertTrue(response.getData().getFiles().size() !=0 );
Assert.assertNull(response.getData().getFiles().get(0).getAdditional());
}
@Test
public void testGetListFoldersAdditionalInformation() {
DsmFileStationClient client = DsmFileStationClient.login(auth);
Response<DsmListFolderResponse> response = client.ls(ROOT_HOME)
.addAdditionalInfo(DsmRequestParameters.Additional.REAL_PATH)
.addAdditionalInfo(DsmRequestParameters.Additional.OWNER)
.addAdditionalInfo(DsmRequestParameters.Additional.MOUNT_POINT_TYPE)
.addAdditionalInfo(DsmRequestParameters.Additional.PERM)
.addAdditionalInfo(DsmRequestParameters.Additional.TIME)
.addAdditionalInfo(DsmRequestParameters.Additional.TYPE)
.call();
Assert.assertTrue(response.isSuccess());
Assert.assertNotNull(response.getData().getOffset());
Assert.assertNotNull(response.getData().getTotal());
Assert.assertNotNull(response.getData().getFiles());
Assert.assertTrue(response.getData().getFiles().size() !=0 );
Assert.assertTrue(response.getData().getFiles().stream().noneMatch(r -> r.getAdditional().getReal_path() == null));
Assert.assertTrue(response.getData().getFiles().stream().noneMatch(r -> r.getAdditional().getOwner() == null));
Assert.assertTrue(response.getData().getFiles().stream().noneMatch(r -> r.getAdditional().getMount_point_type() == null));
Assert.assertTrue(response.getData().getFiles().stream().noneMatch(r -> r.getAdditional().getPerm() == null));
Assert.assertTrue(response.getData().getFiles().stream().noneMatch(r -> r.getAdditional().getTime() == null));
Assert.assertTrue(response.getData().getFiles().stream().noneMatch(r -> r.getAdditional().getType() == null));
}
@Test
public void testGetListFoldersLimit() {
DsmFileStationClient client = DsmFileStationClient.login(auth);
Response<DsmListFolderResponse> response = client.ls(ROOT_HOME)
.setLimit(2)
.call();
Assert.assertTrue(response.isSuccess());
Assert.assertNotNull(response.getData().getOffset());
Assert.assertNotNull(response.getData().getTotal());
Assert.assertNotNull(response.getData().getFiles());
Assert.assertEquals(2, response.getData().getFiles().size());
}
@Test
public void testGetListFolderRootNotExist() {
DsmFileStationClient client = DsmFileStationClient.login(auth);
Response<DsmListFolderResponse> response = client.ls(NOT_ROOT_HOME).call();
Assert.assertNotNull(response);
Assert.assertFalse(response.isSuccess());
Assert.assertNull(response.getData());
Assert.assertNotNull(response.getError());
Assert.assertEquals(NOT_ROOT_HOME_ERROR_CODE, response.getError().getCode());
}
}
import clients.DsmFileStationClient;
import exeptions.DsmException;
import exeptions.DsmLoginException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import requests.DsmAuth;
import java.io.IOException;
public class DsmLoginTest extends DsmTest{
DsmAuth auth;
@Before
public void initTest() throws IOException {
super.initTest();
auth = DsmAuth.fromResource("env.properties");
}
@Test
public void testLoginFromResourceSuccess() {
DsmFileStationClient client = DsmFileStationClient.login(auth);
Assert.assertNotNull(client);
Assert.assertNotNull(client.getDsmAuth());
}
@Test(expected = DsmLoginException.class)
public void testLoginWithAuthNull() {
DsmFileStationClient.login(null);
}
@Test(expected = DsmLoginException.class)
public void testLoginAuthenticationWrongUserName() {
DsmAuth dsmAuth = auth
.setUserName("username")
.setPassword("password");
DsmFileStationClient.login(dsmAuth);
}
@Test(expected = DsmLoginException.class)
public void testLoginAuthenticationWrongPassword() {
DsmAuth dsmAuth = auth
.setPassword("password");
DsmFileStationClient.login(dsmAuth);
}
@Test(expected = DsmException.class)
public void testLoginAuthenticationWrongPort() {
DsmAuth dsmAuth = auth
.setPort(5444);
DsmFileStationClient.login(dsmAuth);
}
@Test(expected = DsmException.class)
public void testLoginAuthenticationWrongHost() {
DsmAuth dsmAuth = auth
.setHost("host");
DsmFileStationClient.login(dsmAuth);
}
}
import clients.DsmFileStationClient;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import requests.DsmAuth;
import java.io.IOException;
public class DsmLogoutTest extends DsmTest{
DsmAuth auth;
@Before
public void initTest() throws IOException {
super.initTest();
auth = DsmAuth.fromResource("env.properties");
}
@Test
public void logoutAnsSuccess() {
DsmFileStationClient client = DsmFileStationClient.login(auth);
Assert.assertTrue(client.logout());
}
}
import clients.DsmFileStationClient;
import exeptions.DsmRenameException;
import org.junit.*;
import org.junit.rules.TemporaryFolder;
import requests.DsmAuth;
import requests.filestation.DsmRequestParameters;
import responses.Response;
import responses.filestation.action.DsmRenameResponse;
import java.io.File;
import java.io.IOException;
public class DsmRenameTest extends DsmTest{
private final String ROOT_FOLDER = "/homes/testResource";
private DsmFileStationClient client;
private File fileToUpload;
@Rule
public TemporaryFolder folder= new TemporaryFolder();
@Before
public void initTest() throws IOException {
super.initTest();
fileToUpload = createNewFile();
client = DsmFileStationClient.login(DsmAuth.fromResource("env.properties"));
client.upload(ROOT_FOLDER, fileToUpload.getAbsolutePath())
.createParentFolders(true)
.overwrite(DsmRequestParameters.OverwriteBehaviour.OVERWRITE)
.call();
}
@After
public void postTest() {
client.simpleDelete(ROOT_FOLDER).setRecursive(true).call();
}
@Test
public void renameFileAndSuccess() {
String newNameFile = "newNameFile1.txt";
Assert.assertTrue(client.exists(ROOT_FOLDER+"/"+ fileToUpload.getName()));
Response<DsmRenameResponse> renameResponse = client.rename(ROOT_FOLDER+"/"+ fileToUpload.getName(), newNameFile)
.call();
Assert.assertTrue(renameResponse.isSuccess());
Assert.assertNotNull(renameResponse.getData());
Assert.assertNotNull(renameResponse.getData().getFiles());
Assert.assertEquals(1, renameResponse.getData().getFiles().size());
Assert.assertTrue(client.exists(ROOT_FOLDER+"/"+ newNameFile));
}
@Test
public void renameFileWithAdditionalAndSuccess() {
String newNameFile = "newNameFile1.txt";
Assert.assertTrue(client.exists(ROOT_FOLDER+"/"+ fileToUpload.getName()));
Response<DsmRenameResponse> renameResponse = client.rename(ROOT_FOLDER+"/"+ fileToUpload.getName(), newNameFile)
.addAdditionalInfo(DsmRequestParameters.Additional.OWNER)
.addAdditionalInfo(DsmRequestParameters.Additional.REAL_PATH)
.call();
Assert.assertTrue(renameResponse.isSuccess());
Assert.assertNotNull(renameResponse.getData());
Assert.assertNotNull(renameResponse.getData().getFiles());
Assert.assertEquals(1, renameResponse.getData().getFiles().size());
Assert.assertNotNull(renameResponse.getData().getFiles().get(0));
Assert.assertNotNull(renameResponse.getData().getFiles().get(0).getAdditional());
Assert.assertTrue(client.exists(ROOT_FOLDER+"/"+ newNameFile));
}
@Test
public void renameMultipleFilesAndSuccess() throws IOException {
String newNameFile = "newNameFile1.txt";
String newNameFile2 = "newNameFile2.txt";
File file = Utils.makeFile(folder, "success", "dummy-upload-file2.txt");
client.upload(ROOT_FOLDER, file.getAbsolutePath())
.createParentFolders(true)
.overwrite(DsmRequestParameters.OverwriteBehaviour.OVERWRITE)
.call();
Assert.assertTrue(client.exists(ROOT_FOLDER+"/"+ fileToUpload.getName()));
Assert.assertTrue(client.exists(ROOT_FOLDER+"/"+ file.getName()));
Response<DsmRenameResponse> renameResponse = client.rename(ROOT_FOLDER+"/"+ fileToUpload.getName(), newNameFile)
.addFileOrFolderToRename(ROOT_FOLDER+"/"+ file.getName())
.addNewNames(newNameFile2)
.call();
Assert.assertTrue(renameResponse.isSuccess());
Assert.assertNotNull(renameResponse.getData());
Assert.assertNotNull(renameResponse.getData().getFiles());
Assert.assertEquals(2, renameResponse.getData().getFiles().size());
Assert.assertTrue(client.exists(ROOT_FOLDER+"/"+ newNameFile));
Assert.assertTrue(client.exists(ROOT_FOLDER+"/"+ newNameFile2));
}
@Test(expected = DsmRenameException.class)
public void renameMultipleWithNoName() {
String newNameFile = "newNameFile1.txt";
Assert.assertTrue(client.exists(ROOT_FOLDER+"/"+ fileToUpload.getName()));
client.rename(ROOT_FOLDER+"/"+ fileToUpload.getName(), newNameFile)
.addFileOrFolderToRename(ROOT_FOLDER+"/"+ fileToUpload.getName())
.call();
}
private File createNewFile() throws IOException {
String fileSuccess = "dummy-upload-file"+System.currentTimeMillis()+".txt";
String content = "success content";
return Utils.makeFile(folder, content, fileSuccess);
}
}
import clients.DsmFileStationClient;
import org.junit.*;
import org.junit.rules.TemporaryFolder;
import requests.DsmAuth;
import requests.filestation.DsmRequestParameters;
import responses.Response;
import responses.filestation.DsmSimpleResponse;
import responses.filestation.search.DsmSearchResultResponse;
import responses.filestation.search.DsmSearchStartResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class DsmSearchTest extends DsmTest{
private final String ROOT_FOLDER = "/homes/testResource";
@Rule
public TemporaryFolder folder= new TemporaryFolder();
public DsmFileStationClient client;
public List<String> fileNames = new ArrayList<>();
@Before
public void initTest() throws IOException {
super.initTest();
client = DsmFileStationClient.login(DsmAuth.fromResource("env.properties"));
for(int i =0; i < 30; i++) {
String fileSuccess = "dummy-upload-file"+System.currentTimeMillis()+".txt";
String content = "success";
File file = Utils.makeFile(folder, content, fileSuccess);
client.upload(ROOT_FOLDER, file.getAbsolutePath())
.createParentFolders(true)
.call();
fileNames.add(fileSuccess);
}
}
@After
public void postTest() {
client.simpleDelete(ROOT_FOLDER).setRecursive(true).call();
}
@Test
public void searchOneFileAndSuccess(){
Random random = new Random();
String selectedFileName = fileNames.get(random.nextInt(fileNames.size() - 1));
Response<DsmSearchStartResponse> startResponse = client.startSearch(selectedFileName)
.setRootFolderPath(ROOT_FOLDER)
.call();
Assert.assertNotNull(startResponse);
Assert.assertTrue(startResponse.isSuccess());
Assert.assertNotNull(startResponse.getData());
Assert.assertNotNull(startResponse.getData().getTaskid());
Response<DsmSearchResultResponse> resultResponse;
do {
resultResponse = client.getSearchResult(startResponse.getData().getTaskid())
.call();
} while (!resultResponse.getData().isFinished());
Assert.assertNotNull(resultResponse);
Assert.assertTrue(resultResponse.isSuccess());
Assert.assertNotNull(resultResponse.getData());
Assert.assertNotNull(resultResponse.getData().getFiles());
Assert.assertEquals(Integer.valueOf(1), resultResponse.getData().getTotal());
}
@Test
public void searchAllFilesAndSuccess(){
Response<DsmSearchStartResponse> startResponse = client.startSearch("*.txt")
.setRootFolderPath(ROOT_FOLDER)
.call();
Assert.assertNotNull(startResponse);
Assert.assertTrue(startResponse.isSuccess());
Assert.assertNotNull(startResponse.getData());
Assert.assertNotNull(startResponse.getData().getTaskid());
Response<DsmSearchResultResponse> resultResponse;
do {
resultResponse = client.getSearchResult(startResponse.getData().getTaskid())
.call();
} while (!resultResponse.getData().isFinished());
Assert.assertNotNull(resultResponse);
Assert.assertTrue(resultResponse.isSuccess());
Assert.assertNotNull(resultResponse.getData());
Assert.assertNotNull(resultResponse.getData().getFiles());
Assert.assertEquals(Integer.valueOf(30), resultResponse.getData().getTotal());
}
@Test
public void searchFileWithRecursiveAndSuccess(){
Random random = new Random();
String selectedFileName = fileNames.get(random.nextInt(fileNames.size() - 1));
Response<DsmSearchStartResponse> startResponse = client.startSearch(selectedFileName)
.setRootFolderPath(ROOT_FOLDER)
.setFileType(DsmRequestParameters.FileType.FILE)
.setRecursive(true)
.call();
Assert.assertNotNull(startResponse);
Assert.assertTrue(startResponse.isSuccess());
Assert.assertNotNull(startResponse.getData());
Assert.assertNotNull(startResponse.getData().getTaskid());
Response<DsmSearchResultResponse> resultResponse;
do {
resultResponse = client.getSearchResult(startResponse.getData().getTaskid())
.call();
} while (!resultResponse.getData().isFinished());
Assert.assertNotNull(resultResponse);
Assert.assertTrue(resultResponse.isSuccess());
Assert.assertNotNull(resultResponse.getData());
Assert.assertNotNull(resultResponse.getData().getFiles());
Assert.assertEquals(Integer.valueOf(1), resultResponse.getData().getTotal());
}
@Test
public void searchMultipleFoldersAndSuccess(){
Response<DsmSearchStartResponse> startResponse = client.startSearch("")
.setRootFolderPath(ROOT_FOLDER)
.setFileType(DsmRequestParameters.FileType.DIR)
.call();
Assert.assertNotNull(startResponse);
Assert.assertTrue(startResponse.isSuccess());
Assert.assertNotNull(startResponse.getData());
Assert.assertNotNull(startResponse.getData().getTaskid());
Response<DsmSearchResultResponse> resultResponse;
do {
resultResponse = client.getSearchResult(startResponse.getData().getTaskid())
.call();
} while (!resultResponse.getData().isFinished());
Assert.assertNotNull(resultResponse);
Assert.assertTrue(resultResponse.isSuccess());
Assert.assertNotNull(resultResponse.getData());
Assert.assertNotNull(resultResponse.getData().getFiles());
Assert.assertEquals(Integer.valueOf(0), resultResponse.getData().getTotal());
}
@Test
public void searchMultipleFilesWithExtensionAndSuccess(){
Response<DsmSearchStartResponse> startResponse = client.startSearch("")
.setRootFolderPath(ROOT_FOLDER)
.setExtension("txt")
.setFileType(DsmRequestParameters.FileType.FILE)
.call();
Assert.assertNotNull(startResponse);
Assert.assertTrue(startResponse.isSuccess());
Assert.assertNotNull(startResponse.getData());
Assert.assertNotNull(startResponse.getData().getTaskid());
Response<DsmSearchResultResponse> resultResponse;
do {
resultResponse = client.getSearchResult(startResponse.getData().getTaskid())
.call();
} while (!resultResponse.getData().isFinished());
Assert.assertNotNull(resultResponse);
Assert.assertTrue(resultResponse.isSuccess());
Assert.assertNotNull(resultResponse.getData());
Assert.assertNotNull(resultResponse.getData().getFiles());
Assert.assertEquals(Integer.valueOf(30), resultResponse.getData().getTotal());
}
@Test
public void searchOneFileWithAdditionalsAndSuccess(){
Response<DsmSearchStartResponse> startResponse = client.startSearch("")
.setRootFolderPath(ROOT_FOLDER)
.setExtension("txt")
.setFileType(DsmRequestParameters.FileType.FILE)
.call();
Assert.assertNotNull(startResponse);
Assert.assertTrue(startResponse.isSuccess());
Assert.assertNotNull(startResponse.getData());
Assert.assertNotNull(startResponse.getData().getTaskid());
Response<DsmSearchResultResponse> resultResponse;
do {
resultResponse = client.getSearchResult(startResponse.getData().getTaskid())
.addAdditionalInformation(DsmRequestParameters.Additional.OWNER)
.addSorts(DsmRequestParameters.Sort.NAME)
.setLimit(20)
.setOffset(3)
.call();
} while (!resultResponse.getData().isFinished());
Assert.assertNotNull(resultResponse);
Assert.assertTrue(resultResponse.isSuccess());
Assert.assertNotNull(resultResponse.getData());
Assert.assertNotNull(resultResponse.getData().getFiles());
Assert.assertEquals(20, resultResponse.getData().getFiles().size());
Assert.assertEquals( Integer.valueOf(3), resultResponse.getData().getOffset());
Assert.assertNotNull(resultResponse.getData().getFiles().get(0).getAdditional());
}
@Test
public void searchMultipleFilesAnsStopAndSuccess(){
Response<DsmSearchStartResponse> startResponse = client.startSearch("")
.setRootFolderPath(ROOT_FOLDER)
.setExtension("txt")
.setFileType(DsmRequestParameters.FileType.FILE)
.call();
Assert.assertNotNull(startResponse);
Assert.assertTrue(startResponse.isSuccess());
Assert.assertNotNull(startResponse.getData());
Assert.assertNotNull(startResponse.getData().getTaskid());
Response<DsmSimpleResponse> stopResponse= client.stopSearch(startResponse.getData().getTaskid()).call();
Assert.assertNotNull(stopResponse);
Assert.assertTrue(stopResponse.isSuccess());
}
}
import clients.DsmFileStationClient;
import org.junit.*;
import org.junit.rules.TemporaryFolder;
import requests.DsmAuth;
import requests.filestation.DsmRequestParameters;
import responses.Response;
import responses.filestation.DsmResponseFields;
import responses.filestation.DsmSimpleResponse;
import responses.filestation.share.DsmShareCreateResponse;
import responses.filestation.share.DsmShareListResponse;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
public class DsmShareTest extends DsmTest{
private final String ROOT_FOLDER = "/homes/testResource";
private DsmFileStationClient client;
private File fileToDownload;
@Rule
public TemporaryFolder folder= new TemporaryFolder();
@Before
public void initTest() throws IOException {
super.initTest();
fileToDownload = createNewFile();
client = DsmFileStationClient.login(DsmAuth.fromResource("env.properties"));
client.upload(ROOT_FOLDER, fileToDownload.getAbsolutePath())
.createParentFolders(true)
.overwrite(DsmRequestParameters.OverwriteBehaviour.OVERWRITE)
.call();
}
@After
public void postTest() {
client.simpleDelete(ROOT_FOLDER).setRecursive(true).call();
}
@Test
public void shareOneFileAndSuccess() {
Assert.assertTrue(client.exists(ROOT_FOLDER+"/"+fileToDownload.getName()));
Response<DsmShareCreateResponse> createLinkResponse = client.createShareLink(ROOT_FOLDER+"/"+fileToDownload.getName())
.call();
Assert.assertTrue(createLinkResponse.isSuccess());
Assert.assertNotNull(createLinkResponse.getData());
Assert.assertNotNull(createLinkResponse.getData().getLinks());
Assert.assertNotNull(createLinkResponse.getData().getLinks().get(0));
Assert.assertNotNull(createLinkResponse.getData().getLinks().get(0).getUrl());
Assert.assertNotNull(createLinkResponse.getData().getLinks().get(0).getPath());
Assert.assertNotNull(createLinkResponse.getData().getLinks().get(0).getId());
Assert.assertNotNull(createLinkResponse.getData().getLinks().get(0).getQrcode());
}
@Test
public void shareOneFileWithAvailableDateAndExpireDateAndSuccess() {
Assert.assertTrue(client.exists(ROOT_FOLDER+"/"+fileToDownload.getName()));
Response<DsmShareCreateResponse> createLinkResponse = client.createShareLink(ROOT_FOLDER+"/"+fileToDownload.getName())
.call();
Assert.assertTrue(createLinkResponse.isSuccess());
Assert.assertNotNull(createLinkResponse.getData());
Assert.assertNotNull(createLinkResponse.getData().getLinks());
Assert.assertNotNull(createLinkResponse.getData().getLinks().get(0));
Assert.assertNotNull(createLinkResponse.getData().getLinks().get(0).getUrl());
Assert.assertNotNull(createLinkResponse.getData().getLinks().get(0).getPath());
Assert.assertNotNull(createLinkResponse.getData().getLinks().get(0).getId());
Assert.assertNotNull(createLinkResponse.getData().getLinks().get(0).getQrcode());
Response<DsmShareCreateResponse> editLinkResponse = client.editShareLink(createLinkResponse.getData().getLinks().get(0).getId())
.setDateAvailable(LocalDateTime.now().plusDays(2))
.setDateExpired(LocalDateTime.now().plusDays(3))
.call();
Assert.assertTrue(editLinkResponse.isSuccess());
Response<DsmResponseFields.SharingLink> shareLinkResponse = client.getShareLinkInfo(createLinkResponse.getData().getLinks().get(0).getId());
Assert.assertTrue(shareLinkResponse.isSuccess());
Assert.assertNotNull(shareLinkResponse.getData());
Assert.assertNotNull(shareLinkResponse.getData().getDate_available());
Assert.assertNotNull(shareLinkResponse.getData().getDate_expired());
Assert.assertNotNull(shareLinkResponse.getData().getIsFolder());
Assert.assertNotNull(shareLinkResponse.getData().getLink_owner());
Assert.assertEquals(DsmResponseFields.SharingLink.Status.valid, shareLinkResponse.getData().getStatus());
Assert.assertNotNull(shareLinkResponse.getData().getUrl());
Assert.assertNotNull(shareLinkResponse.getData().getPath());
}
@Test
public void shareOneFileWithPasswordAndSuccess() {
Assert.assertTrue(client.exists(ROOT_FOLDER+"/"+fileToDownload.getName()));
Response<DsmShareCreateResponse> createLinkResponse = client.createShareLink(ROOT_FOLDER+"/"+fileToDownload.getName())
.call();
Assert.assertTrue(createLinkResponse.isSuccess());
Assert.assertNotNull(createLinkResponse.getData());
Assert.assertNotNull(createLinkResponse.getData().getLinks());
Assert.assertNotNull(createLinkResponse.getData().getLinks().get(0));
Assert.assertNotNull(createLinkResponse.getData().getLinks().get(0).getUrl());
Assert.assertNotNull(createLinkResponse.getData().getLinks().get(0).getPath());
Assert.assertNotNull(createLinkResponse.getData().getLinks().get(0).getId());
Assert.assertNotNull(createLinkResponse.getData().getLinks().get(0).getQrcode());
Response<DsmShareCreateResponse> editLinkResponse = client.editShareLink(createLinkResponse.getData().getLinks().get(0).getId())
.setPassword("password")
.call();
Assert.assertTrue(editLinkResponse.isSuccess());
Response<DsmResponseFields.SharingLink> shareLinkResponse = client.getShareLinkInfo(createLinkResponse.getData().getLinks().get(0).getId());
Assert.assertTrue(shareLinkResponse.isSuccess());
Assert.assertNotNull(shareLinkResponse.getData());
Assert.assertNotNull(shareLinkResponse.getData().getIsFolder());
Assert.assertNotNull(shareLinkResponse.getData().getLink_owner());
Assert.assertEquals(DsmResponseFields.SharingLink.Status.valid, shareLinkResponse.getData().getStatus());
Assert.assertNotNull(shareLinkResponse.getData().getUrl());
Assert.assertNotNull(shareLinkResponse.getData().getPath());
}
@Test
public void shareMultipleOneFilesAndSuccess() {
Assert.assertTrue(client.exists(ROOT_FOLDER+"/"+fileToDownload.getName()));
client.createFolder(ROOT_FOLDER,"toBeShared").call();
Response<DsmShareCreateResponse> createLinkResponse = client.createShareLink(ROOT_FOLDER+"/"+fileToDownload.getName())
.addFileOrFolder(ROOT_FOLDER+"/toBeShared")
.call();
Assert.assertTrue(createLinkResponse.isSuccess());
Assert.assertNotNull(createLinkResponse.getData());
Assert.assertNotNull(createLinkResponse.getData().getLinks());
Assert.assertEquals(2, createLinkResponse.getData().getLinks().size());
}
@Test
public void getAllShareLinksAndSuccess() {
Assert.assertTrue(client.exists(ROOT_FOLDER+"/"+fileToDownload.getName()));
client.createFolder(ROOT_FOLDER,"toBeShared").call();
client.createShareLink(ROOT_FOLDER+"/"+fileToDownload.getName())
.addFileOrFolder(ROOT_FOLDER+"/toBeShared")
.call();
Response<DsmShareListResponse> shareListResponseResponse = client.getAllShareLinks().call();
Assert.assertTrue(shareListResponseResponse.isSuccess());
Assert.assertNotNull(shareListResponseResponse.getData());
Assert.assertNotNull(shareListResponseResponse.getData().getLinks());
Assert.assertTrue( shareListResponseResponse.getData().getLinks().size() != 0);
}
@Test
public void getAllShareLinksLimitAndOffsetAndSuccess() {
Assert.assertTrue(client.exists(ROOT_FOLDER+"/"+fileToDownload.getName()));
client.createFolder(ROOT_FOLDER,"toBeShared").call();
client.createFolder(ROOT_FOLDER,"toBeShared2").call();
client.createFolder(ROOT_FOLDER,"toBeShared3").call();
client.createFolder(ROOT_FOLDER,"toBeShared4").call();
client.createFolder(ROOT_FOLDER,"toBeShared5").call();
client.createFolder(ROOT_FOLDER,"toBeShared6").call();
client.createFolder(ROOT_FOLDER,"toBeShared7").call();
client.createFolder(ROOT_FOLDER,"toBeShared8").call();
client.createShareLink(ROOT_FOLDER+"/"+fileToDownload.getName())
.addFileOrFolder(ROOT_FOLDER+"/toBeShared")
.addFileOrFolder(ROOT_FOLDER+"/toBeShared2")
.addFileOrFolder(ROOT_FOLDER+"/toBeShared3")
.addFileOrFolder(ROOT_FOLDER+"/toBeShared4")
.addFileOrFolder(ROOT_FOLDER+"/toBeShared5")
.addFileOrFolder(ROOT_FOLDER+"/toBeShared6")
.addFileOrFolder(ROOT_FOLDER+"/toBeShared7")
.addFileOrFolder(ROOT_FOLDER+"/toBeShared8")
.call();
Response<DsmShareListResponse> shareListResponseResponse = client.getAllShareLinks()
.setLimit(6)
.setOffset(2)
.setForceClean(true)
.addSort(DsmRequestParameters.ShareSort.name)
.setDirection(DsmRequestParameters.SortDirection.ASC)
.call();
Assert.assertTrue(shareListResponseResponse.isSuccess());
Assert.assertNotNull(shareListResponseResponse.getData());
Assert.assertNotNull(shareListResponseResponse.getData().getLinks());
Assert.assertEquals(6, shareListResponseResponse.getData().getLinks().size());
}
@Test
public void deleteShareLinkAndSuccess() {
Assert.assertTrue(client.exists(ROOT_FOLDER+"/"+fileToDownload.getName()));
client.createFolder(ROOT_FOLDER,"toBeShared").call();
Response<DsmShareCreateResponse> createLinkResponse = client.createShareLink(ROOT_FOLDER+"/"+fileToDownload.getName())
.addFileOrFolder(ROOT_FOLDER+"/toBeShared")
.call();
Assert.assertTrue(createLinkResponse.isSuccess());
Assert.assertNotNull(createLinkResponse.getData());
Assert.assertNotNull(createLinkResponse.getData().getLinks());
Assert.assertNotNull(createLinkResponse.getData().getLinks().get(0));
Assert.assertNotNull(createLinkResponse.getData().getLinks().get(0).getId());
Response<DsmSimpleResponse> dsmSimpleResponseResponse = client.deleteShareLink(createLinkResponse.getData().getLinks().get(0).getId());
Assert.assertTrue(dsmSimpleResponseResponse.isSuccess());
Response<DsmResponseFields.SharingLink> shareLinkResponse = client.getShareLinkInfo(createLinkResponse.getData().getLinks().get(0).getId());
Assert.assertTrue(shareLinkResponse.isSuccess());
Assert.assertNull(shareLinkResponse.getData());
}
@Test
public void clearInvalidShareLinkAndSuccess() {
Assert.assertTrue(client.exists(ROOT_FOLDER+"/"+fileToDownload.getName()));
client.createFolder(ROOT_FOLDER,"toBeShared").call();
Response<DsmShareCreateResponse> createLinkResponse = client.createShareLink(ROOT_FOLDER+"/"+fileToDownload.getName())
.addFileOrFolder(ROOT_FOLDER+"/toBeShared")
.call();
Assert.assertTrue(createLinkResponse.isSuccess());
Assert.assertNotNull(createLinkResponse.getData());
Assert.assertNotNull(createLinkResponse.getData().getLinks());
Assert.assertNotNull(createLinkResponse.getData().getLinks().get(0));
Assert.assertNotNull(createLinkResponse.getData().getLinks().get(0).getId());
Response<DsmSimpleResponse> dsmSimpleResponseResponse = client.clearInvalidShareLinks();
Assert.assertTrue(dsmSimpleResponseResponse.isSuccess());
}
private File createNewFile() throws IOException {
String fileSuccess = "dummy-upload-file"+System.currentTimeMillis()+".txt";
String content = "success content";
return Utils.makeFile(folder, content, fileSuccess);
}
}
import clients.DsmFileStationClient;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import requests.DsmAuth;
import requests.filestation.DsmRequestParameters;
import responses.Response;
import responses.filestation.lists.DsmSharedFolderResponse;
import java.io.IOException;
public class DsmSharedFolderTest extends DsmTest{
DsmAuth auth;
@Before
public void initTest() throws IOException {
super.initTest();
auth = DsmAuth.fromResource("env.properties");
}
@Test
public void testGetSharedFoldersAndSuccess() {
DsmFileStationClient client = DsmFileStationClient.login(auth);
Response<DsmSharedFolderResponse> response = client.getAllSharedFolders().call();
Assert.assertTrue(response.isSuccess());
Assert.assertNotNull(response.getData().getOffset());
Assert.assertNotNull(response.getData().getTotal());
Assert.assertNotNull(response.getData().getShares());
Assert.assertTrue(response.getData().getShares().size() !=0 );
Assert.assertNull(response.getData().getShares().get(0).getAdditional());
}
@Test
public void testGetSharedFoldersSort() {
DsmFileStationClient client = DsmFileStationClient.login(auth);
Response<DsmSharedFolderResponse> response = client.getAllSharedFolders()
.addSort(DsmRequestParameters.Sort.ATIME)
.addSort(DsmRequestParameters.Sort.NAME)
.setSortDirection(DsmRequestParameters.SortDirection.DESC)
.call();
Assert.assertTrue(response.isSuccess());
Assert.assertNotNull(response.getData().getOffset());
Assert.assertNotNull(response.getData().getTotal());
Assert.assertNotNull(response.getData().getShares());
Assert.assertTrue(response.getData().getShares().size() !=0 );
Assert.assertNull(response.getData().getShares().get(0).getAdditional());
}
@Test
public void testGetSharedFoldersAdditionalInformation() {
DsmFileStationClient client = DsmFileStationClient.login(auth);
Response<DsmSharedFolderResponse> response = client.getAllSharedFolders()
.addAdditionalInfo(DsmRequestParameters.Additional.REAL_PATH)
.addAdditionalInfo(DsmRequestParameters.Additional.OWNER)
.addAdditionalInfo(DsmRequestParameters.Additional.MOUNT_POINT_TYPE)
.addAdditionalInfo(DsmRequestParameters.Additional.PERM)
.addAdditionalInfo(DsmRequestParameters.Additional.TIME)
.addAdditionalInfo(DsmRequestParameters.Additional.VOLUME_STATUS)
.call();
Assert.assertTrue(response.isSuccess());
Assert.assertNotNull(response.getData().getOffset());
Assert.assertNotNull(response.getData().getTotal());
Assert.assertNotNull(response.getData().getShares());
Assert.assertTrue(response.getData().getShares().size() !=0 );
Assert.assertTrue(response.getData().getShares().stream().noneMatch(r -> r.getAdditional().getReal_path() == null));
Assert.assertTrue(response.getData().getShares().stream().noneMatch(r -> r.getAdditional().getOwner() == null));
Assert.assertTrue(response.getData().getShares().stream().noneMatch(r -> r.getAdditional().getMount_point_type() == null));
Assert.assertTrue(response.getData().getShares().stream().noneMatch(r -> r.getAdditional().getPerm() == null));
Assert.assertTrue(response.getData().getShares().stream().noneMatch(r -> r.getAdditional().getTime() == null));
Assert.assertTrue(response.getData().getShares().stream().noneMatch(r -> r.getAdditional().getVolume_status() == null));
}
@Test
public void testGetSharedFoldersLimit() {
DsmFileStationClient client = DsmFileStationClient.login(auth);
Response<DsmSharedFolderResponse> response = client.getAllSharedFolders()
.setLimit(2)
.call();
Assert.assertTrue(response.isSuccess());
Assert.assertNotNull(response.getData().getOffset());
Assert.assertNotNull(response.getData().getTotal());
Assert.assertNotNull(response.getData().getShares());
Assert.assertEquals(2, response.getData().getShares().size());
}
@Test
public void testGetSharedFoldersOnlyWritable() {
DsmFileStationClient client = DsmFileStationClient.login(auth);
Response<DsmSharedFolderResponse> response = client.getAllSharedFolders()
.setOnlyWritable(true)
.call();
Assert.assertTrue(response.isSuccess());
Assert.assertNotNull(response.getData().getOffset());
Assert.assertNotNull(response.getData().getTotal());
Assert.assertNotNull(response.getData().getShares());
}
}
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
public class DsmTest {
public void initTest() throws IOException {
Logger rootLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
rootLogger.setLevel(Level.INFO);
}
}
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import clients.DsmFileStationClient;
import exeptions.DsmUploadException;
import org.junit.*;
import org.junit.rules.TemporaryFolder;
import org.slf4j.LoggerFactory;
import requests.DsmAuth;
import requests.filestation.DsmRequestParameters;
import responses.Response;
import responses.filestation.lists.DsmListFolderResponse;
import responses.filestation.DsmResponseFields;
import responses.filestation.transfert.DsmUploadResponse;
import utils.DateUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Optional;
public class DsmUploadTest extends DsmTest{
private final String ROOT_FOLDER = "/homes/testResource";
@Rule
public TemporaryFolder folder= new TemporaryFolder();
public DsmFileStationClient client;
@Before
public void initTest() throws IOException {
super.initTest();
client = DsmFileStationClient.login(DsmAuth.fromResource("env.properties"));
}
@After
public void postTest() {
client.simpleDelete(ROOT_FOLDER).setRecursive(true).call();
}
@Test
public void uploadFileSuccess() throws IOException {
String fileSuccess = "dummy-upload-file"+System.currentTimeMillis()+".txt";
String content = "success";
File file = Utils.makeFile(folder, content, fileSuccess);
Response<DsmUploadResponse> response = client.
upload(ROOT_FOLDER, file.getAbsolutePath())
.createParentFolders(true)
.call();
Assert.assertNotNull(response);
Assert.assertTrue(response.isSuccess());
Assert.assertNotNull(response.getData());
}
@Test
public void uploadFileWithNameSuccess() throws IOException {
String fileSuccess = "dummy-upload-file"+System.currentTimeMillis()+".txt";
String content = "success";
File file = Utils.makeFile(folder, content, fileSuccess);
Response<DsmUploadResponse> response = client.
upload(ROOT_FOLDER, file.getAbsolutePath(), fileSuccess + ".renamed")
.createParentFolders(true)
.call();
Assert.assertNotNull(response);
Assert.assertTrue(response.isSuccess());
Assert.assertNotNull(response.getData());
}
@Test
public void uploadFileWithStreamSuccess() throws IOException {
String fileSuccess = "dummy-upload-file"+System.currentTimeMillis()+".txt";
String content = "success";
File file = Utils.makeFile(folder, content, fileSuccess);
InputStream fileStream = new FileInputStream(file);
Response<DsmUploadResponse> response = client.
upload(ROOT_FOLDER, fileStream, fileSuccess)
.createParentFolders(true)
.call();
fileStream.close();
Assert.assertNotNull(response);
Assert.assertTrue(response.isSuccess());
Assert.assertNotNull(response.getData());
}
@Test
public void uploadFileWithOverwriteSuccess() throws IOException {
String fileSuccess = "dummy-upload-file.txt";
String content = "success";
File file = Utils.makeFile(folder, content, fileSuccess);
client.upload(ROOT_FOLDER, file.getAbsolutePath()).
overwrite(DsmRequestParameters.OverwriteBehaviour.OVERWRITE).
call();
Response<DsmUploadResponse> response2 =
client.upload(ROOT_FOLDER, file.getAbsolutePath())
.createParentFolders(true)
.overwrite(DsmRequestParameters.OverwriteBehaviour.OVERWRITE)
.call();
Assert.assertNotNull(response2);
Assert.assertTrue(response2.isSuccess());
Assert.assertNotNull(response2.getData());
}
@Test
public void uploadFileWithCreateFolderIfNotExistSuccess() throws IOException {
String fileSuccess = "dummy-upload-file.txt";
String content = "success";
File file = Utils.makeFile(folder, content, fileSuccess);
Response<DsmUploadResponse> response = client.
upload(ROOT_FOLDER+"/testResources", file.getAbsolutePath()).
createParentFolders(true).
overwrite(DsmRequestParameters.OverwriteBehaviour.OVERWRITE)
.call();
Assert.assertNotNull(response);
Assert.assertTrue(response.isSuccess());
Assert.assertNotNull(response.getData());
}
@Test(expected = DsmUploadException.class)
public void uploadFileWithSourceFileNotExist() {
String fileSuccess = "dummy-upload-file"+System.currentTimeMillis()+".txt";
File file = new File(fileSuccess);
client.upload(ROOT_FOLDER+"/test", file.getAbsolutePath()).call();
}
@Test
public void uploadFileWithDatesShouldSuccess() throws IOException {
String fileSuccess = "dummy-upload-file"+System.currentTimeMillis()+".txt";
String content = "success";
File file = Utils.makeFile(folder, content, fileSuccess);
Response<DsmUploadResponse> response = client.
upload(ROOT_FOLDER, file.getAbsolutePath())
.createParentFolders(true)
.setCreatedTime(LocalDateTime.of(2019,3,5,4,5,6,1))
.setLastModifiedTime(LocalDateTime.of(2020,3,5,4,5,6,1))
.setLastAccessedTime(LocalDateTime.of(2020,9,5,4,5,6,1))
.call();
Assert.assertNotNull(response);
Assert.assertTrue(response.isSuccess());
Assert.assertNotNull(response.getData());
DsmResponseFields.Files dsmFiles = getFile(client, fileSuccess);
Assert.assertEquals(dsmFiles.getAdditional().getTime().getAtime().longValue(), DateUtils.convertLocalDateTimeToUnixTimestamp(LocalDateTime.of(2020,9,5,4,5,6,1)) / 1000);
Assert.assertEquals(dsmFiles.getAdditional().getTime().getCrtime().longValue(), DateUtils.convertLocalDateTimeToUnixTimestamp(LocalDateTime.of(2019,3,5,4,5,6,1)) / 1000);
Assert.assertEquals(dsmFiles.getAdditional().getTime().getMtime().longValue(), DateUtils.convertLocalDateTimeToUnixTimestamp(LocalDateTime.of(2020,3,5,4,5,6,1)) / 1000);
}
private DsmResponseFields.Files getFile(DsmFileStationClient client , String fileName) {
Response<DsmListFolderResponse> listFolderResponseResponse = client.ls(ROOT_FOLDER)
.addAdditionalInfo(DsmRequestParameters.Additional.TIME)
.call();
Assert.assertNotNull(listFolderResponseResponse);
Assert.assertTrue(listFolderResponseResponse.isSuccess());
Assert.assertNotNull(listFolderResponseResponse.getData());
Optional<DsmResponseFields.Files> filesOptional =listFolderResponseResponse.getData().getFiles().stream().filter(f -> f.getName().equals(fileName)).findAny();
Assert.assertTrue(filesOptional.isPresent());
return filesOptional.get();
}
}
import org.junit.rules.TemporaryFolder;
import java.io.*;
import java.util.Collections;
import java.util.List;
public class Utils {
public static void writeToFile(File file, List<String> line) {
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
for(String link : line) {
bw.write(link);
bw.newLine();
}
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
protected static File makeFile(TemporaryFolder folder, List<String> lines, String fileName) throws IOException {
File file = folder.newFile(fileName);
if(file.exists()) {
writeToFile(file, lines);
}
return file;
}
protected static File makeFile(TemporaryFolder folder, String content, String fileName) throws IOException {
File file = folder.newFile(fileName);
if(file.exists()) {
writeToFile(file, Collections.singletonList(content));
}
return file;
}
}
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