code
stringlengths
1
1.05M
repo_name
stringlengths
7
65
path
stringlengths
2
255
language
stringclasses
236 values
license
stringclasses
24 values
size
int64
1
1.05M
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "DeserializerTest.hpp" #include "oatpp/parser/json/mapping/ObjectMapper.hpp" #include "oatpp/core/macro/codegen.hpp" namespace oatpp { namespace test { namespace parser { namespace json { namespace mapping { namespace { #include OATPP_CODEGEN_BEGIN(DTO) typedef oatpp::parser::Caret ParsingCaret; typedef oatpp::parser::json::mapping::Serializer Serializer; typedef oatpp::parser::json::mapping::Deserializer Deserializer; class EmptyDto : public oatpp::DTO { DTO_INIT(EmptyDto, DTO) }; class Test1 : public oatpp::DTO { DTO_INIT(Test1, DTO) DTO_FIELD(String, strF); }; class Test2 : public oatpp::DTO { DTO_INIT(Test2, DTO) DTO_FIELD(Int32, int32F); }; class Test3 : public oatpp::DTO { DTO_INIT(Test3, DTO) DTO_FIELD(Float32, float32F); }; class Test4 : public oatpp::DTO { DTO_INIT(Test4, DTO) DTO_FIELD(Object<EmptyDto>, object); DTO_FIELD(List<Object<EmptyDto>>, list); DTO_FIELD(Fields<Object<EmptyDto>>, map); }; class AnyDto : public oatpp::DTO { DTO_INIT(AnyDto, DTO) DTO_FIELD(Any, any); }; #include OATPP_CODEGEN_END(DTO) } void DeserializerTest::onRun(){ auto mapper = oatpp::parser::json::mapping::ObjectMapper::createShared(); auto obj1 = mapper->readFromString<oatpp::Object<Test1>>("{}"); OATPP_ASSERT(obj1); OATPP_ASSERT(!obj1->strF); obj1 = mapper->readFromString<oatpp::Object<Test1>>("{\"strF\":\"value1\"}"); OATPP_ASSERT(obj1); OATPP_ASSERT(obj1->strF); OATPP_ASSERT(obj1->strF == "value1"); obj1 = mapper->readFromString<oatpp::Object<Test1>>("{\n\r\t\f\"strF\"\n\r\t\f:\n\r\t\f\"value1\"\n\r\t\f}"); OATPP_ASSERT(obj1); OATPP_ASSERT(obj1->strF); OATPP_ASSERT(obj1->strF == "value1"); auto obj2 = mapper->readFromString<oatpp::Object<Test2>>("{\"int32F\": null}"); OATPP_ASSERT(obj2); OATPP_ASSERT(!obj2->int32F); obj2 = mapper->readFromString<oatpp::Object<Test2>>("{\"int32F\": 32}"); OATPP_ASSERT(obj2); OATPP_ASSERT(obj2->int32F == 32); obj2 = mapper->readFromString<oatpp::Object<Test2>>("{\"int32F\": -32}"); OATPP_ASSERT(obj2); OATPP_ASSERT(obj2->int32F == -32); auto obj3 = mapper->readFromString<oatpp::Object<Test3>>("{\"float32F\": null}"); OATPP_ASSERT(obj3); OATPP_ASSERT(!obj3->float32F); obj3 = mapper->readFromString<oatpp::Object<Test3>>("{\"float32F\": 32}"); OATPP_ASSERT(obj3); OATPP_ASSERT(obj3->float32F == 32); obj3 = mapper->readFromString<oatpp::Object<Test3>>("{\"float32F\": 1.32e1}"); OATPP_ASSERT(obj3); OATPP_ASSERT(obj3->float32F); obj3 = mapper->readFromString<oatpp::Object<Test3>>("{\"float32F\": 1.32e+1 }"); OATPP_ASSERT(obj3); OATPP_ASSERT(obj3->float32F); obj3 = mapper->readFromString<oatpp::Object<Test3>>("{\"float32F\": 1.32e-1 }"); OATPP_ASSERT(obj3); OATPP_ASSERT(obj3->float32F); obj3 = mapper->readFromString<oatpp::Object<Test3>>("{\"float32F\": -1.32E-1 }"); OATPP_ASSERT(obj3); OATPP_ASSERT(obj3->float32F); obj3 = mapper->readFromString<oatpp::Object<Test3>>("{\"float32F\": -1.32E1 }"); OATPP_ASSERT(obj3); OATPP_ASSERT(obj3->float32F); auto list = mapper->readFromString<oatpp::List<oatpp::Int32>>("[1, 2, 3]"); OATPP_ASSERT(list); OATPP_ASSERT(list->size() == 3); OATPP_ASSERT(list[0] == 1); OATPP_ASSERT(list[1] == 2); OATPP_ASSERT(list[2] == 3); // Empty test auto obj4 = mapper->readFromString<oatpp::Object<Test4>>("{\"object\": {}, \"list\": [], \"map\": {}}"); OATPP_ASSERT(obj4); OATPP_ASSERT(obj4->object); OATPP_ASSERT(obj4->list); OATPP_ASSERT(obj4->list->size() == 0); OATPP_ASSERT(obj4->map->size() == 0); obj4 = mapper->readFromString<oatpp::Object<Test4>>("{\"object\": {\n\r\t}, \"list\": [\n\r\t], \"map\": {\n\r\t}}"); OATPP_ASSERT(obj4); OATPP_ASSERT(obj4->object); OATPP_ASSERT(obj4->list); OATPP_ASSERT(obj4->list->size() == 0); OATPP_ASSERT(obj4->map->size() == 0); OATPP_LOGD(TAG, "Any: String") { auto dto = mapper->readFromString<oatpp::Object<AnyDto>>(R"({"any":"my_string"})"); OATPP_ASSERT(dto); OATPP_ASSERT(dto->any.getStoredType() == String::Class::getType()); OATPP_ASSERT(dto->any.retrieve<String>() == "my_string"); } OATPP_LOGD(TAG, "Any: Boolean") { auto dto = mapper->readFromString<oatpp::Object<AnyDto>>(R"({"any":false})"); OATPP_ASSERT(dto); OATPP_ASSERT(dto->any.getStoredType() == Boolean::Class::getType()); OATPP_ASSERT(dto->any.retrieve<Boolean>() == false); } OATPP_LOGD(TAG, "Any: Negative Float") { auto dto = mapper->readFromString<oatpp::Object<AnyDto>>(R"({"any":-1.23456789,"another":1.1})"); OATPP_ASSERT(dto); OATPP_ASSERT(dto->any.getStoredType() == Float64::Class::getType()); OATPP_ASSERT(dto->any.retrieve<Float64>() == -1.23456789); } OATPP_LOGD(TAG, "Any: Positive Float") { auto dto = mapper->readFromString<oatpp::Object<AnyDto>>(R"({"any":1.23456789,"another":1.1})"); OATPP_ASSERT(dto); OATPP_ASSERT(dto->any.getStoredType() == Float64::Class::getType()); OATPP_ASSERT(dto->any.retrieve<Float64>() == 1.23456789); } OATPP_LOGD(TAG, "Any: Negative exponential Float") { auto dto = mapper->readFromString<oatpp::Object<AnyDto>>(R"({"any":-1.2345e30,"another":1.1})"); OATPP_ASSERT(dto); OATPP_ASSERT(dto->any.getStoredType() == Float64::Class::getType()); OATPP_ASSERT(dto->any.retrieve<Float64>() == -1.2345e30); } OATPP_LOGD(TAG, "Any: Positive exponential Float") { auto dto = mapper->readFromString<oatpp::Object<AnyDto>>(R"({"any":1.2345e30,"another":1.1})"); OATPP_ASSERT(dto); OATPP_ASSERT(dto->any.getStoredType() == Float64::Class::getType()); OATPP_ASSERT(dto->any.retrieve<Float64>() == 1.2345e30); } OATPP_LOGD(TAG, "Any: Unsigned Integer") { auto dto = mapper->readFromString<oatpp::Object<AnyDto>>(R"({"any":12345678901234567890,"another":1.1})"); OATPP_ASSERT(dto); OATPP_ASSERT(dto->any.getStoredType() == UInt64::Class::getType()); OATPP_ASSERT(dto->any.retrieve<UInt64>() == 12345678901234567890u); } OATPP_LOGD(TAG, "Any: Signed Integer") { auto dto = mapper->readFromString<oatpp::Object<AnyDto>>(R"({"any":-1234567890,"another":1.1})"); OATPP_ASSERT(dto); OATPP_ASSERT(dto->any.getStoredType() == Int64::Class::getType()); OATPP_ASSERT(dto->any.retrieve<Int64>() == -1234567890); } } }}}}}
vincent-in-black-sesame/oat
test/oatpp/parser/json/mapping/DeserializerTest.cpp
C++
apache-2.0
7,430
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_parser_json_mapping_DeserializerTest_hpp #define oatpp_test_parser_json_mapping_DeserializerTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace parser { namespace json { namespace mapping { class DeserializerTest : public UnitTest{ public: DeserializerTest():UnitTest("TEST[parser::json::mapping::DeserializerTest]"){} void onRun() override; }; }}}}} #endif /* oatpp_test_parser_json_mapping_DeserializerTest_hpp */
vincent-in-black-sesame/oat
test/oatpp/parser/json/mapping/DeserializerTest.hpp
C++
apache-2.0
1,487
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "EnumTest.hpp" #include "oatpp/parser/json/mapping/ObjectMapper.hpp" #include "oatpp/core/macro/codegen.hpp" namespace oatpp { namespace test { namespace parser { namespace json { namespace mapping { namespace { #include OATPP_CODEGEN_BEGIN(DTO) ENUM(Enum0, v_int32); ENUM(Enum1, v_int32, VALUE(V1, 10, "enum1-v1"), VALUE(V2, 20, "enum1-v2"), VALUE(V3, 30, "enum1-v3") ); class DTO1 : public oatpp::DTO { DTO_INIT(DTO1, DTO) DTO_FIELD(Enum<Enum1>::AsString, enum1); }; #include OATPP_CODEGEN_END(DTO) } void EnumTest::onRun() { oatpp::parser::json::mapping::ObjectMapper mapper; { OATPP_LOGI(TAG, "Serializer as string..."); oatpp::Fields<oatpp::Enum<Enum1>::AsString> map = {{"enum", Enum1::V1}}; auto json = mapper.writeToString(map); OATPP_LOGD(TAG, "json='%s'", json->c_str()); OATPP_ASSERT(json == "{\"enum\":\"enum1-v1\"}"); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Serializer as string null..."); oatpp::Fields<oatpp::Enum<Enum1>::AsString> map = {{"enum", nullptr}}; auto json = mapper.writeToString(map); OATPP_LOGD(TAG, "json='%s'", json->c_str()); OATPP_ASSERT(json == "{\"enum\":null}"); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Serializer as string error on null..."); bool error = false; oatpp::Fields<oatpp::Enum<Enum1>::AsString::NotNull> map = {{"enum", nullptr}}; try { auto json = mapper.writeToString(map); } catch (const std::runtime_error& e) { OATPP_LOGD(TAG, "error - %s", e.what()); error = true; } OATPP_ASSERT(error == true); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Serializer as int..."); oatpp::Fields<oatpp::Enum<Enum1>::AsNumber> map = {{"enum", Enum1::V1}}; auto json = mapper.writeToString(map); OATPP_LOGD(TAG, "json='%s'", json->c_str()); OATPP_ASSERT(json == "{\"enum\":10}"); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Serializer as int null..."); oatpp::Fields<oatpp::Enum<Enum1>::AsNumber> map = {{"enum", nullptr}}; auto json = mapper.writeToString(map); OATPP_LOGD(TAG, "json='%s'", json->c_str()); OATPP_ASSERT(json == "{\"enum\":null}"); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Serializer as int error on null..."); bool error = false; oatpp::Fields<oatpp::Enum<Enum1>::AsNumber::NotNull> map = {{"enum", nullptr}}; try { auto json = mapper.writeToString(map); } catch (const std::runtime_error& e) { OATPP_LOGD(TAG, "error - %s", e.what()); error = true; } OATPP_ASSERT(error == true); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Deserializer as string..."); oatpp::String json = "{\"enum\":\"enum1-v2\"}"; auto map = mapper.readFromString<oatpp::Fields<oatpp::Enum<Enum1>::AsString>>(json); OATPP_ASSERT(map["enum"] == Enum1::V2); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Deserializer as string null..."); oatpp::String json = "{\"enum\":null}"; auto map = mapper.readFromString<oatpp::Fields<oatpp::Enum<Enum1>::AsString>>(json); OATPP_ASSERT(map["enum"] == nullptr); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Deserializer as string error on null..."); bool error = false; oatpp::String json = "{\"enum\":null}"; try { auto map = mapper.readFromString<oatpp::Fields<oatpp::Enum<Enum1>::AsString::NotNull>>(json); } catch (const oatpp::parser::ParsingError& e) { OATPP_LOGD(TAG, "error - %s", e.what()); error = true; } OATPP_ASSERT(error == true); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Deserializer as int..."); oatpp::String json = "{\"enum\":20}"; auto map = mapper.readFromString<oatpp::Fields<oatpp::Enum<Enum1>::AsNumber>>(json); OATPP_ASSERT(map["enum"] == Enum1::V2); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Deserializer as int null..."); oatpp::String json = "{\"enum\":null}"; auto map = mapper.readFromString<oatpp::Fields<oatpp::Enum<Enum1>::AsNumber>>(json); OATPP_ASSERT(map["enum"] == nullptr); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Deserializer as int error on null..."); bool error = false; oatpp::String json = "{\"enum\":null}"; try { auto map = mapper.readFromString<oatpp::Fields<oatpp::Enum<Enum1>::AsNumber::NotNull>>(json); } catch (const oatpp::parser::ParsingError& e) { OATPP_LOGD(TAG, "error - %s", e.what()); error = true; } OATPP_ASSERT(error == true); OATPP_LOGI(TAG, "OK"); } } }}}}}
vincent-in-black-sesame/oat
test/oatpp/parser/json/mapping/EnumTest.cpp
C++
apache-2.0
5,566
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_parser_json_mapping_EnumTest_hpp #define oatpp_test_parser_json_mapping_EnumTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace parser { namespace json { namespace mapping { class EnumTest : public UnitTest{ public: EnumTest():UnitTest("TEST[parser::json::mapping::EnumTest]"){} void onRun() override; }; }}}}} #endif /* oatpp_test_parser_json_mapping_EnumTest_hpp */
vincent-in-black-sesame/oat
test/oatpp/parser/json/mapping/EnumTest.hpp
C++
apache-2.0
1,431
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "UnorderedSetTest.hpp" #include "oatpp/parser/json/mapping/ObjectMapper.hpp" namespace oatpp { namespace test { namespace parser { namespace json { namespace mapping { void UnorderedSetTest::onRun() { oatpp::parser::json::mapping::ObjectMapper mapper; { oatpp::UnorderedSet<oatpp::String> set = {"Hello", "World", "!"}; auto json = mapper.writeToString(set); OATPP_LOGD(TAG, "json='%s'", json->c_str()); } { oatpp::String json = "[\"Hello\",\"World\",\"!\",\"Hello\",\"World\",\"!\"]"; auto set = mapper.readFromString<oatpp::UnorderedSet<oatpp::String>>(json); OATPP_ASSERT(set); OATPP_ASSERT(set->size() == 3); for(auto& item : *set) { OATPP_LOGD(TAG, "item='%s'", item->c_str()); } } } }}}}}
vincent-in-black-sesame/oat
test/oatpp/parser/json/mapping/UnorderedSetTest.cpp
C++
apache-2.0
1,762
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_parser_json_mapping_UnorderedSetTest_hpp #define oatpp_test_parser_json_mapping_UnorderedSetTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace parser { namespace json { namespace mapping { class UnorderedSetTest : public UnitTest{ public: UnorderedSetTest():UnitTest("TEST[parser::json::mapping::UnorderedSetTest]"){} void onRun() override; }; }}}}} #endif /* oatpp_test_parser_json_mapping_UnorderedSetTest_hpp */
vincent-in-black-sesame/oat
test/oatpp/parser/json/mapping/UnorderedSetTest.hpp
C++
apache-2.0
1,479
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "ClientRetryTest.hpp" #include "oatpp/web/app/Client.hpp" #include "oatpp/web/app/ControllerWithInterceptors.hpp" #include "oatpp/web/app/Controller.hpp" #include "oatpp/web/app/BasicAuthorizationController.hpp" #include "oatpp/web/app/BearerAuthorizationController.hpp" #include "oatpp/web/client/HttpRequestExecutor.hpp" #include "oatpp/web/server/HttpConnectionHandler.hpp" #include "oatpp/web/server/HttpRouter.hpp" #include "oatpp/parser/json/mapping/ObjectMapper.hpp" #include "oatpp/network/tcp/server/ConnectionProvider.hpp" #include "oatpp/network/tcp/client/ConnectionProvider.hpp" #include "oatpp/network/virtual_/client/ConnectionProvider.hpp" #include "oatpp/network/virtual_/server/ConnectionProvider.hpp" #include "oatpp/network/virtual_/Interface.hpp" #include "oatpp/network/ConnectionPool.hpp" #include "oatpp/core/macro/component.hpp" #include "oatpp-test/web/ClientServerTestRunner.hpp" #include "oatpp-test/Checker.hpp" namespace oatpp { namespace test { namespace web { namespace { typedef oatpp::web::server::api::ApiController ApiController; class TestServerComponent { private: v_uint16 m_port; public: TestServerComponent(v_uint16 port) : m_port(port) {} OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::network::ServerConnectionProvider>, serverConnectionProvider)([this] { if(m_port == 0) { // Use oatpp virtual interface auto _interface = oatpp::network::virtual_::Interface::obtainShared("virtualhost"); return std::static_pointer_cast<oatpp::network::ServerConnectionProvider>( oatpp::network::virtual_::server::ConnectionProvider::createShared(_interface) ); } return std::static_pointer_cast<oatpp::network::ServerConnectionProvider>( oatpp::network::tcp::server::ConnectionProvider::createShared({"localhost", m_port}) ); }()); OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::web::server::HttpRouter>, httpRouter)([] { return oatpp::web::server::HttpRouter::createShared(); }()); OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::network::ConnectionHandler>, serverConnectionHandler)([] { OATPP_COMPONENT(std::shared_ptr<oatpp::web::server::HttpRouter>, router); return oatpp::web::server::HttpConnectionHandler::createShared(router); }()); OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::data::mapping::ObjectMapper>, objectMapper)([] { return oatpp::parser::json::mapping::ObjectMapper::createShared(); }()); }; class TestClientComponent { private: v_uint16 m_port; public: TestClientComponent(v_uint16 port) : m_port(port) {} OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::network::ClientConnectionProvider>, clientConnectionProvider)([this] { if(m_port == 0) { auto _interface = oatpp::network::virtual_::Interface::obtainShared("virtualhost"); return std::static_pointer_cast<oatpp::network::ClientConnectionProvider>( oatpp::network::virtual_::client::ConnectionProvider::createShared(_interface) ); } return std::static_pointer_cast<oatpp::network::ClientConnectionProvider>( oatpp::network::tcp::client::ConnectionProvider::createShared({"localhost", m_port}) ); }()); }; void runServer(v_uint16 port, v_int32 delaySeconds, v_int32 iterations, bool stable, const std::shared_ptr<app::Controller>& controller) { TestServerComponent component(port); oatpp::test::web::ClientServerTestRunner runner; runner.addController(controller); runner.run([&runner, delaySeconds, iterations, stable, controller] { for(v_int32 i = 0; i < iterations; i ++) { std::this_thread::sleep_for(std::chrono::seconds(delaySeconds)); if(!stable) { controller->available = !controller->available; OATPP_LOGI("Server", "Available=%d", (v_int32)controller->available.load()); } } }, std::chrono::minutes(10)); std::this_thread::sleep_for(std::chrono::seconds(1)); } } void ClientRetryTest::onRun() { TestClientComponent component(m_port); auto objectMapper = oatpp::parser::json::mapping::ObjectMapper::createShared(); auto controller = app::Controller::createShared(objectMapper); OATPP_COMPONENT(std::shared_ptr<oatpp::network::ClientConnectionProvider>, connectionProvider); { OATPP_LOGI(TAG, "Test: no server available"); oatpp::test::PerformanceChecker checker("test: no server available"); auto retryPolicy = std::make_shared<oatpp::web::client::SimpleRetryPolicy>(2, std::chrono::seconds(1)); auto requestExecutor = oatpp::web::client::HttpRequestExecutor::createShared(connectionProvider, retryPolicy); auto client = app::Client::createShared(requestExecutor, objectMapper); auto response = client->getRoot(); auto ticks = checker.getElapsedTicks(); OATPP_LOGD(TAG, "ticks=%d", ticks); if(m_port == 0) { OATPP_ASSERT(response.get() == nullptr); OATPP_ASSERT(ticks >= 2 * 1000 * 1000 /* 2s */); OATPP_ASSERT(ticks < 3 * 1000 * 1000 /* 3s */); } else { // TODO - investigate why it takes more than 2 seconds on windows to try to connect to unavailable host #if !defined(WIN32) && !defined(_WIN32) OATPP_ASSERT(response.get() == nullptr); OATPP_ASSERT(ticks >= 2 * 1000 * 1000 /* 2s */); OATPP_ASSERT(ticks < 3 * 1000 * 1000 /* 3s */); #endif } } { OATPP_LOGI(TAG, "Test: server pops up"); oatpp::test::PerformanceChecker checker("test: server pops up"); auto retryPolicy = std::make_shared<oatpp::web::client::SimpleRetryPolicy>(10 * 10, std::chrono::milliseconds(100)); auto requestExecutor = oatpp::web::client::HttpRequestExecutor::createShared(connectionProvider, retryPolicy); auto client = app::Client::createShared(requestExecutor, objectMapper); std::list<std::thread> threads; for(v_int32 i = 0; i < 100; i ++) { threads.push_back(std::thread([client]{ auto response = client->getRoot(); OATPP_ASSERT(response && "Test: server pops up"); OATPP_ASSERT(response->getStatusCode() == 200); auto data = response->readBodyToString(); OATPP_ASSERT(data == "Hello World!!!"); })); } OATPP_LOGD(TAG, "Waiting for server to start..."); std::this_thread::sleep_for(std::chrono::seconds(3)); runServer(m_port, 2, 2, true, controller); for(std::thread& thread : threads) { thread.join(); } auto ticks = checker.getElapsedTicks(); OATPP_ASSERT(ticks < 10 * 1000 * 1000 /* 10s */); } { OATPP_LOGI(TAG, "Test: unstable server!"); auto retryPolicy = std::make_shared<oatpp::web::client::SimpleRetryPolicy>(-1, std::chrono::seconds(1)); auto connectionPool = oatpp::network::ClientConnectionPool::createShared(connectionProvider, 10, std::chrono::seconds(1)); auto requestExecutor = oatpp::web::client::HttpRequestExecutor::createShared(connectionPool, retryPolicy); auto client = app::Client::createShared(requestExecutor, objectMapper); std::list<std::thread> threads; std::thread clientThread([client]{ v_int64 counter = 0; v_int64 tick0 = oatpp::base::Environment::getMicroTickCount(); while(oatpp::base::Environment::getMicroTickCount() - tick0 < 10 * 1000 * 1000) { auto response = client->getAvailability(); OATPP_ASSERT(response && "Test: unstable server!"); OATPP_ASSERT(response->getStatusCode() == 200); auto data = response->readBodyToString(); OATPP_ASSERT(data == "Hello World!!!"); counter ++; if(counter % 1000 == 0) { OATPP_LOGD("client", "requests=%d", counter); } } }); runServer(m_port, 2, 6, false, controller); clientThread.join(); connectionPool->stop(); } std::this_thread::sleep_for(std::chrono::seconds(2)); // wait connection pool. } }}}
vincent-in-black-sesame/oat
test/oatpp/web/ClientRetryTest.cpp
C++
apache-2.0
8,821
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_web_ClientRetryTest_hpp #define oatpp_test_web_ClientRetryTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace web { class ClientRetryTest : public UnitTest { private: v_uint16 m_port; public: ClientRetryTest(v_uint16 port) : UnitTest("TEST[web::ClientRetryTest]") , m_port(port) {} void onRun() override; }; }}} #endif /* oatpp_test_web_ClientRetryTest_hpp */
vincent-in-black-sesame/oat
test/oatpp/web/ClientRetryTest.hpp
C++
apache-2.0
1,436
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "FullAsyncClientTest.hpp" #include "oatpp/web/app/Client.hpp" #include "oatpp/web/app/ControllerAsync.hpp" #include "oatpp/web/client/HttpRequestExecutor.hpp" #include "oatpp/web/server/AsyncHttpConnectionHandler.hpp" #include "oatpp/web/server/HttpRouter.hpp" #include "oatpp/parser/json/mapping/ObjectMapper.hpp" #include "oatpp/network/tcp/server/ConnectionProvider.hpp" #include "oatpp/network/tcp/client/ConnectionProvider.hpp" #include "oatpp/network/virtual_/client/ConnectionProvider.hpp" #include "oatpp/network/virtual_/server/ConnectionProvider.hpp" #include "oatpp/network/virtual_/Interface.hpp" #include "oatpp/core/macro/component.hpp" #include "oatpp-test/web/ClientServerTestRunner.hpp" namespace oatpp { namespace test { namespace web { namespace { typedef oatpp::web::protocol::http::incoming::Response IncomingResponse; class TestComponent { private: v_uint16 m_port; public: TestComponent(v_uint16 port) : m_port(port) {} OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::async::Executor>, executor)([] { return std::make_shared<oatpp::async::Executor>(4, 1, 1); }()); OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::network::virtual_::Interface>, virtualInterface)([] { return oatpp::network::virtual_::Interface::obtainShared("virtualhost"); }()); OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::network::ServerConnectionProvider>, serverConnectionProvider)([this] { if(m_port == 0) { OATPP_COMPONENT(std::shared_ptr<oatpp::network::virtual_::Interface>, _interface); return std::static_pointer_cast<oatpp::network::ServerConnectionProvider>( oatpp::network::virtual_::server::ConnectionProvider::createShared(_interface) ); } return std::static_pointer_cast<oatpp::network::ServerConnectionProvider>( oatpp::network::tcp::server::ConnectionProvider::createShared({"localhost", m_port}) ); }()); OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::web::server::HttpRouter>, httpRouter)([] { return oatpp::web::server::HttpRouter::createShared(); }()); OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::network::ConnectionHandler>, serverConnectionHandler)([] { OATPP_COMPONENT(std::shared_ptr<oatpp::web::server::HttpRouter>, router); OATPP_COMPONENT(std::shared_ptr<oatpp::async::Executor>, executor); return oatpp::web::server::AsyncHttpConnectionHandler::createShared(router, executor); }()); OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::data::mapping::ObjectMapper>, objectMapper)([] { return oatpp::parser::json::mapping::ObjectMapper::createShared(); }()); OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::network::ClientConnectionProvider>, clientConnectionProvider)([this] { if(m_port == 0) { OATPP_COMPONENT(std::shared_ptr<oatpp::network::virtual_::Interface>, _interface); return std::static_pointer_cast<oatpp::network::ClientConnectionProvider>( oatpp::network::virtual_::client::ConnectionProvider::createShared(_interface) ); } return std::static_pointer_cast<oatpp::network::ClientConnectionProvider>( oatpp::network::tcp::client::ConnectionProvider::createShared({"localhost", m_port}) ); }()); OATPP_CREATE_COMPONENT(std::shared_ptr<app::Client>, appClient)([] { OATPP_COMPONENT(std::shared_ptr<oatpp::network::ClientConnectionProvider>, clientConnectionProvider); OATPP_COMPONENT(std::shared_ptr<oatpp::data::mapping::ObjectMapper>, objectMapper); auto retryPolicy = std::make_shared<oatpp::web::client::SimpleRetryPolicy>(5, std::chrono::seconds(1)); auto requestExecutor = oatpp::web::client::HttpRequestExecutor::createShared(clientConnectionProvider, retryPolicy); return app::Client::createShared(requestExecutor, objectMapper); }()); }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ClientCoroutine_getRootAsync class ClientCoroutine_getRootAsync : public oatpp::async::Coroutine<ClientCoroutine_getRootAsync> { public: static std::atomic<v_int32> SUCCESS_COUNTER; private: OATPP_COMPONENT(std::shared_ptr<app::Client>, appClient); public: Action act() override { return appClient->getRootAsync().callbackTo(&ClientCoroutine_getRootAsync::onResponse); } Action onResponse(const std::shared_ptr<IncomingResponse>& response) { OATPP_ASSERT(response->getStatusCode() == 200 && "ClientCoroutine_getRootAsync"); return response->readBodyToStringAsync().callbackTo(&ClientCoroutine_getRootAsync::onBodyRead); } Action onBodyRead(const oatpp::String& body) { OATPP_ASSERT(body == "Hello World Async!!!"); ++ SUCCESS_COUNTER; return finish(); } Action handleError(Error* error) override { if(error->is<oatpp::AsyncIOError>()) { auto e = static_cast<oatpp::AsyncIOError*>(error); OATPP_LOGE("[FullAsyncClientTest::ClientCoroutine_getRootAsync::handleError()]", "AsyncIOError. %s, %d", e->what(), e->getCode()); } else { OATPP_LOGE("[FullAsyncClientTest::ClientCoroutine_getRootAsync::handleError()]", "Error. %s", error->what()); } OATPP_ASSERT(!"Error"); return error; } }; std::atomic<v_int32> ClientCoroutine_getRootAsync::SUCCESS_COUNTER(0); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ClientCoroutine_postBodyAsync class ClientCoroutine_postBodyAsync : public oatpp::async::Coroutine<ClientCoroutine_postBodyAsync> { public: static std::atomic<v_int32> SUCCESS_COUNTER; private: OATPP_COMPONENT(std::shared_ptr<app::Client>, appClient); OATPP_COMPONENT(std::shared_ptr<oatpp::data::mapping::ObjectMapper>, objectMapper); public: Action act() override { return appClient->postBodyAsync("my_test_body").callbackTo(&ClientCoroutine_postBodyAsync::onResponse); } Action onResponse(const std::shared_ptr<IncomingResponse>& response) { OATPP_ASSERT(response->getStatusCode() == 200 && "ClientCoroutine_postBodyAsync"); return response->readBodyToDtoAsync<oatpp::Object<app::TestDto>>(objectMapper).callbackTo(&ClientCoroutine_postBodyAsync::onBodyRead); } Action onBodyRead(const oatpp::Object<app::TestDto>& body) { OATPP_ASSERT(body); OATPP_ASSERT(body->testValue == "my_test_body"); ++ SUCCESS_COUNTER; return finish(); } Action handleError(Error* error) override { if(error->is<oatpp::AsyncIOError>()) { auto e = static_cast<oatpp::AsyncIOError*>(error); OATPP_LOGE("[FullAsyncClientTest::ClientCoroutine_postBodyAsync::handleError()]", "AsyncIOError. %s, %d", e->what(), e->getCode()); } else { OATPP_LOGE("[FullAsyncClientTest::ClientCoroutine_postBodyAsync::handleError()]", "Error. %s", error->what()); } OATPP_ASSERT(!"Error"); return error; } }; std::atomic<v_int32> ClientCoroutine_postBodyAsync::SUCCESS_COUNTER(0); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ClientCoroutine_echoBodyAsync class ClientCoroutine_echoBodyAsync : public oatpp::async::Coroutine<ClientCoroutine_echoBodyAsync> { public: static std::atomic<v_int32> SUCCESS_COUNTER; private: OATPP_COMPONENT(std::shared_ptr<app::Client>, appClient); oatpp::String m_data; public: Action act() override { oatpp::data::stream::BufferOutputStream stream; for(v_int32 i = 0; i < oatpp::data::buffer::IOBuffer::BUFFER_SIZE; i++) { stream.writeSimple("0123456789", 10); } m_data = stream.toString(); return appClient->echoBodyAsync(m_data).callbackTo(&ClientCoroutine_echoBodyAsync::onResponse); } Action onResponse(const std::shared_ptr<IncomingResponse>& response) { OATPP_ASSERT(response->getStatusCode() == 200 && "ClientCoroutine_echoBodyAsync"); return response->readBodyToStringAsync().callbackTo(&ClientCoroutine_echoBodyAsync::onBodyRead); } Action onBodyRead(const oatpp::String& body) { OATPP_ASSERT(body == m_data); ++ SUCCESS_COUNTER; return finish(); } Action handleError(Error* error) override { if(error) { if(error->is<oatpp::AsyncIOError>()) { auto e = static_cast<oatpp::AsyncIOError*>(error); OATPP_LOGE("[FullAsyncClientTest::ClientCoroutine_echoBodyAsync::handleError()]", "AsyncIOError. %s, %d", e->what(), e->getCode()); } else { OATPP_LOGE("[FullAsyncClientTest::ClientCoroutine_echoBodyAsync::handleError()]", "Error. %s", error->what()); } } OATPP_ASSERT(!"Error"); return error; } }; std::atomic<v_int32> ClientCoroutine_echoBodyAsync::SUCCESS_COUNTER(0); } void FullAsyncClientTest::onRun() { TestComponent component(m_port); oatpp::test::web::ClientServerTestRunner runner; runner.addController(app::ControllerAsync::createShared()); runner.run([this, &runner] { OATPP_COMPONENT(std::shared_ptr<oatpp::async::Executor>, executor); ClientCoroutine_getRootAsync::SUCCESS_COUNTER = 0; ClientCoroutine_postBodyAsync::SUCCESS_COUNTER = 0; ClientCoroutine_echoBodyAsync::SUCCESS_COUNTER = 0; v_int32 iterations = m_connectionsPerEndpoint; for(v_int32 i = 0; i < iterations; i++) { executor->execute<ClientCoroutine_getRootAsync>(); executor->execute<ClientCoroutine_postBodyAsync>(); executor->execute<ClientCoroutine_echoBodyAsync>(); } while( ClientCoroutine_getRootAsync::SUCCESS_COUNTER != -1 || ClientCoroutine_postBodyAsync::SUCCESS_COUNTER != -1 || ClientCoroutine_echoBodyAsync::SUCCESS_COUNTER != -1 ) { OATPP_LOGV("Client", "Root=%d, postBody=%d, echoBody=%d", ClientCoroutine_getRootAsync::SUCCESS_COUNTER.load(), ClientCoroutine_postBodyAsync::SUCCESS_COUNTER.load(), ClientCoroutine_echoBodyAsync::SUCCESS_COUNTER.load() ); std::this_thread::sleep_for(std::chrono::milliseconds(100)); if(ClientCoroutine_getRootAsync::SUCCESS_COUNTER == iterations){ ClientCoroutine_getRootAsync::SUCCESS_COUNTER = -1; OATPP_LOGV("Client", "getRootAsync - DONE!"); } if(ClientCoroutine_postBodyAsync::SUCCESS_COUNTER == iterations){ ClientCoroutine_postBodyAsync::SUCCESS_COUNTER = -1; OATPP_LOGV("Client", "postBodyAsync - DONE!"); } if(ClientCoroutine_echoBodyAsync::SUCCESS_COUNTER == iterations){ ClientCoroutine_echoBodyAsync::SUCCESS_COUNTER = -1; OATPP_LOGV("Client", "echoBodyAsync - DONE!"); } } OATPP_ASSERT(ClientCoroutine_getRootAsync::SUCCESS_COUNTER == -1); // -1 is success OATPP_ASSERT(ClientCoroutine_postBodyAsync::SUCCESS_COUNTER == -1); // -1 is success OATPP_ASSERT(ClientCoroutine_echoBodyAsync::SUCCESS_COUNTER == -1); // -1 is success executor->waitTasksFinished(); // Wait executor tasks before quit. executor->stop(); }, std::chrono::minutes(10)); OATPP_COMPONENT(std::shared_ptr<oatpp::async::Executor>, executor); executor->join(); } }}}
vincent-in-black-sesame/oat
test/oatpp/web/FullAsyncClientTest.cpp
C++
apache-2.0
12,010
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_web_FullAsyncClientTest_hpp #define oatpp_test_web_FullAsyncClientTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace web { class FullAsyncClientTest : public UnitTest { private: v_uint16 m_port; v_int32 m_connectionsPerEndpoint; public: FullAsyncClientTest(v_uint16 port, v_int32 connectionsPerEndpoint) : UnitTest("TEST[web::FullAsyncClientTest]") , m_port(port) , m_connectionsPerEndpoint(connectionsPerEndpoint) {} void onRun() override; }; }}} #endif /* oatpp_test_web_FullAsyncClientTest_hpp */
vincent-in-black-sesame/oat
test/oatpp/web/FullAsyncClientTest.hpp
C++
apache-2.0
1,583
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "FullAsyncTest.hpp" #include "oatpp/web/app/Client.hpp" #include "oatpp/web/app/ControllerWithInterceptorsAsync.hpp" #include "oatpp/web/app/ControllerAsync.hpp" #include "oatpp/web/client/HttpRequestExecutor.hpp" #include "oatpp/web/server/AsyncHttpConnectionHandler.hpp" #include "oatpp/web/server/HttpRouter.hpp" #include "oatpp/parser/json/mapping/ObjectMapper.hpp" #include "oatpp/network/tcp/server/ConnectionProvider.hpp" #include "oatpp/network/tcp/client/ConnectionProvider.hpp" #include "oatpp/network/virtual_/client/ConnectionProvider.hpp" #include "oatpp/network/virtual_/server/ConnectionProvider.hpp" #include "oatpp/network/virtual_/Interface.hpp" #include "oatpp/core/data/resource/InMemoryData.hpp" #include "oatpp/core/macro/component.hpp" #include "oatpp-test/web/ClientServerTestRunner.hpp" namespace oatpp { namespace test { namespace web { namespace { typedef oatpp::web::mime::multipart::PartList PartList; typedef oatpp::web::protocol::http::outgoing::MultipartBody MultipartBody; class TestComponent { private: v_uint16 m_port; public: TestComponent(v_uint16 port) : m_port(port) {} OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::async::Executor>, executor)([] { return std::make_shared<oatpp::async::Executor>(1, 1, 1); }()); OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::network::virtual_::Interface>, virtualInterface)([] { return oatpp::network::virtual_::Interface::obtainShared("virtualhost"); }()); OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::network::ServerConnectionProvider>, serverConnectionProvider)([this] { if(m_port == 0) { OATPP_COMPONENT(std::shared_ptr<oatpp::network::virtual_::Interface>, _interface); return std::static_pointer_cast<oatpp::network::ServerConnectionProvider>( oatpp::network::virtual_::server::ConnectionProvider::createShared(_interface) ); } return std::static_pointer_cast<oatpp::network::ServerConnectionProvider>( oatpp::network::tcp::server::ConnectionProvider::createShared({"localhost", m_port}) ); }()); OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::web::server::HttpRouter>, httpRouter)([] { return oatpp::web::server::HttpRouter::createShared(); }()); OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::network::ConnectionHandler>, serverConnectionHandler)([] { OATPP_COMPONENT(std::shared_ptr<oatpp::web::server::HttpRouter>, router); OATPP_COMPONENT(std::shared_ptr<oatpp::async::Executor>, executor); return oatpp::web::server::AsyncHttpConnectionHandler::createShared(router, executor); }()); OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::data::mapping::ObjectMapper>, objectMapper)([] { return oatpp::parser::json::mapping::ObjectMapper::createShared(); }()); OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::network::ClientConnectionProvider>, clientConnectionProvider)([this] { if(m_port == 0) { OATPP_COMPONENT(std::shared_ptr<oatpp::network::virtual_::Interface>, _interface); return std::static_pointer_cast<oatpp::network::ClientConnectionProvider>( oatpp::network::virtual_::client::ConnectionProvider::createShared(_interface) ); } return std::static_pointer_cast<oatpp::network::ClientConnectionProvider>( oatpp::network::tcp::client::ConnectionProvider::createShared({"localhost", m_port}) ); }()); }; std::shared_ptr<PartList> createMultipart(const std::unordered_map<oatpp::String, oatpp::String>& map) { auto multipart = oatpp::web::mime::multipart::PartList::createSharedWithRandomBoundary(); for(auto& pair : map) { oatpp::web::mime::multipart::Headers partHeaders; auto part = std::make_shared<oatpp::web::mime::multipart::Part>(partHeaders); multipart->writeNextPartSimple(part); part->putHeader("Content-Disposition", "form-data; name=\"" + pair.first + "\""); part->setPayload(std::make_shared<oatpp::data::resource::InMemoryData>(pair.second)); } return multipart; } } void FullAsyncTest::onRun() { TestComponent component(m_port); oatpp::test::web::ClientServerTestRunner runner; runner.addController(app::ControllerAsync::createShared()); runner.addController(app::ControllerWithInterceptorsAsync::createShared()); runner.run([this, &runner] { OATPP_COMPONENT(std::shared_ptr<oatpp::network::ClientConnectionProvider>, clientConnectionProvider); OATPP_COMPONENT(std::shared_ptr<oatpp::data::mapping::ObjectMapper>, objectMapper); auto requestExecutor = oatpp::web::client::HttpRequestExecutor::createShared(clientConnectionProvider); auto client = app::Client::createShared(requestExecutor, objectMapper); auto connection = client->getConnection(); OATPP_ASSERT(connection); v_int32 iterationsStep = m_iterationsPerStep; auto lastTick = oatpp::base::Environment::getMicroTickCount(); for(v_int32 i = 0; i < iterationsStep * 10; i ++) { //OATPP_LOGV("i", "%d", i); { // test simple GET auto response = client->getRoot(connection); OATPP_ASSERT(response->getStatusCode() == 200); auto value = response->readBodyToString(); OATPP_ASSERT(value == "Hello World Async!!!"); } { // test GET with path parameter auto response = client->getWithParams("my_test_param-Async", connection); OATPP_ASSERT(response->getStatusCode() == 200); auto dto = response->readBodyToDto<oatpp::Object<app::TestDto>>(objectMapper.get()); OATPP_ASSERT(dto); OATPP_ASSERT(dto->testValue == "my_test_param-Async"); } { // test GET with header parameter auto response = client->getWithHeaders("my_test_header-Async", connection); OATPP_ASSERT(response->getStatusCode() == 200); auto dto = response->readBodyToDto<oatpp::Object<app::TestDto>>(objectMapper.get()); OATPP_ASSERT(dto); OATPP_ASSERT(dto->testValue == "my_test_header-Async"); } { // test POST with body auto response = client->postBody("my_test_body-Async", connection); OATPP_ASSERT(response->getStatusCode() == 200); auto dto = response->readBodyToDto<oatpp::Object<app::TestDto>>(objectMapper.get()); OATPP_ASSERT(dto); OATPP_ASSERT(dto->testValue == "my_test_body-Async"); } { // test Big Echo with body oatpp::data::stream::BufferOutputStream stream; for(v_int32 i = 0; i < oatpp::data::buffer::IOBuffer::BUFFER_SIZE; i++) { stream.writeSimple("0123456789", 10); } auto data = stream.toString(); auto response = client->echoBody(data, connection); OATPP_ASSERT(response->getStatusCode() == 200); auto returnedData = response->readBodyToString(); OATPP_ASSERT(returnedData); OATPP_ASSERT(returnedData == data); } { // test Chunked body oatpp::String sample = "__abcdefghijklmnopqrstuvwxyz-0123456789"; v_int32 numIterations = 10; oatpp::data::stream::BufferOutputStream stream; for(v_int32 i = 0; i < numIterations; i++) { stream.writeSimple(sample->data(), sample->size()); } auto data = stream.toString(); auto response = client->getChunked(sample, numIterations, connection); OATPP_ASSERT(response->getStatusCode() == 200); auto returnedData = response->readBodyToString(); OATPP_ASSERT(returnedData); OATPP_ASSERT(returnedData == data); } { // Multipart body std::unordered_map<oatpp::String, oatpp::String> map; map["value1"] = "Hello"; map["value2"] = "World"; auto multipart = createMultipart(map); auto body = std::make_shared<MultipartBody>(multipart); auto response = client->multipartTest(i + 1, body); OATPP_ASSERT(response->getStatusCode() == 200); multipart = std::make_shared<oatpp::web::mime::multipart::PartList>(response->getHeaders()); oatpp::web::mime::multipart::Reader multipartReader(multipart.get()); multipartReader.setPartReader("value1", oatpp::web::mime::multipart::createInMemoryPartReader(10)); multipartReader.setPartReader("value2", oatpp::web::mime::multipart::createInMemoryPartReader(10)); response->transferBody(&multipartReader); OATPP_ASSERT(multipart->getAllParts().size() == 2); auto part1 = multipart->getNamedPart("value1"); auto part2 = multipart->getNamedPart("value2"); OATPP_ASSERT(part1); OATPP_ASSERT(part1->getPayload()); OATPP_ASSERT(part2); OATPP_ASSERT(part2->getPayload()); OATPP_ASSERT(part1->getPayload()->getInMemoryData() == "Hello"); OATPP_ASSERT(part2->getPayload()->getInMemoryData() == "World"); } { // test interceptor GET auto response = client->getInterceptors(connection); OATPP_ASSERT(response->getStatusCode() == 200); auto value = response->readBodyToString(); OATPP_ASSERT(value == "Hello World Async!!!"); } { // test host header auto response = client->getHostHeader(connection); OATPP_ASSERT(response->getStatusCode() == 200); auto value = response->readBodyToString(); auto host = clientConnectionProvider->getProperty("host"); OATPP_ASSERT(host); OATPP_ASSERT(value == host.toString() + ":" + oatpp::utils::conversion::int32ToStr(m_port)); } if((i + 1) % iterationsStep == 0) { auto ticks = oatpp::base::Environment::getMicroTickCount() - lastTick; lastTick = oatpp::base::Environment::getMicroTickCount(); OATPP_LOGV("i", "%d, tick=%d", i + 1, ticks); } } connection.reset(); std::this_thread::sleep_for(std::chrono::milliseconds(200)); }, std::chrono::minutes(10)); OATPP_COMPONENT(std::shared_ptr<oatpp::async::Executor>, executor); executor->waitTasksFinished(); executor->stop(); executor->join(); } }}}
vincent-in-black-sesame/oat
test/oatpp/web/FullAsyncTest.cpp
C++
apache-2.0
11,011
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_web_FullAsyncTest_hpp #define oatpp_test_web_FullAsyncTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace web { class FullAsyncTest : public UnitTest { private: v_uint16 m_port; v_int32 m_iterationsPerStep; public: FullAsyncTest(v_uint16 port, v_int32 iterationsPerStep) : UnitTest("TEST[web::FullAsyncTest]") , m_port(port) , m_iterationsPerStep(iterationsPerStep) {} void onRun() override; }; }}} #endif /* oatpp_test_web_FullAsyncTest_hpp */
vincent-in-black-sesame/oat
test/oatpp/web/FullAsyncTest.hpp
C++
apache-2.0
1,535
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "FullTest.hpp" #include "oatpp/web/app/Client.hpp" #include "oatpp/web/app/ControllerWithInterceptors.hpp" #include "oatpp/web/app/ControllerWithErrorHandler.hpp" #include "oatpp/web/app/Controller.hpp" #include "oatpp/web/app/BasicAuthorizationController.hpp" #include "oatpp/web/app/BearerAuthorizationController.hpp" #include "oatpp/web/client/HttpRequestExecutor.hpp" #include "oatpp/web/server/HttpConnectionHandler.hpp" #include "oatpp/web/server/HttpRouter.hpp" #include "oatpp/parser/json/mapping/ObjectMapper.hpp" #include "oatpp/network/tcp/server/ConnectionProvider.hpp" #include "oatpp/network/tcp/client/ConnectionProvider.hpp" #include "oatpp/network/virtual_/client/ConnectionProvider.hpp" #include "oatpp/network/virtual_/server/ConnectionProvider.hpp" #include "oatpp/network/virtual_/Interface.hpp" #include "oatpp/core/data/resource/InMemoryData.hpp" #include "oatpp/core/macro/component.hpp" #include "oatpp-test/web/ClientServerTestRunner.hpp" namespace oatpp { namespace test { namespace web { namespace { typedef oatpp::web::mime::multipart::PartList PartList; typedef oatpp::web::protocol::http::outgoing::MultipartBody MultipartBody; class TestComponent { private: v_uint16 m_port; public: TestComponent(v_uint16 port) : m_port(port) {} OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::network::virtual_::Interface>, virtualInterface)([] { return oatpp::network::virtual_::Interface::obtainShared("virtualhost"); }()); OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::network::ServerConnectionProvider>, serverConnectionProvider)([this] { if(m_port == 0) { // Use oatpp virtual interface OATPP_COMPONENT(std::shared_ptr<oatpp::network::virtual_::Interface>, _interface); return std::static_pointer_cast<oatpp::network::ServerConnectionProvider>( oatpp::network::virtual_::server::ConnectionProvider::createShared(_interface) ); } return std::static_pointer_cast<oatpp::network::ServerConnectionProvider>( oatpp::network::tcp::server::ConnectionProvider::createShared({"localhost", m_port}) ); }()); OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::web::server::HttpRouter>, httpRouter)([] { return oatpp::web::server::HttpRouter::createShared(); }()); OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::network::ConnectionHandler>, serverConnectionHandler)([] { OATPP_COMPONENT(std::shared_ptr<oatpp::web::server::HttpRouter>, router); return oatpp::web::server::HttpConnectionHandler::createShared(router); }()); OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::data::mapping::ObjectMapper>, objectMapper)([] { return oatpp::parser::json::mapping::ObjectMapper::createShared(); }()); OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::network::ClientConnectionProvider>, clientConnectionProvider)([this] { if(m_port == 0) { OATPP_COMPONENT(std::shared_ptr<oatpp::network::virtual_::Interface>, _interface); return std::static_pointer_cast<oatpp::network::ClientConnectionProvider>( oatpp::network::virtual_::client::ConnectionProvider::createShared(_interface) ); } return std::static_pointer_cast<oatpp::network::ClientConnectionProvider>( oatpp::network::tcp::client::ConnectionProvider::createShared({"localhost", m_port}) ); }()); }; std::shared_ptr<PartList> createMultipart(const std::unordered_map<oatpp::String, oatpp::String>& map) { auto multipart = oatpp::web::mime::multipart::PartList::createSharedWithRandomBoundary(); for(auto& pair : map) { oatpp::web::mime::multipart::Headers partHeaders; auto part = std::make_shared<oatpp::web::mime::multipart::Part>(partHeaders); multipart->writeNextPartSimple(part); part->putHeader("Content-Disposition", "form-data; name=\"" + pair.first + "\""); part->setPayload(std::make_shared<oatpp::data::resource::InMemoryData>(pair.second)); } return multipart; } } void FullTest::onRun() { TestComponent component(m_port); oatpp::test::web::ClientServerTestRunner runner; runner.addController(app::Controller::createShared()); runner.addController(app::ControllerWithInterceptors::createShared()); runner.addController(app::ControllerWithErrorHandler::createShared()); runner.addController(app::DefaultBasicAuthorizationController::createShared()); runner.addController(app::BasicAuthorizationController::createShared()); runner.addController(app::BearerAuthorizationController::createShared()); runner.run([this, &runner] { OATPP_COMPONENT(std::shared_ptr<oatpp::network::ClientConnectionProvider>, clientConnectionProvider); OATPP_COMPONENT(std::shared_ptr<oatpp::data::mapping::ObjectMapper>, objectMapper); auto requestExecutor = oatpp::web::client::HttpRequestExecutor::createShared(clientConnectionProvider); auto client = app::Client::createShared(requestExecutor, objectMapper); auto connection = client->getConnection(); OATPP_ASSERT(connection); v_int32 iterationsStep = m_iterationsPerStep; auto lastTick = oatpp::base::Environment::getMicroTickCount(); for(v_int32 i = 0; i < iterationsStep * 10; i ++) { { // test simple GET auto response = client->getRoot(connection); OATPP_ASSERT(response->getStatusCode() == 200); auto value = response->readBodyToString(); OATPP_ASSERT(value == "Hello World!!!"); } { // test simple GET with CORS auto response = client->getCors(connection); OATPP_ASSERT(response->getStatusCode() == 200); auto value = response->readBodyToString(); OATPP_ASSERT(value == "Ping"); auto header = response->getHeader(oatpp::web::protocol::http::Header::CORS_ORIGIN); OATPP_ASSERT(header); OATPP_ASSERT(header == "*"); header = response->getHeader(oatpp::web::protocol::http::Header::CORS_METHODS); OATPP_ASSERT(header); OATPP_ASSERT(header == "GET, POST, OPTIONS"); header = response->getHeader(oatpp::web::protocol::http::Header::CORS_HEADERS); OATPP_ASSERT(header); OATPP_ASSERT(header == "DNT, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Range, Authorization"); } { // test simple OPTIONS with CORS auto response = client->optionsCors(connection); OATPP_ASSERT(response->getStatusCode() == 204); auto header = response->getHeader(oatpp::web::protocol::http::Header::CORS_ORIGIN); OATPP_ASSERT(header); OATPP_ASSERT(header == "*"); header = response->getHeader(oatpp::web::protocol::http::Header::CORS_METHODS); OATPP_ASSERT(header); OATPP_ASSERT(header == "GET, POST, OPTIONS"); header = response->getHeader(oatpp::web::protocol::http::Header::CORS_HEADERS); OATPP_ASSERT(header); OATPP_ASSERT(header == "DNT, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Range, Authorization"); } { // test simple GET with CORS auto response = client->getCorsOrigin(connection); OATPP_ASSERT(response->getStatusCode() == 200); auto value = response->readBodyToString(); OATPP_ASSERT(value == "Pong"); auto header = response->getHeader(oatpp::web::protocol::http::Header::CORS_ORIGIN); OATPP_ASSERT(header); OATPP_ASSERT(header == "127.0.0.1"); header = response->getHeader(oatpp::web::protocol::http::Header::CORS_METHODS); OATPP_ASSERT(header); OATPP_ASSERT(header == "GET, POST, OPTIONS"); header = response->getHeader(oatpp::web::protocol::http::Header::CORS_HEADERS); OATPP_ASSERT(header); OATPP_ASSERT(header == "DNT, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Range, Authorization"); } { // test simple GET with CORS auto response = client->getCorsOriginMethods(connection); OATPP_ASSERT(response->getStatusCode() == 200); auto value = response->readBodyToString(); OATPP_ASSERT(value == "Ping"); auto header = response->getHeader(oatpp::web::protocol::http::Header::CORS_ORIGIN); OATPP_ASSERT(header); OATPP_ASSERT(header == "127.0.0.1"); header = response->getHeader(oatpp::web::protocol::http::Header::CORS_METHODS); OATPP_ASSERT(header); OATPP_ASSERT(header == "GET, OPTIONS"); header = response->getHeader(oatpp::web::protocol::http::Header::CORS_HEADERS); OATPP_ASSERT(header); OATPP_ASSERT(header == "DNT, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Range, Authorization"); } { // test simple GET with CORS auto response = client->getCorsOriginMethodsHeader(connection); OATPP_ASSERT(response->getStatusCode() == 200); auto value = response->readBodyToString(); OATPP_ASSERT(value == "Pong"); auto header = response->getHeader(oatpp::web::protocol::http::Header::CORS_ORIGIN); OATPP_ASSERT(header); OATPP_ASSERT(header == "127.0.0.1"); header = response->getHeader(oatpp::web::protocol::http::Header::CORS_METHODS); OATPP_ASSERT(header); OATPP_ASSERT(header == "GET, OPTIONS"); header = response->getHeader(oatpp::web::protocol::http::Header::CORS_HEADERS); OATPP_ASSERT(header); OATPP_ASSERT(header == "X-PWNT"); } { // test GET with path parameter auto response = client->getWithParams("my_test_param", connection); OATPP_ASSERT(response->getStatusCode() == 200); auto dto = response->readBodyToDto<oatpp::Object<app::TestDto>>(objectMapper.get()); OATPP_ASSERT(dto); OATPP_ASSERT(dto->testValue == "my_test_param"); } { // test GET with query parameters auto response = client->getWithQueries("oatpp", 1, connection); OATPP_ASSERT(response->getStatusCode() == 200); auto dto = response->readBodyToDto<oatpp::Object<app::TestDto>>(objectMapper.get()); OATPP_ASSERT(dto); OATPP_ASSERT(dto->testValue == "name=oatpp&age=1"); } { // test GET with optional query parameters auto response = client->getWithOptQueries("oatpp", connection); OATPP_ASSERT(response->getStatusCode() == 200); auto dto = response->readBodyToDto<oatpp::Object<app::TestDto>>(objectMapper.get()); OATPP_ASSERT(dto); OATPP_ASSERT(dto->testValue == "name=oatpp&age=101"); } { // test GET with query parameters auto response = client->getWithQueriesMap("value1", 32, 0.32f, connection); OATPP_ASSERT(response->getStatusCode() == 200); auto dto = response->readBodyToDto<oatpp::Object<app::TestDto>>(objectMapper.get()); OATPP_ASSERT(dto); OATPP_ASSERT(dto->testMap); OATPP_ASSERT(dto->testMap->size() == 3); OATPP_ASSERT(dto->testMap["key1"] == "value1"); OATPP_ASSERT(dto->testMap["key2"] == "32"); OATPP_ASSERT(dto->testMap["key3"] == oatpp::utils::conversion::float32ToStr(0.32f)); } { // test GET with header parameter auto response = client->getWithHeaders("my_test_header", connection); OATPP_ASSERT(response->getStatusCode() == 200); auto dto = response->readBodyToDto<oatpp::Object<app::TestDto>>(objectMapper.get()); OATPP_ASSERT(dto); OATPP_ASSERT(dto->testValue == "my_test_header"); } { // test POST with body auto response = client->postBody("my_test_body", connection); OATPP_ASSERT(response->getStatusCode() == 200); auto dto = response->readBodyToDto<oatpp::Object<app::TestDto>>(objectMapper.get()); OATPP_ASSERT(dto); OATPP_ASSERT(dto->testValue == "my_test_body"); } { // test POST with dto body auto dtoIn = app::TestDto::createShared(); dtoIn->testValueInt = i; auto response = client->postBodyDto(dtoIn, connection); OATPP_ASSERT(response->getStatusCode() == 200); auto dtoOut = response->readBodyToDto<oatpp::Object<app::TestDto>>(objectMapper.get()); OATPP_ASSERT(dtoOut); OATPP_ASSERT(dtoOut->testValueInt == i); } { // test Enum as String OATPP_ASSERT(oatpp::Enum<app::AllowedPathParams>::getEntries().size() == 2); oatpp::Enum<app::AllowedPathParams> v = app::AllowedPathParams::HELLO; auto response = client->getHeaderEnumAsString(v, connection); OATPP_ASSERT(response->getStatusCode() == 200); } { // test Enum as String oatpp::Enum<app::AllowedPathParams> v = app::AllowedPathParams::HELLO; auto response = client->getHeaderEnumAsNumber(v, connection); OATPP_ASSERT(response->getStatusCode() == 200); } { // test Big Echo with body oatpp::data::stream::BufferOutputStream stream; for(v_int32 i = 0; i < oatpp::data::buffer::IOBuffer::BUFFER_SIZE; i++) { stream.writeSimple("0123456789", 10); } auto data = stream.toString(); auto response = client->echoBody(data, connection); OATPP_ASSERT(response->getStatusCode() == 200); auto returnedData = response->readBodyToString(); OATPP_ASSERT(returnedData); OATPP_ASSERT(returnedData == data); } { auto response = client->headerValueSet(" VALUE_1, VALUE_2, VALUE_3", connection); OATPP_ASSERT(response->getStatusCode() == 200); } { auto response = client->getDefaultHeaders1(connection); OATPP_ASSERT(response->getStatusCode() == 200); } { auto response = client->getDefaultHeaders2("some param", connection); OATPP_ASSERT(response->getStatusCode() == 200); } { // test custom authorization handler with custom authorization object auto response = client->defaultBasicAuthorization("foo:bar", connection); OATPP_ASSERT(response->getStatusCode() == 200); } { // test call of an endpoint that requiers authorization headers, but we don't send one auto response = client->defaultBasicAuthorizationWithoutHeader(); OATPP_ASSERT(response->getStatusCode() == 401); oatpp::String body = response->readBodyToString(); OATPP_ASSERT(body == "server=oatpp/" OATPP_VERSION "\n" "code=401\n" "description=Unauthorized\n" "message=Authorization Required\n"); // should also add the WWW-Authenticate header when Authorization is missing auto header = response->getHeader(oatpp::web::protocol::http::Header::WWW_AUTHENTICATE); OATPP_ASSERT(header); OATPP_ASSERT(header == "Basic realm=\"default-test-realm\""); } { // test custom authorization handler with custom authorization object auto response = client->customBasicAuthorization("foo:bar", connection); OATPP_ASSERT(response->getStatusCode() == 200); } { // test call of an endpoint that requiers authorization headers, but we don't send one auto response = client->customBasicAuthorizationWithoutHeader(); OATPP_ASSERT(response->getStatusCode() == 401); oatpp::String body = response->readBodyToString(); OATPP_ASSERT(body == "server=oatpp/" OATPP_VERSION "\n" "code=401\n" "description=Unauthorized\n" "message=Authorization Required\n"); // should also add the WWW-Authenticate header when Authorization is missing auto header = response->getHeader(oatpp::web::protocol::http::Header::WWW_AUTHENTICATE); OATPP_ASSERT(header); OATPP_ASSERT(header == "Basic realm=\"custom-test-realm\""); } { // test custom authorization handler with custom authorization object with unknown credentials where the // handler returns nullptr auto response = client->customBasicAuthorization("john:doe"); oatpp::String body = response->readBodyToString(); OATPP_ASSERT(response->getStatusCode() == 401); OATPP_ASSERT(body == "server=oatpp/" OATPP_VERSION "\n" "code=401\n" "description=Unauthorized\n" "message=Unauthorized\n"); // should also add the WWW-Authenticate header when Authorization is missing or wrong auto header = response->getHeader(oatpp::web::protocol::http::Header::WWW_AUTHENTICATE); OATPP_ASSERT(header); OATPP_ASSERT(header == "Basic realm=\"custom-test-realm\""); } { // test custom authorization handler with custom authorization method oatpp::String token = "4e99e8c12de7e01535248d2bac85e732"; auto response = client->bearerAuthorization(token); oatpp::String body = response->readBodyToString(); OATPP_ASSERT(response->getStatusCode() == 200); } { // test custom authorization handler with custom authorization object with unknown credentials where the // handler returns nullptr oatpp::String token = "900150983cd24fb0d6963f7d28e17f72"; auto response = client->bearerAuthorization(token); oatpp::String body = response->readBodyToString(); OATPP_ASSERT(response->getStatusCode() == 401); OATPP_ASSERT(body == "server=oatpp/" OATPP_VERSION "\n" "code=401\n" "description=Unauthorized\n" "message=Unauthorized\n"); // should also add the WWW-Authenticate header when Authorization is missing or wrong auto header = response->getHeader(oatpp::web::protocol::http::Header::WWW_AUTHENTICATE); OATPP_ASSERT(header); OATPP_ASSERT(header == "Bearer realm=\"custom-bearer-realm\""); } { // test Chunked body oatpp::String sample = "__abcdefghijklmnopqrstuvwxyz-0123456789"; v_int32 numIterations = 10; oatpp::data::stream::BufferOutputStream stream; for(v_int32 i = 0; i < numIterations; i++) { stream.writeSimple(sample->data(), sample->size()); } auto data = stream.toString(); auto response = client->getChunked(sample, numIterations, connection); OATPP_ASSERT(response->getStatusCode() == 200); auto returnedData = response->readBodyToString(); OATPP_ASSERT(returnedData); OATPP_ASSERT(returnedData == data); } { // Multipart body std::unordered_map<oatpp::String, oatpp::String> map; map["value1"] = "Hello"; map["value2"] = "World"; auto multipart = createMultipart(map); auto body = std::make_shared<MultipartBody>(multipart); auto response = client->multipartTest(i + 1, body); OATPP_ASSERT(response->getStatusCode() == 200); multipart = std::make_shared<oatpp::web::mime::multipart::PartList>(response->getHeaders()); oatpp::web::mime::multipart::Reader multipartReader(multipart.get()); multipartReader.setPartReader("value1", oatpp::web::mime::multipart::createInMemoryPartReader(10)); multipartReader.setPartReader("value2", oatpp::web::mime::multipart::createInMemoryPartReader(10)); response->transferBody(&multipartReader); OATPP_ASSERT(multipart->getAllParts().size() == 2); auto part1 = multipart->getNamedPart("value1"); auto part2 = multipart->getNamedPart("value2"); OATPP_ASSERT(part1); OATPP_ASSERT(part1->getPayload()); OATPP_ASSERT(part2); OATPP_ASSERT(part2->getPayload()); OATPP_ASSERT(part1->getPayload()->getInMemoryData() == "Hello"); OATPP_ASSERT(part2->getPayload()->getInMemoryData() == "World"); } { // test interceptors auto response = client->getInterceptors(connection); OATPP_ASSERT(response->getStatusCode() == 200); auto value = response->readBodyToString(); OATPP_ASSERT(value == "Hello World!!!"); } { // test controller's error handler catches auto response = client->getCaughtError(connection); OATPP_ASSERT(response->getStatusCode() == 418); auto value = response->readBodyToString(); OATPP_ASSERT(value == "Controller With Errors!"); } { // test header replacement auto response = client->getInterceptors(connection); OATPP_ASSERT(response->getStatusCode() == 200); OATPP_ASSERT(response->getHeader("to-be-replaced") == "replaced_value"); } if((i + 1) % iterationsStep == 0) { auto ticks = oatpp::base::Environment::getMicroTickCount() - lastTick; lastTick = oatpp::base::Environment::getMicroTickCount(); OATPP_LOGV("i", "%d, tick=%d", i + 1, ticks); } { // test bundle auto response = client->getBundle(connection); OATPP_ASSERT(response->getStatusCode() == 200); auto dto = response->readBodyToDto<oatpp::Object<app::TestDto>>(objectMapper.get()); OATPP_ASSERT(dto); OATPP_ASSERT(dto->testValue == "str-param"); OATPP_ASSERT(dto->testValueInt == 32000); } { // test host header auto response = client->getHostHeader(connection); OATPP_ASSERT(response->getStatusCode() == 200); auto value = response->readBodyToString(); auto host = clientConnectionProvider->getProperty("host"); OATPP_ASSERT(host); OATPP_ASSERT(value == host.toString() + ":" + oatpp::utils::conversion::int32ToStr(m_port)); } } }, std::chrono::minutes(10)); std::this_thread::sleep_for(std::chrono::seconds(1)); } }}}
vincent-in-black-sesame/oat
test/oatpp/web/FullTest.cpp
C++
apache-2.0
22,814
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_web_FullTest_hpp #define oatpp_test_web_FullTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace web { class FullTest : public UnitTest { private: v_uint16 m_port; v_int32 m_iterationsPerStep; public: FullTest(v_uint16 port, v_int32 iterationsPerStep) : UnitTest("TEST[web::FullTest]") , m_port(port) , m_iterationsPerStep(iterationsPerStep) {} void onRun() override; }; }}} #endif /* oatpp_test_web_FullTest_hpp */
vincent-in-black-sesame/oat
test/oatpp/web/FullTest.hpp
C++
apache-2.0
1,503
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "PipelineAsyncTest.hpp" #include "oatpp/web/app/ControllerAsync.hpp" #include "oatpp/web/server/AsyncHttpConnectionHandler.hpp" #include "oatpp/web/server/HttpRouter.hpp" #include "oatpp/parser/json/mapping/ObjectMapper.hpp" #include "oatpp/network/tcp/server/ConnectionProvider.hpp" #include "oatpp/network/tcp/client/ConnectionProvider.hpp" #include "oatpp/network/virtual_/client/ConnectionProvider.hpp" #include "oatpp/network/virtual_/server/ConnectionProvider.hpp" #include "oatpp/network/virtual_/Interface.hpp" #include "oatpp/core/data/stream/BufferStream.hpp" #include "oatpp/core/macro/component.hpp" #include "oatpp-test/web/ClientServerTestRunner.hpp" namespace oatpp { namespace test { namespace web { namespace { class TestComponent { private: v_uint16 m_port; public: TestComponent(v_uint16 port) : m_port(port) {} OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::async::Executor>, executor)([] { return std::make_shared<oatpp::async::Executor>(1, 1, 1); }()); OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::network::virtual_::Interface>, virtualInterface)([] { return oatpp::network::virtual_::Interface::obtainShared("virtualhost"); }()); OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::network::ServerConnectionProvider>, serverConnectionProvider)([this] { if(m_port == 0) { // Use oatpp virtual interface OATPP_COMPONENT(std::shared_ptr<oatpp::network::virtual_::Interface>, _interface); return std::static_pointer_cast<oatpp::network::ServerConnectionProvider>( oatpp::network::virtual_::server::ConnectionProvider::createShared(_interface) ); } return std::static_pointer_cast<oatpp::network::ServerConnectionProvider>( oatpp::network::tcp::server::ConnectionProvider::createShared({"localhost", m_port}) ); }()); OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::web::server::HttpRouter>, httpRouter)([] { return oatpp::web::server::HttpRouter::createShared(); }()); OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::network::ConnectionHandler>, serverConnectionHandler)([] { OATPP_COMPONENT(std::shared_ptr<oatpp::web::server::HttpRouter>, router); OATPP_COMPONENT(std::shared_ptr<oatpp::async::Executor>, executor); return oatpp::web::server::AsyncHttpConnectionHandler::createShared(router, executor); }()); OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::data::mapping::ObjectMapper>, objectMapper)([] { return oatpp::parser::json::mapping::ObjectMapper::createShared(); }()); OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::network::ClientConnectionProvider>, clientConnectionProvider)([this] { if(m_port == 0) { OATPP_COMPONENT(std::shared_ptr<oatpp::network::virtual_::Interface>, _interface); return std::static_pointer_cast<oatpp::network::ClientConnectionProvider>( oatpp::network::virtual_::client::ConnectionProvider::createShared(_interface) ); } return std::static_pointer_cast<oatpp::network::ClientConnectionProvider>( oatpp::network::tcp::client::ConnectionProvider::createShared({"localhost", m_port}) ); }()); }; const char* const SAMPLE_IN = "GET / HTTP/1.1\r\n" "Connection: keep-alive\r\n" "Content-Length: 0\r\n" "\r\n"; const char* const SAMPLE_OUT = "HTTP/1.1 200 OK\r\n" "Content-Length: 20\r\n" "Connection: keep-alive\r\n" "Server: oatpp/" OATPP_VERSION "\r\n" "\r\n" "Hello World Async!!!"; } void PipelineAsyncTest::onRun() { TestComponent component(m_port); oatpp::test::web::ClientServerTestRunner runner; runner.addController(app::ControllerAsync::createShared()); runner.run([this, &runner] { OATPP_COMPONENT(std::shared_ptr<oatpp::network::ClientConnectionProvider>, clientConnectionProvider); auto connection = clientConnectionProvider->get(); connection.object->setInputStreamIOMode(oatpp::data::stream::IOMode::BLOCKING); std::thread pipeInThread([this, connection] { oatpp::data::stream::BufferOutputStream pipelineStream; for (v_int32 i = 0; i < m_pipelineSize; i++) { pipelineStream << SAMPLE_IN; } oatpp::data::stream::BufferInputStream inputStream(pipelineStream.toString()); oatpp::data::buffer::IOBuffer ioBuffer; oatpp::data::stream::transfer(&inputStream, connection.object.get(), 0, ioBuffer.getData(), ioBuffer.getSize()); }); std::thread pipeOutThread([this, connection] { oatpp::String sample = SAMPLE_OUT; oatpp::data::stream::BufferOutputStream receiveStream; oatpp::data::buffer::IOBuffer ioBuffer; auto res = oatpp::data::stream::transfer(connection.object.get(), &receiveStream, sample->size() * m_pipelineSize, ioBuffer.getData(), ioBuffer.getSize()); auto result = receiveStream.toString(); OATPP_ASSERT(result->size() == sample->size() * m_pipelineSize); //OATPP_ASSERT(result == wantedResult); // headers may come in different order on different OSs }); pipeOutThread.join(); pipeInThread.join(); /////////////////////////////////////////////////////////////////////////////////////////////////////// // Stop server and unblock accepting thread //connection.reset(); std::this_thread::sleep_for(std::chrono::milliseconds(200)); }, std::chrono::minutes(10)); OATPP_COMPONENT(std::shared_ptr<oatpp::async::Executor>, executor); executor->waitTasksFinished(); executor->stop(); executor->join(); } }}}
vincent-in-black-sesame/oat
test/oatpp/web/PipelineAsyncTest.cpp
C++
apache-2.0
6,463
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_web_PipelineAsyncTest_hpp #define oatpp_test_web_PipelineAsyncTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace web { class PipelineAsyncTest : public UnitTest { private: v_uint16 m_port; v_int32 m_pipelineSize; public: PipelineAsyncTest(v_uint16 port, v_int32 pipelineSize) : UnitTest("TEST[web::PipelineAsyncTest]") , m_port(port) , m_pipelineSize(pipelineSize) {} void onRun() override; }; }}} #endif // oatpp_test_web_PipelineAsyncTest_hpp
vincent-in-black-sesame/oat
test/oatpp/web/PipelineAsyncTest.hpp
C++
apache-2.0
1,528
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "PipelineTest.hpp" #include "oatpp/web/app/Controller.hpp" #include "oatpp/web/server/HttpConnectionHandler.hpp" #include "oatpp/web/server/HttpRouter.hpp" #include "oatpp/parser/json/mapping/ObjectMapper.hpp" #include "oatpp/network/tcp/server/ConnectionProvider.hpp" #include "oatpp/network/tcp/client/ConnectionProvider.hpp" #include "oatpp/network/virtual_/client/ConnectionProvider.hpp" #include "oatpp/network/virtual_/server/ConnectionProvider.hpp" #include "oatpp/network/virtual_/Interface.hpp" #include "oatpp/core/data/stream/BufferStream.hpp" #include "oatpp/core/macro/component.hpp" #include "oatpp-test/web/ClientServerTestRunner.hpp" namespace oatpp { namespace test { namespace web { namespace { class TestComponent { private: v_uint16 m_port; public: TestComponent(v_uint16 port) : m_port(port) {} OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::network::virtual_::Interface>, virtualInterface)([] { return oatpp::network::virtual_::Interface::obtainShared("virtualhost"); }()); OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::network::ServerConnectionProvider>, serverConnectionProvider)([this] { if(m_port == 0) { // Use oatpp virtual interface OATPP_COMPONENT(std::shared_ptr<oatpp::network::virtual_::Interface>, _interface); return std::static_pointer_cast<oatpp::network::ServerConnectionProvider>( oatpp::network::virtual_::server::ConnectionProvider::createShared(_interface) ); } return std::static_pointer_cast<oatpp::network::ServerConnectionProvider>( oatpp::network::tcp::server::ConnectionProvider::createShared({"localhost", m_port}) ); }()); OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::web::server::HttpRouter>, httpRouter)([] { return oatpp::web::server::HttpRouter::createShared(); }()); OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::network::ConnectionHandler>, serverConnectionHandler)([] { OATPP_COMPONENT(std::shared_ptr<oatpp::web::server::HttpRouter>, router); return oatpp::web::server::HttpConnectionHandler::createShared(router); }()); OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::data::mapping::ObjectMapper>, objectMapper)([] { return oatpp::parser::json::mapping::ObjectMapper::createShared(); }()); OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::network::ClientConnectionProvider>, clientConnectionProvider)([this] { if(m_port == 0) { OATPP_COMPONENT(std::shared_ptr<oatpp::network::virtual_::Interface>, _interface); return std::static_pointer_cast<oatpp::network::ClientConnectionProvider>( oatpp::network::virtual_::client::ConnectionProvider::createShared(_interface) ); } return std::static_pointer_cast<oatpp::network::ClientConnectionProvider>( oatpp::network::tcp::client::ConnectionProvider::createShared({"localhost", m_port}) ); }()); }; const char* const SAMPLE_IN = "GET / HTTP/1.1\r\n" "Connection: keep-alive\r\n" "Content-Length: 0\r\n" "\r\n"; const char* const SAMPLE_OUT = "HTTP/1.1 200 OK\r\n" "Content-Length: 14\r\n" "Connection: keep-alive\r\n" "Server: oatpp/" OATPP_VERSION "\r\n" "\r\n" "Hello World!!!"; } void PipelineTest::onRun() { TestComponent component(m_port); oatpp::test::web::ClientServerTestRunner runner; runner.addController(app::Controller::createShared()); runner.run([this, &runner] { OATPP_COMPONENT(std::shared_ptr<oatpp::network::ClientConnectionProvider>, clientConnectionProvider); auto connection = clientConnectionProvider->get(); connection.object->setInputStreamIOMode(oatpp::data::stream::IOMode::BLOCKING); std::thread pipeInThread([this, connection] { oatpp::data::stream::BufferOutputStream pipelineStream; for (v_int32 i = 0; i < m_pipelineSize; i++) { pipelineStream << SAMPLE_IN; } auto dataToSend = pipelineStream.toString(); OATPP_LOGD(TAG, "Sending %d bytes", dataToSend->size()); oatpp::data::stream::BufferInputStream inputStream(dataToSend); oatpp::data::buffer::IOBuffer ioBuffer; auto res = oatpp::data::stream::transfer(&inputStream, connection.object.get(), 0, ioBuffer.getData(), ioBuffer.getSize()); }); std::thread pipeOutThread([this, connection] { oatpp::String sample = SAMPLE_OUT; oatpp::data::stream::BufferOutputStream receiveStream; oatpp::data::buffer::IOBuffer ioBuffer; v_io_size transferSize = sample->size() * m_pipelineSize; OATPP_LOGD(TAG, "want to Receive %d bytes", transferSize); auto res = oatpp::data::stream::transfer(connection.object.get(), &receiveStream, transferSize, ioBuffer.getData(), ioBuffer.getSize()); auto result = receiveStream.toString(); OATPP_ASSERT(result->size() == sample->size() * m_pipelineSize); //OATPP_ASSERT(result == wantedResult); // headers may come in different order on different OSs }); pipeOutThread.join(); pipeInThread.join(); }, std::chrono::minutes(10)); std::this_thread::sleep_for(std::chrono::seconds(1)); } }}}
vincent-in-black-sesame/oat
test/oatpp/web/PipelineTest.cpp
C++
apache-2.0
6,078
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_web_PipelineTest_hpp #define oatpp_test_web_PipelineTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace web { class PipelineTest : public UnitTest { private: v_uint16 m_port; v_int32 m_pipelineSize; public: PipelineTest(v_uint16 port, v_int32 pipelineSize) : UnitTest("TEST[web::PipelineTest]") , m_port(port) , m_pipelineSize(pipelineSize) {} void onRun() override; }; }}} #endif // oatpp_test_web_PipelineTest_hpp
vincent-in-black-sesame/oat
test/oatpp/web/PipelineTest.hpp
C++
apache-2.0
1,498
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * Benedikt-Alexander Mokroß <bam@icognize.de> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_web_app_AuthorizationController_hpp #define oatpp_test_web_app_AuthorizationController_hpp #include "./DTOs.hpp" #include "oatpp/web/server/api/ApiController.hpp" #include "oatpp/parser/json/mapping/ObjectMapper.hpp" #include "oatpp/core/utils/ConversionUtils.hpp" #include "oatpp/core/macro/codegen.hpp" #include "oatpp/core/macro/component.hpp" #include <sstream> namespace oatpp { namespace test { namespace web { namespace app { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Default Basic Authorization class DefaultBasicAuthorizationController : public oatpp::web::server::api::ApiController { private: static constexpr const char* TAG = "test::web::app::BasicAuthorizationController"; public: DefaultBasicAuthorizationController(const std::shared_ptr<ObjectMapper>& objectMapper) : oatpp::web::server::api::ApiController(objectMapper) { setDefaultAuthorizationHandler(std::make_shared<oatpp::web::server::handler::BasicAuthorizationHandler>("default-test-realm")); } public: static std::shared_ptr<DefaultBasicAuthorizationController> createShared(const std::shared_ptr<ObjectMapper>& objectMapper = OATPP_GET_COMPONENT(std::shared_ptr<ObjectMapper>)){ return std::make_shared<DefaultBasicAuthorizationController>(objectMapper); } #include OATPP_CODEGEN_BEGIN(ApiController) ENDPOINT("GET", "default-basic-authorization", basicAuthorization, AUTHORIZATION(std::shared_ptr<oatpp::web::server::handler::DefaultBasicAuthorizationObject>, authObject)) { auto dto = TestDto::createShared(); dto->testValue = authObject->userId + ":" + authObject->password; if(dto->testValue == "foo:bar") { return createDtoResponse(Status::CODE_200, dto); } else { return createDtoResponse(Status::CODE_401, dto); } } #include OATPP_CODEGEN_END(ApiController) }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Custom Basic Authorization class MyAuthorizationObject : public oatpp::web::server::handler::AuthorizationObject { public: MyAuthorizationObject(v_int64 pId, const oatpp::String& pAuthString) : id(pId) , authString(pAuthString) {} v_int64 id; oatpp::String authString; }; class MyBasicAuthorizationHandler : public oatpp::web::server::handler::BasicAuthorizationHandler { public: MyBasicAuthorizationHandler() : BasicAuthorizationHandler("custom-test-realm") {} std::shared_ptr<AuthorizationObject> authorize(const oatpp::String& userId, const oatpp::String& password) override { if(userId == "foo" && password == "bar") { return std::make_shared<MyAuthorizationObject>(1337, userId + ":" + password); } return nullptr; } }; class BasicAuthorizationController : public oatpp::web::server::api::ApiController { private: static constexpr const char* TAG = "test::web::app::BasicAuthorizationController"; public: std::shared_ptr<AuthorizationHandler> m_authHandler = std::make_shared<MyBasicAuthorizationHandler>(); public: BasicAuthorizationController(const std::shared_ptr<ObjectMapper>& objectMapper) : oatpp::web::server::api::ApiController(objectMapper) {} public: static std::shared_ptr<BasicAuthorizationController> createShared(const std::shared_ptr<ObjectMapper>& objectMapper = OATPP_GET_COMPONENT(std::shared_ptr<ObjectMapper>)){ return std::make_shared<BasicAuthorizationController>(objectMapper); } #include OATPP_CODEGEN_BEGIN(ApiController) ENDPOINT("GET", "basic-authorization", basicAuthorization, AUTHORIZATION(std::shared_ptr<MyAuthorizationObject>, authObject, m_authHandler)) { auto dto = TestDto::createShared(); dto->testValue = authObject->authString; if(dto->testValue == "foo:bar" && authObject->id == 1337) { return createDtoResponse(Status::CODE_200, dto); } else { return createDtoResponse(Status::CODE_401, dto); } } #include OATPP_CODEGEN_END(ApiController) }; }}}} #endif /* oatpp_test_web_app_Controller_hpp */
vincent-in-black-sesame/oat
test/oatpp/web/app/BasicAuthorizationController.hpp
C++
apache-2.0
5,195
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * Benedikt-Alexander Mokroß <bam@icognize.de> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_web_app_BearerAuthorizationController_hpp #define oatpp_test_web_app_BearerAuthorizationController_hpp #include "./DTOs.hpp" #include "oatpp/web/server/api/ApiController.hpp" #include "oatpp/parser/json/mapping/ObjectMapper.hpp" #include "oatpp/core/utils/ConversionUtils.hpp" #include "oatpp/core/macro/codegen.hpp" #include "oatpp/core/macro/component.hpp" #include <sstream> namespace oatpp { namespace test { namespace web { namespace app { class BearerAuthorizationObject : public oatpp::web::server::handler::AuthorizationObject { public: oatpp::String user; oatpp::String password; oatpp::String token; }; class MyBearerAuthorizationHandler : public oatpp::web::server::handler::BearerAuthorizationHandler { public: MyBearerAuthorizationHandler() : oatpp::web::server::handler::BearerAuthorizationHandler("custom-bearer-realm") {} std::shared_ptr<AuthorizationObject> authorize(const oatpp::String& token) override { if(token == "4e99e8c12de7e01535248d2bac85e732") { auto obj = std::make_shared<BearerAuthorizationObject>(); obj->user = "foo"; obj->password = "bar"; obj->token = token; return obj; } return nullptr; } }; class BearerAuthorizationController : public oatpp::web::server::api::ApiController { private: static constexpr const char* TAG = "test::web::app::BearerAuthorizationController"; private: std::shared_ptr<AuthorizationHandler> m_authHandler = std::make_shared<MyBearerAuthorizationHandler>(); public: BearerAuthorizationController(const std::shared_ptr<ObjectMapper>& objectMapper) : oatpp::web::server::api::ApiController(objectMapper) {} public: static std::shared_ptr<BearerAuthorizationController> createShared(const std::shared_ptr<ObjectMapper>& objectMapper = OATPP_GET_COMPONENT(std::shared_ptr<ObjectMapper>)){ return std::make_shared<BearerAuthorizationController>(objectMapper); } #include OATPP_CODEGEN_BEGIN(ApiController) ENDPOINT("GET", "bearer-authorization", authorization, AUTHORIZATION(std::shared_ptr<BearerAuthorizationObject>, authorizatioBearer, m_authHandler)) { auto dto = TestDto::createShared(); dto->testValue = authorizatioBearer->user + ":" + authorizatioBearer->password; if(dto->testValue == "foo:bar" && authorizatioBearer->token == "4e99e8c12de7e01535248d2bac85e732") { return createDtoResponse(Status::CODE_200, dto); } else { return createDtoResponse(Status::CODE_401, dto); } } #include OATPP_CODEGEN_END(ApiController) }; }}}} #endif /* oatpp_test_web_app_Controller_hpp */
vincent-in-black-sesame/oat
test/oatpp/web/app/BearerAuthorizationController.hpp
C++
apache-2.0
3,672
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_web_app_Client_hpp #define oatpp_test_web_app_Client_hpp #include "./DTOs.hpp" #include "oatpp/web/client/ApiClient.hpp" #include "oatpp/web/protocol/http/outgoing/MultipartBody.hpp" #include "oatpp/encoding/Base64.hpp" #include "oatpp/core/macro/codegen.hpp" namespace oatpp { namespace test { namespace web { namespace app { class Client : public oatpp::web::client::ApiClient { public: typedef oatpp::web::protocol::http::outgoing::MultipartBody MultipartBody; public: #include OATPP_CODEGEN_BEGIN(ApiClient) API_CLIENT_INIT(Client) API_CALL("GET", "/", getRoot) API_CALL("GET", "/availability", getAvailability) API_CALL("GET", "/cors", getCors) API_CALL("OPTIONS", "/cors", optionsCors) API_CALL("GET", "/cors-origin", getCorsOrigin) API_CALL("GET", "/cors-origin-methods", getCorsOriginMethods) API_CALL("GET", "/cors-origin-methods-headers", getCorsOriginMethodsHeader) API_CALL("GET", "params/{param}", getWithParams, PATH(String, param)) API_CALL("GET", "queries", getWithQueries, QUERY(String, name), QUERY(Int32, age)) API_CALL("GET", "queries/optional", getWithOptQueries, QUERY(String, name)) API_CALL("GET", "queries/map", getWithQueriesMap, QUERY(String, key1), QUERY(Int32, key2), QUERY(Float32, key3)) API_CALL("GET", "headers", getWithHeaders, HEADER(String, param, "X-TEST-HEADER")) API_CALL("POST", "body", postBody, BODY_STRING(String, body)) API_CALL("POST", "body-dto", postBodyDto, BODY_DTO(Object<TestDto>, body)) API_CALL("GET", "enum/as-string", getHeaderEnumAsString, HEADER(Enum<AllowedPathParams>::AsString, enumValue, "enum")) API_CALL("GET", "enum/as-number", getHeaderEnumAsNumber, HEADER(Enum<AllowedPathParams>::AsNumber, enumValue, "enum")) API_CALL("POST", "echo", echoBody, BODY_STRING(String, body)) API_CALL("GET", "header-value-set", headerValueSet, HEADER(String, valueSet, "X-VALUE-SET")) API_CALL("GET", "default-basic-authorization", defaultBasicAuthorization, AUTHORIZATION_BASIC(String, authString)) API_CALL("GET", "default-basic-authorization", defaultBasicAuthorizationWithoutHeader) API_CALL("GET", "basic-authorization", customBasicAuthorization, AUTHORIZATION_BASIC(String, authString)) API_CALL("GET", "basic-authorization", customBasicAuthorizationWithoutHeader) API_CALL("GET", "bearer-authorization", bearerAuthorization, AUTHORIZATION(String, authString, "Bearer")) API_CALL("GET", "chunked/{text-value}/{num-iterations}", getChunked, PATH(String, text, "text-value"), PATH(Int32, numIterations, "num-iterations")) API_CALL("POST", "test/multipart/{chunk-size}", multipartTest, PATH(Int32, chunkSize, "chunk-size"), BODY(std::shared_ptr<MultipartBody>, body)) API_CALL("GET", "test/interceptors", getInterceptors) API_CALL("GET", "test/errorhandling", getCaughtError) API_CALL_HEADERS(getDefaultHeaders1) { headers.put("X-DEFAULT", "hello_1"); } API_CALL("GET", "default_headers", getDefaultHeaders1) API_CALL_HEADERS(getDefaultHeaders2) { headers.put("X-DEFAULT", "hello_2"); } API_CALL("GET", "default_headers/{param}", getDefaultHeaders2, PATH(String, param)) API_CALL("GET", "bundle", getBundle) API_CALL("GET", "host_header", getHostHeader) API_CALL_ASYNC("GET", "/", getRootAsync) API_CALL_ASYNC("GET", "/", getRootAsyncWithCKA, HEADER(String, connection, "Connection")) API_CALL_ASYNC("GET", "params/{param}", getWithParamsAsync, PATH(String, param)) API_CALL_ASYNC("GET", "queries", getWithQueriesAsync, QUERY(String, name), QUERY(Int32, age)) API_CALL_ASYNC("GET", "queries/map", getWithQueriesMapAsync, QUERY(String, key1), QUERY(Int32, key2), QUERY(Float32, key3)) API_CALL_ASYNC("GET", "headers", getWithHeadersAsync, HEADER(String, param, "X-TEST-HEADER")) API_CALL_ASYNC("POST", "body", postBodyAsync, BODY_STRING(String, body)) API_CALL_ASYNC("POST", "echo", echoBodyAsync, BODY_STRING(String, body)) API_CALL_ASYNC("GET", "header-value-set", headerValueSetAsync, HEADER(String, valueSet, "X-VALUE-SET")) API_CALL_ASYNC("GET", "chunked/{text-value}/{num-iterations}", getChunkedAsync, PATH(String, text, "text-value"), PATH(Int32, numIterations, "num-iterations")) API_CALL_HEADERS(GetDefaultHeaders3) { headers.put("X-DEFAULT", "hello_3"); } API_CALL_ASYNC("GET", "default_headers", GetDefaultHeaders3) API_CALL_HEADERS(GetDefaultHeaders4) { headers.put("X-DEFAULT", "hello_4"); } API_CALL_ASYNC("GET", "default_headers/{param}", GetDefaultHeaders4, PATH(String, param)) #include OATPP_CODEGEN_END(ApiClient) }; }}}} #endif /* oatpp_test_web_app_Client_hpp */
vincent-in-black-sesame/oat
test/oatpp/web/app/Client.hpp
C++
apache-2.0
5,605
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_web_app_Controller_hpp #define oatpp_test_web_app_Controller_hpp #include "./DTOs.hpp" #include "oatpp/web/mime/multipart/FileProvider.hpp" #include "oatpp/web/mime/multipart/InMemoryDataProvider.hpp" #include "oatpp/web/mime/multipart/Reader.hpp" #include "oatpp/web/mime/multipart/PartList.hpp" #include "oatpp/web/protocol/http/outgoing/MultipartBody.hpp" #include "oatpp/web/protocol/http/outgoing/StreamingBody.hpp" #include "oatpp/web/server/api/ApiController.hpp" #include "oatpp/parser/json/mapping/ObjectMapper.hpp" #include "oatpp/core/data/resource/File.hpp" #include "oatpp/core/data/stream/FileStream.hpp" #include "oatpp/core/utils/ConversionUtils.hpp" #include "oatpp/core/macro/codegen.hpp" #include "oatpp/core/macro/component.hpp" #include <sstream> #include <thread> namespace oatpp { namespace test { namespace web { namespace app { namespace multipart = oatpp::web::mime::multipart; #include OATPP_CODEGEN_BEGIN(ApiController) class Controller : public oatpp::web::server::api::ApiController { private: static constexpr const char* TAG = "test::web::app::Controller"; public: Controller(const std::shared_ptr<ObjectMapper>& objectMapper) : oatpp::web::server::api::ApiController(objectMapper) , available(true) {} public: static std::shared_ptr<Controller> createShared(const std::shared_ptr<ObjectMapper>& objectMapper = OATPP_GET_COMPONENT(std::shared_ptr<ObjectMapper>)){ return std::make_shared<Controller>(objectMapper); } std::atomic<bool> available; ENDPOINT("GET", "/", root) { //OATPP_LOGD(TAG, "GET ROOT"); return createResponse(Status::CODE_200, "Hello World!!!"); } ENDPOINT("GET", "/availability", availability) { //OATPP_LOGV(TAG, "GET '/availability'"); if(available) { return createResponse(Status::CODE_200, "Hello World!!!"); } OATPP_LOGI(TAG, "GET '/availability'. Service unavailable."); OATPP_ASSERT_HTTP(false, Status::CODE_503, "Service unavailable") } ADD_CORS(cors); ENDPOINT("GET", "/cors", cors) { return createResponse(Status::CODE_200, "Ping"); } ADD_CORS(corsOrigin, "127.0.0.1"); ENDPOINT("GET", "/cors-origin", corsOrigin) { return createResponse(Status::CODE_200, "Pong"); } ADD_CORS(corsOriginMethods, "127.0.0.1", "GET, OPTIONS"); ENDPOINT("GET", "/cors-origin-methods", corsOriginMethods) { return createResponse(Status::CODE_200, "Ping"); } ADD_CORS(corsOriginMethodsHeaders, "127.0.0.1", "GET, OPTIONS", "X-PWNT"); ENDPOINT("GET", "/cors-origin-methods-headers", corsOriginMethodsHeaders) { return createResponse(Status::CODE_200, "Pong"); } ENDPOINT("GET", "params/{param}", getWithParams, PATH(String, param)) { //OATPP_LOGV(TAG, "GET params/%s", param->c_str()); auto dto = TestDto::createShared(); dto->testValue = param; return createDtoResponse(Status::CODE_200, dto); } ENDPOINT("GET", "queries", getWithQueries, QUERY(String, name), QUERY(Int32, age)) { auto dto = TestDto::createShared(); dto->testValue = "name=" + name + "&age=" + oatpp::utils::conversion::int32ToStr(*age); return createDtoResponse(Status::CODE_200, dto); } ENDPOINT("GET", "queries/optional", getWithOptQueries, QUERY(String, name, "name", "Default"), QUERY(Int32, age, "age", 101)) { auto dto = TestDto::createShared(); dto->testValue = "name=" + name + "&age=" + oatpp::utils::conversion::int32ToStr(*age); return createDtoResponse(Status::CODE_200, dto); } ENDPOINT("GET", "queries/map", getWithQueriesMap, QUERIES(QueryParams, queries)) { auto dto = TestDto::createShared(); dto->testMap = dto->testMap.createShared(); for(auto& it : queries.getAll()) { dto->testMap[it.first.toString()] = it.second.toString(); } return createDtoResponse(Status::CODE_200, dto); } ENDPOINT("GET", "headers", getWithHeaders, HEADER(String, param, "X-TEST-HEADER")) { //OATPP_LOGV(TAG, "GET headers {X-TEST-HEADER: %s}", param->c_str()); auto dto = TestDto::createShared(); dto->testValue = param; return createDtoResponse(Status::CODE_200, dto); } ENDPOINT("POST", "body", postBody, BODY_STRING(String, body)) { //OATPP_LOGV(TAG, "POST body %s", body->c_str()); auto dto = TestDto::createShared(); dto->testValue = body; return createDtoResponse(Status::CODE_200, dto); } ENDPOINT("POST", "body-dto", postBodyDto, BODY_DTO(Object<TestDto>, body)) { //OATPP_LOGV(TAG, "POST body %s", body->c_str()); return createDtoResponse(Status::CODE_200, body); } ENDPOINT("POST", "echo", echo, BODY_STRING(String, body)) { //OATPP_LOGV(TAG, "POST body(echo) size=%d", body->getSize()); return createResponse(Status::CODE_200, body); } ENDPOINT("GET", "header-value-set", headerValueSet, HEADER(String, valueSet, "X-VALUE-SET")) { oatpp::web::protocol::http::HeaderValueData valueData; oatpp::web::protocol::http::Parser::parseHeaderValueData(valueData, valueSet, ','); OATPP_ASSERT_HTTP(valueData.tokens.find("VALUE_1") != valueData.tokens.end(), Status::CODE_400, "No header 'VALUE_1' in value set"); OATPP_ASSERT_HTTP(valueData.tokens.find("VALUE_2") != valueData.tokens.end(), Status::CODE_400, "No header 'VALUE_2' in value set"); OATPP_ASSERT_HTTP(valueData.tokens.find("VALUE_3") != valueData.tokens.end(), Status::CODE_400, "No header 'VALUE_3' in value set"); return createResponse(Status::CODE_200, ""); } class ReadCallback : public oatpp::data::stream::ReadCallback { private: oatpp::String m_text; v_int32 m_counter; v_int32 m_iterations; data::buffer::InlineWriteData m_inlineData; public: ReadCallback(const oatpp::String& text, v_int32 iterations) : m_text(text) , m_counter(0) , m_iterations(iterations) , m_inlineData(text->data(), text->size()) {} v_io_size read(void *buffer, v_buff_size count, async::Action& action) override { if(m_counter < m_iterations) { v_buff_size desiredToRead = m_inlineData.bytesLeft; if (desiredToRead > 0) { if (desiredToRead > count) { desiredToRead = count; } std::memcpy(buffer, m_inlineData.currBufferPtr, desiredToRead); m_inlineData.inc(desiredToRead); if (m_inlineData.bytesLeft == 0) { m_inlineData.set(m_text->data(), m_text->size()); m_counter++; } return desiredToRead; } } return 0; } }; ENDPOINT("GET", "chunked/{text-value}/{num-iterations}", chunked, PATH(String, text, "text-value"), PATH(Int32, numIterations, "num-iterations"), REQUEST(std::shared_ptr<IncomingRequest>, request)) { auto body = std::make_shared<oatpp::web::protocol::http::outgoing::StreamingBody> (std::make_shared<ReadCallback>(text, *numIterations)); return OutgoingResponse::createShared(Status::CODE_200, body); } ENDPOINT("POST", "test/multipart/{chunk-size}", multipartTest, PATH(Int32, chunkSize, "chunk-size"), REQUEST(std::shared_ptr<IncomingRequest>, request)) { auto multipart = std::make_shared<oatpp::web::mime::multipart::PartList>(request->getHeaders()); oatpp::web::mime::multipart::Reader multipartReader(multipart.get()); multipartReader.setDefaultPartReader(oatpp::web::mime::multipart::createInMemoryPartReader(10)); request->transferBody(&multipartReader); auto responseBody = std::make_shared<oatpp::web::protocol::http::outgoing::MultipartBody>(multipart); return OutgoingResponse::createShared(Status::CODE_200, responseBody); } ENDPOINT("POST", "test/multipart-all", multipartFileTest, REQUEST(std::shared_ptr<IncomingRequest>, request)) { /* Prepare multipart container. */ auto multipart = std::make_shared<multipart::PartList>(request->getHeaders()); /* Create multipart reader. */ multipart::Reader multipartReader(multipart.get()); /* Configure to read part with name "part1" into memory */ multipartReader.setPartReader("part1", multipart::createInMemoryPartReader(256 /* max-data-size */)); /* Configure to stream part with name "part2" to file */ multipartReader.setPartReader("part2", multipart::createFilePartReader("/Users/leonid/Documents/test/my-text-file.tf")); /* Configure to read all other parts into memory */ multipartReader.setDefaultPartReader(multipart::createInMemoryPartReader(16 * 1024 /* max-data-size */)); /* Read multipart body */ request->transferBody(&multipartReader); /* Print number of uploaded parts */ OATPP_LOGD("Multipart", "parts_count=%d", multipart->count()); /* Print value of "part1" */ auto part1 = multipart->getNamedPart("part1"); OATPP_ASSERT_HTTP(part1, Status::CODE_400, "part1 is empty"); OATPP_LOGD("Multipart", "part1='%s'", part1->getPayload()->getInMemoryData()->c_str()); /* Get part by name "part2"*/ auto filePart = multipart->getNamedPart("part2"); OATPP_ASSERT_HTTP(filePart, Status::CODE_400, "part2 is empty"); auto inputStream = filePart->getPayload()->openInputStream(); // TODO - process file stream. return createResponse(Status::CODE_200, "OK"); } class MPStream : public oatpp::web::mime::multipart::Multipart { public: typedef oatpp::web::mime::multipart::Part Part; private: v_uint32 counter = 0; public: MPStream() : oatpp::web::mime::multipart::Multipart(generateRandomBoundary()) {} std::shared_ptr<Part> readNextPart(async::Action& action) override { if(counter == 10) { return nullptr; } std::this_thread::sleep_for(std::chrono::seconds(1)); auto part = std::make_shared<Part>(); part->putHeader(Header::CONTENT_TYPE, "text/html"); oatpp::String frameData; // if(counter % 2 == 0) { // frameData = "<html><body>0</body></html>"; // } else { // frameData = "<html><body>1</body></html>"; // } // part->setDataInfo(std::make_shared<oatpp::data::stream::BufferInputStream>(frameData)); if(counter % 2 == 0) { part->setPayload(std::make_shared<data::resource::File>("/Users/leonid/Documents/test/frame1.jpg")); } else { part->setPayload(std::make_shared<data::resource::File>("/Users/leonid/Documents/test/frame2.jpg")); } ++ counter; OATPP_LOGD("Multipart", "Frame sent!"); return part; } void writeNextPart(const std::shared_ptr<Part>& part, async::Action& action) override { throw std::runtime_error("No writes here!!!"); } }; ENDPOINT("GET", "multipart-stream", multipartStream) { auto multipart = std::make_shared<MPStream>(); auto body = std::make_shared<oatpp::web::protocol::http::outgoing::MultipartBody>( multipart, "multipart/x-mixed-replace", true /* flush parts */ ); return OutgoingResponse::createShared(Status::CODE_200, body); } ENDPOINT("GET", "enum/as-string", testEnumString, HEADER(Enum<AllowedPathParams>::AsString, enumValue, "enum")) { return createResponse(Status::CODE_200, ""); } ENDPOINT("GET", "enum/as-number", testEnumNumber, HEADER(Enum<AllowedPathParams>::AsNumber, enumValue, "enum")) { return createResponse(Status::CODE_200, ""); } ENDPOINT("GET", "default_headers", getDefaultHeaders1, HEADER(String, header, "X-DEFAULT")) { if(header == "hello_1") { return createResponse(Status::CODE_200, ""); } return createResponse(Status::CODE_400, ""); } ENDPOINT("GET", "default_headers/{param}", getDefaultHeaders2, HEADER(String, header, "X-DEFAULT"), PATH(String, param)) { if(header == "hello_2") { return createResponse(Status::CODE_200, ""); } return createResponse(Status::CODE_400, ""); } ENDPOINT_INTERCEPTOR(getBundle, middleware) { request->putBundleData("str_param", oatpp::String("str-param")); request->putBundleData("int_param", oatpp::Int32(32000)); return (this->*intercepted)(request); } ENDPOINT("GET", "bundle", getBundle, BUNDLE(String, str_param), BUNDLE(Int32, a, "int_param")) { auto dto = TestDto::createShared(); dto->testValue = str_param; dto->testValueInt = a; return createDtoResponse(Status::CODE_200, dto); } ENDPOINT("GET", "host_header", getHostHeader, REQUEST(std::shared_ptr<IncomingRequest>, request)) { auto hostHeader = request->getHeader("Host"); if(hostHeader) { return createResponse(Status::CODE_200, hostHeader); } return createResponse(Status::CODE_400, ""); } }; #include OATPP_CODEGEN_END(ApiController) }}}} #endif /* oatpp_test_web_app_Controller_hpp */
vincent-in-black-sesame/oat
test/oatpp/web/app/Controller.hpp
C++
apache-2.0
13,942
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_web_app_ControllerAsync_hpp #define oatpp_test_web_app_ControllerAsync_hpp #include "./DTOs.hpp" #include "oatpp/web/mime/multipart/FileProvider.hpp" #include "oatpp/web/mime/multipart/InMemoryDataProvider.hpp" #include "oatpp/web/mime/multipart/Reader.hpp" #include "oatpp/web/mime/multipart/PartList.hpp" #include "oatpp/web/protocol/http/outgoing/MultipartBody.hpp" #include "oatpp/web/protocol/http/outgoing/StreamingBody.hpp" #include "oatpp/web/server/api/ApiController.hpp" #include "oatpp/parser/json/mapping/ObjectMapper.hpp" #include "oatpp/core/data/resource/File.hpp" #include "oatpp/core/data/stream/FileStream.hpp" #include "oatpp/core/data/stream/Stream.hpp" #include "oatpp/core/utils/ConversionUtils.hpp" #include "oatpp/core/macro/codegen.hpp" #include "oatpp/core/macro/component.hpp" namespace oatpp { namespace test { namespace web { namespace app { namespace multipart = oatpp::web::mime::multipart; class ControllerAsync : public oatpp::web::server::api::ApiController { private: static constexpr const char* TAG = "test::web::app::ControllerAsync"; public: ControllerAsync(const std::shared_ptr<ObjectMapper>& objectMapper) : oatpp::web::server::api::ApiController(objectMapper) {} public: static std::shared_ptr<ControllerAsync> createShared(const std::shared_ptr<ObjectMapper>& objectMapper = OATPP_GET_COMPONENT(std::shared_ptr<ObjectMapper>)){ return std::make_shared<ControllerAsync>(objectMapper); } #include OATPP_CODEGEN_BEGIN(ApiController) ENDPOINT_ASYNC("GET", "/", Root) { ENDPOINT_ASYNC_INIT(Root) Action act() { //OATPP_LOGV(TAG, "GET '/'"); return _return(controller->createResponse(Status::CODE_200, "Hello World Async!!!")); } }; ENDPOINT_ASYNC("GET", "params/{param}", GetWithParams) { ENDPOINT_ASYNC_INIT(GetWithParams) Action act() { auto param = request->getPathVariable("param"); //OATPP_LOGV(TAG, "GET params/%s", param->c_str()); auto dto = TestDto::createShared(); dto->testValue = param; return _return(controller->createDtoResponse(Status::CODE_200, dto)); } }; ENDPOINT_ASYNC("GET", "headers", GetWithHeaders) { ENDPOINT_ASYNC_INIT(GetWithHeaders) Action act() { auto param = request->getHeader("X-TEST-HEADER"); //OATPP_LOGV(TAG, "GET headers {X-TEST-HEADER: %s}", param->c_str()); auto dto = TestDto::createShared(); dto->testValue = param; return _return(controller->createDtoResponse(Status::CODE_200, dto)); } }; ENDPOINT_ASYNC("POST", "body", PostBody) { ENDPOINT_ASYNC_INIT(PostBody) Action act() { //OATPP_LOGV(TAG, "POST body. Reading body..."); return request->readBodyToStringAsync().callbackTo(&PostBody::onBodyRead); } Action onBodyRead(const String& body) { //OATPP_LOGV(TAG, "POST body %s", body->c_str()); auto dto = TestDto::createShared(); dto->testValue = body; return _return(controller->createDtoResponse(Status::CODE_200, dto)); } }; ENDPOINT_ASYNC("POST", "echo", Echo) { ENDPOINT_ASYNC_INIT(Echo) Action act() { //OATPP_LOGV(TAG, "POST body(echo). Reading body..."); return request->readBodyToStringAsync().callbackTo(&Echo::onBodyRead); } Action onBodyRead(const String& body) { //OATPP_LOGV(TAG, "POST echo size=%d", body->getSize()); return _return(controller->createResponse(Status::CODE_200, body)); } }; ENDPOINT_ASYNC("GET", "chunked/{text-value}/{num-iterations}", Chunked) { ENDPOINT_ASYNC_INIT(Chunked) class ReadCallback : public oatpp::data::stream::ReadCallback { private: oatpp::String m_text; v_int32 m_counter; v_int32 m_iterations; data::buffer::InlineWriteData m_inlineData; public: ReadCallback(const oatpp::String& text, v_int32 iterations) : m_text(text) , m_counter(0) , m_iterations(iterations) , m_inlineData(text->data(), text->size()) {} v_io_size read(void *buffer, v_buff_size count, async::Action& action) override { if(m_counter < m_iterations) { v_buff_size desiredToRead = m_inlineData.bytesLeft; if (desiredToRead > 0) { if (desiredToRead > count) { desiredToRead = count; } std::memcpy(buffer, m_inlineData.currBufferPtr, desiredToRead); m_inlineData.inc(desiredToRead); if (m_inlineData.bytesLeft == 0) { m_inlineData.set(m_text->data(), m_text->size()); m_counter++; } return desiredToRead; } } return 0; } }; Action act() { oatpp::String text = request->getPathVariable("text-value"); auto numIterations = oatpp::utils::conversion::strToInt32(request->getPathVariable("num-iterations")->c_str()); auto body = std::make_shared<oatpp::web::protocol::http::outgoing::StreamingBody> (std::make_shared<ReadCallback>(text, numIterations)); return _return(OutgoingResponse::createShared(Status::CODE_200, body)); } }; ENDPOINT_ASYNC("POST", "test/multipart/{chunk-size}", MultipartTest) { ENDPOINT_ASYNC_INIT(MultipartTest) v_int32 m_chunkSize; std::shared_ptr<oatpp::web::mime::multipart::PartList> m_multipart; Action act() override { m_chunkSize = oatpp::utils::conversion::strToInt32(request->getPathVariable("chunk-size")->c_str()); m_multipart = std::make_shared<oatpp::web::mime::multipart::PartList>(request->getHeaders()); auto multipartReader = std::make_shared<oatpp::web::mime::multipart::AsyncReader>(m_multipart); multipartReader->setDefaultPartReader(oatpp::web::mime::multipart::createAsyncInMemoryPartReader(10)); return request->transferBodyAsync(multipartReader).next(yieldTo(&MultipartTest::respond)); } Action respond() { auto responseBody = std::make_shared<oatpp::web::protocol::http::outgoing::MultipartBody>(m_multipart); return _return(OutgoingResponse::createShared(Status::CODE_200, responseBody)); } }; ENDPOINT_ASYNC("POST", "test/multipart-all", MultipartUpload) { ENDPOINT_ASYNC_INIT(MultipartUpload) /* Coroutine State */ std::shared_ptr<multipart::PartList> m_multipart; Action act() override { m_multipart = std::make_shared<multipart::PartList>(request->getHeaders()); auto multipartReader = std::make_shared<multipart::AsyncReader>(m_multipart); /* Configure to read part with name "part1" into memory */ multipartReader->setPartReader("part1", multipart::createAsyncInMemoryPartReader(256 /* max-data-size */)); /* Configure to stream part with name "part2" to file */ multipartReader->setPartReader("part2", multipart::createAsyncFilePartReader("/Users/leonid/Documents/test/my-text-file.tf")); /* Configure to read all other parts into memory */ multipartReader->setDefaultPartReader(multipart::createAsyncInMemoryPartReader(16 * 1024 /* max-data-size */)); /* Read multipart body */ return request->transferBodyAsync(multipartReader).next(yieldTo(&MultipartUpload::onUploaded)); } Action onUploaded() { /* Print number of uploaded parts */ OATPP_LOGD("Multipart", "parts_count=%d", m_multipart->count()); /* Get multipart by name */ auto part1 = m_multipart->getNamedPart("part1"); /* Asser part not-null */ OATPP_ASSERT_HTTP(part1, Status::CODE_400, "part1 is empty"); /* Print value of "part1" */ OATPP_LOGD("Multipart", "part1='%s'", part1->getPayload()->getInMemoryData()->c_str()); /* Get multipart by name */ auto filePart = m_multipart->getNamedPart("part2"); /* Asser part not-null */ OATPP_ASSERT_HTTP(filePart, Status::CODE_400, "part2 is empty"); auto inputStream = filePart->getPayload()->openInputStream(); // TODO - process file stream. return _return(controller->createResponse(Status::CODE_200, "OK")); } }; class MPStream : public oatpp::web::mime::multipart::Multipart { public: typedef oatpp::web::mime::multipart::Part Part; private: v_uint32 counter = 0; bool m_wait = false; public: MPStream() : oatpp::web::mime::multipart::Multipart(generateRandomBoundary()) {} std::shared_ptr<Part> readNextPart(async::Action& action) override { if(counter == 10) { return nullptr; } if(m_wait) { m_wait = false; action = async::Action::createWaitRepeatAction(1000 * 1000 + oatpp::base::Environment::getMicroTickCount()); return nullptr; } m_wait = true; auto part = std::make_shared<Part>(); part->putHeader(Header::CONTENT_TYPE, "text/html"); oatpp::String frameData; // if(counter % 2 == 0) { // frameData = "<html><body>0</body></html>"; // } else { // frameData = "<html><body>1</body></html>"; // } // part->setDataInfo(std::make_shared<oatpp::data::stream::BufferInputStream>(frameData)); if(counter % 2 == 0) { part->setPayload(std::make_shared<data::resource::File>("/Users/leonid/Documents/test/frame1.jpg")); } else { part->setPayload(std::make_shared<data::resource::File>("/Users/leonid/Documents/test/frame2.jpg")); } ++ counter; OATPP_LOGD("Multipart", "Frame sent!"); return part; } void writeNextPart(const std::shared_ptr<Part>& part, async::Action& action) override { throw std::runtime_error("No writes here!!!"); } }; ENDPOINT_ASYNC("GET", "multipart-stream", MultipartStream) { ENDPOINT_ASYNC_INIT(MultipartStream) Action act() { auto multipart = std::make_shared<MPStream>(); auto body = std::make_shared<oatpp::web::protocol::http::outgoing::MultipartBody>( multipart, "multipart/x-mixed-replace", true /* flush parts */ ); return _return(OutgoingResponse::createShared(Status::CODE_200, body)); } }; ENDPOINT_ASYNC("GET", "host_header", HostHeader) { ENDPOINT_ASYNC_INIT(HostHeader) Action act() { auto hostHeader = request->getHeader("Host"); if(hostHeader) { return _return(controller->createResponse(Status::CODE_200, hostHeader)); } return _return(controller->createResponse(Status::CODE_400, "")); } }; #include OATPP_CODEGEN_END(ApiController) }; }}}} #endif /* oatpp_test_web_app_ControllerAsync_hpp */
vincent-in-black-sesame/oat
test/oatpp/web/app/ControllerAsync.hpp
C++
apache-2.0
11,602
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_web_app_ControllerWithErrorHandler_hpp #define oatpp_test_web_app_ControllerWithErrorHandler_hpp #include "oatpp/web/server/api/ApiController.hpp" #include "oatpp/parser/json/mapping/ObjectMapper.hpp" #include "oatpp/core/utils/ConversionUtils.hpp" #include "oatpp/core/macro/codegen.hpp" #include "oatpp/core/macro/component.hpp" #include <sstream> namespace oatpp { namespace test { namespace web { namespace app { namespace http = oatpp::web::protocol::http; /** * Custom Error Handler. */ class CustomErrorHandler : public oatpp::base::Countable, public oatpp::web::server::handler::ErrorHandler { public: /** * Constructor. */ CustomErrorHandler() = default; public: /** * Create shared DefaultErrorHandler. * @return - `std::shared_ptr` to DefaultErrorHandler. */ static std::shared_ptr<CustomErrorHandler> createShared() { return std::make_shared<CustomErrorHandler>(); } std::shared_ptr<http::outgoing::Response> handleError(const std::exception_ptr& error) override { try { std::rethrow_exception(error); } catch(const std::runtime_error& e) { return oatpp::web::protocol::http::outgoing::ResponseFactory::createResponse(http::Status::CODE_418, e.what()); } catch(...) { throw; } } std::shared_ptr<oatpp::web::protocol::http::outgoing::Response> handleError(const http::Status& status, const oatpp::String& message, const Headers& headers) override { throw std::logic_error("Function not implemented"); } }; class ControllerWithErrorHandler : public oatpp::web::server::api::ApiController { private: static constexpr const char* TAG = "test::web::app::ControllerWithErrorHandler"; public: explicit ControllerWithErrorHandler(const std::shared_ptr<ObjectMapper>& objectMapper) : oatpp::web::server::api::ApiController(objectMapper) { setErrorHandler(CustomErrorHandler::createShared()); } public: static std::shared_ptr<ControllerWithErrorHandler> createShared(const std::shared_ptr<ObjectMapper>& objectMapper = OATPP_GET_COMPONENT(std::shared_ptr<ObjectMapper>)){ return std::make_shared<ControllerWithErrorHandler>(objectMapper); } #include OATPP_CODEGEN_BEGIN(ApiController) ENDPOINT("GET", "test/errorhandling", errorCaught, REQUEST(std::shared_ptr<IncomingRequest>, request)) { throw std::runtime_error("Controller With Errors!"); } #include OATPP_CODEGEN_END(ApiController) }; }}}} #endif /* oatpp_test_web_app_ControllerWithErrorHandler_hpp */
vincent-in-black-sesame/oat
test/oatpp/web/app/ControllerWithErrorHandler.hpp
C++
apache-2.0
3,517
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_web_app_ControllerWithInterceptors_hpp #define oatpp_test_web_app_ControllerWithInterceptors_hpp #include "oatpp/web/server/api/ApiController.hpp" #include "oatpp/parser/json/mapping/ObjectMapper.hpp" #include "oatpp/core/utils/ConversionUtils.hpp" #include "oatpp/core/macro/codegen.hpp" #include "oatpp/core/macro/component.hpp" #include <sstream> namespace oatpp { namespace test { namespace web { namespace app { namespace multipart = oatpp::web::mime::multipart; class ControllerWithInterceptors : public oatpp::web::server::api::ApiController { private: static constexpr const char* TAG = "test::web::app::ControllerWithInterceptors"; public: ControllerWithInterceptors(const std::shared_ptr<ObjectMapper>& objectMapper) : oatpp::web::server::api::ApiController(objectMapper) {} public: static std::shared_ptr<ControllerWithInterceptors> createShared(const std::shared_ptr<ObjectMapper>& objectMapper = OATPP_GET_COMPONENT(std::shared_ptr<ObjectMapper>)){ return std::make_shared<ControllerWithInterceptors>(objectMapper); } #include OATPP_CODEGEN_BEGIN(ApiController) ENDPOINT_INTERCEPTOR(interceptor, inter1) { /* assert order of interception */ OATPP_ASSERT(request->getHeader("header-in-inter2") == "inter2"); OATPP_ASSERT(request->getHeader("header-in-inter3") == "inter3"); /********************************/ request->putHeader("header-in-inter1", "inter1"); auto response = (this->*intercepted)(request); response->putHeader("header-out-inter1", "inter1"); return response; } ENDPOINT_INTERCEPTOR(interceptor, inter2) { /* assert order of interception */ OATPP_ASSERT(request->getHeader("header-in-inter3") == "inter3"); /********************************/ request->putHeader("header-in-inter2", "inter2"); auto response = (this->*intercepted)(request); response->putHeader("header-out-inter2", "inter2"); return response; } ENDPOINT_INTERCEPTOR(interceptor, inter3) { request->putHeader("header-in-inter3", "inter3"); auto response = (this->*intercepted)(request); response->putHeader("header-out-inter3", "inter3"); return response; } ENDPOINT_INTERCEPTOR(interceptor, replacer) { auto response = (this->*intercepted)(request); response->putOrReplaceHeader("to-be-replaced", "replaced_value"); return response; } ENDPOINT_INTERCEPTOR(interceptor, asserter) { auto response = (this->*intercepted)(request); OATPP_ASSERT(response->getHeader("header-out-inter1") == "inter1"); OATPP_ASSERT(response->getHeader("header-out-inter2") == "inter2"); OATPP_ASSERT(response->getHeader("header-out-inter3") == "inter3"); return response; } ENDPOINT("GET", "test/interceptors", interceptor, REQUEST(std::shared_ptr<IncomingRequest>, request)) { OATPP_ASSERT(request->getHeader("header-in-inter1") == "inter1"); OATPP_ASSERT(request->getHeader("header-in-inter2") == "inter2"); OATPP_ASSERT(request->getHeader("header-in-inter3") == "inter3"); auto response = createResponse(Status::CODE_200, "Hello World!!!"); response->putHeader("to-be-replaced", "original_value"); return response; } #include OATPP_CODEGEN_END(ApiController) }; }}}} #endif /* oatpp_test_web_app_ControllerWithInterceptors_hpp */
vincent-in-black-sesame/oat
test/oatpp/web/app/ControllerWithInterceptors.hpp
C++
apache-2.0
4,327
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_web_app_ControllerWithInterceptorsAsync_hpp #define oatpp_test_web_app_ControllerWithInterceptorsAsync_hpp #include "oatpp/web/server/api/ApiController.hpp" #include "oatpp/parser/json/mapping/ObjectMapper.hpp" #include "oatpp/core/utils/ConversionUtils.hpp" #include "oatpp/core/macro/codegen.hpp" #include "oatpp/core/macro/component.hpp" #include <sstream> namespace oatpp { namespace test { namespace web { namespace app { namespace multipart = oatpp::web::mime::multipart; class ControllerWithInterceptorsAsync : public oatpp::web::server::api::ApiController { private: static constexpr const char* TAG = "test::web::app::ControllerWithInterceptorsAsync"; public: ControllerWithInterceptorsAsync(const std::shared_ptr<ObjectMapper>& objectMapper) : oatpp::web::server::api::ApiController(objectMapper) {} public: static std::shared_ptr<ControllerWithInterceptorsAsync> createShared(const std::shared_ptr<ObjectMapper>& objectMapper = OATPP_GET_COMPONENT(std::shared_ptr<ObjectMapper>)){ return std::make_shared<ControllerWithInterceptorsAsync>(objectMapper); } #include OATPP_CODEGEN_BEGIN(ApiController) ENDPOINT_INTERCEPTOR_ASYNC(Interceptor, inter1) { /* assert order of interception */ OATPP_ASSERT(request->getHeader("header-in-inter2") == "inter2"); OATPP_ASSERT(request->getHeader("header-in-inter3") == "inter3"); /********************************/ request->putHeader("header-in-inter1", "inter1"); return (this->*intercepted)(request); } ENDPOINT_INTERCEPTOR_ASYNC(Interceptor, inter2) { /* assert order of interception */ OATPP_ASSERT(request->getHeader("header-in-inter3") == "inter3"); /********************************/ request->putHeader("header-in-inter2", "inter2"); return (this->*intercepted)(request); } ENDPOINT_INTERCEPTOR_ASYNC(Interceptor, inter3) { class IterceptorCoroutine : public oatpp::async::CoroutineWithResult<IterceptorCoroutine, const std::shared_ptr<OutgoingResponse>&> { private: ControllerWithInterceptorsAsync* m_this; Handler<ControllerWithInterceptorsAsync>::MethodAsync m_intercepted; std::shared_ptr<IncomingRequest> m_request; public: IterceptorCoroutine(ControllerWithInterceptorsAsync* _this, const Handler<ControllerWithInterceptorsAsync>::MethodAsync& intercepted, const std::shared_ptr<IncomingRequest>& request) : m_this(_this) , m_intercepted(intercepted) , m_request(request) {} oatpp::async::Action act() override { m_request->putHeader("header-in-inter3", "inter3"); return (m_this->*m_intercepted)(m_request).callbackTo(&IterceptorCoroutine::onResponse); } oatpp::async::Action onResponse(const std::shared_ptr<OutgoingResponse>& response) { response->putHeader("header-out-inter3", "inter3"); return this->_return(response); } }; return IterceptorCoroutine::startForResult(this, intercepted, request); } ENDPOINT_INTERCEPTOR_ASYNC(Interceptor, asserter) { class IterceptorCoroutine : public oatpp::async::CoroutineWithResult<IterceptorCoroutine, const std::shared_ptr<OutgoingResponse>&> { private: ControllerWithInterceptorsAsync* m_this; Handler<ControllerWithInterceptorsAsync>::MethodAsync m_intercepted; std::shared_ptr<IncomingRequest> m_request; public: IterceptorCoroutine(ControllerWithInterceptorsAsync* _this, const Handler<ControllerWithInterceptorsAsync>::MethodAsync& intercepted, const std::shared_ptr<IncomingRequest>& request) : m_this(_this) , m_intercepted(intercepted) , m_request(request) {} oatpp::async::Action act() override { return (m_this->*m_intercepted)(m_request).callbackTo(&IterceptorCoroutine::onResponse); } oatpp::async::Action onResponse(const std::shared_ptr<OutgoingResponse>& response) { OATPP_ASSERT(response->getHeader("header-out-inter3") == "inter3"); return this->_return(response); } }; return IterceptorCoroutine::startForResult(this, intercepted, request); } ENDPOINT_ASYNC("GET", "test/interceptors", Interceptor) { ENDPOINT_ASYNC_INIT(Interceptor) Action act() { OATPP_ASSERT(request->getHeader("header-in-inter1") == "inter1"); OATPP_ASSERT(request->getHeader("header-in-inter2") == "inter2"); OATPP_ASSERT(request->getHeader("header-in-inter3") == "inter3"); return _return(controller->createResponse(Status::CODE_200, "Hello World Async!!!")); } }; #include OATPP_CODEGEN_END(ApiController) }; }}}} #endif /* oatpp_test_web_app_ControllerWithInterceptorsAsync_hpp */
vincent-in-black-sesame/oat
test/oatpp/web/app/ControllerWithInterceptorsAsync.hpp
C++
apache-2.0
5,805
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_web_app_DTOs_hpp #define oatpp_test_web_app_DTOs_hpp #include "oatpp/core/macro/codegen.hpp" #include "oatpp/core/Types.hpp" namespace oatpp { namespace test { namespace web { namespace app { #include OATPP_CODEGEN_BEGIN(DTO) class TestDto : public oatpp::DTO { DTO_INIT(TestDto, DTO) DTO_FIELD(String, testValue); DTO_FIELD(Int32, testValueInt); DTO_FIELD(Fields<String>, testMap); }; ENUM(AllowedPathParams, v_int32, VALUE(HELLO, 100, "hello"), VALUE(WORLD, 200, "world") ) #include OATPP_CODEGEN_END(DTO) }}}} #endif /* oatpp_test_web_app_DTOs_hpp */
vincent-in-black-sesame/oat
test/oatpp/web/app/DTOs.hpp
C++
apache-2.0
1,600
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>, * Matthias Haselmaier <mhaselmaier@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "StatefulParserTest.hpp" #include "oatpp/web/mime/multipart/PartList.hpp" #include "oatpp/web/mime/multipart/InMemoryDataProvider.hpp" #include "oatpp/web/mime/multipart/Reader.hpp" #include "oatpp/core/data/stream/BufferStream.hpp" #include <unordered_map> namespace oatpp { namespace test { namespace web { namespace mime { namespace multipart { namespace { typedef oatpp::web::mime::multipart::Part Part; static const char* TEST_DATA_1 = "--12345\r\n" "Content-Disposition: form-data; name=\"part1\"\r\n" "\r\n" "part1-value\r\n" "--12345\r\n" "Content-Disposition: form-data; name='part2' filename=\"filename.txt\"\r\n" "\r\n" "--part2-file-content-line1\r\n" "--1234part2-file-content-line2\r\n" "--12345\r\n" "Content-Disposition: form-data; name=part3 filename=\"filename.jpg\"\r\n" "\r\n" "part3-file-binary-data\r\n" "--12345\r\n" "Content-Disposition: form-data; name=\"part4\"\r\n" "\r\n" "part4-first-value\r\n" "--12345\r\n" "Content-Disposition: form-data; name=\"part4\"\r\n" "\r\n" "part4-second-value\r\n" "--12345--\r\n" ; void parseStepByStep(const oatpp::String& text, const oatpp::String& boundary, const std::shared_ptr<oatpp::web::mime::multipart::StatefulParser::Listener>& listener, const v_int32 step) { oatpp::web::mime::multipart::StatefulParser parser(boundary, listener, nullptr); oatpp::data::stream::BufferInputStream stream(text.getPtr(), text->data(), text->size()); std::unique_ptr<v_char8[]> buffer(new v_char8[step]); v_io_size size; while((size = stream.readSimple(buffer.get(), step)) != 0) { oatpp::data::buffer::InlineWriteData inlineData(buffer.get(), size); while(inlineData.bytesLeft > 0 && !parser.finished()) { oatpp::async::Action action; parser.parseNext(inlineData, action); } } OATPP_ASSERT(parser.finished()); } void assertPartData(const std::shared_ptr<Part>& part, const oatpp::String& value) { auto payload = part->getPayload(); OATPP_ASSERT(payload) OATPP_ASSERT(payload->getInMemoryData()); OATPP_ASSERT(payload->getInMemoryData() == value); v_int64 bufferSize = 16; std::unique_ptr<v_char8[]> buffer(new v_char8[bufferSize]); oatpp::data::stream::BufferOutputStream stream; oatpp::data::stream::transfer(payload->openInputStream(), &stream, 0, buffer.get(), bufferSize); oatpp::String readData = stream.toString(); OATPP_ASSERT(readData == payload->getInMemoryData()); } } void StatefulParserTest::onRun() { oatpp::String text = TEST_DATA_1; for(v_int32 i = 1; i < text->size(); i++) { oatpp::web::mime::multipart::PartList multipart("12345"); auto listener = std::make_shared<oatpp::web::mime::multipart::PartsParser>(&multipart); listener->setDefaultPartReader(oatpp::web::mime::multipart::createInMemoryPartReader(128)); parseStepByStep(text, "12345", listener, i); if(multipart.count() != 5) { OATPP_LOGD(TAG, "TEST_DATA_1 itearation %d", i); } OATPP_ASSERT(multipart.count() == 5); auto part1 = multipart.getNamedPart("part1"); auto part2 = multipart.getNamedPart("part2"); auto part3 = multipart.getNamedPart("part3"); auto part4 = multipart.getNamedPart("part4"); auto part4List = multipart.getNamedParts("part4"); OATPP_ASSERT(part1); OATPP_ASSERT(part2); OATPP_ASSERT(part3); OATPP_ASSERT(part4); OATPP_ASSERT(part4List.size() == 2); OATPP_ASSERT(part4List.front().get() == part4.get()); OATPP_ASSERT(part1->getFilename().get() == nullptr); OATPP_ASSERT(part2->getFilename() == "filename.txt"); OATPP_ASSERT(part3->getFilename() == "filename.jpg"); assertPartData(part1, "part1-value"); assertPartData(part2, "--part2-file-content-line1\r\n--1234part2-file-content-line2"); assertPartData(part3, "part3-file-binary-data"); assertPartData(part4List.front(), "part4-first-value"); assertPartData(part4List.back(), "part4-second-value"); } } }}}}}
vincent-in-black-sesame/oat
test/oatpp/web/mime/multipart/StatefulParserTest.cpp
C++
apache-2.0
5,193
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_web_mime_multipart_StatefulParserTest_hpp #define oatpp_test_web_mime_multipart_StatefulParserTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace web { namespace mime { namespace multipart { class StatefulParserTest : public UnitTest { public: StatefulParserTest():UnitTest("TEST[web::mime::multipart::StatefulParserTest]"){} void onRun() override; }; }}}}} #endif /* oatpp_test_web_mime_multipart_StatefulParserTest_hpp */
vincent-in-black-sesame/oat
test/oatpp/web/mime/multipart/StatefulParserTest.hpp
C++
apache-2.0
1,487
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "ChunkedTest.hpp" #include "oatpp/web/protocol/http/encoding/Chunked.hpp" #include "oatpp/core/data/stream/BufferStream.hpp" namespace oatpp { namespace test { namespace web { namespace protocol { namespace http { namespace encoding { void ChunkedTest::onRun() { oatpp::String data = "Hello World!!!"; oatpp::String encoded; oatpp::String decoded; { // Empty string oatpp::data::stream::BufferInputStream inStream(oatpp::String("")); oatpp::data::stream::BufferOutputStream outStream; oatpp::web::protocol::http::encoding::EncoderChunked encoder; const v_int32 bufferSize = 5; v_char8 buffer[bufferSize]; auto count = oatpp::data::stream::transfer(&inStream, &outStream, 0, buffer, bufferSize, &encoder); encoded = outStream.toString(); OATPP_ASSERT(count == 0); OATPP_ASSERT(encoded == "0\r\n\r\n"); } { // Empty string oatpp::data::stream::BufferInputStream inStream(encoded); oatpp::data::stream::BufferOutputStream outStream; oatpp::web::protocol::http::encoding::DecoderChunked decoder; const v_int32 bufferSize = 5; v_char8 buffer[bufferSize]; auto count = oatpp::data::stream::transfer(&inStream, &outStream, 0, buffer, bufferSize, &decoder); decoded = outStream.toString(); OATPP_ASSERT(count == encoded->size()); OATPP_ASSERT(decoded == ""); } { oatpp::data::stream::BufferInputStream inStream(data); oatpp::data::stream::BufferOutputStream outStream; oatpp::web::protocol::http::encoding::EncoderChunked encoder; const v_int32 bufferSize = 5; v_char8 buffer[bufferSize]; auto count = oatpp::data::stream::transfer(&inStream, &outStream, 0, buffer, bufferSize, &encoder); encoded = outStream.toString(); OATPP_ASSERT(count == data->size()); OATPP_ASSERT(encoded == "5\r\nHello\r\n5\r\n Worl\r\n4\r\nd!!!\r\n0\r\n\r\n"); } { oatpp::data::stream::BufferInputStream inStream(encoded); oatpp::data::stream::BufferOutputStream outStream; oatpp::web::protocol::http::encoding::DecoderChunked decoder; const v_int32 bufferSize = 5; v_char8 buffer[bufferSize]; auto count = oatpp::data::stream::transfer(&inStream, &outStream, 0, buffer, bufferSize, &decoder); decoded = outStream.toString(); OATPP_ASSERT(count == encoded->size()); OATPP_LOGD(TAG, "decoded='%s'", decoded->c_str()); OATPP_ASSERT(decoded == data); } { oatpp::data::stream::BufferInputStream inStream(data); oatpp::data::stream::BufferOutputStream outStream; oatpp::web::protocol::http::encoding::EncoderChunked encoder; oatpp::web::protocol::http::encoding::DecoderChunked decoder; oatpp::data::buffer::ProcessingPipeline pipeline({ &encoder, &decoder }); const v_int32 bufferSize = 5; v_char8 buffer[bufferSize]; auto count = oatpp::data::stream::transfer(&inStream, &outStream, 0, buffer, bufferSize, &pipeline); auto result = outStream.toString(); OATPP_ASSERT(count == data->size()); OATPP_LOGD(TAG, "result='%s'", result->c_str()); OATPP_ASSERT(result == data); } } }}}}}}
vincent-in-black-sesame/oat
test/oatpp/web/protocol/http/encoding/ChunkedTest.cpp
C++
apache-2.0
4,117
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_web_protocol_http_encoding_ChunkedTest_hpp #define oatpp_test_web_protocol_http_encoding_ChunkedTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace web { namespace protocol { namespace http { namespace encoding { class ChunkedTest : public UnitTest { public: ChunkedTest():UnitTest("TEST[web::protocol::http::encoding::ChunkedTest]"){} void onRun() override; }; }}}}}} #endif /* oatpp_test_web_protocol_http_encoding_ChunkedTest_hpp */
vincent-in-black-sesame/oat
test/oatpp/web/protocol/http/encoding/ChunkedTest.hpp
C++
apache-2.0
1,499
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "HttpRouterTest.hpp" #include "oatpp/web/server/HttpRouter.hpp" #include "oatpp/core/Types.hpp" namespace oatpp { namespace test { namespace web { namespace server { namespace { typedef oatpp::web::server::HttpRouterTemplate<v_int32> NumRouter; } void HttpRouterTest::onRun() { NumRouter router; router.route("GET", "ints/1", 1); router.route("GET", "ints/2", 2); router.route("GET", "ints/all/{value}", -1); router.route("POST", "ints/1", 1); router.route("POST", "ints/2", 2); router.route("POST", "ints/{value}", 3); router.route("POST", "ints/*", 4); router.route("POST", "*", -100); { OATPP_LOGI(TAG, "Case 1"); auto r = router.getRoute("GET", "ints/1"); OATPP_ASSERT(r.isValid()); OATPP_ASSERT(r); OATPP_ASSERT(r.getEndpoint() == 1); } { OATPP_LOGI(TAG, "Case 2"); auto r = router.getRoute("GET", "/ints/1"); OATPP_ASSERT(r.isValid()); OATPP_ASSERT(r); OATPP_ASSERT(r.getEndpoint() == 1); } { OATPP_LOGI(TAG, "Case 3"); auto r = router.getRoute("GET", "ints/1//"); OATPP_ASSERT(r.isValid()); OATPP_ASSERT(r); OATPP_ASSERT(r.getEndpoint() == 1); } { OATPP_LOGI(TAG, "Case 4"); auto r = router.getRoute("GET", "//ints///1//"); OATPP_ASSERT(r.isValid()); OATPP_ASSERT(r); OATPP_ASSERT(r.getEndpoint() == 1); } { OATPP_LOGI(TAG, "Case 5"); auto r = router.getRoute("GET", "ints/1/*"); OATPP_ASSERT(r.isValid() == false); OATPP_ASSERT(!r); } { OATPP_LOGI(TAG, "Case 6"); auto r = router.getRoute("GET", "ints/2"); OATPP_ASSERT(r.isValid()); OATPP_ASSERT(r); OATPP_ASSERT(r.getEndpoint() == 2); } { OATPP_LOGI(TAG, "Case 7"); auto r = router.getRoute("GET", "ints/all/10"); OATPP_ASSERT(r.isValid()); OATPP_ASSERT(r); OATPP_ASSERT(r.getEndpoint() == -1); OATPP_ASSERT(r.getMatchMap().getVariables().size() == 1); OATPP_ASSERT(r.getMatchMap().getVariable("value") == "10"); } { OATPP_LOGI(TAG, "Case 8"); auto r = router.getRoute("GET", "//ints//all//10//"); OATPP_ASSERT(r.isValid()); OATPP_ASSERT(r); OATPP_ASSERT(r.getEndpoint() == -1); OATPP_ASSERT(r.getMatchMap().getVariables().size() == 1); OATPP_ASSERT(r.getMatchMap().getVariable("value") == "10"); } { OATPP_LOGI(TAG, "Case 9"); auto r = router.getRoute("GET", "//ints//all//10//*"); OATPP_ASSERT(r.isValid() == false); OATPP_ASSERT(!r); } { OATPP_LOGI(TAG, "Case 10"); auto r = router.getRoute("POST", "ints/1"); OATPP_ASSERT(r.isValid()); OATPP_ASSERT(r); OATPP_ASSERT(r.getEndpoint() == 1); } { OATPP_LOGI(TAG, "Case 11"); auto r = router.getRoute("POST", "ints/2"); OATPP_ASSERT(r.isValid()); OATPP_ASSERT(r); OATPP_ASSERT(r.getEndpoint() == 2); } { OATPP_LOGI(TAG, "Case 12"); auto r = router.getRoute("POST", "ints/3"); OATPP_ASSERT(r.isValid()); OATPP_ASSERT(r); OATPP_ASSERT(r.getEndpoint() == 3); OATPP_ASSERT(r.getMatchMap().getVariables().size() == 1); OATPP_ASSERT(r.getMatchMap().getVariable("value") == "3"); } { OATPP_LOGI(TAG, "Case 13"); auto r = router.getRoute("POST", "ints/3/10"); OATPP_ASSERT(r.isValid()); OATPP_ASSERT(r); OATPP_ASSERT(r.getEndpoint() == 4); OATPP_ASSERT(r.getMatchMap().getTail() == "3/10"); } { OATPP_LOGI(TAG, "Case 14"); auto r = router.getRoute("POST", "abc"); OATPP_ASSERT(r.isValid()); OATPP_ASSERT(r); OATPP_ASSERT(r.getEndpoint() == -100); OATPP_ASSERT(r.getMatchMap().getTail() == "abc"); } } }}}}
vincent-in-black-sesame/oat
test/oatpp/web/server/HttpRouterTest.cpp
C++
apache-2.0
4,614
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_web_server_HttpRouterTest_hpp #define oatpp_test_web_server_HttpRouterTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace web { namespace server { class HttpRouterTest : public UnitTest { public: HttpRouterTest():UnitTest("TEST[web::server::HttpRouterTest]"){} void onRun() override; }; }}}} #endif /* oatpp_test_web_server_HttpRouterTest_hpp */
vincent-in-black-sesame/oat
test/oatpp/web/server/HttpRouterTest.hpp
C++
apache-2.0
1,409
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "ServerStopTest.hpp" #include "oatpp/web/client/HttpRequestExecutor.hpp" #include "oatpp/web/server/AsyncHttpConnectionHandler.hpp" #include "oatpp/web/server/HttpConnectionHandler.hpp" #include "oatpp/web/protocol/http/outgoing/StreamingBody.hpp" #include "oatpp/network/virtual_/server/ConnectionProvider.hpp" #include "oatpp/network/virtual_/client/ConnectionProvider.hpp" #include "oatpp/network/tcp/server/ConnectionProvider.hpp" #include "oatpp/network/tcp/client/ConnectionProvider.hpp" #include "oatpp/network/Server.hpp" namespace oatpp { namespace test { namespace web { namespace server { namespace { class ReadCallback : public oatpp::data::stream::ReadCallback { public: v_io_size read(void *buffer, v_buff_size count, async::Action &action) override { std::this_thread::sleep_for(std::chrono::milliseconds(100)); char *data = (char *) buffer; data[0] = 'A'; return 1; } }; class AsyncReadCallback : public oatpp::data::stream::ReadCallback { private: bool wait = false; public: v_io_size read(void *buffer, v_buff_size count, async::Action &action) override { wait = !wait; if(wait) { action = oatpp::async::Action::createWaitRepeatAction( oatpp::base::Environment::getMicroTickCount() + 100 * 1000); return oatpp::IOError::RETRY_READ; } char *data = (char *) buffer; data[0] = 'A'; return 1; } }; class StreamingHandler : public oatpp::web::server::HttpRequestHandler { public: std::shared_ptr<OutgoingResponse> handle(const std::shared_ptr<IncomingRequest> &request) override { auto body = std::make_shared<oatpp::web::protocol::http::outgoing::StreamingBody> (std::make_shared<ReadCallback>()); return OutgoingResponse::createShared(Status::CODE_200, body); } }; class AsyncStreamingHandler : public oatpp::web::server::HttpRequestHandler { public: oatpp::async::CoroutineStarterForResult<const std::shared_ptr<OutgoingResponse> &> handleAsync(const std::shared_ptr<IncomingRequest> &request) { class StreamCoroutine : public oatpp::async::CoroutineWithResult<StreamCoroutine, const std::shared_ptr<OutgoingResponse> &> { public: Action act() override { auto body = std::make_shared<oatpp::web::protocol::http::outgoing::StreamingBody> (std::make_shared<AsyncReadCallback>()); return _return(OutgoingResponse::createShared(Status::CODE_200, body)); } }; return StreamCoroutine::startForResult(); } }; std::shared_ptr<oatpp::network::Server> runServer(const std::shared_ptr<oatpp::network::ServerConnectionProvider>& connectionProvider) { auto router = oatpp::web::server::HttpRouter::createShared(); router->route("GET", "/stream", std::make_shared<StreamingHandler>()); auto connectionHandler = oatpp::web::server::HttpConnectionHandler::createShared(router); auto server = std::make_shared<oatpp::network::Server>(connectionProvider, connectionHandler); std::thread t([server, connectionHandler] { server->run(); OATPP_LOGD("TEST", "server stopped"); connectionHandler->stop(); OATPP_LOGD("TEST", "connectionHandler stopped"); }); t.detach(); return server; } std::shared_ptr<oatpp::network::Server> runAsyncServer(const std::shared_ptr<oatpp::network::ServerConnectionProvider>& connectionProvider) { auto router = oatpp::web::server::HttpRouter::createShared(); router->route("GET", "/stream", std::make_shared<AsyncStreamingHandler>()); auto executor = std::make_shared<oatpp::async::Executor>(); auto connectionHandler = oatpp::web::server::AsyncHttpConnectionHandler::createShared(router, executor); auto server = std::make_shared<oatpp::network::Server>(connectionProvider, connectionHandler); std::thread t([server, connectionHandler, executor] { server->run(); OATPP_LOGD("TEST_ASYNC", "server stopped"); connectionHandler->stop(); OATPP_LOGD("TEST_ASYNC", "connectionHandler stopped"); executor->waitTasksFinished(); executor->stop(); executor->join(); OATPP_LOGD("TEST_ASYNC", "executor stopped"); }); t.detach(); return server; } void runClient(const std::shared_ptr<oatpp::network::ClientConnectionProvider>& connectionProvider) { oatpp::web::client::HttpRequestExecutor executor(connectionProvider); auto response = executor.execute("GET", "/stream", oatpp::web::protocol::http::Headers({}), nullptr, nullptr); OATPP_ASSERT(response->getStatusCode() == 200); auto data = response->readBodyToString(); OATPP_ASSERT(data) OATPP_LOGD("TEST", "data->size() == %d", data->size()) } } void ServerStopTest::onRun() { std::shared_ptr<oatpp::network::ServerConnectionProvider> serverConnectionProvider; std::shared_ptr<oatpp::network::ClientConnectionProvider> clientConnectionProvider; if(m_port == 0) { auto _interface = oatpp::network::virtual_::Interface::obtainShared("virtualhost"); serverConnectionProvider = oatpp::network::virtual_::server::ConnectionProvider::createShared(_interface); clientConnectionProvider = oatpp::network::virtual_::client::ConnectionProvider::createShared(_interface); } else { serverConnectionProvider = oatpp::network::tcp::server::ConnectionProvider::createShared({"localhost", 8000}); clientConnectionProvider = oatpp::network::tcp::client::ConnectionProvider::createShared({"localhost", 8000}); } { OATPP_LOGD(TAG, "Run Simple API test on host=%s, port=%s", serverConnectionProvider->getProperty("host").toString()->c_str(), serverConnectionProvider->getProperty("port").toString()->c_str()) auto server = runServer(serverConnectionProvider); std::list<std::thread> threads; for(v_int32 i = 0; i < 100; i ++) { threads.emplace_back(std::thread([clientConnectionProvider]{ runClient(clientConnectionProvider); })); } std::this_thread::sleep_for(std::chrono::seconds(10)); server->stop(); for(auto& t : threads) { t.join(); } /* wait connection handler to stop */ std::this_thread::sleep_for(std::chrono::seconds(5)); OATPP_LOGD(TAG, "DONE"); } { OATPP_LOGD(TAG, "Run Async API test on host=%s, port=%s", serverConnectionProvider->getProperty("host").toString()->c_str(), serverConnectionProvider->getProperty("port").toString()->c_str()) auto server = runAsyncServer(serverConnectionProvider); std::list<std::thread> threads; for(v_int32 i = 0; i < 100; i ++) { threads.emplace_back(std::thread([clientConnectionProvider]{ runClient(clientConnectionProvider); })); } std::this_thread::sleep_for(std::chrono::seconds(10)); server->stop(); for(auto& t : threads) { t.join(); } /* wait connection handler to stop */ std::this_thread::sleep_for(std::chrono::seconds(5)); OATPP_LOGD(TAG, "DONE"); } } }}}}
vincent-in-black-sesame/oat
test/oatpp/web/server/ServerStopTest.cpp
C++
apache-2.0
7,920
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_web_server_ServerStopTest_hpp #define oatpp_test_web_server_ServerStopTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace web { namespace server { class ServerStopTest : public UnitTest { private: v_uint16 m_port; public: ServerStopTest(v_uint16 port) : UnitTest("TEST[web::server::ServerStopTest]") , m_port(port) {} void onRun() override; }; }}}} #endif /* oatpp_test_web_server_ServerStopTest_hpp */
vincent-in-black-sesame/oat
test/oatpp/web/server/ServerStopTest.hpp
C++
apache-2.0
1,479
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "ApiControllerTest.hpp" #include "oatpp/web/server/api/ApiController.hpp" #include "oatpp/core/macro/codegen.hpp" namespace oatpp { namespace test { namespace web { namespace server { namespace api { namespace { class Controller : public oatpp::web::server::api::ApiController { public: Controller(const std::shared_ptr<ObjectMapper>& objectMapper) : oatpp::web::server::api::ApiController(objectMapper) {} public: static std::shared_ptr<Controller> createShared(const std::shared_ptr<ObjectMapper>& objectMapper){ return std::make_shared<Controller>(objectMapper); } #include OATPP_CODEGEN_BEGIN(ApiController) ENDPOINT_INFO(root) { info->summary = "root_summary"; info->addResponse<String>(Status::CODE_200, "text/plain", "test1-success"); info->addResponse<String>(Status::CODE_404, "text/plain"); } ENDPOINT("GET", "/", root) { return createResponse(Status::CODE_200, "test1"); } ENDPOINT_INFO(pathParams) { info->pathParams["param1"].description = "this is param1"; info->queryParams.add<String>("q1").description = "query param"; info->headers.add<String>("X-TEST-HEADER").description = "TEST-HEADER-PARAM"; } ENDPOINT("GET", "path/{param1}/{param2}", pathParams, PATH(String, param1), PATH(String, param2)) { return createResponse(Status::CODE_200, "test2"); } ENDPOINT_INFO(queryParams) { info->queryParams["param1"].description = "this is param1"; } ENDPOINT("GET", "query", queryParams, QUERY(String, param1), QUERY(String, param2)) { return createResponse(Status::CODE_200, "test3"); } ENDPOINT_INFO(noContent) { info->addResponse(Status::CODE_204, "No Content"); } ENDPOINT("GET", "noContent", noContent) { return createResponse(Status::CODE_204); } #include OATPP_CODEGEN_END(ApiController) }; } // methods/fields with "Z__" prefix are for internal use only. // Do not use these methods/fields for user-tests as naming can be changed void ApiControllerTest::onRun() { typedef oatpp::web::protocol::http::Status Status; Controller controller(nullptr); oatpp::data::stream::BufferOutputStream headersOutBuffer; { auto endpoint = controller.Z__ENDPOINT_root; OATPP_ASSERT(endpoint); OATPP_ASSERT(endpoint->info()->summary == "root_summary"); auto r200 = endpoint->info()->responses[Status::CODE_200]; OATPP_ASSERT(r200.contentType == "text/plain"); OATPP_ASSERT(r200.schema == oatpp::String::Class::getType()); OATPP_ASSERT(r200.description == "test1-success"); auto r404 = endpoint->info()->responses[Status::CODE_404]; OATPP_ASSERT(r404.contentType == "text/plain"); OATPP_ASSERT(r404.description == "Not Found"); OATPP_ASSERT(r404.schema == oatpp::String::Class::getType()); auto response = controller.root(); OATPP_ASSERT(response->getStatus().code == 200); oatpp::data::stream::BufferOutputStream stream; response->send(&stream, &headersOutBuffer, nullptr); OATPP_LOGD(TAG, "response:\n---\n%s\n---\n", stream.toString()->c_str()); } { auto endpoint = controller.Z__ENDPOINT_pathParams; OATPP_ASSERT(endpoint); OATPP_ASSERT(!endpoint->info()->summary); OATPP_ASSERT(endpoint->info()->pathParams["param1"].name == "param1"); OATPP_ASSERT(endpoint->info()->pathParams["param1"].description == "this is param1"); OATPP_ASSERT(endpoint->info()->pathParams["param2"].name == "param2"); OATPP_ASSERT(!endpoint->info()->pathParams["param2"].description); OATPP_ASSERT(endpoint->info()->queryParams["q1"].name == "q1"); OATPP_ASSERT(endpoint->info()->queryParams["q1"].description == "query param"); OATPP_ASSERT(endpoint->info()->headers["X-TEST-HEADER"].name == "X-TEST-HEADER"); OATPP_ASSERT(endpoint->info()->headers["X-TEST-HEADER"].description == "TEST-HEADER-PARAM"); auto response = controller.pathParams("p1", "p2"); OATPP_ASSERT(response->getStatus().code == 200); oatpp::data::stream::BufferOutputStream stream; response->send(&stream, &headersOutBuffer, nullptr); OATPP_LOGD(TAG, "response:\n---\n%s\n---\n", stream.toString()->c_str()); } { auto endpoint = controller.Z__ENDPOINT_queryParams; OATPP_ASSERT(endpoint); OATPP_ASSERT(!endpoint->info()->summary); OATPP_ASSERT(endpoint->info()->queryParams["param1"].name == "param1"); OATPP_ASSERT(endpoint->info()->queryParams["param1"].description == "this is param1"); OATPP_ASSERT(endpoint->info()->queryParams["param2"].name == "param2"); OATPP_ASSERT(!endpoint->info()->queryParams["param2"].description); auto response = controller.queryParams("p1", "p2"); OATPP_ASSERT(response->getStatus().code == 200); oatpp::data::stream::BufferOutputStream stream; response->send(&stream, &headersOutBuffer, nullptr); OATPP_LOGD(TAG, "response:\n---\n%s\n---\n", stream.toString()->c_str()); } { auto endpoint = controller.Z__ENDPOINT_noContent; OATPP_ASSERT(endpoint); OATPP_ASSERT(!endpoint->info()->summary); auto r204 = endpoint->info()->responses[Status::CODE_204]; OATPP_ASSERT(!r204.contentType); OATPP_ASSERT(!r204.schema); OATPP_ASSERT(r204.description == "No Content"); auto response = controller.noContent(); OATPP_ASSERT(response->getStatus().code == 204); OATPP_ASSERT(!response->getBody()); oatpp::data::stream::BufferOutputStream stream; response->send(&stream, &headersOutBuffer, nullptr); OATPP_LOGD(TAG, "response:\n---\n%s\n---\n", stream.toString()->c_str()); } } }}}}}
vincent-in-black-sesame/oat
test/oatpp/web/server/api/ApiControllerTest.cpp
C++
apache-2.0
6,598
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_web_server_api_ApiControllerTest_hpp #define oatpp_test_web_server_api_ApiControllerTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace web { namespace server { namespace api { class ApiControllerTest : public UnitTest { public: ApiControllerTest():UnitTest("TEST[web::server::api::ApiControllerTest]"){} void onRun() override; }; }}}}} #endif /* oatpp_test_web_server_api_ApiControllerTest_hpp */
vincent-in-black-sesame/oat
test/oatpp/web/server/api/ApiControllerTest.hpp
C++
apache-2.0
1,461
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * Benedikt-Alexander Mokroß <bam@icognize.de> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "AuthorizationHandlerTest.hpp" #include "oatpp/web/server/handler/AuthorizationHandler.hpp" namespace oatpp { namespace test { namespace web { namespace server { namespace handler { namespace { class MyBasicAuthorizationObject : public oatpp::web::server::handler::AuthorizationObject { public: oatpp::String userId; oatpp::String password; }; class MyBasicAuthorizationHandler : public oatpp::web::server::handler::BasicAuthorizationHandler { public: std::shared_ptr<AuthorizationObject> authorize(const oatpp::String& userId, const oatpp::String& password) { auto authObject = std::make_shared<MyBasicAuthorizationObject>(); authObject->userId = userId; authObject->password = password; return authObject; } }; } void AuthorizationHandlerTest::onRun() { oatpp::String user = "foo"; oatpp::String password = "bar"; oatpp::String header = "Basic Zm9vOmJhcg=="; { MyBasicAuthorizationHandler basicAuthHandler; auto auth = std::static_pointer_cast<MyBasicAuthorizationObject>(basicAuthHandler.handleAuthorization(header)); OATPP_LOGV(TAG, "header=\"%s\" -> user=\"%s\" password=\"%s\"", header->c_str(), auth->userId->c_str(), auth->password->c_str()); OATPP_ASSERT(auth->userId == "foo"); OATPP_ASSERT(auth->password == "bar"); } { oatpp::web::server::handler::BasicAuthorizationHandler defaultBasicAuthHandler; auto auth = std::static_pointer_cast<oatpp::web::server::handler::DefaultBasicAuthorizationObject>(defaultBasicAuthHandler.handleAuthorization(header)); OATPP_LOGV(TAG, "header=\"%s\" -> user=\"%s\" password=\"%s\"", header->c_str(), auth->userId->c_str(), auth->password->c_str()); OATPP_ASSERT(auth->userId == "foo"); OATPP_ASSERT(auth->password == "bar"); } } }}}}}
vincent-in-black-sesame/oat
test/oatpp/web/server/handler/AuthorizationHandlerTest.cpp
C++
apache-2.0
2,849
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * Benedikt-Alexander Mokroß <bam@icognize.de> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_encoding_AuthorizationHandlerTest_hpp #define oatpp_test_encoding_AuthorizationHandlerTest_hpp #include <oatpp/web/server/handler/AuthorizationHandler.hpp> #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace web { namespace server { namespace handler { class AuthorizationHandlerTest : public UnitTest{ public: AuthorizationHandlerTest():UnitTest("TEST[web::server::handler::AuthorizationHandlerTest]"){} void onRun() override; }; }}}}} #endif /* oatpp_test_encoding_Base64Test_hpp */
vincent-in-black-sesame/oat
test/oatpp/web/server/handler/AuthorizationHandlerTest.hpp
C++
apache-2.0
1,610
#!/bin/sh MODULE_NAME="oatpp" MODULE_VERSION="0.19.1" echo "remove include folder: '/usr/local/include/oatpp-$MODULE_VERSION/$MODULE_NAME'" rm -rf "/usr/local/include/oatpp-$MODULE_VERSION/$MODULE_NAME" echo "remove cmake package: '/usr/local/lib/cmake/$MODULE_NAME-$MODULE_VERSION'" rm -rf "/usr/local/lib/cmake/$MODULE_NAME-$MODULE_VERSION" MODULE_LIB_PATH="/usr/local/lib/oatpp-$MODULE_VERSION" echo "remove '$MODULE_LIB_PATH/lib$MODULE_NAME.dylib'" rm "$MODULE_LIB_PATH/lib$MODULE_NAME.dylib" echo "remove '$MODULE_LIB_PATH/lib$MODULE_NAME.so'" rm "$MODULE_LIB_PATH/lib$MODULE_NAME.so" echo "remove '$MODULE_LIB_PATH/lib$MODULE_NAME.a'" rm "$MODULE_LIB_PATH/lib$MODULE_NAME.a"
vincent-in-black-sesame/oat
utility/module-uninstall.sh
Shell
apache-2.0
688
package cn.vin; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; /** * Created by Vincent on 2018/3/26. */ @EnableEurekaServer @SpringBootApplication public class Application { public static void main(String[] args) { System.out.println(11); new SpringApplicationBuilder(Application.class) .web(true).run(args); int i = 2; int j = 3; System.out.println(90000); } }
vincentjava/test
src/main/java/cn/vin/Application.java
Java
unknown
594
package com.boot.common; public interface DubboService { String getInfo (String param) ; UserEntity getUserInfo (UserEntity userEntity) ; String timeOut (Integer time) ; }
vincentjava/middle-ware-parent
ware-dubbo-parent/block-dubbo-common/src/main/java/com/boot/common/DubboService.java
Java
unknown
187
package com.boot.common; import java.io.Serializable; public class UserEntity implements Serializable { private Integer id ; private String userName ; @Override public String toString() { return "UserEntity{id=" + id +", userName='" + userName + "}"; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } }
vincentjava/middle-ware-parent
ware-dubbo-parent/block-dubbo-common/src/main/java/com/boot/common/UserEntity.java
Java
unknown
559
package com.boot.common; public interface VersionService { String getVersion () ; }
vincentjava/middle-ware-parent
ware-dubbo-parent/block-dubbo-common/src/main/java/com/boot/common/VersionService.java
Java
unknown
89
package com.boot.consume; import com.alibaba.dubbo.config.spring.context.annotation.EnableDubbo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @EnableDubbo @SpringBootApplication public class ConsumeApplication { public static void main(String[] args) { SpringApplication.run(ConsumeApplication.class,args) ; } }
vincentjava/middle-ware-parent
ware-dubbo-parent/block-dubbo-consume/src/main/java/com/boot/consume/ConsumeApplication.java
Java
unknown
405
package com.boot.consume.controller; import com.boot.common.UserEntity; import com.boot.consume.service.ConsumeService; import com.boot.consume.service.VersionServiceImpl; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; /* http://localhost:7008/getParam 响应参数:[Hello,Cicada] http://localhost:7008/getUserInfo 响应参数:{"id":1,"userName":"知了"} */ @RestController public class DubboController { @Resource private ConsumeService consumeService ; @Resource private VersionServiceImpl versionService1 ; @Resource private VersionServiceImpl versionService2 ; @RequestMapping("/getParam") public String getParam (){ return consumeService.getInfo("知了...") ; } @RequestMapping("/getUserInfo") public UserEntity getUserInfo (){ UserEntity userEntity = new UserEntity() ; userEntity.setId(1); userEntity.setUserName("知了"); return consumeService.getUserInfo(userEntity) ; } /** * 抛出超时异常 * com.alibaba.dubbo.remoting.TimeoutException */ @RequestMapping("/timeOut") public String timeOut (){ return consumeService.timeOut(2000) ; } /** * 测试接口版本 * 启动日志 * <dubbo:reference object="com.alibaba.dubbo.common.bytecode.proxy1@3ad65" * singleton="true" * interface="com.boot.common.VersionService" * uniqueServiceName="com.boot.common.VersionService:1.0.0" * generic="false" version="1.0.0" * id="com.boot.common.VersionService" /> has been built. */ @RequestMapping("/getVersion1") public String getVersion1 (){ return versionService1.getVersion() ; } @RequestMapping("/getVersion2") public String getVersion2 (){ return versionService2.version2() ; } }
vincentjava/middle-ware-parent
ware-dubbo-parent/block-dubbo-consume/src/main/java/com/boot/consume/controller/DubboController.java
Java
unknown
1,932
package com.boot.consume.service; import com.alibaba.dubbo.config.annotation.Reference; import com.boot.common.DubboService; import com.boot.common.UserEntity; import org.springframework.stereotype.Service; @Service public class ConsumeService implements DubboService { @Reference private DubboService dubboService ; @Override public String getInfo(String param) { return dubboService.getInfo(param); } @Override public UserEntity getUserInfo(UserEntity userEntity) { return dubboService.getUserInfo(userEntity); } @Override public String timeOut(Integer time) { return dubboService.timeOut(time); } }
vincentjava/middle-ware-parent
ware-dubbo-parent/block-dubbo-consume/src/main/java/com/boot/consume/service/ConsumeService.java
Java
unknown
676
package com.boot.consume.service; import com.alibaba.dubbo.config.annotation.Reference; import com.boot.common.VersionService; import org.springframework.stereotype.Service; @Service public class VersionServiceImpl implements VersionService { @Reference(version = "1.0.0") private VersionService versionService1 ; @Reference(version = "2.0.0") private VersionService versionService2 ; @Override public String getVersion() { return versionService1.getVersion(); } public String version2 (){ return versionService2.getVersion() ; } }
vincentjava/middle-ware-parent
ware-dubbo-parent/block-dubbo-consume/src/main/java/com/boot/consume/service/VersionServiceImpl.java
Java
unknown
590
package com.boot.consume; import com.alibaba.dubbo.config.spring.context.annotation.EnableDubbo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /* [zk: localhost:2181(CONNECTED) 0] ls / [dubbo, zookeeper] [zk: localhost:2181(CONNECTED) 1] ls /dubbo [com.boot.common.DubboService] [zk: localhost:2181(CONNECTED) 2] */ @EnableDubbo @SpringBootApplication public class ProviderApplication { public static void main(String[] args) { SpringApplication.run(ProviderApplication.class,args) ; } }
vincentjava/middle-ware-parent
ware-dubbo-parent/block-dubbo-provider/src/main/java/com/boot/consume/ProviderApplication.java
Java
unknown
580
package com.boot.consume.service; import com.boot.common.DubboService; import com.alibaba.dubbo.config.annotation.Service; import com.boot.common.UserEntity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; /* * 注意这里的注解 * com.alibaba.dubbo.config.annotation.Service */ @Service(timeout = 2000) @Component public class DubboServiceImpl implements DubboService { private static Logger LOGGER = LoggerFactory.getLogger(DubboServiceImpl.class) ; @Override public String getInfo(String param) { LOGGER.info("字符参数:{}",param); return "[Hello,Cicada]"; } @Override public UserEntity getUserInfo(UserEntity userEntity) { LOGGER.info("实体类参数:{}",userEntity); return userEntity; } @Override public String timeOut(Integer time) { LOGGER.info("超时测试:{}",time); try{ Thread.sleep(3000); } catch (Exception e){ e.printStackTrace(); return "超时了..." ; } return "SUCCESS"; } }
vincentjava/middle-ware-parent
ware-dubbo-parent/block-dubbo-provider/src/main/java/com/boot/consume/service/DubboServiceImpl.java
Java
unknown
1,122
package com.boot.consume.service; import com.alibaba.dubbo.config.annotation.Service; import com.boot.common.VersionService; import org.springframework.stereotype.Component; @Service(version = "1.0.0") @Component public class VersionOneImpl implements VersionService { @Override public String getVersion() { return "{当前版本:1.0.0}"; } }
vincentjava/middle-ware-parent
ware-dubbo-parent/block-dubbo-provider/src/main/java/com/boot/consume/service/VersionOneImpl.java
Java
unknown
367
package com.boot.consume.service; import com.alibaba.dubbo.config.annotation.Service; import com.boot.common.VersionService; import org.springframework.stereotype.Component; @Service(version = "2.0.0") @Component public class VersionTwoImpl implements VersionService { @Override public String getVersion() { return "{当前版本:2.0.0}"; } }
vincentjava/middle-ware-parent
ware-dubbo-parent/block-dubbo-provider/src/main/java/com/boot/consume/service/VersionTwoImpl.java
Java
unknown
367
package com.elastic.search; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ElasticApplication { public static void main(String[] args) { SpringApplication.run(ElasticApplication.class,args) ; } }
vincentjava/middle-ware-parent
ware-elastic-search/src/main/java/com/elastic/search/ElasticApplication.java
Java
unknown
323
package com.elastic.search.controller; import com.elastic.search.model.RequestLog; import com.elastic.search.service.RequestLogService; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import java.util.Optional; @RestController public class RequestLogController { @Resource private RequestLogService requestLogService ; /** * 数据入库 Elastic */ @RequestMapping("/insert") public String insert (){ return requestLogService.esInsert(10) ; } /** * 查询全部 Elastic */ @RequestMapping("/findAll") public Iterable<RequestLog> findAll (){ return requestLogService.esFindAll() ; } /** * 根据ID修改 * ID:1560406811693 */ @RequestMapping("/updateById/{id}") public String updateById (@PathVariable Long id){ RequestLog requestLog = new RequestLog() ; requestLog.setId(id); requestLog.setUserName("updateName"); return requestLogService.esUpdateById(requestLog) ; } /** * 根据ID查询 */ @RequestMapping("/selectById/{id}") public RequestLog selectById (@PathVariable Long id){ Optional<RequestLog> requestLog = requestLogService.esSelectById(id) ; return requestLog.get() ; } /** * 根据指定条件排序 */ @RequestMapping("/selectOrder") public Iterable<RequestLog> selectOrder (){ return requestLogService.esFindOrder() ; } /** * 多条件排序 */ @RequestMapping("/selectOrders") public Iterable<RequestLog> selectOrders (){ return requestLogService.esFindOrders() ; } /** * 多条件 + 范围 搜索 */ @RequestMapping("/search") public Iterable<RequestLog> search (){ return requestLogService.search() ; } /** * 分页查询 */ public void findPage (){ } }
vincentjava/middle-ware-parent
ware-elastic-search/src/main/java/com/elastic/search/controller/RequestLogController.java
Java
unknown
2,061
package com.elastic.search.model; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; /** * 点开 Document 可以看到配置内容 * 加上了@Document注解之后,默认情况下这个实体中所有的属性都会被建立索引、并且分词。 * indexName索引名称 理解为数据库名 限定小写 * type 理解为数据库的表名称 * shards = 5 默认分区数 * replicas = 1 每个分区默认的备份数 * refreshInterval = "1s" 刷新间隔 * indexStoreType = "fs" 索引文件存储类型 */ @Document(indexName = "requestlogindex",type = "requestlog") public class RequestLog { //Id注解Elasticsearch里相应于该列就是主键,查询时可以使用主键查询 @Id private Long id; private String orderNo; private String userId; private String userName; private String createTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getOrderNo() { return orderNo; } public void setOrderNo(String orderNo) { this.orderNo = orderNo == null ? null : orderNo.trim(); } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId == null ? null : userId.trim(); } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName == null ? null : userName.trim(); } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } }
vincentjava/middle-ware-parent
ware-elastic-search/src/main/java/com/elastic/search/model/RequestLog.java
Java
unknown
1,727
package com.elastic.search.repository; import com.elastic.search.model.RequestLog; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; public interface RequestLogRepository extends ElasticsearchRepository<RequestLog,Long> { }
vincentjava/middle-ware-parent
ware-elastic-search/src/main/java/com/elastic/search/repository/RequestLogRepository.java
Java
unknown
258
package com.elastic.search.service; import com.elastic.search.model.RequestLog; import java.util.Optional; public interface RequestLogService { String esInsert (Integer num) ; Iterable<RequestLog> esFindAll () ; String esUpdateById (RequestLog requestLog) ; Optional<RequestLog> esSelectById (Long id) ; Iterable<RequestLog> esFindOrder () ; Iterable<RequestLog> esFindOrders () ; Iterable<RequestLog> search () ; }
vincentjava/middle-ware-parent
ware-elastic-search/src/main/java/com/elastic/search/service/RequestLogService.java
Java
unknown
447
package com.elastic.search.service.impl; import com.elastic.search.model.RequestLog; import com.elastic.search.repository.RequestLogRepository; import com.elastic.search.service.RequestLogService; import com.elastic.search.util.DateUtil; import org.elasticsearch.index.query.*; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Optional; @Service public class RequestLogServiceImpl implements RequestLogService { @Resource private RequestLogRepository requestLogRepository ; @Override public String esInsert(Integer num) { for (int i = 0 ; i < num ; i++){ RequestLog requestLog = new RequestLog() ; requestLog.setId(System.currentTimeMillis()); requestLog.setOrderNo(DateUtil.formatDate(new Date(),DateUtil.DATE_FORMAT_02)+System.currentTimeMillis()); requestLog.setUserId("userId"+i); requestLog.setUserName("张三"+i); requestLog.setCreateTime(DateUtil.formatDate(new Date(),DateUtil.DATE_FORMAT_01)); requestLogRepository.save(requestLog) ; } return "success" ; } @Override public Iterable<RequestLog> esFindAll (){ return requestLogRepository.findAll() ; } @Override public String esUpdateById(RequestLog requestLog) { requestLogRepository.save(requestLog); return "success" ; } @Override public Optional<RequestLog> esSelectById(Long id) { return requestLogRepository.findById(id) ; } @Override public Iterable<RequestLog> esFindOrder() { // 用户名倒序 // Sort sort = new Sort(Sort.Direction.DESC,"userName.keyword") ; // 创建时间正序 Sort sort = new Sort(Sort.Direction.ASC,"createTime.keyword") ; return requestLogRepository.findAll(sort) ; } @Override public Iterable<RequestLog> esFindOrders() { List<Sort.Order> sortList = new ArrayList<>() ; Sort.Order sort1 = new Sort.Order(Sort.Direction.ASC,"createTime.keyword") ; Sort.Order sort2 = new Sort.Order(Sort.Direction.DESC,"userName.keyword") ; sortList.add(sort1) ; sortList.add(sort2) ; Sort orders = Sort.by(sortList) ; return requestLogRepository.findAll(orders) ; } @Override public Iterable<RequestLog> search() { // 全文搜索关键字 /* String queryString="张三"; QueryStringQueryBuilder builder = new QueryStringQueryBuilder(queryString); requestLogRepository.search(builder) ; */ /* * 多条件查询 */ QueryBuilder builder = QueryBuilders.boolQuery() // .must(QueryBuilders.matchQuery("userName.keyword", "历张")) 搜索不到 .must(QueryBuilders.matchQuery("userName", "张三")) // 可以搜索 .must(QueryBuilders.matchQuery("orderNo", "20190613736278243")); return requestLogRepository.search(builder) ; } }
vincentjava/middle-ware-parent
ware-elastic-search/src/main/java/com/elastic/search/service/impl/RequestLogServiceImpl.java
Java
unknown
3,150
package com.elastic.search.util; import org.joda.time.DateTime; import java.util.Date; /** * 基于 JODA 组件的时间工具类 */ public class DateUtil { private DateUtil (){} public static final String DATE_FORMAT_01 = "yyyy-MM-dd HH:mm:ss" ; public static final String DATE_FORMAT_02 = "yyyyMMdd" ; /** * 指定格式获取时间 */ public static String formatDate (Date date,String dateFormat){ DateTime dateTime = new DateTime(date) ; return dateTime.toString(dateFormat) ; } }
vincentjava/middle-ware-parent
ware-elastic-search/src/main/java/com/elastic/search/util/DateUtil.java
Java
unknown
541
package com.email.send; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableAsync; @EnableAsync @SpringBootApplication public class EmailApplication { public static void main(String[] args) { SpringApplication.run(EmailApplication.class,args) ; } }
vincentjava/middle-ware-parent
ware-email-send/src/main/java/com/email/send/EmailApplication.java
Java
unknown
390
package com.email.send.controller; import com.email.send.model.SendEmailModel; import com.email.send.param.EmailType; import com.email.send.service.EmailService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; @RestController public class EmailController { private static final Logger LOGGER = LoggerFactory.getLogger(EmailController.class) ; @Resource private EmailService emailService ; @RequestMapping("/sendEmail") public String sendEmail (){ SendEmailModel model = new SendEmailModel() ; model.setReceiver("xxxxx@qq.com"); emailService.sendEmail(EmailType.EMAIL_TEXT_KEY.getCode(),model); LOGGER.info("执行结束====>>"); return "success" ; } }
vincentjava/middle-ware-parent
ware-email-send/src/main/java/com/email/send/controller/EmailController.java
Java
unknown
890
package com.email.send.model; /** * 邮件发送参数封装 */ public class SendEmailModel { public static final String EMAIL_TEXT_KEY = "email_balance_key" ; public static final String EMAIL_IMAGE_KEY = "email_req_num_key" ; public static final String EMAIL_FILE_KEY = "email_open_account_key" ; /** * 收件人邮箱 */ private String receiver ; public String getReceiver() { return receiver; } public void setReceiver(String receiver) { this.receiver = receiver; } }
vincentjava/middle-ware-parent
ware-email-send/src/main/java/com/email/send/model/SendEmailModel.java
Java
unknown
542
package com.email.send.param; public enum BodyType { EMAIL_TEXT_BODY("email_text_key","您好:%s,我是:%s"), EMAIL_IMAGE_BODY("email_image_key","图片名称:%s"), EMAIL_FILE_BODY("email_file_key","文件名称:%s"); private String code ; private String value ; BodyType (String code,String value){ this.code = code ; this.value = value ; } public static String getByCode (String code){ BodyType[] values = BodyType.values() ; for (BodyType bodyType : values) { if (bodyType.code.equalsIgnoreCase(code)){ return bodyType.value ; } } return null ; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
vincentjava/middle-ware-parent
ware-email-send/src/main/java/com/email/send/param/BodyType.java
Java
unknown
954
package com.email.send.param; /** * 邮箱发送参数配置 */ public class EmailParam { /** * 邮箱服务器地址 */ // public static final String emailHost = "smtp.mxhichina.com" ; 阿里云企业邮箱配置(账号+密码) // public static final String emailHost = "smtp.aliyun.com" ; 阿里云个人邮箱配置(账号+密码) public static final String emailHost = "smtp.163.com" ; // 网易邮箱配置(账号+授权码) /** * 邮箱协议 */ public static final String emailProtocol = "smtp" ; /** * 邮箱发件人 */ public static final String emailSender = "xxxxxx@163.com" ; /** * 邮箱授权码 */ public static final String password = "authCode"; /** * 邮箱授权 */ public static final String emailAuth = "true" ; /** * 邮箱昵称 */ public static final String emailNick = "知了一笑" ; }
vincentjava/middle-ware-parent
ware-email-send/src/main/java/com/email/send/param/EmailParam.java
Java
unknown
946
package com.email.send.param; /** * 邮件发送类型 */ public enum EmailType { EMAIL_TEXT_KEY("email_text_key","文本邮件"), EMAIL_IMAGE_KEY("email_image_key","图片邮件"), EMAIL_FILE_KEY("email_file_key","文件邮件"); private String code ; private String value ; EmailType (String code,String value){ this.code = code ; this.value = value ; } public static String getByCode (String code){ EmailType[] values = EmailType.values() ; for (EmailType emailType : values) { if (emailType.code.equalsIgnoreCase(code)){ return emailType.value ; } } return null ; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
vincentjava/middle-ware-parent
ware-email-send/src/main/java/com/email/send/param/EmailType.java
Java
unknown
968
package com.email.send.service; import com.email.send.model.SendEmailModel; public interface EmailService { void sendEmail (String emailKey, SendEmailModel model) ; }
vincentjava/middle-ware-parent
ware-email-send/src/main/java/com/email/send/service/EmailService.java
Java
unknown
173
package com.email.send.service.impl; import com.email.send.model.SendEmailModel; import com.email.send.param.BodyType; import com.email.send.param.EmailType; import com.email.send.service.EmailService; import com.email.send.util.EmailUtil; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; @Component @Service public class EmailServiceImpl implements EmailService { @Async("taskExecutor") @Override public void sendEmail(String emailKey, SendEmailModel model) { try{ // 异步执行 Thread.sleep(1000); String textBody = EmailUtil.convertTextModel(BodyType.getByCode(emailKey),"知了","一笑"); // 发送文本邮件 EmailUtil.sendEmail01(model.getReceiver(), EmailType.getByCode(emailKey),textBody); // 发送复杂邮件:文本+图片+附件 String body = "自定义图片:<img src='cid:gzh.jpg'/>,网络图片:<img src='http://pic37.nipic.com/20140113/8800276_184927469000_2.png'/>"; // EmailUtil.sendEmail02(model.getReceiver(),"文本+图片+附件",body); } catch (Exception e){ e.printStackTrace(); } } }
vincentjava/middle-ware-parent
ware-email-send/src/main/java/com/email/send/service/impl/EmailServiceImpl.java
Java
unknown
1,272
package com.email.send.util; import com.email.send.param.EmailParam; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import java.io.FileOutputStream; import java.util.Properties; /** * 邮箱发送工具类 */ public class EmailUtil { public static void main(String[] args) throws Exception { sendEmail01("dzyaly@aliyun.com","复杂邮件","自定义图片:<img src='cid:gzh.jpg'/>,网络图片:<img src='http://pic37.nipic.com/20140113/8800276_184927469000_2.png'/>") ; } /** * 邮箱发送模式01:纯文本格式 */ public static void sendEmail01 (String receiver,String title,String body) throws Exception { Properties prop = new Properties(); prop.setProperty("mail.host", EmailParam.emailHost); prop.setProperty("mail.transport.protocol", EmailParam.emailProtocol); prop.setProperty("mail.smtp.auth", EmailParam.emailAuth); //使用JavaMail发送邮件的5个步骤 //1、创建session Session session = Session.getInstance(prop); //开启Session的debug模式,这样就可以查看到程序发送Email的运行状态 session.setDebug(true); //2、通过session得到transport对象 Transport ts = session.getTransport(); //3、使用邮箱的用户名和密码连上邮件服务器,发送邮件时,发件人需要提交邮箱的用户名和密码给smtp服务器,用户名和密码都通过验证之后才能够正常发送邮件给收件人。 ts.connect(EmailParam.emailHost, EmailParam.emailSender, EmailParam.password); //4、创建邮件 // Message message = createEmail01(session,receiver,title,body); Message message = createEmail01(session,receiver,title,body); //5、发送邮件 ts.sendMessage(message, message.getAllRecipients()); ts.close(); } /** * 邮箱发送模式02:复杂格式 */ public static void sendEmail02 (String receiver,String title,String body) throws Exception { Properties prop = new Properties(); prop.setProperty("mail.host", EmailParam.emailHost); prop.setProperty("mail.transport.protocol", EmailParam.emailProtocol); prop.setProperty("mail.smtp.auth", EmailParam.emailAuth); //使用JavaMail发送邮件的5个步骤 //1、创建session Session session = Session.getInstance(prop); //开启Session的debug模式,这样就可以查看到程序发送Email的运行状态 session.setDebug(true); //2、通过session得到transport对象 Transport ts = session.getTransport(); //3、使用邮箱的用户名和密码连上邮件服务器,发送邮件时,发件人需要提交邮箱的用户名和密码给smtp服务器,用户名和密码都通过验证之后才能够正常发送邮件给收件人。 ts.connect(EmailParam.emailHost, EmailParam.emailSender, EmailParam.password); //4、创建邮件 // Message message = createEmail01(session,receiver,title,body); Message message = createEmail02(session,receiver,title,body); //5、发送邮件 ts.sendMessage(message, message.getAllRecipients()); ts.close(); } /** * 创建文本邮件 */ private static MimeMessage createEmail01(Session session,String receiver,String title,String body) throws Exception { //创建邮件对象 MimeMessage message = new MimeMessage(session); //指明邮件的发件人 String nick = javax.mail.internet.MimeUtility.encodeText(EmailParam.emailNick); message.setFrom(new InternetAddress(nick+"<"+EmailParam.emailSender+">")); //指明邮件的收件人 message.setRecipient(Message.RecipientType.TO, new InternetAddress(receiver)); //邮件的标题 message.setSubject(title); //邮件的文本内容 message.setContent(body, "text/html;charset=UTF-8"); //返回创建好的邮件对象 return message; } private static MimeMessage createEmail02 (Session session,String receiver,String title,String body) throws Exception{ //创建邮件对象 MimeMessage message = new MimeMessage(session); //指明邮件的发件人 String nick = javax.mail.internet.MimeUtility.encodeText(EmailParam.emailNick); message.setFrom(new InternetAddress(nick+"<"+EmailParam.emailSender+">")); //指明邮件的收件人 message.setRecipient(Message.RecipientType.TO, new InternetAddress(receiver)); //邮件的标题 message.setSubject(title); //文本内容 MimeBodyPart text = new MimeBodyPart() ; text.setContent(body,"text/html;charset=UTF-8"); //图片内容 MimeBodyPart image = new MimeBodyPart(); image.setDataHandler(new DataHandler(new FileDataSource("ware-email-send/src/gzh.jpg"))); image.setContentID("gzh.jpg"); //附件内容 MimeBodyPart attach = new MimeBodyPart(); DataHandler file = new DataHandler(new FileDataSource("ware-email-send/src/gzh.zip")); attach.setDataHandler(file); attach.setFileName(file.getName()); //关系:正文和图片 MimeMultipart multipart1 = new MimeMultipart(); multipart1.addBodyPart(text); multipart1.addBodyPart(image); multipart1.setSubType("related"); //关系:正文和附件 MimeMultipart multipart2 = new MimeMultipart(); multipart2.addBodyPart(attach); // 全文内容 MimeBodyPart content = new MimeBodyPart(); content.setContent(multipart1); multipart2.addBodyPart(content); multipart2.setSubType("mixed"); // 封装 MimeMessage 对象 message.setContent(multipart2); message.saveChanges(); // 本地查看文件格式 message.writeTo(new FileOutputStream("F:\\MixedMail.eml")); //返回创建好的邮件对象 return message; } /** * 文本邮箱模板 */ public static String convertTextModel (String body,String param1,String param2){ return String.format(body,param1,param2) ; } /** * 图片邮箱模板 */ public static String convertImageModel (String body,String param1){ return String.format(body,param1) ; } /** * 文件邮箱模板 */ public static String convertFileModel (String body,String param1){ return String.format(body,param1) ; } }
vincentjava/middle-ware-parent
ware-email-send/src/main/java/com/email/send/util/EmailUtil.java
Java
unknown
6,867
package com.email.send.util; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.Executor; import java.util.concurrent.ThreadPoolExecutor; /** * 定义异步任务执行线程池 */ @Configuration public class TaskPoolConfig { @Bean("taskExecutor") public Executor taskExecutor () { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // 核心线程数10:线程池创建时候初始化的线程数 executor.setCorePoolSize(10); // 最大线程数20:线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程 executor.setMaxPoolSize(15); // 缓冲队列200:用来缓冲执行任务的队列 executor.setQueueCapacity(200); // 允许线程的空闲时间60秒:当超过了核心线程数之外的线程在空闲时间到达之后会被销毁 executor.setKeepAliveSeconds(60); // 线程池名的前缀:设置好了之后可以方便定位处理任务所在的线程池 executor.setThreadNamePrefix("taskExecutor-"); /* 线程池对拒绝任务的处理策略:这里采用了CallerRunsPolicy策略, 当线程池没有处理能力的时候,该策略会直接在 execute 方法的调用线程中运行被拒绝的任务; 如果执行程序已关闭,则会丢弃该任务 */ executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 设置线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean executor.setWaitForTasksToCompleteOnShutdown(true); // 设置线程池中任务的等待时间,如果超过这个时候还没有销毁就强制销毁,以确保应用最后能够被关闭,而不是阻塞住。 executor.setAwaitTerminationSeconds(600); return executor; } }
vincentjava/middle-ware-parent
ware-email-send/src/main/java/com/email/send/util/TaskPoolConfig.java
Java
unknown
2,051
package com.fast.dfs; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import springfox.documentation.swagger2.annotations.EnableSwagger2; @EnableSwagger2 @SpringBootApplication public class DFSApplication { public static void main(String[] args) { SpringApplication.run(DFSApplication.class,args) ; } }
vincentjava/middle-ware-parent
ware-fast-dfs/src/main/java/com/fast/dfs/DFSApplication.java
Java
unknown
393
package com.fast.dfs.config; import com.github.tobato.fastdfs.FdfsClientConfig; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableMBeanExport; import org.springframework.context.annotation.Import; import org.springframework.jmx.support.RegistrationPolicy; @Configuration @Import(FdfsClientConfig.class) // Jmx重复注册bean的问题 @EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING) public class DfsConfig { }
vincentjava/middle-ware-parent
ware-fast-dfs/src/main/java/com/fast/dfs/config/DfsConfig.java
Java
unknown
498
package com.fast.dfs.config; import com.github.tobato.fastdfs.domain.fdfs.StorePath; import com.github.tobato.fastdfs.service.FastFileStorageClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; @Component public class FileDfsUtil { private static final Logger LOGGER = LoggerFactory.getLogger(FileDfsUtil.class); @Resource private FastFileStorageClient storageClient ; /** * 上传文件 */ public String upload(MultipartFile multipartFile) throws Exception{ String originalFilename = multipartFile.getOriginalFilename(). substring(multipartFile.getOriginalFilename(). lastIndexOf(".") + 1); StorePath storePath = this.storageClient.uploadImageAndCrtThumbImage( multipartFile.getInputStream(), multipartFile.getSize(),originalFilename , null); return storePath.getFullPath() ; } /** * 删除文件 */ public void deleteFile(String fileUrl) { if (StringUtils.isEmpty(fileUrl)) { LOGGER.info("fileUrl == >>文件路径为空..."); return; } try { StorePath storePath = StorePath.parseFromUrl(fileUrl); storageClient.deleteFile(storePath.getGroup(), storePath.getPath()); } catch (Exception e) { LOGGER.info(e.getMessage()); } } }
vincentjava/middle-ware-parent
ware-fast-dfs/src/main/java/com/fast/dfs/config/FileDfsUtil.java
Java
unknown
1,635
package com.fast.dfs.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; /** * Swagger 配置文件 */ @Configuration public class SwaggerConfig { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.fast.dfs")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("SpringBoot利用Swagger构建API文档") .description("使用RestFul风格, 创建人:知了一笑") .termsOfServiceUrl("https://github.com/cicadasmile") .version("version 1.0") .build(); } }
vincentjava/middle-ware-parent
ware-fast-dfs/src/main/java/com/fast/dfs/config/SwaggerConfig.java
Java
unknown
1,225
package com.fast.dfs.controller; import com.fast.dfs.config.FileDfsUtil; import io.swagger.annotations.ApiOperation; import org.springframework.http.ResponseEntity; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; @RestController public class FileController { @Resource private FileDfsUtil fileDfsUtil ; /** * http://localhost:7010/swagger-ui.html * http://192.168.72.130/group1/M00/00/00/wKhIgl0n4AKABxQEABhlMYw_3Lo825.png */ @ApiOperation(value="上传文件", notes="测试FastDFS文件上传") @RequestMapping(value = "/uploadFile",headers="content-type=multipart/form-data", method = RequestMethod.POST) public ResponseEntity<String> uploadFile (@RequestParam("file") MultipartFile file){ String result ; try{ String path = fileDfsUtil.upload(file) ; if (!StringUtils.isEmpty(path)){ result = path ; } else { result = "上传失败" ; } } catch (Exception e){ e.printStackTrace() ; result = "服务异常" ; } return ResponseEntity.ok(result); } /** * 文件删除 */ @RequestMapping(value = "/deleteByPath", method = RequestMethod.GET) public ResponseEntity<String> deleteByPath (){ String filePathName = "group1/M00/00/00/wKhIgl0n4AKABxQEABhlMYw_3Lo825.png" ; fileDfsUtil.deleteFile(filePathName); return ResponseEntity.ok("SUCCESS") ; } }
vincentjava/middle-ware-parent
ware-fast-dfs/src/main/java/com/fast/dfs/controller/FileController.java
Java
unknown
1,624
package com.jwt.token; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class JwtApplication { public static void main(String[] args) { SpringApplication.run(JwtApplication.class,args) ; } }
vincentjava/middle-ware-parent
ware-jwt-token/src/main/java/com/jwt/token/JwtApplication.java
Java
unknown
310
package com.jwt.token.config; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import java.util.Date; @ConfigurationProperties(prefix = "config.jwt") @Component public class JwtConfig { /* * 根据身份ID标识,生成Token */ public String getToken (String identityId){ Date nowDate = new Date(); //过期时间 Date expireDate = new Date(nowDate.getTime() + expire * 1000); return Jwts.builder() .setHeaderParam("typ", "JWT") .setSubject(identityId) .setIssuedAt(nowDate) .setExpiration(expireDate) .signWith(SignatureAlgorithm.HS512, secret) .compact(); } /* * 获取 Token 中注册信息 */ public Claims getTokenClaim (String token) { try { return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody(); }catch (Exception e){ e.printStackTrace(); return null; } } /* * Token 是否过期验证 */ public boolean isTokenExpired (Date expirationTime) { return expirationTime.before(new Date()); } private String secret; private long expire; private String header; public String getSecret() { return secret; } public void setSecret(String secret) { this.secret = secret; } public long getExpire() { return expire; } public void setExpire(long expire) { this.expire = expire; } public String getHeader() { return header; } public void setHeader(String header) { this.header = header; } }
vincentjava/middle-ware-parent
ware-jwt-token/src/main/java/com/jwt/token/config/JwtConfig.java
Java
unknown
1,856
package com.jwt.token.config; import com.jwt.token.interceptor.TokenInterceptor; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import javax.annotation.Resource; @Configuration public class WebConfig implements WebMvcConfigurer { /** * 拦截器注册 */ @Resource private TokenInterceptor tokenInterceptor ; public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(tokenInterceptor).addPathPatterns("/**"); } }
vincentjava/middle-ware-parent
ware-jwt-token/src/main/java/com/jwt/token/config/WebConfig.java
Java
unknown
647
package com.jwt.token.controller; import com.jwt.token.config.JwtConfig; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import java.util.HashMap; import java.util.Map; @RestController public class TokenController { @Resource private JwtConfig jwtConfig ; /* * 返参格式 * { * "userName": "ID123", * "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9. * eyJzdWIiOiJJRDEyM3B3MTIzIiwiaWF0Ijox. * SqqaZfG_g2OMijyN5eG0bPmkIQaqMRFlUvny" * } */ // 拦截器直接放行,返回Token @PostMapping("/login") public Map<String,String> login (@RequestParam("userName") String userName, @RequestParam("passWord") String passWord){ Map<String,String> result = new HashMap<>() ; // 省略数据源校验 String token = jwtConfig.getToken(userName+passWord) ; if (!StringUtils.isEmpty(token)) { result.put("token",token) ; } result.put("userName",userName) ; return result ; } // 需要 Token 验证的接口 @PostMapping("/info") public String info (){ return "info" ; } }
vincentjava/middle-ware-parent
ware-jwt-token/src/main/java/com/jwt/token/controller/TokenController.java
Java
unknown
1,411
package com.jwt.token.interceptor; import com.jwt.token.config.JwtConfig; import io.jsonwebtoken.Claims; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Token 拦截器 */ @Component public class TokenInterceptor extends HandlerInterceptorAdapter { @Resource private JwtConfig jwtConfig ; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 地址过滤 String uri = request.getRequestURI() ; if (uri.contains("/login")){ return true ; } // Token 验证 String token = request.getHeader(jwtConfig.getHeader()); if(StringUtils.isEmpty(token)){ token = request.getParameter(jwtConfig.getHeader()); } if(StringUtils.isEmpty(token)){ throw new Exception(jwtConfig.getHeader()+ "不能为空"); } Claims claims = jwtConfig.getTokenClaim(token); if(claims == null || jwtConfig.isTokenExpired(claims.getExpiration())){ throw new Exception(jwtConfig.getHeader() + "失效,请重新登录"); } //设置 identityId 用户身份ID request.setAttribute("identityId", claims.getSubject()); return true; } }
vincentjava/middle-ware-parent
ware-jwt-token/src/main/java/com/jwt/token/interceptor/TokenInterceptor.java
Java
unknown
1,586
package com.quart.job; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class QuartJobApplication { public static void main(String[] args) { SpringApplication.run(QuartJobApplication.class, args); } }
vincentjava/middle-ware-parent
ware-quart-job/src/main/java/com/quart/job/QuartJobApplication.java
Java
unknown
320
package com.quart.job.config; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.support.http.StatViewServlet; import com.alibaba.druid.support.http.WebStatFilter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import javax.sql.DataSource; /** * Druid数据库连接池配置文件 */ @Configuration public class DruidConfig { private static final Logger logger = LoggerFactory.getLogger(DruidConfig.class); @Value("${spring.datasource.druid.url}") private String dbUrl; @Value("${spring.datasource.druid.username}") private String username; @Value("${spring.datasource.druid.password}") private String password; @Value("${spring.datasource.druid.driverClassName}") private String driverClassName; @Value("${spring.datasource.druid.initial-size}") private int initialSize; @Value("${spring.datasource.druid.max-active}") private int maxActive; @Value("${spring.datasource.druid.min-idle}") private int minIdle; @Value("${spring.datasource.druid.max-wait}") private int maxWait; @Value("${spring.datasource.druid.pool-prepared-statements}") private boolean poolPreparedStatements; @Value("${spring.datasource.druid.max-pool-prepared-statement-per-connection-size}") private int maxPoolPreparedStatementPerConnectionSize; @Value("${spring.datasource.druid.time-between-eviction-runs-millis}") private int timeBetweenEvictionRunsMillis; @Value("${spring.datasource.druid.min-evictable-idle-time-millis}") private int minEvictableIdleTimeMillis; @Value("${spring.datasource.druid.max-evictable-idle-time-millis}") private int maxEvictableIdleTimeMillis; @Value("${spring.datasource.druid.validation-query}") private String validationQuery; @Value("${spring.datasource.druid.test-while-idle}") private boolean testWhileIdle; @Value("${spring.datasource.druid.test-on-borrow}") private boolean testOnBorrow; @Value("${spring.datasource.druid.test-on-return}") private boolean testOnReturn; @Value("${spring.datasource.druid.filters}") private String filters; @Value("{spring.datasource.druid.connection-properties}") private String connectionProperties; @Bean //声明其为Bean实例 @Primary //在同样的DataSource中,首先使用被标注的DataSource public DataSource dataSource() { DruidDataSource datasource = new DruidDataSource(); datasource.setUrl(dbUrl); datasource.setUsername(username); datasource.setPassword(password); datasource.setDriverClassName(driverClassName); datasource.setInitialSize(initialSize); datasource.setMinIdle(minIdle); datasource.setMaxActive(maxActive); datasource.setMaxWait(maxWait); datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); datasource.setMaxEvictableIdleTimeMillis(minEvictableIdleTimeMillis); datasource.setValidationQuery(validationQuery); datasource.setTestWhileIdle(testWhileIdle); datasource.setTestOnBorrow(testOnBorrow); datasource.setTestOnReturn(testOnReturn); datasource.setPoolPreparedStatements(poolPreparedStatements); datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize); try { datasource.setFilters(filters); } catch (Exception e) { logger.error("druid configuration initialization filter", e); } datasource.setConnectionProperties(connectionProperties); return datasource; } @Bean public ServletRegistrationBean statViewServlet(){ ServletRegistrationBean srb = new ServletRegistrationBean(new StatViewServlet(),"/druid/*"); //设置控制台管理用户 srb.addInitParameter("loginUsername","root"); srb.addInitParameter("loginPassword","root"); //是否可以重置数据 srb.addInitParameter("resetEnable","false"); return srb; } @Bean public FilterRegistrationBean statFilter(){ //创建过滤器 FilterRegistrationBean frb = new FilterRegistrationBean(new WebStatFilter()); //设置过滤器过滤路径 frb.addUrlPatterns("/*"); //忽略过滤的形式 frb.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); return frb; } }
vincentjava/middle-ware-parent
ware-quart-job/src/main/java/com/quart/job/config/DruidConfig.java
Java
unknown
4,950
package com.quart.job.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.quartz.SchedulerFactoryBean; import javax.sql.DataSource; import java.util.Properties; @Configuration public class ScheduleConfig { @Bean public SchedulerFactoryBean schedulerFactoryBean(DataSource dataSource) { // Quartz参数配置 Properties prop = new Properties(); // Schedule调度器的实体名字 prop.put("org.quartz.scheduler.instanceName", "HuskyScheduler"); // 设置为AUTO时使用,默认的实现org.quartz.scheduler.SimpleInstanceGenerator是基于主机名称和时间戳生成。 prop.put("org.quartz.scheduler.instanceId", "AUTO"); // 线程池配置 prop.put("org.quartz.threadPool.class", "org.quartz.simpl.SimpleThreadPool"); prop.put("org.quartz.threadPool.threadCount", "20"); prop.put("org.quartz.threadPool.threadPriority", "5"); // JobStore配置:Scheduler在运行时用来存储相关的信息 // JDBCJobStore和JobStoreTX都使用关系数据库来存储Schedule相关的信息。 // JobStoreTX在每次执行任务后都使用commit或者rollback来提交更改。 prop.put("org.quartz.jobStore.class", "org.quartz.impl.jdbcjobstore.JobStoreTX"); // 集群配置:如果有多个调度器实体的话则必须设置为true prop.put("org.quartz.jobStore.isClustered", "true"); // 集群配置:检查集群下的其他调度器实体的时间间隔 prop.put("org.quartz.jobStore.clusterCheckinInterval", "15000"); // 设置一个频度(毫秒),用于实例报告给集群中的其他实例 prop.put("org.quartz.jobStore.maxMisfiresToHandleAtATime", "1"); // 触发器触发失败后再次触犯的时间间隔 prop.put("org.quartz.jobStore.misfireThreshold", "12000"); // 数据库表前缀 prop.put("org.quartz.jobStore.tablePrefix", "qrtz_"); // 从 LOCKS 表查询一行并对这行记录加锁的 SQL 语句 prop.put("org.quartz.jobStore.selectWithLockSQL", "SELECT * FROM {0}LOCKS UPDLOCK WHERE LOCK_NAME = ?"); // 定时器工厂配置 SchedulerFactoryBean factory = new SchedulerFactoryBean(); factory.setDataSource(dataSource); factory.setQuartzProperties(prop); factory.setSchedulerName("HuskyScheduler"); factory.setStartupDelay(30); factory.setApplicationContextSchedulerContextKey("applicationContextKey"); // 可选,QuartzScheduler 启动时更新己存在的Job factory.setOverwriteExistingJobs(true); // 设置自动启动,默认为true factory.setAutoStartup(true); return factory; } }
vincentjava/middle-ware-parent
ware-quart-job/src/main/java/com/quart/job/config/ScheduleConfig.java
Java
unknown
2,843
package com.quart.job.controller; import com.quart.job.entity.ScheduleJobBean; import com.quart.job.service.ScheduleJobService; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import java.util.Date; @RestController @RequestMapping("/job") public class ScheduleJobWeb { @Resource private ScheduleJobService scheduleJobService ; /** * 添加定时器 */ @RequestMapping("/insertJob") public ScheduleJobBean insertJob (){ ScheduleJobBean scheduleJobBean = new ScheduleJobBean() ; scheduleJobBean.setJobId(1L); scheduleJobBean.setBeanName("getTimeTask"); // 每分钟执行一次 scheduleJobBean.setCronExpression("0 0/1 * * * ?"); scheduleJobBean.setParams("Hello,Quart-Job"); scheduleJobBean.setStatus(0); scheduleJobBean.setRemark("获取时间定时器"); scheduleJobBean.setCreateTime(new Date()); scheduleJobService.insert(scheduleJobBean) ; return scheduleJobBean ; } /** * 执行一次定时器 */ @RequestMapping("/runJob") public String runJob (){ Long jobId = 1L ; scheduleJobService.run(jobId); return "success" ; } /** * 更新定时器 */ @RequestMapping("/updateJob") public String updateJob (){ Long jobId = 1L ; ScheduleJobBean scheduleJobBean = scheduleJobService.selectByPrimaryKey(jobId) ; scheduleJobBean.setParams("Hello,Job_Quart"); scheduleJobService.updateByPrimaryKeySelective(scheduleJobBean) ; return "success" ; } /** * 停止定时器 */ @RequestMapping("/pauseJob") public String pauseJob (){ Long jobId = 1L ; scheduleJobService.pauseJob(jobId); return "success" ; } /** * 恢复定时器 */ @RequestMapping("/resumeJob") public String resumeJob (){ Long jobId = 1L ; scheduleJobService.resumeJob(jobId); return "success" ; } /** * 删除定时器 */ @RequestMapping("/deleteJob") public String deleteJob (){ Long jobId = 1L ; scheduleJobService.delete(jobId); return "success" ; } }
vincentjava/middle-ware-parent
ware-quart-job/src/main/java/com/quart/job/controller/ScheduleJobWeb.java
Java
unknown
2,322
package com.quart.job.entity; import java.io.Serializable; import java.util.Date; /** * 定时任务配置管理 */ public class ScheduleJobBean implements Serializable { private static final long serialVersionUID = 1L; /** * 任务调度参数key */ public static final String JOB_PARAM_KEY = "JOB_PARAM_KEY"; private Long jobId; private String beanName; private String params; private String cronExpression; private Integer status; private String remark; private Date createTime; public Long getJobId() { return jobId; } public void setJobId(Long jobId) { this.jobId = jobId; } public String getBeanName() { return beanName; } public void setBeanName(String beanName) { this.beanName = beanName; } public String getParams() { return params; } public void setParams(String params) { this.params = params; } public String getCronExpression() { return cronExpression; } public void setCronExpression(String cronExpression) { this.cronExpression = cronExpression; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } }
vincentjava/middle-ware-parent
ware-quart-job/src/main/java/com/quart/job/entity/ScheduleJobBean.java
Java
unknown
1,405
package com.quart.job.entity; import java.util.ArrayList; import java.util.Date; import java.util.List; public class ScheduleJobExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public ScheduleJobExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andJobIdIsNull() { addCriterion("job_id is null"); return (Criteria) this; } public Criteria andJobIdIsNotNull() { addCriterion("job_id is not null"); return (Criteria) this; } public Criteria andJobIdEqualTo(Long value) { addCriterion("job_id =", value, "jobId"); return (Criteria) this; } public Criteria andJobIdNotEqualTo(Long value) { addCriterion("job_id <>", value, "jobId"); return (Criteria) this; } public Criteria andJobIdGreaterThan(Long value) { addCriterion("job_id >", value, "jobId"); return (Criteria) this; } public Criteria andJobIdGreaterThanOrEqualTo(Long value) { addCriterion("job_id >=", value, "jobId"); return (Criteria) this; } public Criteria andJobIdLessThan(Long value) { addCriterion("job_id <", value, "jobId"); return (Criteria) this; } public Criteria andJobIdLessThanOrEqualTo(Long value) { addCriterion("job_id <=", value, "jobId"); return (Criteria) this; } public Criteria andJobIdIn(List<Long> values) { addCriterion("job_id in", values, "jobId"); return (Criteria) this; } public Criteria andJobIdNotIn(List<Long> values) { addCriterion("job_id not in", values, "jobId"); return (Criteria) this; } public Criteria andJobIdBetween(Long value1, Long value2) { addCriterion("job_id between", value1, value2, "jobId"); return (Criteria) this; } public Criteria andJobIdNotBetween(Long value1, Long value2) { addCriterion("job_id not between", value1, value2, "jobId"); return (Criteria) this; } public Criteria andBeanNameIsNull() { addCriterion("bean_name is null"); return (Criteria) this; } public Criteria andBeanNameIsNotNull() { addCriterion("bean_name is not null"); return (Criteria) this; } public Criteria andBeanNameEqualTo(String value) { addCriterion("bean_name =", value, "beanName"); return (Criteria) this; } public Criteria andBeanNameNotEqualTo(String value) { addCriterion("bean_name <>", value, "beanName"); return (Criteria) this; } public Criteria andBeanNameGreaterThan(String value) { addCriterion("bean_name >", value, "beanName"); return (Criteria) this; } public Criteria andBeanNameGreaterThanOrEqualTo(String value) { addCriterion("bean_name >=", value, "beanName"); return (Criteria) this; } public Criteria andBeanNameLessThan(String value) { addCriterion("bean_name <", value, "beanName"); return (Criteria) this; } public Criteria andBeanNameLessThanOrEqualTo(String value) { addCriterion("bean_name <=", value, "beanName"); return (Criteria) this; } public Criteria andBeanNameLike(String value) { addCriterion("bean_name like", value, "beanName"); return (Criteria) this; } public Criteria andBeanNameNotLike(String value) { addCriterion("bean_name not like", value, "beanName"); return (Criteria) this; } public Criteria andBeanNameIn(List<String> values) { addCriterion("bean_name in", values, "beanName"); return (Criteria) this; } public Criteria andBeanNameNotIn(List<String> values) { addCriterion("bean_name not in", values, "beanName"); return (Criteria) this; } public Criteria andBeanNameBetween(String value1, String value2) { addCriterion("bean_name between", value1, value2, "beanName"); return (Criteria) this; } public Criteria andBeanNameNotBetween(String value1, String value2) { addCriterion("bean_name not between", value1, value2, "beanName"); return (Criteria) this; } public Criteria andParamsIsNull() { addCriterion("params is null"); return (Criteria) this; } public Criteria andParamsIsNotNull() { addCriterion("params is not null"); return (Criteria) this; } public Criteria andParamsEqualTo(String value) { addCriterion("params =", value, "params"); return (Criteria) this; } public Criteria andParamsNotEqualTo(String value) { addCriterion("params <>", value, "params"); return (Criteria) this; } public Criteria andParamsGreaterThan(String value) { addCriterion("params >", value, "params"); return (Criteria) this; } public Criteria andParamsGreaterThanOrEqualTo(String value) { addCriterion("params >=", value, "params"); return (Criteria) this; } public Criteria andParamsLessThan(String value) { addCriterion("params <", value, "params"); return (Criteria) this; } public Criteria andParamsLessThanOrEqualTo(String value) { addCriterion("params <=", value, "params"); return (Criteria) this; } public Criteria andParamsLike(String value) { addCriterion("params like", value, "params"); return (Criteria) this; } public Criteria andParamsNotLike(String value) { addCriterion("params not like", value, "params"); return (Criteria) this; } public Criteria andParamsIn(List<String> values) { addCriterion("params in", values, "params"); return (Criteria) this; } public Criteria andParamsNotIn(List<String> values) { addCriterion("params not in", values, "params"); return (Criteria) this; } public Criteria andParamsBetween(String value1, String value2) { addCriterion("params between", value1, value2, "params"); return (Criteria) this; } public Criteria andParamsNotBetween(String value1, String value2) { addCriterion("params not between", value1, value2, "params"); return (Criteria) this; } public Criteria andCronExpressionIsNull() { addCriterion("cron_expression is null"); return (Criteria) this; } public Criteria andCronExpressionIsNotNull() { addCriterion("cron_expression is not null"); return (Criteria) this; } public Criteria andCronExpressionEqualTo(String value) { addCriterion("cron_expression =", value, "cronExpression"); return (Criteria) this; } public Criteria andCronExpressionNotEqualTo(String value) { addCriterion("cron_expression <>", value, "cronExpression"); return (Criteria) this; } public Criteria andCronExpressionGreaterThan(String value) { addCriterion("cron_expression >", value, "cronExpression"); return (Criteria) this; } public Criteria andCronExpressionGreaterThanOrEqualTo(String value) { addCriterion("cron_expression >=", value, "cronExpression"); return (Criteria) this; } public Criteria andCronExpressionLessThan(String value) { addCriterion("cron_expression <", value, "cronExpression"); return (Criteria) this; } public Criteria andCronExpressionLessThanOrEqualTo(String value) { addCriterion("cron_expression <=", value, "cronExpression"); return (Criteria) this; } public Criteria andCronExpressionLike(String value) { addCriterion("cron_expression like", value, "cronExpression"); return (Criteria) this; } public Criteria andCronExpressionNotLike(String value) { addCriterion("cron_expression not like", value, "cronExpression"); return (Criteria) this; } public Criteria andCronExpressionIn(List<String> values) { addCriterion("cron_expression in", values, "cronExpression"); return (Criteria) this; } public Criteria andCronExpressionNotIn(List<String> values) { addCriterion("cron_expression not in", values, "cronExpression"); return (Criteria) this; } public Criteria andCronExpressionBetween(String value1, String value2) { addCriterion("cron_expression between", value1, value2, "cronExpression"); return (Criteria) this; } public Criteria andCronExpressionNotBetween(String value1, String value2) { addCriterion("cron_expression not between", value1, value2, "cronExpression"); return (Criteria) this; } public Criteria andStatusIsNull() { addCriterion("status is null"); return (Criteria) this; } public Criteria andStatusIsNotNull() { addCriterion("status is not null"); return (Criteria) this; } public Criteria andStatusEqualTo(Byte value) { addCriterion("status =", value, "status"); return (Criteria) this; } public Criteria andStatusNotEqualTo(Byte value) { addCriterion("status <>", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThan(Byte value) { addCriterion("status >", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThanOrEqualTo(Byte value) { addCriterion("status >=", value, "status"); return (Criteria) this; } public Criteria andStatusLessThan(Byte value) { addCriterion("status <", value, "status"); return (Criteria) this; } public Criteria andStatusLessThanOrEqualTo(Byte value) { addCriterion("status <=", value, "status"); return (Criteria) this; } public Criteria andStatusIn(List<Byte> values) { addCriterion("status in", values, "status"); return (Criteria) this; } public Criteria andStatusNotIn(List<Byte> values) { addCriterion("status not in", values, "status"); return (Criteria) this; } public Criteria andStatusBetween(Byte value1, Byte value2) { addCriterion("status between", value1, value2, "status"); return (Criteria) this; } public Criteria andStatusNotBetween(Byte value1, Byte value2) { addCriterion("status not between", value1, value2, "status"); return (Criteria) this; } public Criteria andRemarkIsNull() { addCriterion("remark is null"); return (Criteria) this; } public Criteria andRemarkIsNotNull() { addCriterion("remark is not null"); return (Criteria) this; } public Criteria andRemarkEqualTo(String value) { addCriterion("remark =", value, "remark"); return (Criteria) this; } public Criteria andRemarkNotEqualTo(String value) { addCriterion("remark <>", value, "remark"); return (Criteria) this; } public Criteria andRemarkGreaterThan(String value) { addCriterion("remark >", value, "remark"); return (Criteria) this; } public Criteria andRemarkGreaterThanOrEqualTo(String value) { addCriterion("remark >=", value, "remark"); return (Criteria) this; } public Criteria andRemarkLessThan(String value) { addCriterion("remark <", value, "remark"); return (Criteria) this; } public Criteria andRemarkLessThanOrEqualTo(String value) { addCriterion("remark <=", value, "remark"); return (Criteria) this; } public Criteria andRemarkLike(String value) { addCriterion("remark like", value, "remark"); return (Criteria) this; } public Criteria andRemarkNotLike(String value) { addCriterion("remark not like", value, "remark"); return (Criteria) this; } public Criteria andRemarkIn(List<String> values) { addCriterion("remark in", values, "remark"); return (Criteria) this; } public Criteria andRemarkNotIn(List<String> values) { addCriterion("remark not in", values, "remark"); return (Criteria) this; } public Criteria andRemarkBetween(String value1, String value2) { addCriterion("remark between", value1, value2, "remark"); return (Criteria) this; } public Criteria andRemarkNotBetween(String value1, String value2) { addCriterion("remark not between", value1, value2, "remark"); return (Criteria) this; } public Criteria andCreateTimeIsNull() { addCriterion("create_time is null"); return (Criteria) this; } public Criteria andCreateTimeIsNotNull() { addCriterion("create_time is not null"); return (Criteria) this; } public Criteria andCreateTimeEqualTo(Date value) { addCriterion("create_time =", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotEqualTo(Date value) { addCriterion("create_time <>", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThan(Date value) { addCriterion("create_time >", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) { addCriterion("create_time >=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThan(Date value) { addCriterion("create_time <", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThanOrEqualTo(Date value) { addCriterion("create_time <=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeIn(List<Date> values) { addCriterion("create_time in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotIn(List<Date> values) { addCriterion("create_time not in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeBetween(Date value1, Date value2) { addCriterion("create_time between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotBetween(Date value1, Date value2) { addCriterion("create_time not between", value1, value2, "createTime"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
vincentjava/middle-ware-parent
ware-quart-job/src/main/java/com/quart/job/entity/ScheduleJobExample.java
Java
unknown
20,799
package com.quart.job.entity; import java.io.Serializable; import java.util.Date; /** * 定时任务日志 */ public class ScheduleJobLogBean implements Serializable { private static final long serialVersionUID = 1L; private Long logId; private Long jobId; private String beanName; private String params; private Integer status; private String error; private Integer times; private Date createTime; public Long getLogId() { return logId; } public void setLogId(Long logId) { this.logId = logId; } public Long getJobId() { return jobId; } public void setJobId(Long jobId) { this.jobId = jobId; } public String getBeanName() { return beanName; } public void setBeanName(String beanName) { this.beanName = beanName; } public String getParams() { return params; } public void setParams(String params) { this.params = params; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public String getError() { return error; } public void setError(String error) { this.error = error; } public Integer getTimes() { return times; } public void setTimes(Integer times) { this.times = times; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } }
vincentjava/middle-ware-parent
ware-quart-job/src/main/java/com/quart/job/entity/ScheduleJobLogBean.java
Java
unknown
1,364
package com.quart.job.entity; import java.util.ArrayList; import java.util.Date; import java.util.List; public class ScheduleJobLogExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public ScheduleJobLogExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andLogIdIsNull() { addCriterion("log_id is null"); return (Criteria) this; } public Criteria andLogIdIsNotNull() { addCriterion("log_id is not null"); return (Criteria) this; } public Criteria andLogIdEqualTo(Long value) { addCriterion("log_id =", value, "logId"); return (Criteria) this; } public Criteria andLogIdNotEqualTo(Long value) { addCriterion("log_id <>", value, "logId"); return (Criteria) this; } public Criteria andLogIdGreaterThan(Long value) { addCriterion("log_id >", value, "logId"); return (Criteria) this; } public Criteria andLogIdGreaterThanOrEqualTo(Long value) { addCriterion("log_id >=", value, "logId"); return (Criteria) this; } public Criteria andLogIdLessThan(Long value) { addCriterion("log_id <", value, "logId"); return (Criteria) this; } public Criteria andLogIdLessThanOrEqualTo(Long value) { addCriterion("log_id <=", value, "logId"); return (Criteria) this; } public Criteria andLogIdIn(List<Long> values) { addCriterion("log_id in", values, "logId"); return (Criteria) this; } public Criteria andLogIdNotIn(List<Long> values) { addCriterion("log_id not in", values, "logId"); return (Criteria) this; } public Criteria andLogIdBetween(Long value1, Long value2) { addCriterion("log_id between", value1, value2, "logId"); return (Criteria) this; } public Criteria andLogIdNotBetween(Long value1, Long value2) { addCriterion("log_id not between", value1, value2, "logId"); return (Criteria) this; } public Criteria andJobIdIsNull() { addCriterion("job_id is null"); return (Criteria) this; } public Criteria andJobIdIsNotNull() { addCriterion("job_id is not null"); return (Criteria) this; } public Criteria andJobIdEqualTo(Long value) { addCriterion("job_id =", value, "jobId"); return (Criteria) this; } public Criteria andJobIdNotEqualTo(Long value) { addCriterion("job_id <>", value, "jobId"); return (Criteria) this; } public Criteria andJobIdGreaterThan(Long value) { addCriterion("job_id >", value, "jobId"); return (Criteria) this; } public Criteria andJobIdGreaterThanOrEqualTo(Long value) { addCriterion("job_id >=", value, "jobId"); return (Criteria) this; } public Criteria andJobIdLessThan(Long value) { addCriterion("job_id <", value, "jobId"); return (Criteria) this; } public Criteria andJobIdLessThanOrEqualTo(Long value) { addCriterion("job_id <=", value, "jobId"); return (Criteria) this; } public Criteria andJobIdIn(List<Long> values) { addCriterion("job_id in", values, "jobId"); return (Criteria) this; } public Criteria andJobIdNotIn(List<Long> values) { addCriterion("job_id not in", values, "jobId"); return (Criteria) this; } public Criteria andJobIdBetween(Long value1, Long value2) { addCriterion("job_id between", value1, value2, "jobId"); return (Criteria) this; } public Criteria andJobIdNotBetween(Long value1, Long value2) { addCriterion("job_id not between", value1, value2, "jobId"); return (Criteria) this; } public Criteria andBeanNameIsNull() { addCriterion("bean_name is null"); return (Criteria) this; } public Criteria andBeanNameIsNotNull() { addCriterion("bean_name is not null"); return (Criteria) this; } public Criteria andBeanNameEqualTo(String value) { addCriterion("bean_name =", value, "beanName"); return (Criteria) this; } public Criteria andBeanNameNotEqualTo(String value) { addCriterion("bean_name <>", value, "beanName"); return (Criteria) this; } public Criteria andBeanNameGreaterThan(String value) { addCriterion("bean_name >", value, "beanName"); return (Criteria) this; } public Criteria andBeanNameGreaterThanOrEqualTo(String value) { addCriterion("bean_name >=", value, "beanName"); return (Criteria) this; } public Criteria andBeanNameLessThan(String value) { addCriterion("bean_name <", value, "beanName"); return (Criteria) this; } public Criteria andBeanNameLessThanOrEqualTo(String value) { addCriterion("bean_name <=", value, "beanName"); return (Criteria) this; } public Criteria andBeanNameLike(String value) { addCriterion("bean_name like", value, "beanName"); return (Criteria) this; } public Criteria andBeanNameNotLike(String value) { addCriterion("bean_name not like", value, "beanName"); return (Criteria) this; } public Criteria andBeanNameIn(List<String> values) { addCriterion("bean_name in", values, "beanName"); return (Criteria) this; } public Criteria andBeanNameNotIn(List<String> values) { addCriterion("bean_name not in", values, "beanName"); return (Criteria) this; } public Criteria andBeanNameBetween(String value1, String value2) { addCriterion("bean_name between", value1, value2, "beanName"); return (Criteria) this; } public Criteria andBeanNameNotBetween(String value1, String value2) { addCriterion("bean_name not between", value1, value2, "beanName"); return (Criteria) this; } public Criteria andParamsIsNull() { addCriterion("params is null"); return (Criteria) this; } public Criteria andParamsIsNotNull() { addCriterion("params is not null"); return (Criteria) this; } public Criteria andParamsEqualTo(String value) { addCriterion("params =", value, "params"); return (Criteria) this; } public Criteria andParamsNotEqualTo(String value) { addCriterion("params <>", value, "params"); return (Criteria) this; } public Criteria andParamsGreaterThan(String value) { addCriterion("params >", value, "params"); return (Criteria) this; } public Criteria andParamsGreaterThanOrEqualTo(String value) { addCriterion("params >=", value, "params"); return (Criteria) this; } public Criteria andParamsLessThan(String value) { addCriterion("params <", value, "params"); return (Criteria) this; } public Criteria andParamsLessThanOrEqualTo(String value) { addCriterion("params <=", value, "params"); return (Criteria) this; } public Criteria andParamsLike(String value) { addCriterion("params like", value, "params"); return (Criteria) this; } public Criteria andParamsNotLike(String value) { addCriterion("params not like", value, "params"); return (Criteria) this; } public Criteria andParamsIn(List<String> values) { addCriterion("params in", values, "params"); return (Criteria) this; } public Criteria andParamsNotIn(List<String> values) { addCriterion("params not in", values, "params"); return (Criteria) this; } public Criteria andParamsBetween(String value1, String value2) { addCriterion("params between", value1, value2, "params"); return (Criteria) this; } public Criteria andParamsNotBetween(String value1, String value2) { addCriterion("params not between", value1, value2, "params"); return (Criteria) this; } public Criteria andStatusIsNull() { addCriterion("status is null"); return (Criteria) this; } public Criteria andStatusIsNotNull() { addCriterion("status is not null"); return (Criteria) this; } public Criteria andStatusEqualTo(Byte value) { addCriterion("status =", value, "status"); return (Criteria) this; } public Criteria andStatusNotEqualTo(Byte value) { addCriterion("status <>", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThan(Byte value) { addCriterion("status >", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThanOrEqualTo(Byte value) { addCriterion("status >=", value, "status"); return (Criteria) this; } public Criteria andStatusLessThan(Byte value) { addCriterion("status <", value, "status"); return (Criteria) this; } public Criteria andStatusLessThanOrEqualTo(Byte value) { addCriterion("status <=", value, "status"); return (Criteria) this; } public Criteria andStatusIn(List<Byte> values) { addCriterion("status in", values, "status"); return (Criteria) this; } public Criteria andStatusNotIn(List<Byte> values) { addCriterion("status not in", values, "status"); return (Criteria) this; } public Criteria andStatusBetween(Byte value1, Byte value2) { addCriterion("status between", value1, value2, "status"); return (Criteria) this; } public Criteria andStatusNotBetween(Byte value1, Byte value2) { addCriterion("status not between", value1, value2, "status"); return (Criteria) this; } public Criteria andErrorIsNull() { addCriterion("error is null"); return (Criteria) this; } public Criteria andErrorIsNotNull() { addCriterion("error is not null"); return (Criteria) this; } public Criteria andErrorEqualTo(String value) { addCriterion("error =", value, "error"); return (Criteria) this; } public Criteria andErrorNotEqualTo(String value) { addCriterion("error <>", value, "error"); return (Criteria) this; } public Criteria andErrorGreaterThan(String value) { addCriterion("error >", value, "error"); return (Criteria) this; } public Criteria andErrorGreaterThanOrEqualTo(String value) { addCriterion("error >=", value, "error"); return (Criteria) this; } public Criteria andErrorLessThan(String value) { addCriterion("error <", value, "error"); return (Criteria) this; } public Criteria andErrorLessThanOrEqualTo(String value) { addCriterion("error <=", value, "error"); return (Criteria) this; } public Criteria andErrorLike(String value) { addCriterion("error like", value, "error"); return (Criteria) this; } public Criteria andErrorNotLike(String value) { addCriterion("error not like", value, "error"); return (Criteria) this; } public Criteria andErrorIn(List<String> values) { addCriterion("error in", values, "error"); return (Criteria) this; } public Criteria andErrorNotIn(List<String> values) { addCriterion("error not in", values, "error"); return (Criteria) this; } public Criteria andErrorBetween(String value1, String value2) { addCriterion("error between", value1, value2, "error"); return (Criteria) this; } public Criteria andErrorNotBetween(String value1, String value2) { addCriterion("error not between", value1, value2, "error"); return (Criteria) this; } public Criteria andTimesIsNull() { addCriterion("times is null"); return (Criteria) this; } public Criteria andTimesIsNotNull() { addCriterion("times is not null"); return (Criteria) this; } public Criteria andTimesEqualTo(Integer value) { addCriterion("times =", value, "times"); return (Criteria) this; } public Criteria andTimesNotEqualTo(Integer value) { addCriterion("times <>", value, "times"); return (Criteria) this; } public Criteria andTimesGreaterThan(Integer value) { addCriterion("times >", value, "times"); return (Criteria) this; } public Criteria andTimesGreaterThanOrEqualTo(Integer value) { addCriterion("times >=", value, "times"); return (Criteria) this; } public Criteria andTimesLessThan(Integer value) { addCriterion("times <", value, "times"); return (Criteria) this; } public Criteria andTimesLessThanOrEqualTo(Integer value) { addCriterion("times <=", value, "times"); return (Criteria) this; } public Criteria andTimesIn(List<Integer> values) { addCriterion("times in", values, "times"); return (Criteria) this; } public Criteria andTimesNotIn(List<Integer> values) { addCriterion("times not in", values, "times"); return (Criteria) this; } public Criteria andTimesBetween(Integer value1, Integer value2) { addCriterion("times between", value1, value2, "times"); return (Criteria) this; } public Criteria andTimesNotBetween(Integer value1, Integer value2) { addCriterion("times not between", value1, value2, "times"); return (Criteria) this; } public Criteria andCreateTimeIsNull() { addCriterion("create_time is null"); return (Criteria) this; } public Criteria andCreateTimeIsNotNull() { addCriterion("create_time is not null"); return (Criteria) this; } public Criteria andCreateTimeEqualTo(Date value) { addCriterion("create_time =", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotEqualTo(Date value) { addCriterion("create_time <>", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThan(Date value) { addCriterion("create_time >", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) { addCriterion("create_time >=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThan(Date value) { addCriterion("create_time <", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThanOrEqualTo(Date value) { addCriterion("create_time <=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeIn(List<Date> values) { addCriterion("create_time in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotIn(List<Date> values) { addCriterion("create_time not in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeBetween(Date value1, Date value2) { addCriterion("create_time between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotBetween(Date value1, Date value2) { addCriterion("create_time not between", value1, value2, "createTime"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
vincentjava/middle-ware-parent
ware-quart-job/src/main/java/com/quart/job/entity/ScheduleJobLogExample.java
Java
unknown
22,023
package com.quart.job.mapper; import com.quart.job.entity.ScheduleJobLogBean; import com.quart.job.entity.ScheduleJobLogExample; import java.util.List; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; @Mapper public interface ScheduleJobLogMapper { int countByExample(ScheduleJobLogExample example); int deleteByExample(ScheduleJobLogExample example); int deleteByPrimaryKey(Long logId); int insert(ScheduleJobLogBean record); int insertSelective(ScheduleJobLogBean record); List<ScheduleJobLogBean> selectByExample(ScheduleJobLogExample example); ScheduleJobLogBean selectByPrimaryKey(Long logId); int updateByExampleSelective(@Param("record") ScheduleJobLogBean record, @Param("example") ScheduleJobLogExample example); int updateByExample(@Param("record") ScheduleJobLogBean record, @Param("example") ScheduleJobLogExample example); int updateByPrimaryKeySelective(ScheduleJobLogBean record); int updateByPrimaryKey(ScheduleJobLogBean record); }
vincentjava/middle-ware-parent
ware-quart-job/src/main/java/com/quart/job/mapper/ScheduleJobLogMapper.java
Java
unknown
1,044
package com.quart.job.mapper; import com.quart.job.entity.ScheduleJobBean; import com.quart.job.entity.ScheduleJobExample; import java.util.List; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; @Mapper public interface ScheduleJobMapper { int countByExample(ScheduleJobExample example); int deleteByExample(ScheduleJobExample example); int deleteByPrimaryKey(Long jobId); int insert(ScheduleJobBean record); int insertSelective(ScheduleJobBean record); List<ScheduleJobBean> selectByExample(ScheduleJobExample example); ScheduleJobBean selectByPrimaryKey(Long jobId); int updateByExampleSelective(@Param("record") ScheduleJobBean record, @Param("example") ScheduleJobExample example); int updateByExample(@Param("record") ScheduleJobBean record, @Param("example") ScheduleJobExample example); int updateByPrimaryKeySelective(ScheduleJobBean record); int updateByPrimaryKey(ScheduleJobBean record); }
vincentjava/middle-ware-parent
ware-quart-job/src/main/java/com/quart/job/mapper/ScheduleJobMapper.java
Java
unknown
997
package com.quart.job.service; import com.quart.job.entity.ScheduleJobLogBean; public interface ScheduleJobLogService { // 保存 int insert(ScheduleJobLogBean record); }
vincentjava/middle-ware-parent
ware-quart-job/src/main/java/com/quart/job/service/ScheduleJobLogService.java
Java
unknown
181
package com.quart.job.service; import com.quart.job.entity.ScheduleJobBean; import com.quart.job.entity.ScheduleJobExample; import java.util.List; public interface ScheduleJobService { // 主键查询 ScheduleJobBean selectByPrimaryKey(Long jobId); // 列表查询 List<ScheduleJobBean> selectByExample(ScheduleJobExample example); // 保存 int insert(ScheduleJobBean record); // 更新 int updateByPrimaryKeySelective(ScheduleJobBean record); // 停止 void pauseJob (Long jobId) ; // 恢复 void resumeJob (Long jobId) ; // 执行 void run (Long jobId) ; // 删除 void delete (Long jobId) ; }
vincentjava/middle-ware-parent
ware-quart-job/src/main/java/com/quart/job/service/ScheduleJobService.java
Java
unknown
663
package com.quart.job.service.impl; import com.quart.job.entity.ScheduleJobLogBean; import com.quart.job.mapper.ScheduleJobLogMapper; import com.quart.job.service.ScheduleJobLogService; import org.springframework.stereotype.Service; import javax.annotation.Resource; @Service("scheduleJobLogService") public class ScheduleJobLogServiceImpl implements ScheduleJobLogService { @Resource private ScheduleJobLogMapper scheduleJobLogMapper ; @Override public int insert(ScheduleJobLogBean record) { return scheduleJobLogMapper.insert(record); } }
vincentjava/middle-ware-parent
ware-quart-job/src/main/java/com/quart/job/service/impl/ScheduleJobLogServiceImpl.java
Java
unknown
574
package com.quart.job.service.impl; import com.quart.job.entity.ScheduleJobBean; import com.quart.job.entity.ScheduleJobExample; import com.quart.job.mapper.ScheduleJobMapper; import com.quart.job.service.ScheduleJobService; import com.quart.job.utils.ScheduleUtil; import org.quartz.CronTrigger; import org.quartz.Scheduler; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.PostConstruct; import javax.annotation.Resource; import java.util.List; @Service public class ScheduleJobServiceImpl implements ScheduleJobService { @Resource private Scheduler scheduler ; @Resource private ScheduleJobMapper scheduleJobMapper ; /** * 定时器初始化 */ @PostConstruct public void init (){ ScheduleJobExample example = new ScheduleJobExample() ; List<ScheduleJobBean> scheduleJobBeanList = scheduleJobMapper.selectByExample(example) ; for (ScheduleJobBean scheduleJobBean : scheduleJobBeanList) { CronTrigger cronTrigger = ScheduleUtil.getCronTrigger(scheduler,scheduleJobBean.getJobId()) ; if (cronTrigger == null){ ScheduleUtil.createJob(scheduler,scheduleJobBean); } else { ScheduleUtil.updateJob(scheduler,scheduleJobBean); } } } @Override public ScheduleJobBean selectByPrimaryKey(Long jobId) { return scheduleJobMapper.selectByPrimaryKey(jobId); } @Override public List<ScheduleJobBean> selectByExample(ScheduleJobExample example) { return scheduleJobMapper.selectByExample(example); } @Override @Transactional(rollbackFor = Exception.class) public int insert(ScheduleJobBean record) { ScheduleUtil.createJob(scheduler,record); return scheduleJobMapper.insert(record); } @Override @Transactional(rollbackFor = Exception.class) public int updateByPrimaryKeySelective(ScheduleJobBean record) { ScheduleUtil.updateJob(scheduler,record); return scheduleJobMapper.updateByPrimaryKeySelective(record); } @Override @Transactional(rollbackFor = Exception.class) public void pauseJob(Long jobId) { ScheduleJobBean scheduleJobBean = scheduleJobMapper.selectByPrimaryKey(jobId) ; ScheduleUtil.pauseJob(scheduler,jobId); scheduleJobBean.setStatus(1); scheduleJobMapper.updateByPrimaryKeySelective(scheduleJobBean) ; } @Override @Transactional(rollbackFor = Exception.class) public void resumeJob(Long jobId) { ScheduleJobBean scheduleJobBean = scheduleJobMapper.selectByPrimaryKey(jobId) ; ScheduleUtil.resumeJob(scheduler,jobId); scheduleJobBean.setStatus(0); scheduleJobMapper.updateByPrimaryKeySelective(scheduleJobBean) ; } @Override @Transactional(rollbackFor = Exception.class) public void run(Long jobId) { ScheduleJobBean scheduleJobBean = scheduleJobMapper.selectByPrimaryKey(jobId) ; ScheduleUtil.run(scheduler,scheduleJobBean); } @Override @Transactional(rollbackFor = Exception.class) public void delete(Long jobId) { ScheduleUtil.deleteJob(scheduler, jobId); scheduleJobMapper.deleteByPrimaryKey(jobId) ; } }
vincentjava/middle-ware-parent
ware-quart-job/src/main/java/com/quart/job/service/impl/ScheduleJobServiceImpl.java
Java
unknown
3,327
package com.quart.job.task; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.Date; @Component("getTimeTask") public class GetTimeTask implements TaskService { private static final Logger LOG = LoggerFactory.getLogger(GetTimeTask.class.getName()) ; private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ; @Override public void run(String params) { LOG.info("Params === >> " + params); LOG.info("当前时间::::"+format.format(new Date())); } }
vincentjava/middle-ware-parent
ware-quart-job/src/main/java/com/quart/job/task/GetTimeTask.java
Java
unknown
643
package com.quart.job.task; public interface TaskService { void run(String params); }
vincentjava/middle-ware-parent
ware-quart-job/src/main/java/com/quart/job/task/TaskService.java
Java
unknown
91
package com.quart.job.utils; import com.quart.job.entity.ScheduleJobBean; import org.quartz.*; /** * 定时器工具类 */ public class ScheduleUtil { private ScheduleUtil (){} private static final String SCHEDULE_NAME = "HUSKY_" ; /** * 触发器 KEY */ public static TriggerKey getTriggerKey(Long jobId){ return TriggerKey.triggerKey(SCHEDULE_NAME+jobId) ; } /** * 定时器 Key */ public static JobKey getJobKey (Long jobId){ return JobKey.jobKey(SCHEDULE_NAME+jobId) ; } /** * 表达式触发器 */ public static CronTrigger getCronTrigger (Scheduler scheduler,Long jobId){ try { return (CronTrigger)scheduler.getTrigger(getTriggerKey(jobId)) ; } catch (SchedulerException e){ throw new RuntimeException("getCronTrigger Fail",e) ; } } /** * 创建定时器 */ public static void createJob (Scheduler scheduler, ScheduleJobBean scheduleJob){ try { // 构建定时器 JobDetail jobDetail = JobBuilder.newJob(TaskJobLog.class).withIdentity(getJobKey(scheduleJob.getJobId())).build() ; CronScheduleBuilder scheduleBuilder = CronScheduleBuilder .cronSchedule(scheduleJob.getCronExpression()) .withMisfireHandlingInstructionDoNothing() ; CronTrigger trigger = TriggerBuilder.newTrigger() .withIdentity(getTriggerKey(scheduleJob.getJobId())) .withSchedule(scheduleBuilder).build() ; jobDetail.getJobDataMap().put(ScheduleJobBean.JOB_PARAM_KEY,scheduleJob); scheduler.scheduleJob(jobDetail,trigger) ; // 如果该定时器处于暂停状态 if (scheduleJob.getStatus() == 1){ pauseJob(scheduler,scheduleJob.getJobId()) ; } } catch (SchedulerException e){ throw new RuntimeException("createJob Fail",e) ; } } /** * 更新定时任务 */ public static void updateJob(Scheduler scheduler, ScheduleJobBean scheduleJob) { try { // 构建定时器 TriggerKey triggerKey = getTriggerKey(scheduleJob.getJobId()); CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression()) .withMisfireHandlingInstructionDoNothing(); CronTrigger trigger = getCronTrigger(scheduler, scheduleJob.getJobId()); trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build(); trigger.getJobDataMap().put(ScheduleJobBean.JOB_PARAM_KEY, scheduleJob); scheduler.rescheduleJob(triggerKey, trigger); // 如果该定时器处于暂停状态 if(scheduleJob.getStatus() == 1){ pauseJob(scheduler, scheduleJob.getJobId()); } } catch (SchedulerException e) { throw new RuntimeException("updateJob Fail",e) ; } } /** * 停止定时器 */ public static void pauseJob (Scheduler scheduler,Long jobId){ try { scheduler.pauseJob(getJobKey(jobId)); } catch (SchedulerException e){ throw new RuntimeException("pauseJob Fail",e) ; } } /** * 恢复定时器 */ public static void resumeJob (Scheduler scheduler,Long jobId){ try { scheduler.resumeJob(getJobKey(jobId)); } catch (SchedulerException e){ throw new RuntimeException("resumeJob Fail",e) ; } } /** * 删除定时器 */ public static void deleteJob (Scheduler scheduler,Long jobId){ try { scheduler.deleteJob(getJobKey(jobId)); } catch (SchedulerException e){ throw new RuntimeException("deleteJob Fail",e) ; } } /** * 执行定时器 */ public static void run (Scheduler scheduler, ScheduleJobBean scheduleJob){ try { JobDataMap dataMap = new JobDataMap() ; dataMap.put(ScheduleJobBean.JOB_PARAM_KEY,scheduleJob); scheduler.triggerJob(getJobKey(scheduleJob.getJobId()),dataMap); } catch (SchedulerException e){ throw new RuntimeException("run Fail",e) ; } } }
vincentjava/middle-ware-parent
ware-quart-job/src/main/java/com/quart/job/utils/ScheduleUtil.java
Java
unknown
4,382
package com.quart.job.utils; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class SpringContextUtil implements ApplicationContextAware { public static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringContextUtil.applicationContext = applicationContext; } public static Object getBean(String name) { return applicationContext.getBean(name); } public static <T> T getBean(String name, Class<T> requiredType) { return applicationContext.getBean(name, requiredType); } public static boolean containsBean(String name) { return applicationContext.containsBean(name); } public static boolean isSingleton(String name) { return applicationContext.isSingleton(name); } public static Class<? extends Object> getType(String name) { return applicationContext.getType(name); } }
vincentjava/middle-ware-parent
ware-quart-job/src/main/java/com/quart/job/utils/SpringContextUtil.java
Java
unknown
1,176
package com.quart.job.utils; import com.quart.job.entity.ScheduleJobBean; import com.quart.job.entity.ScheduleJobLogBean; import com.quart.job.service.ScheduleJobLogService; import org.quartz.JobExecutionContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.quartz.QuartzJobBean; import java.lang.reflect.Method; import java.util.Date; /** * 定时器执行日志记录 */ public class TaskJobLog extends QuartzJobBean { private static final Logger LOG = LoggerFactory.getLogger(TaskJobLog.class) ; @Override protected void executeInternal(JobExecutionContext context) { ScheduleJobBean jobBean = (ScheduleJobBean)context.getMergedJobDataMap().get(ScheduleJobBean.JOB_PARAM_KEY) ; ScheduleJobLogService scheduleJobLogService = (ScheduleJobLogService)SpringContextUtil.getBean("scheduleJobLogService") ; // 定时器日志记录 ScheduleJobLogBean logBean = new ScheduleJobLogBean () ; logBean.setJobId(jobBean.getJobId()); logBean.setBeanName(jobBean.getBeanName()); logBean.setParams(jobBean.getParams()); logBean.setCreateTime(new Date()); long beginTime = System.currentTimeMillis() ; try { // 加载并执行定时器的 run 方法 Object target = SpringContextUtil.getBean(jobBean.getBeanName()); Method method = target.getClass().getDeclaredMethod("run", String.class); method.invoke(target, jobBean.getParams()); long executeTime = System.currentTimeMillis() - beginTime; logBean.setTimes((int)executeTime); logBean.setStatus(0); LOG.info("定时器 === >> "+jobBean.getJobId()+"执行成功,耗时 === >> " + executeTime); } catch (Exception e){ // 异常信息 long executeTime = System.currentTimeMillis() - beginTime; logBean.setTimes((int)executeTime); logBean.setStatus(1); logBean.setError(e.getMessage()); } finally { scheduleJobLogService.insert(logBean) ; } } }
vincentjava/middle-ware-parent
ware-quart-job/src/main/java/com/quart/job/utils/TaskJobLog.java
Java
unknown
2,122
package com.redis.cluster; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; @SpringBootApplication(exclude= {DataSourceAutoConfiguration.class}) public class RedisApplication { public static void main(String[] args) { SpringApplication.run(RedisApplication.class,args) ; } }
vincentjava/middle-ware-parent
ware-redis-cluster/src/main/java/com/redis/cluster/RedisApplication.java
Java
unknown
444
package com.redis.cluster.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.StringRedisTemplate; @Configuration public class RedisConfig { @Bean public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) { StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(); stringRedisTemplate.setConnectionFactory(factory); return stringRedisTemplate; } }
vincentjava/middle-ware-parent
ware-redis-cluster/src/main/java/com/redis/cluster/config/RedisConfig.java
Java
unknown
604