View Javadoc

1   /*
2   Copyright 2011-2014 AGH-UST, http://www.agh.edu.pl
3   Faculty of Computer Science, Electronics and Telecommunications
4   Department of Computer Science 
5   
6   See the NOTICE file distributed with this work for additional
7   information regarding copyright ownership
8   
9   Licensed under the Apache License, Version 2.0 (the "License");
10  you may not use this file except in compliance with the License.
11  You may obtain a copy of the License at
12  
13    http://www.apache.org/licenses/LICENSE-2.0
14  
15  Unless required by applicable law or agreed to in writing, software
16  distributed under the License is distributed on an "AS IS" BASIS,
17  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  See the License for the specific language governing permissions and
19  limitations under the License.
20  */
21  package org.universAAL.ri.gateway.eimanager.impl.exporting;
22  
23  import java.io.IOException;
24  import java.util.ArrayList;
25  import java.util.Arrays;
26  import java.util.HashMap;
27  import java.util.List;
28  import java.util.Map;
29  
30  import org.universAAL.middleware.context.ContextBus;
31  import org.universAAL.middleware.context.ContextBusFacade;
32  import org.universAAL.middleware.context.ContextEvent;
33  import org.universAAL.middleware.context.ContextEventPattern;
34  import org.universAAL.middleware.service.ServiceBus;
35  import org.universAAL.middleware.service.ServiceBusFacade;
36  import org.universAAL.middleware.service.ServiceCall;
37  import org.universAAL.middleware.service.ServiceResponse;
38  import org.universAAL.middleware.service.owls.profile.ServiceProfile;
39  import org.universAAL.middleware.bus.member.BusMember;
40  import org.universAAL.middleware.tracker.IBusMemberRegistry;
41  import org.universAAL.middleware.tracker.IBusMemberRegistryListener;
42  import org.universAAL.middleware.tracker.IBusMemberRegistry.BusType;
43  import org.universAAL.middleware.ui.IUIBus;
44  import org.universAAL.middleware.ui.UIBusFacade;
45  import org.universAAL.middleware.ui.UIHandlerProfile;
46  import org.universAAL.middleware.ui.UIRequest;
47  import org.universAAL.middleware.ui.UIResponse;
48  import org.universAAL.ri.gateway.communicator.Activator;
49  import org.universAAL.ri.gateway.communicator.service.GatewayCommunicator;
50  import org.universAAL.ri.gateway.communicator.service.Message;
51  import org.universAAL.ri.gateway.communicator.service.impl.Serializer;
52  import org.universAAL.ri.gateway.eimanager.impl.AbstractProxyManager;
53  import org.universAAL.ri.gateway.eimanager.impl.BusMemberType;
54  import org.universAAL.ri.gateway.eimanager.impl.ProxyBusMember;
55  import org.universAAL.ri.gateway.eimanager.impl.importing.ImportRequest;
56  import org.universAAL.ri.gateway.eimanager.impl.registry.RegistryEntry;
57  
58  public class ExportedProxyManager extends AbstractProxyManager implements
59  		IBusMemberRegistryListener {
60  
61  	private Map<String, ProxyBusMember> generatedProxies;
62  	private GatewayCommunicator communicator;
63  	private ServiceBus serviceBus;
64  	private ContextBus contextBus;
65  	private IUIBus uiBus;
66  
67  	public ExportedProxyManager(final GatewayCommunicator communicator) {
68  		super();
69  		generatedProxies = new HashMap<String, ProxyBusMember>();
70  		this.communicator = communicator;
71  		serviceBus = ServiceBusFacade.fetchBus(Activator.mc);
72  		contextBus = ContextBusFacade.fetchBus(Activator.mc);
73  		uiBus = UIBusFacade.fetchBus(Activator.mc);
74  
75  		IBusMemberRegistry registry = (IBusMemberRegistry) Activator.mc
76  				.getContainer().fetchSharedObject(Activator.mc,
77  						IBusMemberRegistry.busRegistryShareParams);
78  		registry.addBusRegistryListener(this, false);
79  	}
80  
81  	public ServiceResponse sendServiceRequest(final String sourceId,
82  			final ServiceCall call, final String memberId) {
83  		if (generatedProxies.get(sourceId) != null) {
84  			return ((ProxyServiceCaller) generatedProxies.get(sourceId))
85  					.invoke(call, memberId);
86  		} else {
87  			return null;
88  		}
89  	}
90  
91  	public void handleContextEvent(final String targetId,
92  			final ContextEvent contextEvent) throws IOException {
93  		Message message = Serializer.Instance.marshallObject(contextEvent);
94  		message.setRemoteProxyRegistrationId(targetId);
95  		communicator.sendContextEvent(message);
96  	}
97  
98  	public void handleUIResponse(final String targetId,
99  			final UIResponse response) throws IOException {
100 		communicator.sendUIResponse(Serializer.Instance
101 				.marshallObject(response));
102 	}
103 
104 	public void sendUIRequest(final String sourceId, final UIRequest request) {
105 		if (generatedProxies.get(sourceId) != null) {
106 			((ProxyUICaller) generatedProxies.get(sourceId)).invoke(request);
107 		}
108 	}
109 
110 	public ProxyRegistration registerProxies(final ImportRequest importRequest)
111 			throws IOException, ClassNotFoundException {
112 		ProxyBusMember member = null;
113 		ProxyRegistration proxyRegistration = null;
114 		switch (BusMemberType.valueOf(importRequest.getMember())) {
115 		case ServiceCaller:
116 			Map<String,List<ServiceProfile>> profilesMap = (Map<String,List<ServiceProfile>>)serviceBus.getMatchingServices(importRequest.getServiceType());
117 
118 			member = new ProxyServiceCaller(this, importRequest.getId(),
119 					Activator.mc, importRequest.getServerNamespace(),
120 					importRequest.getServiceType(), profilesMap);
121 			
122 //			ServiceProfile[] profilesArray = profilesMap.values().toArray(new ServiceProfile[0]);
123 			
124 			proxyRegistration = new ProxyRegistration(member.getId(), profilesMap);
125 			break;
126 		case ContextSubscriber:
127 			String[] serializedCpe = importRequest.getCpe();
128 			ContextEventPattern[] cpe = new ContextEventPattern[serializedCpe.length];
129 			System.out.println("Export received:");
130 			for (int i = 0; i < serializedCpe.length; i++) {
131 				// System.out.println(serializedCpe[i]);
132 				cpe[i] = Serializer.Instance.unmarshallObject(
133 						ContextEventPattern.class, serializedCpe[i], Thread
134 								.currentThread().getContextClassLoader());
135 			}
136 			member = new ProxyContextSubscriber(this, Activator.mc, cpe);
137 
138 			//ContextEventPattern[] matchedEvents = contextBus
139 			//		.getAllProvisions(member.getId());
140 			proxyRegistration = new ProxyRegistration(member.getId(),
141 					cpe);
142 			break;
143 		case UICaller:
144 			UIHandlerProfile[] uiProfiles = uiBus.getMatchingProfiles(importRequest.getModalityRegex());
145 
146 			member = new ProxyUICaller(this, importRequest.getId(),
147 					Activator.mc, importRequest.getModalityRegex(), uiProfiles);
148 
149 			proxyRegistration = new ProxyRegistration(member.getId(),
150 					uiProfiles);
151 			break;
152 		}
153 		if (member != null) {
154 			generatedProxies.put(member.getId(), member);
155 		}
156 		return proxyRegistration;
157 	}
158 
159 	public void unregisterProxies(final ImportRequest importRequest) {
160 		String id = importRequest.getId();
161 		if (generatedProxies.containsKey(id)) {
162 			generatedProxies.get(id).removeProxy();
163 			generatedProxies.remove(id);
164 		}
165 	}
166 
167 	public void registryEntryAdded(final RegistryEntry entry) {
168 		/*
169 		 * if (entry instanceof ExportEntry) {
170 		 * registerProxiesIfNecessary((ExportEntry) entry); }
171 		 */
172 	}
173 
174 	public void registryEntryRemoved(final RegistryEntry entry) {
175 		/*
176 		 * if (entry instanceof ExportEntry) {
177 		 * unregisterProxiesIfNecessary((ExportEntry) entry); }
178 		 */
179 	}
180 
181 	public void busMemberAdded(final BusMember arg0, final BusType arg1) {
182 		reloadServices();
183 	}
184 
185 	public void busMemberRemoved(final BusMember arg0, final BusType arg1) {
186 		reloadServices();
187 	}
188 
189 	/*
190 	 * This method refreshes the ServiceProfiles/UIHandlerProfiles of every proxy that is remotely
191 	 * imported on remote spaces. If a set of ServiceProfiles/UIHandlerProfiles changes for any of
192 	 * exported services, the information is sent to other spaces to refresh
193 	 * their knowledge.
194 	 */
195 	private void reloadServices() {
196 		for (ProxyBusMember p : generatedProxies.values()) {
197 			if (p instanceof ProxyServiceCaller) {
198 				ProxyServiceCaller member = (ProxyServiceCaller) p;
199 				Map<String,List<ServiceProfile>> profilesMap = (Map<String,List<ServiceProfile>>)serviceBus.getMatchingServices(member.getServiceType());
200 				
201 				List<ServiceProfile> profilesList = new ArrayList<ServiceProfile>();
202 				for(List<ServiceProfile> value : profilesMap.values()){
203 					profilesList.addAll(value);
204 				}
205 				
206 				ServiceProfile[] profiles = profilesList.toArray(new ServiceProfile[0]);
207 				
208 				if (!Arrays.equals(profiles, member.getProfiles())) {
209 					try {
210 						member.setProfiles(profilesMap);
211 						Map<String, List<String>> serializedMap = new HashMap<String, List<String>>();
212 						
213 						for(String key: profilesMap.keySet()){
214 							if (serializedMap.get(key) == null){
215 								serializedMap.put(key, new ArrayList<String>());
216 							}
217 							for(ServiceProfile pr : profilesMap.get(key)){
218 								serializedMap.get(key).add((String) Serializer.Instance
219 										.marshallObject(pr).getContent());
220 							}
221 						}
222 						
223 						/*serialized = new String[profiles.values().size()+2*profiles.keySet().s];
224 						
225 						
226 						for (int i = 2; i < profiles.values().size().length + 2; i++) {
227 							serialized[i] = (String) Serializer.Instance
228 									.marshallObject(profiles[i]).getContent();
229 						}*/
230 						Object reg = new ProxyRegistration(member.getId(),
231 								serializedMap);
232 						communicator.sendImportRefresh(new Message(reg));
233 					} catch (IOException e) {
234 						e.printStackTrace();
235 					}
236 				}
237 			} else if (p instanceof ProxyUICaller) {
238 				ProxyUICaller member = (ProxyUICaller) p;
239 				UIHandlerProfile[] profiles = uiBus.getMatchingProfiles(member.getModalityRegex());
240 				if (!Arrays.equals(profiles, member.getHandlerProfiles())) {
241 					try {
242 						member.setHandlerProfiles(profiles);
243 						String[] serialized = new String[profiles.length];
244 						for (int i = 0; i < profiles.length; i++) {
245 							serialized[i] = (String) Serializer.Instance
246 									.marshallObject(profiles[i]).getContent();
247 						}
248 						Object reg = new ProxyRegistration(member.getId(),
249 								serialized);
250 						communicator.sendImportRefresh(new Message(reg));
251 					} catch (IOException e) {
252 						e.printStackTrace();
253 					}
254 				}
255 			}
256 		}
257 	}
258 
259 }