KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sslexplorer > networkplaces > NetworkPlaceUtil


1 /*
2  * SSL-Explorer
3  *
4  * Copyright (C) 2003-2006 3SP LTD. All Rights Reserved
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2 of
9  * the License, or (at your option) any later version.
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public
16  * License along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */

19             
20 package com.sslexplorer.networkplaces;
21
22 import java.util.ArrayList JavaDoc;
23 import java.util.Iterator JavaDoc;
24 import java.util.List JavaDoc;
25 import java.util.regex.Matcher JavaDoc;
26 import java.util.regex.Pattern JavaDoc;
27
28 import org.apache.commons.logging.Log;
29 import org.apache.commons.logging.LogFactory;
30
31 import com.maverick.util.URLUTF8Encoder;
32 import com.sslexplorer.boot.ReplacementEngine;
33 import com.sslexplorer.boot.Replacer;
34 import com.sslexplorer.boot.Util;
35 import com.sslexplorer.policyframework.PolicyDatabaseFactory;
36 import com.sslexplorer.policyframework.ResourceUtil;
37 import com.sslexplorer.security.SessionInfo;
38 import com.sslexplorer.vfs.VFSProvider;
39 import com.sslexplorer.vfs.VFSProviderManager;
40 import com.sslexplorer.vfs.VFSRepository;
41 import com.sslexplorer.vfs.VFSStore;
42 import com.sslexplorer.vfs.utils.URI;
43 import com.sslexplorer.vfs.utils.URI.MalformedURIException;
44 import com.sslexplorer.vfs.webdav.DAVBundleActionMessageException;
45 import com.sslexplorer.vfs.webdav.DAVUtilities;
46
47 public final class NetworkPlaceUtil {
48     
49     final static Log log = LogFactory.getLog(NetworkPlaceUtil.class);
50
51     /**
52      * Create a valid VFS URI from a path.
53      *
54      * @param path path
55      * @return URI
56      * @throws IllegalArgumentException if URI cannot be create
57      */

58     public static URI createURIForPath(String JavaDoc path) {
59         NetworkPlace np = createNetworkPlaceForPath(path);
60         
61         try {
62             String JavaDoc userInfo = URLUTF8Encoder.encode(np.getUsername(), false);
63             if(!Util.isNullOrTrimmedBlank(np.getPassword())) {
64                 userInfo = URLUTF8Encoder.encode(np.getUsername(), false);
65             }
66             URI uri = new URI(np.getScheme(), userInfo, np.getHost(), np.getPort(), np.getPath(), null, null);
67             return uri;
68         }
69         catch(Exception JavaDoc e) {
70             throw new IllegalArgumentException JavaDoc("Could not create URI.");
71         }
72     }
73     
74     /**
75      * Create a network place object given a path.
76      *
77      * @param path
78      * @return network place
79      * @throws IllegalArgumentException if resource cannot be created
80      *
81      */

82     public static NetworkPlace createNetworkPlaceForPath(String JavaDoc path) {
83         NetworkPlace np = null;
84         
85
86         try {
87             np = new DefaultNetworkPlace(1, 0,
88                     "", "", "", "", path, 0, "", "", NetworkPlace.TYPE_HIDDEN, false, false, false, false, null, null);
89             NetworkPlaceUtil.convertNetworkPlace(np);
90         }
91         catch(Exception JavaDoc e) {
92             log.error(e);
93             throw new IllegalArgumentException JavaDoc("Could not convert path to network place.");
94         }
95
96         VFSProvider provider = VFSProviderManager.getInstance().getProvider(np.getScheme());
97         if(provider == null) {
98             throw new IllegalArgumentException JavaDoc("No provider " + np.getScheme());
99         }
100         
101         return np;
102         
103     }
104     
105
106     /**
107      * Get a list of {@link NetworkPlaceItem} objects that may be used by the user
108      * of the given session.
109      *
110      * @param session
111      * @return network place items
112      * @throws DAVBundleActionMessageException
113      * @throws Exception
114      */

115     public static List JavaDoc<NetworkPlaceItem> refreshNetworkMounts(VFSRepository repository, SessionInfo session) throws DAVBundleActionMessageException, Exception JavaDoc {
116         List JavaDoc<NetworkPlaceItem> networkPlaceItems = new ArrayList JavaDoc<NetworkPlaceItem>();
117         List JavaDoc granted = ResourceUtil.getGrantedResource(session, NetworkPlacePlugin.NETWORK_PLACE_RESOURCE_TYPE);
118         for (Iterator JavaDoc i = granted.iterator(); i.hasNext();) {
119             NetworkPlace np = (NetworkPlace) i.next();
120             try {
121                 VFSProvider provider = VFSProviderManager.getInstance().getProvider(np.getScheme());
122                 if (provider == null) {
123                     if(np.getScheme().equals("")) {
124                         URI uri = createURIForPath(np.getPath());
125                         provider = VFSProviderManager.getInstance().getProvider(uri.getScheme());
126                     }
127                     if(provider == null)
128                         throw new Exception JavaDoc("No provider for network place URI " + np.getPath());
129                 }
130                 if (np.getType() != NetworkPlace.TYPE_HIDDEN) {
131                     // Create a store so we can get the mount path
132
VFSStore store = repository.getStore(provider.getScheme());
133                     NetworkPlaceItem npi = new NetworkPlaceItem(np, store.getMountPath(np.getResourceName()), PolicyDatabaseFactory.getInstance()
134                                     .getPoliciesAttachedToResource(np, session.getUser().getRealm()), np
135                                     .sessionPasswordRequired(session));
136                     networkPlaceItems.add(npi);
137                 }
138             } catch (Exception JavaDoc e) {
139                 log.warn("Failed to register " + np.getResourceName() + " with store.", e);
140             }
141         }
142         return networkPlaceItems;
143     }
144
145
146     /**
147      * Convert a network place that only has a path into a network
148      * place with separate elements. Used by the install task
149      * and when creating a network place using the <i>URI</i> type
150      *
151      * @param networkPlace
152      * @throws Exception
153      */

154     public static void convertNetworkPlace(NetworkPlace networkPlace) throws Exception JavaDoc {
155         if(Util.isNullOrTrimmedBlank(networkPlace.getScheme())) {
156             String JavaDoc path = networkPlace.getPath();
157             
158             Replacer r = new Replacer() {
159                 public String JavaDoc getReplacement(Pattern JavaDoc pattern, Matcher JavaDoc matcher, String JavaDoc replacementPattern) {
160     
161                     String JavaDoc match = matcher.group();
162                     String JavaDoc key = match.substring(2, match.length() - 1);
163                     try {
164                         int idx = key.indexOf(":");
165                         if (idx == -1) {
166                             throw new Exception JavaDoc("String replacement pattern is in incorrect format for " + key
167                                 + ". Must be <TYPE>:<key>");
168                         }
169                         String JavaDoc type = key.substring(0, idx);
170                         key = key.substring(idx + 1);
171                         return "_prototype_" + type + "_" + key + "_";
172                     }
173                     catch(Exception JavaDoc e) {
174                         NetworkPlaceInstall.log.error("Failed to replace.", e);
175                     }
176                     return "prototype";
177                 }
178                 
179             };
180             
181             // Replace all replacement variables with prototype values
182
ReplacementEngine engine = new ReplacementEngine();
183             engine.addPattern(NetworkPlaceInstall.VARIABLE_PATTERN, r, null);
184             path = engine.replace(path);
185             
186             //
187
URI newUri = null;
188             
189             // Is it a UNC path
190
if(path.startsWith("\\\\")) {
191                 try {
192                     newUri = new URI("smb:" + path.replace('\\', '/'));
193                 }
194                 catch(MalformedURIException murie) {
195                     murie.printStackTrace();
196                 }
197             }
198             
199             // Is this a supported RI?
200
if(newUri == null) {
201                 int idx = path.indexOf(':');
202                 if(idx > 1) { // index of 1 would mean a windows absolute path
203
// Is it an non windows absolute file URI?
204
String JavaDoc rpath = path.substring(idx + 1);
205                     String JavaDoc scheme = path.substring(0, idx);
206                     if(scheme.equals("file")) {
207                         if(rpath.startsWith("//") && !rpath.startsWith("///") &&
208                                         ( rpath.length() < 4 || rpath.charAt(3) != ':' ) ) {
209                             path = scheme + ":/" + rpath;
210                         }
211                     }
212                     
213                     newUri = new URI(path);
214                 }
215             }
216             
217             // Is it a local file? (wont work for replacements)
218
boolean switchSlash = false;
219             if(newUri == null) {
220                 if(path.contains("\\")) {
221                     switchSlash = true;
222                 }
223                 try {
224                     String JavaDoc scheme;
225                     if(path.toLowerCase().endsWith(".jar")) {
226                         scheme = "jar";
227                     } else if(path.toLowerCase().endsWith(".zip")) {
228                         scheme = "zip";
229                     } else {
230                         scheme = "file";
231                     }
232                     newUri = new URI(scheme + ":///" + DAVUtilities.stripLeadingSlash(path.replace('\\', '/')));
233                 } catch (MalformedURIException e) {
234                     e.printStackTrace();
235                 }
236             }
237             
238             // Convert the network place if required
239
if(newUri != null) {
240                 engine = new ReplacementEngine();
241     
242                 
243                 r = new Replacer() {
244                     public String JavaDoc getReplacement(Pattern JavaDoc pattern, Matcher JavaDoc matcher, String JavaDoc replacementPattern) {
245                         String JavaDoc match = matcher.group();
246                         String JavaDoc key = match.substring(11, match.length() - 1);
247                         try {
248                             int idx = key.indexOf("_");
249                             if (idx == -1) {
250                                 throw new Exception JavaDoc("String replacement pattern is in incorrect format for " + key
251                                     + ". Must be <TYPE>:<key>");
252                             }
253                             String JavaDoc type = key.substring(0, idx);
254                             key = key.substring(idx + 1);
255                             return "${" + type + ":" + key + "}";
256                         }
257                         catch(Exception JavaDoc e) {
258                             NetworkPlaceInstall.log.error("Failed to replace.", e);
259                         }
260                         return "prototype";
261                     }
262                     
263                 };
264                 engine.addPattern(NetworkPlaceInstall.PROTOTYPE_PATTERN, r, null);
265                 String JavaDoc newScheme = newUri.getScheme();
266                 String JavaDoc newHost = newUri.getHost();
267                 if(!Util.isNullOrTrimmedBlank(newHost)) {
268                     newHost = engine.replace(newHost);
269                 }
270                 int newPort = Math.max(newUri.getPort(), 0);
271                 String JavaDoc newPath = newUri.getPath();
272                 if(!Util.isNullOrTrimmedBlank(newPath)) {
273                     newPath = Util.urlDecode(engine.replace(newPath));
274                 }
275                 if(newPath.startsWith("/") && newPath.length() > 2 && newPath.charAt(2) == ':') {
276                     newPath = newPath.substring(1);
277                 }
278                 if(switchSlash) {
279                     newPath = newPath.replace('/', '\\');
280                 }
281                 String JavaDoc newFragment = newUri.getFragment();
282                 if(!Util.isNullOrTrimmedBlank(newFragment)) {
283                     newFragment = engine.replace(newFragment);
284                 }
285                 String JavaDoc newUserinfo = newUri.getUserinfo();
286                 int idx = newUserinfo == null ? -1 : newUserinfo.indexOf(':');
287                 String JavaDoc newUsername = newUserinfo;
288                 String JavaDoc newPassword = "";
289                 if(idx != -1) {
290                     newPassword = newUsername.substring(idx + 1);
291                     newUsername = newUsername.substring(0, idx);
292                 }
293                 if(!Util.isNullOrTrimmedBlank(newUsername)) {
294                     newUsername = Util.urlDecode(engine.replace(newUsername));
295                 }
296                 if(!Util.isNullOrTrimmedBlank(newPassword)) {
297                     newPassword = Util.urlDecode(engine.replace(newPassword));
298                 }
299                 
300                 networkPlace.setScheme(Util.emptyWhenNull(newScheme));
301                 networkPlace.setHost(Util.emptyWhenNull(newHost));
302                 networkPlace.setPort(newPort);
303                 networkPlace.setPath(Util.emptyWhenNull(newPath));
304                 networkPlace.setUsername(Util.emptyWhenNull(newUsername));
305                 networkPlace.setPassword(Util.emptyWhenNull(newPassword));
306     
307                 // networkPlace.setFragment(newFragment);
308
}
309         }
310     }
311 }
312
Popular Tags