diff --git a/other/master-clients/cpp-restsdk/.gitignore b/other/master-clients/cpp-restsdk/.gitignore new file mode 100644 index 000000000..4581ef2ee --- /dev/null +++ b/other/master-clients/cpp-restsdk/.gitignore @@ -0,0 +1,29 @@ +# Compiled Object files +*.slo +*.lo +*.o +*.obj + +# Precompiled Headers +*.gch +*.pch + +# Compiled Dynamic libraries +*.so +*.dylib +*.dll + +# Fortran module files +*.mod +*.smod + +# Compiled Static libraries +*.lai +*.la +*.a +*.lib + +# Executables +*.exe +*.out +*.app diff --git a/other/master-clients/cpp-restsdk/.openapi-generator-ignore b/other/master-clients/cpp-restsdk/.openapi-generator-ignore new file mode 100644 index 000000000..7484ee590 --- /dev/null +++ b/other/master-clients/cpp-restsdk/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/other/master-clients/cpp-restsdk/.openapi-generator/FILES b/other/master-clients/cpp-restsdk/.openapi-generator/FILES new file mode 100644 index 000000000..e8fd97792 --- /dev/null +++ b/other/master-clients/cpp-restsdk/.openapi-generator/FILES @@ -0,0 +1,28 @@ +.gitignore +CMakeLists.txt +Config.cmake.in +README.md +git_push.sh +include/CppRestOpenAPIClient/ApiClient.h +include/CppRestOpenAPIClient/ApiConfiguration.h +include/CppRestOpenAPIClient/ApiException.h +include/CppRestOpenAPIClient/HttpContent.h +include/CppRestOpenAPIClient/IHttpBody.h +include/CppRestOpenAPIClient/JsonBody.h +include/CppRestOpenAPIClient/ModelBase.h +include/CppRestOpenAPIClient/MultipartFormData.h +include/CppRestOpenAPIClient/Object.h +include/CppRestOpenAPIClient/api/DefaultApi.h +include/CppRestOpenAPIClient/model/FileKey.h +include/CppRestOpenAPIClient/model/Location.h +src/ApiClient.cpp +src/ApiConfiguration.cpp +src/ApiException.cpp +src/HttpContent.cpp +src/JsonBody.cpp +src/ModelBase.cpp +src/MultipartFormData.cpp +src/Object.cpp +src/api/DefaultApi.cpp +src/model/FileKey.cpp +src/model/Location.cpp diff --git a/other/master-clients/cpp-restsdk/.openapi-generator/VERSION b/other/master-clients/cpp-restsdk/.openapi-generator/VERSION new file mode 100644 index 000000000..c0be8a799 --- /dev/null +++ b/other/master-clients/cpp-restsdk/.openapi-generator/VERSION @@ -0,0 +1 @@ +6.4.0 \ No newline at end of file diff --git a/other/master-clients/cpp-restsdk/CMakeLists.txt b/other/master-clients/cpp-restsdk/CMakeLists.txt new file mode 100644 index 000000000..06412ef96 --- /dev/null +++ b/other/master-clients/cpp-restsdk/CMakeLists.txt @@ -0,0 +1,91 @@ +# +# Seaweedfs Master Server API +# The Seaweedfs Master Server API allows you to store blobs +# +# The version of the OpenAPI document: 1.0.0 +# +# https://openapi-generator.tech +# +# NOTE: Auto generated by OpenAPI Generator (https://openapi-generator.tech). + +cmake_minimum_required (VERSION 3.1) + +project(CppRestOpenAPIClient) + +set(CMAKE_POSITION_INDEPENDENT_CODE ON) +set(CXX_STANDARD_REQUIRED ON) + +if(NOT CMAKE_CXX_STANDARD) + set(CMAKE_CXX_STANDARD 14) +endif() + +if(NOT CMAKE_BUILD_TYPE) + set(CMAKE_BUILD_TYPE Release) +endif() + +find_package(cpprestsdk REQUIRED) +find_package(Boost REQUIRED) + +include(GNUInstallDirs) +include(CMakePackageConfigHelpers) + +file(GLOB_RECURSE HEADER_FILES "include/*.h") +file(GLOB_RECURSE SOURCE_FILES "src/*.cpp") + +add_library(${PROJECT_NAME} ${HEADER_FILES} ${SOURCE_FILES}) + +target_compile_options(${PROJECT_NAME} + PRIVATE + $<$,$,$>: + -Wall -Wno-unused-variable> +) + +target_include_directories(${PROJECT_NAME} + PUBLIC + $ + $ +) + +target_link_directories(${PROJECT_NAME} + PRIVATE + ${Boost_LIBRARY_DIRS} +) + +if (UNIX) + message(STATUS "Building client library for Linux/Unix") + + target_link_libraries(${PROJECT_NAME} PUBLIC cpprest ${Boost_LIBRARIES} crypto) +else() + message(STATUS "Building client library for Windows") + + target_link_libraries(${PROJECT_NAME} PUBLIC cpprestsdk::cpprest ${Boost_LIBRARIES} bcrypt) +endif() + +configure_package_config_file(${CMAKE_CURRENT_SOURCE_DIR}/Config.cmake.in + "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake" + INSTALL_DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}" +) + +install( + TARGETS ${PROJECT_NAME} + EXPORT ${PROJECT_NAME}Targets + LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" + ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" + RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" + INCLUDES DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" +) + +install( + DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/include/${PROJECT_NAME} + DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} +) + +install( + FILES "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake" + DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME} +) + +install( + EXPORT ${PROJECT_NAME}Targets + DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME} +) diff --git a/other/master-clients/cpp-restsdk/Config.cmake.in b/other/master-clients/cpp-restsdk/Config.cmake.in new file mode 100644 index 000000000..9015c2ba5 --- /dev/null +++ b/other/master-clients/cpp-restsdk/Config.cmake.in @@ -0,0 +1,5 @@ +@PACKAGE_INIT@ + +include(${CMAKE_CURRENT_LIST_DIR}/@PROJECT_NAME@Targets.cmake) + +check_required_components("@PROJECT_NAME@") diff --git a/other/master-clients/cpp-restsdk/README.md b/other/master-clients/cpp-restsdk/README.md new file mode 100644 index 000000000..b47a0a274 --- /dev/null +++ b/other/master-clients/cpp-restsdk/README.md @@ -0,0 +1,50 @@ +# C++ API client + +The Seaweedfs Master Server API allows you to store blobs + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [OpenAPI spec](https://openapis.org) from a remote server, you can easily generate an API client. + +- API version: 3.43.0 +- Package version: +- Build package: org.openapitools.codegen.languages.CppRestSdkClientCodegen + +- API namespace: org.openapitools.client.api +- Model namespace: org.openapitools.client.model + +## Installation + +### Prerequisites + +Install [cpprestsdk](https://github.com/Microsoft/cpprestsdk). + +- Windows: `vcpkg install cpprestsdk cpprestsdk:x64-windows boost-uuid boost-uuid:x64-windows` +- Mac: `brew install cpprestsdk` +- Linux: `sudo apt-get install libcpprest-dev` + +### Build + +```sh +cmake -DCPPREST_ROOT=/usr -DCMAKE_CXX_FLAGS="-I/usr/local/opt/openssl/include" -DCMAKE_MODULE_LINKER_FLAGS="-L/usr/local/opt/openssl/lib" +make +``` + +### Build on Windows with Visual Studio (VS2017) + +- Right click on folder containing source code +- Select 'Open in visual studio' +- Once visual studio opens, CMake should show up in top menu bar. +- Select CMake > Build All. + +*Note: If the CMake menu item doesn't show up in Visual Studio, CMake +for Visual Studio must be installed. In this case, open the 'Visual Studio +Installer' application. Select 'modify' Visual Studio 2017. Make sure +'Desktop Development with C++' is installed, and specifically that 'Visual +C++ tools for CMake' is selected in the 'Installation Details' section. + +Also be sure to review the CMakeLists.txt file. Edits are likely required.* + +## Author + + + diff --git a/other/master-clients/cpp-restsdk/git_push.sh b/other/master-clients/cpp-restsdk/git_push.sh new file mode 100644 index 000000000..f53a75d4f --- /dev/null +++ b/other/master-clients/cpp-restsdk/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/other/master-clients/cpp-restsdk/include/CppRestOpenAPIClient/ApiClient.h b/other/master-clients/cpp-restsdk/include/CppRestOpenAPIClient/ApiClient.h new file mode 100644 index 000000000..e6c66d73a --- /dev/null +++ b/other/master-clients/cpp-restsdk/include/CppRestOpenAPIClient/ApiClient.h @@ -0,0 +1,114 @@ +/** + * Seaweedfs Master Server API + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * NOTE: This class is auto generated by OpenAPI-Generator 6.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * ApiClient.h + * + * This is an API client responsible for stating the HTTP calls + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_API_ApiClient_H_ +#define ORG_OPENAPITOOLS_CLIENT_API_ApiClient_H_ + + +#include "CppRestOpenAPIClient/ApiConfiguration.h" +#include "CppRestOpenAPIClient/ApiException.h" +#include "CppRestOpenAPIClient/IHttpBody.h" +#include "CppRestOpenAPIClient/HttpContent.h" + +#if defined (_WIN32) || defined (_WIN64) +#undef U +#endif + +#include +#include + +#include +#include +#include + +namespace org { +namespace openapitools { +namespace client { +namespace api { + +using namespace org::openapitools::client::model; + +class ApiClient +{ +public: + ApiClient( std::shared_ptr configuration = nullptr ); + virtual ~ApiClient(); + + typedef std::function ResponseHandlerType; + + const ResponseHandlerType& getResponseHandler() const; + void setResponseHandler(const ResponseHandlerType& responseHandler); + + std::shared_ptr getConfiguration() const; + void setConfiguration(std::shared_ptr configuration); + + static utility::string_t parameterToString(utility::string_t value); + static utility::string_t parameterToString(int32_t value); + static utility::string_t parameterToString(int64_t value); + static utility::string_t parameterToString(float value); + static utility::string_t parameterToString(double value); + static utility::string_t parameterToString(const utility::datetime &value); + static utility::string_t parameterToString(bool value); + template + static utility::string_t parameterToString(const std::vector& value); + template + static utility::string_t parameterToString(const std::shared_ptr& value); + + pplx::task callApi( + const utility::string_t& path, + const utility::string_t& method, + const std::map& queryParams, + const std::shared_ptr postBody, + const std::map& headerParams, + const std::map& formParams, + const std::map>& fileParams, + const utility::string_t& contentType + ) const; + +protected: + + ResponseHandlerType m_ResponseHandler; + std::shared_ptr m_Configuration; +}; + +template +utility::string_t ApiClient::parameterToString(const std::vector& value) +{ + utility::stringstream_t ss; + + for( size_t i = 0; i < value.size(); i++) + { + if( i > 0) ss << utility::conversions::to_string_t(", "); + ss << ApiClient::parameterToString(value[i]); + } + + return ss.str(); +} + +template +utility::string_t ApiClient::parameterToString(const std::shared_ptr& value) +{ + return parameterToString(*value.get()); +} + + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_API_ApiClient_H_ */ diff --git a/other/master-clients/cpp-restsdk/include/CppRestOpenAPIClient/ApiConfiguration.h b/other/master-clients/cpp-restsdk/include/CppRestOpenAPIClient/ApiConfiguration.h new file mode 100644 index 000000000..02c5a4a0a --- /dev/null +++ b/other/master-clients/cpp-restsdk/include/CppRestOpenAPIClient/ApiConfiguration.h @@ -0,0 +1,66 @@ +/** + * Seaweedfs Master Server API + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * NOTE: This class is auto generated by OpenAPI-Generator 6.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * ApiConfiguration.h + * + * This class represents a single item of a multipart-formdata request. + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_API_ApiConfiguration_H_ +#define ORG_OPENAPITOOLS_CLIENT_API_ApiConfiguration_H_ + + + +#include +#include + +#include + +namespace org { +namespace openapitools { +namespace client { +namespace api { + +class ApiConfiguration +{ +public: + ApiConfiguration(); + virtual ~ApiConfiguration(); + + const web::http::client::http_client_config& getHttpConfig() const; + void setHttpConfig( web::http::client::http_client_config& value ); + + utility::string_t getBaseUrl() const; + void setBaseUrl( const utility::string_t value ); + + utility::string_t getUserAgent() const; + void setUserAgent( const utility::string_t value ); + + std::map& getDefaultHeaders(); + const std::map& getDefaultHeaders() const; + + utility::string_t getApiKey( const utility::string_t& prefix) const; + void setApiKey( const utility::string_t& prefix, const utility::string_t& apiKey ); + +protected: + utility::string_t m_BaseUrl; + std::map m_DefaultHeaders; + std::map m_ApiKeys; + web::http::client::http_client_config m_HttpConfig; + utility::string_t m_UserAgent; +}; + +} +} +} +} +#endif /* ORG_OPENAPITOOLS_CLIENT_API_ApiConfiguration_H_ */ diff --git a/other/master-clients/cpp-restsdk/include/CppRestOpenAPIClient/ApiException.h b/other/master-clients/cpp-restsdk/include/CppRestOpenAPIClient/ApiException.h new file mode 100644 index 000000000..86a28dfd1 --- /dev/null +++ b/other/master-clients/cpp-restsdk/include/CppRestOpenAPIClient/ApiException.h @@ -0,0 +1,60 @@ +/** + * Seaweedfs Master Server API + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * NOTE: This class is auto generated by OpenAPI-Generator 6.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * ApiException.h + * + * This is the exception being thrown in case the api call was not successful + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_API_ApiException_H_ +#define ORG_OPENAPITOOLS_CLIENT_API_ApiException_H_ + + + +#include +#include + +#include +#include + +namespace org { +namespace openapitools { +namespace client { +namespace api { + +class ApiException + : public web::http::http_exception +{ +public: + ApiException( int errorCode + , const utility::string_t& message + , std::shared_ptr content = nullptr ); + ApiException( int errorCode + , const utility::string_t& message + , std::map& headers + , std::shared_ptr content = nullptr ); + virtual ~ApiException(); + + std::map& getHeaders(); + std::shared_ptr getContent() const; + +protected: + std::shared_ptr m_Content; + std::map m_Headers; +}; + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_API_ApiBase_H_ */ diff --git a/other/master-clients/cpp-restsdk/include/CppRestOpenAPIClient/HttpContent.h b/other/master-clients/cpp-restsdk/include/CppRestOpenAPIClient/HttpContent.h new file mode 100644 index 000000000..61398c003 --- /dev/null +++ b/other/master-clients/cpp-restsdk/include/CppRestOpenAPIClient/HttpContent.h @@ -0,0 +1,69 @@ +/** + * Seaweedfs Master Server API + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * NOTE: This class is auto generated by OpenAPI-Generator 6.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * HttpContent.h + * + * This class represents a single item of a multipart-formdata request. + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_HttpContent_H_ +#define ORG_OPENAPITOOLS_CLIENT_MODEL_HttpContent_H_ + + + +#include + +#include + +namespace org { +namespace openapitools { +namespace client { +namespace model { + +class HttpContent +{ +public: + HttpContent(); + virtual ~HttpContent(); + + virtual utility::string_t getContentDisposition() const; + virtual void setContentDisposition( const utility::string_t& value ); + + virtual utility::string_t getName() const; + virtual void setName( const utility::string_t& value ); + + virtual utility::string_t getFileName() const; + virtual void setFileName( const utility::string_t& value ); + + virtual utility::string_t getContentType() const; + virtual void setContentType( const utility::string_t& value ); + + virtual std::shared_ptr getData() const; + virtual void setData( std::shared_ptr value ); + + virtual void writeTo( std::ostream& stream ); + +protected: + // NOTE: no utility::string_t here because those strings can only contain ascii + utility::string_t m_ContentDisposition; + utility::string_t m_Name; + utility::string_t m_FileName; + utility::string_t m_ContentType; + std::shared_ptr m_Data; +}; + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_HttpContent_H_ */ diff --git a/other/master-clients/cpp-restsdk/include/CppRestOpenAPIClient/IHttpBody.h b/other/master-clients/cpp-restsdk/include/CppRestOpenAPIClient/IHttpBody.h new file mode 100644 index 000000000..73444810a --- /dev/null +++ b/other/master-clients/cpp-restsdk/include/CppRestOpenAPIClient/IHttpBody.h @@ -0,0 +1,42 @@ +/** + * Seaweedfs Master Server API + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * NOTE: This class is auto generated by OpenAPI-Generator 6.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * IHttpBody.h + * + * This is the interface for contents that can be sent to a remote HTTP server. + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_IHttpBody_H_ +#define ORG_OPENAPITOOLS_CLIENT_MODEL_IHttpBody_H_ + + +#include + +namespace org { +namespace openapitools { +namespace client { +namespace model { + +class IHttpBody +{ +public: + virtual ~IHttpBody() { } + + virtual void writeTo( std::ostream& stream ) = 0; +}; + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_IHttpBody_H_ */ diff --git a/other/master-clients/cpp-restsdk/include/CppRestOpenAPIClient/JsonBody.h b/other/master-clients/cpp-restsdk/include/CppRestOpenAPIClient/JsonBody.h new file mode 100644 index 000000000..b9ab9cad4 --- /dev/null +++ b/other/master-clients/cpp-restsdk/include/CppRestOpenAPIClient/JsonBody.h @@ -0,0 +1,49 @@ +/** + * Seaweedfs Master Server API + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * NOTE: This class is auto generated by OpenAPI-Generator 6.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * JsonBody.h + * + * This is a JSON http body which can be submitted via http + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_JsonBody_H_ +#define ORG_OPENAPITOOLS_CLIENT_MODEL_JsonBody_H_ + + +#include "CppRestOpenAPIClient/IHttpBody.h" + +#include + +namespace org { +namespace openapitools { +namespace client { +namespace model { + +class JsonBody + : public IHttpBody +{ +public: + JsonBody( const web::json::value& value ); + virtual ~JsonBody(); + + void writeTo( std::ostream& target ) override; + +protected: + web::json::value m_Json; +}; + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_JsonBody_H_ */ diff --git a/other/master-clients/cpp-restsdk/include/CppRestOpenAPIClient/ModelBase.h b/other/master-clients/cpp-restsdk/include/CppRestOpenAPIClient/ModelBase.h new file mode 100644 index 000000000..e1866c784 --- /dev/null +++ b/other/master-clients/cpp-restsdk/include/CppRestOpenAPIClient/ModelBase.h @@ -0,0 +1,342 @@ +/** + * Seaweedfs Master Server API + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * NOTE: This class is auto generated by OpenAPI-Generator 6.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * ModelBase.h + * + * This is the base class for all model classes + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_ModelBase_H_ +#define ORG_OPENAPITOOLS_CLIENT_MODEL_ModelBase_H_ + + + +#include "CppRestOpenAPIClient/HttpContent.h" +#include "CppRestOpenAPIClient/MultipartFormData.h" + +#include +#include + +#include +#include + +namespace org { +namespace openapitools { +namespace client { +namespace model { + +class ModelBase +{ +public: + ModelBase(); + virtual ~ModelBase(); + + virtual void validate() = 0; + + virtual web::json::value toJson() const = 0; + virtual bool fromJson( const web::json::value& json ) = 0; + + virtual void toMultipart( std::shared_ptr multipart, const utility::string_t& namePrefix ) const = 0; + virtual bool fromMultiPart( std::shared_ptr multipart, const utility::string_t& namePrefix ) = 0; + + virtual bool isSet() const; + + static utility::string_t toString( const bool val ); + static utility::string_t toString( const float val ); + static utility::string_t toString( const double val ); + static utility::string_t toString( const int32_t val ); + static utility::string_t toString( const int64_t val ); + static utility::string_t toString( const utility::string_t &val ); + static utility::string_t toString( const utility::datetime &val ); + static utility::string_t toString( const web::json::value &val ); + static utility::string_t toString( const std::shared_ptr& val ); + template + static utility::string_t toString( const std::shared_ptr& val ); + template + static utility::string_t toString( const std::vector & val ); + + static web::json::value toJson( bool val ); + static web::json::value toJson( float val ); + static web::json::value toJson( double val ); + static web::json::value toJson( int32_t val ); + static web::json::value toJson( int64_t val ); + static web::json::value toJson( const utility::string_t& val ); + static web::json::value toJson( const utility::datetime& val ); + static web::json::value toJson( const web::json::value& val ); + static web::json::value toJson( const std::shared_ptr& val ); + template + static web::json::value toJson( const std::shared_ptr& val ); + static web::json::value toJson( const std::shared_ptr& val ); + template + static web::json::value toJson( const std::vector& val ); + template + static web::json::value toJson( const std::map& val ); + + static bool fromString( const utility::string_t& val, bool & ); + static bool fromString( const utility::string_t& val, float & ); + static bool fromString( const utility::string_t& val, double & ); + static bool fromString( const utility::string_t& val, int32_t & ); + static bool fromString( const utility::string_t& val, int64_t & ); + static bool fromString( const utility::string_t& val, utility::string_t & ); + static bool fromString( const utility::string_t& val, utility::datetime & ); + static bool fromString( const utility::string_t& val, web::json::value & ); + static bool fromString( const utility::string_t& val, std::shared_ptr & ); + template + static bool fromString( const utility::string_t& val, std::shared_ptr& ); + static bool fromString( const utility::string_t& val, std::shared_ptr& outVal ); + template + static bool fromString( const utility::string_t& val, std::vector & ); + template + static bool fromString( const utility::string_t& val, std::map & ); + + static bool fromJson( const web::json::value& val, bool & ); + static bool fromJson( const web::json::value& val, float & ); + static bool fromJson( const web::json::value& val, double & ); + static bool fromJson( const web::json::value& val, int32_t & ); + static bool fromJson( const web::json::value& val, int64_t & ); + static bool fromJson( const web::json::value& val, utility::string_t & ); + static bool fromJson( const web::json::value& val, utility::datetime & ); + static bool fromJson( const web::json::value& val, web::json::value & ); + static bool fromJson( const web::json::value& val, std::shared_ptr & ); + template + static bool fromJson( const web::json::value& val, std::shared_ptr& ); + static bool fromJson( const web::json::value& val, std::shared_ptr &outVal ); + template + static bool fromJson( const web::json::value& val, std::vector & ); + template + static bool fromJson( const web::json::value& val, std::map & ); + + + static std::shared_ptr toHttpContent( const utility::string_t& name, bool value, const utility::string_t& contentType = utility::conversions::to_string_t("") ); + static std::shared_ptr toHttpContent( const utility::string_t& name, float value, const utility::string_t& contentType = utility::conversions::to_string_t("") ); + static std::shared_ptr toHttpContent( const utility::string_t& name, double value, const utility::string_t& contentType = utility::conversions::to_string_t("") ); + static std::shared_ptr toHttpContent( const utility::string_t& name, int32_t value, const utility::string_t& contentType = utility::conversions::to_string_t("") ); + static std::shared_ptr toHttpContent( const utility::string_t& name, int64_t value, const utility::string_t& contentType = utility::conversions::to_string_t("") ); + static std::shared_ptr toHttpContent( const utility::string_t& name, const utility::string_t& value, const utility::string_t& contentType = utility::conversions::to_string_t("")); + static std::shared_ptr toHttpContent( const utility::string_t& name, const utility::datetime& value, const utility::string_t& contentType = utility::conversions::to_string_t("")); + static std::shared_ptr toHttpContent( const utility::string_t& name, const web::json::value& value, const utility::string_t& contentType = utility::conversions::to_string_t("application/json") ); + static std::shared_ptr toHttpContent( const utility::string_t& name, const std::shared_ptr& ); + template + static std::shared_ptr toHttpContent( const utility::string_t& name, const std::shared_ptr& , const utility::string_t& contentType = utility::conversions::to_string_t("application/json") ); + static std::shared_ptr toHttpContent(const utility::string_t& name, const std::shared_ptr& value , const utility::string_t& contentType = utility::conversions::to_string_t("application/json") ); + template + static std::shared_ptr toHttpContent( const utility::string_t& name, const std::vector& value, const utility::string_t& contentType = utility::conversions::to_string_t("") ); + template + static std::shared_ptr toHttpContent( const utility::string_t& name, const std::map& value, const utility::string_t& contentType = utility::conversions::to_string_t("") ); + + static bool fromHttpContent( std::shared_ptr val, bool & ); + static bool fromHttpContent( std::shared_ptr val, float & ); + static bool fromHttpContent( std::shared_ptr val, double & ); + static bool fromHttpContent( std::shared_ptr val, int64_t & ); + static bool fromHttpContent( std::shared_ptr val, int32_t & ); + static bool fromHttpContent( std::shared_ptr val, utility::string_t & ); + static bool fromHttpContent( std::shared_ptr val, utility::datetime & ); + static bool fromHttpContent( std::shared_ptr val, web::json::value & ); + static bool fromHttpContent( std::shared_ptr val, std::shared_ptr& ); + template + static bool fromHttpContent( std::shared_ptr val, std::shared_ptr& ); + template + static bool fromHttpContent( std::shared_ptr val, std::vector & ); + template + static bool fromHttpContent( std::shared_ptr val, std::map & ); + + static utility::string_t toBase64( utility::string_t value ); + static utility::string_t toBase64( std::shared_ptr value ); + static std::shared_ptr fromBase64( const utility::string_t& encoded ); +protected: + bool m_IsSet; +}; + +template +utility::string_t ModelBase::toString( const std::shared_ptr& val ) +{ + utility::stringstream_t ss; + if( val != nullptr ) + { + val->toJson().serialize(ss); + } + return utility::string_t(ss.str()); +} +template +utility::string_t ModelBase::toString( const std::vector & val ) +{ + utility::string_t strArray; + for ( const auto &item : val ) + { + strArray.append( toString(item) + "," ); + } + if (val.count() > 0) + { + strArray.pop_back(); + } + return strArray; +} +template +web::json::value ModelBase::toJson( const std::shared_ptr& val ) +{ + web::json::value retVal; + if(val != nullptr) + { + retVal = val->toJson(); + } + return retVal; +} +template +web::json::value ModelBase::toJson( const std::vector& value ) +{ + std::vector ret; + for ( const auto& x : value ) + { + ret.push_back( toJson(x) ); + } + return web::json::value::array(ret); +} +template +web::json::value ModelBase::toJson( const std::map& val ) +{ + web::json::value obj; + for ( const auto &itemkey : val ) + { + obj[itemkey.first] = toJson( itemkey.second ); + } + return obj; +} +template +bool ModelBase::fromString( const utility::string_t& val, std::shared_ptr& outVal ) +{ + bool ok = false; + if(outVal == nullptr) + { + outVal = std::shared_ptr(new T()); + } + if( outVal != nullptr ) + { + ok = outVal->fromJson(web::json::value::parse(val)); + } + return ok; +} +template +bool ModelBase::fromJson( const web::json::value& val, std::shared_ptr &outVal ) +{ + bool ok = false; + if(outVal == nullptr) + { + outVal = std::shared_ptr(new T()); + } + if( outVal != nullptr ) + { + ok = outVal->fromJson(val); + } + return ok; +} +template +bool ModelBase::fromJson( const web::json::value& val, std::vector &outVal ) +{ + bool ok = true; + if (val.is_array()) + { + for (const auto jitem : val.as_array()) + { + T item; + ok &= fromJson(jitem, item); + outVal.push_back(item); + } + } + else + { + ok = false; + } + return ok; +} +template +bool ModelBase::fromJson( const web::json::value& jval, std::map &outVal ) +{ + bool ok = true; + if ( jval.is_object() ) + { + auto obj = jval.as_object(); + for( auto objItr = obj.begin() ; objItr != obj.end() ; objItr++ ) + { + T itemVal; + ok &= fromJson(objItr->second, itemVal); + outVal.insert(std::pair(objItr->first, itemVal)); + } + } + else + { + ok = false; + } + return ok; +} +template +std::shared_ptr ModelBase::toHttpContent(const utility::string_t& name, const std::shared_ptr& value , const utility::string_t& contentType ) +{ + std::shared_ptr content( new HttpContent ); + if (value != nullptr ) + { + content->setName( name ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); + content->setContentType( contentType ); + content->setData( std::shared_ptr( new std::stringstream( utility::conversions::to_utf8string( value->toJson().serialize() ) ) ) ); + } + return content; +} +template +std::shared_ptr ModelBase::toHttpContent( const utility::string_t& name, const std::vector& value, const utility::string_t& contentType ) +{ + web::json::value json_array = ModelBase::toJson(value); + std::shared_ptr content( new HttpContent ); + content->setName( name ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); + content->setContentType( contentType ); + content->setData( std::shared_ptr( new std::stringstream( utility::conversions::to_utf8string(json_array.serialize()) ) ) ); + return content; +} +template +std::shared_ptr ModelBase::toHttpContent( const utility::string_t& name, const std::map& value, const utility::string_t& contentType ) +{ + web::json::value jobj = ModelBase::toJson(value); + std::shared_ptr content( new HttpContent ); + content->setName( name ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); + content->setContentType( contentType ); + content->setData( std::shared_ptr( new std::stringstream( utility::conversions::to_utf8string(jobj.serialize()) ) ) ); + return content; +} +template +bool ModelBase::fromHttpContent( std::shared_ptr val, std::shared_ptr& outVal ) +{ + utility::string_t str; + if(val == nullptr) return false; + if( outVal == nullptr ) + { + outVal = std::shared_ptr(new T()); + } + ModelBase::fromHttpContent(val, str); + return fromString(str, outVal); +} +template +bool ModelBase::fromHttpContent( std::shared_ptr val, std::vector & ) +{ + return true; +} +template +bool ModelBase::fromHttpContent( std::shared_ptr val, std::map & ) +{ + return true; +} +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_ModelBase_H_ */ diff --git a/other/master-clients/cpp-restsdk/include/CppRestOpenAPIClient/MultipartFormData.h b/other/master-clients/cpp-restsdk/include/CppRestOpenAPIClient/MultipartFormData.h new file mode 100644 index 000000000..162203692 --- /dev/null +++ b/other/master-clients/cpp-restsdk/include/CppRestOpenAPIClient/MultipartFormData.h @@ -0,0 +1,61 @@ +/** + * Seaweedfs Master Server API + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * NOTE: This class is auto generated by OpenAPI-Generator 6.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * MultipartFormData.h + * + * This class represents a container for building application/x-multipart-formdata requests. + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_MultipartFormData_H_ +#define ORG_OPENAPITOOLS_CLIENT_MODEL_MultipartFormData_H_ + + +#include "CppRestOpenAPIClient/IHttpBody.h" +#include "CppRestOpenAPIClient/HttpContent.h" + +#include + +#include +#include +#include + +namespace org { +namespace openapitools { +namespace client { +namespace model { + +class MultipartFormData + : public IHttpBody +{ +public: + MultipartFormData(); + MultipartFormData(const utility::string_t& boundary); + virtual ~MultipartFormData(); + + virtual void add( std::shared_ptr content ); + virtual utility::string_t getBoundary(); + virtual std::shared_ptr getContent(const utility::string_t& name) const; + virtual bool hasContent(const utility::string_t& name) const; + virtual void writeTo( std::ostream& target ); + +protected: + std::vector> m_Contents; + utility::string_t m_Boundary; + std::map> m_ContentLookup; +}; + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_MultipartFormData_H_ */ diff --git a/other/master-clients/cpp-restsdk/include/CppRestOpenAPIClient/Object.h b/other/master-clients/cpp-restsdk/include/CppRestOpenAPIClient/Object.h new file mode 100644 index 000000000..f02be728b --- /dev/null +++ b/other/master-clients/cpp-restsdk/include/CppRestOpenAPIClient/Object.h @@ -0,0 +1,62 @@ +/** + * Seaweedfs Master Server API + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * NOTE: This class is auto generated by OpenAPI-Generator 6.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * Object.h + * + * This is the implementation of a JSON object. + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_Object_H_ +#define ORG_OPENAPITOOLS_CLIENT_MODEL_Object_H_ + + +#include "CppRestOpenAPIClient/ModelBase.h" + +#include +#include + +namespace org { +namespace openapitools { +namespace client { +namespace model { + +class Object : public ModelBase +{ +public: + Object(); + virtual ~Object(); + + ///////////////////////////////////////////// + /// ModelBase overrides + void validate() override; + + web::json::value toJson() const override; + bool fromJson(const web::json::value& json) override; + + void toMultipart(std::shared_ptr multipart, const utility::string_t& namePrefix) const override; + bool fromMultiPart(std::shared_ptr multipart, const utility::string_t& namePrefix) override; + + ///////////////////////////////////////////// + /// Object manipulation + web::json::value getValue(const utility::string_t& key) const; + void setValue(const utility::string_t& key, const web::json::value& value); + +private: + web::json::value m_object; +}; + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_Object_H_ */ diff --git a/other/master-clients/cpp-restsdk/include/CppRestOpenAPIClient/api/DefaultApi.h b/other/master-clients/cpp-restsdk/include/CppRestOpenAPIClient/api/DefaultApi.h new file mode 100644 index 000000000..4b53bc889 --- /dev/null +++ b/other/master-clients/cpp-restsdk/include/CppRestOpenAPIClient/api/DefaultApi.h @@ -0,0 +1,103 @@ +/** + * Seaweedfs Master Server API + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * NOTE: This class is auto generated by OpenAPI-Generator 6.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * DefaultApi.h + * + * + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_API_DefaultApi_H_ +#define ORG_OPENAPITOOLS_CLIENT_API_DefaultApi_H_ + + + +#include "CppRestOpenAPIClient/ApiClient.h" + +#include "CppRestOpenAPIClient/model/AnyType.h" +#include "CppRestOpenAPIClient/model/FileKey.h" +#include + +namespace org { +namespace openapitools { +namespace client { +namespace api { + +using namespace org::openapitools::client::model; + + + +class DefaultApi +{ +public: + + explicit DefaultApi( std::shared_ptr apiClient ); + + virtual ~DefaultApi(); + + /// + /// Assign a file key + /// + /// + /// This operation is very cheap. Just increase a number in master server's memory. + /// + /// how many file ids to assign. Use <fid>_1, <fid>_2 for the assigned additional file ids. e.g. 3,01637037d6_1, 3,01637037d6_2 (optional, default to nullptr) + /// required collection name (optional, default to nullptr) + /// preferred data center (optional, default to nullptr) + /// preferred rack (optional, default to nullptr) + /// preferred volume server, e.g. 127.0.0.1:8080 (optional, default to nullptr) + /// If you have disks labelled, this must be supplied to specify the disk type to allocate on. (optional, default to nullptr) + /// replica placement strategy (optional, default to nullptr) + /// file expiration time limit, example: 3m for 3 minutes. units: m-minute, h-hour, d-day, w-week, M-month, y-year (optional, default to nullptr) + /// If no matching volumes, pre-allocate this number of bytes on disk for new volumes. (optional, default to nullptr) + /// Only implemented for windows. Use memory mapped files with specified size for new volumes. (optional, default to nullptr) + /// If no matching volumes, create specified number of new volumes. (optional, default to nullptr) + pplx::task> dirAssign( + boost::optional> count, + boost::optional> collection, + boost::optional> dataCenter, + boost::optional> rack, + boost::optional> dataNode, + boost::optional> disk, + boost::optional> replication, + boost::optional> ttl, + boost::optional> preallocate, + boost::optional> memoryMapMaxSizeMb, + boost::optional> writableVolumeCount + ) const; + /// + /// Lookup volume + /// + /// + /// We would need to find out whether the volumes have moved. + /// + /// volume id (optional, default to nullptr) + /// optionally to speed up the lookup (optional, default to nullptr) + /// If provided, this returns the fileId location and a JWT to update or delete the file. (optional, default to nullptr) + /// works together with \"fileId\", if read=yes, JWT is generated for reads. (optional, default to nullptr) + pplx::task> dirLookup( + boost::optional> volumeId, + boost::optional> collection, + boost::optional> fileId, + boost::optional> read + ) const; + +protected: + std::shared_ptr m_ApiClient; +}; + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_API_DefaultApi_H_ */ + diff --git a/other/master-clients/cpp-restsdk/include/CppRestOpenAPIClient/model/FileKey.h b/other/master-clients/cpp-restsdk/include/CppRestOpenAPIClient/model/FileKey.h new file mode 100644 index 000000000..2751407af --- /dev/null +++ b/other/master-clients/cpp-restsdk/include/CppRestOpenAPIClient/model/FileKey.h @@ -0,0 +1,99 @@ +/** + * Seaweedfs Master Server API + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * NOTE: This class is auto generated by OpenAPI-Generator 6.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * FileKey.h + * + * + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_FileKey_H_ +#define ORG_OPENAPITOOLS_CLIENT_MODEL_FileKey_H_ + + +#include "CppRestOpenAPIClient/ModelBase.h" + +#include "CppRestOpenAPIClient/model/AnyType.h" + +namespace org { +namespace openapitools { +namespace client { +namespace model { + + +/// +/// +/// +class FileKey + : public ModelBase +{ +public: + FileKey(); + virtual ~FileKey(); + + ///////////////////////////////////////////// + /// ModelBase overrides + + void validate() override; + + web::json::value toJson() const override; + bool fromJson(const web::json::value& json) override; + + void toMultipart(std::shared_ptr multipart, const utility::string_t& namePrefix) const override; + bool fromMultiPart(std::shared_ptr multipart, const utility::string_t& namePrefix) override; + + ///////////////////////////////////////////// + /// FileKey members + + /// + /// + /// + std::shared_ptr getCount() const; + bool countIsSet() const; + void unsetCount(); + + void setCount(const std::shared_ptr& value); + + /// + /// + /// + std::shared_ptr getFid() const; + bool fidIsSet() const; + void unsetFid(); + + void setFid(const std::shared_ptr& value); + + /// + /// + /// + std::shared_ptr getUrl() const; + bool urlIsSet() const; + void unsetUrl(); + + void setUrl(const std::shared_ptr& value); + + +protected: + std::shared_ptr m_Count; + bool m_CountIsSet; + std::shared_ptr m_Fid; + bool m_FidIsSet; + std::shared_ptr m_Url; + bool m_UrlIsSet; +}; + + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_FileKey_H_ */ diff --git a/other/master-clients/cpp-restsdk/include/CppRestOpenAPIClient/model/Location.h b/other/master-clients/cpp-restsdk/include/CppRestOpenAPIClient/model/Location.h new file mode 100644 index 000000000..cbbd2b191 --- /dev/null +++ b/other/master-clients/cpp-restsdk/include/CppRestOpenAPIClient/model/Location.h @@ -0,0 +1,88 @@ +/** + * Seaweedfs Master Server API + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * NOTE: This class is auto generated by OpenAPI-Generator 6.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * Location.h + * + * + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_Location_H_ +#define ORG_OPENAPITOOLS_CLIENT_MODEL_Location_H_ + + +#include "CppRestOpenAPIClient/ModelBase.h" + +#include "CppRestOpenAPIClient/model/AnyType.h" + +namespace org { +namespace openapitools { +namespace client { +namespace model { + + +/// +/// +/// +class Location + : public ModelBase +{ +public: + Location(); + virtual ~Location(); + + ///////////////////////////////////////////// + /// ModelBase overrides + + void validate() override; + + web::json::value toJson() const override; + bool fromJson(const web::json::value& json) override; + + void toMultipart(std::shared_ptr multipart, const utility::string_t& namePrefix) const override; + bool fromMultiPart(std::shared_ptr multipart, const utility::string_t& namePrefix) override; + + ///////////////////////////////////////////// + /// Location members + + /// + /// + /// + std::shared_ptr getPublicUrl() const; + bool publicUrlIsSet() const; + void unsetPublicUrl(); + + void setPublicUrl(const std::shared_ptr& value); + + /// + /// + /// + std::shared_ptr getUrl() const; + bool urlIsSet() const; + void unsetUrl(); + + void setUrl(const std::shared_ptr& value); + + +protected: + std::shared_ptr m_PublicUrl; + bool m_PublicUrlIsSet; + std::shared_ptr m_Url; + bool m_UrlIsSet; +}; + + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_Location_H_ */ diff --git a/other/master-clients/cpp-restsdk/src/ApiClient.cpp b/other/master-clients/cpp-restsdk/src/ApiClient.cpp new file mode 100644 index 000000000..be7128ae0 --- /dev/null +++ b/other/master-clients/cpp-restsdk/src/ApiClient.cpp @@ -0,0 +1,208 @@ +/** + * Seaweedfs Master Server API + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * NOTE: This class is auto generated by OpenAPI-Generator 6.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "CppRestOpenAPIClient/ApiClient.h" +#include "CppRestOpenAPIClient/MultipartFormData.h" +#include "CppRestOpenAPIClient/ModelBase.h" + +#include +#include +#include + +template +utility::string_t toString(const T value) +{ + utility::ostringstream_t out; + out << std::setprecision(std::numeric_limits::digits10) << std::fixed << value; + return out.str(); +} + +namespace org { +namespace openapitools { +namespace client { +namespace api { + +using namespace org::openapitools::client::model; + +ApiClient::ApiClient(std::shared_ptr configuration ) + : m_Configuration(configuration) +{ +} +ApiClient::~ApiClient() +{ +} + +const ApiClient::ResponseHandlerType& ApiClient::getResponseHandler() const { + return m_ResponseHandler; +} + +void ApiClient::setResponseHandler(const ResponseHandlerType& responseHandler) { + m_ResponseHandler = responseHandler; +} + +std::shared_ptr ApiClient::getConfiguration() const +{ + return m_Configuration; +} +void ApiClient::setConfiguration(std::shared_ptr configuration) +{ + m_Configuration = configuration; +} + + +utility::string_t ApiClient::parameterToString(utility::string_t value) +{ + return value; +} +utility::string_t ApiClient::parameterToString(int64_t value) +{ + std::stringstream valueAsStringStream; + valueAsStringStream << value; + return utility::conversions::to_string_t(valueAsStringStream.str()); +} +utility::string_t ApiClient::parameterToString(int32_t value) +{ + std::stringstream valueAsStringStream; + valueAsStringStream << value; + return utility::conversions::to_string_t(valueAsStringStream.str()); +} + +utility::string_t ApiClient::parameterToString(float value) +{ + return utility::conversions::to_string_t(toString(value)); +} + +utility::string_t ApiClient::parameterToString(double value) +{ + return utility::conversions::to_string_t(toString(value)); +} + +utility::string_t ApiClient::parameterToString(const utility::datetime &value) +{ + return utility::conversions::to_string_t(value.to_string(utility::datetime::ISO_8601)); +} + +utility::string_t ApiClient::parameterToString(bool value) +{ + std::stringstream valueAsStringStream; + valueAsStringStream << std::boolalpha << value; + return utility::conversions::to_string_t(valueAsStringStream.str()); +} + +pplx::task ApiClient::callApi( + const utility::string_t& path, + const utility::string_t& method, + const std::map& queryParams, + const std::shared_ptr postBody, + const std::map& headerParams, + const std::map& formParams, + const std::map>& fileParams, + const utility::string_t& contentType +) const +{ + if (postBody != nullptr && formParams.size() != 0) + { + throw ApiException(400, utility::conversions::to_string_t("Cannot have body and form params")); + } + + if (postBody != nullptr && fileParams.size() != 0) + { + throw ApiException(400, utility::conversions::to_string_t("Cannot have body and file params")); + } + + if (fileParams.size() > 0 && contentType != utility::conversions::to_string_t("multipart/form-data")) + { + throw ApiException(400, utility::conversions::to_string_t("Operations with file parameters must be called with multipart/form-data")); + } + + web::http::client::http_client client(m_Configuration->getBaseUrl(), m_Configuration->getHttpConfig()); + + web::http::http_request request; + for (const auto& kvp : headerParams) + { + request.headers().add(kvp.first, kvp.second); + } + + if (fileParams.size() > 0) + { + MultipartFormData uploadData; + for (const auto& kvp : formParams) + { + uploadData.add(ModelBase::toHttpContent(kvp.first, kvp.second)); + } + for (const auto& kvp : fileParams) + { + uploadData.add(ModelBase::toHttpContent(kvp.first, kvp.second)); + } + std::stringstream data; + uploadData.writeTo(data); + auto bodyString = data.str(); + const auto length = bodyString.size(); + request.set_body(concurrency::streams::bytestream::open_istream(std::move(bodyString)), length, utility::conversions::to_string_t("multipart/form-data; boundary=") + uploadData.getBoundary()); + } + else + { + if (postBody != nullptr) + { + std::stringstream data; + postBody->writeTo(data); + auto bodyString = data.str(); + const auto length = bodyString.size(); + request.set_body(concurrency::streams::bytestream::open_istream(std::move(bodyString)), length, contentType); + } + else + { + if (contentType == utility::conversions::to_string_t("application/json")) + { + web::json::value body_data = web::json::value::object(); + for (auto& kvp : formParams) + { + body_data[kvp.first] = ModelBase::toJson(kvp.second); + } + if (!formParams.empty()) + { + request.set_body(body_data); + } + } + else + { + web::http::uri_builder formData; + for (const auto& kvp : formParams) + { + formData.append_query(kvp.first, kvp.second); + } + if (!formParams.empty()) + { + request.set_body(formData.query(), utility::conversions::to_string_t("application/x-www-form-urlencoded")); + } + } + } + } + + web::http::uri_builder builder(path); + for (const auto& kvp : queryParams) + { + builder.append_query(kvp.first, kvp.second); + } + request.set_request_uri(builder.to_uri()); + request.set_method(method); + if ( !request.headers().has( web::http::header_names::user_agent ) ) + { + request.headers().add( web::http::header_names::user_agent, m_Configuration->getUserAgent() ); + } + + return client.request(request); +} + +} +} +} +} diff --git a/other/master-clients/cpp-restsdk/src/ApiConfiguration.cpp b/other/master-clients/cpp-restsdk/src/ApiConfiguration.cpp new file mode 100644 index 000000000..af52076d0 --- /dev/null +++ b/other/master-clients/cpp-restsdk/src/ApiConfiguration.cpp @@ -0,0 +1,85 @@ +/** + * Seaweedfs Master Server API + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * NOTE: This class is auto generated by OpenAPI-Generator 6.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "CppRestOpenAPIClient/ApiConfiguration.h" + +namespace org { +namespace openapitools { +namespace client { +namespace api { + +ApiConfiguration::ApiConfiguration() +{ +} + +ApiConfiguration::~ApiConfiguration() +{ +} + +const web::http::client::http_client_config& ApiConfiguration::getHttpConfig() const +{ + return m_HttpConfig; +} + +void ApiConfiguration::setHttpConfig( web::http::client::http_client_config& value ) +{ + m_HttpConfig = value; +} + +utility::string_t ApiConfiguration::getBaseUrl() const +{ + return m_BaseUrl; +} + +void ApiConfiguration::setBaseUrl( const utility::string_t value ) +{ + m_BaseUrl = value; +} + +utility::string_t ApiConfiguration::getUserAgent() const +{ + return m_UserAgent; +} + +void ApiConfiguration::setUserAgent( const utility::string_t value ) +{ + m_UserAgent = value; +} + +std::map& ApiConfiguration::getDefaultHeaders() +{ + return m_DefaultHeaders; +} + +const std::map& ApiConfiguration::getDefaultHeaders() const +{ + return m_DefaultHeaders; +} + +utility::string_t ApiConfiguration::getApiKey( const utility::string_t& prefix) const +{ + auto result = m_ApiKeys.find(prefix); + if( result != m_ApiKeys.end() ) + { + return result->second; + } + return utility::conversions::to_string_t(""); +} + +void ApiConfiguration::setApiKey( const utility::string_t& prefix, const utility::string_t& apiKey ) +{ + m_ApiKeys[prefix] = apiKey; +} + +} +} +} +} diff --git a/other/master-clients/cpp-restsdk/src/ApiException.cpp b/other/master-clients/cpp-restsdk/src/ApiException.cpp new file mode 100644 index 000000000..86a1f13f6 --- /dev/null +++ b/other/master-clients/cpp-restsdk/src/ApiException.cpp @@ -0,0 +1,53 @@ +/** + * Seaweedfs Master Server API + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * NOTE: This class is auto generated by OpenAPI-Generator 6.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "CppRestOpenAPIClient/ApiException.h" + +namespace org { +namespace openapitools { +namespace client { +namespace api { + +ApiException::ApiException( int errorCode + , const utility::string_t& message + , std::shared_ptr content /*= nullptr*/ ) + : web::http::http_exception( errorCode, message ) + , m_Content(content) +{ +} +ApiException::ApiException( int errorCode + , const utility::string_t& message + , std::map& headers + , std::shared_ptr content /*= nullptr*/ ) + : web::http::http_exception( errorCode, message ) + , m_Content(content) + , m_Headers(headers) +{ +} + +ApiException::~ApiException() +{ +} + +std::shared_ptr ApiException::getContent() const +{ + return m_Content; +} + +std::map& ApiException::getHeaders() +{ + return m_Headers; +} + +} +} +} +} diff --git a/other/master-clients/cpp-restsdk/src/HttpContent.cpp b/other/master-clients/cpp-restsdk/src/HttpContent.cpp new file mode 100644 index 000000000..98dcbdf71 --- /dev/null +++ b/other/master-clients/cpp-restsdk/src/HttpContent.cpp @@ -0,0 +1,86 @@ +/** + * Seaweedfs Master Server API + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * NOTE: This class is auto generated by OpenAPI-Generator 6.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "CppRestOpenAPIClient/HttpContent.h" + +namespace org { +namespace openapitools { +namespace client { +namespace model { + +HttpContent::HttpContent() +{ +} + +HttpContent::~HttpContent() +{ +} + +utility::string_t HttpContent::getContentDisposition() const +{ + return m_ContentDisposition; +} + +void HttpContent::setContentDisposition( const utility::string_t & value ) +{ + m_ContentDisposition = value; +} + +utility::string_t HttpContent::getName() const +{ + return m_Name; +} + +void HttpContent::setName( const utility::string_t & value ) +{ + m_Name = value; +} + +utility::string_t HttpContent::getFileName() const +{ + return m_FileName; +} + +void HttpContent::setFileName( const utility::string_t & value ) +{ + m_FileName = value; +} + +utility::string_t HttpContent::getContentType() const +{ + return m_ContentType; +} + +void HttpContent::setContentType( const utility::string_t & value ) +{ + m_ContentType = value; +} + +std::shared_ptr HttpContent::getData() const +{ + return m_Data; +} + +void HttpContent::setData( std::shared_ptr value ) +{ + m_Data = value; +} + +void HttpContent::writeTo( std::ostream& stream ) +{ + m_Data->seekg( 0, m_Data->beg ); + stream << m_Data->rdbuf(); +} + +} +} +} +} diff --git a/other/master-clients/cpp-restsdk/src/JsonBody.cpp b/other/master-clients/cpp-restsdk/src/JsonBody.cpp new file mode 100644 index 000000000..6d8444e01 --- /dev/null +++ b/other/master-clients/cpp-restsdk/src/JsonBody.cpp @@ -0,0 +1,36 @@ +/** + * Seaweedfs Master Server API + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * NOTE: This class is auto generated by OpenAPI-Generator 6.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "CppRestOpenAPIClient/JsonBody.h" + +namespace org { +namespace openapitools { +namespace client { +namespace model { + +JsonBody::JsonBody( const web::json::value& json) + : m_Json(json) +{ +} + +JsonBody::~JsonBody() +{ +} + +void JsonBody::writeTo( std::ostream& target ) +{ + m_Json.serialize(target); +} + +} +} +} +} diff --git a/other/master-clients/cpp-restsdk/src/ModelBase.cpp b/other/master-clients/cpp-restsdk/src/ModelBase.cpp new file mode 100644 index 000000000..1875dd5f7 --- /dev/null +++ b/other/master-clients/cpp-restsdk/src/ModelBase.cpp @@ -0,0 +1,665 @@ +/** + * Seaweedfs Master Server API + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * NOTE: This class is auto generated by OpenAPI-Generator 6.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "CppRestOpenAPIClient/ModelBase.h" + +namespace org { +namespace openapitools { +namespace client { +namespace model { + +ModelBase::ModelBase(): m_IsSet(false) +{ +} +ModelBase::~ModelBase() +{ +} +bool ModelBase::isSet() const +{ + return m_IsSet; +} +utility::string_t ModelBase::toString( const bool val ) +{ + utility::stringstream_t ss; + ss << val; + return utility::string_t(ss.str()); +} +utility::string_t ModelBase::toString( const float val ) +{ + utility::stringstream_t ss; + ss << val; + return utility::string_t(ss.str()); +} +utility::string_t ModelBase::toString( const double val ) +{ + utility::stringstream_t ss; + ss << val; + return utility::string_t(ss.str()); +} +utility::string_t ModelBase::toString( const int32_t val ) +{ + utility::stringstream_t ss; + ss << val; + return utility::string_t(ss.str()); +} +utility::string_t ModelBase::toString( const int64_t val ) +{ + utility::stringstream_t ss; + ss << val; + return utility::string_t(ss.str()); +} +utility::string_t ModelBase::toString (const utility::string_t &val ) +{ + utility::stringstream_t ss; + ss << val; + return utility::string_t(ss.str()); +} +utility::string_t ModelBase::toString( const utility::datetime &val ) +{ + return val.to_string(utility::datetime::ISO_8601); +} +utility::string_t ModelBase::toString( const web::json::value &val ) +{ + return val.serialize(); +} +utility::string_t ModelBase::toString( const std::shared_ptr& val ) +{ + utility::stringstream_t ss; + if( val != nullptr ) + { + ss << val->getData(); + } + return utility::string_t(ss.str()); +} +web::json::value ModelBase::toJson(bool value) +{ + return web::json::value::boolean(value); +} +web::json::value ModelBase::toJson( float value ) +{ + return web::json::value::number(value); +} +web::json::value ModelBase::toJson( double value ) +{ + return web::json::value::number(value); +} +web::json::value ModelBase::toJson( int32_t value ) +{ + return web::json::value::number(value); +} +web::json::value ModelBase::toJson( int64_t value ) +{ + return web::json::value::number(value); +} +web::json::value ModelBase::toJson( const utility::string_t& value ) +{ + return web::json::value::string(value); +} +web::json::value ModelBase::toJson( const utility::datetime& value ) +{ + return web::json::value::string(value.to_string(utility::datetime::ISO_8601)); +} +web::json::value ModelBase::toJson( const web::json::value& value ) +{ + return value; +} +web::json::value ModelBase::toJson( const std::shared_ptr& content ) +{ + web::json::value value; + if(content != nullptr) + { + value[utility::conversions::to_string_t("ContentDisposition")] = ModelBase::toJson(content->getContentDisposition()); + value[utility::conversions::to_string_t("ContentType")] = ModelBase::toJson(content->getContentType()); + value[utility::conversions::to_string_t("FileName")] = ModelBase::toJson(content->getFileName()); + value[utility::conversions::to_string_t("InputStream")] = web::json::value::string( ModelBase::toBase64(content->getData()) ); + } + return value; +} +web::json::value ModelBase::toJson( const std::shared_ptr& val ) +{ + web::json::value retVal; + if(val != nullptr) + { + retVal = toJson(*val); + } + return retVal; +} +bool ModelBase::fromString( const utility::string_t& val, bool &outVal ) +{ + utility::stringstream_t ss(val); + bool success = true; + try + { + ss >> outVal; + } + catch (...) + { + success = false; + } + return success; +} +bool ModelBase::fromString( const utility::string_t& val, float &outVal ) +{ + utility::stringstream_t ss(val); + bool success = true; + try + { + ss >> outVal; + } + catch (...) + { + int64_t intVal = 0; + success = ModelBase::fromString(val, intVal); + if(success) + { + outVal = static_cast(intVal); + } + } + return success; +} +bool ModelBase::fromString( const utility::string_t& val, double &outVal ) +{ + utility::stringstream_t ss(val); + bool success = true; + try + { + ss >> outVal; + } + catch (...) + { + int64_t intVal = 0; + success = ModelBase::fromString(val, intVal); + if(success) + { + outVal = static_cast(intVal); + } + } + return success; +} +bool ModelBase::fromString( const utility::string_t& val, int32_t &outVal ) +{ + utility::stringstream_t ss(val); + bool success = true; + try + { + ss >> outVal; + } + catch (...) + { + success = false; + } + return success; +} +bool ModelBase::fromString( const utility::string_t& val, int64_t &outVal ) +{ + utility::stringstream_t ss(val); + bool success = true; + try + { + ss >> outVal; + } + catch (...) + { + success = false; + } + return success; +} +bool ModelBase::fromString( const utility::string_t& val, utility::string_t &outVal ) +{ + utility::stringstream_t ss(val); + bool success = true; + try + { + ss >> outVal; + } + catch (...) + { + success = false; + } + return success; +} +bool ModelBase::fromString( const utility::string_t& val, utility::datetime &outVal ) +{ + bool success = true; + auto dt = utility::datetime::from_string(val, utility::datetime::ISO_8601); + if( dt.is_initialized() ) + { + outVal = dt; + } + else + { + success = false; + } + return success; +} +bool ModelBase::fromString( const utility::string_t& val, web::json::value &outVal ) +{ + outVal = web::json::value::parse(val); + return !outVal.is_null(); +} +bool ModelBase::fromString( const utility::string_t& val, std::shared_ptr& outVal ) +{ + bool ok = true; + if(outVal == nullptr) + { + outVal = std::shared_ptr(new HttpContent()); + } + if(outVal != nullptr) + { + outVal->setData(std::shared_ptr(new std::stringstream(utility::conversions::to_utf8string(val)))); + } + else + { + ok = false; + } + return ok; +} +bool ModelBase::fromString( const utility::string_t& val, std::shared_ptr& outVal ) +{ + bool ok = false; + if(outVal == nullptr) + { + outVal = std::shared_ptr(new utility::datetime()); + } + if( outVal != nullptr ) + { + ok = fromJson(web::json::value::parse(val), *outVal); + } + return ok; +} +bool ModelBase::fromJson( const web::json::value& val, bool & outVal ) +{ + outVal = !val.is_boolean() ? false : val.as_bool(); + return val.is_boolean(); +} +bool ModelBase::fromJson( const web::json::value& val, float & outVal ) +{ + outVal = (!val.is_double() && !val.is_integer()) ? std::numeric_limits::quiet_NaN(): static_cast(val.as_double()); + return val.is_double() || val.is_integer(); +} +bool ModelBase::fromJson( const web::json::value& val, double & outVal ) +{ + outVal = (!val.is_double() && !val.is_integer()) ? std::numeric_limits::quiet_NaN(): val.as_double(); + return val.is_double() || val.is_integer(); +} +bool ModelBase::fromJson( const web::json::value& val, int32_t & outVal ) +{ + outVal = !val.is_integer() ? std::numeric_limits::quiet_NaN() : val.as_integer(); + return val.is_integer(); +} +bool ModelBase::fromJson( const web::json::value& val, int64_t & outVal ) +{ + outVal = !val.is_number() ? std::numeric_limits::quiet_NaN() : val.as_number().to_int64(); + return val.is_number(); +} +bool ModelBase::fromJson( const web::json::value& val, utility::string_t & outVal ) +{ + outVal = val.is_string() ? val.as_string() : utility::conversions::to_string_t(""); + return val.is_string(); +} +bool ModelBase::fromJson( const web::json::value& val, utility::datetime & outVal ) +{ + outVal = val.is_null() ? utility::datetime::from_string(utility::conversions::to_string_t("NULL"), utility::datetime::ISO_8601) : utility::datetime::from_string(val.as_string(), utility::datetime::ISO_8601); + return outVal.is_initialized(); +} +bool ModelBase::fromJson( const web::json::value& val, web::json::value & outVal ) +{ + outVal = val; + return !val.is_null(); +} +bool ModelBase::fromJson( const web::json::value& val, std::shared_ptr& content ) +{ + bool result = false; + if( content != nullptr) + { + result = true; + if(content == nullptr) + { + content = std::shared_ptr(new HttpContent()); + } + if(val.has_field(utility::conversions::to_string_t("ContentDisposition"))) + { + utility::string_t value; + result = result && ModelBase::fromJson(val.at(utility::conversions::to_string_t("ContentDisposition")), value); + content->setContentDisposition( value ); + } + if(val.has_field(utility::conversions::to_string_t("ContentType"))) + { + utility::string_t value; + result = result && ModelBase::fromJson(val.at(utility::conversions::to_string_t("ContentType")), value); + content->setContentType( value ); + } + if(val.has_field(utility::conversions::to_string_t("FileName"))) + { + utility::string_t value; + result = result && ModelBase::fromJson(val.at(utility::conversions::to_string_t("FileName")), value); + content->setFileName( value ); + } + if(val.has_field(utility::conversions::to_string_t("InputStream"))) + { + utility::string_t value; + result = result && ModelBase::fromJson(val.at(utility::conversions::to_string_t("InputStream")), value); + content->setData( ModelBase::fromBase64( value ) ); + } + } + return result; +} +bool ModelBase::fromJson( const web::json::value& val, std::shared_ptr &outVal ) +{ + bool ok = false; + if(outVal == nullptr) + { + outVal = std::shared_ptr(new utility::datetime()); + } + if( outVal != nullptr ) + { + ok = fromJson(val, *outVal); + } + return ok; +} +std::shared_ptr ModelBase::toHttpContent( const utility::string_t& name, bool value, const utility::string_t& contentType ) +{ + std::shared_ptr content( new HttpContent ); + content->setName( name ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); + content->setContentType( contentType ); + std::stringstream* valueAsStringStream = new std::stringstream(); + (*valueAsStringStream) << value; + content->setData( std::shared_ptr( valueAsStringStream ) ); + return content; +} +std::shared_ptr ModelBase::toHttpContent( const utility::string_t& name, float value, const utility::string_t& contentType ) +{ + std::shared_ptr content( new HttpContent ); + content->setName( name ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); + content->setContentType( contentType ); + std::stringstream* valueAsStringStream = new std::stringstream(); + (*valueAsStringStream) << value; + content->setData( std::shared_ptr( valueAsStringStream ) ); + return content; +} +std::shared_ptr ModelBase::toHttpContent( const utility::string_t& name, double value, const utility::string_t& contentType ) +{ + std::shared_ptr content( new HttpContent ); + content->setName( name ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); + content->setContentType( contentType ); + std::stringstream* valueAsStringStream = new std::stringstream(); + (*valueAsStringStream) << value; + content->setData( std::shared_ptr( valueAsStringStream ) ); + return content; +} +std::shared_ptr ModelBase::toHttpContent( const utility::string_t& name, int32_t value, const utility::string_t& contentType ) +{ + std::shared_ptr content( new HttpContent ); + content->setName( name ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); + content->setContentType( contentType ); + std::stringstream* valueAsStringStream = new std::stringstream(); + (*valueAsStringStream) << value; + content->setData( std::shared_ptr( valueAsStringStream ) ); + return content; +} +std::shared_ptr ModelBase::toHttpContent( const utility::string_t& name, int64_t value, const utility::string_t& contentType ) +{ + std::shared_ptr content( new HttpContent ); + content->setName( name ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); + content->setContentType( contentType ); + std::stringstream* valueAsStringStream = new std::stringstream(); + (*valueAsStringStream) << value; + content->setData( std::shared_ptr( valueAsStringStream) ) ; + return content; +} +std::shared_ptr ModelBase::toHttpContent( const utility::string_t& name, const utility::string_t& value, const utility::string_t& contentType) +{ + std::shared_ptr content(new HttpContent); + content->setName( name ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); + content->setContentType( contentType ); + content->setData( std::shared_ptr( new std::stringstream( utility::conversions::to_utf8string(value) ) ) ); + return content; +} +std::shared_ptr ModelBase::toHttpContent( const utility::string_t& name, const utility::datetime& value, const utility::string_t& contentType ) +{ + std::shared_ptr content( new HttpContent ); + content->setName( name ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); + content->setContentType( contentType ); + content->setData( std::shared_ptr( new std::stringstream( utility::conversions::to_utf8string(value.to_string(utility::datetime::ISO_8601) ) ) ) ); + return content; +} +std::shared_ptr ModelBase::toHttpContent( const utility::string_t& name, const web::json::value& value, const utility::string_t& contentType ) +{ + std::shared_ptr content( new HttpContent ); + content->setName( name ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); + content->setContentType( contentType ); + content->setData( std::shared_ptr( new std::stringstream( utility::conversions::to_utf8string(value.serialize()) ) ) ); + return content; +} +std::shared_ptr ModelBase::toHttpContent( const utility::string_t& name, const std::shared_ptr& value ) +{ + std::shared_ptr content( new HttpContent ); + if( value != nullptr ) + { + content->setName( name ); + content->setContentDisposition( value->getContentDisposition() ); + content->setContentType( value->getContentType() ); + content->setData( value->getData() ); + content->setFileName( value->getFileName() ); + } + return content; +} +std::shared_ptr ModelBase::toHttpContent(const utility::string_t& name, const std::shared_ptr& value , const utility::string_t& contentType ) +{ + std::shared_ptr content( new HttpContent ); + if (value != nullptr ) + { + content->setName( name ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); + content->setContentType( contentType ); + content->setData( std::shared_ptr( new std::stringstream( utility::conversions::to_utf8string( toJson(*value).serialize() ) ) ) ); + } + return content; +} +bool ModelBase::fromHttpContent(std::shared_ptr val, bool & outVal ) +{ + utility::string_t str; + if( val == nullptr ) return false; + ModelBase::fromHttpContent(val, str); + return fromString(str, outVal); +} +bool ModelBase::fromHttpContent(std::shared_ptr val, float & outVal ) +{ + utility::string_t str; + if( val == nullptr ) return false; + ModelBase::fromHttpContent(val, str); + return fromString(str, outVal); +} +bool ModelBase::fromHttpContent(std::shared_ptr val, double & outVal ) +{ + utility::string_t str; + if( val == nullptr ) return false; + ModelBase::fromHttpContent(val, str); + return fromString(str, outVal); +} +bool ModelBase::fromHttpContent(std::shared_ptr val, int32_t & outVal ) +{ + utility::string_t str; + if( val == nullptr ) return false; + ModelBase::fromHttpContent(val, str); + return fromString(str, outVal); +} +bool ModelBase::fromHttpContent(std::shared_ptr val, int64_t & outVal ) +{ + utility::string_t str; + if( val == nullptr ) return false; + ModelBase::fromHttpContent(val, str); + return fromString(str, outVal); +} +bool ModelBase::fromHttpContent(std::shared_ptr val, utility::string_t & outVal ) +{ + if( val == nullptr ) return false; + std::shared_ptr data = val->getData(); + data->seekg( 0, data->beg ); + + std::string str((std::istreambuf_iterator(*data.get())), + std::istreambuf_iterator()); + outVal = utility::conversions::to_string_t(str); + return true; +} +bool ModelBase::fromHttpContent(std::shared_ptr val, utility::datetime & outVal ) +{ + utility::string_t str; + if( val == nullptr ) return false; + ModelBase::fromHttpContent(val, str); + outVal = utility::datetime::from_string(str, utility::datetime::ISO_8601); + return true; +} +bool ModelBase::fromHttpContent(std::shared_ptr val, web::json::value & outVal ) +{ + utility::string_t str; + if( val == nullptr ) return false; + ModelBase::fromHttpContent(val, str); + return fromString(str, outVal); +} +bool ModelBase::fromHttpContent(std::shared_ptr val, std::shared_ptr& outVal ) +{ + utility::string_t str; + if( val == nullptr ) return false; + if( outVal == nullptr ) + { + outVal = std::shared_ptr(new HttpContent()); + } + ModelBase::fromHttpContent(val, str); + return fromString(str, outVal); +} +// base64 encoding/decoding based on : https://en.wikibooks.org/wiki/Algorithm_Implementation/Miscellaneous/Base64#C.2B.2B +const static char Base64Chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +const static char Base64PadChar = '='; +utility::string_t ModelBase::toBase64( utility::string_t value ) +{ + std::shared_ptr source( new std::stringstream( utility::conversions::to_utf8string(value) ) ); + return ModelBase::toBase64(source); +} +utility::string_t ModelBase::toBase64( std::shared_ptr value ) +{ + value->seekg( 0, value->end ); + size_t length = value->tellg(); + value->seekg( 0, value->beg ); + utility::string_t base64; + base64.reserve( ((length / 3) + (length % 3 > 0)) * 4 ); + char read[3] = { 0 }; + uint32_t temp; + for ( size_t idx = 0; idx < length / 3; idx++ ) + { + value->read( read, 3 ); + temp = (read[0]) << 16; + temp += (read[1]) << 8; + temp += (read[2]); + base64.append( 1, Base64Chars[(temp & 0x00FC0000) >> 18] ); + base64.append( 1, Base64Chars[(temp & 0x0003F000) >> 12] ); + base64.append( 1, Base64Chars[(temp & 0x00000FC0) >> 6] ); + base64.append( 1, Base64Chars[(temp & 0x0000003F)] ); + } + switch ( length % 3 ) + { + case 1: + value->read( read, 1 ); + temp = read[0] << 16; + base64.append( 1, Base64Chars[(temp & 0x00FC0000) >> 18] ); + base64.append( 1, Base64Chars[(temp & 0x0003F000) >> 12] ); + base64.append( 2, Base64PadChar ); + break; + case 2: + value->read( read, 2 ); + temp = read[0] << 16; + temp += read[1] << 8; + base64.append( 1, Base64Chars[(temp & 0x00FC0000) >> 18] ); + base64.append( 1, Base64Chars[(temp & 0x0003F000) >> 12] ); + base64.append( 1, Base64Chars[(temp & 0x00000FC0) >> 6] ); + base64.append( 1, Base64PadChar ); + break; + } + return base64; +} +std::shared_ptr ModelBase::fromBase64( const utility::string_t& encoded ) +{ + std::shared_ptr result(new std::stringstream); + + char outBuf[3] = { 0 }; + uint32_t temp = 0; + + utility::string_t::const_iterator cursor = encoded.begin(); + while ( cursor < encoded.end() ) + { + for ( size_t quantumPosition = 0; quantumPosition < 4; quantumPosition++ ) + { + temp <<= 6; + if ( *cursor >= 0x41 && *cursor <= 0x5A ) + { + temp |= *cursor - 0x41; + } + else if ( *cursor >= 0x61 && *cursor <= 0x7A ) + { + temp |= *cursor - 0x47; + } + else if ( *cursor >= 0x30 && *cursor <= 0x39 ) + { + temp |= *cursor + 0x04; + } + else if ( *cursor == 0x2B ) + { + temp |= 0x3E; //change to 0x2D for URL alphabet + } + else if ( *cursor == 0x2F ) + { + temp |= 0x3F; //change to 0x5F for URL alphabet + } + else if ( *cursor == Base64PadChar ) //pad + { + switch ( encoded.end() - cursor ) + { + case 1: //One pad character + outBuf[0] = (temp >> 16) & 0x000000FF; + outBuf[1] = (temp >> 8) & 0x000000FF; + result->write( outBuf, 2 ); + return result; + case 2: //Two pad characters + outBuf[0] = (temp >> 10) & 0x000000FF; + result->write( outBuf, 1 ); + return result; + default: + throw web::json::json_exception( utility::conversions::to_string_t( "Invalid Padding in Base 64!" ).c_str() ); + } + } + else + { + throw web::json::json_exception( utility::conversions::to_string_t( "Non-Valid Character in Base 64!" ).c_str() ); + } + ++cursor; + } + + outBuf[0] = (temp >> 16) & 0x000000FF; + outBuf[1] = (temp >> 8) & 0x000000FF; + outBuf[2] = (temp) & 0x000000FF; + result->write( outBuf, 3 ); + } + + return result; +} + +} +} +} +} diff --git a/other/master-clients/cpp-restsdk/src/MultipartFormData.cpp b/other/master-clients/cpp-restsdk/src/MultipartFormData.cpp new file mode 100644 index 000000000..bb1d50e2d --- /dev/null +++ b/other/master-clients/cpp-restsdk/src/MultipartFormData.cpp @@ -0,0 +1,112 @@ +/** + * Seaweedfs Master Server API + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * NOTE: This class is auto generated by OpenAPI-Generator 6.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "CppRestOpenAPIClient/MultipartFormData.h" +#include "CppRestOpenAPIClient/ModelBase.h" + +#include +#include + +namespace org { +namespace openapitools { +namespace client { +namespace model { + +MultipartFormData::MultipartFormData() +{ + utility::stringstream_t uuidString; + uuidString << boost::uuids::random_generator()(); + m_Boundary = uuidString.str(); +} + +MultipartFormData::MultipartFormData(const utility::string_t& boundary) + : m_Boundary(boundary) +{ + +} + +MultipartFormData::~MultipartFormData() +{ +} + +utility::string_t MultipartFormData::getBoundary() +{ + return m_Boundary; +} + +void MultipartFormData::add( std::shared_ptr content ) +{ + m_Contents.push_back( content ); + m_ContentLookup[content->getName()] = content; +} + +bool MultipartFormData::hasContent(const utility::string_t& name) const +{ + return m_ContentLookup.find(name) != m_ContentLookup.end(); +} + +std::shared_ptr MultipartFormData::getContent(const utility::string_t& name) const +{ + auto result = m_ContentLookup.find(name); + if(result == m_ContentLookup.end()) + { + return std::shared_ptr(nullptr); + } + return result->second; +} + +void MultipartFormData::writeTo( std::ostream& target ) +{ + for ( size_t i = 0; i < m_Contents.size(); i++ ) + { + std::shared_ptr content = m_Contents[i]; + + // boundary + target << "\r\n" << "--" << utility::conversions::to_utf8string( m_Boundary ) << "\r\n"; + + // headers + target << "Content-Disposition: " << utility::conversions::to_utf8string( content->getContentDisposition() ); + if ( content->getName().size() > 0 ) + { + target << "; name=\"" << utility::conversions::to_utf8string( content->getName() ) << "\""; + } + if ( content->getFileName().size() > 0 ) + { + target << "; filename=\"" << utility::conversions::to_utf8string( content->getFileName() ) << "\""; + } + target << "\r\n"; + + if ( content->getContentType().size() > 0 ) + { + target << "Content-Type: " << utility::conversions::to_utf8string( content->getContentType() ) << "\r\n"; + } + + target << "\r\n"; + + // body + std::shared_ptr data = content->getData(); + + data->seekg( 0, data->end ); + std::vector dataBytes( data->tellg() ); + + data->seekg( 0, data->beg ); + data->read( &dataBytes[0], dataBytes.size() ); + + std::copy( dataBytes.begin(), dataBytes.end(), std::ostreambuf_iterator( target ) ); + } + + target << "\r\n--" << utility::conversions::to_utf8string( m_Boundary ) << "--\r\n"; +} + +} +} +} +} diff --git a/other/master-clients/cpp-restsdk/src/Object.cpp b/other/master-clients/cpp-restsdk/src/Object.cpp new file mode 100644 index 000000000..ce81e0d92 --- /dev/null +++ b/other/master-clients/cpp-restsdk/src/Object.cpp @@ -0,0 +1,91 @@ +/** + * Seaweedfs Master Server API + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * NOTE: This class is auto generated by OpenAPI-Generator 6.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "CppRestOpenAPIClient/Object.h" + +namespace org { +namespace openapitools { +namespace client { +namespace model { + +Object::Object() +{ + m_object = web::json::value::object(); +} + +Object::~Object() +{ +} + +void Object::validate() +{ + +} + +web::json::value Object::toJson() const +{ + return m_object; +} + +bool Object::fromJson(const web::json::value& val) +{ + if (val.is_object()) + { + m_object = val; + m_IsSet = true; + } + return isSet(); +} + +void Object::toMultipart(std::shared_ptr multipart, const utility::string_t& prefix) const +{ + utility::string_t namePrefix = prefix; + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(".")) + { + namePrefix += utility::conversions::to_string_t("."); + } + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("object"), m_object)); +} + +bool Object::fromMultiPart(std::shared_ptr multipart, const utility::string_t& prefix) +{ + utility::string_t namePrefix = prefix; + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(".")) + { + namePrefix += utility::conversions::to_string_t("."); + } + + if( ModelBase::fromHttpContent(multipart->getContent(namePrefix + utility::conversions::to_string_t("object")), m_object ) ) + { + m_IsSet = true; + } + return isSet(); +} + +web::json::value Object::getValue(const utility::string_t& key) const +{ + return m_object.at(key); +} + + +void Object::setValue(const utility::string_t& key, const web::json::value& value) +{ + if( !value.is_null() ) + { + m_object[key] = value; + m_IsSet = true; + } +} + +} +} +} +} diff --git a/other/master-clients/cpp-restsdk/src/api/DefaultApi.cpp b/other/master-clients/cpp-restsdk/src/api/DefaultApi.cpp new file mode 100644 index 000000000..a788d95ac --- /dev/null +++ b/other/master-clients/cpp-restsdk/src/api/DefaultApi.cpp @@ -0,0 +1,347 @@ +/** + * Seaweedfs Master Server API + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * NOTE: This class is auto generated by OpenAPI-Generator 6.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +#include "CppRestOpenAPIClient/api/DefaultApi.h" +#include "CppRestOpenAPIClient/IHttpBody.h" +#include "CppRestOpenAPIClient/JsonBody.h" +#include "CppRestOpenAPIClient/MultipartFormData.h" + +#include + +#include + +namespace org { +namespace openapitools { +namespace client { +namespace api { + +using namespace org::openapitools::client::model; + +DefaultApi::DefaultApi( std::shared_ptr apiClient ) + : m_ApiClient(apiClient) +{ +} + +DefaultApi::~DefaultApi() +{ +} + +pplx::task> DefaultApi::dirAssign(boost::optional> count, boost::optional> collection, boost::optional> dataCenter, boost::optional> rack, boost::optional> dataNode, boost::optional> disk, boost::optional> replication, boost::optional> ttl, boost::optional> preallocate, boost::optional> memoryMapMaxSizeMb, boost::optional> writableVolumeCount) const +{ + + + std::shared_ptr localVarApiConfiguration( m_ApiClient->getConfiguration() ); + utility::string_t localVarPath = utility::conversions::to_string_t("/dir/assign"); + + std::map localVarQueryParams; + std::map localVarHeaderParams( localVarApiConfiguration->getDefaultHeaders() ); + std::map localVarFormParams; + std::map> localVarFileParams; + + std::unordered_set localVarResponseHttpContentTypes; + localVarResponseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); + + utility::string_t localVarResponseHttpContentType; + + // use JSON if possible + if ( localVarResponseHttpContentTypes.size() == 0 ) + { + localVarResponseHttpContentType = utility::conversions::to_string_t("application/json"); + } + // JSON + else if ( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarResponseHttpContentTypes.end() ) + { + localVarResponseHttpContentType = utility::conversions::to_string_t("application/json"); + } + // multipart formdata + else if( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarResponseHttpContentTypes.end() ) + { + localVarResponseHttpContentType = utility::conversions::to_string_t("multipart/form-data"); + } + else + { + throw ApiException(400, utility::conversions::to_string_t("DefaultApi->dirAssign does not produce any supported media type")); + } + + localVarHeaderParams[utility::conversions::to_string_t("Accept")] = localVarResponseHttpContentType; + + std::unordered_set localVarConsumeHttpContentTypes; + + if (count && *count != nullptr) + { + localVarQueryParams[utility::conversions::to_string_t("count")] = ApiClient::parameterToString(*count); + } + if (collection && *collection != nullptr) + { + localVarQueryParams[utility::conversions::to_string_t("collection")] = ApiClient::parameterToString(*collection); + } + if (dataCenter && *dataCenter != nullptr) + { + localVarQueryParams[utility::conversions::to_string_t("dataCenter")] = ApiClient::parameterToString(*dataCenter); + } + if (rack && *rack != nullptr) + { + localVarQueryParams[utility::conversions::to_string_t("rack")] = ApiClient::parameterToString(*rack); + } + if (dataNode && *dataNode != nullptr) + { + localVarQueryParams[utility::conversions::to_string_t("dataNode")] = ApiClient::parameterToString(*dataNode); + } + if (disk && *disk != nullptr) + { + localVarQueryParams[utility::conversions::to_string_t("disk")] = ApiClient::parameterToString(*disk); + } + if (replication && *replication != nullptr) + { + localVarQueryParams[utility::conversions::to_string_t("replication")] = ApiClient::parameterToString(*replication); + } + if (ttl && *ttl != nullptr) + { + localVarQueryParams[utility::conversions::to_string_t("ttl")] = ApiClient::parameterToString(*ttl); + } + if (preallocate && *preallocate != nullptr) + { + localVarQueryParams[utility::conversions::to_string_t("preallocate")] = ApiClient::parameterToString(*preallocate); + } + if (memoryMapMaxSizeMb && *memoryMapMaxSizeMb != nullptr) + { + localVarQueryParams[utility::conversions::to_string_t("memoryMapMaxSizeMb")] = ApiClient::parameterToString(*memoryMapMaxSizeMb); + } + if (writableVolumeCount && *writableVolumeCount != nullptr) + { + localVarQueryParams[utility::conversions::to_string_t("writableVolumeCount")] = ApiClient::parameterToString(*writableVolumeCount); + } + + std::shared_ptr localVarHttpBody; + utility::string_t localVarRequestHttpContentType; + + // use JSON if possible + if ( localVarConsumeHttpContentTypes.size() == 0 || localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarConsumeHttpContentTypes.end() ) + { + localVarRequestHttpContentType = utility::conversions::to_string_t("application/json"); + } + // multipart formdata + else if( localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarConsumeHttpContentTypes.end() ) + { + localVarRequestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); + } + else if (localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/x-www-form-urlencoded")) != localVarConsumeHttpContentTypes.end()) + { + localVarRequestHttpContentType = utility::conversions::to_string_t("application/x-www-form-urlencoded"); + } + else + { + throw ApiException(415, utility::conversions::to_string_t("DefaultApi->dirAssign does not consume any supported media type")); + } + + + return m_ApiClient->callApi(localVarPath, utility::conversions::to_string_t("GET"), localVarQueryParams, localVarHttpBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarRequestHttpContentType) + .then([=](web::http::http_response localVarResponse) + { + if (m_ApiClient->getResponseHandler()) + { + m_ApiClient->getResponseHandler()(localVarResponse.status_code(), localVarResponse.headers()); + } + + // 1xx - informational : OK + // 2xx - successful : OK + // 3xx - redirection : OK + // 4xx - client error : not OK + // 5xx - client error : not OK + if (localVarResponse.status_code() >= 400) + { + throw ApiException(localVarResponse.status_code() + , utility::conversions::to_string_t("error calling dirAssign: ") + localVarResponse.reason_phrase() + , std::make_shared(localVarResponse.extract_utf8string(true).get())); + } + + // check response content type + if(localVarResponse.headers().has(utility::conversions::to_string_t("Content-Type"))) + { + utility::string_t localVarContentType = localVarResponse.headers()[utility::conversions::to_string_t("Content-Type")]; + if( localVarContentType.find(localVarResponseHttpContentType) == std::string::npos ) + { + throw ApiException(500 + , utility::conversions::to_string_t("error calling dirAssign: unexpected response type: ") + localVarContentType + , std::make_shared(localVarResponse.extract_utf8string(true).get())); + } + } + + return localVarResponse.extract_string(); + }) + .then([=](utility::string_t localVarResponse) + { + std::shared_ptr localVarResult(new FileKey()); + + if(localVarResponseHttpContentType == utility::conversions::to_string_t("application/json")) + { + web::json::value localVarJson = web::json::value::parse(localVarResponse); + + ModelBase::fromJson(localVarJson, localVarResult); + } + // else if(localVarResponseHttpContentType == utility::conversions::to_string_t("multipart/form-data")) + // { + // TODO multipart response parsing + // } + else + { + throw ApiException(500 + , utility::conversions::to_string_t("error calling dirAssign: unsupported response type")); + } + + return localVarResult; + }); +} +pplx::task> DefaultApi::dirLookup(boost::optional> volumeId, boost::optional> collection, boost::optional> fileId, boost::optional> read) const +{ + + + std::shared_ptr localVarApiConfiguration( m_ApiClient->getConfiguration() ); + utility::string_t localVarPath = utility::conversions::to_string_t("/dir/lookup"); + + std::map localVarQueryParams; + std::map localVarHeaderParams( localVarApiConfiguration->getDefaultHeaders() ); + std::map localVarFormParams; + std::map> localVarFileParams; + + std::unordered_set localVarResponseHttpContentTypes; + localVarResponseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); + + utility::string_t localVarResponseHttpContentType; + + // use JSON if possible + if ( localVarResponseHttpContentTypes.size() == 0 ) + { + localVarResponseHttpContentType = utility::conversions::to_string_t("application/json"); + } + // JSON + else if ( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarResponseHttpContentTypes.end() ) + { + localVarResponseHttpContentType = utility::conversions::to_string_t("application/json"); + } + // multipart formdata + else if( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarResponseHttpContentTypes.end() ) + { + localVarResponseHttpContentType = utility::conversions::to_string_t("multipart/form-data"); + } + else + { + throw ApiException(400, utility::conversions::to_string_t("DefaultApi->dirLookup does not produce any supported media type")); + } + + localVarHeaderParams[utility::conversions::to_string_t("Accept")] = localVarResponseHttpContentType; + + std::unordered_set localVarConsumeHttpContentTypes; + + if (volumeId && *volumeId != nullptr) + { + localVarQueryParams[utility::conversions::to_string_t("volumeId")] = ApiClient::parameterToString(*volumeId); + } + if (collection && *collection != nullptr) + { + localVarQueryParams[utility::conversions::to_string_t("collection")] = ApiClient::parameterToString(*collection); + } + if (fileId && *fileId != nullptr) + { + localVarQueryParams[utility::conversions::to_string_t("fileId")] = ApiClient::parameterToString(*fileId); + } + if (read && *read != nullptr) + { + localVarQueryParams[utility::conversions::to_string_t("read")] = ApiClient::parameterToString(*read); + } + + std::shared_ptr localVarHttpBody; + utility::string_t localVarRequestHttpContentType; + + // use JSON if possible + if ( localVarConsumeHttpContentTypes.size() == 0 || localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarConsumeHttpContentTypes.end() ) + { + localVarRequestHttpContentType = utility::conversions::to_string_t("application/json"); + } + // multipart formdata + else if( localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarConsumeHttpContentTypes.end() ) + { + localVarRequestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); + } + else if (localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/x-www-form-urlencoded")) != localVarConsumeHttpContentTypes.end()) + { + localVarRequestHttpContentType = utility::conversions::to_string_t("application/x-www-form-urlencoded"); + } + else + { + throw ApiException(415, utility::conversions::to_string_t("DefaultApi->dirLookup does not consume any supported media type")); + } + + + return m_ApiClient->callApi(localVarPath, utility::conversions::to_string_t("GET"), localVarQueryParams, localVarHttpBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarRequestHttpContentType) + .then([=](web::http::http_response localVarResponse) + { + if (m_ApiClient->getResponseHandler()) + { + m_ApiClient->getResponseHandler()(localVarResponse.status_code(), localVarResponse.headers()); + } + + // 1xx - informational : OK + // 2xx - successful : OK + // 3xx - redirection : OK + // 4xx - client error : not OK + // 5xx - client error : not OK + if (localVarResponse.status_code() >= 400) + { + throw ApiException(localVarResponse.status_code() + , utility::conversions::to_string_t("error calling dirLookup: ") + localVarResponse.reason_phrase() + , std::make_shared(localVarResponse.extract_utf8string(true).get())); + } + + // check response content type + if(localVarResponse.headers().has(utility::conversions::to_string_t("Content-Type"))) + { + utility::string_t localVarContentType = localVarResponse.headers()[utility::conversions::to_string_t("Content-Type")]; + if( localVarContentType.find(localVarResponseHttpContentType) == std::string::npos ) + { + throw ApiException(500 + , utility::conversions::to_string_t("error calling dirLookup: unexpected response type: ") + localVarContentType + , std::make_shared(localVarResponse.extract_utf8string(true).get())); + } + } + + return localVarResponse.extract_string(); + }) + .then([=](utility::string_t localVarResponse) + { + std::shared_ptr localVarResult(nullptr); + + if(localVarResponseHttpContentType == utility::conversions::to_string_t("application/json")) + { + web::json::value localVarJson = web::json::value::parse(localVarResponse); + + ModelBase::fromJson(localVarJson, localVarResult); + } + // else if(localVarResponseHttpContentType == utility::conversions::to_string_t("multipart/form-data")) + // { + // TODO multipart response parsing + // } + else + { + throw ApiException(500 + , utility::conversions::to_string_t("error calling dirLookup: unsupported response type")); + } + + return localVarResult; + }); +} + +} +} +} +} + diff --git a/other/master-clients/cpp-restsdk/src/model/FileKey.cpp b/other/master-clients/cpp-restsdk/src/model/FileKey.cpp new file mode 100644 index 000000000..b3929ddd4 --- /dev/null +++ b/other/master-clients/cpp-restsdk/src/model/FileKey.cpp @@ -0,0 +1,213 @@ +/** + * Seaweedfs Master Server API + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * NOTE: This class is auto generated by OpenAPI-Generator 6.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "CppRestOpenAPIClient/model/FileKey.h" + +namespace org { +namespace openapitools { +namespace client { +namespace model { + + + +FileKey::FileKey() +{ + m_CountIsSet = false; + m_FidIsSet = false; + m_UrlIsSet = false; +} + +FileKey::~FileKey() +{ +} + +void FileKey::validate() +{ + // TODO: implement validation +} + +web::json::value FileKey::toJson() const +{ + + web::json::value val = web::json::value::object(); + + if(m_CountIsSet) + { + val[utility::conversions::to_string_t(U("count"))] = ModelBase::toJson(m_Count); + } + if(m_FidIsSet) + { + val[utility::conversions::to_string_t(U("fid"))] = ModelBase::toJson(m_Fid); + } + if(m_UrlIsSet) + { + val[utility::conversions::to_string_t(U("url"))] = ModelBase::toJson(m_Url); + } + + return val; +} + +bool FileKey::fromJson(const web::json::value& val) +{ + bool ok = true; + + if(val.has_field(utility::conversions::to_string_t(U("count")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("count"))); + if(!fieldValue.is_null()) + { + std::shared_ptr refVal_setCount; + ok &= ModelBase::fromJson(fieldValue, refVal_setCount); + setCount(refVal_setCount); + } + } + if(val.has_field(utility::conversions::to_string_t(U("fid")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("fid"))); + if(!fieldValue.is_null()) + { + std::shared_ptr refVal_setFid; + ok &= ModelBase::fromJson(fieldValue, refVal_setFid); + setFid(refVal_setFid); + } + } + if(val.has_field(utility::conversions::to_string_t(U("url")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("url"))); + if(!fieldValue.is_null()) + { + std::shared_ptr refVal_setUrl; + ok &= ModelBase::fromJson(fieldValue, refVal_setUrl); + setUrl(refVal_setUrl); + } + } + return ok; +} + +void FileKey::toMultipart(std::shared_ptr multipart, const utility::string_t& prefix) const +{ + utility::string_t namePrefix = prefix; + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(U("."))) + { + namePrefix += utility::conversions::to_string_t(U(".")); + } + if(m_CountIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("count")), m_Count)); + } + if(m_FidIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("fid")), m_Fid)); + } + if(m_UrlIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("url")), m_Url)); + } +} + +bool FileKey::fromMultiPart(std::shared_ptr multipart, const utility::string_t& prefix) +{ + bool ok = true; + utility::string_t namePrefix = prefix; + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(U("."))) + { + namePrefix += utility::conversions::to_string_t(U(".")); + } + + if(multipart->hasContent(utility::conversions::to_string_t(U("count")))) + { + std::shared_ptr refVal_setCount; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("count"))), refVal_setCount ); + setCount(refVal_setCount); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("fid")))) + { + std::shared_ptr refVal_setFid; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("fid"))), refVal_setFid ); + setFid(refVal_setFid); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("url")))) + { + std::shared_ptr refVal_setUrl; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("url"))), refVal_setUrl ); + setUrl(refVal_setUrl); + } + return ok; +} + +std::shared_ptr FileKey::getCount() const +{ + return m_Count; +} + +void FileKey::setCount(const std::shared_ptr& value) +{ + m_Count = value; + m_CountIsSet = true; +} + +bool FileKey::countIsSet() const +{ + return m_CountIsSet; +} + +void FileKey::unsetCount() +{ + m_CountIsSet = false; +} +std::shared_ptr FileKey::getFid() const +{ + return m_Fid; +} + +void FileKey::setFid(const std::shared_ptr& value) +{ + m_Fid = value; + m_FidIsSet = true; +} + +bool FileKey::fidIsSet() const +{ + return m_FidIsSet; +} + +void FileKey::unsetFid() +{ + m_FidIsSet = false; +} +std::shared_ptr FileKey::getUrl() const +{ + return m_Url; +} + +void FileKey::setUrl(const std::shared_ptr& value) +{ + m_Url = value; + m_UrlIsSet = true; +} + +bool FileKey::urlIsSet() const +{ + return m_UrlIsSet; +} + +void FileKey::unsetUrl() +{ + m_UrlIsSet = false; +} +} +} +} +} + + diff --git a/other/master-clients/cpp-restsdk/src/model/Location.cpp b/other/master-clients/cpp-restsdk/src/model/Location.cpp new file mode 100644 index 000000000..eb03afed4 --- /dev/null +++ b/other/master-clients/cpp-restsdk/src/model/Location.cpp @@ -0,0 +1,168 @@ +/** + * Seaweedfs Master Server API + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * NOTE: This class is auto generated by OpenAPI-Generator 6.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "CppRestOpenAPIClient/model/Location.h" + +namespace org { +namespace openapitools { +namespace client { +namespace model { + + + +Location::Location() +{ + m_PublicUrlIsSet = false; + m_UrlIsSet = false; +} + +Location::~Location() +{ +} + +void Location::validate() +{ + // TODO: implement validation +} + +web::json::value Location::toJson() const +{ + + web::json::value val = web::json::value::object(); + + if(m_PublicUrlIsSet) + { + val[utility::conversions::to_string_t(U("publicUrl"))] = ModelBase::toJson(m_PublicUrl); + } + if(m_UrlIsSet) + { + val[utility::conversions::to_string_t(U("url"))] = ModelBase::toJson(m_Url); + } + + return val; +} + +bool Location::fromJson(const web::json::value& val) +{ + bool ok = true; + + if(val.has_field(utility::conversions::to_string_t(U("publicUrl")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("publicUrl"))); + if(!fieldValue.is_null()) + { + std::shared_ptr refVal_setPublicUrl; + ok &= ModelBase::fromJson(fieldValue, refVal_setPublicUrl); + setPublicUrl(refVal_setPublicUrl); + } + } + if(val.has_field(utility::conversions::to_string_t(U("url")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("url"))); + if(!fieldValue.is_null()) + { + std::shared_ptr refVal_setUrl; + ok &= ModelBase::fromJson(fieldValue, refVal_setUrl); + setUrl(refVal_setUrl); + } + } + return ok; +} + +void Location::toMultipart(std::shared_ptr multipart, const utility::string_t& prefix) const +{ + utility::string_t namePrefix = prefix; + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(U("."))) + { + namePrefix += utility::conversions::to_string_t(U(".")); + } + if(m_PublicUrlIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("publicUrl")), m_PublicUrl)); + } + if(m_UrlIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("url")), m_Url)); + } +} + +bool Location::fromMultiPart(std::shared_ptr multipart, const utility::string_t& prefix) +{ + bool ok = true; + utility::string_t namePrefix = prefix; + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(U("."))) + { + namePrefix += utility::conversions::to_string_t(U(".")); + } + + if(multipart->hasContent(utility::conversions::to_string_t(U("publicUrl")))) + { + std::shared_ptr refVal_setPublicUrl; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("publicUrl"))), refVal_setPublicUrl ); + setPublicUrl(refVal_setPublicUrl); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("url")))) + { + std::shared_ptr refVal_setUrl; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("url"))), refVal_setUrl ); + setUrl(refVal_setUrl); + } + return ok; +} + +std::shared_ptr Location::getPublicUrl() const +{ + return m_PublicUrl; +} + +void Location::setPublicUrl(const std::shared_ptr& value) +{ + m_PublicUrl = value; + m_PublicUrlIsSet = true; +} + +bool Location::publicUrlIsSet() const +{ + return m_PublicUrlIsSet; +} + +void Location::unsetPublicUrl() +{ + m_PublicUrlIsSet = false; +} +std::shared_ptr Location::getUrl() const +{ + return m_Url; +} + +void Location::setUrl(const std::shared_ptr& value) +{ + m_Url = value; + m_UrlIsSet = true; +} + +bool Location::urlIsSet() const +{ + return m_UrlIsSet; +} + +void Location::unsetUrl() +{ + m_UrlIsSet = false; +} +} +} +} +} + + diff --git a/other/master-clients/csharp/.gitignore b/other/master-clients/csharp/.gitignore new file mode 100644 index 000000000..1ee53850b --- /dev/null +++ b/other/master-clients/csharp/.gitignore @@ -0,0 +1,362 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd diff --git a/other/master-clients/csharp/.openapi-generator-ignore b/other/master-clients/csharp/.openapi-generator-ignore new file mode 100644 index 000000000..7484ee590 --- /dev/null +++ b/other/master-clients/csharp/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/other/master-clients/csharp/.openapi-generator/FILES b/other/master-clients/csharp/.openapi-generator/FILES new file mode 100644 index 000000000..b390e60fd --- /dev/null +++ b/other/master-clients/csharp/.openapi-generator/FILES @@ -0,0 +1,33 @@ +.gitignore +.openapi-generator-ignore +.travis.yml +Org.OpenAPITools.sln +README.md +build.bat +build.sh +docs/DefaultApi.md +docs/FileKey.md +docs/Location.md +git_push.sh +mono_nunit_test.sh +src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs +src/Org.OpenAPITools.Test/Model/FileKeyTests.cs +src/Org.OpenAPITools.Test/Model/LocationTests.cs +src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +src/Org.OpenAPITools.Test/packages.config +src/Org.OpenAPITools/Api/DefaultApi.cs +src/Org.OpenAPITools/Client/ApiClient.cs +src/Org.OpenAPITools/Client/ApiException.cs +src/Org.OpenAPITools/Client/ApiResponse.cs +src/Org.OpenAPITools/Client/Configuration.cs +src/Org.OpenAPITools/Client/ExceptionFactory.cs +src/Org.OpenAPITools/Client/GlobalConfiguration.cs +src/Org.OpenAPITools/Client/IApiAccessor.cs +src/Org.OpenAPITools/Client/IReadableConfiguration.cs +src/Org.OpenAPITools/Client/OpenAPIDateConverter.cs +src/Org.OpenAPITools/Model/FileKey.cs +src/Org.OpenAPITools/Model/Location.cs +src/Org.OpenAPITools/Org.OpenAPITools.csproj +src/Org.OpenAPITools/Org.OpenAPITools.nuspec +src/Org.OpenAPITools/Properties/AssemblyInfo.cs +src/Org.OpenAPITools/packages.config diff --git a/other/master-clients/csharp/.openapi-generator/VERSION b/other/master-clients/csharp/.openapi-generator/VERSION new file mode 100644 index 000000000..c0be8a799 --- /dev/null +++ b/other/master-clients/csharp/.openapi-generator/VERSION @@ -0,0 +1 @@ +6.4.0 \ No newline at end of file diff --git a/other/master-clients/csharp/.travis.yml b/other/master-clients/csharp/.travis.yml new file mode 100644 index 000000000..e4965fc7e --- /dev/null +++ b/other/master-clients/csharp/.travis.yml @@ -0,0 +1,9 @@ +# +# Generated by: https://github.com/openapitools/openapi-generator.git +# +language: csharp +mono: + - latest +solution: Org.OpenAPITools.sln +script: + - /bin/sh ./mono_nunit_test.sh diff --git a/other/master-clients/csharp/Org.OpenAPITools.sln b/other/master-clients/csharp/Org.OpenAPITools.sln new file mode 100644 index 000000000..e75436fdf --- /dev/null +++ b/other/master-clients/csharp/Org.OpenAPITools.sln @@ -0,0 +1,27 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2012 +VisualStudioVersion = 12.0.0.0 +MinimumVisualStudioVersion = 10.0.0.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Org.OpenAPITools", "src\Org.OpenAPITools\Org.OpenAPITools.csproj", "{BC7B99B9-DA58-46D9-BFF5-76505068ECE5}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Org.OpenAPITools.Test", "src\Org.OpenAPITools.Test\Org.OpenAPITools.Test.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {BC7B99B9-DA58-46D9-BFF5-76505068ECE5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BC7B99B9-DA58-46D9-BFF5-76505068ECE5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BC7B99B9-DA58-46D9-BFF5-76505068ECE5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BC7B99B9-DA58-46D9-BFF5-76505068ECE5}.Release|Any CPU.Build.0 = Release|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal \ No newline at end of file diff --git a/other/master-clients/csharp/README.md b/other/master-clients/csharp/README.md new file mode 100644 index 000000000..7c10c57b7 --- /dev/null +++ b/other/master-clients/csharp/README.md @@ -0,0 +1,130 @@ +# Org.OpenAPITools - the C# library for the Seaweedfs Master Server API + +The Seaweedfs Master Server API allows you to store blobs + +This C# SDK is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: 3.43.0 +- SDK version: 1.0.0 +- Build package: org.openapitools.codegen.languages.CSharpClientCodegen + +## Frameworks supported + + +- .NET 4.0 or later +- Windows Phone 7.1 (Mango) + +## Dependencies + + +- [RestSharp](https://www.nuget.org/packages/RestSharp) - 105.1.0 or later +- [Json.NET](https://www.nuget.org/packages/Newtonsoft.Json/) - 7.0.0 or later +- [JsonSubTypes](https://www.nuget.org/packages/JsonSubTypes/) - 1.2.0 or later + +The DLLs included in the package may not be the latest version. We recommend using [NuGet](https://docs.nuget.org/consume/installing-nuget) to obtain the latest version of the packages: + +``` +Install-Package RestSharp +Install-Package Newtonsoft.Json +Install-Package JsonSubTypes +``` + +NOTE: RestSharp versions greater than 105.1.0 have a bug which causes file uploads to fail. See [RestSharp#742](https://github.com/restsharp/RestSharp/issues/742) + +## Installation + +Run the following command to generate the DLL + +- [Mac/Linux] `/bin/sh build.sh` +- [Windows] `build.bat` + +Then include the DLL (under the `bin` folder) in the C# project, and use the namespaces: + +```csharp +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +``` + + +## Packaging + +A `.nuspec` is included with the project. You can follow the Nuget quickstart to [create](https://docs.microsoft.com/en-us/nuget/quickstart/create-and-publish-a-package#create-the-package) and [publish](https://docs.microsoft.com/en-us/nuget/quickstart/create-and-publish-a-package#publish-the-package) packages. + +This `.nuspec` uses placeholders from the `.csproj`, so build the `.csproj` directly: + +``` +nuget pack -Build -OutputDirectory out Org.OpenAPITools.csproj +``` + +Then, publish to a [local feed](https://docs.microsoft.com/en-us/nuget/hosting-packages/local-feeds) or [other host](https://docs.microsoft.com/en-us/nuget/hosting-packages/overview) and consume the new package via Nuget as usual. + + +## Getting Started + +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class Example + { + public static void Main() + { + + Configuration.Default.BasePath = "https://127.0.0.1:9333"; + var apiInstance = new DefaultApi(Configuration.Default); + var count = new Object(); // Object | how many file ids to assign. Use _1, _2 for the assigned additional file ids. e.g. 3,01637037d6_1, 3,01637037d6_2 (optional) + var collection = new Object(); // Object | required collection name (optional) + var dataCenter = new Object(); // Object | preferred data center (optional) + var rack = new Object(); // Object | preferred rack (optional) + var dataNode = new Object(); // Object | preferred volume server, e.g. 127.0.0.1:8080 (optional) + var disk = new Object(); // Object | If you have disks labelled, this must be supplied to specify the disk type to allocate on. (optional) + var replication = new Object(); // Object | replica placement strategy (optional) + var ttl = new Object(); // Object | file expiration time limit, example: 3m for 3 minutes. units: m-minute, h-hour, d-day, w-week, M-month, y-year (optional) + var preallocate = new Object(); // Object | If no matching volumes, pre-allocate this number of bytes on disk for new volumes. (optional) + var memoryMapMaxSizeMb = new Object(); // Object | Only implemented for windows. Use memory mapped files with specified size for new volumes. (optional) + var writableVolumeCount = new Object(); // Object | If no matching volumes, create specified number of new volumes. (optional) + + try + { + // Assign a file key + FileKey result = apiInstance.DirAssign(count, collection, dataCenter, rack, dataNode, disk, replication, ttl, preallocate, memoryMapMaxSizeMb, writableVolumeCount); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling DefaultApi.DirAssign: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + + } + } +} +``` + +## Documentation for API Endpoints + +All URIs are relative to *https://127.0.0.1:9333* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*DefaultApi* | [**DirAssign**](docs/DefaultApi.md#dirassign) | **GET** /dir/assign | Assign a file key +*DefaultApi* | [**DirLookup**](docs/DefaultApi.md#dirlookup) | **GET** /dir/lookup | Lookup volume + + +## Documentation for Models + + - [Model.FileKey](docs/FileKey.md) + - [Model.Location](docs/Location.md) + + +## Documentation for Authorization + +All endpoints do not require authorization. diff --git a/other/master-clients/csharp/build.bat b/other/master-clients/csharp/build.bat new file mode 100644 index 000000000..e153457ad --- /dev/null +++ b/other/master-clients/csharp/build.bat @@ -0,0 +1,16 @@ +:: Generated by: https://github.com/openapitools/openapi-generator.git +:: + +@echo off + +SET CSCPATH=%SYSTEMROOT%\Microsoft.NET\Framework\v4.0.30319 + +if not exist ".\nuget.exe" powershell -Command "(new-object System.Net.WebClient).DownloadFile('https://dist.nuget.org/win-x86-commandline/latest/nuget.exe', '.\nuget.exe')" +.\nuget.exe install src\Org.OpenAPITools\packages.config -o packages + +if not exist ".\bin" mkdir bin + +copy packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll bin\Newtonsoft.Json.dll +copy packages\JsonSubTypes.1.6.0\lib\net45\JsonSubTypes.dll bin\JsonSubTypes.dll +copy packages\RestSharp.105.1.0\lib\net45\RestSharp.dll bin\RestSharp.dll +%CSCPATH%\csc /reference:bin\Newtonsoft.Json.dll;bin\JsonSubTypes.dll;bin\RestSharp.dll;System.ComponentModel.DataAnnotations.dll /target:library /out:bin\Org.OpenAPITools.dll /recurse:src\Org.OpenAPITools\*.cs /doc:bin\Org.OpenAPITools.xml diff --git a/other/master-clients/csharp/build.sh b/other/master-clients/csharp/build.sh new file mode 100644 index 000000000..ddb1644db --- /dev/null +++ b/other/master-clients/csharp/build.sh @@ -0,0 +1,68 @@ +#!/usr/bin/env bash +# +# Generated by: https://github.com/openapitools/openapi-generator.git +# + +frameworkVersion=net45 + +# sdk must match installed frameworks under PREFIX/lib/mono/[value] +sdk=4.5.2-api + +# langversion refers to C# language features. see man mcs for details. +langversion=${sdk} +nuget_cmd=nuget + +# Match against our known SDK possibilities +case "${sdk}" in + 4) + langversion=4 + ;; + 4.5*) + langversion=5 + ;; + 4.6*) + langversion=6 + ;; + 4.7*) + langversion=7 # ignoring 7.1 for now. + ;; + *) + langversion=6 + ;; +esac + +echo "[INFO] Target framework: ${frameworkVersion}" + +if ! type nuget &>/dev/null; then + echo "[INFO] Download nuget and packages" + wget -nc https://dist.nuget.org/win-x86-commandline/latest/nuget.exe; + nuget_cmd="mono nuget.exe" +fi + +mozroots --import --sync +${nuget_cmd} install src/Org.OpenAPITools/packages.config -o packages; + +echo "[INFO] Copy DLLs to the 'bin' folder" +mkdir -p bin; +cp packages/Newtonsoft.Json.12.0.3/lib/net45/Newtonsoft.Json.dll bin/Newtonsoft.Json.dll; +cp packages/RestSharp.105.1.0/lib/net45/RestSharp.dll bin/RestSharp.dll; +cp packages/JsonSubTypes.1.6.0/lib/net45/JsonSubTypes.dll bin/JsonSubTypes.dll + +echo "[INFO] Run 'mcs' to build bin/Org.OpenAPITools.dll" +mcs -langversion:${langversion} -sdk:${sdk} -r:bin/Newtonsoft.Json.dll,bin/JsonSubTypes.dll,\ +bin/RestSharp.dll,\ +System.ComponentModel.DataAnnotations.dll,\ +System.Runtime.Serialization.dll \ +-target:library \ +-out:bin/Org.OpenAPITools.dll \ +-recurse:'src/Org.OpenAPITools/*.cs' \ +-doc:bin/Org.OpenAPITools.xml \ +-platform:anycpu + +if [ $? -ne 0 ] +then + echo "[ERROR] Compilation failed with exit code $?" + exit 1 +else + echo "[INFO] bin/Org.OpenAPITools.dll was created successfully" +fi diff --git a/other/master-clients/csharp/docs/DefaultApi.md b/other/master-clients/csharp/docs/DefaultApi.md new file mode 100644 index 000000000..a7049cd4c --- /dev/null +++ b/other/master-clients/csharp/docs/DefaultApi.md @@ -0,0 +1,188 @@ +# Org.OpenAPITools.Api.DefaultApi + +All URIs are relative to *https://127.0.0.1:9333* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**DirAssign**](DefaultApi.md#dirassign) | **GET** /dir/assign | Assign a file key +[**DirLookup**](DefaultApi.md#dirlookup) | **GET** /dir/lookup | Lookup volume + + + +## DirAssign + +> FileKey DirAssign (Object count = null, Object collection = null, Object dataCenter = null, Object rack = null, Object dataNode = null, Object disk = null, Object replication = null, Object ttl = null, Object preallocate = null, Object memoryMapMaxSizeMb = null, Object writableVolumeCount = null) + +Assign a file key + +This operation is very cheap. Just increase a number in master server's memory. + +### Example + +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class DirAssignExample + { + public static void Main() + { + Configuration.Default.BasePath = "https://127.0.0.1:9333"; + var apiInstance = new DefaultApi(Configuration.Default); + var count = new Object(); // Object | how many file ids to assign. Use _1, _2 for the assigned additional file ids. e.g. 3,01637037d6_1, 3,01637037d6_2 (optional) + var collection = new Object(); // Object | required collection name (optional) + var dataCenter = new Object(); // Object | preferred data center (optional) + var rack = new Object(); // Object | preferred rack (optional) + var dataNode = new Object(); // Object | preferred volume server, e.g. 127.0.0.1:8080 (optional) + var disk = new Object(); // Object | If you have disks labelled, this must be supplied to specify the disk type to allocate on. (optional) + var replication = new Object(); // Object | replica placement strategy (optional) + var ttl = new Object(); // Object | file expiration time limit, example: 3m for 3 minutes. units: m-minute, h-hour, d-day, w-week, M-month, y-year (optional) + var preallocate = new Object(); // Object | If no matching volumes, pre-allocate this number of bytes on disk for new volumes. (optional) + var memoryMapMaxSizeMb = new Object(); // Object | Only implemented for windows. Use memory mapped files with specified size for new volumes. (optional) + var writableVolumeCount = new Object(); // Object | If no matching volumes, create specified number of new volumes. (optional) + + try + { + // Assign a file key + FileKey result = apiInstance.DirAssign(count, collection, dataCenter, rack, dataNode, disk, replication, ttl, preallocate, memoryMapMaxSizeMb, writableVolumeCount); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling DefaultApi.DirAssign: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **count** | [**Object**](Object.md)| how many file ids to assign. Use <fid>_1, <fid>_2 for the assigned additional file ids. e.g. 3,01637037d6_1, 3,01637037d6_2 | [optional] + **collection** | [**Object**](Object.md)| required collection name | [optional] + **dataCenter** | [**Object**](Object.md)| preferred data center | [optional] + **rack** | [**Object**](Object.md)| preferred rack | [optional] + **dataNode** | [**Object**](Object.md)| preferred volume server, e.g. 127.0.0.1:8080 | [optional] + **disk** | [**Object**](Object.md)| If you have disks labelled, this must be supplied to specify the disk type to allocate on. | [optional] + **replication** | [**Object**](Object.md)| replica placement strategy | [optional] + **ttl** | [**Object**](Object.md)| file expiration time limit, example: 3m for 3 minutes. units: m-minute, h-hour, d-day, w-week, M-month, y-year | [optional] + **preallocate** | [**Object**](Object.md)| If no matching volumes, pre-allocate this number of bytes on disk for new volumes. | [optional] + **memoryMapMaxSizeMb** | [**Object**](Object.md)| Only implemented for windows. Use memory mapped files with specified size for new volumes. | [optional] + **writableVolumeCount** | [**Object**](Object.md)| If no matching volumes, create specified number of new volumes. | [optional] + +### Return type + +[**FileKey**](FileKey.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +[[Back to top]](#) +[[Back to API list]](../README.md#documentation-for-api-endpoints) +[[Back to Model list]](../README.md#documentation-for-models) +[[Back to README]](../README.md) + + +## DirLookup + +> Object DirLookup (Object volumeId = null, Object collection = null, Object fileId = null, Object read = null) + +Lookup volume + +We would need to find out whether the volumes have moved. + +### Example + +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class DirLookupExample + { + public static void Main() + { + Configuration.Default.BasePath = "https://127.0.0.1:9333"; + var apiInstance = new DefaultApi(Configuration.Default); + var volumeId = new Object(); // Object | volume id (optional) + var collection = new Object(); // Object | optionally to speed up the lookup (optional) + var fileId = new Object(); // Object | If provided, this returns the fileId location and a JWT to update or delete the file. (optional) + var read = new Object(); // Object | works together with \"fileId\", if read=yes, JWT is generated for reads. (optional) + + try + { + // Lookup volume + Object result = apiInstance.DirLookup(volumeId, collection, fileId, read); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling DefaultApi.DirLookup: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **volumeId** | [**Object**](Object.md)| volume id | [optional] + **collection** | [**Object**](Object.md)| optionally to speed up the lookup | [optional] + **fileId** | [**Object**](Object.md)| If provided, this returns the fileId location and a JWT to update or delete the file. | [optional] + **read** | [**Object**](Object.md)| works together with \"fileId\", if read=yes, JWT is generated for reads. | [optional] + +### Return type + +**Object** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +[[Back to top]](#) +[[Back to API list]](../README.md#documentation-for-api-endpoints) +[[Back to Model list]](../README.md#documentation-for-models) +[[Back to README]](../README.md) + diff --git a/other/master-clients/csharp/docs/FileKey.md b/other/master-clients/csharp/docs/FileKey.md new file mode 100644 index 000000000..f2e35bdb7 --- /dev/null +++ b/other/master-clients/csharp/docs/FileKey.md @@ -0,0 +1,15 @@ + +# Org.OpenAPITools.Model.FileKey + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Count** | **Object** | | [optional] +**Fid** | **Object** | | [optional] +**Url** | **Object** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) +[[Back to API list]](../README.md#documentation-for-api-endpoints) +[[Back to README]](../README.md) + diff --git a/other/master-clients/csharp/docs/Location.md b/other/master-clients/csharp/docs/Location.md new file mode 100644 index 000000000..fa225be59 --- /dev/null +++ b/other/master-clients/csharp/docs/Location.md @@ -0,0 +1,14 @@ + +# Org.OpenAPITools.Model.Location + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**PublicUrl** | **Object** | | [optional] +**Url** | **Object** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) +[[Back to API list]](../README.md#documentation-for-api-endpoints) +[[Back to README]](../README.md) + diff --git a/other/master-clients/csharp/git_push.sh b/other/master-clients/csharp/git_push.sh new file mode 100644 index 000000000..f53a75d4f --- /dev/null +++ b/other/master-clients/csharp/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/other/master-clients/csharp/mono_nunit_test.sh b/other/master-clients/csharp/mono_nunit_test.sh new file mode 100644 index 000000000..ef4209de2 --- /dev/null +++ b/other/master-clients/csharp/mono_nunit_test.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# +# Generated by: https://github.com/openapitools/openapi-generator.git +# + +wget -nc https://dist.nuget.org/win-x86-commandline/latest/nuget.exe +mozroots --import --sync + +echo "[INFO] remove bin/Debug/Org.OpenAPITools.Test.dll" +rm src/Org.OpenAPITools.Test/bin/Debug/Org.OpenAPITools.Test.dll 2> /dev/null + +echo "[INFO] install NUnit runners via NuGet" +wget -nc https://dist.nuget.org/win-x86-commandline/latest/nuget.exe +mozroots --import --sync +mono nuget.exe install src/Org.OpenAPITools.Test/packages.config -o packages + +echo "[INFO] Install NUnit Console 3.x runners via NuGet" +mono nuget.exe install NUnit.ConsoleRunner -Version 3.10.0 -OutputDirectory packages + +echo "[INFO] Build the solution and run the unit test" +xbuild Org.OpenAPITools.sln && \ + mono ./packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe src/Org.OpenAPITools.Test/bin/Debug/Org.OpenAPITools.Test.dll diff --git a/other/master-clients/csharp/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs b/other/master-clients/csharp/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs new file mode 100644 index 000000000..132dadb31 --- /dev/null +++ b/other/master-clients/csharp/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs @@ -0,0 +1,105 @@ +/* + * Seaweedfs Master Server API + * + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.IO; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Reflection; +using RestSharp; +using NUnit.Framework; + +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; + +namespace Org.OpenAPITools.Test +{ + /// + /// Class for testing DefaultApi + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the API endpoint. + /// + public class DefaultApiTests + { + private DefaultApi instance; + + /// + /// Setup before each unit test + /// + [SetUp] + public void Init() + { + instance = new DefaultApi(); + } + + /// + /// Clean up after each unit test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of DefaultApi + /// + [Test] + public void InstanceTest() + { + // TODO uncomment below to test 'IsInstanceOf' DefaultApi + //Assert.IsInstanceOf(typeof(DefaultApi), instance); + } + + + /// + /// Test DirAssign + /// + [Test] + public void DirAssignTest() + { + // TODO uncomment below to test the method and replace null with proper value + //Object count = null; + //Object collection = null; + //Object dataCenter = null; + //Object rack = null; + //Object dataNode = null; + //Object disk = null; + //Object replication = null; + //Object ttl = null; + //Object preallocate = null; + //Object memoryMapMaxSizeMb = null; + //Object writableVolumeCount = null; + //var response = instance.DirAssign(count, collection, dataCenter, rack, dataNode, disk, replication, ttl, preallocate, memoryMapMaxSizeMb, writableVolumeCount); + //Assert.IsInstanceOf(typeof(FileKey), response, "response is FileKey"); + } + + /// + /// Test DirLookup + /// + [Test] + public void DirLookupTest() + { + // TODO uncomment below to test the method and replace null with proper value + //Object volumeId = null; + //Object collection = null; + //Object fileId = null; + //Object read = null; + //var response = instance.DirLookup(volumeId, collection, fileId, read); + //Assert.IsInstanceOf(typeof(Object), response, "response is Object"); + } + + } + +} diff --git a/other/master-clients/csharp/src/Org.OpenAPITools.Test/Model/FileKeyTests.cs b/other/master-clients/csharp/src/Org.OpenAPITools.Test/Model/FileKeyTests.cs new file mode 100644 index 000000000..e0bf8724e --- /dev/null +++ b/other/master-clients/csharp/src/Org.OpenAPITools.Test/Model/FileKeyTests.cs @@ -0,0 +1,95 @@ +/* + * Seaweedfs Master Server API + * + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test +{ + /// + /// Class for testing FileKey + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class FileKeyTests + { + // TODO uncomment below to declare an instance variable for FileKey + //private FileKey instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of FileKey + //instance = new FileKey(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of FileKey + /// + [Test] + public void FileKeyInstanceTest() + { + // TODO uncomment below to test "IsInstanceOf" FileKey + //Assert.IsInstanceOf(typeof(FileKey), instance); + } + + + /// + /// Test the property 'Count' + /// + [Test] + public void CountTest() + { + // TODO unit test for the property 'Count' + } + /// + /// Test the property 'Fid' + /// + [Test] + public void FidTest() + { + // TODO unit test for the property 'Fid' + } + /// + /// Test the property 'Url' + /// + [Test] + public void UrlTest() + { + // TODO unit test for the property 'Url' + } + + } + +} diff --git a/other/master-clients/csharp/src/Org.OpenAPITools.Test/Model/LocationTests.cs b/other/master-clients/csharp/src/Org.OpenAPITools.Test/Model/LocationTests.cs new file mode 100644 index 000000000..8014fbd3a --- /dev/null +++ b/other/master-clients/csharp/src/Org.OpenAPITools.Test/Model/LocationTests.cs @@ -0,0 +1,87 @@ +/* + * Seaweedfs Master Server API + * + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test +{ + /// + /// Class for testing Location + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class LocationTests + { + // TODO uncomment below to declare an instance variable for Location + //private Location instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of Location + //instance = new Location(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of Location + /// + [Test] + public void LocationInstanceTest() + { + // TODO uncomment below to test "IsInstanceOf" Location + //Assert.IsInstanceOf(typeof(Location), instance); + } + + + /// + /// Test the property 'PublicUrl' + /// + [Test] + public void PublicUrlTest() + { + // TODO unit test for the property 'PublicUrl' + } + /// + /// Test the property 'Url' + /// + [Test] + public void UrlTest() + { + // TODO unit test for the property 'Url' + } + + } + +} diff --git a/other/master-clients/csharp/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/other/master-clients/csharp/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj new file mode 100644 index 000000000..34f7c2747 --- /dev/null +++ b/other/master-clients/csharp/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -0,0 +1,88 @@ + + + + + Debug + AnyCPU + {19F1DEBC-DE5E-4517-8062-F000CD499087} + Library + Properties + Org.OpenAPITools.Test + Org.OpenAPITools.Test + v4.5 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + $(SolutionDir)\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll + ..\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll + ..\..\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll + ..\..\vendor\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll + + + $(SolutionDir)\packages\JsonSubTypes.1.6.0\lib\net45\JsonSubTypes.dll + ..\packages\JsonSubTypes.1.6.0\lib\net45\JsonSubTypes.dll + ..\..\packages\JsonSubTypes.1.6.0\lib\net45\JsonSubTypes.dll + ..\..\vendor\JsonSubTypes.1.6.0\lib\net45\JsonSubTypes.dll + + + $(SolutionDir)\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll + ..\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll + ..\..\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll + ..\..\vendor\RestSharp.105.1.0\lib\net45\RestSharp.dll + + + $(SolutionDir)\packages\NUnit.3.11.0\lib\net45\nunit.framework.dll + ..\packages\NUnit.3.11.0\lib\net45\nunit.framework.dll + ..\..\packages\NUnit.3.11.0\lib\net45\nunit.framework.dll + ..\..\vendor\NUnit.3.11.0\lib\net45\nunit.framework.dll + + + + + + + + + + + + {BC7B99B9-DA58-46D9-BFF5-76505068ECE5} + Org.OpenAPITools + + + diff --git a/other/master-clients/csharp/src/Org.OpenAPITools.Test/packages.config b/other/master-clients/csharp/src/Org.OpenAPITools.Test/packages.config new file mode 100644 index 000000000..a3a1bab35 --- /dev/null +++ b/other/master-clients/csharp/src/Org.OpenAPITools.Test/packages.config @@ -0,0 +1,7 @@ + + + + + + + diff --git a/other/master-clients/csharp/src/Org.OpenAPITools/Api/DefaultApi.cs b/other/master-clients/csharp/src/Org.OpenAPITools/Api/DefaultApi.cs new file mode 100644 index 000000000..98d299eef --- /dev/null +++ b/other/master-clients/csharp/src/Org.OpenAPITools/Api/DefaultApi.cs @@ -0,0 +1,618 @@ +/* + * Seaweedfs Master Server API + * + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Threading; +using RestSharp; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Org.OpenAPITools.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IDefaultApi : IApiAccessor + { + #region Synchronous Operations + /// + /// Assign a file key + /// + /// + /// This operation is very cheap. Just increase a number in master server's memory. + /// + /// Thrown when fails to make API call + /// how many file ids to assign. Use <fid>_1, <fid>_2 for the assigned additional file ids. e.g. 3,01637037d6_1, 3,01637037d6_2 (optional) + /// required collection name (optional) + /// preferred data center (optional) + /// preferred rack (optional) + /// preferred volume server, e.g. 127.0.0.1:8080 (optional) + /// If you have disks labelled, this must be supplied to specify the disk type to allocate on. (optional) + /// replica placement strategy (optional) + /// file expiration time limit, example: 3m for 3 minutes. units: m-minute, h-hour, d-day, w-week, M-month, y-year (optional) + /// If no matching volumes, pre-allocate this number of bytes on disk for new volumes. (optional) + /// Only implemented for windows. Use memory mapped files with specified size for new volumes. (optional) + /// If no matching volumes, create specified number of new volumes. (optional) + /// FileKey + FileKey DirAssign (Object count = default(Object), Object collection = default(Object), Object dataCenter = default(Object), Object rack = default(Object), Object dataNode = default(Object), Object disk = default(Object), Object replication = default(Object), Object ttl = default(Object), Object preallocate = default(Object), Object memoryMapMaxSizeMb = default(Object), Object writableVolumeCount = default(Object)); + + /// + /// Assign a file key + /// + /// + /// This operation is very cheap. Just increase a number in master server's memory. + /// + /// Thrown when fails to make API call + /// how many file ids to assign. Use <fid>_1, <fid>_2 for the assigned additional file ids. e.g. 3,01637037d6_1, 3,01637037d6_2 (optional) + /// required collection name (optional) + /// preferred data center (optional) + /// preferred rack (optional) + /// preferred volume server, e.g. 127.0.0.1:8080 (optional) + /// If you have disks labelled, this must be supplied to specify the disk type to allocate on. (optional) + /// replica placement strategy (optional) + /// file expiration time limit, example: 3m for 3 minutes. units: m-minute, h-hour, d-day, w-week, M-month, y-year (optional) + /// If no matching volumes, pre-allocate this number of bytes on disk for new volumes. (optional) + /// Only implemented for windows. Use memory mapped files with specified size for new volumes. (optional) + /// If no matching volumes, create specified number of new volumes. (optional) + /// ApiResponse of FileKey + ApiResponse DirAssignWithHttpInfo (Object count = default(Object), Object collection = default(Object), Object dataCenter = default(Object), Object rack = default(Object), Object dataNode = default(Object), Object disk = default(Object), Object replication = default(Object), Object ttl = default(Object), Object preallocate = default(Object), Object memoryMapMaxSizeMb = default(Object), Object writableVolumeCount = default(Object)); + /// + /// Lookup volume + /// + /// + /// We would need to find out whether the volumes have moved. + /// + /// Thrown when fails to make API call + /// volume id (optional) + /// optionally to speed up the lookup (optional) + /// If provided, this returns the fileId location and a JWT to update or delete the file. (optional) + /// works together with \"fileId\", if read=yes, JWT is generated for reads. (optional) + /// Object + Object DirLookup (Object volumeId = default(Object), Object collection = default(Object), Object fileId = default(Object), Object read = default(Object)); + + /// + /// Lookup volume + /// + /// + /// We would need to find out whether the volumes have moved. + /// + /// Thrown when fails to make API call + /// volume id (optional) + /// optionally to speed up the lookup (optional) + /// If provided, this returns the fileId location and a JWT to update or delete the file. (optional) + /// works together with \"fileId\", if read=yes, JWT is generated for reads. (optional) + /// ApiResponse of Object + ApiResponse DirLookupWithHttpInfo (Object volumeId = default(Object), Object collection = default(Object), Object fileId = default(Object), Object read = default(Object)); + #endregion Synchronous Operations + #region Asynchronous Operations + /// + /// Assign a file key + /// + /// + /// This operation is very cheap. Just increase a number in master server's memory. + /// + /// Thrown when fails to make API call + /// how many file ids to assign. Use <fid>_1, <fid>_2 for the assigned additional file ids. e.g. 3,01637037d6_1, 3,01637037d6_2 (optional) + /// required collection name (optional) + /// preferred data center (optional) + /// preferred rack (optional) + /// preferred volume server, e.g. 127.0.0.1:8080 (optional) + /// If you have disks labelled, this must be supplied to specify the disk type to allocate on. (optional) + /// replica placement strategy (optional) + /// file expiration time limit, example: 3m for 3 minutes. units: m-minute, h-hour, d-day, w-week, M-month, y-year (optional) + /// If no matching volumes, pre-allocate this number of bytes on disk for new volumes. (optional) + /// Only implemented for windows. Use memory mapped files with specified size for new volumes. (optional) + /// If no matching volumes, create specified number of new volumes. (optional) + /// Cancellation Token to cancel request (optional) + /// Task of FileKey + System.Threading.Tasks.Task DirAssignAsync (Object count = default(Object), Object collection = default(Object), Object dataCenter = default(Object), Object rack = default(Object), Object dataNode = default(Object), Object disk = default(Object), Object replication = default(Object), Object ttl = default(Object), Object preallocate = default(Object), Object memoryMapMaxSizeMb = default(Object), Object writableVolumeCount = default(Object), CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Assign a file key + /// + /// + /// This operation is very cheap. Just increase a number in master server's memory. + /// + /// Thrown when fails to make API call + /// how many file ids to assign. Use <fid>_1, <fid>_2 for the assigned additional file ids. e.g. 3,01637037d6_1, 3,01637037d6_2 (optional) + /// required collection name (optional) + /// preferred data center (optional) + /// preferred rack (optional) + /// preferred volume server, e.g. 127.0.0.1:8080 (optional) + /// If you have disks labelled, this must be supplied to specify the disk type to allocate on. (optional) + /// replica placement strategy (optional) + /// file expiration time limit, example: 3m for 3 minutes. units: m-minute, h-hour, d-day, w-week, M-month, y-year (optional) + /// If no matching volumes, pre-allocate this number of bytes on disk for new volumes. (optional) + /// Only implemented for windows. Use memory mapped files with specified size for new volumes. (optional) + /// If no matching volumes, create specified number of new volumes. (optional) + /// Cancellation Token to cancel request (optional) + /// Task of ApiResponse (FileKey) + System.Threading.Tasks.Task> DirAssignWithHttpInfoAsync (Object count = default(Object), Object collection = default(Object), Object dataCenter = default(Object), Object rack = default(Object), Object dataNode = default(Object), Object disk = default(Object), Object replication = default(Object), Object ttl = default(Object), Object preallocate = default(Object), Object memoryMapMaxSizeMb = default(Object), Object writableVolumeCount = default(Object), CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Lookup volume + /// + /// + /// We would need to find out whether the volumes have moved. + /// + /// Thrown when fails to make API call + /// volume id (optional) + /// optionally to speed up the lookup (optional) + /// If provided, this returns the fileId location and a JWT to update or delete the file. (optional) + /// works together with \"fileId\", if read=yes, JWT is generated for reads. (optional) + /// Cancellation Token to cancel request (optional) + /// Task of Object + System.Threading.Tasks.Task DirLookupAsync (Object volumeId = default(Object), Object collection = default(Object), Object fileId = default(Object), Object read = default(Object), CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Lookup volume + /// + /// + /// We would need to find out whether the volumes have moved. + /// + /// Thrown when fails to make API call + /// volume id (optional) + /// optionally to speed up the lookup (optional) + /// If provided, this returns the fileId location and a JWT to update or delete the file. (optional) + /// works together with \"fileId\", if read=yes, JWT is generated for reads. (optional) + /// Cancellation Token to cancel request (optional) + /// Task of ApiResponse (Object) + System.Threading.Tasks.Task> DirLookupWithHttpInfoAsync (Object volumeId = default(Object), Object collection = default(Object), Object fileId = default(Object), Object read = default(Object), CancellationToken cancellationToken = default(CancellationToken)); + #endregion Asynchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public partial class DefaultApi : IDefaultApi + { + private Org.OpenAPITools.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + + /// + /// Initializes a new instance of the class. + /// + /// + public DefaultApi(String basePath) + { + this.Configuration = new Org.OpenAPITools.Client.Configuration { BasePath = basePath }; + + ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class + /// + /// + public DefaultApi() + { + this.Configuration = Org.OpenAPITools.Client.Configuration.Default; + + ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class + /// using Configuration object + /// + /// An instance of Configuration + /// + public DefaultApi(Org.OpenAPITools.Client.Configuration configuration = null) + { + if (configuration == null) // use the default one in Configuration + this.Configuration = Org.OpenAPITools.Client.Configuration.Default; + else + this.Configuration = configuration; + + ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Gets the base path of the API client. + /// + /// The base path + public String GetBasePath() + { + return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); + } + + /// + /// Sets the base path of the API client. + /// + /// The base path + [Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")] + public void SetBasePath(String basePath) + { + // do nothing + } + + /// + /// Gets or sets the configuration object + /// + /// An instance of the Configuration + public Org.OpenAPITools.Client.Configuration Configuration {get; set;} + + /// + /// Provides a factory method hook for the creation of exceptions. + /// + public Org.OpenAPITools.Client.ExceptionFactory ExceptionFactory + { + get + { + if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) + { + throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); + } + return _exceptionFactory; + } + set { _exceptionFactory = value; } + } + + /// + /// Gets the default header. + /// + /// Dictionary of HTTP header + [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] + public IDictionary DefaultHeader() + { + return new ReadOnlyDictionary(this.Configuration.DefaultHeader); + } + + /// + /// Add default header. + /// + /// Header field name. + /// Header field value. + /// + [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] + public void AddDefaultHeader(string key, string value) + { + this.Configuration.AddDefaultHeader(key, value); + } + + /// + /// Assign a file key This operation is very cheap. Just increase a number in master server's memory. + /// + /// Thrown when fails to make API call + /// how many file ids to assign. Use <fid>_1, <fid>_2 for the assigned additional file ids. e.g. 3,01637037d6_1, 3,01637037d6_2 (optional) + /// required collection name (optional) + /// preferred data center (optional) + /// preferred rack (optional) + /// preferred volume server, e.g. 127.0.0.1:8080 (optional) + /// If you have disks labelled, this must be supplied to specify the disk type to allocate on. (optional) + /// replica placement strategy (optional) + /// file expiration time limit, example: 3m for 3 minutes. units: m-minute, h-hour, d-day, w-week, M-month, y-year (optional) + /// If no matching volumes, pre-allocate this number of bytes on disk for new volumes. (optional) + /// Only implemented for windows. Use memory mapped files with specified size for new volumes. (optional) + /// If no matching volumes, create specified number of new volumes. (optional) + /// FileKey + public FileKey DirAssign (Object count = default(Object), Object collection = default(Object), Object dataCenter = default(Object), Object rack = default(Object), Object dataNode = default(Object), Object disk = default(Object), Object replication = default(Object), Object ttl = default(Object), Object preallocate = default(Object), Object memoryMapMaxSizeMb = default(Object), Object writableVolumeCount = default(Object)) + { + ApiResponse localVarResponse = DirAssignWithHttpInfo(count, collection, dataCenter, rack, dataNode, disk, replication, ttl, preallocate, memoryMapMaxSizeMb, writableVolumeCount); + return localVarResponse.Data; + } + + /// + /// Assign a file key This operation is very cheap. Just increase a number in master server's memory. + /// + /// Thrown when fails to make API call + /// how many file ids to assign. Use <fid>_1, <fid>_2 for the assigned additional file ids. e.g. 3,01637037d6_1, 3,01637037d6_2 (optional) + /// required collection name (optional) + /// preferred data center (optional) + /// preferred rack (optional) + /// preferred volume server, e.g. 127.0.0.1:8080 (optional) + /// If you have disks labelled, this must be supplied to specify the disk type to allocate on. (optional) + /// replica placement strategy (optional) + /// file expiration time limit, example: 3m for 3 minutes. units: m-minute, h-hour, d-day, w-week, M-month, y-year (optional) + /// If no matching volumes, pre-allocate this number of bytes on disk for new volumes. (optional) + /// Only implemented for windows. Use memory mapped files with specified size for new volumes. (optional) + /// If no matching volumes, create specified number of new volumes. (optional) + /// ApiResponse of FileKey + public ApiResponse DirAssignWithHttpInfo (Object count = default(Object), Object collection = default(Object), Object dataCenter = default(Object), Object rack = default(Object), Object dataNode = default(Object), Object disk = default(Object), Object replication = default(Object), Object ttl = default(Object), Object preallocate = default(Object), Object memoryMapMaxSizeMb = default(Object), Object writableVolumeCount = default(Object)) + { + + var localVarPath = "/dir/assign"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + var localVarHeaderParams = new Dictionary(this.Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/json" + }; + String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + if (count != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "count", count)); // query parameter + if (collection != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "collection", collection)); // query parameter + if (dataCenter != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "dataCenter", dataCenter)); // query parameter + if (rack != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "rack", rack)); // query parameter + if (dataNode != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "dataNode", dataNode)); // query parameter + if (disk != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "disk", disk)); // query parameter + if (replication != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "replication", replication)); // query parameter + if (ttl != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "ttl", ttl)); // query parameter + if (preallocate != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "preallocate", preallocate)); // query parameter + if (memoryMapMaxSizeMb != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "memoryMapMaxSizeMb", memoryMapMaxSizeMb)); // query parameter + if (writableVolumeCount != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "writableVolumeCount", writableVolumeCount)); // query parameter + + + // make the HTTP request + IRestResponse localVarResponse = (IRestResponse) this.Configuration.ApiClient.CallApi(localVarPath, + Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + localVarPathParams, localVarHttpContentType); + + int localVarStatusCode = (int) localVarResponse.StatusCode; + + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("DirAssign", localVarResponse); + if (exception != null) throw exception; + } + + return new ApiResponse(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => string.Join(",", x.Value)), + (FileKey) this.Configuration.ApiClient.Deserialize(localVarResponse, typeof(FileKey))); + } + + /// + /// Assign a file key This operation is very cheap. Just increase a number in master server's memory. + /// + /// Thrown when fails to make API call + /// how many file ids to assign. Use <fid>_1, <fid>_2 for the assigned additional file ids. e.g. 3,01637037d6_1, 3,01637037d6_2 (optional) + /// required collection name (optional) + /// preferred data center (optional) + /// preferred rack (optional) + /// preferred volume server, e.g. 127.0.0.1:8080 (optional) + /// If you have disks labelled, this must be supplied to specify the disk type to allocate on. (optional) + /// replica placement strategy (optional) + /// file expiration time limit, example: 3m for 3 minutes. units: m-minute, h-hour, d-day, w-week, M-month, y-year (optional) + /// If no matching volumes, pre-allocate this number of bytes on disk for new volumes. (optional) + /// Only implemented for windows. Use memory mapped files with specified size for new volumes. (optional) + /// If no matching volumes, create specified number of new volumes. (optional) + /// Cancellation Token to cancel request (optional) + /// Task of FileKey + public async System.Threading.Tasks.Task DirAssignAsync (Object count = default(Object), Object collection = default(Object), Object dataCenter = default(Object), Object rack = default(Object), Object dataNode = default(Object), Object disk = default(Object), Object replication = default(Object), Object ttl = default(Object), Object preallocate = default(Object), Object memoryMapMaxSizeMb = default(Object), Object writableVolumeCount = default(Object), CancellationToken cancellationToken = default(CancellationToken)) + { + ApiResponse localVarResponse = await DirAssignWithHttpInfoAsync(count, collection, dataCenter, rack, dataNode, disk, replication, ttl, preallocate, memoryMapMaxSizeMb, writableVolumeCount, cancellationToken); + return localVarResponse.Data; + + } + + /// + /// Assign a file key This operation is very cheap. Just increase a number in master server's memory. + /// + /// Thrown when fails to make API call + /// how many file ids to assign. Use <fid>_1, <fid>_2 for the assigned additional file ids. e.g. 3,01637037d6_1, 3,01637037d6_2 (optional) + /// required collection name (optional) + /// preferred data center (optional) + /// preferred rack (optional) + /// preferred volume server, e.g. 127.0.0.1:8080 (optional) + /// If you have disks labelled, this must be supplied to specify the disk type to allocate on. (optional) + /// replica placement strategy (optional) + /// file expiration time limit, example: 3m for 3 minutes. units: m-minute, h-hour, d-day, w-week, M-month, y-year (optional) + /// If no matching volumes, pre-allocate this number of bytes on disk for new volumes. (optional) + /// Only implemented for windows. Use memory mapped files with specified size for new volumes. (optional) + /// If no matching volumes, create specified number of new volumes. (optional) + /// Cancellation Token to cancel request (optional) + /// Task of ApiResponse (FileKey) + public async System.Threading.Tasks.Task> DirAssignWithHttpInfoAsync (Object count = default(Object), Object collection = default(Object), Object dataCenter = default(Object), Object rack = default(Object), Object dataNode = default(Object), Object disk = default(Object), Object replication = default(Object), Object ttl = default(Object), Object preallocate = default(Object), Object memoryMapMaxSizeMb = default(Object), Object writableVolumeCount = default(Object), CancellationToken cancellationToken = default(CancellationToken)) + { + + var localVarPath = "/dir/assign"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + var localVarHeaderParams = new Dictionary(this.Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/json" + }; + String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + if (count != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "count", count)); // query parameter + if (collection != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "collection", collection)); // query parameter + if (dataCenter != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "dataCenter", dataCenter)); // query parameter + if (rack != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "rack", rack)); // query parameter + if (dataNode != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "dataNode", dataNode)); // query parameter + if (disk != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "disk", disk)); // query parameter + if (replication != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "replication", replication)); // query parameter + if (ttl != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "ttl", ttl)); // query parameter + if (preallocate != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "preallocate", preallocate)); // query parameter + if (memoryMapMaxSizeMb != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "memoryMapMaxSizeMb", memoryMapMaxSizeMb)); // query parameter + if (writableVolumeCount != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "writableVolumeCount", writableVolumeCount)); // query parameter + + + // make the HTTP request + IRestResponse localVarResponse = (IRestResponse) await this.Configuration.ApiClient.CallApiAsync(localVarPath, + Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + localVarPathParams, localVarHttpContentType, cancellationToken); + + int localVarStatusCode = (int) localVarResponse.StatusCode; + + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("DirAssign", localVarResponse); + if (exception != null) throw exception; + } + + return new ApiResponse(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => string.Join(",", x.Value)), + (FileKey) this.Configuration.ApiClient.Deserialize(localVarResponse, typeof(FileKey))); + } + + /// + /// Lookup volume We would need to find out whether the volumes have moved. + /// + /// Thrown when fails to make API call + /// volume id (optional) + /// optionally to speed up the lookup (optional) + /// If provided, this returns the fileId location and a JWT to update or delete the file. (optional) + /// works together with \"fileId\", if read=yes, JWT is generated for reads. (optional) + /// Object + public Object DirLookup (Object volumeId = default(Object), Object collection = default(Object), Object fileId = default(Object), Object read = default(Object)) + { + ApiResponse localVarResponse = DirLookupWithHttpInfo(volumeId, collection, fileId, read); + return localVarResponse.Data; + } + + /// + /// Lookup volume We would need to find out whether the volumes have moved. + /// + /// Thrown when fails to make API call + /// volume id (optional) + /// optionally to speed up the lookup (optional) + /// If provided, this returns the fileId location and a JWT to update or delete the file. (optional) + /// works together with \"fileId\", if read=yes, JWT is generated for reads. (optional) + /// ApiResponse of Object + public ApiResponse DirLookupWithHttpInfo (Object volumeId = default(Object), Object collection = default(Object), Object fileId = default(Object), Object read = default(Object)) + { + + var localVarPath = "/dir/lookup"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + var localVarHeaderParams = new Dictionary(this.Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/json" + }; + String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + if (volumeId != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "volumeId", volumeId)); // query parameter + if (collection != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "collection", collection)); // query parameter + if (fileId != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "fileId", fileId)); // query parameter + if (read != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "read", read)); // query parameter + + + // make the HTTP request + IRestResponse localVarResponse = (IRestResponse) this.Configuration.ApiClient.CallApi(localVarPath, + Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + localVarPathParams, localVarHttpContentType); + + int localVarStatusCode = (int) localVarResponse.StatusCode; + + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("DirLookup", localVarResponse); + if (exception != null) throw exception; + } + + return new ApiResponse(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => string.Join(",", x.Value)), + (Object) this.Configuration.ApiClient.Deserialize(localVarResponse, typeof(Object))); + } + + /// + /// Lookup volume We would need to find out whether the volumes have moved. + /// + /// Thrown when fails to make API call + /// volume id (optional) + /// optionally to speed up the lookup (optional) + /// If provided, this returns the fileId location and a JWT to update or delete the file. (optional) + /// works together with \"fileId\", if read=yes, JWT is generated for reads. (optional) + /// Cancellation Token to cancel request (optional) + /// Task of Object + public async System.Threading.Tasks.Task DirLookupAsync (Object volumeId = default(Object), Object collection = default(Object), Object fileId = default(Object), Object read = default(Object), CancellationToken cancellationToken = default(CancellationToken)) + { + ApiResponse localVarResponse = await DirLookupWithHttpInfoAsync(volumeId, collection, fileId, read, cancellationToken); + return localVarResponse.Data; + + } + + /// + /// Lookup volume We would need to find out whether the volumes have moved. + /// + /// Thrown when fails to make API call + /// volume id (optional) + /// optionally to speed up the lookup (optional) + /// If provided, this returns the fileId location and a JWT to update or delete the file. (optional) + /// works together with \"fileId\", if read=yes, JWT is generated for reads. (optional) + /// Cancellation Token to cancel request (optional) + /// Task of ApiResponse (Object) + public async System.Threading.Tasks.Task> DirLookupWithHttpInfoAsync (Object volumeId = default(Object), Object collection = default(Object), Object fileId = default(Object), Object read = default(Object), CancellationToken cancellationToken = default(CancellationToken)) + { + + var localVarPath = "/dir/lookup"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + var localVarHeaderParams = new Dictionary(this.Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/json" + }; + String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + if (volumeId != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "volumeId", volumeId)); // query parameter + if (collection != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "collection", collection)); // query parameter + if (fileId != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "fileId", fileId)); // query parameter + if (read != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "read", read)); // query parameter + + + // make the HTTP request + IRestResponse localVarResponse = (IRestResponse) await this.Configuration.ApiClient.CallApiAsync(localVarPath, + Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + localVarPathParams, localVarHttpContentType, cancellationToken); + + int localVarStatusCode = (int) localVarResponse.StatusCode; + + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("DirLookup", localVarResponse); + if (exception != null) throw exception; + } + + return new ApiResponse(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => string.Join(",", x.Value)), + (Object) this.Configuration.ApiClient.Deserialize(localVarResponse, typeof(Object))); + } + + } +} diff --git a/other/master-clients/csharp/src/Org.OpenAPITools/Client/ApiClient.cs b/other/master-clients/csharp/src/Org.OpenAPITools/Client/ApiClient.cs new file mode 100644 index 000000000..39ec18853 --- /dev/null +++ b/other/master-clients/csharp/src/Org.OpenAPITools/Client/ApiClient.cs @@ -0,0 +1,536 @@ +/* + * Seaweedfs Master Server API + * + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.Text.RegularExpressions; +using System.IO; +using System.Threading; +using System.Web; +using System.Linq; +using System.Net; +using System.Text; +using Newtonsoft.Json; +using RestSharp; + +namespace Org.OpenAPITools.Client +{ + /// + /// API client is mainly responsible for making the HTTP call to the API backend. + /// + public partial class ApiClient + { + public JsonSerializerSettings serializerSettings = new JsonSerializerSettings + { + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor + }; + + /// + /// Allows for extending request processing for generated code. + /// + /// The RestSharp request object + partial void InterceptRequest(IRestRequest request); + + /// + /// Allows for extending response processing for generated code. + /// + /// The RestSharp request object + /// The RestSharp response object + partial void InterceptResponse(IRestRequest request, IRestResponse response); + + /// + /// Initializes a new instance of the class + /// with default configuration. + /// + public ApiClient() + { + Configuration = Org.OpenAPITools.Client.Configuration.Default; + RestClient = new RestClient("https://127.0.0.1:9333"); + } + + /// + /// Initializes a new instance of the class + /// with default base path (https://127.0.0.1:9333). + /// + /// An instance of Configuration. + public ApiClient(Configuration config) + { + Configuration = config ?? Org.OpenAPITools.Client.Configuration.Default; + + RestClient = new RestClient(Configuration.BasePath); + } + + /// + /// Initializes a new instance of the class + /// with default configuration. + /// + /// The base path. + public ApiClient(String basePath = "https://127.0.0.1:9333") + { + if (String.IsNullOrEmpty(basePath)) + throw new ArgumentException("basePath cannot be empty"); + + RestClient = new RestClient(basePath); + Configuration = Client.Configuration.Default; + } + + /// + /// Gets or sets the default API client for making HTTP calls. + /// + /// The default API client. + [Obsolete("ApiClient.Default is deprecated, please use 'Configuration.Default.ApiClient' instead.")] + public static ApiClient Default; + + /// + /// Gets or sets an instance of the IReadableConfiguration. + /// + /// An instance of the IReadableConfiguration. + /// + /// helps us to avoid modifying possibly global + /// configuration values from within a given client. It does not guarantee thread-safety + /// of the instance in any way. + /// + public IReadableConfiguration Configuration { get; set; } + + /// + /// Gets or sets the RestClient. + /// + /// An instance of the RestClient + public RestClient RestClient { get; set; } + + // Creates and sets up a RestRequest prior to a call. + private RestRequest PrepareRequest( + String path, RestSharp.Method method, List> queryParams, Object postBody, + Dictionary headerParams, Dictionary formParams, + Dictionary fileParams, Dictionary pathParams, + String contentType) + { + var request = new RestRequest(path, method); + + // add path parameter, if any + foreach(var param in pathParams) + request.AddParameter(param.Key, param.Value, ParameterType.UrlSegment); + + // add header parameter, if any + foreach(var param in headerParams) + request.AddHeader(param.Key, param.Value); + + // add query parameter, if any + foreach(var param in queryParams) + request.AddQueryParameter(param.Key, param.Value); + + // add form parameter, if any + foreach(var param in formParams) + request.AddParameter(param.Key, param.Value); + + // add file parameter, if any + foreach(var param in fileParams) + { + request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType); + } + + if (postBody != null) // http body (model or byte[]) parameter + { + request.AddParameter(contentType, postBody, ParameterType.RequestBody); + } + + return request; + } + + /// + /// Makes the HTTP request (Sync). + /// + /// URL path. + /// HTTP method. + /// Query parameters. + /// HTTP body (POST request). + /// Header parameters. + /// Form parameters. + /// File parameters. + /// Path parameters. + /// Content Type of the request + /// Object + public Object CallApi( + String path, RestSharp.Method method, List> queryParams, Object postBody, + Dictionary headerParams, Dictionary formParams, + Dictionary fileParams, Dictionary pathParams, + String contentType) + { + var request = PrepareRequest( + path, method, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, contentType); + + // set timeout + + RestClient.Timeout = Configuration.Timeout; + // set user agent + RestClient.UserAgent = Configuration.UserAgent; + + InterceptRequest(request); + var response = RestClient.Execute(request); + InterceptResponse(request, response); + + return (Object) response; + } + /// + /// Makes the asynchronous HTTP request. + /// + /// URL path. + /// HTTP method. + /// Query parameters. + /// HTTP body (POST request). + /// Header parameters. + /// Form parameters. + /// File parameters. + /// Path parameters. + /// Content type. + /// Cancellation Token. + /// The Task instance. + public async System.Threading.Tasks.Task CallApiAsync( + String path, RestSharp.Method method, List> queryParams, Object postBody, + Dictionary headerParams, Dictionary formParams, + Dictionary fileParams, Dictionary pathParams, + String contentType, CancellationToken cancellationToken) + { + var request = PrepareRequest( + path, method, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, contentType); + RestClient.UserAgent = Configuration.UserAgent; + InterceptRequest(request); + var response = await RestClient.ExecuteTaskAsync(request, cancellationToken); + InterceptResponse(request, response); + return (Object)response; + } + + /// + /// Escape string (url-encoded). + /// + /// String to be escaped. + /// Escaped string. + public string EscapeString(string str) + { + return UrlEncode(str); + } + + /// + /// Create FileParameter based on Stream. + /// + /// Parameter name. + /// Input stream. + /// FileParameter. + public FileParameter ParameterToFile(string name, Stream stream) + { + if (stream is FileStream) + return FileParameter.Create(name, ReadAsBytes(stream), Path.GetFileName(((FileStream)stream).Name)); + else + return FileParameter.Create(name, ReadAsBytes(stream), "no_file_name_provided"); + } + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// Formatted string. + public string ParameterToString(object obj) + { + if (obj is DateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return ((DateTime)obj).ToString (Configuration.DateTimeFormat); + else if (obj is DateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return ((DateTimeOffset)obj).ToString (Configuration.DateTimeFormat); + else if (obj is bool) + return (bool)obj ? "true" : "false"; + else if (obj is IList) + { + var flattenedString = new StringBuilder(); + foreach (var param in (IList)obj) + { + if (flattenedString.Length > 0) + flattenedString.Append(","); + flattenedString.Append(param); + } + return flattenedString.ToString(); + } + else + return Convert.ToString (obj); + } + + /// + /// Deserialize the JSON string into a proper object. + /// + /// The HTTP response. + /// Object type. + /// Object representation of the JSON string. + public object Deserialize(IRestResponse response, Type type) + { + IList headers = response.Headers; + if (type == typeof(byte[])) // return byte array + { + return response.RawBytes; + } + + // TODO: ? if (type.IsAssignableFrom(typeof(Stream))) + if (type == typeof(Stream)) + { + if (headers != null) + { + var filePath = String.IsNullOrEmpty(Configuration.TempFolderPath) + ? Path.GetTempPath() + : Configuration.TempFolderPath; + var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$"); + foreach (var header in headers) + { + var match = regex.Match(header.ToString()); + if (match.Success) + { + string fileName = filePath + SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); + File.WriteAllBytes(fileName, response.RawBytes); + return new FileStream(fileName, FileMode.Open); + } + } + } + var stream = new MemoryStream(response.RawBytes); + return stream; + } + + if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object + { + return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind); + } + + if (type == typeof(String) || type.Name.StartsWith("System.Nullable")) // return primitive type + { + return ConvertType(response.Content, type); + } + + // at this point, it must be a model (json) + try + { + return JsonConvert.DeserializeObject(response.Content, type, serializerSettings); + } + catch (Exception e) + { + throw new ApiException(500, e.Message); + } + } + + /// + /// Serialize an input (model) into JSON string + /// + /// Object. + /// JSON string. + public String Serialize(object obj) + { + try + { + return obj != null ? JsonConvert.SerializeObject(obj) : null; + } + catch (Exception e) + { + throw new ApiException(500, e.Message); + } + } + + /// + ///Check if the given MIME is a JSON MIME. + ///JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public bool IsJsonMime(String mime) + { + var jsonRegex = new Regex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$"); + return mime != null && (jsonRegex.IsMatch(mime) || mime.Equals("application/json-patch+json")); + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public String SelectHeaderContentType(String[] contentTypes) + { + if (contentTypes.Length == 0) + return "application/json"; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType.ToLower())) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public String SelectHeaderAccept(String[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return String.Join(",", accepts); + } + + /// + /// Encode string in base64 format. + /// + /// String to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Dynamically cast the object into target type. + /// + /// Object to be casted + /// Target type + /// Casted object + public static dynamic ConvertType(dynamic fromObject, Type toObject) + { + return Convert.ChangeType(fromObject, toObject); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + byte[] buf = new byte[16*1024]; + using (MemoryStream ms = new MemoryStream()) + { + int count; + while ((count = inputStream.Read(buf, 0, buf.Length)) > 0) + { + ms.Write(buf, 0, count); + } + return ms.ToArray(); + } + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// String to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Sanitize filename by removing the path + /// + /// Filename + /// Filename + public static string SanitizeFilename(string filename) + { + Match match = Regex.Match(filename, @".*[/\\](.*)$"); + + if (match.Success) + { + return match.Groups[1].Value; + } + else + { + return filename; + } + } + + /// + /// Convert params to key/value pairs. + /// Use collectionFormat to properly format lists and collections. + /// + /// Collection format. + /// Key name. + /// Value object. + /// A list of KeyValuePairs + public IEnumerable> ParameterToKeyValuePairs(string collectionFormat, string name, object value) + { + var parameters = new List>(); + + if (IsCollection(value) && collectionFormat == "multi") + { + var valueCollection = value as IEnumerable; + parameters.AddRange(from object item in valueCollection select new KeyValuePair(name, ParameterToString(item))); + } + else + { + parameters.Add(new KeyValuePair(name, ParameterToString(value))); + } + + return parameters; + } + + /// + /// Check if generic object is a collection. + /// + /// + /// True if object is a collection type + private static bool IsCollection(object value) + { + return value is IList || value is ICollection; + } + } +} diff --git a/other/master-clients/csharp/src/Org.OpenAPITools/Client/ApiException.cs b/other/master-clients/csharp/src/Org.OpenAPITools/Client/ApiException.cs new file mode 100644 index 000000000..9155fa00e --- /dev/null +++ b/other/master-clients/csharp/src/Org.OpenAPITools/Client/ApiException.cs @@ -0,0 +1,60 @@ +/* + * Seaweedfs Master Server API + * + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; + +namespace Org.OpenAPITools.Client +{ + /// + /// API Exception + /// + public class ApiException : Exception + { + /// + /// Gets or sets the error code (HTTP status code) + /// + /// The error code (HTTP status code). + public int ErrorCode { get; set; } + + /// + /// Gets or sets the error content (body json object) + /// + /// The error content (Http response body). + public dynamic ErrorContent { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + public ApiException() {} + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. + public ApiException(int errorCode, string message) : base(message) + { + this.ErrorCode = errorCode; + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. + /// Error content. + public ApiException(int errorCode, string message, dynamic errorContent = null) : base(message) + { + this.ErrorCode = errorCode; + this.ErrorContent = errorContent; + } + } + +} diff --git a/other/master-clients/csharp/src/Org.OpenAPITools/Client/ApiResponse.cs b/other/master-clients/csharp/src/Org.OpenAPITools/Client/ApiResponse.cs new file mode 100644 index 000000000..f9903fd53 --- /dev/null +++ b/other/master-clients/csharp/src/Org.OpenAPITools/Client/ApiResponse.cs @@ -0,0 +1,54 @@ +/* + * Seaweedfs Master Server API + * + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Collections.Generic; + +namespace Org.OpenAPITools.Client +{ + /// + /// API Response + /// + public class ApiResponse + { + /// + /// Gets or sets the status code (HTTP status code) + /// + /// The status code. + public int StatusCode { get; private set; } + + /// + /// Gets or sets the HTTP headers + /// + /// HTTP headers + public IDictionary Headers { get; private set; } + + /// + /// Gets or sets the data (parsed HTTP body) + /// + /// The data. + public T Data { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// HTTP headers. + /// Data (parsed HTTP body) + public ApiResponse(int statusCode, IDictionary headers, T data) + { + this.StatusCode= statusCode; + this.Headers = headers; + this.Data = data; + } + + } + +} diff --git a/other/master-clients/csharp/src/Org.OpenAPITools/Client/Configuration.cs b/other/master-clients/csharp/src/Org.OpenAPITools/Client/Configuration.cs new file mode 100644 index 000000000..9d237b8e4 --- /dev/null +++ b/other/master-clients/csharp/src/Org.OpenAPITools/Client/Configuration.cs @@ -0,0 +1,452 @@ +/* + * Seaweedfs Master Server API + * + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Reflection; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; + +namespace Org.OpenAPITools.Client +{ + /// + /// Represents a set of configuration settings + /// + public class Configuration : IReadableConfiguration + { + #region Constants + + /// + /// Version of the package. + /// + /// Version of the package. + public const string Version = "1.0.0"; + + /// + /// Identifier for ISO 8601 DateTime Format + /// + /// See https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 for more information. + // ReSharper disable once InconsistentNaming + public const string ISO8601_DATETIME_FORMAT = "o"; + + #endregion Constants + + #region Static Members + + private static readonly object GlobalConfigSync = new { }; + private static Configuration _globalConfiguration; + + /// + /// Default creation of exceptions for a given method name and response object + /// + public static readonly ExceptionFactory DefaultExceptionFactory = (methodName, response) => + { + var status = (int)response.StatusCode; + if (status >= 400) + { + return new ApiException(status, + string.Format("Error calling {0}: {1}", methodName, response.Content), + response.Content); + } + if (status == 0) + { + return new ApiException(status, + string.Format("Error calling {0}: {1}", methodName, response.ErrorMessage), response.ErrorMessage); + } + return null; + }; + + /// + /// Gets or sets the default Configuration. + /// + /// Configuration. + public static Configuration Default + { + get { return _globalConfiguration; } + set + { + lock (GlobalConfigSync) + { + _globalConfiguration = value; + } + } + } + + #endregion Static Members + + #region Private Members + + /// + /// Gets or sets the API key based on the authentication name. + /// + /// The API key. + private IDictionary _apiKey = null; + + /// + /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name. + /// + /// The prefix of the API key. + private IDictionary _apiKeyPrefix = null; + + private string _dateTimeFormat = ISO8601_DATETIME_FORMAT; + private string _tempFolderPath = Path.GetTempPath(); + + #endregion Private Members + + #region Constructors + + static Configuration() + { + _globalConfiguration = new GlobalConfiguration(); + } + + /// + /// Initializes a new instance of the class + /// + public Configuration() + { + UserAgent = "OpenAPI-Generator/1.0.0/csharp"; + BasePath = "https://127.0.0.1:9333"; + DefaultHeader = new ConcurrentDictionary(); + ApiKey = new ConcurrentDictionary(); + ApiKeyPrefix = new ConcurrentDictionary(); + + // Setting Timeout has side effects (forces ApiClient creation). + Timeout = 100000; + } + + /// + /// Initializes a new instance of the class + /// + public Configuration( + IDictionary defaultHeader, + IDictionary apiKey, + IDictionary apiKeyPrefix, + string basePath = "https://127.0.0.1:9333") : this() + { + if (string.IsNullOrWhiteSpace(basePath)) + throw new ArgumentException("The provided basePath is invalid.", "basePath"); + if (defaultHeader == null) + throw new ArgumentNullException("defaultHeader"); + if (apiKey == null) + throw new ArgumentNullException("apiKey"); + if (apiKeyPrefix == null) + throw new ArgumentNullException("apiKeyPrefix"); + + BasePath = basePath; + + foreach (var keyValuePair in defaultHeader) + { + DefaultHeader.Add(keyValuePair); + } + + foreach (var keyValuePair in apiKey) + { + ApiKey.Add(keyValuePair); + } + + foreach (var keyValuePair in apiKeyPrefix) + { + ApiKeyPrefix.Add(keyValuePair); + } + } + + /// + /// Initializes a new instance of the class with different settings + /// + /// Api client + /// Dictionary of default HTTP header + /// Username + /// Password + /// accessToken + /// Dictionary of API key + /// Dictionary of API key prefix + /// Temp folder path + /// DateTime format string + /// HTTP connection timeout (in milliseconds) + /// HTTP user agent + [Obsolete("Use explicit object construction and setting of properties.", true)] + public Configuration( + // ReSharper disable UnusedParameter.Local + ApiClient apiClient = null, + IDictionary defaultHeader = null, + string username = null, + string password = null, + string accessToken = null, + IDictionary apiKey = null, + IDictionary apiKeyPrefix = null, + string tempFolderPath = null, + string dateTimeFormat = null, + int timeout = 100000, + string userAgent = "OpenAPI-Generator/1.0.0/csharp" + // ReSharper restore UnusedParameter.Local + ) + { + + } + + /// + /// Initializes a new instance of the Configuration class. + /// + /// Api client. + [Obsolete("This constructor caused unexpected sharing of static data. It is no longer supported.", true)] + // ReSharper disable once UnusedParameter.Local + public Configuration(ApiClient apiClient) + { + + } + + #endregion Constructors + + + #region Properties + + private ApiClient _apiClient = null; + /// + /// Gets an instance of an ApiClient for this configuration + /// + public virtual ApiClient ApiClient + { + get + { + if (_apiClient == null) _apiClient = CreateApiClient(); + return _apiClient; + } + } + + private String _basePath = null; + /// + /// Gets or sets the base path for API access. + /// + public virtual string BasePath { + get { return _basePath; } + set { + _basePath = value; + // pass-through to ApiClient if it's set. + if(_apiClient != null) { + _apiClient.RestClient.BaseUrl = new Uri(_basePath); + } + } + } + + /// + /// Gets or sets the default header. + /// + public virtual IDictionary DefaultHeader { get; set; } + + /// + /// Gets or sets the HTTP timeout (milliseconds) of ApiClient. Default to 100000 milliseconds. + /// + public virtual int Timeout + { + + get { return ApiClient.RestClient.Timeout; } + set { ApiClient.RestClient.Timeout = value; } + } + + /// + /// Gets or sets the HTTP user agent. + /// + /// Http user agent. + public virtual string UserAgent { get; set; } + + /// + /// Gets or sets the username (HTTP basic authentication). + /// + /// The username. + public virtual string Username { get; set; } + + /// + /// Gets or sets the password (HTTP basic authentication). + /// + /// The password. + public virtual string Password { get; set; } + + /// + /// Gets the API key with prefix. + /// + /// API key identifier (authentication scheme). + /// API key with prefix. + public string GetApiKeyWithPrefix(string apiKeyIdentifier) + { + var apiKeyValue = ""; + ApiKey.TryGetValue (apiKeyIdentifier, out apiKeyValue); + var apiKeyPrefix = ""; + if (ApiKeyPrefix.TryGetValue (apiKeyIdentifier, out apiKeyPrefix)) + return apiKeyPrefix + " " + apiKeyValue; + else + return apiKeyValue; + } + + /// + /// Gets or sets the access token for OAuth2 authentication. + /// + /// The access token. + public virtual string AccessToken { get; set; } + + /// + /// Gets or sets the temporary folder path to store the files downloaded from the server. + /// + /// Folder path. + public virtual string TempFolderPath + { + get { return _tempFolderPath; } + + set + { + if (string.IsNullOrEmpty(value)) + { + _tempFolderPath = Path.GetTempPath(); + return; + } + + // create the directory if it does not exist + if (!Directory.Exists(value)) + { + Directory.CreateDirectory(value); + } + + // check if the path contains directory separator at the end + if (value[value.Length - 1] == Path.DirectorySeparatorChar) + { + _tempFolderPath = value; + } + else + { + _tempFolderPath = value + Path.DirectorySeparatorChar; + } + } + } + + /// + /// Gets or sets the date time format used when serializing in the ApiClient + /// By default, it's set to ISO 8601 - "o", for others see: + /// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx + /// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx + /// No validation is done to ensure that the string you're providing is valid + /// + /// The DateTimeFormat string + public virtual string DateTimeFormat + { + get { return _dateTimeFormat; } + set + { + if (string.IsNullOrEmpty(value)) + { + // Never allow a blank or null string, go back to the default + _dateTimeFormat = ISO8601_DATETIME_FORMAT; + return; + } + + // Caution, no validation when you choose date time format other than ISO 8601 + // Take a look at the above links + _dateTimeFormat = value; + } + } + + /// + /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name. + /// + /// The prefix of the API key. + public virtual IDictionary ApiKeyPrefix + { + get { return _apiKeyPrefix; } + set + { + if (value == null) + { + throw new InvalidOperationException("ApiKeyPrefix collection may not be null."); + } + _apiKeyPrefix = value; + } + } + + /// + /// Gets or sets the API key based on the authentication name. + /// + /// The API key. + public virtual IDictionary ApiKey + { + get { return _apiKey; } + set + { + if (value == null) + { + throw new InvalidOperationException("ApiKey collection may not be null."); + } + _apiKey = value; + } + } + + #endregion Properties + + #region Methods + + /// + /// Add default header. + /// + /// Header field name. + /// Header field value. + /// + public void AddDefaultHeader(string key, string value) + { + DefaultHeader[key] = value; + } + + /// + /// Creates a new based on this instance. + /// + /// + public ApiClient CreateApiClient() + { + return new ApiClient(BasePath) { Configuration = this }; + } + + + /// + /// Returns a string with essential information for debugging. + /// + public static String ToDebugReport() + { + String report = "C# SDK (Org.OpenAPITools) Debug Report:\n"; + report += " OS: " + System.Environment.OSVersion + "\n"; + report += " .NET Framework Version: " + System.Environment.Version + "\n"; + report += " Version of the API: 3.43.0\n"; + report += " SDK Package Version: 1.0.0\n"; + + return report; + } + + /// + /// Add Api Key Header. + /// + /// Api Key name. + /// Api Key value. + /// + public void AddApiKey(string key, string value) + { + ApiKey[key] = value; + } + + /// + /// Sets the API key prefix. + /// + /// Api Key name. + /// Api Key value. + public void AddApiKeyPrefix(string key, string value) + { + ApiKeyPrefix[key] = value; + } + + #endregion Methods + } +} diff --git a/other/master-clients/csharp/src/Org.OpenAPITools/Client/ExceptionFactory.cs b/other/master-clients/csharp/src/Org.OpenAPITools/Client/ExceptionFactory.cs new file mode 100644 index 000000000..726a34d0a --- /dev/null +++ b/other/master-clients/csharp/src/Org.OpenAPITools/Client/ExceptionFactory.cs @@ -0,0 +1,24 @@ +/* + * Seaweedfs Master Server API + * + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using RestSharp; + +namespace Org.OpenAPITools.Client +{ + /// + /// A delegate to ExceptionFactory method + /// + /// Method name + /// Response + /// Exceptions + public delegate Exception ExceptionFactory(string methodName, IRestResponse response); +} diff --git a/other/master-clients/csharp/src/Org.OpenAPITools/Client/GlobalConfiguration.cs b/other/master-clients/csharp/src/Org.OpenAPITools/Client/GlobalConfiguration.cs new file mode 100644 index 000000000..528efcce2 --- /dev/null +++ b/other/master-clients/csharp/src/Org.OpenAPITools/Client/GlobalConfiguration.cs @@ -0,0 +1,34 @@ +/* + * Seaweedfs Master Server API + * + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Reflection; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; + +namespace Org.OpenAPITools.Client +{ + /// + /// provides a compile-time extension point for globally configuring + /// API Clients. + /// + /// + /// A customized implementation via partial class may reside in another file and may + /// be excluded from automatic generation via a .openapi-generator-ignore file. + /// + public partial class GlobalConfiguration : Configuration + { + + } +} \ No newline at end of file diff --git a/other/master-clients/csharp/src/Org.OpenAPITools/Client/IApiAccessor.cs b/other/master-clients/csharp/src/Org.OpenAPITools/Client/IApiAccessor.cs new file mode 100644 index 000000000..d8c722d71 --- /dev/null +++ b/other/master-clients/csharp/src/Org.OpenAPITools/Client/IApiAccessor.cs @@ -0,0 +1,42 @@ +/* + * Seaweedfs Master Server API + * + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using RestSharp; + +namespace Org.OpenAPITools.Client +{ + /// + /// Represents configuration aspects required to interact with the API endpoints. + /// + public interface IApiAccessor + { + /// + /// Gets or sets the configuration object + /// + /// An instance of the Configuration + Configuration Configuration {get; set;} + + /// + /// Gets the base path of the API client. + /// + /// The base path + String GetBasePath(); + + /// + /// Provides a factory method hook for the creation of exceptions. + /// + ExceptionFactory ExceptionFactory { get; set; } + } +} diff --git a/other/master-clients/csharp/src/Org.OpenAPITools/Client/IReadableConfiguration.cs b/other/master-clients/csharp/src/Org.OpenAPITools/Client/IReadableConfiguration.cs new file mode 100644 index 000000000..656080695 --- /dev/null +++ b/other/master-clients/csharp/src/Org.OpenAPITools/Client/IReadableConfiguration.cs @@ -0,0 +1,94 @@ +/* + * Seaweedfs Master Server API + * + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System.Collections.Generic; + +namespace Org.OpenAPITools.Client +{ + /// + /// Represents a readable-only configuration contract. + /// + public interface IReadableConfiguration + { + /// + /// Gets the access token. + /// + /// Access token. + string AccessToken { get; } + + /// + /// Gets the API key. + /// + /// API key. + IDictionary ApiKey { get; } + + /// + /// Gets the API key prefix. + /// + /// API key prefix. + IDictionary ApiKeyPrefix { get; } + + /// + /// Gets the base path. + /// + /// Base path. + string BasePath { get; } + + /// + /// Gets the date time format. + /// + /// Date time format. + string DateTimeFormat { get; } + + /// + /// Gets the default header. + /// + /// Default header. + IDictionary DefaultHeader { get; } + + /// + /// Gets the temp folder path. + /// + /// Temp folder path. + string TempFolderPath { get; } + + /// + /// Gets the HTTP connection timeout (in milliseconds) + /// + /// HTTP connection timeout. + int Timeout { get; } + + /// + /// Gets the user agent. + /// + /// User agent. + string UserAgent { get; } + + /// + /// Gets the username. + /// + /// Username. + string Username { get; } + + /// + /// Gets the password. + /// + /// Password. + string Password { get; } + + /// + /// Gets the API key with prefix. + /// + /// API key identifier (authentication scheme). + /// API key with prefix. + string GetApiKeyWithPrefix(string apiKeyIdentifier); + } +} diff --git a/other/master-clients/csharp/src/Org.OpenAPITools/Client/OpenAPIDateConverter.cs b/other/master-clients/csharp/src/Org.OpenAPITools/Client/OpenAPIDateConverter.cs new file mode 100644 index 000000000..c514d7803 --- /dev/null +++ b/other/master-clients/csharp/src/Org.OpenAPITools/Client/OpenAPIDateConverter.cs @@ -0,0 +1,30 @@ +/* + * Seaweedfs Master Server API + * + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using Newtonsoft.Json.Converters; + +namespace Org.OpenAPITools.Client +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class OpenAPIDateConverter : IsoDateTimeConverter + { + /// + /// Initializes a new instance of the class. + /// + public OpenAPIDateConverter() + { + // full-date = date-fullyear "-" date-month "-" date-mday + DateTimeFormat = "yyyy-MM-dd"; + } + } +} diff --git a/other/master-clients/csharp/src/Org.OpenAPITools/Model/FileKey.cs b/other/master-clients/csharp/src/Org.OpenAPITools/Model/FileKey.cs new file mode 100644 index 000000000..7e1986c52 --- /dev/null +++ b/other/master-clients/csharp/src/Org.OpenAPITools/Model/FileKey.cs @@ -0,0 +1,159 @@ +/* + * Seaweedfs Master Server API + * + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; + +namespace Org.OpenAPITools.Model +{ + /// + /// FileKey + /// + [DataContract] + public partial class FileKey : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// count. + /// fid. + /// url. + public FileKey(Object count = default(Object), Object fid = default(Object), Object url = default(Object)) + { + this.Count = count; + this.Fid = fid; + this.Url = url; + this.Count = count; + this.Fid = fid; + this.Url = url; + } + + /// + /// Gets or Sets Count + /// + [DataMember(Name="count", EmitDefaultValue=true)] + public Object Count { get; set; } + + /// + /// Gets or Sets Fid + /// + [DataMember(Name="fid", EmitDefaultValue=true)] + public Object Fid { get; set; } + + /// + /// Gets or Sets Url + /// + [DataMember(Name="url", EmitDefaultValue=true)] + public Object Url { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class FileKey {\n"); + sb.Append(" Count: ").Append(Count).Append("\n"); + sb.Append(" Fid: ").Append(Fid).Append("\n"); + sb.Append(" Url: ").Append(Url).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return this.Equals(input as FileKey); + } + + /// + /// Returns true if FileKey instances are equal + /// + /// Instance of FileKey to be compared + /// Boolean + public bool Equals(FileKey input) + { + if (input == null) + return false; + + return + ( + this.Count == input.Count || + (this.Count != null && + this.Count.Equals(input.Count)) + ) && + ( + this.Fid == input.Fid || + (this.Fid != null && + this.Fid.Equals(input.Fid)) + ) && + ( + this.Url == input.Url || + (this.Url != null && + this.Url.Equals(input.Url)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.Count != null) + hashCode = hashCode * 59 + this.Count.GetHashCode(); + if (this.Fid != null) + hashCode = hashCode * 59 + this.Fid.GetHashCode(); + if (this.Url != null) + hashCode = hashCode * 59 + this.Url.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/other/master-clients/csharp/src/Org.OpenAPITools/Model/Location.cs b/other/master-clients/csharp/src/Org.OpenAPITools/Model/Location.cs new file mode 100644 index 000000000..7f02cbe55 --- /dev/null +++ b/other/master-clients/csharp/src/Org.OpenAPITools/Model/Location.cs @@ -0,0 +1,142 @@ +/* + * Seaweedfs Master Server API + * + * The Seaweedfs Master Server API allows you to store blobs + * + * The version of the OpenAPI document: 3.43.0 + * + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; + +namespace Org.OpenAPITools.Model +{ + /// + /// Location + /// + [DataContract] + public partial class Location : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// publicUrl. + /// url. + public Location(Object publicUrl = default(Object), Object url = default(Object)) + { + this.PublicUrl = publicUrl; + this.Url = url; + this.PublicUrl = publicUrl; + this.Url = url; + } + + /// + /// Gets or Sets PublicUrl + /// + [DataMember(Name="publicUrl", EmitDefaultValue=true)] + public Object PublicUrl { get; set; } + + /// + /// Gets or Sets Url + /// + [DataMember(Name="url", EmitDefaultValue=true)] + public Object Url { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class Location {\n"); + sb.Append(" PublicUrl: ").Append(PublicUrl).Append("\n"); + sb.Append(" Url: ").Append(Url).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return this.Equals(input as Location); + } + + /// + /// Returns true if Location instances are equal + /// + /// Instance of Location to be compared + /// Boolean + public bool Equals(Location input) + { + if (input == null) + return false; + + return + ( + this.PublicUrl == input.PublicUrl || + (this.PublicUrl != null && + this.PublicUrl.Equals(input.PublicUrl)) + ) && + ( + this.Url == input.Url || + (this.Url != null && + this.Url.Equals(input.Url)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.PublicUrl != null) + hashCode = hashCode * 59 + this.PublicUrl.GetHashCode(); + if (this.Url != null) + hashCode = hashCode * 59 + this.Url.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/other/master-clients/csharp/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/other/master-clients/csharp/src/Org.OpenAPITools/Org.OpenAPITools.csproj new file mode 100644 index 000000000..4e3794dca --- /dev/null +++ b/other/master-clients/csharp/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -0,0 +1,79 @@ + + + + + + Debug + AnyCPU + {BC7B99B9-DA58-46D9-BFF5-76505068ECE5} + Library + Properties + Org.OpenAPITools + Org.OpenAPITools + v4.5 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + bin\Debug\Org.OpenAPITools.xml + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + bin\Release\Org.OpenAPITools.xml + + + + + + + + + + + + + $(SolutionDir)\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll + ..\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll + ..\..\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll + ..\..\vendor\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll + + + $(SolutionDir)\packages\JsonSubTypes.1.6.0\lib\net45\JsonSubTypes.dll + ..\packages\JsonSubTypes.1.6.0\lib\net45\JsonSubTypes.dll + ..\..\packages\JsonSubTypes.1.6.0\lib\net45\JsonSubTypes.dll + ..\..\vendor\JsonSubTypes.1.6.0\lib\net45\JsonSubTypes.dll + + + $(SolutionDir)\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll + ..\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll + ..\..\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll + ..\..\vendor\RestSharp.105.1.0\lib\net45\RestSharp.dll + + + + + + + + + + diff --git a/other/master-clients/csharp/src/Org.OpenAPITools/Org.OpenAPITools.nuspec b/other/master-clients/csharp/src/Org.OpenAPITools/Org.OpenAPITools.nuspec new file mode 100644 index 000000000..8d30d56e3 --- /dev/null +++ b/other/master-clients/csharp/src/Org.OpenAPITools/Org.OpenAPITools.nuspec @@ -0,0 +1,41 @@ + + + + + $id$ + OpenAPI Library + + + $version$ + + + $author$ + + + $author$ + false + false + + + A library generated from a OpenAPI doc + http://localhost + + + + + + + + + + + + + + + + + + diff --git a/other/master-clients/csharp/src/Org.OpenAPITools/Properties/AssemblyInfo.cs b/other/master-clients/csharp/src/Org.OpenAPITools/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..d1abdf793 --- /dev/null +++ b/other/master-clients/csharp/src/Org.OpenAPITools/Properties/AssemblyInfo.cs @@ -0,0 +1,32 @@ +using System.Reflection; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("OpenAPI Library")] +[assembly: AssemblyDescription("A library generated from a OpenAPI doc")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("OpenAPI")] +[assembly: AssemblyProduct("OpenAPILibrary")] +[assembly: AssemblyCopyright("No Copyright")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0")] +[assembly: AssemblyFileVersion("1.0.0")] diff --git a/other/master-clients/csharp/src/Org.OpenAPITools/packages.config b/other/master-clients/csharp/src/Org.OpenAPITools/packages.config new file mode 100644 index 000000000..a3a1bab35 --- /dev/null +++ b/other/master-clients/csharp/src/Org.OpenAPITools/packages.config @@ -0,0 +1,7 @@ + + + + + + + diff --git a/other/master-clients/go/.gitignore b/other/master-clients/go/.gitignore new file mode 100644 index 000000000..daf913b1b --- /dev/null +++ b/other/master-clients/go/.gitignore @@ -0,0 +1,24 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof diff --git a/other/master-clients/go/.openapi-generator-ignore b/other/master-clients/go/.openapi-generator-ignore new file mode 100644 index 000000000..7484ee590 --- /dev/null +++ b/other/master-clients/go/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/other/master-clients/go/.openapi-generator/FILES b/other/master-clients/go/.openapi-generator/FILES new file mode 100644 index 000000000..3a1521f36 --- /dev/null +++ b/other/master-clients/go/.openapi-generator/FILES @@ -0,0 +1,19 @@ +.gitignore +.openapi-generator-ignore +.travis.yml +README.md +api/openapi.yaml +api_default.go +client.go +configuration.go +docs/DefaultApi.md +docs/FileKey.md +docs/Location.md +git_push.sh +go.mod +go.sum +model_file_key.go +model_location.go +response.go +test/api_default_test.go +utils.go diff --git a/other/master-clients/go/.openapi-generator/VERSION b/other/master-clients/go/.openapi-generator/VERSION new file mode 100644 index 000000000..c0be8a799 --- /dev/null +++ b/other/master-clients/go/.openapi-generator/VERSION @@ -0,0 +1 @@ +6.4.0 \ No newline at end of file diff --git a/other/master-clients/go/.travis.yml b/other/master-clients/go/.travis.yml new file mode 100644 index 000000000..f5cb2ce9a --- /dev/null +++ b/other/master-clients/go/.travis.yml @@ -0,0 +1,8 @@ +language: go + +install: + - go get -d -v . + +script: + - go build -v ./ + diff --git a/other/master-clients/go/README.md b/other/master-clients/go/README.md new file mode 100644 index 000000000..0a6a93dfb --- /dev/null +++ b/other/master-clients/go/README.md @@ -0,0 +1,114 @@ +# Go API client for openapi + +The Seaweedfs Master Server API allows you to store blobs + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [OpenAPI-spec](https://www.openapis.org/) from a remote server, you can easily generate an API client. + +- API version: 3.43.0 +- Package version: 1.0.0 +- Build package: org.openapitools.codegen.languages.GoClientCodegen + +## Installation + +Install the following dependencies: + +```shell +go get github.com/stretchr/testify/assert +go get golang.org/x/net/context +``` + +Put the package under your project folder and add the following in import: + +```golang +import openapi "github.com/GIT_USER_ID/GIT_REPO_ID" +``` + +To use a proxy, set the environment variable `HTTP_PROXY`: + +```golang +os.Setenv("HTTP_PROXY", "http://proxy_name:proxy_port") +``` + +## Configuration of Server URL + +Default configuration comes with `Servers` field that contains server objects as defined in the OpenAPI specification. + +### Select Server Configuration + +For using other server than the one defined on index 0 set context value `sw.ContextServerIndex` of type `int`. + +```golang +ctx := context.WithValue(context.Background(), openapi.ContextServerIndex, 1) +``` + +### Templated Server URL + +Templated server URL is formatted using default variables from configuration or from context value `sw.ContextServerVariables` of type `map[string]string`. + +```golang +ctx := context.WithValue(context.Background(), openapi.ContextServerVariables, map[string]string{ + "basePath": "v2", +}) +``` + +Note, enum values are always validated and all unused variables are silently ignored. + +### URLs Configuration per Operation + +Each operation can use different server URL defined using `OperationServers` map in the `Configuration`. +An operation is uniquely identified by `"{classname}Service.{nickname}"` string. +Similar rules for overriding default operation server index and variables applies by using `sw.ContextOperationServerIndices` and `sw.ContextOperationServerVariables` context maps. + +```golang +ctx := context.WithValue(context.Background(), openapi.ContextOperationServerIndices, map[string]int{ + "{classname}Service.{nickname}": 2, +}) +ctx = context.WithValue(context.Background(), openapi.ContextOperationServerVariables, map[string]map[string]string{ + "{classname}Service.{nickname}": { + "port": "8443", + }, +}) +``` + +## Documentation for API Endpoints + +All URIs are relative to *https://127.0.0.1:9333* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*DefaultApi* | [**DirAssign**](docs/DefaultApi.md#dirassign) | **Get** /dir/assign | Assign a file key +*DefaultApi* | [**DirLookup**](docs/DefaultApi.md#dirlookup) | **Get** /dir/lookup | Lookup volume + + +## Documentation For Models + + - [FileKey](docs/FileKey.md) + - [Location](docs/Location.md) + + +## Documentation For Authorization + + Endpoints do not require authorization. + + +## Documentation for Utility Methods + +Due to the fact that model structure members are all pointers, this package contains +a number of utility functions to easily obtain pointers to values of basic types. +Each of these functions takes a value of the given basic type and returns a pointer to it: + +* `PtrBool` +* `PtrInt` +* `PtrInt32` +* `PtrInt64` +* `PtrFloat` +* `PtrFloat32` +* `PtrFloat64` +* `PtrString` +* `PtrTime` + +## Author + + + diff --git a/other/master-clients/go/api/openapi.yaml b/other/master-clients/go/api/openapi.yaml new file mode 100644 index 000000000..6682ed3b7 --- /dev/null +++ b/other/master-clients/go/api/openapi.yaml @@ -0,0 +1,174 @@ +openapi: 3.1.0 +info: + description: The Seaweedfs Master Server API allows you to store blobs + title: Seaweedfs Master Server API + version: 3.43.0 +servers: +- url: https://127.0.0.1:9333/ +paths: + /dir/assign: + get: + description: This operation is very cheap. Just increase a number in master + server's memory. + operationId: dirAssign + parameters: + - description: "how many file ids to assign. Use _1, _2 for the assigned\ + \ additional file ids. e.g. 3,01637037d6_1, 3,01637037d6_2" + explode: true + in: query + name: count + required: false + schema: + format: int32 + style: form + - description: required collection name + explode: true + in: query + name: collection + required: false + schema: {} + style: form + - description: preferred data center + explode: true + in: query + name: dataCenter + required: false + schema: {} + style: form + - description: preferred rack + explode: true + in: query + name: rack + required: false + schema: {} + style: form + - description: "preferred volume server, e.g. 127.0.0.1:8080" + explode: true + in: query + name: dataNode + required: false + schema: {} + style: form + - description: "If you have disks labelled, this must be supplied to specify\ + \ the disk type to allocate on." + explode: true + in: query + name: disk + required: false + schema: {} + style: form + - description: replica placement strategy + explode: true + in: query + name: replication + required: false + schema: {} + style: form + - description: "file expiration time limit, example: 3m for 3 minutes. units:\ + \ m-minute, h-hour, d-day, w-week, M-month, y-year" + explode: true + in: query + name: ttl + required: false + schema: {} + style: form + - description: "If no matching volumes, pre-allocate this number of bytes on\ + \ disk for new volumes." + explode: true + in: query + name: preallocate + required: false + schema: + format: int64 + style: form + - description: Only implemented for windows. Use memory mapped files with specified + size for new volumes. + explode: true + in: query + name: memoryMapMaxSizeMb + required: false + schema: + format: int32 + style: form + - description: "If no matching volumes, create specified number of new volumes." + explode: true + in: query + name: writableVolumeCount + required: false + schema: + format: int32 + style: form + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/FileKey' + description: successful operation + summary: Assign a file key + /dir/lookup: + get: + description: We would need to find out whether the volumes have moved. + operationId: dirLookup + parameters: + - description: volume id + explode: true + in: query + name: volumeId + required: false + schema: + format: int32 + style: form + - description: optionally to speed up the lookup + explode: true + in: query + name: collection + required: false + schema: {} + style: form + - description: "If provided, this returns the fileId location and a JWT to update\ + \ or delete the file." + explode: true + in: query + name: fileId + required: false + schema: {} + style: form + - description: "works together with \"fileId\", if read=yes, JWT is generated\ + \ for reads." + explode: true + in: query + name: read + required: false + schema: {} + style: form + responses: + "200": + content: + application/json: + schema: + items: + $ref: '#/components/schemas/Location' + description: successful operation + summary: Lookup volume +components: + schemas: + FileKey: + example: + fid: "3,01637037d6" + count: 10 + url: 127.0.0.1:8080 + properties: + count: + example: 10 + format: int64 + fid: + example: "3,01637037d6" + url: + example: 127.0.0.1:8080 + Location: + properties: + publicUrl: + example: localhost:8080 + url: + example: localhost:8080 diff --git a/other/master-clients/go/api_default.go b/other/master-clients/go/api_default.go new file mode 100644 index 000000000..077473207 --- /dev/null +++ b/other/master-clients/go/api_default.go @@ -0,0 +1,372 @@ +/* +Seaweedfs Master Server API + +The Seaweedfs Master Server API allows you to store blobs + +API version: 3.43.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "io" + "net/http" + "net/url" +) + +// DefaultApiService DefaultApi service +type DefaultApiService service + +type ApiDirAssignRequest struct { + ctx context.Context + ApiService *DefaultApiService + count *interface{} + collection *interface{} + dataCenter *interface{} + rack *interface{} + dataNode *interface{} + disk *interface{} + replication *interface{} + ttl *interface{} + preallocate *interface{} + memoryMapMaxSizeMb *interface{} + writableVolumeCount *interface{} +} + +// how many file ids to assign. Use <fid>_1, <fid>_2 for the assigned additional file ids. e.g. 3,01637037d6_1, 3,01637037d6_2 +func (r ApiDirAssignRequest) Count(count interface{}) ApiDirAssignRequest { + r.count = &count + return r +} + +// required collection name +func (r ApiDirAssignRequest) Collection(collection interface{}) ApiDirAssignRequest { + r.collection = &collection + return r +} + +// preferred data center +func (r ApiDirAssignRequest) DataCenter(dataCenter interface{}) ApiDirAssignRequest { + r.dataCenter = &dataCenter + return r +} + +// preferred rack +func (r ApiDirAssignRequest) Rack(rack interface{}) ApiDirAssignRequest { + r.rack = &rack + return r +} + +// preferred volume server, e.g. 127.0.0.1:8080 +func (r ApiDirAssignRequest) DataNode(dataNode interface{}) ApiDirAssignRequest { + r.dataNode = &dataNode + return r +} + +// If you have disks labelled, this must be supplied to specify the disk type to allocate on. +func (r ApiDirAssignRequest) Disk(disk interface{}) ApiDirAssignRequest { + r.disk = &disk + return r +} + +// replica placement strategy +func (r ApiDirAssignRequest) Replication(replication interface{}) ApiDirAssignRequest { + r.replication = &replication + return r +} + +// file expiration time limit, example: 3m for 3 minutes. units: m-minute, h-hour, d-day, w-week, M-month, y-year +func (r ApiDirAssignRequest) Ttl(ttl interface{}) ApiDirAssignRequest { + r.ttl = &ttl + return r +} + +// If no matching volumes, pre-allocate this number of bytes on disk for new volumes. +func (r ApiDirAssignRequest) Preallocate(preallocate interface{}) ApiDirAssignRequest { + r.preallocate = &preallocate + return r +} + +// Only implemented for windows. Use memory mapped files with specified size for new volumes. +func (r ApiDirAssignRequest) MemoryMapMaxSizeMb(memoryMapMaxSizeMb interface{}) ApiDirAssignRequest { + r.memoryMapMaxSizeMb = &memoryMapMaxSizeMb + return r +} + +// If no matching volumes, create specified number of new volumes. +func (r ApiDirAssignRequest) WritableVolumeCount(writableVolumeCount interface{}) ApiDirAssignRequest { + r.writableVolumeCount = &writableVolumeCount + return r +} + +func (r ApiDirAssignRequest) Execute() (*FileKey, *http.Response, error) { + return r.ApiService.DirAssignExecute(r) +} + +/* +DirAssign Assign a file key + +This operation is very cheap. Just increase a number in master server's memory. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiDirAssignRequest +*/ +func (a *DefaultApiService) DirAssign(ctx context.Context) ApiDirAssignRequest { + return ApiDirAssignRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +// +// @return FileKey +func (a *DefaultApiService) DirAssignExecute(r ApiDirAssignRequest) (*FileKey, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *FileKey + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "DefaultApiService.DirAssign") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/dir/assign" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.count != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "count", r.count, "") + } + if r.collection != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "collection", r.collection, "") + } + if r.dataCenter != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "dataCenter", r.dataCenter, "") + } + if r.rack != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "rack", r.rack, "") + } + if r.dataNode != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "dataNode", r.dataNode, "") + } + if r.disk != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "disk", r.disk, "") + } + if r.replication != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "replication", r.replication, "") + } + if r.ttl != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "ttl", r.ttl, "") + } + if r.preallocate != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "preallocate", r.preallocate, "") + } + if r.memoryMapMaxSizeMb != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "memoryMapMaxSizeMb", r.memoryMapMaxSizeMb, "") + } + if r.writableVolumeCount != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "writableVolumeCount", r.writableVolumeCount, "") + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiDirLookupRequest struct { + ctx context.Context + ApiService *DefaultApiService + volumeId *interface{} + collection *interface{} + fileId *interface{} + read *interface{} +} + +// volume id +func (r ApiDirLookupRequest) VolumeId(volumeId interface{}) ApiDirLookupRequest { + r.volumeId = &volumeId + return r +} + +// optionally to speed up the lookup +func (r ApiDirLookupRequest) Collection(collection interface{}) ApiDirLookupRequest { + r.collection = &collection + return r +} + +// If provided, this returns the fileId location and a JWT to update or delete the file. +func (r ApiDirLookupRequest) FileId(fileId interface{}) ApiDirLookupRequest { + r.fileId = &fileId + return r +} + +// works together with \"fileId\", if read=yes, JWT is generated for reads. +func (r ApiDirLookupRequest) Read(read interface{}) ApiDirLookupRequest { + r.read = &read + return r +} + +func (r ApiDirLookupRequest) Execute() (interface{}, *http.Response, error) { + return r.ApiService.DirLookupExecute(r) +} + +/* +DirLookup Lookup volume + +We would need to find out whether the volumes have moved. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiDirLookupRequest +*/ +func (a *DefaultApiService) DirLookup(ctx context.Context) ApiDirLookupRequest { + return ApiDirLookupRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +// +// @return interface{} +func (a *DefaultApiService) DirLookupExecute(r ApiDirLookupRequest) (interface{}, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue interface{} + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "DefaultApiService.DirLookup") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/dir/lookup" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.volumeId != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "volumeId", r.volumeId, "") + } + if r.collection != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "collection", r.collection, "") + } + if r.fileId != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "fileId", r.fileId, "") + } + if r.read != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "read", r.read, "") + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/other/master-clients/go/client.go b/other/master-clients/go/client.go new file mode 100644 index 000000000..59b45502e --- /dev/null +++ b/other/master-clients/go/client.go @@ -0,0 +1,654 @@ +/* +Seaweedfs Master Server API + +The Seaweedfs Master Server API allows you to store blobs + +API version: 3.43.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "encoding/json" + "encoding/xml" + "errors" + "fmt" + "io" + "log" + "mime/multipart" + "net/http" + "net/http/httputil" + "net/url" + "os" + "path/filepath" + "reflect" + "regexp" + "strconv" + "strings" + "time" + "unicode/utf8" +) + +var ( + jsonCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:vnd\.[^;]+\+)?json)`) + xmlCheck = regexp.MustCompile(`(?i:(?:application|text)/xml)`) + queryParamSplit = regexp.MustCompile(`(^|&)([^&]+)`) + queryDescape = strings.NewReplacer("%5B", "[", "%5D", "]") +) + +// APIClient manages communication with the Seaweedfs Master Server API API v3.43.0 +// In most cases there should be only one, shared, APIClient. +type APIClient struct { + cfg *Configuration + common service // Reuse a single struct instead of allocating one for each service on the heap. + + // API Services + + DefaultApi *DefaultApiService +} + +type service struct { + client *APIClient +} + +// NewAPIClient creates a new API client. Requires a userAgent string describing your application. +// optionally a custom http.Client to allow for advanced features such as caching. +func NewAPIClient(cfg *Configuration) *APIClient { + if cfg.HTTPClient == nil { + cfg.HTTPClient = http.DefaultClient + } + + c := &APIClient{} + c.cfg = cfg + c.common.client = c + + // API Services + c.DefaultApi = (*DefaultApiService)(&c.common) + + return c +} + +func atoi(in string) (int, error) { + return strconv.Atoi(in) +} + +// selectHeaderContentType select a content type from the available list. +func selectHeaderContentType(contentTypes []string) string { + if len(contentTypes) == 0 { + return "" + } + if contains(contentTypes, "application/json") { + return "application/json" + } + return contentTypes[0] // use the first content type specified in 'consumes' +} + +// selectHeaderAccept join all accept types and return +func selectHeaderAccept(accepts []string) string { + if len(accepts) == 0 { + return "" + } + + if contains(accepts, "application/json") { + return "application/json" + } + + return strings.Join(accepts, ",") +} + +// contains is a case insensitive match, finding needle in a haystack +func contains(haystack []string, needle string) bool { + for _, a := range haystack { + if strings.EqualFold(a, needle) { + return true + } + } + return false +} + +// Verify optional parameters are of the correct type. +func typeCheckParameter(obj interface{}, expected string, name string) error { + // Make sure there is an object. + if obj == nil { + return nil + } + + // Check the type is as expected. + if reflect.TypeOf(obj).String() != expected { + return fmt.Errorf("expected %s to be of type %s but received %s", name, expected, reflect.TypeOf(obj).String()) + } + return nil +} + +func parameterValueToString(obj interface{}, key string) string { + if reflect.TypeOf(obj).Kind() != reflect.Ptr { + return fmt.Sprintf("%v", obj) + } + var param, ok = obj.(MappedNullable) + if !ok { + return "" + } + dataMap, err := param.ToMap() + if err != nil { + return "" + } + return fmt.Sprintf("%v", dataMap[key]) +} + +// parameterAddToHeaderOrQuery adds the provided object to the request header or url query +// supporting deep object syntax +func parameterAddToHeaderOrQuery(headerOrQueryParams interface{}, keyPrefix string, obj interface{}, collectionType string) { + var v = reflect.ValueOf(obj) + var value = "" + if v == reflect.ValueOf(nil) { + value = "null" + } else { + switch v.Kind() { + case reflect.Invalid: + value = "invalid" + + case reflect.Struct: + if t, ok := obj.(MappedNullable); ok { + dataMap, err := t.ToMap() + if err != nil { + return + } + parameterAddToHeaderOrQuery(headerOrQueryParams, keyPrefix, dataMap, collectionType) + return + } + if t, ok := obj.(time.Time); ok { + parameterAddToHeaderOrQuery(headerOrQueryParams, keyPrefix, t.Format(time.RFC3339), collectionType) + return + } + value = v.Type().String() + " value" + case reflect.Slice: + var indValue = reflect.ValueOf(obj) + if indValue == reflect.ValueOf(nil) { + return + } + var lenIndValue = indValue.Len() + for i := 0; i < lenIndValue; i++ { + var arrayValue = indValue.Index(i) + parameterAddToHeaderOrQuery(headerOrQueryParams, keyPrefix, arrayValue.Interface(), collectionType) + } + return + + case reflect.Map: + var indValue = reflect.ValueOf(obj) + if indValue == reflect.ValueOf(nil) { + return + } + iter := indValue.MapRange() + for iter.Next() { + k, v := iter.Key(), iter.Value() + parameterAddToHeaderOrQuery(headerOrQueryParams, fmt.Sprintf("%s[%s]", keyPrefix, k.String()), v.Interface(), collectionType) + } + return + + case reflect.Interface: + fallthrough + case reflect.Ptr: + parameterAddToHeaderOrQuery(headerOrQueryParams, keyPrefix, v.Elem().Interface(), collectionType) + return + + case reflect.Int, reflect.Int8, reflect.Int16, + reflect.Int32, reflect.Int64: + value = strconv.FormatInt(v.Int(), 10) + case reflect.Uint, reflect.Uint8, reflect.Uint16, + reflect.Uint32, reflect.Uint64, reflect.Uintptr: + value = strconv.FormatUint(v.Uint(), 10) + case reflect.Float32, reflect.Float64: + value = strconv.FormatFloat(v.Float(), 'g', -1, 32) + case reflect.Bool: + value = strconv.FormatBool(v.Bool()) + case reflect.String: + value = v.String() + default: + value = v.Type().String() + " value" + } + } + + switch valuesMap := headerOrQueryParams.(type) { + case url.Values: + if collectionType == "csv" && valuesMap.Get(keyPrefix) != "" { + valuesMap.Set(keyPrefix, valuesMap.Get(keyPrefix)+","+value) + } else { + valuesMap.Add(keyPrefix, value) + } + break + case map[string]string: + valuesMap[keyPrefix] = value + break + } +} + +// helper for converting interface{} parameters to json strings +func parameterToJson(obj interface{}) (string, error) { + jsonBuf, err := json.Marshal(obj) + if err != nil { + return "", err + } + return string(jsonBuf), err +} + +// callAPI do the request. +func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) { + if c.cfg.Debug { + dump, err := httputil.DumpRequestOut(request, true) + if err != nil { + return nil, err + } + log.Printf("\n%s\n", string(dump)) + } + + resp, err := c.cfg.HTTPClient.Do(request) + if err != nil { + return resp, err + } + + if c.cfg.Debug { + dump, err := httputil.DumpResponse(resp, true) + if err != nil { + return resp, err + } + log.Printf("\n%s\n", string(dump)) + } + return resp, err +} + +// Allow modification of underlying config for alternate implementations and testing +// Caution: modifying the configuration while live can cause data races and potentially unwanted behavior +func (c *APIClient) GetConfig() *Configuration { + return c.cfg +} + +type formFile struct { + fileBytes []byte + fileName string + formFileName string +} + +// prepareRequest build the request +func (c *APIClient) prepareRequest( + ctx context.Context, + path string, method string, + postBody interface{}, + headerParams map[string]string, + queryParams url.Values, + formParams url.Values, + formFiles []formFile) (localVarRequest *http.Request, err error) { + + var body *bytes.Buffer + + // Detect postBody type and post. + if postBody != nil { + contentType := headerParams["Content-Type"] + if contentType == "" { + contentType = detectContentType(postBody) + headerParams["Content-Type"] = contentType + } + + body, err = setBody(postBody, contentType) + if err != nil { + return nil, err + } + } + + // add form parameters and file if available. + if strings.HasPrefix(headerParams["Content-Type"], "multipart/form-data") && len(formParams) > 0 || (len(formFiles) > 0) { + if body != nil { + return nil, errors.New("Cannot specify postBody and multipart form at the same time.") + } + body = &bytes.Buffer{} + w := multipart.NewWriter(body) + + for k, v := range formParams { + for _, iv := range v { + if strings.HasPrefix(k, "@") { // file + err = addFile(w, k[1:], iv) + if err != nil { + return nil, err + } + } else { // form value + w.WriteField(k, iv) + } + } + } + for _, formFile := range formFiles { + if len(formFile.fileBytes) > 0 && formFile.fileName != "" { + w.Boundary() + part, err := w.CreateFormFile(formFile.formFileName, filepath.Base(formFile.fileName)) + if err != nil { + return nil, err + } + _, err = part.Write(formFile.fileBytes) + if err != nil { + return nil, err + } + } + } + + // Set the Boundary in the Content-Type + headerParams["Content-Type"] = w.FormDataContentType() + + // Set Content-Length + headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) + w.Close() + } + + if strings.HasPrefix(headerParams["Content-Type"], "application/x-www-form-urlencoded") && len(formParams) > 0 { + if body != nil { + return nil, errors.New("Cannot specify postBody and x-www-form-urlencoded form at the same time.") + } + body = &bytes.Buffer{} + body.WriteString(formParams.Encode()) + // Set Content-Length + headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) + } + + // Setup path and query parameters + url, err := url.Parse(path) + if err != nil { + return nil, err + } + + // Override request host, if applicable + if c.cfg.Host != "" { + url.Host = c.cfg.Host + } + + // Override request scheme, if applicable + if c.cfg.Scheme != "" { + url.Scheme = c.cfg.Scheme + } + + // Adding Query Param + query := url.Query() + for k, v := range queryParams { + for _, iv := range v { + query.Add(k, iv) + } + } + + // Encode the parameters. + url.RawQuery = queryParamSplit.ReplaceAllStringFunc(query.Encode(), func(s string) string { + pieces := strings.Split(s, "=") + pieces[0] = queryDescape.Replace(pieces[0]) + return strings.Join(pieces, "=") + }) + + // Generate a new request + if body != nil { + localVarRequest, err = http.NewRequest(method, url.String(), body) + } else { + localVarRequest, err = http.NewRequest(method, url.String(), nil) + } + if err != nil { + return nil, err + } + + // add header parameters, if any + if len(headerParams) > 0 { + headers := http.Header{} + for h, v := range headerParams { + headers[h] = []string{v} + } + localVarRequest.Header = headers + } + + // Add the user agent to the request. + localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent) + + if ctx != nil { + // add context to the request + localVarRequest = localVarRequest.WithContext(ctx) + + // Walk through any authentication. + + } + + for header, value := range c.cfg.DefaultHeader { + localVarRequest.Header.Add(header, value) + } + return localVarRequest, nil +} + +func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err error) { + if len(b) == 0 { + return nil + } + if s, ok := v.(*string); ok { + *s = string(b) + return nil + } + if f, ok := v.(*os.File); ok { + f, err = os.CreateTemp("", "HttpClientFile") + if err != nil { + return + } + _, err = f.Write(b) + if err != nil { + return + } + _, err = f.Seek(0, io.SeekStart) + return + } + if f, ok := v.(**os.File); ok { + *f, err = os.CreateTemp("", "HttpClientFile") + if err != nil { + return + } + _, err = (*f).Write(b) + if err != nil { + return + } + _, err = (*f).Seek(0, io.SeekStart) + return + } + if xmlCheck.MatchString(contentType) { + if err = xml.Unmarshal(b, v); err != nil { + return err + } + return nil + } + if jsonCheck.MatchString(contentType) { + if actualObj, ok := v.(interface{ GetActualInstance() interface{} }); ok { // oneOf, anyOf schemas + if unmarshalObj, ok := actualObj.(interface{ UnmarshalJSON([]byte) error }); ok { // make sure it has UnmarshalJSON defined + if err = unmarshalObj.UnmarshalJSON(b); err != nil { + return err + } + } else { + return errors.New("Unknown type with GetActualInstance but no unmarshalObj.UnmarshalJSON defined") + } + } else if err = json.Unmarshal(b, v); err != nil { // simple model + return err + } + return nil + } + return errors.New("undefined response type") +} + +// Add a file to the multipart request +func addFile(w *multipart.Writer, fieldName, path string) error { + file, err := os.Open(filepath.Clean(path)) + if err != nil { + return err + } + err = file.Close() + if err != nil { + return err + } + + part, err := w.CreateFormFile(fieldName, filepath.Base(path)) + if err != nil { + return err + } + _, err = io.Copy(part, file) + + return err +} + +// Prevent trying to import "fmt" +func reportError(format string, a ...interface{}) error { + return fmt.Errorf(format, a...) +} + +// A wrapper for strict JSON decoding +func newStrictDecoder(data []byte) *json.Decoder { + dec := json.NewDecoder(bytes.NewBuffer(data)) + dec.DisallowUnknownFields() + return dec +} + +// Set request body from an interface{} +func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) { + if bodyBuf == nil { + bodyBuf = &bytes.Buffer{} + } + + if reader, ok := body.(io.Reader); ok { + _, err = bodyBuf.ReadFrom(reader) + } else if fp, ok := body.(*os.File); ok { + _, err = bodyBuf.ReadFrom(fp) + } else if b, ok := body.([]byte); ok { + _, err = bodyBuf.Write(b) + } else if s, ok := body.(string); ok { + _, err = bodyBuf.WriteString(s) + } else if s, ok := body.(*string); ok { + _, err = bodyBuf.WriteString(*s) + } else if jsonCheck.MatchString(contentType) { + err = json.NewEncoder(bodyBuf).Encode(body) + } else if xmlCheck.MatchString(contentType) { + err = xml.NewEncoder(bodyBuf).Encode(body) + } + + if err != nil { + return nil, err + } + + if bodyBuf.Len() == 0 { + err = fmt.Errorf("invalid body type %s\n", contentType) + return nil, err + } + return bodyBuf, nil +} + +// detectContentType method is used to figure out `Request.Body` content type for request header +func detectContentType(body interface{}) string { + contentType := "text/plain; charset=utf-8" + kind := reflect.TypeOf(body).Kind() + + switch kind { + case reflect.Struct, reflect.Map, reflect.Ptr: + contentType = "application/json; charset=utf-8" + case reflect.String: + contentType = "text/plain; charset=utf-8" + default: + if b, ok := body.([]byte); ok { + contentType = http.DetectContentType(b) + } else if kind == reflect.Slice { + contentType = "application/json; charset=utf-8" + } + } + + return contentType +} + +// Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go +type cacheControl map[string]string + +func parseCacheControl(headers http.Header) cacheControl { + cc := cacheControl{} + ccHeader := headers.Get("Cache-Control") + for _, part := range strings.Split(ccHeader, ",") { + part = strings.Trim(part, " ") + if part == "" { + continue + } + if strings.ContainsRune(part, '=') { + keyval := strings.Split(part, "=") + cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",") + } else { + cc[part] = "" + } + } + return cc +} + +// CacheExpires helper function to determine remaining time before repeating a request. +func CacheExpires(r *http.Response) time.Time { + // Figure out when the cache expires. + var expires time.Time + now, err := time.Parse(time.RFC1123, r.Header.Get("date")) + if err != nil { + return time.Now() + } + respCacheControl := parseCacheControl(r.Header) + + if maxAge, ok := respCacheControl["max-age"]; ok { + lifetime, err := time.ParseDuration(maxAge + "s") + if err != nil { + expires = now + } else { + expires = now.Add(lifetime) + } + } else { + expiresHeader := r.Header.Get("Expires") + if expiresHeader != "" { + expires, err = time.Parse(time.RFC1123, expiresHeader) + if err != nil { + expires = now + } + } + } + return expires +} + +func strlen(s string) int { + return utf8.RuneCountInString(s) +} + +// GenericOpenAPIError Provides access to the body, error and model on returned errors. +type GenericOpenAPIError struct { + body []byte + error string + model interface{} +} + +// Error returns non-empty string if there was an error. +func (e GenericOpenAPIError) Error() string { + return e.error +} + +// Body returns the raw bytes of the response +func (e GenericOpenAPIError) Body() []byte { + return e.body +} + +// Model returns the unpacked model of the error +func (e GenericOpenAPIError) Model() interface{} { + return e.model +} + +// format error message using title and detail when model implements rfc7807 +func formatErrorMessage(status string, v interface{}) string { + str := "" + metaValue := reflect.ValueOf(v).Elem() + + field := metaValue.FieldByName("Title") + if field != (reflect.Value{}) { + str = fmt.Sprintf("%s", field.Interface()) + } + + field = metaValue.FieldByName("Detail") + if field != (reflect.Value{}) { + str = fmt.Sprintf("%s (%s)", str, field.Interface()) + } + + // status title (detail) + return strings.TrimSpace(fmt.Sprintf("%s %s", status, str)) +} diff --git a/other/master-clients/go/configuration.go b/other/master-clients/go/configuration.go new file mode 100644 index 000000000..d569449ef --- /dev/null +++ b/other/master-clients/go/configuration.go @@ -0,0 +1,214 @@ +/* +Seaweedfs Master Server API + +The Seaweedfs Master Server API allows you to store blobs + +API version: 3.43.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "context" + "fmt" + "net/http" + "strings" +) + +// contextKeys are used to identify the type of value in the context. +// Since these are string, it is possible to get a short description of the +// context key for logging and debugging using key.String(). + +type contextKey string + +func (c contextKey) String() string { + return "auth " + string(c) +} + +var ( + // ContextServerIndex uses a server configuration from the index. + ContextServerIndex = contextKey("serverIndex") + + // ContextOperationServerIndices uses a server configuration from the index mapping. + ContextOperationServerIndices = contextKey("serverOperationIndices") + + // ContextServerVariables overrides a server configuration variables. + ContextServerVariables = contextKey("serverVariables") + + // ContextOperationServerVariables overrides a server configuration variables using operation specific values. + ContextOperationServerVariables = contextKey("serverOperationVariables") +) + +// BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth +type BasicAuth struct { + UserName string `json:"userName,omitempty"` + Password string `json:"password,omitempty"` +} + +// APIKey provides API key based authentication to a request passed via context using ContextAPIKey +type APIKey struct { + Key string + Prefix string +} + +// ServerVariable stores the information about a server variable +type ServerVariable struct { + Description string + DefaultValue string + EnumValues []string +} + +// ServerConfiguration stores the information about a server +type ServerConfiguration struct { + URL string + Description string + Variables map[string]ServerVariable +} + +// ServerConfigurations stores multiple ServerConfiguration items +type ServerConfigurations []ServerConfiguration + +// Configuration stores the configuration of the API client +type Configuration struct { + Host string `json:"host,omitempty"` + Scheme string `json:"scheme,omitempty"` + DefaultHeader map[string]string `json:"defaultHeader,omitempty"` + UserAgent string `json:"userAgent,omitempty"` + Debug bool `json:"debug,omitempty"` + Servers ServerConfigurations + OperationServers map[string]ServerConfigurations + HTTPClient *http.Client +} + +// NewConfiguration returns a new Configuration object +func NewConfiguration() *Configuration { + cfg := &Configuration{ + DefaultHeader: make(map[string]string), + UserAgent: "OpenAPI-Generator/1.0.0/go", + Debug: false, + Servers: ServerConfigurations{ + { + URL: "https://127.0.0.1:9333", + Description: "No description provided", + }, + }, + OperationServers: map[string]ServerConfigurations{}, + } + return cfg +} + +// AddDefaultHeader adds a new HTTP header to the default header in the request +func (c *Configuration) AddDefaultHeader(key string, value string) { + c.DefaultHeader[key] = value +} + +// URL formats template on a index using given variables +func (sc ServerConfigurations) URL(index int, variables map[string]string) (string, error) { + if index < 0 || len(sc) <= index { + return "", fmt.Errorf("index %v out of range %v", index, len(sc)-1) + } + server := sc[index] + url := server.URL + + // go through variables and replace placeholders + for name, variable := range server.Variables { + if value, ok := variables[name]; ok { + found := bool(len(variable.EnumValues) == 0) + for _, enumValue := range variable.EnumValues { + if value == enumValue { + found = true + } + } + if !found { + return "", fmt.Errorf("the variable %s in the server URL has invalid value %v. Must be %v", name, value, variable.EnumValues) + } + url = strings.Replace(url, "{"+name+"}", value, -1) + } else { + url = strings.Replace(url, "{"+name+"}", variable.DefaultValue, -1) + } + } + return url, nil +} + +// ServerURL returns URL based on server settings +func (c *Configuration) ServerURL(index int, variables map[string]string) (string, error) { + return c.Servers.URL(index, variables) +} + +func getServerIndex(ctx context.Context) (int, error) { + si := ctx.Value(ContextServerIndex) + if si != nil { + if index, ok := si.(int); ok { + return index, nil + } + return 0, reportError("Invalid type %T should be int", si) + } + return 0, nil +} + +func getServerOperationIndex(ctx context.Context, endpoint string) (int, error) { + osi := ctx.Value(ContextOperationServerIndices) + if osi != nil { + if operationIndices, ok := osi.(map[string]int); !ok { + return 0, reportError("Invalid type %T should be map[string]int", osi) + } else { + index, ok := operationIndices[endpoint] + if ok { + return index, nil + } + } + } + return getServerIndex(ctx) +} + +func getServerVariables(ctx context.Context) (map[string]string, error) { + sv := ctx.Value(ContextServerVariables) + if sv != nil { + if variables, ok := sv.(map[string]string); ok { + return variables, nil + } + return nil, reportError("ctx value of ContextServerVariables has invalid type %T should be map[string]string", sv) + } + return nil, nil +} + +func getServerOperationVariables(ctx context.Context, endpoint string) (map[string]string, error) { + osv := ctx.Value(ContextOperationServerVariables) + if osv != nil { + if operationVariables, ok := osv.(map[string]map[string]string); !ok { + return nil, reportError("ctx value of ContextOperationServerVariables has invalid type %T should be map[string]map[string]string", osv) + } else { + variables, ok := operationVariables[endpoint] + if ok { + return variables, nil + } + } + } + return getServerVariables(ctx) +} + +// ServerURLWithContext returns a new server URL given an endpoint +func (c *Configuration) ServerURLWithContext(ctx context.Context, endpoint string) (string, error) { + sc, ok := c.OperationServers[endpoint] + if !ok { + sc = c.Servers + } + + if ctx == nil { + return sc.URL(0, nil) + } + + index, err := getServerOperationIndex(ctx, endpoint) + if err != nil { + return "", err + } + + variables, err := getServerOperationVariables(ctx, endpoint) + if err != nil { + return "", err + } + + return sc.URL(index, variables) +} diff --git a/other/master-clients/go/docs/DefaultApi.md b/other/master-clients/go/docs/DefaultApi.md new file mode 100644 index 000000000..f199089e8 --- /dev/null +++ b/other/master-clients/go/docs/DefaultApi.md @@ -0,0 +1,168 @@ +# \DefaultApi + +All URIs are relative to *https://127.0.0.1:9333* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**DirAssign**](DefaultApi.md#DirAssign) | **Get** /dir/assign | Assign a file key +[**DirLookup**](DefaultApi.md#DirLookup) | **Get** /dir/lookup | Lookup volume + + + +## DirAssign + +> FileKey DirAssign(ctx).Count(count).Collection(collection).DataCenter(dataCenter).Rack(rack).DataNode(dataNode).Disk(disk).Replication(replication).Ttl(ttl).Preallocate(preallocate).MemoryMapMaxSizeMb(memoryMapMaxSizeMb).WritableVolumeCount(writableVolumeCount).Execute() + +Assign a file key + + + +### Example + +```go +package main + +import ( + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" +) + +func main() { + count := TODO // interface{} | how many file ids to assign. Use _1, _2 for the assigned additional file ids. e.g. 3,01637037d6_1, 3,01637037d6_2 (optional) + collection := TODO // interface{} | required collection name (optional) + dataCenter := TODO // interface{} | preferred data center (optional) + rack := TODO // interface{} | preferred rack (optional) + dataNode := TODO // interface{} | preferred volume server, e.g. 127.0.0.1:8080 (optional) + disk := TODO // interface{} | If you have disks labelled, this must be supplied to specify the disk type to allocate on. (optional) + replication := TODO // interface{} | replica placement strategy (optional) + ttl := TODO // interface{} | file expiration time limit, example: 3m for 3 minutes. units: m-minute, h-hour, d-day, w-week, M-month, y-year (optional) + preallocate := TODO // interface{} | If no matching volumes, pre-allocate this number of bytes on disk for new volumes. (optional) + memoryMapMaxSizeMb := TODO // interface{} | Only implemented for windows. Use memory mapped files with specified size for new volumes. (optional) + writableVolumeCount := TODO // interface{} | If no matching volumes, create specified number of new volumes. (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.DefaultApi.DirAssign(context.Background()).Count(count).Collection(collection).DataCenter(dataCenter).Rack(rack).DataNode(dataNode).Disk(disk).Replication(replication).Ttl(ttl).Preallocate(preallocate).MemoryMapMaxSizeMb(memoryMapMaxSizeMb).WritableVolumeCount(writableVolumeCount).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `DefaultApi.DirAssign``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `DirAssign`: FileKey + fmt.Fprintf(os.Stdout, "Response from `DefaultApi.DirAssign`: %v\n", resp) +} +``` + +### Path Parameters + + + +### Other Parameters + +Other parameters are passed through a pointer to a apiDirAssignRequest struct via the builder pattern + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **count** | [**interface{}**](interface{}.md) | how many file ids to assign. Use <fid>_1, <fid>_2 for the assigned additional file ids. e.g. 3,01637037d6_1, 3,01637037d6_2 | + **collection** | [**interface{}**](interface{}.md) | required collection name | + **dataCenter** | [**interface{}**](interface{}.md) | preferred data center | + **rack** | [**interface{}**](interface{}.md) | preferred rack | + **dataNode** | [**interface{}**](interface{}.md) | preferred volume server, e.g. 127.0.0.1:8080 | + **disk** | [**interface{}**](interface{}.md) | If you have disks labelled, this must be supplied to specify the disk type to allocate on. | + **replication** | [**interface{}**](interface{}.md) | replica placement strategy | + **ttl** | [**interface{}**](interface{}.md) | file expiration time limit, example: 3m for 3 minutes. units: m-minute, h-hour, d-day, w-week, M-month, y-year | + **preallocate** | [**interface{}**](interface{}.md) | If no matching volumes, pre-allocate this number of bytes on disk for new volumes. | + **memoryMapMaxSizeMb** | [**interface{}**](interface{}.md) | Only implemented for windows. Use memory mapped files with specified size for new volumes. | + **writableVolumeCount** | [**interface{}**](interface{}.md) | If no matching volumes, create specified number of new volumes. | + +### Return type + +[**FileKey**](FileKey.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) +[[Back to Model list]](../README.md#documentation-for-models) +[[Back to README]](../README.md) + + +## DirLookup + +> interface{} DirLookup(ctx).VolumeId(volumeId).Collection(collection).FileId(fileId).Read(read).Execute() + +Lookup volume + + + +### Example + +```go +package main + +import ( + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" +) + +func main() { + volumeId := TODO // interface{} | volume id (optional) + collection := TODO // interface{} | optionally to speed up the lookup (optional) + fileId := TODO // interface{} | If provided, this returns the fileId location and a JWT to update or delete the file. (optional) + read := TODO // interface{} | works together with \"fileId\", if read=yes, JWT is generated for reads. (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.DefaultApi.DirLookup(context.Background()).VolumeId(volumeId).Collection(collection).FileId(fileId).Read(read).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `DefaultApi.DirLookup``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `DirLookup`: interface{} + fmt.Fprintf(os.Stdout, "Response from `DefaultApi.DirLookup`: %v\n", resp) +} +``` + +### Path Parameters + + + +### Other Parameters + +Other parameters are passed through a pointer to a apiDirLookupRequest struct via the builder pattern + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **volumeId** | [**interface{}**](interface{}.md) | volume id | + **collection** | [**interface{}**](interface{}.md) | optionally to speed up the lookup | + **fileId** | [**interface{}**](interface{}.md) | If provided, this returns the fileId location and a JWT to update or delete the file. | + **read** | [**interface{}**](interface{}.md) | works together with \"fileId\", if read=yes, JWT is generated for reads. | + +### Return type + +**interface{}** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) +[[Back to Model list]](../README.md#documentation-for-models) +[[Back to README]](../README.md) + diff --git a/other/master-clients/go/docs/FileKey.md b/other/master-clients/go/docs/FileKey.md new file mode 100644 index 000000000..f888ff18b --- /dev/null +++ b/other/master-clients/go/docs/FileKey.md @@ -0,0 +1,138 @@ +# FileKey + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Count** | Pointer to **interface{}** | | [optional] +**Fid** | Pointer to **interface{}** | | [optional] +**Url** | Pointer to **interface{}** | | [optional] + +## Methods + +### NewFileKey + +`func NewFileKey() *FileKey` + +NewFileKey instantiates a new FileKey object +This constructor will assign default values to properties that have it defined, +and makes sure properties required by API are set, but the set of arguments +will change when the set of required properties is changed + +### NewFileKeyWithDefaults + +`func NewFileKeyWithDefaults() *FileKey` + +NewFileKeyWithDefaults instantiates a new FileKey object +This constructor will only assign default values to properties that have it defined, +but it doesn't guarantee that properties required by API are set + +### GetCount + +`func (o *FileKey) GetCount() interface{}` + +GetCount returns the Count field if non-nil, zero value otherwise. + +### GetCountOk + +`func (o *FileKey) GetCountOk() (*interface{}, bool)` + +GetCountOk returns a tuple with the Count field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### SetCount + +`func (o *FileKey) SetCount(v interface{})` + +SetCount sets Count field to given value. + +### HasCount + +`func (o *FileKey) HasCount() bool` + +HasCount returns a boolean if a field has been set. + +### SetCountNil + +`func (o *FileKey) SetCountNil(b bool)` + + SetCountNil sets the value for Count to be an explicit nil + +### UnsetCount +`func (o *FileKey) UnsetCount()` + +UnsetCount ensures that no value is present for Count, not even an explicit nil +### GetFid + +`func (o *FileKey) GetFid() interface{}` + +GetFid returns the Fid field if non-nil, zero value otherwise. + +### GetFidOk + +`func (o *FileKey) GetFidOk() (*interface{}, bool)` + +GetFidOk returns a tuple with the Fid field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### SetFid + +`func (o *FileKey) SetFid(v interface{})` + +SetFid sets Fid field to given value. + +### HasFid + +`func (o *FileKey) HasFid() bool` + +HasFid returns a boolean if a field has been set. + +### SetFidNil + +`func (o *FileKey) SetFidNil(b bool)` + + SetFidNil sets the value for Fid to be an explicit nil + +### UnsetFid +`func (o *FileKey) UnsetFid()` + +UnsetFid ensures that no value is present for Fid, not even an explicit nil +### GetUrl + +`func (o *FileKey) GetUrl() interface{}` + +GetUrl returns the Url field if non-nil, zero value otherwise. + +### GetUrlOk + +`func (o *FileKey) GetUrlOk() (*interface{}, bool)` + +GetUrlOk returns a tuple with the Url field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### SetUrl + +`func (o *FileKey) SetUrl(v interface{})` + +SetUrl sets Url field to given value. + +### HasUrl + +`func (o *FileKey) HasUrl() bool` + +HasUrl returns a boolean if a field has been set. + +### SetUrlNil + +`func (o *FileKey) SetUrlNil(b bool)` + + SetUrlNil sets the value for Url to be an explicit nil + +### UnsetUrl +`func (o *FileKey) UnsetUrl()` + +UnsetUrl ensures that no value is present for Url, not even an explicit nil + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/other/master-clients/go/docs/Location.md b/other/master-clients/go/docs/Location.md new file mode 100644 index 000000000..02448614e --- /dev/null +++ b/other/master-clients/go/docs/Location.md @@ -0,0 +1,102 @@ +# Location + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**PublicUrl** | Pointer to **interface{}** | | [optional] +**Url** | Pointer to **interface{}** | | [optional] + +## Methods + +### NewLocation + +`func NewLocation() *Location` + +NewLocation instantiates a new Location object +This constructor will assign default values to properties that have it defined, +and makes sure properties required by API are set, but the set of arguments +will change when the set of required properties is changed + +### NewLocationWithDefaults + +`func NewLocationWithDefaults() *Location` + +NewLocationWithDefaults instantiates a new Location object +This constructor will only assign default values to properties that have it defined, +but it doesn't guarantee that properties required by API are set + +### GetPublicUrl + +`func (o *Location) GetPublicUrl() interface{}` + +GetPublicUrl returns the PublicUrl field if non-nil, zero value otherwise. + +### GetPublicUrlOk + +`func (o *Location) GetPublicUrlOk() (*interface{}, bool)` + +GetPublicUrlOk returns a tuple with the PublicUrl field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### SetPublicUrl + +`func (o *Location) SetPublicUrl(v interface{})` + +SetPublicUrl sets PublicUrl field to given value. + +### HasPublicUrl + +`func (o *Location) HasPublicUrl() bool` + +HasPublicUrl returns a boolean if a field has been set. + +### SetPublicUrlNil + +`func (o *Location) SetPublicUrlNil(b bool)` + + SetPublicUrlNil sets the value for PublicUrl to be an explicit nil + +### UnsetPublicUrl +`func (o *Location) UnsetPublicUrl()` + +UnsetPublicUrl ensures that no value is present for PublicUrl, not even an explicit nil +### GetUrl + +`func (o *Location) GetUrl() interface{}` + +GetUrl returns the Url field if non-nil, zero value otherwise. + +### GetUrlOk + +`func (o *Location) GetUrlOk() (*interface{}, bool)` + +GetUrlOk returns a tuple with the Url field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### SetUrl + +`func (o *Location) SetUrl(v interface{})` + +SetUrl sets Url field to given value. + +### HasUrl + +`func (o *Location) HasUrl() bool` + +HasUrl returns a boolean if a field has been set. + +### SetUrlNil + +`func (o *Location) SetUrlNil(b bool)` + + SetUrlNil sets the value for Url to be an explicit nil + +### UnsetUrl +`func (o *Location) UnsetUrl()` + +UnsetUrl ensures that no value is present for Url, not even an explicit nil + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/other/master-clients/go/git_push.sh b/other/master-clients/go/git_push.sh new file mode 100644 index 000000000..f53a75d4f --- /dev/null +++ b/other/master-clients/go/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/other/master-clients/go/go.mod b/other/master-clients/go/go.mod new file mode 100644 index 000000000..7fca7eee9 --- /dev/null +++ b/other/master-clients/go/go.mod @@ -0,0 +1,6 @@ +module github.com/GIT_USER_ID/GIT_REPO_ID + +go 1.18 + +require ( +) diff --git a/other/master-clients/go/go.sum b/other/master-clients/go/go.sum new file mode 100644 index 000000000..c966c8ddf --- /dev/null +++ b/other/master-clients/go/go.sum @@ -0,0 +1,11 @@ +cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e h1:bRhVy7zSSasaqNksaRZiA5EEI+Ei4I1nO5Jh72wfHlg= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4 h1:YUO/7uOKsKeq9UokNS62b8FYywz3ker1l1vDZRCRefw= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +google.golang.org/appengine v1.4.0 h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= diff --git a/other/master-clients/go/model_file_key.go b/other/master-clients/go/model_file_key.go new file mode 100644 index 000000000..af5fbca2b --- /dev/null +++ b/other/master-clients/go/model_file_key.go @@ -0,0 +1,199 @@ +/* +Seaweedfs Master Server API + +The Seaweedfs Master Server API allows you to store blobs + +API version: 3.43.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "encoding/json" +) + +// checks if the FileKey type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &FileKey{} + +// FileKey struct for FileKey +type FileKey struct { + Count interface{} `json:"count,omitempty"` + Fid interface{} `json:"fid,omitempty"` + Url interface{} `json:"url,omitempty"` +} + +// NewFileKey instantiates a new FileKey object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewFileKey() *FileKey { + this := FileKey{} + return &this +} + +// NewFileKeyWithDefaults instantiates a new FileKey object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewFileKeyWithDefaults() *FileKey { + this := FileKey{} + return &this +} + +// GetCount returns the Count field value if set, zero value otherwise (both if not set or set to explicit null). +func (o *FileKey) GetCount() interface{} { + if o == nil { + var ret interface{} + return ret + } + return o.Count +} + +// GetCountOk returns a tuple with the Count field value if set, nil otherwise +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *FileKey) GetCountOk() (*interface{}, bool) { + if o == nil || IsNil(o.Count) { + return nil, false + } + return &o.Count, true +} + +// HasCount returns a boolean if a field has been set. +func (o *FileKey) HasCount() bool { + if o != nil && IsNil(o.Count) { + return true + } + + return false +} + +// SetCount gets a reference to the given interface{} and assigns it to the Count field. +func (o *FileKey) SetCount(v interface{}) { + o.Count = v +} + +// GetFid returns the Fid field value if set, zero value otherwise (both if not set or set to explicit null). +func (o *FileKey) GetFid() interface{} { + if o == nil { + var ret interface{} + return ret + } + return o.Fid +} + +// GetFidOk returns a tuple with the Fid field value if set, nil otherwise +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *FileKey) GetFidOk() (*interface{}, bool) { + if o == nil || IsNil(o.Fid) { + return nil, false + } + return &o.Fid, true +} + +// HasFid returns a boolean if a field has been set. +func (o *FileKey) HasFid() bool { + if o != nil && IsNil(o.Fid) { + return true + } + + return false +} + +// SetFid gets a reference to the given interface{} and assigns it to the Fid field. +func (o *FileKey) SetFid(v interface{}) { + o.Fid = v +} + +// GetUrl returns the Url field value if set, zero value otherwise (both if not set or set to explicit null). +func (o *FileKey) GetUrl() interface{} { + if o == nil { + var ret interface{} + return ret + } + return o.Url +} + +// GetUrlOk returns a tuple with the Url field value if set, nil otherwise +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *FileKey) GetUrlOk() (*interface{}, bool) { + if o == nil || IsNil(o.Url) { + return nil, false + } + return &o.Url, true +} + +// HasUrl returns a boolean if a field has been set. +func (o *FileKey) HasUrl() bool { + if o != nil && IsNil(o.Url) { + return true + } + + return false +} + +// SetUrl gets a reference to the given interface{} and assigns it to the Url field. +func (o *FileKey) SetUrl(v interface{}) { + o.Url = v +} + +func (o FileKey) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o FileKey) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if o.Count != nil { + toSerialize["count"] = o.Count + } + if o.Fid != nil { + toSerialize["fid"] = o.Fid + } + if o.Url != nil { + toSerialize["url"] = o.Url + } + return toSerialize, nil +} + +type NullableFileKey struct { + value *FileKey + isSet bool +} + +func (v NullableFileKey) Get() *FileKey { + return v.value +} + +func (v *NullableFileKey) Set(val *FileKey) { + v.value = val + v.isSet = true +} + +func (v NullableFileKey) IsSet() bool { + return v.isSet +} + +func (v *NullableFileKey) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableFileKey(val *FileKey) *NullableFileKey { + return &NullableFileKey{value: val, isSet: true} +} + +func (v NullableFileKey) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableFileKey) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/other/master-clients/go/model_location.go b/other/master-clients/go/model_location.go new file mode 100644 index 000000000..daa112237 --- /dev/null +++ b/other/master-clients/go/model_location.go @@ -0,0 +1,162 @@ +/* +Seaweedfs Master Server API + +The Seaweedfs Master Server API allows you to store blobs + +API version: 3.43.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "encoding/json" +) + +// checks if the Location type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &Location{} + +// Location struct for Location +type Location struct { + PublicUrl interface{} `json:"publicUrl,omitempty"` + Url interface{} `json:"url,omitempty"` +} + +// NewLocation instantiates a new Location object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewLocation() *Location { + this := Location{} + return &this +} + +// NewLocationWithDefaults instantiates a new Location object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewLocationWithDefaults() *Location { + this := Location{} + return &this +} + +// GetPublicUrl returns the PublicUrl field value if set, zero value otherwise (both if not set or set to explicit null). +func (o *Location) GetPublicUrl() interface{} { + if o == nil { + var ret interface{} + return ret + } + return o.PublicUrl +} + +// GetPublicUrlOk returns a tuple with the PublicUrl field value if set, nil otherwise +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *Location) GetPublicUrlOk() (*interface{}, bool) { + if o == nil || IsNil(o.PublicUrl) { + return nil, false + } + return &o.PublicUrl, true +} + +// HasPublicUrl returns a boolean if a field has been set. +func (o *Location) HasPublicUrl() bool { + if o != nil && IsNil(o.PublicUrl) { + return true + } + + return false +} + +// SetPublicUrl gets a reference to the given interface{} and assigns it to the PublicUrl field. +func (o *Location) SetPublicUrl(v interface{}) { + o.PublicUrl = v +} + +// GetUrl returns the Url field value if set, zero value otherwise (both if not set or set to explicit null). +func (o *Location) GetUrl() interface{} { + if o == nil { + var ret interface{} + return ret + } + return o.Url +} + +// GetUrlOk returns a tuple with the Url field value if set, nil otherwise +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *Location) GetUrlOk() (*interface{}, bool) { + if o == nil || IsNil(o.Url) { + return nil, false + } + return &o.Url, true +} + +// HasUrl returns a boolean if a field has been set. +func (o *Location) HasUrl() bool { + if o != nil && IsNil(o.Url) { + return true + } + + return false +} + +// SetUrl gets a reference to the given interface{} and assigns it to the Url field. +func (o *Location) SetUrl(v interface{}) { + o.Url = v +} + +func (o Location) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o Location) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if o.PublicUrl != nil { + toSerialize["publicUrl"] = o.PublicUrl + } + if o.Url != nil { + toSerialize["url"] = o.Url + } + return toSerialize, nil +} + +type NullableLocation struct { + value *Location + isSet bool +} + +func (v NullableLocation) Get() *Location { + return v.value +} + +func (v *NullableLocation) Set(val *Location) { + v.value = val + v.isSet = true +} + +func (v NullableLocation) IsSet() bool { + return v.isSet +} + +func (v *NullableLocation) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableLocation(val *Location) *NullableLocation { + return &NullableLocation{value: val, isSet: true} +} + +func (v NullableLocation) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableLocation) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/other/master-clients/go/response.go b/other/master-clients/go/response.go new file mode 100644 index 000000000..b83a380d8 --- /dev/null +++ b/other/master-clients/go/response.go @@ -0,0 +1,47 @@ +/* +Seaweedfs Master Server API + +The Seaweedfs Master Server API allows you to store blobs + +API version: 3.43.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "net/http" +) + +// APIResponse stores the API response returned by the server. +type APIResponse struct { + *http.Response `json:"-"` + Message string `json:"message,omitempty"` + // Operation is the name of the OpenAPI operation. + Operation string `json:"operation,omitempty"` + // RequestURL is the request URL. This value is always available, even if the + // embedded *http.Response is nil. + RequestURL string `json:"url,omitempty"` + // Method is the HTTP method used for the request. This value is always + // available, even if the embedded *http.Response is nil. + Method string `json:"method,omitempty"` + // Payload holds the contents of the response body (which may be nil or empty). + // This is provided here as the raw response.Body() reader will have already + // been drained. + Payload []byte `json:"-"` +} + +// NewAPIResponse returns a new APIResponse object. +func NewAPIResponse(r *http.Response) *APIResponse { + + response := &APIResponse{Response: r} + return response +} + +// NewAPIResponseWithError returns a new APIResponse object with the provided error message. +func NewAPIResponseWithError(errorMessage string) *APIResponse { + + response := &APIResponse{Message: errorMessage} + return response +} diff --git a/other/master-clients/go/test/api_default_test.go b/other/master-clients/go/test/api_default_test.go new file mode 100644 index 000000000..d48e3d8c7 --- /dev/null +++ b/other/master-clients/go/test/api_default_test.go @@ -0,0 +1,49 @@ +/* +Seaweedfs Master Server API + +Testing DefaultApiService + +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); + +package openapi + +import ( + "context" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "testing" +) + +func Test_openapi_DefaultApiService(t *testing.T) { + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + + t.Run("Test DefaultApiService DirAssign", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.DefaultApi.DirAssign(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test DefaultApiService DirLookup", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.DefaultApi.DirLookup(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + +} diff --git a/other/master-clients/go/utils.go b/other/master-clients/go/utils.go new file mode 100644 index 000000000..890002cc1 --- /dev/null +++ b/other/master-clients/go/utils.go @@ -0,0 +1,347 @@ +/* +Seaweedfs Master Server API + +The Seaweedfs Master Server API allows you to store blobs + +API version: 3.43.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "encoding/json" + "reflect" + "time" +) + +// PtrBool is a helper routine that returns a pointer to given boolean value. +func PtrBool(v bool) *bool { return &v } + +// PtrInt is a helper routine that returns a pointer to given integer value. +func PtrInt(v int) *int { return &v } + +// PtrInt32 is a helper routine that returns a pointer to given integer value. +func PtrInt32(v int32) *int32 { return &v } + +// PtrInt64 is a helper routine that returns a pointer to given integer value. +func PtrInt64(v int64) *int64 { return &v } + +// PtrFloat32 is a helper routine that returns a pointer to given float value. +func PtrFloat32(v float32) *float32 { return &v } + +// PtrFloat64 is a helper routine that returns a pointer to given float value. +func PtrFloat64(v float64) *float64 { return &v } + +// PtrString is a helper routine that returns a pointer to given string value. +func PtrString(v string) *string { return &v } + +// PtrTime is helper routine that returns a pointer to given Time value. +func PtrTime(v time.Time) *time.Time { return &v } + +type NullableBool struct { + value *bool + isSet bool +} + +func (v NullableBool) Get() *bool { + return v.value +} + +func (v *NullableBool) Set(val *bool) { + v.value = val + v.isSet = true +} + +func (v NullableBool) IsSet() bool { + return v.isSet +} + +func (v *NullableBool) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableBool(val *bool) *NullableBool { + return &NullableBool{value: val, isSet: true} +} + +func (v NullableBool) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableBool) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableInt struct { + value *int + isSet bool +} + +func (v NullableInt) Get() *int { + return v.value +} + +func (v *NullableInt) Set(val *int) { + v.value = val + v.isSet = true +} + +func (v NullableInt) IsSet() bool { + return v.isSet +} + +func (v *NullableInt) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableInt(val *int) *NullableInt { + return &NullableInt{value: val, isSet: true} +} + +func (v NullableInt) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableInt) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableInt32 struct { + value *int32 + isSet bool +} + +func (v NullableInt32) Get() *int32 { + return v.value +} + +func (v *NullableInt32) Set(val *int32) { + v.value = val + v.isSet = true +} + +func (v NullableInt32) IsSet() bool { + return v.isSet +} + +func (v *NullableInt32) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableInt32(val *int32) *NullableInt32 { + return &NullableInt32{value: val, isSet: true} +} + +func (v NullableInt32) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableInt32) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableInt64 struct { + value *int64 + isSet bool +} + +func (v NullableInt64) Get() *int64 { + return v.value +} + +func (v *NullableInt64) Set(val *int64) { + v.value = val + v.isSet = true +} + +func (v NullableInt64) IsSet() bool { + return v.isSet +} + +func (v *NullableInt64) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableInt64(val *int64) *NullableInt64 { + return &NullableInt64{value: val, isSet: true} +} + +func (v NullableInt64) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableInt64) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableFloat32 struct { + value *float32 + isSet bool +} + +func (v NullableFloat32) Get() *float32 { + return v.value +} + +func (v *NullableFloat32) Set(val *float32) { + v.value = val + v.isSet = true +} + +func (v NullableFloat32) IsSet() bool { + return v.isSet +} + +func (v *NullableFloat32) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableFloat32(val *float32) *NullableFloat32 { + return &NullableFloat32{value: val, isSet: true} +} + +func (v NullableFloat32) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableFloat32) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableFloat64 struct { + value *float64 + isSet bool +} + +func (v NullableFloat64) Get() *float64 { + return v.value +} + +func (v *NullableFloat64) Set(val *float64) { + v.value = val + v.isSet = true +} + +func (v NullableFloat64) IsSet() bool { + return v.isSet +} + +func (v *NullableFloat64) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableFloat64(val *float64) *NullableFloat64 { + return &NullableFloat64{value: val, isSet: true} +} + +func (v NullableFloat64) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableFloat64) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableString struct { + value *string + isSet bool +} + +func (v NullableString) Get() *string { + return v.value +} + +func (v *NullableString) Set(val *string) { + v.value = val + v.isSet = true +} + +func (v NullableString) IsSet() bool { + return v.isSet +} + +func (v *NullableString) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableString(val *string) *NullableString { + return &NullableString{value: val, isSet: true} +} + +func (v NullableString) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableString) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableTime struct { + value *time.Time + isSet bool +} + +func (v NullableTime) Get() *time.Time { + return v.value +} + +func (v *NullableTime) Set(val *time.Time) { + v.value = val + v.isSet = true +} + +func (v NullableTime) IsSet() bool { + return v.isSet +} + +func (v *NullableTime) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableTime(val *time.Time) *NullableTime { + return &NullableTime{value: val, isSet: true} +} + +func (v NullableTime) MarshalJSON() ([]byte, error) { + return v.value.MarshalJSON() +} + +func (v *NullableTime) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +// IsNil checks if an input is nil +func IsNil(i interface{}) bool { + if i == nil { + return true + } + switch reflect.TypeOf(i).Kind() { + case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.UnsafePointer, reflect.Interface, reflect.Slice: + return reflect.ValueOf(i).IsNil() + case reflect.Array: + return reflect.ValueOf(i).IsZero() + } + return false +} + +type MappedNullable interface { + ToMap() (map[string]interface{}, error) +} diff --git a/other/master-clients/php/.gitignore b/other/master-clients/php/.gitignore new file mode 100644 index 000000000..9f1681c2b --- /dev/null +++ b/other/master-clients/php/.gitignore @@ -0,0 +1,15 @@ +# ref: https://github.com/github/gitignore/blob/master/Composer.gitignore + +composer.phar +/vendor/ + +# Commit your application's lock file https://getcomposer.org/doc/01-basic-usage.md#commit-your-composer-lock-file-to-version-control +# You may choose to ignore a library lock file http://getcomposer.org/doc/02-libraries.md#lock-file +# composer.lock + +# php-cs-fixer cache +.php_cs.cache +.php-cs-fixer.cache + +# PHPUnit cache +.phpunit.result.cache diff --git a/other/master-clients/php/.openapi-generator-ignore b/other/master-clients/php/.openapi-generator-ignore new file mode 100644 index 000000000..7484ee590 --- /dev/null +++ b/other/master-clients/php/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/other/master-clients/php/.openapi-generator/FILES b/other/master-clients/php/.openapi-generator/FILES new file mode 100644 index 000000000..3a57c2eea --- /dev/null +++ b/other/master-clients/php/.openapi-generator/FILES @@ -0,0 +1,22 @@ +.gitignore +.openapi-generator-ignore +.php-cs-fixer.dist.php +.travis.yml +README.md +composer.json +docs/Api/DefaultApi.md +docs/Model/FileKey.md +docs/Model/Location.md +git_push.sh +lib/Api/DefaultApi.php +lib/ApiException.php +lib/Configuration.php +lib/HeaderSelector.php +lib/Model/FileKey.php +lib/Model/Location.php +lib/Model/ModelInterface.php +lib/ObjectSerializer.php +phpunit.xml.dist +test/Api/DefaultApiTest.php +test/Model/FileKeyTest.php +test/Model/LocationTest.php diff --git a/other/master-clients/php/.openapi-generator/VERSION b/other/master-clients/php/.openapi-generator/VERSION new file mode 100644 index 000000000..c0be8a799 --- /dev/null +++ b/other/master-clients/php/.openapi-generator/VERSION @@ -0,0 +1 @@ +6.4.0 \ No newline at end of file diff --git a/other/master-clients/php/.php-cs-fixer.dist.php b/other/master-clients/php/.php-cs-fixer.dist.php new file mode 100644 index 000000000..af9cf39fd --- /dev/null +++ b/other/master-clients/php/.php-cs-fixer.dist.php @@ -0,0 +1,29 @@ +in(__DIR__) + ->exclude('vendor') + ->exclude('test') + ->exclude('tests') +; + +$config = new PhpCsFixer\Config(); +return $config->setRules([ + '@PSR12' => true, + 'phpdoc_order' => true, + 'array_syntax' => [ 'syntax' => 'short' ], + 'strict_comparison' => true, + 'strict_param' => true, + 'no_trailing_whitespace' => false, + 'no_trailing_whitespace_in_comment' => false, + 'braces' => false, + 'single_blank_line_at_eof' => false, + 'blank_line_after_namespace' => false, + 'no_leading_import_slash' => false, + ]) + ->setFinder($finder) +; diff --git a/other/master-clients/php/.travis.yml b/other/master-clients/php/.travis.yml new file mode 100644 index 000000000..667b81565 --- /dev/null +++ b/other/master-clients/php/.travis.yml @@ -0,0 +1,8 @@ +language: php +# Bionic environment has preinstalled PHP from 7.1 to 7.4 +# https://docs.travis-ci.com/user/reference/bionic/#php-support +dist: bionic +php: + - 7.4 +before_install: "composer install" +script: "vendor/bin/phpunit" diff --git a/other/master-clients/php/README.md b/other/master-clients/php/README.md new file mode 100644 index 000000000..183655512 --- /dev/null +++ b/other/master-clients/php/README.md @@ -0,0 +1,113 @@ +# OpenAPIClient-php + +The Seaweedfs Master Server API allows you to store blobs + + +## Installation & Usage + +### Requirements + +PHP 7.4 and later. +Should also work with PHP 8.0. + +### Composer + +To install the bindings via [Composer](https://getcomposer.org/), add the following to `composer.json`: + +```json +{ + "repositories": [ + { + "type": "vcs", + "url": "https://github.com/GIT_USER_ID/GIT_REPO_ID.git" + } + ], + "require": { + "GIT_USER_ID/GIT_REPO_ID": "*@dev" + } +} +``` + +Then run `composer install` + +### Manual Installation + +Download the files and include `autoload.php`: + +```php +_1, _2 for the assigned additional file ids. e.g. 3,01637037d6_1, 3,01637037d6_2 +$collection = NULL; // mixed | required collection name +$data_center = NULL; // mixed | preferred data center +$rack = NULL; // mixed | preferred rack +$data_node = NULL; // mixed | preferred volume server, e.g. 127.0.0.1:8080 +$disk = NULL; // mixed | If you have disks labelled, this must be supplied to specify the disk type to allocate on. +$replication = NULL; // mixed | replica placement strategy +$ttl = NULL; // mixed | file expiration time limit, example: 3m for 3 minutes. units: m-minute, h-hour, d-day, w-week, M-month, y-year +$preallocate = NULL; // mixed | If no matching volumes, pre-allocate this number of bytes on disk for new volumes. +$memory_map_max_size_mb = NULL; // mixed | Only implemented for windows. Use memory mapped files with specified size for new volumes. +$writable_volume_count = NULL; // mixed | If no matching volumes, create specified number of new volumes. + +try { + $result = $apiInstance->dirAssign($count, $collection, $data_center, $rack, $data_node, $disk, $replication, $ttl, $preallocate, $memory_map_max_size_mb, $writable_volume_count); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling DefaultApi->dirAssign: ', $e->getMessage(), PHP_EOL; +} + +``` + +## API Endpoints + +All URIs are relative to *https://127.0.0.1:9333* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*DefaultApi* | [**dirAssign**](docs/Api/DefaultApi.md#dirassign) | **GET** /dir/assign | Assign a file key +*DefaultApi* | [**dirLookup**](docs/Api/DefaultApi.md#dirlookup) | **GET** /dir/lookup | Lookup volume + +## Models + +- [FileKey](docs/Model/FileKey.md) +- [Location](docs/Model/Location.md) + +## Authorization +All endpoints do not require authorization. +## Tests + +To run the tests, use: + +```bash +composer install +vendor/bin/phpunit +``` + +## Author + + + +## About this package + +This PHP package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: `3.43.0` +- Build package: `org.openapitools.codegen.languages.PhpClientCodegen` diff --git a/other/master-clients/php/composer.json b/other/master-clients/php/composer.json new file mode 100644 index 000000000..708eb7b39 --- /dev/null +++ b/other/master-clients/php/composer.json @@ -0,0 +1,38 @@ +{ + "description": "The Seaweedfs Master Server API allows you to store blobs", + "keywords": [ + "openapitools", + "openapi-generator", + "openapi", + "php", + "sdk", + "rest", + "api" + ], + "homepage": "https://openapi-generator.tech", + "license": "unlicense", + "authors": [ + { + "name": "OpenAPI-Generator contributors", + "homepage": "https://openapi-generator.tech" + } + ], + "require": { + "php": "^7.4 || ^8.0", + "ext-curl": "*", + "ext-json": "*", + "ext-mbstring": "*", + "guzzlehttp/guzzle": "^7.3", + "guzzlehttp/psr7": "^1.7 || ^2.0" + }, + "require-dev": { + "phpunit/phpunit": "^8.0 || ^9.0", + "friendsofphp/php-cs-fixer": "^3.5" + }, + "autoload": { + "psr-4": { "OpenAPI\\Client\\" : "lib/" } + }, + "autoload-dev": { + "psr-4": { "OpenAPI\\Client\\Test\\" : "test/" } + } +} diff --git a/other/master-clients/php/docs/Api/DefaultApi.md b/other/master-clients/php/docs/Api/DefaultApi.md new file mode 100644 index 000000000..4afbe2b47 --- /dev/null +++ b/other/master-clients/php/docs/Api/DefaultApi.md @@ -0,0 +1,147 @@ +# OpenAPI\Client\DefaultApi + +All URIs are relative to https://127.0.0.1:9333, except if the operation defines another base path. + +| Method | HTTP request | Description | +| ------------- | ------------- | ------------- | +| [**dirAssign()**](DefaultApi.md#dirAssign) | **GET** /dir/assign | Assign a file key | +| [**dirLookup()**](DefaultApi.md#dirLookup) | **GET** /dir/lookup | Lookup volume | + + +## `dirAssign()` + +```php +dirAssign($count, $collection, $data_center, $rack, $data_node, $disk, $replication, $ttl, $preallocate, $memory_map_max_size_mb, $writable_volume_count): \OpenAPI\Client\Model\FileKey +``` + +Assign a file key + +This operation is very cheap. Just increase a number in master server's memory. + +### Example + +```php +_1, _2 for the assigned additional file ids. e.g. 3,01637037d6_1, 3,01637037d6_2 +$collection = NULL; // mixed | required collection name +$data_center = NULL; // mixed | preferred data center +$rack = NULL; // mixed | preferred rack +$data_node = NULL; // mixed | preferred volume server, e.g. 127.0.0.1:8080 +$disk = NULL; // mixed | If you have disks labelled, this must be supplied to specify the disk type to allocate on. +$replication = NULL; // mixed | replica placement strategy +$ttl = NULL; // mixed | file expiration time limit, example: 3m for 3 minutes. units: m-minute, h-hour, d-day, w-week, M-month, y-year +$preallocate = NULL; // mixed | If no matching volumes, pre-allocate this number of bytes on disk for new volumes. +$memory_map_max_size_mb = NULL; // mixed | Only implemented for windows. Use memory mapped files with specified size for new volumes. +$writable_volume_count = NULL; // mixed | If no matching volumes, create specified number of new volumes. + +try { + $result = $apiInstance->dirAssign($count, $collection, $data_center, $rack, $data_node, $disk, $replication, $ttl, $preallocate, $memory_map_max_size_mb, $writable_volume_count); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling DefaultApi->dirAssign: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **count** | [**mixed**](../Model/.md)| how many file ids to assign. Use <fid>_1, <fid>_2 for the assigned additional file ids. e.g. 3,01637037d6_1, 3,01637037d6_2 | [optional] | +| **collection** | [**mixed**](../Model/.md)| required collection name | [optional] | +| **data_center** | [**mixed**](../Model/.md)| preferred data center | [optional] | +| **rack** | [**mixed**](../Model/.md)| preferred rack | [optional] | +| **data_node** | [**mixed**](../Model/.md)| preferred volume server, e.g. 127.0.0.1:8080 | [optional] | +| **disk** | [**mixed**](../Model/.md)| If you have disks labelled, this must be supplied to specify the disk type to allocate on. | [optional] | +| **replication** | [**mixed**](../Model/.md)| replica placement strategy | [optional] | +| **ttl** | [**mixed**](../Model/.md)| file expiration time limit, example: 3m for 3 minutes. units: m-minute, h-hour, d-day, w-week, M-month, y-year | [optional] | +| **preallocate** | [**mixed**](../Model/.md)| If no matching volumes, pre-allocate this number of bytes on disk for new volumes. | [optional] | +| **memory_map_max_size_mb** | [**mixed**](../Model/.md)| Only implemented for windows. Use memory mapped files with specified size for new volumes. | [optional] | +| **writable_volume_count** | [**mixed**](../Model/.md)| If no matching volumes, create specified number of new volumes. | [optional] | + +### Return type + +[**\OpenAPI\Client\Model\FileKey**](../Model/FileKey.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: `application/json` + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) + +## `dirLookup()` + +```php +dirLookup($volume_id, $collection, $file_id, $read): mixed +``` + +Lookup volume + +We would need to find out whether the volumes have moved. + +### Example + +```php +dirLookup($volume_id, $collection, $file_id, $read); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling DefaultApi->dirLookup: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **volume_id** | [**mixed**](../Model/.md)| volume id | [optional] | +| **collection** | [**mixed**](../Model/.md)| optionally to speed up the lookup | [optional] | +| **file_id** | [**mixed**](../Model/.md)| If provided, this returns the fileId location and a JWT to update or delete the file. | [optional] | +| **read** | [**mixed**](../Model/.md)| works together with \"fileId\", if read=yes, JWT is generated for reads. | [optional] | + +### Return type + +**mixed** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: `application/json` + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) diff --git a/other/master-clients/php/docs/Model/FileKey.md b/other/master-clients/php/docs/Model/FileKey.md new file mode 100644 index 000000000..c3fe075e0 --- /dev/null +++ b/other/master-clients/php/docs/Model/FileKey.md @@ -0,0 +1,11 @@ +# # FileKey + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**count** | **mixed** | | [optional] +**fid** | **mixed** | | [optional] +**url** | **mixed** | | [optional] + +[[Back to Model list]](../../README.md#models) [[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md) diff --git a/other/master-clients/php/docs/Model/Location.md b/other/master-clients/php/docs/Model/Location.md new file mode 100644 index 000000000..88a5e5ab2 --- /dev/null +++ b/other/master-clients/php/docs/Model/Location.md @@ -0,0 +1,10 @@ +# # Location + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**public_url** | **mixed** | | [optional] +**url** | **mixed** | | [optional] + +[[Back to Model list]](../../README.md#models) [[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md) diff --git a/other/master-clients/php/git_push.sh b/other/master-clients/php/git_push.sh new file mode 100644 index 000000000..f53a75d4f --- /dev/null +++ b/other/master-clients/php/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/other/master-clients/php/lib/Api/DefaultApi.php b/other/master-clients/php/lib/Api/DefaultApi.php new file mode 100644 index 000000000..ec9109240 --- /dev/null +++ b/other/master-clients/php/lib/Api/DefaultApi.php @@ -0,0 +1,897 @@ + [ + 'application/json', + ], + 'dirLookup' => [ + 'application/json', + ], + ]; + +/** + * @param ClientInterface $client + * @param Configuration $config + * @param HeaderSelector $selector + * @param int $hostIndex (Optional) host index to select the list of hosts if defined in the OpenAPI spec + */ + public function __construct( + ClientInterface $client = null, + Configuration $config = null, + HeaderSelector $selector = null, + $hostIndex = 0 + ) { + $this->client = $client ?: new Client(); + $this->config = $config ?: new Configuration(); + $this->headerSelector = $selector ?: new HeaderSelector(); + $this->hostIndex = $hostIndex; + } + + /** + * Set the host index + * + * @param int $hostIndex Host index (required) + */ + public function setHostIndex($hostIndex): void + { + $this->hostIndex = $hostIndex; + } + + /** + * Get the host index + * + * @return int Host index + */ + public function getHostIndex() + { + return $this->hostIndex; + } + + /** + * @return Configuration + */ + public function getConfig() + { + return $this->config; + } + + /** + * Operation dirAssign + * + * Assign a file key + * + * @param mixed $count how many file ids to assign. Use <fid>_1, <fid>_2 for the assigned additional file ids. e.g. 3,01637037d6_1, 3,01637037d6_2 (optional) + * @param mixed $collection required collection name (optional) + * @param mixed $data_center preferred data center (optional) + * @param mixed $rack preferred rack (optional) + * @param mixed $data_node preferred volume server, e.g. 127.0.0.1:8080 (optional) + * @param mixed $disk If you have disks labelled, this must be supplied to specify the disk type to allocate on. (optional) + * @param mixed $replication replica placement strategy (optional) + * @param mixed $ttl file expiration time limit, example: 3m for 3 minutes. units: m-minute, h-hour, d-day, w-week, M-month, y-year (optional) + * @param mixed $preallocate If no matching volumes, pre-allocate this number of bytes on disk for new volumes. (optional) + * @param mixed $memory_map_max_size_mb Only implemented for windows. Use memory mapped files with specified size for new volumes. (optional) + * @param mixed $writable_volume_count If no matching volumes, create specified number of new volumes. (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['dirAssign'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return \OpenAPI\Client\Model\FileKey + */ + public function dirAssign($count = null, $collection = null, $data_center = null, $rack = null, $data_node = null, $disk = null, $replication = null, $ttl = null, $preallocate = null, $memory_map_max_size_mb = null, $writable_volume_count = null, string $contentType = self::contentTypes['dirAssign'][0]) + { + list($response) = $this->dirAssignWithHttpInfo($count, $collection, $data_center, $rack, $data_node, $disk, $replication, $ttl, $preallocate, $memory_map_max_size_mb, $writable_volume_count, $contentType); + return $response; + } + + /** + * Operation dirAssignWithHttpInfo + * + * Assign a file key + * + * @param mixed $count how many file ids to assign. Use <fid>_1, <fid>_2 for the assigned additional file ids. e.g. 3,01637037d6_1, 3,01637037d6_2 (optional) + * @param mixed $collection required collection name (optional) + * @param mixed $data_center preferred data center (optional) + * @param mixed $rack preferred rack (optional) + * @param mixed $data_node preferred volume server, e.g. 127.0.0.1:8080 (optional) + * @param mixed $disk If you have disks labelled, this must be supplied to specify the disk type to allocate on. (optional) + * @param mixed $replication replica placement strategy (optional) + * @param mixed $ttl file expiration time limit, example: 3m for 3 minutes. units: m-minute, h-hour, d-day, w-week, M-month, y-year (optional) + * @param mixed $preallocate If no matching volumes, pre-allocate this number of bytes on disk for new volumes. (optional) + * @param mixed $memory_map_max_size_mb Only implemented for windows. Use memory mapped files with specified size for new volumes. (optional) + * @param mixed $writable_volume_count If no matching volumes, create specified number of new volumes. (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['dirAssign'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of \OpenAPI\Client\Model\FileKey, HTTP status code, HTTP response headers (array of strings) + */ + public function dirAssignWithHttpInfo($count = null, $collection = null, $data_center = null, $rack = null, $data_node = null, $disk = null, $replication = null, $ttl = null, $preallocate = null, $memory_map_max_size_mb = null, $writable_volume_count = null, string $contentType = self::contentTypes['dirAssign'][0]) + { + $request = $this->dirAssignRequest($count, $collection, $data_center, $rack, $data_node, $disk, $replication, $ttl, $preallocate, $memory_map_max_size_mb, $writable_volume_count, $contentType); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? (string) $e->getResponse()->getBody() : null + ); + } catch (ConnectException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + null, + null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + (string) $request->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + + switch($statusCode) { + case 200: + if ('\OpenAPI\Client\Model\FileKey' === '\SplFileObject') { + $content = $response->getBody(); //stream goes to serializer + } else { + $content = (string) $response->getBody(); + if ('\OpenAPI\Client\Model\FileKey' !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\FileKey', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = '\OpenAPI\Client\Model\FileKey'; + if ($returnType === '\SplFileObject') { + $content = $response->getBody(); //stream goes to serializer + } else { + $content = (string) $response->getBody(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\OpenAPI\Client\Model\FileKey', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + break; + } + throw $e; + } + } + + /** + * Operation dirAssignAsync + * + * Assign a file key + * + * @param mixed $count how many file ids to assign. Use <fid>_1, <fid>_2 for the assigned additional file ids. e.g. 3,01637037d6_1, 3,01637037d6_2 (optional) + * @param mixed $collection required collection name (optional) + * @param mixed $data_center preferred data center (optional) + * @param mixed $rack preferred rack (optional) + * @param mixed $data_node preferred volume server, e.g. 127.0.0.1:8080 (optional) + * @param mixed $disk If you have disks labelled, this must be supplied to specify the disk type to allocate on. (optional) + * @param mixed $replication replica placement strategy (optional) + * @param mixed $ttl file expiration time limit, example: 3m for 3 minutes. units: m-minute, h-hour, d-day, w-week, M-month, y-year (optional) + * @param mixed $preallocate If no matching volumes, pre-allocate this number of bytes on disk for new volumes. (optional) + * @param mixed $memory_map_max_size_mb Only implemented for windows. Use memory mapped files with specified size for new volumes. (optional) + * @param mixed $writable_volume_count If no matching volumes, create specified number of new volumes. (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['dirAssign'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function dirAssignAsync($count = null, $collection = null, $data_center = null, $rack = null, $data_node = null, $disk = null, $replication = null, $ttl = null, $preallocate = null, $memory_map_max_size_mb = null, $writable_volume_count = null, string $contentType = self::contentTypes['dirAssign'][0]) + { + return $this->dirAssignAsyncWithHttpInfo($count, $collection, $data_center, $rack, $data_node, $disk, $replication, $ttl, $preallocate, $memory_map_max_size_mb, $writable_volume_count, $contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation dirAssignAsyncWithHttpInfo + * + * Assign a file key + * + * @param mixed $count how many file ids to assign. Use <fid>_1, <fid>_2 for the assigned additional file ids. e.g. 3,01637037d6_1, 3,01637037d6_2 (optional) + * @param mixed $collection required collection name (optional) + * @param mixed $data_center preferred data center (optional) + * @param mixed $rack preferred rack (optional) + * @param mixed $data_node preferred volume server, e.g. 127.0.0.1:8080 (optional) + * @param mixed $disk If you have disks labelled, this must be supplied to specify the disk type to allocate on. (optional) + * @param mixed $replication replica placement strategy (optional) + * @param mixed $ttl file expiration time limit, example: 3m for 3 minutes. units: m-minute, h-hour, d-day, w-week, M-month, y-year (optional) + * @param mixed $preallocate If no matching volumes, pre-allocate this number of bytes on disk for new volumes. (optional) + * @param mixed $memory_map_max_size_mb Only implemented for windows. Use memory mapped files with specified size for new volumes. (optional) + * @param mixed $writable_volume_count If no matching volumes, create specified number of new volumes. (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['dirAssign'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function dirAssignAsyncWithHttpInfo($count = null, $collection = null, $data_center = null, $rack = null, $data_node = null, $disk = null, $replication = null, $ttl = null, $preallocate = null, $memory_map_max_size_mb = null, $writable_volume_count = null, string $contentType = self::contentTypes['dirAssign'][0]) + { + $returnType = '\OpenAPI\Client\Model\FileKey'; + $request = $this->dirAssignRequest($count, $collection, $data_center, $rack, $data_node, $disk, $replication, $ttl, $preallocate, $memory_map_max_size_mb, $writable_volume_count, $contentType); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + if ($returnType === '\SplFileObject') { + $content = $response->getBody(); //stream goes to serializer + } else { + $content = (string) $response->getBody(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'dirAssign' + * + * @param mixed $count how many file ids to assign. Use <fid>_1, <fid>_2 for the assigned additional file ids. e.g. 3,01637037d6_1, 3,01637037d6_2 (optional) + * @param mixed $collection required collection name (optional) + * @param mixed $data_center preferred data center (optional) + * @param mixed $rack preferred rack (optional) + * @param mixed $data_node preferred volume server, e.g. 127.0.0.1:8080 (optional) + * @param mixed $disk If you have disks labelled, this must be supplied to specify the disk type to allocate on. (optional) + * @param mixed $replication replica placement strategy (optional) + * @param mixed $ttl file expiration time limit, example: 3m for 3 minutes. units: m-minute, h-hour, d-day, w-week, M-month, y-year (optional) + * @param mixed $preallocate If no matching volumes, pre-allocate this number of bytes on disk for new volumes. (optional) + * @param mixed $memory_map_max_size_mb Only implemented for windows. Use memory mapped files with specified size for new volumes. (optional) + * @param mixed $writable_volume_count If no matching volumes, create specified number of new volumes. (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['dirAssign'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function dirAssignRequest($count = null, $collection = null, $data_center = null, $rack = null, $data_node = null, $disk = null, $replication = null, $ttl = null, $preallocate = null, $memory_map_max_size_mb = null, $writable_volume_count = null, string $contentType = self::contentTypes['dirAssign'][0]) + { + + + + + + + + + + + + + + $resourcePath = '/dir/assign'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $count, + 'count', // param base name + 'mixed', // openApiType + 'form', // style + true, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $collection, + 'collection', // param base name + 'mixed', // openApiType + 'form', // style + true, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $data_center, + 'dataCenter', // param base name + 'mixed', // openApiType + 'form', // style + true, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $rack, + 'rack', // param base name + 'mixed', // openApiType + 'form', // style + true, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $data_node, + 'dataNode', // param base name + 'mixed', // openApiType + 'form', // style + true, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $disk, + 'disk', // param base name + 'mixed', // openApiType + 'form', // style + true, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $replication, + 'replication', // param base name + 'mixed', // openApiType + 'form', // style + true, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $ttl, + 'ttl', // param base name + 'mixed', // openApiType + 'form', // style + true, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $preallocate, + 'preallocate', // param base name + 'mixed', // openApiType + 'form', // style + true, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $memory_map_max_size_mb, + 'memoryMapMaxSizeMb', // param base name + 'mixed', // openApiType + 'form', // style + true, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $writable_volume_count, + 'writableVolumeCount', // param base name + 'mixed', // openApiType + 'form', // style + true, // explode + false // required + ) ?? []); + + + + + $headers = $this->headerSelector->selectHeaders( + ['application/json', ], + $contentType, + $multipart + ); + + // for model (json/xml) + if (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; + foreach ($formParamValueItems as $formParamValueItem) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValueItem + ]; + } + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { + # if Content-Type contains "application/json", json_encode the form parameters + $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); + } else { + // for HTTP post (form) + $httpBody = ObjectSerializer::buildQuery($formParams); + } + } + + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $operationHost = $this->config->getHost(); + $query = ObjectSerializer::buildQuery($queryParams); + return new Request( + 'GET', + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation dirLookup + * + * Lookup volume + * + * @param mixed $volume_id volume id (optional) + * @param mixed $collection optionally to speed up the lookup (optional) + * @param mixed $file_id If provided, this returns the fileId location and a JWT to update or delete the file. (optional) + * @param mixed $read works together with \"fileId\", if read=yes, JWT is generated for reads. (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['dirLookup'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return mixed + */ + public function dirLookup($volume_id = null, $collection = null, $file_id = null, $read = null, string $contentType = self::contentTypes['dirLookup'][0]) + { + list($response) = $this->dirLookupWithHttpInfo($volume_id, $collection, $file_id, $read, $contentType); + return $response; + } + + /** + * Operation dirLookupWithHttpInfo + * + * Lookup volume + * + * @param mixed $volume_id volume id (optional) + * @param mixed $collection optionally to speed up the lookup (optional) + * @param mixed $file_id If provided, this returns the fileId location and a JWT to update or delete the file. (optional) + * @param mixed $read works together with \"fileId\", if read=yes, JWT is generated for reads. (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['dirLookup'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of mixed, HTTP status code, HTTP response headers (array of strings) + */ + public function dirLookupWithHttpInfo($volume_id = null, $collection = null, $file_id = null, $read = null, string $contentType = self::contentTypes['dirLookup'][0]) + { + $request = $this->dirLookupRequest($volume_id, $collection, $file_id, $read, $contentType); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? (string) $e->getResponse()->getBody() : null + ); + } catch (ConnectException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + null, + null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + (string) $request->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + + switch($statusCode) { + case 200: + if ('mixed' === '\SplFileObject') { + $content = $response->getBody(); //stream goes to serializer + } else { + $content = (string) $response->getBody(); + if ('mixed' !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, 'mixed', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = 'mixed'; + if ($returnType === '\SplFileObject') { + $content = $response->getBody(); //stream goes to serializer + } else { + $content = (string) $response->getBody(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + 'mixed', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + break; + } + throw $e; + } + } + + /** + * Operation dirLookupAsync + * + * Lookup volume + * + * @param mixed $volume_id volume id (optional) + * @param mixed $collection optionally to speed up the lookup (optional) + * @param mixed $file_id If provided, this returns the fileId location and a JWT to update or delete the file. (optional) + * @param mixed $read works together with \"fileId\", if read=yes, JWT is generated for reads. (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['dirLookup'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function dirLookupAsync($volume_id = null, $collection = null, $file_id = null, $read = null, string $contentType = self::contentTypes['dirLookup'][0]) + { + return $this->dirLookupAsyncWithHttpInfo($volume_id, $collection, $file_id, $read, $contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation dirLookupAsyncWithHttpInfo + * + * Lookup volume + * + * @param mixed $volume_id volume id (optional) + * @param mixed $collection optionally to speed up the lookup (optional) + * @param mixed $file_id If provided, this returns the fileId location and a JWT to update or delete the file. (optional) + * @param mixed $read works together with \"fileId\", if read=yes, JWT is generated for reads. (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['dirLookup'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function dirLookupAsyncWithHttpInfo($volume_id = null, $collection = null, $file_id = null, $read = null, string $contentType = self::contentTypes['dirLookup'][0]) + { + $returnType = 'mixed'; + $request = $this->dirLookupRequest($volume_id, $collection, $file_id, $read, $contentType); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + if ($returnType === '\SplFileObject') { + $content = $response->getBody(); //stream goes to serializer + } else { + $content = (string) $response->getBody(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'dirLookup' + * + * @param mixed $volume_id volume id (optional) + * @param mixed $collection optionally to speed up the lookup (optional) + * @param mixed $file_id If provided, this returns the fileId location and a JWT to update or delete the file. (optional) + * @param mixed $read works together with \"fileId\", if read=yes, JWT is generated for reads. (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['dirLookup'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function dirLookupRequest($volume_id = null, $collection = null, $file_id = null, $read = null, string $contentType = self::contentTypes['dirLookup'][0]) + { + + + + + + + $resourcePath = '/dir/lookup'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $volume_id, + 'volumeId', // param base name + 'mixed', // openApiType + 'form', // style + true, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $collection, + 'collection', // param base name + 'mixed', // openApiType + 'form', // style + true, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $file_id, + 'fileId', // param base name + 'mixed', // openApiType + 'form', // style + true, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $read, + 'read', // param base name + 'mixed', // openApiType + 'form', // style + true, // explode + false // required + ) ?? []); + + + + + $headers = $this->headerSelector->selectHeaders( + ['application/json', ], + $contentType, + $multipart + ); + + // for model (json/xml) + if (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; + foreach ($formParamValueItems as $formParamValueItem) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValueItem + ]; + } + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { + # if Content-Type contains "application/json", json_encode the form parameters + $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); + } else { + // for HTTP post (form) + $httpBody = ObjectSerializer::buildQuery($formParams); + } + } + + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $operationHost = $this->config->getHost(); + $query = ObjectSerializer::buildQuery($queryParams); + return new Request( + 'GET', + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Create http client option + * + * @throws \RuntimeException on file opening failure + * @return array of http client options + */ + protected function createHttpClientOption() + { + $options = []; + if ($this->config->getDebug()) { + $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a'); + if (!$options[RequestOptions::DEBUG]) { + throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile()); + } + } + + return $options; + } +} diff --git a/other/master-clients/php/lib/ApiException.php b/other/master-clients/php/lib/ApiException.php new file mode 100644 index 000000000..c1f186a34 --- /dev/null +++ b/other/master-clients/php/lib/ApiException.php @@ -0,0 +1,119 @@ +responseHeaders = $responseHeaders; + $this->responseBody = $responseBody; + } + + /** + * Gets the HTTP response header + * + * @return string[]|null HTTP response header + */ + public function getResponseHeaders() + { + return $this->responseHeaders; + } + + /** + * Gets the HTTP body of the server response either as Json or string + * + * @return \stdClass|string|null HTTP body of the server response either as \stdClass or string + */ + public function getResponseBody() + { + return $this->responseBody; + } + + /** + * Sets the deserialized response object (during deserialization) + * + * @param mixed $obj Deserialized response object + * + * @return void + */ + public function setResponseObject($obj) + { + $this->responseObject = $obj; + } + + /** + * Gets the deserialized response object (during deserialization) + * + * @return mixed the deserialized response object + */ + public function getResponseObject() + { + return $this->responseObject; + } +} diff --git a/other/master-clients/php/lib/Configuration.php b/other/master-clients/php/lib/Configuration.php new file mode 100644 index 000000000..ceed1dba0 --- /dev/null +++ b/other/master-clients/php/lib/Configuration.php @@ -0,0 +1,531 @@ +tempFolderPath = sys_get_temp_dir(); + } + + /** + * Sets API key + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * @param string $key API key or token + * + * @return $this + */ + public function setApiKey($apiKeyIdentifier, $key) + { + $this->apiKeys[$apiKeyIdentifier] = $key; + return $this; + } + + /** + * Gets API key + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * + * @return null|string API key or token + */ + public function getApiKey($apiKeyIdentifier) + { + return isset($this->apiKeys[$apiKeyIdentifier]) ? $this->apiKeys[$apiKeyIdentifier] : null; + } + + /** + * Sets the prefix for API key (e.g. Bearer) + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * @param string $prefix API key prefix, e.g. Bearer + * + * @return $this + */ + public function setApiKeyPrefix($apiKeyIdentifier, $prefix) + { + $this->apiKeyPrefixes[$apiKeyIdentifier] = $prefix; + return $this; + } + + /** + * Gets API key prefix + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * + * @return null|string + */ + public function getApiKeyPrefix($apiKeyIdentifier) + { + return isset($this->apiKeyPrefixes[$apiKeyIdentifier]) ? $this->apiKeyPrefixes[$apiKeyIdentifier] : null; + } + + /** + * Sets the access token for OAuth + * + * @param string $accessToken Token for OAuth + * + * @return $this + */ + public function setAccessToken($accessToken) + { + $this->accessToken = $accessToken; + return $this; + } + + /** + * Gets the access token for OAuth + * + * @return string Access token for OAuth + */ + public function getAccessToken() + { + return $this->accessToken; + } + + /** + * Sets boolean format for query string. + * + * @param string $booleanFormatForQueryString Boolean format for query string + * + * @return $this + */ + public function setBooleanFormatForQueryString(string $booleanFormat) + { + $this->booleanFormatForQueryString = $booleanFormat; + + return $this; + } + + /** + * Gets boolean format for query string. + * + * @return string Boolean format for query string + */ + public function getBooleanFormatForQueryString(): string + { + return $this->booleanFormatForQueryString; + } + + /** + * Sets the username for HTTP basic authentication + * + * @param string $username Username for HTTP basic authentication + * + * @return $this + */ + public function setUsername($username) + { + $this->username = $username; + return $this; + } + + /** + * Gets the username for HTTP basic authentication + * + * @return string Username for HTTP basic authentication + */ + public function getUsername() + { + return $this->username; + } + + /** + * Sets the password for HTTP basic authentication + * + * @param string $password Password for HTTP basic authentication + * + * @return $this + */ + public function setPassword($password) + { + $this->password = $password; + return $this; + } + + /** + * Gets the password for HTTP basic authentication + * + * @return string Password for HTTP basic authentication + */ + public function getPassword() + { + return $this->password; + } + + /** + * Sets the host + * + * @param string $host Host + * + * @return $this + */ + public function setHost($host) + { + $this->host = $host; + return $this; + } + + /** + * Gets the host + * + * @return string Host + */ + public function getHost() + { + return $this->host; + } + + /** + * Sets the user agent of the api client + * + * @param string $userAgent the user agent of the api client + * + * @throws \InvalidArgumentException + * @return $this + */ + public function setUserAgent($userAgent) + { + if (!is_string($userAgent)) { + throw new \InvalidArgumentException('User-agent must be a string.'); + } + + $this->userAgent = $userAgent; + return $this; + } + + /** + * Gets the user agent of the api client + * + * @return string user agent + */ + public function getUserAgent() + { + return $this->userAgent; + } + + /** + * Sets debug flag + * + * @param bool $debug Debug flag + * + * @return $this + */ + public function setDebug($debug) + { + $this->debug = $debug; + return $this; + } + + /** + * Gets the debug flag + * + * @return bool + */ + public function getDebug() + { + return $this->debug; + } + + /** + * Sets the debug file + * + * @param string $debugFile Debug file + * + * @return $this + */ + public function setDebugFile($debugFile) + { + $this->debugFile = $debugFile; + return $this; + } + + /** + * Gets the debug file + * + * @return string + */ + public function getDebugFile() + { + return $this->debugFile; + } + + /** + * Sets the temp folder path + * + * @param string $tempFolderPath Temp folder path + * + * @return $this + */ + public function setTempFolderPath($tempFolderPath) + { + $this->tempFolderPath = $tempFolderPath; + return $this; + } + + /** + * Gets the temp folder path + * + * @return string Temp folder path + */ + public function getTempFolderPath() + { + return $this->tempFolderPath; + } + + /** + * Gets the default configuration instance + * + * @return Configuration + */ + public static function getDefaultConfiguration() + { + if (self::$defaultConfiguration === null) { + self::$defaultConfiguration = new Configuration(); + } + + return self::$defaultConfiguration; + } + + /** + * Sets the default configuration instance + * + * @param Configuration $config An instance of the Configuration Object + * + * @return void + */ + public static function setDefaultConfiguration(Configuration $config) + { + self::$defaultConfiguration = $config; + } + + /** + * Gets the essential information for debugging + * + * @return string The report for debugging + */ + public static function toDebugReport() + { + $report = 'PHP SDK (OpenAPI\Client) Debug Report:' . PHP_EOL; + $report .= ' OS: ' . php_uname() . PHP_EOL; + $report .= ' PHP Version: ' . PHP_VERSION . PHP_EOL; + $report .= ' The version of the OpenAPI document: 3.43.0' . PHP_EOL; + $report .= ' Temp Folder Path: ' . self::getDefaultConfiguration()->getTempFolderPath() . PHP_EOL; + + return $report; + } + + /** + * Get API key (with prefix if set) + * + * @param string $apiKeyIdentifier name of apikey + * + * @return null|string API key with the prefix + */ + public function getApiKeyWithPrefix($apiKeyIdentifier) + { + $prefix = $this->getApiKeyPrefix($apiKeyIdentifier); + $apiKey = $this->getApiKey($apiKeyIdentifier); + + if ($apiKey === null) { + return null; + } + + if ($prefix === null) { + $keyWithPrefix = $apiKey; + } else { + $keyWithPrefix = $prefix . ' ' . $apiKey; + } + + return $keyWithPrefix; + } + + /** + * Returns an array of host settings + * + * @return array an array of host settings + */ + public function getHostSettings() + { + return [ + [ + "url" => "https://127.0.0.1:9333", + "description" => "No description provided", + ] + ]; + } + + /** + * Returns URL based on host settings, index and variables + * + * @param array $hostSettings array of host settings, generated from getHostSettings() or equivalent from the API clients + * @param int $hostIndex index of the host settings + * @param array|null $variables hash of variable and the corresponding value (optional) + * @return string URL based on host settings + */ + public static function getHostString(array $hostsSettings, $hostIndex, array $variables = null) + { + if (null === $variables) { + $variables = []; + } + + // check array index out of bound + if ($hostIndex < 0 || $hostIndex >= count($hostsSettings)) { + throw new \InvalidArgumentException("Invalid index $hostIndex when selecting the host. Must be less than ".count($hostsSettings)); + } + + $host = $hostsSettings[$hostIndex]; + $url = $host["url"]; + + // go through variable and assign a value + foreach ($host["variables"] ?? [] as $name => $variable) { + if (array_key_exists($name, $variables)) { // check to see if it's in the variables provided by the user + if (!isset($variable['enum_values']) || in_array($variables[$name], $variable["enum_values"], true)) { // check to see if the value is in the enum + $url = str_replace("{".$name."}", $variables[$name], $url); + } else { + throw new \InvalidArgumentException("The variable `$name` in the host URL has invalid value ".$variables[$name].". Must be ".join(',', $variable["enum_values"])."."); + } + } else { + // use default value + $url = str_replace("{".$name."}", $variable["default_value"], $url); + } + } + + return $url; + } + + /** + * Returns URL based on the index and variables + * + * @param int $index index of the host settings + * @param array|null $variables hash of variable and the corresponding value (optional) + * @return string URL based on host settings + */ + public function getHostFromSettings($index, $variables = null) + { + return self::getHostString($this->getHostSettings(), $index, $variables); + } +} diff --git a/other/master-clients/php/lib/HeaderSelector.php b/other/master-clients/php/lib/HeaderSelector.php new file mode 100644 index 000000000..30b65122f --- /dev/null +++ b/other/master-clients/php/lib/HeaderSelector.php @@ -0,0 +1,245 @@ +selectAcceptHeader($accept); + if ($accept !== null) { + $headers['Accept'] = $accept; + } + + if (!$isMultipart) { + if($contentType === '') { + $contentType = 'application/json'; + } + + $headers['Content-Type'] = $contentType; + } + + return $headers; + } + + /** + * Return the header 'Accept' based on an array of Accept provided. + * + * @param string[] $accept Array of header + * + * @return null|string Accept (e.g. application/json) + */ + private function selectAcceptHeader(array $accept): ?string + { + # filter out empty entries + $accept = array_filter($accept); + + if (count($accept) === 0) { + return null; + } + + # If there's only one Accept header, just use it + if (count($accept) === 1) { + return reset($accept); + } + + # If none of the available Accept headers is of type "json", then just use all them + $headersWithJson = preg_grep('~(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$~', $accept); + if (count($headersWithJson) === 0) { + return implode(',', $accept); + } + + # If we got here, then we need add quality values (weight), as described in IETF RFC 9110, Items 12.4.2/12.5.1, + # to give the highest priority to json-like headers - recalculating the existing ones, if needed + return $this->getAcceptHeaderWithAdjustedWeight($accept, $headersWithJson); + } + + /** + * Create an Accept header string from the given "Accept" headers array, recalculating all weights + * + * @param string[] $accept Array of Accept Headers + * @param string[] $headersWithJson Array of Accept Headers of type "json" + * + * @return string "Accept" Header (e.g. "application/json, text/html; q=0.9") + */ + private function getAcceptHeaderWithAdjustedWeight(array $accept, array $headersWithJson): string + { + $processedHeaders = [ + 'withApplicationJson' => [], + 'withJson' => [], + 'withoutJson' => [], + ]; + + foreach ($accept as $header) { + + $headerData = $this->getHeaderAndWeight($header); + + if (stripos($headerData['header'], 'application/json') === 0) { + $processedHeaders['withApplicationJson'][] = $headerData; + } elseif (in_array($header, $headersWithJson, true)) { + $processedHeaders['withJson'][] = $headerData; + } else { + $processedHeaders['withoutJson'][] = $headerData; + } + } + + $acceptHeaders = []; + $currentWeight = 1000; + + $hasMoreThan28Headers = count($accept) > 28; + + foreach($processedHeaders as $headers) { + if (count($headers) > 0) { + $acceptHeaders[] = $this->adjustWeight($headers, $currentWeight, $hasMoreThan28Headers); + } + } + + $acceptHeaders = array_merge(...$acceptHeaders); + + return implode(',', $acceptHeaders); + } + + /** + * Given an Accept header, returns an associative array splitting the header and its weight + * + * @param string $header "Accept" Header + * + * @return array with the header and its weight + */ + private function getHeaderAndWeight(string $header): array + { + # matches headers with weight, splitting the header and the weight in $outputArray + if (preg_match('/(.*);\s*q=(1(?:\.0+)?|0\.\d+)$/', $header, $outputArray) === 1) { + $headerData = [ + 'header' => $outputArray[1], + 'weight' => (int)($outputArray[2] * 1000), + ]; + } else { + $headerData = [ + 'header' => trim($header), + 'weight' => 1000, + ]; + } + + return $headerData; + } + + /** + * @param array[] $headers + * @param float $currentWeight + * @param bool $hasMoreThan28Headers + * @return string[] array of adjusted "Accept" headers + */ + private function adjustWeight(array $headers, float &$currentWeight, bool $hasMoreThan28Headers): array + { + usort($headers, function (array $a, array $b) { + return $b['weight'] - $a['weight']; + }); + + $acceptHeaders = []; + foreach ($headers as $index => $header) { + if($index > 0 && $headers[$index - 1]['weight'] > $header['weight']) + { + $currentWeight = $this->getNextWeight($currentWeight, $hasMoreThan28Headers); + } + + $weight = $currentWeight; + + $acceptHeaders[] = $this->buildAcceptHeader($header['header'], $weight); + } + + $currentWeight = $this->getNextWeight($currentWeight, $hasMoreThan28Headers); + + return $acceptHeaders; + } + + /** + * @param string $header + * @param int $weight + * @return string + */ + private function buildAcceptHeader(string $header, int $weight): string + { + if($weight === 1000) { + return $header; + } + + return trim($header, '; ') . ';q=' . rtrim(sprintf('%0.3f', $weight / 1000), '0'); + } + + /** + * Calculate the next weight, based on the current one. + * + * If there are less than 28 "Accept" headers, the weights will be decreased by 1 on its highest significant digit, using the + * following formula: + * + * next weight = current weight - 10 ^ (floor(log(current weight - 1))) + * + * ( current weight minus ( 10 raised to the power of ( floor of (log to the base 10 of ( current weight minus 1 ) ) ) ) ) + * + * Starting from 1000, this generates the following series: + * + * 1000, 900, 800, 700, 600, 500, 400, 300, 200, 100, 90, 80, 70, 60, 50, 40, 30, 20, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 + * + * The resulting quality codes are closer to the average "normal" usage of them (like "q=0.9", "q=0.8" and so on), but it only works + * if there is a maximum of 28 "Accept" headers. If we have more than that (which is extremely unlikely), then we fall back to a 1-by-1 + * decrement rule, which will result in quality codes like "q=0.999", "q=0.998" etc. + * + * @param int $currentWeight varying from 1 to 1000 (will be divided by 1000 to build the quality value) + * @param bool $hasMoreThan28Headers + * @return int + */ + public function getNextWeight(int $currentWeight, bool $hasMoreThan28Headers): int + { + if ($currentWeight <= 1) { + return 1; + } + + if ($hasMoreThan28Headers) { + return $currentWeight - 1; + } + + return $currentWeight - 10 ** floor( log10($currentWeight - 1) ); + } +} diff --git a/other/master-clients/php/lib/Model/FileKey.php b/other/master-clients/php/lib/Model/FileKey.php new file mode 100644 index 000000000..e5d792edb --- /dev/null +++ b/other/master-clients/php/lib/Model/FileKey.php @@ -0,0 +1,498 @@ + + */ +class FileKey implements ModelInterface, ArrayAccess, \JsonSerializable +{ + public const DISCRIMINATOR = null; + + /** + * The original name of the model. + * + * @var string + */ + protected static $openAPIModelName = 'FileKey'; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $openAPITypes = [ + 'count' => 'mixed', + 'fid' => 'mixed', + 'url' => 'mixed' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + * @phpstan-var array + * @psalm-var array + */ + protected static $openAPIFormats = [ + 'count' => 'int64', + 'fid' => null, + 'url' => null + ]; + + /** + * Array of nullable properties. Used for (de)serialization + * + * @var boolean[] + */ + protected static array $openAPINullables = [ + 'count' => true, + 'fid' => true, + 'url' => true + ]; + + /** + * If a nullable field gets set to null, insert it here + * + * @var boolean[] + */ + protected array $openAPINullablesSetToNull = []; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPITypes() + { + return self::$openAPITypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPIFormats() + { + return self::$openAPIFormats; + } + + /** + * Array of nullable properties + * + * @return array + */ + protected static function openAPINullables(): array + { + return self::$openAPINullables; + } + + /** + * Array of nullable field names deliberately set to null + * + * @return boolean[] + */ + private function getOpenAPINullablesSetToNull(): array + { + return $this->openAPINullablesSetToNull; + } + + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + + /** + * Checks if a property is nullable + * + * @param string $property + * @return bool + */ + public static function isNullable(string $property): bool + { + return self::openAPINullables()[$property] ?? false; + } + + /** + * Checks if a nullable property is set to null. + * + * @param string $property + * @return bool + */ + public function isNullableSetToNull(string $property): bool + { + return in_array($property, $this->getOpenAPINullablesSetToNull(), true); + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'count' => 'count', + 'fid' => 'fid', + 'url' => 'url' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'count' => 'setCount', + 'fid' => 'setFid', + 'url' => 'setUrl' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'count' => 'getCount', + 'fid' => 'getFid', + 'url' => 'getUrl' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$openAPIModelName; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->setIfExists('count', $data ?? [], null); + $this->setIfExists('fid', $data ?? [], null); + $this->setIfExists('url', $data ?? [], null); + } + + /** + * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName + * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the + * $this->openAPINullablesSetToNull array + * + * @param string $variableName + * @param array $fields + * @param mixed $defaultValue + */ + private function setIfExists(string $variableName, array $fields, $defaultValue): void + { + if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { + $this->openAPINullablesSetToNull[] = $variableName; + } + + $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets count + * + * @return mixed|null + */ + public function getCount() + { + return $this->container['count']; + } + + /** + * Sets count + * + * @param mixed|null $count count + * + * @return self + */ + public function setCount($count) + { + if (is_null($count)) { + array_push($this->openAPINullablesSetToNull, 'count'); + } else { + $nullablesSetToNull = $this->getOpenAPINullablesSetToNull(); + $index = array_search('count', $nullablesSetToNull); + if ($index !== FALSE) { + unset($nullablesSetToNull[$index]); + $this->setOpenAPINullablesSetToNull($nullablesSetToNull); + } + } + $this->container['count'] = $count; + + return $this; + } + + /** + * Gets fid + * + * @return mixed|null + */ + public function getFid() + { + return $this->container['fid']; + } + + /** + * Sets fid + * + * @param mixed|null $fid fid + * + * @return self + */ + public function setFid($fid) + { + if (is_null($fid)) { + array_push($this->openAPINullablesSetToNull, 'fid'); + } else { + $nullablesSetToNull = $this->getOpenAPINullablesSetToNull(); + $index = array_search('fid', $nullablesSetToNull); + if ($index !== FALSE) { + unset($nullablesSetToNull[$index]); + $this->setOpenAPINullablesSetToNull($nullablesSetToNull); + } + } + $this->container['fid'] = $fid; + + return $this; + } + + /** + * Gets url + * + * @return mixed|null + */ + public function getUrl() + { + return $this->container['url']; + } + + /** + * Sets url + * + * @param mixed|null $url url + * + * @return self + */ + public function setUrl($url) + { + if (is_null($url)) { + array_push($this->openAPINullablesSetToNull, 'url'); + } else { + $nullablesSetToNull = $this->getOpenAPINullablesSetToNull(); + $index = array_search('url', $nullablesSetToNull); + if ($index !== FALSE) { + unset($nullablesSetToNull[$index]); + $this->setOpenAPINullablesSetToNull($nullablesSetToNull); + } + } + $this->container['url'] = $url; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset): bool + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed|null + */ + #[\ReturnTypeWillChange] + public function offsetGet($offset) + { + return $this->container[$offset] ?? null; + } + + /** + * Sets value based on offset. + * + * @param int|null $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value): void + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset): void + { + unset($this->container[$offset]); + } + + /** + * Serializes the object to a value that can be serialized natively by json_encode(). + * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php + * + * @return mixed Returns data which can be serialized by json_encode(), which is a value + * of any type other than a resource. + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return ObjectSerializer::sanitizeForSerialization($this); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + /** + * Gets a header-safe presentation of the object + * + * @return string + */ + public function toHeaderValue() + { + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/other/master-clients/php/lib/Model/Location.php b/other/master-clients/php/lib/Model/Location.php new file mode 100644 index 000000000..19fdeda4f --- /dev/null +++ b/other/master-clients/php/lib/Model/Location.php @@ -0,0 +1,457 @@ + + */ +class Location implements ModelInterface, ArrayAccess, \JsonSerializable +{ + public const DISCRIMINATOR = null; + + /** + * The original name of the model. + * + * @var string + */ + protected static $openAPIModelName = 'Location'; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $openAPITypes = [ + 'public_url' => 'mixed', + 'url' => 'mixed' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + * @phpstan-var array + * @psalm-var array + */ + protected static $openAPIFormats = [ + 'public_url' => null, + 'url' => null + ]; + + /** + * Array of nullable properties. Used for (de)serialization + * + * @var boolean[] + */ + protected static array $openAPINullables = [ + 'public_url' => true, + 'url' => true + ]; + + /** + * If a nullable field gets set to null, insert it here + * + * @var boolean[] + */ + protected array $openAPINullablesSetToNull = []; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPITypes() + { + return self::$openAPITypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPIFormats() + { + return self::$openAPIFormats; + } + + /** + * Array of nullable properties + * + * @return array + */ + protected static function openAPINullables(): array + { + return self::$openAPINullables; + } + + /** + * Array of nullable field names deliberately set to null + * + * @return boolean[] + */ + private function getOpenAPINullablesSetToNull(): array + { + return $this->openAPINullablesSetToNull; + } + + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + + /** + * Checks if a property is nullable + * + * @param string $property + * @return bool + */ + public static function isNullable(string $property): bool + { + return self::openAPINullables()[$property] ?? false; + } + + /** + * Checks if a nullable property is set to null. + * + * @param string $property + * @return bool + */ + public function isNullableSetToNull(string $property): bool + { + return in_array($property, $this->getOpenAPINullablesSetToNull(), true); + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'public_url' => 'publicUrl', + 'url' => 'url' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'public_url' => 'setPublicUrl', + 'url' => 'setUrl' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'public_url' => 'getPublicUrl', + 'url' => 'getUrl' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$openAPIModelName; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->setIfExists('public_url', $data ?? [], null); + $this->setIfExists('url', $data ?? [], null); + } + + /** + * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName + * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the + * $this->openAPINullablesSetToNull array + * + * @param string $variableName + * @param array $fields + * @param mixed $defaultValue + */ + private function setIfExists(string $variableName, array $fields, $defaultValue): void + { + if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { + $this->openAPINullablesSetToNull[] = $variableName; + } + + $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets public_url + * + * @return mixed|null + */ + public function getPublicUrl() + { + return $this->container['public_url']; + } + + /** + * Sets public_url + * + * @param mixed|null $public_url public_url + * + * @return self + */ + public function setPublicUrl($public_url) + { + if (is_null($public_url)) { + array_push($this->openAPINullablesSetToNull, 'public_url'); + } else { + $nullablesSetToNull = $this->getOpenAPINullablesSetToNull(); + $index = array_search('public_url', $nullablesSetToNull); + if ($index !== FALSE) { + unset($nullablesSetToNull[$index]); + $this->setOpenAPINullablesSetToNull($nullablesSetToNull); + } + } + $this->container['public_url'] = $public_url; + + return $this; + } + + /** + * Gets url + * + * @return mixed|null + */ + public function getUrl() + { + return $this->container['url']; + } + + /** + * Sets url + * + * @param mixed|null $url url + * + * @return self + */ + public function setUrl($url) + { + if (is_null($url)) { + array_push($this->openAPINullablesSetToNull, 'url'); + } else { + $nullablesSetToNull = $this->getOpenAPINullablesSetToNull(); + $index = array_search('url', $nullablesSetToNull); + if ($index !== FALSE) { + unset($nullablesSetToNull[$index]); + $this->setOpenAPINullablesSetToNull($nullablesSetToNull); + } + } + $this->container['url'] = $url; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset): bool + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed|null + */ + #[\ReturnTypeWillChange] + public function offsetGet($offset) + { + return $this->container[$offset] ?? null; + } + + /** + * Sets value based on offset. + * + * @param int|null $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value): void + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset): void + { + unset($this->container[$offset]); + } + + /** + * Serializes the object to a value that can be serialized natively by json_encode(). + * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php + * + * @return mixed Returns data which can be serialized by json_encode(), which is a value + * of any type other than a resource. + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return ObjectSerializer::sanitizeForSerialization($this); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + /** + * Gets a header-safe presentation of the object + * + * @return string + */ + public function toHeaderValue() + { + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/other/master-clients/php/lib/Model/ModelInterface.php b/other/master-clients/php/lib/Model/ModelInterface.php new file mode 100644 index 000000000..d5083c493 --- /dev/null +++ b/other/master-clients/php/lib/Model/ModelInterface.php @@ -0,0 +1,111 @@ +format('Y-m-d') : $data->format(self::$dateTimeFormat); + } + + if (is_array($data)) { + foreach ($data as $property => $value) { + $data[$property] = self::sanitizeForSerialization($value); + } + return $data; + } + + if (is_object($data)) { + $values = []; + if ($data instanceof ModelInterface) { + $formats = $data::openAPIFormats(); + foreach ($data::openAPITypes() as $property => $openAPIType) { + $getter = $data::getters()[$property]; + $value = $data->$getter(); + if ($value !== null && !in_array($openAPIType, ['\DateTime', '\SplFileObject', 'array', 'bool', 'boolean', 'byte', 'float', 'int', 'integer', 'mixed', 'number', 'object', 'string', 'void'], true)) { + $callable = [$openAPIType, 'getAllowableEnumValues']; + if (is_callable($callable)) { + /** array $callable */ + $allowedEnumTypes = $callable(); + if (!in_array($value, $allowedEnumTypes, true)) { + $imploded = implode("', '", $allowedEnumTypes); + throw new \InvalidArgumentException("Invalid value for enum '$openAPIType', must be one of: '$imploded'"); + } + } + } + if (($data::isNullable($property) && $data->isNullableSetToNull($property)) || $value !== null) { + $values[$data::attributeMap()[$property]] = self::sanitizeForSerialization($value, $openAPIType, $formats[$property]); + } + } + } else { + foreach($data as $property => $value) { + $values[$property] = self::sanitizeForSerialization($value); + } + } + return (object)$values; + } else { + return (string)$data; + } + } + + /** + * Sanitize filename by removing path. + * e.g. ../../sun.gif becomes sun.gif + * + * @param string $filename filename to be sanitized + * + * @return string the sanitized filename + */ + public static function sanitizeFilename($filename) + { + if (preg_match("/.*[\/\\\\](.*)$/", $filename, $match)) { + return $match[1]; + } else { + return $filename; + } + } + + /** + * Shorter timestamp microseconds to 6 digits length. + * + * @param string $timestamp Original timestamp + * + * @return string the shorten timestamp + */ + public static function sanitizeTimestamp($timestamp) + { + if (!is_string($timestamp)) return $timestamp; + + return preg_replace('/(:\d{2}.\d{6})\d*/', '$1', $timestamp); + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the path, by url-encoding. + * + * @param string $value a string which will be part of the path + * + * @return string the serialized object + */ + public static function toPathValue($value) + { + return rawurlencode(self::toString($value)); + } + + /** + * Checks if a value is empty, based on its OpenAPI type. + * + * @param mixed $value + * @param string $openApiType + * + * @return bool true if $value is empty + */ + private static function isEmptyValue($value, string $openApiType): bool + { + # If empty() returns false, it is not empty regardless of its type. + if (!empty($value)) { + return false; + } + + # Null is always empty, as we cannot send a real "null" value in a query parameter. + if ($value === null) { + return true; + } + + switch ($openApiType) { + # For numeric values, false and '' are considered empty. + # This comparison is safe for floating point values, since the previous call to empty() will + # filter out values that don't match 0. + case 'int': + case 'integer': + return $value !== 0; + + case 'number': + case 'float': + return $value !== 0 && $value !== 0.0; + + # For boolean values, '' is considered empty + case 'bool': + case 'boolean': + return !in_array($value, [false, 0], true); + + # For all the other types, any value at this point can be considered empty. + default: + return true; + } + } + + /** + * Take query parameter properties and turn it into an array suitable for + * native http_build_query or GuzzleHttp\Psr7\Query::build. + * + * @param mixed $value Parameter value + * @param string $paramName Parameter name + * @param string $openApiType OpenAPIType eg. array or object + * @param string $style Parameter serialization style + * @param bool $explode Parameter explode option + * @param bool $required Whether query param is required or not + * + * @return array + */ + public static function toQueryValue( + $value, + string $paramName, + string $openApiType = 'string', + string $style = 'form', + bool $explode = true, + bool $required = true + ): array { + + # Check if we should omit this parameter from the query. This should only happen when: + # - Parameter is NOT required; AND + # - its value is set to a value that is equivalent to "empty", depending on its OpenAPI type. For + # example, 0 as "int" or "boolean" is NOT an empty value. + if (self::isEmptyValue($value, $openApiType)) { + if ($required) { + return ["{$paramName}" => '']; + } else { + return []; + } + } + + # Handle DateTime objects in query + if($openApiType === "\\DateTime" && $value instanceof \DateTime) { + return ["{$paramName}" => $value->format(self::$dateTimeFormat)]; + } + + $query = []; + $value = (in_array($openApiType, ['object', 'array'], true)) ? (array)$value : $value; + + // since \GuzzleHttp\Psr7\Query::build fails with nested arrays + // need to flatten array first + $flattenArray = function ($arr, $name, &$result = []) use (&$flattenArray, $style, $explode) { + if (!is_array($arr)) return $arr; + + foreach ($arr as $k => $v) { + $prop = ($style === 'deepObject') ? $prop = "{$name}[{$k}]" : $k; + + if (is_array($v)) { + $flattenArray($v, $prop, $result); + } else { + if ($style !== 'deepObject' && !$explode) { + // push key itself + $result[] = $prop; + } + $result[$prop] = $v; + } + } + return $result; + }; + + $value = $flattenArray($value, $paramName); + + if ($openApiType === 'object' && ($style === 'deepObject' || $explode)) { + return $value; + } + + if ('boolean' === $openApiType && is_bool($value)) { + $value = self::convertBoolToQueryStringFormat($value); + } + + // handle style in serializeCollection + $query[$paramName] = ($explode) ? $value : self::serializeCollection((array)$value, $style); + + return $query; + } + + /** + * Convert boolean value to format for query string. + * + * @param bool $value Boolean value + * + * @return int|string Boolean value in format + */ + public static function convertBoolToQueryStringFormat(bool $value) + { + if (Configuration::BOOLEAN_FORMAT_STRING == Configuration::getDefaultConfiguration()->getBooleanFormatForQueryString()) { + return $value ? 'true' : 'false'; + } + + return (int) $value; + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the header. If it's a string, pass through unchanged + * If it's a datetime object, format it in ISO8601 + * + * @param string $value a string which will be part of the header + * + * @return string the header string + */ + public static function toHeaderValue($value) + { + $callable = [$value, 'toHeaderValue']; + if (is_callable($callable)) { + return $callable(); + } + + return self::toString($value); + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the http body (form parameter). If it's a string, pass through unchanged + * If it's a datetime object, format it in ISO8601 + * + * @param string|\SplFileObject $value the value of the form parameter + * + * @return string the form string + */ + public static function toFormValue($value) + { + if ($value instanceof \SplFileObject) { + return $value->getRealPath(); + } else { + return self::toString($value); + } + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the parameter. If it's a string, pass through unchanged + * If it's a datetime object, format it in ISO8601 + * If it's a boolean, convert it to "true" or "false". + * + * @param string|bool|\DateTime $value the value of the parameter + * + * @return string the header string + */ + public static function toString($value) + { + if ($value instanceof \DateTime) { // datetime in ISO8601 format + return $value->format(self::$dateTimeFormat); + } elseif (is_bool($value)) { + return $value ? 'true' : 'false'; + } else { + return (string) $value; + } + } + + /** + * Serialize an array to a string. + * + * @param array $collection collection to serialize to a string + * @param string $style the format use for serialization (csv, + * ssv, tsv, pipes, multi) + * @param bool $allowCollectionFormatMulti allow collection format to be a multidimensional array + * + * @return string + */ + public static function serializeCollection(array $collection, $style, $allowCollectionFormatMulti = false) + { + if ($allowCollectionFormatMulti && ('multi' === $style)) { + // http_build_query() almost does the job for us. We just + // need to fix the result of multidimensional arrays. + return preg_replace('/%5B[0-9]+%5D=/', '=', http_build_query($collection, '', '&')); + } + switch ($style) { + case 'pipeDelimited': + case 'pipes': + return implode('|', $collection); + + case 'tsv': + return implode("\t", $collection); + + case 'spaceDelimited': + case 'ssv': + return implode(' ', $collection); + + case 'simple': + case 'csv': + // Deliberate fall through. CSV is default format. + default: + return implode(',', $collection); + } + } + + /** + * Deserialize a JSON string into an object + * + * @param mixed $data object or primitive to be deserialized + * @param string $class class name is passed as a string + * @param string[] $httpHeaders HTTP headers + * @param string $discriminator discriminator if polymorphism is used + * + * @return object|array|null a single or an array of $class instances + */ + public static function deserialize($data, $class, $httpHeaders = null) + { + if (null === $data) { + return null; + } + + if (strcasecmp(substr($class, -2), '[]') === 0) { + $data = is_string($data) ? json_decode($data) : $data; + + if (!is_array($data)) { + throw new \InvalidArgumentException("Invalid array '$class'"); + } + + $subClass = substr($class, 0, -2); + $values = []; + foreach ($data as $key => $value) { + $values[] = self::deserialize($value, $subClass, null); + } + return $values; + } + + if (preg_match('/^(array<|map\[)/', $class)) { // for associative array e.g. array + $data = is_string($data) ? json_decode($data) : $data; + settype($data, 'array'); + $inner = substr($class, 4, -1); + $deserialized = []; + if (strrpos($inner, ",") !== false) { + $subClass_array = explode(',', $inner, 2); + $subClass = $subClass_array[1]; + foreach ($data as $key => $value) { + $deserialized[$key] = self::deserialize($value, $subClass, null); + } + } + return $deserialized; + } + + if ($class === 'object') { + settype($data, 'array'); + return $data; + } elseif ($class === 'mixed') { + settype($data, gettype($data)); + return $data; + } + + if ($class === '\DateTime') { + // Some APIs return an invalid, empty string as a + // date-time property. DateTime::__construct() will return + // the current time for empty input which is probably not + // what is meant. The invalid empty string is probably to + // be interpreted as a missing field/value. Let's handle + // this graceful. + if (!empty($data)) { + try { + return new \DateTime($data); + } catch (\Exception $exception) { + // Some APIs return a date-time with too high nanosecond + // precision for php's DateTime to handle. + // With provided regexp 6 digits of microseconds saved + return new \DateTime(self::sanitizeTimestamp($data)); + } + } else { + return null; + } + } + + if ($class === '\SplFileObject') { + $data = Utils::streamFor($data); + + /** @var \Psr\Http\Message\StreamInterface $data */ + + // determine file name + if ( + is_array($httpHeaders) + && array_key_exists('Content-Disposition', $httpHeaders) + && preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match) + ) { + $filename = Configuration::getDefaultConfiguration()->getTempFolderPath() . DIRECTORY_SEPARATOR . self::sanitizeFilename($match[1]); + } else { + $filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), ''); + } + + $file = fopen($filename, 'w'); + while ($chunk = $data->read(200)) { + fwrite($file, $chunk); + } + fclose($file); + + return new \SplFileObject($filename, 'r'); + } + + /** @psalm-suppress ParadoxicalCondition */ + if (in_array($class, ['\DateTime', '\SplFileObject', 'array', 'bool', 'boolean', 'byte', 'float', 'int', 'integer', 'mixed', 'number', 'object', 'string', 'void'], true)) { + settype($data, $class); + return $data; + } + + + if (method_exists($class, 'getAllowableEnumValues')) { + if (!in_array($data, $class::getAllowableEnumValues(), true)) { + $imploded = implode("', '", $class::getAllowableEnumValues()); + throw new \InvalidArgumentException("Invalid value for enum '$class', must be one of: '$imploded'"); + } + return $data; + } else { + $data = is_string($data) ? json_decode($data) : $data; + + if (is_array($data)) { + $data = (object)$data; + } + + // If a discriminator is defined and points to a valid subclass, use it. + $discriminator = $class::DISCRIMINATOR; + if (!empty($discriminator) && isset($data->{$discriminator}) && is_string($data->{$discriminator})) { + $subclass = '\OpenAPI\Client\Model\\' . $data->{$discriminator}; + if (is_subclass_of($subclass, $class)) { + $class = $subclass; + } + } + + /** @var ModelInterface $instance */ + $instance = new $class(); + foreach ($instance::openAPITypes() as $property => $type) { + $propertySetter = $instance::setters()[$property]; + + if (!isset($propertySetter)) { + continue; + } + + if (!isset($data->{$instance::attributeMap()[$property]})) { + if ($instance::isNullable($property)) { + $instance->$propertySetter(null); + } + + continue; + } + + if (isset($data->{$instance::attributeMap()[$property]})) { + $propertyValue = $data->{$instance::attributeMap()[$property]}; + $instance->$propertySetter(self::deserialize($propertyValue, $type, null)); + } + } + return $instance; + } + } + + /** + * Native `http_build_query` wrapper. + * @see https://www.php.net/manual/en/function.http-build-query + * + * @param array|object $data May be an array or object containing properties. + * @param string $numeric_prefix If numeric indices are used in the base array and this parameter is provided, it will be prepended to the numeric index for elements in the base array only. + * @param string|null $arg_separator arg_separator.output is used to separate arguments but may be overridden by specifying this parameter. + * @param int $encoding_type Encoding type. By default, PHP_QUERY_RFC1738. + * + * @return string + */ + public static function buildQuery( + $data, + string $numeric_prefix = '', + ?string $arg_separator = null, + int $encoding_type = \PHP_QUERY_RFC3986 + ): string { + return \GuzzleHttp\Psr7\Query::build($data, $encoding_type); + } +} diff --git a/other/master-clients/php/phpunit.xml.dist b/other/master-clients/php/phpunit.xml.dist new file mode 100644 index 000000000..485899aaf --- /dev/null +++ b/other/master-clients/php/phpunit.xml.dist @@ -0,0 +1,18 @@ + + + + + ./lib/Api + ./lib/Model + + + + + ./test/Api + ./test/Model + + + + + + diff --git a/other/master-clients/php/test/Api/DefaultApiTest.php b/other/master-clients/php/test/Api/DefaultApiTest.php new file mode 100644 index 000000000..b7f00479c --- /dev/null +++ b/other/master-clients/php/test/Api/DefaultApiTest.php @@ -0,0 +1,97 @@ +markTestIncomplete('Not implemented'); + } + + /** + * Test case for dirLookup + * + * Lookup volume. + * + */ + public function testDirLookup() + { + // TODO: implement + $this->markTestIncomplete('Not implemented'); + } +} diff --git a/other/master-clients/php/test/Model/FileKeyTest.php b/other/master-clients/php/test/Model/FileKeyTest.php new file mode 100644 index 000000000..27398e582 --- /dev/null +++ b/other/master-clients/php/test/Model/FileKeyTest.php @@ -0,0 +1,108 @@ +markTestIncomplete('Not implemented'); + } + + /** + * Test attribute "count" + */ + public function testPropertyCount() + { + // TODO: implement + $this->markTestIncomplete('Not implemented'); + } + + /** + * Test attribute "fid" + */ + public function testPropertyFid() + { + // TODO: implement + $this->markTestIncomplete('Not implemented'); + } + + /** + * Test attribute "url" + */ + public function testPropertyUrl() + { + // TODO: implement + $this->markTestIncomplete('Not implemented'); + } +} diff --git a/other/master-clients/php/test/Model/LocationTest.php b/other/master-clients/php/test/Model/LocationTest.php new file mode 100644 index 000000000..06829bf90 --- /dev/null +++ b/other/master-clients/php/test/Model/LocationTest.php @@ -0,0 +1,99 @@ +markTestIncomplete('Not implemented'); + } + + /** + * Test attribute "public_url" + */ + public function testPropertyPublicUrl() + { + // TODO: implement + $this->markTestIncomplete('Not implemented'); + } + + /** + * Test attribute "url" + */ + public function testPropertyUrl() + { + // TODO: implement + $this->markTestIncomplete('Not implemented'); + } +} diff --git a/other/master-clients/ruby/.gitignore b/other/master-clients/ruby/.gitignore new file mode 100644 index 000000000..05a17cb8f --- /dev/null +++ b/other/master-clients/ruby/.gitignore @@ -0,0 +1,39 @@ +# Generated by: https://openapi-generator.tech +# + +*.gem +*.rbc +/.config +/coverage/ +/InstalledFiles +/pkg/ +/spec/reports/ +/spec/examples.txt +/test/tmp/ +/test/version_tmp/ +/tmp/ + +## Specific to RubyMotion: +.dat* +.repl_history +build/ + +## Documentation cache and generated files: +/.yardoc/ +/_yardoc/ +/doc/ +/rdoc/ + +## Environment normalization: +/.bundle/ +/vendor/bundle +/lib/bundler/man/ + +# for a library or gem, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# Gemfile.lock +# .ruby-version +# .ruby-gemset + +# unless supporting rvm < 1.11.0 or doing something fancy, ignore this: +.rvmrc diff --git a/other/master-clients/ruby/.gitlab-ci.yml b/other/master-clients/ruby/.gitlab-ci.yml new file mode 100644 index 000000000..3a253c45c --- /dev/null +++ b/other/master-clients/ruby/.gitlab-ci.yml @@ -0,0 +1,26 @@ +.ruby: &ruby + variables: + LANG: "C.UTF-8" + before_script: + - ruby -v + - bundle config set --local deployment true + - bundle install -j $(nproc) + parallel: + matrix: + - RUBY_VERSION: ['2.7', '3.0', '3.1'] + image: "ruby:$RUBY_VERSION" + cache: + paths: + - vendor/ruby + key: 'ruby-$RUBY_VERSION' + +gem: + extends: .ruby + script: + - bundle exec rspec + - bundle exec rake build + - bundle exec rake install + artifacts: + paths: + - pkg/*.gem + diff --git a/other/master-clients/ruby/.openapi-generator-ignore b/other/master-clients/ruby/.openapi-generator-ignore new file mode 100644 index 000000000..7484ee590 --- /dev/null +++ b/other/master-clients/ruby/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/other/master-clients/ruby/.openapi-generator/FILES b/other/master-clients/ruby/.openapi-generator/FILES new file mode 100644 index 000000000..4dc6d4422 --- /dev/null +++ b/other/master-clients/ruby/.openapi-generator/FILES @@ -0,0 +1,28 @@ +.gitignore +.gitlab-ci.yml +.openapi-generator-ignore +.rspec +.rubocop.yml +.travis.yml +Gemfile +README.md +Rakefile +docs/DefaultApi.md +docs/FileKey.md +docs/Location.md +git_push.sh +lib/openapi_client.rb +lib/openapi_client/api/default_api.rb +lib/openapi_client/api_client.rb +lib/openapi_client/api_error.rb +lib/openapi_client/configuration.rb +lib/openapi_client/models/file_key.rb +lib/openapi_client/models/location.rb +lib/openapi_client/version.rb +openapi_client.gemspec +spec/api/default_api_spec.rb +spec/api_client_spec.rb +spec/configuration_spec.rb +spec/models/file_key_spec.rb +spec/models/location_spec.rb +spec/spec_helper.rb diff --git a/other/master-clients/ruby/.openapi-generator/VERSION b/other/master-clients/ruby/.openapi-generator/VERSION new file mode 100644 index 000000000..c0be8a799 --- /dev/null +++ b/other/master-clients/ruby/.openapi-generator/VERSION @@ -0,0 +1 @@ +6.4.0 \ No newline at end of file diff --git a/other/master-clients/ruby/.rspec b/other/master-clients/ruby/.rspec new file mode 100644 index 000000000..83e16f804 --- /dev/null +++ b/other/master-clients/ruby/.rspec @@ -0,0 +1,2 @@ +--color +--require spec_helper diff --git a/other/master-clients/ruby/.rubocop.yml b/other/master-clients/ruby/.rubocop.yml new file mode 100644 index 000000000..d32b2b1cd --- /dev/null +++ b/other/master-clients/ruby/.rubocop.yml @@ -0,0 +1,148 @@ +# This file is based on https://github.com/rails/rails/blob/master/.rubocop.yml (MIT license) +# Automatically generated by OpenAPI Generator (https://openapi-generator.tech) +AllCops: + TargetRubyVersion: 2.4 + # RuboCop has a bunch of cops enabled by default. This setting tells RuboCop + # to ignore them, so only the ones explicitly set in this file are enabled. + DisabledByDefault: true + Exclude: + - '**/templates/**/*' + - '**/vendor/**/*' + - 'actionpack/lib/action_dispatch/journey/parser.rb' + +# Prefer &&/|| over and/or. +Style/AndOr: + Enabled: true + +# Align `when` with `case`. +Layout/CaseIndentation: + Enabled: true + +# Align comments with method definitions. +Layout/CommentIndentation: + Enabled: true + +Layout/ElseAlignment: + Enabled: true + +Layout/EmptyLineAfterMagicComment: + Enabled: true + +# In a regular class definition, no empty lines around the body. +Layout/EmptyLinesAroundClassBody: + Enabled: true + +# In a regular method definition, no empty lines around the body. +Layout/EmptyLinesAroundMethodBody: + Enabled: true + +# In a regular module definition, no empty lines around the body. +Layout/EmptyLinesAroundModuleBody: + Enabled: true + +Layout/FirstArgumentIndentation: + Enabled: true + +# Use Ruby >= 1.9 syntax for hashes. Prefer { a: :b } over { :a => :b }. +Style/HashSyntax: + Enabled: false + +# Method definitions after `private` or `protected` isolated calls need one +# extra level of indentation. +Layout/IndentationConsistency: + Enabled: true + EnforcedStyle: indented_internal_methods + +# Two spaces, no tabs (for indentation). +Layout/IndentationWidth: + Enabled: true + +Layout/LeadingCommentSpace: + Enabled: true + +Layout/SpaceAfterColon: + Enabled: true + +Layout/SpaceAfterComma: + Enabled: true + +Layout/SpaceAroundEqualsInParameterDefault: + Enabled: true + +Layout/SpaceAroundKeyword: + Enabled: true + +Layout/SpaceAroundOperators: + Enabled: true + +Layout/SpaceBeforeComma: + Enabled: true + +Layout/SpaceBeforeFirstArg: + Enabled: true + +Style/DefWithParentheses: + Enabled: true + +# Defining a method with parameters needs parentheses. +Style/MethodDefParentheses: + Enabled: true + +Style/FrozenStringLiteralComment: + Enabled: false + EnforcedStyle: always + +# Use `foo {}` not `foo{}`. +Layout/SpaceBeforeBlockBraces: + Enabled: true + +# Use `foo { bar }` not `foo {bar}`. +Layout/SpaceInsideBlockBraces: + Enabled: true + +# Use `{ a: 1 }` not `{a:1}`. +Layout/SpaceInsideHashLiteralBraces: + Enabled: true + +Layout/SpaceInsideParens: + Enabled: true + +# Check quotes usage according to lint rule below. +#Style/StringLiterals: +# Enabled: true +# EnforcedStyle: single_quotes + +# Detect hard tabs, no hard tabs. +Layout/IndentationStyle: + Enabled: true + +# Blank lines should not have any spaces. +Layout/TrailingEmptyLines: + Enabled: true + +# No trailing whitespace. +Layout/TrailingWhitespace: + Enabled: false + +# Use quotes for string literals when they are enough. +Style/RedundantPercentQ: + Enabled: true + +# Align `end` with the matching keyword or starting expression except for +# assignments, where it should be aligned with the LHS. +Layout/EndAlignment: + Enabled: true + EnforcedStyleAlignWith: variable + AutoCorrect: true + +# Use my_method(my_arg) not my_method( my_arg ) or my_method my_arg. +Lint/RequireParentheses: + Enabled: true + +Style/RedundantReturn: + Enabled: true + AllowMultipleReturnValues: true + +Style/Semicolon: + Enabled: true + AllowAsExpressionSeparator: true diff --git a/other/master-clients/ruby/.travis.yml b/other/master-clients/ruby/.travis.yml new file mode 100644 index 000000000..ef5d971f6 --- /dev/null +++ b/other/master-clients/ruby/.travis.yml @@ -0,0 +1,11 @@ +language: ruby +cache: bundler +rvm: + - 2.7 + - 3.0 + - 3.1 +script: + - bundle install --path vendor/bundle + - bundle exec rspec + - gem build openapi_client.gemspec + - gem install ./openapi_client-1.0.0.gem diff --git a/other/master-clients/ruby/Gemfile b/other/master-clients/ruby/Gemfile new file mode 100644 index 000000000..c2e3127cd --- /dev/null +++ b/other/master-clients/ruby/Gemfile @@ -0,0 +1,9 @@ +source 'https://rubygems.org' + +gemspec + +group :development, :test do + gem 'rake', '~> 13.0.1' + gem 'pry-byebug' + gem 'rubocop', '~> 0.66.0' +end diff --git a/other/master-clients/ruby/README.md b/other/master-clients/ruby/README.md new file mode 100644 index 000000000..b751679c8 --- /dev/null +++ b/other/master-clients/ruby/README.md @@ -0,0 +1,103 @@ +# openapi_client + +OpenapiClient - the Ruby gem for the Seaweedfs Master Server API + +The Seaweedfs Master Server API allows you to store blobs + +This SDK is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: 3.43.0 +- Package version: 1.0.0 +- Build package: org.openapitools.codegen.languages.RubyClientCodegen + +## Installation + +### Build a gem + +To build the Ruby code into a gem: + +```shell +gem build openapi_client.gemspec +``` + +Then either install the gem locally: + +```shell +gem install ./openapi_client-1.0.0.gem +``` + +(for development, run `gem install --dev ./openapi_client-1.0.0.gem` to install the development dependencies) + +or publish the gem to a gem hosting service, e.g. [RubyGems](https://rubygems.org/). + +Finally add this to the Gemfile: + + gem 'openapi_client', '~> 1.0.0' + +### Install from Git + +If the Ruby gem is hosted at a git repository: https://github.com/GIT_USER_ID/GIT_REPO_ID, then add the following in the Gemfile: + + gem 'openapi_client', :git => 'https://github.com/GIT_USER_ID/GIT_REPO_ID.git' + +### Include the Ruby code directly + +Include the Ruby code directly using `-I` as follows: + +```shell +ruby -Ilib script.rb +``` + +## Getting Started + +Please follow the [installation](#installation) procedure and then run the following code: + +```ruby +# Load the gem +require 'openapi_client' + +api_instance = OpenapiClient::DefaultApi.new +opts = { + count: TODO, # Object | how many file ids to assign. Use _1, _2 for the assigned additional file ids. e.g. 3,01637037d6_1, 3,01637037d6_2 + collection: TODO, # Object | required collection name + data_center: TODO, # Object | preferred data center + rack: TODO, # Object | preferred rack + data_node: TODO, # Object | preferred volume server, e.g. 127.0.0.1:8080 + disk: TODO, # Object | If you have disks labelled, this must be supplied to specify the disk type to allocate on. + replication: TODO, # Object | replica placement strategy + ttl: TODO, # Object | file expiration time limit, example: 3m for 3 minutes. units: m-minute, h-hour, d-day, w-week, M-month, y-year + preallocate: TODO, # Object | If no matching volumes, pre-allocate this number of bytes on disk for new volumes. + memory_map_max_size_mb: TODO, # Object | Only implemented for windows. Use memory mapped files with specified size for new volumes. + writable_volume_count: TODO # Object | If no matching volumes, create specified number of new volumes. +} + +begin + #Assign a file key + result = api_instance.dir_assign(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Exception when calling DefaultApi->dir_assign: #{e}" +end + +``` + +## Documentation for API Endpoints + +All URIs are relative to *https://127.0.0.1:9333* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*OpenapiClient::DefaultApi* | [**dir_assign**](docs/DefaultApi.md#dir_assign) | **GET** /dir/assign | Assign a file key +*OpenapiClient::DefaultApi* | [**dir_lookup**](docs/DefaultApi.md#dir_lookup) | **GET** /dir/lookup | Lookup volume + + +## Documentation for Models + + - [OpenapiClient::FileKey](docs/FileKey.md) + - [OpenapiClient::Location](docs/Location.md) + + +## Documentation for Authorization + + All endpoints do not require authorization. + diff --git a/other/master-clients/ruby/Rakefile b/other/master-clients/ruby/Rakefile new file mode 100644 index 000000000..c72ca30d4 --- /dev/null +++ b/other/master-clients/ruby/Rakefile @@ -0,0 +1,10 @@ +require "bundler/gem_tasks" + +begin + require 'rspec/core/rake_task' + + RSpec::Core::RakeTask.new(:spec) + task default: :spec +rescue LoadError + # no rspec available +end diff --git a/other/master-clients/ruby/docs/DefaultApi.md b/other/master-clients/ruby/docs/DefaultApi.md new file mode 100644 index 000000000..dcb49c7f3 --- /dev/null +++ b/other/master-clients/ruby/docs/DefaultApi.md @@ -0,0 +1,167 @@ +# OpenapiClient::DefaultApi + +All URIs are relative to *https://127.0.0.1:9333* + +| Method | HTTP request | Description | +| ------ | ------------ | ----------- | +| [**dir_assign**](DefaultApi.md#dir_assign) | **GET** /dir/assign | Assign a file key | +| [**dir_lookup**](DefaultApi.md#dir_lookup) | **GET** /dir/lookup | Lookup volume | + + +## dir_assign + +> dir_assign(opts) + +Assign a file key + +This operation is very cheap. Just increase a number in master server's memory. + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::DefaultApi.new +opts = { + count: TODO, # Object | how many file ids to assign. Use _1, _2 for the assigned additional file ids. e.g. 3,01637037d6_1, 3,01637037d6_2 + collection: TODO, # Object | required collection name + data_center: TODO, # Object | preferred data center + rack: TODO, # Object | preferred rack + data_node: TODO, # Object | preferred volume server, e.g. 127.0.0.1:8080 + disk: TODO, # Object | If you have disks labelled, this must be supplied to specify the disk type to allocate on. + replication: TODO, # Object | replica placement strategy + ttl: TODO, # Object | file expiration time limit, example: 3m for 3 minutes. units: m-minute, h-hour, d-day, w-week, M-month, y-year + preallocate: TODO, # Object | If no matching volumes, pre-allocate this number of bytes on disk for new volumes. + memory_map_max_size_mb: TODO, # Object | Only implemented for windows. Use memory mapped files with specified size for new volumes. + writable_volume_count: TODO # Object | If no matching volumes, create specified number of new volumes. +} + +begin + # Assign a file key + result = api_instance.dir_assign(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling DefaultApi->dir_assign: #{e}" +end +``` + +#### Using the dir_assign_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> , Integer, Hash)> dir_assign_with_http_info(opts) + +```ruby +begin + # Assign a file key + data, status_code, headers = api_instance.dir_assign_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => +rescue OpenapiClient::ApiError => e + puts "Error when calling DefaultApi->dir_assign_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **count** | [**Object**](.md) | how many file ids to assign. Use <fid>_1, <fid>_2 for the assigned additional file ids. e.g. 3,01637037d6_1, 3,01637037d6_2 | [optional] | +| **collection** | [**Object**](.md) | required collection name | [optional] | +| **data_center** | [**Object**](.md) | preferred data center | [optional] | +| **rack** | [**Object**](.md) | preferred rack | [optional] | +| **data_node** | [**Object**](.md) | preferred volume server, e.g. 127.0.0.1:8080 | [optional] | +| **disk** | [**Object**](.md) | If you have disks labelled, this must be supplied to specify the disk type to allocate on. | [optional] | +| **replication** | [**Object**](.md) | replica placement strategy | [optional] | +| **ttl** | [**Object**](.md) | file expiration time limit, example: 3m for 3 minutes. units: m-minute, h-hour, d-day, w-week, M-month, y-year | [optional] | +| **preallocate** | [**Object**](.md) | If no matching volumes, pre-allocate this number of bytes on disk for new volumes. | [optional] | +| **memory_map_max_size_mb** | [**Object**](.md) | Only implemented for windows. Use memory mapped files with specified size for new volumes. | [optional] | +| **writable_volume_count** | [**Object**](.md) | If no matching volumes, create specified number of new volumes. | [optional] | + +### Return type + +[**FileKey**](FileKey.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + + +## dir_lookup + +> Object dir_lookup(opts) + +Lookup volume + +We would need to find out whether the volumes have moved. + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::DefaultApi.new +opts = { + volume_id: TODO, # Object | volume id + collection: TODO, # Object | optionally to speed up the lookup + file_id: TODO, # Object | If provided, this returns the fileId location and a JWT to update or delete the file. + read: TODO # Object | works together with \"fileId\", if read=yes, JWT is generated for reads. +} + +begin + # Lookup volume + result = api_instance.dir_lookup(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling DefaultApi->dir_lookup: #{e}" +end +``` + +#### Using the dir_lookup_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> dir_lookup_with_http_info(opts) + +```ruby +begin + # Lookup volume + data, status_code, headers = api_instance.dir_lookup_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => Object +rescue OpenapiClient::ApiError => e + puts "Error when calling DefaultApi->dir_lookup_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **volume_id** | [**Object**](.md) | volume id | [optional] | +| **collection** | [**Object**](.md) | optionally to speed up the lookup | [optional] | +| **file_id** | [**Object**](.md) | If provided, this returns the fileId location and a JWT to update or delete the file. | [optional] | +| **read** | [**Object**](.md) | works together with \"fileId\", if read=yes, JWT is generated for reads. | [optional] | + +### Return type + +**Object** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + diff --git a/other/master-clients/ruby/docs/FileKey.md b/other/master-clients/ruby/docs/FileKey.md new file mode 100644 index 000000000..40a0bc7f8 --- /dev/null +++ b/other/master-clients/ruby/docs/FileKey.md @@ -0,0 +1,22 @@ +# OpenapiClient::FileKey + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **count** | **Object** | | [optional] | +| **fid** | **Object** | | [optional] | +| **url** | **Object** | | [optional] | + +## Example + +```ruby +require 'openapi_client' + +instance = OpenapiClient::FileKey.new( + count: 10, + fid: 3,01637037d6, + url: 127.0.0.1:8080 +) +``` + diff --git a/other/master-clients/ruby/docs/Location.md b/other/master-clients/ruby/docs/Location.md new file mode 100644 index 000000000..0963dd868 --- /dev/null +++ b/other/master-clients/ruby/docs/Location.md @@ -0,0 +1,20 @@ +# OpenapiClient::Location + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **public_url** | **Object** | | [optional] | +| **url** | **Object** | | [optional] | + +## Example + +```ruby +require 'openapi_client' + +instance = OpenapiClient::Location.new( + public_url: localhost:8080, + url: localhost:8080 +) +``` + diff --git a/other/master-clients/ruby/git_push.sh b/other/master-clients/ruby/git_push.sh new file mode 100644 index 000000000..f53a75d4f --- /dev/null +++ b/other/master-clients/ruby/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/other/master-clients/ruby/lib/openapi_client.rb b/other/master-clients/ruby/lib/openapi_client.rb new file mode 100644 index 000000000..94adc4225 --- /dev/null +++ b/other/master-clients/ruby/lib/openapi_client.rb @@ -0,0 +1,42 @@ +=begin +#Seaweedfs Master Server API + +#The Seaweedfs Master Server API allows you to store blobs + +The version of the OpenAPI document: 3.43.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.4.0 + +=end + +# Common files +require 'openapi_client/api_client' +require 'openapi_client/api_error' +require 'openapi_client/version' +require 'openapi_client/configuration' + +# Models +require 'openapi_client/models/file_key' +require 'openapi_client/models/location' + +# APIs +require 'openapi_client/api/default_api' + +module OpenapiClient + class << self + # Customize default settings for the SDK using block. + # OpenapiClient.configure do |config| + # config.username = "xxx" + # config.password = "xxx" + # end + # If no block given, return the default Configuration object. + def configure + if block_given? + yield(Configuration.default) + else + Configuration.default + end + end + end +end diff --git a/other/master-clients/ruby/lib/openapi_client/api/default_api.rb b/other/master-clients/ruby/lib/openapi_client/api/default_api.rb new file mode 100644 index 000000000..9b1a93bd5 --- /dev/null +++ b/other/master-clients/ruby/lib/openapi_client/api/default_api.rb @@ -0,0 +1,181 @@ +=begin +#Seaweedfs Master Server API + +#The Seaweedfs Master Server API allows you to store blobs + +The version of the OpenAPI document: 3.43.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.4.0 + +=end + +require 'cgi' + +module OpenapiClient + class DefaultApi + attr_accessor :api_client + + def initialize(api_client = ApiClient.default) + @api_client = api_client + end + # Assign a file key + # This operation is very cheap. Just increase a number in master server's memory. + # @param [Hash] opts the optional parameters + # @option opts [Object] :count how many file ids to assign. Use <fid>_1, <fid>_2 for the assigned additional file ids. e.g. 3,01637037d6_1, 3,01637037d6_2 + # @option opts [Object] :collection required collection name + # @option opts [Object] :data_center preferred data center + # @option opts [Object] :rack preferred rack + # @option opts [Object] :data_node preferred volume server, e.g. 127.0.0.1:8080 + # @option opts [Object] :disk If you have disks labelled, this must be supplied to specify the disk type to allocate on. + # @option opts [Object] :replication replica placement strategy + # @option opts [Object] :ttl file expiration time limit, example: 3m for 3 minutes. units: m-minute, h-hour, d-day, w-week, M-month, y-year + # @option opts [Object] :preallocate If no matching volumes, pre-allocate this number of bytes on disk for new volumes. + # @option opts [Object] :memory_map_max_size_mb Only implemented for windows. Use memory mapped files with specified size for new volumes. + # @option opts [Object] :writable_volume_count If no matching volumes, create specified number of new volumes. + # @return [FileKey] + def dir_assign(opts = {}) + data, _status_code, _headers = dir_assign_with_http_info(opts) + data + end + + # Assign a file key + # This operation is very cheap. Just increase a number in master server's memory. + # @param [Hash] opts the optional parameters + # @option opts [Object] :count how many file ids to assign. Use <fid>_1, <fid>_2 for the assigned additional file ids. e.g. 3,01637037d6_1, 3,01637037d6_2 + # @option opts [Object] :collection required collection name + # @option opts [Object] :data_center preferred data center + # @option opts [Object] :rack preferred rack + # @option opts [Object] :data_node preferred volume server, e.g. 127.0.0.1:8080 + # @option opts [Object] :disk If you have disks labelled, this must be supplied to specify the disk type to allocate on. + # @option opts [Object] :replication replica placement strategy + # @option opts [Object] :ttl file expiration time limit, example: 3m for 3 minutes. units: m-minute, h-hour, d-day, w-week, M-month, y-year + # @option opts [Object] :preallocate If no matching volumes, pre-allocate this number of bytes on disk for new volumes. + # @option opts [Object] :memory_map_max_size_mb Only implemented for windows. Use memory mapped files with specified size for new volumes. + # @option opts [Object] :writable_volume_count If no matching volumes, create specified number of new volumes. + # @return [Array<(FileKey, Integer, Hash)>] FileKey data, response status code and response headers + def dir_assign_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: DefaultApi.dir_assign ...' + end + # resource path + local_var_path = '/dir/assign' + + # query parameters + query_params = opts[:query_params] || {} + query_params[:'count'] = opts[:'count'] if !opts[:'count'].nil? + query_params[:'collection'] = opts[:'collection'] if !opts[:'collection'].nil? + query_params[:'dataCenter'] = opts[:'data_center'] if !opts[:'data_center'].nil? + query_params[:'rack'] = opts[:'rack'] if !opts[:'rack'].nil? + query_params[:'dataNode'] = opts[:'data_node'] if !opts[:'data_node'].nil? + query_params[:'disk'] = opts[:'disk'] if !opts[:'disk'].nil? + query_params[:'replication'] = opts[:'replication'] if !opts[:'replication'].nil? + query_params[:'ttl'] = opts[:'ttl'] if !opts[:'ttl'].nil? + query_params[:'preallocate'] = opts[:'preallocate'] if !opts[:'preallocate'].nil? + query_params[:'memoryMapMaxSizeMb'] = opts[:'memory_map_max_size_mb'] if !opts[:'memory_map_max_size_mb'].nil? + query_params[:'writableVolumeCount'] = opts[:'writable_volume_count'] if !opts[:'writable_volume_count'].nil? + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['application/json']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'FileKey' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"DefaultApi.dir_assign", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: DefaultApi#dir_assign\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Lookup volume + # We would need to find out whether the volumes have moved. + # @param [Hash] opts the optional parameters + # @option opts [Object] :volume_id volume id + # @option opts [Object] :collection optionally to speed up the lookup + # @option opts [Object] :file_id If provided, this returns the fileId location and a JWT to update or delete the file. + # @option opts [Object] :read works together with \"fileId\", if read=yes, JWT is generated for reads. + # @return [Object] + def dir_lookup(opts = {}) + data, _status_code, _headers = dir_lookup_with_http_info(opts) + data + end + + # Lookup volume + # We would need to find out whether the volumes have moved. + # @param [Hash] opts the optional parameters + # @option opts [Object] :volume_id volume id + # @option opts [Object] :collection optionally to speed up the lookup + # @option opts [Object] :file_id If provided, this returns the fileId location and a JWT to update or delete the file. + # @option opts [Object] :read works together with \"fileId\", if read=yes, JWT is generated for reads. + # @return [Array<(Object, Integer, Hash)>] Object data, response status code and response headers + def dir_lookup_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: DefaultApi.dir_lookup ...' + end + # resource path + local_var_path = '/dir/lookup' + + # query parameters + query_params = opts[:query_params] || {} + query_params[:'volumeId'] = opts[:'volume_id'] if !opts[:'volume_id'].nil? + query_params[:'collection'] = opts[:'collection'] if !opts[:'collection'].nil? + query_params[:'fileId'] = opts[:'file_id'] if !opts[:'file_id'].nil? + query_params[:'read'] = opts[:'read'] if !opts[:'read'].nil? + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['application/json']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'Object' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"DefaultApi.dir_lookup", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: DefaultApi#dir_lookup\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + end +end diff --git a/other/master-clients/ruby/lib/openapi_client/api_client.rb b/other/master-clients/ruby/lib/openapi_client/api_client.rb new file mode 100644 index 000000000..deac56b60 --- /dev/null +++ b/other/master-clients/ruby/lib/openapi_client/api_client.rb @@ -0,0 +1,391 @@ +=begin +#Seaweedfs Master Server API + +#The Seaweedfs Master Server API allows you to store blobs + +The version of the OpenAPI document: 3.43.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.4.0 + +=end + +require 'date' +require 'json' +require 'logger' +require 'tempfile' +require 'time' +require 'typhoeus' + +module OpenapiClient + class ApiClient + # The Configuration object holding settings to be used in the API client. + attr_accessor :config + + # Defines the headers to be used in HTTP requests of all API calls by default. + # + # @return [Hash] + attr_accessor :default_headers + + # Initializes the ApiClient + # @option config [Configuration] Configuration for initializing the object, default to Configuration.default + def initialize(config = Configuration.default) + @config = config + @user_agent = "OpenAPI-Generator/#{VERSION}/ruby" + @default_headers = { + 'Content-Type' => 'application/json', + 'User-Agent' => @user_agent + } + end + + def self.default + @@default ||= ApiClient.new + end + + # Call an API with given options. + # + # @return [Array<(Object, Integer, Hash)>] an array of 3 elements: + # the data deserialized from response body (could be nil), response status code and response headers. + def call_api(http_method, path, opts = {}) + request = build_request(http_method, path, opts) + response = request.run + + if @config.debugging + @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n" + end + + unless response.success? + if response.timed_out? + fail ApiError.new('Connection timed out') + elsif response.code == 0 + # Errors from libcurl will be made visible here + fail ApiError.new(:code => 0, + :message => response.return_message) + else + fail ApiError.new(:code => response.code, + :response_headers => response.headers, + :response_body => response.body), + response.status_message + end + end + + if opts[:return_type] + data = deserialize(response, opts[:return_type]) + else + data = nil + end + return data, response.code, response.headers + end + + # Builds the HTTP request + # + # @param [String] http_method HTTP method/verb (e.g. POST) + # @param [String] path URL path (e.g. /account/new) + # @option opts [Hash] :header_params Header parameters + # @option opts [Hash] :query_params Query parameters + # @option opts [Hash] :form_params Query parameters + # @option opts [Object] :body HTTP body (JSON/XML) + # @return [Typhoeus::Request] A Typhoeus Request + def build_request(http_method, path, opts = {}) + url = build_request_url(path, opts) + http_method = http_method.to_sym.downcase + + header_params = @default_headers.merge(opts[:header_params] || {}) + query_params = opts[:query_params] || {} + form_params = opts[:form_params] || {} + follow_location = opts[:follow_location] || true + + + # set ssl_verifyhosts option based on @config.verify_ssl_host (true/false) + _verify_ssl_host = @config.verify_ssl_host ? 2 : 0 + + req_opts = { + :method => http_method, + :headers => header_params, + :params => query_params, + :params_encoding => @config.params_encoding, + :timeout => @config.timeout, + :ssl_verifypeer => @config.verify_ssl, + :ssl_verifyhost => _verify_ssl_host, + :sslcert => @config.cert_file, + :sslkey => @config.key_file, + :verbose => @config.debugging, + :followlocation => follow_location + } + + # set custom cert, if provided + req_opts[:cainfo] = @config.ssl_ca_cert if @config.ssl_ca_cert + + if [:post, :patch, :put, :delete].include?(http_method) + req_body = build_request_body(header_params, form_params, opts[:body]) + req_opts.update :body => req_body + if @config.debugging + @config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n" + end + end + + request = Typhoeus::Request.new(url, req_opts) + download_file(request) if opts[:return_type] == 'File' + request + end + + # Builds the HTTP request body + # + # @param [Hash] header_params Header parameters + # @param [Hash] form_params Query parameters + # @param [Object] body HTTP body (JSON/XML) + # @return [String] HTTP body data in the form of string + def build_request_body(header_params, form_params, body) + # http form + if header_params['Content-Type'] == 'application/x-www-form-urlencoded' || + header_params['Content-Type'] == 'multipart/form-data' + data = {} + form_params.each do |key, value| + case value + when ::File, ::Array, nil + # let typhoeus handle File, Array and nil parameters + data[key] = value + else + data[key] = value.to_s + end + end + elsif body + data = body.is_a?(String) ? body : body.to_json + else + data = nil + end + data + end + + # Save response body into a file in (the defined) temporary folder, using the filename + # from the "Content-Disposition" header if provided, otherwise a random filename. + # The response body is written to the file in chunks in order to handle files which + # size is larger than maximum Ruby String or even larger than the maximum memory a Ruby + # process can use. + # + # @see Configuration#temp_folder_path + def download_file(request) + tempfile = nil + encoding = nil + request.on_headers do |response| + content_disposition = response.headers['Content-Disposition'] + if content_disposition && content_disposition =~ /filename=/i + filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] + prefix = sanitize_filename(filename) + else + prefix = 'download-' + end + prefix = prefix + '-' unless prefix.end_with?('-') + encoding = response.body.encoding + tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding) + @tempfile = tempfile + end + request.on_body do |chunk| + chunk.force_encoding(encoding) + tempfile.write(chunk) + end + request.on_complete do |response| + if tempfile + tempfile.close + @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\ + "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\ + "will be deleted automatically with GC. It's also recommended to delete the temp file "\ + "explicitly with `tempfile.delete`" + end + end + end + + # Check if the given MIME is a JSON MIME. + # JSON MIME examples: + # application/json + # application/json; charset=UTF8 + # APPLICATION/JSON + # */* + # @param [String] mime MIME + # @return [Boolean] True if the MIME is application/json + def json_mime?(mime) + (mime == '*/*') || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil? + end + + # Deserialize the response to the given return type. + # + # @param [Response] response HTTP response + # @param [String] return_type some examples: "User", "Array", "Hash" + def deserialize(response, return_type) + body = response.body + + # handle file downloading - return the File instance processed in request callbacks + # note that response body is empty when the file is written in chunks in request on_body callback + return @tempfile if return_type == 'File' + + return nil if body.nil? || body.empty? + + # return response body directly for String return type + return body if return_type == 'String' + + # ensuring a default content type + content_type = response.headers['Content-Type'] || 'application/json' + + fail "Content-Type is not supported: #{content_type}" unless json_mime?(content_type) + + begin + data = JSON.parse("[#{body}]", :symbolize_names => true)[0] + rescue JSON::ParserError => e + if %w(String Date Time).include?(return_type) + data = body + else + raise e + end + end + + convert_to_type data, return_type + end + + # Convert data to the given return type. + # @param [Object] data Data to be converted + # @param [String] return_type Return type + # @return [Mixed] Data in a particular type + def convert_to_type(data, return_type) + return nil if data.nil? + case return_type + when 'String' + data.to_s + when 'Integer' + data.to_i + when 'Float' + data.to_f + when 'Boolean' + data == true + when 'Time' + # parse date time (expecting ISO 8601 format) + Time.parse data + when 'Date' + # parse date time (expecting ISO 8601 format) + Date.parse data + when 'Object' + # generic object (usually a Hash), return directly + data + when /\AArray<(.+)>\z/ + # e.g. Array + sub_type = $1 + data.map { |item| convert_to_type(item, sub_type) } + when /\AHash\\z/ + # e.g. Hash + sub_type = $1 + {}.tap do |hash| + data.each { |k, v| hash[k] = convert_to_type(v, sub_type) } + end + else + # models (e.g. Pet) or oneOf + klass = OpenapiClient.const_get(return_type) + klass.respond_to?(:openapi_one_of) ? klass.build(data) : klass.build_from_hash(data) + end + end + + # Sanitize filename by removing path. + # e.g. ../../sun.gif becomes sun.gif + # + # @param [String] filename the filename to be sanitized + # @return [String] the sanitized filename + def sanitize_filename(filename) + filename.gsub(/.*[\/\\]/, '') + end + + def build_request_url(path, opts = {}) + # Add leading and trailing slashes to path + path = "/#{path}".gsub(/\/+/, '/') + @config.base_url(opts[:operation]) + path + end + + # Update header and query params based on authentication settings. + # + # @param [Hash] header_params Header parameters + # @param [Hash] query_params Query parameters + # @param [String] auth_names Authentication scheme name + def update_params_for_auth!(header_params, query_params, auth_names) + Array(auth_names).each do |auth_name| + auth_setting = @config.auth_settings[auth_name] + next unless auth_setting + case auth_setting[:in] + when 'header' then header_params[auth_setting[:key]] = auth_setting[:value] + when 'query' then query_params[auth_setting[:key]] = auth_setting[:value] + else fail ArgumentError, 'Authentication token must be in `query` or `header`' + end + end + end + + # Sets user agent in HTTP header + # + # @param [String] user_agent User agent (e.g. openapi-generator/ruby/1.0.0) + def user_agent=(user_agent) + @user_agent = user_agent + @default_headers['User-Agent'] = @user_agent + end + + # Return Accept header based on an array of accepts provided. + # @param [Array] accepts array for Accept + # @return [String] the Accept header (e.g. application/json) + def select_header_accept(accepts) + return nil if accepts.nil? || accepts.empty? + # use JSON when present, otherwise use all of the provided + json_accept = accepts.find { |s| json_mime?(s) } + json_accept || accepts.join(',') + end + + # Return Content-Type header based on an array of content types provided. + # @param [Array] content_types array for Content-Type + # @return [String] the Content-Type header (e.g. application/json) + def select_header_content_type(content_types) + # return nil by default + return if content_types.nil? || content_types.empty? + # use JSON when present, otherwise use the first one + json_content_type = content_types.find { |s| json_mime?(s) } + json_content_type || content_types.first + end + + # Convert object (array, hash, object, etc) to JSON string. + # @param [Object] model object to be converted into JSON string + # @return [String] JSON string representation of the object + def object_to_http_body(model) + return model if model.nil? || model.is_a?(String) + local_body = nil + if model.is_a?(Array) + local_body = model.map { |m| object_to_hash(m) } + else + local_body = object_to_hash(model) + end + local_body.to_json + end + + # Convert object(non-array) to hash. + # @param [Object] obj object to be converted into JSON string + # @return [String] JSON string representation of the object + def object_to_hash(obj) + if obj.respond_to?(:to_hash) + obj.to_hash + else + obj + end + end + + # Build parameter value according to the given collection format. + # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi + def build_collection_param(param, collection_format) + case collection_format + when :csv + param.join(',') + when :ssv + param.join(' ') + when :tsv + param.join("\t") + when :pipes + param.join('|') + when :multi + # return the array directly as typhoeus will handle it as expected + param + else + fail "unknown collection format: #{collection_format.inspect}" + end + end + end +end diff --git a/other/master-clients/ruby/lib/openapi_client/api_error.rb b/other/master-clients/ruby/lib/openapi_client/api_error.rb new file mode 100644 index 000000000..c123b90c3 --- /dev/null +++ b/other/master-clients/ruby/lib/openapi_client/api_error.rb @@ -0,0 +1,58 @@ +=begin +#Seaweedfs Master Server API + +#The Seaweedfs Master Server API allows you to store blobs + +The version of the OpenAPI document: 3.43.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.4.0 + +=end + +module OpenapiClient + class ApiError < StandardError + attr_reader :code, :response_headers, :response_body + + # Usage examples: + # ApiError.new + # ApiError.new("message") + # ApiError.new(:code => 500, :response_headers => {}, :response_body => "") + # ApiError.new(:code => 404, :message => "Not Found") + def initialize(arg = nil) + if arg.is_a? Hash + if arg.key?(:message) || arg.key?('message') + super(arg[:message] || arg['message']) + else + super arg + end + + arg.each do |k, v| + instance_variable_set "@#{k}", v + end + else + super arg + @message = arg + end + end + + # Override to_s to display a friendly error message + def to_s + message + end + + def message + if @message.nil? + msg = "Error message: the server returns an error" + else + msg = @message + end + + msg += "\nHTTP status code: #{code}" if code + msg += "\nResponse headers: #{response_headers}" if response_headers + msg += "\nResponse body: #{response_body}" if response_body + + msg + end + end +end diff --git a/other/master-clients/ruby/lib/openapi_client/configuration.rb b/other/master-clients/ruby/lib/openapi_client/configuration.rb new file mode 100644 index 000000000..406f1df61 --- /dev/null +++ b/other/master-clients/ruby/lib/openapi_client/configuration.rb @@ -0,0 +1,283 @@ +=begin +#Seaweedfs Master Server API + +#The Seaweedfs Master Server API allows you to store blobs + +The version of the OpenAPI document: 3.43.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.4.0 + +=end + +module OpenapiClient + class Configuration + # Defines url scheme + attr_accessor :scheme + + # Defines url host + attr_accessor :host + + # Defines url base path + attr_accessor :base_path + + # Define server configuration index + attr_accessor :server_index + + # Define server operation configuration index + attr_accessor :server_operation_index + + # Default server variables + attr_accessor :server_variables + + # Default server operation variables + attr_accessor :server_operation_variables + + # Defines API keys used with API Key authentications. + # + # @return [Hash] key: parameter name, value: parameter value (API key) + # + # @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string) + # config.api_key['api_key'] = 'xxx' + attr_accessor :api_key + + # Defines API key prefixes used with API Key authentications. + # + # @return [Hash] key: parameter name, value: API key prefix + # + # @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers) + # config.api_key_prefix['api_key'] = 'Token' + attr_accessor :api_key_prefix + + # Defines the username used with HTTP basic authentication. + # + # @return [String] + attr_accessor :username + + # Defines the password used with HTTP basic authentication. + # + # @return [String] + attr_accessor :password + + # Defines the access token (Bearer) used with OAuth2. + attr_accessor :access_token + + # Defines a Proc used to fetch or refresh access tokens (Bearer) used with OAuth2. + # Overrides the access_token if set + # @return [Proc] + attr_accessor :access_token_getter + + # Set this to enable/disable debugging. When enabled (set to true), HTTP request/response + # details will be logged with `logger.debug` (see the `logger` attribute). + # Default to false. + # + # @return [true, false] + attr_accessor :debugging + + # Defines the logger used for debugging. + # Default to `Rails.logger` (when in Rails) or logging to STDOUT. + # + # @return [#debug] + attr_accessor :logger + + # Defines the temporary folder to store downloaded files + # (for API endpoints that have file response). + # Default to use `Tempfile`. + # + # @return [String] + attr_accessor :temp_folder_path + + # The time limit for HTTP request in seconds. + # Default to 0 (never times out). + attr_accessor :timeout + + # Set this to false to skip client side validation in the operation. + # Default to true. + # @return [true, false] + attr_accessor :client_side_validation + + ### TLS/SSL setting + # Set this to false to skip verifying SSL certificate when calling API from https server. + # Default to true. + # + # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. + # + # @return [true, false] + attr_accessor :verify_ssl + + ### TLS/SSL setting + # Set this to false to skip verifying SSL host name + # Default to true. + # + # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. + # + # @return [true, false] + attr_accessor :verify_ssl_host + + ### TLS/SSL setting + # Set this to customize the certificate file to verify the peer. + # + # @return [String] the path to the certificate file + # + # @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code: + # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145 + attr_accessor :ssl_ca_cert + + ### TLS/SSL setting + # Client certificate file (for client certificate) + attr_accessor :cert_file + + ### TLS/SSL setting + # Client private key file (for client certificate) + attr_accessor :key_file + + # Set this to customize parameters encoding of array parameter with multi collectionFormat. + # Default to nil. + # + # @see The params_encoding option of Ethon. Related source code: + # https://github.com/typhoeus/ethon/blob/master/lib/ethon/easy/queryable.rb#L96 + attr_accessor :params_encoding + + + attr_accessor :inject_format + + attr_accessor :force_ending_format + + def initialize + @scheme = 'https' + @host = '127.0.0.1:9333' + @base_path = '' + @server_index = 0 + @server_operation_index = {} + @server_variables = {} + @server_operation_variables = {} + @api_key = {} + @api_key_prefix = {} + @client_side_validation = true + @verify_ssl = true + @verify_ssl_host = true + @cert_file = nil + @key_file = nil + @timeout = 0 + @params_encoding = nil + @debugging = false + @inject_format = false + @force_ending_format = false + @logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT) + + yield(self) if block_given? + end + + # The default Configuration object. + def self.default + @@default ||= Configuration.new + end + + def configure + yield(self) if block_given? + end + + def scheme=(scheme) + # remove :// from scheme + @scheme = scheme.sub(/:\/\//, '') + end + + def host=(host) + # remove http(s):// and anything after a slash + @host = host.sub(/https?:\/\//, '').split('/').first + end + + def base_path=(base_path) + # Add leading and trailing slashes to base_path + @base_path = "/#{base_path}".gsub(/\/+/, '/') + @base_path = '' if @base_path == '/' + end + + # Returns base URL for specified operation based on server settings + def base_url(operation = nil) + index = server_operation_index.fetch(operation, server_index) + return "#{scheme}://#{[host, base_path].join('/').gsub(/\/+/, '/')}".sub(/\/+\z/, '') if index == nil + + server_url(index, server_operation_variables.fetch(operation, server_variables), operation_server_settings[operation]) + end + + # Gets API key (with prefix if set). + # @param [String] param_name the parameter name of API key auth + def api_key_with_prefix(param_name, param_alias = nil) + key = @api_key[param_name] + key = @api_key.fetch(param_alias, key) unless param_alias.nil? + if @api_key_prefix[param_name] + "#{@api_key_prefix[param_name]} #{key}" + else + key + end + end + + # Gets access_token using access_token_getter or uses the static access_token + def access_token_with_refresh + return access_token if access_token_getter.nil? + access_token_getter.call + end + + # Gets Basic Auth token string + def basic_auth_token + 'Basic ' + ["#{username}:#{password}"].pack('m').delete("\r\n") + end + + # Returns Auth Settings hash for api client. + def auth_settings + { + } + end + + # Returns an array of Server setting + def server_settings + [ + { + url: "https://127.0.0.1:9333", + description: "No description provided", + } + ] + end + + def operation_server_settings + { + } + end + + # Returns URL based on server settings + # + # @param index array index of the server settings + # @param variables hash of variable and the corresponding value + def server_url(index, variables = {}, servers = nil) + servers = server_settings if servers == nil + + # check array index out of bound + if (index < 0 || index >= servers.size) + fail ArgumentError, "Invalid index #{index} when selecting the server. Must be less than #{servers.size}" + end + + server = servers[index] + url = server[:url] + + return url unless server.key? :variables + + # go through variable and assign a value + server[:variables].each do |name, variable| + if variables.key?(name) + if (!server[:variables][name].key?(:enum_values) || server[:variables][name][:enum_values].include?(variables[name])) + url.gsub! "{" + name.to_s + "}", variables[name] + else + fail ArgumentError, "The variable `#{name}` in the server URL has invalid value #{variables[name]}. Must be #{server[:variables][name][:enum_values]}." + end + else + # use default value + url.gsub! "{" + name.to_s + "}", server[:variables][name][:default_value] + end + end + + url + end + + end +end diff --git a/other/master-clients/ruby/lib/openapi_client/models/file_key.rb b/other/master-clients/ruby/lib/openapi_client/models/file_key.rb new file mode 100644 index 000000000..85a30c366 --- /dev/null +++ b/other/master-clients/ruby/lib/openapi_client/models/file_key.rb @@ -0,0 +1,240 @@ +=begin +#Seaweedfs Master Server API + +#The Seaweedfs Master Server API allows you to store blobs + +The version of the OpenAPI document: 3.43.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.4.0 + +=end + +require 'date' +require 'time' + +module OpenapiClient + class FileKey + attr_accessor :count + + attr_accessor :fid + + attr_accessor :url + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'count' => :'count', + :'fid' => :'fid', + :'url' => :'url' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'count' => :'Object', + :'fid' => :'Object', + :'url' => :'Object' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + :'count', + :'fid', + :'url' + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `OpenapiClient::FileKey` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `OpenapiClient::FileKey`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'count') + self.count = attributes[:'count'] + end + + if attributes.key?(:'fid') + self.fid = attributes[:'fid'] + end + + if attributes.key?(:'url') + self.url = attributes[:'url'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + count == o.count && + fid == o.fid && + url == o.url + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [count, fid, url].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = OpenapiClient.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/other/master-clients/ruby/lib/openapi_client/models/location.rb b/other/master-clients/ruby/lib/openapi_client/models/location.rb new file mode 100644 index 000000000..ca1ea56b5 --- /dev/null +++ b/other/master-clients/ruby/lib/openapi_client/models/location.rb @@ -0,0 +1,230 @@ +=begin +#Seaweedfs Master Server API + +#The Seaweedfs Master Server API allows you to store blobs + +The version of the OpenAPI document: 3.43.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.4.0 + +=end + +require 'date' +require 'time' + +module OpenapiClient + class Location + attr_accessor :public_url + + attr_accessor :url + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'public_url' => :'publicUrl', + :'url' => :'url' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'public_url' => :'Object', + :'url' => :'Object' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + :'public_url', + :'url' + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `OpenapiClient::Location` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `OpenapiClient::Location`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'public_url') + self.public_url = attributes[:'public_url'] + end + + if attributes.key?(:'url') + self.url = attributes[:'url'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + public_url == o.public_url && + url == o.url + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [public_url, url].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = OpenapiClient.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/other/master-clients/ruby/lib/openapi_client/version.rb b/other/master-clients/ruby/lib/openapi_client/version.rb new file mode 100644 index 000000000..aefb28c98 --- /dev/null +++ b/other/master-clients/ruby/lib/openapi_client/version.rb @@ -0,0 +1,15 @@ +=begin +#Seaweedfs Master Server API + +#The Seaweedfs Master Server API allows you to store blobs + +The version of the OpenAPI document: 3.43.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.4.0 + +=end + +module OpenapiClient + VERSION = '1.0.0' +end diff --git a/other/master-clients/ruby/openapi_client.gemspec b/other/master-clients/ruby/openapi_client.gemspec new file mode 100644 index 000000000..e64530bc1 --- /dev/null +++ b/other/master-clients/ruby/openapi_client.gemspec @@ -0,0 +1,38 @@ +# -*- encoding: utf-8 -*- + +=begin +#Seaweedfs Master Server API + +#The Seaweedfs Master Server API allows you to store blobs + +The version of the OpenAPI document: 3.43.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.4.0 + +=end + +$:.push File.expand_path("../lib", __FILE__) +require "openapi_client/version" + +Gem::Specification.new do |s| + s.name = "openapi_client" + s.version = OpenapiClient::VERSION + s.platform = Gem::Platform::RUBY + s.authors = ["OpenAPI-Generator"] + s.email = [""] + s.homepage = "https://openapi-generator.tech" + s.summary = "Seaweedfs Master Server API Ruby Gem" + s.description = "The Seaweedfs Master Server API allows you to store blobs" + s.license = "Unlicense" + s.required_ruby_version = ">= 2.7" + + s.add_runtime_dependency 'typhoeus', '~> 1.0', '>= 1.0.1' + + s.add_development_dependency 'rspec', '~> 3.6', '>= 3.6.0' + + s.files = `find *`.split("\n").uniq.sort.select { |f| !f.empty? } + s.test_files = `find spec/*`.split("\n") + s.executables = [] + s.require_paths = ["lib"] +end diff --git a/other/master-clients/ruby/spec/api/default_api_spec.rb b/other/master-clients/ruby/spec/api/default_api_spec.rb new file mode 100644 index 000000000..e97e5e011 --- /dev/null +++ b/other/master-clients/ruby/spec/api/default_api_spec.rb @@ -0,0 +1,72 @@ +=begin +#Seaweedfs Master Server API + +#The Seaweedfs Master Server API allows you to store blobs + +The version of the OpenAPI document: 3.43.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.4.0 + +=end + +require 'spec_helper' +require 'json' + +# Unit tests for OpenapiClient::DefaultApi +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe 'DefaultApi' do + before do + # run before each test + @api_instance = OpenapiClient::DefaultApi.new + end + + after do + # run after each test + end + + describe 'test an instance of DefaultApi' do + it 'should create an instance of DefaultApi' do + expect(@api_instance).to be_instance_of(OpenapiClient::DefaultApi) + end + end + + # unit tests for dir_assign + # Assign a file key + # This operation is very cheap. Just increase a number in master server's memory. + # @param [Hash] opts the optional parameters + # @option opts [Object] :count how many file ids to assign. Use <fid>_1, <fid>_2 for the assigned additional file ids. e.g. 3,01637037d6_1, 3,01637037d6_2 + # @option opts [Object] :collection required collection name + # @option opts [Object] :data_center preferred data center + # @option opts [Object] :rack preferred rack + # @option opts [Object] :data_node preferred volume server, e.g. 127.0.0.1:8080 + # @option opts [Object] :disk If you have disks labelled, this must be supplied to specify the disk type to allocate on. + # @option opts [Object] :replication replica placement strategy + # @option opts [Object] :ttl file expiration time limit, example: 3m for 3 minutes. units: m-minute, h-hour, d-day, w-week, M-month, y-year + # @option opts [Object] :preallocate If no matching volumes, pre-allocate this number of bytes on disk for new volumes. + # @option opts [Object] :memory_map_max_size_mb Only implemented for windows. Use memory mapped files with specified size for new volumes. + # @option opts [Object] :writable_volume_count If no matching volumes, create specified number of new volumes. + # @return [FileKey] + describe 'dir_assign test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for dir_lookup + # Lookup volume + # We would need to find out whether the volumes have moved. + # @param [Hash] opts the optional parameters + # @option opts [Object] :volume_id volume id + # @option opts [Object] :collection optionally to speed up the lookup + # @option opts [Object] :file_id If provided, this returns the fileId location and a JWT to update or delete the file. + # @option opts [Object] :read works together with \"fileId\", if read=yes, JWT is generated for reads. + # @return [Object] + describe 'dir_lookup test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/other/master-clients/ruby/spec/api_client_spec.rb b/other/master-clients/ruby/spec/api_client_spec.rb new file mode 100644 index 000000000..915dd13b6 --- /dev/null +++ b/other/master-clients/ruby/spec/api_client_spec.rb @@ -0,0 +1,228 @@ +=begin +#Seaweedfs Master Server API + +#The Seaweedfs Master Server API allows you to store blobs + +The version of the OpenAPI document: 3.43.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.4.0 + +=end + +require 'spec_helper' + +describe OpenapiClient::ApiClient do + context 'initialization' do + context 'URL stuff' do + context 'host' do + it 'removes http from host' do + OpenapiClient.configure { |c| c.host = 'http://example.com' } + expect(OpenapiClient::Configuration.default.host).to eq('example.com') + end + + it 'removes https from host' do + OpenapiClient.configure { |c| c.host = 'https://wookiee.com' } + expect(OpenapiClient::ApiClient.default.config.host).to eq('wookiee.com') + end + + it 'removes trailing path from host' do + OpenapiClient.configure { |c| c.host = 'hobo.com/v4' } + expect(OpenapiClient::Configuration.default.host).to eq('hobo.com') + end + end + + context 'base_path' do + it "prepends a slash to base_path" do + OpenapiClient.configure { |c| c.base_path = 'v4/dog' } + expect(OpenapiClient::Configuration.default.base_path).to eq('/v4/dog') + end + + it "doesn't prepend a slash if one is already there" do + OpenapiClient.configure { |c| c.base_path = '/v4/dog' } + expect(OpenapiClient::Configuration.default.base_path).to eq('/v4/dog') + end + + it "ends up as a blank string if nil" do + OpenapiClient.configure { |c| c.base_path = nil } + expect(OpenapiClient::Configuration.default.base_path).to eq('') + end + end + end + end + + describe 'params_encoding in #build_request' do + let(:config) { OpenapiClient::Configuration.new } + let(:api_client) { OpenapiClient::ApiClient.new(config) } + + it 'defaults to nil' do + expect(OpenapiClient::Configuration.default.params_encoding).to eq(nil) + expect(config.params_encoding).to eq(nil) + + request = api_client.build_request(:get, '/test') + expect(request.options[:params_encoding]).to eq(nil) + end + + it 'can be customized' do + config.params_encoding = :multi + request = api_client.build_request(:get, '/test') + expect(request.options[:params_encoding]).to eq(:multi) + end + end + + describe 'timeout in #build_request' do + let(:config) { OpenapiClient::Configuration.new } + let(:api_client) { OpenapiClient::ApiClient.new(config) } + + it 'defaults to 0' do + expect(OpenapiClient::Configuration.default.timeout).to eq(0) + expect(config.timeout).to eq(0) + + request = api_client.build_request(:get, '/test') + expect(request.options[:timeout]).to eq(0) + end + + it 'can be customized' do + config.timeout = 100 + request = api_client.build_request(:get, '/test') + expect(request.options[:timeout]).to eq(100) + end + end + + + + describe '#deserialize' do + it "handles Array" do + api_client = OpenapiClient::ApiClient.new + headers = { 'Content-Type' => 'application/json' } + response = double('response', headers: headers, body: '[12, 34]') + data = api_client.deserialize(response, 'Array') + expect(data).to be_instance_of(Array) + expect(data).to eq([12, 34]) + end + + it 'handles Array>' do + api_client = OpenapiClient::ApiClient.new + headers = { 'Content-Type' => 'application/json' } + response = double('response', headers: headers, body: '[[12, 34], [56]]') + data = api_client.deserialize(response, 'Array>') + expect(data).to be_instance_of(Array) + expect(data).to eq([[12, 34], [56]]) + end + + it 'handles Hash' do + api_client = OpenapiClient::ApiClient.new + headers = { 'Content-Type' => 'application/json' } + response = double('response', headers: headers, body: '{"message": "Hello"}') + data = api_client.deserialize(response, 'Hash') + expect(data).to be_instance_of(Hash) + expect(data).to eq(:message => 'Hello') + end + end + + describe "#object_to_hash" do + it 'ignores nils and includes empty arrays' do + # uncomment below to test object_to_hash for model + # api_client = OpenapiClient::ApiClient.new + # _model = OpenapiClient::ModelName.new + # update the model attribute below + # _model.id = 1 + # update the expected value (hash) below + # expected = {id: 1, name: '', tags: []} + # expect(api_client.object_to_hash(_model)).to eq(expected) + end + end + + describe '#build_collection_param' do + let(:param) { ['aa', 'bb', 'cc'] } + let(:api_client) { OpenapiClient::ApiClient.new } + + it 'works for csv' do + expect(api_client.build_collection_param(param, :csv)).to eq('aa,bb,cc') + end + + it 'works for ssv' do + expect(api_client.build_collection_param(param, :ssv)).to eq('aa bb cc') + end + + it 'works for tsv' do + expect(api_client.build_collection_param(param, :tsv)).to eq("aa\tbb\tcc") + end + + it 'works for pipes' do + expect(api_client.build_collection_param(param, :pipes)).to eq('aa|bb|cc') + end + + it 'works for multi' do + expect(api_client.build_collection_param(param, :multi)).to eq(['aa', 'bb', 'cc']) + end + + it 'fails for invalid collection format' do + expect { api_client.build_collection_param(param, :INVALID) }.to raise_error(RuntimeError, 'unknown collection format: :INVALID') + end + end + + describe '#json_mime?' do + let(:api_client) { OpenapiClient::ApiClient.new } + + it 'works' do + expect(api_client.json_mime?(nil)).to eq false + expect(api_client.json_mime?('')).to eq false + + expect(api_client.json_mime?('application/json')).to eq true + expect(api_client.json_mime?('application/json; charset=UTF8')).to eq true + expect(api_client.json_mime?('APPLICATION/JSON')).to eq true + + expect(api_client.json_mime?('application/xml')).to eq false + expect(api_client.json_mime?('text/plain')).to eq false + expect(api_client.json_mime?('application/jsonp')).to eq false + end + end + + describe '#select_header_accept' do + let(:api_client) { OpenapiClient::ApiClient.new } + + it 'works' do + expect(api_client.select_header_accept(nil)).to be_nil + expect(api_client.select_header_accept([])).to be_nil + + expect(api_client.select_header_accept(['application/json'])).to eq('application/json') + expect(api_client.select_header_accept(['application/xml', 'application/json; charset=UTF8'])).to eq('application/json; charset=UTF8') + expect(api_client.select_header_accept(['APPLICATION/JSON', 'text/html'])).to eq('APPLICATION/JSON') + + expect(api_client.select_header_accept(['application/xml'])).to eq('application/xml') + expect(api_client.select_header_accept(['text/html', 'application/xml'])).to eq('text/html,application/xml') + end + end + + describe '#select_header_content_type' do + let(:api_client) { OpenapiClient::ApiClient.new } + + it 'works' do + expect(api_client.select_header_content_type(nil)).to be_nil + expect(api_client.select_header_content_type([])).to be_nil + + expect(api_client.select_header_content_type(['application/json'])).to eq('application/json') + expect(api_client.select_header_content_type(['application/xml', 'application/json; charset=UTF8'])).to eq('application/json; charset=UTF8') + expect(api_client.select_header_content_type(['APPLICATION/JSON', 'text/html'])).to eq('APPLICATION/JSON') + expect(api_client.select_header_content_type(['application/xml'])).to eq('application/xml') + expect(api_client.select_header_content_type(['text/plain', 'application/xml'])).to eq('text/plain') + end + end + + describe '#sanitize_filename' do + let(:api_client) { OpenapiClient::ApiClient.new } + + it 'works' do + expect(api_client.sanitize_filename('sun')).to eq('sun') + expect(api_client.sanitize_filename('sun.gif')).to eq('sun.gif') + expect(api_client.sanitize_filename('../sun.gif')).to eq('sun.gif') + expect(api_client.sanitize_filename('/var/tmp/sun.gif')).to eq('sun.gif') + expect(api_client.sanitize_filename('./sun.gif')).to eq('sun.gif') + expect(api_client.sanitize_filename('..\sun.gif')).to eq('sun.gif') + expect(api_client.sanitize_filename('\var\tmp\sun.gif')).to eq('sun.gif') + expect(api_client.sanitize_filename('c:\var\tmp\sun.gif')).to eq('sun.gif') + expect(api_client.sanitize_filename('.\sun.gif')).to eq('sun.gif') + end + end +end diff --git a/other/master-clients/ruby/spec/configuration_spec.rb b/other/master-clients/ruby/spec/configuration_spec.rb new file mode 100644 index 000000000..0a7a0f884 --- /dev/null +++ b/other/master-clients/ruby/spec/configuration_spec.rb @@ -0,0 +1,42 @@ +=begin +#Seaweedfs Master Server API + +#The Seaweedfs Master Server API allows you to store blobs + +The version of the OpenAPI document: 3.43.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.4.0 + +=end + +require 'spec_helper' + +describe OpenapiClient::Configuration do + let(:config) { OpenapiClient::Configuration.default } + + before(:each) do + # uncomment below to setup host and base_path + # require 'URI' + # uri = URI.parse("https://127.0.0.1:9333") + # OpenapiClient.configure do |c| + # c.host = uri.host + # c.base_path = uri.path + # end + end + + describe '#base_url' do + it 'should have the default value' do + # uncomment below to test default value of the base path + # expect(config.base_url).to eq("https://127.0.0.1:9333") + end + + it 'should remove trailing slashes' do + [nil, '', '/', '//'].each do |base_path| + config.base_path = base_path + # uncomment below to test trailing slashes + # expect(config.base_url).to eq("https://127.0.0.1:9333") + end + end + end +end diff --git a/other/master-clients/ruby/spec/models/file_key_spec.rb b/other/master-clients/ruby/spec/models/file_key_spec.rb new file mode 100644 index 000000000..6507983c1 --- /dev/null +++ b/other/master-clients/ruby/spec/models/file_key_spec.rb @@ -0,0 +1,46 @@ +=begin +#Seaweedfs Master Server API + +#The Seaweedfs Master Server API allows you to store blobs + +The version of the OpenAPI document: 3.43.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.4.0 + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for OpenapiClient::FileKey +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe OpenapiClient::FileKey do + let(:instance) { OpenapiClient::FileKey.new } + + describe 'test an instance of FileKey' do + it 'should create an instance of FileKey' do + expect(instance).to be_instance_of(OpenapiClient::FileKey) + end + end + describe 'test attribute "count"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "fid"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "url"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/other/master-clients/ruby/spec/models/location_spec.rb b/other/master-clients/ruby/spec/models/location_spec.rb new file mode 100644 index 000000000..419cb005b --- /dev/null +++ b/other/master-clients/ruby/spec/models/location_spec.rb @@ -0,0 +1,40 @@ +=begin +#Seaweedfs Master Server API + +#The Seaweedfs Master Server API allows you to store blobs + +The version of the OpenAPI document: 3.43.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.4.0 + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for OpenapiClient::Location +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe OpenapiClient::Location do + let(:instance) { OpenapiClient::Location.new } + + describe 'test an instance of Location' do + it 'should create an instance of Location' do + expect(instance).to be_instance_of(OpenapiClient::Location) + end + end + describe 'test attribute "public_url"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "url"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/other/master-clients/ruby/spec/spec_helper.rb b/other/master-clients/ruby/spec/spec_helper.rb new file mode 100644 index 000000000..56e8dd446 --- /dev/null +++ b/other/master-clients/ruby/spec/spec_helper.rb @@ -0,0 +1,111 @@ +=begin +#Seaweedfs Master Server API + +#The Seaweedfs Master Server API allows you to store blobs + +The version of the OpenAPI document: 3.43.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.4.0 + +=end + +# load the gem +require 'openapi_client' + +# The following was generated by the `rspec --init` command. Conventionally, all +# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. +# The generated `.rspec` file contains `--require spec_helper` which will cause +# this file to always be loaded, without a need to explicitly require it in any +# files. +# +# Given that it is always loaded, you are encouraged to keep this file as +# light-weight as possible. Requiring heavyweight dependencies from this file +# will add to the boot time of your test suite on EVERY test run, even for an +# individual file that may not need all of that loaded. Instead, consider making +# a separate helper file that requires the additional dependencies and performs +# the additional setup, and require it from the spec files that actually need +# it. +# +# The `.rspec` file also contains a few flags that are not defaults but that +# users commonly want. +# +# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration +RSpec.configure do |config| + # rspec-expectations config goes here. You can use an alternate + # assertion/expectation library such as wrong or the stdlib/minitest + # assertions if you prefer. + config.expect_with :rspec do |expectations| + # This option will default to `true` in RSpec 4. It makes the `description` + # and `failure_message` of custom matchers include text for helper methods + # defined using `chain`, e.g.: + # be_bigger_than(2).and_smaller_than(4).description + # # => "be bigger than 2 and smaller than 4" + # ...rather than: + # # => "be bigger than 2" + expectations.include_chain_clauses_in_custom_matcher_descriptions = true + end + + # rspec-mocks config goes here. You can use an alternate test double + # library (such as bogus or mocha) by changing the `mock_with` option here. + config.mock_with :rspec do |mocks| + # Prevents you from mocking or stubbing a method that does not exist on + # a real object. This is generally recommended, and will default to + # `true` in RSpec 4. + mocks.verify_partial_doubles = true + end + +# The settings below are suggested to provide a good initial experience +# with RSpec, but feel free to customize to your heart's content. +=begin + # These two settings work together to allow you to limit a spec run + # to individual examples or groups you care about by tagging them with + # `:focus` metadata. When nothing is tagged with `:focus`, all examples + # get run. + config.filter_run :focus + config.run_all_when_everything_filtered = true + + # Allows RSpec to persist some state between runs in order to support + # the `--only-failures` and `--next-failure` CLI options. We recommend + # you configure your source control system to ignore this file. + config.example_status_persistence_file_path = "spec/examples.txt" + + # Limits the available syntax to the non-monkey patched syntax that is + # recommended. For more details, see: + # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/ + # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ + # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode + config.disable_monkey_patching! + + # This setting enables warnings. It's recommended, but in some cases may + # be too noisy due to issues in dependencies. + config.warnings = true + + # Many RSpec users commonly either run the entire suite or an individual + # file, and it's useful to allow more verbose output when running an + # individual spec file. + if config.files_to_run.one? + # Use the documentation formatter for detailed output, + # unless a formatter has already been configured + # (e.g. via a command-line flag). + config.default_formatter = 'doc' + end + + # Print the 10 slowest examples and example groups at the + # end of the spec run, to help surface which specs are running + # particularly slow. + config.profile_examples = 10 + + # Run specs in random order to surface order dependencies. If you find an + # order dependency and want to debug it, you can fix the order by providing + # the seed, which is printed after each run. + # --seed 1234 + config.order = :random + + # Seed global randomization in this process using the `--seed` CLI option. + # Setting this allows you to use `--seed` to deterministically reproduce + # test failures related to randomization by passing the same `--seed` value + # as the one that triggered the failure. + Kernel.srand config.seed +=end +end diff --git a/other/swagger/Makefile b/other/swagger/Makefile new file mode 100644 index 000000000..54fb41a90 --- /dev/null +++ b/other/swagger/Makefile @@ -0,0 +1,4 @@ +gen: + for lang in cpp-restsdk csharp go kotlin-client php python ruby; do \ + openapi-generator generate -i master.yaml -g $$lang -o ../master-clients/$$lang; \ + done \ No newline at end of file diff --git a/other/swagger/master.yaml b/other/swagger/master.yaml new file mode 100644 index 000000000..e157466c2 --- /dev/null +++ b/other/swagger/master.yaml @@ -0,0 +1,141 @@ +openapi: 3.1.0 +info: + title: Seaweedfs Master Server API + description: |- + The Seaweedfs Master Server API allows you to store blobs + version: 3.43.0 +servers: + - url: https://127.0.0.1:9333/ +paths: + /dir/assign: + get: + summary: Assign a file key + description: This operation is very cheap. Just increase a number in master server's memory. + operationId: dirAssign + parameters: + - name: count + in: query + description: how many file ids to assign. Use _1, _2 for the assigned additional file ids. e.g. 3,01637037d6_1, 3,01637037d6_2 + schema: + type: integer + format: int32 + - name: collection + in: query + description: required collection name + schema: + type: string + - name: dataCenter + in: query + description: preferred data center + schema: + type: string + - name: rack + in: query + description: preferred rack + schema: + type: string + - name: dataNode + in: query + description: preferred volume server, e.g. 127.0.0.1:8080 + schema: + type: string + - name: disk + in: query + description: If you have disks labelled, this must be supplied to specify the disk type to allocate on. + schema: + type: string + - name: replication + in: query + description: replica placement strategy + schema: + type: string + - name: ttl + in: query + description: "file expiration time limit, example: 3m for 3 minutes. units: m-minute, h-hour, d-day, w-week, M-month, y-year" + schema: + type: string + - name: preallocate + in: query + description: If no matching volumes, pre-allocate this number of bytes on disk for new volumes. + schema: + type: integer + format: int64 + - name: memoryMapMaxSizeMb + in: query + description: Only implemented for windows. Use memory mapped files with specified size for new volumes. + schema: + type: integer + format: int32 + - name: writableVolumeCount + in: query + description: If no matching volumes, create specified number of new volumes. + schema: + type: integer + format: int32 + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/FileKey' + /dir/lookup: + get: + summary: Lookup volume + description: We would need to find out whether the volumes have moved. + operationId: dirLookup + parameters: + - name: volumeId + in: query + description: volume id + schema: + type: integer + format: int32 + - name: collection + in: query + description: optionally to speed up the lookup + schema: + type: string + - name: fileId + in: query + description: If provided, this returns the fileId location and a JWT to update or delete the file. + schema: + type: string + - name: read + in: query + description: works together with "fileId", if read=yes, JWT is generated for reads. + schema: + type: string + responses: + '200': + description: successful operation + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Location' +components: + schemas: + FileKey: + type: object + properties: + count: + type: integer + format: int64 + example: 10 + fid: + type: string + example: 3,01637037d6 + url: + type: string + example: 127.0.0.1:8080 + Location: + type: object + properties: + publicUrl: + type: string + example: localhost:8080 + url: + type: string + example: localhost:8080 \ No newline at end of file