1// ServerConnectionProvider.cpp
2
3#include "AutoLocker.h"
4#include "ExtendedServerInfo.h"
5#include "ServerConnection.h"
6#include "ServerConnectionProvider.h"
7
8// constructor
9ServerConnectionProvider::ServerConnectionProvider(VolumeManager* volumeManager,
10	ExtendedServerInfo* serverInfo,
11	vnode_id connectionBrokenTarget)
12	: Referencable(true),
13	  fLock("server connection provider"),
14	  fVolumeManager(volumeManager),
15	  fServerInfo(serverInfo),
16	  fServerConnection(NULL),
17	  fConnectionBrokenTarget(connectionBrokenTarget)
18{
19	if (fServerInfo)
20		fServerInfo->AddReference();
21}
22
23// destructor
24ServerConnectionProvider::~ServerConnectionProvider()
25{
26	AutoLocker<Locker> _(fLock);
27	if (fServerConnection) {
28		fServerConnection->Close();
29		fServerConnection->RemoveReference();
30	}
31
32	if (fServerInfo)
33		fServerInfo->RemoveReference();
34}
35
36// Init
37status_t
38ServerConnectionProvider::Init()
39{
40	return B_OK;
41}
42
43// GetServerConnection
44status_t
45ServerConnectionProvider::GetServerConnection(
46	ServerConnection** serverConnection)
47{
48	AutoLocker<Locker> _(fLock);
49
50	// if there is no server connection yet, create one
51	if (!fServerConnection) {
52		fServerConnection = new(nothrow) ServerConnection(fVolumeManager,
53			fServerInfo);
54		if (!fServerConnection)
55			return B_NO_MEMORY;
56		status_t error = fServerConnection->Init(fConnectionBrokenTarget);
57		if (error != B_OK)
58			return error;
59	}
60
61	if (!fServerConnection->IsConnected())
62		return B_ERROR;
63
64	fServerConnection->AddReference();
65	*serverConnection = fServerConnection;
66	return B_OK;
67}
68
69// GetExistingServerConnection
70ServerConnection*
71ServerConnectionProvider::GetExistingServerConnection()
72{
73	AutoLocker<Locker> _(fLock);
74
75	// if there is no server connection yet, create one
76	if (!fServerConnection || !fServerConnection->IsConnected())
77		return NULL;
78
79	fServerConnection->AddReference();
80	return fServerConnection;
81}
82
83// CloseServerConnection
84void
85ServerConnectionProvider::CloseServerConnection()
86{
87	AutoLocker<Locker> _(fLock);
88	if (fServerConnection)
89		fServerConnection->Close();
90}
91
92