gorealis v2 refactor (#5)

* Changing default timeout for start maintenance.

* Upgrading dependencies to gorealis v2 and thrift  0.12.0

* Refactored to update to gorealis v2.
This commit is contained in:
Renan DelValle 2018-12-27 11:31:51 -08:00 committed by GitHub
parent ad4dd9606e
commit 6ab5c9334d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
1335 changed files with 137431 additions and 61530 deletions

View file

@ -58,6 +58,10 @@ if WITH_HAXE
SUBDIRS += haxe
endif
if WITH_DOTNETCORE
SUBDIRS += netcore
endif
if WITH_GO
SUBDIRS += go
endif
@ -70,6 +74,14 @@ if WITH_DART
SUBDIRS += dart
endif
if WITH_RS
SUBDIRS += rs
endif
if WITH_CL
SUBDIRS += cl
endif
#
# generate html for ThriftTest.thrift
#

View file

@ -24,11 +24,9 @@ BUILT_SOURCES = \
gen-c_glib/shared_types.h \
gen-c_glib/tutorial_types.h
AM_CFLAGS = -g -Wall -Wextra -pedantic $(GLIB_CFLAGS) $(GOBJECT_CFLAGS) @GCOV_CFLAGS@
AM_CFLAGS = -g -Wall -Wextra -pedantic $(GLIB_CFLAGS) $(GOBJECT_CFLAGS) $(OPENSSL_INCLUDES) @GCOV_CFLAGS@
AM_CPPFLAGS = -I$(top_srcdir)/lib/c_glib/src -Igen-c_glib
AM_LDFLAGS = $(GLIB_LIBS) $(GOBJECT_LIBS) @GCOV_LDFLAGS@
THRIFT = $(top_builddir)/compiler/cpp/thrift
AM_LDFLAGS = $(GLIB_LIBS) $(GOBJECT_LIBS) $(OPENSSL_LDFLAGS) $(OPENSSL_LIBS) @GCOV_LDFLAGS@
noinst_LTLIBRARIES = \
libtutorialgencglib.la
@ -55,6 +53,7 @@ noinst_PROGRAMS = \
tutorial_server_SOURCES = \
c_glib_server.c
tutorial_server_LDFLAGS = $(OPENSSL_LIBS)
tutorial_server_LDADD = \
libtutorialgencglib.la \

65
vendor/git.apache.org/thrift.git/tutorial/cl/Makefile.am generated vendored Executable file
View file

@ -0,0 +1,65 @@
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
setup-local-lisp-env: ensure-externals.sh
bash ensure-externals.sh
gen-cl: $(top_srcdir)/tutorial/tutorial.thrift
$(THRIFT) --gen cl -r $<
ALL_FILE_PREREQS = \
load-locally.lisp \
make-tutorial-server.lisp \
make-tutorial-client.lisp \
shared-implementation.lisp \
thrift-tutorial.asd \
tutorial-implementation.lisp
# NOTE: the server and client cannot be built in parallel
# because on loading the make-tutorial-* scripts SBCL will
# attempt to compile their dependencies. Unfortunately,
# because their dependencies are shared, parallel jobs can
# end up overwriting or corrupting the compiled files
all-local: gen-cl setup-local-lisp-env $(ALL_FILE_PREREQS)
$(SBCL) --script make-tutorial-server.lisp
$(SBCL) --script make-tutorial-client.lisp
tutorialserver: all
./TutorialServer
tutorialclient: all
./TutorialClient
clean-local:
-$(RM) -r gen-*
-$(RM) -r externals
-$(RM) -r quicklisp
-$(RM) -r lib
-$(RM) quicklisp.lisp
-$(RM) backport-update.zip
-$(RM) shared-implementation.fasl
-$(RM) tutorial-implementation.fasl
-$(RM) TutorialServer
-$(RM) TutorialClient
EXTRA_DIST = \
tutorial-implementation.lisp \
shared-implementation.lisp \
thrift-tutorial.asd \
make-tutorial-server.lisp \
make-tutorial-client.lisp

View file

@ -0,0 +1 @@
../../lib/cl/ensure-externals.sh

View file

@ -0,0 +1,22 @@
(in-package #:cl-user)
;;;; 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.
;;;; Just a script for loading the library itself, using bundled dependencies.
;;;; This is an identical copy of the file in lib/cl.
(require "asdf")
(load (merge-pathnames "externals/bundle.lisp" *load-truename*))
(asdf:load-asd (merge-pathnames "lib/de.setf.thrift-backport-update/thrift.asd" *load-truename*))
(asdf:load-system :thrift)

View file

@ -0,0 +1,51 @@
(in-package #:cl-user)
;;;; 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.
(require "asdf")
(load (merge-pathnames "load-locally.lisp" *load-truename*))
(asdf:load-system :net.didierverna.clon)
(asdf:load-asd (merge-pathnames "gen-cl/shared/thrift-gen-shared.asd" *load-truename*))
(asdf:load-asd (merge-pathnames "gen-cl/tutorial/thrift-gen-tutorial.asd" *load-truename*))
(asdf:load-asd (merge-pathnames "thrift-tutorial.asd" *load-truename*))
(asdf:load-system :thrift-tutorial)
(net.didierverna.clon:nickname-package)
(defun main ()
"Entry point for the binary."
(thrift:with-client (prot #u"thrift://127.0.0.1:9090")
(tutorial.calculator:ping prot)
(format t "ping()~%")
(format t "1 + 1 = ~a~%" (tutorial.calculator:add prot 1 1))
(let ((work-instance (tutorial:make-work :num1 5
:num2 0
:op tutorial:operation.divide
:comment "Booya!")))
(handler-case (format t
"5 / 0 = ~a - Oh, really? An exception should have been thrown here.~%"
(tutorial.calculator:calculate prot 1 work-instance))
(tutorial:invalidoperation (e)
(format t "---~%(Expected) Invalid Operation caught: ~%~a~%---~%" e))))
(let ((work-instance (tutorial:make-work :num1 15
:num2 10
:op tutorial:operation.subtract
:comment "Playing nice this time.")))
(handler-case (format t
"15 - 10 = ~a~%"
(tutorial.calculator:calculate prot 1 work-instance))
(tutorial:invalidoperation (e)
(format t "---~%(Unexpected) Invalid Operation caught: ~%~a~%---~%" e))))
(format t "Check log: ~a~%" (shared.shared-service:get-struct prot 1))))
(clon:dump "TutorialClient" main)

View file

@ -0,0 +1,29 @@
(in-package #:cl-user)
;;;; 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.
(require "asdf")
(load (merge-pathnames "load-locally.lisp" *load-truename*))
(asdf:load-system :net.didierverna.clon)
(asdf:load-asd (merge-pathnames "gen-cl/shared/thrift-gen-shared.asd" *load-truename*))
(asdf:load-asd (merge-pathnames "gen-cl/tutorial/thrift-gen-tutorial.asd" *load-truename*))
(asdf:load-asd (merge-pathnames "thrift-tutorial.asd" *load-truename*))
(asdf:load-system :thrift-tutorial)
(net.didierverna.clon:nickname-package)
(defun main ()
"Entry point for the binary."
(thrift:serve #u"thrift://127.0.0.1:9090" tutorial:calculator))
(clon:dump "TutorialServer" main)

View file

@ -0,0 +1,25 @@
(in-package #:shared-implementation)
;;;; 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.
(defvar *structs* (make-hash-table))
(defun shared.shared-service-implementation:get-struct (key)
(format t "getStruct(~a)~%" key)
(gethash key *structs*))
(defun add-log (key value)
(setf (gethash key *structs*)
(make-instance 'shared:sharedstruct
:key key
:value (write-to-string value))))

View file

@ -0,0 +1,17 @@
;;;; 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.
(asdf:defsystem #:thrift-tutorial
:depends-on (#:thrift-gen-tutorial)
:serial t
:components ((:file "shared-implementation")
(:file "tutorial-implementation")))

View file

@ -0,0 +1,41 @@
(in-package #:tutorial-implementation)
;;;; 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.
(defun tutorial.calculator-implementation:ping ()
(format t "ping()~%"))
(defun tutorial.calculator-implementation:add (num1 num2)
(format t "add(~a, ~a)~%" num1 num2)
(+ num1 num2))
(defun tutorial.calculator-implementation:calculate (logid work)
(format t "calculate(~a, ~a)~%" logid work)
(handler-case
(let* ((num1 (tutorial:work-num1 work))
(num2 (tutorial:work-num2 work))
(op (tutorial:work-op work))
(result
(cond
((= op tutorial:operation.add) (+ num1 num2))
((= op tutorial:operation.subtract) (- num1 num2))
((= op tutorial:operation.multiply) (* num1 num2))
((= op tutorial:operation.divide) (/ num1 num2)))))
(shared-implementation::add-log logid result)
result)
(division-by-zero () (error 'tutorial:invalidoperation
:why "Division by zero."
:what-op (tutorial:work-op work)))))
(defun tutorial.calculator-implementation:zip ()
(format t "zip()~%"))

View file

@ -44,9 +44,13 @@ add_custom_command(OUTPUT gen-cpp/Calculator.cpp gen-cpp/SharedService.cpp gen-c
add_executable(TutorialServer CppServer.cpp)
target_link_libraries(TutorialServer tutorialgencpp)
LINK_AGAINST_THRIFT_LIBRARY(TutorialServer thrift)
target_link_libraries(TutorialServer ${ZLIB_LIBRARIES})
if (ZLIB_FOUND)
target_link_libraries(TutorialServer ${ZLIB_LIBRARIES})
endif ()
add_executable(TutorialClient CppClient.cpp)
target_link_libraries(TutorialClient tutorialgencpp)
LINK_AGAINST_THRIFT_LIBRARY(TutorialClient thrift)
target_link_libraries(TutorialClient ${ZLIB_LIBRARIES})
if (ZLIB_FOUND)
target_link_libraries(TutorialClient ${ZLIB_LIBRARIES})
endif ()

View file

@ -22,6 +22,7 @@
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/transport/TSocket.h>
#include <thrift/transport/TTransportUtils.h>
#include <thrift/stdcxx.h>
#include "../gen-cpp/Calculator.h"
@ -34,9 +35,9 @@ using namespace tutorial;
using namespace shared;
int main() {
boost::shared_ptr<TTransport> socket(new TSocket("localhost", 9090));
boost::shared_ptr<TTransport> transport(new TBufferedTransport(socket));
boost::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
stdcxx::shared_ptr<TTransport> socket(new TSocket("localhost", 9090));
stdcxx::shared_ptr<TTransport> transport(new TBufferedTransport(socket));
stdcxx::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
CalculatorClient client(protocol);
try {

View file

@ -27,8 +27,7 @@
#include <thrift/transport/TSocket.h>
#include <thrift/transport/TTransportUtils.h>
#include <thrift/TToString.h>
#include <boost/make_shared.hpp>
#include <thrift/stdcxx.h>
#include <iostream>
#include <stdexcept>
@ -118,7 +117,7 @@ class CalculatorCloneFactory : virtual public CalculatorIfFactory {
virtual ~CalculatorCloneFactory() {}
virtual CalculatorIf* getHandler(const ::apache::thrift::TConnectionInfo& connInfo)
{
boost::shared_ptr<TSocket> sock = boost::dynamic_pointer_cast<TSocket>(connInfo.transport);
stdcxx::shared_ptr<TSocket> sock = stdcxx::dynamic_pointer_cast<TSocket>(connInfo.transport);
cout << "Incoming connection\n";
cout << "\tSocketInfo: " << sock->getSocketInfo() << "\n";
cout << "\tPeerHost: " << sock->getPeerHost() << "\n";
@ -133,18 +132,18 @@ class CalculatorCloneFactory : virtual public CalculatorIfFactory {
int main() {
TThreadedServer server(
boost::make_shared<CalculatorProcessorFactory>(boost::make_shared<CalculatorCloneFactory>()),
boost::make_shared<TServerSocket>(9090), //port
boost::make_shared<TBufferedTransportFactory>(),
boost::make_shared<TBinaryProtocolFactory>());
stdcxx::make_shared<CalculatorProcessorFactory>(stdcxx::make_shared<CalculatorCloneFactory>()),
stdcxx::make_shared<TServerSocket>(9090), //port
stdcxx::make_shared<TBufferedTransportFactory>(),
stdcxx::make_shared<TBinaryProtocolFactory>());
/*
// if you don't need per-connection state, do the following instead
TThreadedServer server(
boost::make_shared<CalculatorProcessor>(boost::make_shared<CalculatorHandler>()),
boost::make_shared<TServerSocket>(9090), //port
boost::make_shared<TBufferedTransportFactory>(),
boost::make_shared<TBinaryProtocolFactory>());
stdcxx::make_shared<CalculatorProcessor>(stdcxx::make_shared<CalculatorHandler>()),
stdcxx::make_shared<TServerSocket>(9090), //port
stdcxx::make_shared<TBufferedTransportFactory>(),
stdcxx::make_shared<TBinaryProtocolFactory>());
*/
/**
@ -152,25 +151,25 @@ int main() {
// This server only allows one connection at a time, but spawns no threads
TSimpleServer server(
boost::make_shared<CalculatorProcessor>(boost::make_shared<CalculatorHandler>()),
boost::make_shared<TServerSocket>(9090),
boost::make_shared<TBufferedTransportFactory>(),
boost::make_shared<TBinaryProtocolFactory>());
stdcxx::make_shared<CalculatorProcessor>(stdcxx::make_shared<CalculatorHandler>()),
stdcxx::make_shared<TServerSocket>(9090),
stdcxx::make_shared<TBufferedTransportFactory>(),
stdcxx::make_shared<TBinaryProtocolFactory>());
const int workerCount = 4;
boost::shared_ptr<ThreadManager> threadManager =
stdcxx::shared_ptr<ThreadManager> threadManager =
ThreadManager::newSimpleThreadManager(workerCount);
threadManager->threadFactory(
boost::make_shared<PlatformThreadFactory>());
stdcxx::make_shared<PlatformThreadFactory>());
threadManager->start();
// This server allows "workerCount" connection at a time, and reuses threads
TThreadPoolServer server(
boost::make_shared<CalculatorProcessorFactory>(boost::make_shared<CalculatorCloneFactory>()),
boost::make_shared<TServerSocket>(9090),
boost::make_shared<TBufferedTransportFactory>(),
boost::make_shared<TBinaryProtocolFactory>(),
stdcxx::make_shared<CalculatorProcessorFactory>(stdcxx::make_shared<CalculatorCloneFactory>()),
stdcxx::make_shared<TServerSocket>(9090),
stdcxx::make_shared<TBufferedTransportFactory>(),
stdcxx::make_shared<TBinaryProtocolFactory>(),
threadManager);
*/

View file

@ -61,8 +61,6 @@ TutorialClient_LDADD = \
#
# Common thrift code generation rules
#
THRIFT = $(top_builddir)/compiler/cpp/thrift
gen-cpp/Calculator.cpp gen-cpp/SharedService.cpp gen-cpp/shared_constants.cpp gen-cpp/shared_types.cpp gen-cpp/tutorial_constants.cpp gen-cpp/tutorial_types.cpp: $(top_srcdir)/tutorial/tutorial.thrift
$(THRIFT) --gen cpp -r $<

View file

@ -27,9 +27,9 @@ using System.Runtime.InteropServices;
[assembly: AssemblyTitle("CsharpClient")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CsharpClient")]
[assembly: AssemblyCopyright("Copyright © 2010 The Apache Software Foundation")]
[assembly: AssemblyCompany("The Apache Software Foundation")]
[assembly: AssemblyProduct("Thrift")]
[assembly: AssemblyCopyright("The Apache Software Foundation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
@ -51,5 +51,5 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.10.0.0")]
[assembly: AssemblyFileVersion("0.10.0.0")]
[assembly: AssemblyVersion("0.12.0.0")]
[assembly: AssemblyFileVersion("0.12.0.0")]

View file

@ -27,9 +27,9 @@ using System.Runtime.InteropServices;
[assembly: AssemblyTitle("CsharpServer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CsharpServer")]
[assembly: AssemblyCopyright("Copyright © 2010 The Apache Software Foundation")]
[assembly: AssemblyCompany("The Apache Software Foundation")]
[assembly: AssemblyProduct("Thrift")]
[assembly: AssemblyCopyright("The Apache Software Foundation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
@ -51,5 +51,5 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.10.0.0")]
[assembly: AssemblyFileVersion("0.10.0.0")]
[assembly: AssemblyVersion("0.12.0.0")]
[assembly: AssemblyFileVersion("0.12.0.0")]

View file

@ -19,8 +19,6 @@
BUILT_SOURCES = gen-dart/tutorial/lib/tutorial.dart gen-dart/shared/lib/shared.dart
THRIFT = $(top_builddir)/compiler/cpp/thrift
gen-dart/tutorial/lib/tutorial.dart gen-dart/shared/lib/shared.dart: $(top_srcdir)/tutorial/tutorial.thrift
$(THRIFT) --gen dart -r $<
@ -30,6 +28,7 @@ clean-local:
$(RM) -r gen-*
find . -type d -name "packages" | xargs $(RM) -r
find . -type f -name ".packages" | xargs $(RM)
find . -type f -name "pubspec.lock" | xargs $(RM)
pub-get: pub-get-gen pub-get-client pub-get-console-client pub-get-server
@ -68,4 +67,7 @@ EXTRA_DIST = \
console_client/pubspec.yaml \
server/bin/main.dart \
server/pubspec.yaml \
console_client/.analysis_options \
client/.analysis_options \
server/.analysis_options \
build.sh

View file

@ -16,7 +16,7 @@
# under the License.
name: tutorial_client
version: 0.10.0
version: 0.12.0
description: A Dart client implementation of the Apache Thrift tutorial
author: Apache Thrift Developers <dev@thrift.apache.org>
homepage: http://thrift.apache.org

View file

@ -16,7 +16,7 @@
# under the License.
name: tutorial_console_client
version: 0.10.0
version: 0.12.0
description: >
A Dart console client to implementation of the Apache Thrift tutorial
author: Apache Thrift Developers <dev@thrift.apache.org>

View file

@ -16,7 +16,7 @@
# under the License.
name: tutorial_server
version: 0.10.0
version: 0.12.0
description: A Dart server to support the Apache Thrift tutorial
author: Apache Thrift Developers <dev@thrift.apache.org>
homepage: http://thrift.apache.org

View file

@ -26,7 +26,7 @@ uses
Generics.Collections,
Thrift in '..\..\..\lib\delphi\src\Thrift.pas',
Thrift.Collections in '..\..\..\lib\delphi\src\Thrift.Collections.pas',
Thrift.Console in '..\..\..\lib\delphi\src\Thrift.Console.pas',
Thrift.Exception in '..\..\..\lib\delphi\src\Thrift.Exception.pas',
Thrift.Utils in '..\..\..\lib\delphi\src\Thrift.Utils.pas',
Thrift.Stream in '..\..\..\lib\delphi\src\Thrift.Stream.pas',
Thrift.Protocol in '..\..\..\lib\delphi\src\Thrift.Protocol.pas',
@ -62,10 +62,10 @@ begin
transport.Open;
client.ping;
Console.WriteLine('ping()');
WriteLn('ping()');
sum := client.add( 1, 1);
Console.WriteLine( Format( '1+1=%d', [sum]));
WriteLn( Format( '1+1=%d', [sum]));
work := TWorkImpl.Create;
@ -74,11 +74,11 @@ begin
work.Num2 := 0;
try
quotient := client.calculate(1, work);
Console.WriteLine( 'Whoa we can divide by 0');
Console.WriteLine( Format('1/0=%d',[quotient]));
WriteLn( 'Whoa we can divide by 0');
WriteLn( Format('1/0=%d',[quotient]));
except
on io: TInvalidOperation
do Console.WriteLine( 'Invalid operation: ' + io.Why);
do WriteLn( 'Invalid operation: ' + io.Why);
end;
work.Op := TOperation.SUBTRACT;
@ -86,20 +86,20 @@ begin
work.Num2 := 10;
try
diff := client.calculate( 1, work);
Console.WriteLine( Format('15-10=%d', [diff]));
WriteLn( Format('15-10=%d', [diff]));
except
on io: TInvalidOperation
do Console.WriteLine( 'Invalid operation: ' + io.Why);
do WriteLn( 'Invalid operation: ' + io.Why);
end;
log := client.getStruct(1);
Console.WriteLine( Format( 'Check log: %s', [log.Value]));
WriteLn( Format( 'Check log: %s', [log.Value]));
transport.Close();
except
on e : Exception
do Console.WriteLine( e.ClassName+': '+e.Message);
do WriteLn( e.ClassName+': '+e.Message);
end;
end;

View file

@ -1,119 +1,119 @@
 <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ProjectGuid>{2B8FB3A1-2F9E-4883-8C53-0F56220B34F6}</ProjectGuid>
<MainSource>DelphiClient.dpr</MainSource>
<ProjectVersion>12.3</ProjectVersion>
<Basis>True</Basis>
<Config Condition="'$(Config)'==''">Debug</Config>
<Platform>Win32</Platform>
<AppType>Console</AppType>
<FrameworkType>None</FrameworkType>
<DCC_DCCCompiler>DCC32</DCC_DCCCompiler>
</PropertyGroup>
<PropertyGroup Condition="'$(Config)'=='Basis' or '$(Base)'!=''">
<Base>true</Base>
</PropertyGroup>
<PropertyGroup Condition="'$(Config)'=='Debug' or '$(Cfg_1)'!=''">
<Cfg_1>true</Cfg_1>
<CfgParent>Base</CfgParent>
<Base>true</Base>
</PropertyGroup>
<PropertyGroup Condition="'$(Config)'=='Release' or '$(Cfg_2)'!=''">
<Cfg_2>true</Cfg_2>
<CfgParent>Base</CfgParent>
<Base>true</Base>
</PropertyGroup>
<PropertyGroup Condition="'$(Base)'!=''">
<DCC_UnitSearchPath>..\..\..\lib\delphi\src;$(DCC_UnitSearchPath)</DCC_UnitSearchPath>
<DCC_ImageBase>00400000</DCC_ImageBase>
<DCC_DcuOutput>.\dcu\$(Config)\$(Platform)</DCC_DcuOutput>
<DCC_UnitAlias>WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;$(DCC_UnitAlias)</DCC_UnitAlias>
<DCC_ExeOutput>..\bin\$(Config)\$(Platform)</DCC_ExeOutput>
<DCC_E>false</DCC_E>
<DCC_N>false</DCC_N>
<DCC_S>false</DCC_S>
<DCC_F>false</DCC_F>
<DCC_K>false</DCC_K>
</PropertyGroup>
<PropertyGroup Condition="'$(Cfg_1)'!=''">
<DCC_Define>DEBUG;$(DCC_Define)</DCC_Define>
<DCC_Optimize>false</DCC_Optimize>
<DCC_GenerateStackFrames>true</DCC_GenerateStackFrames>
</PropertyGroup>
<PropertyGroup Condition="'$(Cfg_2)'!=''">
<DCC_LocalDebugSymbols>false</DCC_LocalDebugSymbols>
<DCC_Define>RELEASE;$(DCC_Define)</DCC_Define>
<DCC_SymbolReferenceInfo>0</DCC_SymbolReferenceInfo>
<DCC_DebugInformation>false</DCC_DebugInformation>
</PropertyGroup>
<ItemGroup>
<DelphiCompile Include="DelphiClient.dpr">
<MainSource>MainSource</MainSource>
</DelphiCompile>
<DCCReference Include="..\..\..\lib\delphi\src\Thrift.pas"/>
<DCCReference Include="..\..\..\lib\delphi\src\Thrift.Collections.pas"/>
<DCCReference Include="..\..\..\lib\delphi\src\Thrift.Console.pas"/>
<DCCReference Include="..\..\..\lib\delphi\src\Thrift.Utils.pas"/>
<DCCReference Include="..\..\..\lib\delphi\src\Thrift.Stream.pas"/>
<DCCReference Include="..\..\..\lib\delphi\src\Thrift.Protocol.pas"/>
<DCCReference Include="..\..\..\lib\delphi\src\Thrift.Server.pas"/>
<DCCReference Include="..\..\..\lib\delphi\src\Thrift.Transport.pas"/>
<DCCReference Include="..\..\gen-delphi\Shared.pas"/>
<DCCReference Include="..\..\gen-delphi\Tutorial.pas"/>
<BuildConfiguration Include="Release">
<Key>Cfg_2</Key>
<CfgParent>Base</CfgParent>
</BuildConfiguration>
<BuildConfiguration Include="Basis">
<Key>Base</Key>
</BuildConfiguration>
<BuildConfiguration Include="Debug">
<Key>Cfg_1</Key>
<CfgParent>Base</CfgParent>
</BuildConfiguration>
</ItemGroup>
<Import Condition="Exists('$(BDS)\Bin\CodeGear.Delphi.Targets')" Project="$(BDS)\Bin\CodeGear.Delphi.Targets"/>
<Import Condition="Exists('$(APPDATA)\Embarcadero\$(BDSAPPDATABASEDIR)\$(PRODUCTVERSION)\UserTools.proj')" Project="$(APPDATA)\Embarcadero\$(BDSAPPDATABASEDIR)\$(PRODUCTVERSION)\UserTools.proj"/>
<ProjectExtensions>
<Borland.Personality>Delphi.Personality.12</Borland.Personality>
<Borland.ProjectType/>
<BorlandProject>
<Delphi.Personality>
<VersionInfo>
<VersionInfo Name="IncludeVerInfo">True</VersionInfo>
<VersionInfo Name="AutoIncBuild">False</VersionInfo>
<VersionInfo Name="MajorVer">1</VersionInfo>
<VersionInfo Name="MinorVer">0</VersionInfo>
<VersionInfo Name="Release">0</VersionInfo>
<VersionInfo Name="Build">0</VersionInfo>
<VersionInfo Name="Debug">False</VersionInfo>
<VersionInfo Name="PreRelease">False</VersionInfo>
<VersionInfo Name="Special">False</VersionInfo>
<VersionInfo Name="Private">False</VersionInfo>
<VersionInfo Name="DLL">False</VersionInfo>
<VersionInfo Name="Locale">1033</VersionInfo>
<VersionInfo Name="CodePage">1252</VersionInfo>
</VersionInfo>
<VersionInfoKeys>
<VersionInfoKeys Name="CompanyName"/>
<VersionInfoKeys Name="FileDescription">Thrift Tutorial</VersionInfoKeys>
<VersionInfoKeys Name="FileVersion">1.0.0.0</VersionInfoKeys>
<VersionInfoKeys Name="InternalName">DelphiClient</VersionInfoKeys>
<VersionInfoKeys Name="LegalCopyright">Copyright © 2012 The Apache Software Foundation</VersionInfoKeys>
<VersionInfoKeys Name="LegalTrademarks"/>
<VersionInfoKeys Name="OriginalFilename">DelphiClient.exe</VersionInfoKeys>
<VersionInfoKeys Name="ProductName">Thrift</VersionInfoKeys>
<VersionInfoKeys Name="ProductVersion">1.0.0.0</VersionInfoKeys>
<VersionInfoKeys Name="Comments"/>
</VersionInfoKeys>
<Source>
<Source Name="MainSource">DelphiClient.dpr</Source>
</Source>
</Delphi.Personality>
<Platforms>
<Platform value="Win32">True</Platform>
</Platforms>
</BorlandProject>
<ProjectFileVersion>12</ProjectFileVersion>
</ProjectExtensions>
</Project>
 <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ProjectGuid>{2B8FB3A1-2F9E-4883-8C53-0F56220B34F6}</ProjectGuid>
<MainSource>DelphiClient.dpr</MainSource>
<ProjectVersion>12.3</ProjectVersion>
<Basis>True</Basis>
<Config Condition="'$(Config)'==''">Debug</Config>
<Platform>Win32</Platform>
<AppType>Console</AppType>
<FrameworkType>None</FrameworkType>
<DCC_DCCCompiler>DCC32</DCC_DCCCompiler>
</PropertyGroup>
<PropertyGroup Condition="'$(Config)'=='Basis' or '$(Base)'!=''">
<Base>true</Base>
</PropertyGroup>
<PropertyGroup Condition="'$(Config)'=='Debug' or '$(Cfg_1)'!=''">
<Cfg_1>true</Cfg_1>
<CfgParent>Base</CfgParent>
<Base>true</Base>
</PropertyGroup>
<PropertyGroup Condition="'$(Config)'=='Release' or '$(Cfg_2)'!=''">
<Cfg_2>true</Cfg_2>
<CfgParent>Base</CfgParent>
<Base>true</Base>
</PropertyGroup>
<PropertyGroup Condition="'$(Base)'!=''">
<DCC_UnitSearchPath>..\..\..\lib\delphi\src;$(DCC_UnitSearchPath)</DCC_UnitSearchPath>
<DCC_ImageBase>00400000</DCC_ImageBase>
<DCC_DcuOutput>.\dcu\$(Config)\$(Platform)</DCC_DcuOutput>
<DCC_UnitAlias>WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;$(DCC_UnitAlias)</DCC_UnitAlias>
<DCC_ExeOutput>..\bin\$(Config)\$(Platform)</DCC_ExeOutput>
<DCC_E>false</DCC_E>
<DCC_N>false</DCC_N>
<DCC_S>false</DCC_S>
<DCC_F>false</DCC_F>
<DCC_K>false</DCC_K>
</PropertyGroup>
<PropertyGroup Condition="'$(Cfg_1)'!=''">
<DCC_Define>DEBUG;$(DCC_Define)</DCC_Define>
<DCC_Optimize>false</DCC_Optimize>
<DCC_GenerateStackFrames>true</DCC_GenerateStackFrames>
</PropertyGroup>
<PropertyGroup Condition="'$(Cfg_2)'!=''">
<DCC_LocalDebugSymbols>false</DCC_LocalDebugSymbols>
<DCC_Define>RELEASE;$(DCC_Define)</DCC_Define>
<DCC_SymbolReferenceInfo>0</DCC_SymbolReferenceInfo>
<DCC_DebugInformation>false</DCC_DebugInformation>
</PropertyGroup>
<ItemGroup>
<DelphiCompile Include="DelphiClient.dpr">
<MainSource>MainSource</MainSource>
</DelphiCompile>
<DCCReference Include="..\..\..\lib\delphi\src\Thrift.pas"/>
<DCCReference Include="..\..\..\lib\delphi\src\Thrift.Collections.pas"/>
<DCCReference Include="..\..\..\lib\delphi\src\Thrift.Exception.pas"/>
<DCCReference Include="..\..\..\lib\delphi\src\Thrift.Utils.pas"/>
<DCCReference Include="..\..\..\lib\delphi\src\Thrift.Stream.pas"/>
<DCCReference Include="..\..\..\lib\delphi\src\Thrift.Protocol.pas"/>
<DCCReference Include="..\..\..\lib\delphi\src\Thrift.Server.pas"/>
<DCCReference Include="..\..\..\lib\delphi\src\Thrift.Transport.pas"/>
<DCCReference Include="..\..\gen-delphi\Shared.pas"/>
<DCCReference Include="..\..\gen-delphi\Tutorial.pas"/>
<BuildConfiguration Include="Release">
<Key>Cfg_2</Key>
<CfgParent>Base</CfgParent>
</BuildConfiguration>
<BuildConfiguration Include="Basis">
<Key>Base</Key>
</BuildConfiguration>
<BuildConfiguration Include="Debug">
<Key>Cfg_1</Key>
<CfgParent>Base</CfgParent>
</BuildConfiguration>
</ItemGroup>
<Import Condition="Exists('$(BDS)\Bin\CodeGear.Delphi.Targets')" Project="$(BDS)\Bin\CodeGear.Delphi.Targets"/>
<Import Condition="Exists('$(APPDATA)\Embarcadero\$(BDSAPPDATABASEDIR)\$(PRODUCTVERSION)\UserTools.proj')" Project="$(APPDATA)\Embarcadero\$(BDSAPPDATABASEDIR)\$(PRODUCTVERSION)\UserTools.proj"/>
<ProjectExtensions>
<Borland.Personality>Delphi.Personality.12</Borland.Personality>
<Borland.ProjectType/>
<BorlandProject>
<Delphi.Personality>
<VersionInfo>
<VersionInfo Name="IncludeVerInfo">True</VersionInfo>
<VersionInfo Name="AutoIncBuild">False</VersionInfo>
<VersionInfo Name="MajorVer">0</VersionInfo>
<VersionInfo Name="MinorVer">12</VersionInfo>
<VersionInfo Name="Release">0</VersionInfo>
<VersionInfo Name="Build">0</VersionInfo>
<VersionInfo Name="Debug">False</VersionInfo>
<VersionInfo Name="PreRelease">False</VersionInfo>
<VersionInfo Name="Special">False</VersionInfo>
<VersionInfo Name="Private">False</VersionInfo>
<VersionInfo Name="DLL">False</VersionInfo>
<VersionInfo Name="Locale">1033</VersionInfo>
<VersionInfo Name="CodePage">1252</VersionInfo>
</VersionInfo>
<VersionInfoKeys>
<VersionInfoKeys Name="CompanyName"/>
<VersionInfoKeys Name="FileDescription">Thrift Tutorial</VersionInfoKeys>
<VersionInfoKeys Name="FileVersion">0.12.0.0</VersionInfoKeys>
<VersionInfoKeys Name="InternalName">DelphiClient</VersionInfoKeys>
<VersionInfoKeys Name="LegalCopyright">Copyright © 2012 The Apache Software Foundation</VersionInfoKeys>
<VersionInfoKeys Name="LegalTrademarks"/>
<VersionInfoKeys Name="OriginalFilename">DelphiClient.exe</VersionInfoKeys>
<VersionInfoKeys Name="ProductName">Thrift</VersionInfoKeys>
<VersionInfoKeys Name="ProductVersion">1.0.0.0</VersionInfoKeys>
<VersionInfoKeys Name="Comments"/>
</VersionInfoKeys>
<Source>
<Source Name="MainSource">DelphiClient.dpr</Source>
</Source>
</Delphi.Personality>
<Platforms>
<Platform value="Win32">True</Platform>
</Platforms>
</BorlandProject>
<ProjectFileVersion>12</ProjectFileVersion>
</ProjectExtensions>
</Project>

View file

@ -28,7 +28,7 @@ uses
Generics.Collections,
Thrift in '..\..\..\lib\delphi\src\Thrift.pas',
Thrift.Collections in '..\..\..\lib\delphi\src\Thrift.Collections.pas',
Thrift.Console in '..\..\..\lib\delphi\src\Thrift.Console.pas',
Thrift.Exception in '..\..\..\lib\delphi\src\Thrift.Exception.pas',
Thrift.Utils in '..\..\..\lib\delphi\src\Thrift.Utils.pas',
Thrift.Stream in '..\..\..\lib\delphi\src\Thrift.Stream.pas',
Thrift.Protocol in '..\..\..\lib\delphi\src\Thrift.Protocol.pas',
@ -86,13 +86,13 @@ end;
procedure TCalculatorHandler.ping;
begin
Console.WriteLine( 'ping()');
WriteLn( 'ping()');
end;
function TCalculatorHandler.add(num1: Integer; num2: Integer): Integer;
begin
Console.WriteLine( Format( 'add( %d, %d)', [num1, num2]));
WriteLn( Format( 'add( %d, %d)', [num1, num2]));
result := num1 + num2;
end;
@ -101,7 +101,7 @@ function TCalculatorHandler.calculate(logid: Integer; const w: IWork): Integer;
var entry : ISharedStruct;
begin
try
Console.WriteLine( Format('calculate( %d, [%d,%d,%d])', [logid, Ord(w.Op), w.Num1, w.Num2]));
WriteLn( Format('calculate( %d, [%d,%d,%d])', [logid, Ord(w.Op), w.Num1, w.Num2]));
case w.Op of
TOperation.ADD : result := w.Num1 + w.Num2;
@ -126,14 +126,14 @@ end;
function TCalculatorHandler.getStruct(key: Integer): ISharedStruct;
begin
Console.WriteLine( Format( 'getStruct(%d)', [key]));
WriteLn( Format( 'getStruct(%d)', [key]));
result := FLog[key];
end;
procedure TCalculatorHandler.zip;
begin
Console.WriteLine( 'zip()');
WriteLn( 'zip()');
end;
@ -152,14 +152,14 @@ begin
transport := TServerSocketImpl.Create( 9090);
server := TSimpleServer.Create( processor, transport);
Console.WriteLine( 'Starting the server...');
WriteLn( 'Starting the server...');
server.Serve();
except
on e: Exception do Console.WriteLine( e.Message);
on e: Exception do WriteLn( e.Message);
end;
Console.WriteLine('done.');
WriteLn('done.');
end;

View file

@ -1,118 +1,118 @@
 <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ProjectGuid>{2B8FB3A1-2F9E-4883-8C53-0F56220B34F6}</ProjectGuid>
<MainSource>DelphiServer.dpr</MainSource>
<ProjectVersion>12.3</ProjectVersion>
<Basis>True</Basis>
<Config Condition="'$(Config)'==''">Debug</Config>
<Platform>Win32</Platform>
<AppType>Console</AppType>
<FrameworkType>None</FrameworkType>
<DCC_DCCCompiler>DCC32</DCC_DCCCompiler>
</PropertyGroup>
<PropertyGroup Condition="'$(Config)'=='Basis' or '$(Base)'!=''">
<Base>true</Base>
</PropertyGroup>
<PropertyGroup Condition="'$(Config)'=='Debug' or '$(Cfg_1)'!=''">
<Cfg_1>true</Cfg_1>
<CfgParent>Base</CfgParent>
<Base>true</Base>
</PropertyGroup>
<PropertyGroup Condition="'$(Config)'=='Release' or '$(Cfg_2)'!=''">
<Cfg_2>true</Cfg_2>
<CfgParent>Base</CfgParent>
<Base>true</Base>
</PropertyGroup>
<PropertyGroup Condition="'$(Base)'!=''">
<DCC_ImageBase>00400000</DCC_ImageBase>
<DCC_DcuOutput>.\dcu\$(Config)\$(Platform)</DCC_DcuOutput>
<DCC_UnitAlias>WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;$(DCC_UnitAlias)</DCC_UnitAlias>
<DCC_ExeOutput>..\bin\$(Config)\$(Platform)</DCC_ExeOutput>
<DCC_E>false</DCC_E>
<DCC_N>false</DCC_N>
<DCC_S>false</DCC_S>
<DCC_F>false</DCC_F>
<DCC_K>false</DCC_K>
</PropertyGroup>
<PropertyGroup Condition="'$(Cfg_1)'!=''">
<DCC_Define>DEBUG;$(DCC_Define)</DCC_Define>
<DCC_Optimize>false</DCC_Optimize>
<DCC_GenerateStackFrames>true</DCC_GenerateStackFrames>
</PropertyGroup>
<PropertyGroup Condition="'$(Cfg_2)'!=''">
<DCC_LocalDebugSymbols>false</DCC_LocalDebugSymbols>
<DCC_Define>RELEASE;$(DCC_Define)</DCC_Define>
<DCC_SymbolReferenceInfo>0</DCC_SymbolReferenceInfo>
<DCC_DebugInformation>false</DCC_DebugInformation>
</PropertyGroup>
<ItemGroup>
<DelphiCompile Include="DelphiServer.dpr">
<MainSource>MainSource</MainSource>
</DelphiCompile>
<DCCReference Include="..\..\..\lib\delphi\src\Thrift.pas"/>
<DCCReference Include="..\..\..\lib\delphi\src\Thrift.Collections.pas"/>
<DCCReference Include="..\..\..\lib\delphi\src\Thrift.Console.pas"/>
<DCCReference Include="..\..\..\lib\delphi\src\Thrift.Utils.pas"/>
<DCCReference Include="..\..\..\lib\delphi\src\Thrift.Stream.pas"/>
<DCCReference Include="..\..\..\lib\delphi\src\Thrift.Protocol.pas"/>
<DCCReference Include="..\..\..\lib\delphi\src\Thrift.Server.pas"/>
<DCCReference Include="..\..\..\lib\delphi\src\Thrift.Transport.pas"/>
<DCCReference Include="..\..\gen-delphi\Shared.pas"/>
<DCCReference Include="..\..\gen-delphi\Tutorial.pas"/>
<BuildConfiguration Include="Release">
<Key>Cfg_2</Key>
<CfgParent>Base</CfgParent>
</BuildConfiguration>
<BuildConfiguration Include="Basis">
<Key>Base</Key>
</BuildConfiguration>
<BuildConfiguration Include="Debug">
<Key>Cfg_1</Key>
<CfgParent>Base</CfgParent>
</BuildConfiguration>
</ItemGroup>
<Import Condition="Exists('$(BDS)\Bin\CodeGear.Delphi.Targets')" Project="$(BDS)\Bin\CodeGear.Delphi.Targets"/>
<Import Condition="Exists('$(APPDATA)\Embarcadero\$(BDSAPPDATABASEDIR)\$(PRODUCTVERSION)\UserTools.proj')" Project="$(APPDATA)\Embarcadero\$(BDSAPPDATABASEDIR)\$(PRODUCTVERSION)\UserTools.proj"/>
<ProjectExtensions>
<Borland.Personality>Delphi.Personality.12</Borland.Personality>
<Borland.ProjectType/>
<BorlandProject>
<Delphi.Personality>
<VersionInfo>
<VersionInfo Name="IncludeVerInfo">True</VersionInfo>
<VersionInfo Name="AutoIncBuild">False</VersionInfo>
<VersionInfo Name="MajorVer">1</VersionInfo>
<VersionInfo Name="MinorVer">0</VersionInfo>
<VersionInfo Name="Release">0</VersionInfo>
<VersionInfo Name="Build">0</VersionInfo>
<VersionInfo Name="Debug">False</VersionInfo>
<VersionInfo Name="PreRelease">False</VersionInfo>
<VersionInfo Name="Special">False</VersionInfo>
<VersionInfo Name="Private">False</VersionInfo>
<VersionInfo Name="DLL">False</VersionInfo>
<VersionInfo Name="Locale">1033</VersionInfo>
<VersionInfo Name="CodePage">1252</VersionInfo>
</VersionInfo>
<VersionInfoKeys>
<VersionInfoKeys Name="CompanyName"/>
<VersionInfoKeys Name="FileDescription">Thrift Tutorial</VersionInfoKeys>
<VersionInfoKeys Name="FileVersion">1.0.0.0</VersionInfoKeys>
<VersionInfoKeys Name="InternalName">DelphiServer</VersionInfoKeys>
<VersionInfoKeys Name="LegalCopyright">Copyright © 2012 The Apache Software Foundation</VersionInfoKeys>
<VersionInfoKeys Name="LegalTrademarks"/>
<VersionInfoKeys Name="OriginalFilename">DelphiServer.exe</VersionInfoKeys>
<VersionInfoKeys Name="ProductName">Thrift</VersionInfoKeys>
<VersionInfoKeys Name="ProductVersion">1.0.0.0</VersionInfoKeys>
<VersionInfoKeys Name="Comments"/>
</VersionInfoKeys>
<Source>
<Source Name="MainSource">DelphiServer.dpr</Source>
</Source>
</Delphi.Personality>
<Platforms>
<Platform value="Win32">True</Platform>
</Platforms>
</BorlandProject>
<ProjectFileVersion>12</ProjectFileVersion>
</ProjectExtensions>
</Project>
 <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ProjectGuid>{2B8FB3A1-2F9E-4883-8C53-0F56220B34F6}</ProjectGuid>
<MainSource>DelphiServer.dpr</MainSource>
<ProjectVersion>12.3</ProjectVersion>
<Basis>True</Basis>
<Config Condition="'$(Config)'==''">Debug</Config>
<Platform>Win32</Platform>
<AppType>Console</AppType>
<FrameworkType>None</FrameworkType>
<DCC_DCCCompiler>DCC32</DCC_DCCCompiler>
</PropertyGroup>
<PropertyGroup Condition="'$(Config)'=='Basis' or '$(Base)'!=''">
<Base>true</Base>
</PropertyGroup>
<PropertyGroup Condition="'$(Config)'=='Debug' or '$(Cfg_1)'!=''">
<Cfg_1>true</Cfg_1>
<CfgParent>Base</CfgParent>
<Base>true</Base>
</PropertyGroup>
<PropertyGroup Condition="'$(Config)'=='Release' or '$(Cfg_2)'!=''">
<Cfg_2>true</Cfg_2>
<CfgParent>Base</CfgParent>
<Base>true</Base>
</PropertyGroup>
<PropertyGroup Condition="'$(Base)'!=''">
<DCC_ImageBase>00400000</DCC_ImageBase>
<DCC_DcuOutput>.\dcu\$(Config)\$(Platform)</DCC_DcuOutput>
<DCC_UnitAlias>WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;$(DCC_UnitAlias)</DCC_UnitAlias>
<DCC_ExeOutput>..\bin\$(Config)\$(Platform)</DCC_ExeOutput>
<DCC_E>false</DCC_E>
<DCC_N>false</DCC_N>
<DCC_S>false</DCC_S>
<DCC_F>false</DCC_F>
<DCC_K>false</DCC_K>
</PropertyGroup>
<PropertyGroup Condition="'$(Cfg_1)'!=''">
<DCC_Define>DEBUG;$(DCC_Define)</DCC_Define>
<DCC_Optimize>false</DCC_Optimize>
<DCC_GenerateStackFrames>true</DCC_GenerateStackFrames>
</PropertyGroup>
<PropertyGroup Condition="'$(Cfg_2)'!=''">
<DCC_LocalDebugSymbols>false</DCC_LocalDebugSymbols>
<DCC_Define>RELEASE;$(DCC_Define)</DCC_Define>
<DCC_SymbolReferenceInfo>0</DCC_SymbolReferenceInfo>
<DCC_DebugInformation>false</DCC_DebugInformation>
</PropertyGroup>
<ItemGroup>
<DelphiCompile Include="DelphiServer.dpr">
<MainSource>MainSource</MainSource>
</DelphiCompile>
<DCCReference Include="..\..\..\lib\delphi\src\Thrift.pas"/>
<DCCReference Include="..\..\..\lib\delphi\src\Thrift.Collections.pas"/>
<DCCReference Include="..\..\..\lib\delphi\src\Thrift.Exception.pas"/>
<DCCReference Include="..\..\..\lib\delphi\src\Thrift.Utils.pas"/>
<DCCReference Include="..\..\..\lib\delphi\src\Thrift.Stream.pas"/>
<DCCReference Include="..\..\..\lib\delphi\src\Thrift.Protocol.pas"/>
<DCCReference Include="..\..\..\lib\delphi\src\Thrift.Server.pas"/>
<DCCReference Include="..\..\..\lib\delphi\src\Thrift.Transport.pas"/>
<DCCReference Include="..\..\gen-delphi\Shared.pas"/>
<DCCReference Include="..\..\gen-delphi\Tutorial.pas"/>
<BuildConfiguration Include="Release">
<Key>Cfg_2</Key>
<CfgParent>Base</CfgParent>
</BuildConfiguration>
<BuildConfiguration Include="Basis">
<Key>Base</Key>
</BuildConfiguration>
<BuildConfiguration Include="Debug">
<Key>Cfg_1</Key>
<CfgParent>Base</CfgParent>
</BuildConfiguration>
</ItemGroup>
<Import Condition="Exists('$(BDS)\Bin\CodeGear.Delphi.Targets')" Project="$(BDS)\Bin\CodeGear.Delphi.Targets"/>
<Import Condition="Exists('$(APPDATA)\Embarcadero\$(BDSAPPDATABASEDIR)\$(PRODUCTVERSION)\UserTools.proj')" Project="$(APPDATA)\Embarcadero\$(BDSAPPDATABASEDIR)\$(PRODUCTVERSION)\UserTools.proj"/>
<ProjectExtensions>
<Borland.Personality>Delphi.Personality.12</Borland.Personality>
<Borland.ProjectType/>
<BorlandProject>
<Delphi.Personality>
<VersionInfo>
<VersionInfo Name="IncludeVerInfo">True</VersionInfo>
<VersionInfo Name="AutoIncBuild">False</VersionInfo>
<VersionInfo Name="MajorVer">0</VersionInfo>
<VersionInfo Name="MinorVer">12</VersionInfo>
<VersionInfo Name="Release">0</VersionInfo>
<VersionInfo Name="Build">0</VersionInfo>
<VersionInfo Name="Debug">False</VersionInfo>
<VersionInfo Name="PreRelease">False</VersionInfo>
<VersionInfo Name="Special">False</VersionInfo>
<VersionInfo Name="Private">False</VersionInfo>
<VersionInfo Name="DLL">False</VersionInfo>
<VersionInfo Name="Locale">1033</VersionInfo>
<VersionInfo Name="CodePage">1252</VersionInfo>
</VersionInfo>
<VersionInfoKeys>
<VersionInfoKeys Name="CompanyName"/>
<VersionInfoKeys Name="FileDescription">Thrift Tutorial</VersionInfoKeys>
<VersionInfoKeys Name="FileVersion">0.12.0.0</VersionInfoKeys>
<VersionInfoKeys Name="InternalName">DelphiServer</VersionInfoKeys>
<VersionInfoKeys Name="LegalCopyright">Copyright © 2012 The Apache Software Foundation</VersionInfoKeys>
<VersionInfoKeys Name="LegalTrademarks"/>
<VersionInfoKeys Name="OriginalFilename">DelphiServer.exe</VersionInfoKeys>
<VersionInfoKeys Name="ProductName">Thrift</VersionInfoKeys>
<VersionInfoKeys Name="ProductVersion">1.0.0.0</VersionInfoKeys>
<VersionInfoKeys Name="Comments"/>
</VersionInfoKeys>
<Source>
<Source Name="MainSource">DelphiServer.dpr</Source>
</Source>
</Delphi.Personality>
<Platforms>
<Platform value="Win32">True</Platform>
</Platforms>
</BorlandProject>
<ProjectFileVersion>12</ProjectFileVersion>
</ProjectExtensions>
</Project>

View file

@ -28,7 +28,7 @@ p(X) ->
ok.
t() ->
Port = 9999,
Port = 9090,
{ok, Client0} = thrift_client_util:new("127.0.0.1",
Port,
@ -44,7 +44,7 @@ t() ->
{Client3, {ok, Sum1}} = thrift_client:call(Client2, add, [1, 4]),
io:format("1+4=~p~n", [Sum1]),
Work = #work{op=?tutorial_Operation_SUBTRACT,
Work = #'Work'{op=?TUTORIAL_OPERATION_SUBTRACT,
num1=15,
num2=10},
{Client4, {ok, Diff}} = thrift_client:call(Client3, calculate, [1, Work]),
@ -55,7 +55,7 @@ t() ->
Client6 =
try
Work1 = #work{op=?tutorial_Operation_DIVIDE,
Work1 = #'Work'{op=?TUTORIAL_OPERATION_DIVIDE,
num1=1,
num2=0},
{ClientS1, {ok, _Quot}} = thrift_client:call(Client5, calculate, [2, Work1]),

View file

@ -1 +0,0 @@
server.sh

37
vendor/git.apache.org/thrift.git/tutorial/erl/client.sh generated vendored Executable file
View file

@ -0,0 +1,37 @@
#!/bin/sh
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
#
ERL_THRIFT=../../lib/erl
if ! [ -d ${ERL_THRIFT}/ebin ]; then
echo "Please build the Thrift library by running \`make' in ${ERL_THRIFT}"
exit 1
fi
if ! [ -d gen-erl ]; then
../../compiler/cpp/thrift -r --gen erl ../tutorial.thrift
fi
erlc -I ${ERL_THRIFT}/include -I ${ERL_THRIFT}/ebin \
-I gen-erl -o gen-erl gen-erl/*.erl &&
erlc -I ${ERL_THRIFT}/include -I gen-erl *.erl &&
erl +K true -pa ${ERL_THRIFT}/ebin -pa gen-erl

View file

@ -55,7 +55,7 @@ t() ->
{Client3, {ok, Sum1}} = thrift_client:call(Client2, add, [1, 4]),
io:format("1+4=~p~n", [Sum1]),
Work = #work{op=?tutorial_Operation_SUBTRACT,
Work = #'Work'{op=?TUTORIAL_OPERATION_SUBTRACT,
num1=15,
num2=10},
{Client4, {ok, Diff}} = thrift_client:call(Client3, calculate, [1, Work]),
@ -66,7 +66,7 @@ t() ->
Client6 =
try
Work1 = #work{op=?tutorial_Operation_DIVIDE,
Work1 = #'Work'{op=?TUTORIAL_OPERATION_DIVIDE,
num1=1,
num2=0},
{ClientS1, {ok, _Quot}} = thrift_client:call(Client5, calculate, [2, Work1]),

View file

@ -36,25 +36,25 @@ add(N1, N2) ->
N1+N2.
calculate(Logid, Work) ->
{ Op, Num1, Num2 } = { Work#work.op, Work#work.num1, Work#work.num2 },
{ Op, Num1, Num2 } = { Work#'Work'.op, Work#'Work'.num1, Work#'Work'.num2 },
debug("calculate(~p, {~p,~p,~p})", [Logid, Op, Num1, Num2]),
case Op of
?tutorial_Operation_ADD -> Num1 + Num2;
?tutorial_Operation_SUBTRACT -> Num1 - Num2;
?tutorial_Operation_MULTIPLY -> Num1 * Num2;
?TUTORIAL_OPERATION_ADD -> Num1 + Num2;
?TUTORIAL_OPERATION_SUBTRACT -> Num1 - Num2;
?TUTORIAL_OPERATION_MULTIPLY -> Num1 * Num2;
?tutorial_Operation_DIVIDE when Num2 == 0 ->
throw(#invalidOperation{whatOp=Op, why="Cannot divide by 0"});
?tutorial_Operation_DIVIDE ->
?TUTORIAL_OPERATION_DIVIDE when Num2 == 0 ->
throw(#'InvalidOperation'{whatOp=Op, why="Cannot divide by 0"});
?TUTORIAL_OPERATION_DIVIDE ->
Num1 div Num2;
_Else ->
throw(#invalidOperation{whatOp=Op, why="Invalid operation"})
throw(#'InvalidOperation'{whatOp=Op, why="Invalid operation"})
end.
getStruct(Key) ->
debug("getStruct(~p)", [Key]),
#sharedStruct{key=Key, value="RARG"}.
#'SharedStruct'{key=Key, value="RARG"}.
zip() ->
debug("zip", []),
@ -63,7 +63,7 @@ zip() ->
%%
start() ->
start(9999).
start(9090).
start(Port) ->
Handler = ?MODULE,

View file

@ -1,37 +0,0 @@
#!/bin/sh
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
#
ERL_THRIFT=../../lib/erl
if ! [ -d ${ERL_THRIFT}/ebin ]; then
echo "Please build the Thrift library by running \`make' in ${ERL_THRIFT}"
exit 1
fi
if ! [ -d gen-erl ]; then
../../compiler/cpp/thrift -r --gen erl ../tutorial.thrift
fi
erlc -I ${ERL_THRIFT}/include -I ${ERL_THRIFT}/ebin \
-I gen-erl -o gen-erl gen-erl/*.erl &&
erlc -I ${ERL_THRIFT}/include -I gen-erl *.erl &&
erl +K true -pa ${ERL_THRIFT}/ebin -pa gen-erl

1
vendor/git.apache.org/thrift.git/tutorial/erl/server.sh generated vendored Symbolic link
View file

@ -0,0 +1 @@
client.sh

View file

@ -17,30 +17,28 @@
# under the License.
#
THRIFT = $(top_builddir)/compiler/cpp/thrift
gen-go/tutorial/calculator.go gen-go/shared/shared_service.go: $(top_srcdir)/tutorial/tutorial.thrift
$(THRIFT) --gen go -r $<
$(THRIFT) --gen go$(COMPILER_EXTRAFLAG) -r $<
all-local: gen-go/tutorial/calculator.go
check: src/git.apache.org/thrift.git/lib/go/thrift
$(THRIFT) -r --gen go $(top_srcdir)/tutorial/tutorial.thrift
check: src/github.com/apache/thrift/lib/go/thrift thirdparty-dep
$(THRIFT) -r --gen go$(COMPILER_EXTRAFLAG) $(top_srcdir)/tutorial/tutorial.thrift
cp -r gen-go/* src/
GOPATH=`pwd` $(GO) build ./...
GOPATH=`pwd` $(GO) build -o go-tutorial src/*.go
GOPATH=`pwd` $(GO) build -o go-tutorial ./src
GOPATH=`pwd` $(GO) build -o calculator-remote src/tutorial/calculator-remote/calculator-remote.go
src/git.apache.org/thrift.git/lib/go/thrift:
mkdir -p src/git.apache.org/thrift.git/lib/go
ln -sf $(realpath $(top_srcdir)/lib/go/thrift) src/git.apache.org/thrift.git/lib/go/thrift
src/github.com/apache/thrift/lib/go/thrift:
mkdir -p src/github.com/apache/thrift/lib/go
ln -sf $(realpath $(top_srcdir)/lib/go/thrift) src/github.com/apache/thrift/lib/go/thrift
thirdparty-dep:
tutorialserver: all
GOPATH=`pwd` $(GO) run src/*.go -server=true
tutorialclient: all
GOPATH=`pwd` $(GO) run src/*.go
GOPATH=`pwd` $(GO) run src/*.go
tutorialsecureserver: all
GOPATH=`pwd` $(GO) run src/*.go -server=true -secure=true

View file

@ -20,24 +20,28 @@ package main
*/
import (
"context"
"crypto/tls"
"fmt"
"git.apache.org/thrift.git/lib/go/thrift"
"tutorial"
"github.com/apache/thrift/lib/go/thrift"
)
var defaultCtx = context.Background()
func handleClient(client *tutorial.CalculatorClient) (err error) {
client.Ping()
client.Ping(defaultCtx)
fmt.Println("ping()")
sum, _ := client.Add(1, 1)
sum, _ := client.Add(defaultCtx, 1, 1)
fmt.Print("1+1=", sum, "\n")
work := tutorial.NewWork()
work.Op = tutorial.Operation_DIVIDE
work.Num1 = 1
work.Num2 = 0
quotient, err := client.Calculate(1, work)
quotient, err := client.Calculate(defaultCtx, 1, work)
if err != nil {
switch v := err.(type) {
case *tutorial.InvalidOperation:
@ -53,7 +57,7 @@ func handleClient(client *tutorial.CalculatorClient) (err error) {
work.Op = tutorial.Operation_SUBTRACT
work.Num1 = 15
work.Num2 = 10
diff, err := client.Calculate(1, work)
diff, err := client.Calculate(defaultCtx, 1, work)
if err != nil {
switch v := err.(type) {
case *tutorial.InvalidOperation:
@ -66,7 +70,7 @@ func handleClient(client *tutorial.CalculatorClient) (err error) {
fmt.Print("15-10=", diff, "\n")
}
log, err := client.GetStruct(1)
log, err := client.GetStruct(defaultCtx, 1)
if err != nil {
fmt.Println("Unable to get struct:", err)
return err
@ -98,5 +102,7 @@ func runClient(transportFactory thrift.TTransportFactory, protocolFactory thrift
if err := transport.Open(); err != nil {
return err
}
return handleClient(tutorial.NewCalculatorClientFactory(transport, protocolFactory))
iprot := protocolFactory.GetProtocol(transport)
oprot := protocolFactory.GetProtocol(transport)
return handleClient(tutorial.NewCalculatorClient(thrift.NewTStandardClient(iprot, oprot)))
}

View file

@ -20,6 +20,7 @@ package main
*/
import (
"context"
"fmt"
"shared"
"strconv"
@ -34,17 +35,17 @@ func NewCalculatorHandler() *CalculatorHandler {
return &CalculatorHandler{log: make(map[int]*shared.SharedStruct)}
}
func (p *CalculatorHandler) Ping() (err error) {
func (p *CalculatorHandler) Ping(ctx context.Context) (err error) {
fmt.Print("ping()\n")
return nil
}
func (p *CalculatorHandler) Add(num1 int32, num2 int32) (retval17 int32, err error) {
func (p *CalculatorHandler) Add(ctx context.Context, num1 int32, num2 int32) (retval17 int32, err error) {
fmt.Print("add(", num1, ",", num2, ")\n")
return num1 + num2, nil
}
func (p *CalculatorHandler) Calculate(logid int32, w *tutorial.Work) (val int32, err error) {
func (p *CalculatorHandler) Calculate(ctx context.Context, logid int32, w *tutorial.Work) (val int32, err error) {
fmt.Print("calculate(", logid, ", {", w.Op, ",", w.Num1, ",", w.Num2, "})\n")
switch w.Op {
case tutorial.Operation_ADD:
@ -89,13 +90,13 @@ func (p *CalculatorHandler) Calculate(logid int32, w *tutorial.Work) (val int32,
return val, err
}
func (p *CalculatorHandler) GetStruct(key int32) (*shared.SharedStruct, error) {
func (p *CalculatorHandler) GetStruct(ctx context.Context, key int32) (*shared.SharedStruct, error) {
fmt.Print("getStruct(", key, ")\n")
v, _ := p.log[int(key)]
return v, nil
}
func (p *CalculatorHandler) Zip() (err error) {
func (p *CalculatorHandler) Zip(ctx context.Context) (err error) {
fmt.Print("zip()\n")
return nil
}

View file

@ -22,7 +22,7 @@ package main
import (
"flag"
"fmt"
"git.apache.org/thrift.git/lib/go/thrift"
"github.com/apache/thrift/lib/go/thrift"
"os"
)

View file

@ -22,7 +22,7 @@ package main
import (
"crypto/tls"
"fmt"
"git.apache.org/thrift.git/lib/go/thrift"
"github.com/apache/thrift/lib/go/thrift"
"tutorial"
)

View file

@ -17,13 +17,10 @@
# under the License.
#
THRIFT = $(top_builddir)/compiler/cpp/thrift
BIN_CPP = bin/Main-debug
BIN_PHP = bin/php/Main-debug.php
BIN_PHP_WEB = bin/php-web-server/Main-debug.php
gen-haxe/tutorial/calculator.hx gen-haxe/shared/shared_service.hx: $(top_srcdir)/tutorial/tutorial.thrift
$(THRIFT) --gen haxe -r $<
@ -83,16 +80,18 @@ clean-local:
$(RM) -r gen-haxe bin
EXTRA_DIST = \
src \
cpp.hxml \
csharp.hxml \
flash.hxml \
java.hxml \
javascript.hxml \
neko.hxml \
php.hxml \
python.hxml \
project.hide \
Tutorial.hxproj \
make_all.bat \
make_all.sh
src \
cpp.hxml \
csharp.hxml \
flash.hxml \
java.hxml \
javascript.hxml \
php-web-server.hxml \
neko.hxml \
php.hxml \
python.hxml \
router.php \
project.hide \
Tutorial.hxproj \
make_all.bat \
make_all.sh

239
vendor/git.apache.org/thrift.git/tutorial/hs/LICENSE generated vendored Normal file
View file

@ -0,0 +1,239 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.
--------------------------------------------------
SOFTWARE DISTRIBUTED WITH THRIFT:
The Apache Thrift software includes a number of subcomponents with
separate copyright notices and license terms. Your use of the source
code for the these subcomponents is subject to the terms and
conditions of the following licenses.
--------------------------------------------------
Portions of the following files are licensed under the MIT License:
lib/erl/src/Makefile.am
Please see doc/otp-base-license.txt for the full terms of this license.
--------------------------------------------------
For the aclocal/ax_boost_base.m4 and contrib/fb303/aclocal/ax_boost_base.m4 components:
# Copyright (c) 2007 Thomas Porschberg <thomas@randspringer.de>
#
# Copying and distribution of this file, with or without
# modification, are permitted in any medium without royalty provided
# the copyright notice and this notice are preserved.
--------------------------------------------------
For the lib/nodejs/lib/thrift/json_parse.js:
/*
json_parse.js
2015-05-02
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
*/
(By Douglas Crockford <douglas@crockford.com>)
--------------------------------------------------

View file

@ -37,3 +37,6 @@ tutorialserver: all
tutorialclient: all
dist/build/HaskellClient/HaskellClient
EXTRA_DIST = \
LICENSE

View file

@ -18,7 +18,7 @@
--
Name: ThriftTutorial
Version: 0.10.0
Version: 0.12.0
Cabal-Version: >= 1.4
License: OtherLicense
Category: Foreign
@ -27,7 +27,7 @@ Synopsis: Thrift Tutorial library package
Homepage: http://thrift.apache.org
Bug-Reports: https://issues.apache.org/jira/browse/THRIFT
Maintainer: dev@thrift.apache.org
License-File: ../../LICENSE
License-File: LICENSE
Description:
Haskell tutorial for the Apache Thrift RPC system. Requires the use of the thrift code generator.

View file

@ -25,11 +25,13 @@
<property name="build" location="build" />
<path id="libs.classpath">
<fileset dir="../../lib/java/build">
<include name="*.jar" />
<exclude name="-test.jar" />
<fileset dir="../../lib/java/build/libs">
<include name="libthrift*.jar" />
<exclude name="libthrift*test.jar" />
<exclude name="libthrift*javadoc.jar" />
<exclude name="libthrift*sources.jar" />
</fileset>
<fileset dir="../../lib/java/build/lib">
<fileset dir="../../lib/java/build/deps">
<include name="*.jar" />
</fileset>
</path>
@ -42,7 +44,7 @@
<pathelement path="${build}" />
<pathelement path="tutorial.jar" />
</path>
<target name="init">
<tstamp />
<mkdir dir="${build}"/>
@ -50,8 +52,8 @@
</target>
<target name="compile" depends="init, generate">
<javac includeantruntime="false" srcdir="${gen}" destdir="${build}" classpathref="libs.classpath" />
<javac includeantruntime="false" srcdir="${src}" destdir="${build}" classpathref="build.classpath" />
<javac compiler="modern" includeantruntime="false" srcdir="${gen}" destdir="${build}" classpathref="libs.classpath" />
<javac compiler="modern" includeantruntime="false" srcdir="${src}" destdir="${build}" classpathref="build.classpath" />
</target>
<target name="test" depends="tutorial" />

View file

@ -31,11 +31,13 @@
<property name="thrift.java.dir" location="${thrift.dir}/lib/java" />
<path id="libs.classpath">
<fileset dir="../../lib/java/build">
<include name="*.jar" />
<exclude name="-test.jar" />
<fileset dir="${thrift.java.dir}/build/libs">
<include name="libthrift*.jar" />
<exclude name="libthrift*test.jar" />
<exclude name="libthrift*javadoc.jar" />
<exclude name="libthrift*sources.jar" />
</fileset>
<fileset dir="../../lib/java/build/lib">
<fileset dir="${thrift.java.dir}/build/deps">
<include name="*.jar" />
</fileset>
</path>
@ -51,13 +53,13 @@
</target>
<target name="compile" depends="init">
<javac includeantruntime="false" srcdir="${gen}" destdir="${build}" classpathref="libs.classpath" />
<javac includeantruntime="false" srcdir="${javasrc}" destdir="${build}" classpathref="build.classpath">
<javac compiler="modern" includeantruntime="false" srcdir="${gen}" destdir="${build}" classpathref="libs.classpath" />
<javac compiler="modern" includeantruntime="false" srcdir="${javasrc}" destdir="${build}" classpathref="build.classpath">
<exclude name="JavaClient.java"/>
<exclude name="JavaServer.java"/>
<include name="CalculatorHandler.java"/>
</javac>
<javac includeantruntime="false" srcdir="${src}" destdir="${build}" classpathref="build.classpath">
<javac compiler="modern" includeantruntime="false" srcdir="${src}" destdir="${build}" classpathref="build.classpath">
<compilerarg value="-Xlint:all"/>
</javac>
</target>
@ -80,7 +82,7 @@
<arg line="--gen js -r ../tutorial.thrift"/>
</exec>
</target>
<target name="clean">
<delete dir="${build}" />
<delete dir="gen-js"/>

View file

@ -0,0 +1 @@
!**/*.pfx

View file

@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
<AssemblyName>Client</AssemblyName>
<PackageId>Client</PackageId>
<OutputType>Exe</OutputType>
<GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
<GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
<GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
<GenerateAssemblyCopyrightAttribute>false</GenerateAssemblyCopyrightAttribute>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Interfaces\Interfaces.csproj" />
<ProjectReference Include="..\..\..\lib\netcore\Thrift\Thrift.csproj" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,355 @@
// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
// to you 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.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Thrift;
using Thrift.Protocols;
using Thrift.Transports;
using Thrift.Transports.Client;
using tutorial;
using shared;
namespace Client
{
public class Program
{
private static readonly ILogger Logger = new LoggerFactory().AddConsole().AddDebug().CreateLogger(nameof(Client));
private static void DisplayHelp()
{
Logger.LogInformation(@"
Usage:
Client.exe -help
will diplay help information
Client.exe -tr:<transport> -pr:<protocol> -mc:<numClients>
will run client with specified arguments (tcp transport and binary protocol by default) and with 1 client
Options:
-tr (transport):
tcp - (default) tcp transport will be used (host - ""localhost"", port - 9090)
tcpbuffered - buffered transport over tcp will be used (host - ""localhost"", port - 9090)
namedpipe - namedpipe transport will be used (pipe address - "".test"")
http - http transport will be used (address - ""http://localhost:9090"")
tcptls - tcp tls transport will be used (host - ""localhost"", port - 9090)
framed - tcp framed transport will be used (host - ""localhost"", port - 9090)
-pr (protocol):
binary - (default) binary protocol will be used
compact - compact protocol will be used
json - json protocol will be used
multiplexed - multiplexed protocol will be used
-mc (multiple clients):
<numClients> - number of multiple clients to connect to server (max 100, default 1)
Sample:
Client.exe -tr:tcp -p:binary
");
}
public static void Main(string[] args)
{
args = args ?? new string[0];
if (args.Any(x => x.StartsWith("-help", StringComparison.OrdinalIgnoreCase)))
{
DisplayHelp();
return;
}
Logger.LogInformation("Starting client...");
using (var source = new CancellationTokenSource())
{
RunAsync(args, source.Token).GetAwaiter().GetResult();
}
}
private static async Task RunAsync(string[] args, CancellationToken cancellationToken)
{
var numClients = GetNumberOfClients(args);
Logger.LogInformation($"Selected # of clients: {numClients}");
var transports = new TClientTransport[numClients];
for (int i = 0; i < numClients; i++)
{
var t = GetTransport(args);
transports[i] = t;
}
Logger.LogInformation($"Selected client transport: {transports[0]}");
var protocols = new Tuple<Protocol, TProtocol>[numClients];
for (int i = 0; i < numClients; i++)
{
var p = GetProtocol(args, transports[i]);
protocols[i] = p;
}
Logger.LogInformation($"Selected client protocol: {protocols[0].Item1}");
var tasks = new Task[numClients];
for (int i = 0; i < numClients; i++)
{
var task = RunClientAsync(protocols[i], cancellationToken);
tasks[i] = task;
}
Task.WaitAll(tasks);
await Task.CompletedTask;
}
private static TClientTransport GetTransport(string[] args)
{
var transport = args.FirstOrDefault(x => x.StartsWith("-tr"))?.Split(':')?[1];
Transport selectedTransport;
if (Enum.TryParse(transport, true, out selectedTransport))
{
switch (selectedTransport)
{
case Transport.Tcp:
return new TSocketClientTransport(IPAddress.Loopback, 9090);
case Transport.NamedPipe:
return new TNamedPipeClientTransport(".test");
case Transport.Http:
return new THttpClientTransport(new Uri("http://localhost:9090"), null);
case Transport.TcpBuffered:
return new TBufferedClientTransport(new TSocketClientTransport(IPAddress.Loopback, 9090));
case Transport.TcpTls:
return new TTlsSocketClientTransport(IPAddress.Loopback, 9090, GetCertificate(), CertValidator, LocalCertificateSelectionCallback);
case Transport.Framed:
return new TFramedClientTransport(new TSocketClientTransport(IPAddress.Loopback, 9090));
}
}
return new TSocketClientTransport(IPAddress.Loopback, 9090);
}
private static int GetNumberOfClients(string[] args)
{
var numClients = args.FirstOrDefault(x => x.StartsWith("-mc"))?.Split(':')?[1];
Logger.LogInformation($"Selected # of clients: {numClients}");
int c;
if( int.TryParse(numClients, out c) && (0 < c) && (c <= 100))
return c;
else
return 1;
}
private static X509Certificate2 GetCertificate()
{
// due to files location in net core better to take certs from top folder
var certFile = GetCertPath(Directory.GetParent(Directory.GetCurrentDirectory()));
return new X509Certificate2(certFile, "ThriftTest");
}
private static string GetCertPath(DirectoryInfo di, int maxCount = 6)
{
var topDir = di;
var certFile =
topDir.EnumerateFiles("ThriftTest.pfx", SearchOption.AllDirectories)
.FirstOrDefault();
if (certFile == null)
{
if (maxCount == 0)
throw new FileNotFoundException("Cannot find file in directories");
return GetCertPath(di.Parent, maxCount - 1);
}
return certFile.FullName;
}
private static X509Certificate LocalCertificateSelectionCallback(object sender,
string targetHost, X509CertificateCollection localCertificates,
X509Certificate remoteCertificate, string[] acceptableIssuers)
{
return GetCertificate();
}
private static bool CertValidator(object sender, X509Certificate certificate,
X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
private static Tuple<Protocol, TProtocol> GetProtocol(string[] args, TClientTransport transport)
{
var protocol = args.FirstOrDefault(x => x.StartsWith("-pr"))?.Split(':')?[1];
Protocol selectedProtocol;
if (Enum.TryParse(protocol, true, out selectedProtocol))
{
switch (selectedProtocol)
{
case Protocol.Binary:
return new Tuple<Protocol, TProtocol>(selectedProtocol, new TBinaryProtocol(transport));
case Protocol.Compact:
return new Tuple<Protocol, TProtocol>(selectedProtocol, new TCompactProtocol(transport));
case Protocol.Json:
return new Tuple<Protocol, TProtocol>(selectedProtocol, new TJsonProtocol(transport));
case Protocol.Multiplexed:
// it returns BinaryProtocol to avoid making wrapped protocol as public in TProtocolDecorator (in RunClientAsync it will be wrapped into Multiplexed protocol)
return new Tuple<Protocol, TProtocol>(selectedProtocol, new TBinaryProtocol(transport));
}
}
return new Tuple<Protocol, TProtocol>(selectedProtocol, new TBinaryProtocol(transport));
}
private static async Task RunClientAsync(Tuple<Protocol, TProtocol> protocolTuple, CancellationToken cancellationToken)
{
try
{
var protocol = protocolTuple.Item2;
var protocolType = protocolTuple.Item1;
TBaseClient client = null;
try
{
if (protocolType != Protocol.Multiplexed)
{
client = new Calculator.Client(protocol);
await ExecuteCalculatorClientOperations(cancellationToken, (Calculator.Client)client);
}
else
{
// it uses binary protocol there to create Multiplexed protocols
var multiplex = new TMultiplexedProtocol(protocol, nameof(Calculator));
client = new Calculator.Client(multiplex);
await ExecuteCalculatorClientOperations(cancellationToken, (Calculator.Client)client);
multiplex = new TMultiplexedProtocol(protocol, nameof(SharedService));
client = new SharedService.Client(multiplex);
await ExecuteSharedServiceClientOperations(cancellationToken, (SharedService.Client)client);
}
}
catch (Exception ex)
{
Logger.LogError($"{client?.ClientId} " + ex);
}
finally
{
protocol.Transport.Close();
}
}
catch (TApplicationException x)
{
Logger.LogError(x.ToString());
}
}
private static async Task ExecuteCalculatorClientOperations(CancellationToken cancellationToken, Calculator.Client client)
{
await client.OpenTransportAsync(cancellationToken);
// Async version
Logger.LogInformation($"{client.ClientId} PingAsync()");
await client.pingAsync(cancellationToken);
Logger.LogInformation($"{client.ClientId} AddAsync(1,1)");
var sum = await client.addAsync(1, 1, cancellationToken);
Logger.LogInformation($"{client.ClientId} AddAsync(1,1)={sum}");
var work = new Work
{
Op = Operation.DIVIDE,
Num1 = 1,
Num2 = 0
};
try
{
Logger.LogInformation($"{client.ClientId} CalculateAsync(1)");
await client.calculateAsync(1, work, cancellationToken);
Logger.LogInformation($"{client.ClientId} Whoa we can divide by 0");
}
catch (InvalidOperation io)
{
Logger.LogInformation($"{client.ClientId} Invalid operation: " + io);
}
work.Op = Operation.SUBTRACT;
work.Num1 = 15;
work.Num2 = 10;
try
{
Logger.LogInformation($"{client.ClientId} CalculateAsync(1)");
var diff = await client.calculateAsync(1, work, cancellationToken);
Logger.LogInformation($"{client.ClientId} 15-10={diff}");
}
catch (InvalidOperation io)
{
Logger.LogInformation($"{client.ClientId} Invalid operation: " + io);
}
Logger.LogInformation($"{client.ClientId} GetStructAsync(1)");
var log = await client.getStructAsync(1, cancellationToken);
Logger.LogInformation($"{client.ClientId} Check log: {log.Value}");
Logger.LogInformation($"{client.ClientId} ZipAsync() with delay 100mc on server side");
await client.zipAsync(cancellationToken);
}
private static async Task ExecuteSharedServiceClientOperations(CancellationToken cancellationToken, SharedService.Client client)
{
await client.OpenTransportAsync(cancellationToken);
// Async version
Logger.LogInformation($"{client.ClientId} SharedService GetStructAsync(1)");
var log = await client.getStructAsync(1, cancellationToken);
Logger.LogInformation($"{client.ClientId} SharedService Value: {log.Value}");
}
private enum Transport
{
Tcp,
NamedPipe,
Http,
TcpBuffered,
Framed,
TcpTls
}
private enum Protocol
{
Binary,
Compact,
Json,
Multiplexed
}
}
}

View file

@ -0,0 +1,40 @@
// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
// to you 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.
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("The Apache Software Foundation")]
[assembly: AssemblyProduct("Thrift")]
[assembly: AssemblyCopyright("The Apache Software Foundation")]
[assembly: AssemblyTrademark("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("de78a01b-f7c6-49d1-97da-669d2ed37641")]

View file

@ -0,0 +1,8 @@
{
"profiles": {
"Client": {
"commandName": "Project",
"commandLineArgs": "-p:multiplexed"
}
}
}

Binary file not shown.

View file

@ -0,0 +1,3 @@
# ignore for autogenerated files
/shared
/tutorial

View file

@ -0,0 +1,30 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<AssemblyName>Interfaces</AssemblyName>
<PackageId>Interfaces</PackageId>
<GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
<GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
<GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
<GenerateAssemblyCopyrightAttribute>false</GenerateAssemblyCopyrightAttribute>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../../../lib/netcore/Thrift/Thrift.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="System.ServiceModel.Primitives" Version="[4.4,)" />
</ItemGroup>
<Target Name="PreBuild" BeforeTargets="_GenerateRestoreProjectSpec;Restore;Compile">
<Exec Condition="'$(OS)' == 'Windows_NT'" Command="where thrift" ConsoleToMSBuild="true">
<Output TaskParameter="ConsoleOutput" PropertyName="PathToThrift" />
</Exec>
<Exec Condition="Exists('$(PathToThrift)')" Command="$(PathToThrift) -out $(ProjectDir) -gen netcore:wcf,union,serial,hashcode -r ./../../tutorial.thrift" />
<Exec Condition="Exists('thrift')" Command="thrift -out $(ProjectDir) -gen netcore:wcf,union,serial,hashcode -r ./../../tutorial.thrift" />
<Exec Condition="Exists('./../../../compiler/cpp/thrift')" Command="./../../../compiler/cpp/thrift -out $(ProjectDir) -gen netcore:wcf,union,serial,hashcode -r ./../../tutorial.thrift" />
</Target>
</Project>

View file

@ -0,0 +1,40 @@
// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
// to you 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.
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("The Apache Software Foundation")]
[assembly: AssemblyProduct("Thrift")]
[assembly: AssemblyCopyright("The Apache Software Foundation")]
[assembly: AssemblyTrademark("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("4d13163d-9067-4c9c-8af0-64e08451397d")]

View file

@ -0,0 +1,42 @@
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
#
SUBDIRS = .
all-local:
$(DOTNETCORE) build
clean-local:
$(RM) Interfaces.dll
$(RM) -r Client/bin
$(RM) -r Client/obj
$(RM) -r Server/bin
$(RM) -r Server/obj
$(RM) -r Interfaces/bin
$(RM) -r Interfaces/obj
EXTRA_DIST = \
Client \
Interfaces \
README.md \
Server \
Tutorial.sln \
build.cmd \
build.sh

View file

@ -0,0 +1,278 @@
# Building of samples for different platforms
# Reused components
- NET Core Standard 2.0
- NET Core App 2.0
# How to build
- Download and install the latest .NET Core SDK for your platform https://www.microsoft.com/net/core#windowsvs2015 (archive for SDK 1.0.0-preview2-003121 located by: https://github.com/dotnet/core/blob/master/release-notes/download-archive.md)
- Ensure that you have thrift.exe which supports netcore lib and it added to PATH
- Go to current folder
- Run **build.sh** or **build.cmd** from the root of cloned repository
- Check tests in **src/Tests** folder
- Continue with /tutorials/netcore
# How to run
Notes: dotnet run supports passing arguments to app after -- symbols (https://docs.microsoft.com/en-us/dotnet/articles/core/tools/dotnet-run) - example: **dotnet run -- -h** will show help for app
- build
- go to folder (Client/Server)
- run with specifying of correct parameters **dotnet run -tr:tcp -pr:multiplexed**, **dotnet run -help** (later, after migration to csproj and latest SDK will be possibility to use more usable form **dotnet run -- arguments**)
#Notes
- Possible adding additional platforms after stabilization of .NET Core (runtimes, platforms (Red Hat Linux, OpenSuse, etc.)
#Known issues
- In trace logging mode you can see some not important internal exceptions
# Running of samples
Please install Thrift C# .NET Core library or copy sources and build them to correcly build and run samples
# NetCore Server
Usage:
Server.exe -h
will diplay help information
Server.exe -tr:<transport> -pr:<protocol>
will run server with specified arguments (tcp transport and binary protocol by default)
Options:
-tr (transport):
tcp - (default) tcp transport will be used (host - ""localhost"", port - 9090)
tcpbuffered - tcp buffered transport will be used (host - ""localhost"", port - 9090)
namedpipe - namedpipe transport will be used (pipe address - "".test"")
http - http transport will be used (http address - ""localhost:9090"")
tcptls - tcp transport with tls will be used (host - ""localhost"", port - 9090)
framed - tcp framed transport will be used (host - ""localhost"", port - 9090)
-pr (protocol):
binary - (default) binary protocol will be used
compact - compact protocol will be used
json - json protocol will be used
Sample:
Server.exe -tr:tcp
**Remarks**:
For TcpTls mode certificate's file ThriftTest.pfx should be in directory with binaries in case of command line usage (or at project level in case of debugging from IDE).
Password for certificate - "ThriftTest".
# NetCore Client
Usage:
Client.exe -h
will diplay help information
Client.exe -tr:<transport> -pr:<protocol> -mc:<numClients>
will run client with specified arguments (tcp transport and binary protocol by default)
Options:
-tr (transport):
tcp - (default) tcp transport will be used (host - ""localhost"", port - 9090)
tcpbuffered - buffered transport over tcp will be used (host - ""localhost"", port - 9090)
namedpipe - namedpipe transport will be used (pipe address - "".test"")
http - http transport will be used (address - ""http://localhost:9090"")
tcptls - tcp tls transport will be used (host - ""localhost"", port - 9090)
framed - tcp framed transport will be used (host - ""localhost"", port - 9090)
-pr (protocol):
binary - (default) binary protocol will be used
compact - compact protocol will be used
json - json protocol will be used
-mc (multiple clients):
<numClients> - number of multiple clients to connect to server (max 100, default 1)
Sample:
Client.exe -tr:tcp -pr:binary -mc:10
Remarks:
For TcpTls mode certificate's file ThriftTest.pfx should be in directory
with binaries in case of command line usage (or at project level in case of debugging from IDE).
Password for certificate - "ThriftTest".
# How to test communication between NetCore and Python
* Generate code with the latest **thrift.exe** util
* Ensure that **thrift.exe** util generated folder **gen-py** with generated code for Python
* Create **client.py** and **server.py** from the code examples below and save them to the folder with previosly generated folder **gen-py**
* Run netcore samples (client and server) and python samples (client and server)
Remarks:
Samples of client and server code below use correct methods (operations)
and fields (properties) according to generated contracts from *.thrift files
At Windows 10 add record **127.0.0.1 testserver** to **C:\Windows\System32\drivers\etc\hosts** file
for correct work of python server
**Python Client:**
```python
import sys
import glob
sys.path.append('gen-py')
from tutorial import Calculator
from tutorial.ttypes import InvalidOperation, Operation, Work
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
def main():
# Make socket
transport = TSocket.TSocket('127.0.0.1', 9090)
# Buffering is critical. Raw sockets are very slow
transport = TTransport.TBufferedTransport(transport)
# Wrap in a protocol
protocol = TBinaryProtocol.TBinaryProtocol(transport)
# Create a client to use the protocol encoder
client = Calculator.Client(protocol)
# Connect!
transport.open()
client.Ping()
print('ping()')
sum = client.Add(1, 1)
print(('1+1=%d' % (sum)))
work = Work()
work.Op = Operation.Divide
work.Num1 = 1
work.Num2 = 0
try:
quotient = client.Calculate(1, work)
print('Whoa? You know how to divide by zero?')
print('FYI the answer is %d' % quotient)
except InvalidOperation as e:
print(('InvalidOperation: %r' % e))
work.Op = Operation.Substract
work.Num1 = 15
work.Num2 = 10
diff = client.Calculate(1, work)
print(('15-10=%d' % (diff)))
log = client.GetStruct(1)
print(('Check log: %s' % (log.Value)))
client.Zip()
print('zip()')
# Close!
transport.close()
if __name__ == '__main__':
try:
main()
except Thrift.TException as tx:
print('%s' % tx.message)
```
**Python Server:**
```python
import glob
import sys
sys.path.append('gen-py')
from tutorial import Calculator
from tutorial.ttypes import InvalidOperation, Operation
from shared.ttypes import SharedStruct
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
class CalculatorHandler:
def __init__(self):
self.log = {}
def Ping(self):
print('ping()')
def Add(self, n1, n2):
print('add(%d,%d)' % (n1, n2))
return n1 + n2
def Calculate(self, logid, work):
print('calculate(%d, %r)' % (logid, work))
if work.Op == Operation.Add:
val = work.Num1 + work.Num2
elif work.Op == Operation.Substract:
val = work.Num1 - work.Num2
elif work.Op == Operation.Multiply:
val = work.Num1 * work.Num2
elif work.Op == Operation.Divide:
if work.Num2 == 0:
x = InvalidOperation()
x.WhatOp = work.Op
x.Why = 'Cannot divide by 0'
raise x
val = work.Num1 / work.Num2
else:
x = InvalidOperation()
x.WhatOp = work.Op
x.Why = 'Invalid operation'
raise x
log = SharedStruct()
log.Key = logid
log.Value = '%d' % (val)
self.log[logid] = log
return val
def GetStruct(self, key):
print('getStruct(%d)' % (key))
return self.log[key]
def Zip(self):
print('zip()')
if __name__ == '__main__':
handler = CalculatorHandler()
processor = Calculator.Processor(handler)
transport = TSocket.TServerSocket(host="testserver", port=9090)
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()
server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
print('Starting the server...')
server.serve()
print('done.')
# You could do one of these for a multithreaded server
# server = TServer.TThreadedServer(processor, transport, tfactory, pfactory)
# server = TServer.TThreadPoolServer(processor, transport, tfactory, pfactory)
```

View file

@ -0,0 +1,428 @@
// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
// to you 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.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Thrift;
using Thrift.Protocols;
using Thrift.Server;
using Thrift.Transports;
using Thrift.Transports.Server;
using tutorial;
using shared;
namespace Server
{
public class Program
{
private static readonly ILogger Logger = new LoggerFactory().AddConsole(LogLevel.Trace).AddDebug(LogLevel.Trace).CreateLogger(nameof(Server));
public static void Main(string[] args)
{
args = args ?? new string[0];
if (args.Any(x => x.StartsWith("-help", StringComparison.OrdinalIgnoreCase)))
{
DisplayHelp();
return;
}
using (var source = new CancellationTokenSource())
{
RunAsync(args, source.Token).GetAwaiter().GetResult();
Logger.LogInformation("Press any key to stop...");
Console.ReadLine();
source.Cancel();
}
Logger.LogInformation("Server stopped");
}
private static void DisplayHelp()
{
Logger.LogInformation(@"
Usage:
Server.exe -help
will diplay help information
Server.exe -tr:<transport> -pr:<protocol>
will run server with specified arguments (tcp transport and binary protocol by default)
Options:
-tr (transport):
tcp - (default) tcp transport will be used (host - ""localhost"", port - 9090)
tcpbuffered - tcp buffered transport will be used (host - ""localhost"", port - 9090)
namedpipe - namedpipe transport will be used (pipe address - "".test"")
http - http transport will be used (http address - ""localhost:9090"")
tcptls - tcp transport with tls will be used (host - ""localhost"", port - 9090)
framed - tcp framed transport will be used (host - ""localhost"", port - 9090)
-pr (protocol):
binary - (default) binary protocol will be used
compact - compact protocol will be used
json - json protocol will be used
multiplexed - multiplexed protocol will be used
Sample:
Server.exe -tr:tcp
");
}
private static async Task RunAsync(string[] args, CancellationToken cancellationToken)
{
var selectedTransport = GetTransport(args);
var selectedProtocol = GetProtocol(args);
if (selectedTransport == Transport.Http)
{
new HttpServerSample().Run(cancellationToken);
}
else
{
await RunSelectedConfigurationAsync(selectedTransport, selectedProtocol, cancellationToken);
}
}
private static Protocol GetProtocol(string[] args)
{
var transport = args.FirstOrDefault(x => x.StartsWith("-pr"))?.Split(':')?[1];
Enum.TryParse(transport, true, out Protocol selectedProtocol);
return selectedProtocol;
}
private static Transport GetTransport(string[] args)
{
var transport = args.FirstOrDefault(x => x.StartsWith("-tr"))?.Split(':')?[1];
Enum.TryParse(transport, true, out Transport selectedTransport);
return selectedTransport;
}
private static async Task RunSelectedConfigurationAsync(Transport transport, Protocol protocol, CancellationToken cancellationToken)
{
var fabric = new LoggerFactory().AddConsole(LogLevel.Trace).AddDebug(LogLevel.Trace);
var handler = new CalculatorAsyncHandler();
ITAsyncProcessor processor = null;
TServerTransport serverTransport = null;
switch (transport)
{
case Transport.Tcp:
serverTransport = new TServerSocketTransport(9090);
break;
case Transport.TcpBuffered:
serverTransport = new TServerSocketTransport(port: 9090, clientTimeout: 10000, useBufferedSockets: true);
break;
case Transport.NamedPipe:
serverTransport = new TNamedPipeServerTransport(".test");
break;
case Transport.TcpTls:
serverTransport = new TTlsServerSocketTransport(9090, false, GetCertificate(), ClientCertValidator, LocalCertificateSelectionCallback);
break;
case Transport.Framed:
serverTransport = new TServerFramedTransport(9090);
break;
}
ITProtocolFactory inputProtocolFactory;
ITProtocolFactory outputProtocolFactory;
switch (protocol)
{
case Protocol.Binary:
{
inputProtocolFactory = new TBinaryProtocol.Factory();
outputProtocolFactory = new TBinaryProtocol.Factory();
processor = new Calculator.AsyncProcessor(handler);
}
break;
case Protocol.Compact:
{
inputProtocolFactory = new TCompactProtocol.Factory();
outputProtocolFactory = new TCompactProtocol.Factory();
processor = new Calculator.AsyncProcessor(handler);
}
break;
case Protocol.Json:
{
inputProtocolFactory = new TJsonProtocol.Factory();
outputProtocolFactory = new TJsonProtocol.Factory();
processor = new Calculator.AsyncProcessor(handler);
}
break;
case Protocol.Multiplexed:
{
inputProtocolFactory = new TBinaryProtocol.Factory();
outputProtocolFactory = new TBinaryProtocol.Factory();
var calcHandler = new CalculatorAsyncHandler();
var calcProcessor = new Calculator.AsyncProcessor(calcHandler);
var sharedServiceHandler = new SharedServiceAsyncHandler();
var sharedServiceProcessor = new SharedService.AsyncProcessor(sharedServiceHandler);
var multiplexedProcessor = new TMultiplexedProcessor();
multiplexedProcessor.RegisterProcessor(nameof(Calculator), calcProcessor);
multiplexedProcessor.RegisterProcessor(nameof(SharedService), sharedServiceProcessor);
processor = multiplexedProcessor;
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(protocol), protocol, null);
}
try
{
Logger.LogInformation(
$"Selected TAsyncServer with {serverTransport} transport, {processor} processor and {inputProtocolFactory} protocol factories");
var server = new AsyncBaseServer(processor, serverTransport, inputProtocolFactory, outputProtocolFactory, fabric);
Logger.LogInformation("Starting the server...");
await server.ServeAsync(cancellationToken);
}
catch (Exception x)
{
Logger.LogInformation(x.ToString());
}
}
private static X509Certificate2 GetCertificate()
{
// due to files location in net core better to take certs from top folder
var certFile = GetCertPath(Directory.GetParent(Directory.GetCurrentDirectory()));
return new X509Certificate2(certFile, "ThriftTest");
}
private static string GetCertPath(DirectoryInfo di, int maxCount = 6)
{
var topDir = di;
var certFile =
topDir.EnumerateFiles("ThriftTest.pfx", SearchOption.AllDirectories)
.FirstOrDefault();
if (certFile == null)
{
if (maxCount == 0)
throw new FileNotFoundException("Cannot find file in directories");
return GetCertPath(di.Parent, maxCount - 1);
}
return certFile.FullName;
}
private static X509Certificate LocalCertificateSelectionCallback(object sender,
string targetHost, X509CertificateCollection localCertificates,
X509Certificate remoteCertificate, string[] acceptableIssuers)
{
return GetCertificate();
}
private static bool ClientCertValidator(object sender, X509Certificate certificate,
X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
private enum Transport
{
Tcp,
TcpBuffered,
NamedPipe,
Http,
TcpTls,
Framed
}
private enum Protocol
{
Binary,
Compact,
Json,
Multiplexed
}
public class HttpServerSample
{
public void Run(CancellationToken cancellationToken)
{
var config = new ConfigurationBuilder()
.AddEnvironmentVariables(prefix: "ASPNETCORE_")
.Build();
var host = new WebHostBuilder()
.UseConfiguration(config)
.UseKestrel()
.UseUrls("http://localhost:9090")
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>()
.Build();
host.RunAsync(cancellationToken).GetAwaiter().GetResult();
}
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<Calculator.IAsync, CalculatorAsyncHandler>();
services.AddTransient<ITAsyncProcessor, Calculator.AsyncProcessor>();
services.AddTransient<THttpServerTransport, THttpServerTransport>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
app.UseMiddleware<THttpServerTransport>();
}
}
}
public class CalculatorAsyncHandler : Calculator.IAsync
{
private readonly Dictionary<int, SharedStruct> _log = new Dictionary<int, SharedStruct>();
public CalculatorAsyncHandler()
{
}
public async Task<SharedStruct> getStructAsync(int key,
CancellationToken cancellationToken)
{
Logger.LogInformation("GetStructAsync({0})", key);
return await Task.FromResult(_log[key]);
}
public async Task pingAsync(CancellationToken cancellationToken)
{
Logger.LogInformation("PingAsync()");
await Task.CompletedTask;
}
public async Task<int> addAsync(int num1, int num2, CancellationToken cancellationToken)
{
Logger.LogInformation($"AddAsync({num1},{num2})");
return await Task.FromResult(num1 + num2);
}
public async Task<int> calculateAsync(int logid, Work w, CancellationToken cancellationToken)
{
Logger.LogInformation($"CalculateAsync({logid}, [{w.Op},{w.Num1},{w.Num2}])");
var val = 0;
switch (w.Op)
{
case Operation.ADD:
val = w.Num1 + w.Num2;
break;
case Operation.SUBTRACT:
val = w.Num1 - w.Num2;
break;
case Operation.MULTIPLY:
val = w.Num1 * w.Num2;
break;
case Operation.DIVIDE:
if (w.Num2 == 0)
{
var io = new InvalidOperation
{
WhatOp = (int) w.Op,
Why = "Cannot divide by 0"
};
throw io;
}
val = w.Num1 / w.Num2;
break;
default:
{
var io = new InvalidOperation
{
WhatOp = (int) w.Op,
Why = "Unknown operation"
};
throw io;
}
}
var entry = new SharedStruct
{
Key = logid,
Value = val.ToString()
};
_log[logid] = entry;
return await Task.FromResult(val);
}
public async Task zipAsync(CancellationToken cancellationToken)
{
Logger.LogInformation("ZipAsync() with delay 100mc");
await Task.Delay(100, CancellationToken.None);
}
}
public class SharedServiceAsyncHandler : SharedService.IAsync
{
public async Task<SharedStruct> getStructAsync(int key, CancellationToken cancellationToken)
{
Logger.LogInformation("GetStructAsync({0})", key);
return await Task.FromResult(new SharedStruct()
{
Key = key,
Value = "GetStructAsync"
});
}
}
}
}

View file

@ -0,0 +1,40 @@
// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
// to you 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.
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("The Apache Software Foundation")]
[assembly: AssemblyProduct("Thrift")]
[assembly: AssemblyCopyright("The Apache Software Foundation")]
[assembly: AssemblyTrademark("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e210fc10-5aff-4b04-ac21-58afc7b74b0c")]

View file

@ -0,0 +1,8 @@
{
"profiles": {
"Server": {
"commandName": "Project",
"commandLineArgs": "-p:multiplexed"
}
}
}

View file

@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
<AssemblyName>Server</AssemblyName>
<PackageId>Server</PackageId>
<OutputType>Exe</OutputType>
<GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
<GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
<GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
<GenerateAssemblyCopyrightAttribute>false</GenerateAssemblyCopyrightAttribute>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../Interfaces/Interfaces.csproj" />
<ProjectReference Include="../../../lib/netcore/Thrift/Thrift.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore" Version="[2.0,)" />
<PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration" Version="[2.0,)" />
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="[2.0,)" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="[2.0,)" />
</ItemGroup>
</Project>

Binary file not shown.

View file

@ -0,0 +1,78 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26114.2
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Thrift", "..\..\lib\netcore\Thrift\Thrift.csproj", "{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Interfaces", "Interfaces\Interfaces.csproj", "{B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Client", "Client\Client.csproj", "{E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Server", "Server\Server.csproj", "{E08F5B84-2B4A-4E09-82D1-E0715775CE5E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Debug|x64.ActiveCfg = Debug|Any CPU
{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Debug|x64.Build.0 = Debug|Any CPU
{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Debug|x86.ActiveCfg = Debug|Any CPU
{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Debug|x86.Build.0 = Debug|Any CPU
{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Release|Any CPU.Build.0 = Release|Any CPU
{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Release|x64.ActiveCfg = Release|Any CPU
{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Release|x64.Build.0 = Release|Any CPU
{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Release|x86.ActiveCfg = Release|Any CPU
{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Release|x86.Build.0 = Release|Any CPU
{B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Debug|x64.ActiveCfg = Debug|Any CPU
{B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Debug|x64.Build.0 = Debug|Any CPU
{B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Debug|x86.ActiveCfg = Debug|Any CPU
{B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Debug|x86.Build.0 = Debug|Any CPU
{B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Release|Any CPU.Build.0 = Release|Any CPU
{B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Release|x64.ActiveCfg = Release|Any CPU
{B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Release|x64.Build.0 = Release|Any CPU
{B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Release|x86.ActiveCfg = Release|Any CPU
{B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Release|x86.Build.0 = Release|Any CPU
{E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Debug|x64.ActiveCfg = Debug|Any CPU
{E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Debug|x64.Build.0 = Debug|Any CPU
{E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Debug|x86.ActiveCfg = Debug|Any CPU
{E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Debug|x86.Build.0 = Debug|Any CPU
{E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Release|Any CPU.Build.0 = Release|Any CPU
{E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Release|x64.ActiveCfg = Release|Any CPU
{E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Release|x64.Build.0 = Release|Any CPU
{E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Release|x86.ActiveCfg = Release|Any CPU
{E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Release|x86.Build.0 = Release|Any CPU
{E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Debug|x64.ActiveCfg = Debug|Any CPU
{E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Debug|x64.Build.0 = Debug|Any CPU
{E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Debug|x86.ActiveCfg = Debug|Any CPU
{E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Debug|x86.Build.0 = Debug|Any CPU
{E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Release|Any CPU.Build.0 = Release|Any CPU
{E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Release|x64.ActiveCfg = Release|Any CPU
{E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Release|x64.Build.0 = Release|Any CPU
{E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Release|x86.ActiveCfg = Release|Any CPU
{E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {070A5D1D-B29D-4603-999D-693DB444AD0D}
EndGlobalSection
EndGlobal

View file

@ -0,0 +1,25 @@
@echo off
rem /*
rem * Licensed to the Apache Software Foundation (ASF) under one
rem * or more contributor license agreements. See the NOTICE file
rem * distributed with this work for additional information
rem * regarding copyright ownership. The ASF licenses this file
rem * to you under the Apache License, Version 2.0 (the
rem * "License"); you may not use this file except in compliance
rem * with the License. You may obtain a copy of the License at
rem *
rem * http://www.apache.org/licenses/LICENSE-2.0
rem *
rem * Unless required by applicable law or agreed to in writing,
rem * software distributed under the License is distributed on an
rem * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
rem * KIND, either express or implied. See the License for the
rem * specific language governing permissions and limitations
rem * under the License.
rem */
setlocal
dotnet --info
dotnet build
:eof

26
vendor/git.apache.org/thrift.git/tutorial/netcore/build.sh generated vendored Executable file
View file

@ -0,0 +1,26 @@
#!/usr/bin/env bash
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
#
#exit if any command fails
set -e
dotnet --info
dotnet build

View file

@ -17,8 +17,6 @@
# under the License.
#
THRIFT = $(top_builddir)/compiler/cpp/thrift
gen-nodejs/Calculator.js gen-nodejs/SharedService.js: $(top_srcdir)/tutorial/tutorial.thrift
$(THRIFT) --gen js:node -r $<

View file

@ -20,7 +20,7 @@
var thrift = require('thrift');
var Calculator = require('./gen-nodejs/Calculator');
var ttypes = require('./gen-nodejs/tutorial_types');
const assert = require('assert');
var transport = thrift.TBufferedTransport;
var protocol = thrift.TBinaryProtocol;

View file

@ -20,7 +20,7 @@
var thrift = require('thrift');
var Calculator = require('./gen-nodejs/Calculator');
var ttypes = require('./gen-nodejs/tutorial_types');
const assert = require('assert');
var transport = thrift.TBufferedTransport;
var protocol = thrift.TBinaryProtocol;

View file

@ -1,5 +1,5 @@
Name: tutorial
Version: 0.10.0
Version: 0.12.0
OASISFormat: 0.3
Synopsis: OCaml Tutorial example
Authors: Apache Thrift Developers <dev@thrift.apache.org>

View file

@ -37,10 +37,10 @@ use tutorial::Types;
use Data::Dumper;
my $socket = new Thrift::Socket('localhost',9090);
my $transport = new Thrift::BufferedTransport($socket,1024,1024);
my $protocol = new Thrift::BinaryProtocol($transport);
my $client = new tutorial::CalculatorClient($protocol);
my $socket = Thrift::Socket->new('localhost',9090);
my $transport = Thrift::BufferedTransport->new($socket,1024,1024);
my $protocol = Thrift::BinaryProtocol->new($transport);
my $client = tutorial::CalculatorClient->new($protocol);
eval{
@ -53,7 +53,7 @@ eval{
my $sum = $client->add(1,1);
print "1+1=$sum\n";
my $work = new tutorial::Work();
my $work = tutorial::Work->new();
$work->op(tutorial::Operation::DIVIDE);
$work->num1(1);
@ -63,7 +63,7 @@ eval{
$client->calculate(1, $work);
print "Whoa! We can divide by zero?\n";
}; if($@) {
warn "InvalidOperation: ".Dumper($@);
warn 'InvalidOperation: '.Dumper($@);
}
$work->op(tutorial::Operation::SUBTRACT);

View file

@ -1,4 +1,4 @@
#!/usr/bin/perl
#!/usr/bin/env perl
#
# Licensed to the Apache Software Foundation (ASF) under one
@ -67,20 +67,20 @@ sub calculate
} elsif ($op == tutorial::Operation::DIVIDE) {
if ($num2 == 0)
{
my $x = new tutorial::InvalidOperation;
my $x = tutorial::InvalidOperation->new();
$x->whatOp($op);
$x->why('Cannot divide by 0');
die $x;
}
$val = $num1 / $num2;
} else {
my $x = new tutorial::InvalidOperation;
my $x = tutorial::InvalidOperation->new();
$x->whatOp($op);
$x->why('Invalid operation');
die $x;
}
my $log = new shared::SharedStruct;
my $log = shared::SharedStruct->new();
$log->key($logid);
$log->value(int($val));
$self->{log}->{$logid} = $log;
@ -104,10 +104,10 @@ sub zip
eval {
my $handler = new CalculatorHandler;
my $processor = new tutorial::CalculatorProcessor($handler);
my $serversocket = new Thrift::ServerSocket(9090);
my $forkingserver = new Thrift::ForkingServer($processor, $serversocket);
my $handler = CalculatorHandler->new();
my $processor = tutorial::CalculatorProcessor->new($handler);
my $serversocket = Thrift::ServerSocket->new(9090);
my $forkingserver = Thrift::ForkingServer->new($processor, $serversocket);
print "Starting the server...\n";
$forkingserver->serve();
print "done.\n";

View file

@ -5,7 +5,7 @@ namespace tutorial\php;
error_reporting(E_ALL);
require_once __DIR__.'/../../lib/php/lib/Thrift/ClassLoader/ThriftClassLoader.php';
require_once __DIR__.'/../../lib/php/lib/ClassLoader/ThriftClassLoader.php';
use Thrift\ClassLoader\ThriftClassLoader;

View file

@ -5,7 +5,7 @@ namespace tutorial\php;
error_reporting(E_ALL);
require_once __DIR__.'/../../lib/php/lib/Thrift/ClassLoader/ThriftClassLoader.php';
require_once __DIR__.'/../../lib/php/lib/ClassLoader/ThriftClassLoader.php';
use Thrift\ClassLoader\ThriftClassLoader;

View file

@ -17,8 +17,6 @@
# under the License.
#
THRIFT = $(top_builddir)/compiler/cpp/thrift
gen-py.tornado/tutorial/Calculator.py gen-py.tornado/shared/SharedService.py: $(top_srcdir)/tutorial/tutorial.thrift
$(THRIFT) --gen py:tornado -r $<

View file

@ -17,8 +17,6 @@
# under the License.
#
THRIFT = $(top_builddir)/compiler/cpp/thrift
gen-py/tutorial/Calculator.py gen-py/shared/SharedService.py: $(top_srcdir)/tutorial/tutorial.thrift
$(THRIFT) --gen py:twisted -r $<

View file

@ -17,8 +17,6 @@
# under the License.
#
THRIFT = $(top_builddir)/compiler/cpp/thrift
gen-py/tutorial/Calculator.py gen-py/shared/SharedService.py: $(top_srcdir)/tutorial/tutorial.thrift
$(THRIFT) --gen py -r $<

View file

@ -81,6 +81,7 @@ def main():
# Close!
transport.close()
if __name__ == '__main__':
try:
main()

View file

@ -82,10 +82,11 @@ class CalculatorHandler:
def zip(self):
print('zip()')
if __name__ == '__main__':
handler = CalculatorHandler()
processor = Calculator.Processor(handler)
transport = TSocket.TServerSocket(port=9090)
transport = TSocket.TServerSocket(host='127.0.0.1', port=9090)
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()

View file

@ -17,8 +17,6 @@
# under the License.
#
THRIFT = $(top_builddir)/compiler/cpp/thrift
gen-py/calculator.rb gen-py/shared_service.rb: $(top_srcdir)/tutorial/tutorial.thrift
$(THRIFT) --gen rb -r $<

View file

@ -0,0 +1,16 @@
[package]
name = "thrift-tutorial"
version = "0.1.0"
license = "Apache-2.0"
authors = ["Apache Thrift Developers <dev@thrift.apache.org>"]
exclude = ["Makefile*", "shared.rs", "tutorial.rs"]
publish = false
[dependencies]
clap = "<2.28.0"
ordered-float = "0.3.0"
try_from = "0.2.0"
[dependencies.thrift]
path = "../../lib/rs"

View file

@ -0,0 +1,52 @@
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
#
THRIFT = $(top_builddir)/compiler/cpp/thrift
gen-rs/tutorial.rs gen-rs/shared.rs: $(top_srcdir)/tutorial/tutorial.thrift
$(THRIFT) -out src --gen rs -r $<
all-local: gen-rs/tutorial.rs
$(CARGO) build
[ -d bin ] || mkdir bin
cp target/debug/tutorial_server bin/tutorial_server
cp target/debug/tutorial_client bin/tutorial_client
check: all
tutorialserver: all
bin/tutorial_server
tutorialclient: all
bin/tutorial_client
clean-local:
$(CARGO) clean
-$(RM) Cargo.lock
-$(RM) src/shared.rs
-$(RM) src/tutorial.rs
-$(RM) -r bin
EXTRA_DIST = \
Cargo.toml \
src/lib.rs \
src/bin/tutorial_server.rs \
src/bin/tutorial_client.rs \
README.md

317
vendor/git.apache.org/thrift.git/tutorial/rs/README.md generated vendored Normal file
View file

@ -0,0 +1,317 @@
# Rust Language Bindings for Thrift
## Getting Started
1. Get the [Thrift compiler](https://thrift.apache.org).
2. Add the following crates to your `Cargo.toml`.
```toml
thrift = "x.y.z" # x.y.z is the version of the thrift compiler
ordered_float = "0.3.0"
try_from = "0.2.0"
```
3. Add the same crates to your `lib.rs` or `main.rs`.
```rust
extern crate ordered_float;
extern crate thrift;
extern crate try_from;
```
4. Generate Rust sources for your IDL (for example, `Tutorial.thrift`).
```shell
thrift -out my_rust_program/src --gen rs -r Tutorial.thrift
```
5. Use the generated source in your code.
```rust
// add extern crates here, or in your lib.rs
extern crate ordered_float;
extern crate thrift;
extern crate try_from;
// generated Rust module
use tutorial;
use thrift::protocol::{TCompactInputProtocol, TCompactOutputProtocol};
use thrift::protocol::{TInputProtocol, TOutputProtocol};
use thrift::transport::{TFramedReadTransport, TFramedWriteTransport};
use thrift::transport::{TIoChannel, TTcpChannel};
use tutorial::{CalculatorSyncClient, TCalculatorSyncClient};
use tutorial::{Operation, Work};
fn main() {
match run() {
Ok(()) => println!("client ran successfully"),
Err(e) => {
println!("client failed with {:?}", e);
std::process::exit(1);
}
}
}
fn run() -> thrift::Result<()> {
//
// build client
//
println!("connect to server on 127.0.0.1:9090");
let mut c = TTcpTransport::new();
c.open("127.0.0.1:9090")?;
let (i_chan, o_chan) = c.split()?;
let i_prot = TCompactInputProtocol::new(
TFramedReadTransport::new(i_chan)
);
let o_prot = TCompactOutputProtocol::new(
TFramedWriteTransport::new(o_chan)
);
let client = CalculatorSyncClient::new(i_prot, o_prot);
//
// alright! - let's make some calls
//
// two-way, void return
client.ping()?;
// two-way with some return
let res = client.calculate(
72,
Work::new(7, 8, Operation::MULTIPLY, None)
)?;
println!("multiplied 7 and 8, got {}", res);
// two-way and returns a Thrift-defined exception
let res = client.calculate(
77,
Work::new(2, 0, Operation::DIVIDE, None)
);
match res {
Ok(v) => panic!("shouldn't have succeeded with result {}", v),
Err(e) => println!("divide by zero failed with {:?}", e),
}
// one-way
client.zip()?;
// done!
Ok(())
}
```
## Code Generation
### Thrift Files and Generated Modules
The Thrift code generator takes each Thrift file and generates a Rust module
with the same name snake-cased. For example, running the compiler on
`ThriftTest.thrift` creates `thrift_test.rs`. To use these generated files add
`mod ...` and `use ...` declarations to your `lib.rs` or `main.rs` - one for
each generated file.
### Results and Errors
The Thrift runtime library defines a `thrift::Result` and a `thrift::Error` type,
both of which are used throught the runtime library and in all generated code.
Conversions are defined from `std::io::Error`, `str` and `String` into
`thrift::Error`.
### Thrift Type and their Rust Equivalents
Thrift defines a number of types, each of which is translated into its Rust
equivalent by the code generator.
* Primitives (bool, i8, i16, i32, i64, double, string, binary)
* Typedefs
* Enums
* Containers
* Structs
* Unions
* Exceptions
* Services
* Constants (primitives, containers, structs)
In addition, unless otherwise noted, thrift includes are translated into
`use ...` statements in the generated code, and all declarations, parameters,
traits and types in the generated code are namespaced appropriately.
The following subsections cover each type and their generated Rust equivalent.
### Primitives
Thrift primitives have straightforward Rust equivalents.
* bool: `bool`
* i8: `i8`
* i16: `i16`
* i32: `i32`
* i64: `i64`
* double: `OrderedFloat<f64>`
* string: `String`
* binary: `Vec<u8>`
### Typedefs
A typedef is translated to a `pub type` declaration.
```thrift
typedef i64 UserId
typedef map<string, UserId> MapType
```
```rust
pub type UserId = i64;
pub type MapType = BTreeMap<String, Bonk>;
```
### Enums
A Thrift enum is represented as a Rust enum, and each variant is transcribed 1:1.
```thrift
enum Numberz
{
ONE = 1,
TWO,
THREE,
FIVE = 5,
SIX,
EIGHT = 8
}
```
```rust
#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum Numberz {
ONE = 1,
TWO = 2,
THREE = 3,
FIVE = 5,
SIX = 6,
EIGHT = 8,
}
impl TryFrom<i32> for Numberz {
// ...
}
```
### Containers
Thrift has three container types: list, set and map. They are translated into
Rust `Vec`, `BTreeSet` and `BTreeMap` respectively. Any Thrift type (this
includes structs, enums and typedefs) can be a list/set element or a map
key/value.
#### List
```thrift
list <i32> numbers
```
```rust
numbers: Vec<i32>
```
#### Set
```thrift
set <i32> numbers
```
```rust
numbers: BTreeSet<i32>
```
#### Map
```thrift
map <string, i32> numbers
```
```rust
numbers: BTreeMap<String, i32>
```
### Structs
A Thrift struct is represented as a Rust struct, and each field transcribed 1:1.
```thrift
struct CrazyNesting {
1: string string_field,
2: optional set<Insanity> set_field,
3: required list<
map<set<i32>, map<i32,set<list<map<Insanity,string>>>>>
>
4: binary binary_field
}
```
```rust
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct CrazyNesting {
pub string_field: Option<String>,
pub set_field: Option<BTreeSet<Insanity>>,
pub list_field: Vec<
BTreeMap<
BTreeSet<i32>,
BTreeMap<i32, BTreeSet<Vec<BTreeMap<Insanity, String>>>>
>
>,
pub binary_field: Option<Vec<u8>>,
}
impl CrazyNesting {
pub fn read_from_in_protocol(i_prot: &mut TInputProtocol)
->
thrift::Result<CrazyNesting> {
// ...
}
pub fn write_to_out_protocol(&self, o_prot: &mut TOutputProtocol)
->
thrift::Result<()> {
// ...
}
}
```
##### Optionality
Thrift has 3 "optionality" types:
1. Required
2. Optional
3. Default
The Rust code generator encodes *Required* fields as the bare type itself, while
*Optional* and *Default* fields are encoded as `Option<TypeName>`.
```thrift
struct Foo {
1: required string bar // 1. required
2: optional string baz // 2. optional
3: string qux // 3. default
}
```
```rust
pub struct Foo {
bar: String, // 1. required
baz: Option<String>, // 2. optional
qux: Option<String>, // 3. default
}
```
## Known Issues
* Struct constants are not supported
* Map, list and set constants require a const holder struct

View file

@ -0,0 +1,130 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.
#[macro_use]
extern crate clap;
extern crate thrift;
extern crate thrift_tutorial;
use thrift::protocol::{TCompactInputProtocol, TCompactOutputProtocol};
use thrift::transport::{
ReadHalf, TFramedReadTransport, TFramedWriteTransport, TIoChannel, TTcpChannel, WriteHalf,
};
use thrift_tutorial::shared::TSharedServiceSyncClient;
use thrift_tutorial::tutorial::{CalculatorSyncClient, Operation, TCalculatorSyncClient, Work};
fn main() {
match run() {
Ok(()) => println!("tutorial client ran successfully"),
Err(e) => {
println!("tutorial client failed with error {:?}", e);
std::process::exit(1);
}
}
}
fn run() -> thrift::Result<()> {
let options = clap_app!(rust_tutorial_client =>
(version: "0.1.0")
(author: "Apache Thrift Developers <dev@thrift.apache.org>")
(about: "Thrift Rust tutorial client")
(@arg host: --host +takes_value "host on which the tutorial server listens")
(@arg port: --port +takes_value "port on which the tutorial server listens")
);
let matches = options.get_matches();
// get any passed-in args or the defaults
let host = matches.value_of("host").unwrap_or("127.0.0.1");
let port = value_t!(matches, "port", u16).unwrap_or(9090);
// build our client and connect to the host:port
let mut client = new_client(host, port)?;
// alright!
// let's start making some calls
// let's start with a ping; the server should respond
println!("ping!");
client.ping()?;
// simple add
println!("add");
let res = client.add(1, 2)?;
println!("added 1, 2 and got {}", res);
let logid = 32;
// let's do...a multiply!
let res = client.calculate(logid, Work::new(7, 8, Operation::Multiply, None))?;
println!("multiplied 7 and 8 and got {}", res);
// let's get the log for it
let res = client.get_struct(32)?;
println!("got log {:?} for operation {}", res, logid);
// ok - let's be bad :(
// do a divide by 0
// logid doesn't matter; won't be recorded
let res = client.calculate(77, Work::new(2, 0, Operation::Divide, "we bad".to_owned()));
// we should have gotten an exception back
match res {
Ok(v) => panic!("should not have succeeded with result {}", v),
Err(e) => println!("divide by zero failed with error {:?}", e),
}
// let's do a one-way call
println!("zip");
client.zip()?;
// and then close out with a final ping
println!("ping!");
client.ping()?;
Ok(())
}
type ClientInputProtocol = TCompactInputProtocol<TFramedReadTransport<ReadHalf<TTcpChannel>>>;
type ClientOutputProtocol = TCompactOutputProtocol<TFramedWriteTransport<WriteHalf<TTcpChannel>>>;
fn new_client(
host: &str,
port: u16,
) -> thrift::Result<CalculatorSyncClient<ClientInputProtocol, ClientOutputProtocol>> {
let mut c = TTcpChannel::new();
// open the underlying TCP stream
println!("connecting to tutorial server on {}:{}", host, port);
c.open(&format!("{}:{}", host, port))?;
// clone the TCP channel into two halves, one which
// we'll use for reading, the other for writing
let (i_chan, o_chan) = c.split()?;
// wrap the raw sockets (slow) with a buffered transport of some kind
let i_tran = TFramedReadTransport::new(i_chan);
let o_tran = TFramedWriteTransport::new(o_chan);
// now create the protocol implementations
let i_prot = TCompactInputProtocol::new(i_tran);
let o_prot = TCompactOutputProtocol::new(o_tran);
// we're done!
Ok(CalculatorSyncClient::new(i_prot, o_prot))
}

View file

@ -0,0 +1,179 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.
#[macro_use]
extern crate clap;
extern crate thrift;
extern crate thrift_tutorial;
use std::collections::HashMap;
use std::convert::{From, Into};
use std::default::Default;
use std::sync::Mutex;
use thrift::protocol::{TCompactInputProtocolFactory, TCompactOutputProtocolFactory};
use thrift::server::TServer;
use thrift::transport::{TFramedReadTransportFactory, TFramedWriteTransportFactory};
use thrift_tutorial::shared::{SharedServiceSyncHandler, SharedStruct};
use thrift_tutorial::tutorial::{CalculatorSyncHandler, CalculatorSyncProcessor};
use thrift_tutorial::tutorial::{InvalidOperation, Operation, Work};
fn main() {
match run() {
Ok(()) => println!("tutorial server ran successfully"),
Err(e) => {
println!("tutorial server failed with error {:?}", e);
std::process::exit(1);
}
}
}
fn run() -> thrift::Result<()> {
let options = clap_app!(rust_tutorial_server =>
(version: "0.1.0")
(author: "Apache Thrift Developers <dev@thrift.apache.org>")
(about: "Thrift Rust tutorial server")
(@arg port: --port +takes_value "port on which the tutorial server listens")
);
let matches = options.get_matches();
let port = value_t!(matches, "port", u16).unwrap_or(9090);
let listen_address = format!("127.0.0.1:{}", port);
println!("binding to {}", listen_address);
let i_tran_fact = TFramedReadTransportFactory::new();
let i_prot_fact = TCompactInputProtocolFactory::new();
let o_tran_fact = TFramedWriteTransportFactory::new();
let o_prot_fact = TCompactOutputProtocolFactory::new();
// demux incoming messages
let processor = CalculatorSyncProcessor::new(CalculatorServer {
..Default::default()
});
// create the server and start listening
let mut server = TServer::new(
i_tran_fact,
i_prot_fact,
o_tran_fact,
o_prot_fact,
processor,
10,
);
server.listen(&listen_address)
}
/// Handles incoming Calculator service calls.
struct CalculatorServer {
log: Mutex<HashMap<i32, SharedStruct>>,
}
impl Default for CalculatorServer {
fn default() -> CalculatorServer {
CalculatorServer {
log: Mutex::new(HashMap::new()),
}
}
}
// since Calculator extends SharedService we have to implement the
// handler for both traits.
//
// SharedService handler
impl SharedServiceSyncHandler for CalculatorServer {
fn handle_get_struct(&self, key: i32) -> thrift::Result<SharedStruct> {
let log = self.log.lock().unwrap();
log.get(&key)
.cloned()
.ok_or_else(|| format!("could not find log for key {}", key).into())
}
}
// Calculator handler
impl CalculatorSyncHandler for CalculatorServer {
fn handle_ping(&self) -> thrift::Result<()> {
println!("pong!");
Ok(())
}
fn handle_add(&self, num1: i32, num2: i32) -> thrift::Result<i32> {
println!("handling add: n1:{} n2:{}", num1, num2);
Ok(num1 + num2)
}
fn handle_calculate(&self, logid: i32, w: Work) -> thrift::Result<i32> {
println!("handling calculate: l:{}, w:{:?}", logid, w);
let res = if let Some(ref op) = w.op {
if w.num1.is_none() || w.num2.is_none() {
Err(InvalidOperation {
what_op: Some(*op as i32),
why: Some("no operands specified".to_owned()),
})
} else {
// so that I don't have to call unwrap() multiple times below
let num1 = w.num1.as_ref().expect("operands checked");
let num2 = w.num2.as_ref().expect("operands checked");
match *op {
Operation::Add => Ok(num1 + num2),
Operation::Subtract => Ok(num1 - num2),
Operation::Multiply => Ok(num1 * num2),
Operation::Divide => {
if *num2 == 0 {
Err(InvalidOperation {
what_op: Some(*op as i32),
why: Some("divide by 0".to_owned()),
})
} else {
Ok(num1 / num2)
}
}
}
}
} else {
Err(InvalidOperation::new(
None,
"no operation specified".to_owned(),
))
};
// if the operation was successful log it
if let Ok(ref v) = res {
let mut log = self.log.lock().unwrap();
log.insert(logid, SharedStruct::new(logid, format!("{}", v)));
}
// the try! macro automatically maps errors
// but, since we aren't using that here we have to map errors manually
//
// exception structs defined in the IDL have an auto-generated
// impl of From::from
res.map_err(From::from)
}
fn handle_zip(&self) -> thrift::Result<()> {
println!("handling zip");
Ok(())
}
}

View file

@ -0,0 +1,23 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.
extern crate ordered_float;
extern crate thrift;
extern crate try_from;
pub mod shared;
pub mod tutorial;

View file

@ -22,6 +22,7 @@
* these definitions.
*/
namespace cl shared
namespace cpp shared
namespace d share // "shared" would collide with the eponymous D keyword.
namespace dart shared
@ -29,6 +30,7 @@ namespace java shared
namespace perl shared
namespace php shared
namespace haxe shared
namespace netcore shared
struct SharedStruct {
1: i32 key

View file

@ -62,6 +62,8 @@ include "shared.thrift"
* Thrift files can namespace, package, or prefix their output in various
* target languages.
*/
namespace cl tutorial
namespace cpp tutorial
namespace d tutorial
namespace dart tutorial
@ -69,6 +71,7 @@ namespace java tutorial
namespace php tutorial
namespace perl tutorial
namespace haxe tutorial
namespace netcore tutorial
/**
* Thrift lets you do typedefs to get pretty names for your types. Standard