Source Code Cross Referenced for CatalogFileWrapperDOMImpl.java in  » IDE-Netbeans » xml » org » netbeans » modules » xml » retriever » catalog » impl » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » IDE Netbeans » xml » org.netbeans.modules.xml.retriever.catalog.impl 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


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-2006 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.xml.retriever.catalog.impl;
043:
044:        import java.beans.PropertyChangeListener;
045:        import java.beans.PropertyChangeSupport;
046:        import java.io.ByteArrayInputStream;
047:        import java.io.ByteArrayOutputStream;
048:        import java.io.File;
049:        import java.io.FileOutputStream;
050:        import java.io.IOException;
051:        import java.io.InputStream;
052:        import java.io.InputStreamReader;
053:        import java.io.OutputStream;
054:        import java.util.ArrayList;
055:        import java.util.HashMap;
056:        import java.util.List;
057:        import java.util.Set;
058:        import java.util.WeakHashMap;
059:        import java.util.logging.Logger;
060:        import javax.swing.event.DocumentEvent;
061:        import javax.swing.event.DocumentListener;
062:        import javax.swing.text.BadLocationException;
063:        import javax.swing.text.StyledDocument;
064:        import javax.xml.parsers.DocumentBuilder;
065:        import javax.xml.parsers.DocumentBuilderFactory;
066:        import javax.xml.parsers.ParserConfigurationException;
067:        import javax.xml.transform.Transformer;
068:        import javax.xml.transform.TransformerFactory;
069:        import javax.xml.transform.dom.DOMSource;
070:        import javax.xml.transform.stream.StreamResult;
071:        import org.netbeans.modules.xml.retriever.catalog.Utilities;
072:        import org.netbeans.modules.xml.xam.dom.DocumentModel;
073:        import org.netbeans.modules.xml.retriever.catalog.CatalogAttribute;
074:        import org.netbeans.modules.xml.retriever.catalog.CatalogElement;
075:        import org.netbeans.modules.xml.retriever.catalog.CatalogEntry;
076:        import org.openide.cookies.EditorCookie;
077:        import org.openide.cookies.SaveCookie;
078:        import org.openide.filesystems.FileLock;
079:        import org.openide.filesystems.FileObject;
080:        import org.openide.filesystems.FileUtil;
081:        import org.openide.loaders.DataObject;
082:        import org.w3c.dom.Document;
083:        import org.w3c.dom.Element;
084:        import org.w3c.dom.NamedNodeMap;
085:        import org.w3c.dom.Node;
086:        import org.w3c.dom.NodeList;
087:        import org.xml.sax.EntityResolver;
088:        import org.xml.sax.InputSource;
089:        import org.xml.sax.SAXException;
090:
091:        /**
092:         *
093:         * @author girix
094:         */
095:        public class CatalogFileWrapperDOMImpl implements  EntityResolver,
096:                CatalogFileWrapper, DocumentListener {
097:            PropertyChangeSupport pcs = new PropertyChangeSupport(this );
098:            private Document catDoc = null;
099:            private Element catalog = null;
100:            private boolean isItMyOwnEvent = false;
101:            public static javax.swing.text.Document backendCatalogSwingDocument = null;
102:            private static final Logger logger = Logger
103:                    .getLogger(CatalogFileWrapperDOMImpl.class.getName());
104:
105:            private DocumentModel.State currentStateOfCatalog = null;
106:
107:            public static boolean TEST_ENVIRONMENT = false;
108:
109:            private FileObject backendCatalogFileObj = null;
110:
111:            boolean rawFileSaveStrategy = false;
112:
113:            SaveCookie saveCookie = null;
114:
115:            private CatalogFileWrapperDOMImpl(FileObject backendCatalogFileObj,
116:                    boolean rawFileSaveStrategy) throws IOException {
117:                this .rawFileSaveStrategy = rawFileSaveStrategy;
118:                this .backendCatalogFileObj = backendCatalogFileObj;
119:                assert (backendCatalogFileObj != null);
120:                //this.backendCatalogSwingDocument.addDocumentListener(this);
121:            }
122:
123:            private synchronized void bootstrap() {
124:                try {
125:                    this .backendCatalogSwingDocument = getDocument(backendCatalogFileObj);
126:                } catch (IOException ex) {
127:                    throw new IllegalStateException(ex);
128:                }
129:                assert (backendCatalogFileObj != null);
130:                try {
131:                    sync();
132:                } catch (IOException ex) {
133:                    throw new IllegalStateException(ex);
134:                }
135:                if (currentStateOfCatalog == DocumentModel.State.NOT_WELL_FORMED)
136:                    throw new IllegalStateException(
137:                            "Catalog File Not wellformed");
138:            }
139:
140:            private synchronized void tearDown() {
141:                this .backendCatalogSwingDocument = null;
142:                catalog = null;
143:                catDoc = null;
144:            }
145:
146:            static WeakHashMap<FileObject, CatalogFileWrapper> fo2wrapMap = new WeakHashMap<FileObject, CatalogFileWrapper>();
147:
148:            public static synchronized CatalogFileWrapper getInstance(
149:                    FileObject backendCatalogFileObj,
150:                    boolean rawFileSaveStrategy) throws IOException {
151:                CatalogFileWrapper result = fo2wrapMap
152:                        .get(backendCatalogFileObj);
153:                if (result == null) {
154:                    result = new CatalogFileWrapperDOMImpl(
155:                            backendCatalogFileObj, rawFileSaveStrategy);
156:                    if (result != null) {
157:                        fo2wrapMap.put(backendCatalogFileObj, result);
158:                        return result;
159:                    }
160:                }
161:                return result;
162:            }
163:
164:            public static synchronized CatalogFileWrapper getInstance(
165:                    FileObject backendCatalogFileObj) throws IOException {
166:                return getInstance(backendCatalogFileObj, false);
167:            }
168:
169:            public synchronized void cleanInstance() {
170:                /*fo2wrapMap.remove(backendCatalogFileObj);
171:                try {
172:                   backendCatalogFileObj.delete();
173:                } catch (IOException ex) {
174:                }*/
175:            }
176:
177:            private javax.swing.text.Document getDocument(
178:                    FileObject backendCatalogFileObj) throws IOException {
179:                logger.finer("ENTER FileObject "
180:                        + backendCatalogFileObj.toString());
181:                DataObject dobj = DataObject.find(backendCatalogFileObj);
182:                EditorCookie this DocumentEditorCookie = (EditorCookie) dobj
183:                        .getCookie(EditorCookie.class);
184:                StyledDocument sd = this DocumentEditorCookie.openDocument();
185:                logger.finer("RETURN");
186:                return sd;
187:            }
188:
189:            private boolean shouldParse(String docContent) {
190:                if ((docContent != null)
191:                        && (docContent.toLowerCase().indexOf("catalog") != -1))
192:                    return true;
193:                return false;
194:            }
195:
196:            public List<CatalogEntry> getSystems() {
197:                return getEntriesByTagName(CatalogElement.system,
198:                        CatalogAttribute.systemId, CatalogAttribute.uri);
199:            }
200:
201:            public void setSystem(int index, CatalogEntry catEnt)
202:                    throws IOException {
203:                setEntryInCatalogFile(index, catEnt, CatalogAttribute.systemId,
204:                        CatalogAttribute.uri);
205:            }
206:
207:            public void deleteSystem(int index) throws IOException {
208:                deleteEntryFromCatalogFile(index, CatalogElement.system);
209:            }
210:
211:            public void addSystem(CatalogEntry catEnt) throws IOException {
212:                addEntryToCatFile(catEnt, CatalogAttribute.systemId,
213:                        CatalogAttribute.uri);
214:            }
215:
216:            public List<CatalogEntry> getDelegateSystems() {
217:                return getEntriesByTagName(CatalogElement.delegateSystem,
218:                        CatalogAttribute.systemIdStartString,
219:                        CatalogAttribute.catalog);
220:            }
221:
222:            public void setDelegateSystem(int index, CatalogEntry catEnt)
223:                    throws IOException {
224:                setEntryInCatalogFile(index, catEnt,
225:                        CatalogAttribute.systemIdStartString,
226:                        CatalogAttribute.catalog);
227:            }
228:
229:            public void deleteDelegateSystem(int index) throws IOException {
230:                deleteEntryFromCatalogFile(index, CatalogElement.delegateSystem);
231:            }
232:
233:            public void addDelegateSystem(CatalogEntry catEnt)
234:                    throws IOException {
235:                addEntryToCatFile(catEnt, CatalogAttribute.systemIdStartString,
236:                        CatalogAttribute.catalog);
237:            }
238:
239:            public List<CatalogEntry> getRewriteSystems() {
240:                return getEntriesByTagName(CatalogElement.rewriteSystem,
241:                        CatalogAttribute.systemIdStartString,
242:                        CatalogAttribute.rewritePrefix);
243:            }
244:
245:            public void setRewriteSystem(int index, CatalogEntry catEnt)
246:                    throws IOException {
247:                setEntryInCatalogFile(index, catEnt,
248:                        CatalogAttribute.systemIdStartString,
249:                        CatalogAttribute.rewritePrefix);
250:            }
251:
252:            public void deleteRewriteSystem(int index) throws IOException {
253:                deleteEntryFromCatalogFile(index, CatalogElement.rewriteSystem);
254:            }
255:
256:            public void addRewriteSystem(CatalogEntry catEnt)
257:                    throws IOException {
258:                addEntryToCatFile(catEnt, CatalogAttribute.systemIdStartString,
259:                        CatalogAttribute.rewritePrefix);
260:            }
261:
262:            private void initCatFile() throws IOException {
263:                logger.finer("ENTER");
264:                NodeList nl = catDoc
265:                        .getElementsByTagName(CatalogElement.catalog.toString());
266:                if (nl.getLength() <= 0) {
267:                    //catalog element does not exists. Create
268:                    catalog = catDoc.createElement(CatalogElement.catalog
269:                            .toString());
270:                    catalog.setAttribute(CatalogAttribute.prefer.toString(),
271:                            "system");
272:                    catalog.setAttribute(CatalogAttribute.xmlns.toString(),
273:                            "urn:oasis:names:tc:entity:xmlns:xml:catalog");
274:                    catDoc.appendChild(catalog);
275:                    flush();
276:                } else {
277:                    catalog = (Element) nl.item(0);
278:                }
279:                logger.finer("RETURN");
280:            }
281:
282:            private List<CatalogEntry> getEntriesByTagName(
283:                    CatalogElement tagName, CatalogAttribute mappingEntityKey,
284:                    CatalogAttribute mappedEntityKey) {
285:                bootstrap();
286:                Object[] obj = { tagName.toString(),
287:                        mappingEntityKey.toString(), mappedEntityKey.toString() };
288:                logger.entering("CatalogModelWrapperDOMImpl",
289:                        "getEntriesByTagName", obj);
290:
291:                NodeList nl = catalog.getElementsByTagName(tagName.toString());
292:                int len = nl.getLength();
293:                if (len < 1)
294:                    return null;
295:                List<CatalogEntry> result = new ArrayList<CatalogEntry>(nl
296:                        .getLength());
297:                for (int i = 0; i < len; i++) {
298:                    String mappingEntity = "";
299:                    String mappedEntity = "";
300:                    Element elm = (Element) nl.item(i);
301:                    mappingEntity = elm.getAttribute(mappingEntityKey
302:                            .toString());
303:                    mappedEntity = elm.getAttribute(mappedEntityKey.toString());
304:                    String strArry[] = { mappingEntityKey.toString(),
305:                            mappedEntityKey.toString() };
306:                    HashMap<String, String> extraAttrs = getOtherAttributes(
307:                            elm, strArry);
308:                    CatalogEntry catEnt;
309:                    if (extraAttrs != null)
310:                        catEnt = new CatalogEntryImpl(tagName, mappingEntity,
311:                                mappedEntity, extraAttrs);
312:                    else
313:                        catEnt = new CatalogEntryImpl(tagName, mappingEntity,
314:                                mappedEntity);
315:                    result.add(catEnt);
316:                }
317:                logger.exiting("CatalogModelWrapperDOMImpl",
318:                        "getEntriesByTagName", result);
319:                tearDown();
320:                return result;
321:            }
322:
323:            private void addEntryToCatFile(CatalogEntry catEnt,
324:                    CatalogAttribute mappingEntityKey,
325:                    CatalogAttribute mappedEntityKey) throws IOException {
326:                bootstrap();
327:                /*Object obj[] = {
328:                    catEnt.toString(), mappingEntityKey.toString(), mappedEntityKey.toString()
329:                };
330:                logger.entering("CatalogModelWrapperDOMImpl", "addEntryToCatFile", obj);*/
331:
332:                Element elm = catDoc.createElement(catEnt.getEntryType()
333:                        .toString());
334:                if (mappedEntityKey != null)
335:                    elm.setAttribute(mappedEntityKey.toString(), catEnt
336:                            .getTarget());
337:                if (mappingEntityKey != null)
338:                    elm.setAttribute(mappingEntityKey.toString(), catEnt
339:                            .getSource());
340:                HashMap<String, String> extraAttribMap = catEnt
341:                        .getExtraAttributeMap();
342:                if (extraAttribMap != null)
343:                    addOtherAttributesToElement(elm, extraAttribMap);
344:
345:                catalog.appendChild(elm);
346:                flush();
347:                logger.exiting(this .toString(), "addEntryToCatFile");
348:                tearDown();
349:            }
350:
351:            private void setEntryInCatalogFile(int index, CatalogEntry catEnt,
352:                    CatalogAttribute mappingEntityKey,
353:                    CatalogAttribute mappedEntityKey) throws IOException {
354:                bootstrap();
355:
356:                Object obj[] = { Integer.valueOf(index), catEnt.toString(),
357:                        mappingEntityKey.toString(), mappedEntityKey.toString() };
358:                logger.entering("CatalogModelWrapperDOMImpl",
359:                        "setEntryInCatalogFile", obj);
360:
361:                Element elm = catDoc.createElement(catEnt.getEntryType()
362:                        .toString());
363:                elm
364:                        .setAttribute(mappedEntityKey.toString(), catEnt
365:                                .getTarget());
366:                elm.setAttribute(mappingEntityKey.toString(), catEnt
367:                        .getSource());
368:                HashMap<String, String> extraAttribMap = catEnt
369:                        .getExtraAttributeMap();
370:                if (extraAttribMap != null)
371:                    addOtherAttributesToElement(elm, extraAttribMap);
372:
373:                NodeList nl = catalog.getElementsByTagName(catEnt
374:                        .getEntryType().toString());
375:                int len = nl.getLength();
376:                if ((index >= len) || (index < 0))
377:                    throw new IndexOutOfBoundsException(
378:                            "Error: Catalog entry does not exists");
379:
380:                Node oldNode = nl.item(index);
381:
382:                catalog.replaceChild(elm, oldNode);
383:
384:                flush();
385:                logger.exiting(this .toString(), "setEntryInCatalogFile");
386:                tearDown();
387:            }
388:
389:            private void deleteEntryFromCatalogFile(int index,
390:                    CatalogElement tagName) throws IOException {
391:                logger.entering(this .toString(), "deleteEntryFromCatalogFile");
392:                bootstrap();
393:                NodeList nl = catalog.getElementsByTagName(tagName.toString());
394:                int len = nl.getLength();
395:                if ((index >= len) || (index < 0))
396:                    throw new IndexOutOfBoundsException(
397:                            "Error: Catalog entry does not exists");
398:
399:                Node oldNode = nl.item(index);
400:
401:                catalog.removeChild(oldNode);
402:
403:                flush();
404:                logger.exiting(this .toString(), "deleteEntryFromCatalogFile");
405:                tearDown();
406:            }
407:
408:            private void addOtherAttributesToElement(Element elm,
409:                    HashMap<String, String> extraAttribMap) {
410:                if (extraAttribMap == null)
411:                    return;
412:                Set<String> keys = extraAttribMap.keySet();
413:                if (keys == null)
414:                    return;
415:                for (String key : keys) {
416:                    String value = (String) extraAttribMap.get(key);
417:                    if (value != null) {
418:                        elm.setAttribute(key, value);
419:                    }
420:                }
421:            }
422:
423:            private HashMap<String, String> getOtherAttributes(Element elm,
424:                    String[] strArry) {
425:                HashMap<String, String> result = new HashMap<String, String>();
426:                NamedNodeMap attrs = elm.getAttributes();
427:                for (int i = 0; i < attrs.getLength(); i++) {
428:                    String key = attrs.item(i).getNodeName();
429:                    boolean isMainAttrib = false;
430:                    for (String str : strArry) {
431:                        if (str.equals(key)) {
432:                            isMainAttrib = true;
433:                            break;
434:                        }
435:                    }
436:                    if (!isMainAttrib) {
437:                        String value = attrs.item(i).getNodeValue();
438:                        if ((key != null) && (value != null))
439:                            result.put(key, value);
440:                    }
441:                }
442:                if (result.isEmpty())
443:                    return null;
444:                return result;
445:            }
446:
447:            public synchronized void sync() throws IOException {
448:                logger.finer("ENTER");
449:                DocumentBuilderFactory dBuilderFact = DocumentBuilderFactory
450:                        .newInstance();
451:                //dBuilderFact.setValidating(true);
452:                DocumentBuilder dBuilder = null;
453:                try {
454:                    dBuilder = dBuilderFact.newDocumentBuilder();
455:                } catch (ParserConfigurationException ex) {
456:                    assignStateAndFirePropChangeEvent(DocumentModel.State.NOT_WELL_FORMED);
457:                    throw new IOException(ex.getMessage());
458:                }
459:                String docContent = null;
460:                try {
461:
462:                    docContent = backendCatalogSwingDocument.getText(0,
463:                            backendCatalogSwingDocument.getLength());
464:                } catch (BadLocationException ex) {
465:                    assignStateAndFirePropChangeEvent(DocumentModel.State.NOT_WELL_FORMED);
466:                    throw new IOException(ex.getMessage());
467:                }
468:                logger.finer("Trying to sync this data to model:" + docContent);
469:                if (shouldParse(docContent)) {
470:                    InputStream catIS = new ByteArrayInputStream(docContent
471:                            .getBytes());
472:                    try {
473:                        //dBuilder.setEntityResolver(this);
474:                        catDoc = dBuilder.parse(catIS);
475:                        logger.finer("Just synced this data :" + docContent);
476:                    } catch (SAXException ex) {
477:                        assignStateAndFirePropChangeEvent(DocumentModel.State.NOT_WELL_FORMED);
478:                        throw new IOException(ex.getMessage());
479:                    }
480:                } else {
481:                    catDoc = dBuilder.newDocument();
482:                }
483:                if (catDoc == null) {
484:                    assignStateAndFirePropChangeEvent(DocumentModel.State.NOT_WELL_FORMED);
485:                    throw new IllegalStateException(
486:                            "Catalog File Not wellformed");
487:                }
488:                assignStateAndFirePropChangeEvent(DocumentModel.State.VALID);
489:                initCatFile();
490:                logger.finer("RETURN");
491:
492:            }
493:
494:            private void assignStateAndFirePropChangeEvent(
495:                    DocumentModel.State currentStateOfCatalog) {
496:                DocumentModel.State prevState = this .currentStateOfCatalog;
497:                this .currentStateOfCatalog = currentStateOfCatalog;
498:                pcs.firePropertyChange("CatalogWraperObject", prevState,
499:                        currentStateOfCatalog);
500:            }
501:
502:            public boolean isValidState() {
503:                if (currentStateOfCatalog == DocumentModel.State.VALID)
504:                    return true;
505:                return false;
506:            }
507:
508:            public synchronized void flush() throws IOException {
509:                logger.finer("ENTER");
510:                isItMyOwnEvent = true;
511:                try {
512:                    TransformerFactory trFactory = TransformerFactory
513:                            .newInstance();
514:                    Transformer transformer = trFactory.newTransformer();
515:                    DOMSource domSource = new DOMSource(catDoc);
516:                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
517:                    StreamResult streamResult = new StreamResult(baos);
518:                    transformer.setOutputProperty("indent", "yes");
519:                    transformer.transform(domSource, streamResult);
520:                    String fileContent = new String(baos.toByteArray());
521:                    String prevContent = backendCatalogSwingDocument.getText(0,
522:                            backendCatalogSwingDocument.getLength());
523:                    if (fileContent.equals(prevContent)) {
524:                        isItMyOwnEvent = false;
525:                        return;
526:                    }
527:                    backendCatalogSwingDocument.remove(0,
528:                            backendCatalogSwingDocument.getLength());
529:                    backendCatalogSwingDocument.insertString(0, fileContent,
530:                            null);
531:                    logger.finer("Just Flushed this data :"
532:                            + backendCatalogSwingDocument.getText(0,
533:                                    backendCatalogSwingDocument.getLength()));
534:                    save(fileContent, prevContent);
535:                } catch (Exception ex) {
536:                    throw new IOException(ex.getMessage());
537:                } finally {
538:                    isItMyOwnEvent = false;
539:                }
540:                logger.finer("RETURN");
541:            }
542:
543:            public void insertUpdate(DocumentEvent e) {
544:                //showStackTrace();
545:                logger.entering("CatalogModelWrapperDOMImpl", "insertUpdate",
546:                        Boolean.valueOf(isItMyOwnEvent));
547:                if (!isItMyOwnEvent) {
548:                    try {
549:                        sync();
550:                    } catch (IOException ex) {
551:                        //ignore this
552:                        //ex.printStackTrace();
553:                    }
554:                    return;
555:                }
556:            }
557:
558:            void showStackTrace() {
559:                try {
560:                    throw new Exception();
561:                } catch (Exception e) {
562:                    e.printStackTrace();
563:                }
564:            }
565:
566:            public void removeUpdate(DocumentEvent e) {
567:                showStackTrace();
568:                logger.entering("CatalogModelWrapperDOMImpl", "removeUpdate",
569:                        Boolean.valueOf(isItMyOwnEvent));
570:                insertUpdate(e);
571:            }
572:
573:            public void changedUpdate(DocumentEvent e) {
574:                logger.entering("CatalogModelWrapperDOMImpl", "changedUpdate",
575:                        Boolean.valueOf(isItMyOwnEvent));
576:                //insertUpdate(e);
577:            }
578:
579:            public void addPropertyChangeListener(PropertyChangeListener l) {
580:                pcs.addPropertyChangeListener(l);
581:            }
582:
583:            public void removePropertyChangeListener(PropertyChangeListener l) {
584:                pcs.removePropertyChangeListener(l);
585:            }
586:
587:            public InputStream getCatalogAsStream() throws IOException {
588:                try {
589:                    String docContent = backendCatalogSwingDocument.getText(0,
590:                            backendCatalogSwingDocument.getLength());
591:                    InputStream bis = new ByteArrayInputStream(docContent
592:                            .getBytes());
593:                    logger.finer("In getCatalogAsStream gona return:"
594:                            + docContent);
595:                    return bis;
596:                } catch (BadLocationException ex) {
597:                    throw new IOException(ex.getMessage());
598:                }
599:            }
600:
601:            public InputSource resolveEntity(String publicId, String systemId)
602:                    throws SAXException, IOException {
603:                logger.finest("ENTRY PublicID:" + publicId + " SystemID:"
604:                        + systemId);
605:                InputSource isrc = new InputSource();
606:                InputStreamReader isr = new InputStreamReader(
607:                        org.apache.xml.resolver.apps.resolver.class
608:                                .getResourceAsStream("/org/apache/xml/resolver/etc/catalog.dtd"));
609:                isrc.setCharacterStream(isr);
610:                if ((systemId != null)
611:                        && systemId
612:                                .equals("urn:oasis:names:tc:entity:xmlns:xml:catalog")) {
613:                    logger.finest("RETURN the DTD");
614:                    return isrc;
615:                }
616:                if ((publicId != null)
617:                        && publicId
618:                                .equals("urn:oasis:names:tc:entity:xmlns:xml:catalog")) {
619:                    logger.finest("RETURN the DTD");
620:                    return isrc;
621:                }
622:                //parser asked for some other resource
623:                logger.finest("RETURN null");
624:                return null;
625:            }
626:
627:            private void save(String fileContent, String previousFileContent) {
628:                //if(rawFileSaveStrategy)
629:                //if(!saveByRawStreamByFO(fileContent, previousFileContent))
630:                //saveByRawStreamByFile(fileContent, previousFileContent);
631:                //else
632:                if (TEST_ENVIRONMENT)
633:                    saveByRawStreamByFile(fileContent, previousFileContent);
634:                else
635:                    saveBySaveCookie();
636:                //saveByDocumentEditorCookie();
637:            }
638:
639:            boolean saveBySaveCookie() {
640:                try {
641:                    DataObject dobj = DataObject.find(backendCatalogFileObj);
642:                    SaveCookie saveCookie = (SaveCookie) dobj
643:                            .getCookie(SaveCookie.class);
644:                    assert (saveCookie != null);
645:                    saveCookie.save();
646:                } catch (IOException ex) {
647:                    return false;
648:                }
649:                return true;
650:            }
651:
652:            boolean saveByRawStreamByFO(String fileContent,
653:                    String previousFileContent) {
654:                OutputStream os = null;
655:                FileLock lock = null;
656:                boolean noException = true;
657:                try {
658:                    lock = backendCatalogFileObj.lock();
659:                    os = backendCatalogFileObj.getOutputStream(lock);
660:                    os.write(fileContent.getBytes());
661:                    os.flush();
662:                    os.close();
663:                    lock.releaseLock();
664:                    os = null;
665:                } catch (IOException ex) {
666:                    ex.printStackTrace();
667:                    noException = false;
668:                } finally {
669:                    if (lock != null)
670:                        lock.releaseLock();
671:                    if (os != null) {
672:                        try {
673:                            os.close();
674:                        } catch (IOException ex) {
675:                        }
676:                    }
677:                    return noException;
678:                }
679:            }
680:
681:            boolean saveByRawStreamByFile(String fileContent,
682:                    String previousFileContent) {
683:                OutputStream os = null;
684:                try {
685:                    File catFile = FileUtil.toFile(backendCatalogFileObj);
686:                    os = new FileOutputStream(catFile);
687:                    os.write(fileContent.getBytes());
688:                    os.flush();
689:                    os.close();
690:                    os = null;
691:                } catch (IOException ex) {
692:                    ex.printStackTrace();
693:                } finally {
694:                    if (os != null) {
695:                        try {
696:                            os.close();
697:                            return false;
698:                        } catch (IOException ex) {
699:                        }
700:                    }
701:                }
702:                return true;
703:            }
704:
705:            void saveByDocumentEditorCookie() {
706:                try {
707:                    DataObject dobj = DataObject.find(backendCatalogFileObj);
708:                    EditorCookie this DocumentEditorCookie = (EditorCookie) dobj
709:                            .getCookie(EditorCookie.class);
710:                    this DocumentEditorCookie.saveDocument();
711:                } catch (IOException ex) {
712:                }
713:            }
714:
715:            private boolean unsuccessfulSave(String fileContent,
716:                    String previousFileContent) {
717:                try {
718:                    if (backendCatalogSwingDocument.getText(0,
719:                            backendCatalogSwingDocument.getLength()).length() != fileContent
720:                            .length()) {
721:                        return true;
722:                    }
723:                } catch (BadLocationException ex) {
724:                }
725:                return false;
726:            }
727:
728:            public void close() {
729:                //thisDocumentEditorCookie.close();
730:                //backendCatalogSwingDocument.removeDocumentListener(this);
731:            }
732:
733:            public DocumentModel.State getCatalogState() {
734:                bootstrap();
735:                tearDown();
736:                return currentStateOfCatalog;
737:            }
738:
739:            protected void finalize() throws Throwable {
740:                try {
741:                    DataObject dobj = DataObject.find(backendCatalogFileObj);
742:                    EditorCookie this DocumentEditorCookie = (EditorCookie) dobj
743:                            .getCookie(EditorCookie.class);
744:                    backendCatalogSwingDocument.removeDocumentListener(this );
745:                    this DocumentEditorCookie.close();
746:                } finally {
747:                    super .finalize();
748:                }
749:            }
750:
751:            public void addNextCatalog(CatalogEntry catEnt) throws IOException {
752:                addEntryToCatFile(catEnt, CatalogAttribute.catalog, null);
753:            }
754:
755:            public void deleteNextCatalog(int index) throws IOException {
756:                deleteEntryFromCatalogFile(index, CatalogElement.nextCatalog);
757:            }
758:
759:            public List<CatalogEntry> getNextCatalogs() {
760:                return getEntriesByTagName(CatalogElement.nextCatalog,
761:                        CatalogAttribute.catalog, CatalogAttribute.catalog);
762:            }
763:
764:        }
w___ww___._j___ava2___s.co__m__ | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.