a01c19cd621ab4778c1bbcd781de9e0e18a13e43
[pithos] / src / gr / ebs / gss / server / webdav / milton / GSSResourceFactory.java
1 /*
2  * Copyright 2011 Electronic Business Systems Ltd.
3  *
4  * This file is part of GSS.
5  *
6  * GSS is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * GSS is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with GSS.  If not, see <http://www.gnu.org/licenses/>.
18  */
19 package gr.ebs.gss.server.webdav.milton;
20
21 import static gr.ebs.gss.server.configuration.GSSConfigurationFactory.getConfiguration;
22 import gr.ebs.gss.client.exceptions.ObjectNotFoundException;
23 import gr.ebs.gss.client.exceptions.RpcException;
24 import gr.ebs.gss.server.domain.User;
25 import gr.ebs.gss.server.domain.dto.FileHeaderDTO;
26 import gr.ebs.gss.server.domain.dto.FolderDTO;
27 import gr.ebs.gss.server.domain.dto.UserDTO;
28 import gr.ebs.gss.server.ejb.ExternalAPI;
29 import gr.ebs.gss.server.ejb.TransactionHelper;
30
31 import java.util.Date;
32 import java.util.concurrent.Callable;
33
34 import javax.naming.Context;
35 import javax.naming.InitialContext;
36 import javax.naming.NamingException;
37 import javax.rmi.PortableRemoteObject;
38
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 import com.bradmcevoy.http.HttpManager;
43 import com.bradmcevoy.http.Resource;
44 import com.bradmcevoy.http.ResourceFactory;
45 import com.bradmcevoy.http.SecurityManager;
46 import com.bradmcevoy.http.Request.Method;
47 import com.ettrema.http.fs.LockManager;
48
49
50 /**
51  * @author kman
52  *
53  */
54 public class GSSResourceFactory implements ResourceFactory {
55         private static final Logger log = LoggerFactory.getLogger(GSSResourceFactory.class);
56         
57         SecurityManager securityManager;
58     LockManager lockManager;
59     Long maxAgeSeconds;
60     String contextPath;
61     boolean allowDirectoryBrowsing;
62     String defaultPage;
63     HttpManager httpManager;
64         @Override
65         public Resource getResource(String host, String url) {
66                 
67
68
69                 log.debug("getResource: host: " + host + " - url:" + url);
70         url = stripContext(url);
71         if(url==null||url.trim().equals("")||url.equals("/")){
72                 url="/";
73                 return new GssRootFolderResource(host, this, null,"/");
74         }
75         /*//log.info("URL:"+url);
76         if(url.equals("/OthersShared")||url.equals("/OthersShared/")){
77                 //log.info("[returning others]");
78                 return new GssOthersResource(host, this);
79         }
80         if(url.startsWith("/OthersShared")){
81                 
82         }*/
83         try {
84                 UserDTO user =null;
85                 if(HttpManager.request().getAuthorization()!=null && HttpManager.request().getAuthorization().getTag()==null){
86                         String username = HttpManager.request().getAuthorization().getUser();
87                         //log.info("username is:"+username);
88                         if(username !=null)
89                                 user = getService().getUserByUserName(username);
90                 }
91                 else if(HttpManager.request().getAuthorization()!=null&&HttpManager.request().getAuthorization().getTag()!=null){
92                         //log.info(HttpManager.request().getAuthorization().getUser());
93                         user =(UserDTO) HttpManager.request().getAuthorization().getTag();//getService().getUserByUserName("past@ebs.gr");
94                 }
95         
96                 if(user==null){
97                         //if(HttpManager.request().getMethod().equals(Method.PROPFIND)){
98                                 ////log.info("[PROP FIND RETURNING ROOT FOR:]"+url);
99                                 return new GssRootFolderResource(host, this, null,url);
100                         //}
101                         ////log.info("[RETURNING NULL FOR:]"+url+" "+HttpManager.request().getMethod());
102                         //return null;
103                 }
104                         
105                 Object r = getResourceGss(url,user);
106                 if(r==null){
107                         
108                         return null;
109                 }
110                 if(r instanceof FolderDTO)
111                         return new GssFolderResource(host, this,r ,user);
112                 else
113                         return new GssFileResource(host, this,r,user);
114                 } catch (RpcException e) {
115                         e.printStackTrace();
116                 }
117                 return null;
118     }
119         public Long maxAgeSeconds(GssResource resource) {
120         return maxAgeSeconds;
121     }
122         protected Object getResourceGss(String path, UserDTO user) throws RpcException{
123                 //log.info(path+" <--> "+HttpManager.request().getAuthorization() + HttpManager.request().getHeaders());
124                 if(user ==null){
125                         if(HttpManager.request().getAuthorization()!=null && HttpManager.request().getAuthorization().getTag()==null){
126                                 String username = HttpManager.request().getAuthorization().getUser();
127                                 //log.info("username is:"+username);
128                                 if(username !=null)
129                                         user = getService().getUserByUserName(username);
130                         }
131                         else if(HttpManager.request().getAuthorization()!=null&&HttpManager.request().getAuthorization().getTag()!=null){
132                                 //log.info(HttpManager.request().getAuthorization().getUser());
133                                 user =(UserDTO) HttpManager.request().getAuthorization().getTag();//getService().getUserByUserName("past@ebs.gr");
134                         }
135                 }
136                 
137                 if(user==null){
138                         //log.info("---------------->"+path);
139                         return null;
140                 }
141                         
142                 //UserDTO user =getService().getUserByUserName("past@ebs.gr");
143                 /*String username = HttpManager.request().getHeaders().get("authorization");
144                 
145         if(username!=null){
146         
147                 username=getUsernameFromAuthHeader(username);
148                 try {
149                                 user= getService().getUserByUserName(username);
150                         } catch (RpcException e) {
151                                 // TODO Auto-generated catch block
152                                 e.printStackTrace();
153                                 return null;
154                         }
155         }*/
156                 boolean exists = true;
157                 Object resource = null;
158                 FileHeaderDTO file = null;
159                 FolderDTO folder = null;
160                 try {
161                         resource = getService().getResourceAtPath(user.getId(), path, true);
162                 } catch (ObjectNotFoundException e) {
163                         exists = false;
164                 } catch (RpcException e) {
165                         
166                         return null;
167                 }
168
169                 if (!exists) {
170                         
171                         return null;
172                 }
173
174                 return resource;
175         }
176         
177         
178          private String stripContext( String url ) {
179                 if( this.contextPath != null && contextPath.length() > 0 ) {
180                     url = url.replaceFirst( '/' + contextPath, "");
181                     log.debug( "stripped context: " + url);
182                     return url;
183                 } else {
184                     return url;
185                 }
186             }
187          
188          /**
189                  * For a provided path, remove the last element and return the rest, that is
190                  * the path of the parent folder.
191                  *
192                  * @param path the specified path
193                  * @return the path of the parent folder
194                  * @throws ObjectNotFoundException if the provided string contains no path
195                  *             delimiters
196                  */
197                 protected String getParentPath(String path) throws ObjectNotFoundException {
198                         int lastDelimiter = path.lastIndexOf('/');
199                         if (lastDelimiter == 0)
200                                 return "/";
201                         if (lastDelimiter == -1)
202                                 // No path found.
203                                 throw new ObjectNotFoundException("There is no parent in the path: " + path);
204                         else if (lastDelimiter < path.length() - 1)
205                                 // Return the part before the delimiter.
206                                 return path.substring(0, lastDelimiter);
207                         else {
208                                 // Remove the trailing delimiter and then recurse.
209                                 String strippedTrail = path.substring(0, lastDelimiter);
210                                 return getParentPath(strippedTrail);
211                         }
212                 }
213                 
214                 /**
215                  * A helper method that retrieves a reference to the ExternalAPI bean and
216                  * stores it for future use.
217                  *
218                  * @return an ExternalAPI instance
219                  * @throws RpcException in case an error occurs
220                  */
221                 protected ExternalAPI getService() throws RpcException {
222                         try {
223                                 final Context ctx = new InitialContext();
224                                 final Object ref = ctx.lookup(getConfiguration().getString("externalApiPath"));
225                                 return (ExternalAPI) PortableRemoteObject.narrow(ref, ExternalAPI.class);
226                         } catch (final NamingException e) {
227                                 log.error("Unable to retrieve the ExternalAPI EJB", e);
228                                 throw new RpcException("An error occurred while contacting the naming service");
229                         }
230                 }
231
232                 private void updateAccounting(final User user, final Date date, final long bandwidthDiff) {
233                         try {
234                                 new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
235                                         @Override
236                                         public Void call() throws Exception {
237                                                 getService().updateAccounting(user, date, bandwidthDiff);
238                                                 return null;
239                                         }
240                                 });
241                         } catch (RuntimeException e) {
242                                 throw e;
243                         } catch (Exception e) {
244                                 // updateAccounting() doesn't throw any checked exceptions
245                                 assert false;
246                         }
247                 }
248
249                 
250                 /**
251                  * Retrieve the securityManager.
252                  *
253                  * @return the securityManager
254                  */
255                 public SecurityManager getSecurityManager() {
256                         return securityManager;
257                 }
258
259                 
260                 /**
261                  * Retrieve the lockManager.
262                  *
263                  * @return the lockManager
264                  */
265                 public LockManager getLockManager() {
266                         return lockManager;
267                 }
268
269                 
270                 /**
271                  * Retrieve the maxAgeSeconds.
272                  *
273                  * @return the maxAgeSeconds
274                  */
275                 public Long getMaxAgeSeconds() {
276                         return maxAgeSeconds;
277                 }
278
279                 
280                 /**
281                  * Retrieve the contextPath.
282                  *
283                  * @return the contextPath
284                  */
285                 public String getContextPath() {
286                         return contextPath;
287                 }
288
289                 
290                 /**
291                  * Retrieve the allowDirectoryBrowsing.
292                  *
293                  * @return the allowDirectoryBrowsing
294                  */
295                 public boolean isAllowDirectoryBrowsing() {
296                         return allowDirectoryBrowsing;
297                 }
298
299                 
300                 /**
301                  * Retrieve the defaultPage.
302                  *
303                  * @return the defaultPage
304                  */
305                 public String getDefaultPage() {
306                         return defaultPage;
307                 }
308                 
309                 public String getRealm(String host) {
310                 return securityManager.getRealm(host);
311             }
312
313                 
314                 /**
315                  * Modify the securityManager.
316                  *
317                  * @param securityManager the securityManager to set
318                  */
319                 public void setSecurityManager(SecurityManager securityManager) {
320                         this.securityManager = securityManager;
321                 }
322
323                 
324                 /**
325                  * Modify the lockManager.
326                  *
327                  * @param lockManager the lockManager to set
328                  */
329                 public void setLockManager(LockManager lockManager) {
330                         this.lockManager = lockManager;
331                 }
332
333                 
334                 /**
335                  * Modify the maxAgeSeconds.
336                  *
337                  * @param maxAgeSeconds the maxAgeSeconds to set
338                  */
339                 public void setMaxAgeSeconds(Long maxAgeSeconds) {
340                         this.maxAgeSeconds = maxAgeSeconds;
341                 }
342
343                 
344                 /**
345                  * Modify the contextPath.
346                  *
347                  * @param contextPath the contextPath to set
348                  */
349                 public void setContextPath(String contextPath) {
350                         this.contextPath = contextPath;
351                 }
352
353                 
354                 /**
355                  * Modify the defaultPage.
356                  *
357                  * @param defaultPage the defaultPage to set
358                  */
359                 public void setDefaultPage(String defaultPage) {
360                         this.defaultPage = defaultPage;
361                 }
362                 
363                 
364                 /**
365                  * Retrieve the httpManager.
366                  *
367                  * @return the httpManager
368                  */
369                 public HttpManager getHttpManager() {
370                         return httpManager;
371                 }
372                 
373                 
374                 /**
375                  * Modify the httpManager.
376                  *
377                  * @param httpManager the httpManager to set
378                  */
379                 public void setHttpManager(HttpManager httpManager) {
380                         this.httpManager = httpManager;
381                 }
382                 
383                 
384         
385                 public static String getUsernameFromAuthHeader(String header) {
386                         String first = header.split(",")[0];
387                         int indx = first.indexOf("\"");
388                         return first.substring(indx+1,first.length()-1);
389                 }
390 }