001: /*
002: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
003: *
004: * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
005: *
006: * The contents of this file are subject to the terms of either the GNU
007: * General Public License Version 2 only ("GPL") or the Common
008: * Development and Distribution License("CDDL") (collectively, the
009: * "License"). You may not use this file except in compliance with the
010: * License. You can obtain a copy of the License at
011: * http://www.netbeans.org/cddl-gplv2.html
012: * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
013: * specific language governing permissions and limitations under the
014: * License. When distributing the software, include this License Header
015: * Notice in each file and include the License file at
016: * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
017: * particular file as subject to the "Classpath" exception as provided
018: * by Sun in the GPL Version 2 section of the License file that
019: * accompanied this code. If applicable, add the following below the
020: * License Header, with the fields enclosed by brackets [] replaced by
021: * your own identifying information:
022: * "Portions Copyrighted [year] [name of copyright owner]"
023: *
024: * Contributor(s):
025: *
026: * The Original Software is NetBeans. The Initial Developer of the Original
027: * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
028: * Microsystems, Inc. All Rights Reserved.
029: *
030: * If you wish your version of this file to be governed by only the CDDL
031: * or only the GPL Version 2, indicate your decision by adding
032: * "[Contributor] elects to include this software in this distribution
033: * under the [CDDL or GPL Version 2] license." If you do not indicate a
034: * single choice of license, a recipient has the option to distribute
035: * your version of this file under either the CDDL, the GPL Version 2 or
036: * to extend the choice of license to its licensees as provided above.
037: * However, if you add GPL Version 2 code and therefore, elected the GPL
038: * Version 2 license, then the option applies only if the new code is
039: * made subject to such option by the copyright holder.
040: */
041:
042: package org.netbeans.modules.websvc.manager;
043:
044: import org.netbeans.modules.websvc.manager.api.WebServiceDescriptor;
045: import java.beans.DefaultPersistenceDelegate;
046: import java.beans.Encoder;
047: import javax.xml.parsers.DocumentBuilder;
048: import javax.xml.parsers.DocumentBuilderFactory;
049: import org.netbeans.modules.websvc.manager.model.WebServiceData;
050: import org.netbeans.modules.websvc.manager.model.WebServiceGroup;
051: import org.netbeans.modules.websvc.manager.model.WebServiceListModel;
052: import java.beans.XMLDecoder;
053: import java.beans.XMLEncoder;
054:
055: import java.io.*;
056: import java.io.BufferedOutputStream;
057: import java.util.*;
058:
059: import java.beans.ExceptionListener;
060: import org.netbeans.modules.websvc.api.jaxws.wsdlmodel.WsdlService;
061: import org.netbeans.modules.websvc.manager.util.ManagerUtil;
062: import org.netbeans.modules.websvc.saas.model.SaasGroup;
063: import org.netbeans.modules.websvc.saas.model.SaasServicesModel;
064: import org.netbeans.modules.websvc.saas.model.WsdlSaas;
065: import org.netbeans.modules.websvc.saas.util.SaasUtil;
066: import org.netbeans.modules.websvc.saas.util.WsdlUtil;
067: import org.openide.ErrorManager;
068: import org.openide.filesystems.FileObject;
069: import org.openide.filesystems.FileSystem;
070: import org.openide.filesystems.Repository;
071: import org.openide.util.NbBundle;
072: import org.w3c.dom.Document;
073: import org.w3c.dom.NamedNodeMap;
074: import org.w3c.dom.NodeList;
075:
076: /**
077: * WebServicePersistenceManager.java
078: * @author Winston Prakash, quynguyen
079: */
080: public class WebServicePersistenceManager implements ExceptionListener {
081: private File websvcDir = new File(WebServiceManager.WEBSVC_HOME);
082: private File websvcRefFile = new File(websvcDir, "websvc_ref.xml");
083: private List<WebServiceDescriptor> descriptorsToWrite = null;
084: private boolean imported = false;
085:
086: public void setImported(boolean v) {
087: imported = v;
088: }
089:
090: public void load() {
091: if (websvcRefFile.exists()) {
092: try {
093: SaasServicesModel model = SaasServicesModel
094: .getInstance();
095: XMLDecoder decoder = new XMLDecoder(
096: new BufferedInputStream(new FileInputStream(
097: websvcRefFile)));
098: List<WebServiceData> wsDatas = new ArrayList<WebServiceData>();
099:
100: List<String> partnerServices = WebServiceListModel
101: .getInstance().getPartnerServices();
102: Object firstObject = decoder.readObject();
103: int wsDataNums;
104:
105: if (firstObject instanceof List) {
106: List<String> loadedServices = (List<String>) firstObject;
107: for (String url : loadedServices) {
108: partnerServices.add(url);
109: }
110: wsDataNums = ((Integer) decoder.readObject())
111: .intValue();
112: } else {
113: wsDataNums = ((Integer) firstObject).intValue();
114: }
115:
116: for (int i = 0; i < wsDataNums; i++) {
117: WebServiceData wsData = null;
118: try {
119: wsData = (WebServiceData) decoder.readObject();
120: } catch (Exception exc) {
121: ErrorManager.getDefault().notify(exc);
122: decoder.close();
123: }
124:
125: wsDatas.add(wsData);
126: }
127: int wsGroupSize = ((Integer) decoder.readObject())
128: .intValue();
129: Map<String, WebServiceGroup> groupByIds = new HashMap<String, WebServiceGroup>();
130: for (int i = 0; i < wsGroupSize; i++) {
131: try {
132: WebServiceGroup group = (WebServiceGroup) decoder
133: .readObject();
134: groupByIds.put(group.getId(), group);
135: if (group.getName() == null) {
136: continue;
137: }
138:
139: /**
140: * For import services created from 6.0
141: * Note: we only need to read old group from imported user dir
142: * New group information are not managed by this persistence.
143: */
144: String trimmed = translateGroupName(group);
145: if (!imported
146: && model.getRootGroup().getChildGroup(
147: group.getName()) == null
148: && model.getRootGroup().getChildGroup(
149: trimmed) == null
150: && !WebServiceListModel.DEFAULT_GROUP
151: .equals(group.getName())) {
152: model.createTopGroup(group.getName());
153: }
154: } catch (Exception exc) {
155: ErrorManager.getDefault().notify(exc);
156: decoder.close();
157: }
158: }
159: decoder.close();
160:
161: for (WebServiceData wsData : wsDatas) {
162: if (imported) { // we don't need to import generated artifacts
163: if (wsData.getJaxRpcDescriptorPath() != null) {
164: wsData
165: .setJaxRpcDescriptor(loadDescriptorFile(websvcDir
166: + File.separator
167: + wsData
168: .getJaxRpcDescriptorPath()));
169: }
170:
171: if (wsData.getJaxWsDescriptorPath() != null) {
172: wsData
173: .setJaxWsDescriptor(loadDescriptorFile(websvcDir
174: + File.separator
175: + wsData
176: .getJaxWsDescriptorPath()));
177: }
178: } else {
179: wsData.reset();
180: WebServiceGroup group = groupByIds.get(wsData
181: .getGroupId());
182: SaasGroup parent = null;
183: if (group.getName() == null) {
184: parent = model.getRootGroup();
185: } else {
186: parent = model.getRootGroup()
187: .getChildGroup(
188: translateGroupName(group));
189: }
190: if (parent == null) {
191: parent = model.getRootGroup();
192: }
193: String url = wsData.getOriginalWsdlUrl();
194: if (SaasUtil.getServiceByUrl(parent, url) != null) {
195: continue;
196: }
197: String display = WsdlUtil
198: .getServiceDirName(url);
199: WsdlSaas service = new WsdlSaas(parent,
200: display, url, wsData.getPackageName());
201: parent.addService(service);
202: service.save();
203: }
204: WebServiceListModel.getInstance().addWebService(
205: wsData);
206: }
207:
208: try {
209: WebServiceGroup defaultGroup = groupByIds
210: .get(WebServiceListModel.DEFAULT_GROUP);
211: if (defaultGroup != null) {
212: WebServiceListModel.getInstance()
213: .addWebServiceGroup(defaultGroup);
214: }
215: } catch (Exception ex) {
216: ErrorManager.getDefault().notify(ex);
217: }
218:
219: } catch (Exception exc) {
220: exc.printStackTrace();
221: }
222: }
223:
224: loadPartnerServices();
225: }
226:
227: private String translateGroupName(WebServiceGroup group) {
228: String name = group.getName();
229: if (name.endsWith(" Services")) {
230: return name.substring(0, name.length() - 9);
231: }
232: return name;
233: }
234:
235: public void save() {
236: WebServiceListModel model = WebServiceListModel.getInstance();
237: if (!model.isInitialized()) {
238: return;
239: }
240:
241: if (!websvcDir.exists())
242: websvcDir.mkdirs();
243: if (websvcRefFile.exists())
244: websvcRefFile.delete();
245: try {
246: XMLEncoder encoder = new XMLEncoder(
247: new BufferedOutputStream(new FileOutputStream(
248: websvcRefFile)));
249: encoder.setExceptionListener(this );
250:
251: DefaultPersistenceDelegate delegate = new WebServiceDataPersistenceDelegate();
252: encoder.setPersistenceDelegate(WsdlService.class, delegate);
253: encoder.setPersistenceDelegate(WebServiceDescriptor.class,
254: delegate);
255:
256: encoder.writeObject(model.getPartnerServices());
257:
258: List<WebServiceData> wsDataSet = model.getWebServiceSet();
259: encoder.writeObject(new Integer(wsDataSet.size()));
260:
261: synchronized (wsDataSet) {
262: for (WebServiceData wsData : wsDataSet) {
263: encoder.writeObject(wsData);
264: }
265: }
266:
267: List<WebServiceGroup> wsGroupSet = model
268: .getWebServiceGroupSet();
269: encoder.writeObject(new Integer(wsGroupSet.size()));
270:
271: synchronized (wsGroupSet) {
272: for (WebServiceGroup group : wsGroupSet) {
273: encoder.writeObject(group);
274: }
275: }
276:
277: encoder.close();
278: encoder.flush();
279: delegate = new DefaultPersistenceDelegate();
280: encoder.setPersistenceDelegate(WsdlService.class, delegate);
281: encoder.setPersistenceDelegate(WebServiceDescriptor.class,
282: delegate);
283:
284: if (descriptorsToWrite != null) {
285: for (WebServiceDescriptor descriptor : descriptorsToWrite) {
286: saveWebServiceDescriptor(descriptor);
287: }
288: }
289: } catch (Exception exc) {
290: ErrorManager.getDefault().notify(exc);
291: return;
292: }
293: }
294:
295: private WebServiceDescriptor loadDescriptorFile(
296: String descriptorPath) {
297: if (descriptorPath == null || descriptorPath.length() == 0) {
298: return null;
299: } else {
300: XMLDecoder decoder = null;
301: try {
302: decoder = new java.beans.XMLDecoder(
303: new java.io.BufferedInputStream(
304: new java.io.FileInputStream(
305: descriptorPath)));
306: return (WebServiceDescriptor) decoder.readObject();
307: } catch (Exception ex) {
308: exceptionThrown(ex);
309: return null;
310: } finally {
311: if (decoder != null) {
312: decoder.close();
313: }
314: }
315: }
316:
317: }
318:
319: /**
320: * Loads (or reloads if the services already exist) a set of partner services
321: *
322: * @param serviceFolder the folder location of the component definitions in the system filesystem
323: * @param partnerName optional partner name for the web service group folder name, should be null
324: * or identical to existing group name if overwriting an existing component's folder
325: */
326: public static void loadPartnerService(String serviceFolder,
327: String partnerName) {
328: FileSystem sfs = Repository.getDefault().getDefaultFileSystem();
329: FileObject folder = sfs.findResource(serviceFolder);
330:
331: loadPartnerFromFolder(folder, partnerName, true);
332: }
333:
334: public static void loadPartnerServices() {
335: FileSystem sfs = Repository.getDefault().getDefaultFileSystem();
336:
337: FileObject f = sfs.findResource("RestComponents"); // NOI18N
338: if (f != null && f.isFolder()) {
339: Enumeration<? extends FileObject> en = f.getFolders(false);
340: while (en.hasMoreElements()) {
341: FileObject nextFolder = en.nextElement();
342: String groupName = ManagerUtil
343: .getLocalizedName(nextFolder);
344: loadPartnerFromFolder(nextFolder, groupName, false);
345: }
346: }
347: }
348:
349: private static void loadPartnerFromFolder(FileObject folder,
350: String groupName, boolean reloadIfExists) {
351: if (folder == null || !folder.isFolder()) {
352: return;
353: }
354:
355: Map<String, String> currentUrls = new HashMap<String, String>(); //url->name
356: List<String> partnerUrls = WebServiceListModel.getInstance()
357: .getPartnerServices();
358:
359: FileObject[] contents = folder.getChildren();
360: for (int i = 0; i < contents.length; i++) {
361: try {
362: DocumentBuilderFactory dbf = DocumentBuilderFactory
363: .newInstance();
364: DocumentBuilder db = dbf.newDocumentBuilder();
365: Document doc = db.parse(contents[i].getInputStream());
366: NodeList nodes = doc.getElementsByTagName("method"); // NOI18N
367:
368: for (int j = 0; j < nodes.getLength(); j++) {
369: NamedNodeMap attributes = nodes.item(j)
370: .getAttributes();
371: String type = attributes.getNamedItem("type")
372: .getNodeValue(); // NOI18N
373: String url = attributes.getNamedItem("url")
374: .getNodeValue(); // NOI18N
375:
376: boolean addUrl = !currentUrls.containsKey(url)
377: && (reloadIfExists || (!reloadIfExists && !partnerUrls
378: .contains(url)));
379:
380: if ("http://schemas.xmlsoap.org/wsdl/".equals(type)
381: && addUrl) { // NOI18N
382: String serviceName = attributes.getNamedItem(
383: "serviceName").getNodeValue(); //NOI18N
384: currentUrls.put(url, serviceName);
385: }
386: }
387: } catch (Exception ex) {
388: String msg = NbBundle.getMessage(
389: WebServicePersistenceManager.class,
390: "MSG_BadContent", contents[i].getPath());
391: Throwable t = ErrorManager.getDefault().annotate(ex,
392: msg);
393: ErrorManager.getDefault().notify(t);
394: }
395: }
396:
397: if (currentUrls.size() > 0) {
398: WebServiceGroup newGroup = null;
399: List<WebServiceGroup> webServiceGroups = WebServiceListModel
400: .getInstance().getWebServiceGroupSet();
401: for (WebServiceGroup group : webServiceGroups) {
402: if (!group.isUserDefined()
403: && group.getName().equals(groupName)) {
404: newGroup = group;
405: break;
406: }
407: }
408:
409: if (newGroup == null) {
410: newGroup = new WebServiceGroup(WebServiceListModel
411: .getInstance().getUniqueWebServiceGroupId());
412: newGroup.setName(groupName);
413: newGroup.setUserDefined(false);
414: }
415:
416: for (Map.Entry<String, String> entry : currentUrls
417: .entrySet()) {
418: String url = entry.getKey();
419:
420: // !reloadIfExists -> !partnerUrls.contains(url)
421: if (!reloadIfExists || !partnerUrls.contains(url)) {
422: // Add a new web service
423: partnerUrls.add(url);
424: WebServiceData wsData = new WebServiceData(url,
425: newGroup.getId());
426: WebServiceListModel.getInstance().addWebService(
427: wsData);
428:
429: newGroup.add(wsData.getId(), true);
430: } else {
431: // reset an existing service
432: WebServiceData existingData = null;
433: List<WebServiceData> wsDatas = WebServiceListModel
434: .getInstance().getWebServiceSet();
435: for (WebServiceData wsData : wsDatas) {
436: if (wsData.getOriginalWsdlUrl().equals(url)) {
437: existingData = wsData;
438: break;
439: }
440: }
441:
442: if (existingData != null) {
443: WebServiceManager.getInstance()
444: .resetWebService(existingData);
445: existingData.setName(entry.getValue());
446: } else {
447: WebServiceData wsData = new WebServiceData(url,
448: newGroup.getId());
449: WebServiceListModel.getInstance()
450: .addWebService(wsData);
451:
452: newGroup.add(wsData.getId(), true);
453: }
454: }
455: }
456:
457: WebServiceListModel.getInstance().addWebServiceGroup(
458: newGroup);
459: }
460: }
461:
462: public void saveDescriptor(WebServiceDescriptor descriptor)
463: throws IOException {
464: XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(
465: new FileOutputStream(descriptor.getXmlDescriptor())));
466: encoder.setExceptionListener(this );
467: DefaultPersistenceDelegate delegate = new WebServiceDataPersistenceDelegate();
468: encoder.setPersistenceDelegate(WsdlService.class, delegate);
469: encoder.writeObject(descriptor);
470:
471: encoder.close();
472: encoder.flush();
473: }
474:
475: public void saveWebServiceDescriptor(WebServiceDescriptor descriptor) {
476: try {
477: saveDescriptor(descriptor);
478: } catch (IOException ex) {
479: exceptionThrown(ex);
480: }
481: }
482:
483: public void exceptionThrown(Exception exc) {
484: ErrorManager.getDefault().notify(exc);
485: }
486:
487: public class WebServiceDataPersistenceDelegate extends
488: DefaultPersistenceDelegate {
489: /**
490: * Suppress the writing of
491: * org.netbeans.modules.websvc.api.jaxws.wsdlmodel.WsdlService
492: * It will be created from the WSDL file
493: */
494: @Override
495: public void writeObject(Object oldInstance, Encoder out) {
496: if (oldInstance instanceof WsdlService) {
497: return;
498: } else if (oldInstance instanceof WebServiceDescriptor) {
499: if (descriptorsToWrite == null) {
500: descriptorsToWrite = new ArrayList<WebServiceDescriptor>();
501: }
502: descriptorsToWrite
503: .add((WebServiceDescriptor) oldInstance);
504: } else {
505: super.writeObject(oldInstance, out);
506: }
507: }
508: }
509:
510: }
|