gmf 中保存 xml resource 的方法


寫兩個方法在這裏,做個記錄,免得以後忘了;


public
 void save(IFileDelegate file, Object object) throws IOException {
        SysDesignDiagram designDiagram 
= (SysDesignDiagram) object;
        
if(StringUtils.isEmpty(designDiagram.getName())){
            String path 
= FileUtil.toPackageWithoutExtension(file.getSourceRelativePath());
            designDiagram.setName(path);
        }

        ByteArrayOutputStream outStream 
= new ByteArrayOutputStream();
        Resource resource 
= this.createResource();

        SysDesignFactory SysDesignFactory 
= new SysDesignFactoryImpl();
        DocumentRoot documentRoot 
= (DocumentRoot) SysDesignFactory
                .createDocumentRoot();

        documentRoot
                .getMixed()
                .add(
                        SysDesignPackage.Literals.DOCUMENT_ROOT__SYS_DESIGN_DIAGRAM,
                        object);
        resource.getContents().add(documentRoot);
        resource.save(outStream, getOptions());

        ByteArrayInputStream inStream 
= new ByteArrayInputStream(outStream
                .toByteArray());

        
try {
            
if(!file.exists())
                file.create(inStream);
            
else
                file.setContents(inStream);
        }
 catch (Exception e) {
            
throw new IOException("save file error.");
        }
 finally {
            IOUtils.closeQuietly(inStream);
        }

    }


創建資源
protected Resource createResource() {
        ResourceFactoryImpl resourceFactory 
= new SysDesignResourceFactoryImpl();
        
return resourceFactory.createResource(URI
                .createURI(SysDesignPackage.eNS_URI));
    }


     


    
public Object parse(IFileDelegate file, IProgressMonitor monitor)
            
throws ModelParseException {
        
if (file.exists()) {

            InputStream inStream 
= null;
            
try {
                inStream 
= file.getContents();

                SysDesignDiagram diagram 
= (SysDesignDiagram) this.parse(
                        inStream, monitor);
                
return diagram;
            }
 finally {
                IOUtils.closeQuietly(inStream);
            }

        }

        
return null;
    }
發佈了31 篇原創文章 · 獲贊 3 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章